<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Antony D'Andrea]]></title><description><![CDATA[Welcome to my little corner of the Internet where I will just dump whatever musings happen to fill my mind.]]></description><link>https://antonydandrea.co.uk/</link><generator>Ghost 0.9</generator><lastBuildDate>Wed, 26 Nov 2025 09:09:47 GMT</lastBuildDate><atom:link href="https://antonydandrea.co.uk/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Hello 2022?]]></title><description><![CDATA[<p>It's amazing how quickly time flies, I can't believe I fell out of even semi-regular blogging so easily.</p>

<p>This site needs a big update. My "About Me" is very out of date, especially the photo. I think 2017 was the last time it was updated.</p>

<p>Wondering if it is time</p>]]></description><link>https://antonydandrea.co.uk/hello-2022/</link><guid isPermaLink="false">58b0feba-c2e7-4002-92d1-1fe2bff5fef6</guid><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 27 May 2022 09:21:18 GMT</pubDate><content:encoded><![CDATA[<p>It's amazing how quickly time flies, I can't believe I fell out of even semi-regular blogging so easily.</p>

<p>This site needs a big update. My "About Me" is very out of date, especially the photo. I think 2017 was the last time it was updated.</p>

<p>Wondering if it is time to shut down, UniverseSite. It pains me to say it because it was my first big project that I saw through to the end and I learnt a lot whilst building it. But after 11 years, I am now only running it for old times sake, but it is costing money for no reason. I doubt anyone is actually going onto it and finding it useful.</p>

<p>Over the past 5 years, I have released a lot of domain names that I was holding onto with the hope of one day turning them into money making side projects.</p>

<p>I actually came back to this blog because I was looking for the step-by-step guide I once made for extending a volume on VirtualBox. I couldn't remember if I actually published it. It seems not.</p>

<p>Well I best get back to work. I am off for a week after today. Getting married next week. Maybe I will see you again some time. At least the SSL certificate is valid again until August.</p>]]></content:encoded></item><item><title><![CDATA[Goodbye 2017, Hello 2018!]]></title><description><![CDATA[<p>So here we are. Less than 70 hours of 2017 to go until the end of the year and the end of this festive period. We start again in January which, in my opinion, really is like the "Monday Morning" of the year.</p>

<p>Over the past year, you may have</p>]]></description><link>https://antonydandrea.co.uk/goodbye-2017-hello-2018/</link><guid isPermaLink="false">c2ac664b-8980-4a59-90c8-d6a0d396f6c3</guid><category><![CDATA[misc]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 29 Dec 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p>So here we are. Less than 70 hours of 2017 to go until the end of the year and the end of this festive period. We start again in January which, in my opinion, really is like the "Monday Morning" of the year.</p>

<p>Over the past year, you may have noticed that I have consistently posted every single week on a Friday. Where I haven't is because of the Ghost scheduler being faulty and not posting, but I have always had a post ready.</p>

<p>This was a challenge that I set myself and I actually started last October. It really was a challenge!</p>

<p>Finding stuff to write about every single week was hard. Some weeks were easy as I may have encountered a problem or learnt something in my day-to-day work that I got to talk about. I also had a list of ideas of things that I wanted to try out that I think would be cool. But some weeks, I would get to Thursday with still no idea what to write.</p>

<p>I am also a terrible procrastinator, so I really would leave things to the last minute by which time, it was too late to write about things that were a little more involved.</p>

<p>But I felt that I had to complete a full year of this and now that the year has finished, I can now stop with the weekly posts.</p>

<p>I am still going to blog, but it will be when I have something to post not forcing something out every single week.</p>

<p>On the whole, it has been a great experience as it has forced me to learn things that I probably would not have if I didn't have this pressure to write. There is also stuff that I blogged about that has been in drafts for as long as this blog has existed (the crazy programming language challenge, for example). I also covered many topics that I myself have looked back on when I have needed that knowledge again. </p>

<p>Committing one post a week was taking up all of the time that I had for side projects. But now that I have that time freed up again, I can now pursue other projects.</p>

<p>I am not going to list here all the things that I hope to do, as quite often, I never stick to it. Back in 2014, I <a href="https://antonydandrea.com/another-year-done/">wrote</a> about what I wanted to do in 2015. These included building an android game and writing a book. As we enter 2018, these are still on my list as not done - so I think this shows how I don't really stick to things. Even back then, I said, "I have found if I write all these in a list, I will get none of them done".</p>

<p>Other cool things from that happened this year include (but are not limited to):</p>

<ul>
<li>I became a <a href="https://connect.sensiolabs.com/badge/101/sensiolabs-certified-twig-designer">Twig certified</a> designer</li>
<li>I made my first ever contribution to an open source project (the ability to specify a side to the <a href="https://twig.symfony.com/doc/2.x/filters/trim.html">trim function</a> in Twig!)</li>
<li>I went to multiple great conferences, most notably, the annual PHP Conference as well as JeffConf which was great</li>
<li>Many day trips and events throughout the year including a great holiday in Cornwall</li>
<li>I finally did a stadium tour of White Hart Lane stadium before it was demolished</li>
<li>I became a Tottenham season ticket holder which was a surprise</li>
</ul>

<p>It is always exciting to look at the year ahead with its endless potential to be amazing and I will do what I can to make that potential become reality.</p>

<p>I hope you all have a successful and fulfilling 2018!</p>]]></content:encoded></item><item><title><![CDATA[PHP Observer Pattern]]></title><description><![CDATA[A very simple guide to using the observer pattern in PHP!]]></description><link>https://antonydandrea.co.uk/php-observer-pattern/</link><guid isPermaLink="false">0a6de7bc-1483-4307-bd15-0eec55f160d7</guid><category><![CDATA[php]]></category><category><![CDATA[patterns]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 22 Dec 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p>This week, I learnt a new design pattern to add to my toolbox. It is called the Observer Pattern.</p>

<p>The example I will go through is based on the one given in the book, <a href="https://www.amazon.co.uk/PHP-Master-Write-Cutting-Edge/dp/0987090879/">PHP Master - Write Cutting Edge Code</a>, which I would highly recommend anyone learning PHP.</p>

<h5 id="whatistheobserverpattern">What is the Observer Pattern?</h5>

<p>It is basically a way of triggering code to run when certain events happen. If you are familiar with Javascript, then this concept will be familiar.</p>

<p>In Javascript, you might attach a function to a "click" event of a button which gets run every time that particular button is pressed.</p>

<p>This pattern allows you to do something similar in PHP. You can register a "listener" and then trigger it when you like. Let's take a look how this works.</p>

<h6 id="theeventclass">The Event Class</h6>

<p>This class will be responsible for storing and running all of the code. It will be made up of static properties and functions so that it can be accessed anywhere in the code base.</p>

<pre><code>class Event
{
    static private $callbacks = [];
}
</code></pre>

<p>First we have an array that will store all of the event names and the functions to run when they are invoked.</p>

<pre><code>static public function register(string $eventName, $callback)
{
    if (!is_callable($callback)) {
        throw new Exception('Must register a callable, '.gettype($callback).' given.');
    }
    self::$callbacks[strtolower($eventName)][] = $callback;
}
</code></pre>

<p>Next we have our <code>register</code> function. It takes 2 parameters: a name and a callback. The callback is typically expected to be a closure (which I covered <a href="https://antonydandrea.com/php-lambdas-and-closures/">here</a>), but can also be an object.</p>

<p>The function throws an Exception if it is not a piece of code that can be run. Otherwise, it adds it to the array. Note that I have allowed for multiple functions to be run with the same event name.</p>

<p>Next we need a way to trigger it. So there is another function:</p>

<pre><code>static public function trigger(string $eventName, $data = null)
{
    if (isset(self::$callbacks[strtolower($eventName)])) {
        foreach(self::$callbacks[strtolower($eventName)] as $callback) {
            $callback($data);
        }
    }
}
</code></pre>

<p>}</p>

<p>Again, very simple. It takes 2 parameters, the name and, optionally, data that you wish to pass into the callback function.</p>

<p>If the name exists in the listener, it loops through all the attached functions and runs them.</p>

<p>So simple.</p>

<h5 id="usingtheeventclass">Using the Event Class</h5>

<p>In my very simplistic example, I am just going to register and even called "my_event" using the class that I just made:</p>

<pre><code>Event::register('my_event', function($data) {
    print $data."\n";
});
</code></pre>

<p>You can see that I pass the function as the second parameter directly and all the function does is print the data parameter.</p>

<p>Now let's say somewhere else in the code I have a function that does something, I can now trigger the event each time it is run:</p>

<pre><code>function doSomething()
{
    print "I did something\n";
    Event::trigger('my_event', date("Y-m-d"));
}
</code></pre>

<p>So this function prints some text then triggers the event "my_event", passing the date as the parameter. As we set up the event earlier, it will just print this.</p>

<p>So if we run this function:</p>

<pre><code>doSomething();
</code></pre>

<p>We get the following output:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/12/Screen-Shot-2017-12-21-at-16-38-04.png" alt=""></p>

<h5 id="summary">Summary</h5>

<p>Obviously in this very simple demo, it seems silly to use events at all, but this is very useful pattern to use in your more complex systems and very easy to set up.</p>

<p>For example, you can trigger things like writing to a log or clearing some cache or sending an alert. It can make your code far more tidy having this all in one place!</p>]]></content:encoded></item><item><title><![CDATA[Creating a Real Time Web App with Pusher]]></title><description><![CDATA[A simple demo of how to use Pusher to create a real time web app in the form of a simple chat room.]]></description><link>https://antonydandrea.co.uk/creating-a-real-time-web-app-with-pusher/</link><guid isPermaLink="false">3ef6433f-06bd-4f06-91ec-9431f9c1f5bf</guid><category><![CDATA[jquery]]></category><category><![CDATA[javascript]]></category><category><![CDATA[ajax]]></category><category><![CDATA[php]]></category><category><![CDATA[html]]></category><category><![CDATA[realtime]]></category><category><![CDATA[pusher]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 15 Dec 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p>A few years ago I went through a phase of being "into" real-time web applications. I did a couple of experiments with Websockets (in particular SocketIO) and got some interesting results. I even included an aspect of this in my university dissertation.</p>

<p>I thought I would revisit this to remind myself of how it works and see what new things have happened.</p>

<p>It seems that it is even easier now than ever before to get started with real-time web applications. Where as before I built a websocket server that had to be on and handle the messages, there are now services that do all of this for you.</p>

<p>An example of this is <a href="https://pusher.com">Pusher</a>. They provide the service for building real time web applications along with tools to monitor usage and a really simple API that does most of the work for you.</p>

<p>There is a free tier that is especially good if you just want to have a play. I won't go into details here how to sign up or a guide to their interface because they do a pretty good job of all that and it is pretty straight forward.</p>

<p>In fact, they even provide a very easy to follow basic code in whatever language you are using, to get you started (some of which this demo is based off).</p>

<p>The demo will build a very basic chat room with no rules or security at all. You just go on and send messages and they appear for everyone that is viewing the page.</p>

<h6 id="html">HTML</h6>

<p>I have put together a very basic HTML page with some help from Bootstrap as well as some inline styles.</p>

<p>The bulk of it looks like this:</p>

<pre><code>&lt;div class="container"&gt;
    &lt;h1 class="text-center"&gt;My Chat Room&lt;/h1&gt;
    &lt;div class="row"&gt;
        &lt;p class="col-xs-12"&gt;Messages:&lt;/p&gt;
        &lt;div id="messages" class="col-xs-12" style="height:400px; overflow-y: scroll; border: 5px solid #000;"&gt;&lt;/div&gt;
        &lt;div class="col-xs-12" style="margin-top: 20px;"&gt;
            &lt;input type="text" id="my_message" class="col-xs-8" /&gt;
            &lt;button id="send_message" class="col-xs-4"&gt;Send&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>Which gives an output that looks like this:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/12/Screen-Shot-2017-12-12-at-19-13-28.png" alt=""></p>

<p>The idea is that when I type something into the text box and click Send, it will update the messages box. This would happen on all who are logged onto the page.</p>

<p>First, let's handle receiving messages from Pusher.</p>

<h6 id="receivingmessagesfrompusher">Receiving Messages from Pusher</h6>

<p>First I create a new app. It rather helpfully provides a clear example of how to use their library based on what technologies you use. So it is useful to select this albeit optional:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/12/Screen-Shot-2017-12-12-at-19-16-36.png" alt=""></p>

<p>Now back to our code.</p>

<p>First, I need to load the Pusher library into the web page:</p>

<pre><code>&lt;script src="https://js.pusher.com/4.1/pusher.min.js"&gt;&lt;/script&gt;
</code></pre>

<p>Next, I need to connect to the API, using my key. The demo code they provide has this boiler plate:</p>

<pre><code>var pusher = new Pusher('api-key-goes-here', {
    cluster: 'eu',
    encrypted: true
 });
