text:
[<File_doc|ui|/src/app/base/util/displayUtils.lua|replace>]
--Tools for display
local displayUtilsInstance = class("displayUtilsInstance")
--Init------------------------------------------
function displayUtilsInstance:ctor(params_)
	self.ttfConfig = {}
    self.ttfConfig.fontFilePath = "FZHLJW.TTF"
    self.ttfConfig.glyphs   = cc.GLYPHCOLLECTION_DYNAMIC
    self.ttfConfig.customGlyphs = nil
    self.ttfConfig.distanceFieldEnabled = true
    self.ttfConfig.outlineSize = 0
    self.spriteFrames={}
end
--Set displayObject's parameter. add to container.
function displayUtilsInstance:placeAndAddChildToContainer(dis_,container_,ax_,ay_,px_,py_,r_,sx_,sy_,a_,index_)
	self:setAnchor(dis_,ax_,ay_)
	self:place(dis_,px_,py_,r_,sx_,sy_,a_)
	container_:addChild(dis_,index_,index_)
end
--Set displayObject's logic parent.
function displayUtilsInstance:setLogicParent(dis_,logicParent_)
	dis_.logicParent=logicParent_--设置逻辑父容器
	dis_:setCascadeOpacityEnabled(true)
	table.insert(logicParent_.displayList,dis_)--放入显示列表
end
function displayUtilsInstance:setAnchor(dis_,ax_,ay_)
	if ax_ and ay_ and (ax_~=0 or ay_~=0) then dis_:setAnchorPoint( cc.p(ax_, ay_)) end
end

function displayUtilsInstance:setSp9Info(dis_,namePath_)
	dis_.spriteIn=cc.Sprite:create(namePath_)
	local _size=dis_.spriteIn:getContentSize()
	dis_.sourceWidth=_size.width
	dis_.sourceHeight=_size.height
	dis_.spriteIn:setVisible(false)
	dis_:addChild(dis_.spriteIn)
end

--Short code for set displayObject's parameter.
function displayUtilsInstance:place(dis_,px_,py_,r_,sx_,sy_,a_)
	if a_~=nil then
		if a_ >0.05 and dis_:isVisible()==false then
			dis_:setVisible(true)
			if dis_.isMotionStreak==true then
			else
				dis_:setOpacity(a_*255)
			end
		elseif a_ <=0.05 and dis_:isVisible() then
			dis_:setVisible(false)
			dis_:setOpacity(a_*255)--看不到但是透明度的数值需要跟着变
		end
	end
	if dis_:isVisible() then
	    if dis_.isSp9==true then
            dis_:setContentSize(cc.size(dis_.sourceWidth * sx_,dis_.sourceHeight * sy_))
        else
			if sx_~=nil then dis_:setScaleX(sx_) end
			if sy_~=nil then dis_:setScaleY(sy_) end
        end
        if px_~=nil and py_ ~=nil then dis_:setPosition( cc.p(px_, py_) ) end
		if r_~=nil then dis_:setRotation(r_) end
	end
end
--Set text's color and width/height
function displayUtilsInstance:textSet(text_,r_,g_,b_,w_,h_)
    text_:setTextColor(cc.c4b(r_,g_,b_,255))
    if w_ then text_:setWidth(w_) end
	if h_ then text_:setHeight(h_) end
	text_:setLineBreakWithoutSpace(true)
end
--Create a pic and scale it
function displayUtilsInstance:getPicScaleToSize(picName_,width_,height_)
    local _pic = cc.Sprite:create(picName_)
    _pic:setAnchorPoint(cc.p(0,0))
    _pic:setScaleX(width_/_pic:getContentSize().width)
    _pic:setScaleY(height_/_pic:getContentSize().height)
    return _pic
end
--Set btn's text
function displayUtilsInstance:setBtnText(btn_,text_,fontName_,fontSize_,align_,color3C_)
	btn_:setTitleFontName(fontName_)
	btn_:setTitleFontSize(fontSize_)
	if align_=="left" then
		btn_:setTitleAlignment(cc.TEXT_ALIGNMENT_LEFT)
	elseif align_=="right" then
		btn_:setTitleAlignment(cc.TEXT_ALIGNMENT_CENTER)
	elseif align_=="center" then
		btn_:setTitleAlignment(cc.TEXT_ALIGNMENT_RIGHT)
	end
	btn_:setTitleColor(color3C_)
	btn_:setTitleText(text_)
end

--Set blend mode to displayObject
function displayUtilsInstance:setBlendToDisplay(dis_,mode_)
	if mode_=="lighten" then--lighten
		dis_:setBlendFunc(cc.blendFunc(gl.ONE , gl.ONE))
	elseif mode_=="overlay" then--overlay
		dis_:setBlendFunc(cc.blendFunc(gl.DST_COLOR , gl.ONE))
	elseif mode_=="multiply" then--multiply 去白
		dis_:setBlendFunc(cc.blendFunc(gl.DST_COLOR , gl.ONE_MINUS_SRC_ALPHA))
	elseif mode_=="screen" then--screen
		dis_:setBlendFunc(cc.blendFunc(gl.ONE_MINUS_DST_COLOR , gl.ONE))
	elseif mode_=="add" then--add 去黑
		dis_:setBlendFunc(cc.blendFunc(gl.SRC_ALPHA, gl.ONE))
	elseif mode_=="layer" then--layer--black edge
		dis_:setBlendFunc(cc.blendFunc(gl.ONE_MINUS_SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA))
	else--unSupport show black rectangle
		dis_:setBlendFunc(cc.blendFunc(gl.ZERO, gl.ONE_MINUS_DST_ALPHA))
	end
end

--Use "stencil_" create a mask in "container_" to mask childs.
function displayUtilsInstance:createMask(container_,stencil_,disCount_)
	local _startIndex=stencil_:getTag()
	local _maskContainer=cc.Layer:create()
	_maskContainer:setPosition(cc.p(0,0))
	_maskContainer:setAnchorPoint(cc.p(0,0))
	for _loopIndex=_startIndex-1,(_startIndex-disCount_),-1 do
		if _loopIndex >0 then
			local _disPlay=container_:getChildByTag(_loopIndex)
			_disPlay:retain()
			stencil_.logicParent:removeChild(_disPlay)
			_maskContainer:addChild(_disPlay,_loopIndex,_loopIndex)
			_disPlay:release()
		else
			break
		end
	end
	local _clippingNode = cc.ClippingNode:create()
	_clippingNode:setAnchorPoint(cc.p(0,0))
	_clippingNode:setStencil(stencil_)
	_clippingNode:setInverted(false)
	_clippingNode:setAlphaThreshold(0)
    _clippingNode:setPosition(cc.p(0,0))
	stencil_:removeFromParent(false)
    _clippingNode:addChild(_maskContainer)
    container_:addChild(_clippingNode,_startIndex)
end

--[[图片调整大小,适应屏幕
	type_   "fit" x,y方向放缩去适应屏幕
			"in"  在屏幕里,等比放缩直到x,y任意一方接触到屏幕边缘
			"out" 在屏幕外,包含屏幕
]]
function displayUtilsInstance:picFitWindowSize(pic_,type_)
	local _picSize=pic_:getContentSize()
	local _uc=uiControl:getInstance()
	if type_ == "fit" then
		local _scaleX,_scaleY=1.0
		_scaleX=_uc.realWidth/_picSize.width
		pic_:setScaleX(_scaleX)
		_scaleY=_uc.realHeight/_picSize.height
		pic_:setScaleY(_scaleY)
		return _scaleX,_scaleY
	else
		local _scale=1.0
		if _picSize.width/_picSize.height>_uc.realWidth/_uc.realHeight then
			if type_=="in" then
				_scale=_uc.realWidth/_picSize.width
			elseif type_=="out" then
				_scale=_uc.realHeight/_picSize.height
			end
		else
			if type_=="in" then
				_scale=_uc.realHeight/_picSize.height
			elseif type_=="out" then
				_scale=_uc.realWidth/_picSize.width
			end
		end
		pic_:setScale(_scale)
		return _scale,_scale
	end
	return nil,nil
end

function displayUtilsInstance:defFromDis(disX_,disY_)
	local _deg = nil
    if disX_ == 0 and disY_==0 then

    elseif disX_ == 0 then
        if disY_>0 then
            _deg =90
        else
            _deg =270
        end
    elseif disY_ == 0 then
        if disX_>0 then
            _deg =0
        else
            _deg =180
        end
    else
        local _tempDeg = math.deg(math.atan(disY_/disX_))
        if _tempDeg >0 then
            if disX_ <0 then
                _deg = _tempDeg +180
            else
                _deg = _tempDeg
            end
        else
            if disX_ <0 then
                _deg = _tempDeg +180
            else
                _deg = _tempDeg + 360
            end
        end
    end
    return _deg
end

function displayUtilsInstance:createPartical(particalName_,type_)
    local _aniSprite = cc.ParticleSystemQuad:create(string.format("%s.plist",particalName_))
    if type_ == "free" then
    	_aniSprite:setPositionType(cc.POSITION_TYPE_FREE)
    elseif type_ == "grouped" then
    	_aniSprite:setPositionType(cc.POSITION_TYPE_GROUPED)
    elseif type_ == "relative" then
    	_aniSprite:setPositionType(cc.POSITION_TYPE_RELATIVE)
    end
   	return _aniSprite
end

