Embrace the Unknown

As programmers its no secret that we like comfort. Well at least most of us. I mean every so often you’ll run into the uncanny ADD-man. You know the guy that is so in need of finding the next thing to jump to you’re pretty convinced he has a deep rooted issue involving being moved around from city to city because of a parent’s career… or paint chips.

For the most part though, we do like a certain comfort zone, and fuck if someone will convince us to get out of the comfort. And why would we? I mean it’s something we know. Something we understand. And isn’t life easier when there’s understanding?

I ran into this a couple jobs ago (I’m a job whore) when I asked for two monitors. Now this idea was something completely foreign and oddly scary to the people there. I mean, alt-tab is just fine, amirite? Wasn’t soon after getting the second one I was being looked at like some kind of child molester.

All I can say is: Don’t knock it until you try it. I meant two monitors, not child molestation. Well at some point the old light bulb went up on someone (Which makes me wonder what turned on before there were lights).

That person dared to start using two monitors. Next thing you know, there was a rash wave of double monitor usage. The world had changed forever. There were whispers of possibly having three monitors.

Side thought: I wonder if this is how the double razor to triple razor to n razor thing started. One guy was all like, “Hey guys, what if we had two razors on a shaver.” and then promptly speared for such thoughts that most likely were from satan. That was until some boss guy who was too high up to spear uttered the same words. Then everyone just went bat f–king crazy and started just throwing on arbitrary numbers out like some kind of reverse auction. And thus the razor wars began.

Anyways, back to the monitor thing. The moral of the story is that you can’t know what you can dare to dream if you have no concept of what’s out there.

Ok I lied sort of. Usually people use the line “The moral of the story” to end a thing like this, but I actually am being all sneaky and I tricked you into something bigger: Programming languages.

I have a confession. Well I have two, but one has to do with a having a song by Miley Cyrus… ok multiple songs… OK EVERY F–KING ALBUM… but that’s not important. The important part is that I’ve been a hardcore Microsoft guy for all 10 or so years of programming. I did not stray at all really. At least not much…

And why not? Microsoft has done a good job keeping the carrot in front of my face.

So why would I want to go anywhere else? I mean, I’m diverse. I use javascript. Besides, I have everything I need just given to me. Read that again. Actually I’ll type it again then just read it: I have everything I need just given to me. There are so many things that .net technologies do for me I really don’t have to do a whole lot. Or know a whole lot. Most lower level language ideas are just completely paved over with easy to use classes and controls. And that’s the problem.

I’ve been on a quest in the last year or two to really push myself to have a much better understanding of important programming concepts… that Microsoft has been so kind to hide from me as to not worry my pretty little face.

And maybe you are ok with that. Maybe you like to just take a pay check or just produce mass quantities of semi working code. Nothing supremely wrong with that. Just realize your career at some point will flat line.

But I say screw that. I need more and damnit I’m going to get out of my comfort level. I will brave the unknown (actually I already have with java and python) and in the long run I’ll be much better off. Why? Because not only do I diversify my languages, I also am privy to new and weird concepts that I would never see if it weren’t for venturing into new languages. Not only that, but I’ve found that some of the concepts and features just being added to C# have been around for a long time in other languages. So why wait for them to mature when you can use them now?

No really, I’m asking that. Give me a good answer…

jQuery: Find a Form Action Using Jquery

This is pretty useful for people trying to pass in a generated action to a javascript file.  Eh?

SKIP IF YOU DON’T CARE ABOUT A REASON FOR USING THIS:

Say you are using the jQuery post method to send things back to the server but all the code for that is in a seperate javascript file.  Well you can’t really do this:

jQuery.ajax({
      type:'POST',
      url: <%= someMethodForCreatingAUrl('controller', 'action') %>,
      dataType:'json',
      data:{
        email: user.userName,
        password: user.password
      },
      success: function(result){
        onSuccess(result);
      },
      error:function (xhr, ajaxOptions, thrownError){
        alert(xhr.status);
      }
    });

if that is in the javascript file.

What you can do is this on the html file:

  <form id="formCreateUser" name="formCreateUser" method="post" action="${someMethodForCreatingAUrl('controller', 'action')}">

And in the javascript file:

ANSWER:

  var formAction = jQuery(ELEMENT_LOGIN_FORM).attr('action');

And there you go. You have the action.

Python / Pylons… Setting the CSS Class on a webhelpers.html.tags Select List

