Data Warehousing, BI and Data Science

2 December 2020

Python: Function, Lambda, Map, Filter, Reduce

Filed under: Data Warehousing — Vincent Rainardi @ 6:43 am

A function with 2 arguments:

def f(a,b):
    c = a * b
    return c
print(f(2,3))
Output: 6

Recursive function:

def factorial(n):
    if n>1: return n*factorial(n-1)
    else: return n
print(factorial(3))
Output: 6

Star argument means I don’t know how many arguments. The argument is stored as a tuple.

def total(*args):
    return(sum(args))
print(total(1,2,3))
Output: 6
def proper_case(a):
    return " ".join([word[0].upper() + word[1:] for word in a.split()])
print(proper_case("going to town"))
Output: Going To Town

Lambda is a shortcut to create a function on the fly.

f = lambda a,b: a*b
print(f(2,3))
Output: 6

Use map to pair a function to a list (to run the function to every element in the list)
Use filter to apply a condition to a list, to look for elements which satisfy that condition.
Use reduce to apply a function to a pair of values each time, repeatedly (reduce is in functools library)

# Using map and lambda to find words beginning with a
L= ['Apple', 'Andy', 'Banana', 'Ben']
list(map(lambda x: 1 if x[0].lower() == 'a' else 0, L))
Output: [1, 1, 0, 0]
# Using map and lambda to produce cube numbers
input_list = [1,2,3]
list(map(lambda x: x**3, input_list))
Output: [1, 8, 27]
# Using map to pair 2 lists
def v_add(x,y): return(x+y)
list1 = [1,2,3] #Argument1 is a list
list2 = (4,5,6) #Argument2 is a tuple
print(list(map(v_add, list1, list2))) #We pass 2 arguments to map
Output: [5, 7, 9]
# Using map to pair 2 lists
L1 = ['P','O']
L2 = ['X','Y']
list(map(lambda x,y: x + ' ' + y, L1, L2))
Output: ['P X', 'O Y']
# Using filter to find the even numbers 
f = lambda x:  x%2 == 0
L = [1,2,3,4,5,6]
list(filter(f, L))
Output: [2, 4, 6]

# Now using lambda
list(filter(lambda x: x % 2 == 0, L))
Output: [2, 4, 6]
# Using filter to find the words that starts with a and ends with y
L = ['Apple', 'Andy', 'Banana', 'Ben']
list(filter(lambda x: x[0].lower()=='a' and x[-1].lower()=='y', L))
Output: ['Andy']
# Using reduce to sum the input
from functools import reduce
def v_add(x,y): return(x+y) 
reduce(v_add, range(1,4))
Output: 6

# Now using lambda
reduce(lambda x, y: x+y, range(1,4))
Output: 6
# Using reduce to find the largest number
L = [22,45,32,20,87,94,30]
def v_max(x,y):
    if x>y: return x
    else: return y
#or v_max = lambda x,y: x if x>y else y
reduce(v_max,L)
# Using reduce to concatenate letters
L = ['A','B','C']
v_concat = lambda x,y: x+y
reduce(v_concat, L)
Output: 'ABC'
# Using reduce to calculate 1 x 2 x 3 x 4 x ...
def f(x,y): return(x*y)
n = 4
L = list(range(1,n+1))
print(1 if n == 0 else reduce(f,L))
Output: 24

1 December 2020

Python: List comprehension

Filed under: Data Warehousing — Vincent Rainardi @ 7:05 am

List comprehension means using for loop to create a list :

L = [i*2 for i in range(1,5)] #5 not included
print(L)
Output: [2,4,6,8]

We can use 2 for loops to get the words in a paragraph :

paragraph = ["This is sentence one." , 'This is sentence two.']
result  = [word for sentence in paragraph for word in sentence.split()]
print(result)
Output:
['This', 'is', 'sentence', 'one', 'This', 'is', 'sentence', 'two']

We can use 2 for loops and an if to get words beginning with certain letters :
(the example below is using the paragraph defined above)

letters = ['s','o']
result = [word for sentence in paragraph for word in sentence.split() if word[0].lower() in letters]
print(result)
Output:
['sentence', 'one.', 'sentence']

We can use an if with any conditions we like :

numbers = [100,200,300,400]
result = [n for n in numbers if n > 200]
print(result)
Output:
[300,400]

We can make a list using double for in i and j format like this:

product_list = [ i*j for i in range(1,3) for j in range(10,20,5) ] #3 and 20 are not included
print(product_list)
Output:
[10, 15, 20, 30]

We can make a dictionary too using for :

result = {i:i*3 for i in range(1,7,2)}
print(result)
Output:
{1: 3, 3: 9, 5: 15}

