Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Saturday, September 28, 2019

REST idempotency for long running jobs

scenarios:
- POST 202
  GET  404, 200

- POST 409

- POST 202
  GET  500
  retry POST

- POST 500
  retry POST
Due to two operations (cache, queue) there is a possibility of inconsistent state where the cache operation succeeds but the queue operation fails. One way to deal is to do a compensation operation (cache undo).
// post
response accept(request):
    item = cache.get(request.id)
    hash = hasher(request.id, request.body,
                  request.header1, request.header2, ...)
    if item == null:
        cache.insert({ id: request.id,
                       hash: hash })
        queue.send(request)
        return { statusCode: 202,
                 location: "{request.id}/status" }
    if hash != item.hash:
        return { statusCode: 409 }
    if item.statusCode == 5xx:
        updateItem(item)
        queue.send(request)
    return { statusCode: 202,
             location: "{request.id}/status" }

updateItem(item):
    item.statusCode = null
    cache.update(item)

// get
response status(id):
    item = store.get(id)
    return { statusCode: 200,
             code: item.statusCode,
             body: item.body }

// cache ttl exceeds possible retry window
cache:
    item get(id):
    insert(item):
    update(item):

store:
    item get(id):

hasher(request):
    // sha1 hash
This deals with the inconsistent state mentioned above but is unable to handle 409 conflicts in the backend. The chance of id collision is quite less. It is mainly an attack vector (attacker uses the same id but different bodies for requests in quick succession).
// post
response accept(request):
    item = cache.get(request.id)
    if item == null || item.statusCode == 5xx:
        queue.send(request)
        return { statusCode: 202,
                 location: "{request.id}/status" }
    hash = hasher(request.id, request.body,
                  request.header1, request.header2, ...)
    if hash != item.hash:
        return { statusCode: 409 }
    return { statusCode: 202,
             location: "{request.id}/status" }

// backend
process(request):
    item = cache.get(request.id)
    if item != null && item.processing:
        // drop message
        return
    if item == null:
        hash = hasher(request.id, request.body,
                      request.header1, request.header2, ...)
        cache.insert({ id: request.id,
                       hash: hash,
                       processing: true })
    // can't deal with 409 here
    if item.statusCode == 5xx:
        item.statusCode = null
        item.processing = true
        cache.updateItem(item)
    processInner(request)

// get
response status(id):
    item = store.get(id)
    return { statusCode: 200,
             code: item.statusCode,
             body: item.body }

// cache ttl exceeds possible retry window
cache:
    item get(id):
    insert(item):
    update(item):

store:
    item get(id):

hasher(request):
    // sha1 hash

Friday, July 15, 2016

dispose pattern

Note: user called dispose() and gc both clean up unmanaged resources. gc does not clean up managed resources as it cleans up objects in any order.

basic dispose pattern
// basic dispose pattern
// only managed resources
basicdispose: idisposable
    // user calls
    public dispose():
        dispose(true)
        gc.suppressfinalize()
    
    // needs to be protected virtual
    protected virtual dispose(disposing):
        if disposing:
            // clean managed resources

dispose pattern for finalizable type
Note: there is a performance penalty with finalize types as they go through the finalize and f-reachable queues.
// dispose pattern for finalizable type
// managed and unmanaged resources
// finalizable types are put in finalize and f-reachable queues by gc
finalizable: idisposable
    // user calls
    public dispose():
        dispose(true)
        gc.suppressfinalize()
    
    // needs to be protected virtual
    protected virtual dispose(disposing):
        if disposing:
            // clean managed resources
        // clean unmanaged resources
    
    // finalize(), gc calls
    ~finalizable():
        dispose(false)

basic dispose pattern with inheritance
With inheritance, call the base class dispose(bool) as well.
basicdispose: idisposable
    // ...

basicdisposeChild: basicdispose
    // user calls
    dispose():
        dispose(true)
        gc.suppressfinalize()
    
    // needs to be protected virtual
    protected virtual dispose(disposing):
        if disposing:
            // clean managed resources
        // clean unmanaged resources
        disposed = true
        
        // call base class dispose(bool)
        base.dispose(disposing)