function displayUtilsInstance:createAnimation(animationName_,loop_,fun_,isPng_)
    local sharedSpriteFrameCache = cc.SpriteFrameCache:getInstance()
    local _picFormat = "%s.pvr.ccz"
    local _picFix = ".png"
    if isPng_ then
    	_picFormat = "%s.png"
    	_picFix=""
    end

    local _frames = sharedSpriteFrameCache:addSpriteFrames(
        string.format("%s.plist",animationName_)
        ,
        string.format(_picFormat,animationName_)
        )

    local _spriteFrames=self.spriteFrames[animationName_]
    if _spriteFrames==nil then
    	_spriteFrames={}
	    local _loopBoolean=true
	    local j=1
	    while _loopBoolean do
	    	local _spritePicName=string.format("%s%04d".._picFix,animationName_,j)
	        local _tempSpriteFrame=sharedSpriteFrameCache:getSpriteFrame(_spritePicName)
	        table.insert(_spriteFrames, _tempSpriteFrame)
	        if _tempSpriteFrame == nil then
	            _loopBoolean=false
	        end
	        j=j+1
	    end
	    self.spriteFrames[animationName_]=_spriteFrames
    end

    local _aniSprite =cc.Sprite:createWithSpriteFrame(_spriteFrames[#_spriteFrames])
    local _animation = cc.Animation:createWithSpriteFrames(_spriteFrames,0.083)
    local _animationSequence
    if loop_ then
        _animationSequence=cc.RepeatForever:create(cc.Animate:create(_animation))
    else
        local function removeFun()
            _aniSprite:stopAllActions()
            _aniSprite:removeFromParent(true)
            if fun_ then fun_() end--make sure call it when is exist
        end
        local callfunc = cc.CallFunc:create(removeFun)
        _animationSequence = cc.Sequence:create(cc.Animate:create(_animation),callfunc)
    end
    _aniSprite:runAction(_animationSequence)
   	return _aniSprite
end

cc.exports.displayUtils={}
function displayUtils:getInstance()
	if self.instance == nil then
		self.instance = displayUtilsInstance:new()
	end
	return self.instance
end


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Histogram</title>
  <link rel="stylesheet" href="css/app.css"/>
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Open Sans">

ACS Programming Challenge

About

News

Results

About US

here's a header

here's some data

{{node}}

©Lawrence Berkeley National Labs

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function() {
  console.log("Hello Pranksters!");

    $("#btn-click").click(function(e) {
    $(".name").empty().append($("input.name").val());
    $(".product").empty().append($("input.product").val());
    $(".quantity").empty().append($("input.quantity").val());
    $(".date").empty().append($("input.date").val());

});

});


text:
from datetime import datetime
from swiftclient import Connection
import MySQLdb
import argparse
import config
import logging
import sys
import os

logger = logging.getLogger('Swift MySQL Backup')
logger.setLevel(logging.INFO)

# create a file handler
handler = logging.FileHandler('swift.log')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

def backup():
    now = datetime.now()
    FILENAME_SUFFIX = "_%(year)d%(month)02d%(day)02d_%(hour)02d%(minute)02d%(second)02d" % {
        'year': now.year,
        'month': now.month,
        'day': now.day,
        'hour': now.hour,
        'minute': now.minute,
        'second': now.second
    }

    try:
        db = MySQLdb.connect(config.mysql_host, config.mysql_user)
        cursor = db.cursor()
        cursor.execute("show databases")
        data = cursor.fetchall()
        return data, FILENAME_SUFFIX
    except:
        logger.info("Database connection error. Check your config.py file....\n")

def MySQLCMD():
    d_result = backup()
    for dbase in d_result[0]:  # dbase[0] returns information_schema
        FILENAME = config.path + dbase[0] + '.' + d_result[1] + '.sql.gz'  # d_result[1] returns FILENAME_SUFFIX
        if dbase[0] != 'mysql' and dbase[0] != 'information_schema' and dbase[0] != 'performance_schema':
            os.system('mysqldump --add-drop-database -u'+config.mysql_user+' -p'+config.mysql_password+' --database '+dbase[0]+' | gzip > '+FILENAME)
    return dbase[0]

def SwCred():
    # This uses swauth (v1.0) auth
    swift = Connection(
        authurl=config.endpoint,
        user=config.user,
        key=config.key,
        auth_version="1",
    )
    return swift

    def SwiftCP():
        sw = SwCred()
        container_name = config.container
        swiftcmd = " -A " + config.endpoint + " -U " + config.user + " -K " + config.key

        for file in os.listdir(config.path):
            with open(os.path.join(config.path, file),
                      'r') as f:  # without os.path.join , you will get ioerror errno 2 no such file or directo$
                file_data = f.read()
                fpath = os.path.join(config.path, file)
                fsize = os.path.getsize(fpath)
                if fsize > 4096000:  # to Backup files that larger than 4GB with Swift cli
                    os.system("swift upload " + container_name + " -S 1073741824 " + fpath + swiftcmd)
                    Message = "File " + fpath + " has been uploaded"
                    logger.info(Message)
                else:
                    sw.put_object(container_name, file, file_data)
                    Message = "File " + file + " has been uploaded"
                    logger.info(Message)

def DelFiles():
    for file in os.listdir(config.path):
        fpath = os.path.join(config.path, file)
        if os.path.isfile(fpath):
            os.unlink(fpath)
            Message = "File " + fpath + " has been deleted"
            logger.info(Message)

def Main():
    parser = argparse.ArgumentParser(description='Backs up MySQL to Softlayer Object Storage (Swift)')
    parser.add_argument('--local', action='store_true',
                        help='Backup up MySQL on local directory that defined in config file')
    parser.add_argument('--backup', action='store_true', help='Backup up MySQL to Softlayer Object Storage')
    parser.add_argument('--delete', action='store_true', help='Delete Local Backup Files')
    args = parser.parse_args()

    if args.local:
        MySQLCMD()

    elif args.backup:
        MySQLCMD()
        SwiftCP()

    elif args.delete:
        DelFiles()

    else:
        logger.info("Select Valid Option")

if __name__=="__main__":

        try:
                Main()

        except KeyboardInterrupt:
                print "KeyboardInterrupt detected!\nByeBye!!..."
                sys.exit()


text:
.class public final Lcom/mediatek/internal/R$bool;
.super Ljava/lang/Object;
.source "R.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/mediatek/internal/R;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "bool"
.end annotation

# static fields
.field public static final config_ntp_by_mobile:I = 0x80c0000

.field public static final config_screenBrightnessVirtualValues:I = 0x80c0008

.field public static final config_skip_network_validation:I = 0x80c0007

.field public static final config_wifi_auto_save_support:I = 0x80c0003

.field public static final config_wifi_framework_stop_scan_after_screen_off_support:I = 0x80c0002

.field public static final config_wifi_utf8_like_gbk_encoding:I = 0x80c0004

.field public static final is_captive_over_mobile:I = 0x80c0001

.field public static final is_mobile_hotspot_always_on_while_plugged:I = 0x80c0005

.field public static final is_mobile_provision_enabled:I = 0x80c0006

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 272
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
default['yum']['elrepo-extras']['mirrorlist'] = "http://elrepo.org/mirrors-elrepo-extras.el#{node['platform_version'].to_i}"
default['yum']['elrepo-extras']['description'] = 'ELRepo.org Extras Yum Repository'
default['yum']['elrepo-extras']['gpgkey'] = 'http://elrepo.org/RPM-GPG-KEY-elrepo.org'
default['yum']['elrepo-extras']['enabled'] = true


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo esc_url(get_feed_link()); ?>">

  <?php wp_head(); ?>
</head>


text:
'use strict';

angular.module('core')
  .service('goaliepageService', function () {
    this.getPlayerContent = function () {
      return ([
        {
          pageTitle: 'Goalie Dashboard',
          sbnav1: '', sbnav1url: '/',
          sbnav2: '', sbnav2url: '#',
          sbnav3: '', sbnav3url: '#',
          sbnav4: '', sbnav4url: '#',
          sbnav5: '', sbnav5url: '#',
          sbnav6: '', sbnav6url: '#',
          secATitle: '', secADesc: '',
          secBTitle: '', secBDesc: '',
          secCTitle: '', secCDesc: '',
          secDTitle: '', secDDesc: ''
        }
      ]);
    };
    this.getPlayerFeatures = function () {
      return (['Nutrition','Goal Planning','Evaluations', 'Online Journal']);
    };
    this.getPlayerMenu = function () {
      return ([
        {name: 'Journal',           desc: '',       i: 'fa fa-star-o',   url: '/goaliedash'},
        {name: 'Goals',             desc: '',       i: 'fa fa-star-o',   url: '/goaliedash'},
        {name: 'Evaluations',       desc: '',       i: 'fa fa-star-o',   url: '/goaliedash'},
        {name: 'Coach Feedback',    desc: '',       i: 'fa fa-star-o',   url: '/goaliedash'},
        {name: 'Submit New Rating', desc: '',       i: 'fa fa-star-o',   url: '/goaliedash'}
      ]);
    };
    this.getPlayerNutrition = function () {
      return ([
        {name: 'Record Entry',         desc: 'Create a Food Journal Entry.',             i: 'fa fa-star-o',   url: '#'},
        {name: 'Nutritional Facts',    desc: 'View and search nutritional information.', i: 'fa fa-star-o',   url: '#'},
        {name: 'Track and View',       desc: 'View your food entry statistics.',         i: 'fa fa-star-o',   url: '#'}
      ]);
    };
    this.getPlayerGoals = function () {
      return ([
        {name: 'Season Goals',        desc: 'Create or edit your season goals.',                 i: 'fa fa-star-o',   url: '#'},
        {name: 'Mid-Season Goals - review',   desc: 'Prepare for the mid-season review with your coach.',i: 'fa fa-star-o',   url: '#'},
        {name: 'End-of-Season Goals - review',desc: 'Prepare for end-of-season review with your coach.',i: 'fa fa-star-o',   url: '#'}
      ]);
    };
    this.getPlayerEvals = function () {
      return ([
        {name: 'Practice Goals',         desc: 'Record and remember what to practice on.',             i: 'fa fa-star-o',   url: '#'},
        {name: 'Journal Entry - Practice ',    desc: 'Record positives, negatives, and other information from a practice.', i: 'fa fa-star-o',   url: '#'},
        {name: 'Journal Entry - Game',  desc: 'Record Game Journal Entry (private to you)',         i: 'fa fa-star-o',   url: '#'},
        {name: 'Game Evaluation',       desc: 'Rate Your Game Performance (for coaching staff)',         i: 'fa fa-star-o',   url: '#'},
        {name: 'Mid-Season Evaluation',       desc: 'Record Game Journal Entry',         i: 'fa fa-star-o',   url: '#'}
      ]);
    };
  });


text:
title: stack
---

## Stacks

`stack` is one of the most used containers in C++. A container is a data structure that stores a collection of objects, some in order, some not. All containers have a different set of functions that allow you to access an object(s) in that collection.

`std::stack` is part of the C++ standard library (hence the prefix `std::`) and allows you to store data in Last In First Out (LIFO) order. NOTE: **All objects within a stack must be of the same data type**

The data type you store within a stack goes within angle brackets next to the stack keyword. For example, if you would like to store a collection of integers the stack would be `std::stack<int> stack_name`

### Stack LIFO Explanation

`stack` allows us to push and pop in specific order. **Push** means inserting an object at the top of the stack. **Pop** means pulling out the last inserted object from the top of the stack. So when you push it is at the top and when you pop you extract the last inserted element.

![alt text](https://github.com/mohammadaziz313/helloworld/blob/master/Lifo_stack.png "LIFO Stack Push and Pop Example")

### Stack Operations

The stack container supports the following operations:
  - push
  - pop
  - empty
  - size
  - back

#### Push

Allows you to insert a new element at the top of the stack, above the current top element.

```cpp
//Push operation in Stack
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
  std::stack<int> s;

  s.push(1);    //Pushing 1 at top of the stack
  s.push(2);    //Pushing 2 at top of the stack

  return 0;
}
```

#### Top

Allows you to access the the top element without removing it from your stack.

```cpp
//Top operation in Stack
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
  std::stack<int> s;

  s.push(1);    //Pushing 1 at top of the stack
  s.push(2);    //Pushing 2 at top of the stack

  std::cout<<s.top()<<'\n';     //Accessing the top of the stack
  std::cout<<s.top()<<'\n';     //Accessing the top of the stack

  return 0;
}
```

    Output:
    2
    2

#### Pop

Removes the element on top of the stack, effectively reducing your stack's size by one.

```cpp
//Pop operation in Stack
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
  std::stack<int> s;

  s.push(1);    //Pushing 1 at top of the stack
  s.push(2);    //Pushing 2 at top of the stack

  std::cout<<s.top()<<'\n';   //Accessing the top of the stack
  s.pop();                    //Removing element from the top of stack
  std::cout<<s.top()<<'\n';   //Accessing the top of the stack

  return 0;
}
```

    Output:
    2
    1

#### Size

Returns the number of elements in the `stack`.

```cpp
//Size operation in Stack
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
  std::stack<int> s;

  s.push(1);    //Pushing 1 at top of the stack
  s.push(2);    //Pushing 2 at top of the stack

  std::cout<<s.size()<<'\n';  //Showing the size of the stack
  s.pop();                    //Removing element from the top of stack
  std::cout<<s.size()<<'\n';  //Showing the size of the stack
  s.pop();                    //Removing element from the top of stack
  std::cout<<s.size()<<'\n';  //Showing the size of the stack

  return 0;
}
```

    Output:
    2
    1
    0

#### Empty

Returns whether the `stack` is empty ,i.e. whether your stack size is zero.
It returns `true` if stack's size 0 else returns `false`

```cpp
//Empty operation in Stack
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
  std::stack<int> s;

  s.push(1);
  s.push(2);

  while(s.empty() != false){
      std::cout<<s.top()<<'\n';
      s.pop();
  }

  std::cout<<"Out of loop"<<'\n';
  return 0;
}
```

    Output:
    2
    1
    Out of loop

## Uses of Stack

1. Expression Evaluation and Conversion.
   stacks are used to evaluate and convert expressions like prefx, postfix and infix expression.
2. In Recursive functions to keep information about the active functions or subroutines.
3. In Backtracking, as in DFS algorithm.
4. Memory management, run-time environment for nested language features. etc


text:
using namespace ofxCv;
using namespace cv;

void ofApp::setup() {
	cam.setup(640, 480);

    gui.setup();
    gui.add(resetBackground.set("Reset Background", false));
    gui.add(learningTime.set("Learning Time", 30, 0, 30));
    gui.add(thresholdValue.set("Threshold Value", 10, 0, 255));
}

void ofApp::update() {
	cam.update();
    if(resetBackground) {
        background.reset();
        resetBackground = false;
    }
	if(cam.isFrameNew()) {
        background.setLearningTime(learningTime);
        background.setThresholdValue(thresholdValue);
		background.update(cam, thresholded);
		thresholded.update();
	}
}

void ofApp::draw() {
	cam.draw(0, 0);
    if(thresholded.isAllocated()) {
        thresholded.draw(640, 0);
    }
    gui.draw();
}


text:
package com.airstem.airflow.ayush.airflow.fragments.player;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.airstem.airflow.ayush.airflow.R;
import com.airstem.airflow.ayush.airflow.adapters.search.TrackAdapter;
import com.airstem.airflow.ayush.airflow.decorators.LineDivider;
import com.airstem.airflow.ayush.airflow.events.search.SearchTrackListener;
import com.airstem.airflow.ayush.airflow.helpers.internet.InternetHelper;
import com.airstem.airflow.ayush.airflow.model.search.SearchTrack;

import java.util.ArrayList;

/**
 * Created by mcd-50 on 11/7/17.
 */

public class SimilarTrackFragment extends Fragment implements SearchTrackListener {

    boolean isLoading;
    int nextPage = 1;
    ProgressDialog progressDialog;
    InternetHelper internetHelper;

    TextView empty;
    RecyclerView listView;
    SwipeRefreshLayout swipeRefreshLayout;
    LinearLayoutManager linearLayoutManager;

    ArrayList<SearchTrack> mItems;
    TrackAdapter mAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.player_similar_fragment, container, false);

        progressDialog = new ProgressDialog(getContext());
        internetHelper = new InternetHelper(getContext());

        empty = (TextView) rootView.findViewById(R.id.player_similar_fragment_empty);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.player_similar_fragment_refresh);
        listView = (RecyclerView) rootView.findViewById(R.id.player_similar_fragment_list);
        listView.setHasFixedSize(true);
        linearLayoutManager = new LinearLayoutManager(getContext());
        listView.setLayoutManager(linearLayoutManager);
        listView.addItemDecoration(new LineDivider(getContext()));

        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setAdapter();
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                nextPage = 1;
                makeRequest(true);
            }
        });
    }

    private void setAdapter() {
        mItems = new ArrayList<>();
        mAdapter = new TrackAdapter(getContext(), mItems, this);
        listView.setAdapter(mAdapter);
    }

    public boolean hasLoaded = false;
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(this.isVisible()){
            if(isVisibleToUser && !hasLoaded){
                makeRequest(true);
            }
            hasLoaded = true;
        }
    }

    public void makeRequest(boolean showDialog){
        if (internetHelper.isNetworkAvailable()) {
            onNetworkAvailable(showDialog);
        } else {
            empty.setVisibility(View.VISIBLE);
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    private void onNetworkAvailable(final boolean showDialog){
        loadData(showDialog);
        empty.setVisibility(View.GONE);
        listView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int totalItemCount = linearLayoutManager.getItemCount();
                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                if (nextPage != -1 && !isLoading && totalItemCount <= lastVisibleItem) {
                    nextPage = nextPage + 1;
                    loadData(showDialog);
                }
            }
        });
    }

    private void loadData(boolean showDialog) {
        try {
            isLoading = true;
            if(showDialog){
                progressDialog.setMessage("Please wait...");
                progressDialog.setCancelable(false);
                progressDialog.show();
            }

        } catch (Exception e) {
            isLoading = false;
            empty.setVisibility(View.VISIBLE);

            e.printStackTrace();
        }
    }

    @Override
    public void onTrackClick(SearchTrack searchTrack) {

    }
}


