Setup react and node.js on virtualenv

Assuming you already have virtualenv installed on your system, here are the steps to setup a node.js and react environment within your virtualenv. Refer to this link to install virtualenv.

1. Create a directory UI-NodeReact (or any other name you want to start up with)

2. Create a virtual env for your project and let’s name it practice

virtualenv --no-site-packages practice

2. Activate the virtual env

source practice/bin/activate

3. Install nodeenv. It’s a tool to create isolated node.js environments.

pip install nodeenv

4. Add a node.js virtual environment to the existing environment that will also give you the npm package manager.

nodeenv -p

5. Install the create-react-app package using the npm package manager from node.js

npm i -g create-react-app@3.0.1

6. Create a new react app

create-react-app react-app

You’ll see the following output:

Success! Created react-app at /Users/varun.verma/Work/virtualenv/UI-NodeReact/practice/react-app
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd react-app
  npm start

Happy hacking!

7. Install Visual Studio Code

8. Install Extensions

  • Simple React Snippets
  • Prettier

9. Format the code on saving.

Settings > Format On Save : Enable

10. Now, you’re ready to open the folder created by the above step into your VS Code and begin programming.

Advertisements

Tableau – Show top 10 customers with highest profit

Using the Sample – Superstore database that comes with Tableau, defining an easy way to display top N items based on a measure.

1. Drag the Customer Name into the Rows field

2. Drag the Profit onto the Marks > Text field. Doing so will make it as the last column get rid of the Abc column that shows up at the end.

3. Create a new Set for the Customer Name. On the General tab, select “Use all”. On the Condition tab, select “None”. On the Top tab, select “By field”, the first dropdown set to “Top” with a value of “10”. On the second dropdown, set the value to your measure of interest, “Profit” in this case and aggregate set to “Sum”. Click OK to save the set.

4. To sort the customer by Profits, right click on Customer Name and click “Sort”. Select Descending and select “Field”, set to first dropdown to “Profit” and aggregation set to “Sum”.

5. Drag the set “Top customers by profit” onto Filters and you’ll see that the list now shows only the top 10 customers based on Profit.

C# DotNet – Sample POST and GET Requests

Here’s a sample GET and POST request to httpbin.org. It’s a great site that allows you to make API calls and build API clients and test out on a remote server without having to build your server for testing the client functionality.

using System; 
using System.IO;
using System.Net;
using System.Text;

class GFG { 

