text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>OPTRAJ: Référence de la classe optimisation.Stats.StatTable</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

OPTRAJ

Page principale

Paquetages

Classes

Fichiers

          <input type="text" id="MSearchField" value="Recherche" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Liste des classes

Index des classes

Hiérarchie des classes

Membres de classe

 Tout Classes Espaces de nommage Fichiers Fonctions Variables

optimisation

Stats

StatTable

Fonctions membres publiques |
Fonctions membres privées |
Attributs privés |
Liste de tous les membres

Référence de la classe optimisation.Stats.StatTable

Représente un tableau de probabilités d'affectations pour un ensemble de SolTemp et un Systeme.
 Plus de détails...

Fonctions membres publiques

def 	__init__

 	Constructeur d'une StatTable vide.  Plus de détails...

def 	__str__

 	transforme une StatTable en version affichable  Plus de détails...

def 	genStatTable

 	génère le tableau de statistiques normalisées a partir d'un set de SolTemp  Plus de détails...

def 	updateRow

 	nettoie une ligne de StatTable en mettant à None toutes les probabilités concernant les ouvriers qui ne sont pas dans ouvrierDispo.  Plus de détails...

def 	pickRandomId

 	Extrait un identifiant d'ouvrier aléatoire correspondant au chantier passé en paramètre.  Plus de détails...

Fonctions membres privées

def 	_getRandomId

 	Renvois aléatoirement l'indice d'un ouvrier disponible pour une ligne donnée.  Plus de détails...

Attributs privés

 	_table

 	_sigma

Description détaillée

Représente un tableau de probabilités d'affectations pour un ensemble de SolTemp et un Systeme.

Ce tableau est défini à partir d'un objet SolTemps et ressemblerais à ceci si on l'écrivait à la main :

1 	2 	3 	4 	5 	6 	7 	8 	9 	10 	11 	12 	13 	14 	15 	16 	17 	18 	19 	20 	21 	22 	23 	24 	25 	26 	27 	28 	29 	30

0.6 	0.8 	0.2 	0.4 	0.4 	0.8 	0 	0.8 	0.2 	0 	0.4 	0.8 	0.4 	0.2 	0.2 	0.4 	0.6 	0 	0.2 	0.4 	0.4 	0.4 	0.4 	0 	0.4 	0.2 	0.2 	0 	0 	0.2

0.4 	0.2 	0.2 	0.4 	0.4 	0.2 	0 	0.4 	0 	0.4 	0.2 	0 	0 	0.2 	0.2 	0.2 	0 	0.2 	0.2 	0 	0.4 	0 	0 	0.4 	0.2 	0.2 	0 	0.6 	0.2 	0.2

0.6 	0.8 	0.2 	0.4 	0.4 	0.8 	0 	0.6 	0.4 	0 	0.2 	0.8 	0.8 	0.4 	0.2 	0.4 	0.6 	0 	0.2 	0.2 	0.4 	0.2 	0.4 	0 	0.4 	0.2 	0.2 	0 	0 	0.2

0 	0 	0 	0.2 	0.2 	0 	0.6 	0 	0.2 	0 	0.2 	0 	0.2 	0.2 	0.4 	0 	0.4 	0.2 	0.2 	0.2 	0 	0.4 	0 	0.2 	0 	0 	0.2 	0 	0 	0

0.4 	0.2 	0.8 	0.4 	0.4 	0.2 	0.4 	0.2 	0.4 	1.0 	0.4 	0.2 	0 	0.4 	0.4 	0.6 	0 	0.8 	0.6 	0.4 	0.6 	0.2 	0.6 	0.8 	0.4 	0.8 	0.6 	1.0 	1.0 	0.8

Chaque ligne étant associée à un id de chantier, et chaque colonne associée à un id d'ouvrier. Les indice représentant la probabilité de trouver l'ouvrier i affecté au chantier j en prenant une des SolTemp au hasard.

Documentation des constructeurs et destructeur

          def optimisation.Stats.StatTable.__init__
          (

          self	)

Constructeur d'une StatTable vide.

Documentation des fonctions membres

          def optimisation.Stats.StatTable.__str__
          (

          self	)

transforme une StatTable en version affichable

Renvoie

une version affichable de la StatTable sous forme de string

          def optimisation.Stats.StatTable._getRandomId
          (

          self,

          workingSiteNumber

          )

private

Renvois aléatoirement l'indice d'un ouvrier disponible pour une ligne donnée.

   On ne rend pas l'indice d'un ouvrier dont la probabilité dans la table est 0 ou None, mais on peut rendre un objet None si aucun ouvrier n'est susceptible d'être pris.

Paramètres

workingSiteNumber	l'indice du chantier (la ligne) pour lequel on effectue l'opération. Un int

Renvoie

le numéro de l'ouvrier tiré. int ou None si aucun ouvrier n'est disponible

Voici le graphe des appelants de cette fonction :

          def optimisation.Stats.StatTable.genStatTable
          (

          self,

          soltemps,

          system

          )

génère le tableau de statistiques normalisées a partir d'un set de SolTemp

Paramètres

soltemps	ensemble de solutions temporaires de référence :: set(SolTemp)

system	le système pour lequel on génère la table :: System

          def optimisation.Stats.StatTable.pickRandomId
          (

          self,

          workingSiteNumber

          )

Extrait un identifiant d'ouvrier aléatoire correspondant au chantier passé en paramètre.

   L'ouvrier est considéré affecté au chantier, Son entrée pour cette ligne est passée à None et le sigma est adapté en conséquence.

Paramètres

workingSiteNumber	l'indice du chantier (la ligne) concerné par l'opération. Un int

Renvoie

le numéro de l'ouvrier tiré. int ou None si aucune ouvrier n'était disponible

Voici le graphe d'appel pour cette fonction :

          def optimisation.Stats.StatTable.updateRow
          (

          self,

          availablesWorkers,

          workingSiteNumber,

          chancesToTakeNew = 100

          )

nettoie une ligne de StatTable en mettant à None toutes les probabilités concernant les ouvriers qui ne sont pas dans ouvrierDispo.

   Cette méthode effectue plusieurs opérations sur une ligne de la StatTable (repérée par workingSiteNumber) :
   - la probabilité liée aux ouvriers ne faisant pas partie de availablesWorkers passe à None
   - suivant la valeur de chancesToTakeNew, on donne une chance de piocher un ouvrier dont l'indice était à 0.
   - le sigma est adapté en conséquence et reflete la somme des probabilités mises à jours de la ligne.

Paramètres

availablesWorkers	l'ensemble des ouvriers disponibles. Un itérable (set, dict, list...) de Worker

workingSiteNumber	l'indice du chantier (la ligne) pour lequel on effectue l'opération. Un int

Documentation des données membres

          optimisation.Stats.StatTable._sigma

private

          optimisation.Stats.StatTable._table

private

La documentation de cette classe a été générée à partir du fichier suivant :

D:/Users/Sacapuces/Documents/Travail/M1/optraj.istic.univ-rennes1.fr/src/optimisation/Stats.py

<address class="footer">
Généré le Samedi Novembre 23 2013 23:24:43 pour OPTRAJ par

 1.8.5
</address>


text:
'use strict';

/**
 * @ngdoc directive
 * @name izzyposWebApp.directive:adminPosHeader
 * @description
 * # adminPosHeader
 */
app.directive('header', function () {
  return {
    templateUrl: 'scripts/directives/header/header.html',
    restrict: 'E',
    replace: true,
  }
});

redpajama_set_name: RedPajamaGithub


text:
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"

using System;
using System.Drawing.Drawing2D;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;

namespace TheArtOfDev.HtmlRenderer.WinForms.Adapters
{
    /// <summary>
    /// Adapter for WinForms graphics path object for core.
    /// </summary>
    internal sealed class GraphicsPathAdapter : RGraphicsPath
    {
        /// <summary>
        /// The actual WinForms graphics path instance.
        /// </summary>
        private readonly GraphicsPath _graphicsPath = new GraphicsPath();

        /// <summary>
        /// the last point added to the path to begin next segment from
        /// </summary>
        private RPoint _lastPoint;

        /// <summary>
        /// The actual WinForms graphics path instance.
        /// </summary>
        public GraphicsPath GraphicsPath
        {
            get { return _graphicsPath; }
        }

        public override void Start(double x, double y)
        {
            _lastPoint = new RPoint(x, y);
        }

        public override void LineTo(double x, double y)
        {
            _graphicsPath.AddLine((float)_lastPoint.X, (float)_lastPoint.Y, (float)x, (float)y);
            _lastPoint = new RPoint(x, y);
        }

        public override void ArcTo(double x, double y, double size, Corner corner)
        {
            float left = (float)(Math.Min(x, _lastPoint.X) - (corner == Corner.TopRight || corner == Corner.BottomRight ? size : 0));
            float top = (float)(Math.Min(y, _lastPoint.Y) - (corner == Corner.BottomLeft || corner == Corner.BottomRight ? size : 0));
            _graphicsPath.AddArc(left, top, (float)size * 2, (float)size * 2, GetStartAngle(corner), 90);
            _lastPoint = new RPoint(x, y);
        }

        public override void Dispose()
        {
            _graphicsPath.Dispose();
        }

        /// <summary>
        /// Get arc start angle for the given corner.
        /// </summary>
        private static int GetStartAngle(Corner corner)
        {
            int startAngle;
            switch (corner)
            {
                case Corner.TopLeft:
                    startAngle = 180;
                    break;
                case Corner.TopRight:
                    startAngle = 270;
                    break;
                case Corner.BottomLeft:
                    startAngle = 90;
                    break;
                case Corner.BottomRight:
                    startAngle = 0;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("corner");
            }
            return startAngle;
        }
    }
}


text:
module Radius
  # Abstract base class for all parsing errors.
  class ParseError < StandardError
  end

  # Occurs when the Parser expects an end tag for one tag and finds the end tag for another.
  class WrongEndTagError < ParseError
    def initialize(expected_tag, got_tag, stack)
      stack_message = " with stack #{stack.inspect}" if stack
      super("wrong end tag `#{got_tag}' found for start tag `#{expected_tag}'#{stack_message}")
    end
  end

  # Occurs when Parser cannot find an end tag for a given tag in a template or when
  # tags are miss-matched in a template.
  class MissingEndTagError < ParseError
    # Create a new MissingEndTagError object for +tag_name+.
    def initialize(tag_name, stack)
      stack_message = " with stack #{stack.inspect}" if stack
      super("end tag not found for start tag `#{tag_name}'#{stack_message}")
    end
  end

  # Occurs when Context#render_tag cannot find the specified tag on a Context.
  class UndefinedTagError < ParseError
    # Create a new UndefinedTagError object for +tag_name+.
    def initialize(tag_name)
      super("undefined tag `#{tag_name}'")
    end
  end

  class TastelessTagError < ParseError #:nodoc:
    def initialize(tag, stack)
      super("internal error with tasteless tag #{tag.inspect} and stack #{stack.inspect}")
    end
  end

  class UndefinedFlavorError < ParseError #:nodoc:
    def initialize(tag, stack)
      super("internal error with unknown flavored tag #{tag.inspect} and stack #{stack.inspect}")
    end
  end
end


text:
(function(){
    this.page_config={
    };
    //命名空间
    this.space_uploader = {};
    this.space_select   = {};
    this.space_industry = {};
    this.space_framework= {};
    this.space_create   = {};

}).call(this);