We can use for to access the key in a dictionary.
In this example I try to get the best Hogwart pupils in a dictionary (highest remarks):

Hogwarts = {1:['Harry',80] , 2:['Ron',70], 3:['Hermione',90], 4:['Neville',60], 5:['Seamus',50]}
best_pupils = {key:value[0] for key,value in students_data.items() if value[1] >= 70}
print(best_pupils)
Output:
{1: 'Harry', 2: 'Ron', 3: 'Hermione'}

Various examples of creating lists and dictionary using for :

#times 2 if i is divisible by 3, otherwise plus 2
result = [i*2 if i%3==0 else i+2 for i in range(1,7)]
print(result)
Output: 
[3, 4, 6, 6, 7, 12]

#create a dictionary containing cube numbers from 1 to 4
n = 4
result = {i:i**3 for i in range(1,n+1)}
print(result)
Output: 
{1: 1, 2: 8, 3: 27, 4: 64}

#A list containing combinations of letters from 2 words
result = [i+j for i in "po" for j in "he"]
print(result)
Output: 
['ph', 'pe', 'oh', 'oe']

#Create a dictionary from a word. The key is in upper case, the value is double letter.
result = {x.upper(): x*2 for x in 'potter'}
print(result)
Output: 
{'P': 'pp', 'O': 'oo', 'T': 'tt', 'E': 'ee', 'R': 'rr'}

Python: If and For

Filed under: Data Warehousing — Vincent Rainardi @ 6:11 am

if-elif-else ends with : and the next line must be indented (can be on the same line though).
Equal is ==, non equal is !=.
Use and, or to combine conditions.

a = 1
if a == 0: print("A") 
elif a != 1: print("B")
elif 4 > a == 8: print("C")
else: print("D")
Output: D
a,b = 5,6
if a==5 and b==7: print("A") 
else: print("B")
if a==5 or b==6: print("A")
else: print("B")
Output:
B
A

for can be used with rangestringlisttupledictionaries or enumerate.
range(a,b,c) means from a to b step c but does not include b.

for i in range(1,5,2): print(i)
Output:
1
3
for i in reversed(range(1,5,2)): print(i)
Output:
3
1

in can be used with a list (without range) like this:

for i in "abc": print(i)
for i in [1,4,2]: print(i)
for i in (1,4,2): print(i)

in can be used with a dictionary like this:

for i,j in {"name":"Harry","age":11}.items(): print(i,j)
Output:
name Harry
age 11

D = {1:["Harry", 11], 2:["Ron", 11], 3:["Hermione", 10]}
for i,j in D.items(): print(i,j)
Output
1 ["Harry", 11]
2 ["Ron", 11]
3 ["Hermione", 10]

for(i,j) can use with enumerate to get the counter in i, like this:

for i,j in enumerate("abc"): print(j, i)
Output:
a 0
b 1
c 2

In for loop we can use break, continue, pass :

a = ''
b = 'abcdef'
for i in range(0,6):
  a += b[i]
  if i == 2: break #pass or continue
print(a)
Output: abc

Use zip to loop around 2 lists together :

list1,list2 = [1,2,3],[10,20,30]
for i,j in zip(list1,list2): print('{0}  {1}'.format(i,j))
Output:
1  10
2  20
3  30

We can use while to make a loop too :

i = 0
while i <= 3:
    print(i)
    i += 1
Output:
0
1
2
3

Use add to append to the range used in the for loop.
Note: add doesn’t output anything.

a = {1, 2}
for i in range(3,5): #5 is not included
    print(a.add(i)) #add doesn't output anything
print(a)
Output:
None
None
{1, 2, 3, 4}

Combining for, if, modulo and pass:

for i in range(1,4): #4 is not included
    if (i % 2 == 0): #modulo means "the reminder"
        print(str(i) + " is divisible by 2")
        pass #after printing 2, continue with 2 (stay in the loop)
    print(str(i) + " is not divisible by 2")
Output:
1 is not divisible by 2
2 is divisible by 2
2 is not divisible by 2
3 is not divisible by 2

27 November 2020

Python: List, Tuple, Dictionary, Set

Filed under: Data Warehousing — Vincent Rainardi @ 4:54 am

List: Use append function to add an element.
Use pop and remove functions to remove an element.

a = ['A','B',1,2]
print(a)
Output: ['A', 'B', 1, 2]

a.pop()
print(a)
Output: ['A', 'B', 1]

a.append('C')
print(a)
Output: ['A', 'B', 1, 'C']

a.remove('B')
print(a)
Output: ['A', 1, 'C']

