Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

June 27 2017


Take Our New Course: Get Started With Elixir

Final product image What You'll Be Creating

Do you want to learn the Elixir language? If so, our new course, Get Started With Elixir, is ideal for you.

In this course, experienced instructor Markus Mühlberger will help you learn the Elixir language, starting with Elixir's Ruby-inspired syntax, and moving on to learn how to code distributed and highly concurrent services in the Elixir language.

Elixir website

You can take our new course straight away with a free 10-day trial of our monthly subscription. If you decide to continue, it costs just $15 a month, and you’ll get access to hundreds of courses, with new ones added every week.


You can also discover thousands of time-saving code scripts and plugins over on Envato Market, so head over there to see what you can find.


Code a Real-Time NativeScript App: Geolocation and Google Maps

NativeScript is a framework for building cross-platform native mobile apps using XML, CSS, and JavaScript. In this series, we'll try out some of the cool things you can do with a NativeScript app: geolocation and Google Maps integration, SQLite database, Firebase integration, and push notifications. Along the way, we'll build a fitness app with real-time capabilities that will use each of these features.

In this tutorial, you'll learn how to work with geolocation and Google Maps in NativeScript apps. 

I'm assuming that you already know how to create apps in NativeScript. If you're new to NativeScript, I recommend that you first check out one of the earlier tutorials in NativeScript before trying to follow this tutorial.

What You'll Be Creating

You'll be creating a walking tracker using geolocation and Google Maps. It will show the user how much distance they've covered and the number of steps they've taken to cover that distance. There will also be a map that will show the user's current location.

To give you an idea, here's what the final output will look like:

app final

Setting Up the Project

Start by creating a new NativeScript app:

To make it easier to set up the UI of the app, I've created a GitHub repo which includes both the starter and final version of the project. You can go ahead and copy the contents of the app folder to your project's app folder. We will only be working with two files: main-page.xml and main-page.js file. The rest is just boilerplate from the NativeScript demo project. 

Running the App

We will be using the Android emulator provided by Android Studio to test the app. This will allow us to use the Android GPS Emulator to simulate the changing of locations from the comfort of our own homes. I don't really like aimlessly walking around outside to test geolocation either! But if that's your thing then I won't stop you.

If you execute tns run android, it will automatically call the Android emulator if it's already installed. If it's not yet installed, you can install it by launching Android Studio, clicking configure, and selecting SDK Manager. This will open the SDK Platforms by default. Click on the SDK Tools tab and make sure to select Android Emulator, and click on Apply to install it.

To use the GPS emulator, download it from GitHub and run the executable war file:

Once that's done, you should be able to access http://localhost:8080/gpsemulator/ from your browser and connect to localhost. Make sure that the Android emulator is already running when you do this. Once you're connected, simply zoom in the map and click on any place you want to use as the location. The app will detect this and use it as its current location.

GPS Emulator

Working With Geolocation

Geolocation in NativeScript is similar to the Geolocation API in JavaScript. The only difference in functionality is the addition of a distance() function which is used for calculating the distance between two locations.

Installing the Geolocation Plugin

In order to work with geolocation, you first need to install the geolocation plugin:

Once that's done, you can now include it from your script files:

Getting the User's Current Location

The NativeScript geolocation plugin includes three functions which you can use for working with the user's current location. We will be using each of these in this app:

  • getCurrentLocation
  • watchLocation
  • distance

Open the main-view-model.js file and add the following code inside the createViewModel() function. Here we're initializing the variables that we will be using later on for storing the different values that are needed for keeping track of the user's location. 

I've added some comments in the code so you know what's going on. There are also some lines of code that are commented out; these are for the Google Maps integration. I've commented them out for now to keep things simple. Once we get to the Google Maps integration, you'll need to remove those comments.

Next, add the code for getting the user's current location. This code is executed when the user taps on the button for starting and stopping the location tracking. The geolocation.getCurrentLocation() method is used to get the current location. 

Here we've specified three options: desiredAccuracy, updateDistance, and timeoutdesiredAccuracy allows you to specify the accuracy in meters. It has two possible values: Accuracy.high, which is about 3 meters, and Accuracy.any, which is about 300 meters. updateDistance specifies how much difference (in meters) there must be between the previous location and the current location before it will update. Lastly, timeout specifies how many milliseconds to wait for a location. 

Once a location is received, we set it as the start_location and push it on the locations array. Later on, this location will be used along with the first location that will be fetched from watching the user's current location to determine the distance traveled.

Watching for the User's Current Location

To get the current location, we use the geolocation.watchLocation() function. This function is similar to the setInterval() function in JavaScript, because it also executes the callback function repeatedly until you stop it with the geolocation.clearWatch() function. The callback function is automatically called based on the updateDistance and minimumUpdateTime

In the code below, the location will be updated if it is at least 5 meters different from the previous location that was fetched. But this update will only happen every 5 seconds. This means that if the user hasn't walked 5 meters or more within 5 seconds, the location won't update. 

Once the user indicates that they want to stop tracking, you need to call the geolocation.clearWatch() function. You also need to reset the rest of the values that are being updated every time the location is changed. 

Getting the Distance Between Two Locations

Now we're ready to get the distance. This can be done by calling the geolocation.distance() function. This function accepts two location objects as its arguments, so we'll use the last two locations that were pushed to the locations array to determine the distance (in meters) traveled by the user from a previously recorded location to the current one. From there, we can use an approximate conversion from meters to the number of steps—I say approximate because not all people will travel the same distance in a single step. 

After that, we can just add the resulting distance and steps to the total_distance and total_steps so we can keep track of the total distance and steps they have taken since they started tracking their location.

At this point, you can now start testing the app using the GPS emulator that I mentioned earlier. Do note that you need to hit save on the main-view-model.js file to trigger an app reload. 

Then pick a location in the GPS emulator so that a fresh location will be fetched by the app once it loads. If you don't do this, it will default to the Googleplex location in Mountain View, California. This means that the next time you pick a location on the emulator, it will jump from this location to the location that you picked. If it's far away then you'll get a really large number for the distance and steps. 

Alternately, you could test on a real device with internet and GPS enabled. Only GPS is required at this point, but once we add Google Maps, the app will need an internet connection.

Working With Google Maps

We will now use Google Maps to add a map that shows the user's current location.

Installing the Google Maps Plugin

Once installed, you need to copy the template string resource files for Android:

Next, open the app/App_Resources/Android/values/nativescript_google_maps_api.xml file and add your own Google Maps API key (server key):

Make sure that you have enabled the Google Maps Android API from the Google Console before you try to use it.

Adding the Map

For the map, open the main-page.xml file and you should see the following:

Here we've specified three options (longitudelatitude, and zoom) and a function to execute once the map is ready. longitude and latitude specify the location you want to render in the map. The zoom specifies the zoom level of the map. mapReady is where we specify the function for adding the marker on the map. This marker represents the user's current location, so it will be rendered at the center of the map.

By default, this won't work as you haven't added the schema definition for the maps yet. So in your Page element, add the definition for the maps element:

Once that's done, a Google map instance should be rendered right below the button for tracking location. It won't have any maps yet since the latitude and longitude haven't been specified yet. To do that, go back to the main-view-model.js file and remove the comments for the lines of code for working with Google Maps:

Adding the Marker

Since we've already declared default coordinates for the marker, we can actually plot a marker once the map is ready:

Next, we need to update the marker position once the user starts tracking their location. You can do that inside the success callback function for the getCurrentLocation() function:

We also need update it when the user's location is updated (inside the success callback function for watchLocation):

Once that's done, a map which renders the default location should show in the app.


In this tutorial, you've created a NativeScript app that allows the user to track how much distance they have covered and the approximate number of steps they've taken to cover that distance. You've also used Google Maps to let the user view their current location. By doing so, you've learned how to use the geolocation and Google Maps plugins for NativeScript.

This is just the start! In the next posts of this series, we'll add a local database, push notifications and other cool features to our app.

In the meantime, check out some of our other posts on NativeScript and cross-platform mobile coding.

  • Mobile App
    Create a Weather App With TypeScript and NativeScript
    Wernher-Bel Ancheta
  • Mobile Development
    Introducing Vue and Weex for Native Mobile Apps
    Lawrence Turton
  • Ionic
    Get Started With Ionic Services: Auth
    Wernher-Bel Ancheta

For a comprehensive introduction to NativeScript, try our video course Code a Mobile App With NativeScript. In this course, Keyvan Kasaei will show you step by step how to build a simple application. Along the way, you'll learn how to implement a simple app workflow with network requests, an MVVM architecture, and some of the most important NativeScript UI components. By the end, you'll understand why you should consider NativeScript for your next mobile app project.


Neutron Creative

7 Freelancing Trends For 2017

7 Freelancing Trends For 2017

The business of freelancing is changing rapidly; anyone active in the industry can see it. My own experience leads me to see certain trends that are already in effect, and are poised to really take off in 2017. Some of the freelancing trends of 2017 will help us, and some can hurt us. Here are the most important 7 trends, and what they mean for all of us.

1) Massive numbers of millennials will start freelancing.

It’s been reported that millennials tend to want to switch jobs frequently – about every 2 years – and avoid the boredom of doing the same job in the same place the same way, in the same place, day after day. And who could blame them? Although the gig economy has been a thing for the past few years, a couple of factors are going to accelerate this trend in 2017:

  • Culturally, the stigma surrounding remote work is virtually (no pun intended) gone.
  • More companies than ever before are more open to using freelancers than ever before.

In other words, freelancing is becoming increasingly normalized. This adds up to tons of opportunity for a workforce that is increasingly choosing to eschew full-time work and instead make the leap into full-time freelancing.

Although the freelancing trends for 2017 means that the influx will be comprised of mostly millennials, it’s not 100%. While most of the more mature and established members of the workforce will stick to the “sure thing” and remain in the traditional employment they’ve become accustomed to, we’re likely to see an uptick in the number of “graybeards” deciding to test the freelancing market.

With a massive influx of fresh talent and an accompanying – if smaller – increase in experienced workers in the freelancing marketplace, the overall market is due to become very competitive before 2017 is over.

Hint: to overcome objections of youth & inexperience, have a case study or two that allows you to demonstrate results to prospective clients.

2) Niche – and even micro-niche – positioning will become increasingly important.

freelancing niche
It seems like you can’t throw a rock in freelancing circles without someone talking about positioning. Again, this is an existing trend that we’ll see accelerating in 2017 thanks to a confluence of cultural and educational factors.

Although larger firms and small, established generalist firms (like mine!) will likely continue on just fine, the increasing number of new freelancers will make for a more competitive market. This increase in competition will force solo operators and small agencies alike to stratify into increasingly specific niches and micro-niches.

Those who don’t specialize or hyper-specialize will likely be pushed toward bottom-of-the-market work. Look for marketplaces like Upwork to be more competitive at the end of 2017 than they were at the start (this is both good AND bad for those making use of these marketplaces).

Specialist positioning is undoubtedly helpful in a number of ways, but the question that remains to be answered is, how niche is TOO niche? 2017 may be the year that freelancers find themselves pushed to find an answer to that question, as they narrow their specialties further and further, hoping to position their offerings favorably against increased competition.

Hint: if you’re not already positioned with a specialty, look at your existing body of work and reverse-engineer the problems and verticals you’ve already solved problems in, then market to that vertical, for that problem.

3) Informal partnerships of otherwise independent freelancers will become more common.

For years, my own firm has been what I refer to as a “merry band of mercenaries” – a gelled team that works together on a regular, ongoing basis, while remaining 1099 workers and maintaining all the appropriate boundaries required by the IRS (the guidelines are clear and strict).

Additionally, my firm has formed alliances with other small firms, with each of us providing labor related to our specialty in order to complete a project owned by one firm. These alliances will prove to be increasingly important in 2017 as freelancers take on sophisticated but finitely-scoped projects that require specialty labor, but that do not allow for the hiring of a regular employee to provide that labor.

It sounds like a fragile arrangement, but “specialists collaborating with specialists” is one of the very oldest ways of working, and it’s not only one of the more interesting freelancing trends for 2017, but more critical than ever.

