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 18 total  RSS 

Drawing with the Web Canvas on the N800

This web page renders a Canvas suitable for doodling sketches on the N800. The additional code can be found from Mathieu Blondel » Blog Archive » Web Canvas [mblondel.org] which also includes the demo [mblondel.org]

   1  
   2  <html>
   3      <head>
   4          <title>Webcanvas test</title>
   5          <style type="text/css">
   6              canvas { border: 1px solid black; }
   7          </style>
   8          <script type="text/javascript"
   9                  src="webcanvas/excanvas.js"></script>
  10          <script type="text/javascript"
  11                  src="webcanvas/json2.js"></script>
  12          <script type="text/javascript"
  13                  src="webcanvas/character.js"></script>    
  14          <script type="text/javascript"
  15                  src="webcanvas/webcanvas.js"></script>
  16  
  17      
  18          <script type="text/javascript">
  19              var webcanvas = null;
  20      
  21              function canvasLoad() {
  22                  var canvas = document.getElementById("webcanvas");
  23      
  24                  if (canvas.getContext) {
  25                      webcanvas = new WebCanvas(canvas);
  26                      webcanvas.draw();
  27                  }
  28              }
  29  
  30              function writingToXML(writing) {
  31                  var char = new Character();
  32                  char.setUTF8("?");
  33                  char.setWriting(writing);
  34                  return char.toXML();
  35              }
  36      
  37              function canvasToXML() {
  38                  if (webcanvas) {
  39                      var writing = webcanvas.getWriting();
  40      
  41                      var output_textarea = document.
  42                                            getElementById("output_textarea");
  43      
  44                      output_textarea.value = writingToXML(writing);
  45                  }
  46              }
  47              
  48              function canvasToPNG() {
  49                  if (webcanvas) {
  50                      var dataURL = webcanvas.toPNG();
  51                      
  52                      if (dataURL) {
  53                          var preview = document.getElementById("preview");
  54                          if(preview.childNodes.length == 2) {
  55                              var image = preview.childNodes[1];
  56                          }
  57                          else {
  58                              var image = document.createElement("img");
  59                              preview.appendChild(image);
  60                          }
  61                          
  62                          image.src = dataURL;
  63                      }
  64                  }
  65              }        
  66  
  67              function canvasToPNGURL() {
  68                  if (webcanvas) {
  69                      
  70                      var dataURL = webcanvas.toPNG();
  71                      
  72                      if (dataURL) {
  73                          window.open(dataURL, "_blank");
  74                      }
  75                  }
  76              }                
  77  
  78              function canvasLoadJSON() {
  79                  if (webcanvas) {
  80                      var input_textarea = document.
  81                                           getElementById("input_textarea");
  82  
  83                      var json = JSON.parse(input_textarea.value);
  84  
  85                      var char = new Character();
  86                      char.copy(json);
  87  
  88                      webcanvas.setWriting(char.getWriting());
  89                  }   
  90             
  91              }
  92      
  93              function canvasClear() {
  94                  if (webcanvas) {
  95                      webcanvas.clear();
  96                      document.getElementById("output_textarea").value = "";
  97                  }
  98              }
  99              
 100              function canvasRevertStroke() {
 101                  if (webcanvas) {
 102                      webcanvas.revertStroke();
 103                  }
 104              }            
 105              
 106              function canvasReplay() {
 107                  if (webcanvas) {
 108                      webcanvas.replay();
 109                  }
 110              }               
 111          </script>
 112      </head>
 113  
 114      <body onload="canvasLoad();">
 115  
 116                      <canvas id="webcanvas" width="780" height="400">
 117                      Fallback content (can be an img tag)
 118                      </canvas>
 119  
 120      </body>
 121  </html>
 122  


Here is a quick sketch drawn with the webcanvas. [twitxr.com]