List operators: * and +
Functions: len, max, sorted, index

print(a*2)
Output: ['A', 1, 'C', 'A', 1, 'C']

print(a+a)
Output: ['A', 1, 'C', 'A', 1, 'C']

a = [2,3,5,1]
print(len(a), max(a), sorted(a), a[0:3], a.index(5))
Output: 4 5 [1, 2, 3, 5] [2, 3, 5] 2

b = [[1,2],[3,4],[5,6]]
print(b[1], '|', b[0][1])
Output: [3, 4] | 2

a[n][m] means list n, element m
a[n:m] means list n to list m-1

a = [[1,2,3],[4,5,6],[7,8,9]]
print(a[0][0])
Output: 1

print(a[:])
Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(a[0:1]) 
Output: [[1, 2, 3]]

print(a[0:2]) 
Output: [[1, 2, 3], [4, 5, 6]]

print(a[1:3]) 
Output: [[4, 5, 6], [7, 8, 9]]

a = [1,2]
b = [3,4]
a.extend(b)
print(a)
Output: [1, 2, 3, 4]

a.insert(3,1)
print(a, a.count(1))
Output: [1, 2, 3, 1, 4] 2

Tuple is like a list but once created it can’t be changed.

a = ("A", 1, "B", 2)
print(a, a[1])
Output: ('A', 1, 'B', 2) 1

b = list(a)
print(b)
Output: ['A', 1, 'B', 2]

c = tuple(b)
print(c)
Output: ('A', 1, 'B', 2)

d = ([1,2],"A")
print(d)
Output: ([1, 2], 'A')

Dictionary uses labels instead of index.
To get the value of a key which may not exist, use get.
To add a key value pair, use =.
We can convert a dictionary to a list. Use values() to get the values, keys() to get the keys.
We can use dict to create a dictionary.
Use update to add a key value pair and del to remove a key value pair.

a = {'Name': 'Harry', 'Age': 11}
print(a, a['Name'])
Output: {'Name': 'Harry', 'Age': 11} Harry

Name = a.get('Name')
City = a.get('City','N/A')
print(Name, City)
Output: Harry N/A

a['City'] = 'London'
print(a)
Output: {'Name': 'Harry', 'Age': 11, 'City': 'London'}

print(list(a.values()), list(a.keys()), 'Harry' in list(a.values()))
Output: ['Harry', 11, 'London'] ['Name', 'Age', 'City'] True

a = dict(Name = 'Harry', Age = 11)
a.update({'City':'London'})
print(a, len(a))
Output: {'Name': 'Harry', 'Age': 11, 'City': 'London'} 3

del (a['City'])
print(a, len(a))
Output: {'Name': 'Harry', 'Age': 11} 2

a = {1: ['Harry',11], 2:['Ron',10]}
print(a)
Output: {1: ['Harry', 11], 2: ['Ron', 10]}

Using set we can do Venn diagram operations such as union, intersection and difference

a = [1,2,2,3,1]
b = set(a)
c = {3,4}
print(a,b,c)
Output: [1, 2, 2, 3, 1] {1, 2, 3} {3, 4}

print(b.union(c), b.intersection(c), b.difference(c), b.symmetric_difference(c))
Output: {1, 2, 3, 4} {3} {1, 2} {1, 2, 4}

a = [1,2,3,4]
print(a[-1])
Output: 4

S = "I love Python"
print(S[2:6], S[-11:-7])
Output: love love

L = [1,2,3]
print(L*2)
Output: [1, 2, 3, 1, 2, 3]

L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2:])
Output: [[7, 8, 9, 10]]

C = [2, 5, 9, 12, 13, 15, 16, 17, 18, 19]
F = [2, 4, 5, 6, 7, 9, 13, 16]
H = [1, 2, 5, 9, 10, 11, 12, 13, 15]
print(sorted(set(C) & set(F) & set(H)))
Output: [2, 5, 9, 13]

print(sorted(set(C) & set(F) - set(H)))
Output: [16]

d = C + F + H
print(d)
Output: [2, 5, 9, 12, 13, 15, 16, 17, 18, 19, 2, 4, 5, 6, 7, 9, 13, 16, 1, 2, 5, 9, 10, 11, 12, 13, 15]

L = []
for i in d:
    if d.count(i) == 2: L.append(i)
print(sorted(list(set(L))))
Output: [12, 15, 16]

L = []
for i in range(1,21):
    if d.count(i) == 0: L.append(i)
print(sorted(list(set(L))))
Output: [3, 8, 14, 20]

Python: String and Array

Filed under: Data Warehousing — Vincent Rainardi @ 4:23 am

To remove spaces from the left or right, use strip, lstrip and rstrip functions.

