Category: Code

Adding Push Notifications to your Parse Server App

I was originally going to write about how to use node.js to enable push notifications, but the latest version of Parse Server now includes basic push notification support using Google Cloud Messaging (GCM) for Android devices and Apple Push Notification Service (APNS) for iOS devices.

Instead, I decided to write about how to enable the built-in push notifications in your Parse Server apps using the updated service.

There are already guides out there on this, but I wanted to put as much information as I could in one place, rather than clicking through to various sources.


Getting Started

This post assumes you previously set up a Parse Server install on Heroku, so some steps will make more sense if you’ve followed that tutorial as well.

To get started, you’ll need your credentials to both GCM and APNS in order to send push notifications to iOS and Android devices.

Preparing your APNS (iOS) credentials

Preparing your Apple Push Notification Service credentials is actually the longest, most detailed part of this post. There are a few steps to follow so I’ll keep them as quick and as short as I can (by the way, if your app is Android only, then you can skip this step obviously):

  1. Log in to the Apple Developer Member Center and click on identifiers under iOS Apps and locate your application in the list.
  2. If you haven’t registered an App Id yet, then click the + symbol and fill out the form, _make sure you check the Push Notifications checkbox.
  3. Click Settings or Edit to continue.
  4. Choose either the Development or Production certificate option and click Create Certificate.
  5. Follow the instructions in the Add iOS Certificate Assistant and click continue.
  6. Using the Certificate Signing request that was just created, generate the APNS Push SSL certificate.
  7. When the Download button appears, you can download your certificate(s). you may need to reload the page for this to update.
  8. Open the download certificate, this will open in the Keychain Access app.
  9. You should see your certificate under My Certificates. If you don’t then check Certificates and it may be there instead.
  10. The final step is to export your certificate as a .p12 file.
    1. Select the certificate that was just added to Keychain Access and select File -> Export Items... from the menu. _Make sure you have select My Certificates from the category menu on the lower left-hand side, if it’s not highlighted then you will not be able to export the certificate as a .p12 file.
    2. When saving the file, use the Personal Information Exchange (.p12) format.
    3. Create a folder in your parse server app called certs and copy the file there.

Ok, you’ve got your .p12 file, we’ll use this shortly to configure push notifications, now onto setting up your GCM credentials.

Preparing your GCM (Android) credentials

Google Cloud Messages is a lot easier to configure than APNS was (by the way, if your app is iOS only then you can skip this step obviously):

  1. Enable GCM for your Android project in the Google Developer Console. This will give you your GCM sender ID, which is your project number. The project number should be a large integer like 129437206252.
  2. Go to the Google developer credentials page, and create a new API key. This API key is your GCM API key.

Configuring Your Parse Server App to Push

Now that we’ve gotten our credentials, we need to update our app to use them.

Let’s look at the config we used in our last post about Parse Server:

var api = new ParseServer({
    databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
    cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
    appId: 'MYAPPID',
    clientKey: 'myclientKey',
    masterKey: 'myMasterKey'
});

First, make sure you run npm install --save parse-server@latest to update your app to the latest version of Parse Server.

Also, you will need to make sure you set the masterKey as that is necessary for sending push notifications from your app via API calls.

Ok, let’s add the new push configuration:

var api = new ParseServer({
    databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
    cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
    appId: 'MYAPPID',
    clientKey: 'myclientKey',
    masterKey: 'myMasterKey',
    push: {
        android: {
            senderId: '', // The Sender ID of GCM
            apiKey: '' // The Server API Key of GCM
        },
        ios: {
            pfx: 'certs/mycert.p12', // the path and filename to the .p12 file you exported earlier.
            cert: '', // If not using the .p12 format, the path to the certificate PEM to load from disk
            bundleId: '', // The bundle identifier associated with your app
            key: '', // If not using the .p12 format, the path to the private key PEM to load from disk
            production: true // Specifies which environment to connect to: Production (if true) or Sandbox
        }
    }
});

Configuring Your Parse Apps to use Parse Server

To update your iOS and / or Android apps to use Parse Server instead of Parse, all you have to do is change the server URL to your installation.