Create JSON data from a Hash using Ruby

   1  
   2  require 'json'
   3  
   4  # create a simple Hash
   5  fruit_and_veg = {"banana" => 1.40, "grapes" => 0.89, "pears" => 0.60, "Rhubarb" => 1.30}
   6  
   7  # now let's create the JSON data structure
   8  list = []
   9  list << fruit_and_veg
  10  
  11  fav = {}
  12  fav["fruit_and_veg"] = list
  13  fav["as_of"] = Time.now.strftime("%Y-%m-%d %H:%M:%S")
  14  food = fav.to_json
  15  
  16  puts food

=> {"as_of": "2008-09-24 00:17:42", "fruit_and_veg": [{"pears": 0.6, "banana": 1.4, "Rhubarb": 1.3, "grapes": 0.89}]}

Read JSON data using Ruby

   1  
   2  require 'open-uri'
   3  require 'json'
   4  
   5  url = 'http://search.twitter.com/trends.json'
   6  
   7  buffer = open(url, "UserAgent" => "Ruby-Wget").read
   8  
   9  # convert JSON data into a hash
  10  result = JSON.parse(buffer)
  11  
  12  trends = result['trends']
  13  trends.each do |subject|
  14    puts subject['name'] + ' ' + subject['url']
  15  end

output:
Clay Aiken http://search.twitter.com/search?q=Clay+Aiken
Sarah Palin http://search.twitter.com/search?q=Sarah+Palin
Heroes http://search.twitter.com/search?q=Heroes
McCain http://search.twitter.com/search?q=McCain
iPhone http://search.twitter.com/search?q=iPhone
Obama http://search.twitter.com/search?q=Obama
Apple http://search.twitter.com/search?q=Apple
T-Mobile G1 http://search.twitter.com/search?q=T-Mobile+G1
AT&T http://search.twitter.com/search?q=AT%26T
CS4 http://search.twitter.com/search?q=CS4


References:
- Yahoo Developer Network - Yahoo! Developer Network [yahoo.com]
- Find out the latest trends on Twitter [dzone.com]

Find out the latest trends on Twitter

   1  require 'httparty'
   2  
   3  class Twitter
   4    include HTTParty
   5  end
   6  
   7  trends = Twitter.get('http://search.twitter.com/trends.json')['trends']
   8  trends.each do |subject|
   9    puts subject['name'] + ' ' + subject['url']
  10  end


output:
Android http://search.twitter.com/search?q=Android
T-Mobile G1 http://search.twitter.com/search?q=T-Mobile+G1
Sarah Palin http://search.twitter.com/search?q=Sarah+Palin
McCain http://search.twitter.com/search?q=McCain
Heroes http://search.twitter.com/search?q=Heroes
Obama http://search.twitter.com/search?q=Obama
iPhone http://search.twitter.com/search?q=iPhone
Apple http://search.twitter.com/search?q=Apple
AT&T http://search.twitter.com/search?q=AT%26T
Clay Aiken http://search.twitter.com/search?q=Clay+Aiken

References:

- Twitter API Wiki / Search API Documentation [twitter.com]
- Make HTTP fun with HTTParty [dzone.com]

Make HTTP fun with HTTParty

HTTPParty is a gem which makes it easier to send and retrieve data through HTTP.

   1  require 'rubygems'
   2  require 'httparty'
   3  
   4  class Ebay
   5    include HTTParty
   6  end
   7  
   8  begin
   9    item = Ebay.get('http://rorbuilder.info/cgi-bin/ebay.cgi?q=260288310590')['ebay']
  10    item.each do |key, value|
  11      puts key + ': ' + value
  12    end
  13  rescue
  14    p 'oops that product doesn\'t exist'
  15  end
  16  

output:
end_date: Tue Sep 23 20:35:37 +0100 2008
price: 102.00
title: Nokia N800+2GB+8GB+Leather Case+Keyboard SU8W on eBay, also, PDAs, Computing (end time 23
-Sep-08 20:35:37 BST)
product_id: 260288310590
description: ...


