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

November 17 2017

12:00

Understanding Sets With JavaScript

Sets can be very powerful if you understand how to use them. A few applications of sets include solving counting problems where you may want to find the number of ways you can group elements together. 

Another application is problems that require you to find relationships between elements. The ECMAScript specification doesn’t include methods for operating on sets in this way. But it is possible to create your own. 

What follows is an overview of set theory with practical applications you can use to extend the capabilities of JavaScript and solve more complex problems.

Contents

  • Basics
  • Union
  • Intersection
  • Difference
  • Symmetric Difference
  • Complement
  • Review

Basics

A set is an unordered collection of elements that are all unique. For example, the list of all employees at your work is a set. Each employee would be an element in the set. In reality, these elements would be stored using an ID or Social Security number because these are values we can ensure will be unique. Note how the order of these elements is irrelevant to us because sorting IDs or Social Security numbers has no meaning.  

We call our set of employees the universal set because it contains all elements under consideration. Let’s imagine another set. This set is the list of employees at your company who work in the engineering department. This is a subset of our employee set because every element in the engineering set also exists in the employee set. Another subset is the list of employees who are freelance contractors. Here is how we would create these sets in JavaScript:

If you want to add another person to one of our sets, we would use the syntax set.add(value) and replace set with the name of our set and value with the value of the element being added. If we try to add an element that is already in the set, it will not be added. Example:

This will print Set { 'Alberta', 'Dr. Gero', 'Trunks', 'Bulma', 'Gohan' }.

Right now, you may be thinking so what? What can I do with this information? Next we will see how we can operate on sets to help us solve some common problems.

Union

What if we want to find all the employees in our company who are freelancers or who work in the engineering department? We would need to combine the two sets, and then remove any duplicate names. This is called the union. 

The union of two sets is the set that contains elements from either set or both sets. Notice how elements in our engineering set are also in the freelancers set. Here is one way you can find the union of both sets:

The ... operator turns our set into an array, and after combining the two arrays, the Set constructor removes the duplicate elements. The union of the two sets will be Set {'Alberta', 'Dr. Gero', 'Trunks', 'Bulma', 'Gohan', 'Piccolo', 'Vegeta', 'Goku' }.

Task

What is the union of the sets [1, 3, 5, 7, 9] and [2, 3, 4, 6]?

Intersection

Suppose we want to find all the employees who are in the engineering department and are freelancers. This is the intersection of the sets. The intersection of two sets is the set containing elements in both sets. 

To reproduce this, we can search through one set and check if each element is in the other set. To check if an element is in a set, we use the has method. Example:

This would return true. Using the has method, we can filter our engineering set for items that are also in the freelancers set.

The intersection of engineering and freelancers is Set { 'Trunks', 'Gohan' }.

Task

What is the intersection of the sets [1, 3, 5, 7, 9] and [2, 3, 4, 6]?

Difference

Let’s consider the scenario where we want to find the engineers who are not freelancers. This is the difference. The difference of two sets is the set containing elements that are in the first set, but not in the second set. 

For us, that means we will start with our engineering set, and then remove any elements that are also in the freelancers set. Example:

The difference of the engineering set and the freelancers set is Set { 'Alberta', 'Dr. Gero', 'Bulma' }. If we want to get the list of people who are freelancers and not engineers, we start with the freelancers set and remove the elements that appear in the engineers set. Example:

This gives us a different result. The difference of the freelancers set and the engineering set is Set { 'Piccolo', 'Vegeta', 'Goku' }.

Task

Find the difference of [1, 3, 5, 7, 9] and [2, 3, 4, 6].

Find the difference of [2, 3, 4, 6] and [1, 3, 5, 7, 9].

Symmetric Difference

Now, we would like to find who in the company is either an engineer or a freelancer, but not both. This is the symmetric difference. The symmetric difference of two sets is the set containing elements from either set, but not both sets. 

One approach we could use is to find the union of the two sets (everyone who is an engineer, freelancer, or both) and subtract the intersection (everyone who is both an engineer and a freelancer). Combining the techniques we used previously, we can get the symmetric difference with the following code:

The symmetric difference of our engineering set and our freelancers set is Set { 'Alberta', 'Dr. Gero', 'Bulma', 'Piccolo', 'Vegeta', 'Goku' }.

Task

Find the symmetric difference of [1, 3, 5, 7, 9] and [2, 3, 4, 6].

Complement

If we have our set of employees and a set of engineers, how could we find the set of all people who are not engineers? One thing we could do is subtract the engineers set from the employees set. This set is the complement to our engineers set in relation to our employees set. Example:

The complement to the engineering set in relation to our employees set is Set { 'Goku', 'Piccolo', 'Vegeta' }.

Task

Given the universal set [1 ,2, 3, 4, 5, 6, 7, 8, 9, 10], find the complement to set [2, 4, 6, 8, 10].

Review

Sets come in handy when you need to compare different lists, combine lists, or find unique elements in a list. The next time you have a problem where you need to analyze data in this way, consider using one of the set operations mentioned above. Here is a list of the key terms that were discussed:

  • Set: A collection of unique, unordered elements.
  • Universal set: All possible elements of a set.
  • Subset: A smaller set within a set.
  • Union of sets A and B: The set that contains elements in either A, B or both.
  • Intersection of sets A and B: The set containing elements from both A and B.
  • Difference of sets A and B: The set containing elements in A but not in B.
  • Symmetric difference of sets A and B: The set containing elements in either A or B, but not both.
  • Complement of set A: The elements in the universal set that are not in A.

As usual, remember if you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato Market.

November 16 2017

12:00

How to Index and Query Data With Haystack and Elasticsearch in Python

Haystack

Haystack is a Python library that provides modular search for Django. It features an API that provides support for different search back ends such as Elasticsearch, Whoosh, Xapian, and Solr.

Elasticsearch

Elasticsearch is a popular Lucene search engine capable of full-text search, and it's developed in Java.

Google search uses the same approach of indexing their data, and that's why it's very easy to retrieve any information with just a few keywords, as shown below.

Elastic Search and Google

Install Django Haystack and Elasticsearch

The first step is to get Elasticsearch up and running locally on your machine. Elasticsearch requires Java, so you need to have Java installed on your machine.

We are going to follow the instructions from the Elasticsearch site.

Download the Elasticsearch 1.4.5 tar as follows:

Extract it as follows:

It will then create a batch of files and folders in your current directory. We then go into the bin directory as follows:

Start Elasticsearch as follows.

To confirm if it has installed successfully, go to http://127.0.0.1:9200/, and you should see something like this.

Ensure you also have haystack installed.

Let's create our Django project. Our project will be able to index all the customers in a bank, making it easy to search and retrieve data using just a few search terms.

This command creates files that provide configurations for Django projects.

Let's create an app for customers.

settings.py Configurations

In order to use Elasticsearch to index our searchable content, we’ll need to define a back-end setting for haystack in our project's settings.py file. We are going to use Elasticsearch as our back end.

HAYSTACK_CONNECTIONS is a required setting and should look like this:

Within the settings.py, we are also going to add haystack and customers to the list of installed apps.

Create Models

Let's create a model for Customers. In customers/models.py, add the following code.

Register your Customer model in admin.py like this:

Create Database and Super User

Apply your migrations and create an admin account.

Run your server and navigate to http://localhost:8000/admin/. You should now be able to see your Customer model there. Go ahead and add new customers in the admin.

Indexing Data

To index our models, we begin by creating a SearchIndex. SearchIndex objects determine what data should be placed in the search index. Each type of model must have a unique searchIndex.

SearchIndex objects are the way haystack determines what data should be placed in the search index and handles the flow of data in. To build a SearchIndex, we are going to inherit from the indexes.SearchIndex and indexes.Indexable, define the fields we want to store our data with, and define a get_model method.

Let's create the CustomerIndex to correspond to our Customer modeling. Create a file search_indexes.py in the customers app directory, and add the following code.

The EdgeNgramField is a field in the haystack SearchIndex that prevents incorrect matches when parts of two different words are mashed together.

It allows us to use the autocomplete feature to conduct queries. We will use autocomplete when we start querying our data.

document=True indicates the primary field for searching within. Additionally, the  use_template=True in the text field allows us to use a data template to build the document that will be indexed.

Let's create the template inside our customers template directory. Inside   search/indexes/customers/customers_text.txt, add the following:

Reindex Data

Now that our data is in the database, it's time to put it in our search index. To do this, simply run ./manage.py rebuild_index. You’ll get totals of how many models were processed and placed in the index.

Alternatively, you can use RealtimeSignalProcessor, which automatically handles updates/deletes for you. To use it, add the following in the settings.py file.

Querying Data

We are going to use a search template and the Haystack API to query data.

Search Template

Add the haystack urls to your URLconf.

Let's create our search template. In templates/search.html, add the following code.

The page.object_list is a list of SearchResult objects that allows us to get the individual model objects, for example, result.first_name.

Your complete project structure should look something like this:

The project directory structure

Now run server, go to 127.0.0.1:8000/search/, and do a search as shown below.

Running a search on a local server

A search of Albert will give results of all customers with the name Albert. If no customer has the name Albert, then the query will give empty results. Feel free to play around with your own data.

Haystack API

Haystack has a SearchQuerySet class that is designed to make it easy and consistent to perform searches and iterate results. Much of the SearchQuerySet API is familiar with Django’s ORM QuerySet.

In customers/views.py, add the following code:

autocomplete is a shortcut method to perform an autocomplete search. It must be run against fields that are either EdgeNgramField or NgramField.

In the above Queryset, we are using the contains method to filter our search to retrieve only the results that contain our defined characters. For example, Al will only retrieve the details of the customers which contain Al. Note that the results will only come from fields that have been defined in the customer_text.txt file.

The results of a query

Apart from the contains Field Lookup, there are other fields available for performing queries, including:

  • content
  • contains
  • exact
  • gt
  • gte
  • lt
  • lte
  • in
  • startswith
  • endswith
  • range
  • fuzzy

Conclusion

A huge amount of data is produced at any given moment in social media, health, shopping, and other sectors. Much of this data is unstructured and scattered. Elasticsearch can be used to process and analyze this data into a form that can be understood and consumed.

Elasticsearch has also been used extensively for content search, data analysis, and queries. For more information, visit the Haystack and Elasticsearch sites.

November 15 2017

18:00

How to Upload Images to Firebase from an Android App

Firebase is a mobile and web application development platform, and Firebase Storage provides secure file uploads and downloads for Firebase apps. In this post, you'll build an Android application with the ability to upload images to Firebase Storage.

Firebase Setup

If you don't have a Firebase account yet, you can create one at the Firebase home page.

Once your account is set up, go to your Firebase console, and click the Add Project button to add a new project.

Firebase home page

Enter your project details and click the Create Project button when done. On the next page, click on the link to Add Firebase to your Android app.

Create project options

Enter your application package name. My application package is com.tutsplus.code.android.tutsplusupload. Note that the package name is namespaced with a unique string that identifies you or your company. An easy way to find this is to open your MainActivity file and copy the package name from the top.

Add Firebase to your Android app

When done, click on Register App. On the next page, you will be given a google-services.json to download to your computer. Copy and paste that file into the app folder of your application. (The path should be something like TutsplusUpload/app.)

Set Firebase Permissions

To allow your app access to Firebase Storage, you need to set up permissions in the Firebase console. From your console, click on Storage, and then click on Rules.

Firebase Storage permissions rules

Paste the rule below and publish. 

This will allow read and write access to your Firebase storage.

Create the Application

Open up Android Studio, and create a new project. You can call your project anything you want. I called mine TutsplusUpload.

Before you proceed, you'll need to add a couple of dependencies. On the left panel of your Android Studio, click on Gradle Scripts.

buildgradle file

Open build.gradle (Project: TutsplusUpload), and add this line of code in the dependencies block.

Next, open build.gradle (Module: app) to add the dependencies for Firebase. These go in the dependencies block also. 

Finally, outside the dependencies block, add the plugin for Google Services.

Save when done, and it should sync.

Set Up the MainActivity Layout

The application will need one activity layout. Two buttons will be needed—one to select an image from your device, and the other to upload the selected image. After selecting the image you want to upload, the image will be displayed in the layout. In other words, the image will not be set from the layout but from the activity.

In your MainActivity layout, you will use two layouts—nesting the linear layout inside the relative layout. Start by adding the code for your relative layout.

The RelativeLayout takes up the whole space provided by the device. The LinearLayout will live inside the RelativeLayout, and will have the two buttons. The buttons should be placed side by side, thus the orientation to be used for the LinearLayout will be horizontal.

Here is the code for the linear layout.

From the above code, you can see that both buttons have ids assigned. The ids will be used to target the button from the main activity such that when the button gets clicked, an interaction is initiated. You will see that soon.

Below the LinearLayout, add the code for the ImageView.

You can also see that the ImageView has an id; you will use this to populate the layout of the selected image. This will be done in the main activity.

Get MainActivity Up

Navigate to your MainActivity, and start by declaring fields. These fields will be used to initialize your views (the buttons and ImageView), as well as the URI indicating where the image will be picked from. Add this to your main activity, above the onCreate method.

PICK_IMAGE_REQUEST is the request code defined as an instance variable.

Now you can initialize your views like so:

In the above code, you are creating new instances of Button and ImageView. The instances point to the buttons you created in your layout.

You have to set a listener that listens for interactions on the buttons. When an interaction happens, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase.

Underneath the initialized views, set the listener for both buttons. The listener looks like this.

This should be in the onCreate() method. As I mentioned above, both buttons call a different method. The Choose button calls the chooseImage() method, while the Upload button calls the uploadImage() method. Let's add those methods. Both methods should be implemented outside the onCreate() method.

Let's start with the method to choose an image. Here is how it should look:

When this method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to browse through the device gallery to select the image. startActivityForResult is used to receive the result, which is the selected image. To display this image, you'll make use of a method called onActivityResult.

onActivityResult receives a request code, result code, and the data. In this method, you will check to see if the request code equals PICK_IMAGE_REQUEST, with the result code equal to RESULT_OK and the data available. If all this is true, you want to display the selected image in the ImageView.

Below the chooseImage() method, add the following code.

Uploading the File to Firebase

Now we can implement the method for uploading the image to Firebase. First, declare the fields needed for Firebase. Do this below the other fields you declared for your class.

storage will be used to create a FirebaseStorage instance, while storageReference will point to the uploaded file. Inside your onCreate() method, add the code to do that—create a FirebaseStorage instance and get the storage reference. References can be seen as pointers to a file in the cloud.

Here is what the uploadImage() method should look like.

When the uploadImage() method is called, a new instance of ProgressDialog is initialized. A text notice showing the user that the image is being uploaded gets displayed. Then a reference to the uploaded image, storageReference.child(), is used to access the uploaded file in the images folder. This folder gets created automatically when the image is uploaded. Listeners are also added, with toast messages. These messages get displayed depending on the state of the upload.