Example: a = " Test%%"
print(a.lstrip().rstrip("%"), a.strip("%").strip())
Output: Test Test

To remove all spaces (including in the middle) use the replace function.

Example: b = " %Te st %% A"
print(b.replace(" ","").replace("%",""))
Output: TestA

To split string use the split function.

Example: c = "A,B,C"
d = c.split(",")
print(d, d[1])
Output: ['A', 'B', 'C'] B

To join strings use the join function.

Example: e = " & ".join(d)
print(e)"
Output: A & B & C

To declare and initialise 3 variables at the same time use commas:

Example: a,b,c = "A", "B", "C"

To get a portion of the string use [a:b:c], which means from position a to position b, skipping c characters (a or b or c can be omitted).
Note: including b (b is included).
A negative index means counting from the right. The right most character is -1.

Example: a = "0123456789"
print(a[0:4], a[1:7:2], a[-2])
Output: 0123 135 8

Example: print(a[:5], a[:], a[::3])
Output: 01234 0123456789 0369

Example: a = "I love Python programming"
print(a[7:13], a[-18:-12], len(a))
Output: Python Python 25

Arithmetic operators are +, -, /, %, **, //
(the last 3 are modulo, power, floor division)

Example: a,b = 5,2
print(a%b, a**b, a//b)
Output: 1 25 2

Comparison operators are >, <, ==, !=

Example: print(a>b, a<b, a==b, a!=b)
Output: True False False True

The print function accepts parameters.

Example: a,b = "A","B"
print("{0} test {1}".format(a,b))
Output: A test B

To concatenate 2 strings use the + operator.

Example: print(a + " & " + b, "Line1\nLine2")
Output: A & B Line1
Line2

To print a double quote, enclose the string with a single quote.
Or escape it with a backslash.

Example: print('a"b', "a\"b")
Output: a"b  a"b

To print a single quote, inclose the string with a double quote.
Or escape it with a backslash.

Example: print("a'b", 'a\'b')
Output: a'b   a'b

To change line use \n.
If we use r (means raw string), \n doesn’t have an affect.

Example: print(r"a\n")
Output:  a\n

Set means distinct members.

Example: a = set('aba')
print(a)
Output: {'a', 'b'}

Set operations are -,|,&,^.

  • a-b: in a but not in b.
  • a|b: in a or b or both.
  • a&b: in both a and b.
  • a^b: in a or b but not both.
Example: a,b = set('ab'), set('ac')
print(a-b, a|b, a&b, a^b)
Output: {'b'} {'a', 'b', 'c'} {'a'} {'b', 'c'}

8 November 2020

Day Measures

Filed under: Data Warehousing — Vincent Rainardi @ 3:04 am

Sometimes the measures we want to store is the number of days. For example:

  • the number of days from when we received an order until we shipped it
  • the number of days from when a booking was made until the engineer visited
  • the number of days from today until a bond matures
  • the number of days since the policy was incepted (began) until today

I call these measures Day Measures.
When a day measure is “from today” or “until today”, then the measure changes everyday.
For example: the maturity of a bond is the number of years from today until a bond matures. If the bond matures in 31st December 2030, and today is 9th Nov 2020, then the maturity is 10.1451 years (10 + 52/365.25).
Tomorrow it is 10.1396. The maturity of a bond is important because the bigger the maturity, the higher the risk that the bond value can be impacted by the interest rate.

Days to shipment (the number of days from when the order is received until shipment) does not change if it was a last year order. But if the order was placed yesterday and it usually takes about 3 weeks for us to fulfill an order, then in the next 3 weeks the “days to shipment” changes every day.

If we have a daily periodic snapshot fact table, and we have a day measure in this fact table, then we need to calculate this measures every day.

The question is: is that right?
Couldn’t we just store the maturity date of the bond, rather than calculating the Maturity daily?
Couldn’t we just store the shipment date and the order date, rather than calculating “days to shipment” daily?

We can and we should. But “in addition to” not “instead of”.
It would be silly to store just the date because everytime we want to use it we need to calculate it. The point of having a data warehouse is not to save storage, but to make it easy to use. Easy to query.
When we calculate the Maturity or Days To Shipment, we don’t need to calculate anything. It is there ready for us to use.

So yes it is worth calculating Days Measures every day, and store them in the daily periodic snapshot fact table.

11 September 2020

Copy Paste Anchor Links (Page Jumps) from Microsoft Word to WordPress

Filed under: Data Warehousing — Vincent Rainardi @ 6:57 am

Problem: when copy-pasting a Word document to WordPress, hyperlinks are preserved but bookmarks are gone.

Solution:

  1. In Microsoft Word create them as hyperlinks
  2. Paste it to WordPress
  3. Change the hyperlinks to anchor links using Notepad
  4. Paste back to WordPress

Step by step:

Step 1. In Microsoft Word, create them as hyperlinks

  • In a blank Microsoft Word document, create this:

Both of the “Section 1” are normal hypelinks, with text = “Section1” (no space), address = “#section1” (no space with # prefix) like this:

  • Highlight it, control-K (Insert Hyperlink), type Address = #Section 1 (notice the hash in the front).
  • Create Section 2 and Section 3 the same way.

Step 2. Copy to WordPress

  • Control-A (select all)
  • Copy paste to WordPress visual editor.

Step 3. Replace the hyperlinks to anchor links in Notepad

  • Control-Shift-Alt-M (switch to Code Editor)
  • Control-A (select all)
  • Paste to Notepad (Notepad++ is better)
  • Control-H (replace), replace href with name, and remove the # as follows:
    find what: <a href=”#, replace with: <a name=”

Step 4. Paste back to WordPress

  • Control-A and paste back to WordPress code editor.
  • Click Update on the top right corner
  • View the page and test the hyperlink

10 September 2020

Turtle

Filed under: Data Warehousing — Vincent Rainardi @ 5:07 am

My son asked me to show graphics in programming and I thought it would be a good idea to show Turtle. In Python of course, as it is the most popular programming language, serving all kinds of communities not just AI. Turtle is a simple way to draw lines and circles. And it’s already built in Python, i.e. you don’t need to install anything.

To start with just type “import turtle”. This is to import the turtle library into python environment.

Then type “t = turtle.Turtle()”. This is to create a variable t so that we don’t have to type turtle.Turtle many many times. It opens a window like this with an arrow facing to the right. That arrow is the cursor. That window is our canvas, where we make our drawing.

To draw a line, type “t.forward(50)”. This is to move the arrow 50 pixel forward (to the right).

To change the same of the cursor, type “t.shape(“turtle”)”:

To draw a circle, type “t.circle(50)”:

To turn the turtle to the right 90 degrees, type “t.right(90)”:

And you can do “t.forward(50)” to draw a line again:

To lift the pen up so it won’t make any line, type “t.penup()”. Now we can move the turtle without drawing anything, for example: “t.setposition(0,-50)” like this:

(0,0) is where we began. It’s x,y so 0,-50 means the x is 0 and the y is -50 (50 down).

50,0 means x = 50 and y = 0, like below:

Remember that our pen is still up at the moment. To start drawing again, let’s put the pen down by typing “t.pendown()”. We can draw a circle again: “t.circle(25)”, like below left:

To undo what we did last, type “t.undo()”, like above right.

To fill with colour, type this:

  • t.fillcolor(“green”)
  • t.begin_fill()
  • t.circle(25)
  • t.end_fill()

And finally, to clear the screen, type: “t.clear()”.

As an example, to make a square, it is like below. We use a “for” loop.

for _ in range(4): {shift-enter}
  t.forward(25) {shift-enter}
  t.right(90) {enter 2x}

Another example: a filled hexagon.

t.fillcolor("green") {enter}
t.begin_fill(){enter}
for _ in range(6): {shift-enter}
   t.forward(25) {shift-enter}
   t.right(60) {enter 2x}
t.end_fill(){enter}

Have fun!

6 September 2020

Dynamic Difference in Power BI

Filed under: Data Warehousing — Vincent Rainardi @ 3:30 pm

If you are looking for how to do dynamic difference (dynamic delta) in Power BI, you’ve come to the right place. This article is about showing how to calculate the difference (say between actual and budget) dynamically or on-the-fly as you switch from product to product. This is done using the SelectedValue function.

Business Scenario

Here is the business scenario: you work in product development in a manufacturing company. You have many products developed in your product development pipeline, each have different costs for each component like this:

Report Layout

The Power BI report should look like this:

You need to be able to select a product (Product A in the above example) and the actual spend vs budget are displayed in a table, along with the difference.

So you are comparing the cost breakdown of a product to the budget. Another business scenario which is similar to this is comparing the performance attribution of a mutual fund to the benchmark. In this case instead of components, we have industry sectors.

Dynamic Difference

The point here is that the differences are calculated on-the-fly, depending on the user selection. That is the key Power BI functionality that I’d like to show you.

There is a function in Power BI called SELECTEDVALUE, which we need to use for this. We use it to find out which product is being selected.

How To Do It

So let’s create the Power BI report.

Step 1. First, in Excel, type this table, and load it in Power BI as Cost table:

Step 2. Create a calculated table to select distinct values from the Product column:

   Product = distinct(‘Cost'[Product])

Step 3. Use it for a slicer so we can select Product A, B and C (filter the Budget out):

Step 4. Create 3 measures: Cost_Budget, Cost_Actual and Cost_Differene as follows:

1. Cost for the budget:
Cost_Budget =
CALCULATE
( SUM(‘Cost'[Cost]),
  FILTER(‘Cost’, ‘Cost'[Product] = “Budget”)
)

2. Cost for the selected product:
Cost_Actual =
CALCULATE
( SUM(‘Cost'[Cost]),
  FILTER(‘Cost’, ‘Cost'[Product] = SELECTEDVALUE(Product[Product]))
)

3. The difference between the budget and actual:
Cost_Difference = [Cost_Budget] – [Cost_Actual]

Step 4. On the report create a table with Component, Budget, Product and Difference in the Values.

Now when we select Product A it will display the cost of Product A and calculate the difference on-the-fly.
And when we select Product B it will display the cost of Product B and calculate the difference on-the-fly.

26 September 2019

Development Operations (DevOps)

Filed under: Data Warehousing — Vincent Rainardi @ 5:45 pm

Whether you are building a data warehouse, a client reporting system, a MDM system or a trade booking system you need to run a development team. Development Operations are things that you need to run a software development team. What do you need to run a development team? They are:
1. Release pipeline
2. Change control
3. Sprint planning
4. Automated testing
5. Code repository
6. Server build

In writing this article I will try to combine all my experiences from about 10 companies in the last 12 years. Some of them do best practices, some do bad practices. I will only write about the good ones here.

1. Release Pipeline

The first thing that you need as a development team is a release pipeline. A release pipeline is a process to automatically build, deploy and test the code to a series of environments, i.e. development, test, UAT, production and support. A release is a collection of code such as stored procedures, SSIS packages, .Net code, views, tables, etc. bundled into 1 package to be deployed together as 1 unit.

Can’t you deploy it manually by copying the code? Of course you can. But it will take more effort. And it is prone to error. What if you want to rollback to previous version? Well you have to do it manually right, by copying the previous version of each component. Who is keeping track of the version for each component? What if you missed 1 component? You could be deploying 50 components in test but only 49 in production. It’s a headache right? With a release pipeline, you can deploy all components into many environments consistently and effortlessly. You deploy into Test environment, and test it here. You deploy into UAT environment, and test it here. And you deploy the same thing into Production. And then you deploy the same thing into Support environment. The environments are guaranteed to be consistent.

If you have 100 stored procedures, 100 tables, 100 views, 100 SSIS packages, a view SSAS cubes, 50 SSRS reports and hundreds of .Net codes, then you will appreciate the benefit of having an automated release pipeline. It is a huge time saver. And it improves your quality.

Deployment into an environment requires approvals. A deployment into the test environment for example, may require the test manager approval. Whereas to deploy a release into production requires an approval from the production support manager.

2. Change Control

The second thing that you need to run a development team is change control. Change control is a process of approving every single change going into production environment. It can be a code change (like a release). It can be a data change (like an UPDATE or DELETE statement). It can be a configuration change (like moving the data folder from C drive to E drive). It can be an infrastructure change (like setting up a new SQL server).

Change control is very important because:
– It shows that the change has been tested properly in Test environment, before it is deployed to production.
– It shows that the development manager and the production support manager are aware about the change.
– When the company is audited you have evidence that every single change in production is approved and tested.
– You can choose which change will be deployed at the same time in production, and which ones are not at the same time to minimise the risk
– It shows the sign off from the business, agreeing to the change.
– When the production deployment failed, it is recorded properly including the reason and the solution.
– It shows that every change in production is controlled, so the production systems are stable and reliable.

A change request is an electronic form which specifies:
– The reason for the change (usually a business reason but can be a technical reason)
– The list of components and data to be changed
– The evidence that the change has been deployed to Test/UAT environment the same way it will be deployed into production
– Link to the design specification or requirement which forms the basis of the change
– The evidence that the change satisfies the design specification or requirement (or if it is a bug fix, the evidence that the change fixes the bug)
– The impact of this change to the business users
– The approval from the business, from the development manager, and from the production support
– The updated documentation for the production support
– How the change will be deployed to production and to the DR system
– How the change will be tested that it works in production
– How the change will be rolled back if it doesn’t work in production
– The date the change is intended to be deployed to production
– The developer who did the change
– Who from the development team will be on support on the day the change is deployed to production
– Which teams are required to deploy the change
– The applications which are impacted, including downstream applications
– The severity of impact of the change, i.e. high, medium, low (the risk)
– The scale of the change, i.e. major change, minor change or medium (how many components)
– Whether it is an emergency change or not

The change request form is not just for application changes, but also for infrastructure changes such as servers and networks. It is for any changes impacting any production system, including codes, files, databases, servers, configurations, firewall, connections, permissions, scheduling.

Major change requests are discussed in a weekly meeting between the developers and the production support team to understand:
– What changes are going in this week
– Whether there are any conflicts between the changes which are going in this week
– Where those changes are in terms of their positions in the daily batch
– If things do go wrong, how long it will take to recover (or to fix)
– Who is required to standby to fix if anything goes wrong (DBA, infrastructure, developer)
– When those changes should be done from production point of view (to minimise the impact).
– To scrutinise the test evidence, not whether the change satisfies the requirements, but whether the change has been deployed in the Test system the same way as it would be deployed in production. In particular, whether the condition of the Test environment is the same as production. Also, whether the impacted application has been tested in Test environment.
– To check that the rollback script really covers the whole change, not just part of it. And whether it has been tested.
– Whether you need to communicate the change to the users or not, and whether the help desk should be prepared to field calls from the users on the deployment day.

The changes are then either approved or rejected. If it is approved, it is given a date and time when it will be deployed. Naturally, the business and the development team want the change to be deployed as soon as possible, but it is the responsibility of the production support team to decide the timing, to minimise the risk. Changes with major impact (or high risk) are usually deployed on Saturday when the business users are not working so they are not impacted and you have Sunday to recover or fix any issues. Changes with medium impact (and medium risk) can be deployed on Friday, so you have Saturday for fixing. Changes with low impact and low risk can be deployed earlier in the week (Wed or Thu but not Mon or Tue).

If there are major changes going in this week end, it is wise to defer deploying other major changes to next week end. Similarly if the required support resources is not available this week end (if it goes wrong) then the change should be postpone to next week.

Some changes requires coordination with an external vendor. So the timing of production deployment must be mutually agreed. Some changes are time-bound, i.e. they have to be done before certain date otherwise the company will get a penalty from the regulator.

Some changes need to be done immediately, for example because of security risk, or risk of losing a great deal of money. This is classified as an emergency change and it is usually a bug which needs to be fixed immediately. The procedure for emergency change request is different to a normal change request. It still requires approval, it still needs to be tested, but a lot more streamlined. In most cases the principle of applying emergency changes is “fix after”, meaning if things go wrong you do not roll the change back, but you fix it. This requires more people to standby compared to a normal change. This “fix after” principle allows the testing to be light weight.

3. Sprint Planning

The third thing that you need to run a development team is sprint planning. A sprint is a unit of two weeks. In theory it is possible to define a sprint as 1 or 3 weeks, but I’ve been working at 4 companies which do sprint, and every single one does 2 weeks.

Yes Sprint is a way of running Agile. No one does Waterfall any more these days. Funny how things moved, 5 years ago people still debating Agile vs Waterfall. But not now. No more debate on that. The debate is more around CI/CD atau automated testing.

Azure DevOps is probably the best tool in the market, followed by Jenkins, Travis. Many are not a complete DevOps tool. GitHub, Grade, JIRA, Bamboo, AWS CodePipeline, Trello for example. They just doing build and source code control but without CI/CD, or vice versa. Or doing both but not sprint planning (Trello do sprint planning but no release pipeline, whereas AWS CodePipeline is the opposite). Even Azure DevOps is not complete (it doesn’t do change control), but it does sprint planning, source code control, release pipeline CI/CD and automated testing.

Every two weeks you plan the works that you need to do in the next sprint. These pieces of work are called user stories. First you define the team capacity, i.e the number of working days minus the holidays. You then allocate how many days is required for each story, who will be doing it, and the acceptance criteria (the definition of done), i.e. just doing the development and test, or until production. Then you check if anyone is under or over allocated. If someone is over capacity, distribute or reduce the work.

After planning, during the 2 weeks sprint run you track the progress of each story. For each story you create a few tasks with an estimate and the person doing it. As each task gets done, you mark the actual hours against the estimate. The status of each task changes from new to in-progress to completed. This will create a burndown chart, which tracks the whole team’s actual hours against estimate.

It’s all very well and good doing planning and tracking as above, but how do you determine what needs to be done in the first place? This is where the product owner comes in. The list of work in each sprint should be driven largely from the prioritised list of projects + product increment. If the team is a dedicated project team, then the list of work comes from just 1 project + the BAU of that project. Some teams serve multiple projects (size of 3 months to 1 year) plus hundreds enhancement requests (size of 2 to 10 days) throughout the year.

4. Automated Testing

The fourth thing that you need to run a development team is automated testing. Many people leave this to the back of the queue, but the reality is that this thing saves a lot of time (and money), and increases the quality of the code enormously. Automated testing means two things:
a) Ensuring that deployment to production does not break anything
b) The code satisfies all the intended functionalities, and none of the unintended ones

Point a) is achieved by copying the production system into the test environment. The lot, i.e. thousands of components, code, settings, databases and files from production is restored into the test environment overnight. Then you apply the latest code and data changes from the release pipeline into this test environment. Then you run the whole system, and check the expected results. The key thing is: all of these are conducted programmatically, every day, without any human intervention.

Point b) is achieved by having a test environment which is completely empty, i.e. no data. You have the databases, but there are no rows in any tables. You have the data folders but there are no data files in them. Then you test 1 piece of code, e.g. a .Net web service or a stored procedure. You do this by setting up test data, e.g. you insert a few rows into the input tables. Each row reflect one specific test scenario. Then you run the code and check the result. Then you repeat it for all pieces of code in the system, thousands of them. For 1 piece of code you need to run some positive tests and some negative tests. The key thing is: all of these are conducted programmatically, every day, without any human intervention.

If you have to do all that manually, it would requires thousands of hours. Actually it would be impossible to do because for every release you will have to repeat both tests. If you don’t have automated testing, you can’t deploy to production 3x a week. The best you can do is once a quarter, because of the amount of testing involved. It does not make sense to do 10 hours of development and then spend 2000 hours of testing right? But once your hours of testing is down to zero, then you can do a 10 hours development, test it and deploy to production. And then you can do another 10 hours of development, and so on.

Because for every single change you run “the whole lot of testing” twice (the a and the b above), you can release very often, and you increase the quality of the code. You do positive testing and negative testing on every component, and also integration testing. The a) above is called “system testing”, and the b) above is called “unit testing”. Both are automated.

