controlling your network speed (7-Dec @ 08:13)
Syntax Highlighted Code
- sudo ipfw pipe 1 config bw 4KByte/s
- sudo ipfw add 100 pipe 1 tcp from any to me 80
- You’ll need to use your hostname or external IP address in the URL.
- When you’re done testing, delete the rule with sudo ipfw delete 100 or delete all custom rules with ipfw flush.
Plain Code
sudo ipfw pipe 1 config bw 4KByte/s
sudo ipfw add 100 pipe 1 tcp from any to me 80
You’ll need to use your hostname or external IP address in the URL.
When you’re done testing, delete the rule with sudo ipfw delete 100 or delete all custom rules with ipfw flush.
When float and double fails (30-Sep @ 20:15)
Syntax Highlighted Code
- >0.5800000000000001
- [33 more lines...]
Plain Code
System.out.println(1.01 - .43);
>0.5800000000000001
System.out.println(1.00 - 4*0.2);
>0.19999999999999996
just rounding? no!
public static void main(String[] args) {
double funds = 1.00;
int itemsBought = 0;
for (double price = .10; funds >= price; price += .10) {
funds -= price;
itemsBought++;
}
System.out.println(itemsBought + " items bought.");
System.out.println("Change $" + funds);
}
>3 items bought.
>Change $0.3999999999999999
Answer should be:
>4 items bought.
>Change $0
In decimal math, there are many numbers that can’t be represented with a fixed number of decimal digits, e.g. 1/3 = 0.3333333333…….
In base 2, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. .2 equals 2/10 equals 1/5, resulting in the binary fractional number 0.001100110011001…
Floating point numbers only have 32 or 64 bits of precision, so the digits are cut off at some point, and the resulting number is 0.199999999999999996 in decimal, not 0.2.
getDate (20-Sep @ 15:33)
Syntax Highlighted Code
Plain Code
private static Date date(int year, int month, int day, int hour, int minute, int second) {
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, day, hour, minute, second);
return cal.getTime();
}
parse url parameter (25-Aug @ 16:49)
Syntax Highlighted Code
- function getUrlParam(name, url) {
- var url = url || window.location.href;
- var queryString = url.substr(url.indexOf('?') + 1);
- var params = queryString.split('&');
- [7 more lines...]
Plain Code
function getUrlParam(name, url) {
var url = url || window.location.href;
var queryString = url.substr(url.indexOf('?') + 1);
var params = queryString.split('&');
for(i in params) {
var paramParts = params[i].split('=');
if(paramParts[0] == name) {
return paramParts[1];
}
}
return undefined;
}
pager (13-Dec @ 16:20)
Syntax Highlighted Code
- /*
- * Pager - jQuery plugin to format serch result pagers
- */
- [101 more lines...]
Plain Code
/*
* Pager - jQuery plugin to format serch result pagers
*/
;(function($) {
function assertHasClass(element, c, errormsg) {
if(!$(element).hasClass(c)) {throw errormsg;}
}
$.extend($.fn, {
showPager: function(callback, size) {
var PAGER_SIZE = parseInt(size) || 14;
$(this).each(function() {
assertHasClass(this, 'pager', "element must be a pager");
var pages = jQuery('.page:not(.nextPage, .previousPage)', this);
if(pages.length <= PAGER_SIZE) {
pages.show();
} else {
var current = pages.index(pages.filter('.currentPage'));
if(current<=PAGER_SIZE-4) {
pages.each(function(i) {
var page = jQuery(this);
if(i === PAGER_SIZE - 2){
page.replaceWith('<span>...</span>');
}else if(i<PAGER_SIZE - 1) {
page.show();
} else if(i === pages.length - 1) {
page.show();
}
});
} else if(current > pages.length-(PAGER_SIZE-2)) {
pages.each(function(i) {
var page = jQuery(this);
if(i === 0){
page.show();
}else if(i === 1){
page.replaceWith('<span>...</span>');
}else if(i > pages.length - (PAGER_SIZE-1)) {
page.show();
}
});
} else {
pages.each(function(i) {
var page = jQuery(this);
if(i === 0){
page.show();
}else if(i === 1){
page.replaceWith('<span>...</span>');
}else if(i === pages.length -1) {
page.show();
}else if(i === pages.length - 2){
page.replaceWith('<span>...</span>');
}else if(i > (current - Math.floor(PAGER_SIZE/2)+2) && (i < (current + Math.floor(PAGER_SIZE/2) - 1))) {
page.show();
}
});
}
}
if(typeof callback == 'function') {
jQuery('a.page', this).click(function() {
callback(this.href.slice(this.href.lastIndexOf('#')+1, this.href.length));
});
}
return this;
});
}
});
})(jQuery);
<%@ attribute name="current" required="true" rtexprvalue="true" type="java.lang.Integer" %>
<%@ attribute name="pages" required="true" rtexprvalue="true" type="java.util.Collection" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<span class="pager">
<c:choose>
<c:when test="${current > 1}"><a class="page previousPage" href="#${current - 1}"><fmt:message key="general.previous"/></a></c:when>
<c:otherwise><span class="page previousPage"><fmt:message key="general.previous"/></span></c:otherwise>
</c:choose>
<c:forEach var="page" items="${pages}">
<c:choose>
<c:when test="${page == current}">
<span class="page currentPage" style="display: none">${page}</span>
</c:when>
<c:when test="${page == -1}">
<span class="page break">...</span>
</c:when>
<c:otherwise>
<a class="page" href="#${page}" style="display: none">${page}</a>
</c:otherwise>
</c:choose>
</c:forEach>
<c:choose>
<c:when test="${current < fn:length(pages)}"><a class="page nextPage" href="#${current + 1}"><fmt:message key="general.next"/></a></c:when>
<c:otherwise><span class="page nextPage"><fmt:message key="general.next"/></span></c:otherwise>
</c:choose>
</span>
shell config script (18-Nov @ 09:51)
Syntax Highlighted Code
- # my shell variables
- #export PS1="\[\033[1;44m\]\u \w\[\033[0m\] "
- export PATH="$PATH:~/bin:~/scripts"
- [50 more lines...]
Plain Code
# my shell variables
#export PS1="\[\033[1;44m\]\u \w\[\033[0m\] "
export PATH="$PATH:~/bin:~/scripts"
#-------------------------------------------------------------
# General aliases:
#-------------------------------------------------------------
alias ll="ls -la"
alias path='echo -e ${PATH//:/\\n}'
alias cd..="cd .."
alias ..="cd .."
alias which="type -a"
#More is not installed, so use less instead
alias more="less"
#-------------------------------------------------------------
# Project related aliases:
#-------------------------------------------------------------
alias follow_log="tail -f /cygdrive/c/java/glassfish/domains/domain1/logs/server.log"
alias cd_logs="cd /cygdrive/c/java/glassfish/domains/domain1/logs"
alias cd_workspace="cd ~/workspace"
alias cd_symphony="cd ~/workspace/symphony-web"
# TSO:
alias cd_admin="cd ~/workspace/tso-admin"
alias cd_builder="cd ~/workspace/tso-builder"
alias cd_portal="cd ~/workspace/tso-portal"
alias cd_melody="cd ~/workspace/tso-melody"
alias build_all="cd_portal && mvn glassfish:undeploy && cd_builder && mvn clean install && mvn eclipse:eclipse"
alias build_all_skip_test="cd_portal && mvn glassfish:undeploy && cd_builder && mvn clean install -Dmaven.test.skip=true && mvn eclipse:eclipse"
alias build_portal="cd_portal && mvn -Dmaven.test.skip=true clean install"
alias build_melody="cd_melody && mvn -Dmaven.test.skip=true clean install"
alias build_and_deploy_portal="cd_portal && mvn glassfish:undeploy && build_portal && mvn glassfish:deploy"
#-------------------------------------------------------------
# File & string-related functions:
#-------------------------------------------------------------
# Find a file with a pattern in name:
function ff() { find . -type f -iname '*'$*'*' -ls ; }
# Find a file with pattern $1 in name and Execute $2 on it:
function fe()
{ find . -type f -iname '*'${1:-}'*' -exec ${2:-file} {} \; ; }
scrollIntoView method JavaScript (13-Nov @ 11:57)
Syntax Highlighted Code
- var targetOffset = jQuery(target).offset().top;
- var containerOffset = jQuery('#productsDiv').offset().top;
- if(targetOffset < containerOffset) {
- target.scrollIntoView();
- }
Plain Code
var targetOffset = jQuery(target).offset().top;
var containerOffset = jQuery('#productsDiv').offset().top;
if(targetOffset < containerOffset) {
target.scrollIntoView();
}
javascript pointcut example (11-Nov @ 10:56)
Syntax Highlighted Code
- /* This will intercept the jQuery bind event
- * and logs the number of calls
- */
- jQuery.fn.bind = function (bind) {
- [5 more lines...]
Plain Code
/* This will intercept the jQuery bind event
* and logs the number of calls
*/
jQuery.fn.bind = function (bind) {
return function () {
console.count("jQuery bind count");
console.log("jQuery bind %o", this);
return bind.apply(this, arguments);
};
}(jQuery.fn.bind);
explorer style jquery treeview (23-Oct @ 14:32)
Syntax Highlighted Code
- /*
- * Treeview 1.4 - jQuery plugin to hide and show branches of a tree
- *
- * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
- [275 more lines...]
Plain Code
/*
* Treeview 1.4 - jQuery plugin to hide and show branches of a tree
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.treeview.js 4684 2008-02-07 19:08:06Z joern.zaefferer $
*
* Additions by Andreas Bjärlestam:
* - Added stayopen option
* - Added expandAll jQuery object method
* - Added removeFolders jQuery object method
*/
;(function($) {
$.extend($.fn, {
swapClass: function(c1, c2) {
var c1Elements = this.filter('.' + c1);
this.filter('.' + c2).removeClass(c2).addClass(c1);
c1Elements.removeClass(c1).addClass(c2);
return this;
},
replaceClass: function(c1, c2) {
return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
},
hoverClass: function(className) {
className = className || "hover";
return this.hover(function() {
$(this).addClass(className);
}, function() {
$(this).removeClass(className);
});
},
heightToggle: function(animated, callback) {
animated ?
this.animate({ height: "toggle" }, animated, callback) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
if(callback)
callback.apply(this, arguments);
});
},
heightHide: function(animated, callback) {
if (animated) {
this.animate({ height: "hide" }, animated, callback);
} else {
this.hide();
if (callback)
this.each(callback);
}
},
prepareBranches: function(settings) {
if (!settings.prerendered) {
// mark last tree items
this.filter(":last-child:not(ul)").addClass(CLASSES.last);
// collapse whole tree, or only those marked as closed, anyway except those marked as open
this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
}
// return all items with sublists
return this.filter(":has(>ul)");
},
applyClasses: function(settings, toggler) {
this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event) {
toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (!settings.prerendered) {
// handle closed ones first
this.filter(":has(>ul:hidden)")
.addClass(CLASSES.expandable)
.replaceClass(CLASSES.last, CLASSES.lastExpandable);
// handle open ones
this.not(":has(>ul:hidden)")
.addClass(CLASSES.collapsable)
.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
// create hitarea
this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea).each(function() {
var classes = "";
$.each($(this).parent().attr("class").split(" "), function() {
classes += this + "-hitarea ";
});
$(this).addClass( classes );
});
}
// apply event to hitarea
this.find("div." + CLASSES.hitarea).click( toggler );
},
expandAll: function() {
if(!this.hasClass("treeview")) {throw "can't expand element that is not a tree"};
$("div." + CLASSES.hitarea, this)
.replaceClass( CLASSES.expandableHitarea, CLASSES.collapsableHitarea )
.replaceClass( CLASSES.lastExpandableHitarea, CLASSES.lastCollapsableHitarea )
.parent()
.replaceClass( CLASSES.expandable, CLASSES.collapsable )
.replaceClass( CLASSES.lastExpandable, CLASSES.lastCollapsable )
.find( ">ul" ).show();
return this;
},
removeFolders: function(folderIds) {
if(!this.hasClass("treeview")) {throw "can't remove folders from element that is not a tree"};
var tree = this;
jQuery.each(folderIds, function() {
tree.find('input.folderId[value='+ this +']').parents('li:first').remove();
});
return this;
},
treeview: function(settings) {
settings = $.extend({
cookieId: "treeview"
}, settings);
if (settings.add) {
return this.trigger("add", [settings.add]);
}
if ( settings.toggle ) {
var callback = settings.toggle;
settings.toggle = function() {
return callback.apply($(this).parent()[0], arguments);
};
}
// factory for treecontroller
function treeController(tree, control) {
// factory for click handlers
function handler(filter) {
return function() {
// reuse toggle event handler, applying the elements to toggle
// start searching for all hitareas
toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
// for plain toggle, no filter is provided, otherwise we need to check the parent element
return filter ? $(this).parent("." + filter).length : true;
}) );
return false;
};
}
// click on first element to collapse tree
$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
// click on second to expand tree
$("a:eq(1)", control).click( handler(CLASSES.expandable) );
// click on third to toggle tree
$("a:eq(2)", control).click( handler() );
}
// handle toggle event
function toggler() {
if( settings.stayopen
&& $(this).is(':not(div.hitarea)')
&& $(this).parent().find(">.hitarea").hasClass(CLASSES.collapsableHitarea)) {
return;
}
$(this)
.parent()
// swap classes for hitarea
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
// swap classes for parent li
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
// find child lists
.find( ">ul" )
// toggle them
.heightToggle( settings.animated, settings.toggle );
if ( settings.unique ) {
$(this).parent()
.siblings()
// swap classes for hitarea
.find(">.hitarea")
.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
.replaceClass( CLASSES.collapsable, CLASSES.expandable )
.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find( ">ul" )
.heightHide( settings.animated, settings.toggle );
}
}
function serialize() {
function binary(arg) {
return arg ? 1 : 0;
}
var data = [];
branches.each(function(i, e) {
data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
});
$.cookie(settings.cookieId, data.join("") );
}
function deserialize() {
var stored = $.cookie(settings.cookieId);
if ( stored ) {
var data = stored.split("");
branches.each(function(i, e) {
$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
});
}
}
// add treeview class to activate styles
this.addClass("treeview");
// prepare branches and find all tree items with child lists
var branches = this.find("li").prepareBranches(settings);
switch(settings.persist) {
case "cookie":
var toggleCallback = settings.toggle;
settings.toggle = function() {
serialize();
if (toggleCallback) {
toggleCallback.apply(this, arguments);
}
};
deserialize();
break;
case "location":
var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); });
if ( current.length ) {
current.addClass("selected").parents("ul, li").add( current.next() ).show();
}
break;
}
branches.applyClasses(settings, toggler);
// if control option is set, create the treecontroller and show it
if ( settings.control ) {
treeController(this, settings.control);
$(settings.control).show();
}
return this.bind("add", function(event, branches) {
$(branches).prev()
.removeClass(CLASSES.last)
.removeClass(CLASSES.lastCollapsable)
.removeClass(CLASSES.lastExpandable)
.find(">.hitarea")
.removeClass(CLASSES.lastCollapsableHitarea)
.removeClass(CLASSES.lastExpandableHitarea);
$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, toggler);
});
}
});
// classes used by the plugin
// need to be styled via external stylesheet, see first example
var CLASSES = $.fn.treeview.classes = {
open: "open",
closed: "closed",
expandable: "expandable",
expandableHitarea: "expandable-hitarea",
lastExpandableHitarea: "lastExpandable-hitarea",
collapsable: "collapsable",
collapsableHitarea: "collapsable-hitarea",
lastCollapsableHitarea: "lastCollapsable-hitarea",
lastCollapsable: "lastCollapsable",
lastExpandable: "lastExpandable",
last: "last",
hitarea: "hitarea"
};
// provide backwards compability
$.fn.Treeview = $.fn.treeview;
})(jQuery);
Turning a list into a tree using recursion (15-Oct @ 14:03)
Syntax Highlighted Code
- private List<FolderTree> getTreeList(int parentId, List<Folder> folderList) {
- List<FolderTree> treeList = null;
- FolderTree tree = null;
- for (Folder folder : folderList) {
- [11 more lines...]
Plain Code
private List<FolderTree> getTreeList(int parentId, List<Folder> folderList) {
List<FolderTree> treeList = null;
FolderTree tree = null;
for (Folder folder : folderList) {
if((parentId == -1 && folder.getLevel() == 1) || (parentId != -1 && folder.getParentId() == parentId)) {
tree = new FolderTree(folder.getName());
tree.setId(folder.getId());
tree.setFolders(getTreeList(tree.getId(), folderList));
if(treeList == null) {
treeList = new ArrayList<FolderTree>();
}
treeList.add(tree);
}
}
return treeList;
}
Turning a list into a tree using HashMap (15-Oct @ 13:53)
Syntax Highlighted Code
- /**
- * This one assumes that the list is ordered so that parents come before children
- */
- public Tree listToTree(List<Item> list) {
- [43 more lines...]
Plain Code
/**
* This one assumes that the list is ordered so that parents come before children
*/
public Tree listToTree(List<Item> list) {
Map<Integer, Tree> refs = new HashMap<Integer, Tree>();
Tree root = new Tree(0);
Tree node = null
for(Item item: list) {
node = new Tree(item.id);
refs.put(item.id, node)
if(item.parent > 0) {
refs.get(item.parent).children().add(node);
} else {
root.children().add(node);
}
}
return root;
}
/**
* This one does not assume any specific order of the list
*/
public Tree listToTree(List<Item> list) {
Map<Integer, Tree> allNodes = new HashMap<Integer, Tree>();
Map<Integer, Collection<Tree>> subNodes = new HashMap<Integer, Collection<Tree>>();
Tree root = new Tree(0);
Tree node = null
for(Item item: list) {
node = new Tree(item.id);
allNodes.put(item.id, node);
if(item.parent.id > 0) {
if(subNodes.get(item.parent.id) == null) {
subNodes.put(item.parent.id, new ArrayList<Tree>());
}
subNodes.get(item.parent.id).add(node);
} else {
root.children().add(node);
}
}
for(Integer parent: subNodes.keySet()) {
allNodes.get(parent).children(subNodes.get());
}
return root;
}
JavaScript event delegator template for jQuery (2-Oct @ 13:48)
Syntax Highlighted Code
- jQuery(document).ready(function() {
- jQuery("body").click(function(e) {
- var target = jQuery(e.target);
- [3 more lines...]
Plain Code
jQuery(document).ready(function() {
jQuery("body").click(function(e) {
var target = jQuery(e.target);
if (target.hasClass('someclass')) return doSomeStuff();
if (target.hasClass('someotherclass')) return doOtherStuff();
});
});
JavaScript AOP Framework (6-May @ 10:01)
Syntax Highlighted Code
- /**
- * AOP framework for aspect oriented programming in JavaScript
- */
- [49 more lines...]
Plain Code
/**
* AOP framework for aspect oriented programming in JavaScript
*/
var AOP = AOP || function() {
//Private methods
function toArray(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
//Public methods
var public = {
around: function(obj, fname, advice) {
var oldFunc = obj[fname];
obj[fname] = function() {
var args = [oldFunc].concat(toArray(arguments));
return advice.apply(this, args);
};
},
before: function(obj, fname, advice) {
var oldFunc = obj[fname];
obj[fname] = function() {
var args = [oldFunc].concat(toArray(arguments));
advice.apply(this, args);
return oldFunc.apply(this, arguments);
};
},
after: function(obj, fname, advice) {
var oldFunc = obj[fname];
obj[fname] = function() {
var args = [oldFunc].concat(toArray(arguments));
oldFunc.apply(this, arguments);
return advice.apply(this, args);
};
},
callMethod: function(args) {
var argsArray = toArray(args);
return argsArray[0].apply(this, argsArray.slice(1));
}
};
return public;
}();
z-index fix for internet explorer (11-Feb @ 15:47)
Syntax Highlighted Code
Plain Code
<html>
<head>
<script type="text/javascript">
// make the specified div a windowed control in IE6
// this masks an iframe (which is a windowed control) onto the div,
// turning the div into a windowed control itself
function makeWindowed(p_div)
{
var is_ie6 =
document.all &&
(navigator.userAgent.toLowerCase().indexOf("msie 6.") != -1);
if (is_ie6)
{
var html =
"<iframe style=\"position: absolute; display: block; " +
"z-index: -1; width: 100%; height: 100%; top: 0; left: 0;" +
"filter: mask(); background-color: #ffffff; \"></iframe>";
if (p_div) p_div.innerHTML += html;
// force refresh of div
var olddisplay = p_div.style.display;
p_div.style.display = 'none';
p_div.style.display = olddisplay;
};
}
</script>
</head>
<body>
<div id="test" style="position: absolute; z-index: 2;
top: 50; left: 30; width: 200px; height: 200px;
background-color: red">
</div>
<select style="position: absolute; z-index: 1; top: 50;">
<option>test</option>
</select>
<a href="javascript:makeWindowed(document.getElementById('test'));">
Make Windowed</a>
</body>
</html>
JavaScript event delegator template (10-Feb @ 13:48)
Syntax Highlighted Code
- window.onload = function () { var navigation = document.getElementById("some_element_high_up_in_the_hierarchy");
- navigation.onclick = function (evt) {
- // Event tweaks, since IE wants to go its own way...
- var event = evt || window.event;
- [5 more lines...]
Plain Code
window.onload = function () { var navigation = document.getElementById("some_element_high_up_in_the_hierarchy");
navigation.onclick = function (evt) {
// Event tweaks, since IE wants to go its own way...
var event = evt || window.event;
var target = event.target || event.srcElement;
if(target.className && target.className==='someClass') {
//do your stuff here
}
}
};
JavaScript module template (1-Dec @ 10:20)
Syntax Highlighted Code
- var MyModule = MyModule || (function() {
- //Put private stuff here
- [43 more lines...]
Plain Code
var MyModule = MyModule || (function() {
//Put private stuff here
var privateProperty = "sectret stuff";
function myPrivateFunction() {
}
//Put public stuff here
var public = {
myPublicProperty: "value",
myPublicMethod: function() {
},
myPublicMethod2: function() {
}
};
return public;
})();
-- Variation --
var MyModule = MyModule || new function() {
//Put private stuff here
var privateProperty = "sectret stuff";
function myPrivateFunction() {
}
//Put public stuff here
this.myPublicProperty = "value";
this.myPublicMethod = function() {
};
this.myPublicMethod2 = function() {
};
}
simple JavaScript logger (1-Dec @ 10:04)
Syntax Highlighted Code
- <span id='testOutput'>Ouptput: <br/></span>
- <script language="JavaScript" type="text/javascript">
- [24 more lines...]
Plain Code
<span id='testOutput'>Ouptput: <br/></span>
<script language="JavaScript" type="text/javascript">
function logg(text) {
var output = document.getElementById('testOutput');
output.innerHTML=output.innerHTML + text + "<br></br>";
return true;
}
//Not sure this one works correctly
function dumpProps(obj, parent) {
// Go through all the properties of the passed-in object
for (var i in obj) {
// if a parent (2nd parameter) was passed in, then use that to
// build the message. Message includes i (the object's property name)
// then the object's property value on a new line
if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
// Display the message. If the user clicks "OK", then continue. If they
// click "CANCEL" then quit this level of recursion
if (!logg(msg)) { return; }
// If this property (i) is an object, then recursively process the object
if (typeof obj[i] == "object") {
if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
}
}
}
</script>
Merging Lists (19-Nov @ 12:48)
Syntax Highlighted Code
- /*
- * main method to try them out
- */
- [76 more lines...]
Plain Code
/*
* main method to try them out
*/
public static void main(String[] args) {
List<ProcessAnimal> animals = new ArrayList<ProcessAnimal>();
List<ProcessAnimal> excluded = new ArrayList<ProcessAnimal>();
for (int i = 0; i < 40; i++) {
ProcessAnimal animal = new ProcessAnimal();
animal.setInternalId(i);
animals.add(animal);
}
for (int i = 0; i < 10; i++) {
ProcessAnimal animal = new ProcessAnimal();
animal.setInternalId(i++);
i++;
excluded.add(animal);
}
long start = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
List<ProcessAnimal> incl = testLists1(animals, excluded);
// System.out.println("Incl.size " + incl.size());
}
System.out.println("Time spent1: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
List<ProcessAnimal> incl = testLists2(animals, excluded);
// System.out.println("Incl.size " + incl.size());
}
System.out.println("Time spent2: " + (System.currentTimeMillis() - start));
}
/**
* This one is faster when the excluded list is big
*/
private static List<ProcessAnimal> testLists2(List<ProcessAnimal> animals, List<ProcessAnimal> excluded) {
List<ProcessAnimal> result = new ArrayList<ProcessAnimal>();
HashMap<Integer, ProcessAnimal> animalMap = new HashMap<Integer, ProcessAnimal>();
HashMap<Integer, ProcessAnimal> exclMap = new HashMap<Integer, ProcessAnimal>();
for (ProcessAnimal animal : animals) {
animalMap.put(animal.getInternalId(), animal);
}
for (ProcessAnimal animal : excluded) {
exclMap.put(animal.getInternalId(), animal);
}
Set<Integer> keys = animalMap.keySet();
for (Integer key : keys) {
if(exclMap.get(key) == null) {
result.add(animalMap.get(key));
}
}
return result;
}
/**
* This one is faster when the excluded list is small
*/
private static List<ProcessAnimal> testLists1(List<ProcessAnimal> animals, List<ProcessAnimal> excluded) {
List<ProcessAnimal> result = new ArrayList<ProcessAnimal>();
for (ProcessAnimal animal : animals) {
boolean included = true;
for (ProcessAnimal excludedAnimal: excluded) {
if(animal.getInternalId() == excludedAnimal.getInternalId()) {
included = false;
}
}
if(included) {
result.add(animal);
}
}
return result;
}
jdbcTemplate example (7-Nov @ 10:21)
Syntax Highlighted Code
- String name = "bosse";
- [2 more lines...]
Plain Code
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String name = "bosse";
int before = jdbcTemplate.queryForInt("select count(*) from PERSON where NAME='bosse' and BIRTH_DATE='"+ formatter.format(today) + "'");
jdbcTemplate.execute("update PERSON set BIRTH_DATE='" + formatter.format(today) + "' where NAME=" + name);