</code></pre>

<p>Finally, I open up a connection and start listening to a particular channel:</p>

<p>var channel = pusher.subscribe('messages');</p>

<p>I could have called this channel anything I wanted, but I named it "messages" in this case.</p>

<p>It should be obvious at this stage that I could have multiple different channels, listening to different things.</p>

<p>Now, I can tell it what to do when it receives data from the channel:</p>

<pre><code>channel.bind('message-received', function(data) {
     alert(data.message);
});
</code></pre>

<p>Again, I could have different names for the events being sent, but I call it "message-recieved". You can see that I specify a function that gets the data as an argument. This data is in the form of JSON so can be accessed as such.</p>

<p>In this case, I am simply opening an alert showing what is in the message key.</p>

<p>I can test this using the Pusher debug console where I created the app.</p>

<p>It allows me to send a message on a channel and with a label that I specify with any data that I like to this particular app:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/12/Screen-Shot-2017-12-12-at-19-32-22.png" alt=""></p>

<p>You can see my data is in the form of JSON and I have a key called "message" with the text, "Hello". You can also see underneath all that, that is has acknowledged the fact that there is one client online and listening to this app.</p>

<p>Sending the message causes the pop-up to show with my message there:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/12/Screen-Shot-2017-12-12-at-19-32-04.png" alt=""></p>

<p>Thus proving that my front end is successfully connected.</p>

<p>Now we just have to make it do something a little more useful, that is, put the message inside the box. This can be done with a single line replacing the alert:</p>

<pre><code>$('#messages').append('&lt;p&gt;'+ data.message +'&lt;/p&gt;');
</code></pre>

<h6 id="serverside">Server Side</h6>

<p>So now we are successfully receiving messages and updating our screen accordingly. Now we want to be able to actually send messages from our browser.</p>

<p>To do this, we need some code on the server side to receive a message from the browser then send it on to Pusher. I have created a file called "message_processor.php".</p>

<p>First we need to install the Push SDK again. We can use composer for this which is great. So in my composer JSON file, I have the line:</p>

<pre><code>"pusher/pusher-php-server": "v3.0.*"
</code></pre>

<p>Then I can just include it into my server file by requiring the vendor autoload file:</p>

<pre><code>require __DIR__ . '/vendor/autoload.php';
</code></pre>

<p>Now I want to check if I have received a post request with the message and if I have run some code:</p>

<pre><code>if ($_POST['message'] &amp;&amp; !empty($_POST['message'])) {
    $message = $_POST['message'];
}
</code></pre>

<p>Next, within the if-statement, I wan to connect to the app again. As you can see, I pass the app id and the API key and secret key. These can be found under App Keys tab on the pusher website.</p>

<pre><code>$options = [
    'cluster' =&gt; 'eu',
    'encrypted' =&gt; true
];
$pusher = new Pusher\Pusher(
    'KEY',
    'SECRET',
    'APPID',
    $options
);
</code></pre>

<p>Finally, I can now simply use my pusher object to broadcast the message to the app:</p>

<pre><code>$data = [
    'message' =&gt; $message
];
$pusher-&gt;trigger('messages', 'message-received', $data);
</code></pre>

<p>As you can see, I am forming an array to send. I then call the trigger function with channel that I am sending it to and the label for that message. It seems silly sending back the message that I just sent, but remember, everyone who is currently on that page will see it appear like magic on their screen.</p>

<h6 id="connectingitallupwithajax">Connecting it all up with AJAX</h6>

<p>Now that I have done the backend code, I want to send a message to it when I press the button. To do this, I make a simple click event function and within this function, I call some AJAX (I covered AJAX in <a href="https://antonydandrea.com/a-quick-guide-to-ajax/">last week's post</a>!):</p>

<pre><code>$('#send_message').click(function(e){
    e.preventDefault();
    $.ajax({
        url: "/pusherdemo/message_processor.php",
        data: {
            message: $('#my_message').val(),
        },
        type: "POST",
        dataType: "json",
        beforeSend: function() {
            $('#send_message').attr('disabled', 'disabled');
        },
        success: function(json) {},
        complete: function(json) {         
            $('#send_message').removeAttr('disabled');
            $('#my_message').val('');
        }
     });
    return false;
});
</code></pre>

<p>As you can see, it sends the contents of the input to the message processor and then clears it. It doesn't do anything in success because it doesn't need to.</p>

<p>Again, it seems a bit weird not using the success function to update the messages, but remember, only YOU would see that. This way, everyone on this chat room will see the message that you just sent.</p>

<p>Now I can't really demonstrate it in the blog post, but all of the above code does work. Here is a screenshot of 2 different browsers both connected to the same page. You can see the messages that I already sent have appeared on both even though I only sent from one:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/12/Screen-Shot-2017-12-12-at-20-28-47.png" alt=""></p>

<h5 id="summary">Summary</h5>

<p>Once again, I have only scratched the surface with what is possible with WebSockets and Pusher with an incredibly simplified demo. </p>

<p>But I hope it shows just how quick it is to get started!</p>]]></content:encoded></item><item><title><![CDATA[A Quick Guide to AJAX]]></title><description><![CDATA[AJAX stands for "Asynchronous JavaScript And XML" and provides a way of making web requests from a web page asynchonously. ]]></description><link>https://antonydandrea.co.uk/a-quick-guide-to-ajax/</link><guid isPermaLink="false">36a0cb52-e95e-4046-887c-b1906bb23a0d</guid><category><![CDATA[javascript]]></category><category><![CDATA[jquery]]></category><category><![CDATA[ajax]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 08 Dec 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p>For the past couple of years, I have used AJAX a lot and have found it so incredibly useful for a variety of different tasks. </p>

<p>I think right now every person developing for the web should have this in their toolset.</p>

<p>This blog will go over the common way that I use it with the help of jQuery.</p>

<h5 id="ajaxandjquery">AJAX and JQuery</h5>

<p>AJAX stands for "Asynchronous JavaScript And XML" and provides a way of making web requests from a web page asynchonously. This is incredibly powerful as it means you can do all kinds of tasks without having to make your user wait or without refreshing the page.</p>

<p>So I am cheating a little when I use AJAX by using JQuery's wrapper of it. You can use it in pure javascript and I am sure there are plenty of tutorials on that, but it is a little bit more wordy than this way.</p>

<p>If you are already using JQuery in your project, then it makes sense to use it to handle your AJAX requests.</p>

<p>The full documentation on how to use it can be found <a href="http://api.jquery.com/jquery.ajax/">here</a>.</p>

<h5 id="demo">Demo</h5>

<p>I have a very simple page with 2 elements:</p>

<pre><code>&lt;h1 id="response"&gt;&lt;/h1&gt;
&lt;button id="my_button"&gt;Make Request&lt;/button&gt;
</code></pre>

<p>When I click the button, it will send an AJAX request and populate the <code>&lt;h1&gt;</code> tags with the response.</p>

<p>Let me just show you the Javascript then I will talk through each section:</p>

<pre><code>$('#my_button').click(function(e){
    e.preventDefault();
    $.ajax({
        url: "/ajax/ajax.php",
        data: {
            name: "Antony",
        },
        type: "POST",
        dataType: "json",
        beforeSend: function() {
            $('#my_button').attr('disabled', 'disabled');
        },
        success: function(json) {
            $('#response').html(json.timestamp + ': ' + json.greeting);
            var t = new Date().getTime();                 
            while (new Date().getTime() &lt; t + 5000);
        },
        complete: function(json) {         
           $('#my_button').removeAttr('disabled');
        }
    });
    return false;
});
</code></pre>

<p>OK.</p>

<p>The first line is a basic way of saying that when I press the button with the ID of "my_button", to run the function. Standard jQuery.</p>

<p>The AJAX request is made up of many parts:</p>

<p><strong>url</strong> - the is the location to make the call. In this case it is just a PHP file in the same directory. But it could be anything from a 3rd party API to literally another website.</p>

<p><strong>data</strong> - this is data that you want to send with the payload to the above URL. Again, this could be anything including data from a form. I have hardcoded my name. You will see later how it is received.</p>

<p><strong>type</strong> - this specifies the HTTP method. Usually it is a POST or GET request. In this case, we are sending the data as a POST request, so the code at the URL should be expecting that.</p>

<p><strong>dataType</strong> - this tells the AJAX what MIME type to expect the response. If you do not specify anything, it will try and guess. Here, I am explicitly saying to parse the incoming response as JSON.</p>

<p><strong>beforeSend</strong> - this can be used to specify a function to complete some task before sending the request. Just like I have here, I usually use this to disabled the button to prevent further requests from being sent whilst the AJAX is waiting for a response. Remember, by default, this is non-blocking, so the user can still interact with the page whilst waiting. Other use cases could be to set some kind of message or loading graphic.</p>

<p><strong>success</strong> - this is the function that is run when the AJAX completed successfully. You can see that the function takes a single parameter which is the response. In this case, it is all in JSON. In my function, I am setting the HTML of the <code>h1</code> element with the contents of the JSON. I am also holding the execution for 5 seconds so that the disabled button could be seen otherwise it is too quick.</p>

<p><strong>complete</strong> - whether the success function runs or not, the complete function always run. This can be used to do any tidying up or to relay a message to the user. In this case, I re-enable the button by removing the attribute.</p>

<p>And thats it! It is really straightforward to put together a simple request.</p>

<p>Now a quick look at ajax.php:</p>

<pre><code>&lt;?php
$name = $_POST['name'];
$response = [
    'greeting' =&gt; "Hello, $name!",
    'timestamp' =&gt; time()
];
header('Content-Type: application/json');
echo json_encode($response);
return true;
</code></pre>

<p>Obviously how you deal with the request and return and the response depends on how your project is set up and any frameworks that you are using. For this demo, it is really simple.</p>

<p>First, you can see that I interact with the <code>$_POST</code> array to get the data that was sent. The key matches the key in <code>data</code> and I am accessing it in <code>$_POST</code> because it is a request of type "post" (as we set earlier).</p>

<p>I simply put together an array and <code>json_encode</code> it and set the header and <code>echo</code> back the result.</p>

<p>If you look at the network tab in the dev tools, you will see the request being made and the JSON response:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/12/Screen-Shot-2017-12-07-at-19-41-03.png" alt=""></p>

<h5 id="summary">Summary</h5>

<p>So as you can see, using AJAX is very very easy and I have only just scratched the service. It is so useful for triggering non-blocking events to give a smoother website experience.</p>

<p>Once again, the full guide on what you can do with jQuery's AJAX can be found <a href="http://api.jquery.com/jquery.ajax/">here</a>. It covers all of the options that I went over in this post and many many more.</p>]]></content:encoded></item><item><title><![CDATA[PHP 7.2]]></title><description><![CDATA[A brief look into some of the new additions coming to PHP in PHP 7.2]]></description><link>https://antonydandrea.co.uk/php-7-2/</link><guid isPermaLink="false">75fdf1eb-3747-4827-b2ff-37f137fed492</guid><category><![CDATA[php]]></category><category><![CDATA[php-7.2]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 01 Dec 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p>It is that time of year again. A new version of PHP has been unleashed into the world.</p>

<p>I think this one is a relatively low-key release in terms of language changing features. A few small things here and there but nothing too big. But here is a selection of changes.</p>

<p>A full list with further details can be found <a href="https://github.com/php/php-src/blob/php-7.2.0RC6/UPGRADING">here</a>.</p>

<h4 id="overviewofversions">Overview of Versions</h4>

<p>So now is a good time to take stock of what versions of PHP are currently supported.</p>

<p>If you are on anything less than PHP 5.6, you are in trouble and you have been for a while. Security support for 5.5 ended some time in the middle of 2016.</p>

<p>PHP 5.6 is no longer getting active support, but is going to to continue to get security support until 31st December 2018. This means that bugs are only going to be fixed if they pose a security threat. It also means that you have also got just over a year to make the leap to PHP 7.</p>

<p>If you are on 5.6, it really isn't that much of a big jump to get to PHP 7 in terms of backwards incompatible changes.</p>

<p>PHP 7.0 ends its active support in 2 days on the 3rd of December 2017 and will continue to get security fixes until the same time next year. So if you are still on this version, I would suggest skipping 7.1 and upgrading straight to 7.2 and now is the time to start thinking about doing this.</p>

<p>PHP 7.1 has active support for another year and security support until today in 2019.</p>

<p>PHP 7.2 obviously has 2 years of active support ahead of it now and a year of security support following that.</p>

<h4 id="features">Features</h4>

<h5 id="overrideargumenttypeannotationshttpswikiphpnetrfcparameternotypevariancebrbr"><a href="https://wiki.php.net/rfc/parameter-no-type-variance">Override Argument Type Annotations</a><br><br></h5>

<p>Let's say that I have the following class:</p>

<pre><code>class MyClass
{
    public function myFunction(int $var)
    {
        return $var;
    }
}
</code></pre>

