Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 23 total  RSS 

Generating Taconite command documents

// description of your code here
Hello,

This is a port of a php class used to generate XML taconite command documents, useful for (very) easy and powerful ajaxy stuff, if you don't know what that is just check it there in french : http://www.desfrenes.com/playground/taconite/ or there in english : http://www.malsup.com/jquery/taconite/.

Basically what it does is generate an XML document that is later processed by a javascript plugin which executes a serie of DOM modifications.

About the code, I'm a Django beginner as well as a Python beginner so kind advices are welcome.

Cheers.
# usage:
#
# t = Taconite()
#
# t.append("#toto","<label>test</label>")
# t.remove("#tutu")
# t.js('alert("hello world");')
# t.toggleClass('blue','body')
# t.css("body","background-color","white")
# [...]
# print t.toprettyxml()

import xml.dom.minidom as dom

class Taconite(dom.Document):
    def __init__(self):
        dom.Document.__init__(self)
        taconite = self.createElement("taconite")
        self.appendChild(taconite)

    def __str__(self):
        return self.toxml(encoding="utf-8")
    
    def camelizeCssProperty(self,property):
        words = property.split('-')
        camelized = words[0].lower()
        for word in words[1:] :
            camelized = camelized + word[0].upper() + word[1:]
        return camelized
    
    def js(self,script):
        command = self.createElement("eval")
        js = self.createTextNode(script)
        command.appendChild(js)
        self.childNodes[0].appendChild(command)
    
    def changeContentCommand(self,method,selector,content):
        html_dom = dom.parseString(content)
        command = self.createElement(method)
        command.setAttribute("select",selector)
        command.appendChild(html_dom.childNodes[0])
        self.childNodes[0].appendChild(command)
    
    def changeStateCommand(self,action,selector):
        command = self.createElement(action)
        command.setAttribute("select",selector)
        self.childNodes[0].appendChild(command)
    
    def CssCommand(self,action,css_class,selector):
        command1 = self.createElement(action)
        command1.setAttribute("select",selector)
        command1.setAttribute("arg1",css_class)
        command2 = self.createElement(action)
        command2.setAttribute("select",selector)
        command2.setAttribute("value",css_class)
        self.childNodes[0].appendChild(command1)
        self.childNodes[0].appendChild(command2)
    
    def addClass(self,css_class,selector):
        self.CssCommand("addClass",css_class,selector)

    def removeClass(self,css_class,selector):
        self.CssCommand("remove",css_class,selector)

    def toggleClass(self,css_class,selector):
        self.CssCommand("toggleClass",css_class,selector)
    
    def append(self,selector,content):
        self.changeContentCommand("append",selector,content)
    
    def prepend(self,selector,content):
        self.changeContentCommand("prepend",selector,content)
        
    
    def before(self,selector,content):
        self.changeContentCommand("before",selector,content)
        
    
    def after(self,selector,content):
        self.changeContentCommand("after",selector,content)
    
    def wrap(self,selector,content):
        self.changeContentCommand("wrap",selector,content)
    
    def replace(self,selector,content):
        self.changeContentCommand("replace",selector,content)
    
    def replaceContent(self,selector,content):
        self.changeContentCommand("replaceContent",selector,content)
    
    def remove(self,selector):
        self.changeStateCommand("remove",selector)
    
    def show(self,selector):
        self.changeStateCommand("show",selector)
    
    def hide(self,selector):
        self.changeStateCommand("hide",selector)
    
    def removeContent(self,selector):
        self.changeStateCommand("empty",selector)
    
    def css(self,selector,property,value):
        command = self.createElement("css")
        command.setAttribute("select",selector)
        command.setAttribute("name",self.camelizeCssProperty(property))
        command.setAttribute("value",value)
        self.childNodes[0].appendChild(command)

