Posted in Python on March 22, 2011 at 8:12 pm by Derek with tags date, python
All the python date functions and types are in the datetime module. So the first thing we’ll need
in our python program is:
import datetime // import the whole module
from datetime import datetime // import the datetime type from the datetime module
What kind of date objects can we work with?
The datetime module contains some useful types:
- datetime – for manipulating dates with times included.
- date – for manipulating dates without times.
- timedelta – for perform operations such as adding and subtracting days from dates.
- time – for manipulating times without dates included.
- tzinfo – for working with timezones
Turn a string into a date
How do we create a python date from a string – perhaps a date we’ve serialized to disk somehow?
Pretty easy… all we need to know is the format the date is stored in. So if our date is stored
in day-month-year format, we can use the datetime format '%d-%m-%Y'. Then we can use the
strptime function to create a datetime from a string.
datestring = '02-03-2011'
format = '%d-%m-%Y'
date = datetime.strptime(datestring, format).date()
print date
We need to call date() on the created date in order to get just the date portion of the datetime
we created with strptime. If we want to keep the time information, we don’t need to do this.
Turn a date into a string
In order to display a date in a nice readable format, we can use the strftime function:
output_format = '%A, %B %d %Y'
print datetime.strftime(date, output_format)
or we could use %c as the format and get the date outputted in the current locale’s format.
Find out what week of the year a date is in
Sometimes, we need to work with the week number that a particular date falls in. We can get
a date’s week number with the isocalendar function. It returns a 3-tuple and the 2nd element
is the week number, so we can get the week number with:
print date.isocalendar()[1]
Add a few days to a date
We can’t add an int to a datetime, but we can add a timedelta to a datetime! So, to
add a day to our date:
date = date + timedelta(1)
print date
That’s it for now…
No comments
Posted in Blogging on March 11, 2011 at 10:09 am by Derek with tags markdown
Markdown is pretty cool… There’s a plugin for
wordpress called ‘Markdown for WordPress and bbPress’ (search for it in your Plugins panel) which
allows you to write your posts in the syntax.
Installing this plugin also seems to solve the extra line breaks problem as well.
No comments
Posted in Blogging, PHP on March 10, 2011 at 10:49 pm by Derek with tags notepad++, php, xmlrpc
In the previous post, I had smashed together a script for notepad++ to allow me to post straight
to my wordpress blog from there… I’ve tidied things up a little and can also edit existing blogs.
The best online help I found was at joysofprogramming.com.
Let’s start with the guts of it all – we can send an xmlrpc to our wordpress blog by using
curl in php:
function get_response($context)
{
global $url;
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url."/xmlrpc.php");
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $context);
$response = curl_exec($curlHandle);
return $response;
}
This function takes a single variable, sets up curl to send a request to xmlrpc.php
and eventually sends the request. In the meantime, we set various curl options… don’t bother
including the header in our response, transfer the response instead of simply outputting it,
content type header for our request and the post data of our request.
The context variable we send in is actually an array containing the details for our
post. So how do we create a post?
function create($meta, $publish)
{
global $username, $password, $url;
$params = array(0, $username, $password, $meta, $publish);
$request = xmlrpc_encode_request("metaWeblog.newPost", $params);
$xmlresponse = get_response($url."/xmlrpc.php", $request);
$response = xmlrpc_decode($xmlresponse);
return "\n# postid:$response";
}
Here’s a function that calls our already defined get_response with an array of
objects. $meta is the data for our post – title, tags, categories for example and the
$publish variable tells wordpress whether or not we want to publish the post. We also
return a string with the response we receive and some text.
How about updating an existing post… its almost the same:
function update($postid, $meta, $publish)
{
global $url, $username, $password;
$params = array($postid, $username, $password, $meta, $publish);
$request = xmlrpc_encode_request("metaWeblog.editPost", $params);
$xmlresponse = get_response($request);
$response = xmlrpc_decode($xmlresponse);
}
When we want to update a post, we need its postid (which will have been returned when we created
the post)
Now… we need to set up our $postid, $meta and $publish
somehow. All that is going to go into the file we’re writing our blog entry to in notepad++. We’re
almost there:
function blog($filename)
{
list($meta, $publish, $postid) = process($filename);
if ($postid == '')
{
$id = create($meta, $publish);
$file = fopen($filename, 'a');
fwrite($file, $id);
fclose($file);
}
else
{
update($postid, $meta, $publish);
}
}
This will create or update a post. If we create a post, we also write an extra line back to the
file with the postid returned from the create function. First thing it
does though is call another function which processes a file:
function process($filename)
{
$lines = file($filename);
$meta = array("description" => "");
$publish = false;
$postid = '';
foreach ($lines as $line)
{
if (strpos($line, '#') === 0)
{
$kv = trim(substr($line,1));
list($key, $value) = split(':', $kv);
$key = trim($key);
$value = trim($value);
if ($key == 'categories' || $key == 'mt_keywords')
{
$meta[$key] = split(',', $value);
}
else if ($key == 'publish')
{
$publish = (bool)$value;
}
else if ($key == 'postid')
{
$postid = $value;
}
else
{
$meta[$key] = $value;
}
}
else
{
$meta["description"] = $meta["description"] . $line;
}
}
return array($meta, $publish, $postid);
}
This function parses the file for lines starting with #, sets some variables
and passes them back for us to work with.
Take a look at the file I’m using to write this post:
# title: Writing and posting blogs with Notepad++
# categories: Blogging, PHP
# mt_keywords: notepad++, php, xmlrpc
# wp_slug:
# mt_allow_comments: 1
# mt_allow_pings: 1
# post_type: post
# publish: 0
<p>In the previous post, I had smashed together a script for notepad++ to allow me to post straight
to my wordpress blog from there... I've tidied things up a little and can also edit existing blogs.
</p>
I think you get the gist… Add the finishing touches by putting all these functions in a php
file:
$url = 'http://myblog.com/wordpress';
$username = 'username';
$password = 'password';
$filename = $argv[1];
blog($filename);
...
And finally adding a NppExec script to notepad++:
php "above php file.php" "$(FULL_CURRENT_PATH)"
npp_open "$(FULL_CURRENT_PATH)"
Sep up a quick keystroke to call the script and now you can create, edit and post blogs in
notepad++. Sweet.
1 comment
Posted in Blogging, PHP on March 9, 2011 at 12:25 am by Derek with tags notepad++, php, wordpress, xmlrpc
See Writing and posting blogs with Notepad++ for an updated version of this script!
Now, I’m fed up with the online WordPress post editor and I use Notepad++ all the time. How about just whacking together some html for my blog posts in my fave editor and posting it to the blog at the stroke of a few shortcut keys. I found a php function in various places around the web that allows remote posting and I started messing about with it – this is what I came up with:
- Already have a wordpress blog up and running somewhere!
- Enable remote posting by logging into your blog as ‘admin’. Navigate to the dashboard / settings / writing and check the box beside XML-RPC in the Remote Posting section.
- Notepad++ with the NppExec plugin. Install Notepad++ and then use the Plugin Manager to install the plugin.
- You must have php installed on your computer.
- You must enable xml-rpc and curl in your php.ini
- Make sure your php executable is on your path… Mine was inside my WAMP install.
- Save this function somewhere on your computer (call it
blog.php maybe): Make sure to change the $url, $username and $password variables to your values! Also, you’ll need to add the xmlrpc.php to your url…
$title,
'description'=>$body,
'mt_allow_comments'=>1, // 1 to allow comments
'mt_allow_pings'=>1, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category)
);
$params = array(0,$username,$password,$content,true);
$request = xmlrpc_encode_request('metaWeblog.newPost',$params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
?>
- Write a nice new blog entry in Notepad++. The first line of this file should be the title you want on your blog, the second line should be the category you want the post to appear in and the third line should be a list of comma-separated tags you want associated with your post. Anything else is considered to be the content of your post.
- Select the menu option Plugins / NppExec / Execute.
- Enter
php "path to where I saved blog.php" $(FULL_CURRENT_PATH) in the dialog box. Click Save.
- You can set up a shortcut key in Notepad++ Settings / Shortcut Mapper…
The only pain with this is that I can’t put extra line breaks in my html… probably due to my less than expert php skills. It would also be nice to be able to edit the content and update the post from Notepad++… Next time…
No comments
Posted in jQuery on March 8, 2011 at 7:30 am by Derek with tags jQuery
I always end up having to head over to the jQuery site to check the docs on how to clear the html from a selection… Its $.empty() not clear():
$("selection").empty()
No comments
Posted in css on March 7, 2011 at 9:12 pm by Derek with tags css, html
Centering things with CSS seems like it should be a straightforward task… not really!
We want to align some text in the middle of a box. Lets try this…
<style>
#box1
{
text-align: center;
vertical-align: middle;
border: 1px solid black;
height: 5em;
}
</style>
<div id='box1'>
<span class='centered1'>I want this to be centered!</span>
</div>
This renders like this:
I want this to be centered!
We’ve gotten it to center in the horizontal direction, but not in the vertical direction. This is because the vertical-align css property is only applied to inline elements. So we shouldn’t even be using it on our div! So let’s try using it on our span:
<style>
#box2
{
text-align: center;
border: 1px solid black;
height: 5em;
}
.centered2
{
vertical-align: middle;
}
</style>
<div id='box2'>
<span class='centered2'>I want this to be centered!</span>
</div>
I want this to be centered!
Nothing changed! We’ve jumped the gun here again… Turns out that the best way to do this is to use the line-height property! Set it to the same height as the parent container…
<style>
#box3
{
text-align: center;
border: 1px solid black;
height: 5em;
}
.centered3
{
vertical-align: middle;
}
</style>
<div id='box3'>
<span class='centered3'>I want this to be centered!</span>
</div>
This works out like this:
I want this to be centered!
If you want the font-size to be different in the child container, you’ll need some mathematical voodoo…
<style>
#box4
{
text-align: center;
border: 1px solid black;
height: 5em;
}
.centered4
{
line-height: 2.5em;
}
</style>
<div id='box4'>
<span class='centered4'>I want this to be centered!</span>
</div>
And the font size gets bigger and the line height doesn’t need to be as large:
I want this to be centered!
Thats just to vertically center an inline element within a div. Even more fun and games when we try to center a block element within another div… next time!
content pre
{
font-size: 12px;
line-height: 1.25em;
}
No comments
Posted in PHP on March 4, 2011 at 8:39 pm by admin with tags ajax, concatenation, post
So I started learning PHP. Had a quick scan through some syntax and language features but got a little ahead of myself. What I really wanted to do was load some data from another website into my page. I wanted to do it from the client-side with ajax, but that’s not possible. PHP function file_get_contents() to the rescue! But it didn’t work… I thought there was some bad setting in my php.ini, but allow_url_fopen was ok.
Turns out that I was building the url for the file_get_contents() function call from some $_POST values from my ajax call. I was being lazy and simply building a string and hadn’t yet found out that the PHP operator for string concatenation is . and not +!
Anyway… problem solved for now.
No comments