Make sure you update to the latest versions of the SDKs so that you have support for Parse Server.

For example, if you followed the previous post about installing Parse Server on Heroku, then you would point your apps to use: https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com where NAME_OF_YOUR_HEROKU_APP is the name of your heroku app you created.

Configuring your iOS apps

[Parse initializeWithConfiguration:[ParseClientConfiguration configurationWithBlock:^(id<ParseMutableClientConfiguration> configuration) {
    ...
    configuration.applicationId = @"MYAPPID";
    configuration.clientKey = @"myclientKey";
    configuration.server = @"https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse";
    ...
}]];

Configuring your Android apps

Parse.initialize(new Parse.Configuration.Builder(myContext)
    .applicationId("MYAPPID")
    .clientKey("myclientKey")
    .server("https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse")
    ...
    .build()
);

You should also update your app so that it registers for GCM with both Parse’s GCM sender ID and your app’s GCM sender ID. To do this, specify the additional GCM sender ID with the following <meta-data> tag as a child of the <application> element in your app’s AndroidManifest.xml.

For example:

<meta-data
    android:name="com.parse.push.gcm_sender_id"
    android:value="id:YOUR_SENDER_ID" />;

Viewing Installations

Once you’ve configured and updated your apps, you’ll be able to see installations using this curl command:

curl -X GET \
    -H "X-Parse-Application-Id: MYAPPID" \
    -H "X-Parse-Master-Key: myMasterKey" \
    https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse/installations

This will show you how many people have your app installed.

Sending Push Notifications

I know, this was the entire reason you read this far, you want to know how to send push notifications correct? I thought so.

Currently, Parse Server can only send push notifications using API requests with your master key. So, for example:

curl -X POST \
    -H "X-Parse-Application-Id: MYAPPID" \
    -H "X-Parse-Master-Key: myMasterKey" \
    -H "Content-Type: application/json" \
    -d '{
        "where": {
            "deviceType": { "$in": [ "ios",  "android"  ]  }
        },
        "data": {
            "title": "Ant-man",
            "alert": "This is awesome. It is awesome."
        }
    }' \
    https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse/push

Will send a push notification to all registered ios or android devices. Push notifications are formatted as title and alert with alert being the actual message.

Push notifications can also be sent from cloud code:

Parse.Push.send({
    where: {
        "deviceType": { "$in": [ "ios",  "android"  ]  }
    },
    data: {
        "title": "Ant-man",
        "alert": "This is awesome. It is awesome."
    }
}, { useMasterKey: true });

You can now do push notifications to your iOS and Android apps!


Closing Out

Hopefully, this guide will be useful for seeing how to add push notifications to your Parse Server apps. Parse Server is shaping up to be a handy utility so it’s fun to look at the various pieces of it.

In a future post, I’ll show you how to integrate a proper job queue which can then take trigger notifications based on certain criteria, such as a new message notification in a chat room that a user has subscribed to, for example.

Getting Started with Parse Server, Heroku and MongoLabs

Last week, Parse announced they would be shutting down their hosting by January 28th 2017, and like just about every other developer out there, I immediately started playing around with their open sourced Parse Server, and setting it up on Heroku.

For the record, I actually host most of my apps on Flybase (for data), Github Pages or S3 (for frontend) and Heroku for quick node.js apps. I also use Digital Ocean or AWS EC2 for other hosting, but I wanted to demonstrate how to quickly host Parse Server on Heroku first, I’ll show how to set Parse Server up on Digital Ocean and AWS EC2 later in other posts.

Parse Server is actually a pretty nicely written library, and I’ve even forked it to include Flybase support instead of Mongo, as well as having a version that supports multiple apps in one install, but today we’ll look at simply getting Parse Server running on Heroku.


Some Background

Until this week, if you were a Parse user, then you did not need to know how your client side code interacted with your Parse database, and even now, you just need a vague understanding of how it works.

But, there is a lot happening behind the scenes when you host your own Parse Server. So, now that you are going to be hosting it yourself, you should understand how some of it works.