Hint: making use of some decent project management software – Basecamp or Asana, for example – will make these arrangements much more manageable.

4) It will become increasingly more difficult to stand out online…

It’s not always this easy to stand out.
To say that it’s very difficult to rise above the noise online is an understatement. At one point, merely having a blog or podcast ensured some degree of traffic and notoriety. Now, these things are considered bare minimum signs of life for your freelancing practice online.

In 2017, most online marketing efforts will languish, with a small layer of “super-winners” at the top claiming the majority of the traffic, clicks, leads and sales. Smart freelancers will have to learn how to capture sub-segments of sub-segments of this traffic that would ordinarily go to the “super-winners”, and claim these leads as their own.

Hint: stick to marketing channels that allow you to best communicate what makes you valuable. Invest in effective marketing-education tools and training, like Tiny Marketing Wins, to help you.

5) …which is why personal networking & referrals will remain king.

We live in what is supposed to be the golden age of online lead-gen and marketing automation, yet the great majority of freelancers find that their online marketing efforts yield zero return – or worse, a net-negative return. By far, the #1 way that freelancers get new client work is via their network, not via stranger-leads that come in due to any kind of automated marketing.

The fact that it’s harder and harder to stand out online will make personal network marketing and referral work more of a source of leads, not less, and many freelancers will give up on trying to attract “stranger leads” online and instead use those automation tools to go deep on personal network marketing.

To be successful amidst these freelancing trends for 2017, it’s important to learn to create more “referrable moments”, meet more valuable contacts, and do a better job of turning one-off projects into long-term relationships with recurring work. Outside of the super-winners, freelancers that don’t go deep into relationship marketing will find that their blog posts, podcast episodes, and social media updates will continue to go unread, unheard, and unseen by prospective clients.

Hint: for going deep on email marketing to your network, I recommend Drip; it’s got everything you need to do either outward-facing lead-gen campaigns or inward-facing nurturing and referral-soliciting campaigns.

6) Lifestyle will become more important than earnings…

What’s YOUR dream?

The Golden era American dream – that anyone can get a stable job that pays enough to own a home and raise a family on one income – is dead and buried. The 21st-Century American Dream can be summed up in one word: flexibility. Sure, we want to support our families, but we also know we’re not going to be able to do it in partnership with one long-term, predictable-schedule, single-location employer.

Well, if we can’t do that, what can we do? We can work flexible hours. We can work remotely. We can work while traveling. We can work with a variety of clients, on a variety of projects. We’ll still earn a great living, but that will be less the focus than it used to be; the focus will increasingly be on having flexibility – being less dictated to, having less conformity demanded of us, and having more say-so in our overall careers than traditional employment ever offered those to whom it also offered long-term stability.

Hint: look for like-minded clients who respect work-life balance themselves, and don’t expect you to run headlong into death-march projects.

7) …even though earning potential will continue to rise.

Make no mistake, whatever the American Dream may be, it still takes money to attain it, and the freelancing market will continue to offer ample money. Rates will likely fluctuate a bit as newer, less-sophisticated operators flood the market and depress rates (at least for low-end work) but the market for established operators who can offer clients clear value propositions and proven track records will remain healthy.

One of the most encouraging freelancing trends for 2017 is that in certain niches and sub-specialties, effective rates are expected to increase by the end of the year, putting many freelancers in a strong position at the start of 2018.

Hint: figure out where your offerings exist on the value continuum and try to shift them close to where money is generated.

Originally posted here, syndicated with permission by the author.


Create a Mobile Application for Displaying Your Website RSS Content With Ionic

Final product image What You'll Be Creating

In this tutorial we will take a look at creating a mobile application which displays the RSS content of a website. We will configure the RSS URL and the application will download it, parse it and display the posts from the RSS. 

To create the mobile application, we will use the Ionic Framework v1 together with AngularJS. To complete this tutorial, you need to have some experience with JavaScript and HTML. Also, it helps if you've worked with AngularJS before. 

If you have never worked with Ionic Framework before, I recommend at least taking a look at the Getting Started guide as it gives you a quick insight into how things work.

Let's begin!

Setting Up the Ionic Project

I will assume that you have installed Node on your system and you also have the npm (the Node package manager). Installing the Ionic framework is as easy as running the following:

This will install both Cordova and Ionic on your computer. 

Cordova is the core technology for Ionic, and basically it allows us to have an embedded browser in our mobile application. In that browser we will be able to run all our HTML and JavaScript code. This is called a hybrid mobile application, as the application does not run native code, but runs inside the browser. 

Next to Cordova, Ionic adds to that the possibility of using AngularJS for writing our code, and it also adds a very neat UI framework.

With Ionic in place, we can create our project using the Ionic CLI, a very useful command-line tool. Ionic provides three default project templates which can be used as a starting point:

  • blank: as the name says, it's an empty project with only the minimal necessary components in place.
  • tabs: an application using tabs for navigating through its screens.
  • sidemenu: an application using a standard mobile side menu for navigation.

For this tutorial, we will be using the tabs application template. To start our project, let's run:

Ionic will download and install all components needed, and it will create the project folder named myWebsiteOnMobile. Go into the project directory by running:

Because our application is a hybrid mobile application, we have the advantage of being able to run the application inside a browser. To do this, Ionic provides a neat built-in web server which runs our application like this:

This will open a browser with our application loaded, and it will look like this:

The Ionic homescreen

To stop the server, use Control-C on your command-line screen. To get a better idea of how the application looks on a mobile, you can use:

This will open the application in the browser, showing an iOS and an Android preview of the app side by side.

The iOS and Android Preview

The tabs Ionic application template has three tabs: Status, Chats, and Account. In the next steps we will adjust the application to fit our needs.

How to Adjust the Default Ionic Tabs Template Application

For our application we will have two tabs:

  • Latest posts: showing a list of latest posts retrieved from the RSS feed.
  • Settings: where the user will be able to configure several aspects of the application.

From the Latest posts tab, the user will be able to click on any of the latest posts and see more information about the post, with the possibility of opening up the post in an external browser.

Since our Latest posts tab is similar to the Chats tab provided by the template, we will reuse that together with the Account tab, which will become our Settings tab. We can do all modifications with the Ionic webserver running, and Ionic will reload the app for us. This is a very neat feature which will speed up development.

As mentioned before, Ionic uses AngularJS, and the whole application is actually an AngularJS module. The module is defined in www/js/app.js, and here is also where the paths or routes of the application are defined. Each screen of the application has a corresponding route.

Let's remove the Status tab since we will not need it. To do this, we first need to change the default screen (or route) of our application to point to the Chats screen, which will become our main screen. The default screen is configured via $urlRouterProvider.otherwise(), so let's change that to:

If we now reload http://localhost:8100 in our browser, we will see that the Chats tab will be loaded by default.

To remove the Status tab, we need to edit the www/templates/tabs.html file that holds the template for the tab component. We will remove the element:

When saving, we will see that the application now has only two tabs: Chats and Account.

While in the www/templates/tabs.html file we notice that there are some HTML tags that are not standard HTML, like ion-tabs, ion-tab, and ion-nav-view. These are actually AngularJS directives defined by the Ionic Framework. The directives are tags that pack functionality behind them, and they are very convenient ways to write more structured and more concise code.

In our case, the ion-tabs directive is the tabs component, which for each tab requires an ion-tab directive.

Let's change our tabs from Chat and Account to our required names Latest posts and Settings. To do this, we will modify several things in the www/templates/tabs.html file:

  • title attribute of the ion-tab elements which determines the text on the tab button. We will change that to Latest posts and Settings respectively.
  • href attribute of the ion-tab elements which points to the route or screen URL. We will change those to #/tab/latest-posts and #/tab/settings.
  • name attribute of the ion-nav-view elements to tab-latest-posts and tab-settings. These are the identifiers for the view templates used for the Latest posts and Settings screens.

As a result, www/templates/tabs.html should look like this:

After making these changes, we will get some errors. This is because we also have to adjust our routes to use the new identifiers we have used. In www/js/app.js, we need to change the state identifiers, the view identifiers and the url for each route according to what we have set above.

For each route (or screen), there is a controller defined. This is a basic MVC (Model-View-Controller) design pattern. Controllers are defined within the file www/js/controllers.js. For consistency purposes, we will change the names of the controllers in both www/js/app.js and www/js/controller.js:

  • ChatsCtrl becomes LatestPostsCtrl.
  • ChatDetailCtrl becomes PostDetailCtrl.
  • AccountCtrl becomes SettingsCtrl.

Also, for each route we have a view template defined, so let's change them too. Edit www/js/app.js and modify templateUrl like this:

  • Change tab-chats.html to tab-latest-posts.html. Also rename the file www/templates/tab-chats.html to www/templates/tab-latest-posts.html.
  • Change chat-detail.html to post-detail.html. Also rename the file www/templates/chat-detail.html to www/templates/post-detail.html.
  • Change tab-account.html to tab-settings.html. Also rename the file www/templates/tab-account.html to www/templates/tab-settings.html.
  • Finally, change the view that gets loaded by default to latest-posts by using $urlRouterProvider.otherwise('/tab/latest-posts').

If all went well then you should end up with the www/js/app.js file looking like this:

And our cleaned up www/js/controllers.js file looks like this:

Now that we have restructured the app to fit our needs, let's move on to the next part and add some functionality.

How to Retrieve an RSS Feed With Ionic

In order to display the list of latest posts, our application will need to retrieve the RSS feed from a URL. As a best practice, it is advisable that this kind of functionality reside in the service layer of the application. In this way we can use it more easily in our controller and then present it to the user by using a view.

The RSS service will make use of Yahoo's YQL REST API to retrieve the RSS of our website. To call on the REST API, we will use the $http provider offered by AngularJS.

Ionic services are usually defined in the www/js/services.js file, so that's where we will put ours too. The code will look like this:

We declare the service using the service() method provided by AngularJS. We then inject Angular's $http module so we can call it in our service.

The self variable is a reference to the RSS service so that we can call it from within the service's methods. The main method of the service is the download() method, which downloads the feed information and processes it. There are two main formats used for website feeds: RSS and ATOM. For our application, we have used the feed of tutorials from Tuts+ which is in ATOM format, but for completeness we have taken into account the RSS format too.

The download() method calls on the YQL API and parses the results using the parseAtom() or the parseRSS() methods depending on the type of feed. The idea here is to have the same output format which will be passed further via the callback next(). With the RSS service in place, we can move on to the controller.

Hooking the RSS Service to the Latest Posts Controller

In our www/js/controllers.js file, we need to load the RSS data and pass it to our view. To do that, we only need to modify our LatestPostsCtrl controller like this:

Using Angular's dependency injection mechanism, we only need to specify the $scope and RSS variables as method parameters, and it will know how to load those modules. The $scope module allows us to set variables on the model bound to the view. Any values set in the scope can be then retrieved and displayed inside the view associated with the controller.

When the view for latest posts is loaded, it will call on the LatestPostsCtrl controller, and this in turn will use the RSS service to download the feed information. The results are parsed and passed back as an array using the posts variable, which we store in the current scope.

With all that out of the way, we can now move on to the view part, displaying the list of posts retrieved from the feed.

Hooking the Latest Posts View to the Feed Data

We now need to modify our view for the latest posts. If you remember, this is configured in the www/js/app.js file via the templateUrl attribute, and it points to the www/templates/tab-latest-posts.html file.

What we will want to do is display the list of feeds. Since the feed information may contain HTML, and this will only clutter the list of latest posts, we need something to extract the text without the HTML tags from a post's content. The easiest way to do that is by defining an AngularJS filter that strips the HTML tags from text. Let's do that in www/js/services.js by adding:

No back to our view inside the www/templates/tab-latest-posts.html file, let's modify it to look like this:

We are using the Ionic list UI component together with Angular's ng-repeat directive, which will iterate through the posts set on the scope of our controller. For each post entry, we will have a list item with its title and with the description stripped of HTML tags by the use of the htmlToPlaintext filter. Also note that clicking a post should take us to the detail of the post because of the href attribute set to #/tab/latest-posts/{{}}. That does not work yet, but we will take care of that in the next section.

