Posted by: pureessence on: October 23, 2011
幸福是什么?其实幸福没有绝对的答案,关键在于你的生活态度。善于抓住幸福的人才懂得什么是幸福。一直以为感受幸福是件很困难的事,那是一种灯火阑珊处的境界。经过岁月的流年以后,才明白,幸福其实很简单,只要心灵有所满足、有所慰藉就是幸福。
幸福就是一种满足感。
健康的活着就是一种莫大的幸福!!
幸福无处不在 只要用心细细体会 你就能感觉到。
Posted by: pureessence on: October 1, 2011
A coworker of my husband’s, let’s call him Watson, has some interesting ways of dealing with situations. As a system administrator, he has unique powers.
Two days ago my husband received a support ticket regarding a temporary employee unable to log into her machine. My husband updated her password and verified and he could log in and closed the ticket. A day later, the ticket was reopened with the same issue. This time my husband tried her login on a different machine and true enough, he got the invalid username or password error. He searched Active Directory looking for the temporary employee’s login and found nothing. It appeared someone had deleted the employee’s account.
My husband scratched his head and inquired Watson:
“Watson, did you do anything with Mary’s account?”
Watson: “Yes, the manager requested that I delete her account.”
My husband got the manager on the phone and asked about the situation. The manager confirmed that he created a ticket to have Mary removed from a certain mailing list. As my husband was on the phone with the manager, Watson was listening and became rather irritated and printed the ticket and showed it to my husband. The ticket titled “Remove Mary from mailing list ABC”. My husband said to Watson:
“Watson, the ticket requested her removed from a mailing list, you deleted her entire Active Directory account!”
Watson: “How else was I supposed to get her off that mailing list?”
My husband: “Remove her from the mailing list?”
Watson barked: “Yes! I could have done that!” and stormed off and did not say anything else.
Posted by: pureessence on: September 22, 2011
There is a business requirement on a project I have at work to only allow a certain number of properties editable at a certain stage of the domain object’s life cycle. And like always, the properties defined to be editable could change in the future.
I already have a page that allows the user to edit all properties of the domain object, I really do not wish to duplicate that code. Please note that if you set an input element on a form as disabled, the value associated with the element will NOT be submitted via form post, that certainly is NOT what I’m looking for. I want the values of the *read only* fields still be submitted by the form but I just don’t want the user to edit the values. So I looked into using the readonly attribute in HTML. It’s complete crap.
For faqs.org:
It’s important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don’t change the value of the field.
Basically it works half-hearted and most browsers (IE, FF) do not indicate (by default) that a field is readonly. So the users will probably be left wondering why they cannot edit the field.
I searched around for an alternative and found this wonderful jQuery plugin readonly. Even though I couldn’t get it to work right for my application, the idea behind it is genius. You basically put overlay layers on top of any input fields you wish to make read only. The plugin seems a bit outdated. Perhaps it doesn’t work well with the newer version of jQuery but the idea still works well. Therefore I implemented my own.
This implementation automatically makes all input fields read only unless the input field has the class excludeMeFromReadOnly. This is just my implementation for demonstration. I do not provide any support for this code. Use where you see fit.
CSS
.readOnlyOverlay {
position: absolute;
background-color: #666;
opacity: 0.3;
filter: alpha(opacity=30);
padding: 0pt !IMPORTANT;
margin: 0pt !IMPORTANT;
}
javascript function generateOverlay
function generateOverlay(element) {
var dimension = getDimensions($(element));
//console.log('top=' + dimension.top + ' left=' + dimension.left +' width='+ dimension.width + ' height=' + dimension.height);
// disassociate corresponding label attributes so the value of the element cannot be changed by clicking on the labels
var id = $(element).attr('id');
var label = $('label[for="'+id+'"]');
$(label).removeAttr('for');
// set my tabindex to -1 so tabs will ignore me
$(element).attr('tabIndex', -1);
$(label).attr('tabIndex', -1);
// create a div overlay
var overlay = $('<div class="readOnlyOverlay"> </div>').appendTo('body');
$(overlay).css('top', dimension.top).css('left', dimension.left).css('width', dimension.width).css('height', dimension.height);
}
javascript function getDimensions
function getDimensions(element){
var ret = {};
// The multiple acquisitions of the CSS styles are required to cover any border and padding the elements may have.
// The Ternary (parseInt(...) || 0) statements fix a bug in IE6 where it returns NaN,
// which doesn't play nicely when adding to numbers...
ret.width = $(element).width()
+ (parseInt($(element).css('borderLeftWidth')) || 0)
+ (parseInt($(element).css('borderRightWidth')) || 0)
+ (parseInt($(element).css('padding-left')) || 0)
+ (parseInt($(element).css('padding-right')) || 0);
ret.height = $(element).height()
+ (parseInt($(element).css('borderTopWidth')) || 0)
+ (parseInt($(element).css('borderBottomWidth')) || 0)
+ (parseInt($(element).css('padding-bottom')) || 0)
+ (parseInt($(element).css('padding-bottom')) || 0);
var offsets = $(element).offset();
ret.left = offsets.left;
ret.top = offsets.top;
return ret;
}
jQuery selector
// select all input,select elements. I'd wrap my form in a div.
$('div#formContent input, div#formContent select, div#formContent textarea').each(function(i, element) {
// if the element doesn't have the class named excludeMeFromReadOnly, overlay it to make it look like it's read only
if(!$(element).hasClass('excludeMeFromReadOnly')) {
generateOverlay($(element));
}
});
Please note, the plugin contains a lot more logic including IE hacks etc. Fortunately for me, I really don’t care about IE prior to version 8 in my particular scenario. Therefore I don’t need all of those hacks.
Posted by: pureessence on: September 2, 2011
Being a big jQuery fan, I use jQuery.each method a lot in my Javascript code. Until recently I didn’t think too hard what jQuery.each really is.
Its description says it’s an iterator but it certainly is NOT a true iterator.
For example:
Let me know what you expect the code below to return.
var myVars = ['foo1', 'foo2', 'foo3'];
function containsValue(myValue, myCollection) {
jQuery.each(myCollection, function(i, val) {
if(val == myValue) {
return true;
}
});
return false;
}
$(document).ready(function() {
console.log(containsValue('foo2', myVars));
});
Before I know better, I’d expect it to return true. Since myCollection DOES CONTAIN the value ‘foo2′. However the function containsValue WILL ALWAYS RETURN FALSE. That’s because when you return out of jQuery.each, it simply exits out of jQuery.each but not the containing function. In fact, whether you do anything in the callback function at all, jQuery.each ALWAYS RETURNS the collection you pass in.
e.g.
var returnedVar = jQuery.each(myVars, function(i, val) {});
console.log(returnedVar === myVars); // evaluates to true
In my opinion, jQuery.each acts more like a closure than an iterator. Sure you may use it as an iterator as long as you not returning anything. If you are just changing behaviors or collecting information, it will mimic an iterator. But you need to know, it really is not an iterator.
Personally I’m going to start to use Javascript’s native for..in statement instead of jQuery.each for Javascript collection variables. There is also an argument that jQuery.each may never perform faster than the native support for an iterator. Therefore below I will rewrite the function above using for..in.
function containsValueWithFor(myValue, myCollection) {
for (index in myCollection) {
if(myCollection[index] == myValue) {
return true;
}
}
return false;
}
console.log(containsValueWithFor('foo2', myVars)); // true
var myMap = {'lala':'foo1', '2':'foo2', 'b':'foo3'};
console.log(containsValueWithFor('foo2', myMap)); // true as well for an object/map
—>Example code<—
Posted by: pureessence on: August 8, 2011
My survey responses to the 2011 nfjs Central Iowa Software Symposium event for my company.
Benefits to you and the company from attending this event:
Keep up to date regarding the current technologies and development in the Java community.
Information that your co-workers / the company should be aware of:
Functional programming is making a big splash on the JVM. We really should come out of the traditional OO & imperative programming mindset and start think of solving programming challenges in a multi-paradigm fashion. We should upgrade from CVS to Git
Information that you learned that may have negative impacts to the company:
None
Would recommend this event / company presenting to someone else? Why?
Yes. The presenters have great knowledge about their topics. They always make me think harder and different about what I am doing at work.
Additional Comments or Suggestions:
I greatly enjoyed learning more about Scala, akka and functional programming thinking. The multi-paradigm session by Ted Neward opened my eyes. I took logic & functional programming courses in college and was super impressed by how concise and powerful those languages can be used to solve particular issues. Now many frameworks on the JVM prove that as Java programmers (who are innately OO & imperative), we may fully utilize the power of programming languages of other paradigms. This motivates me to explore a newer realm of programming.
I learned a lot from the Seven wastes of software development session e.g. communication is 38% tone, 7% words & 55% body languages. Therefore we should avoid plain emails for especially business rules discussion; converse with a coworker face to face is a much more effective way of communication. I think I don’t always do well in this area. Perhaps programmers are generally shy and introverted. I need to learn to open up more.
I also loved the Spock session although I feel Spock as a framework is yet completely mature for prime time. The fact it doesn’t have a version 1.x release somewhat speaks for this. (And it’s not yet in maven central repository.) I love its various features. But it’s still under heavy development phase as its community is actively adding more features to the framework. If we start using it now, we may need to upgrade our code dramatically later to get its full effects e.g. the @Unroll feature is going to change soon. However, I’m super excited to revisit it in a few months or so to see where it’s at. The fact that it’s a test framework great for both state testing & interaction testing (mocking) is awesome! It sounds like the mocking part of it is yet as mature as other mocking frameworks e.g. Mockito. For example, it doesn’t support partial mock/spy. This does not make me want to switch from Mockito to use it.
I will also use many of the new features of Groovy I learned since I just started using Groovy for testing. The SQL class Groovy has is extremely powerful and gave me many ideas as how I can utilize it to make testing more dynamic and more maintenance free.
Posted by: pureessence on: July 24, 2011
After over ten years of javascript programming, I’m finally seriously considering writing at least unit tests for my javascript. Since I’m such a big fan of jQuery, QUnit seems like the obvious choice.
It’s sad but better late than never.
The truth is, in my opinion, the fact that javascript test frameworks do not yet maturely work with many of the continuous integration software deters programmers from using them. What’s the point of unit testing if they don’t automatically get run? Based on my research, JSUnit is the only one that integrates with ANT innately. But JSUnit is more of an abandomware now so people are looking for alternatives.
QUnit + CI topics
>> Run my test suite <<
QUnit simple example:
HTML:
<!DOCTYPE html> <html> <head> <title>Test Suite</title> <script src="http://code.jquery.com/jquery-latest.js"></script> <link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" /> <script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script> <!-- Your source files go here --> <script type="text/javascript" src="functions.js"></script> <!-- Your tests files go here --> <script type="text/javascript" src="isEvenTest.js"></script> <script type="text/javascript" src="startsWithTest.js"></script> </head> <body> <h1 id="qunit-header">QUnit example</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <!-- Any HTML you may require for your tests to work properly --> <div id="qunit-fixture">test markup, will be hidden</div> </body> </html>
Source javascript file:
function isEven(val) {
return val % 2 === 0;
}
function startsWith(data, startsWithStr) {
data = jQuery.trim(data);
startsWithStr = jQuery.trim(startsWithStr);
if(data) {
return data.toUpperCase().lastIndexOf(startsWithStr.toUpperCase(), 0) === 0;
} else if(data === startsWithStr) {
return true;
} else {
return false;
}
}
Sample test file:
$(document).ready(function(){
module("startsWithTest");
test('startsWith', function() {
ok(startsWith("ll-925", "ll-"), 'Starts with ll-');
ok(!startsWith("ll-925", "xl-"), 'Does not start with xl-');
ok(!startsWith("", "xx-"), 'Does not start with xx-');
ok(startsWith(" xx-sdgj ", "xx-"), 'Trimming test: starts with xx-');
ok(startsWith(" xx-sdgj", " xx- "), 'Trimming test 2: starts with xx-');
ok(startsWith("", " "), 'Empty string starts with empty string');
ok(startsWith("Mn-u59", "mN-"), 'Non case sensitive test');
// raises(startsWith(foo, " "), 'Undefined test 1'); // undefined is obviously not considered a normal exception
})
});
>> git repo for the source <<
Additional resources:
Posted by: pureessence on: July 24, 2011
Gui Lin (Chinese: 桂林; pinyin: Guìlín;) is a prefecture-level city in China, situated in the northeast of the Guangxi Zhuang Autonomous Region on the west bank of the Li River. Its name means “forest of Sweet Osmanthus”, owing to the large number of fragrant Sweet Osmanthus trees located in the city. The city has long been renowned for its unique scenery.
My father and his girlfriend’s family visited Gui Lin about a month ago.
Although the scenery was exceptional like you’d expect but his experience was far from it. Gui Lin is a cyclone for tourist traps. He shared some of his bad experience and they were so jaw dropping, I have to blog about them.
The Taxi
There is no meter on any of the taxi in that city. You bargain the price prior to your ride with the taxi driver and then s/he takes you to your destination. See a problem with this particular arrangement or lack of governmental enforcement of honesty? Well, he’s experienced it.
On the way back from a previous trip, my father inquired the average cab fare from his hotel to the dock for his next day’s cruise. The driver indicated around 60 rmb. The next morning, a different taxi driver wanted 80 rmb for the ride. My father did not give in since he thought the fare should be 60 rmb. The taxi driver instead of not agreeing to the ride, took the 60 rmb and dropped them off at a different dock than their actual desired destination. It took them a while to figure out they were at the WRONG dock since they were unfamiliar with the area. They were late for their cruise and had to spend additional fare in order to travel to the correct dock.
The Bamboo Raft Ride
A bamboo raft takes you down the stream of the river slowly by its current. My father had arranged a taxi to pick them up at the end of the trip. Although the price of the ride was advertised to include food, they provided inedible dishes on the raft so they could market other dishes for extra cost. There were various vendors who stationed at different locations down the stream. Some claimed the fish dishes were prepared with fish freshly caught in the river earlier in the morning. They charged a lot for them. My father and his girlfriend’s family did not purchase any. They were later dropped off at a dock in which they thought was the end of the trip. However, after a half hour wait for the taxi, my father called the taxi driver he paid for. The taxi driver informed my dad that he was dropped at the wrong location. The raft people dropped them off way prior to the end of the trip. My father was once more duped for exercising his right of not purchasing overpriced marketed tourist goods.
Gui Lin has been on my list of must visit places for a long time. Based on my dad’s accounts, I think I’m going to wait a little longer for that wish.
Posted by: pureessence on: July 22, 2011
Today is my first attempt at using SPEL. After a mighty struggle, I was able to conquer it!
Background:
I needed a year variable for some work on a jsp page. It’s not always defined. I know for our routable datasource, a default year is required in order for it to work. I wanted to use the same default year but I only want the variable to be defined once and used in both places.
So I looked into SPEL.
It seems like the correct solution for the problem.
My original idea:

As it turns out, SPEL does not yet support embedded variables. SPEL, you must improve yourself!
My workaround:
I do not love it but it accomplishes my goal of not defining it more than one place.
Define the variable in a properties file e.g. application.properties
defaultYear=2011
Then use placeholder instead of SPEL notation to include it in spring.
Syntax grrr syntax:
Sadly some of my time was to learn the fact you CANNOT put a space between # and { in SPEL. For example, # {bean.property} will NOT work, but #{bean.property} will. It seems obvious afterwards but the error message you get just DOES NOT help you come to that conclusion.
Moral of the story:
SPEL is very handy but it’s yet perfect. Do keep that in mind as an alternative solution when dealing with Spring. If you use annotation, you can do @Value(“#{bean.property}”). Refer documentation for more info.
Posted by: pureessence on: July 19, 2011
My husband Andy made these meatballs last night. They were soooooo good. I had to share the recipe since it’s his ORIGINAL creation with inspiration from Robert Irvine.
Ingredients
½ lb Ground Beef
½ lb Ground Pork
1 Bratwurst Patty (approx. 1/3 lb ground bratwurst)
1 cup panko bread crumbs
2 eggs
½ cup fresh chopped green onion
½ cup fresh chopped parsley
½ cup fresh chopped cilantro
2 large cloves garlic diced or minced
¼ cup chopped Basil
Cooking direction
Preheat Oven to 375 degrees – combine all ingredients and mix well. Form into 1.5” balls and place in a greased baking pan. Bake covered for 20 minutes. Uncover and bake an additional 5 minutes.
Posted by: pureessence on: June 25, 2011
At work, I’ve implemented a queue monitor batch application. Due to business rule changes, it now needs to monitor two queues. Instead of creating another batch application, I really wanted to stick with the same application but just create two threads, each monitoring its own queue.
However, the twist I need is to have the main batch application thread die as soon as either queue monitoring thread dies.
I’ve been searching for a graceful way to handle such a concurrency need in Java. Thank you to Gary Myers, I’ve got a great start on it.
The basic idea is to pass a java blocking queue to both of the threads and if either thread fails, do blockingQueue.offer to indicate so. Then in the main thread, it will check for the blocking queue’s result. blockingQueue.take() blocks/waits for it to return and then continues the execution of the main thread.
Things I learned that made today AMAZING!
Below is a simple concurrency example that demonstrates the idea from Gary Myers.
Worker:
public class Worker implements Runnable {
private BlockingQueue<String> finishedQueue;
private String result;
private long sleepTime;
public Worker(BlockingQueue<String> finishedQueue, String result, long sleepTime) {
this.finishedQueue=finishedQueue;
this.result=result;
this.sleepTime=sleepTime;
}
public void run() {
try {
TimeUnit.SECONDS.sleep(sleepTime);
finishedQueue.offer(result); //you have to use offer to get this queue to work. It will throw an exception if there is something in the queue.
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
DaemonThreadFactory:
public class DaemonThreadFactory implements ThreadFactory {
private AtomicInteger counter;
public DaemonThreadFactory() {
this.counter=new AtomicInteger(0);
}
public Thread newThread(Runnable r) {
Thread thread=new Thread(r);
//if you wanted you can make this class generic by having the constructor take arguments that can be used to configure the following
thread.setDaemon(true); //need it to be daemon so the JVM will die even if there is a thread running
thread.setName("Daemon Thread: " + counter.incrementAndGet()); //you don't have to give it a name, but I always do.
return thread;
}
}
Test the threads in a simple example:
public class Main {
public static void main(String[] args) throws InterruptedException {
ExecutorService service=Executors.newFixedThreadPool(2, new DaemonThreadFactory());
SynchronousQueue<String> queue=new SynchronousQueue<String>(); //this queue can hold 1 element at a time, so basically the first thread to finish will be the one to successfully put the element in the queue
//create the runnables before hand so that extra time isn't spent instantiating the runnables at submission time.
Runnable runnable1=new Worker(queue, "Runnable 1", 4);
Runnable runnable2=new Worker(queue, "Runnable 2", 3);
service.execute(runnable1);
service.execute(runnable2);
System.out.println("before queue");
System.out.println(queue.take());
System.out.println("after queue");
service.shutdown();
}
}
I will not go into the details of the code I added for queue monitoring as they are a lot more involved.
The coolest thing I learned about ActiveMQ is how you can embed it using the following spring configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:amq="http://activemq.apache.org/schema/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/context/spring-jms-3.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">
<!-- Embedded ActiveMQ Broker -->
<amq:broker id="broker" useJmx="false" persistent="true">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://localhost:0" />
</amq:transportConnectors>
</amq:broker>
<!-- ActiveMQ Destination -->
<amq:queue id="destination" physicalName="com.threads.example.queue" />
<!-- JMS ConnectionFactory to use, configuring the embedded broker using XML -->
<amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost" />
<!-- JMS Producer Configuration -->
<bean id="jmsProducerConnectionFactory"
class="org.springframework.jms.connection.SingleConnectionFactory"
depends-on="broker"
p:targetConnectionFactory-ref="jmsFactory" />
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
p:connectionFactory-ref="jmsProducerConnectionFactory"
p:defaultDestination-ref="destination" />
</beans>
If running in Eclipse…
The following error may occur in Eclipse
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'amq:broker'.
To fix it, you must associate the ActiveMQ XSD URL with the schema.
Go to XML->XML Catalog in Preferences, and add a User Specified Entry.
Location: http://activemq.apache.org/schema/core/activemq-core-5.3.0.xsd
Key Type: Namespace Name
Key: http://activemq.apache.org/schema/core
Then add a second one:
Location: http://activemq.apache.org/schema/core/activemq-core-5.3.0.xsd
Key Type: Schema Location
Key: http://activemq.apache.org/schema/core/activemq-core.xsd
Hit OK.
For more info, visit this stackoverflow thread.
SocialVibe