First of all, most of the more difficult work is handled inside the Client side library, and then sent to the server side code as HTTP requests. None of this changes, the only change is where you talk to Parse rather than how you talk to Parse.

That means that all you have to keep in mind when explaining how your self-hosted Parse Server works will be these three sections:

  1. Client code from which you make requests to the server
  2. Server-side code that receives and processes these requests
  3. A Database where the server-side code stores and retrieves data from.

Previously, Parse took care of all of this, but now, we have to setup our mongo database and web server. Luckily, Heroku and Mongolabs work together nicely and almost automatically in this process.

Let’s get started already!

First, You will need to create an account with Heroku, so go create one now if you haven’t already.

Then you’ll need to download the latest version of the Heroku tool-belt here. Once the download has finished you will be able to use heroku commands from the command line. (You’ll see why you want to do this in step 3)

1. Push the button

In your browser, go to: https://github.com/ParsePlatform/parse-server-example, this is a sample node.js app that uses express.js and parse server to

You’ll see a purple button here that says Deploy to heroku.

Press it, press it right now.

2. Prepare the app with Heroku

Heroku’s one button deploys are handy for creating a new app, when you clicked the button in step 1, it took you to a page inside Heroku that asked you to name your app, give it a nice random name, or Heroku will name it for you.

MongoLab was also auto-selected as a necessary add-on, so that’s taken care of for you.

Further down the page, it will give you a list of options:

  1. Keep /parse as your PARSE_MOUNT.
  2. Enter any name you want for APP_ID.
  3. Enter any key you want for the MASTER_KEY.

Now press the deploy for free button, and wait a few minutes.

Once done, you can enter your parse server app by the https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse, if you see a message that says:

I dream of being a web site.

This is placeholder text, and tells you it worked.

3. Modifying your parse server

From the terminal, you want to use the Heroku toolbelt I mentioned before step 1 to download your Heroku’d Parse server and make changes.

Login into heroku using the Heroku toolbelt:

heroku login

Finally, you can clone your new heroku app:

heroku git:clone -a MYPARSEAPPNAME

This will download your parse server app to your local computer inside a folder called whatever you named your heroku app. Replace MYPARSEAPPNAME with the name of your app on Heroku.

If you’ve worked with Parse at all before, then you’re already familiar with having to add a clientKey and appId into the initialization of your client code, to allow your app to communicate with Parse.

Now however, you need to set these keys both in your client code and in the server code.

Open up index.js and set both the clientKey, and appId, to whatever you want

var api = new ParseServer({
  databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
  appId: 'MYAPPID',
  clientKey: 'myclientKey',
  masterKey: 'myMasterKey'
});

You will then need to go into the initialization block of your code, and set a matching appId.

On your client side, the only code change you’ll need to make is to specify your new server address. This is the address of your Heroku app that hosts your server side code. You can find it in the settings of your app on your Heroku Dashboard. It is just a URL of the form

https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse

Your client code would now look something like this (for javascript):

Parse.initialize('APP_ID', 'CLIENT_KEY');
Parse.serverURL = 'https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse';
var Test = Parse.Object.extend('TestObject');
var test = new Test();
test.save({'animal': true, 'type': 'dog'},{
    success: function () {
        console.log('success');
    },error: function() {
        console.log('error');
    }
});

The final step is to update your Heroku app, since you changed the appId and added a clientKey.

To do that, run these three commands in the terminal:

$ git add --all .
$ git commit -m "My first commit"
$ git push heroku master

When you change code locally, it isn’t updated on Heroku automatically, so you have to run those three commands to:

  1. Add any new files
  2. Commit all changed, added or removed files so the server knows what changed
  3. Upload the changes to Heroku

Also, where you see My first commit, it helps to update that to reflect any changes you’ve made.

4. FINISHED

You can now use your client side Parse code just as you always did, and works as it did before.

Now instead of connecting to a Parse run server, your client code is connecting directly to your Heroku app, which saves all your data in your MongoDB database.

Your queries all work the same as before.

About Cloud Code

you may have noticed this line:

  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',

This tells your server where your cloud code is located. Cloud code is a feature from Parse that serves as short functions that you can call quickly via HTTP requests such as this one:

curl -X POST \
    -H "X-Parse-Application-Id: myAppId" \
    -H "Content-Type: application/json" \
    -d '{}' \
    https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse/functions/hello

When you migrate from Parse to a self-hosted Parse Server, you can also move over any cloud code you’ve set up so that you just call it when you want to work with it.

The default, included cloud code function is:

Parse.Cloud.define('hello', function(req, res) {
    res.success('Hi');
});

Which means when you make the HTTP request above, you get a return of Hi, where hello is the name of the function you created. You can have as many function as you want, and they all serve different purposes.


It is worth mentioning that several features that made Parse really useful, will not be available in your parse server right away.

The biggest feature that is missing is Push Notifications. But as it happens, it’s pretty easy to add Push Notification support to node.js, and I’ll cover in a later tutorial just how to add Push to your new Parse Server.

Background jobs was another feature missing, but you can look at queue systems or cron jobs to replace them easily. I also plan to write about migrated background jobs to a queued jobs setup.

I also recommend installing the free New Relic add-on inside your heroku app for handy analytics.

Is Heroku really free?

Yes and no, when you first start out, it’s free, but when you are ready to actually use your Parse Server apps then you’ll want to look at the $7 hobby plan at least, the reason for this is because free heroku apps are required to sleep after 30 minutes of inactivity and must sleep for 6 hours in a 24 hour period. This is fine for development, but when ready to actually make use of it, you want to upgrade to the hobby plan for starters.

As I introduce you to posts about deploying Parse Server to other setups such as Digital Ocean and Amazon’s AWS instances, you’ll get a feel for which pricing plans you prefer.

Still Confused?

If you have questions about Parse Server, setting up push notifications, moving your data from Parse to MongoDB or Flybase, then just feel free to get in touch at anytime and I’ll be happy to answer any questions or lend a hand or two.

Use Data McFly to build a real-time Todo app

If you like to keep organized, then you want a todo app. In this tutorial, we’re going to build a simple real-time todo app.

This app will consist of four functions:

  1. Add new items to do
  2. Mark items as done
  3. Mark items as not done (undo)
  4. Delete items

This is simple functionality, but it is exactly what a todo app is all about, and can run anywhere as this will consist of an html file, a javascript file and some very basic css.

All you need to build your todo app is a free Data McFly account. There’s no server-side programming needed for this app.

This was a quick, fun tutorial to write. Showing how to build a simple todo list app using Data McFly.

Build a real-time SMS call center with Data McFly and Twilio

Do you want to know one of the beautiful things about Data McFly? It integrates really easily with other services.

In this article, we are going to walk through using Data McFly and Twilio together to build a real-time SMS call center.

This could be used as a customer help desk where customers send a text message for help and an agent sends a reply back from their web browser.

The actual phone work will be handled by Twilio, and Data McFly will store the data and display the chats in real-time. We’ll use node.js to send and receive the text messages and an HTML frontend to handle the actual chatting.

I decided this week to give myself the task of building a real-time SMS call center that used Data McFly for the data handling and real-time communication, and Twilio for the phone work.

The end result turned out pretty well.

Upgrade an ASUS Chromebox – more RAM, bigger SSD, and Ubuntu

ASUS makes a pretty handy Chromebox, and it’s handy not just because it’s running ChromeOS, it’s handy because of everything you can do to the box itself.

The ASUS Chromebox is easily upgradeable, and capable of running just about any linux distribution.

The model I picked up, the M004U has the following specs:

  • Celeron 2955U (1.4GHz) 64 bit Dual core processor with 2MB L3 Cache
  • 2GB DDR3 1600 RAM with 2 slots
  • 16GB SSD HDD
  • 802.11 b/g/n dual-band wireless, Bluetooth 4.0, and gigabit ethernet
  • four USB 3.0 ports
  • Intel HD Graphics with support for dual displays
  • an SD/MMC card reader

This post will cover how to go about upgrading the hardware, and get it up and running in a dual boot mode to ChromeOS and Chrubuntu.