If we now run the application using ionic serve --lab, we should get something like this:

Viewing Latest Posts

Showing the Details of a Post

When clicking on a post in the list, we go to the post details screen of the application. Because each screen of the application has its own controller and therefore its own scope, we can't access the list of posts to display a specific post. We can call the RSS service again, but that would be inefficient.

To solve this problem, we can make use of the $rootScope directive offered by Angular. This references a scope that overarches all controllers in the application. Let's modify our LatestPostCtrl to set the posts in the $rootScope and then search for the specific post that the user clicked in the PostDetailCtrl. The resulting code in www/js/controllers.js will look like this:

We simply injected $rootScope in both controllers and used it for passing posts between the two controllers. Please note that we don't need to make any changes in our latest posts view as $rootScope and $scope are both accessible in the same way from the view.

Inside the PostDetailCtrl controller, we simply search for the post with the id passed in the link clicked by the user. We do that by comparing each post ID with the value in the URL passed via the $stateParams.postId variable. If we find a match then we set the post on the scope so we can use it in our view.

Let's now adjust our post detail view www/templates/post-detail.html like this:

This is what we have done in the view:

  • We have placed the title of the post in the header of the screen.
  • We have placed an "Open" button in the header on the right. This button will open the post link in an external browser because of the attribute target="_system". We have to do this because the application is already running in a browser due to Cordova. If we didn't set that attribute, the post would have opened in the same browser as the application, and then we would not have a way to return to the application.
  • We display the description of the post as HTML by using Angular's ng-bind-html directive.

While running the application, I noticed that if the post description contains images, some of them fall off the screen. This might be the case with other HTML elements like videos. We can easily fix this by adding the following CSS rule in www/css/style.css.

If we now take a look at the application and click on one of the posts, we should see something like this:

Seeing posts for Tuts articles

And our application is almost complete. In the next section, we will take a look at implementing the settings screen.

Adding Settings for Our Ionic Application

For our settings screen, we will implement a way to indicate how many posts to display on the main screen of the application. We will store this setting in the localStorage memory, which is not erased when the application is closed. Let's edit the controllers file www/js/controllers.js and change the SettingsCtrl controller like this:

Also, we need to modify the settings screen in www/templates/tab-settings.html like this:

The controller retrieves the setting myWebsiteOnMobile.maxPosts from the localStorage. If it does not exist, it will be null, and we will consider that there is no limit for the maximum number of posts.

We call the $scope.$watch() method to monitor changes of the settings.maxPosts variable, which is bound to the radio control in the settings screen.

With all this in place, every time we change the maximum number of posts on the settings screen, the setting will be stored in the localStorage, and it will be retrieved from there when the application restarts.

Now let's make use of this setting. This is as simple as adding this in the LatestPostsCtrl from www/js/controllers.js:

And adding a directive in the latest posts screen www/templates/tab-latest-posts.html:

Notice the limitTo:maxPosts Angular filter. This will limit the number of posts displayed to the number taken from the localStorage. By default, this will be null, which will display all the feeds retrieved by the RSS service.

Congratulations! We now have a fully working application displaying an RSS feed.


In this tutorial, we have seen how to create a hybrid mobile application using the Ionic Framework and AngularJS. There is only one more thing to do: run the application on a mobile device or mobile emulator. This is very simple with Ionic. To run the application on an Android emulator, just run:

If you want to download a premade Ionic application template for transforming any website to a mobile application, try the Website to Mobile Ionic Application Template from CodeCanyon.

An application template on CodeCanyon

June 26 2017


What Are Dictionary Comprehensions in Python?


Recently, we looked at list comprehensions in Python. Similar to its sibling the list comprehension, a dictionary comprehension is nothing more than a shorthand way of creating a new dictionary collection. While it may seem a little more complicated than the list version, it is actually quite simple to understand. 

In this video tutorial from my course on Data Handling With Python, I'll show you exactly what dictionary comprehensions are and how you can use them.

Dictionary comprehensions in Python

Watch the Full Course

Do you want to learn Python in depth? If so, the full course, Data Handling With Python, is for you. It goes beyond the basics and takes you through Python data management in detail. Beyond comprehensions, we'll also look at map, filter, lambdas, and generators, as well as reading and writing to files and complex objects. 

And if you want something even more comprehensive, try my seven-hour course Learn to Code With Python, which includes the lessons on data management but also covers a whole lot more aspects of the Python language.

Type and Pixel

How to Deploy a WordPress Plugin From TravisCI to

Not everyone likes subversion. If you use Git to manage WordPress plugin development, keeping your Git repo and the SVN repo in sync is tedious. Luckily, we can use TravisCI deployment provider to automate SVN deployment after tests.


You need these before moving on:

  1. GitHub account
  2. TravisCI account
  3. Plugin source code
  4. plugin SVN repo (You get this after plugin review approval.)

First Push to GitHub

In order to use TravisCI, we have to host the plugin repository on GitHub.

First, create a new repository on GitHub by going to this page and filling in the repository name.

create new GitHub repository GitHub new repository page

Then, we are going to commit all plugin files into Git and push it to this GitHub repository. Remember to replace the remote URL with yours.

Connecting TravisCI

Connect your GitHub repository with TravisCI by going to your TravisCI account page and switching on your repository. Click Sync account in the upper right corner if your newly created repository doesn't show up in the list.

TravisCI account settings

You're all set. Every time you push new commits or someone makes pull requests to GitHub, it will trigger a build on TravisCI.

First Build on TravisCI

TravisCI uses a YAML file named .travis.yml in the root of your repository to customize the builds. Learn more from the build customizing document to see how you can control the build lifecycle.

This is a basic configuration file that instructs TravisCI to run builds on PHP 7.0 and 7.1. Since testing is out of the scope of this tutorial, I replaced the actual test commands with echo 'Tested'

Commit this file and push it to GitHub. TravisCI builds will be triggered automatically.

TravisCI current build

Adding Deployment Provider Configuration

Deployment providers run if the tests passed and pre-defined conditionals (the on section) are met. TravisCI provides nearly 40 official deployment providers. Sadly, none of them support subversion repositories. Thus, I made my own custom provider. You can find it on GitHub and its pull request.

To use it, add these lines to the end of .travis.yml.

Configuration Explanation


The before_deploy section copies three files into the build directory which is to be checked into the subversion repository. In the real world, this is where you want to run gulp or grunt tasks to prepare the production-ready plugin. 

Don't copy test files or any unnecessary files into build as the whole build directory is released to users, and users don't need your test files.

provider and edge

We tell TravisCI to install my provider from the add-wordpress-plugin-deployment branch Once the pull request has been merged, the edge part is unnecessary.


The on section controls whether a deployment should be performed. Deployment is triggered only when all requirements are met.

In the above example, we deploy to only when:

  1. it's a PHP 7.1 build
  2. it's a tagged commit
  3. it's triggered by the TangRufus/tutsplus-dpl-demo repo (forks and pull requests would not trigger deployment)


The plugin's slug. 

If your plugin's URL is, then my-awesome-plugin is the plugin's slug. 


Your account username with which you submitted the plugin for review approval.


The password of the account. Never save this password in the .travis.yml in plain text!

In the above example, we use the $WORDPRESS_ORG_PASSWORD environment variable, which can be set on the TravisCI web dashboard. Choose Settings from the cog menu, and click on Add in the Environment Variables section. Never enable the "Display value in build log" option!



Everything in this directory will be committed to the subversion repository, i.e. will be included in the downloadable zip file. 

We set this to build because we have copied plugin files into build during before_deploy.


Assume that we have fixed some bugs and are ready to publish a new version to

These commands commit the changes to the master branch but do not trigger a deployment:

Only tagged commits trigger deployment:


Head back to TravisCI and open the PHP 7.1 build log. You should see a deployment is logged.

And on the trac (<your-plugin-slug>):

WordPress plugin subversion trac


svn commit Twice

Since TravisCI ships with an old version of subversion which doesn't play well with subdirectories, I do svn commit twice.

The first svn commit removes everything inside trunk. The second svn commit copies everything from build_dir to trunk.


This provider is still experimental and is not merged to TravisCI's official repo yet. You can keep track of TravisCI's feedback on its pull request.

Using edge doesn't merge my branch into the upstream master. There is a chance that my branch is behind the official repo. When it happens, you can fork my branch and rebase it, and then change source in .travis.yml to your GitHub repository.

Wrapping Up

To use this deployment provider:

  1. Host the plugin repository on GitHub.
  2. Connect GitHub and TravisCI.
  3. Add the configuration to .travis.yml.
  4. Push a tag.

I hope all the above helps you deploy plugins to faster. 

WordPress has an incredibly active economy. There are themes, plugins, libraries, and many other products that help you build out your site and project. The open-source nature of the platform also makes it a great option for you to improve your programming skills. Whatever the case, you can see everything we have available in the Envato Marketplace.

Thanks for reading!


Now Available on Envato Elements: Unlimited Stock Photos

Welcome to unlimited stock photos on Envato Elements!

If you're already an Elements subscriber, you'll now see that, along with all the graphics, fonts, web templates, 3D models and everything else you've been used to downloading, you have unlimited access to over 240,000 high-quality stock images. Enjoy!

If you're not an Elements subscriber, here's how it works. For a single monthly subscription of US$29, you get unlimited downloads from a broad and highly curated selection of:

  • graphics (vectors, icons, patterns, textures, illustrations and more)
  • add-ons (think Photoshop and Illustrator actions, Lightroom presets, etc.)
  • fonts
  • graphic templates (logos, infographics, product mockups, etc.)
  • presentation templates (Keynote and PowerPoint)
  • web templates (landing pages, full websites, email newsletters, etc.)
  • CMS templates (Shopify, Magento, OpenCart, and a lot more)
  • 3D models

Oh, and you also get free access to over 1,000 courses and 170 eBooks here on Envato Tuts+, as well as free AND CO membership to help you with invoicing and contracts. 

And because all of that just wasn't enough, now you get almost a quarter of a million stock photos too.

Stock photo on Envato Elements Workplace image from Envato Elements

Why Envato Elements?

Of course, there are loads of stock photo sites out there already, both free and paid. So why should you bother with Envato Elements? Here are a few reasons:

1. Get Premium Quality

On some other stock photo sites, the emphasis is on quantity: thousands of people uploading millions of images, with little quality control. On Envato Elements, the collection is carefully curated to make sure you have access to the very best images, without having to wade through tons of mediocre ones.

Photography image on Envato Elements Photography image on Envato Elements

2. Get Broad Commercial Rights

No matter whether you're using photos for a website, an artwork, a client project or a professional document, you need to know that you have the right to use those images and won't get sued for copyright infringement. All the items on Envato Elements come with a simple, easy-to-understand commercial license, so that you can use them in your projects with confidence—and without having to squint at a mass of small print.

Happy couple image on Envato Elements Happy couple image on Envato Elements

3. Find Exactly What You Need

Elements offers some useful filters to help you find what you need quickly and effectively. You can search by subject, of course, but you can also filter for image orientation (landscape, portrait, or square) and for the predominant colours in the image. So you can find images that not only convey the right message, but also fit seamlessly with your overall design.

Image of Tuscany from Envato Elements Image of Tuscany from Envato Elements

4. Get a Lot of Other Stuff Too

As I mentioned above, you get a ton of other useful things bundled with an Elements subscription. There are no usage limits, no credits to keep track of. You just use as many photos, templates, fonts and graphics as you need for the projects you're working on. So whether you're a web designer, a developer, an artist a businessperson or a freelancer in a number of creative fields, you'll be able to get good value out of an Elements subscription.

Food image on Envato Elements Food image on Envato Elements

What to Do Next

To learn more about the new selection of photos, head over to Envato Elements. You can browse the full selection of items even if you don't have an account, so take a look around to get an idea of what's on offer and decide whether it would be useful for you.

Keep in mind that Envato Elements is expanding all the time, both in terms of the number of categories being offered and the number of items in each category. So this is a subscription that's only going to get more valuable over time.

June 23 2017


Securing iOS Data at Rest: Encryption

