Archive > December 2010

Upscreen: A Screenshot Utility using the Min.us API

» 31 December 2010 » In C/C++, Open-Source, Programming, Releases » 3 Comments

It’s been a long time since I posted something, again. Well actually I was hospitalized for 6 days, from December 18 to 24. I nearly spent Christmas the hospital. And after the hospital days, I worked on 2 projects, one is paid, and the other one is this.

The Story

Min.us is a great image hosting website. And when the time they sent me their API (I asked; their API wasn’t public yet that time) I came up with an idea, and yes basically the idea is to upload the screenshot taken in a computer to the min.us image hosting. When I finished the first (paid) project, I switched to this one. And I started with finding a way to execute code when the user pressed the PrintScreen key. I thought of using Windows Hooks but later on, I found out about RegisterHotKey and used it instead. But there’s a little problem, when I registered PrintScreen as a hotkey. Just like:

RegisterHotKey(NULL, 1, NULL, 0x2C);

The normal function of the key is disabled. This is bad, and I probably really need to use a keyboard hook instead. But no, instead I changed the hotkey and set it to Win + PrintScreen.

RegisterHotKey(NULL, 1, MOD_WIN | MOD_NOREPEAT, 0x2C);

So yes, it’s working great now. Though the PrintScreen key must be pressed first to load the image to the clipboard. So if you’re going to upload a screenshot, Press PrintScreen, then Win + PrintScreen. The good thing caused by this is, you can choose what to upload, and just place it in your clipboard. Say you need to upload an image from the internet, copy it, and then press Win + PrintScreen. Sweet.

Next, I need to get the data from the clipboard, and that was easy using GetClipboardData. Then, I need to save the bitmap file from the clipboard. I had some trouble finding a way to do this, so I used a function named CreateBMPFile and CreateBitmapInfoStruct. Success, now originally I was planning to use the BMP image and upload it right away. Then I just realized, the BMP file generated was uncompressed. So I think I need to use PNG instead (No not JPG, never). For this conversion I did some research. I ended up on using the ATL image header, and the CImage class. Well basically, converting an image is just 3 lines:

void Upscreen::ConvertToPNG(LPTSTR &sourceName, LPTSTR &destName) {
	CImage img;
	img.Load(sourceName);
	img.Save(destName);
}

Now that I have my PNG image, its time to upload it. By this time, Min.us have their API published and you can view it here. I only used two methods, CreateGallery and UploadItem. And I created a C++ class for the API:

class Minus {
public:
	std::string editorId, id, readerId;

	Minus();
	virtual ~Minus();
	void CreateGallery();
	void UploadItem(std::string&);

private:
	std::string key;
};

It’s incomplete, because the other two methods wasn’t included. So basically we need to get the editor_id, reader_id, and key from the first method then use these variables on the second method. To get these variables, an HTTP GET request must be accomplished. I do not want to use too much external libraries, so I just used Winsock2. I didn’t have too much trouble performing this, and the only issue I had was separating the HTTP headers from the response body. And later on, I found out its very easy:

response = response.substr(response.find("\r\n\r\n"));

The API’s response content type is JSON. I found it hard finding a good JSON parser in C++. And I ended using JSON Spirit . The downside is, this uses Boost Headers, so both must be downloaded.

I got the variables I need, now to the HTTP POST request. This is the bloodiest part of the program. I had trouble reading the the PNG file, and used ReadFile instead. Then, I didn’t know std::string is not suitable for storing binary data. So after switching many data types, I finally decided to use just a char * pointer to hold the data. And to pass the data, I put the POST headers and the data to a std::vector variable. All went well, but I’m a having 404 error in the POST request, and the data is incomplete. I just figured out the example URL in the Min.us API documentation is wrong. The trailing slash after UploadItem is causing the 404 error, and removing it fixed the problem. The other one was caused by the Content-Length parameter. I used WireShark and LiveHTTPHeaders to trace the packets and again, some bloody debugging. Later on, I found out the number I’ve been passing exceeded by one. After this part, all went so easy. The only thing I have to deal with is validation. Whenever the clipboard has data other than an image, it crashes. So I just placed an if condition to check if the PNG data exist. Because no PNG data will be saved if there’s no valid bitmap file present.

