Saturday, February 13, 2010

Jacks or Better

I recently went to Las Vegas and became intrigued with the game Jacks or Better (JoB). This was partly due to the fact that my fiance and I were fairly successful playing the game: we won $13 overall! I was also interested in the game because there is the illusion that you have excellent odds of winning. A hand of Jacks or Better seems very easy to get.

For those who don't know JoB, the rules are pretty simple: any hand with a pair of Jacks or better is a winner. The game can cost any amount to play, but here I focus on the $1 game. Winning hands with a $1 bet depend on the type of Jacks or Better, but they typically follow this pattern:

Jacks or better: $1
2 pair: $2
3 of a kind: $3
Straight: $4
Flush: $6
Full house: $9
Four of a kind: $25
Straight flush: $50
Royal flush: $250

There are many strategies already well documented online. I found the strategy below (I lost the link to the site with this strategy, but here's a link to a similar one). Basically, you want to hold cards in the order of rules listed.

Hold any winning hand of four cards or better
Hold any 4 cards to a royal flush (10, J, Q, K, A)
Hold any other winning hand
Hold any 4 cards to Straight Flush
Hold any 3 cards to a royal flush
Hold any 4 cards to a flush
Hold 2 of a kind
Hold any cards to an open straight
Hold any 2 high cards of the same suit
Hold any 3 cards to a straight flush
Hold a J, Q, and K of different suits
Hold any two high cards of different suits
Hold J, Q or K with a Ten of the same suit
Hold any single high card

With this strategy in mind, I was curious to see what the winnings would be over time. I wrote a program in python to simulate a person playing the game of JoB using the strategy listed above. I started the agent with an initial amount of $50. The agent played until he was below $50 or 50 times (which amounts to 50 plays). Over the course of play, I tracked how much the agent won or loss, and repeated this process 10,000 times. After 10,000 rounds, I plotted the results using matplotlib. The results are below:



As you can see, most of the runs fall between a gain of $50 and a loss of $50. There are much steeper gains than losses. Here are some statistics I gathered during the run:

Total Winnings: -$1.46
Number of Runs Zero or Above: 3734
Highest amount earned during a run: $258
Number of Runs Below Zero: 5973
Highest amount lost during a run: $32

What's so interesting about this is that the total winnings is practically zero! After 10,000 times of playing, the agent loses less than $2. I was curious to see if this small loss would hold over time, so, to the dismay of my computer, I ran the code a couple more times. The next two times, the agent lost $1.85 and $1.36. With such small gains for the casino, I'm wondering how much a casino makes off this game. I suppose that a good number of players do not know the best strategy, so this might tip there earnings even higher.

Also interesting about these results is the 5:3 ratio of losing to not losing. This would suggest that the agent should lose more. However, the agent can win a lot more than it loses. Each play only costs a dollar, but a win could be up to $250. Even with these large earnings, it's not enough to overcome the losing trend. It might seem like you have a good opportunity to win with Jacks or Better. However, in the long run, you will still lose like any other game in Las Vegas. :)

I've posted my code here for anyone to review. Also, please feel free to offer any suggestions for enhancements to the strategy or the code!

Tuesday, February 9, 2010

Summer Enrichment Program Website Now Live!

I'm pleased to announce the launch of the Summer Enrichment Program (SEP) Website! As I mentioned in my previous post, the SEP is a program designed to get young women excited about computer science. It's being held this summer at the University of San Francisco, most likely during the week of June 28th - July 2nd.



Thanks to Anna Hurley for designing the logo! It's perfect!

Saturday, February 6, 2010

Minimizing the Gender Gap in Computer Science

I'm female. And I like computers and technology. I'm a minority. This has led me to try to understand the gender gap in technology. In this post, I take a look at some recent studies in the field and look at my own experience to develop some ideas that might help minimize this gap.

First, I should ask the question: why do we even need women in technology? The field seems to be progressing fine without them, right? A good reason to have women more involved in technology is because groups with both women and men tend to work better together. According to this article in Forbes, papers that have both men and women authors have 42% more citations than papers with a single gender. It seems that women have a very positive effect on any collaborative work!

Next comes the question: why are girls avoiding the tech industry? One study suggests that the environment itself prevents them from taking an interest. A group of scientists recently performed a study on students' interest in computer science. Students were asked to sit in 2 very different rooms and asked to fill out a survey about their interest in computer science. Given a room decorated with very geeky paraphernalia, the girls were much less likely to be interested in computers than if they were in a room with gender-neutral decor.

Also, as a child, I remember my own experiences. I liked playing computer games as a kid, and I liked programming my TI-85 as a high school student. But I never took a computer class in high school. In fact, I never even considered computers as a potential career path. How could this happen? One obvious reason was that computer classes were never required in elementary school, middle school, or high school. Another major factor was peer pressure. I'm afraid to say this, but only the geekiest, most unpopular kids were taking the computer courses at my high school. Taking such a course would be akin to "social suicide".

So, what can be done to get more girls in the industry? First, we should address the fact that the environment might have an affect on students' perception of computer science. We should make an effort to minimize any male-oriented objects in the environment and make the classrooms as gender neutral as possible. One study suggests that we should eliminate all boys from the room, since single-sex classrooms increase the likelihood that girls will take interest in computer science.

Another suggestion I have is based on my own experience. I think we should require students to learn how to use computers starting from elementary school all the way through high school. By exposing all students to computers, these classes would not be reserved for the geekiest, most unpopular students. Plus, it would allow all students to explore computers as a potential career. We already impose requirements for biology, math, and English, why not computers too? Computer engineering is a highly viable career option (maybe more than English). And, even if computer science isn't a student's main interest, knowing how to use computers and technology is integral to almost every professional career and would be useful for everyone.

Finally, I think we need to reach out to girls on more areas than just schools. There are many other media that can help. I'm so excited to see that Barbie is reaching out to young girls! Let's not stop here, though! TV programs for young children can do the same by including more girls using computers and studying computer science. Teen magazines can include articles about programming and majoring in computer engineering. Movies can include more female computer scientists.

With all these ideas in mind, we can start making a difference! I'm going to start this semester. I'm helping plan the Summer Enrichment Program for high school girls interested in computer science. The program is held by my grad school, USF. It runs for a week in the summer and exposes girls to a wide range of topics in computer science. Last year, we taught them about computer architecture, python programming, and java programming. The program is such a great event. Last year, the girls showed marked increase in their interest in computer science, approximately 1.5 points on a scale of 5. I look forward to this year's program and hope to inspire the girls just as much!

If you are interested in minimizing the gender gap too, I urge you to get involved!

Tuesday, February 2, 2010

Forms with File Fields - Java

Background

The standard HttpServletRequest class is not capable of handling file input fields in an HTML form. If you use this class, you will only receive the file name as the parameter value and not the entire file itself. In this tutorial, I will show you how to create the HTML form and process the form data using the com.oreilly.servlet package.

Step 1: Creating the Form

To create a form with a file input field, you need two add 2 additional features to any form: an enctype attribute to the form tag and a file input field. Set the enctype as "multipart/form-data". Here is what the code would look like:

 <form action="upload" id="upload" name="upload" enctype="multipart/form-data" method="post">
Name: <input type="text" name="name" id="name" />
Attachment: <input type="file" name="attachment" id="attachment" />
<input type="submit" value="submit" />
</form>
Step 2: Processing the form data

Like I mentioned earlier, the standard HttpServletRequest class is not capable of handling file input fields. Luckily, there are several easy-to-use libraries already created for capturing file data from multipart forms. I recommend using the com.oreilly.servlet package. The methods in this library use the same names as the HttpServletRequest methods, making is very easy to learn and use.

Download the jar file from the servlets.com website. Install the jar file to use with your project. (If you are using Eclipse, you can find instructions on how to install .jar files in your project here.)

Import the package at the top of your file.

 import com.oreilly.servlet.*;  

Create a new MultipartRequest object. The constructor can accept several parameters (see the API). I like to use the constructor accepting the following parameters: the HttpServletRequest from the doPost method, the path to the directory where file is to be saved, and the size limit of the files. If you do not specify a size limit of the files, a default of 1MB will be set.

 MultipartRequest mpRequest = new MultipartRequest(request, "/Users/bob/project/attachments", 3000000);  

Once the MultipartRequest object has been initialized, you can retrieve form data. Use the getParameter method to retrieve form input field data for all fields other than the file field. Use this method with the input field name as a parameter to retrieve the value of the field.

 String name = mpRequest.getParameter("name");  

For the file field, use the getFile method to retrieve the file uploaded in the file input field. Use the name of the file input field as a parameter. This method returns a file object, which is the file that was uploaded in the form. The file is saved in the directory specified when creating the MultipartRequest object.

 File file = mpRequest.getFile("attachment");  

That's about it! Simple, right? There are several other methods that you can use in the com.oreilly.servlet package, which are discussed in the API.

Saturday, January 23, 2010

HTML emails

HTML emails can be hard to create since most of the tricks used to develop web pages are completely unusable when creating HTML emails. CSS is not well supported, images can be a disaster, and layout is best done using tables (gasp). www.MailChimp.com describes the situation quite nicely: "Think back to the old days of the web browser wars. When Netscape and Microsoft were duking it out. There was no Flash plugin. It was only shockwave. Put away your DIVs and DHTML. Dust off those tables, shim.gifs, and font tags, because you’re gonna need 'em."

Webmail services

Webmail services strip the <html> <head> and <body> tags from an HTML email. Keep this in mind when coding emails.

Email width

Since most people view emails in a reading pane rather than full screen, set the email width at:

500-600 pixels

Images

Images are not displayed immediately in all email clients (to name a few: Outlook 2003, Outlook Express, AOL, Gmail, Thunderbird) . The user has to allow the email client to display images before they are shown. Since this is the case, do the following when using images in emails:

  • Enter a height and a width in the image tag to act as a placeholder
  • Use alternative text (alt="")
  • Don't use images for important content
  • Don't use background images. They are not displayed by all email clients.
Javascript, ActiveX, Flash, and embedded movie files

Don't even think about it.

Tables

Don't use div tags to position elements since some email clients strip div tags. Using tables for layout is probably the best way to create a well-formed email. www.MailChimp.com suggests using separate tables for the header, body, and footer of emails since some email clients do not handle colspan (Lotus Notes).

As noted above, Webmail services strip the <body> tag from an email. If you have a background color applied to the body tag, this will get stripped as well. Use a 100% wide table to hold your email and apply the background color to the table.

CSS

There is no standard support for CSS in today's email clients. No email clients allow for external style sheets, and, since Webmail services strip the portion of the email, it is best to place any style within the body of the email. In addition, CSS positioning is not supported by email clients.

To keep email style consistent throughout all email clients, review the following table :

Email ClientSupports…
Yahoo! MailCSS
HotmailCSS
Outlook and Outlook ExpressCSS
GmailInline CSS
Lotus NotesInline CSS
AOL 9CSS
ThunderbirdCSS
Mac MailCSS
EntourageCSS
Eudora for the MacNo CSS


Testing

Email clients to test:
  • Web: Hotmail, Yahoo! Mail, Yahoo! Mail Beta, Gmail
  • PC – Outlook, Outlook Express, AOL 9, Thunderbird, Lotus Notes
  • Mac – Mac Mail, Entourage, Eudora
Summary:
  • Inline CSS is most widely supported
  • Don't use CSS to position elements
  • Use tables for layout (maybe even use separate tables for header, body, footer)
  • If applying a background color, wrap the whole email in a 100% width table
  • Test in all email clients before sending your email!
Where I Got My Info

Monday, January 11, 2010

Source Code Formatter

Just wanted to send out a quick thanks to the developers of the source code formatter tool I used to format the code in my previous post! It's very helpful; I'm sure I'll be using it many times in the future! Check it out here: http://codeformatter.blogspot.com/2009/06/about-code-formatter.html.

Sunday, January 10, 2010

How to Create a Bookmarklet Like FriendFeed's

Background

I've been working on a gift web site called Gifty with my fiance, James. The site allows users to create groups, such as a family group. The user can then add their gift wishlist to the group. Other users in the group can see the person's wishlist and select which gifts to get that person.

I thought a great addition for the site would be a bookmarklet similar to FriendFeed's. The user would be able to add a gift from any site they're on. For example, if they're on the Amazon Kindle page, when they clicked on the bookmarklet, they would be able to add the Kindle to their wishlist.

Before I began, I had to figure out how FriendFeed did it. I encountered a couple surprises along the way, and thought I'd share with everyone the details of the code.

The Concept

The concept is pretty simple:
  1. Create a link that is purely a JavaScript method call, which acts as the bookmark
  2. Have this JavaScript method add a div element to any page using JavaScript
  3. Display a form in this div element
  4. Have the form submit a post to a URL on Gifty
  5. Remove the div element from the page.
Seems easy, right? Well, yes, the concept is easy, but there are a few tricky aspects that I didn't foresee. I'll go through each step, describing how I (and FriendFeed) accomplished the goal.

1. Create a link that is purely a JavaScript method call, which acts as the bookmark

This step was very simple. Drag the following link to your bookmark bar and test it out:

Bookmark

You should see a JavaScript alert pop up, while you remain on the same page. (If nothing happens, you might have JavaScript disabled.) What is the code behind this link? It's simply

 javascript:alert('hi')


Now, I wanted to do something more complex than a simple alert, of course, so I reviewed FriendFeed's bookmark JavaScript, which is as follows:

javascript:void((function(){
var%20e=document.createElement('script');
e.setAttribute('type','text/javascript');
e.setAttribute('src','http://friendfeed.com/share/bookmarklet/javascript');
document.body.appendChild(e)})())


As you can see, their function creates a new script element with their JavaScript file as the source and appends this to the page. How clever! All updates to the code can be changed in their file. As long as the link to the JavaScript file remains the same, new versions will be pushed automatically to all users.

I replaced FriendFeed's src file with my own, bookmarklet.js, and was on my way to the next step.

2. Have this javascript method add a div element to any page using javascript

Adding the div tag to the page is pretty simple, too. I applied a similar approach to FriendFeed, and used the following code:

 var container = document.createElement("div");
container.style.padding = "0";
container.style.margin = "0";
container.style.border = "1px solid #000000";
container.id = "giftybox";
container.style.position = "absolute";
container.style.top = "0";
container.style.right = "0";
container.style.zIndex = 100000;
container.style.width = "350px";
container.style.height = "210px";
container.style.backgroundColor = "white";
document.body.appendChild(container);


A new document element is created and all the style is applied to the element. Important style attributes to note are the absolute positioning and the z-index. The absolute positioning allows the element to be placed exactly where we ask it to be placed on the page, in spite of any other elements that might be in the way. The z-index means that this element should be placed at a position of 100,000 above any other elements. This takes an assumption that all other HTML elements on the page have a z-index smaller than this. If there's an element with a z-index of 100,000+, then that element will display in front of my div. However, I'm willing to take the bet that most HTML elements will not have such a large z-index, and have settled with 100K.

This JavaScript is placed in the JavaScript file mentioned above. To make sure my JavaScript didn't interfere with any other JavaScript on the page, I used namespaces. I created a new variable called giftyFunctions and set this equal to an anonymous function with the return value being a map of the function name to another anonymous function. Confused? Here's what it looks like in the code:

 var giftyFunctions = function() {
return {
addDiv : function() {
//code from above
}
}
}


Now, at the bottom of the file, I can call the function to add the div element as follows:

 giftyFunctions().addDiv();


This should, hopefully, eliminate the possibility that another function on the page would have the same name and would interfere with my function.

3. Display a form in the div element

The form was a bit trickier. The HTML had to be hosted on our own servers for two reasons:
  1. We needed to make sure the user is logged in before showing the form
  2. We needed to add user-specific data to the page (e.g., what groups they belong to)
To get around this, I looked to FriendFeed again. Again, they provided a very clever solution: they added an iframe element to the div element added earlier. The source was set to an HTML page hosted on their own servers. I applied a similar approach, creating the following HTML page:

 <body onload="addText();">
<p style="float:right;"><a href="javascript:closeBox('close');">Close</a></p>
<p><strong>Gifty</strong></p>
<form id="frameform">
<p><label for="giftDescription">Gift Name:</label> <input type="text" name="_giftDescription" id="_giftDescription" /></p>
<p><label for="giftLink">Link:</label> <input type="text" name="_giftLink" id="_giftLink" /></p>
<p><label for="groupId">Group:</label> <select name="_groupId" id ="_groupId" >
{% for group in userGroups %}
<option value={{ group.key.id }}>{{ group.groupName }}</option>
{% endfor %}
</select></p>
<input type="button" value="Submit" onclick="submitForm();" />
</form>
</body>


Note that this form does not contain an action, and the submit button is just a button with a JavaScript onclick event. This differs from FriendFeed's form, in which they use an actual submit input. I'm using a button since I want to control the submission of the form via the JavaScript function, submitForm. More about this later.

The iframe source is set to the above HTML by adding a couple lines of JavaScript to the JavaScript file:

 container.innerHTML = '<iframe style="width:100%;height:100%;border:0px;" id="giftyframe"></iframe>';
document.body.appendChild(container);
giftySetIframe();


The setIFrameLocation code is as follows:

 function setIFrameLocation() {
var iframe;
if (navigator.userAgent.indexOf("Safari") != -1) {
iframe = frames["giftyframe"];
} else {
iframe = document.getElementById("giftyframe").contentWindow;
}
if (!iframe) return;
var url = 'http://www.kathrynbrisbin.com/development/practice/frame.html'
url += '#gifty?giftname=' + document.title;
url += '&giftylocation=' + window.location.href;
try {
iframe.location.replace(url);
} catch (e) {
iframe.location = url; // safari
}
}


Note, there are two parameters added to the end of the iframe URL: giftname and giftylocation. These two parameters pass important information to the iframe so that the two input fields in the form, Gift Name and Link, can be given initial values. These are added via the addText function called on page load.

 function addText() { 
var windowLocation = window.location.href;
var params = windowLocation.split('#gifty?')[1];
var subparams = params.split('&gifty');
var title = unescape(subparams[0].split('=',2)[1]);
parentLocation = subparams[1].substring(subparams[1].indexOf('=')+1,subparams[1].length);
document.getElementById('_giftDescription').value = title;
document.getElementById('_giftLink').value = parentLocation;
}


Now that the form is added to the div, it's time to move on to the form submission.

4.
Have the form submit a post to a URL on Gifty

As I mentioned earlier, the form submission is performed via the submitForm method. This method uses a jQuery AJAX method to submit the form data via a post. The code is extremely simple, thanks to jQuery's help:

 function submitForm() {
$.post("/bookmarklet", $("#frameform").serialize());
...
}


The $.post function, a jQuery function, takes a URL and data as parameters. It makes an asynchronous call to the URL and posts the data to the URL. Since the call is asynchronous, it allows the user to remain on the current page. More information can be found on the jQuery website.

5. Remove the div element from the page.

Once the form is submitted, the div element needs to be removed from the page. To do so, control needs to return to the parent window, since the iframe itself can not remove the div element from the parent page. Unfortunately, JavaScript does easily allow for control to return to the parent. If the source of an iframe has a different domain from the parent, the parent property can not be used. So, what to do??

Again, I looked to FriendFeed to see their approach. Their solution was unique. In the initial JavaScript file, they set up an interval for a function that checks the page URL every 50 milliseconds. The function checks whether a message has been added to the end of the URL. The message begins with # + a FriendFeed specific string + =. Depending on the message, the function performs different actions, including removal of the div element.

I mimicked this design, and added the interval to my bookmarklet.js file:

 var interval = window.setInterval(function(){
giftyFrameMessage();
}, 50);


The giftyFrameMessage function finds the message at the end of the URL and sends this to another function to handle messages:

 function giftyFrameMessage(){
var gCurScroll = giftyScrollPos();
var hash = location.href.split('#');
if (hash.length > 1 && hash[hash.length - 1].match('gifty') != null) {
location.replace(hash[0] + "#");
giftySetScroll(gCurScroll);
giftyHandleMessage(hash[hash.length - 1]);
}
}


Finally, the giftyHandleMessage simply closes the div element:

 function giftyHandleMessage(msg){
giftyClose();
}
//close the box
function giftyClose(){
var giftybox = document.getElementById('giftybox');
giftybox.parentNode.removeChild(giftybox);
window.onscroll = null;
}


This function can be more complex and perform different actions based on the message. However, my code required nothing more complex at this point.

Now that I had the interval set up, I had to update the URL from the iframe. The iframe doesn't have access to the parent, but it does have access to "top". After submitting the form, I called the following method:

 function closeBox(message) {
var url = parentLocation + "#gifty=" + message;
try {
top.location.replace(url);
} catch (e) {
top.location = url;
}
}


This changes the URL, adding the message to the end. Once the giftyFrameMessage function is called, it finds the #gifty string in it, and then closes the div.

And that's the majority of the code for the FriendFeed bookmarklet! Of course there's much more to it than this, but this will help get you started!