<p>It has a single function called <code>myFunction</code> that takes a single argument that has been specified as being an integer. All it does is return the argument as it is.</p>

<p>Now if I make another class that extends the one above:</p>

<pre><code>class MyChildClass extends MyClass
{
    public function myFunction($var)
    {
        return $var;
    }
}
</code></pre>

<p>I have overridden the function, <code>myFunction</code> and although it does the same thing, it no longer has the type hint.</p>

<p>If I now use this class:</p>

<pre><code>$obj = new MyChildClass;
var_dump($obj-&gt;myFunction(3));
</code></pre>

<p>This would give me the expected result but it will come with a warning:</p>

<pre><code>PHP Warning:  Declaration of MyChildClass::myFunction($var) should be compatible with MyClass::myFunction(int $var) 
</code></pre>

<p>This warning will no longer occur from PHP 7.2 onwards. I am not sure how useful this feature will be. In my mind, it could lead to laziness when inheriting from libraries as it is no longer forcing you to use a type.</p>

<p>But apparently it "complies with contravariance of method argument types under the Liskov Substitution Principle". Who am I to argue with Liskov?</p>

<h5 id="overrideabstractfunctionwithanotherabstractfunctionhttpswikiphpnetrfcallowabstractfunctionoverridebrbr"><a href="https://wiki.php.net/rfc/allow-abstract-function-override">Override Abstract Function With Another Abstract Function</a><br><br></h5>

<p>Let's say I have an abstract class:</p>

<pre><code>abstract class MyClass
{
    abstract function myFunc(int $param);
}
</code></pre>

<p>And another that inherits it:</p>

<pre><code>abstract class MyOtherClass extends MyClass
{
    abstract function myFunc(int $param):int;
}
</code></pre>

<p>In my inherited class, I override <code>myFunc</code> with another abstract function and even give it a return type.</p>

<p>Now if I implement this abstract class and use it:</p>

<pre><code>class FinalClass extends MyOtherClass
{
    public function myFunc(int $param):int
    {
        return ($param * $param);
    }
}
$obj = new FinalClass;
var_dump($obj-&gt;myFunc(3));
</code></pre>

<p>I would get an error:</p>

<pre><code>PHP Fatal error:  Can't inherit abstract function MyClass::myFunc() (previously declared abstract in MyOtherClass)
</code></pre>

<p>You could not inherit an abstract class in this way. From PHP 7.2, you can. So the above code would run successfully and give me the result:</p>

<pre><code>int(9)
</code></pre>

<h5 id="trailingcommaingroupusestatementshttpswikiphpnetrfclistsyntaxtrailingcommasbrbr"><a href="https://wiki.php.net/rfc/list-syntax-trailing-commas">Trailing Comma in Group Use Statements</a><br><br></h5>

<p>From PHP 7.0, you have had the ability to group use statements like so:</p>

<pre><code>use SomePackage\{
      MyClass,
    AnotherClass
};
</code></pre>

<p>But if you had a trailing comma like this:</p>

<pre><code>use SomePackage\{
      MyClass,
    AnotherClass,
};
</code></pre>

<p>You would get a parse error:</p>

<pre><code>Parse error: syntax error, unexpected '}', expecting identifier (T_STRING) or function (T_FUNCTION) or const (T_CONST)
</code></pre>

<p>From PHP 7.2, you are now allowed to have the trailing comma. This makes it possible to do cleaner diffs when doing source management. It is why it is often down in long arrays (I personally hate it though).</p>

<p>The original RFC had a few different places to have the trailing comma allowed but this was the only one that was accepted.</p>

<h5 id="objecttypeannotationhttpswikiphpnetrfcobjecttypehintbrbr"><a href="https://wiki.php.net/rfc/object-typehint">Object Type Annotation</a><br><br></h5>

<p>PHP 7.2 brings another type that you can use to type hint with called 'object'.</p>

<p>Take the following:</p>

<pre><code>class MyClass
{
     public static function myFunc(object $param)
     {
         return $param;
     }
}
</code></pre>

<p>If I try to use the function and pass it a generic object:</p>

<pre><code>var_dump(MyClass::myFunc(json_decode('{}')));
</code></pre>

<p>I get a fatal error:</p>

<pre><code>Fatal error: Uncaught TypeError: Argument 1 passed to MyClass::myFunc() must be an instance of object, instance of stdClass given
</code></pre>

<p>Because it is expecting some object that is an instance of a class called "object". But as of 7.2, "object" is a reserved word, and the code runs correctly.</p>

<p>This is a very useful addition as it gets rid of the need for the <code>is_object</code> check that one would normally have to do in this case.</p>

<h5 id="mcryptnowinthecryptsbrbr">MCrypt Now In The Crypts<br><br></h5>

<p>This is actually something removed rather than added and I have included it as it is the biggest change that effects me personally.</p>

<p>In PHP 7.1, the Mcrypt extension was deprecated. Now it is completely removed. This is because libmycrypt has not been maintained for 10 years! So it is now considered insecure and even if you are not planning upgrade, you should stop using it.</p>

<p>Alternatives that you can use are OpenSSL or, new to 7.2, <a href="https://wiki.php.net/rfc/libsodium">libsodium</a>. The functions are very similar so porting across should be straightforward.</p>

<p>If you absolutely can not migrate away from it but really want to upgrade to 7.2, it is still available as a PECL extension so could be installed separately (but you should seriously just scrap it completely).</p>

<h4 id="summary">Summary</h4>

<p>So there are just a few of the features added (and removed) in this latest iteration of PHP. You can read about these and the rest of the release notes <a href="http://php.net/archive/2017.php#id2017-11-30-1">here on the PHP website</a>.</p>]]></content:encoded></item><item><title><![CDATA[Serverless PHP]]></title><description><![CDATA[A brief guide to how to use IBM Cloud Functions to run PHP code serverless.]]></description><link>https://antonydandrea.co.uk/serverless-php/</link><guid isPermaLink="false">3fe71a2e-dcd0-4e35-a6e1-99f7b988785b</guid><category><![CDATA[php]]></category><category><![CDATA[serverless]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 24 Nov 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p>"Serverless" is a bit of a buzzword nowadays. I even went to a <a href="https://www.jeffconf.com/">conference </a>about it earlier this year. </p>

<p>It is the idea that instead of purchasing a server (or paying a provider for one), you give the provider the functions that you want to run and they will be responsible of putting it on the server and maintaining that side of things.</p>

<p>It is essentially "serverless" to you, the user, as you don't need to worry about any of that kind of stuff. You also only pay when the function is called making a lot cheaper than a dedicated server in certain cases.</p>

<p>My problem so far has been the lack of support for PHP functions. If you know Node or Python, then you have loads of choices to set it up including AWS Lambda.</p>

<p>That was until I went to the above conference and became made aware of <a href="https://console.bluemix.net/openwhisk/">Bluemix functions</a>: an IBM implementation of <a href="https://openwhisk.apache.org/">OpenWhisk</a> which is an "open source cloud platform". </p>

<p>For basic executions of up to 5,000,000 executions a month, its free. This experimenting fall well within that price bracket.</p>

<p>Rob Allen did a great <a href="https://akrabat.com/getting-started-with-serverless-php/">blog post</a> to get started using it and that is what I used to get me started to write this one.</p>

<h5 id="installingthecli">Installing the CLI</h5>

<p>First thing that you have to do is sign up to IBM Cloud. This the new name for Bluemix, although you will still see the name used for the functions.</p>

<p>Here is the <a href="https://console.bluemix.net/openwhisk/">link</a>,</p>

<p>The process is pretty self explanatory. You don't even need payment details. I would advise you put in a name for company even though it is optional as this is used in the URL for your functions later. If you leave it blank it uses the e-mail in the URL which is something you may not want public if you plan on sharing it.</p>

<p>You could create and modify your functions on the web interface but there is a CLI plugin which is probably more preferable as you can then develop on your own setup.</p>

<p>There are instructions for Windows, Mac and Ubuntu. I used Ubuntu so can only speak for that.</p>

<p>First you download the package:</p>

<pre><code>curl -fsSL https://clis.ng.bluemix.net/install/linux | sh
</code></pre>

<p>The website then goes through the 4 steps of setting it up which I won't copy and paste here. They even personalise it to pre-fill your e-mail address for settings etc.</p>

<h5 id="thecode">The Code</h5>

<p>The code for a single function is pretty straightforward. You have a file with a function called "main" which can call other functions or do everything itself.</p>

<p>My example is a simple quadratic equation calculator. It takes 3 parameters a, b and c and does the calculations based on the formula:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/11/Screen-Shot-2017-11-23-at-16-32-04.png" alt=""></p>

<p>So here is the code. I will go through the points of interest for this post below:</p>

<pre><code>function main(array $args) : array
{
    $ouput = [];
    $error = '';
    foreach (['a', 'b', 'c'] as $part) {
        if (isset($args[$part])) {
            if (!is_numeric($args[$part])) {
                $error = $part.' is not a valid integer.'.$args[$part];
                break;
            }
        } else {
            $error = 'Missing value for '.$part.'.';
            break;
        }
    }
    if (!empty($error)) {
        $output['runtime_error'] = $error;
    } else {
        extract($args);
        $value1 = (($b * (-1))+(sqrt((($b**2)-(4*$a*$c)))))/(2*$a);
        $value2 = (($b * (-1))-(sqrt((($b**2)-(4*$a*$c)))))/(2*$a);
        if (is_nan($value1) || is_nan($value2)) {
            $output['runtime_error'] = 'Not a valid quadratic equation.';
        } else {
            $output['x1'] = $value1;
            $output['x2'] = $value2;
        }
    }
    return $output;
}
</code></pre>

<p>So the first point of interest is the function signature:</p>

<pre><code>function main(array $args) : array
</code></pre>

<p>As you an see, it is called "main" takes a single array called "$args" and has a return type of "array".</p>

<p><code>$args</code> contains all of the parameters that you call with the function (if any) where the key is the name and value, the value. More later how we pass these but for now accept that they go into the array.</p>

<p>The code itself starts off by validating the input parameters, making sure they are numbers and that none of them are missing. All of the response is going into an array, <code>$output</code>, that is returned at the end.</p>

<p>One thing to note that is that if there is an error, I called the response key "response_error". This is because when it was "error", I got unusual results when running this script on the web.</p>

<p>The returned array is transformed by Bluemix into JSON by default if you do not specify anything.</p>

<p>The rest of the code is doing the calculations. That is not important for this blog so I will leave you to look through that.</p>

<h5 id="installingandcalling">Installing and Calling</h5>

<p>Once you have done your code, it is time to send it to IBM to host.</p>

<p>To do this, you use a simple command:</p>

<pre><code>bx wsk action update nameOfFunction /path/to/file.php
</code></pre>

<p>This will create (or update if it already exists) a function of the said name with the code that you send.</p>

<p>You can see the list of installed actions with:</p>

<pre><code>bx wsk action list
</code></pre>

<p>To run a function, in the command line do:</p>

<pre><code>bx wsk action invoke --result nameOfFunction
</code></pre>

<p>If you want to add parameters use the param flag:</p>

<pre><code>bx wsk action invoke --result nameOfFunction --param nameOfParam valueOfParam
</code></pre>

<p>So with my quadratic equation example, here is me calling with with various parameters to show the error handling.</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/11/step7.png" alt=""></p>

<p>Note, this is before I changed <code>$output['error']</code> to <code>$output['runtime_error']</code>, so the response says error. Also note that the response is automatically sent as JSON by default.</p>

<p>If I pass it valid parameters, I get the 2 values of x.</p>

<h5 id="makingitavailableonweb">Making it available on Web</h5>

<p>Of course one thing you will want to do with these functions is the make them available on the web. This is very easy to do.</p>

<p>When you install the function on IBM, you can add another flag:</p>

<pre><code>bx wsk action update nameOfFunction /path/to/file.php --web true
</code></pre>

<p>Now to see the URL, you can do:</p>

<pre><code>bx wsk get nameOfFunction --url
</code></pre>

<p>This will give you the full URL of you function. You can then hit this in any web browser and IBM will give you a formatted JSON response. To add parameters, you can do it in the normal way expected on the web: <code>?param=value&amp;param2=value2</code>. So after doing this with my function, let's see it on the web:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/11/final.png" alt=""></p>

<h5 id="summary">Summary</h5>

<p>As you can see, it is incredibly easy to get started with serverless code in PHP. As usual, I have barely scratched the surface with what is possible and I look forward to experimenting in the coming weeks.</p>

<p>No longer do you need to pay for an entire server environment to run a few simple lines of code!</p>