//选择行业页面显示及文本内容
(function(){

    this.view_box={
        show:function(){
            var $head   = $('#header'),
            $box    = $('#industry-choose'),
            $items  = $('#item-container');
            $head.css('position','fixed');
            //$box.css('top','50px');
            $box.animate({top:0+'%'},150,'linear',function(){
                $items.hide();
            });
        },
        hide:function(){
            var $head   = $('#header'),
            $box    = $('#industry-choose'),
            $items  = $('#item-container');
            $items.show();
            $head.css('position','static');
            $box.animate({top:100+'%'},150,'linear');
        }
    };
}).call(space_industry);

//框架绑定
(function(){
    this.first_active=0;
    this.selected = [];
    this.input_selected=[];
    this.second_level = function(){
        var parent = space_industry.list[space_framework.first_active],
            list = parent.child,
            ll = list.length,
            selected = space_framework.selected,
            ret = [],
            first = [{active:false,name:'全部'}];

        for(var n = 0 ; n < ll; n++) {
            var a = false;
            if(selected.indexOf(list[n]) != -1){
                a = true;
            }
            ret.push({active:a,name:list[n]});
        }
        if(selected.indexOf(parent.name) != -1){
            first[0].active = true;
        }

        return first.concat(ret);
    };
    this.list_render = function(index){
        if(typeof index != 'undefined'){
            space_framework.first_active=index;
        }
        space_framework.industry.btn_confirm=space_framework.selected.length>0?true:false;
        space_framework.industry.list=space_industry.list;
        space_framework.industry.second_level=space_framework.second_level();
    };
    this.add_selected = function(name,isinput){
        var list = space_framework.selected,
            all =space_industry.list[space_framework.first_active],
            ele = name,
            ll=list.length,
            child=all.child,
            cl=child.length;
        if(name == '全部'){
            ele = all.name;
            for(var i = 0; i < ll; i ++){
                for(var n = 0; n <cl ; n++){
                    if(list[i] == child[n]){
                        list.splice(i,1);
                        i--;
                    }
                }
            }
        }
        else{
            if(!isinput){
                for(var i = 0; i < ll; i ++){
                    if(list[i] == all.name){
                        list.splice(i,1);
                        i--;
                    }
                }
            }
        }
        if(list.length<5 && typeof ele != 'undefined' && list.indexOf(ele) == -1){
                list.push(ele);
        }
        space_framework.industry.selected  = list;
    };
    this.write_new = function(){
        if(!!space_framework.industry.input){
            space_framework.add_selected(space_framework.industry.input,true);
            space_framework.list_render();
            space_framework.industry.input='';
        }
    };
    this.industry = avalon.define('industry-select', function (vm) {
        //space_industry.view_box.hide();
        vm.list=[];
        vm.selected= [];
        vm.input_selected=[];
        vm.second_level = [];
        vm.input = '';
        vm.btn_confirm=false;
        vm.cancle_industry=function(el){
            space_framework.selected.splice(el,1);
            space_framework.industry.selected = space_framework.selected;
            space_framework.list_render();
        };
        vm.cancle_input_industry=function(el){
            space_framework.input_selected.splice(el,1);
            space_framework.industry.input_selected = space_framework.input_selected;
            space_framework.industry.selected = space_framework.selected = space_framework.input_selected.concat();
            space_framework.list_render();
        };
        vm.first_active=function(index){
            space_framework.list_render(index);
        };
        vm.second_active=function(name){
            space_framework.add_selected(name);
            space_framework.list_render();
        };
        vm.write_new=space_framework.write_new;
        vm.cancle_choose=function(){
            space_framework.industry.input_selected = space_framework.input_selected;
            space_framework.industry.selected = space_framework.selected = space_framework.input_selected.concat();
            space_industry.view_box.hide();
            space_framework.list_render();
        };
        vm.confirm_choose=function(){
            if(space_framework.selected.length>0){
                space_framework.industry.input_selected = space_framework.input_selected = space_framework.selected.concat();
                space_industry.view_box.hide();
            }
        };
        vm.input_enter=function(e){
            if(e.keyCode == 13){
                space_framework.write_new();
            }
        };
        vm.box_show=function(){
            space_industry.view_box.show();
            space_framework.list_render();
        };
    })
}).call(space_framework);

//获取行业列表
(function(){
    this.list=[];

    data_list=[{child:["移动电商","测试"],name:"移动互联网"},{child:["火锅","连锁经营"],name:"餐饮娱乐"}];

    space_framework.industry.list = space_industry.list = data_list;
    space_framework.industry.second_level=space_framework.second_level();

}).call(space_industry);

/*标题控制*/
(function(){
    var self = this;
    this.avalon_title_control = avalon.define("title-controller", function (vm) {
         vm.toggle_content=function(id){
                $('#btn_invistor'+id).fadeOut();
                $('#invistor'+(parseInt(id)+1)).fadeIn();
        };
    });
}).call(define('title-space'));

//选择阶段 职位
(function(){
    var $select1 = $('#select1'),
        $select2 = $('#select2'),
        $select3 = $('#select3'),
        $select4 = $('#select4');

        $select_position1 = $('#select_position1'),
        $select_position2 = $('#select_position2'),
        $select_position3 = $('#select_position3'),

        $shop_type = $('#shop_type');

    $select1.children('select').change(function(){
        var t = $(this), v= t.val();
        t.prev().html(v);

    });
    $select2.children('select').change(function(){
        var t = $(this), v= t.val();
        t.prev().html(v);
    });
    $select3.children('select').change(function(){
        var t = $(this), v= t.val();
        t.prev().html(v);
    });
    $select4.children('select').change(function(){
        var t = $(this), v= t.val();
        //if(v != 0)
            t.prev().html(v);
    });

    $select_position1.children('select').change(function(){
        var t = $(this), v= t.val();
        //if(v != 0)
            t.prev().html(v);
    });

    $select_position2.children('select').change(function(){
        var t = $(this), v= t.val();
        //if(v != 0)
            t.prev().html(v);
    });

    $select_position3.children('select').change(function(){
        var t = $(this), v= t.val();
        //if(v != 0)
            t.prev().html(v);
    });

    $shop_type.children('select').prev().html('新店开设');
    $shop_type.children('select').change(function(){
        var t = $(this), v= t.val();
        $('#new_shop').toggle();
        $('#old_shop').toggle();

        t.prev().html(v);
    });

}).call(space_select);


text:
from django_json_queries import Query

from .models import Product

class ProductQuery(Query):
    class Meta:
        model = Product
        fields = [
            'name',
            'released',
            'released__year',
            'manufacturer__name',
        ]


text:
class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :events, through: :taggings
  has_many :users, through: :taggings
  belongs_to :category

  validates :name, :category_id, presence: true
end


text:
class Feedback {
  constructor(target) {
    this.target = target;
    this.properties = {};
    this.base = [];
  }

  addBase(error, data) {
    this.base.push({error: error, data: data});
    return this;
  }

  addProperty(name, error, data) {
    if (!this.properties[name]) {
      this.properties[name] = [];
    }

    this.properties[name].push({error: error, data: data});
    return this;
  }
}

export default Feedback;


text:
Number.prototype.toFixed = function (dec){
	var angka = this;
	var pembagi = Math.pow(10,dec);
	var hasil = Math.round(angka*pembagi)/pembagi;
	return hasil;
}


text:
package etcdraft

import (
	"context"
	"encoding/pem"
	"fmt"
	"sync"
	"sync/atomic"
	"time"

	"code.cloudfoundry.org/clock"
	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
	"github.com/hyperledger/fabric-protos-go/orderer"
	"github.com/hyperledger/fabric-protos-go/orderer/etcdraft"
	"github.com/hyperledger/fabric/bccsp"
	"github.com/hyperledger/fabric/common/channelconfig"
	"github.com/hyperledger/fabric/common/flogging"
	"github.com/hyperledger/fabric/orderer/common/cluster"
	"github.com/hyperledger/fabric/orderer/common/types"
	"github.com/hyperledger/fabric/orderer/consensus"
	"github.com/hyperledger/fabric/protoutil"
	"github.com/pkg/errors"
	"go.etcd.io/etcd/raft"
	"go.etcd.io/etcd/raft/raftpb"
	"go.etcd.io/etcd/wal"
)

const (
	BYTE = 1 << (10 * iota)
	KILOBYTE
	MEGABYTE
	GIGABYTE
	TERABYTE
)

const (
	// DefaultSnapshotCatchUpEntries is the default number of entries
	// to preserve in memory when a snapshot is taken. This is for
	// slow followers to catch up.
	DefaultSnapshotCatchUpEntries = uint64(4)

	// DefaultSnapshotIntervalSize is the default snapshot interval. It is
	// used if SnapshotIntervalSize is not provided in channel config options.
	// It is needed to enforce snapshot being set.
	DefaultSnapshotIntervalSize = 16 * MEGABYTE

	// DefaultEvictionSuspicion is the threshold that a node will start
	// suspecting its own eviction if it has been leaderless for this
	// period of time.
	DefaultEvictionSuspicion = time.Minute * 10

	// DefaultLeaderlessCheckInterval is the interval that a chain checks
	// its own leadership status.
	DefaultLeaderlessCheckInterval = time.Second * 10
)

//go:generate counterfeiter -o mocks/configurator.go . Configurator

// Configurator is used to configure the communication layer
// when the chain starts.
type Configurator interface {
	Configure(channel string, newNodes []cluster.RemoteNode)
}

//go:generate counterfeiter -o mocks/mock_rpc.go . RPC

// RPC is used to mock the transport layer in tests.
type RPC interface {
	SendConsensus(dest uint64, msg *orderer.ConsensusRequest) error
	SendSubmit(dest uint64, request *orderer.SubmitRequest, report func(err error)) error
}

//go:generate counterfeiter -o mocks/mock_blockpuller.go . BlockPuller

// BlockPuller is used to pull blocks from other OSN
type BlockPuller interface {
	PullBlock(seq uint64) *common.Block
	HeightsByEndpoints() (map[string]uint64, error)
	Close()
}

// CreateBlockPuller is a function to create BlockPuller on demand.
// It is passed into chain initializer so that tests could mock this.
type CreateBlockPuller func() (BlockPuller, error)

// Options contains all the configurations relevant to the chain.
type Options struct {
	RPCTimeout time.Duration
	RaftID     uint64

	Clock clock.Clock

	WALDir               string
	SnapDir              string
	SnapshotIntervalSize uint32

	// This is configurable mainly for testing purpose. Users are not
	// expected to alter this. Instead, DefaultSnapshotCatchUpEntries is used.
	SnapshotCatchUpEntries uint64

	MemoryStorage MemoryStorage
	Logger        *flogging.FabricLogger

	TickInterval      time.Duration
	ElectionTick      int
	HeartbeatTick     int
	MaxSizePerMsg     uint64
	MaxInflightBlocks int

	// BlockMetadata and Consenters should only be modified while under lock
	// of raftMetadataLock
	BlockMetadata *etcdraft.BlockMetadata
	Consenters    map[uint64]*etcdraft.Consenter

	// MigrationInit is set when the node starts right after consensus-type migration
	MigrationInit bool

	Metrics *Metrics
	Cert    []byte

	EvictionSuspicion   time.Duration
	LeaderCheckInterval time.Duration
}

type submit struct {
	req    *orderer.SubmitRequest
	leader chan uint64
}

type gc struct {
	index uint64
	state raftpb.ConfState
	data  []byte
}

