Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Code Snippets

 

November 25, 2018

Code Snippets

 

November 25, 2018

AWS – Elastic Container Service(ECS)

ECS with AWS CLI

Get list of clusters within ECS

aws ecs list-clusters --profile {profile-name}

// output
{
    "clusterArns": [
        "arn:aws:ecs:us-east-1:123456789:cluster/server-api",
        "arn:aws:ecs:us-east-1:123456789:cluster/server-web"
    ]
}

 

Get list of services within a cluster

aws ecs list-services --cluster server-api --profile {profile-name}

//output
{
    "serviceArns": [
        "arn:aws:ecs:us-east-1:12345679:service/server-api-service"
    ]
}

Build docker and push image to ECR

# authenticate to ECR
aws ecr get-login-password --region us-east-1 --profile folau | docker login --username AWS --password-stdin {account-num}.dkr.ecr.us-east-1.amazonaws.com

# build image
docker build -t backend-api .

# tag
docker tag backend-api:latest {account-num}.dkr.ecr.us-east-1.amazonaws.com/backend-api:latest

# push imge to ECR
docker push {account-num}.dkr.ecr.us-east-1.amazonaws.com/backend-api:latest

Build docker, push image to ECR, and deploy image to ECS Fargate

#!/bin/sh

# us-east-1
aws ecr get-login-password --region us-east-1 --profile {aws-profile} | docker login --username AWS --password-stdin {aws-account-number}.dkr.ecr.{aws-region}.amazonaws.com

docker build -t {project-name} .

docker tag {project-name}:latest {aws-account-number}.dkr.ecr.{aws-region}.amazonaws.com/{ecr-repository}:latest

docker push {aws-account-number}.dkr.ecr.{aws-region}.amazonaws.com/{ecr-repository}:latest

# task-definition with no version will use the lastest version
aws ecs update-service \
--cluster {cluster-name} \
--service {service-name} \
--task-definition {task-def-name} \
--force-new-deployment \
--profile {profileName}

# Example
#!/bin/sh

aws ecr get-login-password --region us-east-1 --profile folau | docker login --username AWS --password-stdin 1231231231.dkr.ecr.us-east-1.amazonaws.com

docker build -t backend-api .

docker tag backend-api:latest 1231231231.dkr.ecr.us-east-1.amazonaws.com/backend-api:latest

docker push 1231231231.dkr.ecr.us-east-1.amazonaws.com/backend-api:latest

aws ecs update-service \
--cluster backend-api \
--service backend-api \
--task-definition backend-api \
--force-new-deployment \
--profile folau

Update desired count

aws ecs update-service --cluster backend-api --service backend-api --task-definition backend-api \ 
--desired-count 0 \ 
--profile folau

 

October 30, 2018

Stack

Stack is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack and the only element that can be removed is the element that is at the top of the stack, just like a pile of objects.

A stack, under the hood, is an ordered list in which insertion and deletion are done only at the top. The last element inserted is the first one to be deleted. Hence, it is called the Last in First out (LIFO) or First in Last out (FILO) list.

A pile of plates in a cafeteria is a good example of a stack. The plates are added to the stack as they are cleaned and they are placed on the top. When a plate, is required it is taken from the top of the stack. The first plate placed on the stack is the last one to be used.

Special names are given to the two changes that can be made to a stack. When an element is inserted in a stack, the concept is called push, and when an element is removed from the stack, the concept is called pop. Trying to pop out an empty stack is called underflow and trying to push an element in a full stack is called overflow.

There are some basic operations that allow us to perform different actions on a stack.

  • Push: Add an element to the top of a stack
  • Pop: Remove an element from the top of a stack
  • IsEmpty: Check if the stack is empty
  • Peek: Get the value of the top element without removing it

Basic features of Stack

  1. Stack is an ordered list of similar data type.
  2. Stack is a LIFO(Last in First out) structure or we can say FILO(First in Last out).
  3. push() function is used to insert new elements into the Stack and pop() function is used to remove an element from the stack. Both insertion and removal are allowed at only one end of Stack called Top.
  4. Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty.