  public static void SamplePostRequest() {
    /*
    // Create a request using a URL that can receive a post. 
    WebRequest request = WebRequest.Create("http://httpbin.org/post");
    // Set the Method property of the request to POST.
    request.Method = "POST";
    // Create POST data and convert it to a byte array.
    string postData = "This is a test that posts this string to a Web server.";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    // Set the ContentType property of the WebRequest.
    request.ContentType = "application/x-www-form-urlencoded";
    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;
    // Get the request stream.
    Stream dataStream = request.GetRequestStream();
    // Write the data to the request stream.
    dataStream.Write(byteArray, 0, byteArray.Length);
    // Close the Stream object.
    dataStream.Close();
    // Get the response.
    WebResponse response = request.GetResponse();
    // Display the status.
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    // Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream();
    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(dataStream);
    // Read the content.
    string responseFromServer = reader.ReadToEnd();
    // Display the content.
    Console.WriteLine(responseFromServer);
    // Clean up the streams.
    reader.Close();
    dataStream.Close();
    response.Close();
    */
  
    var request = (HttpWebRequest)WebRequest.Create("http://httpbin.org/post");

    var postData = "key1=" + Uri.EscapeDataString("val2");
    postData += "&key2=" + Uri.EscapeDataString("val2");
    var data = Encoding.ASCII.GetBytes(postData);

    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream()) {
      stream.Write(data, 0, data.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    Console.WriteLine(responseString);
  }
  
  public static void SampleGetRequest() {
    var request = (HttpWebRequest)WebRequest.Create("http://httpbin.org/get?amount=1000&currency=usd&source=token&description=TEST");
    request.Headers.Add("Authorization",
      "pjYWjP3dICR400v0Lt2iyE");
    request.ContentType = "application/x-www-form-urlencoded";
    request.Method = "GET";

    var response = (HttpWebResponse)request.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    Console.WriteLine(responseString);
  }

  public static void Main() { 
    Console.WriteLine("Making Sample POST Request\n");
    SamplePostRequest();
    Console.WriteLine("\n");

    Console.WriteLine("Making Sample GET Request\n");
    SampleGetRequest();
    Console.WriteLine("\n");

  } 
} 

Data Structure – Trie and Radix Tree

Trie

Tries are an extremely special and useful data-structure that are based on the prefix of a string. They are used to represent the “Retrieval” of data and thus the name Trie.

A Trie is a special data structure used to store strings that can be visualized like a graph. It consists of nodes and edges. Each node consists of at max 26 children and edges connect each parent node to its children. These 26 pointers are nothing but pointers for each of the 26 letters of the English alphabet A separate edge is maintained for every edge. Strings are stored in a top to bottom manner on the basis of their prefix in a trie. All prefixes of length 1 are stored at until level 1, all prefixes of length 2 are sorted at until level 2 and so on.

Here is a visual representation of the set of words [‘CAB’, ‘CAR’, ‘CAN’] stored in a Trie data structure. You traverse from root towards it’s child nodes until you reach the EOW (End of Word) marker that denotes that a word from the set.

But in real, the node that has multiple characters at a level has multiple characters within itself. ‘B’, ‘R’, ‘N’ have a common prefix ‘CA’. The characters ‘B’, ‘R’, ‘N’ are all children of ‘A’ and are stored in a single node. Each character points to a new node that can contain other children or EOW.

Strengths

  1. Sometimes Space-Efficient: If you’re storing lots of words that start with similar patterns, tries may reduce the overall storage cost by storing shared prefixes once.
  2. Efficient Prefix Queries: Tries can quickly answer queries about words with shared prefixes, like:
    • How many words start with “choco”?
    • What’s the most likely next letter in a word that starts with “strawber”?

Weaknesses

  1. Usually Space-Inefficient: Tries rarely save space when compared to storing strings in a set. ASCII characters in a string are one byte each. Each link between trie nodes is a pointer to an address—eight bytes on a 64-bit system. So, the overhead of linking nodes together often outweighs the savings from storing fewer characters.
  2. Not Standard: Most languages don’t come with a built-in trie implementation. You’ll need to implement one yourself.

Tries v/s Sets

Say you were implementing a spell checker. You’ll look for each word to see if it appears in Merriam-Webster’s dictionary.

You could put all the dictionary words in a trie. Or, you could put them in a set.

Both options have the same average-case lookup complexity: O(k), where kk is the number of characters in the lookup string:

  • For the trie, you’d have to walk from the root of the trie through kk nodes, one character at a time.
  • For the hash set, you have to compute a hash value from all kk characters of the string in order to index into the underlying array.
    So, if they have the same complexity, which one should you use?

Use a trie if you want to quickly find words starting with the same prefix. In our spell checker, this might be useful for suggesting corrections (i.e.: fixing “chocolatr” to “chocolate”). The only way to do this with a hash set would be to iterate through all the words, in O(n) time.

Use a hash set if you just need to check if a string is present or you’re optimizing for space. In most cases, a hash set will take up fewer bytes than a trie. And, hash set lookups will probably be faster than trie lookups—trie nodes can be scattered throughout memory, which isn’t cache friendly.

Radix Trees

A radix tree is like a trie, but it saves space by combining nodes together if they only have one child. Here’s what a radix tree with “Maria”, “Mariana”, and “David” looks like.

Radix trees are more cache friendly than tries, since the characters within a single node are usually stored in an array of characters, adjacent to each other in memory.

Implementing Trie data structure using Python

Before we begin with the code, here’s a visual representation of how the nodes for trie are joined together. Each letter in a node points to the memory location of the child node. The last nodes in the trie do not have any characters and the EOW is flagged as True.

Real time execution

class Node:
    def __init__(self):
        self.children = {}
        self.endOfWord = False

def insertWord(root, word):
  '''
  Loop through characters in a word and keep adding them at a new node, linking them together
  If char already in node, pass
  Increment the current to the child with the character
  After the characters in word are over, mark current as EOW
  '''
  current = root
  for char in word:
    if char in current.children.keys():
      pass
    else:
      current.children[char] = Node()
    current = current.children[char]
  current.endOfWord = True

def allWords(prefix, node, results):
  '''
  Recursively call the loop
  Prefix will be prefix + current character
  Node will be position of char's child
  results are passed by reference to keep storing result

  Eventually, when we reach EOW, the prefix will have all the chars from starting and will be the word that we need. We add this word to the result
  '''
  if node.endOfWord:
    results.append(prefix)
  for char in node.children.keys():
    #print char, node, node.children
    allWords(prefix + char, node.children[char], results)
  
def searchWord(root, word):
  '''
  Loop through chars of the word in the trie
    If char in word is not in trie.children(), return
    If char found, keep iterating
  After iteration for word is done, we should be at the end of word. If not, then word doesn't exist and we return false.
  '''
  current = root
  search_result = True
  for char in word:
    if char in current.children.keys():
      pass
    else:
      search_result = False
      break
    current = current.children[char]
  if not current.endOfWord:
    search_result = False
  return search_result

def getWordsWithPrefix(prefix, node, prefix_result):
  '''
  We loop through charcters in the prefix along with trie
  If mismatch, return
  If no mismatch during iteration, we have reached the end of prefix. Now we need to get words from current to end with the previx that we passed. So call allWords with prefix
  '''
  current = node
  for char in prefix:
    if char in current.children.keys():
      pass
    else:
      return
    current = current.children[char]
  allWords(prefix, current, prefix_result)

root = Node()
words = ['bed', 'ben']
words = ['bed', 'bedlam', 'bond', 'bomber', 'bombay']
for word in words:
  insertWord(root, word)

results = []
prefix = ''
allWords(prefix, root, results)
# prefix will be added to every word found in the result, so we start with ''
# results is empty, passed as reference so all results are stored in this list
print 'All words in trie: {}\n\n'.format(results)

search_word = 'bomb'
search_result = searchWord(root, search_word)
print 'Search {} in {}: {}'.format(search_word, words, search_result)

search_word = 'bomber'
search_result = searchWord(root, search_word)
print 'Search {} in {}: {}'.format(search_word, words, search_result)

prefix_result = []
prefix = 'be'
getWordsWithPrefix(prefix, root, prefix_result)
print '\n\nWords starting with {}: {}'.format(prefix, prefix_result)

Python Data Structures

List

A comma separated collection of elements, represented by square bracket []

  • list.index(element) – Finds the given element in a list and returns its position. If the same element is present more than once, index() method returns its smallest/first position.
  • list.append(item) – Adds a single item to the existing list.
  • list1.extend(list2) – Extends the list by adding all items of a list (passed as an argument) to the end, in-place.
  • list.insert(index, element) – Inserts an element to the list at a given index.
  • list.remove(element) – Searches for the given element in the list and removes the first matching element.
  • list.count(element) – Returns the number of occurrences of an element in a list.
  • list.pop(index) – Removes the item at the given index from the list. The method also returns the removed item.
  • list.reverse() – Reverses the elements of a given list, in-place.
  • list.sort(key=…, reverse=…) – Sorts the elements of a given list in a specific order – Ascending or Descending, in-place.
  • new_list = list.copy() – Returns a shallow copy of the list.
  • list.clear() – Removes all items from the list.

Tuple

A comma separated collection of elements, represented by round brackets (). A tuple is read only.