// Chain implements consensus.Chain interface.
type Chain struct {
	configurator Configurator

	rpc RPC

	raftID    uint64
	channelID string

	lastKnownLeader uint64
	ActiveNodes     atomic.Value

	submitC  chan *submit
	applyC   chan apply
	observeC chan<- raft.SoftState // Notifies external observer on leader change (passed in optionally as an argument for tests)
	haltC    chan struct{}         // Signals to goroutines that the chain is halting
	doneC    chan struct{}         // Closes when the chain halts
	startC   chan struct{}         // Closes when the node is started
	snapC    chan *raftpb.Snapshot // Signal to catch up with snapshot
	gcC      chan *gc              // Signal to take snapshot

	errorCLock sync.RWMutex
	errorC     chan struct{} // returned by Errored()

	raftMetadataLock     sync.RWMutex
	confChangeInProgress *raftpb.ConfChange
	justElected          bool // this is true when node has just been elected
	configInflight       bool // this is true when there is config block or ConfChange in flight
	blockInflight        int  // number of in flight blocks

	clock clock.Clock // Tests can inject a fake clock

	support consensus.ConsenterSupport

	lastBlock    *common.Block
	appliedIndex uint64

	// needed by snapshotting
	sizeLimit        uint32 // SnapshotIntervalSize in bytes
	accDataSize      uint32 // accumulative data size since last snapshot
	lastSnapBlockNum uint64
	confState        raftpb.ConfState // Etcdraft requires ConfState to be persisted within snapshot

	createPuller CreateBlockPuller // func used to create BlockPuller on demand

	fresh bool // indicate if this is a fresh raft node

	// this is exported so that test can use `Node.Status()` to get raft node status.
	Node *node
	opts Options

	Metrics *Metrics
	logger  *flogging.FabricLogger

	periodicChecker *PeriodicCheck

	haltCallback func()

	statusReportMutex sync.Mutex
	consensusRelation types.ConsensusRelation
	status            types.Status

	// BCCSP instance
	CryptoProvider bccsp.BCCSP
}

// NewChain constructs a chain object.
func NewChain(
	support consensus.ConsenterSupport,
	opts Options,
	conf Configurator,
	rpc RPC,
	cryptoProvider bccsp.BCCSP,
	f CreateBlockPuller,
	haltCallback func(),
	observeC chan<- raft.SoftState,
) (*Chain, error) {
	lg := opts.Logger.With("channel", support.ChannelID(), "node", opts.RaftID)

	fresh := !wal.Exist(opts.WALDir)
	storage, err := CreateStorage(lg, opts.WALDir, opts.SnapDir, opts.MemoryStorage)
	if err != nil {
		return nil, errors.Errorf("failed to restore persisted raft data: %s", err)
	}

	if opts.SnapshotCatchUpEntries == 0 {
		storage.SnapshotCatchUpEntries = DefaultSnapshotCatchUpEntries
	} else {
		storage.SnapshotCatchUpEntries = opts.SnapshotCatchUpEntries
	}

	sizeLimit := opts.SnapshotIntervalSize
	if sizeLimit == 0 {
		sizeLimit = DefaultSnapshotIntervalSize
	}

	// get block number in last snapshot, if exists
	var snapBlkNum uint64
	var cc raftpb.ConfState
	if s := storage.Snapshot(); !raft.IsEmptySnap(s) {
		b := protoutil.UnmarshalBlockOrPanic(s.Data)
		snapBlkNum = b.Header.Number
		cc = s.Metadata.ConfState
	}

	b := support.Block(support.Height() - 1)
	if b == nil {
		return nil, errors.Errorf("failed to get last block")
	}

	c := &Chain{
		configurator:      conf,
		rpc:               rpc,
		channelID:         support.ChannelID(),
		raftID:            opts.RaftID,
		submitC:           make(chan *submit),
		applyC:            make(chan apply),
		haltC:             make(chan struct{}),
		doneC:             make(chan struct{}),
		startC:            make(chan struct{}),
		snapC:             make(chan *raftpb.Snapshot),
		errorC:            make(chan struct{}),
		gcC:               make(chan *gc),
		observeC:          observeC,
		support:           support,
		fresh:             fresh,
		appliedIndex:      opts.BlockMetadata.RaftIndex,
		lastBlock:         b,
		sizeLimit:         sizeLimit,
		lastSnapBlockNum:  snapBlkNum,
		confState:         cc,
		createPuller:      f,
		clock:             opts.Clock,
		haltCallback:      haltCallback,
		consensusRelation: types.ConsensusRelationConsenter,
		status:            types.StatusActive,
		Metrics: &Metrics{
			ClusterSize:             opts.Metrics.ClusterSize.With("channel", support.ChannelID()),
			IsLeader:                opts.Metrics.IsLeader.With("channel", support.ChannelID()),
			ActiveNodes:             opts.Metrics.ActiveNodes.With("channel", support.ChannelID()),
			CommittedBlockNumber:    opts.Metrics.CommittedBlockNumber.With("channel", support.ChannelID()),
			SnapshotBlockNumber:     opts.Metrics.SnapshotBlockNumber.With("channel", support.ChannelID()),
			LeaderChanges:           opts.Metrics.LeaderChanges.With("channel", support.ChannelID()),
			ProposalFailures:        opts.Metrics.ProposalFailures.With("channel", support.ChannelID()),
			DataPersistDuration:     opts.Metrics.DataPersistDuration.With("channel", support.ChannelID()),
			NormalProposalsReceived: opts.Metrics.NormalProposalsReceived.With("channel", support.ChannelID()),
			ConfigProposalsReceived: opts.Metrics.ConfigProposalsReceived.With("channel", support.ChannelID()),
		},
		logger:         lg,
		opts:           opts,
		CryptoProvider: cryptoProvider,
	}

	// Sets initial values for metrics
	c.Metrics.ClusterSize.Set(float64(len(c.opts.BlockMetadata.ConsenterIds)))
	c.Metrics.IsLeader.Set(float64(0)) // all nodes start out as followers
	c.Metrics.ActiveNodes.Set(float64(0))
	c.Metrics.CommittedBlockNumber.Set(float64(c.lastBlock.Header.Number))
	c.Metrics.SnapshotBlockNumber.Set(float64(c.lastSnapBlockNum))

	// DO NOT use Applied option in config, see https://github.com/etcd-io/etcd/issues/10217
	// We guard against replay of written blocks with `appliedIndex` instead.
	config := &raft.Config{
		ID:              c.raftID,
		ElectionTick:    c.opts.ElectionTick,
		HeartbeatTick:   c.opts.HeartbeatTick,
		MaxSizePerMsg:   c.opts.MaxSizePerMsg,
		MaxInflightMsgs: c.opts.MaxInflightBlocks,
		Logger:          c.logger,
		Storage:         c.opts.MemoryStorage,
		// PreVote prevents reconnected node from disturbing network.
		// See etcd/raft doc for more details.
		PreVote:                   true,
		CheckQuorum:               true,
		DisableProposalForwarding: true, // This prevents blocks from being accidentally proposed by followers
	}

	disseminator := &Disseminator{RPC: c.rpc}
	disseminator.UpdateMetadata(nil) // initialize
	c.ActiveNodes.Store([]uint64{})

	c.Node = &node{
		chainID:      c.channelID,
		chain:        c,
		logger:       c.logger,
		metrics:      c.Metrics,
		storage:      storage,
		rpc:          disseminator,
		config:       config,
		tickInterval: c.opts.TickInterval,
		clock:        c.clock,
		metadata:     c.opts.BlockMetadata,
		tracker: &Tracker{
			id:     c.raftID,
			sender: disseminator,
			gauge:  c.Metrics.ActiveNodes,
			active: &c.ActiveNodes,
			logger: c.logger,
		},
	}

	return c, nil
}

// Start instructs the orderer to begin serving the chain and keep it current.
func (c *Chain) Start() {
	c.logger.Infof("Starting Raft node")

	if err := c.configureComm(); err != nil {
		c.logger.Errorf("Failed to start chain, aborting: +%v", err)
		close(c.doneC)
		return
	}

	isJoin := c.support.Height() > 1
	if isJoin && c.opts.MigrationInit {
		isJoin = false
		c.logger.Infof("Consensus-type migration detected, starting new raft node on an existing channel; height=%d", c.support.Height())
	}
	c.Node.start(c.fresh, isJoin)

	close(c.startC)
	close(c.errorC)

	go c.gc()
	go c.run()

	es := c.newEvictionSuspector()

	interval := DefaultLeaderlessCheckInterval
	if c.opts.LeaderCheckInterval != 0 {
		interval = c.opts.LeaderCheckInterval
	}

	c.periodicChecker = &PeriodicCheck{
		Logger:        c.logger,
		Report:        es.confirmSuspicion,
		ReportCleared: es.clearSuspicion,
		CheckInterval: interval,
		Condition:     c.suspectEviction,
	}
	c.periodicChecker.Run()
}

// Order submits normal type transactions for ordering.
func (c *Chain) Order(env *common.Envelope, configSeq uint64) error {
	c.Metrics.NormalProposalsReceived.Add(1)
	return c.Submit(&orderer.SubmitRequest{LastValidationSeq: configSeq, Payload: env, Channel: c.channelID}, 0)
}

// Configure submits config type transactions for ordering.
func (c *Chain) Configure(env *common.Envelope, configSeq uint64) error {
	c.Metrics.ConfigProposalsReceived.Add(1)
	return c.Submit(&orderer.SubmitRequest{LastValidationSeq: configSeq, Payload: env, Channel: c.channelID}, 0)
}

// WaitReady blocks when the chain:
// - is catching up with other nodes using snapshot
//
// In any other case, it returns right away.
func (c *Chain) WaitReady() error {
	if err := c.isRunning(); err != nil {
		return err
	}

	select {
	case c.submitC <- nil:
	case <-c.doneC:
		return errors.Errorf("chain is stopped")
	}

	return nil
}

// Errored returns a channel that closes when the chain stops.
func (c *Chain) Errored() <-chan struct{} {
	c.errorCLock.RLock()
	defer c.errorCLock.RUnlock()
	return c.errorC
}

// Halt stops the chain.
func (c *Chain) Halt() {
	c.stop()
}

func (c *Chain) stop() bool {
	select {
	case <-c.startC:
	default:
		c.logger.Warn("Attempted to halt a chain that has not started")
		return false
	}

	select {
	case c.haltC <- struct{}{}:
	case <-c.doneC:
		return false
	}
	<-c.doneC

	c.statusReportMutex.Lock()
	defer c.statusReportMutex.Unlock()
	c.status = types.StatusInactive

	return true
}

// halt stops the chain and calls the haltCallback function, which allows the
// chain to transfer responsibility to a follower or the inactive chain registry when a chain
// discovers it is no longer a member of a channel.
func (c *Chain) halt() {
	if stopped := c.stop(); !stopped {
		c.logger.Info("This node was stopped, the haltCallback will not be called")
		return
	}
	if c.haltCallback != nil {
		c.haltCallback() // Must be invoked WITHOUT any internal lock

		c.statusReportMutex.Lock()
		defer c.statusReportMutex.Unlock()

		// If the haltCallback registers the chain in to the inactive chain registry (i.e., system channel exists) then
		// this is the correct consensusRelation. If the haltCallback transfers responsibility to a follower.Chain, then
		// this chain is about to be GC anyway. The new follower.Chain replacing this one will report the correct
		// StatusReport.
		c.consensusRelation = types.ConsensusRelationConfigTracker
	}
}

func (c *Chain) isRunning() error {
	select {
	case <-c.startC:
	default:
		return errors.Errorf("chain is not started")
	}

	select {
	case <-c.doneC:
		return errors.Errorf("chain is stopped")
	default:
	}

	return nil
}