Reference of keyCodes

    switch (oEvent.keyCode) {
       case 38: //up arrow  
       case 40: //down arrow
       case 37: //left arrow
       case 39: //right arrow
       case 33: //page up  
       case 34: //page down  
       case 36: //home  
       case 35: //end                  
       case 13: //enter  
       case 9: //tab  
       case 27: //esc  
       case 16: //shift  
       case 17: //ctrl  
       case 18: //alt  
       case 20: //caps lock
       case 8: //backspace  
       case 46: //delete
           return true;
           break;

       default: 

Note: When capturing combination keys there is dedicated boolean attributes for each of the special keys (CTRL, SHIFT, ALT).
Reference: Make Life Easy With Autocomplete Textboxes [JavaScript & AJAX Tutorials] [sitepoint.com]

insertAfter() with insertBefore() and node.nextSibling

insertAfter() with insertBefore() and node.nextSibling

Node.prototype.insertAfter = function(newNode, refNode) {
	if(refNode.nextSibling) {
		return this.insertBefore(newNode, refNode.nextSibling);
	} else {
		return this.appendChild(newNode);
	}
}


Source: Benoit Asselin

Include CSS Stylesheet by DOM


function includeCSS(p_file) {
	var v_css  = document.createElement('link');
	v_css.rel = 'stylesheet'
	v_css.type = 'text/css';
	v_css.href = p_file;
	document.getElementsByTagName('head')[0].appendChild(v_css);
}



Source: Document Object Model (DOM) Level 1 Specification

DOM Mouse-Over Element Selection and Isolation

DOM ISO.v.0.3.0.7.bookmarklet.js
bookmarklet for selecting and isolating an element on a page.

two sections:
section 1: Mouseover DOM, setup and handle mouse events and show information about element in informational div. Click to select, Any key to cancel.
section 2: Element Isolation with help of XPath. prompt user for XPath expression e.g., //DIV[@id='post-body']. then use XPath to select all elements not(ancestor or descendant or self), then delete those elements. also ignore self-or-descendants of head and title.

tools:
Ruderman's javascript development environment: https://www.squarefree.com/bookmarklets/webdevel.html#jsenv
Mielczarek's js to bookmarklet generator: http://ted.mielczarek.org/code/mozilla/bookmarklet.html


(function() {
	//GLOBALS
		//globals for classMausWork
		var gSelectedElement;	//currently only one selection
		var gHoverElement;		//whatever element the mouse is over
		var gHovering=false;	//mouse is over something
		var gObjArrMW=[];	//global array of classMausWork objects.  for removing event listeners when done selecting.
		
		//extended	
		var infoDiv;		//currently just container for InfoDivHover, might add more here
		var infoDivHover;	//container for hoverText text node.
		var hoverText;		//show information about current element that the mouse is over
		//const EXPERIMENTAL_NEW_CODE=true;	//debugging. new features.
	
	
	//START
	SetupDOMSelection();	



		
	//(Section 1) Element Selection
	function SetupDOMSelection()
	{

		{
			//setup event listeners
			//var pathx="//div | //span | //table | //td | //tr | //ul | //ol | //li | //p";
			var pathx="//div | //span | //table | //th | //td | //tr | //ul | //ol | //li | //p | //iframe";
			var selection=$XPathSelect(pathx);
			for(var element, i=0;element=selection(i);i++)
			{			
				if(element.tagName.match(/^(div|span|table|td|tr|ul|ol|li|p)$/i))	//redundant check.
				{
					var m = new classMausWork(element);
					gObjArrMW.push(m);
					attachMouseEventListeners(m);
				}
			}
			document.body.addEventListener('mousedown',MiscEvent,false);
			document.body.addEventListener('mouseover',MiscEvent,false);
			document.body.addEventListener('mouseout',MiscEvent,false);
			document.addEventListener('keypress',MiscEvent,false);
		}
		{
			//setup informational div to show which element the mouse is over.
			infoDiv=document.createElement('div');
			var s=infoDiv.style;
			s.position='fixed';
			s.top='0';
			s.right='0';
			
			s.display='block';
			s.width='auto';
			s.padding='0px';

			document.body.appendChild(infoDiv);
			infoDivHover=document.createElement('div');

			s=infoDivHover.style;
			s.fontWeight='bold';			
			s.padding='3px';
			s.Opacity='0.8';
			s.borderWidth='thin';
			s.borderStyle='solid';
			s.borderColor='white';
			s.backgroundColor='black';
			s.color='white';
			
			infoDiv.appendChild(infoDivHover);			
			hoverText=document.createTextNode('selecting');
			infoDivHover.appendChild(hoverText);
		}
	}
	
	function CleanupDOMSelection()
	{
		for(var m; m=gObjArrMW.pop(); )
		{
			detachMouseEventListeners(m);
		}
		ElementRemove(infoDiv);
		document.body.removeEventListener('mousedown',MiscEvent,false);
		document.body.removeEventListener('mouseover',MiscEvent,false);
		document.body.removeEventListener('mouseout',MiscEvent,false);		
		document.removeEventListener('keypress',MiscEvent,false);
	}	

	function attachMouseEventListeners(c)
	{
		//c is object of class classMausWork
		c.element.addEventListener("mouseover",c.mouse_over,false);				
		c.element.addEventListener("mouseout",c.mouse_out,false);	
		c.element.addEventListener("mousedown",c.mouse_click,false);		
	}

	function detachMouseEventListeners(c)
	{
		//c is object of class classMausWork
		c.resetElementStyle();
		c.element.removeEventListener("mouseover",c.mouse_over,false);				
		c.element.removeEventListener("mouseout",c.mouse_out,false);	
		c.element.removeEventListener("mousedown",c.mouse_click,false);		
	}

	//mouse event  handling class for element, el.
	function classMausWork(element)
	{	
		//store information about the element this object is assigned to handle. element,  original style, etc.	
		this.element=element;
		
		var elementStyle=element.getAttribute('style');
		var target;
		
		this.mouse_over=function(ev)
		{	
			if(gHovering)return;
			var e=element;			
			var s=e.style;
			s.backgroundColor='yellow';
			s.borderWidth='thin';
			s.borderColor='lime';
			s.borderStyle='solid';					
			InfoMSG(ElementInfo(e),'yellow','blue','yellow');
			gHoverElement=e;
			gHovering=true;
			target=ev.target;
			ev.stopPropagation();		
		};
		
		this.mouse_out=function(ev)
		{
			if(!gHovering)return;
			if(gHoverElement!=element ||ev.target!=target)return;
			var e=element;
			e.setAttribute('style',elementStyle);
			InfoMSG('-','white','black','white');	
			gHoverElement=null;
			gHovering=false;
			target=null;
			//ev.stopPropagation();
		};
		
		this.mouse_click=function(ev)
		{
			if(!gHovering)return;
			if(gHoverElement!=element ||ev.target!=target)return;
			var e=element;
			e.setAttribute('style',elementStyle);
			ev.stopPropagation();			
			CleanupDOMSelection();			
			gHoverElement=null;
			gHovering=false;
			target=null;
			
			if(ev.button==0)
			{
				gSelectedElement=e;
				ElementSelected(e);	//finished selecting, cleanup then move to next part (section 2), element isolation.
			}
		};
		
		this.resetElementStyle=function()
		{
			element.setAttribute('style',elementStyle);
		};		
	}

	function MiscEvent(ev)		//keypress, and mouseover/mouseout/mousedown event on body.  cancel selecting.
	{
		if(ev.type=='mouseout' && !gHovering)
		{
			InfoMSG('-','white','black','white');
		}
		else if(ev.type=='mouseover' && !gHovering)
		{
			InfoMSG('cancel','yellow','red','yellow');
		}
		else //keypress on document or mousedown on body, cancel ops.
		{
			CleanupDOMSelection();
		}
	}
	
	function InfoMSG(text,color,bgcolor,border)
	{
		
		var s=infoDivHover.style;
		if(color)s.color=color;
		if(bgcolor)s.backgroundColor=bgcolor;
		if(border)s.borderColor=border;
		if(text)hoverText.data=text;
	}
	


	
	
	//(Section 2) Element Isolation
	function ElementSelected(element)	//finished selecting element.  setup string to prompt user.
	{
		PromptUserXpath(ElementInfo(element));
	}
	
	
	function PromptUserXpath(defaultpath)		//prompt user, isolate element.
	{
		var userpath = prompt("XPath of elements to isolate : ", defaultpath);
		if(userpath && userpath.length>0)
		{
			var addPredicate = "[count(./ancestor-or-self::head)=0][count(./ancestor-or-self::title)=0]";	//exclude head & title elements from selection so they aren't removed
			var addPath = "//script | //form | //object | //embed";	//include these elements in selection for removal
			var pathx=TransformXPath_NoAncestorDescendentSelf(userpath, addPredicate, addPath);		//the xpath selection of all elements to be removed/deleted.
			
			try
			{
				var element;
				var elements=$XPathSelect(pathx);	
				for(var i=0;element=elements(i);i++)
				{			

					if(!element.nodeName.match(/^(head|title)$/i))	//redundant check.
					{
						ElementRemove(element);
					}
				}
			}
			
			catch(err)
			{
				alert("wtf: "+err);
			}
			
		}
	}
	
		
	
	//support
	function $XPathSelect(p, context) 
	{
	  if (!context) context = document;
	  var i, arr = [], xpr = document.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
	  return function(x) { return xpr.snapshotItem(x); };	//closure.  wooot!  returns function-type array of elements (usually elements, or something else depending on the xpath expression).
	}
	
	function ElementRemove(e)
	{
		if(e)e.parentNode.removeChild(e);
	}
	
	function ElementInfo(element)
	{
		var txt='';
		if(element)
		{
			txt=element.tagName.toLowerCase();		//txt=element.tagName;
			txt=attrib(txt,element,'id');
			txt=attrib(txt,element,'class');	
			txt='//'+txt;
		}
		return txt;
		
		function attrib(t,e,a)
		{			
			if(e.hasAttribute(a))
			{
				t+="[@"+a+"='"+e.getAttribute(a)+"']";
			}
			return t;
		}
		
	}


	
	//function to 'invert' the XPath by selecting all elements that are not ancestor and not descendent and not self.
	function TransformXPath_NoAncestorDescendentSelf(u, includePredicates, includePaths)
	{	
		
		//sample input (u):					//div[@class='sortbox']
		//sample output						//*[  not(./descendant-or-self::*=//div[@class='sortbox'])][  not(./ancestor-or-self::*=//div[@class='sortbox'])]
		//sample output with additional conditions:		//*[  not(./descendant-or-self::*=//div[@class='sortbox'])][  not(./ancestor-or-self::*=//div[@class='sortbox'])][count(./ancestor-or-self::head)=0][count(./ancestor-or-self::title)=0]
		
			//obsolete method.  much faster but can only be used for limited types of (simple) xpath expressions -- unlike the current version, which should be able to convert any xpath.
			//input:			table[@id='topbar']
			//output:			//*[not(./descendant-or-self::table[@id='topbar']) and not(./ancestor-or-self::table[@id='topbar'])]
			//output (alternative):	//*[count(./descendant-or-self::table[@id='topbar'])=0 and count(./ancestor-or-self::table[@id='topbar'])=0]
		
		
		var o1=	'./descendant-or-self::*='+gr(u);
		o1=	'not' + gr(o1);
		o1=	nt(o1);	
		var o2= './ancestor-or-self::*='+gr(u);
		o2=	'not' + gr(o2);
		o2=	nt(o2);

		var o=	'//*'+o1+o2;
		if(includePredicates && includePredicates.length>0)	o += includePredicates;
		if(includePaths && includePaths.length>0) o += ' | ' + includePaths;
		return o;
		
		
		function nt(term){return wrap(term,'[]');}	//node test; predicate - enclose with bracket.
		function gr(term){return wrap(term,'()');}	//group - parenthesize.
		function wrap(term, enclosure){return enclosure.charAt(0)+term+enclosure.charAt(1);}
	}	
	


	
})();

HTML/JavaScript - Select list - Add/Remove Options (DOM)

from http://www.mredkj.com/tutorials/tutorial005.html


Overview

* Insert Before Selected - A new option is created and added above the selected option (as determined by selectedIndex). If none are selected, then no option is added.
* Remove Selected - Deletes the selected option (or options) from the list. If no options are selected, no options are deleted.
* Append Last - No matter what is selected, a new option is added at the end.
* Remove Last - No matter what is selected, the last option is deleted from the list.


Explanation

According to DOM Level 1, the following is the syntax for the add and remove methods in HTMLSelectElement:

void add(in HTMLElement element, in HTMLElement before) raises(DOMException);
void remove(in long index);

The add method takes two arguments: the element to add, and the element to insert before. The spec also says you can add to the end of the list by passing null as the second argument.

The remove method just takes a number: the index of the option to be removed.


The JavaScript
<script language="JavaScript" type="text/javascript">
<!--
var count1 = 0;
var count2 = 0;

function insertOptionBefore(num)
{
  var elSel = document.getElementById('selectX');
  if (elSel.selectedIndex >= 0) {
    var elOptNew = document.createElement('option');
    elOptNew.text = 'Insert' + num;
    elOptNew.value = 'insert' + num;
    var elOptOld = elSel.options[elSel.selectedIndex];  
    try {
      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew, elSel.selectedIndex); // IE only
    }
  }
}