With disposed flag
basicdispose: idisposable
    disposed = false
    // user calls
    public dispose():
        dispose(true)
        gc.suppressfinalize()
    
    // needs to be protected virtual
    protected virtual dispose(disposing):
        if disposed:
            return
        if disposing:
            // clean managed resources
        disposed = true

Saturday, December 27, 2014

equals

Shortest way.
public override bool equals(obj): 
    T that
    return obj != null
        && (that = obj as T) != null
        && this.x == that.x

Thursday, December 25, 2014

recursion and yield return

Get a list of nodes given a tree structure of nodes.
A
|
+--B
|
+--C
|  |
|  +--D
|
+--E
Result:
{ A, B, C, D, E }

Data structure:
node:
    string name
    list<node> children

Using recursion:
traverse(root):
    list = new
    Get(root, list)
    return list

// with list
Get(node, list):
    list.add(node)
    if node.children == null:
        return
    foreach child in node.children:
        Get(child, list)

Using recursion and yield return:
traverse(root):
    return Get(root)
    
// with yield return
Get(node):
    yield return node
    if node.children == null:
        yield break
    foreach child in node.children:
        foreach n in Get(child):
            yield return n

But it is inefficient when the tree is deep as every method call creates an iterator (see this), i.e. O(n) iterators. So the work-around is to not use recursion and save nodes in a stack with O(n) space and O(logn) iterators.
traverse(root):
    return Get(root)
    
// without recursion, with yield return
Get(node):
    stack = new
    stack.push(node)
    while !stack.empty():
        var n = stack.pop()
        yield return n
        if n.children == null:
            continue
        // reverse to preserve children order
        foreach child in n.children.reverse():
            stack.push(child)


[Hat tip to RT, JS, EL]

Friday, May 24, 2013

git

Note that:
- Git is hard. 
- You should read a book about git first before using it on a project. 
- You'll not get a good git gui because there will never be one. 
- You'll understand the reason for index when you understand interactive hunk staging.
- You'll get bit by git rebase. 
- You'll get discombobulated by git reset.
- I experienced infinite joy when I stumbled upon this before gitk. I hope you too.
git log --graph --decorate --all --oneline
- You'll be utterly befuddled by reading the repo graph despite gitk.
- You'll be in git zen when you eventually get the usefulness of this.
git rebase --onto
- You'll experience euphoria when you run git filter-branch and it works.
- You'll eventually realize that git is a superior VCS.


Books:
Version Control With Git 2e - Loeliger McCullough 2012 O'Reilly (454 pages)
Pro Git 1e - Scott Chacon 2009 Apress (238 pages)

Git Internals - Scott Chacon 2008 PeepCode (121 pages)
Git from the Bottom Up - John Wiegley 2009 (31 pages)

Git Internals has a chapter 'The Git Data Model' with neat diagrams and I think it explains the data model better than other books but the book itself is not worth $9 - $12 price.

Version Control With Git is a good beginner book. Pro Git is a good reference book. Pro Git's 'Distributed Git' chapter describes workflows that other books do not. Version Control With Git has good chapters on 'Advanced Manipulations' and 'Tips, Tricks, and Techniques'. Once comfortable, you want a reference book.


git commands: 
gist


Workflows:
The upper branches are more stable than the lower ones i.e. lower branches are merged into upper.

basic workflow:
master
feature branches

git workflow:
master
maint
next
pu
feature branches

A successful Git branching model workflow:
One important point is to not fast-forward branches by default when merging into upper branches.
master
hotfix
release
develop
feature branches

It ironic that git, a distributed VCS, is gaining popularity in this day and age. Here is to clean histories. Git: 1, Others: 0.

github/rmandvikar

Friday, May 21, 2010

codejam 2010 qualifications

qualifications problems


A Snapper Chain

The snappers are same as incrementing binary bits. The overflow is discarded. ANDing K with 111...N bits gives the state of the snappers after K snaps. The count of 1 bits of that number if same as N means the state is ON else OFF.

string snapperChain(int n, int k)
    int nbit = (int) Math.Pow(2, n) - 1;
    int result = nbit & k;
    int count1 = count1bits(result);
    
    if (count1 == n)
        return "ON";
    else
        return "OFF";

int count1bits(int num)
    int n = num;
    int count = 0;
    while (n != 0)
        n = n & (n - 1);
        count++;
    return count;


B Fair Warning