// Consensus passes the given ConsensusRequest message to the raft.Node instance
func (c *Chain) Consensus(req *orderer.ConsensusRequest, sender uint64) error {
	if err := c.isRunning(); err != nil {
		return err
	}

	stepMsg := &raftpb.Message{}
	if err := proto.Unmarshal(req.Payload, stepMsg); err != nil {
		return fmt.Errorf("failed to unmarshal StepRequest payload to Raft Message: %s", err)
	}

	if stepMsg.To != c.raftID {
		c.logger.Warnf("Received msg to %d, my ID is probably wrong due to out of date, cowardly halting", stepMsg.To)
		c.halt()
		return nil
	}

	if err := c.Node.Step(context.TODO(), *stepMsg); err != nil {
		return fmt.Errorf("failed to process Raft Step message: %s", err)
	}

	if len(req.Metadata) == 0 || atomic.LoadUint64(&c.lastKnownLeader) != sender { // ignore metadata from non-leader
		return nil
	}

	clusterMetadata := &etcdraft.ClusterMetadata{}
	if err := proto.Unmarshal(req.Metadata, clusterMetadata); err != nil {
		return errors.Errorf("failed to unmarshal ClusterMetadata: %s", err)
	}

	c.Metrics.ActiveNodes.Set(float64(len(clusterMetadata.ActiveNodes)))
	c.ActiveNodes.Store(clusterMetadata.ActiveNodes)

	return nil
}

// Submit forwards the incoming request to:
// - the local run goroutine if this is leader
// - the actual leader via the transport mechanism
// The call fails if there's no leader elected yet.
func (c *Chain) Submit(req *orderer.SubmitRequest, sender uint64) error {
	if err := c.isRunning(); err != nil {
		c.Metrics.ProposalFailures.Add(1)
		return err
	}

	leadC := make(chan uint64, 1)
	select {
	case c.submitC <- &submit{req, leadC}:
		lead := <-leadC
		if lead == raft.None {
			c.Metrics.ProposalFailures.Add(1)
			return errors.Errorf("no Raft leader")
		}

		if lead != c.raftID {
			if err := c.forwardToLeader(lead, req); err != nil {
				return err
			}
		}

	case <-c.doneC:
		c.Metrics.ProposalFailures.Add(1)
		return errors.Errorf("chain is stopped")
	}

	return nil
}

func (c *Chain) forwardToLeader(lead uint64, req *orderer.SubmitRequest) error {
	c.logger.Infof("Forwarding transaction to the leader %d", lead)
	timer := time.NewTimer(c.opts.RPCTimeout)
	defer timer.Stop()

	sentChan := make(chan struct{})
	atomicErr := &atomic.Value{}

	report := func(err error) {
		if err != nil {
			atomicErr.Store(err.Error())
			c.Metrics.ProposalFailures.Add(1)
		}
		close(sentChan)
	}

	c.rpc.SendSubmit(lead, req, report)

	select {
	case <-sentChan:
	case <-c.doneC:
		return errors.Errorf("chain is stopped")
	case <-timer.C:
		return errors.Errorf("timed out (%v) waiting on forwarding to %d", c.opts.RPCTimeout, lead)
	}

	if atomicErr.Load() != nil {
		return errors.Errorf(atomicErr.Load().(string))
	}
	return nil
}

type apply struct {
	entries []raftpb.Entry
	soft    *raft.SoftState
}

func isCandidate(state raft.StateType) bool {
	return state == raft.StatePreCandidate || state == raft.StateCandidate
}

func (c *Chain) run() {
	ticking := false
	timer := c.clock.NewTimer(time.Second)
	// we need a stopped timer rather than nil,
	// because we will be select waiting on timer.C()
	if !timer.Stop() {
		<-timer.C()
	}

	// if timer is already started, this is a no-op
	startTimer := func() {
		if !ticking {
			ticking = true
			timer.Reset(c.support.SharedConfig().BatchTimeout())
		}
	}

	stopTimer := func() {
		if !timer.Stop() && ticking {
			// we only need to drain the channel if the timer expired (not explicitly stopped)
			<-timer.C()
		}
		ticking = false
	}

	var soft raft.SoftState
	submitC := c.submitC
	var bc *blockCreator

	var propC chan<- *common.Block
	var cancelProp context.CancelFunc
	cancelProp = func() {} // no-op as initial value

	becomeLeader := func() (chan<- *common.Block, context.CancelFunc) {
		c.Metrics.IsLeader.Set(1)

		c.blockInflight = 0
		c.justElected = true
		submitC = nil
		ch := make(chan *common.Block, c.opts.MaxInflightBlocks)

		// if there is unfinished ConfChange, we should resume the effort to propose it as
		// new leader, and wait for it to be committed before start serving new requests.
		if cc := c.getInFlightConfChange(); cc != nil {
			// The reason `ProposeConfChange` should be called in go routine is documented in `writeConfigBlock` method.
			go func() {
				if err := c.Node.ProposeConfChange(context.TODO(), *cc); err != nil {
					c.logger.Warnf("Failed to propose configuration update to Raft node: %s", err)
				}
			}()

			c.confChangeInProgress = cc
			c.configInflight = true
		}

		// Leader should call Propose in go routine, because this method may be blocked
		// if node is leaderless (this can happen when leader steps down in a heavily
		// loaded network). We need to make sure applyC can still be consumed properly.
		ctx, cancel := context.WithCancel(context.Background())
		go func(ctx context.Context, ch <-chan *common.Block) {
			for {
				select {
				case b := <-ch:
					data := protoutil.MarshalOrPanic(b)
					if err := c.Node.Propose(ctx, data); err != nil {
						c.logger.Errorf("Failed to propose block [%d] to raft and discard %d blocks in queue: %s", b.Header.Number, len(ch), err)
						return
					}
					c.logger.Debugf("Proposed block [%d] to raft consensus", b.Header.Number)

				case <-ctx.Done():
					c.logger.Debugf("Quit proposing blocks, discarded %d blocks in the queue", len(ch))
					return
				}
			}
		}(ctx, ch)

		return ch, cancel
	}

	becomeFollower := func() {
		cancelProp()
		c.blockInflight = 0
		_ = c.support.BlockCutter().Cut()
		stopTimer()
		submitC = c.submitC
		bc = nil
		c.Metrics.IsLeader.Set(0)
	}

	for {
		select {
		case s := <-submitC:
			if s == nil {
				// polled by `WaitReady`
				continue
			}

			if soft.RaftState == raft.StatePreCandidate || soft.RaftState == raft.StateCandidate {
				s.leader <- raft.None
				continue
			}

			s.leader <- soft.Lead
			if soft.Lead != c.raftID {
				continue
			}

			batches, pending, err := c.ordered(s.req)
			if err != nil {
				c.logger.Errorf("Failed to order message: %s", err)
				continue
			}
			if pending {
				startTimer() // no-op if timer is already started
			} else {
				stopTimer()
			}

			c.propose(propC, bc, batches...)

			if c.configInflight {
				c.logger.Info("Received config transaction, pause accepting transaction till it is committed")
				submitC = nil
			} else if c.blockInflight >= c.opts.MaxInflightBlocks {
				c.logger.Debugf("Number of in-flight blocks (%d) reaches limit (%d), pause accepting transaction",
					c.blockInflight, c.opts.MaxInflightBlocks)
				submitC = nil
			}

		case app := <-c.applyC:
			if app.soft != nil {
				newLeader := atomic.LoadUint64(&app.soft.Lead) // etcdraft requires atomic access
				if newLeader != soft.Lead {
					c.logger.Infof("Raft leader changed: %d -> %d", soft.Lead, newLeader)
					c.Metrics.LeaderChanges.Add(1)

					atomic.StoreUint64(&c.lastKnownLeader, newLeader)

					if newLeader == c.raftID {
						propC, cancelProp = becomeLeader()
					}

					if soft.Lead == c.raftID {
						becomeFollower()
					}
				}

				foundLeader := soft.Lead == raft.None && newLeader != raft.None
				quitCandidate := isCandidate(soft.RaftState) && !isCandidate(app.soft.RaftState)

				if foundLeader || quitCandidate {
					c.errorCLock.Lock()
					c.errorC = make(chan struct{})
					c.errorCLock.Unlock()
				}

				if isCandidate(app.soft.RaftState) || newLeader == raft.None {
					atomic.StoreUint64(&c.lastKnownLeader, raft.None)
					select {
					case <-c.errorC:
					default:
						nodeCount := len(c.opts.BlockMetadata.ConsenterIds)
						// Only close the error channel (to signal the broadcast/deliver front-end a consensus backend error)
						// If we are a cluster of size 3 or more, otherwise we can't expand a cluster of size 1 to 2 nodes.
						if nodeCount > 2 {
							close(c.errorC)
						} else {
							c.logger.Warningf("No leader is present, cluster size is %d", nodeCount)
						}
					}
				}

				soft = raft.SoftState{Lead: newLeader, RaftState: app.soft.RaftState}

				// notify external observer
				select {
				case c.observeC <- soft:
				default:
				}
			}

			c.apply(app.entries)

			if c.justElected {
				msgInflight := c.Node.lastIndex() > c.appliedIndex
				if msgInflight {
					c.logger.Debugf("There are in flight blocks, new leader should not serve requests")
					continue
				}

				if c.configInflight {
					c.logger.Debugf("There is config block in flight, new leader should not serve requests")
					continue
				}

				c.logger.Infof("Start accepting requests as Raft leader at block [%d]", c.lastBlock.Header.Number)
				bc = &blockCreator{
					hash:   protoutil.BlockHeaderHash(c.lastBlock.Header),
					number: c.lastBlock.Header.Number,
					logger: c.logger,
				}
				submitC = c.submitC
				c.justElected = false
			} else if c.configInflight {
				c.logger.Info("Config block or ConfChange in flight, pause accepting transaction")
				submitC = nil
			} else if c.blockInflight < c.opts.MaxInflightBlocks {
				submitC = c.submitC
			}

		case <-timer.C():
			ticking = false

			batch := c.support.BlockCutter().Cut()
			if len(batch) == 0 {
				c.logger.Warningf("Batch timer expired with no pending requests, this might indicate a bug")
				continue
			}

			c.logger.Debugf("Batch timer expired, creating block")
			c.propose(propC, bc, batch) // we are certain this is normal block, no need to block

		case sn := <-c.snapC:
			if sn.Metadata.Index != 0 {
				if sn.Metadata.Index <= c.appliedIndex {
					c.logger.Debugf("Skip snapshot taken at index %d, because it is behind current applied index %d", sn.Metadata.Index, c.appliedIndex)
					break
				}

				c.confState = sn.Metadata.ConfState
				c.appliedIndex = sn.Metadata.Index
			} else {
				c.logger.Infof("Received artificial snapshot to trigger catchup")
			}

			if err := c.catchUp(sn); err != nil {
				c.logger.Panicf("Failed to recover from snapshot taken at Term %d and Index %d: %s",
					sn.Metadata.Term, sn.Metadata.Index, err)
			}

		case <-c.doneC:
			stopTimer()
			cancelProp()

			select {
			case <-c.errorC: // avoid closing closed channel
			default:
				close(c.errorC)
			}

			c.logger.Infof("Stop serving requests")
			c.periodicChecker.Stop()
			return
		}
	}
}