function removeOptionSelected()
{
  var elSel = document.getElementById('selectX');
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) {
      elSel.remove(i);
    }
  }
}

function appendOptionLast(num)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = 'Append' + num;
  elOptNew.value = 'append' + num;
  var elSel = document.getElementById('selectX');

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}

function removeOptionLast()
{
  var elSel = document.getElementById('selectX');
  if (elSel.length > 0)
  {
    elSel.remove(elSel.length - 1);
  }
}
//-->
</script>



The HTML
<form>
<input type="button" value="o" onclick="insertOptionBefore(count1++);" />
Insert Before Selected<br />
<input type="button" value="o" onclick="removeOptionSelected();" />
Remove Selected<br />
<select id="selectX" size="10" multiple="multiple">
<option value="original1" selected="selected">Orig1</option>
<option value="original2">Orig2</option>
</select>
<br />
<input type="button" value="o" onclick="appendOptionLast(count2++);" />
Append Last<br />
<input type="button" value="o" onclick="removeOptionLast();" />
Remove Last
</form>

Java DOM: Sample XPath Query

    try
    {
      XPath xpath = XPathFactory.newInstance().newXPath();
      Element e = (Element) xpath.evaluate("/Archive/Section/Description", parentNode,
          XPathConstants.NODE);
      printXmlNode(e);
    }
    catch (XPathExpressionException e)
    {
      e.printStackTrace();
    }