<p>Once again, check out Rob Allen's <a href="https://akrabat.com/getting-started-with-serverless-php/">blog post</a> which helped get me started. He has also done a few more posts delving deeper into what you can do and has a link to a Git repository with more sample code.</p>]]></content:encoded></item><item><title><![CDATA[Raspberry Pi Night Camera - Part 2: Power and Lights]]></title><description><![CDATA[How I created a motion night camera with a Pi Zero and other parts. Part two has how I managed to hook up IR lights and power.]]></description><link>https://antonydandrea.co.uk/raspberry-pi-night-camera-part-2-power-and-lights/</link><guid isPermaLink="false">d387856b-2dda-4d21-a1f4-edda666c14bb</guid><category><![CDATA[raspberry]]></category><category><![CDATA[raspberry-pi]]></category><category><![CDATA[pi]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 17 Nov 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p><a href="https://antonydandrea.com/raspberry-pi-night-camera-part-1-motion-triggered-camera-and-clock/">Last week</a>, I wrote about a project that I started involving a Raspberry Pi Zero, a night camera and a motion sensor.</p>

<p>This week I will show how I solved the 2 more problems: lighting and power.</p>

<h6 id="lighting">Lighting</h6>

<p>Night vision cameras can't actually see in the dark. Like all other cameras, they still need light. But the light they can see is infra red light which is what separates them from the rest.</p>

<p>So most night vision cameras, have an infra red light that is invisible to human eye, but lights up an area perfectly for a camera to see.</p>

<p>For this project, I decided to use the <a href="http://www.ebay.co.uk/itm/IllumiPi-GPIO-project-kit-for-Raspberry-Pi-LED-CCTV-security-light-switch-kit-/131071521247">IllumiPi</a> kit, which provided all of the power cables and components hook up most IR lights. I also bought <a href="https://www.ebay.co.uk/itm/Infra-Red-LED-IR-security-light-48-LEDs-Works-with-Raspberry-Pi-NoIR-camera-/131394656136">this</a> light which is compatible with the camera and IllumiPi.</p>

<p>It needs 12V to power it and I originally bought a battery pack for 8 AA batteries. More on this in the next section.</p>

<p>So I followed the instructions and when I finished plugging it all in, it looked like this, roughly: </p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/11/Untitled-Sketch_bb-1.png" alt=""></p>

<p>The black cables are ground and red live. The light and battery live cables actually join together on the breadboard.</p>

<p>You can see that the live cable plugs in the Pi at GPIO 24. This will become important when we do the code.</p>

<p>The way that I understand it works, is that the voltage regulator (that black thing) completes the circuit and is sort of a switch depending on if GPIO 24 is on or off.</p>

<p>Next I had to add code. </p>

<p><a href="https://antonydandrea.com/raspberry-pi-night-camera-part-1-motion-triggered-camera-and-clock/">Last week</a> I went through the code that uses the motion sensor to trigger the camera.</p>

<p>To this, I added the lights.</p>

<p>As I said above, the circuit is completed by the cable plugged into GPIO 24. So first I set this pin up for output:</p>

<pre><code>LIGHT_PIN = 24
GPIO.setup(LIGHT_PIN, GPIO.OUT)
</code></pre>

<p>Next, inside my while loop all I had to do, was turn the light pin on and then off:</p>

<pre><code>while True:
    if GPIO.input(PIR_PIN):
        filename = time.strftime("%d_%m_%Y_%H_%M_%S")
        GPIO.output(LIGHT_PIN, GPIO.HIGH)
        time.sleep(1)
        camera.capture('/home/pi/pic_'+filename+'.jpg')
        GPIO.output(LIGHT_PIN, GPIO.LOW)
        print "Picture Taken"
        time.sleep(3)
</code></pre>

<p>The key line here is:</p>

<pre><code>GPIO.output(LIGHT_PIN, GPIO.HIGH)
</code></pre>

<p>Which turns in on. And then after the picture is taken:</p>

<pre><code>GPIO.output(LIGHT_PIN, GPIO.LOW)
</code></pre>

<p>To turn it off.</p>

<p>I added a delay of 1 second in between turning it on and taking the picture as I found it took the picture too quickly after it was barely on.</p>

<p>Also it should be noted that the light array I am using has a built in sensor so that it won't switch on if it is too light around it.</p>

<p>And that is it! That is all it took to add the lights!</p>

<h6 id="poweringup">Powering Up</h6>

<p>As I previously mentioned, my biggest blocker was figuring out how to power everything without mains electricity.</p>

<p>The lights require its own 12 volts of power. I originally bought a pack that held 8 AA batteries to achieve this. But I was pretty disappointed with this solution as it was very big.</p>

<p>One of the reasons for doing this project with the Raspberry Pi Zero was because of its tiny size. The 8 AAs negated this.</p>

<p>Upon revisiting this project this year, however, I discovered that you could get a single, fairly small battery that provides the required power! They are called 23A batteries.</p>

<p>I bought <a href="https://www.ebay.co.uk/itm/131709599720">this</a> from E-Bay which also had the holder for it to plug in. I am delighted with how small it is!</p>

<p>The Pi itself, I am powering with a Lithium Ion battery. I bought <a href="https://shop.pimoroni.com/products/lipo-battery-pack?utm_medium=cpc&amp;utm_source=googlepla&amp;variant=20429082055&amp;gclid=Cj0KCQiAi7XQBRDnARIsANeLIesfbGgYmpjd7iY53wMqVCkwnqYeHbsix3mQ-S9UwhfiLEirZ3S_0AoaAuv3EALw_wcB">this one</a> from Pimoroni. I also bought the <a href="https://thepihut.com/products/zero-lipo?variant=36235929617&amp;gclid=Cj0KCQiAi7XQBRDnARIsANeLIetUKfFBQi8sp6uzGM1nmSSllyLFEGl7EydjSbkZ_ewU29szp2Oc9kQaApm1EALw_wcB#fo_c=1889&amp;fo_k=0b7f871a98630d153302407b46111263&amp;fo_s=gplauk">Zero LiPo</a> which provides the interface to plug it into the Raspberry Pi and is designed to be small enough to use with the Pi Zero. I had to also buy a charger for the battery so chose <a href="https://thepihut.com/products/adafruit-micro-lipo-w-microusb-jack-usb-liion-lipoly-charger-v1">this one</a>.</p>

<p>It would be nice if one day I figure out a way to have only one battery powering both AND the charger built in. But for now, this will do.</p>

<h6 id="summary">Summary</h6>

<p>So that's it really! The last thing to do is solder it altogether and find suitable housing for it. I may do another blog post in future to show the finished product and the results I got from it.</p>

<p>I funded a Kickstarter a while back to get this <a href="https://shop.pimoroni.com/products/protozero?utm_medium=cpc&amp;utm_source=googlepla&amp;variant=19382888071&amp;gclid=Cj0KCQiAi7XQBRDnARIsANeLIeuiu34apSbNKYW__JoYMTtB1wMsmmKoRy-w7ekHacjVCdsIIfLHaN0aAq7mEALw_wcB">protoboard</a> which will allow me to solder it all together and keep it small. As for the housing, it seems I will have to make some home made. We will see.</p>

<p>I am quite excited to finally get this finished in the next couple weeks! I hope the last couple of blog post have been enough to get you started on similar projects.</p>]]></content:encoded></item><item><title><![CDATA[Raspberry Pi Night Camera - Part 1: Motion Triggered Camera and Clock]]></title><description><![CDATA[How I created a motion night camera with a Pi Zero and other parts. Part one is just the camera, motion detector and clock.]]></description><link>https://antonydandrea.co.uk/raspberry-pi-night-camera-part-1-motion-triggered-camera-and-clock/</link><guid isPermaLink="false">6bd11e32-8ba2-4796-aaf1-0c775be84a63</guid><category><![CDATA[raspberry]]></category><category><![CDATA[pi]]></category><category><![CDATA[raspberry-pi]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 10 Nov 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p>About a year ago, I decided to try an build a night camera with my Raspberry Pi Zero that would be small and compact and take photos in the dark when triggered by a motion detector.</p>

<p>I hit a few challenges along the way and then some months went by without doing anything and now that we are back around to November, I decided to dust it off and give it another go.</p>

<h6 id="parts">Parts</h6>

<p><strong><a href="https://thepihut.com/products/raspberry-pi-zero?variant=14062725188">Raspberry Pi Zero</a></strong><br>
The center piece of this entire thing. It is basically a much smaller version of the standard Raspberry Pi with a size of 65mmx30mmx5mm. The trade off for this is that it is slightly less powerful in terms of processing power and you have to solder on your own pins, but the version that I bought introduced the camera slot which was crucial for this. They have since released a version that has built in Wi-Fi, but the version that I have doesn't.</p>

<p><strong><a href="https://thepihut.com/products/raspberry-pi-noir-camera-module">Pi Noir Camera Module</a></strong><br>
This is a Raspberry Pi compatible night vision camera. By night vision, I mean that it detects infra-red light (which is what we will use to light up the night instead of visible light). It works with any Raspberry Pi that has the camera port and the libraries for it are already installed on the OS.</p>

<p><strong><a href="https://thepihut.com/products/raspberry-pi-zero-camera-adapter">Raspberry Pi Zero Camera Adapter</a></strong><br>
As the Pi Zero is smaller, so is the camera port. For that reason, to use the above camera on a Pi Zero, you will need to buy this ribbon. The ribbon on the camera is easily interchangeable so that makes it very easy.</p>

<p><strong><a href="https://thepihut.com/products/pir-motion-sensor-module">PIR Motion Sensor Module</a></strong><br>
Finally, I used this motion sensor to trigger the camera. It requires no additional software and can provide input to the Raspberry Pi depending on whether it detects movement or not.</p>

<p><strong><a href="https://thepihut.com/products/mini-rtc-module-for-raspberry-pi">Mini RTC Module</a></strong><br>
This is not necessary for the camera itself but I wanted to make sure that the Pi had the correct time when I switched it on so that the photos have the correct timestamp. The Pi has no built in ability to keep the time when it is switched off. Instead, it uses the Internet to sync the clock when it boots up. As my camera will not have Internet access, this was not possible. This module is basically a clock with a battery built in that keeps the time. I then have to configure the Pi to use this time instead of its own.</p>

<h6 id="howtheyconnect">How they connect</h6>

<p>I tried to make a diagram to illustrate this but it took too long, so here is a an image of the pins on the Pi Zero and I will describe it to you (found <a href="https://othermod.com/wp-content/uploads/button.jpg">here</a>):</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/11/button.jpg" alt=""></p>

<p>This is actually an older version of the Pi that doesn't have the camera port.</p>

<p>The motion sensor has 3 inputs that I connected with jumper cables. The power input which was plugged into number 2 that provides 5 volts of power. The ground cable that completes the circuit, I plugged into number 6 (but could have plugged into any of the other ground pins). The data pin that actually provides input could be plugged into any of the GPIO pins but I plugged it into pin 19 which is GPIO 10 (this become relavant in the code).</p>

<p>The clock could have been conntected with jumper cables, but I plugged it directly onto the pins such that power plugged into port number 1 which provides 3 volts. It takes 5 pins (so 1, 3, 5, 7 and 9). Plugging into the board directly is a lot cleaner than 5 more cables.</p>

<p>Here is a photo of everything plugged in together:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/11/20171104_123841.jpg" alt=""></p>

<h6 id="thecode">The code</h6>

<p>Lets start with programming the motion sensor and camera. What I want is for the camera to take a photo when the detector detects movement.</p>

<p>You may already know that scripts in the standard Pi OS are generally written in Python and there is no exception here.</p>

<p>Here is the script and an explanation of each part:</p>

<pre><code>import RPi.GPIO as GPIO
import time
from picamera import PiCamera
</code></pre>

<p>So here, I am just importing some built in libraries that I will use later. The most notable one is the PiCamera.</p>

<pre><code>GPIO.setmode(GPIO.BCM)
</code></pre>

<p>You may have noticed from the above diagram that there are different ways of numbering the pins. This just sets it so that we use the GPIO numbers.</p>

<pre><code>PIR_PIN = 10
GPIO.setup(PIR_PIN, GPIO.IN)
</code></pre>

<p>Here, I am creating a variable that stores the GPIO pin number of the data input of the motion detector. If you remember earlier, I plugged it into GPIO 10. I then set up that pin to expect an input (rather than an output).</p>

<pre><code>try:

except KeyboardInterrupt:
    print "Quit"
    GPIO.cleanup()
</code></pre>

<p>The entire code will go within the try block. This is because it will run until I stop it with the keyboard. When I do that, the <code>KeyboardInterrupt</code> is detected and the program ends cleanly. <code>GPIO.cleanup()</code> is important as if I didn't do this, when I run the script again it will error as it attempts to reassign an already in use pin.</p>

<p>Within the try block have the following code.</p>

<pre><code>print "Motion Triggered Camera"
camera = PiCamera()
camera.exposure_mode = 'night'
time.sleep(2)
print "Ready"
</code></pre>