Real quick one, once again just for my future searching concerns, just wanted to point out how to set the css class on a select list when using the webhelpers.html.tags.select helper. Won’t get into how I hate html helper classes, but in this case it’s for something so simple AND it makes it easier to hook into a precreated list. Anyways, it’s me being lazy and breaking my rules.

With that being said, took me a bit to find out how to set the css class on the created select list:

    ${h.select('selectGender', '', h.lookups.list(h.lookups.GENDER_LOOKUP), 'selectGender', class_='input' ) }

Its that “class_=” part. Really simple once you see it, but annoying if you don’t know it.

Just a quick break down on what the select method takes in:

h.select(name, selected option, list, id, extra stuff)

Off Topic: My Love For Star Trek The Motion Picture

There are few things that I accept about myself: I’m ruggishly handsome, I have a superior intellect, and I’m the only person on the planet that thinks Star Trek the Motion Picture is the best Star Trek movie out there. And no I’m not talking about the 2009 movie, though I really enjoy that one, but the 1979 one. People usually just stare at me when I confess this after way too many drinks, but its true. Its my go to movie. If I don’t feel like watching anything else, I can always watch it. Actually I just had to adjust the TV as I am watching it right now.

Most people think it’s boring or something, but in my mind it’s by far the most true to the original series and by far the most intriguing. If nothing else, it keeps the original series’s flair for the unknown. You really aren’t given a lot of information off the bat except that what ever is out there just made the feared Klingons look like little bitches. I’m sorry, but any one who was brought up on the original knows there’s only one force in the universe that can go toe to toe with them and still survive… James T f—ing Kirk. This thing makes him look like a complete tool. Right off the bat you’re just thinking “Oh s—, what can stop this?” This thing makes the doomsday machine look like a ice cream vendor.

And I think that’s part of where my love comes in. The other movies, except maybe that disaster IV, you knew it was just the normal foe. Even Khan was assumed he would in some way get his a– handed to him James T Kirk style. But this thing (Why is every object we don’t understand called a thing?) is so far beyond powerful that you just can’t possibly accept that Kirk would kill or bang it. There is a feeling of complete and utter danger that none of the other movies really have. That feeling of powerlessness.

The next thing is the total seventies feeling too it. Yeah I know there are a lot of bad movies from that era, but the ones that we remember have something in common, a magically weaving of music and sight. There is something just… eh visceral about this movie that you can’t replicate in a movie. Something about the visual feel and the way the music just seems to draw out everything the eyes can’t see is something I think is the only part of the seventies worth noting. It was a time of experimenting with just about everything and as the saying goes sometimes the blind squirrel finds a nut. That is how I feel about this movie. The deliberate nature of it’s filming being paced by its music brings a certain overload of the senses at times. Some people call it slow or dull, but I call it purposeful and enveloping. It draws you in and tries to tell you a story that words could never do.

Beyond all of that, the twist at the end is so out there but makes so much sense that you can’t deny its possibility. I’m sorry but every times I hear the “V…g..e..r….voy…g…er…. Voyager” it just makes me think, “Now that’s an idea.” Well actually I end up repeating the line in only the way Shatner could deliver, but after that I think about the idea thing.

I understand that most people won’t watch this movie and get what I’m talking about. I get that I might be insane. I’m ok with that. Because as I sit here watching this movie for what is probably well beyond the 100th time, I know that I will enjoy every stupid second of it. You can go watch the stupid one with the whales if you want. This motion picture is mine.

Python: Getting the Current Year, Day, Month, Hour, Minute, Second… Even Microsecond? EH?

This is more to be filed under “I don’t want to have to search the wabz for this again so I’m using my blog to post something so I don’t have to”, but if someone else in this world gets something from this, then well someone else in the world gets something from this. As I’m the only person I care about, helping myself is about as far as my concern goes.

This is really simple:

import datetime from datetime

    def someMethod():

       currentSecond= datetime.now().second
       currentMinute = datetime.now().minute
       currentHour = datetime.now().hour

       currentDay = datetime.now().day
       currentMonth = datetime.now().month
       currentYear = datetime.now().year

And actually there is one more if you print out datetime.now():

2010-09-24 10:06:06.599000

That .599000 is called microsecond:

       datetime.now().microsecond

Anyhow, thanks for playing.

How to Debug Pylons with PyCharm

