Categories
Blog News

Woes in Python 2.x : UnicodeEncodeError : ‘ascii’ codec can’t encode

Phew ! This is a reminder to myself…

I’ve wrapped my head once already around unicode, but it was so long ago that I had to do it all over again when the error suddenly came up again.

The error I had was the dreaded “UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa1′ in position 0: ordinal not in range(128)” error which does not really explain what you are doing wrong but leaves you scratching your head wondering where in heaven’s name you should start looking.

I read the following articles :

But what really solved the problem for me was this StackOverflow answer by Alex Martelli (Bless You Joel Spolsky for this idea and Bless all the people answering there!)

I was in a similar position code-wise : I had a unicode object that I wanted to convert tot utf-8, but I was using the “decode” function.

I actually should have been using the “encode to <codec>” function !

Duh ! Once you have a unicode object, you need to encode it into utf-8 or whatever encoding you need. I was using decode !!!

Oh. Well, perhaps my unicode fu is still not as good as it should be…

Categories
Blog News

Proof of concept for a simple webserver running python code

Here is a small code example using CherryPy to run a very simple webserver that

  • generates a simple math question
  • compares the answer to the solution.

It’s meant as a proof of concept, so there is no security built in. It’s running on localhost on port 8888 (modifiable in the main part of the code).
It allows you to play around and test out your ideas.

Do not use this code on an outside network !

It’s simply an example showing how easy it is to set up a web server and how you can create pages for it using python and CherryPy. It’s been cobbled together in an evening from previous programming so there’s some cruft left in. I’ve also extensively commented the code.

Requirements:

  • python 2.7 ( 2.5 will work as well is my guess )
  • cherrypy 3.2.2 ( use easy_install or pip to download and install the latest version)
  • site.py ( the file containing the python code )

You start the server in a command prompt using : python site.py which will start the server. Leave the command prompt open.

You can then visit the webserver by opening a browser and going to http://localhost:8888 to see the index page and play around with it.

#
# MathPoc : Proof of concept of a simple math problem, bringing it to the browser
#
# Alex Boschmans
#
# Version 0.2, February 2011
#
# 0.2 Added some error checks and expanded math to not just adding but also 
# subtraction and multiplication and divisions. Extensively commented code.

header = """<HTML>
            <HEAD>
                <title>MATH Proof of Concept</title>
            </HEAD>
            <BODY>
        """
footer = "</BODY></HTML>"

indexhtml = """
        <H1>Math Proof of Concept</H1>
        <p>Please answer the following question</p>
                <p>How much is %d %s %d ? </p>
                
                <form action="/response" method="post">
                Answer: <input type="text" name="answer" />
                <input type="hidden" name="number1" value="%d">
                <input type="hidden" name="number2" value="%d">
                <input type="hidden" name="operation" value="%s">
                <input type="submit" value="Submit" />
                </form>
                
        """

def generatequestion():
    # This generates the question that we will pose using the random function
    # Generate a random question using 2 random numbers between 1 and 10
    number1 = random.randint(1,10) 
    number2 = random.randint(1,10)
    # Now we choose an operatioin
    ops = ["+", "-", "x", "/"]
    operation = random.choice(ops)
    # Let's check the division
    if operation == "/":
        # Prevent divisions with remainders using the modulo operator
        # Using module on the two numbers evaluates to 0 when no remainder is present
        # While the modulo remainder is not equal to 0, generate two new numbers
        while number1 % number2 <> 0:
                number1 = random.randint(1,10) 
                number2 = random.randint(1,10)
    # Assemble the html, inputting the numbers in the foreseen places in the html
    # In a more extensive project, you would keep this html in a template file and 
    # call it with a dictionary of items that need to be filled in the template
    question = indexhtml % (number1, operation, number2, number1, number2, operation)
    # Add common html like header and footer - these are defined just once and reused
    # for each page
    html = header + question + footer
    # Return the completed html to the calling function (in this case index)
    return html