Set Permission in the App

Finally, you need to request permission that your application will make use of. Without this, users of your application will not be able to browse their device gallery and connect to the internet with your application. Doing this is easy—simply paste the following in your AndroidManifest file. Paste it just above the application element tag.

This requests for permission to use the internet and read external storage.

Testing the App

Now go ahead and run your application! You should be able to select an image and successfully upload it to Firebase. To confirm the image uploaded, go back to your console and check in the Files part of your storage.

The finished app

Conclusion

Firebase provides developers with lots of benefits, and file upload with storage is one of them. Uploading images from your Android application requires you to work with Activities and Intents. By following along with this tutorial, your understanding of Activities and Intents has deepened. I hope you enjoyed it!

Check out some of our other posts for more background about Activities and Intents, or take a look at some of our other tutorials on using Firebase with Android!

  • Android SDK
    What Are Android Intents?
    Chinedu Izuchukwu
  • Android SDK
    What Is the Android Activity Lifecycle?
    Chinedu Izuchukwu
  • Android SDK
    Firebase for Android: File Storage
    Paul Trebilcox-Ruiz
  • Android SDK
    How to Create an Android Chat App Using Firebase
    Ashraff Hathibelagal

14:11

New eBooks Available for Subscribers

Do you want to learn more about programming for the Internet of Things? How about mastering object-oriented programming or game development with Swift? Our latest batch of eBooks will teach you all you need to know about these topics and more. What's more, they're all completely free for Envato Elements subscribers to download.

eBooks available for Tuts subscribers

Our Latest Selection of eBooks

This month we’ve made eight new eBooks available for Envato Elements and Tuts+ subscribers to download. Here’s a summary of those books and what you can learn from them.

  • Swift 3 Object-Oriented Programming

    Swift 3 Object-Oriented Programming

    Want to program iOS apps? This book introduces you to the object-oriented paradigm and its implementation in the Swift 3 programming language to help you understand how real-world objects can become part of fundamental reusable elements in the code. 

    You will organize data in blueprints that generate instances. You’ll work with examples so you understand how to encapsulate and hide data by working with properties and access control. Then, you’ll get to grips with complex scenarios where you use instances that belong to more than one blueprint. You’ll discover the power of contract programming and parametric polymorphism. You’ll combine generic code with inheritance and multiple inheritance. Later, you’ll see how to combine functional programming with object-oriented programming and find out how to refactor your existing code for easy maintenance.

  • Swift 3 Game Development

    Swift 3 Game Development

    Swift is the perfect choice for game development. Developers are intrigued by Swift 3.0 and want to make use of new features to develop their best games yet. Packed with best practices and easy-to-use examples, this book leads you step by step through the development of your first Swift game.

    This book starts by introducing SpriteKit and Swift's new features that can be used for game development. After setting up your first Swift project, you will build your first custom class, learn how to draw and animate your game, and add physics simulations.

    Then, you will add the player character, scenes, backgrounds, menus, leaderboards, and much more. By the end of this book, you will be able to create your own iOS games using Swift and SpriteKit.

  • Learning Functional Data Structures and Algorithms

    Learning Functional Data Structures and Algorithms

    With the advent of functional programming and with powerful functional languages such as Scala, Clojure and Elixir becoming part of important enterprise applications, functional data structures have gained an important place in the developer toolkit. But how do we express traditional algorithms in functional setting? Won’t we end up copying too much? Do we trade performance for versioned data structures?

    This book attempts to answer these questions by looking at functional implementations of traditional algorithms. By the end of the book, you'll have a solid understanding of functional programming and will be able to write efficient functional data structures and algorithms for your applications.

  • Angular Test-Driven Development

    Angular Test-Driven Development

    This is a complete guide that shows you testing techniques with Karma that will help you perform unit testing and end-to-end testing with Protractor. It will show you how to optimize your Angular development process using TDD techniques and ensure your final project is free of bugs. All examples in this book are based on Angular v2 and are compatible with Angular v4.

    You'll start by reviewing the TDD life cycle, TDD in the context of JavaScript, and various JavaScript test tools and frameworks. Then you'll learn to test for multiple classes, partial views, location references, CSS, and the HTML element. Amongst other things, you'll also configure a Karma file to automate the testing and tackle elements of Angular (components, services, classes, and broadcasting) using TDD.

  • Angular Services

    Angular Services

    A primary concern with modern-day applications is that they need to be dynamic, and for that, data access from the server side, data authentication, and security are very important. Angular leverages its services to create such state-of-the-art dynamic applications.

    This book will help you create and design customized services, integrate them into your applications, import third-party plugins, and make your apps perform better and faster. This book is up to date for the 2.4 release and is compatible with the 4.0 release as well, and it does not have any code based on the beta or release candidates.

  • Internet of Things Programming With JavaScript

    Internet of Things Programming With JavaScript

    The Internet of Things (IoT) is an entirely new platform for developers and engineers, but you can use the familiar JavaScript programming language. This book will teach you how to interact with endpoint devices by developing web services in JavaScript and also set up an interface to control all connected devices.

    The book begins with setting up a centralized web server that serves as a hub for all connected devices. It then progresses further towards building web services to facilitate high-level communication between connected devices. Using Arduino and Raspberry Pi Zero as endpoint devices, the book will show you how devices can communicate with each other, perform a wide range of tasks, and also be controlled from a centralized location using JavaScript. You'll end by creating a hybrid app to control the devices that can be run from a browser or installed on a smartphone.

  • Go Design Patterns

    Go Design Patterns

    Go is a multi-paradigm programming language that has built-in facilities to create concurrent applications. Design patterns allow developers to efficiently address common problems faced during developing applications.

    Go Design Patterns provides you with a reference point to software design patterns and CSP concurrency design patterns to help them build applications in a more idiomatic, robust, and convenient way in Go.

    The book starts with a brief introduction to Go programming essentials and design patterns. You will then learn how to apply the 23 Gang of Four (GoF) design patterns in Go and also learn about CSP concurrency patterns, the "killer feature" in Go that has helped Google develop software to maintain thousands of servers.

  • Functional PHP

    Functional PHP

    A functional approach encourages code reuse, greatly simplifies testing, and results in code that is concise and easy to understand. This book will demonstrate how PHP can also be used as a functional language, letting you learn about various function techniques to write maintainable and readable code.

    After a quick introduction to functional programming, you will dive right in with code examples so you can get the most of what you’ve learned. Through the tips and best practices in this book, you’ll be able to do more with less code and reduce bugs in your applications. Not only will you be able to boost your performance, but you will also find out how to eliminate common loop problems. By the end of the book, you will know a wide variety of new techniques that you can use on any new or legacy codebase.

Start Reading With a Combined Subscription

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to these eBooks, but also to our growing library of over 1,000 video courses on Envato Tuts+.

Plus you now get unlimited downloads from the huge Envato Elements library of 400,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

12:00

Gates and Policies in Laravel

Today, we're going to discuss the authorization system of the Laravel web framework. The Laravel framework implements authorization in the form of gates and policies. After an introduction to gates and policies, I'll demonstrate the concepts by implementing a custom example.

I assume that you're already aware of the built-in Laravel authentication system as that's something essential in order to understand the concept of authorization. Obviously, the authorization system works in conjunction with the authentication system in order to identify the legitimate user session.

If you're not aware of the Laravel authentication system, I would highly recommend going through the official documentation, which provides you with hands-on insight into the subject.

Laravel's Approach to Authorization

By now, you should already know that the Laravel authorization system comes in two flavors—gates and policies. Although it may sound like a complicated affair, I would say it's pretty easy to implement it once you get the hang of it!

Gates allow you to define an authorization rule using a simple closure-based approach. In other words, when you want to authorize an action that's not related to any specific model, the gate is the perfect place to implement that logic.

Let's have a quick look at what gate-based authorization looks like:

The above snippet defines the authorization rule update-post that you could call from anywhere in your application.

On the other hand, you should use policies when you want to group the authorization logic of any model. For example, let's say you have a Post model in your application, and you want to authorize the CRUD actions of that model. In that case, it's the policy that you need to implement.

As you can see, it's a pretty simple policy class that defines the authorization for the CRUD actions of the Post model.

So that was an introduction to gates and policies in Laravel. From the next section onwards, we'll go through a practical demonstration of each element.

Gates

In this section, we'll see a real-world example to understand the concept of gates.

More often than not, you end up looking at the Laravel service provider when you need to register a component or a service. Following that convention, let's go ahead and define our custom gate in the app/Providers/AuthServiceProvider.php as shown in the following snippet.

In the boot method, we've defined our custom gate:

While defining a gate, it takes a closure that returns either TRUE or FALSE based on the authorization logic that's defined in the gate definition. Apart from the closure function, there are other ways you could define gates.

For example, the following gate definition calls the controller action instead of the closure function.

Now, let's go ahead and add a custom route so that we can go through a demonstration of how gate-based authorization works. In the routes file routes/web.php, let's add the following route.

Let's create an associated controller file app/Http/Controllers/PostController.php as well.

In most cases, you'll end up using either the allows or denies method of the Gate facade to authorize a certain action. In our example above, we've used the allows method to check if the current user is able to perform the update-post action.

Users with sharp eyes would have noticed that we've only passed the second argument $post to the closure. The first argument, the current logged-in user, is automatically injected by the Gate facade.

So that's how you're supposed to use gates to authorize actions in your Laravel application. The next section is all about how to use policies, should you wish to implement authorization for your models.

Policies

As we discussed earlier, when you want to logically group your authorization actions for any particular model or resource, it's the policy you're looking for.

In this section, we'll create a policy for the Post model that will be used to authorize all the CRUD actions. I assume that you've already implemented the Post model in your application; otherwise, something similar will do.

The Laravel artisan command is your best friend when it comes to creating stubbed code. You can use the following artisan command to create a policy for the Post model.

As you can see, we've supplied the --model=Post argument so that it creates all the CRUD methods. In the absence of that, it'll create a blank Policy class. You can locate the newly created Policy class at app/Policies/PostPolicy.php.

Let's replace it with the following code.

To be able to use our Policy class, we need to register it using the Laravel service provider as shown in the following snippet.

We've added the mapping of our Policy in the $policies property. It tells Laravel to call the corresponding policy method to authorize the CRUD action.

You also need to register the policies using the registerPolicies method, as we've done in the boot method.

Moving further, let's create a couple of custom routes in the routes/web.php file so that we can test our Policy methods there.

Finally, let's create an associated controller at app/Http/Controllers/PostController.php.

There are different ways you could authorize your actions using Policies. In our example above, we’ve used the User model to authorize our Post model actions.

The User model provides two useful methods for authorization purposes—can and cant. The can method is used to check if the current user is able to execute a certain action. And the counterpart of the can method, the cant method, is used to determine the inability of the action execution.

Let’s grab the snippet of the view method from the controller to see what exactly it does.

Firstly, we load the currently logged-in user, which gives us the object of the User model. Next, we load an example post using the Post model.

Moving ahead, we’ve used the can method of the User model to authorize the view action of the Post model. The first argument of the can method is the action name that you want to authorize, and the second argument is the model object that you want to get authorized against.

That was a demonstration of how to use the User model to authorize the actions using policies. Alternatively, you could use the Controller Helper as well, if you’re in the controller while authorizing a certain action.

As you can see, you don’t need to load the User model if you use the Controller Helper.

So that was the concept of policies at your disposal, and it’s really handy while authorizing a model or a resource as it allows you to group the authorization logic in one place.

Just make sure that you don’t use gates and policies altogether for the same actions of the Model, otherwise it’ll create issues. That’s it from my side for today, and I’ll call it a day!

Conclusion

Today, it was Laravel authorization that took the center stage in my article. At the beginning of the article, I introduced the main elements of Laravel authorization, gates and policies.

Following that, we went through creating our custom gate and policy to see how it works in the real world. I hope you’ve enjoyed the article and learned something useful in the context of Laravel.

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study on Envato Market.

As always, I would love to hear from you in the form of comments using the feed below!

08:12

Envato Elements Now Includes WordPress Themes & Plugins!

If you work with WordPress, you're in luck—WordPress themes and plugins are now included in an annual Envato Elements subscription. And what's more, you can lock in a special introductory rate for a limited time. Read on for more details.

Adios theme on Envato Elements

What's Included

Envato Elements already gives you unlimited downloads from a massive library of 400,000+ photos, graphics, templates, and other creative assets. Plus it gives you free access to more than 1,000 courses and 240 eBooks here on Envato Tuts+.

From today, you'll still get all of that plus a curated collection of beautiful, premium WordPress themes and plugins. 

As with everything else on Envato Elements, this is an "all you can eat" deal. You can download as many themes and plugins as you want, with no limits or credits to keep track of. And there's a simple licensing system so that you know you're covered for all of your projects.

Right now, there are over 190 top themes and 130 plugins available to choose from, and you can expect that number to grow as more authors join the platform and existing authors upload more items. 

WordPress Themes

There's a wide range of premium themes on offer, whether you're looking for a multipurpose theme suitable for a corporate audience or something more creative that would work for a blog or portfolio site. There are even niche themes for real estate sites, wedding sites and more—and of course, you can find e-commerce themes to help you make sales from your site.

Focuson theme on Envato Elements

WordPress Plugins

A well-designed theme is a great start, of course, but if you're working with WordPress you'll also need access to premium plugins to add the features and functionality you want.

Envato Elements has you covered here too, with a selection of powerful plugins to help you create booking and scheduling systems, contact forms, responsive menus, social media feeds, and more.

FlyFly WordPress plugin on Envato Elements

What It Costs

It's important to understand that WordPress themes and plugins are only available with an annual subscription, not a monthly one. Usually, an Envato Elements subscription costs $29 a month, so the annual subscription will be $348 a year ($29 x 12).

However, for a limited time, you can save $120 on your subscription and sign up for just $228 (the equivalent of $19 a month). Remember, for that price you get not only the WordPress themes and plugins but also thousands of photos, fonts, graphics, templates and more. It's a pretty special deal.

So head over to Envato Elements to see what's on offer, and if you like what you see, sign up for an annual subscription to start making unlimited downloads. Don't spend too long thinking about it, though, because this introductory deal won't last forever!

November 14 2017

17:43

How to Create Simple Button Fades With CSS

In this video from my course on Practical Web Animation, you'll learn how to create a simple hover effect using CSS. We'll be making our navigation buttons more interesting by animating the background and text colors on hover. You'll also learn some neat CSS tricks for properly centering a menu on the page.

How to Create Simple Button Fades

 

Fork the Pen and Make Style Changes

The first thing you need to do is create your own version of the starting pen on CodePen, which contains all the code you need to get started.

So once you open that up, go ahead and click on the Fork button to create a new copy of it, and then you can start making changes in your new copy. 

