DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Coding Topics

article thumbnail
Java: RegEx: Splitting A Space-, Comma-, And Semi-colon Separated List
// Greedy RegEx quantifier used // X+ = X, one or more times // [\\s,;]+ = one or more times of either \s , or ; String test_data = "hello world, this is a test, ;again"; _logger.debug("Source: " + test_data); for (String tag : test_data.split("[\\s,;]+")) { _logger.debug("Received tag: [" + tag + "]"); }
August 5, 2007
by Snippets Manager
· 38,263 Views · 1 Like
article thumbnail
Class PHP XMLHttpRequest Emulator Using Curl.
// XMLHttpRequest emulator using curl. * @version 0.5 2007/07/16 23:00:13 * @link http://www.myopera.com/moises-l Comments & suggestions * @link http://files.myopera.com/moises-l/files/class.XMLHttpRequest.php Available at * @copyright GPL © 2007, Moises Lima * @license http://creativecommons.org/licenses/by-nc-sa/2.5/ Released under a Creative Commons License */ class XMLHttpRequest{ /** * String version of data returned from server process. * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-responsetext * @access public * @var string * @name $responseText */ var $responseText; /** * DOM-compatible document object of data returned from server process. * which can be examined and parsed using W3C DOM node tree methods and properties * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-responsexml * @access public * @var object * @name $responseXML */ var $responseXML; /** * The http status code returned by server as a number (e.g. 404 for "Not Found" or 200 for "OK"). * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-status * @access public * @var number * @name $status */ var $status; /** * The http status code returned by server as a string (e.g. "Not Found" or "OK") * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-statustext * @access public * @var string * @name $statusText */ var $statusText; /** * The state of the object * 0 = uninitialized * 1 = loading * 2 = loaded * 3 = interactive * 4 = complete * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-readystate * @access public * @var number * @name $readyState */ var $readyState; /** * The error string * @link http://www.w3.org/TR/XMLHttpRequest/#notcovered * @access public * @var string * @name $error */ var $error; /** * An event handler for an event that fires at every state change * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-onreadystatechange * @access public * @name $onreadystatechange */ var $onreadystatechange; /** * An event handler for an event that fires at finished requisition * @link http://www.w3.org/TR/XMLHttpRequest/#notcovered * @access public * @name $onload */ var $onload; /** * An event handler for an event that fires at errors * @link http://www.w3.org/TR/XMLHttpRequest/#notcovered * @access public * @name $onerror */ var $onerror; // http://www.w3.org/TR/XMLHttpRequest/#notcovered /** * cURL handle * @access private * @name $curl */ var $curl; /** * responseHeaders process * @access private * @name $responseHeaders */ var $responseHeaders; /** * cURL headers * @access private * @name $headers */ var $headers=array("Connection: Keep-Alive","Keep-Alive: 300"); /** * Curl info * @access public * @name $curl_version * @var Array */ var $curl_version; /** * TRUE to follow any "Location: " header that the server sends as part of the HTTP header. * @access public * @name $followLocation * @var Bolean */ var $followLocation; /** * Class constructor (compatibility with PHP 4). */ function XMLHttpRequest(){ $this->open="function open() { [native code] }"; $this->setRequestHeader="function setRequestHeader() { [native code] }"; $this->getAllResponseHeaders="function getAllResponseHeaders() { [native code] }"; $this->getResponseHeader="function getResponseHeader() { [native code] }"; $this->send="function send() { [native code] }"; $this->readyState = 0; $this->curl = curl_init(); $this->curl_version = curl_version(); $this->followLocation=false; curl_setopt($this->curl, CURLOPT_HEADER, true); if(isset($_SERVER['HTTP_USER_AGENT'])){ curl_setopt($this->curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ); }else{ curl_setopt($this->curl, CURLOPT_USERAGENT, "XMLHttpRequest/0.2"); } curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this->curl, CURLOPT_TIMEOUT, 1000); curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 300); } /** * @access private */ function __toString(){ return "[object XMLHttpRequest]"; } /** * Specifies the method, URL, and other optional attributes of a request. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-open * @param String $method HTTP Methods defined in section 5.1.1 of RFC 2616 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html * @param String $url Specifies either the absolute or a relative URL of the data on the Web service. * @param Bolean $async FakeSauro Erectus. * @param String $user specifies the name of the user for HTTP authentication. * @param String $password specifies the password of the user for HTTP authentication. * @return void */ function open($method, $url, $async=true, $user="", $password=""){ $this->readyState = 1; if(!empty($method) && !empty($url)){ $method=strtoupper(trim($method)); /* if(!ereg("^(GET|POST|HEAD|PUT|DELETE|OPTIONS)$",$method)){ throw new Exception("Unknown HTTP request method [$method]"); } */ if(isset($_SERVER['HTTP_REFERER']) && empty($this->url) ){ curl_setopt($this->curl, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']); }elseif(isset($this->url)){ curl_setopt($this->curl, CURLOPT_REFERER, $this->url); } $this->url = $url; curl_setopt($this->curl, CURLOPT_URL, $this->url); if($method=="POST"){ curl_setopt($this->curl, CURLOPT_POST, 1); }elseif($method=="GET"){ curl_setopt($this->curl, CURLOPT_POST, 0); }else{ curl_setopt($this->curl, CURLOPT_POST, 0); curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $method); } } if(ereg("^(https)",$url)){ curl_setopt($this->curl,CURLOPT_SSL_VERIFYPEER,false); } if(!empty($user) && !empty($password)){ curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($this->curl,CURLOPT_USERPWD,$user.":". $password); } } /** * Assigns a label/value pair to the header to be sent with a request. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-setrequestheader * @param String $label Specifies the header label. * @param String $value Specifies the header value. * @return void */ function setRequestHeader($label, $value){ $this->headers[] = "$label: $value"; curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers); } /** * Returns complete set of headers (labels and values) as a string. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-getallresponseheaders * @return string Complete set of headers (labels and values) as a string */ function getAllResponseHeaders(){ return $this->responseHeaders; } /** * Returns the value of the specified http header. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-getresponseheader. * @param String $label * @return String|null The string value of a single header label. */ function getResponseHeader($label){ $value=array(); preg_match_all('/(?s)'.$label.': (.*?)\s\n/i', $this->responseHeaders , $value); if(count($value ) > 0){ return implode(', ' , $value[1]); } return null; } function getResponseHeader2($label){ $value=array(); preg_match('/(?s)'.$label.': (.*?)\s\n/i', $this->responseHeaders , $value); if(count($value ) > 0){ return $value[1]; } return null; } /** * Transmits the request, optionally with postable string or DOM object data. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-getresponseheader * @param String $data * @return void */ function send($data=null){ $sT=array(); if(isset($this->onreadystatechange))eval($this->onreadystatechange); if($data){ curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data); } $this->response= curl_exec($this->curl); $header_size = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE); $this->responseHeaders = substr($this->response, 0, $header_size - 4); if($this->followLocation){ $location=array(); while(preg_match('/Location:(.*?)\n/', $this->responseHeaders, $location)){ curl_setopt($this->curl, CURLOPT_REFERER, $this->url); $url = @parse_url(trim(array_pop($location))); if (!$url){ break; } $last_url = parse_url(curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL)); if (!isset($url['scheme']))$url['scheme'] = $last_url['scheme']; if (!isset($url['host']))$url['host'] = $last_url['host']; if (!isset($url['path']))$url['path'] = $last_url['path']; $this->url = $url['scheme'] . '://' . $url['host'] . $url['path'] . (isset($url['query'])?'?'.$url['query']:''); curl_setopt($this->curl, CURLOPT_POST, 0); //curl_setopt($this->curl, CURLOPT_POSTFIELDS,0); curl_setopt($this->curl, CURLOPT_URL, $this->url); $this->response= curl_exec($this->curl); $header_size = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE); $this->responseHeaders = substr($this->response, 0, $header_size - 4); } } $this->error = curl_error($this->curl); if ($this->error) { if(isset($this->onerror))eval($this->onerror); } $this->readyState = 2; if(isset($this->onreadystatechange))eval($this->onreadystatechange); $this->responseText = substr($this->response, $header_size); preg_match('/^HTTP\/\d\.\d\s+(\d{3}) (.*)\s\n/i', $this->responseHeaders , $sT); if(count($sT ) > 2){ $this->responseHeaders = ereg_replace ($sT[0], "", $this->responseHeaders); $this->status = $sT[1]; $this->statusText = $sT[2]; } if(version_compare(PHP_VERSION , "5", ">=")){ if (preg_match('/(application|text)\/[\w+\+]?xml/i', $this->getResponseHeader("Content-Type"))){ libxml_use_internal_errors(true); $this->responseXML = new DOMDocument(); $this->responseXML->loadXML($this->responseText); $errors = libxml_get_errors(); if (!empty($errors)){ $this->responseXML=null; $error=$errors[0]; $this->error= trim($error->message) ." in $this->url on line $error->line column: $error->column "; if(isset($this->onerror))eval($this->onerror); } libxml_clear_errors(); } } $this->readyState = 3; if(isset($this->onreadystatechange))eval($this->onreadystatechange); $this->headers=Array(); $this->readyState = 4; if(isset($this->onreadystatechange))eval($this->onreadystatechange); if(isset($this->onload))eval($this->onload); } /** * Closes a cURL session and frees all resources. * @name close * @access public * @return void */ function close(){ curl_close($this->curl); } } ?>
July 18, 2007
by Snippets Manager
· 3,579 Views
article thumbnail
PHP - Change Active Directory Password
You are changing the password for ". $info[$i]["givenname"][0] .", " . $info[$i]["sn"][0] ." (" . $info[$i]["samaccountname"][0] .") to " . $_POST['user_pass'] ." \n"; $passwd1 = $_POST['user_pass']; $userDn = $info[$i]["distinguishedname"][0]; $newPassword = $passwd1; $newPassword = "\"" . $newPassword . "\""; $len = strlen($newPassword); for ($i = 0; $i < $len; $i++){ $newPassw .= "{$newPassword{$i}\000";} $newPassword = $newPassw; $userdata["unicodePwd"] = $newPassword; $result = ldap_mod_replace($ldap, $userDn , $userdata); if ($result) echo "Your password has been changed!" ; else echo "There was a problem changing your password, please call IT for help"; } } @ldap_close($ldap); ?>
May 23, 2007
by Snippets Manager
· 4,669 Views
article thumbnail
Remove Empty XML Nodes
Remove nodes like (without attributes & without children) public static void RemoveEmptyNodes(XmlDocument doc) { XmlNodeList nodes = doc.SelectNodes("//node()"); foreach (XmlNode node in nodes) if ((node.Attributes.Count == 0) && (node.ChildNodes.Count == 0)) node.ParentNode.RemoveChild(node); }
May 15, 2007
by Snippets Manager
· 8,568 Views
article thumbnail
Java: Lucene: Simple In-Memory Search Example
// Adapted from http://javatechniques.com/blog/lucene-in-memory-text-search-example // Works with present APIs in Lucene 2.1.0 /** * A simple example of an in-memory search using Lucene. */ import java.io.IOException; import java.io.StringReader; import org.apache.lucene.search.Hits; import org.apache.lucene.search.Query; import org.apache.lucene.document.Field; import org.apache.lucene.search.Searcher; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.document.Document; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.analysis.standard.StandardAnalyzer; public class InMemoryExample { public static void main(String[] args) { // Construct a RAMDirectory to hold the in-memory representation // of the index. RAMDirectory idx = new RAMDirectory(); try { // Make an writer to create the index IndexWriter writer = new IndexWriter(idx, new StandardAnalyzer(), true); // Add some Document objects containing quotes writer.addDocument(createDocument("Theodore Roosevelt", "It behooves every man to remember that the work of the " + "critic, is of altogether secondary importance, and that, " + "in the end, progress is accomplished by the man who does " + "things.")); writer.addDocument(createDocument("Friedrich Hayek", "The case for individual freedom rests largely on the " + "recognition of the inevitable and universal ignorance " + "of all of us concerning a great many of the factors on " + "which the achievements of our ends and welfare depend.")); writer.addDocument(createDocument("Ayn Rand", "There is nothing to take a man’s freedom away from " + "him, save other men. To be free, a man must be free " + "of his brothers.")); writer.addDocument(createDocument("Mohandas Gandhi", "Freedom is not worth having if it does not connote " + "freedom to err.")); // Optimize and close the writer to finish building the index writer.optimize(); writer.close(); // Build an IndexSearcher using the in-memory index Searcher searcher = new IndexSearcher(idx); // Run some queries search(searcher, "freedom"); search(searcher, "free"); search(searcher, "progress or achievements"); searcher.close(); } catch (IOException ioe) { // In this example we aren’t really doing an I/O, so this // exception should never actually be thrown. ioe.printStackTrace(); } catch (ParseException pe) { pe.printStackTrace(); } } /** * Make a Document object with an un-indexed title field and an indexed * content field. */ private static Document createDocument(String title, String content) { Document doc = new Document(); // Add the title as an unindexed field… doc.add(new Field("title", title, Field.Store.YES, Field.Index.NO)); // …and the content as an indexed field. Note that indexed // Text fields are constructed using a Reader. Lucene can read // and index very large chunks of text, without storing the // entire content verbatim in the index. In this example we // can just wrap the content string in a StringReader. doc.add(new Field("content", new StringReader(content))); return doc; } /** * Searches for the given string in the "content" field */ private static void search(Searcher searcher, String queryString) throws ParseException, IOException { // Build a Query object QueryParser parser = new QueryParser("content", new StandardAnalyzer()); Query query = parser.parse(queryString); // Search for the query Hits hits = searcher.search(query); // Examine the Hits object to see if there were any matches int hitCount = hits.length(); if (hitCount == 0) { System.out.println("No matches were found for \"" + queryString + "\""); } else { System.out.println("Hits for \"" + queryString + "\" were found in quotes by:"); // Iterate over the Documents in the Hits object for (int i = 0; i < hitCount; i++) { Document doc = hits.doc(i); // Print the value that we stored in the "title" field. Note // that this Field was not indexed, but (unlike the // "contents" field) was stored verbatim and can be // retrieved. System.out.println(" " + (i + 1) + ". " + doc.get("title")); } } System.out.println(); } }
May 15, 2007
by Snippets Manager
· 6,246 Views
article thumbnail
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) { // ... }
May 14, 2007
by Snippets Manager
· 19,278 Views
article thumbnail
How To Convert A String With A Date To A Calendar
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date date = sdf.parse(strDate); Calendar cal = Calendar.getInstance(); cal.setTime(date);
May 8, 2007
by Snippets Manager
· 160,548 Views · 3 Likes
article thumbnail
Range() In Java
A range is a very handy feature of programing languages like Python. * range( 10 ) -> 0 1 2 3 4 5 6 7 8 9 * range( 5, 10 ) -> 5 6 7 8 9 * range( 0, 10, 3 ) -> 0 3 6 9 * range( '0', '9' ) -> 012345678 With an extended for loop it is possible to use such a feature too: /* * This project is made available under the terms of the BSD license, more information can be found at * http://www.opensource.org/licenses/bsd-license.html * * Copyright (c) 2007. Christian Ullenboom (http://www.tutego.com/) and contributors. All rights reserved. */ package com.tutego; import java.util.Iterator; /** * Class that generates immutable sequences (ranges) as Iterable * objects. A range represents a start (0 if not given), an stop (mandatory) and * an optional step (1 by default). The start value is included in the range, * the stop value is exclusive. Every range is handled by an Iterable * which can by used in an extended for loop. * * * for ( int i : range( 0, 10, 3 ) ) * System.out.print( i + " " ); // 0 3 6 9 * * * @author Christian Ullenboom (tutego) * @version 1.0 */ public class Range { public static Iterable range( final int start, final int stop, final int step ) { if ( step <= 0 ) throw new IllegalArgumentException( "step > 0 isrequired!" ); return new Iterable() { public Iterator iterator() { return new Iterator() { private int counter = start; public boolean hasNext() { return counter < stop; } public Integer next() { try { return counter; } finally { counter += step; } } public void remove() { } }; } }; } public static Iterable range( final int start, final int stop ) { return range( start, stop, 1 ); } public static Iterable range( final int stop ) { return range( 0, stop, 1 ); } } This is an example: package com.tutego; import static com.tutego.Range.range; public class RangeDemo { public static void main( String[] args ) { for ( int i : range( 10 ) ) System.out.print( i + " " ); System.out.println(); for ( int i : range( 5, 10 ) ) System.out.print( i + " " ); System.out.println(); for ( int i : range( 0, 10, 3 ) ) System.out.print( i + " " ); System.out.println(); for ( int i : range( '0', '9' ) ) System.out.print( (char) i ); System.out.println(); String[] a = { "Mary", "had", "a", "little", "lamb" }; for ( int i : range(a.length ) ) System.out.printf( "%d %s%n", i, a[i] ); } }
April 24, 2007
by Snippets Manager
· 32,673 Views · 1 Like
article thumbnail
Reading Corrupted/partial Zip Files In Python
First a simple script for reading non-corruted zipfiles in python: filename = 'foo.zip' import zipfile z = zipfile.ZipFile(filename) for i in z.infolist(): print i.filename, i.file_size z.read('somefile') Next we use 'zip -FF foo.zip' to fix the zipfile, before reading it: filename = 'foo.zip' import zipfile try: z = zipfile.ZipFile(filename) except zipfile.BadZipfile: import commands commands.getoutput('zip -FF '+filename) z = zipfile.ZipFile(filename) for i in z.infolist(): print i.filename, i.file_size try: z.read('somefile') except zipfile.BadZipfile: print 'Bad CRC-32' In short: use 'zip -FF file.zip' to fix the file. It will restore the filelist.
April 9, 2007
by Snippets Manager
· 10,062 Views · 3 Likes
article thumbnail
Get MD5 Hash In A Few Lines Of Java
1 import java.security.*; 2 import java.math.*; 3 4 public class MD5 { 5 public static void main(String args[]) throws Exception{ 6 String s="This is a test"; 7 MessageDigest m=MessageDigest.getInstance("MD5"); 8 m.update(s.getBytes(),0,s.length()); 9 System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16)); 10 } 11 }
March 18, 2007
by Greg Miller
· 46,200 Views · 2 Likes
article thumbnail
JavaScript: Programmatically Click The Form Submit Button
// Programmatically Click the Form Submit Button // by using the 'click()' method submitTags : function() { var btnSubmitTags = document.getElementById( TagsHelperConfig.FORM_TAGS_ENTRY_SUBMIT_BUTTON_ID ); // Programmatically click the submit button btnSubmitTags.click(); }
March 6, 2007
by Snippets Manager
· 12,502 Views · 3 Likes
article thumbnail
Add A Jar File To Java Load Path At Run Time
import java.net.URL; import java.io.IOException; import java.net.URLClassLoader; import java.net.MalformedURLException; public class JarFileLoader extends URLClassLoader { public JarFileLoader (URL[] urls) { super (urls); } public void addFile (String path) throws MalformedURLException { String urlPath = "jar:file://" + path + "!/"; addURL (new URL (urlPath)); } public static void main (String args []) { try { System.out.println ("First attempt..."); Class.forName ("org.gjt.mm.mysql.Driver"); } catch (Exception ex) { System.out.println ("Failed."); } try { URL urls [] = {}; JarFileLoader cl = new JarFileLoader (urls); cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar"); System.out.println ("Second attempt..."); cl.loadClass ("org.gjt.mm.mysql.Driver"); System.out.println ("Success!"); } catch (Exception ex) { System.out.println ("Failed."); ex.printStackTrace (); } } }
February 23, 2007
by Snippets Manager
· 31,651 Views
article thumbnail
Retrieving All Parameters to a Java Servlet
Here's a really simple code snippet for retrieving parameters to a Java servlet.
February 10, 2007
by Snippets Manager
· 27,261 Views · 2 Likes
article thumbnail
Get The Unix Epoch Time In One Line Of C#
One line of C#, so much awesomeness: The Unix epoch time.
January 3, 2007
by Greg Miller
· 31,192 Views
article thumbnail
Convert Single Object To List
List list = java.util.Arrays.asList("foo");
October 12, 2006
by Snippets Manager
· 80,861 Views · 3 Likes
article thumbnail
Simple XML-RPC In PHP (using CURL)
# Using the XML-RPC extension to format the XML package $request = xmlrpc_encode_request("weblogUpdates.ping", array("Copenhagen Ruby Brigade", "http://copenhagenrb.dk/") ); # Using the cURL extension to send it off, # first creating a custom header block $header[] = "Host: rpc.technorati.com"; $header[] = "Content-type: text/xml"; $header[] = "Content-length: ".strlen($request) . "\r\n"; $header[] = $request; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, "http://rpc.technorati.com/rpc/ping"); # URL to post to curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable curl_setopt( $ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' ); # This POST is special, and uses its specified Content-type $result = curl_exec( $ch ); # run! curl_close($ch); echo $result;
September 15, 2006
by Snippets Manager
· 7,182 Views
article thumbnail
Loop In PHP Using For (Descending)
For those times you need to do a loop in PHP, but have the outcome be in descending order (ie, start at 10 and end at 1). $totalcode="10"; for($i=$totalcode; $i>0; $i--){ echo"$i"; }
June 20, 2006
by Snippets Manager
· 13,234 Views
article thumbnail
Python Script To Clean Desktop.
This little script cleans my desktop. from os import listdir as ls, mkdir, remove as rm from os.path import join, isdir, exists from shutil import copyfile as copy """ I always downloads pictures and documents directly onto my desktop, as a result my desktop turns out to look like a recycle bin. This script helps me to organize these small files into directories according to their types. @author : PhoenixR """ exts = {'jpg' : 'Pictures', 'png' :'Pictures', 'gif' :'Pictures', 'pdf' : 'Documents', 'doc':'Documents' , 'ppt' : 'Documents'} def get_type(file) : if exts.has_key( file[-3:] ) : return exts[file[-3:]] else : return None def new_dir( path, file, type=None) : """ Make a new directory is the file type hasn't been recognized. Copy the file to the new directory, and remove the original copy. """ if type is None : return if not exists( join(path, type) ) : mkdir( join(path, type) ) copy( join(path, file), join( path, join(type, file) )) print 'File %s is deleted' % join(path, file) rm( join(path,file) ) def main(root=None) : if root is None : path = '.' else : path = root files = ls(path) for file in files : if not isdir( join( path, file) ) : new_dir( path, file, get_type( file) ) if __name__ == '__main__' : main()
June 12, 2006
by Snippets Manager
· 3,093 Views
article thumbnail
Send Email with Attachment(s) In Python
This code snippet will help you send an email (with attachments) in Python.
May 16, 2006
by Snippets Manager
· 39,916 Views · 1 Like
article thumbnail
Script Excel From Python
from win32com.client import constants, Dispatch import pythoncom import os borderTop = 3 borderBottom = 4 borderLeft = 1 borderRight = 2 borderSolid = 1 borderDashed = 2 borderDotted = 3 colorBlack = 1 directionUp = -4162 directionDown = -4121 directionLeft = -4131 directionRight = -4152 class ExcelDocument(object): """ Some convenience methods for Excel documents accessed through COM. """ def __init__(self, visible=False): self.app = Dispatch("Excel.Application") self.app.Visible = visible self.sheet = 1 def new(self, filename=None): """ Create a new Excel workbook. If 'filename' specified, use the file as a template. """ self.app.Workbooks.Add(filename) def open(self, filename): """ Open an existing Excel workbook for editing. """ self.app.Workbooks.Open(filename) def set_sheet(self, sheet): """ Set the active worksheet. """ self.sheet = sheet def get_range(self, range): """ Get a range object for the specified range or single cell. """ return self.app.ActiveWorkbook.Sheets(self.sheet).Range(range) def set_value(self, cell, value=''): """ Set the value of 'cell' to 'value'. """ self.get_range(cell).Value = value def get_value(self, cell): """ Get the value of 'cell'. """ value = self.get_range(cell).Value if isinstance(value, tuple): value = [v[0] for v in value] return value def set_border(self, range, side, line_style=borderSolid, color=colorBlack): """ Set a border on the specified range of cells or single cell. 'range' = range of cells or single cell 'side' = one of borderTop, borderBottom, borderLeft, borderRight 'line_style' = one of borderSolid, borderDashed, borderDotted, others? 'color' = one of colorBlack, others? """ range = self.get_range(range).Borders(side) range.LineStyle = line_style range.Color = color def sort(self, range, key_cell): """ Sort the specified 'range' of the activeworksheet by the specified 'key_cell'. """ range.Sort(Key1=self.get_range(key_cell), Order1=1, Header=0, OrderCustom=1, MatchCase=False, Orientation=1) def hide_row(self, row, hide=True): """ Hide the specified 'row'. Specify hide=False to show the row. """ self.get_range('a%s' % row).EntireRow.Hidden = hide def hide_column(self, column, hide=True): """ Hide the specified 'column'. Specify hide=False to show the column. """ self.get_range('%s1' % column).EntireColumn.Hidden = hide def delete_row(self, row, shift=directionUp): """ Delete the entire 'row'. """ self.get_range('a%s' % row).EntireRow.Delete(Shift=shift) def delete_column(self, column, shift=directionLeft): """ Delete the entire 'column'. """ self.get_range('%s1' % column).EntireColumn.Delete(Shift=shift) def fit_column(self, column): """ Resize the specified 'column' to fit all its contents. """ self.get_range('%s1' % column).EntireColumn.AutoFit() def save(self): """ Save the active workbook. """ self.app.ActiveWorkbook.Save() def save_as(self, filename, delete_existing=False): """ Save the active workbook as a different filename. If 'delete_existing' is specified and the file already exists, it will be deleted before saving. """ if delete_existing and os.path.exists(filename): os.remove(filename) self.app.ActiveWorkbook.SaveAs(filename) def print_out(self): """ Print the active workbook. """ self.app.Application.PrintOut() def close(self): """ Close the active workbook. """ self.app.ActiveWorkbook.Close() def quit(self): """ Quit Excel. """ return self.app.Quit()
May 16, 2006
by Snippets Manager
· 6,158 Views
  • Previous
  • ...
  • 903
  • 904
  • 905
  • 906
  • 907
  • 908
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×