# This is the class that the cherrypy server uses and where you create the views that the 
# webuser sees. After each definition there is a <function>.exposed=True that indicates if the 
# webuser can see this page or not. 
class MathPoc:
    def index(self):
        # This is the main index page that is shown to the user when he first visits the site.
        # We create the page by calling the function generatequestion (which is outside the class
        # MathPoc but accessible and we show it to the user by 'return'ing the page 
        page = generatequestion()
        return page
        # The webuser will now see the page and will have a chance to enter an answer.
        # In the html form I've specified that the submitted result will go to the url "response"
        # I've added all the values I want to receive either as hidden values (eg the 
        # original numbers, the operation) or as part of the form (eg the answer)
    index.exposed = True
    
    def response(self, answer, number1, number2, operation):
        # First check if we received an answer or if the user submitted without an answer
        if answer:
            # Calculate our own answer ourselves and generate a response to the user
            # We receive strings, so convert them to integers using int()
            number1 = int(number1)
            number2 = int(number2)
            answer = int(answer)
            # Answer is dependent on operation
            if operation == "+":
                solution = number1 + number2
            elif operation == "-":
                solution = number1 - number2
            elif operation == "x":
                solution = number1 * number2
            else:
                solution = number1 / number2
            # See if the answer is correct and display according the result
            # Using templates, you could put all this in one template and 
            # call the template with options so it knows what to show
            if solution <> answer:
                html = """
                <H1>Sorry.</H1>
                <p>The question was : %s %s %s = ?</p>
                <p>Your answer %s is wrong. The correct answer is %d.</p>
                <p><a href = "/">Try Again.</a></p>
                """ % (number1, operation, number2, answer, solution)
            else:
                html = """
                <H1>Correct !</H1>
                <p>The question was : %s %s %s = %s</p>
                <p>Your answer is correct !</p>
                <p><a href = "/">Try Again.</a></p>
                """ % (number1, operation, number2, answer)
        else:
            # We did not receive an answer
            html = """
            <h1>Sorry ?</h1>
            <p>You need to fill in an answer !</p>
            <p><a href = "/">Try Again.</a></p>
            """
        # Return the page to the user, adding the common html
        return header + html + footer
    response.exposed = True

if __name__ == '__main__':
    import random
    import cherrypy
    import os, sys
    # Set the current directory - this is probably not needed for this example, cruft.
    try:
        current_dir = os.path.dirname(os.path.abspath(__file__))
    except:
        # probably running inside py2exe which doesn't set __file__
        current_dir = os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))

    # Set up site-wide config first so we get a log if errors occur.
    # Adding the setting 'environment': 'production' to the below turns off auto-reload.
    # Otherwise CherryPy monitors the code and any change to code reloads the server - handy for development !
    cherrypy.config.update({'server.socket_port':8888,
                            'server.socket_host':'127.0.0.1',
                            'log.error_file': 'site.log',
                            'log.screen': True})
    # CherryPy will complain of an empty config but will continue
    conf = {}
    cherrypy.tree.mount(MathPoc())
    #cherrypy.config.update({'server.socket_port':8888})
    cherrypy.quickstart(MathPoc(),'/', config=conf)
Categories
Blog News

Small review of Zurb Foundation

It sounds more like a rock band, but it’s actually a tool for rapid prototyping in html and css, and a fairly easy way for a css-vapid guy like me to give my websites a basic ‘good look’ in about 5 minutes and still have some control over the design. Plus it’s very flexible, they aim to make it so that you can show your website on multiple different devices.

Foundation is a complete framework, and includes both the javascript, the css files and some instructions to get you going. And if you drop a mail, they are quick to respond, even if it is a stupid question like I asked.

I’ve been playing around with their open-source foundation download code, and I must admit their examples ‘click’ for me. For example to add a button, you specify a css class like this class=”nice blue radius button” which is almost human english ! This way I can focus on my python skills and still produce some nice-looking pages !