I used this IntX code for 64+ bits data structure. The trick is to subtract the min of the array and find their gcd - which gives Tmax. ymin is calculated then. One way is to sort the array and find the gcd from index 1...N. Another way is to find the min and put checks for 0 in gcd function.

string fairWarning(IntX[] input)
    IntX Tmax = -1;
    IntX ymin = -1;

    //Array.Sort(input);
    IntX min = minf(input);
    
    for (int i = 0; i < input.Length; i++)
        input[i] = input[i] - min;
    Tmax = gcdf(input);

    if (Tmax == 0 || (min % Tmax) == 0)
        ymin = 0;
    else
        ymin = Tmax - (min % Tmax);
    
    return ymin.ToString()

//min of array
IntX minf(IntX[] input)
    IntX min = input[0];
    for (int i = 0; i < input.Length; i++)
        if (input[i] < min)
            min = input[i];
    return min;

//gcd of array
IntX gcdf(IntX[] input)
    IntX a = input[0];
    for (int i = 1; i < input.Length; i++)
        IntX b = input[i];
        if (i < input.Length-1 && a == 0)
            i++;
            a = input[i];
        if (i < input.Length-1 && b == 0)
            i++;
            b = input[i];
        a = gcdf(a, b);
    return a;

//gcd of a, b
IntX gcdf(IntX a, IntX b)
    if (a == 0 && b == 0)
        throw new ArgumentException();
    while (b != 0)
        IntX t = a % b;
        a = b;
        b = t;
    return a; count;


C Theme Park

Limits
1 <= T <= 50
gi <= k

Small dataset
1 <= R <= 1000
1 <= k <= 100
1 <= N <= 10
1 <= gi <= 10

Large dataset
1 <= R <= 10^8
1 <= k <= 10^9
1 <= N <= 1000
1 <= gi <= 10^7

My first solution was of O(R*N) time i.e. 10^8 * 10^3 which does not work for large dataset. The trick is to first calculate and cache the sums and save the next group position which takes O(N*N) time i.e. 10^6 and then add the sums in O(R) time i.e. 10^8 - the sum is calculated for each position i of N in cache[] and the next group index in nextCacheIndex[].

Int64 themePark(Int64 R, Int64 k, Int64[] q)
    Int64 totalMoney = 0;
    Int64 groups = q.Length;

    Int64[] cache = new Int64[q.Length];
    Int64[] nextCacheIndex = new Int64[q.Length];

    for (Int64 i = 0; i < groups; i++)
        Int64 sum = 0;
        Int64 nextIndex = i;

        Int64 groupCount = 0;
        //while sum <= k and not at the end of the *current* queue 
        while ((sum + q[nextIndex] <= k) && (groupCount < groups))
            sum += q[nextIndex];
            nextIndex = (nextIndex + 1) % groups;
            groupCount++;
        cache[i] = sum;
        nextCacheIndex[i] = nextIndex;

    Int64 index = 0;
    for (Int64 r = 0; r < R; r++)
        totalMoney += cache[index];
        index = nextCacheIndex[index];

    return totalMoney;


[codejam]

Wednesday, July 30, 2008

How to call a function at memory address 0

As per Andrew Koenig, this is about understanding declarations in the paper, c traps and pitfalls.


(* (void (*)()) 0)();


int i: i is an int

int *i: *i is an int, i is a pointer to int

int fi(): fi() is int, fi is a function that returns int

int *gi(): *gi() or *(gi()) is int, gi() returns a pointer to int, gi is a function that returns a pointer to int. As () binds tighter than *, *gi() is same as *(gi())

int (*fi)(): (*fi)() is int, *fi is a function that returns an int, fi is a pointer to a function that returns an int. Also, (*fi)() would be the call statement to the function.

Based on this, the above declaration is divided into two parts.
(* 0)()  - this is similar to (*fi)() explained above. This calls the function at 0 using the pointer to a function at 0.

The only thing missing is that we need to cast 0 to a type of pointer to a function returning void which is done by void (*)().

void (*)() - For (*fi)(), fi is pointer to a function where fi is a dummy variable. So void (*)() is a pointer to a function returning void. For type-casting, we enclose it in brackets as (void (*)()).

Thus,


(* (void (*)()) 0)();



[Hat tip to Haroon Saeed, C Traps and Pitfalls]