Robert Basic's blog

Posts tagged 'hack'

Saturday night hack - coords

by Robert Basic on March 24, 2013.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

When I was just starting out learning programming, everything was so simple. I did not care about design patterns and best practices and unit tests and how will users use that piece of code. Hell, I did not even know those things exist. I was having fun, I was learning, I was free to do whatever I wanted to do, I was playing, I was like a child. Not that there is something wrong caring about those things now, but then I was able to put out a piece of code that was fixing a core of one problem I had and that was it. Once I was done with that, I would move on to the next problem. For a long time now I was missing that feeling of not caring, just fix the damn problem and move on. Just to slap together some crappy piece of code, use it once or twice and then forget about it.

And that was exactly what I did last night. I sat down and in some five or six hours I put together coords. It is an ugly as hell little pygtk application, void of any good practices, no tests, just a few comments here and there and that’s it. And I had fun writing it! I completely lost track of time while hacking, got into the zone and today, after some six hours of sleep I woke up feeling like I was on a vacation for a week.

The application itself doesn’t do much, it helps determine coordinates on your desktop. Start the application, click “track”, drag the mouse from the top-left corner you’re interested in to the bottom-left one and that’s it. The entire functionality is shown in this ten second long gif that runs somewhere here on the page. The best part is that it actually solves a problem I had, it helps me determine coordinates on my desktop and then I can use those coordinates for byzanz-record. I loved every second I spent hacking on this.

Best part is that even this little application had a quite an interesting challenge to solve, namely, to determine the position of the mouse anywhere on the screen. It’s no big deal to determine the position of the mouse inside your application, but once you want to break out of it, well, it gets bit tricky.

With pygtk one can only subscribe to events that happen inside the application itself. To go lower than that one needs to use a different library, something like xlib (python-xlib from python). After much poking around I found a way to do it from pygtk itself. It is possible to get hold of the root window instance, which is created by the X server itself (you can’t create a root window from an application, or make an application be a root window, afaik). Once you have the root window, grab the pointer, and then filter events you are interested in on the root window before they get sent from the X server to gtk. Or at least that is how I understood this whole process. While having control over the pointer, get the mouse coordinates from the time left button is pressed till the time it is released. Don’t forget to ungrab/release the pointer once your done. And that’s all there is to it, more or less.

The interesting parts are:

def start_tracking(self, widget, data=None):
    mask = gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK
    self.root_window = gtk.gdk.get_default_root_window()
    gtk.gdk.pointer_grab(self.root_window, False, mask)
    self.root_window.add_filter(self.track_region, self.region)
def track_region(self, event, region):
    x, y, flags = event.window.get_pointer()
    if 'GDK_BUTTON1_MASK' in flags.value_names \
            and region.track_started == False:
        region.start_x = x
        region.start_y = y
        region.track_started = True
        region.track_ended = False
    if 'GDK_BUTTON1_MASK' not in flags.value_names \
            and region.track_started == True:
        region.end_x = x
        region.end_y = y
        region.track_ended = True
        region.track_started = False
        # ungrab the pointer so we get control back
        gtk.gdk.pointer_ungrab()
        self.show_region_values(region)
    return gtk.gdk.FILTER_CONTINUE

Isn’t it ugly? Very. But it works and it solves the problem I had. Btw you can check out the code on github to have a bit more context for all this.

Happy hackin’!

Tags: byzanz, hack, pygtk, python.
Categories: Development, Programming, Software.

Need help on your PHP projects? Let's talk!

Changing Jenkins' home directory on Ubuntu

by Robert Basic on August 04, 2011.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

I’ve started to play around with Jenkins yesterday and I kinda don’t like that it’s default home directory is /var/lib/jenkins so I changed it to /home/jenkins, so I’m throwing the steps needed out here for future reference.

First, stop jenkins:

robert@odin:~$ sudo /etc/init.d/jenkins stop

Create the new home directory and move existing stuff from the old home to the new one:

robert@odin:~$ sudo usermod -m -d /home/jenkins jenkins

Now, I didn’t manage to set the ENV JENKINS_HOME to the new home, it was always using the old one, so I edited the init.d script:

robert@odin:~$ sudo vi /etc/init.d/jenkins

and in the “DAEMON_ARGS=…” line change JENKINS_HOME env to –env=JENKINS_HOME=/home/jenkins. In the end the whole line reads something like:

DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=/home/jenkins --output=$JENKINS_LOG --pidfile=$PIDFILE"

Update on September 20th: Vranac blogged about how to change the JENKINS_HOME properly

Start jenkins

robert@odin:~$ sudo /etc/init.d/jenkins start

and go to http://server:port/configure and verify that jenkins works as before and is using the new home.

Happy hackin’!

Tags: hack, jenkins, ubuntu.
Categories: Development, Software.

Need help on your PHP projects? Let's talk!

Contributing to open source

by Robert Basic on March 17, 2011.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Often times people ask me why do I contribute to open source, why do I “waste money and time” on free stuff when I could easily do the same thing for money? Don’t have I enough of staring at the computer at work where, well, I do the same thing - hack on code? Ummm. No.

Honestly, I don’t earn much. Enough for the rent, bills, food, but giving the fact that I don’t have a family, it’s enough for me, for now. So, I don’t make a s**t loads of money, but am still willing to work for free? Ummm. No.

Thing is, I really don’t consider this to be work. This is fun. This is hacking. This is creating stuff. This is solving problems. This is my passion. So no, I don’t work for free. I don’t work. I code, I hack.

But why open source?

Giving back

Giving back is nice. Not necessarily giving back to the same project, but just giving back to the open source community in general. It just makes you a better and nicer person :)

Knowledge

Both in high school and in college the fastest way for me to gain knowledge was to learn, collaborate with other students. Open source gives me the chance to share knowledge with hackers from all over the world; from Portugal, via Nova Scotia to Texas. It gives me the chance to be taught and to teach.

Experience

Open source gives the opportunity to work with people from every part of the globe. Getting ideas across by the means of email, chat, irc can be hard. Open source gives me the chance to improve my communication skills. Heck, I sometimes even have troubles explaining my ideas to my co-workers who sits right next to me.

Reading other peoples code, fixing bugs, writing documentation, adding new features, testing. Hack skills ++

Also, each and every accepted patch and merged pull request gives me that warm and fuzzy feeling inside.

Contacts

Open source introduces you to new people. Who knows what can come out of these random introductions? Can’t be bad, that’s for sure.

This is why I contribute to open source: it is fun, it is hacking, it is creating stuff, it is solving problems.

It is my passion.

Tags: contributing, hack, hacking, open source, random.
Categories: Blablabla.

Need help on your PHP projects? Let's talk!

Wordpress as CMS tutorial

by Robert Basic on March 14, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Wordpress is one of the best blogging platforms out there — if not the best. It’s very powerful, can be easily extended and modified. It’s documentation is very well written and, so far, had answer to all of my crazy questions :)

You know what’s the best part of Wordpress? With some knowledge of PHP and MySql, you can turn it into much more than just a blogging platform. After doing some HTML to WP work for Roger, I thought of one way how could Wordpress be transformed into a CMS. Note the “one way”. This is not the only way for doing this, and, most likely, not the best way.

I didn’t look much, but I think that there are some nice plugins out there that can do this. But, where’s the fun in the download, upload, activate process? Nowhere!

I will show you how to change your Wordpress into a CMS and it really doesn’t take much coding to achieve this! The example presented here is simple and will have a static page for it’s home page, another static page for the “Portfolio” page and the blog. The home and portfolio page will have some of own content and both will include some content from other static pages. You all most likely know the blog part ;)

Static pages