<p>The printing and sleeping is just for aesthetics (which won't be necessary when this program runs in the background). The important part here is that I am creating a new camera object and setting it to be in night mode.</p>

<pre><code>while True:
    if GPIO.input(PIR_PIN):
        filename = time.strftime("%d_%m_%Y_%H_%M_%S")            
        camera.capture('/home/pi/pic_'+filename+'.jpg')
        print "Picture Taken"
        time.sleep(3)
</code></pre>

<p>So I have a while loop as I want the program to keep working until I stop it. I have an if statement: <code>GPIO.input(PIR_PIN)</code>. So on every loop (which runs split seconds at a time) it will check if it received an input from the motion detector. If it did, it will run the code beneath it. If not, the loop will come round again and it will run the if statement again.</p>

<p>I supposed in <strong>theory</strong> there is a possibility that you could be detected in between the if statement failing and the next loop starting and not be captured, but this is hard, which is why there are delays when the picture is taken.</p>

<p>So I create a new file name using the current date and time.</p>

<p>I simply run the <code>capture</code> function passing it the full path to save the picture as a parameter. It really is that simple!</p>

<p>I added a 3 second delay otherwise I would be flooded with pictures if something passed by the camera. So for 3 seconds, it will not attempt to check the motion detector again.</p>

<p>And that's it really! With just a few lines of code, I was able to get a motion triggered camera up and running.</p>

<p>Now for the clock. This required a system setup rather than code. I used <a href="https://thepihut.com/blogs/raspberry-pi-tutorials/17209332-adding-a-real-time-clock-to-your-raspberry-pi">this tutorial</a> to set it up.</p>

<p>I won't copy and paste the instructions here. Go and check them out as they are pretty easy to follow. Once I had that, I was able to keep the correct time for the Pi even between power ups.</p>

<h6 id="summary">Summary</h6>

<p>So that is Phase 1 of my project complete. In reality I actually add to clock last but I changed the order for these blog posts. But you can see just how simple it was to add a simple detector.</p>

<p>Next time, I will talk about how I added infra red illumination as well as how I powered it all away from the mains!</p>]]></content:encoded></item><item><title><![CDATA[Crazy Programming Languages Challenge - Part 5 - Zombie]]></title><description><![CDATA[5th and final part of a series of posts where I look at and try out  esoteric programming languages. This week, it is Zombie.]]></description><link>https://antonydandrea.co.uk/zombie/</link><guid isPermaLink="false">3c1d61e4-4c9b-412f-8511-6a59dca517d7</guid><category><![CDATA[crazy-programming-challenge]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 03 Nov 2017 09:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Each week I have been taking on an unusual programming language and seeing what it is like to code in.</p>

<ol>
<li><a href="https://antonydandrea.com/brainfuck">Brainfuck</a>  </li>
<li><a href="https://antonydandrea.com/lolcode">LOLCODE</a>  </li>
<li><a href="https://antonydandrea.com/whitespace">Whitespace</a>  </li>
<li><a href="https://antonydandrea.com/piet">Piet</a>  </li>
<li><del>Malbolge</del><a href="https://antonydandrea.com/zombie">Zombie</a> &lt;- You are here</li>
</ol>

<p>This week was supposed to be Malbolge. I know that all these programming languages have had a degree of difficulty, that is almost a requirement of esoteric programming languages, but Malbolge was just a different level of difficulty. After many hours of studying it, I had to admit defeat and change the language for this final part.</p>

<p>You can have a go with this language yourself if you fancy a a challenge. Here are some links to get you started:</p>

<ul>
<li><a href="https://en.wikipedia.org/wiki/Malbolge">Wikipedia page with further links</a></li>
<li><a href="http://web.archive.org/web/20000815230017/http:/www.mines.edu/students/b/bolmstea/malbolge/">Archive copy of the official website</a></li>
</ul>

<p>I actually picked these 5 languages when I planned to do this series all those years ago and had the original draft saved all of this time. </p>

<p>Now I am changing this last one (regretfully to be honest), I decided to go with something to go with the spooky theme as it was Halloween on Tuesday - hence I have chosen Zombie.</p>

<h5 id="overview">Overview</h5>

<p>Zombie is an acronym that stands for Zombie-Oriented Machine-Being Interface Engine and is designed for evil necromancers to do evil things.</p>

<p>One important aspect is that it runs a multithreaded environment. This means multiple entities can run at the same time and in parallel.</p>

<p>Entities are structural units of code. They have different types such as zombies, ghosts, vampires and demons (and many more).</p>

<p>Each type has a slightly different behaviour and have slightly different commands to use them. We will only focus on the most basic type which is zombie.</p>

<p>Zombies are very straightforward: they run each task sequentially and don't start the next one until the previous one has finished.</p>

<p>Another example is Ghosts. These run tasks whenever they feel like it. They will eventually run all the tasks but there is an undetermined amount of time between them.</p>

<p>Full details of the different types and the commands that can be run can be found <a href="http://www.dangermouse.net/esoteric/zombie.html">here</a>. It is fairly straight forward to follow and so I don't want to just regurgitate what is written.</p>

<h5 id="installingandrunning">Installing and Running</h5>

<p>I am using this <a href="https://esolangs.org/wiki/User:Marinus/ZOMBIE_interpreter">interpreter</a> that is written in Python. I am not sure how closely it follows the language specification, but was very easy to use.</p>

<p>Simply copy the code into a new <code>.py</code>. Then in the terminal, run:</p>

<pre><code>python nameOfYourInterpreter.py zombieCodeFile.zom
</code></pre>

<p>I am not sure the <code>.zom</code> extension is actually needed, I just added that myself.</p>

<p>That is it. The code compiles and runs. Obviously, you will need to install Python on whatever machine you are working on. I will leave you to work that part out yourself.</p>

<h5 id="buildinghelloworld">Building "Hello, World!"</h5>

<p>First we declare our zombie and give it name:</p>

<pre><code>HelloWorld is a zombie
</code></pre>

<p>This is creating a zombie entity that will be run. Valid programs must declare at least one of these.</p>

<p>After declaring it, I then have to give it some "tasks". These are just like functions in normal programing languages.</p>

<p>The tasks are written inside a summon/animate pair:</p>

<pre><code>summon
    //tasks go here
animate
</code></pre>

<p>Summon and animate mark the beginning and end of an entities task list.</p>

<p>It also sets the current entity as being active if it is a zombie.</p>

<p>We will have one task for printing Hello, World! to the screen:</p>

<pre><code>task SayHello
    say "Hello, World!"
animate
</code></pre>

<p>As you can see, you have to use the task keyword follow by the name of the task to start it off. The end of the task is marked again with animate.</p>

<p>The actual code: <code>say "Hello, World!"</code> is pretty self explanatory and makes this very straightforward.</p>

<h5 id="summary">Summary</h5>

<p>I have barely scratched the surface with what you can do with this language (mostly because I ran out of time as I wasted quite a lot trying Malbolge). As I said before, more details of what can be done and what is allowed can be found <a href="http://www.dangermouse.net/esoteric/zombie.html">here</a>. It is fairly high level compared to some of the others I have played with and so you can probably create some decent programs.</p>

<p>That brings the end to this little mini-series. I am sorry for the sort of rushed ending but this series has been in drafts for a bout 4 years and so to have finally completed and published it is a great feeling. I hope that you enjoyed it as much as I did trying out these languages.</p>

<p>They have inspired me a little bit to perhaps have a go at creating my own...</p>]]></content:encoded></item><item><title><![CDATA[Crazy Programming Languages Challenge - Part 4 - Piet]]></title><description><![CDATA[Part 4 of a series of posts where I look at and try out  esoteric programming languages. This week, it is Piet.]]></description><link>https://antonydandrea.co.uk/piet/</link><guid isPermaLink="false">db47ff7e-af7d-493a-b1ad-90b39ac15df0</guid><category><![CDATA[crazy-programming-challenge]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 27 Oct 2017 08:00:00 GMT</pubDate><media:content url="http://antonydandrea.co.uk/content/images/2017/10/Screen-Shot-2017-10-24-at-09-51-26-1.png" medium="image"/><content:encoded><![CDATA[<ol>
<li><a href="https://antonydandrea.com/brainfuck">Brainfuck</a>  </li>
<li><a href="https://antonydandrea.com/lolcode">LOLCODE</a>  </li>
<li><a href="https://antonydandrea.com/whitespace">Whitespace</a>  </li>
<li><a href="https://antonydandrea.com/piet">Piet</a> &lt;- You are here  </li>
<li><del>Malbolge</del><a href="https://antonydandrea.com/zombie">Zombie</a></li>
</ol>

<h5 id="overview">Overview</h5>

<img src="http://antonydandrea.co.uk/content/images/2017/10/Screen-Shot-2017-10-24-at-09-51-26-1.png" alt="Crazy Programming Languages Challenge - Part 4 - Piet"><p>This is perhaps the most beautiful programming language that I have seen. In the words of its creator, <a href="http://www.dangermouse.net/esoteric/piet.html">David Morgan-Mars</a>, the code is "in the form of abstract art". It is named after <a href="https://en.wikipedia.org/wiki/Piet_Mondrian">Piet Mondrian</a>, a Dutch painter who pioneered abstract art. The language is created in pictures that look like his works. There are some fantastic examples that I recommend looking at <a href="http://www.dangermouse.net/esoteric/piet/samples.html">here</a>, where people have not only produced functioning programs, but also added the extra challenge of making them as artistic as possible.</p>

<p>Each "pixel" of an image is called a codel. This is a single unit of the image, which is not the same as literal pixels that an image would be made up of.</p>

<p>Codels make a colour block, which are "contiguous block of any number of codels of one colour". The can be any size and shape and only diagonal codels don't count as being contiguous.</p>

<p>There are 6 colours: yellow, green, cyan, blue, magenta, red each of which can be light, normal or dark, plus black and white.</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/piet.PNG" alt="Crazy Programming Languages Challenge - Part 4 - Piet"></p>

<p>Like Whitespace, this works using a stack which stores only integers that can be treated as numbers or Unicode character codes.</p>

<p>Commands are a little difficult to explain. They are created by the changes in colour and in lightness rather than the colours themselves. You can actually start with any colour and a command would be a number of steps from that colour to another colour.</p>

<p>For example, lets say a codel is green, the command for adding is one step along the colour cycle therefore I would use cyan to "add". If my first colour was red, the "add" command would be yellow. There is also a cycle with the darkness/lightness.</p>

<p>The order that I wrote the colours earlier is the order of the cycles.</p>

<p>There is a nice little table that has the main commands:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/edsfedsfewds.PNG" alt="Crazy Programming Languages Challenge - Part 4 - Piet"></p>

<p>It is a little confusing to get explain and to understand at first.</p>

<h5 id="installingandrunning">Installing and Running</h5>

<p>You there are no "official" tools for using this language, but there is a list of ones that people have made <a href="http://www.dangermouse.net/esoteric/piet/tools.html">here</a>. </p>

<p>I decided to use <a href="http://zobier.net/piet/">http://zobier.net/piet/</a> which is completly web based so it required no setup or installation:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/ghgf.PNG" alt="Crazy Programming Languages Challenge - Part 4 - Piet"></p>

<p>As you can see, it provides a nice little interface with all of the available colours and allows me to step through the execution.</p>

<p>Remember earlier I was talking about the colour cycle and how the colour of the command depends on the current colour - well, in the top right, you can see the available operations and what colour these should be.</p>

<h5 id="buildinghelloworld">Building "Hello, World!"</h5>

<p>This should be interesting.</p>

<p>My understanding is that the best way of doing this, like with previous languages, is to push the ASCII number to the stack, and then print it. But you can see that my editor is not very big and so doesn't allow for many commands to be run. "H" alone would take up 72 of the 100 squares.</p>

<p>So, I will just be printing "Hi!" and doing mathematical operations to save space (like I did with <a href="https://antonydandrea.com/brainfuck">Brainfuck</a>).</p>

<p>So the steps that my program will follow:</p>

<ol>
<li>Add 9 to the stack  </li>
<li>Add 8 to the stack  </li>
<li>Multiply the top two items of the tack (9 and 8) and put the result (72) there  </li>
<li>Print the top item of the stack as an ASCII character (H) </li>
</ol>

<p>The most complex part of this language is figuring out how it traverses across the colours. My initial attempts kept crashing the browser as it seemed that it was not as simple as just having adjacent colours.</p>

<p>Taken a starting colour, representing a number is simply colouring in that number of blocks with the same colour. If I want to store more than one number, then the next block has to be lighter than the previous.</p>

<p>So my program looks like this so far:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/Hi.PNG" alt="Crazy Programming Languages Challenge - Part 4 - Piet"></p>

<p>You can see I am starting with a dark green colour. I have a block of 9 squares. Next I have a block of 8 squares. This is lighter as light green is the next shade on the shade cycle described earlier. Next, is one block of the normal green.</p>