text:
'use strict';

app.controller('UserController',['$scope','AuthenticationService','$http','apiBaseUrl', function($scope, AuthenticationService, $http,apiBaseUrl){

    $scope.username = AuthenticationService.user();

    $scope.deleteDatabase = function(){

        $http({
            url: apiBaseUrl + '/admin/delete',
            method: "POST",
            data: {
                username: $scope.username
            },
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(function successCallback(response) {
            alert("database deleted");
        }, function errorCallback(response) {
            console.error("error deleting DB: " + response);
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
    }

}]);


text:
source ./extras/colors

# Homebrew Setup
# ------------------------------------------------------------------------------

brew update

printf "\n$INFO - %s$RESET\n" "Updated Homebrew."

brew upgrade

printf "\n$INFO - %s$RESET\n" "Upgraded Homebrew."

# Binaries
# ------------------------------------------------------------------------------

binaries=(

  # Unix Tools
  coreutils
  findutils
  bash
  bash-completion
  grep

  # General Tools
  graphicsmagick
  git
  node
  tree

  # Miscellaneous
  youtube-dl

)

# Install Binaries
# ------------------------------------------------------------------------------

brew install ${binaries[@]}

printf "\n$INFO - %s$RESET\n" "Installed binary packages."

# Cleanup
# ------------------------------------------------------------------------------

brew cleanup

printf "\n$INFO - %s$RESET\n" "Cleaning up Homebrew."


text:
from threading import Lock
from flask import Flask, render_template, session, request, \
    copy_current_request_context
from flask_socketio import SocketIO, emit, join_room, leave_room, \
    close_room, rooms, disconnect

# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on installed packages.
async_mode = None

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()

def background_thread():
    """Example of how to send server generated events to clients."""
    count = 0
    while True:
        socketio.sleep(10)
        count += 1
        socketio.emit('my_response',
                      {'data': 'Server generated event', 'count': count})

@app.route('/')
def index():
    return render_template('index.html', async_mode=socketio.async_mode)

@socketio.event
def my_event(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']})

@socketio.event
def my_broadcast_event(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']},
         broadcast=True)

@socketio.event
def join(message):
    join_room(message['room'])
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': 'In rooms: ' + ', '.join(rooms()),
          'count': session['receive_count']})

@socketio.event
def leave(message):
    leave_room(message['room'])
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': 'In rooms: ' + ', '.join(rooms()),
          'count': session['receive_count']})

@socketio.on('close_room')
def on_close_room(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response', {'data': 'Room ' + message['room'] + ' is closing.',
                         'count': session['receive_count']},
         to=message['room'])
    close_room(message['room'])

@socketio.event
def my_room_event(message):
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response',
         {'data': message['data'], 'count': session['receive_count']},
         to=message['room'])

@socketio.event
def disconnect_request():
    @copy_current_request_context
    def can_disconnect():
        disconnect()

    session['receive_count'] = session.get('receive_count', 0) + 1
    # for this emit we use a callback function
    # when the callback function is invoked we know that the message has been
    # received and it is safe to disconnect
    emit('my_response',
         {'data': 'Disconnected!', 'count': session['receive_count']},
         callback=can_disconnect)

@socketio.event
def my_ping():
    emit('my_pong')

@socketio.event
def connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(background_thread)
    emit('my_response', {'data': 'Connected', 'count': 0})

@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected', request.sid)

if __name__ == '__main__':
    socketio.run(app)


text:
jQuery(function ($) {
	function toggle_thumb_content() {
		if($('#cc_you_can_work_category').val()=='work')
			$('#cc_you_can_work_thumbnail_content_container').fadeIn();
		else {
			$('#cc_you_can_work_thumbnail_content_container').fadeOut();
			//$('#cc_you_can_work_thumbnail_content').val('');
		}
	}
	$(document).ready(function() {
		toggle_thumb_content();

		$('#cc_you_can_work_category').change(toggle_thumb_content);

		$('#cc-sortable').sortable({
			update: function() {
				$('#cc_you_can_order').val(JSON.stringify($('#cc-sortable').sortable('toArray')));
			}
		});
		$('#cc_you_can_order').val(JSON.stringify($('#cc-sortable').sortable('toArray')));

	});
});


text:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.ComponentModel.Composition;

namespace CarouselPageDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window,INotifyPropertyChanged
    {
        #region INotifyPropertyChanged RaisePropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        private int _lastIndex = 0;

        #region CarouselPages (INotifyPropertyChanged Property)
        [ImportMany(typeof(ICarouselPage))]
        private ObservableCollection<ICarouselPage> _carouselPages;

        public ObservableCollection<ICarouselPage> CarouselPages
        {
            get { return _carouselPages; }
            set
            {
                if (_carouselPages != null && _carouselPages.Equals(value)) return;
                _carouselPages = value;
                RaisePropertyChanged("CarouselPages");
            }
        }
        #endregion

        #region ActivePage (INotifyPropertyChanged Property)

        private ICarouselPage _activePage;

        public ICarouselPage ActivePage
        {
            get { return _activePage; }
            set
            {
                if (_activePage != null && _activePage.Equals(value)) return;
                _activePage = value;
                RaisePropertyChanged("ActivePage");
            }
        }

        #endregion

        #region AnimaterPage (INotifyPropertyChanged Property)

        private ICarouselPage _animaterPage;

        public ICarouselPage AnimaterPage
        {
            get { return _animaterPage; }
            set
            {
                if (_animaterPage != null && _animaterPage.Equals(value)) return;
                _animaterPage = value;
                RaisePropertyChanged("AnimaterPage");
            }
        }

        #endregion

        public MainWindow()
        {
            PageComposition();
            //Console.WriteLine(_carouselPages.Count);
            InitializeComponent();
        }

        private void PageComposition()
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

        private void PointerOnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Viewer == null) return;
            AnimaterPage = CarouselPages[_lastIndex];
            if (_lastIndex < Pointer.SelectedIndex)
                Viewer.BeginStoryboard((Storyboard) Resources["SlideLeftToRight"]);
            else
                Viewer.BeginStoryboard((Storyboard) Resources["SlideRightToLeft"]);

            _lastIndex = Pointer.SelectedIndex;
        }
    }
}


text:
package org.apache.taglibs.standard.lang.jstl;

/**
 * <p>The implementation of the multiply operator
 *
 * @author Nathan Abramson - Art Technology Group
 */