Java DOM: Printing the Content of a Node

    try
    {
      // Set up the output transformer
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      trans.setOutputProperty(OutputKeys.INDENT, "yes");

      // Print the DOM node

      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      DOMSource source = new DOMSource(node);
      trans.transform(source, result);
      String xmlString = sw.toString();

      System.out.println(xmlString);
    }
    catch (TransformerException e)
    {
      e.printStackTrace();
    }

Java DOM : Creating an XML Document from XML File

// description of your code here

    try
    {
      //
      // Create the XML Document
      //

      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.parse(filePath);

      // ...

    }
    catch (Exception e)
    {
      // ...
    }

Simple Java DOM XML Processing Example

// Simple Java DOM XML Processing Example
// Source: http://www.genedavis.com/library/xml/java_dom_xml_creation.php


import java.io.*;

import org.w3c.dom.*;

import javax.xml.parsers.*;

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class DomXmlExample {

    /**
     * Our goal is to create a DOM XML tree and then print the XML.
     */
    public static void main (String args[]) {
        new DomXmlExample();
    }

    public DomXmlExample() {
        try {
            /////////////////////////////
            // Creating an empty XML Document

            // We need a Document
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            ////////////////////////
            // Creating the XML tree

            // create the root element and add it to the document
            Element root = doc.createElement("root");
            doc.appendChild(root);

            // create a comment and put it in the root element
            Comment comment = doc.createComment("Just a thought");
            root.appendChild(comment);

            // create child element, add an attribute, and add to root
            Element child = doc.createElement("child");
            child.setAttribute("name", "value");
            root.appendChild(child);

            // add a text element to the child
            Text text = doc.createTextNode("Filler, ... I could have had a foo!");
            child.appendChild(text);

            /////////////////
            // Output the XML

            // set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            // create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            String xmlString = sw.toString();

            // print xml
            System.out.println("Here's the xml:\n\n" + xmlString);

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
« Newer Snippets
Older Snippets »
Showing 1-10 of 23 total  RSS