So I really hate Eclipse. Something fierce. And I have to admit it’s not really fair since I come from Visual Studios/C# which together can cost upwards of 2k to buy so it better be a great product. And Eclipse is free so you know, yah. But since IronPython may be dead, and it was annoying to set up anyway, I’ve been stuck with Eclipse… Until today. Turns out those Resharper guys (Resharper being the best thing ever since the last best thing ever.) made a Python IDE: PyCharm. At first I was all like “Whooa” then I was all like “Whoooooa” then I read there was no support for Pylons… then I was like “Wha?”.

Although it looks like PyCharm doesn’t directly support debugging with Pylons, I took my limited knowledge from Eclipse and just hopefully bashed it into PyCharm…. and I made a screen shot:


It’s really simple.

Script is the Paster script that is normally used to start the serve.

Script Parameters is just the normal serve command used WITHOUT the –reload.

Make sure you grab the right python interpreter that has Pylons “installed” and away you go. Just have that one set as the current debug config and run it.

Once it’s up and running, just go to the page and set a breakpoint. Yay.

Python / Pylons: Unit Testing a Controller And Unit Testing a Json Response

Nice thing about Python and Pylons is the complete lack of finds on the google. Basically anything you search on gets you the same 5 links… helpful or not.

This is a quick one though, and by quick I mean quick for you after it took me a f— load of time to get the f—ing thing right. Forgive me for swearing… even though I do it all the time… but in this case I really wanted emphasize how f—ing annoying it was to get this right.

So here’s the thing, you want to unit test a controller. Great. Now the nice thing is it’s actually pretty easy with what’s built into the TestController which is found in the __init__.py file in yourProject/tests. Imported simply by :

from yourProject.tests import *

Provided you didn’t move the tests folder.

Take the start of this method:

   def test_loginUser_bad_input(self):
          #Here is the call to the controller and the return response
          response = self.app.post(url(controller='security', action='loginUser', email='null', password='null' ))

Now here’s the interesting thing, response is actually a response object. Can you belee dat? At first I thought it was just whatever the controller method would return if called by a method and not during some web request. Turns out that self.app.post actually acts like a real request. Go f—ing figure. I like. So simple yet so capable. It’s like a long lost brother of mine. You know, the long lost brother that is simple yet capable… and is a method. I’m not sure any of that makes sense.

Now the second part of this debacle is how to work with a json response. For this example I am using jsonpickle but in reality the only thing to take from this is WHERE the stupid json actually is:

    jsonResponse = jsonpickle.decode(str(response.body))

Yeah so at first I thought it would be just jsonpickle.decode(response) but kept getting all sort of unhappiness. Now like I noted up top, the response is an actually object return that holds all sorts of information. (including header information.. yay?) So the next guess was what you see right above. Go figure what I was looking for was in the .body attribute.

See, told you it was simple. Painful for me, but in the end you win. And I bet you like that. Sadist f—.

Pylons: Dynamic Templates with Mako Using Controllers and jQuery

So a friend of mine (Yes I do have friends and occasionally the ARE real) asked me if there was a way to have a partial control/template have dynamic content using a controller. At first I was like ‘f— no’ but that passed quickly as I realized I was actually answering myself on whether Species should have yet another sequel. As for his question, I gave it some thought and the easiest way I could think it jquery and using it’s ajax method to call a controller and use the response (json for this example) to create the content. Could it be done? You bet your Rolex knock off that you bought in New York from some guy named Loey that looked legit for a guy selling things out of a dumpster.

Turns out the solution is fairly simple. Use jquery to call a controller’s action on the template’s load. Even can pass in whatever you need from the parent container.

Here is the parent page:

<!--This is the partial template page -->
<%namespace name="getInfo" file="getInfo.html" />

<html>
  <head>
   <script type="text/javascript" src="${h.url('/scripts/jquery-1.4.2.min.js')}"></script>
  </head>
  <body>
    This is just plain text that is pre method call.  Textbox will be fill post method call.
    <!--This is the method set up on the partial template -->
    ${getInfo.getInfo(1) }
  </body>
</html>

Here is the partial template file:

<%def name="getInfo(id)">
  <script type="text/javascript">
    //This is the method to be called to get whatever it is you need from the controller action
    function getInfo(id){
      jQuery.ajax({
        type:'POST',
        url: '${h.url(controller='getInfo', action='index')}',
        dataType:'json',
        data:{ id:id },
        success: function(result){
          onSuccess(result);
        },
        error:function (xhr, ajaxOptions, thrownError){
          alert(xhr.status);
        }
      });
    }

    function onSuccess(result){
      jQuery('#testLabel').val(result.returnValue);
    }
    <!-- This will force the getInfo method to be called when this page loads. -->
    getInfo(${id});
  </script>

  <!-- This is the content to be updated -->
  <input type="text" id="testLabel" name="testLabel" />