Here are the parts I used:

  • ASUS CHROMEBOX-M004U Desktop PC Celeron 2955U (1.4GHz) 2GB DDR3 16GB SSD HDD from Amazon
  • Crucial 8GB Kit (4GBx2) DDR3/DDR3L 1600 MT/s (PC3-12800) CL11 SODIMM 204-Pin 1.35V/1.5V Memory For Mac CT2C4G3S160BM from Amazon
  • MyDigitalSSD SC2 Super Cache 2 42mm SATA III 6G M.2 NGFF M2 SSD Solid State Drive (128GB) From Amazon

I also had a wireless Logitech k360 keyboard and mouse I could use, as well as a Samsung monitor for a display.

Getting into the Hardware

First off, you don’t need to make any kind of system image before modifying the unit, you can simply remove the installed SSD and RAM and insert your new parts and go from there. In the instructions below, you’ll make a USB stick that can be used to restore the disk to a factory fresh image of Chrome OS.

To do this, first remove the four rubber feet on the bottom of the unit. You may need to use a small flat head screwdriver to help get them off. Don’t place them anywhere sticky side down!

You’ll then find four screws underneath where the feet were, remove them. Then carefully remove the bottom of the unit. This may be a little difficult, so you may try and slip a small screwdriver in the vents to help. Don’t scratch it up or use force.

You should now be taking a look inside, and marvelling at the relative simplicity of the device!

You’ll see the RAM chip(s), which can be easily removed by opening the clips on the edges and lifting outward.

cb1

If you are upgrading the SSD, you’ll need a tiny screwdriver to remove the screw holding in the wireless/bluetooth card, which is easily identified by the two wires that connect to it. You may remove this card entirely, or do like I did and just remove the screw holding it in and it should give you enough room to install the SSD. Underneath this is the stock Sandisk SSD, which is held in by one screw on it’s far edge, so remove the screw, and pull out the SSD.

Place your new SSD in the slot, and put the tiny screw back in to hold it. Now put the wireless/bluetooth card back in place, and put it’s screw back in as well.

Now put the bottom of the case back on, put the screws back in, and put the feet back on. You’re done with the hardware upgrade!

Getting into ChromeOS

Now you’ll need to install Chrome OS onto your new empty SSD. To do this, visit this page and follow the instructions for your operating system to create a USB stick;

https://chrome.google.com/webstore/detail/chromebook-recovery-utili/jndclpdbaamdhonoechobihbbiimdgai?utm_source=gmail

This tool is a chrome extension but it creates the USB stick beautifully, just choose your chromebox model and it will install the recovery disk for you.

Now, to get started:

  1. Start your Chromebook.
  2. When the “Chrome OS is missing or damaged” screen appears, insert the USB flash drive or SD card you created into the USB port or SD card slot on your Chrome device.
  3. Wait for the Chromebook to boot up from the flash drive.
  4. Follow the instructions that appear on the screen.
  5. On successful installation of the Chrome operating system, you will be prompted to remove the USB flash drive or SD card.
  6. Remove the USB flash drive or SD card when prompted, and your Chromebook will automatically restart.
  7. You should now be able to start your Chromebook as normal.

Now you are ready to do the install of Ubuntu if you so desire. If you just want a fast ChromeOS box, you are done!

Getting into Chrubuntu

Make sure you have ethernet plugged in, or access to a wireless access point so you can download the necessary files.

Find the developer switch on your machine (it’s in a little hole on the back of the left side next to the SD slot). Very carefully press a small paper clip end into this hole and press the power button and the remove the paperclip. When it boots, press ctrl-D to turn off OS verification mode. It should prompt you to turn on Developer mode by using the paper clip again without pressing the power button. It will now boot into developer mode, and take several minutes to prepare itself.

When it has booted, hit Ctrl-D and it will come up to the setup screen, make sure your correct networking is selected. Select continue and accept the agreement.

At the sign in screen press Ctrl-Alt-F2 to get into a shell.

Login with user chronos and hit enter, …it should not ask for a password.

Become root using the command;

sudo bash

Then issue the command to boot into the development bios by default;

chromeos-firmwareupdate --mode=todev