<p>It is is on the bottom right of the previous block because that is where I believe the pointer ends up. This tells the program to store the previous two numbers into the stack. If I kept cycling through the shades, I would have kept adding numbers.</p>

<p>The light blue is to multiply. It is light blue because, as in the table above, it is one step along the hue cycle from the previous colour.</p>

<p>Finally, we have a dark green to print the top of the stack as a character.</p>

<p>You can actually try this out yourself. If you go to the editor and paste the following into the box beneath the colours on the right hand side then click any colour, you will see it loaded:</p>

<p><code>10jjjhhtttttjjjhhtttttjjjhhtttttttthhikjtttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt</code></p>

<p>Word of warning, you should step through instead of play as this version of the program doesn't terminate so it crashes the browser.</p>

<p>So, I will continue with the other characters in the same way. I am able to start with any colour I like after I have printed, so I went with purple for <code>i</code> and then blue for <code>!</code>. Hopefully you can follow the program:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/Screen-Shot-2017-10-24-at-09-51-26.png" alt="Crazy Programming Languages Challenge - Part 4 - Piet"></p>

<p>You can run it yourself with:</p>

<p><code>10jjjhhtttttjjjhhtttttjjjhhtttttttthhikjttaaattttsssqpattttqqqomttttqqqqnnnnpttrrrnnnnpttrrttnnnpdecst</code></p>

<p>It traverses down the shades of purple which adds 3, 7 and 5 to the stack. The red block multiplies the first two numbers (5 and 7) and then the yellow multiplies the top two numbers again (35 and 3). Then the dark red prints the <code>i</code>.</p>

<p>Then we move onto the blue storing and multiplying 3 and 11. The black squares are used as a sort of flow control. It stops the pointer from going from the light pink to the green, but instead forces it to go left and then down to the last teal square.</p>

<p>The last teal square causes the program to ask for an input. I had difficulty correctly terminating the programming and I am not sure if it was because of a bug in the editor. This was a sort of hack that allowed me to just press play and reach the end.</p>

<p>You will see the output it produces:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/sadsafds.PNG" alt="Crazy Programming Languages Challenge - Part 4 - Piet"></p>

<h5 id="summary">Summary</h5>

<p>This was, by far, the trickiest language to get my head around of this challenge but also the most interesting. Producing a picture at the end is a pretty cool way of representing code and seeing the art that people had made from it was great!</p>

<p>Due to its complexity, I probably didn't do a very good job explaining it, so once again, here are some resources that I used:</p>

<ul>
<li><a href="http://www.dangermouse.net/esoteric/piet.html">The official website</a></li>
<li><a href="http://zobier.net/piet/">The editor</a></li>
<li><a href="http://homepages.vub.ac.be/~diddesen/piet/index.html">This blog post also gives a good walkthrough of the language</a></li>
</ul>

<p>Next week is the final part of this challenge and will be Malbolge.</p>]]></content:encoded></item><item><title><![CDATA[Crazy Programming Languages Challenge - Part 3 - Whitespace]]></title><description><![CDATA[Part 3 of a series of posts where I look at and try out  esoteric programming languages. This week, it is Whitespace.]]></description><link>https://antonydandrea.co.uk/whitespace/</link><guid isPermaLink="false">2dd4a515-f074-4ca2-acc4-3dbb66c38a5c</guid><category><![CDATA[crazy-programming-challenge]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 20 Oct 2017 08:00:00 GMT</pubDate><content:encoded><![CDATA[<p>For your enjoyment and my own, I am trying out some crazy programming languages:</p>

<ol>
<li><a href="https://antonydandrea.com/brainfuck">Brainfuck</a>  </li>
<li><a href="https://antonydandrea.com/lolcode">LOLCODE</a>  </li>
<li><a href="https://antonydandrea.com/whitespace">Whitespace</a> &lt;- You are here  </li>
<li><a href="https://antonydandrea.com/piet">Piet</a>  </li>
<li><del>Malbolge</del><a href="https://antonydandrea.com/zombie">Zombie</a></li>
</ol>

<p>This week, I am trying out Whitespace.</p>

<h5 id="overview">Overview</h5>

<p>Whitespace is a language designed as it says on the tin. The only characters that it contains are whitespaces: Space, Tab and Line Feed.</p>

<p>This means an entire program just looks like a blank document if you do not highlight it. It is also incredibly harder to program in as you quite literally can't see what you are doing.</p>

<p>It works using a stack and heap model. The commands involving putting things on top of the stack and interacting with those elements.</p>

<p>For example, SPACE-SPACE-NUMBER will put a number on the top of a stack. A number is represented as a binary string where SPACE is 0 and a TAB is 1.</p>

<p>Similar to Brainfuck, characters are represented in their ASCII number equivalent.</p>

<p>This [website](http://progopedia.com/language/whitespace/ <br>
) has a full list of commands available. I am not going to list them all out here.</p>

<h5 id="installingandrunning">Installing and Running</h5>

<p>It was actually very tricky to find the official resources for this program as a lot of links are now dead. Luckily, the Wayback Machine saved copies of the relevant web pages and I was able to obtain what I needed.</p>

<p>Here is a <a href="http://web.archive.org/web/20150717203521/http://compsoc.dur.ac.uk:80/whitespace/index.php">link</a> to the website stored on the web archive.</p>

<p>The compiler that I chose is on [Github here](https://github.com/hostilefork/whitespacers/tree/master/c <br>
). I chose this one because it was the most straightforward to set up. I was unable to get any of the official ones to work.</p>

<p>Once you download the C file, you will need to run:</p>

<pre><code>  gcc whitespace.c -o wspace
</code></pre>

<p>Then you can simply run:</p>

<pre><code> ./wspace /path/to/file.ws
</code></pre>

<p>Notice that I use the .ws extension to my whitespace file.</p>

<p>I recommend using Sublime to write this code as it is able to show tabs and spaces a little clearer. Just highlight the whole text and you will see the spaces are represented by <code>.</code> and the tabs represented by <code>-</code>:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/Screen-Shot-2017-10-17-at-06-51-53.png" alt=""></p>

<p>You can type normal text to annotate the code to make it easier to read, the compiler will simply ignore anything that is not whitespace.</p>

<h5 id="buildinghelloworld">Building "Hello, World!"</h5>

<p>Last week, LOLCODE was reasonably straightforward, so I was able to build something a little more complex than "Hello, World!". I tried to do this again, but I could not get input from the terminal to work correctly, so we are back to "Hello, World!".</p>

<p>It is a little easier than in Brainfuck as all you have to do is add the number to the top of the stack and then run the command for printing the top item.</p>

<p>So the first letter <code>H</code>, is ASCII number 72. To put it in the stack, it needs to be converted to binary first. 72 is: 01001000. The command is two spaces followed by a number where space is 0 and 1 is tab. Then it ends with a line feed. This would look like this:</p>

<pre><code>  {            }
;      
</code></pre>

<p>I have put in the  curly braces as nothing would show otherwise! I think it is safe to say that would easier if I represent everything with words:</p>

<pre><code>[SPACE][SPACE][SPACE][TAB][SPACE][SPACE][TAB][SPACE][SPACE][SPACE][LF]
</code></pre>

<p>To print the top of the stack, the code is:</p>

<pre><code>[TAB][LF]
[SPACE][SPACE]
</code></pre>

<p>It is incredibly tempting to add a new line each time you want to begin a new operation but it is important not to.</p>

<p>Storing the next letter, e, would begin straight after the previous <code>[SPACE]</code>.</p>

<p>So, if we continue this pattern of storing a letter to the top of the stack and then printing it, our code looks a little like this:</p>

<pre><code>[SPACE][SPACE][SPACE][TAB][SPACE][SPACE][TAB][SPACE][SPACE][SPACE][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][TAB][SPACE][SPACE][TAB][SPACE][TAB][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][TAB][SPACE][TAB][TAB][SPACE][SPACE][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][TAB][SPACE][TAB][TAB][SPACE][SPACE][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][TAB][SPACE][TAB][TAB][TAB][TAB][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][SPACE][TAB][TAB][SPACE][SPACE][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][SPACE][SPACE][SPACE][SPACE][SPACE][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][SPACE][TAB][SPACE][TAB][TAB][TAB][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][TAB][SPACE][TAB][TAB][TAB][TAB][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][TAB][TAB][SPACE][SPACE][TAB][SPACE][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][TAB][SPACE][TAB][TAB][SPACE][SPACE][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][TAB][SPACE][SPACE][TAB][SPACE][SPACE][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][SPACE][SPACE][SPACE][SPACE][TAB][LF]
[TAB][LF]
[SPACE][SPACE][SPACE][SPACE][SPACE][TAB][SPACE][TAB][SPACE][LF][TAB][LF]
[SPACE][SPACE][LF]
</code></pre>

<p>Try it out yourself by pasting it into a text editor and finding and replacing all of the characters (Note, however, I added newlines next to <code>[LF]</code> to visualise here correctly, so you would have to replace <code>[LF]\n</code>). When I run it, I successfully get the message:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/Screenshot-from-2017-10-18-05-52-06.png" alt=""></p>

<h5 id="summary">Summary</h5>

<p>A very tricky language to code in mostly because you can't see what you are doing. Other than the visual difficulties, it is not actually that hard to understand and there is plenty of built in operations that would allow for fairly complex programs to be built.</p>

<p>The other difficulty was also finding the resources to actually run the programs and learn the language. Once again, the resources that I used were:</p>

<ul>
<li><a href="http://web.archive.org/web/20150717203521/http://compsoc.dur.ac.uk:80/whitespace/index.php">Official documentation</a></li>
<li><a href="https://github.com/hostilefork/whitespacers/">Compilers in multiple languages on Github</a></li>
<li><a href="http://progopedia.com/language/whitespace/">Progopedia also has a good article on the language</a></li>
</ul>

<p>Next week, the challenge continues with <a href="https://antonydandrea.com/piet">Piet</a>.</p>]]></content:encoded></item><item><title><![CDATA[Crazy Programming Languages Challenge - Part 2 - LOLCODE]]></title><description><![CDATA[Part 2 of a series of posts where I look at and try out  esoteric programming languages. This week, it is LOLCODE.]]></description><link>https://antonydandrea.co.uk/lolcode/</link><guid isPermaLink="false">67cd6bdd-f682-47e8-889f-226e6813438d</guid><category><![CDATA[crazy-programming-challenge]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 13 Oct 2017 08:00:00 GMT</pubDate><content:encoded><![CDATA[<p>For your enjoyment and my own, I am trying out some crazy programming languages:</p>

<ol>
<li><a href="https://antonydandrea.com/brainfuck">Brainfuck</a>  </li>
<li><a href="https://antonydandrea.com/lolcode">LOLCODE</a> &lt;- You are here  </li>
<li><a href="https://antonydandrea.com/whitespace">Whitespace</a>  </li>
<li><a href="https://antonydandrea.com/piet">Piet</a>  </li>
<li><del>Malbolge</del><a href="https://antonydandrea.com/zombie">Zombie</a></li>
</ol>

<p>Last week I tried Brainfuck which was as bad as I thought. This week, LOLCODE.</p>

<h5 id="overview">Overview</h5>

<p>Unlike Brainfuck, LOLCODE is a little bit more like traditional programming languages in the way that it is written.</p>

<p>The full spec can be found <a href="https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md">here</a>. I am not going to cover everything written there here as does have a lot of substance.</p>

<p>The basic premise is that all of the keywords of the language are written like "Internet slang". So for example:</p>

<p>A new variable can be created like:</p>

<pre><code>I HAS A VAR
</code></pre>

<p>A comment can be written like:</p>

<pre><code>BTW this is a comment
</code></pre>

<p>An if-else statement could be written likes so:</p>

<pre><code>BOTH SAEM A [AN] B
O RLY?
    YA RLY
       VISIBLE "Hello"
    NO WAI
        VISIBLE "Goodbye"
OIC
</code></pre>

<p>It is actually quite funny seeing of the language constructs recreated in this language. As I said, I can't cover anything so even if you are not going to try the language, you may find it amusing to read the <a href="https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md">spec</a>.</p>

<h5 id="installingandrunning">Installing and Running</h5>

<p>Installing LOLCODE is actually very straightforward and the instructions for doing so are on the <a href="http://lolcode.org/">official website</a>:</p>

<pre><code>git clone https://github.com/justinmeza/lci.git
cd lci
cmake .
make &amp;&amp; make install
</code></pre>

<p>I had only 2 minor issues. I had to install <code>cmake</code> but that was simply <code>apt-get install cmake</code>. The other problem is that you have to be a sudoer to run make install otherwise you will get an error.</p>