Here is the same example but with more clarity:
   1  class Ebay
   2    include HTTParty
   3    format: xml
   4  
   5    base_uri 'http://rorbuilder.info'
   6  
   7    def self.find_by_product_id(q)
   8        return get('/cgi-bin/ebay.cgi?', :query => {:q => q})['ebay']
   9    end
  10  end
  11  
  12  begin
  13    item = Ebay.find_by_product_id('260288310590')
  14    item.each do |key, value|
  15      puts key + ': ' + value
  16    end
  17  rescue
  18    p 'oops that product doesn\'t exist'
  19  end

Reference: It's an HTTParty and Everyone Is Invited! // RailsTips.org by John Nunemaker [railstips.org]

YUI: parse json data from a async request

   1  
   2  var initializeHistoryLog = function(){
   3  	var historyLog = YAHOO.util.Dom.get('historyLog');
   4  
   5  	// Define the callbacks for the asyncRequest
   6  	var callbacks = {
   7  		success : function (o) {
   8  			// Process the JSON data returned from the server
   9  			var values = [];
  10  			try {
  11  				values = YAHOO.lang.JSON.parse(o.responseText).ResultSet.Result;
  12  			}
  13  			catch (e) {
  14  				return;
  15  			}
  16  
  17  			var el = document.createElement("temp");
  18  			for (var i = 0, len = values.length; i < len; ++i) {
  19  				var v = values[i];
  20  				YAHOO.widget.DataTable.formatDate(el, null, null, YAHOO.util.DataSource.parseDate(v.Date))
  21  				historyLog.innerHTML += '<div class="entry"><div class="date">' + el.innerHTML + ' ' + v.Time + '</div><div class="text"><div class="action">' + v.Action + '</div><div class="changes">' + v.Changes.join('<br>') + '</div></div></div><hr>';
  22  			}
  23  		},
  24  
  25  		failure : function (o) {
  26  			if (!YAHOO.util.Connect.isCallInProgress(o)) {
  27  			}
  28  		},
  29  
  30  		timeout : 3000
  31  	}
  32  
  33  	// Make the call to the server for JSON data
  34  	YAHOO.util.Connect.asyncRequest('GET',"json_GetHistoryLog?openagent&unid=" + unid, callbacks);
  35  }

PHP headers to serve JSON

The first two headers prevent the browser from caching the response (a problem with IE and GET requests) and the third sets the correct MIME type for JSON.

   1  
   2  header('Cache-Control: no-cache, must-revalidate');
   3  header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
   4  header('Content-type: application/json');

Output JavaScript variables from PHP

Class with useful static methods for outputting PHP values into JavaScript format.

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  
   5  class JS{
   6  	//generic and maybe not the desired results xD
   7  	function value($o){
   8  		if($o === null)
   9  			return 'null';
  10  		$t = strtolower(gettype($o));
  11  		if($t == 'string' && is_numeric($o) && ($o[0] || strlen($o) == 1) || in_array($t, array('double', 'integer')))
  12  			$t = 'number';
  13  		elseif($t == 'string' && preg_match('@^\d{4}(?:-\d{1,2}){1,2}(?: (?:\d{1,2}:){2}\d{1,2})?$@', $o)) //strtotime works also with "strange" values strtotime('x')
  14  			$t = 'date';
  15  		elseif($t == 'array' && ($c = count($k = array_keys($o))) && $k !== range(0, $c - 1))
  16  			$t = 'object';
  17  		elseif(!in_array($t, array('boolean', 'string', 'array', 'object')))
  18  			$t = 'string';
  19  		$t = 'from' . $t;
  20  		return self::$t($o);
  21  	}
  22  	function fromNumber($o){
  23  		return +$o . '';
  24  	}
  25  	function fromObject($o){
  26  		$r = array();
  27  		foreach($o as $n => $v)
  28  			$r[] = self::fromString($n) . ':' . self::value($v);
  29  		return '{' . implode(',', $r) . '}';
  30  	}
  31  	function fromBoolean($o){
  32  		return $o ? 'true' : 'false';
  33  	}
  34  	//$q = should quote? 
  35  	//$c = char that will be used to quote
  36  	function fromString($o, $q = true, $c = '"'){
  37  		return ($p = $q ? $c : '') . preg_replace('/\r\n|\n\r|\r/', '\n', str_replace($c, '\\' . $c, str_replace('\\', '\\\\', $o))) . $p;
  38  	}
  39  	function fromArray($o){
  40  		$s = '';
  41  		foreach($o as $v)
  42  			$s .= ($s ? ',' : '') . self::value($v);
  43  		return '[' . $s . ']';
  44  	}
  45  	function fromDate($o){
  46  		(is_numeric($o) && $o = +$o) || ($o = strtotime($o)) > 0 || ($o = mktime());
  47  		$o = explode(',', date('Y,n,j,G,i,s', $o));
  48  		foreach($o as $i => $v)
  49  			$o[$i] = +$v;
  50  		return 'new Date(' . implode(',', $o)  . ')';
  51  	}
  52  }


