Author: tejas

  • Getting Started with Elixir Programming Language

    If you have been reading blog posts, hacker news threads, your favorite developers tweets or listening to podcasts, at this point you’ve probably heard about the Elixir programming language. The language was created by José Valim, a well known developer in the open-source world. You may know him from the Ruby on Rails MVC framework or from devise and simple_form ruby gems him and his co-workers from the Plataformatec have been working on in the last few years.
    According the José Valim, Elixir was born in 2011. He had the idea to build the new language due the lack of good tools to solve the concurrency problems in the ruby world. At that time, after spending time studying concurrency and distributed focused languages, he found two languages that he liked, Erlang and Clojure which run in the JVM. He liked everything he saw in the Erlang language (Erlang VM) and he hated the things he didn’t see, like polymorphism, metaprogramming and language extendability attributes which Clojure was good at. So, Elixir was born with that in mind, to have an alternative for Clojure and a dynamic language which runs in the Erlang Virtual Machine with good extendability support.
    Getting Started with Elixir Programming Language
    Elixir describes itself as a dynamic, functional language with immutable state and an actor based approach to concurrency designed for building scalable and maintainable applications with a simple, modern and tidy syntax. The language runs in the Erlang Virtual Machine, a battle proof, high-performance and distributed virtual machine known for its low latency and fault tolerance characteristics.
    Before we see some code, it’s worth saying that Elixir has been accepted by the community which is growing. If you want to learn Elixir today you will easily find books, libraries, conferences, meetups, podcasts, blog posts, newsletters and all sorts of learning sources out there as well as it was accepted by the Erlang creators.
    Let’s see some code!

    Install Elixir:

    Installing Elixir is super easy in all major platforms and is an one-liner in most of them.

    Arch Linux

    Elixir is available on Arch Linux through the official repositories:

    pacman -S elixir
    

    Ubuntu

    Installing Elixir in Ubuntu is a bit tidious. But it is easy enough nonetheless.

    wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
    apt-get update
    apt-get install esl-erlang
    apt-get install elixir
    

    OS X

    Install Elixir in OS X using Homebrew.

    brew install elixir
    

    Meet IEx

    After the installation is completed, it’s time to open your shell. You will spend a lot of time in your shell if you want to develop in Elixir.
    Elixir’s interactive shell or IEx is a REPL – (Read Evaluate Print Loop) where you can explore Elixir. You can input expressions there and they will be evaluated giving you immediate feedback. Keep in mind that your code is truly evaluated and not compiled, so make sure not to run profiling nor benchmarks in the shell.

    The Break Command

    There’s an important thing you need to know before you start the IEx RELP – how to exit it.
    You’re probably used to hitting CTRL+C to close the programs running in the terminal. If you hit  CTRL+C in the IEx RELP, you will open up the Break Menu. Once in the break menu, you can hit CTRL+C again to quit the shell as well as pressing a.

    I’m not going to dive into the break menu functions. But, let’s see a few IEx helpers!

    Helpers

    IEx provides a bunch of helpers, in order to list all of them type: h().
    And this is what you should see:

    Those are some of my favorites, I think they will be yours as well.

    • h as we just saw, this function will print the helper message.
    • h/1 which is the same function, but now it expects one argument.

    For instance, whenever you want to see the documentation of the String strip/2 method you can easily do:

    Probably the second most useful IEx helper you’re going to use while programming in Elixir is the c/2, which compiles a given elixir file (or a list) and expects as a second parameter a path to write the compiled files to.
    Let’s say you are working in one of the https://exercism.io/ Elixir exersices, the Anagram exercise.
    So you have implemented the Anagram module, which has the method match/2 in the anagram.exs file. As the good developer you are, you have written a few specs to make sure everything works as expected as well.
    This is how your current directory looks:

    Now, in order to run your tests against the Anagram module you need to run/compile the tests.

    As you just saw, in order to compile a file, simply invoke the elixir executable passing as argument path to the file you want to compile.
    Now let’s say you want to run the IEx REPL with the Anagram module accessible in the session context. There are two commonly used options. The first is you can require the file by using the options -r, something like iex -r anagram.exs. The second one, you can compile right from the IEx session.

    Simple, just like that!
    Ok, what about if you want to recompile a module? Should you exit the IEx, run it again and compile the file again? Nope! If you have a good memory, you will remember that when we listed all the helpers available in the IEx RELP, we saw something about a recompile command. Let’s see how it works.

    Notice that this time, you passed as an argument the module itself and not the file path.
    As we saw, IEx has a bunch of other useful helpers that will help you learn and understand better how an Elixir program works.

    Basics of Elixir Types

    Numbers

    There are two types of numbers. Arbitrary sized integers and floating points numbers.

    Integers

    Integers can be written in the decimal base, hexadecimal, octal and binary.
    As in Ruby, you can use underscore to separate groups of three digits when writing large numbers. For instance you could right a hundred million like this:

    100_000_000
    

    Octal:

    0o444
    

    Hexdecimal:

    0xabc
    

    Binary:

    0b1011
    

    Floats

    Floare are IEEE 754 double precision. They have 16 digits of accuracy and a maximum exponent of around 10308.
    Floats are written using a decimal point. There must be at least one digit before and after the point. You can also append a trailing exponent. For instance 1.0, 0.3141589e1, and 314159.0-e.

    Atoms

    Atoms are constants that represent names. They are immutable values. You write an atom with a leading colon : and a sequence of letters, digits, underscores, and at signs @. You can also write them with a leading colon : and an arbitrary sequence of characters enclosed by quotes.
    Atoms are a very powerful tool, they are used to reference erlang functions as well as keys and Elixir methods.
    Here are a few valid atoms.

    :name, :first_name, :"last name",  :===, :is_it_@_question?
    

    Booleans

    Of course, booleans are true and false values. But the nice thing about them is at the end of the day, they’re just atoms.

    Strings

    By default, strings in Elixir are UTF-8 compliant. To use them you can have an arbitrary number of characters enclosed by " or '. You can also have interpolated expressions inside the string as well as escaped characters.

    Be aware that single quoted strings are actually a list of binaries.

    Anonymous Functions

    As a functional language, Elixir has anonymous functions as a basic type. A simple way to write a function is fn (argument_list) -> body end. But a function can have multiple bodies with multiple argument lists, guard clauses, and so on.
    Dave Thomas, in the Programming Elixir book, suggests we think of fn…end as being the quotes that surround a string literal, where instead of returning a string value we are returning a function.

    Tuples

    Tuple is an immutable indexed array. They are fast to return its size and slow to append new values due its immutable nature. When updating a tuple, you are actually creating a whole new copy of the tuple self.
    Tuples are very often used as the return value of an array. While coding in Elixir you will very often see this, {:ok, something_else_here}.
    Here’s how we write a tuple: {?a,?b,?c}.

    Pattern Matching

    I won’t be able to explain everything you need to know about Pattern Matching, however what you are about to read covers a lot of what you need to know to get started.
    Elixir uses = as a match operator. To understand this, we kind of need to unlearn what we know about = in other traditional languages. In traditional languages the equals operator is for assignment. In Elixir, the equals operators is for pattern matching.
    So, that’s the way it works values in the left hand side. If they are variables they are bound to the right hand side, if they are not variables elixir tries to match them with the right hand side.

    Pin Operator

    Elixir provides a way to always force pattern matching against the variable in the left hand side, the pin operator.

    Lists

    In Elixir, Lists look like arrays as we know it from other languages but they are not. Lists are linked structures which consist of a head and a tail.

    Keyword Lists

    Keyword Lists are a list of Tuple pairs.
    You simply write them as lists. For instance: [{:one, 1}, 2, {:three, 3}]. There’s a shortcut for defining lists, here’s how it looks: [one: 1, three: 3].
    In order to retrieve an item from a keyword list you can either use:

    Keyword.get([{:one, 1}, 2, {:three, 3}], :one)
    

    Or use the shortcut:

    [{:one, 1}, 2, {:three, 3}][:one]
    

    Because keyword lists are slow when retrieving a value, in it is an expensive operation, so if you are storing data that needs fast access you should use a Map.

    Maps

    Maps are an efficient collection of key/value pairs. The key can have any value you want as a key, but usually should be the same type. Different from keyword lists, Maps allow only one entry for a given key. They are efficient as they grow and they can be used in the Elixir pattern matching in general use maps when you need an associative array.
    Here’s how you can write a Map:

    %{ :one => 1, :two => 2, 3 => 3, "four" => 4, [] => %{}, {} => [k: :v]}
    

    Conclusion

    Elixir is awesome, easy to understand, has simple but powerful types and very useful tooling around it which will help you when beginning to learn. In this first part, we have covered the various data types Elixir programs are built on and the operators that power them. In later parts we will dive deeper into the world of Elixir – functional and concurrent programming.
    This post originally appeared in Toptal

  • PHP Encoder v1.8

    PHP Encoder v1.8

    Hi Everyone here i am introducing a PHP Encoder tools.
    With this tool you can encode your PHP code in secure code. once you encode code only execution time web-server will decode it. and nobody can decode it.
    This is my first beta version release so this tool will expire after 1 July 2016.
    I am releasing this tool as testing purpose. So please help me if you found any bug in this tool.
    To activate this tool you need to enter email id, Password & serial key. currently i have create only user to test it. and this key will expire after 1 July 2016. Also i am inviting you to crack it So if you can crack it then just comment in Comment Box.

    Email: [email protected]
    Password: 1234
    Serial: 1234

    v1.8 Changelog:

    * Improve activation
    * PHP7 Compatible
    * Improve stability
    * Bug fixes

    v1.5 Changelog:
    * Fix issue of freezing after activation & checking for update.
    * Improve stability
    * Speedup on checking for update

    [wpdm_package id=’2281′]

  • Android Developer’s Guide to Fragment Navigation Pattern

    Over the years, I’ve seen many different navigation pattern implementations in Android. Some of the apps were using only Activities, while others Activities mixed with Fragments and/or with Custom Views.
    One of my favorite navigation pattern implementations is based on the “One-Activity-Multiple-Fragments” philosophy, or simply the Fragment Navigation Pattern, where every screen in the application is a full screen Fragment and all or most of these fragments are contained in one Activity.
    This approach not only simplifies how the navigation is implemented, but it has much better performance and consequently offers a better user experience.
    Android Developer’s Guide to Fragment Navigation Pattern
    In this article we will look at some common navigation pattern implementations in Android, and then introduce the Fragment based navigation pattern, comparing and contrasting with the others. A demo application implementing this pattern has been uploaded to GitHub.

    World of Activities

    A typical Android application which uses only activities is organized into a tree-like structure (more precisely into a directed graph) where the root activity is started by the launcher. As you navigate in the application there is an activity back stack maintained by the OS.
    A simple example is shown in the diagram below:

    Activity A1 is the entry point in our application (for example, it represents a splash screen or a main menu) and from it the user can navigate to A2 or A3. When you need to communicate between activities you can use the startActivityForResult() or maybe you share a globally accessible business logic object between them.
    When you need to add a new Activity you need to perform the following steps:

    • Define the new activity
    • Register it in the AndroidManifest.xml
    • Open it with a startActivity() from another activity

    Of course this navigation diagram is a fairly a simplistic approach. It can become very complex when you need to manipulate the back stack or when you have to reuse the same activity multiple times, for example when you would like to navigate the user through some tutorial screens but each screen in fact uses the same activity as a base.
    Fortunately we have tools for it called tasks and some guidelines for proper back stack navigation.
    Then, with API level 11 came fragments…

    World of Fragments

    “Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet’s screen is much larger than that of a handset, there’s more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity’s appearance at runtime and preserve those changes in a back stack that’s managed by the activity.” – cited from the Google’s API guide for Fragments.

    This new toy allowed developers to build a multi-pane UI and reuse the components in other activities. Some developers love this while others don’t. It is a popular debate whether to use fragments or not, but I think everybody would agree that fragments brought in additional complexity and the developers really need to understand them in order to use them properly.

    Fullscreen Fragment Nightmare in Android

    I started to see more and more examples where the fragments were not just representing a part of the screen, but in fact the whole screen was a fragment contained in an activity. Once I even saw a design where every activity had exactly one full screen fragment and nothing more and the only reason why these activities existed was to host these fragments. Next to the obvious design flaw, there is another problem with this approach. Have a look at the diagram from below:

    How can A1 communicate with F1? Well A1 has total control over F1 since it created F1. A1 can pass a bundle, for example, on the creation of F1 or can invoke its public methods. How can F1 communicate with A1? Well this is more complicated, but it can be resolved with a callback/observer pattern where the A1 subscribes to F1 and F1 notifies A1.
    But how can A1 and A2 communicate with each other? This has been covered already, for example via startActivityForResult().
    And now the real question comes: how can F1 and F2 communicate with each other? Even in this case we can have a business logic component which is globally available, so it can be used to pass data. But this does not always lead to elegant design. What if F2 needs to pass some data to F1 in a more direct way? Well, with a callback pattern F2 can notify A2, then A2 finishes with a result and this result is captured by A1 which notifies F1.
    This approach needs a lot of boilerplate code and quickly becomes a source of bugs, pain and anger.
    What if we could get rid all of the activities and keep only one of them which keeps the rest of the fragments?

    Fragment Navigation Pattern

    Over the years I started to use the “One-Activity-Multiple-Fragments” pattern in most of my applications and I still use it. There are a lot of discussions out there about this approach, for example here and here. What I missed however is a concrete example which I can see and test myself.
    Let’s have a look at the following diagram:

    Now we have only one container activity and we have multiple fragments which have again a tree like structure. The navigation between them is handled by the FragmentManager, it has its back stack.
    Notice that now we don’t have the startActivityForResult() but we can implement a callback/observer pattern. Let’s see some pros and cons of this approach:

    Pros:

    1. Cleaner and more maintainable AndroidManifest.xml

    Now that we have only one Activity, we no longer need to update the manifest every time we add a new screen. Unlike activities, we do not have to declare fragments.
    This could seem like a minor thing, but for larger applications which have 50+ activities this can significantly improve readability of the AndroidManifest.xml file.
    Look at the manifest file of the example application which has several screens. The manifest file still remains super simple.

    <?xml version="1.0" encoding="utf-8"?>
       package="com.exarlabs.android.fragmentnavigationdemo.ui" >
       <application android:name= ".FragmentNavigationDemoApplication"
           android:allowBackup="true"
           android:icon="@mipmap/ic_launcher"
           android:label="@string/app_name"
           android:supportsRtl="true"
           android:theme="@style/AppTheme">
           <activity
               android:name="com.exarlabs.android.fragmentnavigationdemo.ui.MainActivity"
               android:label="@string/app_name"
               android:screenOrientation="portrait"
               android:theme="@style/AppTheme.NoActionBar" >
               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />
                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>
           </activity>
       </application>
    </manifest>
    

    2. Centralized navigation management

    In my code example, you will see that I use NavigationManager which in my case it is injected into every fragment. This manager can be used as a centralised place for logging, back stack management and so on, so navigation behaviours are decoupled from the rest of the business logic and not spread around in implementations of different screens.
    Let’s imagine a situation where we would like to start a screen where the user can select some items from a list of person. You also would like to pass some filtering arguments like age and occupation and gender.
    In case of Activities, you would write:

    Intent intent = new Intent();
    intent.putExtra("age", 40);
    intent.putExtra("occupation", "developer");
    intent.putExtra("gender", "female");
    startActivityForResult(intent, 100);
    

    Then you have to define the onActivityResult somewhere below and handle the result.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
    

    My personal problem with this approach is that these arguments are “extras” and they are not mandatory, so I have to make sure that the receiving activity handles all the different cases when an extra is missing. Later on when some refactoring is made and the “age” extra for example is no longer needed, then I have to search everywhere in the code where I start this activity and make sure that all the extras are correct.
    Furthermore, wouldn’t it be nicer if the result (list of persons) would arrive in a form of _List_ and not in a serialized form which must be deserialized?
    In case of fragment based navigation, everything is more straightforward. All you have to do is to write a method in the NavigationManager called startPersonSelectorFragment() with the necessary arguments and with a callback implementation.

    mNavigationManager.startPersonSelectorFragment(40, "developer", "female",
          new PersonSelectorFragment.OnPersonSelectedListener() {
              @Override
              public boolean onPersonsSelected(List<Person> selection) {
           [do something]
                  return false;
              }
          });
    

    Or with RetroLambda

    mNavigationManager.startPersonSelectorFragment(40, "developer", "female", selection -> [do something]);
    

    3. Better means of communication between screens

    Between activities, we can share only a Bundle which can hold primitives or serialized data. Now with fragments we can implement a callback pattern where for example, F1 can listen to F2 passing arbitrary objects. Please have a look at the previous examples’ callback implementation, which returns back a _List_.

    4. Building Fragments are less expensive than building Activities

    This becomes obvious when you use a drawer which has for example 5 menu items and on each page the drawer should be displayed again.
    In case of pure activity navigation, each page should inflate and initialize the drawer, which is of course expensive.
    On the diagram below you can see several root fragments (FR*) which are the full screen fragments which can be accessed directly from the drawer, and also the drawer is only accessible when these fragments are displayed. Everything which is to the right of the dashed line in the diagram are there as an example of an arbitrary navigation scheme.

    Since the container activity holds the drawer, we have only one drawer instance so at every navigation step where the drawer should be visible you don’t have to inflate and initialize it again. Still not convinced how all of these work? Take a look at my sample application which demonstrates drawer usage.

    Cons

    My greatest fear had always been that if I used fragment based navigation pattern in a project, somewhere down the road I would encounter an unforeseen problem which would be difficult to solve around the added complexity of fragments, 3rd party libraries and the different OS versions. What if I had to refactor everything I’ve done so far?
    Indeed, I had to resolve problems with nested fragments, 3rd party libraries which also use fragments such as ShinobiControls, ViewPagers and FragmentStatePagerAdapters.
    I must admit that gaining sufficient experience with fragments to be able to solve these problems was a rather long process. But in every case the issue was not that the philosophy is bad, but that I did not understand fragments well enough. Maybe if you understand fragments better than I did you would not even encounter these issues.
    The only con that I can mention now is that we can still encounter problems which would not be trivial to solve since there is no mature library out there which showcase all the complex scenarios of a complex application with fragment based navigation.

    Conclusion

    In this article, we have seen an alternative way to implement navigation in an Android application. We compared it with the traditional navigation philosophy that uses activities and we have seen a few good reasons why it is advantageous to use it over the traditional approach.
    In case you haven’t already, check out the demo application uploaded to GitHub implementing. Feel free to fork or contribute to it with nicer examples which would better show its usage.
    This post originally appeared in Toptal Engineering blog, by Becze Szabolcs

  • Boost Your Productivity With Amazon Web Services

    During the last few years, the hottest word on everyone’s lip has been “productivity.” In the rapidly evolving Internet world, getting something done fast always gets an upvote. Despite needing to implement real business logic quickly and accurately, as an experienced PHP developer I still spent hundreds of hours on other tasks, such as setting up database or caches, deploying projects, monitoring online statistics, and so on. Many developers have struggled with these so called miscellaneous tasks for years, wasting time instead concentrating on the project logic.
    My life changed when a friend mentioned Amazon Web Services (AWS) four years ago. It opened a new door, and led to a tremendous boost in productivity and project quality. For anyone who has not used AWS, please read this article, which I am sure you will find worth your time.
    Boosting your productivity

    Amazon Web Services (AWS) can boost your productivity, literally, in minutes.

    AWS Background

    Amazon Web Services was officially launched in 2006. Many people will have heard of it, but probably don’t know what it can offer. So, the first question is: What is AWS?

    Amazon Web Services (AWS), is a collection of cloud computing services, also called web services, that make up a cloud-computing platform offered by Amazon.com.

    Wikipedia
    From this definition, we know two things: AWS is based in the cloud, and AWS is a collection of services, instead of a single service. Since this does not tell you much, in my opinion, it is better for a beginner to understand AWS as:

    • AWS is a collection of services in the cloud, as the definition says.
    • AWS provides fast computing resources online (for example, you need 10 minutes to set up a Linux server).
    • AWS offers affordable fees.
    • AWS provides easy-to-use services out of the box, which is saves lots of time manually setting up a database, cache, storage, network and other infrastructure services.
    • AWS is always available and is highly scalable.

    There are, of course, many more advantages to using AWS, so, let’s have a quick overview of how it can boost your productivity.

    Create an AWS account for free

    To begin using any service, you need to have an account. Creating an account for AWS should take you no more than five minutes. Make sure you have the following information at hand:

    • An Email address, which is used to receive a confirmation email.
    • A credit card, which will not be billed since the setup process is always free.
    • A phone number, which will receive an automated system call to identify user

    That’s it. Once you have the info listed above ready, visit AWS web page, and create an account following the easy-to-follow instructions.
    Note the following:

    • Most AWS services offer an abundance of free tier resources on a monthly basis. That is, testing AWS typically costs you little or nothing.
    • The phone number and other personal information has not been abused, according to my experience

    Get your first EC2 server setup

    One of the benefits of a cloud service is the ability to get shared resources on demand. Amazon has provided four tiers of service for the user to access its services, listed in the order of easiness:

    • Management Console,
    • Command-Line-Tool,
    • SDK,
    • RESTful API.

    In this article, we will be using the Management Console. So, after you log in to the console, you will see a screen like below:
    Setting up your first EC2 server in the AWS
    There are two areas to note:

    • On the top-right corner, you will find the region selector. AWS provides services in 11 different regions across the world, and it is still growing. Choose a region as your choice, or leave it to US East (N. Virginia) as default. Different regions may vary in pricing, which you should bear in mind as your usage grows.
    • Most of the screen is filled with a list of services. We will cover EC2 in this section. Take a quick look at what AWS provides. Don’t worry if they don’t make sense, all of the services will work on their own. However, you will get greater productivity by using a combination of them.

    The most fundamental need of a cloud resource is the virtual server. EC2, or Elastic Compute Cloud, is the name chosen by Amazon for its virtual server service. Let’s have a look at how easy it is to get a Linux server online.

    • In the EC2 management console, start the launching process like below:

    Setting up your first EC2 server in the AWS

    • Choose a machine image (AMI for short) to begin. This is the operating system that will run your machine. Pick any system of your preference. I recommend you start with Amazon Linux, which uses yum to manage packages:

    Setting up your first EC2 server in the AWS

    • Next, select an instance type. You can understand this as your hardware specification for your virtual server. You can start with t2.micro, because you will get 750 hours of free usage every month with this instance for the first year. Note this is valid only the first year from the date you sign up, and only for the t2.micro instance. It’s a good deal if you only want to have a taste of AWS.

    Setting up your first EC2 server in the AWS

    • With the ability to configure the server in more detail, you can launch the server. The first time you use EC2, you will see a screen similar to the one below. The warning about security tells us how much Amazon emphasizes the security aspect. However, we can ignore this warning until we visit the section about managed services.

    Setting up your first EC2 server in the AWS

    • Finally, to access a remote server, we need an identity. AWS will prompt us to choose an SSH key pair, as in the image below. Download the privacy key file and click the launch button. And yes, we are done; a new virtual server is being configured and will be ready in a few minutes.

    Setting up your first EC2 server in the AWS

    • Once the instance is ready, you may log into the system as default user ec2-user, with your privacy key. ec2-user is the AWS default that also has sudo ability. Although it is not possible to change the default username, you may create any user and assign the appropriate privileges according to your preferences. The address of your server can be found here:

    Setting up your first EC2 server in the AWS
    The process above should take less than five minutes, and that is how easily we get a virtual server up and running. In the next section, we will learn how AWS helps us manage the instance we just created.

    On-demand billing

    Most AWS resources are billed in hours, which provides good flexibility. For example, taking the EC2 instance we just created, there are two ways to put it out of service: stop and terminate. Both actions will stop the billing. The difference is that by stopping an instance, we can re-start it later with all our work saved. In contrast, by terminating an instance, we give the instance back to AWS for recycling and there is no way to recover the information. The need to terminate an instance results from AWS setting a limit of 20 instances per region per account by default, and a stopped instance still counts until it is terminated.
    We can stop an instance quickly by:
    Setting up your first EC2 server in the AWS
    When you stop your EC2 instance, your bill stops growing, as well. It’s especially useful in the following scenarios:

    • When you want to try something new, it is more cost friendly if you only need to pay for a couple of hours, and you probably won’t exceed the free tier for some services.
    • When your computing need is in production environment scales. For example, in the past, I needed to reserve computing resources which are usually 30-50 percent more than the peak usage. With AWS, I could provision resources in a more flexible way:

    Setting up your first EC2 server in the AWS
    Pricing information for AWS is available online. After making some calculations, you may raise the question: Is AWS actually cheaper? By multiplying the hourly rate for a month’s time, it looks like it’s not competitive at all. The answer is yes and no.
    AWS is not cheaper if you simply calculate the hourly rate for the on-demand resource over a month. However, we still have the reserved instances billing choices as illustrated below:
    Setting up your first EC2 server in the AWS
    For the minimum resource requirements, we can achieve a 30 to70 percent discount using the reserved instance, along with other varying resources billed as an on-demand instance. In practice, this will be 30 to 40 percent cheaper with the one-year commitment, and even more with a three-year commitment using reserved instances. That is why I’ll vote “Yes” on the above question. And AWS is even cheaper if you include the security and monitoring benefits.

    Managed services

    One aim of AWS is to eliminate as much of the operational cost as possible. Traditionally, we need a large team of system engineers to maintain the security and health of our infrastructure, either online on onsite. Experienced teams will write and deploy their automated tools to simplify the process. However, managing services becomes a complicated project in practice, as well. AWS acts as a lifesaver in helping us manage our resources. Below, I have listed some of the services provided by AWS that are most used:

    • AWS Security Group,
    • IAM, Identity Access Management,
    • CloudWatch,
    • And a list of auto deployment services such as OpsWorks (which will not be covered in this article).

    AWS Security Group

    How AWS handles access control of services is done in two separate layers. On the network level, it is achieved by using an idea known as “security groups.” All AWS services are in security groups. And the security group determines who is allowed to pass through. Taking our EC2 instance, AWS has automatically created a security group for us:
    Setting up your first EC2 server in the AWS
    We can decide what can comes in and what can go out by configuring inbound/outbound rules. TCP, UDP, and ICMP rules are supported by the EC2 service. The security group acts like an external hardware level firewall, and we never need think about patching it.
    One more advantage of using security group is that it is reusable. One security group can be shared among many resources. In practice, it greatly improves maintenance efficiency by removing the hassle of setting security policy one by one for each resource. Also, the shareable nature of a security group enables us to configure it in a single place, and apply that security policy to any other resources, without the hassle of setting it manually, one by one for each resource.

    Identity and Access Management

    AWS provides another method to handle access control by using IAM. This is an application level security control for when you need to access the RESTful interfaces. Each REST request must be signed so that AWS knows about who is accessing the service. Also, by checking against a preconfigured list of policies, AWS will determine if the action should be denied or allowed through.
    We will not cover IAM in detail in this article. However, note that AWS puts a lot of thought into security so you can be sure no unauthorized visitors can access your confidential data.

    CloudWatch

    CloudWatch is a service provided by AWS to collect and track all kinds of metrics from your AWS resources. It is more powerful because of its ability to react to certain events (or alarms). With the help of CloudWatch, we can monitor the health of our newly created EC2 instance.

    • We can add alarms to our EC2 instance quickly:

    Setting up your first EC2 server in the AWS

    • Alarms may be created by specifying criteria for many different purposes:

    Setting up your first EC2 server in the AWS
    NOTE: SNS is a topic based service provided by AWS to send notifications. Notifications can be sent by email, SMS, iOS/Android push notification and many other formats.
    From monitoring to notifying, CloudWatch attempts to automate monitoring needs in a few clicks. There are tons of metrics predefined for various AWS services. For the advanced user, you can even create custom metrics for your application.
    Regarding cost, the free tier service provided by CloudWatch is usually plenty for start-up projects. However, even when your business grows, the added costs are usually less than 1 percent of the service cost. Check detailed pricing for further information. Considering how easy it is to set up a monitoring system using CloudWatch, it has become the most used monitoring tool.

    Hassle free application services

    As developers, we have likely experienced the following scenarios:

    • Our application needs a database component, which means that we have to:
      • Get a server for the database.
      • Install the database software.
      • Configure monitors for the server and the database.
      • Plan backup schemes.
      • Patch the software as needed.
      • And many other not listed here.
    • Our application needs distributed file storage, which means that we have to:
      • Find existing open source (or commercial) solutions for distributed file storage.
      • Prepare the needed servers.
      • Install and configure the chosen solution, which is usually not straightforward.
      • Configure monitors for the server and the database
      • And many other not listed here
    • Our application needs a cache.
    • Our application needs a message queue.
    • And many other problems to be solved, plus, we need to do pre-configuration and post-monitoring work.

    And, as you may have already guessed, this is another significant area where AWS helps. There are a lot of application level services available, so you won’t need to consider anything else.
    Let’s cover some of them to give you a quick picture.

    RDS, database managed for you but not by you

    Relational databases (RDBMS) have been widely adopted by a lot of applications. In the production environment, special attention is always needed when deploying applications using RDBMS, beginning with how to setup and configure the database, followed by when and how backups are made and restored.
    In our team, our Database Administrator (DBA) used to spend at least 30 percent of his time writing setup and maintenance scripts. With the introduction of AWS RDS, our DBA got more time to do SQL performance tuning, which is the preferred area to invest your DBA in.
    So, what does RDS offer you? In short:

    • RDS provides support for most of the popular database engines, including MySQL, SQLServer, PostgreSQL.
    • A database, either a node or a cluster, can be created in a few clicks.
    • RDS offers built-in support for shared database parameters, under the service named “Parameter Group”.
    • RDS provides built-in support for access management with the help of Security Group , which is quite similar to the one we covered for EC2.
    • RDS offers additional services by enabling Multi-AZ in a single click. All monitoring, standby and failover switching are done automatically.
    • Maintenance and backup of RDS are automated.

    To conclude, RDS saves a considerable amount of time when it comes to setup and maintenance of the database services. In exchange, you will pay about 40 percent more than the corresponding EC2 server. So, it is a business decision whether to opt for RDS or deploy the corresponding server on your own. However, it does allow you to invest more time in work that’s related to real business rather than infrastructure stability and scalability. Plus, you will soon notice that this is the way of business AWS advocates.

    Dynamo DB, a key-value storage scales to billions of records

    NoSQL has become a favorite topic in recent years. Since many real life projects do not need the support of various relational DBMS, a list of NoSQL databases has been introduced to the market. Amazon is not falling behind in this. DynamoDB (https://aws.amazon.com/dynamodb) is the key-value store announced by Amazon in 2012, and the core contributor to this service is Werner Vogels, CTO of Amazon, one of the world’s top experts on ultra-scalable systems.
    It is no secret that Amazon handles massive traffic. DynamoDB is derived from Dynamo, which has been the internal storage engine for many Amazon’s businesses, including its shopping cart service that serves billions of requests every Christmas. DynamoDB has no limitation in scaling up.
    Further, when compared to other NoSQL solutions, such as Cassandra or MongoDB, there is an enormous economic advantage to DynamoDB; it is billed in the unit of reserved throughput (how many write/read per second is allowed), which can be increased or decreased in real time. Below is a cost comparison table between DynamoDB and other standalone NoSQL solution:

    Business Need DynamoDB service DynamoDB cost Using another service Cost when using another service
    Small Business
    (less than 1000 DAU, 16GB data)
    10 write unit
    10 read unit
    $9.07/month • t1.micro ••
    16GB EBS •••
    $14.64/month
    Medium Business
    (less than 100k DAU, 160GB data)
    100 write unit
    100 read unit
    $101.62/month m4.xlarge
    160GB EBS
    $190.95/month
    Large Business
    (up to 1m DAU, 1TB data)
    1000 write unit
    1000 read unit
    $852.58/month Clustered c4.4xlarge • 512GB EBS • $1329.24/month

    • to be fair, price is calculated using on-demand pricing in US-EAST region
    •• AWS EC2 instances are selected to host other NoSQL services
    ••• EBS is the persistent storage service provided by AWS
    As we can read from the table, DynamoDB provides its service out of the box, and usually at a lower price compared to building your own key-value storage. This is because unless you hit the maximum capacity of your MongoDB/Cassandra cluster, you are paying more for something you never use.
    Amazon offers its service in a fully-managed manner. This means that you don’t have to worry how to setup, scale or monitor your DynamoDB; they are all done by AWS. In fact, reading and writing DynamoDB items are always measured in constant time complexity, regardless of the size of data being manipulated. Therefore, some applications have chosen to discard cache layers after they switched to DynamoDB. Amazing, indeed.

    SQS, distributed queue service

    When working with large volumes of data, we often distribute calculations to many computing nodes. When doing business globally, we are often in need of a pipeline to process data collected from nodes distributed in a geographically wide range. To help meet the requirements for such events, AWS introduces SQS, Simple Queue Service. Like many acknowledged queue services, SQS offers a way to pass messages/jobs between different logical components, in a persistent manner.
    As its name indicates, SQS is a basic service that is available at the beginning of AWS. However, Amazon has steadily been developing SQS, and depending on the need, SQS maybe as simple or as powerful as you need with many customizable parameters. Some of the advanced features of SQS are:

    • Retaining messages for up to 14 days.
    • Visibility mechanism for avoiding message loss in a failure event.
    • Delivery delay per message.
    • Redrive policy to handle failed messages (so-called dead letter).

    Queue services shouldn’t be too complicated. You may wonder why it is worth using a whole section just to introduce SQS. Perhaps you have already guessed the reason; like other AWS service, SQS is a fully managed service, which means:

    • The queue is highly scalable; it can be tens of messages you are passing through or millions per second, so SQS scales on the fly.
    • The queue is persistent and distributed, which means critical data will not be lost unless they expire.
    • You do not need to setup a server to deploy your queue software. And of course, you do not need to setup complex monitoring for the service, either

    S3, a file storage, but not only a file storage

    S3 stands for Simple Storage Service andis like Dropbox as a service for the end-user, but this is for applications. By definition, S3 is an object-based storage with a simple web interface.
    S3 is simple for the user, but also comes with lots of advanced features. I S3 has become an industry standard, especially for applications using other AWS services. This is mainly because S3 is so easy to integrate that it has become a popular external storage destination for most AWS services. Also, many services, such as DynamoDB, SQS and so on, make heavy use of S3 internally.
    Understanding S3 should amplify the benefits of using other AWS managed services. This is because most of the services store their backups on S3. Also, S3 is the common export/import destination for services including, but not limited to, DynamoDB, RDS, and Redshift.
    Finally, S3 is like other AWS services; it’s fully managed so we can simply start using the service without setting up any server or failover mechanisms. Economy wise, S3 is also a pay as you use service, so, you can always try it out without much cost.

    More advanced services and SDK

    There are many other AWS services also worth noting. Due to limited space, we are just listing some interesting ones here:

    • Redshift: A column based database which can be used to process trillions of data in a very fast manner. You must try it if you are responsible for the ETL of a large amount of data.
    • Data Pipeline: IAllows you to quickly transfer data between AWS services, and further enables periodical processing of data in a smaller shard.
    • ElastiCache: Managed Memcache server, simple but does the job perfectly.
    • Lambda: Next generation of cloud computing. Lambda runs an uploaded piece of code in an event-driven fashion that opens a new door for designing distributed applications.
    • Route53: Powerful DNS solution with the support of weighted response, geolocation based response on top of other industrial standard DNS solutions.
    • SNS: Easy-to-use notification service, designed in subscriber/publisher pattern.
    • Many more.

    I think it is a good habit to check AWS whenever you are introducing some new component to your application. Most often, AWS will give you a sweet surprise as it will have a ready a SaaS alternative to offer.
    Furthermore, to make it easier to access RESTful interfaces, Amazon has provided SDKs in almost all popular programming languages. You should have no problem finding your favorite SDK.

    Summary

    We have covered some of the most widely used services of AWS in this article. For sure there are some areas that AWS will help your business. You might choose to migrate an existing service component to its AWS equivalent, such as MySQL database to RDS, for instance. You may well find yourself asking if there are any AWS services for this component of my software? So, get an AWS account today, and get your productivity boost in minutes.
    This post originally appeared in Toptal Engineering blog

  • How to Bootstrap and Create .NET Projects

    Create .NET project

    To create a .NET project from scratch is as simple as using Visual Studio wizard. Go to File => New Project, or Add New Project to an existing solution. Once a new project has been created, you can start coding right away. However, the default project settings produced by wizards are hardly acceptable for professional teams, because they set a too low bar on quality. Moreover, no wizards can know about other setup steps you need to perform in your particular development environment.
    In this article, I will walk you through several important settings you should enable as soon as you create a new project, which is important to minimize a future technical debt. Also, we will review some common practices many .NET developers apply when they are structuring solutions and new projects. Even if you are not applying some of these ideas, it is nice to learn and get an overview of what most teams do.

    Structure

    Having a well-defined structure is vital for complex projects. This improves the on-boarding experience when newcomers are joining a team, and makes your life easier when you are supporting old projects. There are two key indicators of a good structure:

    • Using solution and project folders
    • Consistent naming

    Folders

    Solution folders, sometimes referred to as virtual folders, are a very handy instrument to group your projects. In the Solution Explorer view simply right-click and select Add => New Solution Folder, then drag-and-drop any of the existing projects to this new folder. These folders are not mirrored in the file system, letting you keep physical structure unchanged, so moving the projects from one Solution Folder to another does not move them physically.

    Having numbered prefixes is not required, but it is making the folders appear ordered right in the Solution Explorer window.
    Visual Studio can work with multiple solutions at the same time by leveraging Partitioned single solution or Multi-solution models. They are rarely used, so I won’t cover them in this article.
    Unlike Solution folders, Project folders match the physical folders structure and therefore persist as real folders on the disk. Moreover, Project folders containing a C# code should match project’s namespace. This makes navigation pretty natural. You can even enable a ReSharper rule to warn on such mismatches.

    Naming

    There are few recommended rules to apply related to naming:

    • Use CamelCase.
    • A project name should match its output assembly name.
    • A project containing automated tests should have the suffix .Tests.
    • All project names should have a common prefix, like Company.Product.


    There are few reasonable rules as well. You should decide on your own when to apply them based on common sense (and English grammar, of course):

    • Use subjects in plural form when a container (project or folder) contains multiple instances of the same kind (e.g. Tests or System.Collections).
    • Use singular form when the whole container contains code all about a single entity (e.g. System.Collections.ObjectModel`).
    • For short abbreviations, use upper case like System.IO does.
    • For long abbreviations, use CamelCase like Modules.Forex..

    A rule of thumb: a short abbreviation should not be longer than three characters.

    Configuring Solution

    Configuring a solution is as simple as providing all infrastructure files you need for your environment. Although some of them can be added later (such as CI integration files), few files you would better have in the very beginning.

    ReSharper Settings

    If you are professional .NET developer, then you very likely use ReSharper. ReSharper is very flexible in managing its settings. As a team leader, you can create and distribute Team Shared settings which will be used by other developers. Team Shared settings are stored in a file with extension .DotSettings. ReSharper will pick these settings automatically if the file name is matching Visual Studio solution name:

    MyCompany.MyProduct.sln
    MyCompany.MyProduct.sln.DotSettings
    

    Therefore, you should create this file in the very beginning if you ultimately want to apply some settings to the whole team. A good example would be the rule of using (or not using) var keyword. Your Team Sharedsettings file can have just this one rule, while others are the developers’ preference. It is worth mentioning that the same way ReSharper settings can be set on a per-project level, because you may have some legacy code that you cannot modify (e.g. change to use var keyword).
    If you named this file correctly, as shown in the example, then any new instance of Visual Studio with a fresh ReSharper setup will be picking this file automatically and enforce the rules. Do not forget to commit this file to the source control.

    StyleCop Rules

    Same as ReSharper settings, you can share StyleCop settings. If you use ReSharper, then you are probably having integration plugin installed that will leverage StyleCop from ReSharper. However, StyleCop stores its settings independently in files named Settings.StyleCop. Similarly, you can have this file along with solution file and project files.
    If you are using StyleCop, do not forget to run StyleCop configuration tool and disable the checks you do not want to perform. By default, all checks are enabled. Save new settings to this file and commit to the source control.

    Text Files

    If you are building a public product and are going to publish the source code, do not forget to create and commit these files as well:

    README.md
    LICENSE
    

    I recommend using markdown format for the README.md file, because it became an industrial standard and supported by public source control services like GitHub, as well as in-house servers like BitBucket (former Stash).

    NuGet Specifications

    If you are building a library which is to be distributed on NuGet Gallery, then you very likely need to create package specification files, like MyProject.nuspec. I prefer creating these files manually and commit them to the source control. Packages are usually released by one of your Continuous Integration (CI for short) job, but also at any time your can build and publish a package manually from the console as follow:

    nuget.exe pack MyLibrary.nuspec
    

    Just don’t forget to increment package version before executing this command.

    CI specific files

    We all use different CI servers, and they all have different configuration scripts and settings. I would just mention some of the common additions you may consider adding:

    • NUnit settings, which specify what assemblies contain tests to be executed on CI server for particular jobs. All tests are practically split into a few categories. There are unit tests that should be run on every build, performance tests that are executed nightly, and integration tests are executed on the per-release basis.
    • NCover settings, which specify what test assemblies should be analyzed for test coverage.
    • SonarQube settings, which determine software metrics will be collected.
    • Job scripts, such as NAnt, PowerShell or simply Windows batch files.

    How to Bootstrap and Create .NET Projects

    Appropriately bootstrapped project decreases future technical debt and makes product source code readable and professional-looking.

    Configuring Projects

    Project files, namely .csproj or .vbpro, contain all settings used by Visual Studio and MSBuild. However, not all of them are available from Project Properties window. To edit these files in Visual Studio manually, you should do the following:

    • Right-click on a project in Solution Explorer view.
    • Select Unload Project .
    • Right-click again to choose action Edit xyz.csproj.
    • Complete editing.
    • Right-click on the project again, and choose Reload Project.

    Alternatively, you can open a project file in your favorite text editor, edit it and save. When you are switching back to Visual Studio window, you will be prompted to reload the changed project.

    Warnings Control

    Building a high-quality software requires you to never ignore build warnings. Therefore, you should enable the maximum warnings level and treat any warnings as errors. Note that you should do this for all build configurations you have, such as Debug and Release. The best way to do this is to write the following settings to the common property group:

    <WarningLevel>4</WarningLevel>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    

    And make sure you don’t have the same settings in other property groups. Otherwise, they will override the corresponding properties from the common group.

    FxCop

    Running FxCop is merely practical to do on every build. Most teams prefer running FxCop from time to time (usually before a release) to make sure there were no severe errors introduced. However, if you want to perform ultimate checking on every build, add this option:

    <RunCodeAnalysis>true</RunCodeAnalysis>
    

    Note that FxCop, like StyleCop, has its own settings which can be placed in the root folder and added to the source control. These settings are likely used when running FxCop on CI servers.

    Documentation

    This part is about XmlDoc. If you are building a public API, then you should create and maintain API documentation. Most developers start with API development (actual coding), and just before a release they enable project setting Build / XML documentation file. Naturally, after another rebuild a bunch of errors appear, because every missing XmlDoc is resulting in a build error. To avoid this, you should enable mentioned option in the very beginning.
    If you are too lazy to write a proper documentation, or you do not like typing too much text, try instruments that automate this process such as GhostDoc.

    Code Contracts

    Code Contracts is an excellent framework from Microsoft Research, which allows you to express preconditions, postconditions and object invariants in your code for runtime
checking, static analysis, and documentation. I used this in many critical projects, and it helped a lot so I encourage you to give it a try.
    If you decide to use Code Contracts, then it is important to enable Contracts at the very beginning, when you have just created a new project. Adding Contracts in the middle of development is possible, but will require changes through many classes, to make Contacts match to each other. So, do not forget to enable all required settings (at least CodeContractsEnableRuntimeChecking) and make sure these settings appear in the common property group.

    StyleCop Enforcement

    Previously we talked about StyleCop configuration for development time. However, when your project is built on a CI server, ReSharper has no effect there and therefore we should enable StyleCop validation to run with MSBuild.
    This is usually done by manual modification of the project file. You need to unload the project in Visual Studio, edit the project file and then load the project back:

    <PropertyGroup>
       <!— add this to the common property group (common to Debug/Release/etc) —>
       <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
    </PropertyGroup>
    <!— add this Import in the very bottom —>
    <Import Project="$(ProgramFiles)\MSBuild\Microsoft\StyleCop\v4.3\Microsoft.StyleCop.targets">
    

    The setting StyleCopTreatErrorsAsWarnings will do what it says: it will break your build on any StyleCop rule violation. The import element is required for MSBuild to add StyleCop task to the build chain.
    You may have noticed the path to Program Files. Because developers may have different StyleCop versions installed, some teams prefer keeping a private copy of the same StyleCop installation under source control. In this case, the path will be relative. This also makes CI machines setup easier, as you don’t need to install StyleCop locally.

    AssemblyInfo

    Every .NET project created by Visual Studio wizard will have AssemblyInfo.cs file populated automatically (see Properties subfolder) which contains some of the Assembly attributes, but no wizard can fill all the Assembly attributes for you. Make sure you have at least these attributes populated:

    • AssemblyTitle
    • AssemblyDescription
    • AssemblyCompany
    • AssemblyProduct
    • AssemblyCopyright
    • AssemblyVersion


    This bare minimum is required for any assemblies you are going to distribute. A practical reason behind this is NuGet: If you are using automatic NuGet specification creation from the selected assembly file, this tool will derive needed information from these properties.
    You can also populate one more property in the very beginning:

    InternalsVisibleTo
    

    This property makes internal classes and interfaces visible to the specified assembly. This is generally used for automated tests you are going to create for your project.

    Connection Strings

    How to manage connection strings is a very popular question on the Stack Overflow. The problem is how to make connection strings unique for every developer or a CI job, and not to expose connection details while publishing the source code.
    In App.config (for desktop applications) or Web.config (for web applications), make the following setting which will be loading user.config file in runtime. Keep this under your source control:

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    	<connectionStrings configSource="user.config"></connectionStrings>
</configuration>
    

    Apparently, user.config file should be excluded from source control, and every developer should have a local copy of this file, preserving connection string privacy:

    <connectionStrings>
    	<add name="test" connectionString="Server=.;Database=...;"/>
</connectionStrings>
    

    .gitignore

    For those who use Git as the source control, it is important to add some file patterns to the .gitignore file. However, our smart community has already built a generalized file, which can be found here: github.com/github/gitignore/blob/master/VisualStudio.gitignore.
    You should take it as a reference .gitignore file and simply add your custom exclusions you may additionally need.

    GitHub Badges

    You may have seen nice looking badges appearing on the README project’s page. If you are publishing your project on the GitHub, consider connecting your project to public services for:

    • Building: to show a build is failing or passing.
    • Testing: to show test coverage and test execution status.
    • Publishing: to show the latest NuGet package version.

    A complete list of badges and related services can be found on shields.io. You may find many interesting badges that are good for Open Source projects.
    Once you have registered your project with a selected service, you will be given a link to the image and a complete markdown-syntax link, which you can add to your README.md file. By the way, this is one of the reasons why you should prefer markdown for Readme files.
    Sample markdown badges, from the Roslyn project:

    [![Build Status]([https://dotnet-ci.cloudapp.net/job/roslyn_master_win_dbg_unit32/badge/icon)](https://dotnet-ci.cloudapp.net/job/roslyn_master_win_dbg_unit32/)](https://dotnet-ci.cloudapp.net/job/roslyn_master_win_dbg_unit32/badge/icon)](https://dotnet-ci.cloudapp.net/job/roslyn_master_win_dbg_unit32/))

[![Join the chat at [https://gitter.im/dotnet/roslyn](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/dotnet/roslyn?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)](https://gitter.im/dotnet/roslyn](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/dotnet/roslyn?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge))

     

    Automatic Solution Structure Validation

    Even though you have set all the settings we discussed in this article, sooner or later one of your developers may change them and commit the changes to the source control. Sometimes this happens by mistake, and often these changes are not caught during the code review. Other than these accidents, we should be watching for the following common errors:

    • Bad references: when someone is referencing a local assembly which others maybe do not have, or when someone has deleted a file from the disk, while link to that file remains in .csproj file. This will break the build for sure, but it may happen too late once the change is pushed, and others pulled it. This is especially crucial for static web files, which you cannot verify during the build.
    • Naming consistency: the tools like StyleCop can control C# source code, but no tools can enforce rules for Project files or Assembly properties. A good example is this: We want to name projects to match output assembly name, and we want project names to have a common prefix like MyCompany.MyProduct.

    I found that watching for these errors in Code Reviews is error prone and should be automated. So I wrote a simple tool that performs these and many other checks to verify the solution consistency. Meet SolutionInspector. This is Open Source and distributed under MIT license. You can build it from source code or install from NuGet:

    Install-Package SolutionInspector
    

    The tool walks through the entire solution structure and applies many validation rules. The rules are configured by XML files, placed along with others solution files. To control settings on the per-project basis, you simply add the same file with different settings to the corresponding project folder.
    No configuration file is required by default. In this case, the tool will apply all available rules and yield all issues to the console.
    Here is the configuration file example:

    <?xml version="1.0" encoding="utf-8"?>

    <Settings xmlns:xsi="[https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema">](https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema">)
    <SolutionSettings>
        <MinSolutionFormatVersion>12.00</MinSolutionFormatVersion>
        <MaxSolutionFormatVersion>12.00</MaxSolutionFormatVersion>
        <DetectMissingFiles>true</DetectMissingFiles>
        <ProjectNamePrefix>MyCompany.MyProduct.</ProjectNamePrefix>
        <ProjectNameIsFileName>true</ProjectNameIsFileName>
        <IgnoredProjects>
            AVerySpecialProject1;
            AVerySpecialProject2;
        </IgnoredProjects>
    </SolutionSettings>
    <ProjectSettings>
        <DetectMissingFiles>true</DetectMissingFiles>
        <AllowBuildEvents>true</AllowBuildEvents>
        <AssemblyNameIsProjectName>true</AssemblyNameIsProjectName>
        <RootNamespaceIsAssemblyName>true</RootNamespaceIsAssemblyName>
        <RequiredImports>StyleCop.MSBuild.Targets</RequiredImports>
        <Properties>
            <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
            <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
        </Properties>
    </ProjectSettings>
    </Settings>
    

    Although the settings are rather descriptive, I’m going to explain some of them:

    • MinSolutionFormatVersion / MaxSolutionFormatVersion will prevent your developers from switching Visual Studio version.
    • DetectMissingFiles is very useful for static web content or other non-code files added to the solution or a project.
    • AllowBuildEvents can prevent from adding custom build events, which may do unnecessary things.
    • Properties is the most flexible element: you can check any properties against desired values, whether those are known properties or custom.

    Conclusion

    We have reviewed several standard practices, configuration files and project settings you can apply when starting a new project. Doing this in the very beginning would decrease future technical debt and will make your product source code looking nice and professional. For Open Source projects this is of particular importance, because any contributor would know your expectations by examining solution configurations and project files.
    This post originally appeared in Toptal

  • An Introduction to Robot Operating System: The Ultimate Robot Application Framework

    The Robot Operating System (ROS) is not an actual operating system, but a framework and set of tools that provide functionality of an operating system on a heterogeneous computer cluster. Its usefulness is not limited to robots, but the majority of tools provided are focused on working with peripheral hardware.
    ROS is split up in more than 2000 packages, each package providing specialized functionality. The number of tools connected to the framework are probably its biggest power.

    Why Should I Use Robot OS?

    ROS provides functionality for hardware abstraction, device drivers, communication between processes over multiple machines, tools for testing and visualization, and much more.
    An Introduction to Robot Operating System: The Ultimate Robot Applications Framework
    The key feature of ROS is the way the software is run and the way it communicates, allowing you to design complex software without knowing how certain hardware works. ROS provides a way to connect a network of processes (nodes) with a central hub. Nodes can be run on multiple devices, and they connect to that hub in various ways.
    The main ways of creating the network are providing requestable services, or defining publisher/subscriber connections with other nodes. Both methods communicate via specified message types. Some types are provided by the core packages, but message types can be defined by individual packages.
    Developers can assemble a complex system by connecting existing solutions for small problems. The way the system is implemented, it allows us to:

    • Replace components with similar interfaces on the fly, removing the need of stopping the system for various changes
    • Multiplexing outputs of multiple components into one input for another component, allowing parallel solving of various problems
    • Connect components made in various programming languages by just implementing the proper connectors to the messaging system, making it easy to develop software by connecting existing modules from various developers
    • Create nodes over a network of devices, without worrying about where code is run and implementing Interprocess communication (IPC) and Remote Procedure Call (RPC) systems
    • Directly connect to feeds on demand from remote hardware without writing any extra code, by employing the previous two bullet points

    We plan on demonstrating how useful that is by iteratively developing a simple solution. There are several key advantages compared to other approaches. ROS has multi platform support and allows connections between processes over multiple devices via peer-to-peer connections that are handled behind the scene. The design allows support for any language by wrapping the C++ communication classes, or manually developing classes for the language interface.
    ROS is made by its own community, meant for its community. After several years, that resulted in a great amount of reusable packages that are simple to integrate, thanks to the architecture of the system.
    Alternative approaches like https://www.mrpt.org/, https://carmen.sourceforge.net/intro.html, https://lcm-proj.github.io/, https://playerstage.sourceforge.net/, https://msdn.microsoft.com/en-us/library/bb648760.aspxand others provide some of those features, but not all. Most of the time, the design downfalls are language support limitations, unoptimized communication between processes, or the lack of support for various devices which is arguably the hardest problem to fix.

    What Are We Going to Build?

    Since our focus is the framework and not the actual algorithms for particular problems, the given problem will be fairly simple. Our goal is to build software for an onboard computer that allows us to remotely control and monitor a robot, connected to us via Wi-Fi, by using a gamepad on our computer and a feed from the camera mounted on the robot.
    First of all, we’ll make a simple program connect to a simple simulation, just to demonstrate basic principles of ROS. We will attach a gamepad to a computer and try to design a good control scheme for turning gamepad input into control signals for a robot.
    The main languages for writing ROS code are C++ and Python, C++ being preferred due to better performance. We will explain our examples in Python due to less boilerplate in code and no need for explicit building.

    Installation and Configuration

    ROS versions are referred to by name. As of this date, the latest release is Jade Turtle, and the latest LTS version Indigo Igloo. Going for the LTS version is preferable, and backwards compatibility isn’t guaranteed in ROS, so all the examples will be written for Indigo.
    ROS is available on various *NIX platforms. The officially supported version is on Ubuntu. The OS X, Arch Linux, Debian, Raspbian and Android versions are supported by the community.
    We will go through the installation process for Ubuntu 14.04 on desktop. The processes for all supported versions and platforms are available on the official website. Virtual machines with ROS installed are also available.
    Installation is platform dependent (and most platforms have packages provided), but workspace configuration is the same for all platforms.

    Installation on Ubuntu

    ROS provides its own repositories. The first step is adding them.

    sudo sh -c 'echo "deb https://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list'
    sudo apt-key adv --keyserver hkp://pool.sks-keyservers.net --recv-key 0xB01FA116
    sudo apt-get update
    

    After that you’ll have all hosted packages for all ROS versions available for your Ubuntu version. For example, Ubuntu 14.04 supports indigo and jade.
    Installing the base packages on desktop has one of three options:

    • sudo apt-get install ros-indigo-ros-base for a minimal installation
    • sudo apt-get install ros-indigo-desktop for having the basic additional GUI tools
    • sudo apt-get install ros-indigo-desktop-full for having all official features, including various simulators and libraries for navigation and perception

    For the best working experience, the full option is recommended. For installation on devices that will only be used to run nodes, the base version is sufficient. No matter what option you choose, you can install any needed package named package_name by running:

    sudo apt-get install ros-indigo-<package-name>
    

    Underscores are replaced by hyphens in the final name, so stage_ros will be in the package ros-indigo-stage-ros.
    The next step is to initialize rosdep. Packages in ROS can declare what components they depend on. rosdep allows you to compile those packages without too much manual dependency handling. To initialize it, call:

    sudo rosdep init
    rosdep update
    

    ROS has several environment variables used by its tools. With the default installation, the bash script to initialize them is located in /opt/ros/indigo/setup.bash. Variables need to be initialized within every bash session, so the best solution is to add them to ~/.bashrc.

    echo "source /opt/ros/indigo/setup.bash" >> ~/.bashrc
    source ~/.bashrc
    

    Some packages install external dependencies via rosinstall, which is available as a package and installed via sudo apt-get install python-rosinstall.
    This is the end of the installation on Ubuntu. What follows is a short introduction to installing workspaces.

    Configuration

    Ever since Groovy Galapagos, ROS workspaces are managed via catkin. We need to define a directory for all packages that we host. Within the directory we create a src folder, and call catkin_init_workspace form inside it. That will create various symbolic links to the currently sourced ROS version. The next step is to add this workspace to environment variables as well.
    To perform this whole workspace configuration, choose an empty directory and execute the following commands:

    mkdir src
    cd src
    catkin_init_workspace
    cd ..
    catkin_make
    echo "source $(pwd)/devel/setup.bash" >> ~/.bashrc
    source ~/.bashrc
    

    You have now created a workspace within which you can create your own ROS packages.

    Getting Familiar with the Tools

    Creating any code is a big jump. Let’s first get familiar with some of the systems running behind the scene. Our first step will be running the basic GUI and seeing what messages it generates.
    To run anything in ROS, a core process needs to be launched. It’s as easy as opening a new terminal window and typing:

    roscore
    

    In your whole connected network of devices, roscore needs to be launched only once, on the device that will host the central hub for communication dispatching.
    The main role of roscore is to tell nodes which other nodes they should connect to, and in which way (whether via a network port or shared memory). The goal is to allow nodes to only care about what data they want to know, rather than what node they want to connect to, while minimizing the time and bandwidth needed to perform all communication.

    rqt

    After running roscore, we can launch the main GUI tool for ROS: rqt. What we see is very underwhelming – an empty window. rqt hosts a wide variety of plugins that can be configured into any visual configuration and any number of predefined views.

    For a start, let’s run the Robot Steering plugin, by choosing it in Plugins > Robot Tools > Robot Steering. What we get is two sliders, representing the linear and rotational motion we want our robot to have. At the top of the plugin we see a text box with /cmd_vel in it. We can rename it to anything we want. It represents the name of the topic to which the steering is publishing. The terminal tools are the best place to see what’s going on in the background.

    Terminal Tools

    ROS has several powerful tools for inspecting what is happening in the system. The first tool we’ll introduce is rostopic. It allows us to inspect topics that nodes can subscribe and publish to. Running rostopic list will yield:

    /cmd_vel
    /rosout
    /rosout_agg
    

    The latter 2 topics are always running and are related to central ROS systems. The /cmd_vel topic is being published by our steering. Renaming the topic in the steering will rename it here as well. Now, we are interested in what’s going on within the topic. Running rostopic echo /cmd_vel will show us nothing (unless you tinkered with the sliders). The process runs until we cancel it. Let us now move the vertical slider to 20 m/s. Looking at the echo, we can see the following repeated over and over again:

    linear:
      x: 0.2
      y: 0.0
      z: 0.0
    angular:
      x: 0.0
      y: 0.0
      z: 0.0
    

    How often does it spam this message? rostopic hz /cmd_vel says at an average rate of 10 Hz. Well, how many topics like this can I run through my slow Wi-Fi connection? rostopic bw /cmd_vel detects an average of 480 B/s.
    Now that’s all well and good, but we talked about message types. This data is good for a human, but an application will need the raw data, and will need to know the message type so it can interpret the data. The type can be determined with rostopic type /cmd_vel, telling us it’s a geometry_msgs/Twist. All of ROS terminal tools called without any arguments return a standard help message.
    The ROS Wiki is good enough to make a web search for this string result in a Wiki explanation to what it contains and how it’s structured. But we don’t have to rely on it. rosmsg is the general tool for message types. Running rosmsg show geometry_msgs/Twist will return:

    geometry_msgs/Vector3 linear
      float64 x
      float64 y
      float64 z
    geometry_msgs/Vector3 angular
      float64 x
      float64 y
      float64 z
    

    The message consists of two 3D vectors, representing linear and angular velocity in 3D space.
    If we want what topics a node is connected to, rosnode info <node-name> will give us detailed data about the node. The tools rostopic, rosmsg and rosnode are the main tools for inspecting raw ROS functionality. ROS has a lot more GUI and terminal tools, but those are out of our scope for this introduction.
    The main tools for running ROS nodes are rusrun and roslaunch. rosrun can run nodes via rosrun <package_name> <node_name>, and roslaunch runs nodes based on launch files, which we’ll get familiar with to a tiny extent since they are the most complex element of the ROS automation.
    We can shut down everything we ran to start working on our first code. For future reference, it will go without saying that running anything ROS related requires an active instance of roscore. A lot of issues you run into can be resolved by closing the terminal window that roscore is run within, and opening a new one to relaunch it. This updates all dependencies that needed to be reloaded, both in bash and in roscore.

    Creating Gamepad Teleoperation

    Our first goal is to imitate the functionality of Robot Steering by creating a node that publishes geometry_msgs/Twist data to /cmd_vel based on gamepad input. Our first stop is the joy package.

    The joy Package

    The joy package provides generic ROS drivers for joysticks and gamepads. It is not included in the default installation, so it needs to be installed via:

    sudo apt-get install ros-indigo-joy
    

    After the installation, we can run rosrun joy joy_node. This will connect us to the default joystick or gamepad. Running rostopic list shows us that we have a topic called /joy. Listening to it via rostopic echo shows us messages of the following format (note that you have to interact with the gamepad or joystick for messages to be published).

    header:
      seq: 4156
      stamp:
        secs: 1450707466
        nsecs: 204517084
      frame_id: ''
    axes: [0.0, 0.0, 0.0, -0.0, 0.0, 0.0, 0.0, 0.0]
    buttons: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    

    You can ignore headers for now. Other than that, we have axes and buttons, explaining nicely what they represent. Moving axes and pushing buttons on the controller will result in these numbers changing. Using our tools, we can determine that the message type is sensor_msgs/Joy and the format is:

    std_msgs/Header header
      uint32 seq
      time stamp
      string frame_id
    float32[] axes
    int32[] buttons
    

    Creating Our Teleoperation

    The first step to writing code is making a package. Within the src folder of the workspace, run:

    catkin_create_pkg toptal_tutorial rospy joy geometry_msgs sensor_msgs
    

    Here we state the name of the package we’re creating, followed by packages we plan to depend upon. No worries, dependencies can be updated manually later on.
    We now have a toptal_tutorial folder. Within the folder, create a scripts folder that will house all our Python scripts.
    Let’s create a file called teleop.py, and within it we’ll set:

    #!/usr/bin/env python
    import rospy
    from sensor_msgs.msg import Joy
    def joy_callback(data):
        print data
    def main():
        rospy.init_node('teleop')
        rospy.Subscriber('joy', Joy, joy_callback)
        while not rospy.is_shutdown():
            pass
    if __name__ == '__main__':
        main()
    

    We’ll also need to set chmod +x teleop.py so the script becomes runnable. Running rosrun joy joy_node in one terminal and rosrun toptal_tutorial teleop.py in another will result in teleop.py’s terminal output being filled with Joy messages.
    Let’s examine what the code does.
    First, we import rospy, which hosts the library for interacting with the ROS framework. Each package that defines messages has a msg subpackage with message definitions in it. We are importing Joy to handle the input. There is no need to import embedded message types (like Header from std_msgs.msg that is in the Joy message) unless we want to explicitly mention them.
    Our first step is initializing a node with a specific name (in this case, we call it “teleop”). After that we create a subscriber that subscribes to the “joy” topic of type sensor_msgs.msg.Joy, and that handles each message by calling the joy_callback function. Callbacks receive one parameter, the data from the message. Accessing members of the data is simple. If we wanted to print the state of the first axis, if we recall the message type, we would call print data.axes[0], and it will be a float. The loop at the end loops until ROS is shut down.
    Our next step would be to handle our data somehow. We should create a Twist message that changes depending on the input, and then we would publish it to the cmd_vel topic.

    #!/usr/bin/env python
    import rospy
    from sensor_msgs.msg import Joy
    from geometry_msgs.msg import Twist  # new
    from functools import partial  # new
    def joy_callback(pub, data):  # modified
        cmd_vel = Twist()  # new
        cmd_vel.linear.x = data.axes[1]  # new
        cmd_vel.angular.z = data.axes[0]  # new
        pub.publish(cmd_vel)  # new
    def main():
        rospy.init_node('teleop')
        pub = rospy.Publisher('cmd_vel', Twist, queue_size=1000)  # new
        rospy.Subscriber('joy', Joy, partial(joy_callback, pub))  # modified
        while not rospy.is_shutdown():
            pass
    if __name__ == '__main__':
        main()
    

    First, we add the Twist message, and we add support for binding function arguments via functools.partial. We create a publisher, pub, that publishes to cmd_vel a message of type Twist. We bind that publisher to the callback, and make it publish a Twist message on every input with the speeds being represented by the first two axes. This code does what we expect it to, and we can see the resulting output via rostopic echo /cmd_vel.
    We still have one issue. The /joy topic can publish at great rates. If we monitor the rostopic hz /cmd_veland move the analog stick in circles, we can see great numbers of messages. Not only does that result in a great amount of communication, but the processes that receive these messages have to process each one of them. There is no need to publish that data so frequently, and we are better off just publishing at a stable rate of 10 Hz. We can accomplish that with the following code.

    #!/usr/bin/env python
    import rospy
    from sensor_msgs.msg import Joy
    from geometry_msgs.msg import Twist
    from functools import partial
    def joy_callback(cmd_vel, data):  # modified
        cmd_vel.linear.x = data.axes[1]
        cmd_vel.angular.z = data.axes[0]
        # moved pub.publish(cmd_vel) to main loop
    def main():
        rospy.init_node('teleop')
        cmd_vel = Twist()  # new
        pub = rospy.Publisher('cmd_vel', Twist, queue_size=1000)
        rospy.Subscriber('joy', Joy, partial(joy_callback, cmd_vel))  # modified
        rate = rospy.Rate(10)  # new
        while not rospy.is_shutdown():
            pub.publish(cmd_vel)  # new
            rate.sleep()  # new
    if __name__ == '__main__':
        main()
    

    We modified the callback to receive the mutable Twist object and modify it within the loop. The sleepfunction from rospy.Rate maintains a stable output frequency.
    The final code will result in the /cmd_vel topic getting velocity commands at 10 Hz, imitating the output of the Robot Steering rqt plugin.

    Running a Simulated System

    Simulating the World

    Our first goal is to create an environment in which we can simulate a scenario we want to achieve. The node stageros within the stage_ros package allows us to run one robot within a 2D stage defined via an image. There is a whole syntax, described within the stage_ros package for world files and how to generate them. It’s fairly simple, but outside of our scope. Luckily, the package comes with several demo world. First, let’s go to the files’ directory by running:

    roscd stage_ros
    cd world
    

    Within the folder there are several files. Let’s run one.

    rosrun stage_ros stageros willow-erratic.world
    

    This created several topics. The meaning of each of them is also documented with the package. The important part is that it has cmd_vel.

    Within the displayed stage, there is a blue square, representing the robot you control. By using either our code or Robot Steering, we can control this robot. Try it out.

    Setting up our system via launch files

    let’s create a launch folder within our package, and within it create a file called teleop.launch. The final folder structure should look like this:

    toptal_tutorial/
    ├── CMakeLists.txt
    ├── launch
    │   └── teleop.launch
    ├── package.xml
    ├── scripts
    │   └── teleop.py
    └── src
    

    Within the teleop.launch file we will define a set of nodes and their interconnections.

    <launch>
      <arg name="world_file" default="$(find stage_ros)/world/willow-four-erratics-multisensor.world" />
      <node pkg="stage_ros" type="stageros" name="simulated_world" args="$(arg world_file)"></node>
      <group ns="robot_0">
        <node pkg="joy" type="joy_node" name="joy_input"></node>
        <node pkg="toptal_tutorial" type="teleop.py" name="joy_convert"></node>
      </group>
    </launch>
    

    The new world consists of four robots, and each of their topics has a prefix of robot_<n>. So, the robot number 0 has a velocity command topic called robot_0/cmd_vel. That is why we put our control within a namespace called robot_0, to adjust their names to the new form. In that sense, you can think of topic names as folders in a filesystem.

    To run launchfiles, no roscore is needed. In a sense, roscore is just a special case of a launchfile that does nothing. If a roscore is missing, only the first launchfile launched will run a core, while the rest will connect to it. Now, we run the launch with:

    roslaunch toptal_tutorial teleop.launch
    

    If all is correct, this will result in a simulator with 4 robots, one of which is controlled with our gamepad or joystick. This world has a lot more under the hood than the previous one. Each of the four robots has:

    /robot_<n>/base_pose_ground_truth
    /robot_<n>/base_scan_0
    /robot_<n>/base_scan_1
    /robot_<n>/camera_info_0
    /robot_<n>/camera_info_1
    /robot_<n>/cmd_vel
    /robot_<n>/depth_0
    /robot_<n>/depth_1
    /robot_<n>/image_0
    /robot_<n>/image_1
    /robot_<n>/odom
    

    We replace <n> with 0, 1, 2, or 3. This brings us to our last topic.

    Viewing Our Data with rqt

    We didn’t go too deep into rqt, but it is the perfect tool for viewing more complex data. You can experiment with all the topics, but we’ll focus on the image_0, image_1, depth_0, and depth_1 topics.
    Let’s launch rqt and remove any opened plugins. Now we’ll open 4 image visualizers (Plugins > Visualization > Image View), and place them in a 2×2 grid formation. Finally, in the top left corner of each of the views, let’s choose one of the four stated topics for robot_0.

    What we get is stereo vision with depth perception, with low resolution cameras. Bear in mind that we could have even gotten this result without our input system. If we just run this (from within the stage_ros/worldfolder):

    rosrun stage_ros stageros willow-four-erratics-multisensor.world
    

    and add the Robot Steering plugin with a topic called /robot_0/cmd_vel, we would have gotten the same results with the controls being on-screen sliders.

    Applying the Results to a Real System

    A lot of hardware has full support for ROS, very often provided by third party volunteers. Many robot platforms have drivers that generate these types of messages, and ROS has nodes that take a webcam and publish an image feed.
    While the last result was a simulation of what we want to achieve, the same can be achieved with the following modifications:

    • Install ROS on the onboard computer of your robot
    • Create a launchfile for the onboard computer that connects ROS to the underlying platform and all high level sensors like cameras, laser range finders and others. The needed nodes can already exist, or can be implemented by creating a publisher/subscriber to ROS on one side, and a driver for serial communications on the other
    • Have the launchfile run at startup
    • On your remote computer add export ROS_MASTER_URI=https://<robot_hostname>:11311/ to your bash startup, making the remote computer look for roscore on that given hostname and port
    • Launch rqt and/or any scripts for monitoring and controlling the robot

    What this really comes down to is just exporting the proper environment variable on the remote device, and the rest handles itself. Running ROS on a computer cluster only needs that one step being done for every machine.

    Conclusion

    We have demonstrated how, with very little coding, you can have a complex system of variables that you can manipulate at your whim. The simple publisher/subscriber system allows you to quickly develop software pipeline that processes data in a cluster of computers, while not worrying about the underlying implementation of certain elements.
    While we used a simple simulator, more complex simulators like gazebo (also included in the full desktop version) allow you to create 3D worlds with physics and complex sensors, and can give you an experience of the final results and product long before it’s developed.
    This introduction was a very basic one, but the hope is that you became more interested in working with this versatile framework.
    This post originally appeared in Toptal Engineering Blog

  • Guide: Software Release Management For Small Teams

    ormalizing The Release Management Process (If There’s Any)

    In some team configurations, especially ones that are found in startups, there are no DevOps, nor infrastructure engineers, to provide support when releasing a new version of the product.
    Moreover, unlike large bureaucratic companies with defined formal processes, the CTO or Head of Software Development team in a startup is often not aware of the complexities of the software release management process; a few developers in the company may be aware of the complex details of the process, but not everyone. If this knowledge is not documented thoroughly, I believe it could result in confusion.
    In this article, I’ll try to provide some tips about how to formalize the release process, particularly from the developer’s point of view.

    Enter The Software Release Checklist

    You may be familiar with the idea of a checklist for some operations, as per the Checklist Manifesto, a book by Atul Gawande. I believe a formal release process (like many other tasks in the software development world) provides developers with an opportunity to implement this protocol. A release process checklist should be kept in a shared document, preferably in the form of a collaborative wiki, or a spreadsheet on Google Drive.
    By sharing this vital document with the team, and by granting editing permissions, every member has access to the formally defined release process. This allows them to understand how the process works. Moreover, following discussions with other team members, it empowers the team to improve upon it every now and then. This should bring transparency and allow the entire team to have real-time access to what’s going on during the release, what steps have been completed, and by whom.
    By looking at this spreadsheet, the stakeholders can decide on a ‘GO’ vs ‘NO GO,’ based on the outcome of the steps. For example, if a stress test goes wrong in a test environment, based on the event the project manager might decide to call off the production release.
    A simple, well thought out spreadsheet checklist can make a big difference in your software release management process.

    A simple, well-thought-out spreadsheet checklist can make a big difference in your software release management process.

    Suggested Steps To Use As A Foundation

    In this section, I’ll propose some steps you can use to build your own checklist for your release process. Some of these steps are by no means mandatory. Each app is different and each organization works in a different way, so feel free to adapt and make changes that will fit better into your workflow.

    1. Create A Release Branch

    It’s likely that you are familiar with the concept of Git Workflow, or with the idea of release branches, a topic that has been explained in a previous blog post.
    Ideally, you should have at least three branches:

    • master: this should reflect the current state of what is in the production environment. Every new commit on master should comprise a new release only.
    • develop: this branch should contain the completed (and tested) upcoming features. It is common to create a separate branch for each feature and then merge it to develop when the feature is ready.
    • release: release branches are a collection of commits that are ready to be sent to production, plus some additional minor bug fixes related to the release.

    Notice the release branches should be removed once the release is completed, therefore these branches are created and destroyed all the time, unlike master or develop, which are always the same.
    In order to create a new release branch, from the develop branch in your git terminal, type:
    $ git checkout -b release/x.y.z
    It is convenient to use a naming convention, such as the one defined above, replacing x.y.z by the major.minor.patch version number according to your needs (it is a policy that you should define within your team and stick to it).
    It is important to say, as well, that if you code some bug fixes into the release branch, you should not forget to merge them back to develop. The main purpose of the release branch is to have a preview snapshot of how the app should behave after it goes into production.
    Organizing and keeping track of different release branches is a crucial aspect of release management.

    Organizing and keeping track of different release branches is a crucial aspect of release management.

    2. Bump Version

    The next step would be to bump (modify or increase) the version number on the release branch.
    You should open the AndroidManifest.xml / package.json / pom.xml / or wherever the app’s version is stored in your project (YMMV), update the version number, and then commit the changes to the current releasebranch.
    It is important to update the version number for two reasons.
    First, you can track and map the features that were introduced in each version, and second, you will be aware of the version they are using should they need to do some troubleshooting or to contact you for support. If you are building a mobile app, the version number you are updating in this step is usually displayed on the user end, in the About section or in Google Play or Apple App Store.This step is also a good opportunity to update environment-dependent-configuration files (although I’d suggest keeping those in a separate repository), such as making the branch point to the production database, or any other tweaks needed on the build process.
    Finally, it is recommended that you push the release branch to origin, so it is available for your other developers:
    $ git push -u origin release/x.y.z

    3a. Merge release branch to master and tag it

    Only the master branch should be deployed for production, thus in this step, we need to merge the releasebranch into master.

    $ git checkout master
    $ git merge --no-ff release/x.y.z
    $ git push
    

    The --no-ff flag is optional, however, its use is recommended in order to force the creation of a new commit object, even though the merge can be completed using the fast-forward technique.
    Next, it is time to tag the release on master branch:
    $ git tag -a x.y.z -m 'description of new version, features or fixes included'
    Tags are useful because you are persisting this specific point in history in the git repository, and you can come back later to recreate a separate branch off a particular tag.

    3b. Use a pull request to merge the release branch

    Another alternative used often, is to use a pull request to merge the release branch into master.
    There are numerous advantages to this approach. A new space is created for collaboration, which the team can use to discuss various release-related issues. This point is a good time to add an extra gate for incorporating a code review process, while having more eyeballs to monitor the code that will be introduced, and to discuss potential modifications.
    Some tools that allow you to implement pull requests into your workflows are GitHub,  Bitbucket and GitLab(merge request as they call it on the latter). With these tools, you don’t type the git commands manually, instead, you use a web interface to set the source branch (release) and the destination branch (master), and then you add one or more reviewers, all of whom will be able to write inline comments on these new changes, suggest improvements, and so on.
    After all the reviewers approve the pull request, you can automatically merge the changes into master by pressing a button on the UI.

    4. Deploy Master To Production Environment

    It is good practice, at this stage, to have a tester on your team do a smoke test (this could be defined on a separate checklist) before deploying the app. A good suggestion is to deploy the master branch into a separate testing environment as done by professional automation testing companies. The tester can then perform some basic actions to make sure nothing went wrong after the merge on the latest build. How to conduct a smoke test is beyond the scope of this article, but you can find a lot of material on the web about it. The result of the smoke test can be integrated into the release checklist/spreadsheet, documenting anything that went wrong.
    At this point, you are ready to deploy the changes and make them live. Go ahead and deploy master branch. This step will depend on the infrastructure stack you are using. It might involve connecting to your Amazon EC2 instance to upload your app, or pushing to a Heroku remote, or connecting via ssh to your VPS to copy the new version, or any other process.
    Do a smoke test, deploy the master branch into a separate testing environment, make sure the deployment was successful.

    Do a smoke test, deploy the master branch into a separate testing environment, make sure the deployment was successful.

    After the app is uploaded, make sure it was deployed successfully and that it works as expected.

    5. Merge Back Into Develop And Delete Release Branch

    Now the release is almost completed, you’ll want to merge the release branch into develop, to update the version number on the latter and to transfer all the bug fixes made to the main development branch:

    $ git checkout develop
    $ git merge release/x.y.z
    

    Now it is time to remove the release branch:
    $ git branch -d release/x.y.z

    6. Changelog Generation

    There should be a file at the root of your project named CHANGELOG.md (or an equivalent) where you should add a new entry whenever there is a new release in order to document everything that’s included in it, like bug fixes, new features, known issues, and any other relevant information in the form of release notes. This is really useful for users and contributors to see what changes have been made between each release (or version) of the project.
    The changelog entry includes the date, version number and some notes about the release. The entries should be kept in reverse chronological order. Here’s a simple template I’ve been using that you can adapt to your project:

    <app's name or component released> <version x.y.z> | <date>
    <developer's name in charge of release> | <developer's email>
    Features:
    * <ticket/issue number>: <ticket/issue summary> (<link to issue tracker>)
    * ...
    Bugs fixed:
    * <ticket/issue number>: <ticket/issue summary> (<link to issue tracker>)
    * ...
    Enhancements:
    * <ticket/issue number>: <ticket/issue summary> (<link to issue tracker>)
    * ...
    Optional: known issues plus other release notes.
    

    In addition, this step can be completely automated by either coding a basic script that traverses the git log and automatically generates the changelog entry, or by using a tool that does the same, such as:

    Keep in mind though, that the degree of automation you get is directly proportional to the strictness of your commit message format. I believe it is always good practice to agree on a specific format for commit messages with the team. By following guidelines on the style of the commit messages, they will be easier to parse and hence more likely that you will be able to automate the generation of the changelog.

    7. Communicate With Stakeholders

    This is where you would usually do some of the following:

    • Let the team know via an internal messaging tool (e.g.: Slack) that a new release has been completed. I recommend creating a new channel (i.e.: #releases) for the sole purpose of communicating release related events. It is easy to add hooks in a Slack channel to post a message after an action has been taken.
    • Alternatively, send an email to the stakeholders with a link to the changelog, or the changelog file attached.
    • Write a blogpost (if you have a blog for your app or product) or a tweet.

    More actions can be taken depending on the nature of your organization. The important thing is not forgetting to communicate that a new version of your product is available.

    8. Grooming The Issue Tracker

    After a release is executed, you will probably need to update the status of some of your tickets to keep track of the bug fixes, or features, currently in production. Generally, this involves changing some tags (for small projects I use a release-pending tag, which I remove after the release is completed).
    If you use milestones for each new version you’ll probably need to update their status or mark them as completed. Some issue trackers even let you plan the release and align it with sprints, track whether a bug is blocking a release, and other useful information.
    It all depends on how you use the tool. I simply want to point out that the task of updating the information in the issue tracker should be included in your release checklist.

    About Automating The Release Process

    The reader might have noticed that, apart from the changelog step outlined above, many of the aforementioned steps can be automated, too.
    The ability to automate some parts of the release process is a huge win and saves a lot of time. I suggest creating scripts, or figuring out how to automate individual steps and then work towards a continuous deliverygoal. Continuous delivery can reduce risk, reduce costs, and reduce the time developers need to spend in managing the release. Consequently, you’ll be able to release more often and be more productive in terms of the hours allocated for development.
    The holy grail of DevOps is to be able to launch a new version by pressing a button (or running a command) that would trigger the release process automatically, or even better, a system that would release a new version of your software at a designated time. Of course, this is difficult to achieve because you also need to automate a lot of the testing process, but it is not impossible.
    A fully automated software release? It’s not as farfetched as some believe.

    A fully automated software release? It’s not as farfetched as some believe.

    Embracing Best Practices

    In this section I’ll describe a couple of recommended practices that I’ve found convenient, either to make the release process smoother or for taking safety measures in case something goes wrong.

    Find the most suitable day to carry out the release

    I usually release apps I am working on on Thursdays, between noon and close of business.
    If you work Monday to Friday, it is not a good idea to launch on a Friday. If something breaks down after the release, you won’t have time to fix it until Monday (unless you want to work during the weekend). That’s why it is more convenient to do releases on Thursday, because you have Friday to monitor the new version after being deployed, fix any problems, or do a rollback.
    Another important thing to mention if you are managing a web app, is to know the time zone the majority of your users are located. You should time the release during a low traffic period to minimize the potential damage if something fails. Sometimes, this can be tricky when your user-base is spread across the whole world, but anyway, you should do some research and decide on the best time.

    Backup Your Database Before A New Release

    If you don’t have periodical backups of your DB scheduled, I strongly suggest you add a step into your release process to perform a backup before starting the release.

    Staged Rollouts

    Ever wonder why, when a publisher announces they’ve launched a new feature, it takes days, or even weeks, for that feature to be available on your phone? That’s because many companies use staged rollouts.
    Facebook has been doing this for a long time. It tests a new feature on five or 10 percent of its users, gradually increasing it until they reach 100 percent of the user-base. During the staged rollout phase, you’ll need to look closely at user feedback and crash reports. With this information, you can then postpone the release, or fix errors, before they affect every user.
    There’s a nice tool on the Android’s Developer Console that implements staged rollouts for your Android apps.
    In a staged rollout, propagation is incremental. As time goes by, the number of users with the latest version goes up.

    In a staged rollout, propagation is incremental. As time goes by, the number of users with the latest version goes up.

    Continuous Integration

    Continuous Integration is a practice worth embracing for many reasons. Firstly, it allows you to detect mistakes early, increasing the rate of successful releases. Secondly, it is the first logical step before implementing Continuous Delivery and full automation as previously described.
    Martin Fowler is a big advocate of Continuous Integration. He describes a huge amount of benefits that can be added to your release process when using this practice. This is a large topic and there are many books and blog posts about it, and I am mentioning it here because I believe it will give you much more confidence in your operations. Amongst the many advantages of using CI, you will find: reduced risk, increased visibility to be aware what is working and what not, earlier detection of bugs, increased frequency of deployments, and many more.
    The starting point to implementing CI is to set up a “continuous integration server;” some nice tools to try are: CruiseControl, Bamboo, Jenkins and Travis.

    Exitlude: It Will All Work Out

    Aggressively, we all defend the role we play Regrettably, times come to send you on your way We’ve seen it all, bonfires of trust, flash floods of pain It doesn’t really matter, don’t you worry, it’ll all work out
    Exitlude, The Killers
    To wrap up, I would say that it’s very important to have a well-defined release process for your app, regardless of its complexity, userbase, or how small your organization is.
    If you don’t, I suggest you start thinking about some basic steps, using this guide and others like it, and brainstorming with your team to come up with a first draft. Try it out on your next release, then iterate. Eventually, you’ll end up building your own release process.
    After that, start thinking about how to automate parts of the process. Think about areas that can be improved. Explore ways of reducing the release time by incorporating small optimizations. Automation should be your ultimate goal; however, don’t plan that from the start, or you will fail by attempting such a big leap. As with with every process, it is better to improve it gradually.
    Do you have any other tricks or guidelines you use for launching new versions of your app? If so, let me know. I don’t come from the DevOps world, I am just a developer who happens to be quite organized and structured, but compared to many veterans, I am still a novice in this respect, so feel free to comment or contact me if you have something to add.
    This post originally appeared in the Toptal Engineering blog

  • Agile, Scrum, and Kanban: What the Heck Do These Words Really Mean?

    When a software developer hears news about a “new JavaScript framework” or a “new IDE,” he doesn’t need to ask more questions to clarify what it’s about. But if he hears about a “new agile framework,” he will likely do the Homer-Simpsonian nodding, pretending that he knows what it’s about, but he will have one, and only one, question: What the heck does “agile framework” mean?
    In the modern software development environment, we increasingly hear words like “agile,” “scrum,” and “kanban,” and they are often used improperly. In this article, I’ll try to explain and to clarify some of these terms.
    Agile methods are designed to help development teams kick butt.

    Agile

    If you want to be the smartass of the crowd, you should use the word “agile” in every other sentence when you are talking about the work process. It has a pretty wide range, does not obligate you to know much about the subject you are talking about, and it is a really nice adjective or adverb: “thinking agile,” “agile approach,” “according to agile principles.” But what does “agile” really mean?
    “Agile” refers to “agile software development,” the approach to development that follows agile principles. But what the heck are “agile principles?” Take a look at the Agile Manifesto and at the 12 principles of agile, which lay the foundations of agile development. From the Manifesto:

    Individuals and interactions over processes and tools
    Working software over comprehensive documentation
    Customer collaboration over contract negotiation
    Responding to change over following a plan

    Agile principles encourage continuous delivery of functioning software, close communication among teams, and high adaptability to changing needs. If you follow these values and principles in your work, you can say that you are working in an agile environment. So, agile software development is not a methodology, it is just a set of different methodologies, frameworks, and techniques that follow the same principles. It can be said that “agile” is a framework for thinking and making decisions.

    Agile is a framework for thinking and making decisions.

    But why is it so important to follow these principles in our work?
    The Manifesto and principles are the result of searching for the best solutions that have evolved over the decades in response to the challenges of software development. Throughout the 70s, 80s, and 90s, different developers and teams all over the world had been experimenting with methods of working and approaches to problem solving, inventing different frameworks and techniques (such as scrum and Extreme Programming), and even coming to the same ideas in parallel. Finally, in February 2001, seventeen developers got together and found the common denominators for all these diverse ideas and experiences. That is how the manifesto was created.

    The Agile Manifesto is the result of different experiences and practical solutions that emerged over the decades.

    Scrum

    If you talk about “agile” methods without knowing what they mean, you may slip up and say things that will uncover you in front of the interlocutor who knows the subject: “Scrum and other agile methodologies.”
    Scrum is not a methodology, though we’ve all heard it called such more often than the number of killings in Game of Thrones. Scrum won’t give an answer to every question, and it won’t provide you with the precise procedure for responding to every situation you face. And probably as a result of this incorrect interpretation, most scrum implementations are also wrong: Teams don’t get value. This results in probably the most foolish statement about scrum: “Scrum doesn’t work.”
    What is scrum? The Scrum Guide defines scrum as:

    “A framework within which people can address complex adaptive problems, while productively and creatively delivering products of the highest possible value.”

    So it’s a framework, and like any other framework it can be, and regularly is, used the wrong way. Using scrum effectively requires not merely adopting the structure set out by scrum, but having a deep understanding and appreciation for agile principles across the entire team.
    Scrum consists of three roles: Product Owner, Scrum Master, and Development Team; four ceremonies: Planning Meeting, Daily Scrum, Sprint Review, and Sprint Retrospective; and three artifacts: Product Backlog, Sprint Backlog, and Product Increment. It is organized into regular time frames, which we call sprints. Sprints should last between one and four weeks.
    The Product Owner, or PO, is responsible for guiding the project’s direction. As new tasks and features are determined, the PO adds them to the Product Backlog. A sprint starts with a Planning Meeting where the Development Team selects the tasks from the Product Backlog to work on and plans how they will be implemented. That is followed by development, during which the Dev Team uses the Sprint Backlog to track progress and meets for the Daily Scrum in order to synchronize activities and adjust the plan, if needed. The result of development should be a Product Increment, something that can be applied to the product and released immediately. At the end of the sprint, the Product Increment is presented to the Product Owner at the Sprint Review, where the product backlog is augmented if further changes are needed. Afterwards, the whole team attends the Sprint Retrospective (also known as the Pub Meeting) where they talk about the work process and how it can be improved.
    The basic Scrum framework.
    That’s it in a few sentences, but if you need a detailed explanation of how scrum works, check out this articlewritten by your truly.
    It is easy to learn and understand scrum, but it’s hard to adopt. There are many reasons this framework may or may not be a good fit for a project. It often requires a lot of changes, not only in everyday development, but also culturally. Scrum fits best with development of complex products, ones that last a long time and that include different kinds of specialists.
    Why is scrum so popular, and why does it have an advantage over the traditional waterfall model? Simply put, because it delivers more value to a product and customers. With “heavyweight” methods such as waterfall, horror stories abound in which nobody sees anything of the project for months. With scrum, that is not possible.
    Scrum is all about the value that is delivered to end users. If you really utilize scrum, you need to deliver something of value every sprint. The value can be measured, and the team is also forced to inspect impediments and adapt, with the goal of delivering more value in the next iteration.
    In most software development we are not building a skyscraper; we don’t need to have the whole plan ready before we start, and stick to that plan until the end. We are developing software, and we have the ability to adapt to different situations and to change the product requirements during development. For a long time, many developers saw this as the eighth deadly sin, but from the product perspective it is a huge benefit for optimizing predictability and controlling risk. Scrum is developed around this ability, and its implementation gives a reliable and efficient way of dealing with necessary changes.
    Many techniques are used in conjunction with scrum: planning poker, pair programming, test-driven development (TDD), behavior-driven development (BDD), and others. They are not really a part of scrum, but rather compatible techniques. One method often mentioned at the same time as scrum is kanban, and there is a lot of confusion about what these two things mean in relationship to each other.

    Kanban

    When you talk about scrum and kanban, one frequently asked question from the crowd will be, “Which is better, scrum or kanban?” And you won’t know what to answer because it’s like comparing apples and oranges, or asking, “Which is better, pancakes or beer?” Both are better.
    Kanban is a simple method that aims for just-in-time delivery while not overloading the team members. It is similar to scrum in that the goal is to deliver maximum value at the end, but it is much more flexible than scrum.
    Kanban was not invented by the software development community. In fact, it has its origins in manufacturing processes at Toyota, and it has wide usage in other spheres. There are no strict procedures that you should follow, and no strict way you should implement and use kanban; it is, rather, a set of principles and practices, and you can choose from these practices to suit your needs. But there is one most-often used implementation of kanban in software development that includes the usage of a kanban board, consisting of columns representing stages of work, and tasks.
    Columns represent the state of a task in the development process. The simplest example consists of three columns: “To Do,” “In Progress,” and “Done.” So, tasks are added to “To Do,” moved to “In Progress” when development starts, and considered “Done” when moved to the last column. But of course, it could be more complex:

    “Backlog” → “Defining Specification” → “Ready for Development” → “Development” → “Code Review” → “Testing” → “Deployed” (→ “No one really uses it” → “Completely Removed”).

    Every column can have subcolumns; for example, “Development” can be divided into “Planning” and “Coding”; “Testing” can be divided into “Unit Testing” and “Integration Testing,” and so on. Columns might be dedicated to specialists, if appropriate. The team defines the columns and stages according to its needs. Per the “pull” philosophy, tasks should only enter the workflow when the demand for them is immediate.
    Kanban boards help visualize the workflow.
    The purpose of this board is to visualize the workflow, which is the first key practice in kanban. In fact, kanban can be done without a board at all! It could be a simple list of tasks in a Google sheet with different background colors indicating the state of the task, or it can be Gantt charts, diagrams, tables… It could even be a set of buckets in your office, where each one represents the state of the task, and where balls are used as tasks. Just visualise the workflow and provide transparency to the whole process.
    Another important principle is to reduce the batch size of your efforts. Simplified, this means avoid multitasking. That can mean reducing the volume of tasks you work on at the same time. If you have three designers in a team, the team might set the maximum number of tasks in the “Designing” column to three.
    Like scrum, kanban also sees the team as the most important figure in the process. But it doesn’t suggest roles as scrum does, and you may keep the existing roles to avoid making changes to your existing process. The same stands for continuous improvement: Kanban generally encourages you to learn and improve continuously, but does not prescribe a specific event just for that process, as does scrum’s Sprint Retrospective.

    Which Should I Use?

    Scrum and kanban are not mutually exclusive and not really comparable. In scrum, there are defined roles, while kanban says, “What the hell, keep your current roles and responsibilities.” Scrum will force you to change your way of working; kanban lets you start with your existing process. In scrum, a clear schedule for events is prescribed by the framework; in kanban you don’t have events. Yet, they have a lot of similarities: Both are value-centric, team members are respected as “bosses” of the system, and essentially, they have the same mission: To continuously eliminate waste and remove obstacles.
    But the question, “What should I use in my particular project and with my particular team?” makes much more sense. Kanban doesn’t require so much of the process and cultural changes, and, in most cases, it will be easier to adopt than scrum. Scrum, on the other hand, offers significantly more structure to guide the process, which can eliminate a great deal of overhead as long as everyone is on the same page.
    But the beauty of both is that neither is a strict set of rules. There is nothing stopping you from picking and choosing the best scrum elements for you, such as a daily meeting or review. And there is no reason you cannot incorporate a kanban board into scrum.
    Scrum has proven to be a highly effective framework when the whole team understands it well. However, in my experience, I find it hard to work in scrum with some clients. The process and cultural changes required for proper scrum implementation can be too much (especially when dealing with someone who believes that he is making a new Google!). On the other hand, kanban is more flexible and doesn’t force people to change. Some authors also say that kanban is a good path to agility, and offers easier implementation of scrum. Others say that using scrum should lead to kanban at the end.
    The truth is that every project is different, and there is no one-size-fits-all solution. As a project manager, it is up to you to determine what works best for your team.
    This post originally appeared in the Toptal Engineering blog

  • Python Design Patterns: For Sleek And Fashionable Code

    Let’s say it again: Python is a high-level programming language with dynamic typing and dynamic binding. I would describe it as a powerful, high-level dynamic language. Many developers are in love with Python because of its clear syntax, well structured modules and packages, and for its enormous flexibility and range of modern features.
    In Python, nothing obliges you to write classes and instantiate objects from them. If you don’t need complex structures in your project, you can just write functions. Even better, you can write a flat script for executing some simple and quick task without structuring the code at all.
    At the same time Python is a 100 percent object-oriented language. How’s that? Well, simply put, everything in Python is an object. Functions are objects, first class objects (whatever that means). This fact about functions being objects is important, so please remember it.
    So, you can write simple scripts in Python, or just open the Python terminal and execute statements right there (that’s so useful!). But at the same time, you can create complex frameworks, applications, libraries and so on. You can do so much in Python. There are of course a number of limitations, but that’s not the topic of this article.
    However, because Python is so powerful and flexible, we need some rules (or patterns) when programming in it. So, let see what patterns are, and how they relate to Python. We will also proceed to implement a few essential Python design patterns.

    Why Is Python Good For Patterns?

    Any programming language is good for patterns. In fact, patterns should be considered in the context of any given programming language. Both the patterns, language syntax and nature impose limitations on our programming. The limitations that come from the language syntax and language nature (dynamic, functional, object oriented, and the like) can differ, as can the reasons behind their existence. The limitations coming from patterns are there for a reason, they are purposeful. That’s the basic goal of patterns; to tell us how to do something and how not to do it. We’ll speak about patterns, and especially Python design patterns, later.
    Python is a dynamic and flexible language. Python design patterns are a great way of harnessing its vast potential.

    Python is a dynamic and flexible language. Python design patterns are a great way of harnessing its vast potential.

    Python’s philosophy is built on top of the idea of well thought out best practices. Python is a dynamic language (did I already said that?) and as such, already implements, or makes it easy to implement, a number of popular design patterns with a few lines of code. Some design patterns are built into Python, so we use them even without knowing. Other patterns are not needed due of the nature of the language.
    For example, Factory is a structural Python design pattern aimed at creating new objects, hiding the instantiation logic from the user. But creation of objects in Python is dynamic by design, so additions like Factory are not necessary. Of course, you are free to implement it if you want to. There might be cases where it would be really useful, but they’re an exception, not the norm.
    What is so good about Python’s philosophy? Let’s start with this (explore it in the Python terminal):

    >>> import this
    The Zen of Python, by Tim Peters
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    

    These might not be patterns in the traditional sense, but these are rules that define the “Pythonic” approach to programming in the most elegant and useful fashion.
    We have also PEP-8 code guidelines that help structure our code. It’s a must for me, with some appropriate exceptions, of course. By the way, these exceptions are encouraged by PEP-8 itself:

    “But most importantly: know when to be inconsistent – sometimes the style guide just doesn’t apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!”

    Combine PEP-8 with The Zen of Python (also a PEP – PEP-20), and you’ll have a perfect foundation to create readable and maintainable code. Add Design Patterns and you are ready to create every kind of software system with consistency and evolvability.

    Python Design Patterns

    What Is A Design Pattern?

    Everything starts with the Gang of Four (GOF). Do a quick online search if you are not familiar with the GOF.
    Design patterns are a common way of solving well known problems. Two main principles are in the bases of the design patterns defined by the GOF:

    • Program to an interface not an implementation.
    • Favor object composition over inheritance.

    Let’s take a closer look at these two principles from the perspective of Python programmers.

    Program to an interface not an implementation

    Think about Duck Typing. In Python we don’t like to define interfaces and program classes according these interfaces, do we? But, listen to me! This doesn’t mean we don’t think about interfaces, in fact with Duck Typing we do that all the time.
    Let’s say some words about the infamous Duck Typing approach to see how it fits in this paradigm: program to an interface.
    If it looks like a duck and quacks like a duck, it's a duck!

    If it looks like a duck and quacks like a duck, it’s a duck!

    We don’t bother with the nature of the object, we don’t have to care what the object is; we just want to know if it’s able to do what we need (we are only interested in the interface of the object).
    Can the object quack? So, let it quack!

    try:
        bird.quack()
    except AttributeError:
        self.lol()
    

    Did we define an interface for our duck? No! Did we program to the interface instead of the implementation? Yes! And, I find this so nice.
    As Alex Martelli points out in his well known presentation about Design Patterns in Python, “Teaching the ducks to type takes a while, but saves you a lot of work afterwards!”

    Favor object composition over inheritance

    Now, that’s what I call a Pythonic principle! I have created fewer classes/subclasses compared to wrapping one class (or more often, several classes) in another class.
    Instead of doing this:

    class User(DbObject):
        pass
    

    We can do something like this:

    class User:
        _persist_methods = ['get', 'save', 'delete']
        def __init__(self, persister):
            self._persister = persister
        def __getattr__(self, attribute):
            if attribute in self._persist_methods:
                return getattr(self._persister, attribute)
    

    The advantages are obvious. We can restrict what methods of the wrapped class to expose. We can inject the persister instance in runtime! For example, today it’s a relational database, but tomorrow it could be whatever, with the interface we need (again those pesky ducks).
    Composition is elegant and natural to Python.

    Behavioral Patterns

    Behavioural Patterns involve communication between objects, how objects interact and fulfil a given task. According to GOF principles, there are a total of 11 behavioral patterns in Python: Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template, Visitor.
    Behavioural patterns deal with inter-object communication, controlling how various objects interact and perform different tasks.

    Behavioural patterns deal with inter-object communication, controlling how various objects interact and perform different tasks.

    I find these patterns very useful, but this does not mean the other pattern groups are not.

    Iterator

    Iterators are built into Python. This is one of the most powerful characteristics of the language. Years ago, I read somewhere that iterators make Python awesome, and I think this is still the case. Learn enough about Python iterators and generators and you’ll know everything you need about this particular Python pattern.

    Chain of responsibility

    This pattern gives us a way to treat a request using different methods, each one addressing a specific part of the request. You know, one of the best principles for good code is the Single Responsibility principle.
    Every piece of code must do one, and only one, thing.
    This principle is deeply integrated in this design pattern.
    For example, if we want to filter some content we can implement different filters, each one doing one precise and clearly defined type of filtering. These filters could be used to filter offensive words, ads, unsuitable video content, and so on.

    class ContentFilter(object):
        def __init__(self, filters=None):
            self._filters = list()
            if filters is not None:
                self._filters += filters
        def filter(self, content):
            for filter in self._filters:
                content = filter(content)
            return content
    filter = ContentFilter([
                    offensive_filter,
                    ads_filter,
                    porno_video_filter])
    filtered_content = filter.filter(content)
    

    Command

    This is one of the first Python design patterns I implemented as a programmer. That reminds me: Patterns are not invented, they are discovered. They exist, we just need to find and put them to use. I discovered this one for an amazing project we implemented many years ago: a special purpose WYSIWYM XML editor. After using this pattern intensively in the code, I read more about it on some sites.
    The command pattern is handy in situations when, for some reason, we need to start by preparing what will be executed and then to execute it when needed. The advantage is that encapsulating actions in such a way enables Python developers to add additional functionalities related to the executed actions, such as undo/redo, or keeping a history of actions and the like.
    Let’s see what a simple and frequently used example looks like:

    class RenameFileCommand(object):
        def __init__(self, from_name, to_name):
            self._from = from_name
            self._to = to_name
        def execute(self):
            os.rename(self._from, self._to)
        def undo(self):
            os.rename(self._to, self._from)
    class History(object):
        def __init__(self):
            self._commands = list()
        def execute(self, command):
            self._commands.append(command)
            command.execute()
        def undo(self):
            self._commands.pop().undo()
    history = History()
    history.execute(RenameFileCommand('docs/cv.doc', 'docs/cv-en.doc'))
    history.execute(RenameFileCommand('docs/cv1.doc', 'docs/cv-bg.doc'))
    history.undo()
    history.undo()
    

    Creational Patterns

    Let’s start by pointing out that creational patterns are not commonly used in Python. Why? Because of the dynamic nature of the language.
    Someone wiser than I once said that Factory is built into Python. It means that the language itself provides us with all the flexibility we need to create objects in a sufficiently elegant fashion; we rarely need to implement anything on top, like Singleton or Factory.
    In one Python Design Patterns tutorial, I found a description of the creational design patterns that stated these design “patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using a new operator.”
    That pretty much sums up the problem: We don’t have a new operator in Python!
    Nevertheless, let’s see how we can implement a few, should we feel we might gain an advantage by using such patterns.

    Singleton

    The Singleton pattern is used when we want to guarantee that only one instance of a given class exists during runtime. Do we really need this pattern in Python? Based on my experience, it’s easier to simply create one instance intentionally and then use it instead of implementing the Singleton pattern.
    But should you want to implement it, here is some good news: In Python, we can alter the instantiation process (along with virtually anything else). Remember the __new__() method I mentioned earlier? Here we go:

    class Logger(object):
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls, '_logger'):
                cls._logger = super(Logger, cls
                        ).__new__(cls, *args, **kwargs)
            return cls._logger
    

    In this example, Logger is a Singleton.
    These are the alternatives to using a Singleton in Python:

    • Use a module.
    • Create one instance somewhere at the top-level of your application, perhaps in the config file.
    • Pass the instance to every object that needs it. That’s a dependency injection and it’s a powerful and easily mastered mechanism.

    Dependency Injection

    I don’t intend to get into a discussion on whether dependency injection is a design pattern, but I will say that it’s a very good mechanism of implementing loose couplings, and it helps make our application maintainable and extendable. Combine it with Duck Typing and the Force will be with you. Always.
    Duck? Human? Python does not care. It's flexible!

    Duck? Human? Python does not care. It’s flexible!

    I listed it in the creational pattern section of this post because it deals with the question of when (or even better: where) the object is created. It’s created outside. Better to say that the objects are not created at all where we use them, so the dependency is not created where it is consumed. The consumer code receives the externally created object and uses it. For further reference, please read the most upvoted answer to this Stackoverflow question
    It’s a nice explanation of dependency injection and gives us a good idea of the potential of this particular technique. Basically the answer explains the problem with the following example:  Don’t get things to drink from the fridge yourself, state a need instead. Tell your parents that you need something to drink with lunch.
    Python offers us all we need to implement that easily. Think about its possible implementation in other languages such as Java and C#, and you’ll quickly realize the beauty of Python.
    Let’s think about a simple example of dependency injection:

    class Command:
        def __init__(self, authenticate=None, authorize=None):
            self.authenticate = authenticate or self._not_authenticated
            self.authorize = authorize or self._not_autorized
        def execute(self, user, action):
            self.authenticate(user)
            self.authorize(user, action)
            return action()
    if in_sudo_mode:
        command = Command(always_authenticated, always_authorized)
    else:
        command = Command(config.authenticate, config.authorize)
    command.execute(current_user, delete_user_action)
    

    We inject the authenticator and authorizer methods in the Command class. All the Command class needs is to execute them successfully without bothering with the implementation details. This way, we may use the Command class with whatever authentication and authorization mechanisms we decide to use in runtime.
    We have shown how to inject dependencies through the constructor, but we can easily inject them by setting directly the object properties, unlocking even more potential:

    command = Command()
    if in_sudo_mode:
        command.authenticate = always_authenticated
        command.authorize = always_authorized
    else:
        command.authenticate = config.authenticate
        command.authorize = config.authorize
    command.execute(current_user, delete_user_action)
    

    There is much more to learn about dependency injection; curious people would search for IoC, for example.
    But before you do that, read another Stackoverflow answer, the most upvoted one to this question.
    Again, we just demonstrated how implementing this wonderful design pattern in Python is just a matter of using the built-in functionalities of the language.
    Let’s not forget what all this means: The dependency injection technique allows for very flexible and easy unit-testing. Imagine an architecture where you can change data storing on-the-fly. Mocking a database becomes a trivial task, doesn’t it? For further information, you can check out Toptal’s Introduction to Mocking in Python.
    You may also want to research Prototype, Builder and Factory design patterns.

    Structural Patterns

    Facade

    This may very well be the most famous Python design pattern.
    Imagine you have a system with a considerable number of objects. Every object is offering a rich set of API methods. You can do a lot of things with this system, but how about simplifying the interface? Why not add an interface object exposing a well thought-out subset of all API methods? A Facade!
    Facade is an elegant Python design pattern. It's a perfect way of streamlining the interface.

    Facade is an elegant Python design pattern. It’s a perfect way of streamlining the interface.

    Python Facade design pattern example:

    class Car(object):
        def __init__(self):
            self._tyres = [Tyre('front_left'),
                                 Tyre('front_right'),
                                 Tyre('rear_left'),
                                 Tyre('rear_right'), ]
            self._tank = Tank(70)
        def tyres_pressure(self):
            return [tyre.pressure for tyre in self._tyres]
        def fuel_level(self):
            return self._tank.level
    

    There is no surprise, no tricks, the Car class is a Facade, and that’s all.

    Adapter

    If Facades are used for interface simplification, Adapters are all about altering the interface. Like using a cow when the system is expecting a duck.
    Let’s say you have a working method for logging information to a given destination. Your method expects the destination to have a write() method (as every file object has, for example).

    def log(message, destination):
        destination.write('[{}] - {}'.format(datetime.now(), message))
    

    I would say it is a well written method with dependency injection, which allows for great extensibility. Say you want to log to some UDP socket instead to a file,you know how to open this UDP socket but the only problem is that the socket object has no write() method. You need an Adapter!

    import socket
    class SocketWriter(object):
        def __init__(self, ip, port):
            self._socket = socket.socket(socket.AF_INET,
                                         socket.SOCK_DGRAM)
            self._ip = ip
            self._port = port
        def write(self, message):
            self._socket.send(message, (self._ip, self._port))
    def log(message, destination):
        destination.write('[{}] - {}'.format(datetime.now(), message))
    upd_logger = SocketWriter('1.2.3.4', '9999')
    log('Something happened', udp_destination)
    

    But why do I find adapter so important? Well, when it’s effectively combined with dependency injection, it gives us huge flexibility. Why alter our well-tested code to support new interfaces when we can just implement an adapter that will translate the new interface to the well known one?
    You should also check out and master bridge and proxy design patterns, due to their similarity to adapter. Think how easy they are to implement in Python, and think about different ways you could use them in your project.

    Decorator

    Oh how lucky we are! Decorators are really nice, and we already have them integrated into the language. What I like the most in Python is that using it teaches us to use best practices. It’s not that we don’t have to be conscious about best practices (and design patterns, in particular), but with Python I feel like I’m following best practices, regardless. Personally, I find Python best practices are intuitive and second nature, and this is something appreciated by novice and elite developers alike.
    The decorator pattern is about introducing additional functionality and in particular, doing it without using inheritance.
    So, let’s check out how we decorate a method without using built-in Python functionality. Here is a straightforward example.

    def execute(user, action):
        self.authenticate(user)
        self.authorize(user, action)
        return action()
    

    What is not so good here is that the execute function does much more than executing something. We are not following the single responsibility principle to the letter.
    It would be good to simply write just following:

    def execute(action):
        return action()
    

    We can implement any authorization and authentication functionality in another place, in a decorator, like so:

    def execute(action, *args, **kwargs):
        return action()
    def autheticated_only(method):
        def decorated(*args, **kwargs):
            if check_authenticated(kwargs['user']):
                return method(*args, **kwargs)
            else:
                raise UnauthenticatedError
        return decorated
    def authorized_only(method):
        def decorated(*args, **kwargs):
            if check_authorized(kwargs['user'], kwargs['action']):
                return method(*args, **kwargs)
            else:
                raise UnauthorizeddError
        return decorated
    execute = authenticated_only(execute)
    execute = authorized_only(execute)
    

    Now the execute() method is:

    • Simple to read
    • Does only one thing (at least when looking at the code)
    • Is decorated with authentication
    • Is decorated with authorization

    We write the same using Python’s integrated decorator syntax:

    def autheticated_only(method):
        def decorated(*args, **kwargs):
            if check_authenticated(kwargs['user']):
                return method(*args, **kwargs )
            else:
                raise UnauthenticatedError
        return decorated
    def authorized_only(method):
        def decorated(*args, **kwargs):
            if check_authorized(kwargs['user'], kwargs['action']):
                return method(*args, **kwargs)
            else:
                raise UnauthorizedError
        return decorated
    @authorized_only
    @authenticated_only
    def execute(action, *args, **kwargs):
        return action()
    

    It is important to note that you are not limited to functions as decorators. A decorator may involve entire classes. The only requirement is that they must be callables. But we have no problem with that; we just need to define the __call__(self) method.
    You may also want to take a closer look at Python’s functools module. There is much to discover there!

    Conclusion

    I have shown how natural and easy is to use Python’s design patterns, but I have also shown how programming in Python should be easy going, too.
    “Simple is better than complex,” remember that? Maybe you have noticed that none of the design patterns is fully and formally described. No complex full-scale implementations were shown. You need to “feel” and implement them in the way that best fits your style and needs. Python is a great language and it gives you all the power you need to produce flexible and reusable code.
    However, it gives you more than that. It gives you the “freedom” to write really bad code. Don’t do it! Don’t Repeat Yourself (DRY) and never write code lines longer than 80 characters. And don’t forget to use design patterns where applicable; it’s one of the best ways to learn from others and gain from their wealth of experience free of charge.

    This post originally appeared on the Toptal Engineering blog
  • Ensemble Methods: Elegant Techniques to Produce Improved Machine Learning Results

    Ensemble methods are techniques that create multiple models and then combine them to produce improved results. Ensemble methods usually produces more accurate solutions than a single model would. This has been the case in a number of machine learning competitions, where the winning solutions used ensemble methods. In the popular Netflix Competition, the winner used an ensemble method to implement a powerful collaborative filtering algorithm. Another example is KDD 2009 where the winner also used ensemble methods. You can also find winners who used these methods in Kaggle competitions, for example here is the interview with the winner of CrowdFlower competition.
    It is important that we understand a few terminologies before we continue with this article. Throughout the article I used the term “model” to describe the output of the algorithm that trained with data. This model is then used for making predictions. This algorithm can be any machine learning algorithm such as logistic regression, decision tree, etc. These models, when used as inputs of ensemble methods, are called ”base models”.
    In this blog post I will cover ensemble methods for classification and describe some widely known methods of ensemble: voting, stacking, bagging and boosting.

    Voting and Averaging Based Ensemble Methods

    Voting and averaging are two of the easiest ensemble methods. They are both easy to understand and implement. Voting is used for classification and averaging is used for regression.
    Voting and Averaging Based Ensemble Methods
    In both methods, the first step is to create multiple classification/regression models using some training dataset. Each base model can be created using different splits of the same training dataset and same algorithm, or using the same dataset with different algorithms, or any other method. The following Python-esque pseudocode shows the use of same training dataset with different algorithms.

    train = load_csv("train.csv")
    target = train["target"]
    train = train.drop("target")
    test = load_csv("test.csv")
    algorithms = [logistic_regression, decision_tree_classification, ...] #for classification
    algorithms = [linear_regression, decision_tree_regressor, ...] #for regression
    predictions = matrix(row_length=len(target), column_length=len(algorithms))
    for i,algorithm in enumerate(algorithms):
        predictions[,i] = algorithm.fit(train, target).predict(test)
    

    According to the above pseudocode, we created predictions for each model and saved them in a matrix called predictions where each column contains predictions from one model.

    Majority Voting

    Every model makes a prediction (votes) for each test instance and the final output prediction is the one that receives more than half of the votes. If none of the predictions get more than half of the votes, we may say that the ensemble method could not make a stable prediction for this instance. Although this is a widely used technique, you may try the most voted prediction (even if that is less than half of the votes) as the final prediction. In some articles, you may see this method being called “plurality voting”.

    Weighted Voting

    Unlike majority voting, where each model has the same rights, we can increase the importance of one or more models. In weighted voting you count the prediction of the better models multiple times. Finding a reasonable set of weights is up to you.

    Simple Averaging

    In simple averaging method, for every instance of test dataset, the average predictions are calculated. This method often reduces overfit and creates a smoother regression model. The following pseudocode code shows this simple averaging method:

    final_predictions = []
    for row_number in len(predictions):
        final_predictions.append(
            mean(prediction[row_number, ])
        )
    

    Weighted Averaging

    Weighted averaging is a slightly modified version of simple averaging, where the prediction of each model is multiplied by the weight and then their average is calculated. The following pseudocode code shows the weighted averaging:

    
    weights = [..., ..., ...] #length is equal to len(algorithms)
    final_predictions = []
    for row_number in len(predictions):
        final_predictions.append(
            mean(prediction[row_number, ]*weights)
        )
    

    Stacking Multiple Machine Learning Models

    Stacking, also known as stacked generalization, is an ensemble method where the models are combined using another machine learning algorithm. The basic idea is to train machine learning algorithms with training dataset and then generate a new dataset with these models. Then this new dataset is used as input for the combiner machine learning algorithm.
    Stacking Multiple Machine Learning Models
    The pseudocode of a stacking procedure is summarized as below:

    base_algorithms = [logistic_regression, decision_tree_classification, ...] #for classification
    stacking_train_dataset = matrix(row_length=len(target), column_length=len(algorithms))
    stacking_test_dataset = matrix(row_length=len(test), column_length=len(algorithms))
    for i,base_algorithm in enumerate(base_algorithms):
        stacking_train_dataset[,i] = base_algorithm.fit(train, target).predict(train)
        stacking_test_dataset[,i] = base_algorithm.predict(test)
    final_predictions = combiner_algorithm.fit(stacking_train_dataset, target).predict(stacking_test_dataset)
    

    As you can see in the above pseudocode, the training dataset for combiner algorithm is generated using the outputs of the base algorithms. In the pseudocode, the base algorithm is generated using training dataset and then the same dataset is used again to make predictions. But as we know, in the real world we do not use the same training dataset for prediction, so to overcome this problem you may see some implementations of stacking where training dataset is splitted. Below you can see a pseudocode where the training dataset is split before training the base algorithms:

    base_algorithms = [logistic_regression, decision_tree_classification, ...] #for classification
    stacking_train_dataset = matrix(row_length=len(target), column_length=len(algorithms))
    stacking_test_dataset = matrix(row_length=len(test), column_length=len(algorithms))
    for i,base_algorithm in enumerate(base_algorithms):
        for trainix, testix in split(train, k=10): #you may use sklearn.cross_validation.KFold of sklearn library
            stacking_train_dataset[testcv,i] = base_algorithm.fit(train[trainix], target[trainix]).predict(train[testix])
    stacking_test_dataset[,i] = base_algorithm.fit(train).predict(test)
    final_predictions = combiner_algorithm.fit(stacking_train_dataset, target).predict(stacking_test_dataset)
    

    Bootstrap Aggregating

    The name Bootstrap Aggregating, also known as “Bagging”, summarizes the key elements of this strategy. In the bagging algorithm, the first step involves creating multiple models. These models are generated using the same algorithm with random sub-samples of the dataset which are drawn from the original dataset randomly with bootstrap sampling method. In bootstrap sampling, some original examples appear more than once and some original examples are not present in the sample. If you want to create a sub-dataset with m elements, you should select a random element from the original dataset m times. And if the goal is generating n dataset, you follow this step n times.
    Bootstrap Aggregating
    At the end, we have n datasets where the number of elements in each dataset is m. The following Python-esque pseudocode show bootstrap sampling:

    def bootstrap_sample(original_dataset, m):
        sub_dataset = []
        for i in range(m):
            sub_dataset.append(
                random_one_element(original_dataset)
            )
        return sub_dataset
    

    The second step in bagging is aggregating the generated models. Well known methods, such as voting and averaging, are used for this purpose.
    The overall pseudocode look like this:

    def bagging(n, m, base_algorithm, train_dataset, target, test_dataset):
        predictions = matrix(row_length=len(target), column_length=n)
        for i in range(n):
            sub_dataset = bootstrap_sample(train_dataset, m)
            predictions[,i] = base_algorithm.fit(original_dataset, target).predict(test_dataset)
        final_predictions = voting(predictions) # for classification
        final_predictions = averaging(predictions) # for regression
        return final_predictions
    

    In bagging, each sub-samples can be generated independently from each other. So generation and training can be done in parallel.
    You can also find implementation of the bagging strategy in some algorithms. For example, Random Forestalgorithm uses the bagging technique with some differences. Random Forest uses random feature selection, and the base algorithm of it is a decision tree algorithm.

    Boosting: Converting Weak Models to Strong Ones

    The term “boosting” is used to describe a family of algorithms which are able to convert weak models to strong models. The model is weak if it has a substantial error rate, but the performance is not random (resulting in an error rate of 0.5 for binary classification). Boosting incrementally builds an ensemble by training each model with the same dataset but where the weights of instances are adjusted according to the error of the last prediction. The main idea is forcing the models to focus on the instances which are hard. Unlike bagging, boosting is a sequential method, and so you can not use parallel operations here.
    The general procedure of the boosting algorithm is defined as follows:

    def adjust_dataset(_train, errors):
        #create a new dataset by using the hardest instances
        ix = get_highest_errors_index(train)
        return concat(_train[ix], random_select(train))
    models = []
    _train = random_select(train)
    for i in range(n): #n rounds
        model = base_algorithm.fit(_train)
        predictions = model.predict(_train)
        models.append(model)
        errors = calculate_error(predictions)
        _train = adjust_dataset(_train, errors)
    final_predictions = combine(models, test)
    

    The adjust_dataset function returns a new dataset containing the hardest instances, which can then be used to force the base algorithm to learn from.
    Adaboost is a widely known algorithm which is a boosting method. The founders of Adaboost won the Gödel Prize for their work. Mostly, decision tree algorithm is preferred as a base algorithm for Adaboost and in sklearn library the default base algorithm for Adaboost is decision tree (AdaBoostRegressor and AdaBoostClassifier). As we discussed in the previous paragraph, the same incremental method applies for Adaboost. Information gathered at each step of the AdaBoost algorithm about the ‘hardness’ of each training sample is fed into the model. The ‘adjusting dataset’ step is different from the one described above and the ‘combining models’ step is calculated by using weighted voting.

    Conclusion

    Although ensemble methods can help you win machine learning competitions by devising sophisticated algorithms and producing results with high accuracy, it is often not preferred in the industries where interpretability is more important. Nonetheless, the effectiveness of these methods are undeniable, and their benefits in appropriate applications can be tremendous. In fields such as healthcare, even the smallest amount of improvement in the accuracy of machine learning algorithms can be something truly valuable.
    This post originally appeared on the Toptal Engineering blog