</%def>

And really that’s it. Very simple. Have the parent page call the partial template method and have the partial template method use whatever value being passed in to send it on to the right controller/action. Once the response is there, update the content.  In this case, result.returnValue that is just a simple string.  Or maybe a puppy.  Could be both.

A more complicated example could use javascript to construct html based on the return but not real important here.  That’s for smart people, read not me, to figure out.

As a bonus, I will actually post the code. NOVEL IDEA!111

What? Why did I choose purple for the color of Mako markup?  Don’t… just don’t.  You have no right to judge.

Python… DOUBLE TEE EFF Exclamation mark one one

Fair Warning: This is all conjecture and idiocy… possible more the latter than the former. With that in mind, this is more of a flow of thought than any kind of organized scientific paper… thing.

NOTE: When I use the word “attribute” I really mean things like properties, fields, methods, ect on a class. Since I am guessing most people reading this come from a C# or Java background, the word “attribute” might be confused with something else. So remember attribute = property/method/field/anything that defines an object.

So as I delve farther and farther into the insanity that is Python, I can feel my mind screaming. Not like “Oh f— I’m being eaten alive” kind of screaming, more like “Don’t open that door! You know the guy with the axe is behind it!” Of course, like any good horror movie character I’m too dumb to know better. So delve I do.

Now I’m what you could consider a classically trained programmer and by that I mean I never programmed before college so I didn’t do much exploration. You know, a Microsoft programmer. With that, I’ve had the ideas of interfaces and class hierarchies complete hammered into my head, so it shouldn’t be any surprise that I’ve tried my best to make Python into c#. After all, that’s what I should be doing. I don’t know any better. DONT JUDGE ME!
It wasn’t until the other day when it just hit me. And I don’t mean slight hit, I mean like I just told Miguel Cabrera I’ve seen better players in Little League. It occurred to me that it’s possible, just possible I might have to change my way of thinking because of one major design difference: dynamic attributes… actually f— it, dynamic everything, but let’s just stick with something simple. In Python something like this:

  someObject = dynamicObject()
  someObject.propertyImJustAddingForTheHellOfIt = 1

Where dynamicObject is nothing but a cheesy class that inherits Object but has nothing on it. (Turns out that if I did someObject = Object() I couldn’t do this since Object by default doesn’t contain the ability to add things dynamically… and this was by design.) So what does this mean? Well it means that anything at anytime could have any attribute. You might be asking why this is such a big deal. Annnnnnd that’s why I’m typing this out so stop asking questions until the end, k?

If any object can have anything on it at anytime, it could be said that types and classes kind of go out the window. Why? Because when it all gets washed away, what really does the work in a program? Methods. Now with C# there is a much stronger enforcement of typing so a method KNOWS that whatever coming in has to be a certain type. This is where object inheritance and interface implementation come in. Because there is such a prerequisite for typing in C#, you have to develop around the object itself and have the methods conform to them. In Python, I question whether this approach is really warranted since with dynamic attributes what really matters is what the method needs. It could be argued in the world of dynamic, the methods actually dictate everything. Since types are basically thrown out the window, what’s the point? Why not just shift all development around methods and their results? It’s kind of an inverse way of looking at things when used to the C# way of doing them.

Method Oriented Programming?

This is something I’m kicking around a bit, but why not base the architecture around methods rather than classes? It would give a much truer sense to the word “Factory”. Instead of worrying about having a class hierarchy, have methods responsible for creating objects on the fly, piecing them together with other methods and such. I would think this could give a program a massive ability to adapt quickly to any given situation if you can add and subtract from objects on the fly since you are not longer concerned with types, just attributes. Does the thing coming in have X attribute? Yes? Great do something. No? Fine don’t do something. (Python has a built in way to check if an object has a certain property) Does it need it to continue? Well call a method to add it to the object. Has the use for it expired? Well just remove it. Taken to an extreme, I could see this being used to construct more self sustainable programs, ones that can makes choices on their own to produce novel outcomes. (Sadly, used like viruses and hacking security systems come to mind, but there has to be more noble uses for this) Sounds like a lot of freedom.