In this post, we'll look at advanced uses of encryption for user data in iOS apps. We'll start with a high-level look at AES encryption, and then go on to look at some examples of how to implement AES encryption in Swift.

In the last post, you learned how to store data using the keychain, which is good for small pieces of information such as keys, passwords, and certificates. 

  • iOS SDK
    Securing iOS Data at Rest: The Keychain
    Collin Stuart

If you are storing a large amount of custom data that you want to be available only after the user or device authenticates, then it's better to encrypt the data using an encryption framework. For example, you may have an app that can archive private chat messages saved by the user or private photos taken by the user, or which can store the user's financial details. In these cases, you would probably want to use encryption.

There are two common flows in applications for encrypting and decrypting data from iOS apps. Either the user is presented with a password screen, or the application is authenticated with a server which returns a key to decrypt the data. 

It's never a good idea to reinvent the wheel when it comes to encryption. Therefore, we are going to use the AES standard provided by the iOS Common Crypto library.


AES is a standard that encrypts data given a key. The same key used to encrypt the data is used to decrypt the data. There are different key sizes, and AES256 (256 bits) is the preferred length to be used with sensitive data.

RNCryptor is a popular encryption wrapper for iOS that supports AES. RNCryptor is a great choice because it gets you up and running very quickly without having to worry about the underlying details. It is also open source so that security researchers can analyze and audit the code.  

On the other hand, if your app deals with very sensitive information and you think your application will be targeted and cracked, you may want to write your own solution. The reason for this is that when many apps use the same code, it can make the hacker's job easier, allowing them to write a cracking app that finds common patterns in the code and applies patches to them. 

Keep in mind, though, that writing your own solution only slows down an attacker and prevents automated attacks. The protection you are getting from your own implementation is that a hacker will need to spend time and dedication on cracking your app alone. 

Whether you choose a third-party solution or choose to roll your own, it's important to be knowledgeable about how encryption systems work. That way, you can decide if a particular framework you want to use is really secure. Therefore, the rest of this tutorial will focus on writing your own custom solution. With the knowledge you'll learn from this tutorial, you'll be able to tell if you're using a particular framework securely. 

We'll start with the creation of a secret key that will be used to encrypt your data.

Create a Key

A very common error in AES encryption is to use a user's password directly as the encryption key. What if the user decides to use a common or weak password? How do we force users to use a key that is random and strong enough (has enough entropy) for encryption and then have them remember it? 

The solution is key stretching. Key stretching derives a key from a password by hashing it many times over with a salt. The salt is just a sequence of random data, and it is a common mistake to omit this salt—the salt gives the key its vitally important entropy, and without the salt, the same key would be derived if the same password was used by someone else.

Without the salt, a dictionary of words could be used to deduce common keys, which could then be used to attack user data. This is called a "dictionary attack". Tables with common keys that correspond to unsalted passwords are used for this purpose. They're called "rainbow tables".

Another pitfall when creating a salt is to use a random number generating function that was not designed for security. An example is the rand() function in C, which can be accessed from Swift. This output can end up being very predictable! 

To create a secure salt,  we will use the function SecRandomCopyBytes to create cryptographically secure random bytes—which is to say, numbers that are difficult to predict. 

To use the code, you'll need to add the following into your bridging header:
#import <CommonCrypto/CommonCrypto.h>

Here is the start of the code that creates a salt. We will add to this code as we go along:

Now we are ready to do key stretching. Fortunately, we already have a function at our disposal to do the actual stretching: the Password-Based Key Derivation Function (PBKDF2). PBKDF2 performs a function many times over to derive the key; increasing the number of iterations expands the time it would take to operate on a set of keys during a brute force attack. It is recommended to use PBKDF2 to generate your key.

Server-Side Key

You may be wondering now about the cases where you don't want to require users to provide a password within your app. Perhaps they are already authenticating with a single sign-on scheme. In this case, have your server generate an AES 256-bit (32 byte) key using a secure generator. The key should be different for different users or devices. On authenticating with your server, you can pass the server a device or user ID over a secure connection, and it can send the corresponding key back. 

This scheme has a major difference. If the key is coming from the server, the entity that controls that server has the capacity to be able to read the encrypted data if the device or data were ever obtained. There is also the potential for the key to be leaked or exposed at a later time. 

On the other hand, if the key is derived from something only the user knows—the user's password—then only the user can decrypt that data. If you are protecting information such as private financial data, only the user should be able to unlock the data. If that information is known to the entity anyway, it may be acceptable to have the server unlock the content via a server-side key.

Modes and IVs

Now that we have a key, let's encrypt some data. There are different modes of encryption, but we'll be using the recommended mode: cipher block chaining (CBC). This operates on our data one block at a time. 

A common pitfall with CBC is the fact that each next unencrypted block of data is XOR’d with the previous encrypted block to make the encryption stronger. The problem here is that the first block is never as unique as all the others. If a message to be encrypted were to start off the same as another message to be encrypted, the beginning encrypted output would be the same, and that would give an attacker a clue to figuring out what the message might be. 

To get around this potential weakness, we'll start the data to be saved with what is called an initialization vector (IV): a block of random bytes. The IV will be XOR’d with the first block of user data, and since each block depends on all blocks processed up until that point, it will ensure that the entire message will be uniquely encrypted, even if it has the same data as another message. In other words, identical messages encrypted with the same key will not produce identical results. So while salts and IVs are considered public, they should not be sequential or reused. 

We will use the same secure SecRandomCopyBytes function to create the IV.

Putting It All Together

To complete our example, we'll use the CCCrypt function with either kCCEncrypt or kCCDecrypt. Because we are using a block cipher, if the message doesn’t fit nicely into a multiple of the block size, we will need to tell the function to automatically add padding to the end. 

As usual in encryption, it is best to follow established standards. In this case, the standard PKCS7 defines how to pad the data. We tell our encryption function to use this standard by supplying the KCCOptionPKCS7Padding option. Putting it all together, here is the full code to encrypt and decrypt a string.

And here is the decryption code:

Finally, here is a test to ensure that data is decrypted correctly after encryption:

In our example, we package all the necessary information and return it as a Dictionary so that all the pieces can later be used to successfully decrypt the data. You only need to store the IV and salt, either in the keychain or on your server.


This completes the three-part series on securing data at rest. We have seen how to properly store passwords, sensitive pieces of information, and large amounts of user data. These techniques are the baseline for protecting stored user information in your app.

It is a huge risk when a user's device is lost or stolen, especially with recent exploits to gain access to a locked device. While many system vulnerabilities are patched with a software update, the device itself is only as secure as the user's passcode and version of iOS. Therefore it is up to the developer of each app to provide strong protection of sensitive data being stored. 

All of the topics covered so far make use of Apple's frameworks. I will leave an idea with you to think about. What happens when Apple's encryption library gets attacked? 

When one commonly used security architecture is compromised, all of the apps that rely on it are also compromised. Any of iOS's dynamically linked libraries, especially on jailbroken devices, can be patched and swapped with malicious ones. 

However, a static library that is bundled with the binary of your app is protected from this kind of attack because if you try and patch it, you end up changing the app binary. This will break the code signature of the app, preventing it from being launched. If you imported and used, for example, OpenSSL for your encryption, your app would not be vulnerable to a widespread Apple API attack. You can compile OpenSSL yourself and statically link it into your app.

So there is always more to learn, and the future of app security on iOS is always evolving. The iOS security architecture even now supports cryptographic devices and smart cards! In closing, you now know the best practices for securing data at rest, so it's up to you to follow them!

In the meantime, check out some of our other content about iOS app development and app security.

  • Security
    How to Hack Your Own App
    Tanya Janca
  • iOS
    Go Further With Swift: Animation, Networking, and Custom Controls
    Markus Mühlberger
  • Swift
    Swift From Scratch: Delegation and Properties
    Bart Jacobs


How to Work With Elixir Comprehensions

Elixir is a very young programming language (emerged in 2011), but it is gaining popularity. I was initially interested in this language because when using it you can look at some common tasks programmers usually solve from a different angle. For instance, you can find out how to iterate over collections without the for cycle, or how to organize your code without classes.

Elixir has some very interesting and powerful features that may be hard to get your head around if you came from the OOP world. However, after some time it all starts to make sense, and you see how expressive the functional code can be. Comprehensions are one such feature, and this article I will explain how to work with them.

Comprehensions and Mapping

Generally speaking, a list comprehension is a special construct that allows you to create a new list based on existing ones. This concept is found in languages like Haskell and Clojure. Erlang also presents it and, therefore, Elixir has comprehensions as well.

You might ask how comprehensions are different from the map/2 function, which also takes a collection and produces a new one? That would be a fair question! Well, in the simplest case, comprehensions do pretty much the same thing. Take a look at this example:

Here I am simply taking a list with three numbers and producing a new list with all the numbers multiplied by 2. The map call can be further simplified as &(&1 * 2) ).

The do_something/1 function can now be rewritten using a comprehension:

This is what a basic comprehension looks like and, in my opinion, the code is a bit more elegant than in the first example. Here, once again, we take each element from the list and multiply it by 2. The el <- list part is called a generator, and it explains how exactly you wish to extract the values from your collection.

Note that we are not forced to pass a list to the do_something/1 function—the code will work with anything that is enumerable:

In this example, I am passing a range as an argument.

Comprehensions work with binstrings as well. The syntax is slightly different as you need to enclose your generator with << and >>. Let's demonstrate this by crafting a very simple function to "decipher" a string protected with a Caesar cipher. The idea is simple: we replace each letter in the word with a letter a fixed number of positions down the alphabet. I'll shift by 1 position for simplicity:

This is looking pretty much the same as the previous example except for the << and >> parts. We take a code of each character in a string, decrement it by one, and construct a string back. So the ciphered message was "elixir"!

But still, there is more than that. Another useful feature of comprehensions is the ability to filter out some elements.

Comprehensions and Filtering

Let's further extend our initial example. I am going to pass a range of integers from 1 to 20, take only the elements that are even, and multiply them by 2:

Here I had to require the Integer module to be able to use the is_even/1 macro. Also, I am using Stream to optimize the code a bit and prevent the iteration from being performed twice.

Now let's rewrite this example with a comprehension again:

So, as you see, for can accept an optional filter to skip some elements from the collection.

You are not limited to only one filter, so the following code is legit as well:

It will take all even numbers less than 10. Just don't forget to delimit filters with commas.

The filters will be evaluated for each element of the collection, and if evaluation returns true, the block is executed. Otherwise, a new element is taken. What's interesting is that generators can also be used to filter out elements by using when:

This is very similar to what we do when writing guard clauses:

Comprehensions With Multiple Collections

Now suppose we have not one but two collections at once, and we'd like to produce a new collection. For example, take all even numbers from the first collection and odd from the second one, and then multiply them:

This example illustrates that comprehensions may work with more than one collection at once. The first even number from collection1 will be taken and multiplied by each odd number from collection2. Next, the second even integer from collection1 will be taken and multiplied, and so on. The result will be: 

What's more, the resulting values are not required to be integers. For instance, you may return a tuple containing integers from the first and the second collections:

Comprehensions With the "Into" Option

Up to this point, the final result of our comprehension was always a list. This is, actually, not mandatory either. You can specify an into parameter that accepts a collection to contain the resulting value. 

This parameter accepts any structure that implements the Collectable protocol, so for example we may generate a map like this:

Here I simply said into:, which can be also replaced with into: %{}. By returning the {el1, el2} tuple, we basically set the first element as a key and the second as the value.

This example is not particularly useful, however, so let's generate a map with a number as a key and its square as a value:

In this example I am using Erlang's :math module directly, as, after all, all modules' names are atoms. Now you can easily find the square for any number from 1 to 20.

Comprehensions and Pattern Matching

The last thing to mention is that you can perform pattern matching in comprehensions as well. In some cases it may come in pretty handy.

Suppose we have a map containing employees' names and their raw salaries:

I want to generate a new map where the names are downcased and converted to atoms, and salaries are calculated using a tax rate:

In this example we define a module attribute @tax with an arbitrary number. Then I deconstruct the data in the comprehension using {name, salary} <- collection. Lastly, format the name and calculate the salary as needed, and store the result in the new map. Quite simple yet expressive.


In this article we have seen how to use Elixir comprehensions. You may need some time to get accustomed to them. This construct is really neat and in some situations can fit in much better than functions like map and filter. You can find some more examples in Elixir's official docs and the getting started guide.

Hopefully, you've found this tutorial useful and interesting! Thank you for staying with me, and see you soon.

June 22 2017


Creating a Grocery List Manager Using Angular, Part 2: Managing Items

In the first part of this Angular tutorial series, you saw how to get started with creating a Grocery List Manager using Angular. You learnt how to create the view for the Grocery component, adding items to the grocery list and displaying the added items.

In this part, you'll implement the features to mark completed items, edit existing items, and remove added items.

Getting Started

Let's get started by cloning the source code from the first part of the tutorial. From your terminal, write in the following code to clone the source code:

Once the source code has been cloned, navigate to the project folder and install the required dependencies.

After installing the dependencies, you will be able to start the server. From the project folder, type in the following commands:

Point your browser to http://localhost:4200/ and you should have the application running.

Updating Grocery Items

Once you have the grocery items added to the list, you should be able to edit and update the items. Let's provide an edit button in the listing grid which, when clicked, will enable the editing of existing items.

Modify the code to include the edit button inside the grid.

Save the above changes and restart the server. Load the page and enter a few items and you will have the edit button for each item.

Grocery List Manager - Edit Button

When the user clicks the edit button, you need to add an on click method to handle the item edit. Modify the to add an on click event for editing the item.

Pass the task to the onEdit method as shown in the above code to identify the item to be edited.

Inside the GroceryComponent class initialize the task scope variable as shown:

In the onClick method, you'll check for the id to see if it's an existing item or a new item. Modify the onClick method as shown:

As seen, you have assigned a unique time stamp as id to each task. Now let's define the onEdit method to edit the existing item. Inside the onEdit method, assign the passed in item to the task variable.

Save the changes and restart the server. Enter a new item in the grocery list and click on the corresponding edit button. You will be able to edit and update the entry by clicking the OK button.

Grocery List Manager - Edit and Update

Deleting Grocery Items

Let's add a delete icon to remove the existing items. Update the file to modify the HTML code as shown:

Here is how the complete file looks:

Add an on click event to the remove icon to delete the grocery item.

Save the changes and restart the server. Try adding new items to the grocery manager app and you will have the items listed along with the delete and edit icons.

Grocery List Manager App - Delete View

To implement the delete functionality, you need to add the onDelete method in the file as shown:

Once the user clicks the delete icon, you need to check the item id against the grocery item list and remove the entry from the tasks list. Here is how the onDelete method looks:

As seen in the above code, you have iterated the tasks list and checked it against the clicked item id. If it matched the item in the tasks list, it is removed using the splice method.

Save the above changes and restart the server. Add a few items to the grocery list manager. It will be added with the delete and edit icons to the task list grid. Try clicking on the remove icon and the item will be deleted from the items list.

Marking the Grocery Item as Done

Let's add the functionality to strike out the items added to the list. Once the user is done with the tasks in the grocery list manager, it should be possible to strike out the completed tasks. To track the new and completed tasks, add a new variable strike to the task information. 

Modify the onClick method to include the new strike variable as shown:

Add a new class called strike in the src/style.css file which would strike out the item.

Include an on click event on the item to toggle the strike variable in the items variable. You'll be applying the strike class to the items based on the boolean value of the strike variable. By default, it will be false. Here is the onStrike method to toggle the strike variables value:

As seen in the above method, you iterate through the list of items. Once the item is found, you toggle the strike value.

Based on the strike variable, you need to apply the class strike to the task name span. Here is how it looks:

As seen, you have used the ngClass directive to apply the class strike to the span element if the task.strike value is true.

Save the above changes and restart the server. Add the items to the list and click on the added item. Once clicked, the item will be struck out as expected.

Grocery List Manager - Strike Out Completed Task

Wrapping It Up

In this tutorial, you saw how to update, delete and mark the task as complete in the grocery manager app using Angular. I hope you enjoyed the tutorial. Do let me know your thoughts in the comments below.

JavaScript has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

Oh, and don't forget that the source code from this tutorial is available on GitHub.


Using Celery With Django for Background Task Processing

Web applications usually start out simple but can become quite complex, and most of them quickly exceed the responsibility of only responding to HTTP requests.

When that happens, one must make a distinction between what has to happen instantly (usually in the HTTP request lifecycle) and what can happen eventually. Why is that? Well, because when your application becomes overloaded with traffic, simple things like this make the difference. 

Operations in a web application can be classified as critical or request-time operations and background tasks, the ones that happen outside request time. These map to the ones described above: 

  • needs to happen instantly: request-time operations
  • needs to happen eventually: background tasks

Request-time operations can be done on a single request/response cycle without worrying that the operation will time out or that the user might have a bad experience. Common examples include CRUD (Create, Read, Update, Delete) database operations and user management (Login/Logout routines).

Background tasks are different as they are usually quite time-consuming and are prone to failure, mostly due to external dependencies. Some common scenarios among complex web applications include:

  • sending confirmation or activity emails
  • daily crawling and scraping some information from various sources and storing them
  • performing data analysis
  • deleting unneeded resources
  • exporting documents/photos in various formats

Background tasks are the main focus of this tutorial. The most common programming pattern used for this scenario is the Producer Consumer Architecture. 

In simple terms, this architecture can be described like this: 

  • Producers create data or tasks.
  • Tasks are put into a queue that is referred to as the task queue. 
  • Consumers are responsible for consuming the data or running the tasks. 

Usually, the consumers retrieve tasks from the queue in a first-in-first-out (FIFO) fashion or according to their priorities. The consumers are also referred to as workers, and that is the term we will be using throughout, as it is consistent with the terminology used by the technologies discussed.

What kind of tasks can be processed in the background? Tasks that:

  • are not essential for the basic functionality of the web application
  • can't be run in the request/response cycle since they are slow (I/O intensive, etc.)
  • depend on external resources that might not be available or not behave as expected
  • might need to be retried at least once
  • have to be executed on a schedule

Celery is the de facto choice for doing background task processing in the Python/Django ecosystem. It has a simple and clear API, and it integrates beautifully with Django. It supports various technologies for the task queue and various paradigms for the workers.

In this tutorial, we're going to create a Django toy web application (dealing with real-world scenarios) that uses background task processing.

Setting Things Up

Assuming you are already familiar with Python package management and virtual environments, let's install Django:

I've decided to build yet another blogging application. The focus of the application will be on simplicity. A user can simply create an account and without too much fuss can create a post and publish it to the platform. 

Set up the quick_publisher Django project:

Let's get the app started:

When starting a new Django project, I like to create a main application that contains, among other things, a custom user model. More often than not, I encounter limitations of the default Django User model. Having a custom User model gives us the benefit of flexibility.

Make sure to check out the Django documentation if you are not familiar with how custom user models work.

Now we need to tell Django to use this User model instead of the default one. Add this line to the quick_publisher/ file:

We also need to add the main application to the INSTALLED_APPS list in the quick_publisher/ file. We can now create the migrations, apply them, and create a superuser to be able to log in to the Django admin panel:

Let's now create a separate Django application that's responsible for posts:

Let's define a simple Post model in publisher/

Hooking the Post model with the Django admin is done in the publisher/ file like this:

Finally, let's hook the publisher application with our project by adding it to the INSTALLED_APPS list.

We can now run the server and head over to http://localhost:8000/admin/ and create our first posts so that we have something to play with:

I trust you've done your homework and you've created the posts. 

Let's move on. The next obvious step is to create a way to view the published posts. 

Let's associate our new view with an URL in: quick_publisher/

Finally, let's create the template that renders the post in: publisher/templates/post.html

We can now head to http://localhost:8000/the-slug-of-the-post-you-created/ in the browser. It's not exactly a miracle of web design, but making good-looking posts is beyond the scope of this tutorial.

Sending Confirmation Emails

Here's the classic scenario:

  • You create an account on a platform.
  • You provide an email address to be uniquely identified on the platform.
  • The platform checks you are indeed the owner of the email address by sending an email with a confirmation link.
  • Until you perform the verification, you are not able to (fully) use the platform.

Let's add an is_verified flag and the verification_uuid on the User model:

Let's use this occasion to add the User model to the admin:

Let's make the changes reflect in the database:

We now need to write a piece of code that sends an email when a user instance is created. This is what Django signals are for, and this is a perfect occasion to touch this subject. 

Signals are fired before/after certain events occur in the application. We can define callback functions that are triggered automatically when the signals are fired. To make a callback trigger, we must first connect it to a signal.

We're going to create a callback that will be triggered after a User model has been created. We'll add this code after the User model definition in: main/

What we've done here is we've defined a user_post_save function and connected it to the post_save signal (one that is triggered after a model has been saved) sent by the User model.

Django doesn't just send emails out on its own; it needs to be tied to an email service. For the sake of simplicity, you can add your Gmail credentials in quick_publisher/, or you can add your favourite email provider. 

Here's what Gmail configuration looks like:

To test things out, go into the admin panel and create a new user with a valid email address you can quickly check. If all went well, you'll receive an email with a verification link. The verification routine is not ready yet. 

Here's how to verify the account:

Hook the views up in: quick_publisher/

Also, remember to create a home.html file under main/templates/home.html. It will be rendered by the home view.

Try to run the entire scenario all over again. If all is well, you'll receive an email with a valid verification URL. If you'll follow the URL and then check in the admin, you can see how the account has been verified.

Sending Emails Asynchronously

Here's the problem with what we've done so far. You might have noticed that creating a user is a bit slow. That's because Django sends the verification email inside the request time. 

This is how it works: we send the user data to the Django application. The application creates a User model and then creates a connection to Gmail (or another service you selected). Django waits for the response, and only then does it return a response to our browser. 

Here is where Celery comes in. First, make sure it is installed:

We now need to create a Celery application in our Django application:

Celery is a task queue. It receives tasks from our Django application, and it will run them in the background. Celery needs to be paired with other services that act as brokers. 

Brokers intermediate the sending of messages between the web application and Celery. In this tutorial, we'll be using Redis. Redis is easy to install, and we can easily get started with it without too much fuss.

You can install Redis by following the instructions on the Redis Quick Start page. You'll need to install the Redis Python library, pip install redis, and the bundle necessary for using Redis and Celery: pip install celery[redis].

Start the Redis server in a separate console like this: $ redis-server

Let's add the Celery/Redis related configs into quick_publisher/

Before anything can be run in Celery, it must be declared as a task. 

Here's how to do this:

What we've done here is this: we moved the sending verification email functionality in another file called

A few notes:

  • The name of the file is important. Celery goes through all the apps in INSTALLED_APPS and registers the tasks in files.
  • Notice how we decorated the send_verification_email function with @app.task. This tells Celery this is a task that will be run in the task queue.
  • Notice how we expect as argument user_id rather than a User object. This is because we might have trouble serializing complex objects when sending the tasks to Celery. It's best to keep them simple.

Going back to main/, the signal code turns into:

Notice how we call the .delay method on the task object. This means we're sending the task off to Celery and we don't wait for the result. If we used send_verification_email( instead, we would still be sending it to Celery, but would be waiting for the task to finish, which is not what we want.

Before you start creating a new user, there's a catch. Celery is a service, and we need to start it. Open a new console, make sure you activate the appropriate virtualenv, and navigate to the project folder.

This starts four Celery process workers. Yes, now you can finally go and create another user. Notice how there's no delay, and make sure to watch the logs in the Celery console and see if the tasks are properly executed. This should look something like this:

Periodic Tasks With Celery

Here's another common scenario. Most mature web applications send their users lifecycle emails in order to keep them engaged. Some common examples of lifecycle emails:

  • monthly reports
  • activity notifications (likes, friendship requests, etc.)
  • reminders to accomplish certain actions ("Don't forget to activate your account")

Here's what we're going to do in our app. We're going to count how many times every post has been viewed and send a daily report to the author. Once every single day, we're going to go through all the users, fetch their posts, and send an email with a table containing the posts and view counts.

Let's change the Post model so that we can accommodate the view counts scenario.

As always, when we change a model, we need to migrate the database:

Let's also modify the view_post Django view to count views:

It would be useful to display the view_count in the template. Add this <p>Viewed {{ post.view_count }} times</p> somewhere inside the publisher/templates/post.html file. Do a few views on a post now and see how the counter increases.

Let's create a Celery task. Since it is about posts, I'm going to place it in publisher/

Every time you make changes to the Celery tasks, remember to restart the Celery process. Celery needs to discover and reload tasks. Before creating a periodic task, we should test this out in the Django shell to make sure everything works as intended:

Hopefully, you received a nifty little report in your email. 

Let's now create a periodic task. Open up quick_publisher/ and register the periodic tasks:

So far, we created a schedule that would run the task publisher.tasks.send_view_count_report every minute as indicated by the crontab() notation. You can also specify various Celery Crontab schedules

Open up another console, activate the appropriate environment, and start the Celery Beat service. 

The Beat service's job is to push tasks in Celery according to the schedule. Take into account that the schedule makes the send_view_count_report task run every minute according to the setup. It's good for testing but not recommended for a real-world web application.

Making Tasks More Reliable

Tasks are often used to perform unreliable operations, operations that depend on external resources or that can easily fail due to various reasons. Here's a guideline for making them more reliable:

  • Make tasks idempotent. An idempotent task is a task that, if stopped midway, doesn't change the state of the system in any way. The task either makes full changes to the system or none at all.
  • Retry the tasks. If the task fails, it's a good idea to try it again and again until it's executed successfully. You can do this in Celery with Celery Retry. One other interesting thing to look at is the Exponential Backoff algorithm. This could come in handy when thinking about limiting unnecessary load on the server from retried tasks.


I hope this has been an interesting tutorial for you and a good introduction to using Celery with Django. 

Here are a few conclusions we can draw:

  • It's good practice to keep unreliable and time-consuming tasks outside the request time.
  • Long-running tasks should be executed in the background by worker processes (or other paradigms).
  • Background tasks can be used for various tasks that are not critical for the basic functioning of the application.
  • Celery can also handle periodic tasks using the celery beat service.
  • Tasks can be more reliable if made idempotent and retried (maybe using exponential backoff).

June 21 2017


Android Design Patterns: The Observer Pattern

What Is the Observer Pattern?

The Observer Pattern is a software design pattern that establishes a one-to-many dependency between objects. Anytime the state of one of the objects (the "subject" or "observable") changes, all of the other objects ("observers") that depend on it are notified.

Let's use the example of users that have subscribed to receive offers from Envato Market via email. The users in this case are observers. Anytime there is an offer from Envato Market, they get notified about it via email. Each user can then either buy into the offer or decide that they might not be really interested in it at that moment. A user (an observer) can also subscribe to receive offers from another e-commerce marketplace if they want and might later completely unsubscribe from receiving offers from any of them. 

This pattern is very similar to the Publish-Subscribe pattern. The subject or observable publishes out a notification to the dependent observers without even knowing how many observers have subscribed to it, or who they are—the observable only knows that they should implement an interface (we'll get to that shortly), without worrying about what action the observers might perform.

Benefits of the Observer Pattern

  • The subject knows little about its observers. The only thing it knows is that the observers implement or agree to a certain contract or interface. 
  • Subjects can be reused without involving their observers, and the same goes for observers too.
  • No modification is done to the subject to accommodate a new observer. The new observer just needs to implement an interface that the subject is aware of and then register to the subject.  
  • An observer can be registered to more than one subject it's registered to.

All these benefits give you loose coupling between modules in your code, which enables you to build a flexible design for your application. In the rest of this post, we'll look at how to create our own Observer pattern implementation, and we'll also use the built-in Java Observer/Observable API as well as looking into third-party libraries that can offer such functionality. 

Building Our Own Observer Pattern

1. Create the Subject Interface

We start by defining an interface that subjects (observables) will implement.

In the code above, we created a Java Interface with three methods. The first method registerObserver(), as it says, will register an observer of type RepositoryObserver (we'll create that interface shortly) to the subject. removeObserver() will be called to remove an observer that wants to stop getting notifications from the subject, and finally, notifyObserver() will send a broadcast to all observers whenever there is a change. Now, let's create a concrete subject class that will implement the subject interface we have created:

The class above implements the Subject interface. We have an ArrayList that holds the observers and then creates it in the private constructor. An observer registers by being added to the ArrayList and likewise, unregisters by being removed from the  ArrayList

Note that we are simulating a network request to retrieve the new data. Once the setUserData() method is called and given the new value for the full name and age, we call the notifyObservers() method which, as it says, notifies or sends a broadcast to all registered observers about the new data change. The new values for the full name and age are also passed along. This subject can have multiple observers but, in this tutorial, we'll create just one observer. But first, let's create the observer interface. 

2. Create the Observer Interface

In the code above, we created the observer interface which concrete observers should implement. This allows our code to be more flexible because we are coding to an interface instead of a concrete implementation. A concrete Subject class does not need to be aware of the many concrete observers it may have; all it knows about them is that they implement the RepositoryObserver interface. 

Let's now create a concrete class that implements this interface.

The first thing to notice in the code above is that UserProfileActivity implements the RepositoryObserver interface—so it must implement the method onUserDataChanged(). In the onCreate() method of the Activity, we got an instance of the UserDataRepository which we then initialized and finally registered this observer to. 

In the onDestroy() method, we want to stop getting notifications, so we unregister from receiving notifications. 

In the onUserDataChanged() method, we want to update the TextView widgets—mTextViewUserFullName and mTextViewUserAge—with the new set of data values.  

Right now we just have one observer class, but it's possible and easy for us to create other classes that want to be observers of the UserDataRepository class. For example, we could easily have a SettingsActivity that wants to also be notified about the user data changes by becoming an observer. 

Push and Pull Models

In the example above, we are using the push model of the observer pattern. In this model, the subject notifies the observers about the change by passing along the data that changed. But in the pull model, the subject will still notify the observers, but it does not actually pass the data that changed. The observers then pull the data they need once they receive the notification. 

Utilising Java's Built-In Observer API

So far, we have created our own Observer pattern implementation, but Java has built-in Observer / Observable support in its API. In this section, we are going to use this. This API simplifies some of the implementation, as you'll see. 

1. Create the Observable

Our UserDataRepository—which is our subject or observable—will now extend the java.util.Observable superclass to become an Observable. This is a class that wants to be observed by one or more observers. 

Now that we have refactored our UserDataRepository class to use the Java Observable API, let's see what has changed compared to the previous version. The first thing to notice is that we are extending a super class (this means that this class can't extend any other class) and not implementing an interface as we did in the previous section. 

We are no longer holding an ArrayList of observers; this is handled in the super class. Similarly, we don't have to worry about registration, removal, or notification of observers—java.util.Observable is handling all of those for us. 

Another difference is that in this class we are employing a pull style. We alert the observers that a change has happened with notifyObservers(), but the observers will need to pull the data using the field getters we have defined in this class. If you want to use the push style instead, then you can use the method notifyObservers(Object arg) and pass the changed data to the observers in the object argument. 

The setChanged() method of the super class sets a flag to true, indicating that the data has changed. Then you can call the notifyObservers() method. Be aware that if you don't call setChanged() before calling notifyObsevers(), the observers won't be notified. You can check the value of this flag by using the method hasChanged() and clear it back to false with clearChanged(). Now that we have our observable class created, let's see how to set up an observer also.  

2. Create the Observer

Our UserDataRepository observable class needs a corresponding Observer to be useful, so let's refactor our UserProfileActivity to implement the java.util.Observer interface. 

In the onCreate() method, we add this class as an observer to the UserDataRepository observable by using the addObserver() method in the java.util.Observable super class.  

In the update() method which the observer must implement, we check if the Observable we receive as a parameter is an instance of our UserDataRepository (note that an observer can subscribe to different observables), and then we cast it to that instance and retrieve the values we want using the field getters. Then we use those values to update the view widgets. 

When the activity is destroyed, we don't need to get any updates from the observable, so we'll just remove the activity from the observer list by calling the method deleteObserver()

Libraries to Implement an Observer Pattern

If you don't want to build your own Observer pattern implementation from scratch or use the Java Observer API, you can use some free and open-source libraries that are available for Android such as Greenrobot's EventBus. To learn more about it, check out my tutorial here on Envato Tuts+.

  • Android
    Communication Within an Android App With EventBus
    Chike Mgbemena

Or, you might like RxAndroid and RxJava. Learn more about them here:

  • Android
    Getting Started With ReactiveX on Android
    Ashraff Hathibelagal


In this tutorial, you learned about the Observer pattern in Java: what is it, the benefits of using it, how to implement your own, using the Java Observer API, and also some third-party libraries for implementing this pattern. 

In the meantime, check out some of our other courses and tutorials on the Java language and Android app development!

  • Android SDK
    RxJava 2 for Android Apps: RxBinding and RxLifecycle
    Jessica Thornsby
  • Android SDK
    Practical Concurrency on Android With HaMeR
    Tin Megali
  • Android
    Ensure High-Quality Android Code With Static Analysis Tools
    Chike Mgbemena
  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal


12 Best Contact Form PHP Scripts

Contact forms are a must have for every website. They encourage your site visitors to engage with you while potentially lowering the amount of spam you get.

For businesses, this engagement with visitors increases the chances of turning them into clients or customers and thus increasing revenue.

Whether your need is for a simple three-line contact form or a more complex one that offers loads of options and functions, you’re sure to find the right PHP contact form here in our 12Best Contact Form PHP Scripts on CodeCanyon.

1. Perfect Contact Us Form

Perfect Contact Us Form is a Bootstrap-based form which is fully customisable and easy to use. It integrates easily with HTML and PHP pages, and all fields use jQuery validation script.

Perfect Contact Us Form

Best features:

  • AJAX based
  • both SMPT and PHP email script
  • jQuery-based Captcha is included for anti spam
  • and more

The PerfectContact Us Form is an easy-to-use form that will appeal to both beginners and more experienced alike.

2. Quform- Responsive AJAX Contact Form

Quform is a versatile AJAX contact form that can be adapted to be a register form, quote form, or any other form needed.

Quform - Responsive AJAX Contact Form

Best features:

  • three ready-to-use themes with six variations
  • ability to integrate into your own theme design
  • ability to create complex form layouts
  • file uploads supported
  • and more

With tons of other customisations available, Quform- Responsive AJAX Contact Form is bound to keep the most discerning user happy.  

3. PHP Form Builder

A CodeCanyon top seller, PHP Form Builder includes the jQuery live validation plugin which enables you to build any type of form, connect your database, insert, update or delete records and send your emails using customizable HTML/CSS templates.

PHP Form Builder

Best features:

  • over 50 prebuilt templates included
  • accepts any HTML5 form elements
  • default options ready for Bootstrap
  • email sending with advanced options
  • and more

With loads of options for creating a variety of elegant contact forms and extensive documentation to help you on your way, PHP Form Builder is definitely a top choice for PHP site owners.

4. SLEEK Contact Form

Having made its debut in April 2017, SLEEK Contact Form is the newest contact form PHP Script on CodeCanyon, and with its simple and beautiful design and functionality, it promises to have a great future.

SLEEK Contact Form

Best features:

  • invisible Google reCaptcha anti-spam system
  • ability to add attachments of any type
  • automatically get the IP and location of the sender inside email
  • easy to modify and implement new fields
  • and more

If you want a simple contact form with a bit of a wow factor, SLEEK Contact Form may be just what you’re looking for.

5. Ultimate PHP, HTML5 & AJAX Contact Form

The Ultimate PHP, HTML5 and AJAX Contact Form replaces the hugely successful AJAX Contact Form and allows you to easily place and manage a self-contained contact form on any page of your existing PHP website.

Ultimate PHP HTML5  AJAX Contact Form

Best features:

  • supports file uploads to attach to email
  • field type validation
  • multiple forms per page allowed
  • Google reCAPTCHA capable
  • and more

The Ultimate PHP, HTML5 & AJAX Contact Form is loaded with useful features that will satisfy PHP site owners looking for a reliable contact form.

6. Contact Form Generator - Easy & Powerful Form Builder

Contact Form Generator is one of CodeCanyon’s best-selling Contact Form PHP Scripts.  It features a user-friendly drag-and-drop interface that helps you build contact forms, feedback forms, online surveys, event registrations etc. and get responses via email in a matter of minutes.

Contact Form Generator - Easy  Powerful Form Builder

Best features:

  • instant email or SMS notifications
  • custom email auto-responder
  • integrated with MailChimp, AWeber and five other email subscription services
  • anti-spam protection
  • and more

Contact Form Generator - Easy & Powerful Form Builder is a highly effective form builder that enables you to create well-designed contact forms and extend their range to include other functions.

7. KONTAKTO - AJAX Contact Form with Styled Map

KONTAKTO only entered the market in March of 2017 but has already developed a name for itself as one of the top-rated scripts in this category. The standout feature of this beautifully designed contact form is the stylish map with a location pin that comes integrated in the form.

KONTAKTO - AJAX Contact Form with Styled Map

Best features:

  • required field validation
  • anti spam with simple Captcha math
  • defaults to PHP mail but SMTP option available
  • repeat submission prevention
  • and more

Simple yet stylish, KONTAKTO - AJAX Contact Form with Styled Map can be easily integrated with your HTML or PHP page and will be a fast favourite with many PHP site owners.

8. ContactPLUS+ PHP Contact Form

ContactPlus+ is another clean and simple contact form which comes in three styles: an un-styled version that you can build to suit your taste, a normal form with just the essential information needed on a contact form, and a longer form to accommodate an address.

ContactPLUS - PHP Contact Form

Best features:

  • Captcha verification
  • successful submission message
  • two styled and one un-styled version
  • and more

If you’re looking for a clean and simple contact form that will integrate easily on you PHP website, ContactPLUS+ PHP Contact Form is the one for you.

9. AJAX Contact Pro - Multi-language HTML5, Bootstrap Contact Form

Built using jQuery and PHP, AJAX Contact Pro comes in eight style variations and has four HTML email templates. One of the features that make this form so special is that it enables users to translate the form fields into their language in real time. If a preferred language isn’t present in the predefined list, the site administrator can add it to the list.

AJAX Contact Pro - Multi-language HTML5 Bootstrap Contact Form

Best features:

  • AJAX form
  • field validations
  • animations
  • modular construction so it can be integrated in an existing project
  • and more

AJAXContact Pro - Multi-language HTML5, Bootstrap Contact Form is certainly a cool addition to the contact form PHP scripts offerings.

10. Hello Form Builder - Contact Form

Powered by AJAX and jQuery, the Hello Form Builder employs an easy-to-use drag-and-drop function to help site owners custom build contact forms with a variety of fields and features like file upload, file attachment, Captcha system, etc.

Hello Form Builder - Contact Form

Best features:

  • 50 background images included
  • ability to customise error messages
  • one-click installation
  • auto responder message
  • and more

Hello Form Builder - Contact Form is a user-friendly builder that will appeal to a wide cross-section of users.

11. Responsive Contact Form

The Responsive Contact Form has just one main option to configure—your email address—to make the script functional on your PHP site.

Responsive Contact Form

Best features

  • AJAX back end to save your bandwidth
  • uses JavaScript jQuery slide
  • very easy to integrate into any existing HTML or PHP page on your website
  • all fields have a validation script
  • and more

See Responsive Contact Form in action over at Code Canyon.

12. ContactForm with Custom Auto Responder

Another of Code Canyon’s top sellers, Contact Form with Custom Auto Responder is easy to edit and add to your PHP or HTML pages.

Contact Form With Custom Auto Responder

Best features:

  • dropdown subject selection with different emails
  • custom auto responder message
  • custom Captcha filter
  • no separate page needed for thank you message
  • and more

ContactForm With Custom Auto Responder has been around for a while but is still holding its own among the newcomers.


These 12 Best Contact Form PHP Scripts just scratch the surface of products available at Envato Market, so if none of them fit your needs, there are plenty of other great options you may prefer.

And if you want to improve your PHP skills, check out the ever so useful free PHP tutorials we have on offer.


Learn the Basics of PHP for WordPress in Our New Course

PHP is the language of WordPress. If you want to customize WordPress, for example by coding themes or plugins, PHP is the programming language you'll need to learn.

In our new Coffee Break Course, WordPress Coding Basics: Learn PHP, Envato Tuts+ instructor Rachel McCollin will give you a quick, ten-minute introduction to PHP coding in WordPress. 

You'll get an overview of PHP coding standards, and take a look at some of the most common WordPress functions that you'll be hooking up to with your code. You'll also learn about core WordPress coding concepts, such as actions and hooks, and you'll get lots of links to tutorials, courses and books that will help you keep learning.

Watch the introduction below to find out more.


You can take our new Coffee Break Course straight away with a free 10-day trial of our monthly subscription. If you decide to continue, it costs just $15 a month, and you’ll get access to hundreds of courses, with new ones added every week.

You can also find loads of useful PHP scripts and WordPress plugins over on Envato Market to help you with your WordPress development. And if you want to learn WordPress development from start to finish, check out our learning guide: Learn WordPress Development.

June 20 2017


How to Use the Google Cloud Vision API in Android Apps

Computer vision is considered an AI-complete problem. In other words, solving it would be equivalent to creating a program that's as smart as humans. Needless to say, such a program is yet to be created. However, if you've ever used apps like Google Goggles or Google Photos—or watched the segment on Google Lens in the keynote of Google I/O 2017—you probably realize that computer vision has become very powerful.

Through a REST-based API called Cloud Vision API, Google shares its revolutionary vision-related technologies with all developers. By using the API, you can effortlessly add impressive features such as face detection, emotion detection, and optical character recognition to your Android apps. In this tutorial, I'll show you how.


To be able to follow this tutorial, you must have:

If some of the above requirements sound unfamiliar to you, I suggest you read the following introductory tutorial about the Google Cloud Machine Learning platform:

  • Android SDK
    How to Use Google Cloud Machine Learning Services for Android
    Ashraff Hathibelagal

1. Enabling the Cloud Vision API

You can use the Cloud Vision API in your Android app only after you've enabled it in the Google Cloud console and acquired a valid API key. So start by logging in to the console and navigating to API Manager > Library > Vision API. In the page that opens, simply press the Enable button.

Enable Cloud Vision API

If you've already generated an API key for your Cloud console project, you can skip to the next step because you will be able to reuse it with the Cloud Vision API. Otherwise, open the Credentials tab and select Create Credentials > API key.

Create API key

In the dialog that pops up, you will see your API key.

2. Adding Dependencies

Like most other APIs offered by Google, the Cloud Vision API can be accessed using the Google API Client library. To use the library in your Android Studio project, add the following compile dependencies in the app module's build.gradle file:

Furthermore, to simplify file I/O operations, I suggest you also add a compile dependency for the Apache Commons IO library.

Because the Google API Client can work only if your app has the INTERNET permission, make sure the following line is present in your project's manifest file:

3. Configuring the API Client

You must configure the Google API client before you use it to interact with the Cloud Vision API. Doing so primarily involves specifying the API key, the HTTP transport, and the JSON factory it should use. As you might expect, the HTTP transport will be responsible for communicating with Google's servers, and the JSON factory will, among other things, be responsible for converting the JSON-based results the API generates into Java objects. 

For modern Android apps, Google recommends that you use the NetHttpTransport class as the HTTP transport and the AndroidJsonFactory class as the JSON factory.

The Vision class represents the Google API Client for Cloud Vision. Although it is possible to create an instance of the class using its constructor, doing so using the Vision.Builder class instead is easier and more flexible.

While using the Vision.Builder class, you must remember to call the setVisionRequestInitializer() method to specify your API key. The following code shows you how:

Once the Vision.Builder instance is ready, you can call its build() method to generate a new Vision instance you can use throughout your app.

At this point, you have everything you need to start using the Cloud Vision API.

4. Detecting and Analyzing Faces

Detecting faces in photographs is a very common requirement in computer vision-related applications. With the Cloud Vision API, you can create a highly accurate face detector that can also identify emotions, lighting conditions, and face landmarks.

For the sake of demonstration, we'll be running face detection on the following photo, which features the crew of Apollo 9:

Sample photo for face detection

I suggest you download a high-resolution version of the photo from Wikimedia Commons and place it in your project's res/raw folder.

Step 1: Encode the Photo

The Cloud Vision API expects its input image to be encoded as a Base64 string that's placed inside an Image object. Before you generate such an object, however, you must convert the photo you downloaded, which is currently a raw image resource, into a byte array. You can quickly do so by opening its input stream using the openRawResource() method of the Resources class and passing it to the toByteArray() method of the IOUtils class.

Because file I/O operations should not be run on the UI thread, make sure you spawn a new thread before opening the input stream. The following code shows you how:

You can now create an Image object by calling its default constructor. To add the byte array to it as a Base64 string, all you need to do is pass the array to its encodeContent() method.

Step 2: Make a Request

Because the Cloud Vision API offers several different features, you must explicitly specify the feature you are interested in while making a request to it. To do so, you must create a Feature object and call its setType() method. The following code shows you how to create a Feature object for face detection only:

Using the Image and the Feature objects, you can now compose an AnnotateImageRequest instance.

Note that an AnnotateImageRequest object must always belong to a BatchAnnotateImagesRequest object because the Cloud Vision API is designed to process multiple images at once. To initialize a BatchAnnotateImagesRequest instance containing a single AnnotateImageRequest object, you can use the Arrays.asList() utility method.

To actually make the face detection request, you must call the execute() method of an Annotate object that's initialized using the BatchAnnotateImagesRequest object you just created. To generate such an object, you must call the annotate() method offered by the Google API Client for Cloud Vision. Here's how:

Step 3: Use the Response

Once the request has been processed, you get a BatchAnnotateImagesResponse object containing the response of the API. For a face detection request, the response contains a FaceAnnotation object for each face the API has detected. You can get a list of all FaceAnnotation objects using the getFaceAnnotations() method.

A FaceAnnotation object contains a lot of useful information about a face, such as its location, its angle, and the emotion it is expressing. As of version 1, the API can only detect the following emotions: joy, sorrow, anger, and surprise.

To keep this tutorial short, let us now simply display the following information in a Toast:

  • The count of the faces
  • The likelihood that they are expressing joy

You can, of course, get the count of the faces by calling the size() method of the List containing the FaceAnnotation objects. To get the likelihood of a face expressing joy, you can call the intuitively named getJoyLikelihood() method of the associated FaceAnnotation object. 

Note that because a simple Toast can only display a single string, you'll have to concatenate all the above details. Additionally, a Toast can only be displayed from the UI thread, so make sure you call it after calling the runOnUiThread() method. The following code shows you how:

You can now go ahead and run the app to see the following result:

Face detection results

5. Reading Text

The process of extracting strings from photos of text is called optical character recognition, or OCR for short. The Cloud Vision API allows you to easily create an optical character reader that can handle photos of both printed and handwritten text. What's more, the reader you create will have no trouble reading angled text or text that's overlaid on a colorful picture.

The API offers two different features for OCR:

  • TEXT_DETECTION, for reading small amounts of text, such as that present on signboards or book covers
  • and DOCUMENT_TEXT_DETECTION, for reading large amounts of text, such as that present on the pages of a novel

The steps you need to follow in order to make an OCR request are identical to the steps you followed to make a face detection request, except for how you initialize the Feature object. For OCR, you must set its type to either TEXT_DETECTION or DOCUMENT_TEXT_DETECTION. For now, let's go with the former.

You will, of course, also have to place a photo containing text inside your project's res/raw folder. If you don't have such a photo, you can use this one, which shows a street sign:

Sample photo for text detection

You can download a high-resolution version of the above photo from Wikimedia Commons.

In order to start processing the results of an OCR operation, after you obtain the BatchAnnotateImagesResponse object, you must call the getFullTextAnnotation() method to get a TextAnnotation object containing all the extracted text.

You can then call the getText() method of the TextAnnotation object to actually get a reference to a string containing the extracted text.

The following code shows you how to display the extracted text using a Toast:

If you run your app now, you should see something like this:

Text detection results


In this tutorial you learned how to use the Cloud Vision API to add face detection, emotion detection, and optical character recognition capabilities to your Android apps. I'm sure you'll agree with me when I say that these new capabilities will allow your apps to offer more intuitive and smarter user interfaces.

It's worth mentioning that there's one important feature that's missing in the Cloud Vision API: face recognition. In its current form, the API can only detect faces, not identify them.

To learn more about the API, you can refer to the official documentation.

And meanwhile, check out some of our other tutorials on adding computer learning to your Android apps!

  • Android SDK
    How to Use Google Cloud Machine Learning Services for Android
    Ashraff Hathibelagal
  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal
  • Android Things
    Android Things and Machine Learning
    Paul Trebilcox-Ruiz

June 19 2017


Can You Make This Look Pretty?

Can You Make This Look Pretty?

One thing not to ask a designer and three reasons why

It happened again yesterday. I was working through the details of some random user interface problem, and a new email landed in my inbox. As soon as I read the harmless subject line, my heart sank a bit. I’d been asked once again to make something look pretty.

It wasn’t the first time in my career as a designer that I’d received a similar request, and it likely won’t be the last. Thankfully it doesn’t happen very often, and it almost always occurs within the context of a new working relationship where past experiences have formed a foundation of expectations about the roles to be played by each team member. I also realize that designers can be notoriously sensitive, and while this can be a very helpful trait, it can also lead to hasty emotional conclusions.

Despite knowing these things, I was a little surprised to be reminded of the effect this question had on me, so before moving ahead with my new assignment, I began to write down a few ideas that ultimately grew into this article. Initially I imagined publishing a list of communication tips for all people who interact with designers — something like “10 things you should never say to a designer” or perhaps “10 things you should never say to anyone” (if you prefer the “everyone is a designer” framing*). Maybe one day I’ll get around to this larger list, but for now I thought it might be helpful to unpack my thoughts about this question as well as offer a few tips to those about to ask it. Here goes.

Asking a designer to make something look pretty assumes that the core problem has already been identified.

One of the fundamental aspects of design is exploring the roots of problems — seeking to understand the deeper meanings, motivations, and influencing systems at the heart of things. A part of this discovery process involves asking clarifying questions about the makeup and desires of the intended audience as well as questions about the goals of the business and the context within which the message or product will be experienced.

Tip to requester-for-pretty: If you are not able to invite a designer to identify the problem with you, adding the backstory that addresses fundamental questions about the audience, their needs, and the needs of the business will make for a much prettier product.

Asking a designer to make something look pretty assumes that the best solution has already been determined.

Another fundamental aspect of design is imagining possible ideas that might effectively solve the identified problem or meet the identified goal. As these ideas emerge, they are tested, refined, and narrowed — expressing both form and function as drafts, sketches, prototypes, or even semi-finished products that sometimes just don’t look very pretty.

Tip to the requester-for-pretty: If you are not able to invite a designer to imagine and refine possible solutions with you, adding the backstory of how the thing you are handing off was developed into its current state will make for a much prettier product.

Asking a designer to make something look pretty assumes that the primary role of a designer is decoration.

I’m certainly not arguing that pretty is unimportant. The aesthetics of a message or product set the emotional context for engagement. Appearance establishes tone and even can make something function better, at least perceptually, because it is presented with a more attractive surface. Yet even the designer who has attained the highest level of mastery with the elements, principles, and tools of user interface design (or graphic design, visualization design, motion design, industrial design, etc.) still needs to find a way to integrate the form with the function. Asking someone to make something look pretty without also providing a context for understanding and insight diminishes their ability to do little more than provide you with an intuitive guess followed by the worst possible question for a designer to ask a client, “Do you like it?” (For a more extensive overview of things to keep in mind when presenting a design, I highly recommend Mike Monteiro’s advice, especially point #13).

Tip to the requester-for-pretty: If you wait until the end of a much longer process to ask a designer for help, you miss an opportunity for a much more thoughtfully integrated product. If nothing else, along with your request, pass along as much related insight and understanding as possible, and be open to some feedback that may challenge your core assumptions. Also, instead of asking, “Can you make this look pretty?”, consider rephrasing your question to something like:

  • Can you make this communicate more clearly?
  • Can you make this easier to use?
  • Can you make this more enjoyable to experience?

Back to my inbox. In case you’re wondering about the next steps I took with my new project, I picked up the phone, called the (well-intentioned, bright, and open-minded) person who sent me the email with the harmless subject line, and began asking questions.

I actually agree with the “everyone is a designer” framing, at least in the general sense that all people are creative and can help identify problems, imagine ideas for making things better, test these ideas, and contribute to future refinements of the thing being made. When the focus and meaning of design gets more particular, however, for example the field of graphic design (and understanding the principles, elements, and tools of the trade) referring to everyone as a designer becomes a confusing generalization.

Originally posted here on Medium, posted on UMS with permission from Mike.


What's New in Swift 4

Swift 4 has been in the works for the last few months. If you're like me, you might follow Swift Evolution to stay up to date with all the proposals and changes. Even if you do, now is a good time to review all the additions and changes to the language in this new iteration.

A snapshot of Swift 4 was already available a few weeks before Xcode 9 was announced at WWDC 2017. In this post you'll learn all about the new features introduced in Swift 4—from brand new APIs to improvements to the language syntax.

Let's first see how you can get the new compiler installed on your machine.

Xcode Setup

There are two ways to run Swift 4. You can either install the Xcode 9 beta if you have a developer account with access to it or you can set up Xcode 8 to run with a Swift 4 snapshot. In the former case, download the beta from your developer account download page.

If you prefer to use Xcode 8, simply head over to to download the latest Swift 4.0 Development snapshot. Once the download finishes, double-click to open the .pkg file, which installs the snapshot. 

Switch to Xcode now and go to Xcode > Toolchains > Manage Toolchains. From there, select the newly installed Swift 4.0 snapshot. Restart Xcode and now Swift 4 will be used when compiling your project or playground. Note that all the code presented in this tutorial is also available in a GitHub repo.

Swift 40 snapshot setup in Xcode 83

New Features

Let's take a look at the new features added to Swift 4. One caveat: the language is still in beta, and we will most likely see more changes and bug fixes before the official version is released. Moreover, some of the most recently approved proposals may still not be implemented at this time, so keep an eye on future release notes to see what will be implemented and fixed.

Encoding and Decoding

JSON parsing is one of the most discussed topics in the Swift community. It's great to see that someone finally took care of writing proposals SE-0166 and SE-0167 and pushed the idea to refresh the archival and serialization APIs in the Foundation framework. In Swift 4, there is no longer any need to parse or encode your class, struct or enum manually. 

New Encodable and Decodable protocols have been added, and you can make your classes conform to them by simply adding Codable (which is an alias for Decodable & Encodable) to the class's inheritance list. Then you can use the JSONEncoder to encode an instance of the class:

As you can see, you instantiate a JSONEncoder object to convert the struct to a JSON string representation. There are a few settings that you can tweak to get the exact JSON format you need. For example, to set a custom date format, you can specify a dateEncodingStrategy in the following way:

The reverse process to decode a string works very similarly, thanks to the JSONDecoder class.

As you can see, by passing the type of the object to the decode method, we let the decoder know what object we expect back from the JSON data. If everything is successful, we'll get an instance of our model object ready to be used.

That's not even all the power and the modularity of the new API. Instead of using a JSONEncoder, you can use the new PropertyListEncoder and PropertyListDecoder in case you need to store data in a plist file. You can also create your own custom encoder and decoder. You only need to make your decoder conform to the Decoder and your encoder to the Encoder protocol.


As part of the String Manifesto, the String type also received quite a big refresh. It now conforms once again (after being removed in Swift 2) to the Collection protocol thanks to proposal SE-0163. So now you can simply enumerate over a string to get all characters.

Substring is a new type that conforms to the same StringProtocol to which String also conforms. You can create a new Substring by just subscripting a String. The following line creates a Substring by omitting the first and last character.

A nice addition that should make it easier to work with big pieces of text is multi-line strings. If you have to create a block of text which spans across multiple lines, you previously had to manually insert \n all over the place. This was very inelegant and difficult to manage. A better way now exists to write multi-line strings, as you can see from the following example:

There are few rules that go along with this new syntax. Each string begins with a triple quotation mark ("""). Then, if the entire string is indented, the spacing of the closing characters decides the spacing to be stripped from each line in the string. For example, if the closing character is indented by 2 tabs, the same amount will be removed from each line. If the string has a line that doesn't have this amount of spacing, the compiler will throw an error.

Key Paths

Key paths were added in Swift 3 to make it easier to reference properties in an object. Instead of referencing an object key with a simple string literal, key paths let us enforce a compile-time check that a type contains the required key—eliminating a common type of runtime error. 

Key paths were a nice addition to Swift 3, but their use was limited to NSObjects and they didn't really play well with structs. These were the main motivations behind proposal SE-0161 to give the API a refresh.

A new syntax was agreed by the community to specify a key path: the path is written starting with a \. It looks like the following:

The nameKeyPath object describes a reference to the name property. It can then be used as a subscript on that object.

If you change the variable from let to var of wwdc, you can also modify a specific property via the key-path subscript syntax.

One-Sided Ranges

SE-0172 proposed to add new prefix and postfix operators to avoid unnecessarily repeating a start or end index when it can be inferred. For example, if you wanted to subscript an array from the second index all the way to the last one, you could write it in the following way:

Previously, the endIndex had to be specified. Now, a shorter syntax exists:

Or, if you want to begin with the start index:

The same syntax can also be used for pattern matching in a switch statement.

Generic Subscripts

Before Swift 4, subscripts were required to define a specific return value type. SE-0148 proposed the possibility of defining a single generic subscript that would infer the return type based on the defined result value. Aside from the type annotation, it works pretty much the same way as before.

As you can see, this really improves the readability of your objects in the cases where you need to access them via the subscript syntax.

Class and Subtype Existentials

One of the missing features from the Swift type system to date has been the ability to constrain a class to a specific protocol. This has been fixed in Swift 4—you can now specify the type of an object and the protocols to which it has to conform, thanks to SE-0156. You can, for example, write a method that takes a UIView that conforms to the Reloadable protocol with the following syntax:

Dictionary and Set Improvements

Dictionary and Set also received a nice refresh in Swift 4. They are much more pleasant to use thanks to a few utility methods that have been added.


Dictionary now has a mapValues method to change all values, avoiding the use of the generic map method that requires working with key, value tuples.

filter Return Type

The filter method now returns an object of the same type you're filtering with.

Defaults for Dictionary Lookup

When working with dictionaries, you can provide a default value when using the subscript syntax to avoid having to later unwrap an optional.

Dictionary Grouping Initializer

Finally, a Dictionary(grouping:) initializer has been introduced to facilitate creating a new dictionary by grouping the elements of an existing collection according to some criteria. 

In the following examples, we create a dictionary by grouping together all conferences that have the same starting letter. The dictionary will have a key for each starting letter in the conferences collection, with each value consisting of all keys that start with that letter.  


If you are interested in going deeper into the new Swift 4 features, here are a few more resources:


Now that you have taken a look at some of the major new features in Swift 4, you're probably champing at the bit to start using them, to help keep your codebase fresh and clean. Start to write your new code to take advantage of the useful new features and think about refactoring some of your previous code to make it simpler and easier to read.

In the meantime, check out some of our other posts on iOS app development!

  • iOS
    Swift Animation Basics
    Markus Mühlberger
  • Mobile Development
    WWDC 2017 Aftermath: The Most Important Announcements
    Bart Jacobs
  • iOS SDK
    Realm Mobile Database for iOS
    Doron Katz
  • iOS
    What's New in iOS 10
    Markus Mühlberger

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!