(if you don’t do this it will erase Ubuntu on next boot. You can undo this by booting again to the shell and issuing the command; chromeos-firmwareupdate --mode=normal)

Now type the command;

reboot

When it has booted, hit Ctrl-D and it will come up to the login screen, and now press Ctrl-Alt-F2 to get into a shell.

Login with user chronos again and hit enter, it should not ask for a password.

At this point you can download custom update scripts that will install the appropriate kernel, and a choice of several flavours of linux.

To use install Chrubuntu, type the command;

curl -L -O http://goo.gl/s9ryd > s9ryd

And after it has downloaded the script, type the command;

sudo bash s9ryd

It will prompt you to choose the appropriate size in Gigabytes you wish to give to ubuntu, I gave it 100

Let the machine reboot (still into ChromeOS), it will say it’s repairing itself and reboot. Now choose the language and networking again, and at the login prompt press Ctrl+Alt+f2 to get a shell and give the username chronos (no password)

You’ll need to run the script again, so type the command;

curl -L -O http://goo.gl/s9ryd > s9ryd

And after it has downloaded the script again, you can install by using parameters, where;

  • default (ubuntu-desktop on x86, xubuntu-desktop on arm)
  • kubuntu-desktop
  • lubuntu-desktop
  • xubuntu-desktop
  • edubuntu-desktop
  • ubuntu-standard (no GUI installed)

So to install the default you would enter;

sudo bash s9ryd

or to install ubuntu-desktop lts, type;

sudo bash s9ryd ubuntu-desktop lts

Now it will run for quite a long time, depending on your connection speed. It will prompt you for locale and other settings, most users can just hit enter.

In fact, once the download starts, I highly suggest you go grab a sandwich or something, anything is better than watching the download count slowly roll around.

When it is finished, it will prompt you to reboot by hitting Enter.

You should now verify that everything is as you like it. You can switch between ChromeOS and Chrubuntu by using the following commands;

To make it always boot Ubuntu, go into Terminal and type;

sudo cgpt add -i 6 -P 5 -S 1 /dev/sda

To make boot to Chrome;

sudo cgpt add -i 6 -P 0 -S 1 /dev/sda

(if, for some reason your keyboard doesn’t work on boot, try reconnecting it)

The default Ubuntu user is user with password also set to user. Please change the password!

You’re done! You can stop here unless you need to always boot to Ubuntu, and want to write some scripts to switch envronments, or want to change the default user.

Boot to Chrubuntu, and Script switching back and forth

To always boot into chrubuntu, at the Google sign in screen press Ctrl-Alt-F2 to get into a shell.

Login with user chronos and hit enter, it should not ask for a password.

type the commands;

sudo cgpt add -i 6 -P 5 -S 1 /dev/sda
sudo reboot

Just wait for it to restart, and it will boot up into your alternate OS

To make it boot to Chrome every time;

sudo cgpt add -i 6 -P 0 -S 1 /dev/sda
sudo reboot

Note: don’t hit Ctrl-D anymore at the OS Security screen, just wait for it to come up… this for some reason didn’t work on the next boot, it did however work from then onward. It also boots up amazingly fast.

WARNING: if you switch the developer switch back off YOU WILL LOSE YOUR UBUNTU INSTALL and go back to a completely reset ChromeBox.

You may want to do yourself a favor, and set up some scripts, so that you can boot to chrome from the terminal in Ubuntu by typing chromeos, and to Ubuntu by doing Ctrl+Alt+F2 and typing ubuntu. To do this do the following steps.

When booted into Ubuntu, find your .bashrc file for the default account user, and add this to the bottom using the vi editor; (you can look up how to use vi on the web, but to put it simply, you would type vi .bashrc, scroll to the bottom, and on a empty line press the “a” key to add text, type in the line below, and when done hit escape, then type :wq to save and exit from vi)

alias chromeos='sudo cgpt add -i 6 -P 0 -S 0 /dev/sda;sudo reboot'

After you have saved the file exit the terminal by typing;

exit

now open a terminal again, and type the command;

chromeos

It should prompt for a password, you should enter user…(we’ll change it later)

Wait for it to boot after beeping, and do a Ctrl+Alt+F2 to get to the chrome shell, login with user chronos, and enter the command;