Example

   1  
   2  $o = new stdClass;
   3  $o->abc = 123;
   4  echo implode("\n<br />", array(
   5  	JS::value('1984-07-22 11:30:12'),
   6  	JS::value('Test'),
   7  	JS::value(1234),
   8  	JS::value(true),
   9  	JS::value(array(1,2,3)),
  10  	JS::value(array('lala' => 'x')),
  11  	JS::value($o)
  12  ));

Simple JSON formatting example

// Simple JSON formatting example

   1  
   2  ({
   3  
   4  	'google' : {
   5  	
   6  		'action': 'http://www.google.com.au/search',
   7  		
   8  		'method': 'POST',		
   9  		
  10  		'input': [
  11  		
  12  			'<input type="hidden" value="en" name="hl"/>',
  13  			
  14  			'<input value="" title="Google Search" size="55" name="q" maxlength="2048"/>',
  15  			
  16  			'<input type="hidden" value="en" name="hl"/>'
  17  		
  18  		],
  19  		
  20  		'buttons': [
  21  		
  22  			'<input type="submit" value="Google Search" name="btnG"/>',
  23  			
  24  			'<input type="submit" value="I\'m Feeling Lucky" name="btnI"/>'
  25  		
  26  		],
  27  		
  28  		'image': 'http://www.google.com/intl/en_ALL/images/logo.gif'
  29  		
  30  	},
  31  	
  32  	'yahoo' : {
  33  	
  34  		'action': 'http://search.yahoo.com/search',
  35  		
  36  		'method': 'POST',		
  37  		
  38  		'input': [
  39  		
  40  			'<input value="" maxlength="255" name="q" id="search" type="text">'
  41  		
  42  		],
  43  		
  44  		'buttons': [
  45  		
  46  			'<input value="Search" type="submit">'
  47  		
  48  		],
  49  		
  50  		'image': 'http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif'		
  51  		
  52  	},	
  53  
  54  	'wikipedia' : {
  55  	
  56  		'action': 'http://en.wikipedia.org/wiki/Special:Search',
  57  		
  58  		'method': 'POST',
  59  		
  60  		'input': [
  61  		
  62  			'<input value="" name="search" type="text">'
  63  		
  64  		],
  65  		
  66  		'buttons': [
  67  		
  68  			'<input value="Search" name="go" type="submit">'
  69  		
  70  		],
  71  		
  72  		'image': 'http://en.wikipedia.org/images/wiki-en.png'		
  73  		
  74  	},	
  75  
  76  	'imdb' : {
  77  	
  78  		'action': 'http://imdb.com/find',
  79  		
  80  		'method': 'POST',
  81  		
  82  		'input': [
  83  		
  84  			'<input value="" name="q">'
  85  		
  86  		],
  87  		
  88  		'buttons': [
  89  		
  90  			'<input value="Search" type="submit">'
  91  		
  92  		],
  93  		
  94  		'image': 'http://i.media-imdb.com/images/nb15/logo2.gif'		
  95  		
  96  	},	
  97  
  98  	'ebay' : {
  99  	
 100  		'action': 'http://search.ebay.com.au/search/search.dll',
 101  		
 102  		'method': 'GET',
 103  		
 104  		'input': [
 105  		
 106  			'<input value="R40" name="from" type="hidden">',
 107  			
 108  			'<input name="satitle" maxlength="300" type="text">'
 109  		
 110  		],
 111  		
 112  		'buttons': [
 113  		
 114  			'<input value="Search" type="submit">'
 115  		
 116  		],
 117  		
 118  		'image': 'http://pics.ebaystatic.com/aw/pics/logos/logoEbay_x45.gif'		
 119  		
 120  	},		
 121  	
 122  	'dictionary' : {
 123  	
 124  		'action': 'http://dictionary.com/search',
 125  		
 126  		'method': 'GET',
 127  		
 128  		'input': [
 129  		
 130  			'<input maxlength="256" value="" name="q" type="text">'
 131  		
 132  		],
 133  		
 134  		'buttons': [
 135  		
 136  			'<input value="Search" type="submit">'
 137  		
 138  		],
 139  		
 140  		'image': 'http://cache.lexico.com/g/d/dictionary_logo.gif'		
 141  		
 142  	},	
 143  
 144  	'iboogie' : {
 145  	
 146  		'action': 'http://www.iboogie.com/searchtree.asp',
 147  		
 148  		'method': 'GET',
 149  		
 150  		'input': [
 151  		
 152  			'<input type="text" value="test" name="name_query" />'
 153  		
 154  		],
 155  		
 156  		'buttons': [
 157  		
 158  			'<input type="submit" value=" Search " class="button"/>'
 159  		
 160  		],
 161  		
 162  		'image': 'http://www.iboogie.com/images/iboogie_us.jpg'		
 163  		
 164  	},		
 165  	
 166  })
 167  
 168  