Categories
Blog News

Finland’s Porrka Playboys doing Bohemian Rapsody.

If I played in a band, I would have liked to play in a band like this this one:

They totally make it work !

Categories
Blog News

Getting XCode from the AppStore ? Don’t forget to install.

Yes, really, I totally missed this one. I was sure that I had XCode, that I had installed it from the AppStore.

Several frustrating moments finally led (via StackOverflow!) to the realisation that XCode is only downloaded, and still needs to be installed afterwards. So just go to your application folder and find the “install xcode” app and double-click it.

Duh (slaps forehead) !

Oh well, onwards with the show of getting mysql-python to install on 10.7.

Categories
Blog News

Facebook-like buttons for Magento

I know that most technical people can do this themselves, but in case you need something a bit more worked out and documented, here is a link to a great facebook-like button (+free analytics if you buy it at the same time) for facebook. 39 dollars if you use the coupon code he mentions in the video.

There’s another plugin out there that costs only 5 dollars, and it includes Google+ and Twitter, but I felt uneasy on buying it because it seemed unfinished + seems to be based on copying shareit code from the shareit website (where you have to agree to basically letting them piggyback your traffic for their purposes). No thank you.

Installation of the basic functionality is a piece of cake or as they state in my part of the country : 2 fingers up the nose easy. Upload the code you purchased and downloaded from the retailevolved website and upload it to your magento directory. Plus the documentation is included and is very clear on what you can do and any variations.

Done !

Plus you can go a step further, and get more functionality like the “send” button if you setup a facebook dev account and get an application id for your website.

Recommended !

Categories
Blog News

Table 7

Categories
Blog News

Dropbox and iCloud : adverseries ?

I just read the announcement on macrumors.com on the upcoming iCloud beta that Apple will soon be launching.

Here is the pricing that Apple will set :

  • 5 GB free, 10 additionnal GB is 20 dollars / euros a year.
  • Bought books, music, apps etc are not counted into this.

Compare that to Dropbox, where I currently have 2,5 GB free storage (thanks to jumping through all the hoops that they wanted me to, default you have less).

The next step up is 50GB for 9.99 $ a month, which works out to about 120 dollars, which is too much for me, both in size and price.

On iCloud I would pay for the same amount (actually more than 50GB, the original 5 GB is also there) 100 dollars yearly, so substantially less.

Maybe Apple will only offer iCloud to Apple Mac users, in which case Dropbox still has a large amount of windows users that it can keep, but I doubt it.

My guess is that Dropbox will either lower the prices or give more GB for the same buck, and perhaps even dramatically so in order to stay competitive.

Update : seems that my calculations are a bit off. A deeper look with more nuance about dropbox and the different pricing can be found here via macstories.net.

Categories
Blog News

Discovering Magento

I’ve been looking at setting up a jewelry shop and Magento seems to fit the bill as an opensource solution for me.

I have to admit, that the learning curve is a bit steep, and installing it locally for a test drive is a hellish ordeal, where you need to configure your localhost file so that your computer has a dns name (at least for version 1.5.1 this was the case) with barely some explanation why this or that is not working.
Blogs aplenty with explications, each with slightly different errors and/or solutions, so while there is information, it’s not always clear if it is relevant.

Anyway, I got it up and running, hosted, and it works fine ! Oodles and oodles of config options, but there’s a logic in there (sometimes twisted logic, but still !)

Here are some sites / blog posts / magento modules I find useful:

Categories
Blog News

Adrien De Schuyteneer, June 14th, 2011. RIP.

My Father-In-Law passed away on June 14 this year. A man of few words, he loved his grandchildren dearly.

He taught me a lot on how to do things correctly as a handyman. I couldn’t even drill a hole in the wall when I met him.

The secret is preparation :

  • use the tools best suited for the job
  • prepare, measure and remeasure
  • be precise

He will be sorely missed by all his friends.