sudo vim .profile

And edit the file (hit the a key to get into insert mode just like in vi) and add:

alias ubuntu='sudo cgpt add -i 6 -P 5 -S 1 /dev/sda;sudo reboot'

Press esc to return to ‘command mode’ Press shift + z then shift + z again to save the file and return to the terminal

Type exit and press enter.

Now in Ubuntu, you can type in a terminal the command; chromeos …and you will boot into chrome …and in Chrome, you can hit Ctrl-Alt-F2 to get the shell, login as chronos, and type ubuntu to boot into ubuntu!

You won’t have to do anything when the dive is rebooted or powered up, just wait a few seconds and it will beep a couple of times, and then boot up into whatever OS was running previously.

Update: I’ve updated this post with a different RAM package, as the original RAM that was being sold got updated to only support 1.5V, and the Chromebox requires 1.35V, so the Crucial RAM listed here now is 1.35V, which works fine with this Chromebox 🙂

Generate UUIDs in PHP

I’m working on a project currently where I am using UUIDs as unique identifiers. PHP doesn’t have a good UUID function for this, so I wrote one that let me generate one.

<?php
function generate_uuid() {
	return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
		mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
		mt_rand( 0, 0xffff ),
		mt_rand( 0, 0x0fff ) | 0x4000,
		mt_rand( 0, 0x3fff ) | 0x8000,
		mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
	);
}
?>

For anyone who doesn’t know, a UUID, or a Universally Unique Identifier is an identifier standard used in software construction, standardized by the Open Software Foundation (OSF) as part of the Distributed Computing Environment (DCE).

UUIDs are meant to enable distributed systems to uniquely identify information without significant central coordination. In this context the word unique should be taken to mean “practically unique” rather than “guaranteed unique”. Since the identifiers have a finite size, it is possible for two differing items to share the same identifier. The identifier size and generation process need to be selected so as to make this sufficiently improbable in practice. Anyone can create a UUID and use it to identify something with reasonable confidence that the same identifier will never be unintentionally created by anyone to identify something else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve identifier (ID) conflicts.

A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens). For example:

a8d5c97d-9978-4b0b-9947-7a95dcb31d0f

There are several versions of UUIDs, in this case the function uses version 4, which is the random UUID generation. This is generally defined as follows

Version 4 UUIDs use a scheme relying only on random numbers. This algorithm sets the version number as well as two reserved bits. All other bits are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479).

Useful Pythonista Links

Pythonista is a great app for iOS that lets you get things done, and there are a lot of useful snippets out there that help make it more useful.

This post is to bring together some of those links, and I will probably update it as I add more. I’ll also tell you why they are useful..

To start, one of the most useful resources is the Pythonista forum, where other users share code for everybody to use. So check it out.

First, to make adding these snippets easier, let’s add some code to download any gist links and create a new script:

  1. Copy the code at this url: “https://gist.github.com/b0644f5ed1d94bd32805” and save it as a new script.
  2. Then go to Settings > Actions Menu and select to add the script to your actions.

Now you can copy the gist URL into your browser and then when you open up pythonista and choose “import from gist” from your actions menu, it will add the snippet as a new script.. Handy.. Very handy..

Now, let’s look at DropBox Integration.. This is handy as you can keep all your files in DropBox and sync between devices..

  1. To start, let’s add the ability to login to DropBox
  2. Once you add this script, you will have to set up an app at http://dropbox.com/developers/apps and make sure it is limited to one folder, rather than all of DropBox.

Now, let’s add the DropBox sync app

This script, when run, will sync your local copy with the copy on DropBox, and update whichever one has recent changes.

I use this to go between my iPad, iPad mini and iPhone and it works well.

I also find this script useful to it as a web server, and download files from your browser. Also, easily customized..

The author of Pythonista also posted this handy Drum Machine script that my daughter loves to play with.

I find The Down For Everyone Or Just Me script really handy when you need to check a web site.

Also, this handy script for installing short cuts via webclips is a little tricky to start out, but works well..

You can also use this script to convert any image in your clipboard into a base64 string.