hCard to JSON bridge

// Requires http://pear.php.net/pepr/pepr-proposal-show.php?id=198 and http://allinthehead.com/hkit
// Many thanks to the authors of these libraries and to the microformats community.
// Demo: http://simplelogica.net/cajondesastre/hcard2json/index.php?url=http://11870.com/pro/19483
// Manuel González Noriega for Simplelógica. Hire us at http://simplelogica.net

   1  
   2  
   3      include('hkit.class.php');
   4      include('JSON.class.php');
   5  		
   6      $debug = true;
   7  		
   8      $status = '200';
   9      $ct = 'text/plain';
  10  		
  11      $hKit = new hKit;
  12      $json = new Services_JSON();
  13  
  14      if ($_GET['url']) {
  15        $result = $hKit->getByURL('hcard', $_GET['url']);
  16  	    
  17        if ($result) {
  18  	$o = ($json->encode($result));
  19  	$ct = ($debug) ? 'text/plain' : 'application/json';			
  20        }
  21        else {
  22  	$o = '404 Not Found';
  23  	$status = '404';
  24        }
  25      }
  26      else {
  27        $o = '400 Bad Request';
  28        $status = '400';
  29      }
  30  	
  31   
  32  
  33    header('Content-type: '.$ct);
  34    
  35    switch($status) {
  36      case '400':
  37        header("HTTP/1.0 400 Bad Request");
  38      break;
  39  	
  40      case '404':
  41        header("HTTP/1.0 404 Not Found");
  42      break;
  43  
  44      case '200':
  45      default:
  46        header("HTTP/1.0 200 OK");
  47      break;
  48  }
  49  
  50  print $o;
  51  
« Newer Snippets
Older Snippets »
Showing 1-10 of 18 total  RSS