  • tuple.count(element) – Returns the number of occurrences of an element in a list.
  • tuple.index(element) – Finds the given element in a list and returns its position. If the same element is present more than once, index() method returns its smallest/first position.

Set

An unordered collection of items, represented by curly brackets {}. Every element is unique (no duplicates) and must be immutable (which cannot be changed). However, the set itself is mutable. We can add or remove items from it. And since set is unordered, you can’t do indexed operations on sets.

  • set.add(element) – Adds the element to the set.
  • set.discard(element) – Removes the element from the set.
  • set.clear() – Removes all items from the set.
  • set.union(set2) – Returns a new set containing all the distinct elements from both the sets. Using the ‘|’ operator between 2 sets is the same as writing set1.union(set2)
  • set.intersection(set2) – Returns a new set containing only the common elements from both the sets. The ‘&’ operator comes can also be used in this case.
  • set.difference(set2) – Returns a new set containing only the elements from the first set and not available from the second set. We can use ‘-‘ operator here.
  • Compare sets – We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets.
    set1 <= set2 is True if set1 is a subset of set2
    set1 >= set2 is True if set1 is a superset of set2

Dictionary

Python dictionary is an unordered collection of items that stores key-value pairs.

  • dict1.clear() – Removes all items from the dictionary.
  • dict1.copy() – Return a shallow copy of the dictionary.
  • dict.fromkeys(seq[,v]) or dict1.fromkeys(seq[,v]) – Return a new dictionary with keys from seq and value equal to v (defaults to None).
  • dict1.get(key) – Return the value of key. If key doesnot exit, return d (defaults to None).
  • dict1.items() – Returns the list of key-value pairs, with the individual pair returned as a tuple.
  • dict1.keys() – Returns the list of keys from the dictionary.
  • dict1.values() – Returns the list of values from the dictionary.
  • dict1.pop(key) – Removes the item with key and returns it’s value. Raises KeyError if key not found.

Tableau – Adding Subtotals

It wasn’t very intuitive to add Subtotals for columns. There’s an option in the Menu by navigating to Analysis > Totals > Add All Subtotals but that does it for all column hierarchy. Not if you only want totals for a particular sub-category.

e.g. The data that I have in a report is split into Quarters, Month and Product. By selecting Add All Subtotals in the Menu would add totals for products, month and quarters. As you can see below, there is a Totals of products for each month (what I wanted). But there is also Totals for each Quarter. And on the very end (not in the image), there is total for the entire Year. It’s just information that I don’t really need and is crowding my screen.

So, what’s the solution to only show Totals for both the products?

Click on the Month from the Columns and select Subtotals.

This would get you the totals for Product Lines in the month. It may happen that you see the numbers not as sum but percentage. To fix that, select a value in the Totals column. The right click and select Format. On the Fields, select the AGG field which relates to your sum. And you can change the Numbers column which is currently selected to “Percentage” and set it to “Number (Standard)”.

NetSuite – Generate new authentication tokens after Sandbox Refresh

About twice a year, we perform our NetSuite Sandbox refresh that would remove the User Token from the Sandbox and all the API integration would not work. As the instructions suggest and what we’ve followed all along is to create a new User Token under:

Home > Settings > Manage Access Tokens > New My Access Token

Select the existing Application and click on Save. This would give you a TOKEN ID and TOKEN SECRET. Of course, the one from below are random numbers and do not belong to an existing account.

TOKEN ID
abcd4a2449d1111111cb91904802222222274bd04011333333333f8bae612345
TOKEN SECRET
wxyz892aec811111111e0eeaca722222222910738f33333333333d78b5942b0d

But as of now, this doesn’t work. First you have to create a new Integration that would generate fresh Consumer Token and Secret. Then you have to link this Application and create a new User Token using this. A new Consumer Token can be created under:

Setup > Integration > Manage Integrations > New
Make sure to select “TOKEN-BASED AUTHENTICATION” on the form and after saving note down the CONSUMER KEY and CONSUMER SECRET generated by the system.

GIT command line help and setup with GitLab

While GitLab has a powerful user interface, if you want to use Git itself, you will have to do so from the command line. If you want to start using Git and GitLab together, make sure that you have created and/or signed into an account on GitLab.

Open a shell
Depending on your operating system, you will need to use a shell of your preference. Here are some suggestions:

Terminal on macOS
GitBash on Windows
Linux Terminal on Linux

Depending on your operating system, you will need to use a shell of your preference. Here are some suggestions:

Terminal on macOSWhile GitLab has a powerful user interface, if you want to use Git itself, you will have to do so from the command line. If you want to start using Git and GitLab together, make sure that you have created and/or signed into an account on GitLab.

Check if Git has already been installed
Git is usually preinstalled on Mac and Linux, so run the following command:

git --version

You should receive a message that tells you which Git version you have on your computer. If you don’t receive a “Git version” message, it means that you need to download Git.

After you are finished installing Git, open a new shell and type git –version again to verify that it was correctly installed.

Add your Git username and set your email
It is important to configure your Git username and email address, since every Git commit will use this information to identify you as the author.

In your shell, type the following command to add your username:

git config --global user.name "YOUR_USERNAME"

Then verify that you have the correct username:

git config --global user.name

To set your email address, type the following command:

git config --global user.email "your_email_address@example.com"

To verify that you entered your email correctly, type:

git config --global user.email

You’ll need to do this only once, since you are using the –global option. It tells Git to always use this information for anything you do on that system. If you want to override this with a different username or email address for specific projects, you can run the command without the –global option when you’re in that project.

Check your information
To view the information that you entered, along with other global options, type:

git config --global --list

Basic Git commands
Start using Git via the command line with the most basic commands as described below.

Initialize a local directory for Git version control
If you have an existing local directory that you want to initialize for version control, use the init command to instruct Git to begin tracking the directory:

git init

This creates a .git directory that contains the Git configuration files.

Once the directory has been initialized, you can add a remote repository and send changes to GitLab.com. You will also need to create a new project in GitLab for your Git repository.

Clone a repository
To start working locally on an existing remote repository, clone it with the command git clone <repository path>. By cloning a repository, you’ll download a copy of its files to your local computer, automatically preserving the Git connection with the remote repository.

You can either clone it via HTTPS or SSH. If you chose to clone it via HTTPS, you’ll have to enter your credentials every time you pull and push. With SSH, you enter your credentials only once.

You can find both paths (HTTPS and SSH) by navigating to your project’s landing page and clicking Clone. GitLab will prompt you with both paths, from which you can copy and paste in your command line.

As an example, consider this repository path:

HTTPS: https://gitlab.com/gitlab-org/gitlab-ce.git
SSH: git@gitlab.com:gitlab-org/gitlab-ce.git
To get started, open a terminal window in the directory you wish to clone the repository files into, and run one of the following commands.

Clone via HTTPS:

git clone https://gitlab.com/gitlab-org/gitlab-ce.git

Clone via SSH:

git clone git@gitlab.com:gitlab-org/gitlab-ce.git

Both commands will download a copy of the files in a folder named after the project’s name. You can then navigate to the directory and start working on it locally.

Switch to the master branch
You are always in a branch when working with Git. The main branch is the master branch, but you can use the same command to switch to a different branch by changing master to the branch name.

git checkout master

Download the latest changes in the project
To work on an up-to-date copy of the project (it is important to do this every time you start working on a project), you pull to get all the changes made by users since the last time you cloned or pulled the project. Use master for the <name-of-branch> to get the main branch code, or the branch name of the branch you are currently working in.

git pull REMOTE <name-of-branch>

When you first clone a repository, REMOTE is typically origin. This is where the repository was cloned from, and it indicates the SSH or HTTPS URL of the repository on the remote server. <name-of-branch> is usually master, but it may be any existing branch.

View your remote repositories
To view your remote repositories, type:

git remote -v

Add a remote repository
To add a link to a remote repository:

git remote add <source-name> <repository-path>

You’ll use this source name every time you push changes to GitLab.com, so use something easy to remember and type.

Create a branch
To create a new branch, to work from without affecting the master branch, type the following (spaces won’t be recognized in the branch name, so you will need to use a hyphen or underscore):

git checkout -b <name-of-branch>

Work on an existing branch
To switch to an existing branch, so you can work on it:

git checkout <name-of-branch>

View the changes you’ve made
It’s important to be aware of what’s happening and the status of your changes. When you add, change, or delete files/folders, Git knows about it. To check the status of your changes:

git status

View differences
To view the differences between your local, unstaged changes and the repository versions that you cloned or pulled, type:

git diff

Add and commit local changes
You’ll see any local changes in red when you type git status. These changes may be new, modified, or deleted files/folders. Use git add to first stage (prepare) a local file/folder for committing. Then use git commit to commit (save) the staged files:

git add <file-name OR folder-name>
git commit -m "COMMENT TO DESCRIBE THE INTENTION OF THE COMMIT"

Add all changes to commit
To add and commit (save) all local changes quickly:

git add .
git commit -m "COMMENT TO DESCRIBE THE INTENTION OF THE COMMIT"

Note: The . character typically means all in Git.

Send changes to GitLab.com or Remote GIT Repository
To push all local commits (saved changes) to the remote repository:

git push <remote> <name-of-branch>

For example, to push your local commits to the master branch of the origin remote:

git push origin master

Delete all changes in the branch
To delete all local changes in the branch that have not been added to the staging area, and leave unstaged files/folders, type:

git checkout .

Note that this removes changes to files, not the files themselves.

Unstage all changes that have been added to the staging area
To undo the most recently added, but not committed, changes to files/folders:

git reset .

Undo most recent commit
To undo the most recent commit, type:

git reset HEAD~1

This leaves the changed files and folders unstaged in your local repository.

Warning: A Git commit should not usually be reverse, particularly if you already pushed it to the remote repository. Although you can undo a commit, the best option is to avoid the situation altogether by working carefully.

Merge a branch with master branch
When you are ready to make all the changes in a branch a permanent addition to the master branch, you merge the two together:

git checkout <name-of-branch>
git merge master

GitBash on Windows
Linux Terminal on Linux

Check if Git has already been installed
Git is usually preinstalled on Mac and Linux, so run the following command:

git --version

You should receive a message that tells you which Git version you have on your computer. If you don’t receive a “Git version” message, it means that you need to download Git.

After you are finished installing Git, open a new shell and type git –version again to verify that it was correctly installed.

Add your Git username and set your email
It is important to configure your Git username and email address, since every Git commit will use this information to identify you as the author.

In your shell, type the following command to add your username:

git config --global user.name "YOUR_USERNAME"

Then verify that you have the correct username:

git config --global user.name

To set your email address, type the following command:

git config --global user.email "your_email_address@example.com"

To verify that you entered your email correctly, type:

git config --global user.email

You’ll need to do this only once, since you are using the –global option. It tells Git to always use this information for anything you do on that system. If you want to override this with a different username or email address for specific projects, you can run the command without the –global option when you’re in that project.

Check your information
To view the information that you entered, along with other global options, type:

git config --global --list

Basic Git commands
Start using Git via the command line with the most basic commands as described below.

Initialize a local directory for Git version control
If you have an existing local directory that you want to initialize for version control, use the init command to instruct Git to begin tracking the directory:

git init

This creates a .git directory that contains the Git configuration files.

Once the directory has been initialized, you can add a remote repository and send changes to GitLab.com. You will also need to create a new project in GitLab for your Git repository.

Clone a repository
To start working locally on an existing remote repository, clone it with the command git clone &lg;repository path>. By cloning a repository, you’ll download a copy of its files to your local computer, automatically preserving the Git connection with the remote repository.

You can either clone it via HTTPS or SSH. If you chose to clone it via HTTPS, you’ll have to enter your credentials every time you pull and push. With SSH, you enter your credentials only once.

You can find both paths (HTTPS and SSH) by navigating to your project’s landing page and clicking Clone. GitLab will prompt you with both paths, from which you can copy and paste in your command line.

As an example, consider this repository path:

HTTPS: https://gitlab.com/gitlab-org/gitlab-ce.git
SSH: git@gitlab.com:gitlab-org/gitlab-ce.git
To get started, open a terminal window in the directory you wish to clone the repository files into, and run one of the following commands.

Clone via HTTPS:

git clone https://gitlab.com/gitlab-org/gitlab-ce.git

Clone via SSH:

git clone git@gitlab.com:gitlab-org/gitlab-ce.git

Both commands will download a copy of the files in a folder named after the project’s name. You can then navigate to the directory and start working on it locally.

Switch to the master branch
You are always in a branch when working with Git. The main branch is the master branch, but you can use the same command to switch to a different branch by changing master to the branch name.

git checkout master

Download the latest changes in the project
To work on an up-to-date copy of the project (it is important to do this every time you start working on a project), you pull to get all the changes made by users since the last time you cloned or pulled the project. Use master for the <name-of-branch> to get the main branch code, or the branch name of the branch you are currently working in.

git pull REMOTE <name-of-branch>

When you first clone a repository, REMOTE is typically origin. This is where the repository was cloned from, and it indicates the SSH or HTTPS URL of the repository on the remote server. <name-of-branch> is usually master, but it may be any existing branch.

View your remote repositories
To view your remote repositories, type:

git remote -v

Add a remote repository
To add a link to a remote repository:

git remote add <source-name> <repository-path>

You’ll use this source name every time you push changes to GitLab.com, so use something easy to remember and type.

Create a branch
To create a new branch, to work from without affecting the master branch, type the following (spaces won’t be recognized in the branch name, so you will need to use a hyphen or underscore):

git checkout -b <name-of-branch>

Work on an existing branch
To switch to an existing branch, so you can work on it:

git checkout <name-of-branch>

View the changes you’ve made
It’s important to be aware of what’s happening and the status of your changes. When you add, change, or delete files/folders, Git knows about it. To check the status of your changes:

git status

View differences
To view the differences between your local, unstaged changes and the repository versions that you cloned or pulled, type:

git diff

Add and commit local changes
You’ll see any local changes in red when you type git status. These changes may be new, modified, or deleted files/folders. Use git add to first stage (prepare) a local file/folder for committing. Then use git commit to commit (save) the staged files:

git add <file-name OR folder-name>
git commit -m "COMMENT TO DESCRIBE THE INTENTION OF THE COMMIT"

Add all changes to commit
To add and commit (save) all local changes quickly:

git add .
git commit -m "COMMENT TO DESCRIBE THE INTENTION OF THE COMMIT"

Note: The . character typically means all in Git.

Send changes to GitLab.com or Remote GIT Repository
To push all local commits (saved changes) to the remote repository:

git push <remote> <name-of-branch>

For example, to push your local commits to the master branch of the origin remote:

git push origin master

Delete all changes in the branch
To delete all local changes in the branch that have not been added to the staging area, and leave unstaged files/folders, type:

git checkout .

Note that this removes changes to files, not the files themselves.

Unstage all changes that have been added to the staging area
To undo the most recently added, but not committed, changes to files/folders:

git reset .

Undo most recent commit
To undo the most recent commit, type:

git reset HEAD~1

This leaves the changed files and folders unstaged in your local repository.

Warning: A Git commit should not usually be reverse, particularly if you already pushed it to the remote repository. Although you can undo a commit, the best option is to avoid the situation altogether by working carefully.

Merge a branch with master branch
When you are ready to make all the changes in a branch a permanent addition to the master branch, you merge the two together:

git checkout <name-of-branch>
git merge master

Dynamic Programming – MultiStage Graph

The multistage graph problem is to find a minimum cost from a source to a sink. A multistage graph is a directed graph having a number of multiple stages. The goal is to find the shortest distance from source to sink.