Does it mean you do not need to do manual testing? No, you still need to. When a major feature is developed, you need to do manually test the functionalities across the whole piece. Suppose you are adding a new feature in an order processing system which enable the system to combine orders from different customers and process them together. There are 9 places in the system which need code changes. Each of these 9 pieces has been unit tested individually using the b) above, which proves that each piece works individually (using minimal amount of data, i.e. a few rows). The whole system has been system tested using the a) above, which proves that there is no negative impact to the system as a whole.

But how do you know that the ability to combine orders really works end-to-end, using a normal production data volume? The automated unit test only uses a few rows, and they are made up data. It does not prove that end to end the new feature is working. To prove that the new feature is working we need to run thousands of real orders from last month across the system, combining hundreds of them, process them and check the output. Are all order processed correctly? Are there any issues? If it passes this test we can say hand on heart that the system now has capability of combining orders.

5. Code Repository

This is a must in any development team. You can use GitHub, TFS, SVN, PVCS, BitBucket, or others, but you need to have the capability of storing code, versioning, master and feature branches, committing changes, packaging and releasing code, merging, collaborating, restoring to previous version, doing code reviews and pull requests.

Whether it is Java code, Python, databases, ETL tool, cubes or reports, they are code. And they ALL need to be in ONE code repository. And the code repository MUST be integrated with the release pipeline. You need to be able to push a release candidate to the release pipeline, test it and deploy it automatically into various environment including test, support and production.

6. Server Build

Like automated testing, this one is frequently put at the back of the queue, but it really is a time saver and money saver. So we need to do it. Server Build is the ability to create a server programmatically. A release pipeline consists of a series of environments such as Dev, Test, UAT, Prod and Support. Each environment consist of several servers, like SQL Server, application server, SSIS server, SSAS server, Python server, etc.

These servers need to be built. If you build them manually, it would take a lot of hours. Not just once, but they will need to be configured, patched and maintained. And when they don’t work, you need to troubleshoot it and fix it.

A better way to create servers in Azure is using PowerShell DSC. For each environment you need to create a DSC configuration which tells PowerShell DSC the server name, resource group, folder paths, Windows features and any other characteristics which are specific to each environment and each server. The PowerShell DSC then reads this DSC configuration and create each server in each environment according to the settings written in this file.

The best practice is to recreate these servers on a weekly basis (except the production environment), to avoid having to upgrade and patch them.

7. BAU/support/bug fixes
8. Business requirement & design
9. Architecture

The traditional understanding of “DevOps” as a system normally includes point 1 to 6, but not 7 to 9. But 7 to 9 are certainly required to run a development team for any system (I do mean software, not civil engineering).

Next Page »

Blog at WordPress.com.