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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Latest Articles - DZone

article thumbnail
Weighted Random In C# (csharp)
weighted random function in c# 3.0. For c# 2.0 just remove 'this' before WeightedRandom rnd argument. public static partial class Utils { static string WeightCountMustBeGreaterThanZero="Weight count must be greater than zero."; static string ElementWeightMustBeGreaterThanOrEqualToZero="Weight must be greater than or equal to zero"; /// /// Returns random index in weights list with probability based on its weight value. /// /// /// List of weights. /// /// Throws an exception if weights is null. /// /// Throws an exception if weights count is zero. /// Throws an exception if any weight is less than zero. /// /// /// Returned values are within range of zero and weights.Count (exclusive). /// Chance of returned value to be i is weights[i]/weights.Sum(). /// Any weight can be equal to zero. Such index is never selected. /// /// /// < code> /// var weights=new List(new int[]{2,3,5,0}); /// int v=new Random().WeightedRandom(weights); /// /// 20% chance for v==0 /// 30% chance for v==1 /// 50% chance for v==2 /// 0% chance for v==3 /// public static int WeightedRandom(this Random rnd, IList weights) { if (weights == null) { throw new ArgumentNullException("weights"); } if (weights.Count == 0) { throw new ArgumentOutOfRangeException("weights", WeightCountMustBeGreaterThanZero); } List total_weights = new List(); for (int i = 0; i < weights.Count; i++) { if (weights[i] < 0) { throw new ArgumentOutOfRangeException("weights", ElementWeightMustBeGreaterThanOrEqualToZero); } int last; if (total_weights.Count > 0) { last = total_weights[total_weights.Count - 1]; } else { last = 0; } int w = checked(last + weights[i]); total_weights.Add(w); } int total_random = rnd.Next(total_weights[total_weights.Count - 1]); for (int i = 0; i < weights.Count; i++) { if (weights[i] > total_random) { return i; } total_random -= weights[i]; } throw new Exception(); } } NUnit tests: [TestFixture] public class TWeightedRandom { [Test] public void WeightedRandom() { var weights = new List(new int[] { 1, 0, 2, 3 }); List l = new List(); int n = 1000 * 1000; Random rnd = new Random(); for (int i = 0; i < n; i++) { l.Add(rnd.WeightedRandom(weights)); } int a = l.Where(v => v == 0).Count(); int b = l.Where(v => v == 2).Count(); int c = l.Where(v => v == 3).Count(); int z = l.Where(v => v == 1).Count(); Assert.AreEqual(n, a + b + c); Assert.AreEqual(0, z); Assert.Less(Math.Abs((double)b / a - 2), 0.1); Assert.Less(Math.Abs((double)c / a - 3), 0.1); } [Test] public void WeightedRandomOverflow() { int num = 1000 * 1000 * 1000; var weights = new List(new int[] { 2 * num, 2 * num }); try { new Random().WeightedRandom(weights); Assert.Fail("overflow not thrown"); } catch (ArithmeticException e) { } } }
April 26, 2007
by Snippets Manager
· 7,281 Views
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,598 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
· 9,985 Views · 3 Likes
article thumbnail
Greasemonkey Script To Get All Xpath Expressions Of 'a' And 'input Type=submit' Elements In A Document
This greasemonkey script uses the JS files loading mechanism that Carlo Zottmann's uses in his YUI GM script (http://ajaxian.com/archives/using-yui-in-greasemonkey-scripts) The one JS file it loads (which you must host somewhere) must contain 3 functions: getElementXPath(), getElementIdx(), and gm_showXPath() You will find getElementXPath and getElementIdx in a previous post of mine. gm_showXPath() is provided here together with the GM script that loads the file and inserts a DIV on top of the HTML page with a link that when pressed will generate a pop-up and write all the XPATH expressions of 'a' and input submit elements in the document. First the JS function that will call getElementXPath() for each doc element we are intersted on. function gm_showXPath() { var win = window.open("", window.location, "width="+700+",height="+300+",menubar=no,toolbar=no,directories=no,scrollbars=yes,status=no,left=0,top=0,resizable=yes"); var xpathInfo = ""; var elt = null; var links = document.getElementsByTagName('a'); var inputs = document.getElementsByTagName('input'); // add click events xpathInfo += " " + window.location + " "; for (var i=0; i < links.length; i++) { elt = links[i]; var id = elt.getAttribute('id'); if (id != "gm_showxpath") { xpathInfo += "href=" + elt.getAttribute('href') + ",xpath="+getElementXPath(links[i]); xpathInfo += " "; } } for (var j=0; j < inputs.length; j++) { elt = inputs[j]; var type = elt.getAttribute('type'); if (type != null && type.toLowerCase() == 'submit') { xpathInfo += "href=" + elt.getAttribute('href') + ",xpath="+getElementXPath(links[i]); xpathInfo += " "; } } win.document.write(xpathInfo); win.document.close(); } Here is the GM script that loads the JS file hosting the 3 functions I mentioned above. The SHOWXP.run function at the bottom of this GM script is the one that inserts the DIV at the top left corner of the page with a link to generate the XPATH "report" // ==UserScript== // @name Show xpaths. // @namespace http://snippets.dzone.com // @description Demo description goes here // @include http*://* // ==/UserScript== var hostname = "http://your_host_name:xyz"; // Settings used by the loader var GM_YUILOADER_CONFIG = { // List of JS libraries and CSS files to load. obj is used for the object // detection used in the loader. Basically, if the object already exists, // the script is not injected in the page. assets: [ { type: 'js', obj: 'XPATH', url: hostname + '/sandbox/xpath/xpath.js', onload: null} ], // What should be the max allowed loading time? In this example, the // script has 6 seconds to load the libraries and CSS files. timeout: 6000, // How often should the script check if everything was loaded? interval: 300, // What to trigger once all assets are loaded (a string). Example: execute // SHOWXP.run() (this will be eval()'ed later on, hence the string) runFunction: 'SHOWXP.run()', } // START LOADER CODE ////////////////////////////////////////////////////////// var DEMO; var GM_YUILOADER = { // Version of the loader VERSION: 20070103, // Simple internal timer to keep track of the passed time. loaderTimer: 0, }; // This function checks whether everything was loaded yet; if not, it'll wait // some more and call itself again. It'll do so until either all assets are // loaded or the max loading time (GM_YUILOADER.loaderTimer.timeout) is // reached. GM_YUILOADER.loaderCheck = function() { var ud = unsafeWindow.document; // Do we have a green light yet? if (ud.GM_YUILOADER_DOC.go) { DEMO = unsafeWindow.DEMO; delete ud.GM_YUILOADER_DOC; GM_YUILOADER.run(); } // Nope, not yet. Rinse & repeat! else { GM_YUILOADER.loaderTimer += GM_YUILOADER_CONFIG.interval; if (GM_YUILOADER.loaderTimer >= GM_YUILOADER_CONFIG.timeout) { return; } setTimeout(GM_YUILOADER.loaderCheck, GM_YUILOADER_CONFIG.interval); } } // Main function that initiates loading the external JS and/or CSS files GM_YUILOADER.loader = function() { if (document.contentType != 'text/html' || !document.body) { return; } var ud = unsafeWindow.document; // This object holds the important stuff to make this work. It's a property // of GM's unsafeWindow.document object. ud.GM_YUILOADER_DOC = { // Number of JS libraries loaded so far (increased by countLoaded() // below) numberLoaded: 0, // Total number of JS files. numberTotal: 0, // If this is bool true, we're good to go! This is checked by // GM_YUILOADER.loaderCheck(). go: false, // This function will be called by the onLoad events. countLoaded: function() { if (++this.numberLoaded == this.numberTotal) { this.go = true; } } }; // Now let's add the extra tags to the page that'll load the libraries and // CSS files. var head = document.getElementsByTagName('head').item(0); var numAssets = GM_YUILOADER_CONFIG.assets.length; for (var a = 0; a < numAssets; a++) { var tag; var asset = GM_YUILOADER_CONFIG.assets[a]; switch (asset.type) { // CSS file case 'css': tag = document.createElement('link'); tag.href = asset.url; tag.type = 'text/css'; tag.rel = 'stylesheet'; break; // Javascript library. case 'js': var injectScript = true; // Object detection try { injectScript = eval('window.' + asset.obj + ' === undefined'); } catch (e) {} if (injectScript) { tag = document.createElement('script'); tag.src = asset.url; // The crucial part: triggering document.GM_YUILOADER.countLoaded() // means keeping track whether all scripts are loaded yet. tag.setAttribute('onload', 'document.GM_YUILOADER_DOC.countLoaded();'); // How many JS libraries are we dealing with again? Let's keep // track. ud.GM_YUILOADER_DOC.numberTotal++; } break; } head.appendChild(tag); } // Did we actually include anything in the page? If so, trigger the // GM_YUILOADER.loaderCheck "watchdog". If not, just tell it to run the // main part of the script. if (ud.GM_YUILOADER_DOC.numberTotal > 0) { setTimeout(GM_YUILOADER.loaderCheck, GM_YUILOADER_CONFIG.interval); } else { ud.GM_YUILOADER_DOC.go = true; GM_YUILOADER.loaderCheck(); } } GM_YUILOADER.run = function() { // When we're here, we're good to go! eval(GM_YUILOADER_CONFIG.runFunction); } // The initial GM_YUILOADER trigger. setTimeout(GM_YUILOADER.loader, 500); // END LOADER CODE //////////////////////////////////////////////////////////// // START PAYLOAD SECTION ////////////////////////////////////////////////////// var SHOWXP = { }; // This function is triggered by the loader engine once the scripts are loaded SHOWXP.run = function() { var divElt = document.createElement('div'); divElt.setAttribute("id", "getxpath"); divElt.setAttribute("style", "background-color: black; font-weight: bold; font-size: 14px; top:0; left:0; position: absolute; border: 1px solid black;"); divElt.innerHTML = "Show XPaths"; document.body.appendChild(divElt); } // END PAYLOAD SECTION ////////////////////////////////////////////////////////
April 2, 2007
by Snippets Manager
· 3,144 Views
article thumbnail
Very Simple Php File Upload
I think this is the minimum necessary to upload a file in php. First, the form, index.php: Send this file: Next, the php to accept the file, upload.php "; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Upload failed"; } echo " "; echo ' '; echo 'Here is some more debugging info:'; print_r($_FILES); print " "; ?>
March 26, 2007
by Snippets Manager
· 42,507 Views · 2 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,125 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,457 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,590 Views
article thumbnail
Flattening Iterator
A trivial utility class for iterating through a collection of objects in a 'flat' manner, descending into any collections (in this case defined as iterators, iterables or arrays, rather than elements of the Collection interface ) it finds and iterating through their elements. This preserves order, so {a, b, {c, d, {e}} will be iterated through as a, b, c, d, e. It's not very complicated, but the implementation amused me so I thought I'd share it. package playground.library.functional.iterator; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack; /** * An iterator that 'flattens out' collections, iterators, arrays, etc. * * That is it will iterate out their contents in order, descending into any * iterators, iterables or arrays provided to it. * * An example (not valid Java for brevity - some type declarations are ommitted): * * new FlattingIterator({1, 2, 3}, {{1, 2}, {3}, new ArrayList({1, 2, 3})) * * Will iterate through the sequence 1, 2, 3, 1, 2, 3, 1, 2, 3. * * Note that this implements a non-generic version of the Iterator interface so * may be cast appropriately - it's very hard to give this class an appropriate * generic type. * * @author david */ public class FlatteningIterator implements Iterator { // Marker object. This is never exposed outside this class, so can be guaranteed // to be != anything else. We use it to indicate an absense of any other object. private final Object blank = new Object(); /* This stack stores all the iterators found so far. The head of the stack is * the iterator which we are currently progressing through */ private final Stack> iterators = new Stack>(); // Storage field for the next element to be returned. blank when the next element // is currently unknown. private Object next = blank; public FlatteningIterator(Object... objects){ this.iterators.push(Arrays.asList(objects).iterator());} public void remove(){ /* Not implemented */} private void moveToNext(){ if ((next == blank) && !this.iterators.empty() ) { if (!iterators.peek().hasNext()){ iterators.pop(); moveToNext();} else{ final Object next = iterators.peek().next(); if (next instanceof Iterator){ iterators.push((Iterator)next); moveToNext();} else if (next instanceof Iterable){ iterators.push(((Iterable)next).iterator()); moveToNext();} else if (next instanceof Array){ iterators.push(Arrays.asList((Array)next).iterator()); moveToNext();} else this.next = next;}} /** * Returns the next element in our iteration, throwing a NoSuchElementException * if none is found. */ public Object next() { moveToNext(); if (this.next == blank) throw new NoSuchElementException(); else{ Object next = this.next; this.next = blank; return next; } /** * Returns if there are any objects left to iterate over. This method * can change the internal state of the object when it is called, but repeated * calls to it will not have any additional side effects. */ public boolean hasNext(){ moveToNext(); return (this.next != blank);} }
February 14, 2007
by Snippets Manager
· 2,722 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,201 Views · 2 Likes
article thumbnail
Html Table To Wiki Converter
For more details on how to call this script from php if your server doesn't support python, click http://just-tech.blogspot.com/2007/01/python-html-tables-to-mediawiki.html import HTMLParser, re, sys class html2wiki(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.wiki = '' # The Wiki text self.wikirow = '' # The current Wiki row of table being constructed from HTML self.inTD = 0 # Used to track if we are inside or outside a ... tag. self.inTR = 0 # Used to track if we are inside or outside a ... tag. self.re_multiplespaces = re.compile('\s+') # regular expression used to remove spaces in excess self.rowCount = 0 # output row counter. self.rowspan = '' self.colspan = '' self.linebreak = ' ' self.data = '' self.prop = '' def handle_starttag(self, tag, attrs): if tag == 'table': self.start_table() elif tag == 'tr': self.start_tr() elif tag == 'td': self.start_td(attrs) def handle_endtag(self, tag): if tag == 'table': self.end_table(); elif tag == 'tr': self.end_tr() elif tag == 'td': self.end_td() def start_table(self): self.wiki += '{| border=1' + self.linebreak self.wiki += '|-' + self.linebreak def end_table(self): self.wiki += '|}' + self.linebreak def start_tr(self): if self.inTR: self.end_tr() # implies self.inTR = 1 def end_tr(self): if self.inTD: self.end_td() # implies self.inTR = 0 if len(self.wikirow) > 0: self.wiki += self.wikirow self.wiki += '|-' + self.linebreak self.wikirow = '' self.rowCount += 1 def start_td(self, attrs): if not self.inTR: self.start_tr() # implies self.data = '' self.prop = '' self.rowspan = '' self.colspan = '' for key, value in attrs: if key == 'rowspan': self.rowspan = value elif key == 'colspan': self.colspan = value self.inTD = 1 def end_td(self): if self.inTD: self.wikirow += '| ' + self.prop + self.re_multiplespaces.sub(' ',self.data.replace('\t',' ').replace(self.linebreak,'').replace('\r','').replace('"','""'))+ self.linebreak; self.data = '' self.inTD = 0 def handle_data(self, data): if self.inTD: if data.strip() != '': self.prop = '' if self.rowspan != '': self.prop = ' rowspan = '+self.rowspan if self.colspan != '': self.prop += ' colspan = '+self.colspan if self.prop: self.prop += ' | ' self.data += data if __name__ == '__main__': parser = html2wiki() if len(sys.argv) == 2: in_file = open(sys.argv[1],"r") text = in_file.read() parser.feed(text) in_file.close() print parser.wiki else: print 'Argument - filename required'
January 26, 2007
by Snippets Manager
· 2,657 Views
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,148 Views
article thumbnail
Sound Over IP With Jmf RTP
This code will allow you to send and recive sound over IP network using RTP protocol. It's just changed classes that I found on java.sun.com page. // this class send sound import java.io.IOException; import java.util.Vector; import javax.media.CaptureDeviceInfo; import javax.media.CaptureDeviceManager; import javax.media.DataSink; import javax.media.Manager; import javax.media.MediaLocator; import javax.media.NoPlayerException; import javax.media.NoProcessorException; import javax.media.NotRealizedError; import javax.media.Player; import javax.media.Processor; import javax.media.control.FormatControl; import javax.media.control.TrackControl; import javax.media.format.AudioFormat; import javax.media.protocol.ContentDescriptor; import javax.media.protocol.DataSource; public class SimpleVoiceTransmiter { /** * @param args */ public static void main(String[] args) { // First find a capture device that will capture linear audio // data at 8bit 8Khz AudioFormat format= new AudioFormat(AudioFormat.LINEAR, 8000, 8, 1); Vector devices= CaptureDeviceManager.getDeviceList( format); CaptureDeviceInfo di= null; if (devices.size() > 0) { di = (CaptureDeviceInfo) devices.elementAt( 0); } else { // exit if we could not find the relevant capturedevice. System.exit(-1); } // Create a processor for this capturedevice & exit if we // cannot create it Processor processor = null; try { processor = Manager.createProcessor(di.getLocator()); } catch (IOException e) { System.exit(-1); } catch (NoProcessorException e) { System.exit(-1); } // configure the processor processor.configure(); while (processor.getState() != Processor.Configured){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } processor.setContentDescriptor( new ContentDescriptor( ContentDescriptor.RAW)); TrackControl track[] = processor.getTrackControls(); boolean encodingOk = false; // Go through the tracks and try to program one of them to // output gsm data. for (int i = 0; i < track.length; i++) { if (!encodingOk && track[i] instanceof FormatControl) { if (((FormatControl)track[i]). setFormat( new AudioFormat(AudioFormat.GSM_RTP, 8000, 8, 1)) == null) { track[i].setEnabled(false); } else { encodingOk = true; } } else { // we could not set this track to gsm, so disable it track[i].setEnabled(false); } } // At this point, we have determined where we can send out // gsm data or not. // realize the processor if (encodingOk) { processor.realize(); while (processor.getState() != Processor.Realized){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // get the output datasource of the processor and exit // if we fail DataSource ds = null; try { ds = processor.getDataOutput(); } catch (NotRealizedError e) { System.exit(-1); } // hand this datasource to manager for creating an RTP // datasink our RTP datasink will multicast the audio try { String url= "rtp://224.0.0.1:22224/audio/16"; MediaLocator m = new MediaLocator(url); DataSink d = Manager.createDataSink(ds, m); d.open(); d.start(); processor.start(); } catch (Exception e) { System.exit(-1); } } } } // second class here // this class recieve sound import java.io.IOException; import java.net.MalformedURLException; import javax.media.Manager; import javax.media.MediaLocator; import javax.media.NoPlayerException; import javax.media.Player; public class SimpleVoiceReciver{ /** * @param args */ public static void main(String[] args) { String url= "rtp://224.0.0.1:22224/audio/16"; MediaLocator mrl= new MediaLocator(url); if (mrl == null) { System.err.println("Can't build MRL for RTP"); System.exit(-1); } // Create a player for this rtp session Player player = null; try { player = Manager.createPlayer(mrl); } catch (NoPlayerException e) { System.err.println("Error:" + e); System.exit(-1); } catch (MalformedURLException e) { System.err.println("Error:" + e); System.exit(-1); } catch (IOException e) { System.err.println("Error:" + e); System.exit(-1); } if (player != null) { System.out.println("Player created."); player.realize(); // wait for realizing while (player.getState() != Player.Realized){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } player.start(); } else { System.err.println("Player doesn't created."); System.exit(-1); } } }
December 8, 2006
by Snippets Manager
· 3,186 Views
article thumbnail
Convert Single Object To List
List list = java.util.Arrays.asList("foo");
October 12, 2006
by Snippets Manager
· 80,822 Views · 3 Likes
article thumbnail
Camino Mas Corto
Ejemplo en java del algoritmo para hallar el camino mas corto de un grafo. se implementa el algoritmo de floyd import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public final class Grafo { private int nnodos; private int nodos[][][]; private char nombres[]; Grafo(int n) { this.nnodos = n; this.nodos = new int[nnodos][nnodos][2]; this.nombres = new char[nnodos]; } public void ingresarArco(int n1, int n2, int peso) { this.nodos[n1][n2][0] = peso; this.nodos[n2][n1][0] = peso; this.nodos[n1][n2][1] = n1; this.nodos[n2][n1][1] = n2; } public void ingresarNombre(int nodo, char letra) { this.nombres[nodo] = letra; } public void calcular() { int i, j, k; for (i = 0; i < this.nnodos; i++) { for (j = 0; j < this.nnodos; j++) { for (k = 0; k < this.nnodos; k++) { if (this.nodos[i][k][0] + this.nodos[k][j][0] < this.nodos[i][j][0]) { this.nodos[i][j][0] = this.nodos[i][k][0] + this.nodos[k][j][0]; this.nodos[i][j][1] = k; } } } } } public int pesominimo(int org, int des) { return this.nodos[org][des][0]; } public String caminocorto(int org, int des) { String cam; if (org == des) { cam = "->" + nombres[org]; } else { cam = caminocorto(org, this.nodos[org][des][1]) + "->" + nombres[des]; } return cam; } public char getNombre(int nodo) { return this.nombres[nodo]; } public static void main(String args[]) throws IOException { Grafo g; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String temp; int res; System.out.println("Entre el numero de nodos del grafo:\n"); temp = br.readLine(); res = Integer.parseInt(temp); g = new Grafo(res); for (int i = 0; i < res; i++) { System.out.println("Cual es el nombre del nodo [" + (i + 1) + "]:\n"); temp = br.readLine(); g.ingresarNombre(i, temp.charAt(0)); } for (int i = 0; i < res; i++) { for (int j = 0; j < res; j++) { if (i < j) { System.out.println("El nodo " + g.getNombre(i) + " esta conectado con el nodo " + g.getNombre(j) + " (s/n)\n"); temp = br.readLine(); if (temp.charAt(0) == 's') { int peso; System.out.println("Cual es el peso del arco:\n"); temp = br.readLine(); peso = Integer.parseInt(temp); g.ingresarArco(i, j, peso); } else { g.ingresarArco(i, j, 10000); } } } } g.calcular(); for (int i = 0; i < res; i++) { for (int j = 0; j < res; j++) { if (i > j) { System.out.println("El camino mas corto entre los nodos:" + g.getNombre(i) + "-" + g.getNombre(j) + " es: \n" + g.caminocorto(i, j) + " y su peso es: " + g.pesominimo(i, j)); } } } } }
September 22, 2006
by Snippets Manager
· 8,777 Views
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,077 Views
article thumbnail
Odd Numbers Up To 1..100 In Ruby
// 10 different ways to display odd numbers 1 through 100 in Ruby 100.times do |i| next if i % 2 == 0 puts i end 50.times { |i| p i*2+1 } (1..100).step(2) { |i| puts i} 1.upto(100) { |i| puts i unless i[0].zero? } puts Array.new(50) { |i| i * 2 + 1 } # a self referential recursive lambda :-) lambda { me = lambda { |x| p x; me.call(x+2) if x < 99 } ; me.call(1) }.call # same thing, but passing the lambda around rec = lambda { |v,l| p v; l.call(v+2,l) if v < 99 } rec.call(-1,rec) # same recursive algorithm, but in method form def odds(x=1) p x odds(x+2) if x < 99 end odds class Integer def odd? self[0].nonzero? end end 100.times { |i| puts i if i.odd? } require 'delegate' class OddNum < DelegateClass(Fixnum) def initialize(value) value |= 1 # force it odd super(value) end def succ # note that the delegated succ gets called when we call super # and the constructor forces it (up) to the next odd number OddNum.new(super) # or # OddNum.new(self + 1) # still using the constructor's force to odd # or # OddNum.new(self + 2) # being odd all on our own end end (OddNum.new(1)..100).each { |i| puts i }
September 8, 2006
by Snippets Manager
· 5,417 Views
article thumbnail
Design Patterns - Command
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; namespace CommandPattern { public interface Command { string Execute(); } public class GarageDoor { public void Up() { Console.WriteLine("Garage Door is Open"); } public void Down() { } public void Stop() { } public void LightOn() { } public void LightOff() { } } public class GarageDoorOpenCommand : Command { public GarageDoor _garageDoor; public GarageDoorOpenCommand(GarageDoor garageDoor) { _garageDoor = garageDoor; } public string Execute() { _garageDoor.Up(); return "Opening Garage Door"; } } public class LightOnCommand: Command { Light _light; public LightOnCommand(Light light) { _light = light; } public string Execute() { _light.On(); return "Turning light on"; } } public class Light { public void On() { Console.WriteLine("This light has been turned on"); } } // The _invoker_. public class RemoteControl { Command _command; public void SetCommand(Command command) { _command = command; } public string PressButton() { return _command.Execute(); } } [TestFixture] public class TestCommandClass { [Test] public void TestCommand() { RemoteControl remoteControl = new RemoteControl(); remoteControl.SetCommand(new LightOnCommand(new Light())); Assert.IsTrue(remoteControl.PressButton() == "Turning light on"); remoteControl.SetCommand(new GarageDoorOpenCommand(new GarageDoor())); Assert.IsTrue(remoteControl.PressButton() == "Opening Garage Door"); } } }
September 5, 2006
by Snippets Manager
· 14 Views
article thumbnail
Time Based Cache
A simple time based cache build around a map store. import java.util.Map; import java.util.WeakHashMap; /** * Simple time-based cache. */ public class SimpleCache { private long maxAge; private Map store; /** * Instanciate a cache with max age of 1 hour and a WeakHashMap as store. * @see java.util.WeakHashMap */ public SimpleCache() { this.maxAge = 1000 * 60 * 60; this.store = new WeakHashMap(); } /** * @param maxAge maximum age of an entry in milliseconds * @param store map to hold entries */ public SimpleCache(long maxAge, Map store) { this.maxAge = maxAge; this.store = store; } /** * Cache an object. * @param key unique identifier to retrieve object * @param value object to cache */ public void put(Object key, Object value) { store.put(key, new Item(value)); } /** * Fetch an object. * @param key unique identifier to retrieve object * @return an object or null in case it isn't stored or it expired */ public Object get(Object key) { Item item = getItem(key); return item == null ? null : item.payload; } /** * Fetch an object or store and return output of callback. * @param key unique identifier to retrieve object * @param block code executed when object not in cache * @return an object */ public synchronized Object get(Object key, Callback block) { Item item = getItem(key); if (item == null) { Object value = block.execute(); item = new Item(value); store.put(key, item); } return item.payload; } /** * Remove an object from cache. * @param key unique identifier to retrieve object */ public void remove(Object key) { store.remove(key); } /** * Get an item, if it expired remove it from cache and return null. * @param key unique identifier to retrieve object * @return an item or null */ private Item getItem(Object key) { Item item = (Item) store.get(key); if (item == null) { return null; } if (System.currentTimeMillis() - item.birth > maxAge) { store.remove(key); return null; } return item; } /** * Value container. */ private static class Item { long birth; Object payload; Item(Object payload) { this.birth = System.currentTimeMillis(); this.payload = payload; } } /** * A visitor interface. */ public static interface Callback { Object execute(); } } And a couple of junit tests: import java.util.HashMap; import junit.framework.TestCase; public class SimpleCacheTest extends TestCase { public void testPutGet () { SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap()); c.put("key1", "value1"); assertEquals("value1", c.get("key1")); c.put("key1", "value1.0"); assertEquals("value1.0", c.get("key1")); c.put("key2", "value2"); assertEquals("value2", c.get("key2")); assertEquals("value1.0", c.get("key1")); } public void testMaxAge () throws InterruptedException { SimpleCache c = new SimpleCache(1000, new HashMap()); c.put("key1", "value1"); assertEquals("value1", c.get("key1")); Thread.sleep(1500); assertNull(c.get("key1")); c.put("key2", "value2"); Thread.sleep(750); c.put("key3", "value3"); Thread.sleep(750); assertNull(c.get("key2")); assertNotNull(c.get("key3")); Thread.sleep(750); assertNull(c.get("key3")); } public void testRemove () { SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap()); c.remove("key"); assertNull(c.get("key")); c.put("key", "value"); assertNotNull(c.get("key")); c.remove("key"); assertNull(c.get("key")); } public void testCallBack () { SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap()); assertEquals("value1", c.get("key1", new SimpleCache.Callback() { public Object execute() { return "value1"; } })); assertEquals("value1", c.get("key1")); // again with a new callback (value) c.get("key1", new SimpleCache.Callback() { public Object execute() { return "value2"; } }); assertEquals("value1", c.get("key1")); } }
August 3, 2006
by Snippets Manager
· 7,220 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,186 Views
  • Previous
  • ...
  • 1623
  • 1624
  • 1625
  • 1626
  • 1627
  • 1628
  • 1629
  • 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
×