After uploading, I used the editor_id variable and attached it to the min.us URL. And made the program open it at the default browser using ShellExecute.

Header Files

The header files I used in this project are:

#include <WinSock2.h>
#include <windows.h>
#include <atlimage.h>
#include <string>
#include <json_spirit\json_spirit_reader_template.h>

Source Code

The source code is released under the GNU GPL v3. Get it here.

Year Ends

So this became my last post for 2010. Very timely, isn’t it? Anyway, Happy New Year!

Continue reading...

Tags: , , , , , ,

Tic Tac Toe in Python

» 15 December 2010 » In Open-Source, Programming, Python » 1 Comment

Tic Tac Toe is an exciting game, well for me it is. And for some reason it just came into my mind to code one. At first I thought this will be so easy, but then I was wrong. I just realized coding a game was never easy, and it took me days to finish this simple game (I’m not coding in full-time though). The code is pretty messy, so please forgive me. Here’s what it looks like:

PyTicTacToe

PyTicTacToe

Features

  • Human-Level Intelligence
  • Coin Toss for who goes first
  • Game Record
  • Clean Game Board

Computer-Level opponents in Tic Tac Toe is boring. You will never win. On this script, you can win, and that eliminates the boredom. The coin toss system is a random pick, and I must say it’s really funny, but efficient.

Source Code

Of course you can have the source code and play it. If you have a good record, you can share it with us. And if you want to make it better, fork it!

Get the source code!

Please leave a comment if you have questions or something to say.

Continue reading...

Tags: , , ,

Collaborative Desktop Sharing

» 14 December 2010 » In Internet, Life, Technology » No Comments

I’m currently using my father’s laptop, and using my desktop computer at the same time. Wait, does that make sense to you? Actually I installed a Virtual Network Computing (VNC) server on my desktop computer, I went to my parents’ room and borrowed my father’s laptop, downloaded a VNC viewer and accessed my computer. Pretty simple.

Why am I Doing This?

Personally I like to work on something comfortable, though the interaction between the VNC viewer and the server is not that smooth, compared to a remote desktop connection. My desktop computer is in the living room, and without VNC, I’m sitting there all day working on my stuff. Actually I’m thinking of just buying a long VGA cable and plug it in our HDTV, then all I need is wireless mouse and keyboard.

Well actually, I’m currently testing VNC because of our school group project on friday night. I’m planning to have one PC plugged in to the HDTV and all of us will be connecting to that PC via VNC and work out the Data Flow Diagram of our project together. And since we’re on a local area network, the speed is not much of a problem.

Downsides

In my current VNC connection, I’ve been having display issues. My desktop resolution is 1280×1024 and the laptop’s resolution is 1280×800. It’s pain scrolling up and down to get a full page. This is fixed by changing my desktop’s resolution to 1280×800, which I considered as a downside as well. Why? I don’t really want to change the server’s resolution, as it may affect other users connecting to it. As for our collaborative project, I’m hoping this will not be a big issue. Otherwise, we’ll be voting for the best resolution.

My desktop in 1280x800

My desktop in 1280x800

Overall, I love this method. And I prefer this over Teamviewer. If you have reactions or comments, feel free to type them below.

Continue reading...

Tags: , , ,

Validating IP Address in C#

» 13 December 2010 » In C#, Programming » 4 Comments

It’s been a while since I posted something, mainly because of real life issues. Now, back to the post.

In my coding experience, way back 2007, I use regular expressions to validate IP addresses in every language. Of course it works, but the downside is.. regular expressions. I’m not saying that’s bad, I just feel like it’s being replaced by more precise methods when it comes to validation. And as for C#, it’s not really that hard.

First, you must import System.Net for the IPAddress class. Next is this function.

private bool isvalid_ip(string ip)
{
	IPAddress ot;
	bool valid = false;
	if (string.IsNullOrEmpty(ip))
	{
		valid = false;
	}
	else
	{
		valid = IPAddress.TryParse(ip, out ot);
	}
	return valid;
}

Off: Personally I don’t like how the VS IDE formats the code. The braces looks messy (for me), but for now let’s stick to it.

I don’t even think I have to explain the code, since it’s very much self-explanatory. And I’m currently using this on a subnet mask calculator in C#, which I will be posting when I’m done.