func (c *Chain) writeBlock(block *common.Block, index uint64) {
	if block.Header.Number > c.lastBlock.Header.Number+1 {
		c.logger.Panicf("Got block [%d], expect block [%d]", block.Header.Number, c.lastBlock.Header.Number+1)
	} else if block.Header.Number < c.lastBlock.Header.Number+1 {
		c.logger.Infof("Got block [%d], expect block [%d], this node was forced to catch up", block.Header.Number, c.lastBlock.Header.Number+1)
		return
	}

	if c.blockInflight > 0 {
		c.blockInflight-- // only reduce on leader
	}
	c.lastBlock = block

	c.logger.Infof("Writing block [%d] (Raft index: %d) to ledger", block.Header.Number, index)

	if protoutil.IsConfigBlock(block) {
		c.writeConfigBlock(block, index)
		return
	}

	c.raftMetadataLock.Lock()
	c.opts.BlockMetadata.RaftIndex = index
	m := protoutil.MarshalOrPanic(c.opts.BlockMetadata)
	c.raftMetadataLock.Unlock()

	c.support.WriteBlock(block, m)
}

// Orders the envelope in the `msg` content. SubmitRequest.
// Returns
//   -- batches [][]*common.Envelope; the batches cut,
//   -- pending bool; if there are envelopes pending to be ordered,
//   -- err error; the error encountered, if any.
// It takes care of config messages as well as the revalidation of messages if the config sequence has advanced.
func (c *Chain) ordered(msg *orderer.SubmitRequest) (batches [][]*common.Envelope, pending bool, err error) {
	seq := c.support.Sequence()

	isconfig, err := c.isConfig(msg.Payload)
	if err != nil {
		return nil, false, errors.Errorf("bad message: %s", err)
	}

	if isconfig {
		// ConfigMsg
		if msg.LastValidationSeq < seq {
			c.logger.Warnf("Config message was validated against %d, although current config seq has advanced (%d)", msg.LastValidationSeq, seq)
			msg.Payload, _, err = c.support.ProcessConfigMsg(msg.Payload)
			if err != nil {
				c.Metrics.ProposalFailures.Add(1)
				return nil, true, errors.Errorf("bad config message: %s", err)
			}
		}

		batch := c.support.BlockCutter().Cut()
		batches = [][]*common.Envelope{}
		if len(batch) != 0 {
			batches = append(batches, batch)
		}
		batches = append(batches, []*common.Envelope{msg.Payload})
		return batches, false, nil
	}
	// it is a normal message
	if msg.LastValidationSeq < seq {
		c.logger.Warnf("Normal message was validated against %d, although current config seq has advanced (%d)", msg.LastValidationSeq, seq)
		if _, err := c.support.ProcessNormalMsg(msg.Payload); err != nil {
			c.Metrics.ProposalFailures.Add(1)
			return nil, true, errors.Errorf("bad normal message: %s", err)
		}
	}
	batches, pending = c.support.BlockCutter().Ordered(msg.Payload)
	return batches, pending, nil
}

func (c *Chain) propose(ch chan<- *common.Block, bc *blockCreator, batches ...[]*common.Envelope) {
	for _, batch := range batches {
		b := bc.createNextBlock(batch)
		c.logger.Infof("Created block [%d], there are %d blocks in flight", b.Header.Number, c.blockInflight)

		select {
		case ch <- b:
		default:
			c.logger.Panic("Programming error: limit of in-flight blocks does not properly take effect or block is proposed by follower")
		}

		// if it is config block, then we should wait for the commit of the block
		if protoutil.IsConfigBlock(b) {
			c.configInflight = true
		}

		c.blockInflight++
	}
}

func (c *Chain) catchUp(snap *raftpb.Snapshot) error {
	b, err := protoutil.UnmarshalBlock(snap.Data)
	if err != nil {
		return errors.Errorf("failed to unmarshal snapshot data to block: %s", err)
	}

	if c.lastBlock.Header.Number >= b.Header.Number {
		c.logger.Warnf("Snapshot is at block [%d], local block number is %d, no sync needed", b.Header.Number, c.lastBlock.Header.Number)
		return nil
	} else if b.Header.Number == c.lastBlock.Header.Number+1 {
		c.logger.Infof("The only missing block [%d] is encapsulated in snapshot, committing it to shortcut catchup process", b.Header.Number)
		c.commitBlock(b)
		c.lastBlock = b
		return nil
	}

	puller, err := c.createPuller()
	if err != nil {
		return errors.Errorf("failed to create block puller: %s", err)
	}
	defer puller.Close()

	next := c.lastBlock.Header.Number + 1

	c.logger.Infof("Catching up with snapshot taken at block [%d], starting from block [%d]", b.Header.Number, next)

	for next <= b.Header.Number {
		block := puller.PullBlock(next)
		if block == nil {
			return errors.Errorf("failed to fetch block [%d] from cluster", next)
		}
		c.commitBlock(block)
		c.lastBlock = block
		next++
	}

	c.logger.Infof("Finished syncing with cluster up to and including block [%d]", b.Header.Number)
	return nil
}

func (c *Chain) commitBlock(block *common.Block) {
	// read consenters metadata to write into the replicated block
	blockMeta, err := protoutil.GetConsenterMetadataFromBlock(block)
	if err != nil {
		c.logger.Panicf("Failed to obtain metadata: %s", err)
	}

	if !protoutil.IsConfigBlock(block) {
		c.support.WriteBlock(block, blockMeta.Value)
		return
	}

	c.support.WriteConfigBlock(block, blockMeta.Value)

	configMembership := c.detectConfChange(block)

	if configMembership != nil && configMembership.Changed() {
		c.logger.Infof("Config block [%d] changes consenter set, communication should be reconfigured", block.Header.Number)

		c.raftMetadataLock.Lock()
		c.opts.BlockMetadata = configMembership.NewBlockMetadata
		c.opts.Consenters = configMembership.NewConsenters
		c.raftMetadataLock.Unlock()

		if err := c.configureComm(); err != nil {
			c.logger.Panicf("Failed to configure communication: %s", err)
		}
	}
}

func (c *Chain) detectConfChange(block *common.Block) *MembershipChanges {
	// If config is targeting THIS channel, inspect consenter set and
	// propose raft ConfChange if it adds/removes node.
	configMetadata := c.newConfigMetadata(block)

	if configMetadata == nil {
		return nil
	}

	if configMetadata.Options != nil &&
		configMetadata.Options.SnapshotIntervalSize != 0 &&
		configMetadata.Options.SnapshotIntervalSize != c.sizeLimit {
		c.logger.Infof("Update snapshot interval size to %d bytes (was %d)",
			configMetadata.Options.SnapshotIntervalSize, c.sizeLimit)
		c.sizeLimit = configMetadata.Options.SnapshotIntervalSize
	}

	changes, err := ComputeMembershipChanges(c.opts.BlockMetadata, c.opts.Consenters, configMetadata.Consenters)
	if err != nil {
		c.logger.Panicf("illegal configuration change detected: %s", err)
	}

	if changes.Rotated() {
		c.logger.Infof("Config block [%d] rotates TLS certificate of node %d", block.Header.Number, changes.RotatedNode)
	}

	return changes
}

func (c *Chain) apply(ents []raftpb.Entry) {
	if len(ents) == 0 {
		return
	}

	if ents[0].Index > c.appliedIndex+1 {
		c.logger.Panicf("first index of committed entry[%d] should <= appliedIndex[%d]+1", ents[0].Index, c.appliedIndex)
	}

	var position int
	for i := range ents {
		switch ents[i].Type {
		case raftpb.EntryNormal:
			if len(ents[i].Data) == 0 {
				break
			}

			position = i
			c.accDataSize += uint32(len(ents[i].Data))

			// We need to strictly avoid re-applying normal entries,
			// otherwise we are writing the same block twice.
			if ents[i].Index <= c.appliedIndex {
				c.logger.Debugf("Received block with raft index (%d) <= applied index (%d), skip", ents[i].Index, c.appliedIndex)
				break
			}

			block := protoutil.UnmarshalBlockOrPanic(ents[i].Data)
			c.writeBlock(block, ents[i].Index)
			c.Metrics.CommittedBlockNumber.Set(float64(block.Header.Number))

		case raftpb.EntryConfChange:
			var cc raftpb.ConfChange
			if err := cc.Unmarshal(ents[i].Data); err != nil {
				c.logger.Warnf("Failed to unmarshal ConfChange data: %s", err)
				continue
			}

			c.confState = *c.Node.ApplyConfChange(cc)

			switch cc.Type {
			case raftpb.ConfChangeAddNode:
				c.logger.Infof("Applied config change to add node %d, current nodes in channel: %+v", cc.NodeID, c.confState.Nodes)
			case raftpb.ConfChangeRemoveNode:
				c.logger.Infof("Applied config change to remove node %d, current nodes in channel: %+v", cc.NodeID, c.confState.Nodes)
			default:
				c.logger.Panic("Programming error, encountered unsupported raft config change")
			}

			// This ConfChange was introduced by a previously committed config block,
			// we can now unblock submitC to accept envelopes.
			var configureComm bool
			if c.confChangeInProgress != nil &&
				c.confChangeInProgress.NodeID == cc.NodeID &&
				c.confChangeInProgress.Type == cc.Type {

				configureComm = true
				c.confChangeInProgress = nil
				c.configInflight = false
				// report the new cluster size
				c.Metrics.ClusterSize.Set(float64(len(c.opts.BlockMetadata.ConsenterIds)))
			}

			lead := atomic.LoadUint64(&c.lastKnownLeader)
			removeLeader := cc.Type == raftpb.ConfChangeRemoveNode && cc.NodeID == lead
			shouldHalt := cc.Type == raftpb.ConfChangeRemoveNode && cc.NodeID == c.raftID

			// unblock `run` go routine so it can still consume Raft messages
			go func() {
				if removeLeader {
					c.logger.Infof("Current leader is being removed from channel, attempt leadership transfer")
					c.Node.abdicateLeader(lead)
				}

				if configureComm && !shouldHalt { // no need to configure comm if this node is going to halt
					if err := c.configureComm(); err != nil {
						c.logger.Panicf("Failed to configure communication: %s", err)
					}
				}

				if shouldHalt {
					c.logger.Infof("This node is being removed from replica set")
					c.halt()
					return
				}
			}()
		}

		if ents[i].Index > c.appliedIndex {
			c.appliedIndex = ents[i].Index
		}
	}

	if c.accDataSize >= c.sizeLimit {
		b := protoutil.UnmarshalBlockOrPanic(ents[position].Data)

		select {
		case c.gcC <- &gc{index: c.appliedIndex, state: c.confState, data: ents[position].Data}:
			c.logger.Infof("Accumulated %d bytes since last snapshot, exceeding size limit (%d bytes), "+
				"taking snapshot at block [%d] (index: %d), last snapshotted block number is %d, current nodes: %+v",
				c.accDataSize, c.sizeLimit, b.Header.Number, c.appliedIndex, c.lastSnapBlockNum, c.confState.Nodes)
			c.accDataSize = 0
			c.lastSnapBlockNum = b.Header.Number
			c.Metrics.SnapshotBlockNumber.Set(float64(b.Header.Number))
		default:
			c.logger.Warnf("Snapshotting is in progress, it is very likely that SnapshotIntervalSize is too small")
		}
	}
}

func (c *Chain) gc() {
	for {
		select {
		case g := <-c.gcC:
			c.Node.takeSnapshot(g.index, g.state, g.data)
		case <-c.doneC:
			c.logger.Infof("Stop garbage collecting")
			return
		}
	}
}

func (c *Chain) isConfig(env *common.Envelope) (bool, error) {
	h, err := protoutil.ChannelHeader(env)
	if err != nil {
		c.logger.Errorf("failed to extract channel header from envelope")
		return false, err
	}

	return h.Type == int32(common.HeaderType_CONFIG) || h.Type == int32(common.HeaderType_ORDERER_TRANSACTION), nil
}