  • The vertices have numbers that correspond to the rows and columns of matrix that will represent our graph.
  • The number on the directed edge denotes the weight/distance between the two vertices.

Here’s a sample set of data that we are using for this particular problem. You can create your own graphs and images using https://csacademy.com/app/graph_editor/

The idea is to start from the sink and go backwards to the source. As we go, we need to compute the distance from the vertex to the sink. The weights on the vertices will represent the distance to the sink.

  • The sink vertex V6 will have a weight of 0.
  • V5 will have a weight of 2 and V4 will have a weight of 5.
  • When we get to Vertex 3, we need to have weight of V2 computed before we can get the weight of V3.
  • V2 will have a weight of (2+6) = 8.
  • Coming back to V3. So far with V2, V4, V5 we’ve seen just one outgoing edge so it was easy to compute the weight of the vertex. Multiple outgoing edges mean multiple routes to get to the sink. The weight of the vertex will therefore be the minimum value of all the possible outgoing routes. Therefore, V3 will be min(V3-V4, V3-V5, V3-V2) which is min(12, 14, 12) and hence weight of V3 will be 12
  • V1 will have a weight of 12
  • V0 will have a weight of min(15, 14, 16), i.e. 14

Below is the python code to solve the problem.
Real time execution

import sys

INF = 999 # Or you could use sys.maxint

'''
Sample graph with 7 vertices
Each vertex of the graph is represented using a row
Value in a row implying that vertex i has a edge to vertex with index j with the cost represented in the graph 
'''
graph = [
          [0,3,8,2,0,0,0,],  #Vertex 0
          [0,0,0,5,7,0,0,],  #Vertex 1
          [0,0,0,0,0,6,0,],  #Vertex 2
          [0,0,4,0,7,12,0,], #Vertex 3
          [0,0,0,0,0,0,5,],  #Vertex 4
          [0,0,0,0,0,0,2,],  #Vertex 5
          [0,0,0,0,0,0,0,],  #Vertex 6
        ]

# Initialize vertex costs with Infinity. Leave the sink vertex to 0
vertex_cost = [INF] * 6 + [0,]
print 'Initialized vertex cost:{}\n'.format(vertex_cost)

def getVertexCost(i):
  '''Get vertex cost for vertex i'''
  other_nodes = graph[i]
  min_cost = vertex_cost[i]
  '''
  Using memoization, if the value exists in the array and is already 
  less than INF then return the value. Otherwise your min_cost stays 
  initialized at INF
  '''
  if min_cost < INF:
    return min_cost
  '''
  Loop through all routes from i to j
  The route that has minimum cost will be chosen
  '''
  for j in range(0,len(other_nodes)):
    # j represents vertex connected to i
    if other_nodes[j]:
      # Compute cost to other node in a recursive mannger
      # Cost to j = Weight of vertex(i,j) + Cost from j to Sink
      cost_j = graph[i][j] + getVertexCost(j)
      if cost_j < min_cost:
        min_cost = cost_j
  return min_cost

def main():
  for i in sorted(range(0,len(graph)-1), reverse=True):
    vertex_cost[i] = getVertexCost(i)
    print 'Cost of vertex {} is {}'.format(i, vertex_cost[i])

  print '\nComputed vertex cost: {}'.format(vertex_cost)
  print '\nMin cost of traversal is the cost of start vertex, i.e. : {}'.format(vertex_cost[0])
  
if __name__ == '__main__':
  main()

Django – Load fixture for a specific app

I just modified a fixture to load some data into the database. But running loaddata gave me errors from another fixture that I didn’t modify or intended to load. So I found this way of loading fixture for only a specific app. This is for Django version 1.8. Before that, running migrate would load all the fixtures in the database. This approach is cleaner because loading data from a fixture truncates the table and re-loads all the data once again.

python manage.py loaddata --app customer initial_data.json

With Django 1.9, the initial_data fixtures have been deprecated and you have to use migrations instead.