Now I’m not saying you can completely get away from class structure… at least I haven’t gone far enough into this concept to see if it’s possible. However, it should be obvious that it at least allows for a completely different way of thinking that may help solve problems that were seemingly impossible to solve using more rigid languages like C#. Of course, it also lends itself to shooting yourself in the foot. Most likely, this approach would need more overall care since you don’t have things like type safety to cover your a–.
Anyways, this is just preliminary rambling of a child (programmatically speaking… and maturity wise) who is just kicking around ideas that weren’t really there before.

An odd side note, python gives a new… or maybe the correct… meaning to the word “constructor” since because of that highly dynamic nature it’s not unlikely to see something like this:

  __int__(self):
    self.someNewField = "This property now exists"
    self.someNewMethod = someFile.someMethod

Which is actually more like a factory then how say c# uses constructors, which more the most part is like a initialization. The other interesting thing to note is how python treats files and methods. If you declare a method on a file, you can actually import that method as if it were an object itself. This makes the above code even easier to accomplish since you can have a file of just methods that you can “import” and add to an object.

What happened to Lan Parties?

As I was making my third attempt to reassemble a horribly aged futon (that had been passed around to so many people there’s no doubt its seen more action than Tom Selleck in his Magnum PI days), wondering if it was some kind of early attempt of Ikea’s to blend furniture with some kind of social experiment to see how much a person can take before starting a three figure body count, and swearing enough to make Bog Saget blush, I decided that the best course of action to keep me from going hulk on it was to think of better place.

Lan Parties - Panel One

That didn’t feed into my almost Gibson-esque epic instability.

Lan Parties - Panel Two

I then started thinking of my friend (no not that way) and how he (still not that way) was having a lan party this weekend and how he had invited me to it. Now I probably would have gone if it weren’t for the fact he lives 10 hours away, I’ve never actually met him in person, and I’m pretty sure he’s actually just inviting me over because he needs a new host body as his is falling apart.

You remember those days. 10 high school (maybe college) dudes all smashed into a basement with 10 computers going full blast, cases and cases of mountain dew, all completely focused on one and one thing only: gaming. Those 48 hour gaming benders fueled by so much caffeine that by the morning of the second days everyone had that weird anxious/excited/electrified feeling that somehow mixes the feeling you get right before you start opening birthday presents and the feeling you get right before vomiting:

Lan Parties - Panel Three

You know, the same feeling we would feel again 10 years later right before having sex for the first time:

Lan Parties - Panel Four

Well this led to me asking my self, “Self, why don’t I go to lan parties anymore?” For the most part, I think part of getting older is realizing that the copious amounts of caffeine taken in at 16 would no doubt kill me or more than likely be replaced with alcohol and no doubt would end with some kind of machine being forced down my throat in a last ditch effort to keep me alive so that I could enjoy the week long hangover to follow.

I think also in my oldness, I’ve lost the ability to play games for any extended period of time. Seems as if that part of my brain has been removed or possibly atrophied due to suffering from depression brought on by lack of use. Either way, I now have a greater capacity to code for extended periods of time instead… Wait. I’m feeling something… I think it’s an idea which would explain why its a feeling I don’t recognize.

What if the gaming lan party were to evolve? What if all that caffeine drinking, sardine can sized room of guys, (I’d say gals too since I realize there are women coders but really, what woman wants to take the chance of being locked in a small room chock full of essentially coked up geeks?), table to table, computer to computer, energy filled mayhem could be used to code? Think about it:

What if you were to take some idea like say a program that compares the hotness factor of supermodels (YEAH SUPERMODELS MAN, CAUSE THAT’S WHAT MANLY MEN DO, YEAH!) or the best picks for fantasy football (more in line with reality) and just go at it for 48 hours straight? I think this could actually work. After all, you have the combination of a ton of minds and no external interruptions to really just hammer something out. I realize there could be some issues inherent with super-fast coding:

Lan Parties - Panel Five

But couldn’t this work? You get lots of up-side on this one. Comradery, energy, excitement, a semi-working program, and quite possibly good, old-fashioned physical nerd fights (hey, that’s what Youtube was invented for) caused by late nights, caffeine psychosis, and uncomfortably close proximity to other people for more than 10 minutes. How could this be a bad idea? So I say, have at it. Prove me wrong about this one. And make sure you take video proof of how wrong I was. You know, some kind of video diary of you attempting to flee the country after they find the 9 bodies you somehow managed rage into the trunk of your car. (Again, that’s what Youtube was invented for).

Lan Parties - Panel Six