Also, if you want to email images, then use this script (also good example of using email from inside pythonista).

And finally, I use this script and bookmarklet to send to pinboard for book marking.

Pythonista is growing, and as it grows, so do the useful scripts that are available.. So play with the links above, and also make sure to read the forums on a regular basis so you can get more useful scripts.

Using Dropbox as a Git repository

I use github heavily, but I have a couple projects that I like to work on across multiple machines, but don’t necessarily want to share them on github, and I already use private repositories…

I decided to use Dropbox as a git server to work with multiple machines as it gives you that extra version control in that you have git and Dropbox’s built-in control.

It turns out it is actually pretty easy to set it all up so here are the quick steps for anyone who is interested (these are only applicable to Macs).

This is actually a great way to work collaboratively and remotely with other developers, or simply keep project files in sync between two different computers. In my case when working from home I’m usually on the Mac Mini and on the road with the Macbook Air so this works really well and allows me to work on the same project from different computers without the hassle of remembering to copy files across etc

  1. Firstly make sure you have the Dropbox app and Git installed on your Mac. If not, you can get Dropbox from here (direct download link) and the latest version of Git from here.
  2. With Dropbox and Git installed, you need to create a bare repository which will be shared with your Dropbox account. Open a Terminal window in your Mac and do the following:
$ cd ~/Dropbox
$ mkdir -p repos/your-repo-name
$ git init --bare repos/your-repo-name
Initialized empty Git repository in /Users/xxxxxx/Dropbox/repos/your-repo-name/
  1. Now with our bare repository created, head to your project folder and let’s start a local git repo and link it with the Dropbox one. If you already have a local repo, skip to step 4:
$ cd ~/ProjectFolder
$ git init .
Initialized empty Git repository in /Users/xxxxx/ProjectFolder/
$ git add .
$ git commit --all -m "Initial commit"
$ git remote add dropbox /Users/xxxxx/Dropbox/repos/your-repo-name/
$ git push dropbox master

Essentially what we’ve done here was initialise a local repo, add and commit all files within that folder to the local repo. We then add a new remote location using the handle “dropbox” to this repo and finally push all the local changes to the “remote” repo (i.e. your Dropbox repo folder).

The rest is done automatically by Dropbox – your folder will be synced with your account and accessible from anywhere. For instance, if you wanted to clone the repo to a different machine, all you need to do is make sure Dropbox is installed and the folders are synced – and then issue the following command:

$ cd ~/Projects
$ git clone -o dropbox /Users/xxxxx/Dropbox/repos/your-repo-name/

If everything goes right, you should have a local copy of your remote repo already configured with your dropbox remote. You can start making changes to your project and when ready, push them back to the remote:

$ git commit --all -m "Changes made!"
$ git push dropbox master

And finally, when you want to sync the remote repository with your local copy, you can:

$ git pull dropbox master

You can also use github for mac as your git client, despite the name, it’s not just for github projects.

Using the x-requested-with header to include content on demand

I like using the same PHP script for both AJAX and non-AJAX content requests. Using one script just makes everything easier because it’s only one file to update/edit and it’s one more cache-able request.

One way to try to detect an AJAX request (as opposed to a regular page load) is by using the x-requested-with header when building ajax powered apps..

PHP Code

<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){
    include('header.php');
}?>
<blockquote cite="http://ia341030.us.archive.org/1/items/alicesadventures19002gut/19002-h/19002-h.htm">
    <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do: once or twice she had peeped
    into the book her sister was reading, but it had no pictures or
    conversations in it, and where is the use of a book, thought Alice,
    without pictures or conversations? So she was considering in her own mind,
    (as well as she could, for the hot day made her feel very sleepy and
    stupid,) whether the pleasure of making a daisy-chain was worth the
    trouble of getting up and picking the daisies, when a white rabbit with
    pink eyes ran close by her.</p>
</blockquote>
<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){
    include('footer.php');
}?>

jQuery Code

$(document).ready(function(){
    $('.ajaxtrigger').click(function(){
        var url = $(this).attr('href');
        $('#target').load(url);
        return false;
    });
});