func (c *Chain) configureComm() error {
	// Reset unreachable map when communication is reconfigured
	c.Node.unreachableLock.Lock()
	c.Node.unreachable = make(map[uint64]struct{})
	c.Node.unreachableLock.Unlock()

	nodes, err := c.remotePeers()
	if err != nil {
		return err
	}

	c.configurator.Configure(c.channelID, nodes)
	return nil
}

func (c *Chain) remotePeers() ([]cluster.RemoteNode, error) {
	c.raftMetadataLock.RLock()
	defer c.raftMetadataLock.RUnlock()

	var nodes []cluster.RemoteNode
	for raftID, consenter := range c.opts.Consenters {
		// No need to know yourself
		if raftID == c.raftID {
			continue
		}
		serverCertAsDER, err := pemToDER(consenter.ServerTlsCert, raftID, "server", c.logger)
		if err != nil {
			return nil, errors.WithStack(err)
		}
		clientCertAsDER, err := pemToDER(consenter.ClientTlsCert, raftID, "client", c.logger)
		if err != nil {
			return nil, errors.WithStack(err)
		}
		nodes = append(nodes, cluster.RemoteNode{
			ID:            raftID,
			Endpoint:      fmt.Sprintf("%s:%d", consenter.Host, consenter.Port),
			ServerTLSCert: serverCertAsDER,
			ClientTLSCert: clientCertAsDER,
		})
	}
	return nodes, nil
}

func pemToDER(pemBytes []byte, id uint64, certType string, logger *flogging.FabricLogger) ([]byte, error) {
	bl, _ := pem.Decode(pemBytes)
	if bl == nil {
		logger.Errorf("Rejecting PEM block of %s TLS cert for node %d, offending PEM is: %s", certType, id, string(pemBytes))
		return nil, errors.Errorf("invalid PEM block")
	}
	return bl.Bytes, nil
}

// writeConfigBlock writes configuration blocks into the ledger in
// addition extracts updates about raft replica set and if there
// are changes updates cluster membership as well
func (c *Chain) writeConfigBlock(block *common.Block, index uint64) {
	hdr, err := ConfigChannelHeader(block)
	if err != nil {
		c.logger.Panicf("Failed to get config header type from config block: %s", err)
	}

	c.configInflight = false

	switch common.HeaderType(hdr.Type) {
	case common.HeaderType_CONFIG:
		configMembership := c.detectConfChange(block)

		c.raftMetadataLock.Lock()
		c.opts.BlockMetadata.RaftIndex = index
		if configMembership != nil {
			c.opts.BlockMetadata = configMembership.NewBlockMetadata
			c.opts.Consenters = configMembership.NewConsenters
		}
		c.raftMetadataLock.Unlock()

		blockMetadataBytes := protoutil.MarshalOrPanic(c.opts.BlockMetadata)

		// write block with metadata
		c.support.WriteConfigBlock(block, blockMetadataBytes)

		if configMembership == nil {
			return
		}

		// update membership
		if configMembership.ConfChange != nil {
			// We need to propose conf change in a go routine, because it may be blocked if raft node
			// becomes leaderless, and we should not block `run` so it can keep consuming applyC,
			// otherwise we have a deadlock.
			go func() {
				// ProposeConfChange returns error only if node being stopped.
				// This proposal is dropped by followers because DisableProposalForwarding is enabled.
				if err := c.Node.ProposeConfChange(context.TODO(), *configMembership.ConfChange); err != nil {
					c.logger.Warnf("Failed to propose configuration update to Raft node: %s", err)
				}
			}()

			c.confChangeInProgress = configMembership.ConfChange

			switch configMembership.ConfChange.Type {
			case raftpb.ConfChangeAddNode:
				c.logger.Infof("Config block just committed adds node %d, pause accepting transactions till config change is applied", configMembership.ConfChange.NodeID)
			case raftpb.ConfChangeRemoveNode:
				c.logger.Infof("Config block just committed removes node %d, pause accepting transactions till config change is applied", configMembership.ConfChange.NodeID)
			default:
				c.logger.Panic("Programming error, encountered unsupported raft config change")
			}

			c.configInflight = true
		} else if configMembership.Rotated() {
			lead := atomic.LoadUint64(&c.lastKnownLeader)
			if configMembership.RotatedNode == lead {
				c.logger.Infof("Certificate of Raft leader is being rotated, attempt leader transfer before reconfiguring communication")
				go func() {
					c.Node.abdicateLeader(lead)
					if err := c.configureComm(); err != nil {
						c.logger.Panicf("Failed to configure communication: %s", err)
					}
				}()
			} else {
				if err := c.configureComm(); err != nil {
					c.logger.Panicf("Failed to configure communication: %s", err)
				}
			}
		}

	case common.HeaderType_ORDERER_TRANSACTION:
		// If this config is channel creation, no extra inspection is needed
		c.raftMetadataLock.Lock()
		c.opts.BlockMetadata.RaftIndex = index
		m := protoutil.MarshalOrPanic(c.opts.BlockMetadata)
		c.raftMetadataLock.Unlock()

		c.support.WriteConfigBlock(block, m)

	default:
		c.logger.Panicf("Programming error: unexpected config type: %s", common.HeaderType(hdr.Type))
	}
}

// getInFlightConfChange returns ConfChange in-flight if any.
// It returns confChangeInProgress if it is not nil. Otherwise
// it returns ConfChange from the last committed block (might be nil).
func (c *Chain) getInFlightConfChange() *raftpb.ConfChange {
	if c.confChangeInProgress != nil {
		return c.confChangeInProgress
	}

	if c.lastBlock.Header.Number == 0 {
		return nil // nothing to failover just started the chain
	}

	if !protoutil.IsConfigBlock(c.lastBlock) {
		return nil
	}

	// extracting current Raft configuration state
	confState := c.Node.ApplyConfChange(raftpb.ConfChange{})

	if len(confState.Nodes) == len(c.opts.BlockMetadata.ConsenterIds) {
		// Raft configuration change could only add one node or
		// remove one node at a time, if raft conf state size is
		// equal to membership stored in block metadata field,
		// that means everything is in sync and no need to propose
		// config update.
		return nil
	}

	return ConfChange(c.opts.BlockMetadata, confState)
}

// newMetadata extract config metadata from the configuration block
func (c *Chain) newConfigMetadata(block *common.Block) *etcdraft.ConfigMetadata {
	metadata, err := ConsensusMetadataFromConfigBlock(block)
	if err != nil {
		c.logger.Panicf("error reading consensus metadata: %s", err)
	}
	return metadata
}

// ValidateConsensusMetadata determines the validity of a
// ConsensusMetadata update during config updates on the channel.
func (c *Chain) ValidateConsensusMetadata(oldOrdererConfig, newOrdererConfig channelconfig.Orderer, newChannel bool) error {
	if newOrdererConfig == nil {
		c.logger.Panic("Programming Error: ValidateConsensusMetadata called with nil new channel config")
		return nil
	}

	// metadata was not updated
	if newOrdererConfig.ConsensusMetadata() == nil {
		return nil
	}

	if oldOrdererConfig == nil {
		c.logger.Panic("Programming Error: ValidateConsensusMetadata called with nil old channel config")
		return nil
	}

	if oldOrdererConfig.ConsensusMetadata() == nil {
		c.logger.Panic("Programming Error: ValidateConsensusMetadata called with nil old metadata")
		return nil
	}

	oldMetadata := &etcdraft.ConfigMetadata{}
	if err := proto.Unmarshal(oldOrdererConfig.ConsensusMetadata(), oldMetadata); err != nil {
		c.logger.Panicf("Programming Error: Failed to unmarshal old etcdraft consensus metadata: %v", err)
	}

	newMetadata := &etcdraft.ConfigMetadata{}
	if err := proto.Unmarshal(newOrdererConfig.ConsensusMetadata(), newMetadata); err != nil {
		return errors.Wrap(err, "failed to unmarshal new etcdraft metadata configuration")
	}

	verifyOpts, err := createX509VerifyOptions(newOrdererConfig)
	if err != nil {
		return errors.Wrapf(err, "failed to create x509 verify options from old and new orderer config")
	}

	if err := VerifyConfigMetadata(newMetadata, verifyOpts); err != nil {
		return errors.Wrap(err, "invalid new config metadata")
	}

	if newChannel {
		// check if the consenters are a subset of the existing consenters (system channel consenters)
		set := ConsentersToMap(oldMetadata.Consenters)
		for _, c := range newMetadata.Consenters {
			if !set.Exists(c) {
				return errors.New("new channel has consenter that is not part of system consenter set")
			}
		}
		return nil
	}

	// create the dummy parameters for ComputeMembershipChanges
	c.raftMetadataLock.RLock()
	dummyOldBlockMetadata := proto.Clone(c.opts.BlockMetadata).(*etcdraft.BlockMetadata)
	c.raftMetadataLock.RUnlock()

	dummyOldConsentersMap := CreateConsentersMap(dummyOldBlockMetadata, oldMetadata)
	changes, err := ComputeMembershipChanges(dummyOldBlockMetadata, dummyOldConsentersMap, newMetadata.Consenters)
	if err != nil {
		return err
	}

	// new config metadata was verified above. Additionally need to check new consenters for certificates expiration
	for _, c := range changes.AddedNodes {
		if err := validateConsenterTLSCerts(c, verifyOpts, false); err != nil {
			return errors.Wrapf(err, "consenter %s:%d has invalid certificates", c.Host, c.Port)
		}
	}

	active := c.ActiveNodes.Load().([]uint64)
	if changes.UnacceptableQuorumLoss(active) {
		return errors.Errorf("%d out of %d nodes are alive, configuration will result in quorum loss", len(active), len(dummyOldConsentersMap))
	}

	return nil
}

// StatusReport returns the ConsensusRelation & Status
func (c *Chain) StatusReport() (types.ConsensusRelation, types.Status) {
	c.statusReportMutex.Lock()
	defer c.statusReportMutex.Unlock()

	return c.consensusRelation, c.status
}

func (c *Chain) suspectEviction() bool {
	if c.isRunning() != nil {
		return false
	}

	return atomic.LoadUint64(&c.lastKnownLeader) == uint64(0)
}

func (c *Chain) newEvictionSuspector() *evictionSuspector {
	consenterCertificate := &ConsenterCertificate{
		Logger:               c.logger,
		ConsenterCertificate: c.opts.Cert,
		CryptoProvider:       c.CryptoProvider,
	}

	return &evictionSuspector{
		amIInChannel:               consenterCertificate.IsConsenterOfChannel,
		evictionSuspicionThreshold: c.opts.EvictionSuspicion,
		writeBlock:                 c.support.Append,
		createPuller:               c.createPuller,
		height:                     c.support.Height,
		triggerCatchUp:             c.triggerCatchup,
		logger:                     c.logger,
		halt: func() {
			c.halt()
		},
	}
}