Code in action

Code in action

That’s all for now, and hope you find it useful.

P.S. I do not take credits for the code, this is a neat trick that everybody can think of.

Continue reading...

Tags: , , , , ,

Finding the Longest Consecutive Characters on a String

» 02 December 2010 » In Programming, Python » 1 Comment

No regular expressions included. Yes, this fair method I’m going to show don’t include regular expressions. Actually there’s nothing wrong with regular expressions, but I think I’m over-using it. If you can browse my Perl section, almost all of my codes use regular expressions.

What’s this all about?

This is a simple algorithm coded in Python. Yes, I’m moving on from Perl. Not actually moving on, as in I’m never gonna use it again, but I think Python is better on this kind of tasks. Well anyway, I recommend you just use the python command line. In windows, there’s a GUI called IDLE and if you want the command line, just fire up cmd (or terminal in UNIX like OS) and run python.

Again, as the title said, this will identify/find the longest consecutive characters on a string. So for example, in the word:

hello

The characters ll are the longest consecutive characters. This is not hard to accomplish, especially with a scripting language as powerful as Python. Let’s take a look at the code, shall we?

Python Code

Let’s say for example, we are given the word iamastriiiiiingwaitwaaaaaaaaaaaaaatttt and we need to determine the longest consecutive characters (which is bunch of a‘s obviously).

string = 'iamastriiiiiingwaitwaaaaaaaaaaaaaatttt'
lastchar = ''
charcount = 0
tmpcount = 1
for i in string:
    if lastchar == i:
        tmpcount += 1
    else:
        tmpcount = 1
    if tmpcount > charcount:
        charcount = tmpcount
        char = i
    lastchar = i

result = ''
for x in range(charcount):
    result += char

print result

The result will be aaaaaaaaaaaaaa.

More Applications

In a simple string, the result can be easily identified. But for a string with too many characters, this script will come in handy.

Improvements

If you have better ways to do this in Python, feel free to leave a comment, or link to the better version.

Continue reading...

Tags: , , , , ,

Crossword Puzzle in HTML

» 02 December 2010 » In Internet, Life, Web Design, Web Development » 1 Comment

This is a pretty basic document I coded yesterday night. Basically this is a Web Design homework and the deadline is tomorrow morning. Yes I know it’s easy, but for the sake of the people curious about it, or those who are still starting with web design, I posted this.

HTML Version

In the past few days, while thinking about this, I decided to code this in HTML5 + CSS + JS. But then, because this is just a homework, and to be passed via e-mail, JS + HTML5 won’t be good.

First, because JS won’t automatically be executed locally, which destroys the first impression. I really wanted to do this in JS to add interactivity. Like, answering the crossword puzzle before revealing the answers, or have a button that will reveal the answers right away.

Second, some HTML5 tags will not work on older browsers, and only up-to-date and modern browsers can interpret its new tags. But if you would think, I only have one audience, my instructor. Well the problem is, if the code fails, my grade will fail too. I do not want to risk that, but anyway, XHTML 1.0 works just fine.

Style

I’m a minimalist, I like things simple, and for this one I sticked to one sans font. White background color, and gray text. Here’s the body style:

body {
	font-family: Arial, Helvetica, Verdana, sans;
	font-size: 1em;
	color: #666;
	background-color: #fff;
}

And yeah, for the table and data, I used the same color scheme.

#crosstable {
	margin: 0 auto 0 auto;
	border: 3px solid #666;
}

#crosstable td {
	width: 30px;
	height: 30px;
	border: 1px solid #666;
	border-spacing: 0;
	padding: 5px 5px 5x 5px;
}

The tricky part is the superscript in the cells. It took me some time to remember all about negative margins. Well anyway, it went well.

#crosstable td sup {
	padding: -5px;
	vertical-align: super;
	font-size: 0.5em;
	position: relative;
	top: -6px;
	left: -7px;
	font-weight: normal;
	margin-right: -0.5em;
}

Output

Of course I’ll show it to you. Besides, I already e-mailed my instructor with a zip archive containing the HTML file and the CSS file. See it here.

Validation

The document is valid XHTML 1.0 Strict. You can see for yourself: Click Here.

Continue reading...

Tags: , , , , ,