First, I want to reduce the space between the buttons. You can do that by setting margin-right to a value of 4px. And you'll see they're a lot closer together. 

Center the Menu

Next, we want to center this navigation on the page. By default, an unordered list is a block-level element, and the easiest way to center a block-level element is using margin: 0 auto;

Our unordered list has a class of .main-nav, so go into that rule and add margin: 0 auto;

At first, that won't work, because since it is a block-level element, by default it takes up the full width of the browser or of its container.

So in order to center it, we first need to give it a width. And I want its width to be determined by the number of items in the menu and the amount of space that those items take up. 

We have five buttons, each with a width of 140 px. And then we have a margin-right on each of those list items of 4 px. So the total width is 5 x 140 = 700, plus the spacing in between, which is 4 x 4 = 16. So our total width of this unordered list is 716 px.

But if we add width: 716px; in the .main-nav class, it doesn't work. You'll see that it does center things, but the "CONTACT US" button has been nudged down to the next line. 

Menu broken onto next line

That's because the "CONTACT US" button also has a margin-right of 4 px. So it's that fifth margin-right that makes it wider than 716 px.

We could fix it by setting our width to 720, but then it's not perfectly centered because we have four extra pixels of margin on the right. So a better option is to simply get rid of the margin-right for the last list item.

We can do that by creating a new rule:

When we do that, everything works fine, and we can go back down to 716 px for the width now, and we see that our "CONTACT US" button is not breaking down to the next line.

Menu properly centered

One more thing we should do is space the menu down a little bit so it's not so close to the top of the browser window. So instead of margin: 0 auto;, we could do margin: 20px auto. That will give it a margin of 20 pixels on the top and on the bottom. And then the auto, obviously, would center it horizontally. 

Create the Hover Effect

So now let's create our hover effect. Our anchor tag right now doesn't have a background color applied to it at all. So let's grab the background color from the list item, cut it, and then move it down to our anchor tag itself. So now our anchor tags have that background color.

Then we'll create a new rule for the hover effect for those anchor tags:

Now, when we hover over the buttons, the background disappears. 

Background disappearing on hover

In order to make this a little more eye-catching, we're going to add a subtle fade. When we're going to fade an item, we first need to determine which rule we need to apply this transition property to. We're not going to apply it to the hover rule; we're going to apply it to the original rule for the anchor tag inside that main nav.

So for that original rule, we're going to add transition: all .5s;. This means that any property we decide to animate will go ahead and animate, and it will last half a second. So now when we hover over each of these buttons, we have a nice subtle fade out.

Make Two Things Fade at the Same Time

Let's tweak this a little bit so that we're fading two different things at the same time. So let's save our work in CodePen and then fork a new version. 

Then take away the background color altogether and put a border around the buttons. So for our original anchor tag rule, we're going to get rid of our background color, and instead we're going to have a border. So add border: 1px solid white;

You'll notice that everything breaks again, and the "CONTACT US" button jumps down to the next line. 

Buttons spacing broken to next line

That's because whenever you add a border to an item that already has a defined width, that border is going to make that item larger. So our width is set to 140 px, but then we have one pixel of border on the left and one pixel of border on the right, making the full width 142 px. 

That's the default behavior, but there is a property called box-sizing that allows us to change that default behavior. If we change box-sizing to border-box, then the final width of our item will be whatever we define for it. So if we define a width of 140 px and then add borders to it, those borders will show up inside the item, and the final width of the item will still be 140 px.

So you can go up to the top and add a new line:

And when we do that, you'll see it automatically gets fixed.

Borders with spacing fixed

Now when we hover over these anchor tags, I want the background color to change to white, and I want the text to change to blue.

So instead of setting our background color to the color of our body background, we're going to set it to a value of white (#fff). So now when we hover over a button, the background color goes to white. And now we just want to change the color of the text to #349, which is the same blue as our background. 

So now when we hover over those, it just inverts itself. The text, which was white, is now the same blue as the background. And the background, which was blue, has changed to white.

Final button fade

Watch the Full Course

In the full course, Practical Web Animation, I will show you practical ways to create animations for buttons, pricing tables, and other web elements, using concise CSS and jQuery to do so.

You can take this course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 300,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

17:13

WordPress Live: Up and Running With WooCommerce

WooCommerce is the most popular eCommerce platform on the web and the most popular way of bringing eCommerce to WordPress. If you're creating an online store, you might be surprised at how easy it is to get up and running with WooCommerce!

In this free live stream course, Rachel McCollin will show you how to set up the WooCommerce plugin for WordPress. Follow along live on YouTube as she installs and configures a WooCommerce store.

Watch the course live to ask questions as you follow along!

If you can't make it to the live stream, you always can watch the recorded course later on Envato Tuts+.

12:51

Java 8 for Android Development: Stream API and Date & Time Libraries

In this three-part series, we’ve been exploring all the major Java 8 features that you can start using in your Android projects today.

In Cleaner Code With Lambda Expressions, we focused on cutting boilerplate from your projects using lambda expressions, and then in Default and Static Methods, we saw how to make these lambda expressions more concise by combining them with method references. We also covered Repeating Annotations and how to declare non-abstract methods in your interfaces using default and static interface methods.

In this final post, we’re going to look at type annotations, functional interfaces, and how to take a more functional approach to data processing with Java 8’s new Stream API.

I’ll also show you how to access some additional Java 8 features that aren’t currently supported by the Android platform, using the Joda-Time and ThreeTenABP libraries.

Type Annotations

Annotations help you write code that’s more robust and less error-prone, by informing code inspection tools such as Lint about the errors they should be looking out for. These inspection tools will then warn you if a piece of code doesn’t conform to the rules laid out by these annotations.

Annotations aren’t a new feature (in fact, they date back to Java 5.0), but in previous versions of Java it was only possible to apply annotations to declarations.

With the release of Java 8, you can now use annotations anywhere you've used a type, including method receivers; class instance creation expressions; the implementation of interfaces; generics and arrays; the specification of throws and implements clauses; and type casting.

Frustratingly, although Java 8 does make it possible to use annotations in more locations than ever before, it doesn’t provide any annotations that are specific to types.

Android’s Annotations Support Library provides access to some additional annotations, such as @Nullable, @NonNull, and annotations for validating resource types such as  @DrawableRes, @DimenRes, @ColorRes, and @StringRes. However, you may also want to use a third-party static analysis tool, such as the Checker Framework, which was co-developed with the JSR 308 specification (the Annotations on Java Types specification). This framework provides its own set of annotations that can be applied to types, plus a number of "checkers" (annotation processors) that hook into the compilation process and perform specific “checks” for each type annotation that’s included in the Checker Framework.

Since Type Annotations don’t affect runtime operation, you can use Java 8’s Type Annotations in your projects while remaining backwards compatible with earlier versions of Java.

Stream API

The Stream API offers an alternative, “pipes-and-filters” approach to collections processing.

Prior to Java 8, you manipulated collections manually, typically by iterating over the collection and operating on each element in turn. This explicit looping required a lot of boilerplate, plus it’s difficult to grasp the for-loop structure until you reach the body of the loop.

The Stream API gives you a way of processing data more efficiently, by performing a single run over that data—regardless of the amount of data you’re processing, or whether you're performing multiple computations.

In Java 8, every class that implements java.util.Collection has a stream method that can convert its instances into Stream objects. For example, if you have an Array:

Then you can convert it into a Stream with the following:

The Stream API processes data by carrying values from a source, through a series of computational steps, known as a stream pipeline. A stream pipeline is composed of the following:

  • A source, such as a Collection, array, or generator function.
  • Zero or more intermediate “lazy” operations. Intermediate operations don’t start processing elements until you invoke a terminal operation—which is why they’re considered lazy. For example, calling Stream.filter() on a data source merely sets up the stream pipeline; no filtering actually occurs until you call the terminal operation. This makes it possible to string multiple operations together, and then perform all of these computations in a single pass of the data. Intermediate operations produce a new stream (for example, filter will produce a stream containing the filtered elements) without modifying the data source, so you’re free to use the original data elsewhere in your project, or create multiple streams from the same source.
  • A terminal operation, such as Stream.forEach. When you invoke the terminal operation, all of your intermediate operations will run and produce a new stream. A stream isn’t capable of storing elements, so as soon as you invoke a terminal operation, that stream is considered “consumed” and is no longer usable. If you do want to revisit the elements of a stream, then you’ll need to generate a new stream from the original data source.

Creating a Stream

There are various ways of obtaining a stream from a data source, including:

  • Stream.of() Creates a stream from individual values:

  • IntStream.range() Creates a stream from a range of numbers:

  • Stream.iterate() Creates a stream by repeatedly applying an operator to each element. For example, here we’re creating a stream where each element increases in value by one:

Transforming a Stream With Operations

There are a ton of operations that you can use to perform functional-style computations on your streams. In this section, I’m going to cover just a few of the most commonly used stream operations.

Map

The map() operation takes a lambda expression as its only argument, and uses this expression to transform the value or the type of every element in the stream. For example, the following gives us a new stream, where every String has been converted to uppercase:

Limit

This operation sets a limit on the size of a stream. For example, if you wanted to create a new stream containing a maximum of five values, then you’d use the following:

Filter

The filter(Predicate<T>) operation lets you define filtering criteria using a lambda expression. This lambda expression must return a boolean value that determines whether each element should be included in the resulting stream. For example, if you had an array of strings and wanted to filter out any strings that contained less than three characters, you’d use the following:  

Sorted

This operation sorts the elements of a stream. For example, the following returns a stream of numbers arranged in ascending order:

Parallel Processing

All stream operations can execute in serial or in parallel, although streams are sequential unless you explicitly specify otherwise. For example, the following will process each element one by one:

To execute a stream in parallel, you need to explicitly mark that stream as parallel, using the parallel() method:

Under the hood, parallel streams use the Fork/Join Framework, so the number of available threads always equals the number of available cores in the CPU.

The drawback to parallel streams is that different cores may be involved each time the code is executed, so you’ll typically get a different output with each execution. Therefore, you should only use parallel streams when the processing order is unimportant, and avoid parallel streams when performing order-based operations, such as findFirst().

Terminal Operations

You collect the results from a stream using a terminal operation, which is always the last element in a chain of stream methods, and always returns something other than a stream.

There are a few different types of terminal operations that return various types of data, but in this section we’re going to look at two of the most commonly used terminal operations.

Collect

The Collect operation gathers all the processed elements into a container, such as a List or Set. Java 8 provides a Collectors utility class, so you don’t need to worry about implementing the Collectors interface, plus factories for many common collectors, including toList(), toSet(), and toCollection().

The following code will produce a List containing red shapes only:

Alternatively, you could collect these filtered elements into a Set:

forEach

The forEach() operation performs some action on each element of the stream, making it the Stream API’s equivalent of a for-each statement.

If you had an items list, then you could use forEach to print all the items that are included in this List:

In the above example we’re using a lambda expression, so it's possible to perform the same work in less code, using a method reference:

Functional Interfaces

A functional interface is an interface that contains exactly one abstract method, known as the functional method.

The concept of single-method interfaces isn’t new—Runnable, Comparator, Callable, and OnClickListener are all examples of this kind of interface, although in previous versions of Java they were known as Single Abstract Method Interfaces (SAM interfaces).  

This is more than a simple name change, as there are some notable differences in how you work with functional (or SAM) interfaces in Java 8, compared with earlier versions.

Prior to Java 8, you typically instantiated a functional interface using a bulky anonymous class implementation. For example, here we’re creating an instance of Runnable using an anonymous class:

As we saw back in part one, when you have a single-method interface, you can instantiate that interface using a lambda expression, rather than an anonymous class. Now, we can update this rule: you can instantiate functional interfaces, using a lambda expression. For example:

Java 8 also introduces a @FunctionalInterface annotation that lets you mark an interface as a functional interface:

To ensure backwards compatibility with earlier versions of Java, the @FunctionalInterface annotation is optional; however, it’s recommended to help ensure you’re implementing your functional interfaces correctly.

If you try to implement two or more methods in an interface that’s marked as @FunctionalInterface, then the compiler will complain that it’s discovered multiple non-overriding abstract methods. For example, the following won’t compile:

And, if you try to compile a @FunctionInterface interface that contains zero methods, then you’re going to encounter a No target method found error.

Functional interfaces must contain exactly one abstract method, but since default and static methods don’t have a body, they’re considered non-abstract. This means that you can include multiple default and static methods in an interface, mark it as @FunctionalInterface, and it’ll still compile.

Java 8 also added a java.util.function package that contains lots of functional interfaces. It's well worth taking the time to familiarize yourself with all of these new functional interfaces, just so you know exactly what’s available out of the box.

JSR-310: Java’s New Date and Time API

Working with date and time in Java has never been particularly straightforward, with many APIs omitting important functionality, such as time-zone information.

Java 8 introduced a new Date and Time API (JSR-310) that aims to resolve these issues, but unfortunately at the time of writing this API isn’t supported on the Android platform. However, you can use some of the new Date and Time features in your Android projects today, using a third-party library.

In this final section, I’m going to show you how to set up and use two popular third-party libraries that make it possible to use Java 8’s Date and Time API on Android.

ThreeTen Android Backport

ThreeTen Android Backport (also known as ThreeTenABP) is an adaption of the popular ThreeTen backport project, which provides an implementation of JSR-310 for Java 6.0 and Java 7.0. ThreeTenABP is designed to provide access to all the Date and Time API classes (albeit with a different package name) without adding a large number of methods to your Android projects.

To start using this library, open your module-level build.gradle file and add ThreeTenABP as a project dependency:

You then need to add the ThreeTenABP import statement:

And initialize the time-zone information in your Application.onCreate() method:

ThreeTenABP contains two classes that display two “types” of time and date information:

  • LocalDateTime, which stores a time and a date in the format 2017-10-16T13:17:57.138
  • ZonedDateTime, which is time-zone aware and stores date and time information in the following format: 2011-12-03T10:15:30+01:00[Europe/Paris]

To give you an idea of how you’d use this library to retrieve date and time information, let’s use the LocalDateTime class to display the current date and time:

Display the date and time using the ThreeTen Android Backport library