public class MultiplyOperator
        extends ArithmeticOperator {
    //-------------------------------------
    // Singleton
    //-------------------------------------

    public static final MultiplyOperator SINGLETON =
            new MultiplyOperator();

    //-------------------------------------

    /**
     * Constructor
     */
    public MultiplyOperator() {
    }

    //-------------------------------------
    // Expression methods
    //-------------------------------------

    /**
     * Returns the symbol representing the operator
     */
    public String getOperatorSymbol() {
        return "*";
    }

    //-------------------------------------

    /**
     * Applies the operator to the given double values, returning a double
     */
    public double apply(double pLeft,
                        double pRight,
                        Logger pLogger) {
        return pLeft * pRight;
    }

    //-------------------------------------

    /**
     * Applies the operator to the given double values, returning a double
     */
    public long apply(long pLeft,
                      long pRight,
                      Logger pLogger) {
        return pLeft * pRight;
    }

    //-------------------------------------
}


text:
package net.davidlauzon.logshaper;

import net.davidlauzon.logshaper.event.LogEvent;
import net.davidlauzon.logshaper.subscriber.AbstractSubscriber;
import net.davidlauzon.logshaper.subscriber.LogSubscriber;

/**
 * Created by david on 15-11-06.
 */
public class SubscriberMock extends AbstractSubscriber implements LogSubscriber
{
    private String lastMessage;

    @Override
    public void onTrace(LogEvent event)
    {
        publish("TRACE " + formatEvent(event));
    }

    @Override
    public void onTrace(LogEvent event, Throwable throwable)
    {
        onTrace(event);
        throwable.printStackTrace();
    }

    @Override
    public void onDebug(LogEvent event)
    {
        publish("DEBUG " + formatEvent(event));
    }

    @Override
    public void onDebug(LogEvent event, Throwable throwable)
    {
        onDebug(event);
        throwable.printStackTrace();
    }

    @Override
    public void onInfo(LogEvent event)
    {
        publish( " INFO " + formatEvent(event));
    }

    @Override
    public void onInfo(LogEvent event, Throwable throwable)
    {
        onInfo(event);
        throwable.printStackTrace();
    }

    @Override
    public void onWarn(LogEvent event)
    {
        publish( " WARN " + formatEvent(event));
    }

    @Override
    public void onWarn(LogEvent event, Throwable throwable)
    {
        onWarn(event);
        throwable.printStackTrace();
    }

    @Override
    public void onError(LogEvent event)
    {
        publish( "ERROR " + formatEvent(event));
    }

    @Override
    public void onError(LogEvent event, Throwable throwable)
    {
        onError(event);
        throwable.printStackTrace();
    }

    private void publish( String msg )
    {
        // Keep the last message so we can validate the output in the tests
        lastMessage = msg;
        System.out.println( msg );
    }

    public String getLastMessage() {
        return lastMessage;
    }
}


text: from Connection1 import Connection


text:
package com.thoughtworks.go.server.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.helper.*;
import com.thoughtworks.go.config.ConfigMigrator;
import com.thoughtworks.go.config.CruiseConfig;
import com.thoughtworks.go.config.JobConfigs;
import com.thoughtworks.go.config.MingleConfig;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.StageConfig;
import com.thoughtworks.go.config.TrackingTool;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.domain.JobResult;
import com.thoughtworks.go.domain.JobState;
import com.thoughtworks.go.domain.MaterialRevisions;
import com.thoughtworks.go.domain.PipelineDependencyGraphOld;
import com.thoughtworks.go.domain.PipelineTimelineEntry;
import com.thoughtworks.go.domain.StageIdentifier;
import com.thoughtworks.go.domain.StageResult;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.presentation.pipelinehistory.JobHistory;
import com.thoughtworks.go.presentation.pipelinehistory.NullStageHistoryItem;
import com.thoughtworks.go.presentation.pipelinehistory.PipelineGroupModel;
import com.thoughtworks.go.presentation.pipelinehistory.PipelineInstanceModel;
import com.thoughtworks.go.presentation.pipelinehistory.PipelineInstanceModels;
import com.thoughtworks.go.presentation.pipelinehistory.PipelineModel;
import com.thoughtworks.go.presentation.pipelinehistory.StageInstanceModel;
import com.thoughtworks.go.presentation.pipelinehistory.StageInstanceModels;
import com.thoughtworks.go.server.dao.PipelineDao;
import com.thoughtworks.go.server.dao.StageDao;
import com.thoughtworks.go.server.domain.JobDurationStrategy;
import com.thoughtworks.go.server.domain.PipelineTimeline;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.domain.user.PipelineSelections;
import com.thoughtworks.go.server.persistence.MaterialRepository;
import com.thoughtworks.go.server.scheduling.TriggerMonitor;
import com.thoughtworks.go.server.service.result.HttpOperationResult;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;