<p>Once you have done this, that is it. You simply run <code>lci</code> and the name of the file (which doesn't have to have any particular extension) and it instantly compiles and runs.</p>

<h5 id="buildinghelloworld">Building "Hello, World!"</h5>

<p>Like last week, I was going to build the basic "Hello, World!" program however the website gave away the answer:</p>

<pre><code>HAI 1.2
    CAN HAS STDIO?
    VISIBLE "HAI WORLD!!!1!"
KTHXBYE
</code></pre>

<p>As you can see, it is also very simple.  It runs like so:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/lolcode-1.png" alt=""></p>

<p>So I decided to try a more complex program: A program to convert between Celsius and Fahrenheit.</p>

<p>It would work by taking an input from the user to decide the mode and then a number that they want to convert. It would then return an answer.</p>

<p>I start the code the same way as the "Hello, World" example above and then I have some variable declarations:</p>

<pre><code>  I HAS A conversion_type
  I HAS A conversion_label
  I HAS A opposite_conversion_label
  I HAS A temperature
</code></pre>

<p>These will all come into play later.</p>

<p>Next, I want the user to enter C to convert to Celsius or F to convert to Farenheit. I do not want the program to continue unless one of these two options have been entered.</p>

<p>So, I create a while loop. In LOLCODE, a while loop looks like this:</p>

<pre><code>IM IN YR label
    BTW code goes here
IM OUTTA YR label
</code></pre>

<p>So you specify a name for the loop and use the same name to close it. It is possible to set this to a condition, however I simply break out of it when I am done, so this is the equivalent of:</p>

<pre><code>while (true) { //code goes here }
</code></pre>

<p>Inside my while loop, I print two lines and wait for an input:</p>

<pre><code>VISIBLE "Press C to convert from Farenheit to Celsius"
VISIBLE "Press F to convert from Celsius to Farenheit"
GIMMEH conversion_type
</code></pre>

<p>Note the <code>GIMMEH</code> command here. This waits for the user to enter an input and then assigns that value into the variable that you give, in this case, <code>conversion_type</code>.</p>

<p>And so now I want to check this input and break out of the loop if it is a valid one. Otherwise, it will just continue asking and receiving.</p>

<p>And now we have the slightly confusing syntax of the conditional statements.</p>

<p>It goes like this:</p>

<pre><code>  BOTH SAEM conversion_type AN "C"
  O RLY?
  YA RLY
      conversion_label R "Farenheit"
      opposite_conversion_label R "Celsius"
      GTFO
  MEBBE BOTH SAEM conversion_type AN "F"
      conversion_label R "Celsius"
      opposite_conversion_label R "Farenheit"            
      GTFO
  OIC 
</code></pre>

<p>Lots of language constructs going on here.</p>

<p>The if statement starts of with a true or false expression. <code>BOTH SAEM</code> takes two things separated with an <code>AN</code> and returns <code>true</code> if they are equal. In this case I am checking if <code>conversion_type</code> is equal to <code>C</code>.</p>

<p>If-statements, start of with <code>O RLY?</code> and end with <code>OIC</code>.</p>

<p>The code within the <code>YA RLY</code> block is what is run if the previous expression is true. So in this case if <code>conversion_type</code> is <code>C</code>.</p>

<p>After this block, I another condition, this time starts with <code>MEBBE</code> and I am now checking if <code>conversion_type</code> is equal to <code>F</code>.</p>

<p>To sum-up the PHP equivilent to this statement would be:</p>

<pre><code>if ($conversion_type === "C") {

} elseif ($conversion_type === "F") {

}
</code></pre>

<p>With code within each block.</p>

<p>The code within each block is simply assigning the variables are initialised earlier with values using the <code>R</code> keyword.</p>

<p>Finally, conditional block ends with <code>GTFO</code> which is what breaks out of the loop that we are in.</p>

<p>Next, I want to get the value that the user wants to convert. This time, I am not going to perform any validation (although I wanted to check if it as a number but was unable to) so there is no need for a loop:</p>

<pre><code>  VISIBLE SMOOSH "Your choice: " conversion_type MKAY
  VISIBLE SMOOSH "Please enter a temperature in " opposite_conversion_label ": " MKAY
  GIMMEH temperature
</code></pre>

<p>Again, I am using <code>VISIBLE</code> and <code>GIMMEH</code> to perform output and input commands. You will also see <code>SMOOSH</code> and <code>MKAY</code>. This is basically string concatenation. I am providing a list of space separated strings that are getting "smooshed" together.</p>

<p>Now that I have a value, I want to run a function. So I have another if statement:</p>

<pre><code>I HAS A answer
BOTH SAEM conversion_type AN "C"
O RLY?
   YA RLY
       answer R I IZ farenheitToCelsius YR temperature MKAY
  MEBBE BOTH SAEM conversion_type AN "F"
       answer R I IZ celsiusToFarenheit YR temperature MKAY
OIC
</code></pre>

<p>Above, I first create another variable for to store the answer and I also have another conditional statement identical to the one earlier.</p>

<p>Then you can see this line:</p>

<pre><code>answer R I IZ farenheitToCelsius YR temperature MKAY
</code></pre>

<p>The first part is easy, <code>answer R</code> is storing whatever is about to happen into the <code>answer</code> variable. Next, we see how a function is called:</p>

<pre><code>I IZ functionName YR param1 param2 MKAY
</code></pre>

<p>You can have as many parameters as you like, we only have the one in our case. This works exactly as you would expect functions to work in terms of how they scope variables and how you return them.</p>

<p>One thing to note is that you have to have the function created BEFORE you used it, unlike languages like PHP where the function only has to be within the scope and the order doesn't matter.</p>

<p>So I have the function written near the beginning of the function:</p>

<pre><code>HOW IZ I farenheitToCelsius YR temperature
    BTW C=(F-32)x5/9
    temperature IS NOW A NUMBAR
    I HAS A answer ITZ QUOSHUNT OF PRODUKT OF 5 AN DIFF OF temperature AN 32 AN 9
    FOUND YR answer
IF U SAY SO
</code></pre>

<p>Functions start with declaring the name and the parameters as you see here and end with <code>IF U SAY SO</code>.</p>

<p>Inside the function itself, you can see I have a little comment of the formula that I need using the syntax for comments, <code>BTW</code>.</p>

<p>I then do <code>temperature IS NOW A NUMBAR</code>. I had to do this to make sure that the parameter is treated as a floating point decimal. Otherwise, if the user gives a whole number, it would be cast as an integer and the calculation would round it.</p>

<p>Next I create a variable and assign it a value in one go: <code>I HAS A answer ITZ</code>, whatever comes after <code>ITZ</code> would be assigned to <code>answer</code>.</p>

<p>Then I use the mathematical functions made available to me to perform the calculations (these are all outlined in the <a href="https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md">documentation</a>). There is no brackets and the functions tend to be structured like:</p>

<pre><code> F x AN y
</code></pre>

<p>So, </p>

<pre><code>QUOSHUNT OF PRODUKT OF 5 AN DIFF OF temperature AN 32 AN 9
</code></pre>

<p>written in English pseudocode is:</p>

<pre><code>division (multiply(5, subtract(temperature, 32)), 9)
</code></pre>

<p>It is a little confusing at first to structure it in this slightly different way.</p>

<p>Finally, the function returns the answer with the line:</p>

<pre><code>FOUND YR answer
</code></pre>

<p>The celsiusToFarenheit counterpart is structured in the exact same way just with a different formula.</p>

<p>Now I have returned from my function, I output the answer:</p>

<pre><code>VISIBLE SMOOSH "The temperature in " opposite_conversion_label " is " answer ". " MKAY
</code></pre>

<p>And thats it!</p>

<p>So if I run the program, this is how it looks:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/Screenshot-from-2017-10-07-18-42-38.png" alt=""></p>

<h5 id="summary">Summary</h5>

<p>There we have it. LOLCODE was actually a lot easier than Brainfuck last week because it was actually a lot closer to the sort of programming that I am used to (albeit with an unusual syntax) and therefore building a more complex program that actually does something useful, was easy. </p>

<p>Again, documentation for this can be found <a href="https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md">here</a>. Next week, I fear it will not be as easy as we go onto <a href="https://antonydandrea.com/whitespace">Whitespace</a>!</p>]]></content:encoded></item><item><title><![CDATA[Crazy Programming Languages Challenge - Part 1 - Brainfuck]]></title><description><![CDATA[Part 1 of a series of posts where I look at and try out  esoteric programming languages. This week, it is Brainfuck.]]></description><link>https://antonydandrea.co.uk/brainfuck/</link><guid isPermaLink="false">79a411fa-9dcb-4492-ac30-9d79e8f44ec8</guid><category><![CDATA[crazy-programming-challenge]]></category><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 06 Oct 2017 08:00:00 GMT</pubDate><content:encoded><![CDATA[<p>I have been wanting to do this challenge for so long! The time has finally come.</p>

<p>Wikipedia, the fountain of all human knowledge, has a very long list of programming languages.</p>

<p>They also have a list of programming languages that are "esoteric" (nope, I have not hear of that word either until now). These are languages that are less conventional than the mainstream programming languages.</p>

<p>For your enjoyment and my own, I decided to go down this list and pick out five try:</p>

<ol>
<li><a href="https://antonydandrea.com/brainfuck">Brainfuck</a> &lt;- You are here  </li>
<li><a href="https://antonydandrea.com/lolcode">LOLCODE</a>  </li>
<li><a href="https://antonydandrea.com/whitespace">Whitespace</a>  </li>
<li><a href="https://antonydandrea.com/piet">Piet</a>  </li>
<li><del>Malbolge</del><a href="https://antonydandrea.com/zombie">Zombie</a></li>
</ol>

<p>Each week I will post my experience of 1 of these languages.</p>

<p>Today I kick it all off with Brainfuck.</p>

<h5 id="overview">Overview</h5>

<p>I started with this post to help familiarise myself with the basics of Brainfuck. The language itself is really rather simple.</p>

<p>There an internal array, kind of like a tape, with 30,000 cells. There is a pointer that points to cell number 1 when the program starts. Each cell can contain a number and hold up to 1 byte of data.</p>

<p>There are just 8 commands that you can do:</p>

<p><code>&lt;</code> and <code>&gt;</code>  move the internal pointer left or right of the current cell.</p>

<p><code>+</code> increments the current cell's value by 1. <code>-</code> decrements by 1.</p>

<p><code>.</code> prints the content of the current cell as an ASCII character.</p>

<p><code>,</code> reads a single input into the current cell (I did not try this and so am not sure of its behaviour).</p>

<p>Then you have <code>[</code> and <code>]</code>. These enable looping. If the value of the current cell is 0 when it reaches <code>[</code>, it will skip to the corresponding <code>]</code>. Otherwise, it will go to the next instruction within the block. If the current cell has 0 when it reaches <code>]</code>, it will exit the the loop to the next instruction, otherwise, it will return to the corresponding <code>[</code>. This is essentially a while loop but it can be confusing when thinking of the current position of the tape and the values in them (which is a running theme).</p>

<p>So overall, every character that is not <code>&gt;&lt;+-.,[]</code>, is ignored. This includes all white space and any comments that you may write outside of the program.</p>

<h5 id="installingandrunning">Installing and Running</h5>

<p>I decided to use this compiler to run my code because it appeared to be the most straightforward to set and use. Go to the link and save the page as a .asm file.</p>

<p>You will then need to install nasm:</p>

<pre><code>sudo apt install nasm
</code></pre>

<p>Next run:</p>

<pre><code>sudo nasm -f bin -o bf /path/to/bf.asm &amp;&amp; sudo chmod +x bf
</code></pre>

<p>This will compile the file you just downloaded and enable you to execute it. You simply have to run ./bf from the directory you put it.</p>

<p>Now to run our first program.</p>

<p>The article that I linked gave a great simple example of a program:</p>

<pre><code>++++++ [ &gt; ++++++++++ &lt; - ] &gt; +++++ .
</code></pre>

<p>What this does is print the letter "A".</p>

<p>How?</p>

<p>The internal pointer begins in position 1. The increments the value in that cell by 1 6 times, therefore we get the value, 6, in the first cell.</p>

<p>Then we have a loop inside the square brackets. The loop starts by going to position 2, and then incrementing by 10. It then goes back to position 1 and decrements once.</p>

<p>So after the first iteration, our tape looks like this (the * shows the position of the pointer):</p>

<pre><code>| 1 | 2  | 3 | 
| 5 | 10 | 0 |
| * |    |   |
</code></pre>

<p>It then goes back to the beginning of the loop and starts the whole thing again: go to position 2, increment by 10, go back to position 1, decrement by 1.</p>

<p>The loop continues until it sees 0 in the current cell that it is in at the end of the block (at the closing <code>]</code>). In this case, it is when position 1 has 0 in it. The tape would look like this:</p>

<pre><code>| 1 | 2  | 3 | 
| 0 | 60 | 0 |
| * |    |   |
</code></pre>

<p>The final part put the pointer into position 2, and increments by 4. So now we have:</p>

<pre><code>| 1 | 2  | 3 | 
| 0 | 64 | 0 |
|   | *  |   |
</code></pre>