func (c *Chain) triggerCatchup(sn *raftpb.Snapshot) {
	select {
	case c.snapC <- sn:
	case <-c.doneC:
	}
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <title><?php echo $website_name ?></title>

  <link href="<?php echo base_url('assets/css/bootstrap.min.css') ?>" rel="stylesheet" />
  <link href="<?php echo base_url('assets/css/custom.css') ?>" rel="stylesheet" />
</head>

<body class="<?php echo $page ?>">


text:
import React, {
  Component,
} from 'react';
import {
  StyleSheet,
  View,
  Animated,
  Text,
  Easing,
} from 'react-native';
import PropTypes from 'prop-types';

const styles = StyleSheet.create({
  all: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  outer: {
    flex: 1,
    overflow: 'hidden',
    backgroundColor: '#ddd',
  },
  inner: {
    flex: 1,
    backgroundColor: '#108ee9',
  },
  text: {
    width: 50,
    textAlign: 'right',
  },
});

class Progress extends Component {
  constructor(props) {
    super(props);
    this.state = {
      progressWidth: new Animated.Value(0),
    };

    this.outerWidth = 0;

    this.onLayout = this.onLayout.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
      const progressWidth = this.getProgressWidth(nextProps.value);
      /* eslint-disable */
      if (this.state.progressWidth._value !== progressWidth) {
      /* eslint-enable */
        Animated.timing(this.state.progressWidth, {
          toValue: progressWidth,
          duration: nextProps.duration,
          // linear animation looks smoother
          easing: Easing.linear,
        }).start();
      }
    }
  }

  getProgressWidth(ratio) {
    if (ratio < 0) {
      return 0;
    } else if (ratio > 1) {
      return this.outerWidth;
    }
    return this.outerWidth * ratio;
  }

  onLayout(e) {
    const { width } = e.nativeEvent.layout;
    if (width !== this.outerWidth) {
      this.outerWidth = width;
      this.setState({
        progressWidth: new Animated.Value(this.getProgressWidth(this.props.value)),
      });
    }
  }

  render() {
    return (
      <View
        style={[styles.all, this.props.style]}
      >
        <View
          style={[styles.outer, {
            height: this.props.width,
            borderRadius: this.props.width / 2,
          }, this.props.outerStyle]}
          onLayout={this.onLayout}
        >
          <Animated.View
            style={[styles.inner, {
              height: this.props.width,
              borderRadius: this.props.width / 2,
            }, this.props.innerStyle, {
              width: this.state.progressWidth,
            }]}
          />
        </View>
        {
          this.props.valueVisible ? (
            <Text
              style={[styles.text, this.props.valueStyle]}
            >
              {this.props.valueFormater(this.props.value)}
            </Text>
          ) : null
        }
      </View>
    );
  }
}

Progress.propTypes = {
  // 容器样式
  style: View.propTypes.style,
  // 进度条宽度
  width: PropTypes.number,
  // 进度条背景样式
  outerStyle: View.propTypes.style,
  // 进度条样式
  innerStyle: View.propTypes.style,
  // 动画时长
  /* eslint-disable */
  duration: PropTypes.number,
  /* eslint-enable */
  // 进度值
  value: PropTypes.number,
  // 是否显示进度值
  valueVisible: PropTypes.bool,
  // 进度值样式
  valueStyle: Text.propTypes.style,
  // 进度值格式函数
  valueFormater: PropTypes.func,
};
Progress.defaultProps = {
  style: null,
  width: 10,
  outerStyle: null,
  innerStyle: null,
  duration: 300,
  value: 0,
  valueVisible: true,
  valueStyle: null,
  valueFormater(value) {
    let percent;
    if (value < 0) {
      percent = 0;
    } else if (value > 1) {
      percent = 100;
    } else {
      percent = Math.round(value * 100);
    }
    return `${percent}%`;
  },
};

export default Progress;


text:
/**
 * Builders designed to help with programmatic configuration of Ehcache using a fluent API
 */
package org.ehcache.config.builders;


text: scons --target=mdk4


text:
'use strict';

describe('Controller: SigninCtrl', function () {

  // load the controller's module
  beforeEach(module('dashApp'));

  var SigninCtrl,
    scope,
    Account,
    httpBackend;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, $q, _$httpBackend_) {
    scope = $rootScope.$new();
    Account = {
      signIn: function(username, password) {
        var deferred = $q.defer();

        if (username == 'user' && password == '1234') {
          deferred.resolve(true);
        } else {
          deferred.resolve(false);
        }

        return deferred.promise;
      }
    };
    SigninCtrl = $controller('SigninCtrl', {
      $scope: scope,
      Account: Account
    });
    httpBackend = _$httpBackend_;
  }));

/*  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });*/

  it('should sign the user in only when correct credential info was given', function() {
    var promise;

    promise = SigninCtrl.signInDash('user', '1234');
    promise.then(function (res) {
      expect(res).toBeTruthy();
    });

    promise = SigninCtrl.signInDash('user', '5678');
    promise.then(function (res) {
      expect(res).toBeFalsy();
    });

    promise = SigninCtrl.signInDash('resu', '1234');
    promise.then(function (res) {
      expect(res).toBeFalsy();
    });
  });
});


text:
package org.keycloak.testsuite.arquillian.containers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.arquillian.config.descriptor.api.ContainerDef;
import org.jboss.arquillian.container.impl.ContainerCreationException;
import org.jboss.arquillian.container.impl.ContainerImpl;
import org.jboss.arquillian.container.spi.ConfigurationException;
import org.jboss.arquillian.container.spi.Container;
import org.jboss.arquillian.container.spi.ContainerRegistry;
import org.jboss.arquillian.container.spi.client.container.DeployableContainer;
import org.jboss.arquillian.container.spi.client.deployment.TargetDescription;
import org.jboss.arquillian.core.api.Injector;
import org.jboss.arquillian.core.spi.ServiceLoader;
import org.jboss.arquillian.core.spi.Validate;
import static org.keycloak.testsuite.arquillian.containers.RegistryCreator.getAdapterImplClassValue;
import static org.keycloak.testsuite.arquillian.containers.RegistryCreator.getContainerAdapter;

/**
 * This class registers all adapters which are specified in the arquillian.xml.
 *
 * In the case there is only one adapter implementation on the classpath, it is
 * not necessary to specify it in the container configuration since it will be
 * used automatically. You have to specify it only in the case you are going to
 * use more than one container.
 *
 * @author Dominik Pospisil <dpospisi@redhat.com>
 * @author Stefan Miklosovic <smikloso@redhat.com>
 * @author Tomas Kyjovsky <tkyjovsk@redhat.com>
 */
public class Registry implements ContainerRegistry {

    private final List<Container> containers;

    private Injector injector;

    private static final Logger logger = Logger.getLogger(RegistryCreator.class.getName());

    public Registry(Injector injector) {
        this.containers = new ArrayList<>();
        this.injector = injector;
    }

    @Override
    public Container create(ContainerDef definition, ServiceLoader loader) {
        Validate.notNull(definition, "Definition must be specified");

        try {
            logger.log(Level.INFO, "Registering container: {0}", definition.getContainerName());

            @SuppressWarnings("rawtypes")
            Collection<DeployableContainer> containerAdapters = loader.all(DeployableContainer.class);

            DeployableContainer<?> dcService = null;

            if (containerAdapters.size() == 1) {
                // just one container on cp
                dcService = containerAdapters.iterator().next();
            } else {
                if (dcService == null) {
                    dcService = getContainerAdapter(getAdapterImplClassValue(definition), containerAdapters);
                }
                if (dcService == null) {
                    throw new ConfigurationException("Unable to get container adapter from Arquillian configuration.");
                }
            }

            // before a Container is added to a collection of containers, inject into its injection point
            return addContainer(injector.inject(
                    new ContainerImpl(definition.getContainerName(), dcService, definition)));

        } catch (Exception e) {
            throw new ContainerCreationException("Could not create Container " + definition.getContainerName(), e);
        }
    }

    @Override
    public List<Container> getContainers() {
        return Collections.unmodifiableList(new ArrayList<>(containers));
    }

    @Override
    public Container getContainer(TargetDescription target) {
        Validate.notNull(target, "Target must be specified");
        if (TargetDescription.DEFAULT.equals(target)) {
            return findDefaultContainer();
        }
        return findMatchingContainer(target.getName());
    }

    private Container addContainer(Container container) {
        containers.add(container);
        return container;
    }

    private Container findDefaultContainer() {
        if (containers.size() == 1) {
            return containers.get(0);
        }
        for (Container container : containers) {
            if (container.getContainerConfiguration().isDefault()) {
                return container;
            }
        }
        return null;
    }

    private Container findMatchingContainer(String name) {
        for (Container container : containers) {
            if (container.getName().equals(name)) {
                return container;
            }
        }
        return null;
    }

    @Override
    public Container getContainer(String name) {
        return findMatchingContainer(name);
    }

}


text:
<!doctype html>

  <link rel="import" href="../../../polymer-elements/polymer-ajax/polymer-ajax.html">

  <polymer-element name="x-cover" attributes="ry ty origin">
    <template>

      <content></content>
    </template>

  </polymer-element>

  <polymer-element name="x-spiral" attributes="off origin">
    <template>

      <content id="content" select="x-cover"></content>
    </template>

  </polymer-element>

  <polymer-element name="x-menu" attributes="xml" on-track="{{track}}" on-trackEnd="{{trackEnd}}" touch-action="none">
    <template>

      <polymer-ajax url="snap/s.txt" handleAs="text" response="{{raw}}" auto></polymer-ajax>

        Perspective: <input type="range" min="0" max="5000" value="1000" on-change="{{perspChange}}">
        Center: <input type="range" min="-2000" max="2000" value="600" on-change="{{radChange}}">
        Scale: <input type="range" min="0.5" max="10" value="1.2" step="0.005" on-change="{{scaleChange}}">

        <button on-tap="{{spin}}">Spin Down</button><button id="up" on-tap="{{spin}}">Spin Up</button>

      <x-spiral id="spiral" off="{{off}}" origin="{{origin}}">
        <template repeat="{{games}}">
          <x-cover>

{{description}} ({{year}})
</x-cover>
        </template>
      </x-spiral>
      <button on-tap="{{spin}}">Spin Down</button><button id="up" on-tap="{{spin}}">Spin Up</button>

    </template>

  </polymer-element>

  <x-menu></x-menu>
  <polymer-ajax id="ajax" url="databases/MAME.xml" handleAs="xml" response="{{xml}}" auto></polymer-ajax>


text:
echo "running in $HOSTNAME"

# will remove an entry in hosts file
cp /etc/hosts /etc/hosts.old
grep -v $1 /etc/hosts.old > /etc/hosts

echo "modified hosts file: "
echo " "
cat /etc/hosts
echo " "
echo "********************************"


text:
'use strict';

function escapeRegexp(source) {
  return String(source).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}

// - nick - first letters of nick
// - strict - exact match when true
//
module.exports = function (N, apiPath) {
  N.validate(apiPath, {
    nick:   { type: 'string',  required: true },
    strict: { type: 'boolean', required: true }
  });

  N.wire.on(apiPath, async function moderator_find_user(env) {
    if (env.params.nick.length < 3 && !env.params.strict) {
      env.res = [];
      return;
    }

    var query = N.models.users.User.find();

    if (env.params.strict) {
      query.where('nick').equals(env.params.nick);
    } else {
      query.where('nick_normalized_lc').regex(new RegExp('^' + escapeRegexp(env.params.nick.toLowerCase())));
    }

    env.res = await query.limit(10)
                         .select('_id name nick')
                         .sort('nick')
                         .lean(true);
  });
};


text:
<?php

namespace Cosmos;

use Cosmos\Storage\Cache;
use Cosmos\Security\Encryption;
use Cosmos\Exceptions\NotFoundInApiException;

class Content{

  private $cosmos, $api_name, $type, $name, $body;

  public function __construct($cosmos, $api_name)
  {
    $this->cosmos = $cosmos;
    $this->api_name = $api_name;
  }