import static com.thoughtworks.go.helper.PipelineMaterialModificationMother.modification;
import static com.thoughtworks.go.presentation.pipelinehistory.PipelineInstanceModels.createPipelineInstanceModels;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class PipelineHistoryServiceTest {
    private PipelineHistoryService pipelineHistoryService;
    private PipelineDao pipelineDao;
    private GoConfigService goConfigService;
    private SecurityService securityService;

    private static final CruiseConfig CRUISE_CONFIG = ConfigMigrator.loadWithMigration("<cruise xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
            + "     xsi:noNamespaceSchemaLocation=\"cruise-config.xsd\" schemaVersion=\"17\" >"
            + "<server artifactsdir=\"target/testfiles/tmpCCRoot/data/logs\"></server>"
            + "  <pipelines>"
            + "    <pipeline name='pipeline'>"
            + "        <materials>"
            + "            <svn url='ape'/>"
            + "        </materials>"
            + "        <stage name='auto'>"
            + "            <jobs>"
            + "                <job name='unit'/>"
            + "            </jobs>"
            + "        </stage>"
            + "        <stage name='manual'>"
            + "            <jobs>"
            + "                <job name='unit'/>"
            + "            </jobs>"
            + "        </stage>"
            + "    </pipeline>"
            + "  </pipelines>"
            + "</cruise>").config;
    private ScheduleService scheduleService;
    private PipelineTimeline pipelineTimeline;
    private PipelineUnlockApiService pipelineUnlockService;
    private SchedulingCheckerService schedulingCheckerService;
    private StageDao stageDao;
    private static final Username USERNAME = new Username(new CaseInsensitiveString("bar"));
    private PipelineConfig config;
    private PipelineLockService pipelineLockService;
    public PipelinePauseService pipelinePauseService;

    @Before
    public void setUp() {
        pipelineDao = mock(PipelineDao.class);
        goConfigService = mock(GoConfigService.class);
        securityService = mock(SecurityService.class);
        scheduleService = mock(ScheduleService.class);
        pipelineLockService = mock(PipelineLockService.class);
        pipelineTimeline = mock(PipelineTimeline.class);
        pipelineUnlockService = mock(PipelineUnlockApiService.class);
        schedulingCheckerService = mock(SchedulingCheckerService.class);
        pipelinePauseService = mock(PipelinePauseService.class);
        stageDao = mock(StageDao.class);
        pipelineHistoryService = new PipelineHistoryService(pipelineDao, stageDao, goConfigService, securityService, scheduleService,
                mock(MaterialRepository.class),
                JobDurationStrategy.ALWAYS_ZERO,
                mock(TriggerMonitor.class),
                pipelineTimeline,
                pipelineUnlockService, schedulingCheckerService, pipelineLockService, pipelinePauseService);
        config = CRUISE_CONFIG.pipelineConfigByName(new CaseInsensitiveString("pipeline"));
    }

    @Test
    public void shouldUnderstandLatestPipelineModel() {
        Username username = new Username(new CaseInsensitiveString("loser"));
        String pipelineName = "junk";
        String groupName = "some-pipeline-group";

        PipelineInstanceModel pipeline = PipelineInstanceModel.createPipeline(pipelineName, -1, "1.0", BuildCause.createManualForced(), new StageInstanceModels());
        when(pipelineDao.loadHistory(pipelineName, 1, 0)).thenReturn(createPipelineInstanceModels(pipeline));
        when(schedulingCheckerService.canManuallyTrigger(pipelineName, username)).thenReturn(false);
        when(securityService.hasViewPermissionForPipeline(username, pipelineName)).thenReturn(true);
        when(securityService.hasOperatePermissionForPipeline(username.getUsername(), pipelineName)).thenReturn(true);
        when(goConfigService.isLockable(pipelineName)).thenReturn(true);
        when(goConfigService.findGroupNameByPipeline(new CaseInsensitiveString(pipelineName))).thenReturn(groupName);
        when(goConfigService.isUserAdminOfGroup(username.getUsername(), groupName)).thenReturn(true);
        when(pipelineLockService.lockedPipeline(pipelineName)).thenReturn(new StageIdentifier(pipelineName, 9, "stage1", "3"));
        stubConfigServiceToReturnPipeline(pipelineName, PipelineConfigMother.createPipelineConfig(pipelineName, "dev", "foo", "bar"));

        PipelineModel loadedPipeline = pipelineHistoryService.latestPipelineModel(username, pipelineName);

        assertThat(loadedPipeline.canForce(), is(false));
        assertThat(loadedPipeline.canOperate(), is(true));
        assertThat(loadedPipeline.getLatestPipelineInstance().isLockable(), is(true));
        assertThat(loadedPipeline.getLatestPipelineInstance().isCurrentlyLocked(), is(true));
        assertThat(loadedPipeline.getLatestPipelineInstance(), is(pipeline));
        assertThat(loadedPipeline.canAdminister(), is(true));
    }

    @Test
    public void shouldLoadCanOperateAndLockableFlagForAllPipelines() {
        Username jez = new Username(new CaseInsensitiveString("jez"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        PipelineConfig pipelineConfig = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline1"));
        pipelineConfig.setTrackingTool(new TrackingTool("http://link", "#"));

        pipelineConfig = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline2"));
        pipelineConfig.setMingleConfig(new MingleConfig("baseUrl", "id"));

        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        PipelineInstanceModels activePipelineInstances = createPipelineInstanceModels();

        StageInstanceModel stage1 = new StageInstanceModel("stage1", "2", JobHistory.withJob("plan1", JobState.Building, JobResult.Unknown, new Date()));
        activePipelineInstances.add(activePipeline("pipeline1", 10, 1.0, stage1, new NullStageHistoryItem("stage2", true)));

        activePipelineInstances.add(activePipeline("pipeline2", 5, 2.5, new StageInstanceModel("plan1", "2", JobHistory.withJob("plan1", JobState.Building, JobResult.Unknown, new Date()))));

        activePipelineInstances.add(
                activePipeline("non-operatable-pipeline", 5, 2.0, new StageInstanceModel("one", "2", JobHistory.withJob("plan1", JobState.Completed, JobResult.Failed, new Date()))));
        when(goConfigService.isLockable("pipeline1")).thenReturn(true);

        when(pipelineDao.loadActivePipelines()).thenReturn(activePipelineInstances);
        stubPermisssionsForActivePipeline(jez, cruiseConfig, "pipeline1", true, true);
        stubPermisssionsForActivePipeline(jez, cruiseConfig, "pipeline2", true, false);
        stubPermisssionsForActivePipeline(jez, cruiseConfig, "non-operatable-pipeline", false, false);
        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);
        when(securityService.hasOperatePermissionForStage("pipeline1", "stage1", CaseInsensitiveString.str(jez.getUsername()))).thenReturn(true);

        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(jez, PipelineSelections.ALL);

        PipelineModel secondPipelineModel = groups.get(0).getPipelineModels().get(1);
        assertPipelineIs(secondPipelineModel, "pipeline2", true, false);
        PipelineInstanceModel secondPim = secondPipelineModel.getLatestPipelineInstance();
        assertThat(secondPim.getTrackingTool(), is(nullValue()));
        assertThat(secondPim.getMingleConfig(), is(new MingleConfig("baseUrl", "id")));
        assertThat(secondPim.isLockable(), is(false));

        PipelineModel firstPipelineModel = groups.get(0).getPipelineModels().get(0);
        assertPipelineIs(firstPipelineModel, "pipeline1", true, true);
        PipelineInstanceModel pim = firstPipelineModel.getLatestPipelineInstance();
        assertThat(pim.isLockable(), is(true));
        assertThat(pim.getTrackingTool(), is(new TrackingTool("http://link", "#")));
        assertThat(pim.getMingleConfig(), is(new MingleConfig()));

        PipelineModel nonOperatablePipelineModel = groups.get(1).getPipelineModels().get(0);
        assertPipelineIs(nonOperatablePipelineModel, "non-operatable-pipeline", false, false);
    }

    @Test
    public void shouldLoadCurrentlyLockedStatusFlagForAllPipelines() {
        Username foo = new Username(new CaseInsensitiveString("foo"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        PipelineInstanceModels activePipelineInstances = createPipelineInstanceModels();

        PipelineInstanceModel pipeline1 = activePipeline("pipeline1", 9, 2.0,
                new StageInstanceModel("stage1", "3", StageResult.Failed, new StageIdentifier()),
                new StageInstanceModel("stage2", "4", JobHistory.withJob("plan1", JobState.Building, JobResult.Unknown, new Date())));

        PipelineInstanceModel pipeline2 = activePipeline("pipeline2", 5, 2.5,
                new StageInstanceModel("plan1", "2", JobHistory.withJob("plan1", JobState.Building, JobResult.Unknown, new Date())));

        PipelineInstanceModel pipeline3 = activePipeline("pipeline3", 5, 2.5,
                new StageInstanceModel("plan1", "2", JobHistory.withJob("plan1", JobState.Building, JobResult.Unknown, new Date())));

        activePipelineInstances.add(pipeline1);
        activePipelineInstances.add(pipeline2);
        activePipelineInstances.add(pipeline3);

        when(pipelineDao.loadActivePipelines()).thenReturn(activePipelineInstances);

        stubPermisssionsForActivePipeline(foo, cruiseConfig, "pipeline1", true, true);
        stubPermisssionsForActivePipeline(foo, cruiseConfig, "pipeline2", true, true);
        stubPermisssionsForActivePipeline(foo, cruiseConfig, "pipeline3", true, true);
        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);
        when(goConfigService.isLockable("pipeline1")).thenReturn(true);
        when(goConfigService.isLockable("pipeline2")).thenReturn(true);
        when(pipelineLockService.lockedPipeline("pipeline1")).thenReturn(new StageIdentifier("pipeline1", 9, "stage1", "3"));

        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(foo, PipelineSelections.ALL);
        PipelineGroupModel group = groups.get(0);

        PipelineModel pipelineModel1 = group.getPipelineModels().get(0);
        PipelineInstanceModel firstPipelinePIM = pipelineModel1.getActivePipelineInstances().get(0);
        assertThat(firstPipelinePIM.isLockable(), is (true));
        assertThat(firstPipelinePIM.isCurrentlyLocked(), is(true));

        PipelineModel pipelineModel2 = group.getPipelineModels().get(1);
        PipelineInstanceModel secondPipeline = pipelineModel2.getActivePipelineInstances().get(0);
        assertThat(secondPipeline.isLockable(), is (true));
        assertThat(secondPipeline.isCurrentlyLocked(), is(false));

        PipelineModel pipelineModel3 = group.getPipelineModels().get(2);
        PipelineInstanceModel thirdPipeline = pipelineModel3.getActivePipelineInstances().get(0);
        assertThat(thirdPipeline.isLockable(), is (false));
        assertThat(thirdPipeline.isCurrentlyLocked(), is(false));
    }

    @Test
    public void shouldLoadCanOperateFlagForAllNonActivePipelines() {
        Username jez = new Username(new CaseInsensitiveString("jez"));
        setupExpectationsForAllActivePipelinesWithTwoGroups(jez);

        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(jez, PipelineSelections.ALL);

        PipelineModel secondPipelineModel = groups.get(0).getPipelineModels().get(1);
        assertPipelineIs(secondPipelineModel, "pipeline2", true, false);

        PipelineModel firstPipelineModel = groups.get(0).getPipelineModels().get(0);
        assertPipelineIs(firstPipelineModel, "pipeline1", true, true);

        PipelineModel nonOperatablePipelineModel = groups.get(1).getPipelineModels().get(0);
        assertPipelineIs(nonOperatablePipelineModel, "non-operatable-pipeline", false, false);
    }

    @Test
    public void shouldSetAdminPermissionOnEveryGroupModel() throws Exception {
        Username jez = new Username(new CaseInsensitiveString("jez"));
        setupExpectationsForAllActivePipelinesWithTwoGroups(jez);
        when(goConfigService.isUserAdminOfGroup(jez.getUsername(), "defaultGroup")).thenReturn(true);
        when(goConfigService.isUserAdminOfGroup(jez.getUsername(), "foo")).thenReturn(false);

        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(jez, PipelineSelections.ALL);

        assertThat(groups.get(0).getPipelineModels().get(0).canAdminister(), is(true));
        assertThat(groups.get(0).getPipelineModels().get(1).canAdminister(), is(true));
        assertThat(groups.get(1).getPipelineModels().get(0).canAdminister(), is(false));

        verify(goConfigService, times(1)).isUserAdminOfGroup(jez.getUsername(), "defaultGroup");
        verify(goConfigService, times(1)).isUserAdminOfGroup(jez.getUsername(), "foo");
    }

    private void setupExpectationsForAllActivePipelinesWithTwoGroups(Username jez) {
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        PipelineInstanceModels activePipelineInstances = createPipelineInstanceModels();

        when(pipelineDao.loadActivePipelines()).thenReturn(activePipelineInstances);
        stubForNonActivePipeline(jez, cruiseConfig, "pipeline1", true, true,
                activePipeline("pipeline1", 10, 2.0, new StageInstanceModel("stage1", "10", JobHistory.withJob("plan1", JobState.Completed, JobResult.Failed, new Date()))));
        stubForNonActivePipeline(jez, cruiseConfig, "pipeline2", true, false,
                activePipeline("pipeline2", 10, 2.0, new StageInstanceModel("stage1", "8", JobHistory.withJob("plan1", JobState.Completed, JobResult.Passed, new Date()))));
        stubForNonActivePipeline(jez, cruiseConfig, "non-operatable-pipeline", false, false,
                activePipeline("non-operatable-pipeline", 10, 2.0, new StageInstanceModel("one", "10", JobHistory.withJob("defaultJob", JobState.Completed, JobResult.Failed, new Date()))));
        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);
    }

    private void stubForNonActivePipeline(Username username, CruiseConfig cruiseConfig, String pipelineName, boolean operatePermission, boolean canTrigger, PipelineInstanceModel pipeline) {
        stubPermisssionsForActivePipeline(username, cruiseConfig, pipelineName, operatePermission, canTrigger);
        when(pipelineDao.loadHistory(pipelineName, 1, 0)).thenReturn(createPipelineInstanceModels(pipeline));
    }

    private void stubPermisssionsForActivePipeline(Username username, CruiseConfig cruiseConfig, String pipelineName, boolean operatePermission, boolean canTrigger) {
        when(securityService.hasViewPermissionForPipeline(username, pipelineName)).thenReturn(true);
        when(securityService.hasOperatePermissionForPipeline(username.getUsername(), pipelineName)).thenReturn(operatePermission);
        stubConfigServiceToReturnPipeline(pipelineName, cruiseConfig.pipelineConfigByName(new CaseInsensitiveString(pipelineName)));
        when(schedulingCheckerService.canManuallyTrigger(pipelineName, username)).thenReturn(canTrigger);
    }

    private void assertPipelineIs(PipelineModel secondPipelineModel, String pipelineName, boolean canOperate, boolean canForce) {
        assertThat(secondPipelineModel.canOperate(), is(canOperate));
        assertThat(secondPipelineModel.canForce(), is(canForce));
        PipelineInstanceModel secondActivePipeline = secondPipelineModel.getActivePipelineInstances().get(0);
        assertThat(secondActivePipeline.getName(), is(pipelineName));
    }

    private PipelineInstanceModel activePipeline(String pipelineName, int pipelineCounter, double naturalOrder, StageInstanceModel... moreStages) {
        StageInstanceModels stagesForNonOperatablePipeline = new StageInstanceModels();
        stagesForNonOperatablePipeline.addAll(Arrays.asList(moreStages));
        PipelineInstanceModel nonOperatablePipeline = PipelineInstanceModel.createPipeline(pipelineName, -1, "1.0", BuildCause.createWithEmptyModifications(), stagesForNonOperatablePipeline);
        nonOperatablePipeline.setNaturalOrder(naturalOrder);
        nonOperatablePipeline.setCounter(pipelineCounter);
        return nonOperatablePipeline;
    }

    @Test
    public void shouldLoadAllActivePipelinesWithPreviousStageState() {
        Username foo = new Username(new CaseInsensitiveString("foo"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        PipelineInstanceModels activePipelineInstances = createPipelineInstanceModels();

        PipelineInstanceModel earlier = activePipeline("pipeline1", 9, 2.0,
                new StageInstanceModel("stage1", "3", StageResult.Failed, new StageIdentifier()),
                new StageInstanceModel("stage2", "4", JobHistory.withJob("plan1", JobState.Building, JobResult.Unknown, new Date())));
        earlier.setId(1);
        PipelineInstanceModel latest = activePipeline("pipeline1", 10, 1.0,
                new StageInstanceModel("stage1", "4", JobHistory.withJob("plan1", JobState.Building, JobResult.Unknown, new Date())),
                new NullStageHistoryItem("stage2", true));
        latest.setId(2);

        activePipelineInstances.add(latest);
        activePipelineInstances.add(earlier);

        when(pipelineDao.loadActivePipelines()).thenReturn(activePipelineInstances);

        when(pipelineDao.loadHistory(1)).thenReturn(earlier);
        when(pipelineDao.loadHistory(2)).thenReturn(latest);
        when(pipelineDao.loadHistory(3)).thenReturn(activePipeline("pipeline1", 11, 3.0,
                new StageInstanceModel("stage1", "3", StageResult.Failed, new StageIdentifier()),
                new StageInstanceModel("stage2", "2", StageResult.Passed, new StageIdentifier())));

        when(pipelineTimeline.runBefore(2, new CaseInsensitiveString("pipeline1"))).thenReturn(new PipelineTimelineEntry("pipeline1", 1, 9, new HashMap<String, List<PipelineTimelineEntry.Revision>>()));
        when(pipelineTimeline.runBefore(1, new CaseInsensitiveString("pipeline1"))).thenReturn(new PipelineTimelineEntry("pipeline1", 3, 11, new HashMap<String, List<PipelineTimelineEntry.Revision>>()));

        stubPermisssionsForActivePipeline(foo, cruiseConfig, "pipeline1", true, true);
        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);

        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(foo, PipelineSelections.ALL);
        PipelineGroupModel group = groups.get(0);
        PipelineModel pipelineModel = group.getPipelineModels().get(0);
        PipelineInstanceModels activePipelines = pipelineModel.getActivePipelineInstances();

        assertPipelineIs(activePipelines.get(0), "pipeline1", "stage1", StageResult.Failed);
        assertPipelineIs(activePipelines.get(1), "pipeline1", "stage2", StageResult.Passed);
    }

    @Test
    public void allActivePipelines_shouldOnlyKeepSelectedPipelines() {
        Username foo = new Username(new CaseInsensitiveString("foo"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        PipelineInstanceModels activePipelineInstances = createPipelineInstanceModels(
                activePipeline("pipeline1", 1, 1.0),
                activePipeline("pipeline2", 1, 1.0),
                activePipeline("pipeline4", 1, 1.0),
                activePipeline("non-operatable-pipeline", 1, 1.0)
        );
        for (String pipeline : new String[]{"pipeline1", "pipeline2", "pipeline3", "pipeline4", "non-operatable-pipeline"}) {
            stubPermisssionsForActivePipeline(foo, cruiseConfig, pipeline, true, true);
            when(pipelineDao.loadHistory(pipeline,1,0)).thenReturn(createPipelineInstanceModels());
        }
        when(pipelineDao.loadActivePipelines()).thenReturn(activePipelineInstances);

        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);
        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(foo, new PipelineSelections(Arrays.asList("pipeline1","pipeline2")));
        assertThat(groups.size(),is(2));
        assertThat(groups.get(0).getName(),is("defaultGroup"));
        assertThat(groups.get(0).containsPipeline("pipeline1"),is(false));
        assertThat(groups.get(0).containsPipeline("pipeline2"),is(false));
        assertThat(groups.get(0).containsPipeline("pipeline3"),is(true));
        assertThat(groups.get(0).containsPipeline("pipeline4"),is(true));
        assertThat(groups.get(1).getName(),is("foo"));
        assertThat(groups.get(1).containsPipeline("non-operatable-pipeline"),is(true));
    }

    @Test
    public void allActivePipelines_shouldRemove_EmptyGroups() {
        Username bar = new Username(new CaseInsensitiveString("non-existant"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        when(pipelineDao.loadActivePipelines()).thenReturn(createPipelineInstanceModels());
        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);

        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(bar, new PipelineSelections());

        assertThat(groups.isEmpty(),is(true));
    }

    @Test
    public void shouldGetActivePipeline() {
        Username foo = new Username(new CaseInsensitiveString("foo"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        PipelineInstanceModels activePipelineInstances = createPipelineInstanceModels(
                activePipeline("pipeline1", 1, 1.0),
                activePipeline("pipeline2", 1, 1.0),
                activePipeline("pipeline4", 1, 1.0),
                activePipeline("non-operatable-pipeline", 1, 1.0)
        );
        for (String pipeline : new String[]{"pipeline1", "pipeline2", "pipeline3", "pipeline4", "non-operatable-pipeline"}) {
            stubPermisssionsForActivePipeline(foo, cruiseConfig, pipeline, true, true);
            when(pipelineDao.loadHistory(pipeline, 1, 0)).thenReturn(createPipelineInstanceModels());
        }
        when(pipelineDao.loadActivePipelines()).thenReturn(activePipelineInstances);

        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);
        List<PipelineGroupModel> groups = pipelineHistoryService.getActivePipelineInstance(foo, "pipeline1");
        assertThat(groups.size(), is(1));
        assertThat(groups.get(0).getName(), is("defaultGroup"));
        assertThat(groups.get(0).containsPipeline("pipeline1"), is(true));
    }

    @Test
    public void getActivePipelineInstance_shouldRemoveEmptyGroups() {
        Username foo = new Username(new CaseInsensitiveString("foo"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        when(pipelineDao.loadActivePipelines()).thenReturn(createPipelineInstanceModels());
        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);
        List<PipelineGroupModel> groups = pipelineHistoryService.getActivePipelineInstance(foo, "pipeline1");
        assertThat(groups.isEmpty(),is(true));
    }

    @Test
    public void allActivePipelines_shouldOnlyKeepSelectedPipelines_andRemove_EmptyGroups() {
        Username foo = new Username(new CaseInsensitiveString("foo"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        PipelineInstanceModels activePipelineInstances = createPipelineInstanceModels(
                activePipeline("pipeline1", 1, 1.0),
                activePipeline("pipeline2", 1, 1.0),
                activePipeline("pipeline4", 1, 1.0),
                activePipeline("non-operatable-pipeline", 1, 1.0)
        );
        for (String pipeline : new String[]{"pipeline1", "pipeline2", "pipeline3", "pipeline4", "non-operatable-pipeline"}) {
            stubPermisssionsForActivePipeline(foo, cruiseConfig, pipeline, true, true);
            when(pipelineDao.loadHistory(pipeline,1,0)).thenReturn(createPipelineInstanceModels());
        }
        when(pipelineDao.loadActivePipelines()).thenReturn(activePipelineInstances);

        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);
        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(foo, new PipelineSelections(Arrays.asList("non-operatable-pipeline")));
        assertThat(groups.size(), is(1));
        assertThat(groups.get(0).getName(), is("defaultGroup"));
        assertThat(groups.get(0).containsPipeline("pipeline1"), is(true));
        assertThat(groups.get(0).containsPipeline("pipeline2"),is(true));
        assertThat(groups.get(0).containsPipeline("pipeline3"), is(true));
        assertThat(groups.get(0).containsPipeline("pipeline4"), is(true));
    }

    @Test
    public void allActivePipelines_shouldSkipNullPipelinesWhenLoadingPreviousStageStae() {
        Username foo = new Username(new CaseInsensitiveString("foo"));
        CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(ConfigFileFixture.CONFIG).config;
        when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
        PipelineInstanceModels activePipelineInstances = createPipelineInstanceModels();

        PipelineInstanceModel latest = activePipeline("pipeline1", 10, 1.0,
                new StageInstanceModel("stage1", "4", JobHistory.withJob("plan1", JobState.Building, JobResult.Unknown, new Date())),
                new NullStageHistoryItem("stage2", true));
        latest.setId(2);

        activePipelineInstances.add(latest);

        when(pipelineDao.loadActivePipelines()).thenReturn(activePipelineInstances);

        when(pipelineDao.loadHistory(1)).thenReturn(null);
        when(pipelineDao.loadHistory(2)).thenReturn(latest);
        when(pipelineDao.loadHistory(3)).thenReturn(activePipeline("pipeline1", 11, 3.0,
                new StageInstanceModel("stage1", "3", StageResult.Failed, new StageIdentifier())));

        //2>1>3

        when(pipelineTimeline.runBefore(2, new CaseInsensitiveString("pipeline1"))).thenReturn(new PipelineTimelineEntry("pipeline1", 1, 9, new HashMap<String, List<PipelineTimelineEntry.Revision>>()));
        when(pipelineTimeline.runBefore(1, new CaseInsensitiveString("pipeline1"))).thenReturn(new PipelineTimelineEntry("pipeline1", 3, 11, new HashMap<String, List<PipelineTimelineEntry.Revision>>()));

        stubPermisssionsForActivePipeline(foo, cruiseConfig, "pipeline1", true, true);
        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(any(String.class)))).thenReturn(true);

        List<PipelineGroupModel> groups = pipelineHistoryService.allActivePipelineInstances(foo, PipelineSelections.ALL);
        PipelineGroupModel group = groups.get(0);
        PipelineModel pipelineModel = group.getPipelineModels().get(0);
        PipelineInstanceModels activePipelines = pipelineModel.getActivePipelineInstances();

        assertPipelineIs(activePipelines.get(0), "pipeline1", "stage1", StageResult.Failed);
    }

    private void assertPipelineIs(PipelineInstanceModel pipeline, String pipelineName, String activeStageName, StageResult previousStageResult) {
        assertThat(pipeline.getName(), is(pipelineName));
        StageInstanceModel activeStage = pipeline.activeStage();
        assertThat(activeStage.getName(), is(activeStageName));
        assertThat(activeStage.getPreviousStage().getResult(), is(previousStageResult));
    }

    @Test
    public void findPipelineInstanceUsingIdShouldPopulateAppendEmptyStagesFromConfig() throws Exception {
        ensureConfigHasPipeline("pipeline");
        ensureHasPermission(Username.ANONYMOUS, "pipeline");
        PipelineInstanceModel instanceModel = PipelineInstanceModel.createEmptyPipelineInstanceModel("pipeline", BuildCause.createNeverRun(), new StageInstanceModels());
        when(pipelineDao.loadHistoryByIdWithBuildCause(1L)).thenReturn(instanceModel);
        stubConfigServiceToReturnPipeline("pipeline", config);

        PipelineInstanceModel pipelineInstance = pipelineHistoryService.findPipelineInstance("pipeline", 1, 1L, Username.ANONYMOUS, new HttpOperationResult());
        StageInstanceModels models = pipelineInstance.getStageHistory();
        assertThat(models.size(), is(2));
    }

    @Test
    public void findPipelineInstanceShouldPopulateAppendEmptyStagesFromConfig() throws Exception {
        ensureConfigHasPipeline("pipeline");
        ensureHasPermission(Username.ANONYMOUS, "pipeline");
        PipelineInstanceModel instanceModel = PipelineInstanceModel.createEmptyPipelineInstanceModel("pipeline", BuildCause.createNeverRun(), new StageInstanceModels());
        when(pipelineDao.findPipelineHistoryByNameAndCounter("pipeline", 1)).thenReturn(instanceModel);
        stubConfigServiceToReturnPipeline("pipeline", config);

        PipelineInstanceModel pipelineInstance = pipelineHistoryService.findPipelineInstance("pipeline", 1, Username.ANONYMOUS, new HttpOperationResult());
        StageInstanceModels models = pipelineInstance.getStageHistory();
        assertThat(models.size(), is(2));
    }

    @Test
    public void findPipelineInstanceShouldChangeResultTo404WhenPipelineNotFound() throws Exception {
        ensureConfigHasPipeline("pipeline");
        ensureHasPermission(Username.ANONYMOUS, "pipeline");
        when(pipelineDao.findPipelineHistoryByNameAndCounter("pipeline", 1)).thenReturn(null);
        when(goConfigService.pipelineConfigNamed(new CaseInsensitiveString("pipeline"))).thenReturn(config);

        HttpOperationResult operationResult = new HttpOperationResult();
        PipelineInstanceModel pipelineInstance = pipelineHistoryService.findPipelineInstance("pipeline", 1, Username.ANONYMOUS, operationResult);
        assertThat(pipelineInstance, is(nullValue()));
        assertThat(operationResult.httpCode(), is(404));
    }

    @Test
    public void shouldPopulateIfPipelineCanBeUnlockedAndIsLockable() throws Exception {
        ensureConfigHasPipeline("pipeline");

        stubConfigServiceToReturnPipeline("pipeline", config);
        when(goConfigService.isLockable("pipeline")).thenReturn(true);

        ensureHasPermission(Username.ANONYMOUS, "pipeline");

        PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createNeverRun(), new StageInstanceModels());
        when(pipelineDao.findPipelineHistoryByNameAndCounter("pipeline", 1)).thenReturn(instanceModel);

        when(pipelineUnlockService.canUnlock(eq("pipeline"), eq(Username.ANONYMOUS), any(HttpOperationResult.class))).thenReturn(true);

        PipelineInstanceModel pipelineInstance = pipelineHistoryService.findPipelineInstance("pipeline", 1, Username.ANONYMOUS, new HttpOperationResult());
        assertThat(pipelineInstance.canUnlock(), is(true));
        assertThat(pipelineInstance.isLockable(), is(true));
    }

    @Test public void shouldPopulateWetherStageAndPipelineCanBeRunAccordingToOperatePermissions() throws Exception {
        ensureConfigHasPipeline("pipeline");
        ensureHasPermission(Username.ANONYMOUS, "pipeline");
        StageInstanceModels stages = new StageInstanceModels();
        stages.add(new StageInstanceModel("dev", "1", new JobHistory()));
        stages.add(new StageInstanceModel("qa", "1", new JobHistory()));
        PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createNeverRun(), stages);
        when(pipelineDao.findPipelineHistoryByNameAndCounter("pipeline", 1)).thenReturn(instanceModel);
        stubConfigServiceToReturnPipeline("pipeline", config);

        StageInstanceModel firstStage = instanceModel.getStageHistory().get(0);
        when(scheduleService.canRun(instanceModel.getPipelineIdentifier(), firstStage.getName(), CaseInsensitiveString.str(Username.ANONYMOUS.getUsername()),
                instanceModel.hasPreviousStageBeenScheduled(firstStage.getName()))).thenReturn(true);
        StageInstanceModel secondStage = instanceModel.getStageHistory().get(1);
        when(scheduleService.canRun(instanceModel.getPipelineIdentifier(), secondStage.getName(), CaseInsensitiveString.str(Username.ANONYMOUS.getUsername()),
                instanceModel.hasPreviousStageBeenScheduled(secondStage.getName()))).thenReturn(false);

        when(securityService.hasOperatePermissionForStage("pipeline", "dev", CaseInsensitiveString.str(Username.ANONYMOUS.getUsername()))).thenReturn(true);
        when(securityService.hasOperatePermissionForStage("pipeline", "qa", CaseInsensitiveString.str(Username.ANONYMOUS.getUsername()))).thenReturn(false);

        PipelineInstanceModel pipelineInstance = pipelineHistoryService.findPipelineInstance("pipeline", 1, Username.ANONYMOUS, new HttpOperationResult());
        StageInstanceModels models = pipelineInstance.getStageHistory();
        assertThat(models.get(0).getCanRun(), is(true));
        assertThat(models.get(1).getCanRun(), is(false));
        assertThat(models.get(0).hasOperatePermission(), is(true));
        assertThat(models.get(1).hasOperatePermission(), is(false));
    }

    @Test public void shouldPopulatePipelineInstanceModelWithTheBeforeAndAfterForTheGivenPipeline() throws Exception {
        DateTime now = new DateTime();
        PipelineTimelineEntry first = PipelineMaterialModificationMother.modification(Arrays.asList("first"), 1, "123", now);
        PipelineTimelineEntry second = PipelineMaterialModificationMother.modification(Arrays.asList("first"), 1, "123", now);

        when(pipelineTimeline.runBefore(1, new CaseInsensitiveString("pipeline"))).thenReturn(first);
        when(pipelineTimeline.runAfter(1, new CaseInsensitiveString("pipeline"))).thenReturn(second);

        PipelineInstanceModel expected = PipelineHistoryMother.pipelineHistoryItemWithOneStage("pipeline", "auto", now.toDate());
        expected.setId(1);
        when(pipelineDao.loadHistory(1)).thenReturn(expected);
        when(goConfigService.currentCruiseConfig()).thenReturn(CRUISE_CONFIG);
        when(goConfigService.pipelineConfigNamed(new CaseInsensitiveString("pipeline"))).thenReturn(config);
        when(securityService.hasOperatePermissionForStage("pipeline", "auto", CaseInsensitiveString.str(Username.ANONYMOUS.getUsername()))).thenReturn(true);
        ensureHasPermission(Username.ANONYMOUS, "pipeline");

        PipelineInstanceModel model = pipelineHistoryService.load(1, Username.ANONYMOUS, new HttpOperationResult());
        assertThat(model.getPipelineBefore(), is(first));
        assertThat(model.getPipelineAfter(), is(second));
        assertThat(model.stage("auto").hasOperatePermission(), is(true));
    }

    @Test
    public void shouldReturnDependencyGraphOnlyIfUserHasPermissions() throws Exception {
        PipelineInstanceModel instanceModel = pim("blahPipeline");
        instanceModel.setId(12);
        PipelineDependencyGraphOld expected = new PipelineDependencyGraphOld(instanceModel, createPipelineInstanceModels());
        when(pipelineDao.pipelineGraphByNameAndCounter("blahPipeline", 12)).thenReturn(expected);
        ensureConfigHasPipeline("blahPipeline");
        when(goConfigService.downstreamPipelinesOf("blahPipeline")).thenReturn(new ArrayList<PipelineConfig>());
        stubConfigServiceToReturnPipeline("blahPipeline", PipelineConfigMother.pipelineConfig("blahPipeline"));
        when(pipelineTimeline.pipelineBefore(12)).thenReturn(1L);
        when(pipelineDao.loadHistory(1)).thenReturn(new PipelineInstanceModel("blahPipeline", 21, "prev-label", BuildCause.createWithEmptyModifications(), new StageInstanceModels()));

        Username foo = new Username(new CaseInsensitiveString("foo"));
        ensureHasPermission(USERNAME, "blahPipeline");
        assertThat(pipelineHistoryService.pipelineDependencyGraph("blahPipeline", 12, foo, new HttpOperationResult()), is(nullValue()));
        assertThat(pipelineHistoryService.pipelineDependencyGraph("blahPipeline", 12, USERNAME, new HttpOperationResult()), is(expected));
    }

    @Test
    public void shouldReturnGraphWithADiffOfMaterialRevisionsForTheGivenPipeline() throws Exception {
        PipelineInstanceModel pim = pim("blahPipeline");
        MaterialRevisions actualRevs = ModificationsMother.multipleModifications();
        pim.setId(23);
        pim.setMaterialRevisionsOnBuildCause(actualRevs);

        PipelineDependencyGraphOld expected = new PipelineDependencyGraphOld(pim, createPipelineInstanceModels());

        when(pipelineDao.pipelineGraphByNameAndCounter("blahPipeline", 12)).thenReturn(expected);
        ensureConfigHasPipeline("blahPipeline");
        when(goConfigService.downstreamPipelinesOf("blahPipeline")).thenReturn(new ArrayList<PipelineConfig>());

        stubConfigServiceToReturnPipeline("blahPipeline", PipelineConfigMother.pipelineConfig("blahPipeline"));
        when(pipelineTimeline.pipelineBefore(23)).thenReturn(1L);
        when(pipelineDao.loadHistory(1L)).thenReturn(new PipelineInstanceModel("blahPipeline", 21, "prev-label", BuildCause.createWithEmptyModifications(), new StageInstanceModels()));

        ensureHasPermission(USERNAME, "blahPipeline");

        PipelineDependencyGraphOld actual = pipelineHistoryService.pipelineDependencyGraph("blahPipeline", 12, USERNAME, new HttpOperationResult());

        assertThat(actual.pipeline().getPreviousLabel(), is("prev-label"));
        assertThat(actual.pipeline().getPreviousCounter(), is(21));
        assertThat(actual.pipeline().getCurrentRevisions(), is(actualRevs));
    }

    @Test
    public void shouldSetStageRunAndOperatePermissionsInTheDependencyGraph() throws Exception {
        PipelineInstanceModel pim = pim("blahPipeline");
        pim.setId(23);
        pim.getStageHistory().add(new StageInstanceModel("stage", "1", new JobHistory()));
        PipelineDependencyGraphOld expected = new PipelineDependencyGraphOld(pim, createPipelineInstanceModels());
        when(pipelineDao.pipelineGraphByNameAndCounter("blahPipeline", 12)).thenReturn(expected);
        ensureConfigHasPipeline("blahPipeline");
        when(goConfigService.downstreamPipelinesOf("blahPipeline")).thenReturn(new ArrayList<PipelineConfig>());
        stubConfigServiceToReturnPipeline("blahPipeline", PipelineConfigMother.pipelineConfig("blahPipeline"));
        when(scheduleService.canRun(pim.getPipelineIdentifier(), "stage", CaseInsensitiveString.str(USERNAME.getUsername()), true)).thenReturn(true);
        when(securityService.hasOperatePermissionForStage("blahPipeline", "stage", CaseInsensitiveString.str(USERNAME.getUsername()))).thenReturn(true);
        when(pipelineTimeline.pipelineBefore(23)).thenReturn(-1L);

        ensureHasPermission(USERNAME, "blahPipeline");
        PipelineDependencyGraphOld actual = pipelineHistoryService.pipelineDependencyGraph("blahPipeline", 12, USERNAME, new HttpOperationResult());
        assertThat(actual.pipeline().getStageHistory().size(), is(1));
        assertThat(actual.pipeline().getStageHistory().get(0).getCanRun(), is(true));
        assertThat(actual.pipeline().getStageHistory().get(0).hasOperatePermission(), is(true));
    }

    @Test
    public void shouldSetStageRunAndOperatePermissionsInTheDependencyGraphForTheDependentPipelinesOfAPipelineInstance() throws Exception {
        PipelineInstanceModel down1Pim = pim("down1");
        down1Pim.getStageHistory().add(new StageInstanceModel("stage", "1", new JobHistory()));
        PipelineInstanceModel actualPim = pim("blahPipeline");
        actualPim.setId(23);
        PipelineDependencyGraphOld returned = new PipelineDependencyGraphOld(actualPim, createPipelineInstanceModels(down1Pim));
        when(pipelineDao.pipelineGraphByNameAndCounter("blahPipeline", 12)).thenReturn(returned);

        ensureConfigHasPipeline("blahPipeline");
        ensureHasPermission(USERNAME, "blahPipeline");

        ensureConfigHasPipeline("down1");
        ensureHasPermission(USERNAME, "down1");

        when(goConfigService.downstreamPipelinesOf("blahPipeline")).thenReturn(Arrays.asList(PipelineConfigMother.pipelineConfig("down1")));
        stubConfigServiceToReturnPipeline("blahPipeline", PipelineConfigMother.pipelineConfig("blahPipeline"));
        stubConfigServiceToReturnPipeline("down1", PipelineConfigMother.pipelineConfig("down1"));

        when(scheduleService.canRun(down1Pim.getPipelineIdentifier(), down1Pim.getStageHistory().first().getName(), CaseInsensitiveString.str(USERNAME.getUsername()), true)).thenReturn(true);
        when(securityService.hasOperatePermissionForStage("down1", "stage", CaseInsensitiveString.str(USERNAME.getUsername()))).thenReturn(true);
        when(pipelineTimeline.pipelineBefore(23)).thenReturn(-1L);

        PipelineDependencyGraphOld actual = pipelineHistoryService.pipelineDependencyGraph("blahPipeline", 12, USERNAME, new HttpOperationResult());

        StageInstanceModel firstStageOfDown1 = actual.dependencies().get(0).getStageHistory().get(0);
        assertThat(actual.dependencies().size(), is(1));
        assertThat(firstStageOfDown1.hasOperatePermission(), is(true));
        assertThat(firstStageOfDown1.getCanRun(), is(true));
    }

    @Test
    public void shouldReturn404WhenPipelineInstanceIsNotPresent() throws Exception {
        when(pipelineDao.pipelineGraphByNameAndCounter("blahPipeline", 12)).thenReturn(null);
        ensureConfigHasPipeline("blahPipeline");
        ensureHasPermission(USERNAME, "blahPipeline");
        HttpOperationResult result = new HttpOperationResult();
        pipelineHistoryService.pipelineDependencyGraph("blahPipeline", 12, USERNAME, result);
        assertThat(result.canContinue(), is(false));
        assertThat(result.httpCode(), is(404));
        assertThat(result.message(), is("Pipeline [blahPipeline] with counter [12] is not found"));
    }

    @Test
    public void shouldRemoveDependencyPipelineWhichIsNotPresentInConfig() throws Exception {
        ensureConfigHasPipeline("blahPipeline");
        ensureConfigHasPipeline("down1");
        ensureConfigContainsPipelineIs("down2", false);
        when(goConfigService.downstreamPipelinesOf("blahPipeline")).thenReturn(Arrays.asList(PipelineConfigMother.pipelineConfig("down1")));

        stubConfigServiceToReturnPipeline("blahPipeline", PipelineConfigMother.pipelineConfig("blahPipeline"));
        PipelineConfig downOneConfig = PipelineConfigMother.pipelineConfig("down1");
        stubConfigServiceToReturnPipeline("down1", downOneConfig);

        when(goConfigService.isLockable("blahPipeline")).thenReturn(true);
        when(pipelineUnlockService.canUnlock("blahPipeline", USERNAME, new HttpOperationResult())).thenReturn(true);
        when(pipelineTimeline.pipelineBefore(23)).thenReturn(-1L);

        ensureHasPermission(USERNAME, "blahPipeline");
        ensureHasPermission(USERNAME, "down1");

        PipelineInstanceModel actualPim = pim("down1");
        actualPim.setCanRun(false);
        actualPim.setStageHistory(PipelineHistoryMother.stagePerJob("stage", PipelineHistoryMother.job(JobResult.Failed)));
        PipelineInstanceModel returned = pim("blahPipeline");
        returned.setId(23);
        PipelineDependencyGraphOld graph = new PipelineDependencyGraphOld(returned, createPipelineInstanceModels(actualPim, pim("down2")));
        when(pipelineDao.pipelineGraphByNameAndCounter("blahPipeline", 12)).thenReturn(graph);
        when(schedulingCheckerService.canManuallyTrigger(actualPim.getName(), USERNAME)).thenReturn(true);

        PipelineDependencyGraphOld actual = pipelineHistoryService.pipelineDependencyGraph("blahPipeline", 12, USERNAME, new HttpOperationResult());
        assertThat(actual.dependencies().size(), is(1));
        assertThat(actual.dependencies().get(0), is(actualPim));
        assertThat(actual.dependencies().get(0).getCanRun(), is(true));
    }

    @Test
    public void shouldAddOtherDependentPipelinePresentInConfig() throws Exception {
        ensureConfigHasPipeline("blahPipeline");
        ensureConfigHasPipeline("down1");
        ensureConfigHasPipeline("noPermission");

        PipelineConfig other = GoConfigMother.createPipelineConfigWithMaterialConfig("other");
        other.add(new StageConfig(new CaseInsensitiveString("badChildhood"), new JobConfigs()));

        when(pipelineUnlockService.canUnlock(eq("blahPipeline"), eq(USERNAME), any(HttpOperationResult.class))).thenReturn(true);
        when(goConfigService.isLockable("blahPipeline")).thenReturn(true);
        when(goConfigService.downstreamPipelinesOf("blahPipeline")).thenReturn(Arrays.asList(other));
        stubConfigServiceToReturnPipeline("blahPipeline", PipelineConfigMother.pipelineConfig("blahPipeline", new StageConfig(new CaseInsensitiveString("first"), new JobConfigs())));
        ensureHasPermission(USERNAME, "blahPipeline");

        stubConfigServiceToReturnMaterialAndPipeline("down1", new MaterialConfigs(MaterialConfigsMother.svnMaterialConfig()), PipelineConfigMother.pipelineConfig("down1", new StageConfig(
                new CaseInsensitiveString("first"), new JobConfigs()
        )));
        ensureHasPermission(USERNAME, "down1");

        stubConfigServiceToReturnMaterialAndPipeline("other", new MaterialConfigs(), other);
        when(pipelineTimeline.pipelineBefore(23)).thenReturn(-1L);

        PipelineInstanceModel actualPim = pim("down1");
        PipelineInstanceModel noPermission = pim("noPermission");
        PipelineInstanceModel returned = pim("blahPipeline");
        returned.setId(23);
        PipelineDependencyGraphOld graph = new PipelineDependencyGraphOld(returned, createPipelineInstanceModels(actualPim, noPermission));
        when(pipelineDao.pipelineGraphByNameAndCounter("blahPipeline", 12)).thenReturn(graph);

        PipelineDependencyGraphOld actual = pipelineHistoryService.pipelineDependencyGraph("blahPipeline", 12, USERNAME, new HttpOperationResult());
        assertThat(actual.pipeline().isLockable(), is(true));
        assertThat(actual.pipeline().canUnlock(), is(true));
        assertThat(actual.dependencies().size(), is(2));
        assertThat(actual.dependencies().get(0), is(actualPim));
        assertHasMaterial(actualPim, MaterialsMother.svnMaterial().config());
        PipelineInstanceModel otherInstance = actual.dependencies().get(1);
        assertThat(otherInstance.getName(), is("other"));
        assertThat(otherInstance.getMaterials().size(), is(0));
    }

    @Test
    public void shouldReturnPageNumberForAPipelineCounter() {
        when(pipelineDao.getPageNumberForCounter("some-pipeline", 100, 10)).thenReturn(1);
        assertThat(pipelineHistoryService.getPageNumberForCounter("some-pipeline", 100, 10), is(1));
    }

    private void stubConfigServiceToReturnMaterialAndPipeline(String downPipelineName, MaterialConfigs downPipelineMaterial, PipelineConfig down1Config) {
        when(goConfigService.materialConfigsFor(new CaseInsensitiveString(downPipelineName))).thenReturn(downPipelineMaterial);
        stubConfigServiceToReturnPipeline(downPipelineName, down1Config);
    }

    private void stubConfigServiceToReturnPipeline(String blahPipelineName, PipelineConfig blahPipelineConfig) {
        when(goConfigService.pipelineConfigNamed(new CaseInsensitiveString(blahPipelineName))).thenReturn(blahPipelineConfig);
        when(goConfigService.findFirstStageOfPipeline(new CaseInsensitiveString(blahPipelineName))).thenReturn(blahPipelineConfig.get(0));
    }

    private void assertHasMaterial(PipelineInstanceModel otherInstance, MaterialConfig materialConfig) {
        assertThat(otherInstance, is(not(nullValue())));
        assertThat(otherInstance.getMaterials(), is(not(nullValue())));
        assertThat(otherInstance.getMaterials().size(), is(1));
        assertThat(otherInstance.getMaterials(), hasItem(materialConfig));
    }

    private PipelineInstanceModel pim(String pipelineName) {
        return PipelineHistoryMother.singlePipeline(pipelineName, new StageInstanceModels());
    }

    private void ensureConfigHasPipeline(String pipelineName) {
        ensureConfigContainsPipelineIs(pipelineName, true);
    }

    private void ensureHasPermission(Username bar, String pipelineName) {
        when(securityService.hasViewPermissionForPipeline(bar, pipelineName)).thenReturn(true);
    }

    private void ensureConfigContainsPipelineIs(String pipelineName, boolean isPresent) {
        when(goConfigService.hasPipelineNamed(new CaseInsensitiveString(pipelineName))).thenReturn(isPresent);
    }
}


text:
[![npm version](https://badge.fury.io/js/%40resolve-js%2Fscripts.svg)](https://badge.fury.io/js/%40resolve-js%2Fscripts)

This package includes scripts and configuration for the [create-resolve-app](../../core/create-resolve-app) package.

Please keep in mind that the resulting configuration must match the [JSON Schema ReSolve Config](configs/schema.resolve.config.json)

![Analytics](https://ga-beacon.appspot.com/UA-118635726-1/packages-resolve-scripts-readme?pixel)


text:
package com.google.api.gax.grpc;

import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.api.gax.rpc.ErrorDetails;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import java.util.Set;

/**
 * Core logic for transforming GRPC exceptions into {@link ApiException}s. This logic is shared
 * amongst all the call types.
 *
 * <p>Package-private for internal use.
 */
class GrpcApiExceptionFactory {

  @VisibleForTesting static final String ERROR_DETAIL_KEY = "grpc-status-details-bin";
  private final ImmutableSet<Code> retryableCodes;

  GrpcApiExceptionFactory(Set<Code> retryCodes) {
    this.retryableCodes = ImmutableSet.copyOf(retryCodes);
  }

  ApiException create(Throwable throwable) {
    if (throwable instanceof StatusException) {
      StatusException e = (StatusException) throwable;
      return create(throwable, e.getStatus().getCode(), e.getTrailers());
    } else if (throwable instanceof StatusRuntimeException) {
      StatusRuntimeException e = (StatusRuntimeException) throwable;
      return create(throwable, e.getStatus().getCode(), e.getTrailers());
    } else if (throwable instanceof ApiException) {
      return (ApiException) throwable;
    } else {
      // Do not retry on unknown throwable, even when UNKNOWN is in retryableCodes
      return ApiExceptionFactory.createException(
          throwable, GrpcStatusCode.of(Status.Code.UNKNOWN), false);
    }
  }

  private ApiException create(Throwable throwable, Status.Code statusCode, Metadata metadata) {
    boolean canRetry = retryableCodes.contains(GrpcStatusCode.grpcCodeToStatusCode(statusCode));
    GrpcStatusCode grpcStatusCode = GrpcStatusCode.of(statusCode);

    if (metadata == null) {
      return ApiExceptionFactory.createException(throwable, grpcStatusCode, canRetry);
    }

    byte[] bytes = metadata.get(Metadata.Key.of(ERROR_DETAIL_KEY, Metadata.BINARY_BYTE_MARSHALLER));
    if (bytes == null) {
      return ApiExceptionFactory.createException(throwable, grpcStatusCode, canRetry);
    }

    com.google.rpc.Status status;
    try {
      status = com.google.rpc.Status.parseFrom(bytes);
    } catch (InvalidProtocolBufferException e) {
      return ApiExceptionFactory.createException(throwable, grpcStatusCode, canRetry);
    }

    ErrorDetails.Builder errorDetailsBuilder = ErrorDetails.builder();
    errorDetailsBuilder.setRawErrorMessages(status.getDetailsList());
    return ApiExceptionFactory.createException(
        throwable, grpcStatusCode, canRetry, errorDetailsBuilder.build());
  }
}


text:
import { put } from 'redux-saga/effects';
import { setCurrentUser } from 'modules/data/ducks/actions';
import { NAMESPACE } from './constants';
import createDucks from '../utils/createDucks';
import rootSelector from './rootSelector';

const ducks = createDucks({
  key: 'fetch',
  apiName: 'fetchProfile',
  rootSelector: (state) => rootSelector(state),
  namespace: NAMESPACE,
  sagas: {
    * beforeFulfilled(profile) {
      yield put(setCurrentUser(profile));
    },
  },
});

// shape of ducks
// {
//   actions: { fetch },
//   default: { fetch: reducer },
//   selector rootSelector.fetch,
//   sagas,
// }

export default ducks.default; export const actions = ducks.actions; export const selector = ducks.selector; export const sagas = ducks.sagas;