<p>64 happens to be the ASCII character code for the letter A. The very final thing, the . , prints what ever the pointer is on. In this case it is in position 2 and therefore the letter A is shown.</p>

<p>This could have been done equally with just 64 <code>+</code>s and a <code>.</code>. But this other solution demonstrates the level of think that you need to create readable programs. Also note that the spaces are ignored and are not needed.</p>

<p>To compile and run the code is simple. First the compiler command is:</p>

<pre><code>/path/to/bf &lt; /path/to/hello.b &gt; /path/to/hello &amp;&amp; chmod +x /path/to/hello
</code></pre>

<p>The part after <code>&amp;&amp;</code> ensure that the program has the correct privileges to be executed.</p>

<p>So running all this:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/A.png" alt=""></p>

<p>Easy.</p>

<h5 id="buildinghelloworld">Building "Hello, World!"</h5>

<p>I want to have to console print "Hello, World!" with the correct punctuation. So using the earlier example as a model, I first need to convert each character into ASCII number and then print them to the screen after generating.</p>

<p>The number that I need are</p>

<pre><code>72 101 108 108 111 44 32 87 111 114 108 100 33
</code></pre>

<p>So, lets start with 72:</p>

<pre><code>++++++++ [ &gt; +++++++++ &lt; - ] &gt; .
</code></pre>

<p>This has the exact same logic as when we printed A. The difference is that since 72 is exactly 8 x 9, we do not have to do the extra adding once the loop is finished. If I run this, I see H printed onto the screen.</p>

<p>My tape now looks like this:</p>

<pre><code>| 1 | 2  | 3 | 
| 0 | 72 | 0 |
|   |  * |   |
</code></pre>

<p>So now I do the next number, 101:</p>

<pre><code>&lt; ++++++++++ [ &gt;&gt; ++++++++++ &lt;&lt; - ] &gt;&gt; + .
</code></pre>

<p>As you can see, I use position 1 as my counter and position 3 to store 101. So now my tape looks like this:</p>

<pre><code>| 1 | 2  | 3   | 4 | 
| 0 | 72 | 101 | 0 |
|   |    | *   |   |
</code></pre>

<p>Next line, 2 ls:</p>

<pre><code>&lt;&lt; +++++++++ [ &gt;&gt;&gt; ++++++++++++ &lt;&lt;&lt; - ] &gt;&gt;&gt; ..
</code></pre>

<p>Same as before but with more arrows going between spaces as I move further down the tape. Also, you can see that I do 2 <code>.</code>s as I print the same letter twice in a row.</p>

<p>I kept going with this same logic until I had something like this:</p>

<pre><code>&lt;&lt; +++++++++ [ &gt;&gt;&gt; ++++++++++++ &lt;&lt;&lt; - ] &gt;&gt;&gt; ..
&lt;&lt;&lt; ++++++++++ [ &gt;&gt;&gt;&gt; ++++++++++ &lt;&lt;&lt;&lt; - ] &gt;&gt;&gt;&gt; +++++++++++ .
&lt;&lt;&lt;&lt; +++++++++++ [ &gt;&gt;&gt;&gt;&gt; ++++ &lt;&lt;&lt;&lt;&lt; - ] &gt;&gt;&gt;&gt;&gt; .
&lt;&lt;&lt;&lt;&lt; ++++ [ &gt;&gt;&gt;&gt;&gt;&gt; ++++++++ &lt;&lt;&lt;&lt;&lt;&lt; - ] &gt;&gt;&gt;&gt;&gt;&gt; .
&lt;&lt;&lt;&lt;&lt;&lt; ++++++++ [ &gt;&gt;&gt;&gt;&gt;&gt;&gt; +++++++++++ &lt;&lt;&lt;&lt;&lt;&lt;&lt; - ] &gt;&gt;&gt;&gt;&gt;&gt;&gt; - .
&lt;&lt;&lt; . &gt;&gt;&gt;&gt;
</code></pre>

<p>The last line is the "o" in "World". As I have this stored previously, I simply move the pointer back to that position, print, then move it back again.</p>

<p>This is where it went wrong for me. As you can see, it is very easy to lose track of the where you are on the tape. Especially if you are going backwards and forwards.</p>

<p>Then I realised I was being silly. I did not need to store every single letter after I had printed them, only the ones that I want to reuse. So I only need to use 3 or 4 cells at most.</p>

<p>So I started again:</p>

<pre><code>++++++++ [ &gt; +++++++++ &lt; - ] &gt; . [-]
</code></pre>

<p>We are back to printing the letter H again. But you can see that I added <code>[-]</code> after I have printed. This effectively clears the current cell to 0 (remember the loop keeps going until the current cell at the <code>]</code> is 0). So at this point, the tape looks like this:</p>

<pre><code>| 1 | 2 | 3 | 4 | 
| 0 | 0 | 0 | 0 |
|   | * |   |   |
</code></pre>

<p>So, if we get to the "ll" again:</p>

<pre><code>++++++++ [ &gt; +++++++++ &lt; - ] &gt; . [-] 
</code></pre>

<p>&lt; ++++++++++ [ > ++++++++++ &lt; - ] > + .[-]
   &lt; +++++++++ [ > ++++++++++++ &lt; - ] > ..</p>

<p>So you can see for "e" we do exactly the same as the "H": get the number, print, then clear. For the "ll", we once again print twice. But as we want to reuse that letter later, we do not clear. So the next line:</p>

<pre><code>&lt; ++++++++++ [ &gt;&gt; ++++++++++ &lt;&lt; - ] &gt;&gt; +++++++++++ .
</code></pre>

<p>Puts "o" into position 3:</p>

<pre><code>| 1 | 2   | 3   | 4 | 
| 0 | 108 | 111 | 0 |
|   |     | *   |   |
</code></pre>

<p>Again, we want to keep "o" for later, so I don't clear it and use position 4 for the other letters:</p>

<pre><code>&lt;&lt;&lt; ++++ [ &gt;&gt;&gt; ++++++++ &lt;&lt;&lt; - ] &gt;&gt;&gt; . [-]
&lt;&lt;&lt; ++++++++ [ &gt;&gt;&gt; +++++++++++ &lt;&lt;&lt; - ] &gt;&gt;&gt; - . [-]
</code></pre>

<p>At this point, we are printing:</p>

<pre><code>Hello, W
</code></pre>

<p>And the tape looks like this:</p>

<pre><code>| 1 | 2   | 3   | 4 | 
| 0 | 108 | 111 | 0 |
|   |     |     | * |
</code></pre>

<p>For the next letter, "o", we only need to go back to position 3 and print what is there. Also, we no longer need to store this letter so we can clear it and work in this cell:</p>

<pre><code>&lt; . [-]
</code></pre>

<p>So now we have</p>

<pre><code>Hello, Wo
</code></pre>

<p>and the tape:</p>

<pre><code>| 1 | 2   | 3 | 4 | 
| 0 | 108 | 0 | 0 |
|   |     | * |   |
</code></pre>

<p>So we carry on working in the 3rd cell, using cell 1 as the counter, the next letter is "r":</p>

<pre><code>&lt;&lt; ++++++++++ [ &gt;&gt; +++++++++++ &lt;&lt; - ] &gt;&gt; ++++ . [-] 
</code></pre>

<p>Now we are ready for "l" again. So as we are position 3, and "l" is stored in position 2, we simply have to go back 1 and print:</p>

<pre><code>&lt; . [-]
</code></pre>

<p>I no longer need this letter, so I can clear it and keep working here for the last 2 letters:</p>

<pre><code>&lt; ++++++++++ [ &gt; ++++++++++ &lt; - ] &gt; .[-]
&lt; +++ [ &gt; +++++++++++ &lt; - ] &gt; .[-]
</code></pre>

<p>So if I now run this:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/10/hello-world.png" alt=""></p>

<p>Woo!</p>

<h5 id="summary">Summary</h5>

<p>So the overall program is like this:</p>

<pre><code>++++++++ [ &gt; +++++++++ &lt; - ] &gt; . [-] 
&lt; ++++++++++ [ &gt; ++++++++++ &lt; - ] &gt; + .[-]
&lt; +++++++++ [ &gt; ++++++++++++ &lt; - ] &gt; ..
&lt; ++++++++++ [ &gt;&gt; ++++++++++ &lt;&lt; - ] &gt;&gt; +++++++++++ .
&lt;&lt;&lt; ++++ [ &gt;&gt;&gt; ++++++++ &lt;&lt;&lt; - ] &gt;&gt;&gt; . [-]
&lt;&lt;&lt; ++++++++ [ &gt;&gt;&gt; +++++++++++ &lt;&lt;&lt; - ] &gt;&gt;&gt; - . [-]
&lt; . [-]
&lt;&lt; ++++++++++ [ &gt;&gt; +++++++++++ &lt;&lt; - ] &gt;&gt; ++++ . [-] 
&lt; . [-]
&lt; ++++++++++ [ &gt; ++++++++++ &lt; - ] &gt; .[-]
&lt; +++ [ &gt; +++++++++++ &lt; - ] &gt; .[-]
</code></pre>

<p>Remember, the spaces and newlines are for us only. This could be minified to a single line.</p>

<p>There is also a much better written version of "Hello, World!" on the <a href="https://en.wikipedia.org/wiki/Brainfuck">Wikipedia page</a> that makes mine look terrible!</p>

<p>I found it to be an interesting challenge to think in terms of a tape and realising that we don't have to store everything once it is outputted to the screen. </p>]]></content:encoded></item><item><title><![CDATA[Building a Basic Web Server in Node.js]]></title><description><![CDATA[Basic guide on how to build a simple web server in Node.js.]]></description><link>https://antonydandrea.co.uk/building-a-basic-web-server-in-node-js/</link><guid isPermaLink="false">48f97b5f-e08c-4a75-926f-9434668729c2</guid><dc:creator><![CDATA[Antony D'Andrea]]></dc:creator><pubDate>Fri, 29 Sep 2017 08:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Node.js is a runtime that can be used to execute javascript code outside of the browser. I have been wanting to look into it for a while now and especially it's place in the MEAN stack (a web stack that is entirely javascript based).</p>

<p>I have the book, <a href="http://shop.oreilly.com/product/0636920026013.do">Node.js for PHP Developers, by Daniel Howard</a>, which is designed to help PHP developers, like myself, get to grips with Node.js by translating the concepts from  one language to the next.</p>

<p>In the post, I will go over the very basic "Hello, World" web server example.</p>

<h5 id="installation">Installation</h5>

<p>As a Windows user, I often have difficulty setting up development environments and usually resort to using an Ubuntu VM. But in this case, it is actually very easy.</p>

<p>If you go to the <a href="https://nodejs.org">nodjs.org</a> website, you can find an installer that will set everything up.</p>

<p>You can then, in command prompt, run the command <code>npm</code> or <code>node</code> without any further issues!</p>

<h4 id="nodejsserver">Node.js Server</h4>

<p>Unlike PHP, node.js doesn't run on a web server. If you want to use it for a web system, then you must build a web server using it!</p>

<p>The following is boiler-plate code for a very basic node.js server:</p>

<pre><code>var http = require('http');

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337');
</code></pre>

<p>So what is it doing?</p>

<p>The first line demonstrates one of the biggest strengths of node.js: the availability and ease of loading of pre-existing modules. In this case, we are loading the module, <code>http</code>, which will provide the functionality that we need.</p>

<p>Next, we use the <code>createServer</code> function from the <code>http</code> module. This accepts a function as it's parameters that is the web server itself. This function accepts two parameters: request and response.</p>

<p>Inside this function, we do two things: we give the response object a header which gives it a 200 OK status and that the content we are returning is plain text. We then give the content, which is a hard coded string. So, anyone who hits this server will be given a plain text string: "Hello World!"  and a 200 OK HTTP status.</p>

<p>The function, <code>createServer</code> then returns the server object with our functionality installed. On the last line, you can see that I call the <code>listen</code> function which tells the server to listen to requests coming to "<a href="http://127.0.0.1:1337">http://127.0.0.1:1337</a>".</p>

<p>Finally, I have a console log just to show that we got there.</p>

<p>So, if I run this using <code>note ws.js</code> (where <code>ws.js</code> is the name of the file with the above code):</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/09/Capture2.PNG" alt=""></p>

<p>You can see that it prints the log, but also the process doesn't end as the server is now running.</p>

<p>I can then hit the address "<a href="http://127.0.0.1:1337">http://127.0.0.1:1337</a>" in my favourite web browser and I see:</p>

<p><img src="https://antonydandrea.co.uk/content/images/2017/09/Capture.PNG" alt=""></p>

<p>A working response.</p>

<h5 id="summary">Summary</h5>

<p>Obviously this is a very simplistic example of a node.js web server and a very simple use for node.js as a language. But it is a great start to get experimenting with! Good luck!</p>]]></content:encoded></item></channel></rss>