This isn’t the most user-friendly way of displaying the date and time! To parse this raw data into something more human-readable, you can use the DateTimeFormatter class and set it to one of the following values:

  • BASIC_ISO_DATE. Formats the date as 2017-1016+01.00
  • ISO_LOCAL_DATE. Formats the date as 2017-10-16
  • ISO_LOCAL_TIME. Formats the time as 14:58:43.242
  • ISO_LOCAL_DATE_TIME. Formats the date and the time as 2017-10-16T14:58:09.616
  • ISO_OFFSET_DATE. Formats the date as 2017-10-16+01.00
  • ISO_OFFSET_TIME.  Formats the time as 14:58:56.218+01:00
  • ISO_OFFSET_DATE_TIME. Formats the date and time as 2017-10-16T14:5836.758+01:00
  • ISO_ZONED_DATE_TIME. Formats the date and time as 2017-10-16T14:58:51.324+01:00(Europe/London)
  • ISO_INSTANT. Formats the date and time as 2017-10-16T13:52:45.246Z
  • ISO_DATE. Formats the date as 2017-10-16+01:00
  • ISO_TIME. Formats the time as 14:58:40.945+01:00
  • ISO_DATE_TIME. Formats the date and time as 2017-10-16T14:55:32.263+01:00(Europe/London)
  • ISO_ORDINAL_DATE. Formats the date as 2017-289+01:00
  • ISO_WEEK_DATE. Formats the date as 2017-W42-1+01:00
  • RFC_1123_DATE_TIME. Formats the date and time as Mon, 16 OCT 2017 14:58:43+01:00

Here, we’re updating our app to display the date and time with DateTimeFormatter.ISO_DATE formatting:

To display this information in a different format, simply substitute DateTimeFormatter.ISO_DATE for another value. For example:

Joda-Time

Prior to Java 8, the Joda-Time library was considered the standard library for handling date and time in Java, to the point where Java 8’s new Date and Time API actually draws “heavily on experience gained from the Joda-Time project.”

While the Joda-Time website recommends that users migrate to Java 8 Date and Time as soon as possible, since Android doesn’t currently support this API, Joda-Time is still a viable option for Android development. However, note that Joda-Time does have a large API and loads time-zone information using a JAR resource, both of which can affect your app’s performance.

To start working with the Joda-Time library, open your module-level build.gradle file and add the following:

The Joda-Time library has six major date and time classes:

  • Instant: Represents a point in the timeline; for example, you can obtain the current date and time by calling Instant.now().
  • DateTime: A general-purpose replacement for JDK’s Calendar class.
  • LocalDate: A date without a time, or any reference to a time zone.
  • LocalTime: A time without a date or any reference to a time zone, for example 14:00:00.
  • LocalDateTime: A local date and time, still without any time-zone information.
  • ZonedDateTime: A date and time with a time zone.

Let’s take a look at how you’d print date and time using Joda-Time. In the following example I’m reusing code from our ThreeTenABP example, so to make things more interesting I’m also using withZone to convert the date and time into a ZonedDateTime value.

Display the date and time using the Joda-Time library

You’ll find a full list of supported time zones in the official Joda-Time docs.

Conclusion

In this post, we looked at how to create more robust code using type annotations, and explored the “pipes-and-filters” approach to data processing with Java 8’s new Stream API.

We also looked at how interfaces have evolved in Java 8 and how to use them in combination with other features we’ve been exploring throughout this series, including lambda expressions and static interface methods.

To wrap things up, I showed you how to access some additional Java 8 features that Android currently doesn’t support by default, using the Joda-Time and ThreeTenABP projects.

You can learn more about the Java 8 release at Oracle’s website.

And while you're here, check out some of our other posts about Java 8 and Android development!

  • Android SDK
    Java vs. Kotlin: Should You Be Using Kotlin for Android Development?
    Jessica Thornsby
  • Kotlin
    Kotlin From Scratch: Variables, Basic Types, and Arrays
    Chike Mgbemena
  • Kotlin
    Kotlin From Scratch: More Fun With Functions
    Chike Mgbemena
  • Android SDK
    Introduction to Android Architecture Components
    Tin Megali
  • Android SDK
    Quick Tip: Write Cleaner Code With Kotlin SAM Conversions
    Ashraff Hathibelagal

12:00

Single-Page Applications With ngRoute and ngAnimate in AngularJS

Single-page applications allow you to refresh a certain portion of a web-page by routing any content stored in a separate .html file. By doing so, you do not reload your main page.

AngularJS provides a module named ngRoute exactly for this purpose.

Another useful module of AngularJS is ngAnimate, which makes it easy to animate with certain CSS classes.

In this tutorial I will try to explain each step thoroughly, although you still need a basic knowledge of AngularJS in order to be able to follow.

Starting With a Main Page

Basic Structure

This index.html file is going to be our main page where we have both fixed and routed content.

I will start with a basic HTML document and include all the necessary libraries along with our custom stylesheet named style.css and a JavaScript file angularApp.js.

 Now I add two DIVs with id names of fixedContent and routedContent inside a mainWrapper DIV.

routedContent is also wrapped inside another DIV named wrapper. That is because the routedContent should be absolute positioned relative to a parent DIV due to the fact that during routing animation, two different pieces of content clash with each other.

As the id names imply, fixedContent will be the static content of our main page, and routedContent will be dynamically changing upon user interaction.

In order to define an Angular app in our HTML file, we need to use the ng-app directive. Since the whole page will be an Angular app, we need to assign this directive to the mainWrapper DIV.

We also need the ng-view directive, which tells the DIV it is assigned to display the routed page content.

Now our index.html file looks like this:

Navigation Menu

We need a navigation menu in order to route different pieces of content to ng-view.

We are going to use the ul and a elements to create a simple horizontal menu. Below you can see the HTML snippet for the menu structure.

By default, the ng-route module uses the ! prefix. However, here we only use # in front of our pages to be routed. This is done with the hashPrefix attribute used in the configuration, which I'll explain later in the related section. For now, take it as it is.

Our final HTML file is as follows:

Styling the Main Page

Since this tutorial focuses on AngularJS, I am not going to detail the CSS styling. If you have former CSS knowledge, style the page as you wish. Otherwise, you can use the styling I provide below.

Pages to Be Routed

Each page that will be routed to DIV with the ng-view directive inside the main HTML file can have a unique HTML structure and CSS styling.

Let's start with page1.html.

Since we want a specific styling for each page, we need separate CSS files for each page. Therefore, we also create a file named page1.css, which will contain the styling rules of page1.html.

The basic HTML structure for page1 is as follows:

At the top, we linked to the CSS file that will be styling the page, and we declared a DIV with id name of page1, where the whole content will be laid.

I will keep it simple, but it is completely up to you how to structure the HTML file. Just bear in mind that your container will always be the DIV to which the ng-view directive is assigned. So everything in your routed pages will be relative to that DIV.

The styling of page1.html is given below:

The other three pages can be totally different, but for the sake of simplicity I am just using the same template for each HTML page and slightly different CSS files (different h1 text-colors).

page2.html & page2.css

page3.html & page3.css

page4.html & page4.css


Setting the ngRoute & ngAnimate in JavaScript

So far we have completed all the necessary HTML and CSS files. Now it is time to write the JavaScript code that controls the routing and animation.

Since our ng-app directive is named mainApp, we use this id in the module function. We also need to include the ngRoute and ngAnimate dependencies.

mainAngular = angular.module('mainApp',['ngRoute', 'ngAnimate']);

Now we have access to $routeProvider and $locationProvider.

We are going to use the $routeProvider to manage the routings and $locationProvider to change the hashPrefix, which is set to ! by default.

We use .when('/page1', {templateUrl: 'page1.html'}) to define the page to be routed when <a href="#page1">Page1</a> is clicked in our main HTML file.

We repeat the same line of code for each page to be routed. At the end, we use .otherwise({redirectTo: '/page1'}), which handles unexpected page names. If you try to visit an undefined page name, say page5, you will be redirected to page1.

The complete JavaScript code is below:

Extra Note: If you wish to add a specific ng-controller directive for any pages to be routed, you can handle this inside the $routeProvider.

An example for page1:

In the end, our page should look like this, and you should be able to navigate between pages with no transition animations.

Final result after styling and routing

Animating the Page Transitions

Now it is time to animate the route transitions.

For animation purposes, AngularJS has built-in CSS classes thanks to the ngAnimate dependency.

Those classes that we are going to use are:

  • ng-enter: The starting CSS styles for the enter animation.
  • ng-enter-active: The finishing CSS styles for the enter animation.
  • ng-leave: The starting CSS styles for the leave animation.
  • ng-leave-active: The finishing CSS styles for the leave animation.

So the routed content which is coming into the main page has a transition from ng-enter to ng-enter-active. Likewise, the content leaving the main page has a transition from ng-leave to ng-leave-active.

We have to attach the above mentioned classes to our routedContent class.

An example transition is given below. You can either design your own transition animations or use this one inside your style.css file.

Below is the final result of the project on Plunker.

Conclusion

In this tutorial, we covered how to create SPA applications with the ng-route module of AngularJS, and then we animated the transitions through the CSS classes of ng-animate.

By using only four CSS classes provided by ng-animate, you can achieve various animations. You can always attach extra classes to have more control over the transition animations. For example, you can make your page transitions direction-aware.

I also mentioned that by attaching the controller directive to each specific page inside the $routeProvider, you can achieve extra control over each page.

JavaScript, with its libraries such as Angular, 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 on Envato Market.

I hope this tutorial gave you an overall idea of how to utilize the ng-route and ng-animate modules together.

November 13 2017

12:00

Get Started With Vue Router

Introduction

Routing becomes an important feature to put in place when you have many components. Thanks to the awesome Vue.js team, this is easy using vue-router.

In this tutorial, you will see how to use vue-router while building a simple Vue.js application.

Set Up the Application

You will make use of Vue-CLI to set up your application for this tutorial. If you do not have it installed already on your machine, you can do so by running:

With that done, you can set up your application using the command below.

You are going to be asked some questions. One of these questions is: Install vue-router? For that, enter y.

Navigate to your project folder from your terminal:

Run the command to install all dependencies:

Start your development server by running:

If you want to install vue-router manually, you can use the command below.

Integrate Vue-Router

When using Vue-CLI, the router gets activated by default. You can see that in your src/router/index.js file.

  1. Vue is imported from vue.
  2. Router is imported from the vue-router package.
  3. HelloWorld is imported from the components folder. We'll talk more about this later.
  4. Router is mounted as middleware to your project.
  5. A default route configuration is created. The route is an array of a JavaScript object. It consists of a path, name, and component. The path gets appended to the URL of your web application. The route created above is meant for the home page. You can change the path to /hello, and it will no longer work for the home page. It will only be triggered when you visit the /hello path of your application. The component tells the route the component you want to load when that path is visited. This is the reason you imported the HelloWorld component. This route is exported as Router.

The exported Router has to be imported in your src/main.js file. This is important for the routes to work. This is taken care of when working with Vue-CLI. Your src/main.js should look like this:

  1. The router is imported from your router folder.
  2. The imported router is used when creating a new Vue instance.

Standard Routes

The route you saw above is an example of a standard route. A standard route is one having a path, component, and name. Let's create our own route. Try this part out yourself using the flow below.

  1. Create a new component called Pack. You need to have some dummy text.
  2. Go to your src/router/index.js, import the new component you created, and add a new path.
  3. Open your browser and point to the new path.

I bet you were able to do that on your own. Let's try it out together.

Here is what my Pack component looks like.

Open your router file, and it should be looking like this.

Now point your browser to http://localhost:8080/#/pack and you should see your new page.

Routes With Parameters

The routes you have made so far are static routes. Let's see how to make dynamic routes. Open your routes file and add another route like this.

Here you have your path set to /user/:id; the :id defines a parameter that allows you to pass values to the routes via the URL. From the above, it is possible to have http://localhost:8080/user/23.

The value passed to the route component, in this case, is 23, and this can be accessed in the User component.

To try this out, create a new component called User. In this component, you want to be able to access the route parameter passed through the URL. This parameter will be saved in a variable called id, and the value outputted in the template. Here is what the component should look like.

Now point your browser to http://localhost:8080/#/user/123 and you will see the parameter displayed. Change from 123 to something else, and the new value will be displayed.

Child Routes

In Vue.js, it is possible to nest routes by defining children routes. This is possible using the children property provided by Vue.js. The children routes are passed as an array of objects. In your test app, you will create a child route for profiles. The child route will be given a path and a component.

First, create a new component called Profile.vue. Here is what it should look like.

Open your router file. The first thing you want to do will be to import the Profile component. After doing that, add the children property to the route for the User component so your route file looks like this.

Now you will be able to access this new component when you point your browser to http://localhost:8080/#/user/13/profile.

Link to Routes

At this moment, the only way to navigate in your application is by entering the URL path in the browser. This is not how you will want to build a real-world application. To link to routes in Vue.js, you'll have to make use of the <router-link> element.

Here is how it is used:

For children routes, here is what it should look like.

The to attribute contains the path to the route.

To set that up in your application, open your App.vue file and make it look like this.

Conclusion

Navigating from one view to another is now very easy. You can go ahead and add more views. Try adding a child route to the profile route, so the path becomes http://localhost:8080/#/user/13/profile/child-path.

In this tutorial, you learned how to set up routing in Vue.js. Going forward, you should have no issues with routing in a Vue.js application. While working on this application, you also learned about the route and params object.

I hope you enjoyed yourself.

November 10 2017

14:00

Implementing an Event Bus With LiveData

Final product image What You'll Be Creating

At the last Google I/O, the Android team released a set of powerful Android Architecture Components. They call it:

A collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.

If you haven't learnt about them, you are strongly advised to check out our awesome series here on Envato Tuts+ about Android Architecture Components by Tin Megali. Make sure you go dive in! 

  • Android SDK
    Introduction to Android Architecture Components
    Tin Megali

In this tutorial, I'll show you how to use the LiveData components from the Android Architectural Components to create an event bus. An event bus can be used to effectively communicate between Android components or between layers of your application—for example, communicating to an Activity from an IntentService that a file has finished downloading. 

We'll build a very simple app that triggers an IntentService to do some work—from an Activity. Our IntentService will then communicate back to the Activity when the work is completed. Our communication channel will be from the LiveData library. 

Prerequisites

To be able to follow this tutorial, you'll need:

You can also learn all the ins and outs of the Kotlin language in my Kotlin From Scratch series.

1. Create an Android Studio Project

Fire up Android Studio 3 and create a new project with an empty activity called MainActivity

Android Studio new project screen

2. Add the Lifecycle Components

After creating a new project, specify the LifeCycle and the LiveData artifacts in your app module's build.gradle. Note that as of this writing, the new architectural components are now in a stable version. So this means you can start using them in production apps. 

These artifacts are available at Google’s Maven repository. 

By adding the dependencies, we have taught gradle how to find the library. Make sure you remember to sync your project after adding them. 

3. Create the LifecycleOwner Activity Subclass

Here our MainActivity implements the LifecycleOwner interface. 

Our activity simply handles the standard activity lifecycle events. Inside each of the lifecycle events, it calls the registry.handleLifecycleEvent(), passing the corresponding event as a parameter.   

4. Create the Layout

We just have a Button that triggers the service. A TextView (invisible by default) shows the text "Work completed!" when the service communicates to our MainActivity

5. Initialize the Widgets

