Tag: Tutorial

  • Setting up a Python Virtual Environment for Web Development

    Virtual Environments are helpful in keeping all the dependencies (packages), required for a Python project, in one place. So you can avoid issues with conflicting dependencies when working on different projects simultaneously. For instance, one major use case is when you want to run different Python versions like 2.7, 3.5, and 3.6 on the same system.

    You can use the following steps when setting up any Python project (including web development project using frameworks like Django, Flask etc.)

    1. Make a top-level Directory

    Create a directory named “virtualenvs” (a parent directory to keep all your virtual environments). All your Python projects will live inside this directory.
    mkdir virtualenvs

    2. Create the Python Virtual Environment

    cd virtualenvs
    python3 -m venv env

    You may use any name for the directory, other than “env”. If you’re curious about what goes inside the auto-generated “env” directory, you can check here:
    cd env
    cat pyvenv.cfg
    python —version
    pip —version

    3. Activate the virtual env

    On Mac: source bin/activate
    On Linux: ./bin/activate
    On Windows: .\Scripts\activate

    Important: You need to activate the virtual environment every time you want to build or run the code. You may edit the code files without activating the venv.
    Use deactivate to leave the virtual environment, or simply close the session/Terminal.

    4. Create the project directory

    mkdir your_proj_name

    Optionally, Initialise git inside your_proj_name directory (you don’t need to commit the other files of env directory into git.):

    git init
    OR if you have the project code already, git clone the code inside env:
    git clone [url]

    5 a. Install packages/dependencies using pip

    If you’ve a requirements.txt file:
    pip install -r requirements.txt

    or install the packages individually, for example for Django:
    pip install django or
    pip install django==2.1 # For a particular version

    5 b. You can also install packages from Source Code

    For example download Django pre-release code from their git repo, and unzip it into a directory named django, then:

    pip install -e django
    OR
    pip install --editable django

    Note that you may run pip from any of env‘s subdirectories: the installed code will always go into the env/lib and env/bin directories.

    6. Finish and Run

    You’re set to start working on the project now.
    If you’re satisfied with the setup, you most probably want to keep a list of dependencies you just installed.

    pip freeze > requirements.txt

    (Keep the requirements file in git if you’ve initialised the git repo.)

    7. Optimizing your daily workflow

    I made this small shell script to automate the task of entering and activating the venv every-time I start:

    #!/bin/bash
    cd virtualenvs/env/
    source bin/activate
    # Configure any other environment variables here -
    # for example, private API keys that you don't want to check in to git.
    cd your_proj_name/
    

    Paste the above code in a file name  start_your_project_name.sh. From now on, to get started, you just have to do this:

    source start_your_project_name.sh
    or ./start_your_project_name.sh
  • Designing the Apple Watch UI – a quick guide

    Designing the Apple Watch UI – a quick guide

    The Apple Watch is releasing in a month! Here’s a list of important things you need to know, if you’re interested in designing or developing an Apple Watch App:

    1. Layout and Screen Sizes

    38mm: 340 pixels x 272 pixels
    42mm: 390 pixels x 312 pixels
    That’s an aspect ratio of 4:5.

     

    2. Icon and Image Sizes

    Unlike the Rounded Square icons on iPhones, the icons on the Apple Watch are round.

    Icon Sizes Required:
    38mm Watch: 48px, 80px, 172px
    42mm Watch: 55px, 88px, 196px

    Tips on designing the Icons (designers take note!):
    – Create all of your image resources as @2x images.
    – Create your icons as full-bleed square images using the given dimensions. The system applies the circular mask automatically.
    PNG format is recommended (for images and icons). Avoid using interlaced PNGs.
    – The standard bit depth for icons and images is 24 bits—that is, 8 bits each for red, green, and blue. You can include an 8-bit alpha channel but doing so is not required. You can also use PNGs with indexed colors to save space in your image files.
    – While designing these, also note that you’ll need the accompanying icons for the iPhone app. (i.e. Watch App can’t work without the iPhone App)
    More information on Icons and Image Sizes.

    3. Color

    “A black background blends seamlessly with the device bezel and maintains the illusion of there being no screen edges. Avoid bright background colors in your interface.”

    “Every app defines a key color. The system uses this key color for the title string in the upper-left corner of the screen and in notification interfaces to highlight your app name or other key information. You should similarly use the key color as part of the branding of your app.” More on colors.

    4. Typography

    There’s a system font “designed specifically for legibility on Apple Watch”. (the San Francisco Font). “Use San Francisco Text font for text that is 19 points or smaller; San Francisco Display font for text that is 20 points or larger.”
    You can chose another font, but be careful to go for a dynamic font (that adjusts well to size — since the watch interface is so small). With Dynamic type, you get automatic adjustments to letter spacing and line height, text that responds appropriately to changes the user makes to text-size settings and more. More on Typography.

    5. Two ways of navigating an App – Hierarchical Vs Page based navigation

    From the start, you have to decide which type of navigation you want. A single App can’t behave as Hierarchical at one point and Page-Based at another point.

    The two types are quite different in look, feel and the way they function. For instance, Horizontal swipes are only available for Page-Based Apps. More information on navigation types.

    6. The three ways of presenting information

    I. via the Main App

    You can reach the App by launching the App from Homescreen. The ways of interacting with your Main App are rather limited right now.
    Here’s what you can do:
    a) Taps (selection)
    b) Vertical Swipes (scroll through the screen)
    c) Horizontal Swipes (go between pages – only available in page based apps.)
    d) Force Touch:
    Pressing the screen with a small amount of force activates the context menu (if any) associated with the current interface controller; this is the only thing a Watch app can do with force touch feature. More information on context menus.


    Design of the Force Touch Context Menu can display up to four actions. The image for the context menu must be a template image — where the alpha channel defines the shape to draw on top of the background. Opaque portions of the image show up as black and fully or partially transparent portions let the background color show through.
    e) Digital Crown: Only ‘scrolling’ support available to third party apps.

    II. via Notifications

    The wearer feels a gentle tap on the wrist when the Notification arrives.
    Notifications are displayed up in two formats.
    a) The “Short Look” is only seen briefly when you raise your wrist — it’s an app icon, an app name, and some brief information.
    That is, the Short Look provides a discreet, minimal amount of information — preserving a degree of privacy. If the wearer lowers his or her wrist, the Short Look interface disappears.

     

    b) The “Long Look” interface appears when the wearer’s wrist remains raised or when the user taps the Short Look interface. It provides more detailed information and more functionality — and it must be actively dismissed by the wearer.
    For Long Looks, the app icon and name move to the top of the screen, and wearers can scroll down through the interface to use custom actions (such as “comment” or “favorite”) or dismiss the notification.

    Read More about notifications.

    III. via Glances

    Glances from all the apps are viewed together at a common swipe-able place. User can tap on a glance to enter the App. All the information on a ‘glance’ must fit on a single screen and is read-only. As the name suggest glances are there to provide the user useful information; don’t use them to spam the user. The area at the bottom of the glance is reserved for the page indicator dots. Read more about glances.

    7. Image Cache

    You can store upto 20MB of image resources in cache on the Apple watch. As with webpages and Apps managing caches efficiently is a hallmark of good front end; so plan your cacheing strategy well. Needless to say use very optimized images. More information on how to use images in the App.

    8. Animation

    To create animation you can loop through “sequentially named images”, infinitely or till a specific count. There’s no mention of support for videos or UIKit like animation.
    These links have good info on how to show animations on Apple Watch:
    http://natashatherobot.com/watchkit-animate/
    http://www.raywenderlich.com/94672/watchkit-faq

    9. Handoff

    Handoff feature can transfer the user action from the watch to the iPhone. Handoff can also be used to dynamically send some information to the main Watch App interface using Notifications or Glances.

    10. Fullscreen Support (Not available)

    There’s no mention of fullscreen support for an app. (The only few seconds that your app will have the fullscreen of the watch to itself is during the short look notification.)

    11. Settings Bundle

    Works the same way as the iOS settings bundle. “Preferences are pieces of information that you store persistently and use to configure your app. Apps often expose preferences to users so that they can customize the appearance and behavior of the app.” More information on the settings bundle on the Watch which complements the existing settings bundle on iOS.

    12. Date and Time

    Use Date and timer objects whenever you want to display a current day or time or implement a precise timer. Date and time labels come in variety of formats suited for the watch. Generally, it’s a bad idea to invent your own date time format. More info on date, time formatting here.

    13. Dependence on iOS App

    Apple Watch requires the presence of an iPhone to run third-party apps.
    “A WatchKit app complements your iOS app; it does not replace it.”
    “During installation of your iOS app, the system prompts the user to install the WatchKit app when a paired Apple Watch is present.”

    Further Reading

    • Apple’s Human Interface Guidelines (HIG) for the Watch (Approximately 2hrs read)
    WatchKit Programming Guide
    • WatchKit Framework Reference (for programmers)
    • Apple’s tips and best practices for developing Watchkit Apps.

  • Navigating large codebases and contributing to Open Source

    (I wrote the following as an email to a someone who asked me for advice. So it’s verbose and written with a personal tone.)

    I. Setup your system and build the project code

    Pick any good Integrated Development Environment (IDE). I like VS Code. You can work on any langauge in VSCode be it C++, JS or Python, and you won’t have to learn the interface of a new editor everytime you switch language. VIM is a good choice too. Then of course there’s emacs and more. I recommend you pick a more generic — widely used editor, instead of something like say Dev C++ that’s restricted to a language.

    Under the hood, VS Code has something called “Intellisense” which creates a sort of index of the whole project when you load the project (So, when you right click on a variable/function you can click on “Go to definition” to jump to where a variable is defined/declared etc.). This indexed code is super useful for navigating a large codebase: a good analogy I read long back is to think of this ‘index’ as a torch to navigate through a dark maze. That’s is basically the difference between an IDE or just using a more basic Editor.

    Also figure out how to use the terminal effectively — modify your terminal’s configuration file to your liking. In older days, people would use things like ctags, cscope, gdb to achive the same via the Terminal; IDEs were buggy and slow. Command line tools like tags and cscope help you jump to definitions/functions etc. just like IDEs. It’s interesting to learn these too, in particular if you’re working on C/C++.

    Then, get a local copy of the code you want to checkout and compile it. Usually there’s a “how to build/run the project” section in the README file.

    You can’t do anything if the project doesn’t build on your system! Look at the build script (makefile, requirements.txt, webpack etc., whatever is used on the project) to see if you can find some hints on how the code is actually “booted”. See the list of other libraries the project depends on.

    Always, read the output of the build process: you’ll find some helpful hints on what command were executed and how the build went.

    II. Understand the business logic for the code base

    Get a high level understanding of the project. Coding usually doesn’t just involve punching keys. You have to understand what the project is trying to achieve, otherwise you would remain confused.

    You’ll have to read the project’s documentation or some literature on the industry. For example, if you’re working on an HTTP networking library, you’ll need to know the HTTP specification fairly well. If you’re working on a library management system, you’ll have to understand how books are categorised in libraries, ISBN format etc.

    If it’s an open source projects, you might even find some talks by the project developers online or some project slides. So search on the web. See if you can find some architecture diagram viz. flowcharts, sequence diagrams, UML class diagrams, Component (Block) diagrams. If you can talk to other developers on the project, that would be useful too.

    III. Set an initial aim

    Decide what you want to do on the code base i.e. do you just want to just learn the code flow, fix some issue or enhance some feature etc. Try to aim high. Setting up audacious goals generally has positive outcomes.

    This essentially is a Bottom-Up approach. You isolate a module/component in the codebase, and work on it.

    Make small changes and see how it affects the code flow. You can always revert back to the original version.

    The Top-Down approach, would be something like grasping the whole source code before editing anythint. While that theoretically sounds like a good idea, it could take too much time and you’ll tire youself out before modifying even a line of code. Learning the whole codebase is overwhelming for everyone.

    New developers at Facebook are encouraged to commit their first code on the first day of joining! This bottom-up approach is a much better start, then trying to understand the whole FB architecture.)

    IV. Make notes as you study the code

    Understand the different classes or abstractions, and try to estimate what each module/class/abstraction is doing. Look at the Folders/Files and try to make sense of what they are doing by their names.

    I usually like to make a lot of rough notes on paper – noting down the classes how they interact, the inheritance structure.

    Draw rough class diagrams on the fly. Also draw a call graph, as in which functions calls the next function etc. Diagrams could be specially useful if you’re a visual person. At times, I have even taken printouts of some code at times and annotated it.

    Big codebases, usually have a lot of asynchronous calls with multiple processes and threads. You might have to understand how the process/threads pass data between themselves.

    V. Look for an entry point into the code

    Usually, projects keep the core code in “src”. While the built binaries usually go into “bin”. There are also other folders like lib, docs, test etc.

    Your IDE will allow you to setup Breakpoints on various files to debug the code. So setup a few breakpoints on functions that you might think will be ‘hit’ when the code is run. When a breakpoint is hit, the code execution stops and you can see a call hierarchy, i.e. a trace of all the functions that were called till the breakpoint.

    VI. Look for the data models

    There are two broad types of coding projects — Data driven and Functionality driven.

    If your code base is to deal with large amounts of structured data then reading the DB Tables/Data structure would be super useful. Here’s a quote that puts it so well:

    “Show me your [code] and conceal your [data structures], and I shall continue to be mystified. Show me your [data structures], and I won’t usually need your [code]; it’ll be obvious.” – Fred Brooks

    VII. Logs, Debug msgs, Test folder

    When you run/build the code, it shows a lot of info on the output terminal or in Log files.

    It might seem daunting initially, but read the output carefully and try to follow what the messages are trying to tell you. You’ll understand a lot about the code flow from here! Eventually, you’ll develop a knack for how to read logfiles and debug messages and this is a super helpful skill.

    If you just can figure out, look into the tests folder, there might be some earsier/helpful code you find their on how to interact with the main source code.

    VIII. Language basics are important

    Big projects could be using very advanced language features, complex design patterns, clever hacks etc. So a good understand of the language syntax itself, Design patterns, OS fundamentals is super useful.

    For example, if you’re working on some mobile app, then understanding the MVP design pattern is almost necessary before even getting started. If the code uses frameworks, you’ll need to understand the framework itself. For example, to build a web application on Django, you’ll need to have gone through the basics of the django framework at the very least.

    You might need to understand how the language interacts with the OS (Android, iOS, Linux, MacOS, embedded systems et al). For e.g. how does File I/O happen or how are threads spawned.

    IX. Be patient

    It takes time, so be patient. Navigating code base isn’t easy for even experienced developers, especially when many people have contributed to the code.

    Additional

    You’ll also need to understand:

    • How code versioning systems work. Most probably git is being used.
    • How bugs are reported and handled on the project.
    • Coding Standards — how variables/functions are to be named or how many spaces are used for indent etc. Be sure to follow the guidelines setup by the project’s maintainer.

    More Tools

    • Tools like grep, find are super helpful.
    • tree
    • tree | less(you can do brew install tree to get tree on Macs)
    • For C/C++ callgrind + kcachegrind are interesting to see call graphs.