  public function fetch()
  {
    $cache = Cache::getInstance();

    // Check if in cache
    if($cache->has($this->api_name)){
      $content = $cache->get($this->api_name);
      $this->body = $content->body;
      $this->name = $content->name;
      $this->type = $content->type;
      return;
    }

    // If not, fetch from api
    if(!$response = json_decode(@file_get_contents($this->url()))){
      throw new NotFoundInApiException;
    }
    $content = (object) $response->contents;

    $this->type = $content->type;
    $this->name = $content->name;
    $this->body = Encryption::decrypt($content->body, $content->cipher, $this->cosmos);

    Cache::getInstance()->addContent($this)->save();
  }

  public function body()
  {
    return $this->body;
  }
  public function name()
  {
    return $this->name;
  }
  public function api_name()
  {
    return $this->api_name;
  }
  public function type()
  {
    return $this->type;
  }

  private function url()
  {
    return 'https://cosmos-cms.com/api/'. $this->cosmos->getApiKey() .'/'. $this->api_name;
  }

  public function __toString()
  {
    return $this->body();
  }

}


text:
"""
The Cell class defines cells of the map. Each cell contains a unit, a city, some resources, or nothing.
"""

#Types of maps: hexagonal and square.
HEX_MAP_TYPE    = ["hex", "hexagonal", "hexagon"]
SQUARE_MAP_TYPE = ["square"]

# Types of units
EMPTY = 0
UNIT  = 1
TOWER = 2

# Possible colors
RED      = 1
GREEN    = 2
BLUE     = 3
YELLOW   = 4

# Corresponding RGB values
RGB_RED = (255, 0, 0)
RGB_GREEN = (0, 128, 0)
RGB_BLUE = (0, 0, 255)
RGB_YELLOW = (255, 255, 0)
RGB_WHITE = (255, 255, 255)
RGB_BLACK = (0, 0, 0)

# Strings corresponding to colors
COLOR_STRINGS = {RED: "red", GREEN: "green",
                 BLUE: "blue", YELLOW: "yellow", EMPTY: "empty"}

# Maximum possible number of players
MAX_PLAYERS = 4

# Resources claimed from tiles
TOWER_RESOURCES = 5

"""
Cell class; describes the contents of a cell of the board.
   .type: type of unit stored in this cell (including "empty")
   .color: color of the unit stored in this cell (or empty)
   .strength: strength of the unit at this cell. This value is 0 if and only if
              the cell is empty.
   .adjacent: a list of the cells adjacent to this one. Can be set using the
              "addAdjacent" function.
"""
class Cell(object):

    def __init__(self, color=EMPTY, strength=EMPTY, type=EMPTY,
                 resources=0, isdisabled=False, adjacent=[]):
        """Constructor for a cell object. Sets all the data fields of the cell."""
        self.color     = color
        self.strength  = strength
        self.type      = type
        self.resources = resources
        self.disabled  = isdisabled
        self.adjacent  = adjacent

def validPlayerColor(color):
    """Checks whether or not a player can take on the input color."""
    if color not in (RED, GREEN, BLUE, YELLOW):
        return False
    else:
        return True

def validColor(color):
    """Check whether or not the input color is a valid color (including EMPTY)."""
    if color not in (RED, GREEN, BLUE, YELLOW, EMPTY):
        return False
    else:
        return True

def getColorString(color):
    """Get the string corresponding to a color."""
    if type(color) is not int:
        raise TypeError("The input to getColorString is not of type int.")
    if color in COLOR_STRINGS:
        return COLOR_STRINGS[color]
    else:
        raise ValueError("Input color not found.")


text:
ALTER TABLE {$NAMESPACE}_maniphest.maniphest_taskauxiliarystorage
  MODIFY value LONGTEXT COLLATE utf8_bin;


text:
from collections import defaultdict
import os
import re
import unittest
import sys

################################################################################

class SmartyParser:

   def __init__(self, path):
      if not os.path.isdir(path):
         raise Exception("Expected a valid path to parse through")

      self.m_path = path
      self.m_missing = []
      self.m_tests = []
      self.m_passed = []
      self.m_failed = []

   def parse(self):
      files = os.listdir(self.m_path)

      failed_smrt_files = []
      passed_smrt_files = []

      for file in files:
         if "fail.smrt" in file:
            failed_smrt_files.append(file)
         elif "pass.smrt" in file:
            passed_smrt_files.append(file)

      def parse_smrt_files(smrt_list):
         test_list = []

         for smrt_file in smrt_list:
            lines = None
            with open(os.path.join(self.m_path, smrt_file)) as file_handle:
               lines = file_handle.readlines()

            lines = "\n".join(lines)
            lines = lines.split("[TESTS]")

            tests = lines[1].split("Tests.lst=")[1:]

            test_names = []
            for test in tests:
               split = test.split(",")

               dir = split[3].strip()
               test_name = split[0].strip()
               test_name = "cmd_".join(test_name.split("cmd"))

               test_names.append((dir, test_name))

            for test in test_names:
               test_list.append(test)

         return test_list

      failed_tests = parse_smrt_files(failed_smrt_files)
      passed_tests = parse_smrt_files(passed_smrt_files)

      cached_ls = defaultdict(lambda: None)

      def iterate_tests(test_list):
         local_tests = []

         for test in test_list:
            smrt_dir = test[0]

            if cached_ls[smrt_dir] is None:
               cached_ls[smrt_dir] = os.listdir(os.path.join(self.m_path, smrt_dir))
               ds = defaultdict(lambda: [])
               file_names = cached_ls[smrt_dir]

               for file_name in file_names:
                  split = file_name.split(".result")
                  ds[split[0]].append(".result".join(split))

               cached_ls[smrt_dir] = ds

            result_files = cached_ls[test[0]]["Tests.lst_" + test[1]]

            if len(result_files) == 0:
               self.m_missing.append(test[0])

            else:
               for file in result_files:
                  if os.path.splitext(file)[1] == ".html":
                     result = self.parse_smarty_file(os.path.join(self.m_path, test[0], file))

                     local_tests.append(result)
                     self.m_tests.append(result)

      self.m_failed = iterate_tests(failed_tests)
      self.m_passed = iterate_tests(passed_tests)

   def parse_smarty_file(self, path):
      lines = self.remove_tags(path)

      tags = defaultdict(lambda: False)

      tags["TEST_IDENTIFIER"] = True
      tags["CATEGORIES"] = True
      tags["RELATIVEPATH"] = True
      tags["WORKINGDIR"] = True
      tags["TEST_CMD_LINE"] = True
      tags["TEST_EXPECTED_RETURN_CODE"] = True
      tags["TEST_ACTUAL_RETURN_CODE"] = True
      tags["TEST_START_TIME"] = True
      tags["TEST_END_TIME"] = True
      tags["TEST_RESULT"] = True
      tags["TEST_OUTPUT"] = True

      capturing_output = False

      for line in lines:
         if "TEST OUTPUT" in line:
            capturing_output = True
            tags["TEST_OUTPUT"] = []

         elif capturing_output is True:
            if "TEXT_EXPECTED_RETURN_CODE" in line:
               capturing_output = False
               tags["TEST_OUTPUT"] = "\n".join(tags["TEST_OUTPUT"])

            else:
               tags["TEST_OUTPUT"].append(line)

         elif "=" in line:
            split = line.split(" = ")

            if tags[split[0]] is True:
               value = "=".join(split[1:])

               tags[split[0]] = value.strip()

         elif ":" in line:
            # TEST_CMD_LINE does not use =
            split = line.split(": ")

            if tags[split[0]] is True:
               tags[split[0]] = ":".join(split[1:])

      return tags

   def remove_tags(self, path):
      tag_re = re.compile(r'<[^>]+>')
      lines = []

      with open(path) as file_handle:
         for line in file_handle:
            line = tag_re.sub('', line)

            # Smarty has a bug such that </BODY will
            # possible be missing the ending >
            # Check for this and remove the tag if found.

            if "</BODY" in line and "</BODY>" not in line:
               line = line.replace("</BODY", "")

            line = line.replace("\r\n", "")

            if len(line) != 0:
               lines.append(line)

      return lines


text:
package org.onosproject.net.driver;

/**
 * Entity capable of resolving a class using its name.
 */
public interface BehaviourClassResolver {

    /**
     * Returns the class corresponding to the specified class name.
     * @param className class className
     * @return class for the resolver
     */
    Class<? extends Behaviour> getBehaviourClass(String className);

}


text:
namespace sly.parser.generator.visitor.dotgraph
{
    public interface IDot
    {
        string ToGraph();
    }
}


text:
#include "testmodule.h"
#include "testcommon.h"

static gboolean test_module_load   (GTypeModule *module);
static void     test_module_unload (GTypeModule *module);

static void
test_module_class_init (TestModuleClass *class)
{
  GTypeModuleClass *module_class = G_TYPE_MODULE_CLASS (class);

  module_class->load = test_module_load;
  module_class->unload = test_module_unload;
}

DEFINE_TYPE (TestModule, test_module,
	     test_module_class_init, NULL, NULL,
	     G_TYPE_TYPE_MODULE)

static gboolean
test_module_load (GTypeModule *module)
{
  TestModule *test_module = TEST_MODULE (module);

  test_module->register_func (module);

  return TRUE;
}

static void
test_module_unload (GTypeModule *module)
{
}

GTypeModule *
test_module_new (TestModuleRegisterFunc register_func)
{
  TestModule *test_module = g_object_new (TEST_TYPE_MODULE, NULL);
  GTypeModule *module = G_TYPE_MODULE (test_module);

  test_module->register_func = register_func;

  /* Register the types initially */
  g_type_module_use (module);
  g_type_module_unuse (module);

  return G_TYPE_MODULE (module);
}


text:
import {Controller} from "@hotwired/stimulus";

export default class extends Controller {
    reloadWithTurbo() {
        Turbo.visit(window.location.toString(), {action: 'replace'})
    }
}


text:
var actions = {
    loadPlugins: "__PLUGINS_LOAD_PLUGINS",
    setPlugins: "__PLUGINS_SET_PLUGINS",
}

var Plugins = require('../services/plugins');

var createState = function(store, loaded) {
    return {
        store: store,
        loaded: loaded,
        loadAll: function(S) {
            S.dispatch(actions.loadPlugins);

            Plugins.installed().then(function(p) {
                S.dispatch(actions.setPlugins, {
                    loading: false,
                    plugins: p,
                });
            }).catch(function(err) {
                // Hmm...
                console.log(err);
            });
        },
    }
}

var Reducer = function(state, action) {
    if (state == undefined) {
        return createState(Immutable.List(), false);
    }

    switch (action.type) {
        case actions.loadPlugins:
            return createState(state.store, true);
        case actions.setPlugins:
            return createState(
                Immutable.List(action.context.plugins),
                action.context.loading
            );
        default:
            return state;
    }
}

module.exports = {
    Reducer: Reducer,
    actions: actions,
}


text:
<?php

namespace gotham\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class UserDeleted implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $user;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        //
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return [
                'gotham-1', // gotham-1 is used for Administrators Group
                'gotham-2',  // gotham-2 is used for Users Group
                ];
    }
}


text:
package softlayer_account_authentication_attribute

// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED


text:
package com.pattern.adapter;

import java.util.Map;

public interface IOuterUser {

    public Map<String, String> getUserBaseInfo();

    public Map<String, String> getUserOfficeInfo();

    public Map<String, String> getUserHomeInfo();
}


text:
'use strict';

describe('Service: Blog', function () {

  // load the service's module
  beforeEach(module('websiteApp'));

  // instantiate service
  var Blog;
  beforeEach(inject(function (_Blog_) {
    Blog = _Blog_;
  }));

  it('should do something', function () {
    expect(!!Blog).toBe(true);
  });

});