We declared our doWorkButton and resultTextView properties inside the MainActivity class with the lateinit modifier. We then initialize them inside the onCreate() method. Anytime the doWorkButton is clicked, we disable it (to prevent clicking the button more than once) and start our MyIntentService (we'll get to that shortly). 

6. Create the Custom Event Class

We just create a simple event message class that we want to pass around on the event bus (or LiveData). 

You can add more properties to this class if you want. 

7. Service Implementation

We implemented an IntentService called MyIntentService. Remember that IntentService lives outside the activity scope and has a background thread, so it is recommended to perform time-consuming tasks such as downloading or fetching remote data via an API inside it.  

However, note that in Android 8.0 if you don't make your IntentService a foreground service by using startForeground(), the Android system will not allow your service to run more than 1 minute—or else it will be stopped immediately. This mechanism is to efficiently manage system resources such as battery life. If your app is targeting Android 8.0, you are advised to use the JobIntentService instead. 

We create a nameless companion object whose companion class is MyIntentService. This companion object has a property called BUS, which is an instance of MutableLiveData.  Remember that companion objects are singletons, so this means that only a single instance of BUS exists. We also passed our CustomEvent as a type argument to the generic MutableLiveData class. 

Remember that the MutableLiveData class is a subclass of LiveData—and has a method called postValue() that can be called from a background thread. 

Inside onHandleIntent(), we have our business logic. Remember that this method is called on a background thread (one of the major differences between an IntentService and a normal Service). The IntentService ends immediately by itself when the onHandleIntent() method finishes its job.  

In our own case, we are simulating work being done (this work can be a file download or communicating with a remote API) by sleeping the current thread for 30 seconds. We then checked if our BUS has any active observers using the hasActiveObservers() method. If there are any, notify and pass our event message to them by using the method postValue(), or else we can simply show a notification (this was not coded in the example above for brevity's sake). 

Remember to include the service in your manifest file.

8. Observer Implementation

We need at least one observer for our mechanism to be useful. So inside the MainActivity class, we are going to subscribe an anonymous observer. 

Inside the onCreate() of MainActivity, we got the event bus BUS from MyIntentService. Then we registered an observer for the event bus (i.e. LiveData) using the observe() method. Next, we registered and inlined an anonymous observer, using the MainActivity as LifecycleOwner. This anonymous observer gets notified when any of the following happens:

  • There is already data available in the LiveData when it subscribes. 
  • The data inside the LiveData gets modified. 

When either of these occurs, we get the event data (from the LiveData) on the main application thread as input to the lambda. We then do the following inside the lambda's body:

  • Make the resultTextView visible.
  • Enable the doWorkButton.
  • Log our custom event property eventProp value to Logcat.

Remember the following about LiveData:

  • When a new observer is attached to our LiveData after a configuration change, LiveData will send the last data it received to the observer—even without us explicitly telling it to do so. In other words, it does this automatically. 
  • When the LifecycleOwner is destroyed, the observer will automatically be unsubscribed. 
  • Finally, LiveData is an observable that is lifecycle-aware. According to the docs:
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

9. Testing the App

Finally, you can run the app! Click the Do Work button and after 30 seconds, you'll see the result. 

Tutorial project result

You can get the complete source code from our GitHub repo.

Conclusion

In this tutorial, you learned how to easily use the LiveData components from the Android Architectural Components to create an event bus—so as to effectively communicate with components of your app. 

I assume you're aware of other libraries you can use for the same purpose, such as Android LocalBroadcastManager or the popular greenrobot EventBus to implement an event bus in your Android application. You can see that using the LiveData instead is preferable to them—because you avoid writing boilerplate or verbose code, and LiveData provides you with better flexibility. 

To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

  • Android
    Communication Within an Android App With EventBus
    Chike Mgbemena
  • Android
    How to Get Started With Push Notifications On Android
    Ashraff Hathibelagal
  • Google Maps
    Getting Started With Google Maps for Android: Basics
    Paul Trebilcox-Ruiz
  • Android SDK
    Concurrency in RxJava 2
    Chike Mgbemena

12:00

Building a Slack Bot Using Python

Final product image What You'll Be Creating

Slack was founded in 2014 and is being touted as the fastest-growing business application in history. It currently has over 50,000 paying companies using its product—including my current place of employment.

Slack has really distinguished itself from its predecessors that were more focused on being a messaging system with some voice and video capabilities. Slack has really pushed the envelope and is working diligently on building on a very powerful App Directory. The App Directory contains hundreds to thousands of integrations that can provide an incredible amount of flexibility to improve your company's efficiency.

The goal of this article is to demonstrate how you can build your own unique integration with Slack, leveraging Python for the logic.

To help focus on understanding the mechanics of a Slack Bot's basics, I will focus on a custom bot.

Why Build a Slack Bot?

Even though Slack has a world-class App Directory, each business has unique business processes. This leaves many companies in a situation where they simply cannot find the perfect application for them.

This is where building your own Slack Bot comes into play.

A Slack Bot's job is to receive and handle events generated by your team's Slack interaction. Slack provides at least 50 different event types, such as:

  • message: A message was sent to a channel.
  • team_join: A new member has joined the team.
  • member_joined_channel: A user joined a public or private channel.

And of course, there are many more event types that your bot can optionally handle and react to. For example, the team_join event is a fantastic event that can begin an entire onboarding process.

The goal of this article will demonstrate how a Slack Bot will interact with the message event to perform specific actions when team members interact with the bot.

Picking the Right Slack Bot Type

In this article, I will create a Python application and a Slack Bot that can be added to your team project to respond to the message event.

To begin, I need to create a Bot on Slack. Two types of bots can be created:

  • a custom bot
  • creating an application and adding a bot user

This article will create a custom bot because an application bot user would be more appropriate if I were planning to write and publish an application on Slack. Given that I wish this bot to be private to my team, a custom bot will suffice.

Create a Custom Slack Bot

A custom bot can be created here: https://my.slack.com/apps/A0F7YS25R-bots. If you are already logged in to your Slack account, on the left select the Add Configuration button; otherwise, log in to your Slack account before proceeding. If you do not have a Slack account, you can sign up for free.

This will take you to a new page that requires you to provide a username for your bot. Enter your username now, ensuring you follow Slack's naming guidelines. Once you have selected an awesome bot name, press Add bot configuration.

After you have successfully created your bot, Slack redirects you to a page that allows for further customization of your bot. I'll leave that part to your creative self. The only thing needed from this page is the API Token that starts with xoxb-. I would either copy this token to a safe place for later use or simply leave this page open until we need the token for the Python application.

Setting Up Your Python Application

According to Slack's official documentation for the Slack Developer Kit for Python, it currently supports version 2.7. It does make mention that version 3 will be supported in the near future.

I've already got version 2.7 installed, so I will stick with that version of Python for now. If your Python installation is already set up and ready to go, you can move on to the next step; otherwise, please visit the Python Download page and download the appropriate version for your operating system.

To install the Slack Developer Kit, I will use PyPi to simplify the installation of the Slack Client. On some operating systems, the pip command can be run directly from a command prompt. If not, you would need to reference the entire path to the pip program.

For example, on my Windows system, I ran the following command to install the Slack Client from a command prompt (referencing the full path to the pip.exe file): \Python27\Scripts\pip install slackclient.

Next, you will want to choose a location to house your application. I enjoy using GitHub, so I created a main python folder that contains all of my different Python applications. Inside this folder, I made a sub-folder appropriately called slackbot.

Once I've chosen where my application will be hosted, I'm going to store the core of my application in a file called slackbot.py.

Your First Slack API Call

It's time to lay fingers to the keyboard and connect to Slack and make our first API call. Let's get right to the code, and I'll explain what's happening after:

The code begins with importing the Slack Client library, followed by instantiating the SlackClient class with your Slack Bot's API Token that you saved earlier. Be sure to replace the example token in this example with your token.

The SlackClient object is stored in a local variable called slack_client that will be used to interact further with Slack.

Using the slack_client, an API call is made to retrieve a list of your team's users. If the API call succeeded, the list of team members is stored in the users variable. The users variable is an array that, using a for loop, prints each team member's name to the console application. 

Slack supports several different types of interactions with the system. The first, which we just completed, made an API call. Slack offers many other types of API calls: Web APIEvents APIConversations APIReal Time Messaging API, and SCIM API. The API call we made to retrieve the list of users leveraged the SCIM API.

In the next example, I will demonstrate how to use the Real Time Messaging System. Once we begin building the final bot, the Conversations API will be used to send messages in response to the commands our bot will respond to.

Connecting to the Real Time Messaging System

The RTM system provides a lot of power because Slack sends events that your application can handle and respond to immediately. Of course, there are so many events that your bot may not need to handle every event. To demonstrate the many different events that occur simply upon connection, the following example will output each event that is received.

Let's immediately look at the code to connect and begin receiving Slack events:

Just like the previous example, this code begins with importing the Slack Client library and instantiates the SlackClient class with the same API Token as earlier. This example also imports the Time library that is used later in the code.

With the SlackClient successfully created, the next line of code makes a call to the rtm_connect method. This is done with an if statement. If the connection fails for some reason, an error message is outputted to the console. When successful, a success message is printed to let us know that we are connected and ready to begin interacting with Slack events.

An endless while loop is then started. Inside this loop, I call the rtm_read method of the Slack Client library.

The results of this call are logged to the console. After this occurs, the application sleeps for 1 second before reading the next potential event from Slack. Below is an example of what it looks like reading events upon first connection:

When the bot is connected, three events are sent by Slack as seen above. Because this is in a while loop, when there is no event, it receives an empty array as seen above with the empty brackets [].

Now that we have a basic understanding of making an API call and connecting to Slack's Real Time Messaging system, it's time to build out a fully functional Slack Bot.

My Slack Bot will listen to events using the RTM system. When it receives a message event that is directed to my bot, my application will respond back to the user with a response to the command that was received.

Building the Slack Bot

To build a full bot, it requires quite a bit of code. To help organize and simplify the final code, I am going to split the functionality into three different classes: Bot, Event, and Command. These classes should be extensible by your own application, improving the functionality of your own bot. Let's explore the purpose of each of the three different classes:

  1. The Bot class will be responsible for connecting to Slack and will begin the while loop to listen for events.
  2. The Event class is responsible for reading the events received from Slack, parsing them out to only deal with message events that are aimed directly to our bot. When a message is received, it will call the Command class and send an API call with the response from the Command class.
  3. The Command class will receive the text from the event and provide a customized message based on the command received. This message will then be sent back to the originating Slack Channel Event class to be sent to the originating channel of the message.

Initializing the Slack Bot

I had previously mentioned that my Python application entry point is placed in the slackbot.py file. This file contains the bare minimum to get the application rolling which is to instantiate the Bot class that will handle the rest of the process:

Creating the Bot Class

The Bot Class contains the heart of the bot's configuration and setup. Let's look at the entire Bot Class that I've placed inside a bot.py file:

The file begins by importing the necessary libraries: time, event, and SlackClient. The event library will be created next.

With the libraries imported, the Bot Class is now created. The class's constructor inside the __init__ function sets up a few variables that will be used throughout the remainder of the code. This includes the slack_client, the bot_name, and the bot_id.

The name of the bot is used to find the ID of the bot. The ID will be used later to parse out events that are aimed directly to the bot. If the application cannot find the bot, the application is exited with an error as it cannot proceed without the ID.

The Event Class is then instantiated to be used a bit later in the class. The final thing the constructor does is call the listen function, which connects to the RTM system and begins the endless loop waiting for events that the bot will handle.

The next function, get_bot_id, is quite similar to the first example that loops through the users, this time finding our bot's ID by finding its name in the list of users and returning the ID. In the event that the bot cannot be found, None is returned, which will cause the previous code to exit because it was unable to find the bot.

The final function in the Bot class is the aforementioned listen function. This function looks very similar to the second example where we first connected to Slack's RTM system. The key difference in this example is that it calls the wait_for_event function that will be explored next in the Event class.

This completes the Bot class, making it responsible for creating the SlackClient and starting the endless loop waiting for events. It, however, does not do anything with those events, leaving that responsibility to the Event class.

The Event Class

The purpose of the Event class is to read any events returned from Slack's RTM system. Each event received will be examined for a message containing a reference to the Bot's ID. The following is the Event class that I've placed inside an event.py file:

This class begins by importing the final class that will be explored, the Command class. The constructor of the Event class receives a single parameter: a reference to the Bot object. This is stored in a variable that can be accessed by the other functions in this class. Inside the __init__ function, another variable is created that instantiates the previously imported Command class.

The next function, wait_for_event, is the function that was called by the Bot's class listen function. This function reads any events that have been received from Slack's RTM system. The rtm_read() function returns an array of events. The wait_for_event function checks if the array contains any events. If it does, the events are looped through and call the Event's internal function parse_event.

The parse_event function receives the event as input. It proceeds to check for a property in the event called text. If this property exists, it then checks that the text property contains a reference to our Bot's ID. When this condition is true, this function calls the final function in this class, the handle_event function.

Before calling the handle_event function, the text property uses the Python split function, the string separator being represented by the bot's ID. This converts the text property into an array. The first element in the array is the string containing the text with the bot's ID. The second element contains the remainder of the message. This element is passed to the above-mentioned handle_event function as the command.

The final function, handle_event, accepts three properties: the user who sent the message, the command that was sent, and the channel it was sent in.

The handle_event function ensures the command and channel contain valid values. When they do, a friendly debug message is outputted to the console that indicates what command was received, the channel it was sent in, and which user sent it.

After the friendly debug message, the handle_event function calls the main function from the earlier mentioned Command class. The result of this function is used by the handle_event function by making an API call that posts the response from the Command class function to the channel that initiated the event.

Let's now look at the Command class to see how it generates a custom response based on the command received from the user.

The Command Class

To complete our bot, it's time to create the final class, Command, in an aptly named command.py file:

I really like how this class turned out because it provides a solid foundation that is easily extendable to handle many more commands than I outlined above.

The constructor to the Command class creates a dictionary of keys with an accompanying function name that will be executed when the command is received from the Event class. In this abbreviated example, the commands dictionary contains two commands: jump and help. This dictionary can be extended to include other commands you wish to handle with your own bot.

The next function, handle_command, is the function that is called when a successful event that contains a message directed to our bot is called from the Event's class handle_event function.

The handle_command function accepts two parameters: the user who sent the message and the command. The function begins by building a response string that will direct a message to the user who sent the command. The function then checks that the command received is a valid command in the dictionary of commands defined in the constructor.

When the command is valid, the associated function to that command is called, appending the string to the response variable created earlier.

If the command does not exist, the response is appended to indicate that the command is not valid. It also calls the help command function to aid the user in understanding what commands are supported by this bot.

The remaining functions, jump and help, generate a custom response which will be sent to the user who initiated the command.

As I mentioned during the constructor, the dictionary of commands can be extended with a new command. To complete that process, an accompanying function must be created that is called automatically by the handle_command function.

Testing the Slack Bot

Now that all of the coding is completed, it's time to test our new bot. To start, we must run our main Python script: slackbot.py. In a command prompt, execute this script with Python, e.g. python slackbot.py.

This will launch our bot and connect to Slack's Real Time Messaging system. Upon success, our debug message should be printed to the console indicating our Slack bot is ready to receive commands.

To execute a command, our bot needs to be invited into a public or private channel. Once the bot is in the channel, a user can tell the bot to jump or ask for help. In my case I would say: @jamietest jump. The bot would aptly respond: @endyourif: Kris Kross will make you jump jump.

This bot is not limited to a single channel. Because it parses out the channel from the event message, it can handle commands from many different channels.

Now it's your turn to give your bot a go and see what you can make it do!

Conclusion

My bot is now complete. I have hopefully shown you the power of creating a Slack bot. With the multiple classes (Bot, Event, and Command) each handling a single concern, the Command class can be extended to handle many more commands.

To see the full source code, I've created a GitHub Repository.

Remember, don’t hesitate to see what we have available for sale and for study in Envato Market, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.

The sky is truly endless in how this bot can be extended. Below is a short list of ideas to extend the initial setup of classes:

  • To add a new command, you would create a new function following the pattern of the jump and help functions inside the Command class. When the function is created, it needs to be added to the dictionary of available commands.
  • Another great way to further enhance your bot is to extend the functionality of the parse_event function in the Event class. Currently, this function is explicitly looking for a message event that contains our Bot ID in the text. This function could be further extended to look for other events, such as team_join. This event could call a new command (in the Command class) that provides the new team member with your company's onboarding documents and policies.
  • Finally, if you are interested in creating a custom application or wish to create your own Slack Commands, you can explore creating a custom application and adding a bot user to the application. Many of the code examples work with either bot type.

I hope you've enjoyed this article on creating a Slack Bot using Python. Use the comments form below to let your fellow readers know how you have extended the examples above to create an extremely robust Slack Bot!

November 09 2017

12:00

How to Create a Custom Authentication Guard in Laravel

In this article, we’re going to cover the authentication system in the Laravel framework. The main aim of this article is to create a custom authentication guard by extending the core authentication system.

Laravel provides a very solid authentication system in the core that makes the implementation of basic authentication a breeze. In fact, you just need to run a couple of artisan commands to set up the scaffolding of an authentication system.

Moreover, the system itself is designed in such a way that you could extend it and plug in your custom authentication adapters as well. That’s what we'll discuss in detail throughout this article. Before we go ahead and dive into the implementation of the custom authentication guard, we’ll start with a discussion of the basic elements in the Laravel authentication system—guards and providers.

The Core Elements: Guards and Providers

The Laravel authentication system is made up of two elements at its core—guards and providers.

Guards

You could think of a guard as a way of supplying the logic that’s used to identify the authenticated users. In the core, Laravel provides different guards like session and token. The session guard maintains the state of the user in each request by cookies, and on the other hand the token guard authenticates the user by checking a valid token in every request.

So, as you can see, the guard defines the logic of authentication, and it’s not necessary that it always deals with that by retrieving valid credentials from the back end. You may implement a guard that simply checks the presence of a specific thing in request headers and authenticates users based on that.

Later in this article, we’ll implement a guard that checks certain JSON parameters in request headers and retrieves the valid user from the MongoDB back end.

Providers

If the guard defines the logic of authentication, the authentication provider is responsible for retrieving the user from the back-end storage. If the guard requires that the user must be validated against the back-end storage then the implementation of retrieving the user goes into the authentication provider.

Laravel ships with two default authentication providers—Database and Eloquent. The Database authentication provider deals with the straightforward retrieval of the user credentials from the back-end storage, while Eloquent provides an abstraction layer that does the needful.

In our example, we’ll implement a MongoDB authentication provider that fetches the user credentials from the MongoDB back end.

So that was a basic introduction to guards and providers in the Laravel authentication system. From the next section onwards, we’ll focus on the development of the custom authentication guard and provider!

A Quick Glance at the File Setup

Let's have a quick look at the list of files that we'll implement throughout the course of this article.

  • config/auth.php: It's the authentication configuration file in which we'll add an entry of our custom guard.
  • config/mongo.php: It's the file that holds the MongoDB configuration.
  • app/Services/Contracts/NosqlServiceInterface.php: It's an interface that our custom Mongo database class implements.
  • app/Database/MongoDatabase.php: It's a main database class that interacts with MongoDB.
  • app/Models/Auth/User.php: It's the User model class that implements the Authenticable contract.
  • app/Extensions/MongoUserProvider.php: It's an implementation of the authentication provider.
  • app/Services/Auth/JsonGuard.php: It's an implementation of the authentication guard driver.
  • app/Providers/AuthServiceProvider.php: This is an existing file that we'll use to add our service container bindings.
  • app/Http/Controllers/MongoController.php: It's a demo controller file that we'll implement to test our custom guard.

Don't worry if the list of the files doesn't make much sense yet as we'll discuss everything in detail as we go through it.

Deep Dive Into the Implementation

In this section, we'll go through the implementation of the required files.

The first thing that we need to do is to inform Laravel about our custom guard. Go ahead and enter the custom guard details in the config/auth.php file as shown.

As you can see, we've added our custom guard under the custom key.

Next, we need to add an associated provider entry in the providers section.

We've added our provider entry under the mongo key.

Finally, let's change the default authentication guard from web to custom.

Of course, it won't work yet, as we've not implemented the necessary files yet. And that's what we'll discuss in the next couple of sections.

Set Up the MongoDB Driver

In this section, we'll implement the necessary files that talk to the underlying MongoDB instance.

Let's first create a configuration file config/mongo.php that holds the default MongoDB connection settings.

Of course, you need to change the placeholder values as per your settings.

Instead of directly creating a class that interacts with MongoDB, we'll create an interface in the first place.

The benefit of creating an interface is that it provides a contract that a developer must adhere to while implementing it. Also, our implementation of MongoDB could be easily swapped with another NoSQL implementation if needed.

Go ahead and create an interface file app/Services/Contracts/NosqlServiceInterface.php with the following contents.

It's a pretty simple interface that declares the basic CRUD methods that a class must define that implements this interface.

Now, let's define an actual class at app/Database/MongoDatabase.php.

Of course, I assume that you've installed MongoDB and the corresponding MongoDB PHP extension.

The __construct method instantiates the MongoClient class with the necessary parameters. The other important method we're interested in is the find method, which retrieves the record based on the criteria provided as method arguments.

So that was the implementation of the MongoDB driver, and I tried to keep it as simple as possible.

Set Up the User Model

Adhering to the standards of the authentication system, we need to implement the User model that must implement the Illuminate\Contracts\Auth\Authenticatable contract.

Go ahead and create a file app/Models/Auth/User.php with the following contents.

You should have already noticed that App\Models\Auth\User implements the Illuminate\Contracts\Auth\Authenticatable contract.

Most of the methods implemented in our class are self-explanatory. Having said that, we've defined the fetchUserByCredentials method, which retrieves the user from the available back end. In our case, it'll be a MongoDatabase class that'll be called to retrieve the necessary information.

So that's the implementation of the User model.

Set Up the Authentication Provider

As we discussed earlier, the Laravel authentication system consists of two elements—guards and providers.

In this section, we'll create an authentication provider that deals with the user retrieval from the back end.

Go ahead and create a file app/Extensions/MongoUserProvider.php as shown below.

Again, you need to make sure that the custom provider must implement the Illuminate\Contracts\Auth\UserProvider contract.

Moving ahead, it defines two important methods—retrieveByCredentials and validateCredentials.

The retrieveByCredentials method is used to retrieve the user credentials using the User model class that was discussed in the earlier section. On the other hand, the validateCredentials method is used to validate a user against the given set of credentials.

And that was the implementation of our custom authentication provider. In the next section, we'll go ahead and create a guard that interacts with the MongoUserProvider authentication provider.

Set Up the Authentication Guard

As we discussed earlier, the guard in the Laravel authentication system provisions how the user is authenticated. In our case, we'll check the presence of the jsondata request parameter that should contain the JSON-encoded string of the credentials.

In this section, we'll create a guard that interacts with the authentication provider that was just created in the last section.

Go ahead and create a file app/Services/Auth/JsonGuard.php with the following contents.

First of all, our class needs to implement the Illuminate\Contracts\Auth\Guard interface. Thus, we need to define all the methods declared in that interface.

The important thing to note here is that the __construct function requires an implementation of Illuminate\Contracts\Auth\UserProvider. In our case, we'll pass an instance of App\Extensions\MongoUserProvider, as we'll see in the later section.

Next, there's a function getJsonParams that retrieves the user credentials from the request parameter named jsondata. As it's expected that we'll receive a JSON encoded string of the user credentials, we've used the json_decode function to decode the JSON data.

In the validate function, the first thing we check is the existence of the $credentials argument. If it's not present, we'll call the getJsonParams method to retrieve user credentials from the request parameters.

Next, we call the retrieveByCredentials method of the MongoUserProvider provider that retrieves the user from the MongoDB database back end. Finally, it's the validateCredentials method of the MongoUserProvider provider that checks the validity of the User.

So that was the implementation of our custom guard. The next section describes how to stitch these pieces together to form a successful authentication system.

Putting It All Together

So far, we've developed all the elements of the custom authentication guard that should provide us a new authentication system. However, it won't work out of the box as we need to register it in the first place using the Laravel service container bindings.

As you should already know, the Laravel service provider is the right place to implement the necessary bindings.

Go ahead and open the file app/Providers/AuthServiceProvider.php that allows us to add authentication service container bindings. If it doesn't contain any custom changes, you could just replace it with the following contents.

Let's go through the boot method that contains most of the provider bindings.

To start with, we'll create bindings for the App\Database\MongoDatabase and App\Models\Auth\User elements.

It's been a while that we've been talking about provider and guard, and it's time to plug our custom guard into the Laravel authentication system.

We've used the provider method of the Auth Facade to add our custom authentication provider under the key mongo. Recall that the key reflects the settings that were added earlier in the auth.php file.

In a similar way, we'll inject our custom guard implementation using the extend method of the Auth facade.

Next, there's a register method that we've used to bind the App\Services\Contracts\NosqlServiceInterface interface to the App\Database\MongoDatabase implementation.

So whenever there's a need to resolve the App\Services\Contracts\NosqlServiceInterface dependency, Laravel responds with the implementation of the App\Database\MongoDatabase adapter.

The benefit of using this approach is that one could easily swap the given implementation with a custom implementation. For example, let's say someone would like to replace the App\Database\MongoDatabase implementation with the CouchDB adapter in future. In that case, they just need to add the corresponding binding in the register method.

So that was the service provider at your disposal. At this moment, we have everything that is required to test our custom guard implementation, so the next and concluding section is all about that.

Does It Work?

You've done all the hard work setting up your first custom authentication guard, and now it's time to reap the benefits as we'll go ahead and give it a try.

Let's quickly implement a pretty basic controller file app/Http/Controllers/MongoController.php as shown below.

Take a close look at the dependency of the login method, which requires the implementation of the Illuminate\Contracts\Auth\Guard guard. Since we've set the custom guard as the default guard in the auth.php file, it's the App\Services\Auth\JsonGuard that'll be injected actually!

Next, we've called the validate method of the App\Services\Auth\JsonGuard class, which in turn initiates a series of method calls:

  • It calls the retrieveByCredentials method of the App\Extensions\MongoUserProvider class.
  • The retrieveByCredentials method calls the fetchUserByCredentials method of the User App\Models\Auth\User class.
  • The fetchUserByCredentials method calls the find method of the App\Database\MongoDatabase to retrieve the user credentials.
  • Finally, the find method of the App\Database\MongoDatabase returns the response!

If everything works as expected, we should get an authenticated user by calling the user method of our guard.

To access the controller, you should add an associated route in the routes/web.php file.

Try accessing the URL http://your-laravel-site/custom/mongo/login without passing any parameters and you should see a "not authorized" message.

On the other hand, try something like http://your-laravel-site/custom/mongo/login?jsondata={"username":"admin","password":"admin"} and that should return a success message if the user is present in your database.

Please note that this is just for example purposes, to demonstrate how the custom guard works. You should implement a foolproof solution for a feature like login. In fact, I've just provided an insight into the authentication flow; you're responsible for building a robust and secure solution for your application.

That ends our journey today, and hopefully I'll be back with more useful stuff. If you want me to write on any specific topics, don't forget to drop me a line!

Conclusion

The Laravel framework provides a solid authentication system in the core that could be extended if you want to implement a custom one. That was the topic of today's article to implement a custom guard and plug it in to the Laravel authentication workflow.

In the course of that, we went ahead and developed a system that authenticates the user based on the JSON payload in the request and matches it with the MongoDB database. And to achieve that, we ended up creating a custom guard and a custom provider implementation.

I hope the exercise has provided you an insight into the Laravel authentication flow, and you should now feel more confident about its inner workings.

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study on Envato Market.

I would love to hear your feedback and suggestions, so shout out loud using the feed below!

09:13

New Course: Code a watchOS App With Swift

Final product image What You'll Be Creating

The Apple Watch is becoming more and more popular—if you don't know how to create apps for it, you're missing out on a useful opportunity.

Our new course, Code a watchOS App With Swift, shows you how to create a simple Apple Watch app with WatchKit, using some very basic skills and technologies. 

Follow along with Derek Jensen across all 19 videos and 2.3 hours of instructions, and you'll learn how to create a watchOS project and how to design an app with the Interface Builder. Along the way, you'll learn how to use some really useful UI components and even how to integrate haptic feedback in your app.

WatchOS app being coded

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 300,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

 

November 08 2017

18:00

Secure Coding in Swift 4

From minimizing pointer use to strong type checking at compile time, Swift is a great language for secure development. But that means it's tempting to forget about security altogether. There are still vulnerabilities, and Swift is also enticing to new developers who haven't yet learned about security. 

This tutorial is a secure coding guide that will address changes in Swift 4 as well as the new tooling options available in Xcode 9 that will help you mitigate security vulnerabilities.

Pointers and Overflows

Many security vulnerabilities have revolved around C and its use of pointers. This is because pointers allow you to access raw memory locations, making it easier to read and write to the wrong area. It has been a major way for attackers to maliciously change a program. 

Swift mostly does away with pointers, but it still allows you to interface with C. Many APIs, including Apple's entire Core Foundation API, are based entirely in C, so it's very easy to introduce the use of pointers back into Swift. 

Fortunately, Apple has named the pointer types appropriately: UnsafePointer<T>, UnsafeRawPointer<T>UnsafeBufferPointer<T>, and UnsafeRawBufferPointer. There will come a time when the API you are interfacing with will return these types, and the main rule when using them is don't store or return pointers for later use. For example:

Because we accessed the pointer outside of the closure, we don't know for sure if the pointer still points to the expected memory contents. The safe way to use the pointer in this example would be to keep it, along with the print statement, within the closure. 

Pointers to strings and arrays also have no bounds checking. This means it's easy to use an unsafe pointer on an array but accidentally access beyond its boundary—a buffer overflow.

The good news is that Swift 4 attempts to crash the app instead of continuing with what would be called undefined behavior. We don't know what buffer[5] points to! However, Swift won't catch every case. Set a breakpoint after the following code and look at variables a and c. They will be set to 999.

This demonstrates a stack overflow because without an explicit allocation, variables are generally stored on the stack. 

In the next example, we make an allocation with a capacity of only a single Int8. Allocations are stored on the heap, so the next line will overflow the heap. For this example, Xcode only warns you with a note in the console that gets is unsafe.

So what's the best way to avoid overflows? It's extremely important when interfacing with C to do bounds checking on the input to make sure it's within range. 

You might be thinking that it's pretty hard to remember and find all of the different cases. So to help you out, Xcode comes with a very useful tool called Address Sanitizer. 

Address Sanitizer has been improved in Xcode 9. It is a tool that helps you catch invalid memory access such as the examples we have just seen. If you will be working with the Unsafe* types, it's a good idea to use the Address Sanitizer tool. It is not enabled by default, so to enable it, go to Product > Scheme > Edit Scheme > Diagnostics, and check Address Sanitizer. In Xcode 9 there is a new sub-option, Detect use of stack after return. This new option detects the use-after-scope and use-after-return vulnerabilities from our first example.

Sometimes overlooked is the integer overflow. This is because integer overflows are security holes only when used as an index or size of a buffer, or if the unexpected value of the overflow changes the flow of critical security code. Swift 4 catches most obvious integer overflows at compile time, such as when the number is clearly larger than the max value of the integer. 

For example, the following will not compile.

But a lot of the times the number will arrive dynamically at runtime, such as when a user enters information in a UITextField. Undefined Behavior Sanitizer is a new tool in Xcode 9 which detects signed integer overflow and other type-mismatch bugs. To enable it, go to Product > Scheme > Edit Scheme > Diagnostics, and turn on Undefined Behavior Sanitizer. Then in Build Settings > Undefined Behavior Sanitizer, set Enable Extra Integer Checks to Yes.

There's another thing worth mentioning about undefined behavior. Even though pure Swift hides pointers, references and copies of buffers are still used behind the scenes, so it's possible to run into behavior that you did not expect. For example, when you start iterating over collection indices, the indices could accidentally be modified by you during iteration.

Here we just caused the numbers array to point to a new array inside the loop. Then what does number point to? This would be normally be called a dangling reference, but in this case Swift implicitly creates a reference to a copy of the buffer of your array for the duration of the loop. That means that the print statement will actually print out 1, 2, and 3 instead of 1, 4, 5.... This is good! Swift is saving you from undefined behavior or an app crash, although you might not have expected that output either. Your peer developers won't expect your collection to be mutated during enumeration, so in general, be extra careful during enumeration that you are not altering the collection.

So Swift 4 has great security enforcement at compile time to catch these security vulnerabilities. There are many situations where the vulnerability doesn't exist until run time when there is user interaction. Swift also includes dynamic checking, which can catch many of the issues at run time too, but it's too expensive to do across threads so it's not performed for multithreaded code. Dynamic checking will catch many but not all violations, so it's still important to write secure code in the first place! 

With that, let's turn to another very common area for vulnerabilities—code injection attacks.

Injection and Format String Attacks

Format string attacks happen when an input string is parsed in your app as a command that you did not intend. While pure Swift strings are not susceptible to format string attacks, the Objective-C NSString and Core Foundation CFString classes are, and they are available from Swift. Both of these classes have methods such as stringWithFormat.

Let's say the user can enter arbitrary text from a UITextField.

This could be a security hole if the format string is handled directly.

Swift 4 tries to handle missing format string arguments by returning 0 or NULL, but it is especially a concern if the string will get passed back to the Objective-C runtime.

While most of the time the incorrect way will just cause a crash, an attacker can carefully craft a format string to write data to specific memory locations on the stack to alter your app behavior (such as changing an isAuthenticated variable). 

Another big culprit is NSPredicate, which can accept a format string that is used to specify what data is retrieved from Core Data. Clauses such as LIKE and CONTAINS allow wildcards and should be avoided, or at least only used for searches. The idea is to avoid enumeration of accounts, for example, where the attacker enters "a*" as the account name. If you change the LIKE clause to ==, this means the string literally has to match “a*”. 

Other common attacks happen by terminating the input string early with a single-quote character so additional commands can be entered. For instance, a login could be bypassed by entering ') OR 1=1 OR (password LIKE '* into the UITextField. That line translates to "where password is like anything”, which bypasses the authentication altogether. The solution is to fully escape any attempts at injection by adding your own double quotes in code. That way, any additional quotes from the user are seen as part of the input string instead of being a special terminating character:

One more way to safeguard against these attacks is to simply search for and exclude specific characters that you know could be harmful in the string. Examples would include quotes, or even dots and slashes. For instance, it is possible to do a directory traversal attack when input gets passed directly to the FileManager class. In this example, the user enters "../" to view the parent directory of the path instead of the intended sub-directory.

Other special characters might include a NULL terminating byte if the string gets used as a C string. Pointers to C strings require a NULL terminating byte. Because of this, it is possible to manipulate the string simply by introducing a NULL byte. The attacker might want to terminate the string early if there was a flag such as needs_auth=1, or when access is on by default and turned off explicitly such as with is_subscriber=0.

Parsing HTML, XML, and JSON strings requires special attention as well. The safest way to work with them is to use Foundation's native libraries that provide objects for each node, such as the NSXMLParser class. Swift 4 introduces type-safe serialization to external formats such as JSON. But if you are reading XML or HTML using a custom system, be sure that special characters from the user input cannot be used to instruct the interpreter.

  • < must become &lt.
  • > should get replaced with &gt.
  • & should become &amp.
  • Inside attribute values, any or ' need to become &quot and &apos, respectively.

Here is an example of a quick way to remove or replace specific characters:

A final area for injection attacks is inside URL handlers. Check to make sure user input is not used directly inside the custom URL handlers openURL and didReceiveRemoteNotification. Verify the URL is what you are expecting and that it doesn't allow a user to arbitrarily enter info to manipulate your logic. For example, instead of letting the user choose which screen in the stack to navigate to by index, allow only specific screens using an opaque identifier, such as t=es84jg5urw

If you are using WKWebViews in your app, it might be good to check the URLs that will be loaded there as well. You can override decidePolicyFor navigationAction, which lets you choose if you want to continue with the URL request. 

Some known webview tricks include loading custom URL schemes the developer did not intend, such as an app-id: to launch an entirely different app or sms: to send a text. Note that embedded webviews don't show a bar with the URL address or SSL status (the lock icon), so the user is not able to determine if the connection is trusted. 

If the webview is full screen, for example, the URL could be hijacked with a webpage that looks just like your login screen except directing the credentials to a malicious domain instead. Other attacks in the past have included cross-site scripting attacks that have leaked cookies and even the entire filesystem. 

The best prevention for all of the mentioned attacks is to take the time to design your interface using native UI controls instead of simply displaying a web-based version within your app.

So far, we've been looking at relatively straightforward kinds of attacks. But let's finish off with a more advanced attack that can happen in the runtime.

Runtime Hacking

Just as Swift becomes more vulnerable when you interface with C, interfacing with Objective-C brings separate vulnerabilities to the table. 

We have already seen the issues with NSString and format string attacks. Another point is that Objective-C is much more dynamic as a language, allowing loose types and methods to be passed around. If your Swift class inherits from NSObject, then it becomes open to Objective-C runtime attacks. 

The most common vulnerability involves dynamically swapping an important security method for another method. For example, a method that returns if a user is validated could be swapped for another method that will almost always return true, such as isRetinaDisplay. Minimizing the use of Objective-C will make your app more robust against this type of attack.

In Swift 4, methods on classes that inherit from an Objective-C class are only exposed to the Objective-C runtime if those methods or the classes themselves are marked with @attribute. Often the Swift function is called instead, even if the @objc attribute is used. This can happen when the method has an @objc attribute but is never actually called from Objective-C. 

In other words, Swift 4 introduces less @objc inference, so this limits the attack surface compared to previous versions. Still, to support the runtime features, Objective-C-based binaries need to retain a lot of class information that cannot be stripped away. This is enough for reverse engineers to rebuild the class interface to figure out what security sections to patch, for example. 

In Swift, there is less information exposed in the binary, and function names are mangled. However, the mangling can be undone by the Xcode tool swift-demangle. In fact, Swift functions have a consistent naming scheme, indicating if each one is a Swift function or not, part of a class, module name and length, class name and length, method name and length, attributes, parameters, and return type. 

These names are shorter in Swift 4. If you're concerned about reverse engineering, make sure the release version of your app strips symbols by going to Build Settings > Deployment > Strip Swift Symbols and setting the option to Yes.

Beyond obfuscating critical security code, you can also request it to be inline. This means that any place that the function is called in your code, the code will be repeated in that place instead of existing only in one location of the binary. 

This way, if an attacker manages to bypass a particular security check, it will not affect any other occurrences of that check situated in other places of your code. Each check has to be patched or hooked, making it much more difficult to successfully perform a crack. You can inline code like this:

Conclusion

Thinking about security should be a big part of development. Merely expecting the language to be secure can lead to vulnerabilities that could have been avoided. Swift is popular for iOS development, but it is available for macOS desktop apps, tvOS, watchOS, and Linux (so you could use it for server-side components where the potential for code execution exploits is much higher). App sandboxing can be broken, such as in the case of jailbroken devices which allow unsigned code to run, so it's important to still think about security and pay attention to Xcode notices while you debug. 

A final tip is to treat compiler warnings as errors. You can force Xcode to do this by going to Build Settings and setting Treat Warnings as Errors to Yes. Don't forget to modernize your project settings when migrating to Xcode 9 to get improved warnings, and last but not least, make use of the new features available by adopting Swift 4 today!

For a primer on other aspects of secure coding for iOS, check out some of my other posts here on Envato Tuts+!

  • iOS SDK
    Securing iOS Data at Rest: Protecting the User's Data
    Collin Stuart
  • iOS SDK
    Securing Communications on iOS
    Collin Stuart
  • Security
    Creating Digital Signatures With Swift
    Collin Stuart

12:00

How to Use Restful Web APIs in Python

This tutorial will introduce you to web APIs and teach you how to use the requests Python library to fetch and update information in web APIs. You will also learn how to interact with the Twitter API as a working example.

Introduction to Web APIs

An API (Application Programming Interface) is a framework for building HTTP services that can be consumed by a wide variety of clients. Web APIs use HTTP protocol to handle requests between the client and the web server.

Some of the most common APIs that enable developers to integrate and use their infrastructure include:

  1. Google APIs
  2. Twitter API
  3. Amazon API
  4. Facebook API

One of the most important reasons to use an API as opposed to other static data sources is because it's real time. For example, the Twitter API we are going to use will fetch real-time data from the social network.

Another advantage is that the data keeps changing, so if you were to download it at intervals, it would be time-consuming.

Using the Requests Library

In order to use an API, you will need to install the requests Python library. Requests is an HTTP library in Python that enables you to send HTTP requests in Python.

Install Requests

In your terminal, type:

To check if the installation has been successful, issue the following command in your Python interpreter or the terminal:

If there are no errors, the installation has been successful.

How to Get Information From a Web API

The GET method is used to get information from a web server. Let's see how to make a GET request to get GitHub's public timeline.

We use the variable req to store the response from our request.

Now that we have made a request to the GitHub timeline, let's get the encoding and the content contained in the response.

Requests has a built-in JSON decode which you can use to get the response of a request in JSON format.

How to Create and Update Information on the Web API

The POST and PUT methods are both used to create and update data. Despite the similarities, it's important to note that using a POST request to update data will result in two entries in the data store if two identical items are submitted.

Create data (POST request):

Update data (PUT request):

Working With the Twitter REST API

In this section, you are going to learn how to obtain Twitter API credentials, authenticate to the Twitter API, and interact with the Twitter API using Python. 

You will also be able to retrieve information from public Twitter accounts, like tweets, followers, etc.

Authenticating With Twitter

We need to authenticate with the Twitter API before we can interact with it. To do this, follow the following steps:

  1. Go to the Twitter Apps page.
  2. Click on Create New App (you need to be logged in to Twitter to access this page). If you don't have a Twitter account, create one.
Twitter App Page

3.  Create a name and description for your app and a website placeholder.

Creating a Twitter Application

4. Locate the Keys and Access Tokens Tab and create your access token.

Twitter Access Tokens

5. You need to take note of the Access token and Access Token secret since you will need them for the authentication process.

6. You also need to take note of the Consumer Key and Consumer Secret.

There are a few libraries that we can use to access the Twitter API, but we are going to use the python-twitter library in this tutorial.

Install python-twitter

To install python-twitter, use:

The Twitter API is exposed via the twitter.Api class, so let's create the class by passing our tokens and secret keys:

Replace your credentials above and make sure they are enclosed in quotes, i.e. consumer_key=‘xxxxxxxxxx’, ...)

Querying Twitter

There are many methods of interacting with the Twitter API, including:

To get data from Twitter, we are going to make an API call with the help of the api object we created above.

We will do the following:

  1. Create a user variable and set it equal to a valid Twitter handle (username).
  2. Call the GetUserTimeline() method on the api object and pass in the following arguments.

  • a valid Twitter handle
  • the number of tweets you want to retrieve (count)
  • a flag to exclude retweets (this is done using include_rts = false)

Let's get the latest tweets from the Envato Tuts+ Code timeline, excluding retweets.

The GetUserTimeline() method will return a list of the latest 30 tweets, so we loop through the list and print the most important information (content) from each tweet.

To retrieve followers, we use the GetFriends() method.

Output

Conclusion

Twitter’s API can be used to a great extent in data analytics. It can also be used in complex big data problems and authenticating apps. Read more about the Twitter API at the Twitter developers site.

Also, don’t hesitate to see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.

November 07 2017

12:00

Working With Tables in React, Part Two

Overview

This is part two of a two-part series about React-Bootstrap-Table. In part one we created a simple React application using react-create-app, added React-Bootstrap-Table, populated a table with data, worked with columns, styled the table, and selected rows. 

In this part we'll continue the journey by expanding rows, adding rows, deleting rows, and covering pagination, cell editing, and advanced customization.

Expanding Rows

This is one of the coolest features of React-bootstrap-table. When displaying tabular data, there is often additional data you may want to see on one or two rows, but you can't display all the data for all the rows. 

One option to address that is to show tooltips, but tooltips require that you hover with the mouse over the target area, and you can only see one tooltip at a time. Expanding rows let you display additional data for each row in a kind of drawer that stays expanded as long as you want, and you can collapse it back when you're done. You can expand as many rows as you want at the same time. Here is how it's done with React-bootstrap-table. 

The love map contains relationships between some Arrested Development characters: Gob loves Marta and Buster loves Lucile 2. The isExpandable() function controls which rows are expandable. In this case, it returns true for rows whose character name is in the love map. The expandRow() function returns a component when a row is expanded. 

The returned component is displayed below the row until the row is collapsed. Configuring row expansion is a little tricky. Some options are just props on the BootstrapTable component. 

The expand column options are one object prop, and then there is a prop called options that contains additional row expansion options like expandRowBgColor and expanding. It would be much simpler if there was just one prop called expandRowProp that contained all the options (like the selectRowProp).

The result of the above code

Pagination

So far we displayed just three rows of data. Tables are designed to display a lot of data that doesn't necessarily fit on the screen at the same time. That's where pagination comes in. React-bootstrap-table supports many pagination options. 

Let's populate our table with 100 items, which will be ten pages of ten items each. We will use a getData() function that returns an array of 100 objects with ids, names, and values based on their index. 

Let's also specify which page to display initially (4), customize the text for prev, next, first and last page (using Unicode arrows for extra coolness) and finally provide a custom function called showTotal() to display the total number of items. Note that the attribute for controlling the previous page button is called "prePage" and not "prevPage" (it got me). All the pagination options go into the general "options" attribute of the table. 

The resulting table of the code above

Adding and Deleting Rows

So far we used the table to display information in a variety of ways. But tables can be used as a user interface for manipulating data. Let's see how to add and remove rows from a table. 

The key attributes are insertRow and deleteRow. When you specify them, "New" and "Delete" buttons are added. If you click the "New" button, a modal dialog opens up and lets you add new rows. If you click the "Delete" button, all selected rows are deleted. To delete rows, you must enable row selection, of course. You can also attach hook functions that are called after adding or deleting rows.

Adding and Deleting Rows

Cell Editing

Another form of data manipulation is in-place editing (a.k.a. cell editing). Cell editing can be triggered by a click or double-click. Cell editing is controlled by the "cellEdit" attribute. In addition to the mode, you can specify non-editable rows and hook functions. 

In the following code, the nonEditableRows function simply returns the row key 3, but could use a more sophisticated logic.

Editing Cells

Exporting Your Data

Sometimes, viewing your data and playing with it in a web UI is not enough, and you need to take your data and feed it to other tools. The way to do it with React-bootstrap-table is very simple. You just add the exportCSV attribute (and optionally a filename) and an export button is added. When you click the button, it allows you to save your data to a CSV file.

Exporting Data

Here is the exported data from our little table:

Customizing All the Things

We covered a lot of material, but React-bootstrap-table has a lot more in store. Practically, every aspect can be customized. Read the full documentation on how to customize a table.

Here is a list of the customizable parts:

  • Cell
  • Toolbar
  • Insert Modal
  • Pagination
  • Column Filter
  • Cell Editing
  • Row Selection Column

Conclusion

React-bootstrap-table packs a powerful punch. It provides out of the box a pleasant user interface for displaying, searching and manipulating tabular data. The API is very consistent—major features can be enabled by specifying a simple attribute and optionally customized with additional attributes that often can be dynamic functions. 

While the default behavior and the basic configuration should satisfy most users, if you need more advanced features and customization, there is ample documentation and examples how to go about it.

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in the marketplace that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.

November 06 2017

14:00

Concurrency and Coroutines in Kotlin

The Java Virtual Machine, or JVM for short, supports multithreading. Any process you run on it is free to create a reasonable number of threads to perform multiple tasks asynchronously. However, writing code that can do so in an optimal and error-free manner can be extremely hard. Over the years, Java, other JVM languages, and a lot of third-party libraries have tried to come up with creative and elegant approaches to address this problem.

For instance, Java 5 introduced the executor framework, which allows you to decouple thread management details from your business logic. Java 8 offers parallel streams, which can easily be used with lambda expressions. RxJava brings reactive extensions to Java, allowing you to write very concise and readable asynchronous code.

Kotlin supports almost all of those approaches and offers a few of its own. In this tutorial, I'll show you how you can use them in Android apps.

Prerequisites

To be able to follow this tutorial, you'll need:

If you aren't comfortable working with lambda expressions and SAM interfaces, I suggest you also read the following tutorial before proceeding:

  • Android SDK
    Quick Tip: Write Cleaner Code With Kotlin SAM Conversions
    Ashraff Hathibelagal

You can also learn all the ins and outs of the Kotlin language in our Kotlin From Scratch series.

1. Creating Threads

Usually, instances of classes that implement the Runnable interface are used to create threads in Kotlin. Because the Runnable interface has just one method, the run() method, you can leverage Kotlin's SAM conversion feature to create new threads with minimal boilerplate code.

Here's how you can use the thread() function, which is a part of Kotlin's standard library, to quickly create and start a new thread:

The above approach is appropriate only when you need to occasionally spawn a thread or two. If concurrency is an important part of your app's business logic and you need a large number of threads, using thread pools with an executor service is a better idea. 

For example, the following code uses the newFixedThreadPool() method of the Executors class to create a thread pool containing eight reusable threads and runs a large number of background operations on it:

It might not be obvious at first glance but, in the above code, the argument to the submit() method of the executor service is actually a Runnable object.

2. Getting Results From Threads

Background tasks created using the Runnable interface cannot return any results directly. If you want to receive results from your threads, you must use the Callable interface instead, which is also a SAM interface.

When you pass a Callable object to the submit() method of an executor service, you receive a Future object. As its name suggests, the Future object will contain the result of the Callable at some point in the future, when the executor service has finished running it. To get the actual result from a Future object, all you need to do is call its get() method—but beware, your thread will block if you call it prematurely.

The following sample code shows you how to create a Callable object that returns a Future of type String, run it, and print its result:

3. Synchronizing Threads

Unlike Java, Kotlin doesn't have the synchronized keyword. Therefore, to synchronize multiple background operations, you are expected to use either the @Synchronized annotation or the synchronized() standard library inline function. The annotation can synchronize an entire method, and the function works on a block of statements.

Both the @Synchronized annotation and the synchronized() function use the concept of monitor locks. 

If you don't already know, every object on the JVM has a monitor associated with it. For now, you can think of a monitor as a special token that a thread can acquire, or lock, to gain exclusive access to the object. Once an object's monitor is locked, other threads that want to work on the object will have to wait until the monitor is released, or unlocked, again.

While the @Synchronized annotation locks the monitor of the object the associated method belongs to, the synchronized() function can lock the monitor of any object that's passed to it as an argument.

4. Understanding Coroutines

Through an experimental library, Kotlin offers an alternative approach to achieve concurrency: coroutines. Coroutines are far lighter than threads and are much easier to manage.

In mobile multithreaded applications, threads are usually used for operations such as fetching information from the Internet or querying databases. Such operations don't involve much computation, and the threads spend most of their lifetime in a blocked state, just waiting for data to come from somewhere else. As you can probably tell, that's not a very efficient way to use the CPU.

Coroutines are designed to be used instead of threads for such operations. The most important thing you need to understand about coroutines is that they are suspendable. In other words, instead of blocking, they can simply stop when necessary and seamlessly continue later. This leads to much better CPU utilization. Indeed, with well-designed coroutines, you can effortlessly run dozens of background operations.

To be able to use coroutines in your Android Studio project, make sure you add the following compile dependency in the app module's build.gradle file:

5. Creating Suspending Functions

A coroutine can be suspended only with the help of a suspending function. Therefore, most coroutines have calls to at least one such function inside them.

To create a suspending function, all you need to do is add the suspend modifier to a regular function. Here's a typical suspending function executing an HTTP GET request using the khttp library:

Note that a suspending function can be called only by a coroutine or another suspending function. If you try calling it from anywhere else, your code will fail to compile.

6. Creating Coroutines

When it comes to creating a new coroutine, Kotlin's standard library has enough coroutine builders to make you feel spoiled for choice. The simplest coroutine builder you can use is the launch() function, and like most other coroutine builders, it expects a suspending lambda, which is nothing but an anonymous suspending function. As such, this lambda is what becomes the coroutine.

The following code creates a coroutine that makes two sequential calls to the suspending function we created in the previous step:

The return value of the launch() function is a Job object, which you can use to manage the coroutine. For example, you can call its join() method to wait for the coroutine to complete. Similarly, you can call its cancel() method to immediately cancel the coroutine.

Using the launch() function is much like creating a new thread with a Runnable object, primarily because you can't return any value from it. If you want to be able to return a value from your coroutine, you must create it using the async() function instead.

The async() function returns a Deferred object, which, just like the Job object, allows you to manage the coroutine. However, it also allows you to use the await() function to wait for the result of the coroutine without blocking the current thread.

For instance, consider the following coroutines that use the fetchWebsiteContents() suspending function and return the content lengths of two different webpage addresses:

With the above code, both the coroutines will start immediately and run in parallel.

If you now want to use the returned lengths, you must call the await() method on both the Deferred objects. However, because the await() method too is a suspending function, you must make sure that you call it from another coroutine.

The following code shows you how to calculate the sum of the two lengths using a new coroutine created with the launch() function:

7. Using Coroutines in the UI Thread

Coroutines do make use of background threads internally, which is why they don't run on an Android app's UI thread by default. Consequently, if you try modifying the contents of your app's user interface from inside a coroutine, you will encounter a runtime error. Fortunately, it's trivially easy to run a coroutine on the UI thread: you just have to pass the UI object as an argument to your coroutine builder.

For example, here's how you can rewrite the last coroutine to display the sum inside a TextView widget:

The above code might seem mundane at first, but look again. It's not only able to wait for two background operations to complete without using callbacks, it's able to do so on the app's UI thread without blocking it!

Having the ability to wait on the UI thread, without making your UI feel sluggish or triggering an Application Not Responding error, often referred to as ANR, simplifies a lot of otherwise complex tasks. 

For instance, with the suspending delay() function, which is the non-blocking equivalent of the Thread.sleep() method, you can now create animations with loops. To help you get started, here's a sample coroutine that increments the x coordinate of a TextView widget every 400 ms, thus creating a marquee-like effect:

Conclusion

While developing Android apps, it is imperative that you perform long-running operations in background threads. In this tutorial, you learned several approaches you can follow to create and manage such threads in Kotlin. You also learned how to use the still experimental coroutines feature to wait inside threads without blocking them.

To learn more about coroutines, you can refer to the official documentation. And while you're here, check out some of our other posts about Kotlin and Android development!

  • Android SDK
    How to Create an Android Chat App Using Firebase
    Ashraff Hathibelagal
  • Android SDK
    Sending Data With Retrofit 2 HTTP Client for Android
    Chike Mgbemena
  • Android SDK
    Get Started With RxJava 2 for Android
    Jessica Thornsby
  • Android SDK
    Java vs. Kotlin: Should You Be Using Kotlin for Android Development?
    Jessica Thornsby

12:00

Working With Tables in React, Part One

Overview

One of the most common user interface elements for presenting your data is a table. It turns out that there are many aspects to control when working with tables, such as:

  • defining columns and headers
  • various cell formats (text, numbers, check boxes)
  • resizing
  • filtering
  • dynamic growing
  • styling

In this two-part series, you'll will learn about the ins and outs of working with tabular data in React using the React Bootstrap Table component. You'll be able to create sophisticated and professional looking tables by default with little effort and yet be able to customize every part you want to.

Create a Vanilla React App

I assume you are familiar with React itself and will focus on working with React Bootstrap Table. Envato Tuts+ has a great series on React you can read for background.

In a nutshell, I used react-create-app to create a vanilla React app and then installed the react-bootstrap-table: npm install react-bootstrap-table --save.

It's important to add the bootstrap CSS to the public/index.html file.

WebStorm

If you use JetBrains' WebStorm and you want to run the tests, add --env=jsdom in your run config.

Basic Table

We will start with a basic table. Here is a basic table component. It imports the BoostrapTable and TableHeaderColumn from react-bootstrap-table and also the CSS from the dist directory. 

The render() method renders a table with three columns: "ID", "Name", and "Value". The actual data in the table comes from the "data" property (this.props.data). The data contains the names of some characters from the hilarious show Arrested Development.

I instantiated the BasicTable in the render() method of the standard App.js and passed some hard-coded data:

To view the table, type: npm start. The configuration created by create-react-app watches over your code and will recompile whenever you change anything, so you need to run only once and then every change will automatically be reflected.

Here is the result:

Basic table output with three columns and rows

Note that each column has exactly the same width.

Working With Columns

You can control many aspects of the columns. In particular, the column widths can be specified in absolute units as percentages or left unspecified. The column width of unspecified columns is the remainder divided equally. For example, for a table width of 100 px, one column specified 15 px, a second column specified 25% (25 px), and a third column specified 30% (15 px). 

Two other columns didn't specify a width. Columns 1, 2 and 3 used 70 px together, which leaves 30 px for columns 4 and 5, which will divide it equally. Column 4 and 5 will each have a width of 15 px. Note that if the table is resized, the numbers will change. Only column 1 will always be 15 px wide. 

The other columns will be computed based on the table width. You can also manage the alignment of text and columns as well as the style of headers and columns. Here is an example of how to specify different column widths, text alignment, and custom styles:

Working with Columns

Styling Your Table

You saw how to style individual columns and headers, but styling can go much further. React-bootstrap-table provides a lot of options for customization. First you can simply add the striped and hover attributes to the BootstrapTable component to get alternate background colors on each row: <BootstrapTable data={this.props.data} striped hover>

To style all rows, use trClassName<BootstrapTable data={data} trClassName='tr-style'> 

If you want to get really fancy, the trStyle can a function. Check out the following table component that styles differently rows where the name is "George Michael":

The GeorgeMichael-Row and Other-Row CSS classes are defined in Table.css:

Styling the table

Selecting Rows

Once you have your data in a table, you may want to select some rows in order to perform some operations on them. React-bootstrap-table provides a wide variety of selection options. All the options are organized in a single object you pass to the component as the selectRow attribute. Here are some of the selection options:

  • single selection mode (radio button)
  • multi-selection mode (checkbox)
  • configurable column selection width
  • select on row click: by default you must click the selector (radio button or checkbox)
  • hide selection column (useful if select on row click is true)
  • change background color on selection
  • initial selected rows
  • selection hooks (on single row or when all rows are selected).

The following components demonstrate many of these options:

Selecting Rows

Conclusion

In this part, we created a simple React application using react-create-app, added React-Bootstrap-Table, populated a table with data, worked with columns, styled the table, and selected rows. 

In the next part, we'll continue the journey by expanding rows, adding rows, deleting rows, and covering pagination, cell editing, and advanced customization. Stay tuned.

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!

Schweinderl