Applications of Stack

  1. Expression Evaluation. Stack is used to evaluate prefix, postfix and infix expressions.
  2. Expression Conversion. An expression can be represented in prefix, postfix or infix notation. Stack can be used to convert one form of expression to another.
  3. Syntax Parsing. Many compilers use a stack for parsing the syntax of expressions, program blocks etc. before translating into low level code.As many of the Programming Languages are context-free languages. So, Stack is also heavily used for Syntax Parsing by most of the Compilers.
  4. Backtracking. Suppose we are finding a path for solving maze problem. We choose a path and after following it we realize that it is wrong. Now we need to go back to the beginning of the path to start with new path. This can be done with the help of stack.Backtracking is a recursive algorithm which is used for solving the optimization problem.So, In order to find the optimized solution of a problem with Backtracking, we have to find each and every possible solution of the problem, doesn’t matter if it is correct or not.In Backtracking, while finding the every possible solution of a problem, we store the solution of a previously calculated problem in Stack and use that solution to solve the upcoming problems.
  5. Parenthesis Checking. Stack is used to check the proper opening and closing of parenthesis.In Programming, we make use of different type of parenthesis, like – (, ), {, }, which are used for opening and closing a block of code.So, these parenthesis get stored in Stack and control the flow of our program.
  6. Function call. Stack is used to keep information about the active functions or subroutines.In Programming, whenever you make a call from one function to the another function. The address of the calling function gets stored in the Stack.So, when the called function gets terminated. The program control move back to the calling function with the help of the address which was stored in the Stack.So, Stack plays the main role when it comes to Calling a Function from other Function.

  7. String reversal. Stack is used to reverse a string. We push the characters of string one by one into stack and then pop character from stack.String Reversal is another amazing Application of Stack. Here, one by one each character of the Stack get inserted into the Stack.So, the first character of the Stack is on the bottom of the Stack and the last character of the String is on the Top of the Stack.After performing the pop operation in Stack, we get the String in Reverse order.
  8. Memory management. Memory Management is the important function of the Operating System. Stack also plays the main role when it comes to Memory Management.
@Data
@NoArgsConstructor
public class MyStack<E> {

    private LinkedList<E> list = new LinkedList<>();

    public E push(E item) {
        list.addFirst(item);
        return item;
    }

    public E pop() {
        if (list.size() <= 0) {
            throw new EmptyStackException();
        }
        return list.remove();
    }

    public int getSize() {
        return list.size();
    }

    public E peek() {
        if (list.size() <= 0) {
            throw new EmptyStackException();
        }
        return list.getFirst();
    }

    public void print() {

        int size = getSize();
        int count = 1;
        
        if (count >= size) {
            return;
        }

        E item = list.getFirst();

        while (item != null) {

            System.out.println(item.toString());

            if (count >= size) {
                break;
            }

            item = list.get(count);

            count++;
        }
    }
}

Source code on Github

October 29, 2018

Javascript Module

JavaScript programs start off pretty small almost every time. Not until your project grows and grows so large that your scripts may start to look like spaghetti code. At this point, your code has to be broken down into separate modules that can be imported where needed.

The good news is that modern browsers have started to support module functionality natively, and this is what this article is all about. This can only be a good thing — browsers can optimize loading of modules, making it more efficient than having to use a library and do all of that extra client-side processing and extra round trips.

 

Export

The first thing you do to get access to module features is export them. This is done using the export statement. The easiest way to use it is to place it in front of any items you want exported out of the module. A more convenient way of exporting all the items you want to export is to use a single export statement at the end of your module file.

You can export functions, var, let, const, and classes. They need to be top-level items; you can’t use export inside a function

class User{
    //private fields are declared with #
    #name;
    constructor(name) {
        this.name = name;
    }

    getName(){
        return this.name;
    }

}

function sayHi(name) {
    return `Hello, ${name}!`;
}

let folau = {

    name: "Folau",

    getName(){
        return this.name;
    }
}

/**
 * export class User {...} -> import {User} from ..
 * export default class User {...} -> import User from ...
 */
// export has to be in the same order as import
// Named exports are explicit. They exactly name what they import, so we have that information from them; that’s a good thing.
export {User, sayHi, folau};

 

Import

Once you’ve exported some features out of your module, you need to import them into your script to be able to use them.

You use the import statement, followed by a comma-separated list of the features you want to import wrapped in curly braces, followed by the keyword from, followed by the path to the module file — a path relative to the site root. we are using the dot (.) syntax to mean “the current location”, followed by the path beyond that to the file we are trying to find. This is much better than writing out the entire relative path each time, as it is shorter, and it makes the URL portable — the example will still work if you move it to a different location in the site hierarchy.

<script type="module">
    // import has to be in the same order as export
    // Named exports are explicit. They exactly name what they import, so we have that information from them; that’s a good thing.
    import {User, sayHi, folau} from './module.js';

    console.log("Module");
   
    let greeting = sayHi("Folau");

    console.log(greeting);// Hello, Folau

    console.log("name: ", folau.getName());// Folau

    let lisa = new User("Lisa");
    console.log("name: ", lisa.getName());// Lisa
</script>

 

Source code on Github

October 28, 2018