Things you should know: each static page has it’s title, it’s slug or name (the thing that shows up in your browsers address bar: http://example.com/portfolio/ - right there, the portfolio is the slug!), has the parent attribute and the template attribute. The parent attribute is used when it’s needed to make one page a child of another, i.e. to show Page2 as a subpage of Page1. The template attribute is used when we want to apply some different layout and styling to a static page. Read more about static pages and how to create your own page templates.

If you want to, you can download the theme I created for this tutorial from here (it’s not a designers masterpiece, what did you expect?), or you can use any theme you want.

I hope you read the part on creating page templates, I really don’t feel like explaining the next part.

Create 3 new files in your template directory (if you’re using my theme, these files are already there): home.php, portfolio.php and blog.php. Contents of these files are:

// home.php
<?php
/*
Template Name: Home
*/
?>

// portfolio.php
<?php
/*
Template Name: Portfolio
*/
?>

// blog.php
<?php
/*
Template Name: Blog
*/

// Which page of the blog are we on?
$paged = get_query_var('paged');
query_posts('cat=-0&paged='.$paged);

// make posts print only the first part with a link to rest of the post.
global $more;
$more = 0;

//load index to show blog
load_template(TEMPLATEPATH . '/index.php');
?>

To understand the contents of the blog.php file, please take a look at this.

Now, go to the dashboard, the Pages section and write 3 new static pages:

  • Home, with the slug home, for the template choose Home from the drop-down list (it's on the right side) and the parent leave as is (Main Page)
  • Portfolio, with the slug portfolio, for the template choose Portfolio
  • Blog, with the slug blog, for the template choose Blog

You can add some content to the Home and Portfolio pages, but don’t add any to the Blog page.

Organizing links

Now, let’s make that when we are on http://example.com/ it shows us the Home page, instead of the Blog, and when on the http://example.com/blog/ to show us the blog!

Go to Settings->Reading and where it says “First page displays” choose “A static page”, and under the “Front page” drop-down choose “Home”.

Now, go to Settings->Permalinks and change the “Custom structure” to /blog/%postname%/ or whatever is your preferred permalinks structure, but it must start with /blog/! If Wordpress can’t write to your .htaccess file (I hope it can’t!), open it up in your editor and type the following (or similar, depends on your setup):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

The point is in the RewriteBase, with that we’re telling WP where to find the blog. On default setups, when http://example.com/ points to the blog, the RewriteBase is simply / but with the blog located at http://example.com/blog/ we need to change the RewriteBase. If all is well, we’re done with organizing the links.

While you’re still in the dashboard, write some new static pages with content. For the parent of these pages choose Portfolio and leave the template the default (the default page template is page.php).

Time for coding!

Here are two functions I wrote for retrieving content from static pages which will be then included in other static pages:

// functions.php
<?php

/**
* Gets last $number_of_subpages from their $parent_page
* If the <!--more--> tag is ignored ($ignore_more=true) returns the entire content of the subpages
*
* @param mixed $parent_page Contains either the slug of the parent page or it's ID
* @param integer $number_of_subpages Number of subpages to return
* @param boolean $ignore_more Whether to ignore the <!--more--> tag or not
* @return array Contents and titles of subapages
*/
function wpascms_get_subpages($parent_page='portfolio', $number_of_subpages=2, $ignore_more=false)
{
    global $wpdb;

    if(is_string($parent_page))
    {
        $parent_page_ID = wpascms_get_parent_page_ID($parent_page);
    }
    else
    {
        $parent_page_ID = $parent_page;
    }  

    if($number_of_subpages == 0)
    {
        $limit = '';
    }
    else
    {
        $limit = 'LIMIT 0, ' . $number_of_subpages;
    }
    // Get all subpages that are published and are childs of the given parent page
    // and order them by date in descending order (latest first)
    // also, if needed, limit to the latest $number_of_subpages
    $subpages = $wpdb->get_results("SELECT * FROM $wpdb->posts
                                    WHERE `post_parent` = '$parent_page_ID' AND `post_type` = 'page' AND `post_status` = 'publish'
                                    ORDER BY `post_date` DESC $limit");

    if(!$ignore_more)
    {
        foreach($subpages as $key=>$subpage)
            if(strpos($subpage->post_content, '<!--more-->') !== false)
            {
                $short_content = explode('<!--more-->', $subpage->post_content, 2);
                $subpages[$key]->post_content = $short_content[0] . '<a href="' . get_permalink($subpage->ID) . '">Read more...</a>';
            }
        }
    }

    return $subpages;
}

function wpascms_get_parent_page_ID($parent_page)
{
    global $wpdb;

    $id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE `post_name` = %s AND `post_type` = 'page' AND `post_status` = 'publish'", $parent_page));

    return $id;
}

?>

The first function, wpascms_get_subpages() returns the given number of subpages from a specific parent page. By default it will break the content on the tag and append a “Read more…” link. The first parameter can be either a string containing the slug of the parent page, or the ID of the parent page. The second parameter is the number of subpages we want returned. If it’s zero, all subpages will be returned. The second function is merely a helper function, to get the id of the parent page based on it’s slug. To read more on querying the database, read this page.

Here’s how I’m calling this function on my example Home page:

<?php
/*
Template name: Home
*/

get_header();
?>

    <div id="home">
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <h2><?php the_title(); ?></h2>

        <?php the_content('<p class="serif">Read the rest of this page »</p>'); ?>

    <?php endwhile; endif; ?>
    </div><!-- home -->

    <div id="latest_works">
    <h1>Recent work</h1>
    <?php $subpages = wpascms_get_subpages();
    if(count($subpages) > 0):
        foreach($subpages as $row=>$subpage):
        if($row%2 == 0)
        {
            $class = "left_work";
        }
        else
        {
            $class = "right_work";
        }
    ?>
        <div class="<?php echo $class; ?>">
            <h2><a href=<?php echo get_permalink($subpage->ID); ?>><?php echo $subpage->post_title; ?></a></h2>
                <?php echo $subpage->post_content; ?>
        </div>
    <?php
        endforeach;
    endif;
    ?>
    </div><!-- latest_works -->

<?php
get_footer();
?>

In words: including the header, then showing any content of the home page. After that getting the subpages: by default, wpascms_get_subpages() is getting the newest 2 subpages of the portfolio page. I’m showing the content of the subpages in 2 columns. What we got with this? Add a new subpage to the portfolio and it will automagically show up on the left side column. In the end, including the footer.

Here’s another example from the portfolio page:

<?php
/*
Template name: Portfolio
*/

get_header();
?>

    <div id="portfolio">
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <h2><?php the_title(); ?></h2>

        <?php the_content('<p class="serif">Read the rest of this page »</p>'); ?>

    <?php endwhile; endif; ?>
    </div><!-- home -->

    <div id="latest_works">

    <?php $subpages = wpascms_get_subpages('portfolio', 0);
    if(count($subpages) > 0):
        foreach($subpages as $row=>$subpage):
    ?>
        <div class="work">
            <h2><a href=<?php echo get_permalink($subpage->ID); ?>><?php echo $subpage->post_title; ?></a></h2>
                <?php echo $subpage->post_content; ?>
        </div>
    <?php
        endforeach;
    endif;
    ?>
    </div><!-- latest_works -->

<?php
get_footer();
?>

Same thing is happening here: including the header, showing the content of the portfolio page. Getting the subpages, but now all of the subpages that are childs of the portfolio page, and showing them one under the other.

All subpages can be viewed each on it’s own page, but that is just a plain ol’ page.php file, so I’ll skip that.

Don’t limit yourself to the existing plugins or waiting for one tutorial/example that will show how you can make everything. Don’t be afraid to get your hands dirty by hacking some code. It really doesn’t take too much to create magic with Wordpress ;)

Cheers!

Tags: blog, cms, example, hack, php, tutorial, wordpress.
Categories: Development, Programming, Software.

Need help on your PHP projects? Let's talk!