From Kaizen
Javascript to make a GMap from xml file
<p>''Code to make a google map from an xml file'
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://maps.google.com/maps?file=api&v=1&key=ABQIAAAAZVts1pLVr1UZk4htR18MNBQ88dZPz3hODFC-BGfe6yjgdR-1sxSISHeiMdJijU29Vsh9Lwq5E2ulqw" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var gmarkers = [];
var gmarkersType = [];
var map;
function mapit() {
if (GBrowserIsCompatible()) {
// arrays to hold copies of the markers
var j = 0;
// create the map
map = new GMap(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.centerAndZoom(new GPoint(-94.75, 40.50), 13);
// create custom icons
var blueicon = new GIcon();
blueicon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
blueicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
blueicon.iconSize = new GSize(12, 20);
blueicon.shadowSize = new GSize(22, 20);
blueicon.iconAnchor = new GPoint(6, 20);
blueicon.infoWindowAnchor = new GPoint(5, 1);
var redicon = new GIcon();
redicon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
redicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
redicon.iconSize = new GSize(12, 20);
redicon.shadowSize = new GSize(22, 20);
redicon.iconAnchor = new GPoint(6, 20);
redicon.infoWindowAnchor = new GPoint(5, 1);
var greenicon = new GIcon();
greenicon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
greenicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
greenicon.iconSize = new GSize(12, 20);
greenicon.shadowSize = new GSize(22, 20);
greenicon.iconAnchor = new GPoint(6, 20);
greenicon.infoWindowAnchor = new GPoint(5, 1);
var purpleicon = new GIcon();
purpleicon.image = "http://labs.google.com/ridefinder/images/mm_20_purple.png";
purpleicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
purpleicon.iconSize = new GSize(12, 20);
purpleicon.shadowSize = new GSize(22, 20);
purpleicon.iconAnchor = new GPoint(6, 20);
purpleicon.infoWindowAnchor = new GPoint(5, 1);
var whiteicon = new GIcon();
whiteicon.image = "http://labs.google.com/ridefinder/images/mm_20_white.png";
whiteicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
whiteicon.iconSize = new GSize(12, 20);
whiteicon.shadowSize = new GSize(22, 20);
whiteicon.iconAnchor = new GPoint(6, 20);
whiteicon.infoWindowAnchor = new GPoint(5, 1);
var blueicon = new GIcon();
blueicon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
blueicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
blueicon.iconSize = new GSize(12, 20);
blueicon.shadowSize = new GSize(22, 20);
blueicon.iconAnchor = new GPoint(6, 20);
blueicon.infoWindowAnchor = new GPoint(5, 1);
// A function to create the marker and set up the event window
function createMarker(point, numpubs, zip, journal) {
if (journal == "Nature") {
var marker = new GMarker(point, redicon);
} else if (journal == "Science") {
var marker = new GMarker(point, greenicon);
} else if (journal == "JPedSurgery") {
var marker = new GMarker(point, blueicon);
} else if (journal == "jurol") {
var marker = new GMarker(point, purpleicon);
} else if (journal == "other") {
var marker = new GMarker(point, whiteicon);
} else {
var marker = new GMarker(point, blueicon);
}
var thisHTMLText = zip + numpubs;
GEvent.addListener(marker, "click", function() {
//marker.openInfoWindowHtml(thisHTMLText);
marker.openInfoWindowHtml('<div style="white-space:nowrap;"><b>'+ zip + '<\/b><br>Total Publications: ' + numpubs+'</div>')
});
// save the info we need to use later
gmarkers[j] = marker;
gmarkersType[j] = journal;
j++;
return marker;
}
// This function picks up the click and opens the corresponding info window. Not used right now
function myclick(i) {
gmarkers[i].openInfoWindowHtml(htmls[i]);
}
// Read the data from example.xml
var request = GXmlHttp.create();
request.open("GET", "journal.xml", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = request.responseXML;
// obtain the array of markers and loop through it
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GPoint(lng,lat);
var numpubs = markers[i].getAttribute("numpubs");
var zip = markers[i].getAttribute("zip");
var journal = markers[i].getAttribute("journal");
if (journal == "") {
journal = "none";
}
// create the marker
var marker = createMarker(point, numpubs, zip, journal);
map.addOverlay(marker);
document.getElementById("message").innerHTML += journal + ' ' + ' ' + numpubs + ' ' + ' ' + zip + '<br>';
}
}
}
request.send(null);
} else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
}
function selectChange(dropdown) {
var filterCommand = dropdown.options[dropdown.selectedIndex].value;
if (filterCommand != "") {
for (var i = 0; i < gmarkersType.length; i++) {
map.removeOverlay(gmarkers[i]);
if (gmarkersType[i] == filterCommand) {
map.addOverlay(gmarkers[i]);
}
}
} else {
for (var i = 0; i < gmarkersType.length; i++) {
map.removeOverlay(gmarkers[i]);
map.addOverlay(gmarkers[i]);
}
}
}
//]]>
</script>
</p>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" content="-1" />
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="robots" content="all" />
<meta name="author" content="Charles L. Snyder: Maps" />
<!-- UPDATE [program title] -->
<title>Charles L. Snyder: Data Maps</title>
<!-- UPDATE [program description text] -->
<meta name="description" content="These are data maps generated by Javascript and the proprietary Google Maps API" />
<!-- UPDATE [program keywords] -->
<meta name="keywords" content="Google, Maps, Science, Nature, Journal of Pediatric Surgery, publications" />
<!-- UPDATE directory path if not using default location -->
<link rel="stylesheet" type="text/css" href="Level3_3.css" />
<!-- BEGIN required program stylesheet | do not delete | add all other stylesheets above -->
<link rel="stylesheet" type="text/css" href="/standard/css/apm001/www.css" />
<!-- END required program stylesheet -->
<!-- BEGIN required APM stylesheet | do not delete | add all other stylesheets above -->
<link rel="stylesheet" type="text/css" href="/cobrand/standard/css/apm001/apm.css" />
<p>
<!-- END required APM stylesheet -->
<!-- UPDATE [location of program RSS feed] | add more <link /> tags for each RSS feed associated with your program -->
<!-- delete <link /> tag if no RSS feeds are associated with your program -->
</head>
<body class="programBody" onload="mapit();">
<div id="first_column">
<table cellspacing="0" cellpadding="1" border="3" width="781" bordercolorlight="#AEC4A6" class="TopLeftBox">
<tr>
<td class="All_Box_Text">
<h2>
Charles L. Snyder: Data Maps
</h2>
<br />
<form id="web_map_filters" method="get" action="#">
<br />
<strong>Sort by Journal:</strong>
<select onchange="selectChange(this); return false;" name="journaltypefilter">
<option label="Journal type" value="" selected="selected">Name of Journal</option>
<option label="Science" value="Science">Science</option>
<option label="Nature" value="Nature">Nature</option>
<option label="J Ped Surg" value="JPedSurgery">JPS</option>
<option label="Urology" value="JUrology">Urology</option>
<option label="Show all" value="">Show all</option>
</select>
<br />
<br />
</td>
</tr>
</table>
</div>
<div id="second_column">
<table cellspacing="0" cellpadding="1" width="775" border="3" bordercolorlight="#AEC4A6">
<tr>
<td width="100%" class="All_Box_Text" bordercolorlight="#AEC4A6">
<div id="map" style="width: 770px; height: 500px;">
</div>
</td>
</tr>
</table>
</div>
<div id="message">
List of Sites<br>
</div>
<!-- END program page area -->
</p>
</body>
</html>
Ruby: Solve Word Scrambles
def main
input_token = ARGV[0] || (print "Enter a scrambled word: " ; gets.chomp)
puts permutations(input_token).select{|w| is_word?(w)}
end
def permutations(word)
len = word.length
if len > 1
result = []
len.times do |idx|
result +=
permutations(word[0..idx] + word[idx+1..-1]).map {|w| word[idx,1] + w}
end
result.uniq
else
[word]
end
end
def is_word?(s)
`echo #{s} | ispell -l`.chop.empty?
end
main
Actionscript: Make an xml - based quiz
var displayTotal; // textfield for displaying user's final score
var totalCorrect = 0; // number of questions user answered correctly
var userAnswers = new Array(); // array containing the user's guesses
var mediaArray = new Array(); // array containing the associated media
var currentQuestion = 0; // number of the question we're on
var questionsArray = new Array(); // array of question objects, built from xml doc
_global.styles.TextArea.setStyle("backgroundColor", 0xCBCFB8);
var quizDoc = new XML();
quizDoc.load("PSRP.xml");
quizDoc.onLoad = buildQuestionsArray;
function buildQuestionsArray () {
stripWhitespaceDoublePass(quizDoc);
var quizNode = quizDoc.firstChild;
var catnum = quizDoc.firstChild.childNodes.length //how many categories are there?
for(m=0; m<catnum;m++){
if (quizDoc.firstChild.childNodes[m].nodeName == _global.yourChoice) {//is this node the category you picked?
_global.sectionqtotal = quizDoc.firstChild.childNodes[m].childNodes.length;//how many ? in it
for(var i = 0; i quizDoc.firstChild.childNodes[m].childNodes.length; i++) {
var thisQuestion = quizDoc.firstChild.childNodes[m].childNodes[i];
var choicesArray = new Array();
for (var j = 0; j thisQuestion.childNodes.length; j++) {
var thisChoice = thisQuestion.childNodes[j];
choicesArray[j] = thisChoice.firstChild.nodeValue;
}
// construct a question object for each QUESTION node, and store it in questionsArray
questionsArray[i] = new Question (parseInt(thisQuestion.attributes.answer),
thisQuestion.attributes.text,
thisQuestion.attributes.explain,
thisQuestion.attributes.media_ques,
thisQuestion.attributes.media_ans,
choicesArray);
}
}
}
makeQuestion(currentQuestion);//call the function to make a ? with the current stuff
}
return_btn.onRelease = function() {//code for a button to go back to the intro frame
questionClip.removeMovieClip();
answerClip.removeMovieClip();
_root.explain_box.text = "";
_root.explain_box.visible = false;
gotoAndPlay("menuFrame");
}
function Question (correctAnswer, questionText, questionExplain, media_ques, media_ans, answers) {
this.correctAnswer = correctAnswer;
this.questionText = questionText;
this.answers = answers;
this.questionExplain = questionExplain;
this.media_ques = media_ques;
this.media_ans = media_ans;
}
function makeQuestion (currentQuestion) {
media_btn._visible = false;
questionClip.removeMovieClip();
_root.attachMovie("questionTemplate", "questionClip", 0);
questionClip._x = 277;
questionClip._y = 205;
questionClip.qNum = "Question\n" + (currentQuestion + 1) + " of " + _global.sectionqtotal;
_global.quest = questionClip.qText = questionsArray[currentQuestion].questionText;
_root.qexplain = questionsArray[currentQuestion].questionExplain;
_root.explain_box.text = "" ;
_root.explain_box.visible = false;
if (questionsArray[currentQuestion].media_ques != "NONE"){//does the ? have media
trace(yourChoice + questionsArray[currentQuestion].media_ques + (CurrentQuestion + 1));
media_btn._visible = true;
}
if (questionsArray[currentQuestion].media_ans == "A"){//does the answer have media?
trace(yourChoice + questionsArray[currentQuestion].media_ans + (CurrentQuestion + 1));
}
for(var i = 0; i < questionsArray[currentQuestion].answers.length; i++) {//make answer clp
questionClip.attachMovie("answerTemplate","answer" + i, i);
questionClip["answer" + i]._y += 70 + (i * 40);
questionClip["answer" + i]._x -= 100;
questionClip["answer" + i].answerText = questionsArray[currentQuestion].answers[i];
}
}
function answer (choice) {
userAnswers.push(choice);
if (currentQuestion + 1 == questionsArray.length) {
questionClip.removeMovieClip();
gotoAndStop ("quizEnd");
} else {
makeQuestion(++currentQuestion);
}
}
function gradeUser() {
for(var i = 0; i < questionsArray.length; i++) {
if(userAnswers[i] == questionsArray[i].correctAnswer) {
totalCorrect++;
}
}
displayTotal = totalCorrect + "/" + questionsArray.length;
}
function stripWhitespaceDoublePass(XMLnode) {
for (var i = 0; i < XMLnode.childNodes.length; i++) {
if(XMLnode.childNodes[i].nodeType == 3) { // If the current node is a text node, check for any useful characters in the node.
var j = 0;
var emptyNode = true;
for(j = 0;j < XMLnode.childNodes[i].nodeValue.length; j++) {
if(XMLnode.childNodes[i].nodeValue.charCodeAt(j) > 32) {
emptyNode = false;
break;
}
}
if(emptyNode) {// If no useful charaters were found, delete the node.
XMLnode.childNodes[i].removeNode();
}
}
}
//Now that all the whitespace nodes have been removed from XMLnode,call stripWhitespaceDoublePass on its remaining children.
for(var k = 0; k < XMLnode.childNodes.length; k++) {
stripWhitespaceDoublePass(XMLnode.childNodes[k]);
}
}
dump.onRelease = function (){
unloadMovie("container2");
}
media_btn.onRelease = function (){
questionClip.duplicateMovieClip("container2",9999);
loadMovie("bigsmall3.swf","container2");
container2._xscale=110;
container2._yscale=100;
container2._x = 0 ;
container2._y = 0 ;
}
stop();
Ruby: Generate an Html - lookup dictionary
p "Enter a title"
title = gets.chomp
dict = {}
IO.foreach(title + ".txt") do
|x|
if
y = /::/.match(x)
y = y.pre_match
z=/::/.match(x)
z = z.post_match
dict[y] = z
end
end
File::open(title + '.htm', 'w') do |f|
f.puts "<HTML>\n<link href='Level3_3.css' rel='stylesheet' type='text/css'><HEAD><TITLE>" + title + "</TITLE></HEAD>"
f.puts "<CENTER><A NAME=\"page_top\"><H1>" + title + "</H1></A>"
f.puts "by Charles L. Snyder, MD<BR>\n"
f.puts "</CENTER>\n<HR>\n"
dict.keys.sort.each {|s| f.puts "<A HREF='#(#{s})'>#{s}</A><BR>"}
f.puts "</CENTER>\n<HR>\n"
i=0
while i < (dict.length)
f.puts '<A NAME="' + dict.keys[i] + '"></A><H2>' + dict.keys.sort[i] + "</H2>" + dict.values[i] + "<BR>"
f.puts "<CENTER><A HREF=\'javascript:window.history.back()\'>Back</A> "
f.puts "</CENTER>\n<HR>\n"
i = i + 1
end
end
Ruby: Make Zipcode, country, keyword, and author histogram from xml
p "Enter a title"
title = gets.chomp
dict = {}
IO.foreach(title + ".txt") do
|x|
if
y = /::/.match(x)
y = y.pre_match
z=/::/.match(x)
z = z.post_match
dict[y] = z
end
end
File::open(title + '.htm', 'w') do |f|
f.puts "<HTML>\n<link href='Level3_3.css' rel='stylesheet' type='text/css'><HEAD><TITLE>" + title + "</TITLE></HEAD>"
f.puts "<CENTER><A NAME=\"page_top\"><H1>" + title + "</H1></A>"
f.puts "by Charles L. Snyder, MD<BR>\n"
f.puts "</CENTER>\n<HR>\n"
dict.keys.sort.each {|s| f.puts "<A HREF='#(#{s})'>#{s}</A><BR>"}
f.puts "</CENTER>\n<HR>\n"
i=0
while i < (dict.length)
f.puts '<A NAME="' + dict.keys[i] + '"></A><H2>' + dict.keys.sort[i] + "</H2>" + dict.values[i] + "<BR>"
f.puts "<CENTER><A HREF=\'javascript:window.history.back()\'>Back</A> "
f.puts "</CENTER>\n<HR>\n"
i = i + 1
end
end
Ruby: Convert xml data into format for running quizmaker(tm) program
require 'ostruct'
require "rexml/document"
include REXML
print "What is the name of the xml file?"
p myFile = gets.chomp
doc = File.open("#{myFile}.xml") {|io| Document.new io}
quiz=[]
doc.elements.each("QUIZ/QUESTION") do |el_q|
question = OpenStruct.new
quiz.push question.text = el_q.attributes["TEXT"]
question.explain = el_q.attributes["EXPLAIN"]
question.answer = el_q.attributes["ANSWER"]
i=0
el_q.elements.each("CHOICE") do |el_ch|
(question.choices||=[]) << el_ch.text
quiz.push(question.choices[i].to_s)
if (i.to_s==question.answer)
quiz.push "Correct! #{question.explain}"
else
quiz.push "False! #{question.explain}"
end
i+=1
end
end
File::open("#{myFile}" + '.quiz', 'w') do |f|
f.puts quiz
end
Ruby: Read zipcode date from csv file, compare to zipcode lookup table, and make xml file for Google Maps
require 'csv'
mydata = []
zips = File.open('zips.txt') do |io|
h = {}
io.each_line do |line|
zip, freq = CSV.parse_line line
h[zip]=freq
end
h
end
File.open("target.xml","w") do |target|
File.open('ZIP_CODES.txt') do |io|
io.each_line do |line|
rec = CSV.parse_line line
freq = zips[rec[0]] or next
rec[1,0]=freq
target.write("<marker Zip=\"" + rec[0] + "\" " + "numpubs=\"" + rec[1] + "\" " + "lat=\" " + rec[2] + "\" " + "lng =\"" + rec[3] + "\" " + "city=\"" + rec[4] + "\" " + "state=\"" + rec[5] + " \"\/>" + "\n")
end
end
end
Ruby to Excel
require 'win32ole'
myfile = '/Users/charleslsnyder/Desktop/rvu.xls' #put in your path and filename
excel = WIN32OLE::new('excel.Application')
workbook = excel.Workbooks.Open(myfile)
worksheet = workbook.Worksheets(1) #get the first worksheet - change the name if needed
worksheet.Select
eor = (worksheet.range("a1").end(-4161).address).delete("$") # >> "$B$7" - end of row (eor)
eoc = (worksheet.range("a1").end(-4121).address).delete("$")
1. puts 'last row is ' + eoc
eoc.slice!(0) # just want the number of the last row
eor.slice!(1-5) #just want the letter of the last column
col_titles = []
surgeons = ["ANDREWS,WALTER S MD","GATTI,JOHN MD", "HOLCOMB,GEORGE WHIT MD", "MURPHY,JOHN PATRICK MD", "OSTLIE,DANIEL J MD", "SHARP,RONALD MD", "SNYDER,CHARLES MD"]
surgeons.each do |surg|
counter =0
worksheet.Range("a:a").each do |f|
modf= f.address.delete("$")
if ((f.value) surg and worksheet.Range("#{modf}").offset(0,4).value 54161)
counter +=1
end
end
puts "#{surg}: did #{counter} operations or encounters during the interval"
end
workbook.close
excel.Quit
Link
Mathematica retrieve oil and gold securities
(* Import crude oil security: tracks 1 month futures *)
rawCrud =
Import["http://www.etfsecurities.com/en/aum/
Historical_NAV_Outstanding_AUM.zip", "*"];
crudPosition = Position[rawCrud[[1, 1, 3]], "CRUD"][[1, 1]];
crudDates = Drop[rawCrud[[1, 1, All, 1]], 3];
crud = Drop[rawCrud[[1, 1, All, crudPosition]], 3];
crudT = Transpose[{crudDates, crud}];
Export["crud.mx", crudT];
(* Import gold bullion security *)
gbss = Import[
"http://www.exchangetradedgold.com/assets/dynamic/ETG/
GBS_UK_GBP_archive.csv"];
gbssData = Drop[gbss, 5];
gbssDates = gbssData[[All, 1]];
gbssPrice = gbssData[[All, 3]];
gbssPlot = Cases[Transpose[{gbssDates, gbssPrice}], {_, _?NumericQ}];
Export["gbss.mx", gbssPlot];
(* Optionally, import saved values *)
crudT = Import["crud.mx"];
gbssPlot = Import["gbss.mx"];
(* Plotting *)
gbssGBP = {#[[1]], #[[2]]/100} & /@ gbssPlot;
DateListPlot[{crudT, gbssGBP}, Joined -> True,
PlotLabel -> Style["\nGold Bullion and Crude Oil Futures", Large],
FrameLabel -> {{Style["=A3", Hue[106/117, 0.6, 0.6], Large],
Style["$", Hue[0.67, 0.6, 0.6], Large]}, {Null, Null}},
RotateLabel -> False, ImageSize -> 450,
PlotRange -> {Automatic, {0, 100}},
Epilog -> {Inset[Style["GBSS:LSE", 12, Bold, Hue[106/117, 0.6, 0.6]],
Automatic, {-4.5, -6}],
Inset[Style["CRUD:LSE", 12, Bold, Hue[0.67, 0.6, 0.6]],
Automatic, {-4.5, 7}]}]