text:
package core

import (
	crand "crypto/rand"
	"errors"
	"fmt"
	"math"
	"math/big"
	mrand "math/rand"
	"time"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/consensus"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/params"
	"github.com/hashicorp/golang-lru"
)

const (
	headerCacheLimit = 512
	tdCacheLimit     = 1024
	numberCacheLimit = 2048
)

// HeaderChain implements the basic block header chain logic that is shared by
// core.BlockChain and light.LightChain. It is not usable in itself, only as
// a part of either structure.
// It is not thread safe either, the encapsulating chain structures should do
// the necessary mutex locking/unlocking.
type HeaderChain struct {
	config *params.ChainConfig

	chainDb       ethdb.Database
	genesisHeader *types.Header

	currentHeader     *types.Header // Current head of the header chain (may be above the block chain!)
	currentHeaderHash common.Hash   // Hash of the current head of the header chain (prevent recomputing all the time)

	headerCache *lru.Cache // Cache for the most recent block headers
	tdCache     *lru.Cache // Cache for the most recent block total difficulties
	numberCache *lru.Cache // Cache for the most recent block numbers

	procInterrupt func() bool

	rand   *mrand.Rand
	engine consensus.Engine
}

// NewHeaderChain creates a new HeaderChain structure.
//  getValidator should return the parent's validator
//  procInterrupt points to the parent's interrupt semaphore
//  wg points to the parent's shutdown wait group
func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
	headerCache, _ := lru.New(headerCacheLimit)
	tdCache, _ := lru.New(tdCacheLimit)
	numberCache, _ := lru.New(numberCacheLimit)

	// Seed a fast but crypto originating random generator
	seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	if err != nil {
		return nil, err
	}

	hc := &HeaderChain{
		config:        config,
		chainDb:       chainDb,
		headerCache:   headerCache,
		tdCache:       tdCache,
		numberCache:   numberCache,
		procInterrupt: procInterrupt,
		rand:          mrand.New(mrand.NewSource(seed.Int64())),
		engine:        engine,
	}

	hc.genesisHeader = hc.GetHeaderByNumber(0)
	if hc.genesisHeader == nil {
		return nil, ErrNoGenesis
	}

	hc.currentHeader = hc.genesisHeader
	if head := GetHeadBlockHash(chainDb); head != (common.Hash{}) {
		if chead := hc.GetHeaderByHash(head); chead != nil {
			hc.currentHeader = chead
		}
	}
	hc.currentHeaderHash = hc.currentHeader.Hash()

	return hc, nil
}

// GetBlockNumber retrieves the block number belonging to the given hash
// from the cache or database
func (hc *HeaderChain) GetBlockNumber(hash common.Hash) uint64 {
	if cached, ok := hc.numberCache.Get(hash); ok {
		return cached.(uint64)
	}
	number := GetBlockNumber(hc.chainDb, hash)
	if number != missingNumber {
		hc.numberCache.Add(hash, number)
	}
	return number
}

// WriteHeader writes a header into the local chain, given that its parent is
// already known. If the total difficulty of the newly inserted header becomes
// greater than the current known TD, the canonical chain is re-routed.
//
// Note: This method is not concurrent-safe with inserting blocks simultaneously
// into the chain, as side effects caused by reorganisations cannot be emulated
// without the real blocks. Hence, writing headers directly should only be done
// in two scenarios: pure-header mode of operation (light clients), or properly
// separated header/block phases (non-archive clients).
func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
	// Cache some values to prevent constant recalculation
	var (
		hash   = header.Hash()
		number = header.Number.Uint64()
	)
	// Calculate the total difficulty of the header
	ptd := hc.GetTd(header.ParentHash, number-1)
	if ptd == nil {
		return NonStatTy, consensus.ErrUnknownAncestor
	}
	localTd := hc.GetTd(hc.currentHeaderHash, hc.currentHeader.Number.Uint64())
	externTd := new(big.Int).Add(header.Difficulty, ptd)

	// Irrelevant of the canonical status, write the td and header to the database
	if err := hc.WriteTd(hash, number, externTd); err != nil {
		log.Crit("Failed to write header total difficulty", "err", err)
	}
	if err := WriteHeader(hc.chainDb, header); err != nil {
		log.Crit("Failed to write header content", "err", err)
	}
	// If the total difficulty is higher than our known, add it to the canonical chain
	// Second clause in the if statement reduces the vulnerability to selfish mining.
	// Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
	if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
		// Delete any canonical number assignments above the new head
		for i := number + 1; ; i++ {
			hash := GetCanonicalHash(hc.chainDb, i)
			if hash == (common.Hash{}) {
				break
			}
			DeleteCanonicalHash(hc.chainDb, i)
		}
		// Overwrite any stale canonical number assignments
		var (
			headHash   = header.ParentHash
			headNumber = header.Number.Uint64() - 1
			headHeader = hc.GetHeader(headHash, headNumber)
		)
		for GetCanonicalHash(hc.chainDb, headNumber) != headHash {
			WriteCanonicalHash(hc.chainDb, headHash, headNumber)

			headHash = headHeader.ParentHash
			headNumber = headHeader.Number.Uint64() - 1
			headHeader = hc.GetHeader(headHash, headNumber)
		}
		// Extend the canonical chain with the new header
		if err := WriteCanonicalHash(hc.chainDb, hash, number); err != nil {
			log.Crit("Failed to insert header number", "err", err)
		}
		if err := WriteHeadHeaderHash(hc.chainDb, hash); err != nil {
			log.Crit("Failed to insert head header hash", "err", err)
		}
		hc.currentHeaderHash, hc.currentHeader = hash, types.CopyHeader(header)

		status = CanonStatTy
	} else {
		status = SideStatTy
	}

	hc.headerCache.Add(hash, header)
	hc.numberCache.Add(hash, number)

	return
}

// WhCallback is a callback function for inserting individual headers.
// A callback is used for two reasons: first, in a LightChain, status should be
// processed and light chain events sent, while in a BlockChain this is not
// necessary since chain events are sent after inserting blocks. Second, the
// header writes should be protected by the parent chain mutex individually.
type WhCallback func(*types.Header) error

func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
	// Do a sanity check that the provided chain is actually ordered and linked
	for i := 1; i < len(chain); i++ {
		if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
			// Chain broke ancestry, log a messge (programming error) and skip insertion
			log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
				"parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())

			return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].Number,
				chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
		}
	}

	// Generate the list of seal verification requests, and start the parallel verifier
	seals := make([]bool, len(chain))
	for i := 0; i < len(seals)/checkFreq; i++ {
		index := i*checkFreq + hc.rand.Intn(checkFreq)
		if index >= len(seals) {
			index = len(seals) - 1
		}
		seals[index] = true
	}
	seals[len(seals)-1] = true // Last should always be verified to avoid junk

	abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
	defer close(abort)

	// Iterate over the headers and ensure they all check out
	for i, header := range chain {
		// If the chain is terminating, stop processing blocks
		if hc.procInterrupt() {
			log.Debug("Premature abort during headers verification")
			return 0, errors.New("aborted")
		}
		// If the header is a banned one, straight out abort
		if BadHashes[header.Hash()] {
			return i, ErrBlacklistedHash
		}
		// Otherwise wait for headers checks and ensure they pass
		if err := <-results; err != nil {
			return i, err
		}
	}

	return 0, nil
}

// InsertHeaderChain attempts to insert the given header chain in to the local
// chain, possibly creating a reorg. If an error is returned, it will return the
// index number of the failing header as well an error describing what went wrong.
//
// The verify parameter can be used to fine tune whether nonce verification
// should be done or not. The reason behind the optional check is because some
// of the header retrieval mechanisms already need to verfy nonces, as well as
// because nonces can be verified sparsely, not needing to check each.
func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
	// Collect some import statistics to report on
	stats := struct{ processed, ignored int }{}
	// All headers passed verification, import them into the database
	for i, header := range chain {
		// Short circuit insertion if shutting down
		if hc.procInterrupt() {
			log.Debug("Premature abort during headers import")
			return i, errors.New("aborted")
		}
		// If the header's already known, skip it, otherwise store
		if hc.HasHeader(header.Hash(), header.Number.Uint64()) {
			stats.ignored++
			continue
		}
		if err := writeHeader(header); err != nil {
			return i, err
		}
		stats.processed++
	}
	// Report some public statistics so the user has a clue what's going on
	last := chain[len(chain)-1]
	log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
		"number", last.Number, "hash", last.Hash(), "ignored", stats.ignored)

	return 0, nil
}

// GetBlockHashesFromHash retrieves a number of block hashes starting at a given
// hash, fetching towards the genesis block.
func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
	// Get the origin header from which to fetch
	header := hc.GetHeaderByHash(hash)
	if header == nil {
		return nil
	}
	// Iterate the headers until enough is collected or the genesis reached
	chain := make([]common.Hash, 0, max)
	for i := uint64(0); i < max; i++ {
		next := header.ParentHash
		if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
			break
		}
		chain = append(chain, next)
		if header.Number.Sign() == 0 {
			break
		}
	}
	return chain
}

// GetTd retrieves a block's total difficulty in the canonical chain from the
// database by hash and number, caching it if found.
func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
	// Short circuit if the td's already in the cache, retrieve otherwise
	if cached, ok := hc.tdCache.Get(hash); ok {
		return cached.(*big.Int)
	}
	td := GetTd(hc.chainDb, hash, number)
	if td == nil {
		return nil
	}
	// Cache the found body for next time and return
	hc.tdCache.Add(hash, td)
	return td
}

// GetTdByHash retrieves a block's total difficulty in the canonical chain from the
// database by hash, caching it if found.
func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
	return hc.GetTd(hash, hc.GetBlockNumber(hash))
}

// WriteTd stores a block's total difficulty into the database, also caching it
// along the way.
func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
	if err := WriteTd(hc.chainDb, hash, number, td); err != nil {
		return err
	}
	hc.tdCache.Add(hash, new(big.Int).Set(td))
	return nil
}

// GetHeader retrieves a block header from the database by hash and number,
// caching it if found.
func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
	// Short circuit if the header's already in the cache, retrieve otherwise
	if header, ok := hc.headerCache.Get(hash); ok {
		return header.(*types.Header)
	}
	header := GetHeader(hc.chainDb, hash, number)
	if header == nil {
		return nil
	}
	// Cache the found header for next time and return
	hc.headerCache.Add(hash, header)
	return header
}

// GetHeaderByHash retrieves a block header from the database by hash, caching it if
// found.
func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
	return hc.GetHeader(hash, hc.GetBlockNumber(hash))
}

// HasHeader checks if a block header is present in the database or not.
func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
	if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
		return true
	}
	ok, _ := hc.chainDb.Has(headerKey(hash, number))
	return ok
}

// GetHeaderByNumber retrieves a block header from the database by number,
// caching it (associated with its hash) if found.
func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
	hash := GetCanonicalHash(hc.chainDb, number)
	if hash == (common.Hash{}) {
		return nil
	}
	return hc.GetHeader(hash, number)
}

// CurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the HeaderChain's internal cache.
func (hc *HeaderChain) CurrentHeader() *types.Header {
	return hc.currentHeader
}

// SetCurrentHeader sets the current head header of the canonical chain.
func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
	if err := WriteHeadHeaderHash(hc.chainDb, head.Hash()); err != nil {
		log.Crit("Failed to insert head header hash", "err", err)
	}
	hc.currentHeader = head
	hc.currentHeaderHash = head.Hash()
}

// DeleteCallback is a callback function that is called by SetHead before
// each header is deleted.
type DeleteCallback func(common.Hash, uint64)

// SetHead rewinds the local chain to a new head. Everything above the new head
// will be deleted and the new one set.
func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
	height := uint64(0)
	if hc.currentHeader != nil {
		height = hc.currentHeader.Number.Uint64()
	}

	for hc.currentHeader != nil && hc.currentHeader.Number.Uint64() > head {
		hash := hc.currentHeader.Hash()
		num := hc.currentHeader.Number.Uint64()
		if delFn != nil {
			delFn(hash, num)
		}
		DeleteHeader(hc.chainDb, hash, num)
		DeleteTd(hc.chainDb, hash, num)
		hc.currentHeader = hc.GetHeader(hc.currentHeader.ParentHash, hc.currentHeader.Number.Uint64()-1)
	}
	// Roll back the canonical chain numbering
	for i := height; i > head; i-- {
		DeleteCanonicalHash(hc.chainDb, i)
	}
	// Clear out any stale content from the caches
	hc.headerCache.Purge()
	hc.tdCache.Purge()
	hc.numberCache.Purge()

	if hc.currentHeader == nil {
		hc.currentHeader = hc.genesisHeader
	}
	hc.currentHeaderHash = hc.currentHeader.Hash()

	if err := WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash); err != nil {
		log.Crit("Failed to reset head header hash", "err", err)
	}
}

// SetGenesis sets a new genesis block header for the chain
func (hc *HeaderChain) SetGenesis(head *types.Header) {
	hc.genesisHeader = head
}

// Config retrieves the header chain's chain configuration.
func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }

// Engine retrieves the header chain's consensus engine.
func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }

// GetBlock implements consensus.ChainReader, and returns nil for every input as
// a header chain does not have blocks available for retrieval.
func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
	return nil
}


text:
set -ev

sudo apt install -q -y zsh

# install ohmyzsh if it isn't already installed
[ -d "${HOME}/.oh-my-zsh" ] || sh -c "$(wget https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh -O -)"

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BranchSwitcher.Utilities;
using SynNet.Services;
using SynNet.Switch;

namespace BranchSwitcherUI.Services
{
	internal class StepsEngineService
	{
		private readonly IStepsExecutionEngine m_Engine;
		private readonly ExecutionSettingsBuilder m_Builder;
		private CancellationTokenSource m_TokenSource;
		private readonly IStepsParametersStore m_ParametersStore;

		public StepsEngineService(
			IStepsExecutionEngine engine,
			IStepsParametersStore parametersStore,
			ExecutionSettingsBuilder builder)
		{
			Guard.NotNull(engine, nameof(engine));
			Guard.NotNull(parametersStore, nameof(parametersStore));
			Guard.NotNull(builder, nameof(builder));

			m_Engine = engine;
			m_Builder = builder;
			m_ParametersStore = parametersStore;
		}

		public Task InvokeStepsEngine(
			IReadOnlyCollection<ISwitchStep> selectedSteps,
			bool force,
			bool ignoreDependent,
			bool cleanHistory)
		{
			Guard.NotEmpty(selectedSteps, nameof(selectedSteps));

			foreach (var step in selectedSteps)
				m_Builder.AddStep(step, m_ParametersStore.Locate(step.GetType()));

			var settings = m_Builder.
				WithOptions(force, ignoreDependent, cleanHistory).
				Build();

			ReleaseTokenSource();

			foreach (var step in selectedSteps)
				step.Token = AcquireCancelToken();

			return Task.Run(
				() => m_Engine.Execute(settings),
				AcquireCancelToken());
		}

		public void CancelSteps()
		{
			if (m_TokenSource != null)
				m_TokenSource.Cancel();

			ReleaseTokenSource();
		}

		private CancellationToken AcquireCancelToken()
		{
			if (m_TokenSource == null)
				m_TokenSource = new CancellationTokenSource();

			return m_TokenSource.Token;
		}

		private void ReleaseTokenSource()
		{
			if (m_TokenSource != null)
			{
				m_TokenSource.Dispose();
				m_TokenSource = null;
			}
		}
	}
}


text:
namespace NuGetGallery.Operations.Model
{
    public class Db
    {
        public string Name { get; set; }
        public byte State { get; set; }
    }
}


text:
          <form action="#" method="get" class="sidebar-form">

          </form>

Patient BHT Options

              <a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/BHT/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>">
                 Patient Profile

              <a href="<?php echo base_url(); ?>index.php/inward/PrescrptionC/index/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>">
                 Prescription

          <?php if ($dischjType == "none") { ?>

                 Laboratory Test

<a href="<?php echo base_url(); ?>index.php/lab/TestRequest/index/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> View Test Results

<a href="<?php echo base_url(); ?>index.php/lab/NewTestRequest/index/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> New Test Request

            <?php } else { ?>

<a href="<?php echo base_url(); ?>index.php/lab/TestRequest/index/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> View Test Results

            <?php } ?>

            <?php if ($dischjType == "none") { ?>

                 Patient Allergies

<a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/AllergyView/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> View Allergies

<a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/NewAllergy/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> Add New Allergy

                 <?php } else { ?>

<a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/AllergyView/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> View Allergies

                 <?php } ?>

                 Charts

<a href="<?php echo base_url(); ?>index.php/inward/temperatureChartC/index/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> Fever Chart

<a href="<?php echo base_url(); ?>index.php/inward/diabeticChartC/index/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> Diabetic Chart

<a href="<?php echo base_url(); ?>index.php/inward/liquidBalanceChartC/index/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>">Liquid Balance Chart

            <?php if ($dischjType == "none") { ?>

                 Patient Transfer

<a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/InternalTransfer/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>">Internal Transfer

<a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/ExternalTransfer/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>">External Transfer

            <?php } ?>

<a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/DischarjView/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>">Discharge Patient

            <?php if ($dischjType == "none") { ?>

                 Patient Diets

<a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/AddDiets/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>">Patient Diets

<a href="<?php echo base_url(); ?>index.php/inward/patientBHTC/ViewDiets/<?php echo $bht_no; ?>/<?php echo $patient_id; ?>"> View patient Diets

                 <?php } else { ?>

                  <?php } ?>


text:
package main

import "fmt"

func main() {
  // buffer up to 2 inputs
  messages := make(chan string, 2)

  messages <- "buffered"
  messages <- "channel"

  // this next line would break the program
  // messages <- "dropped"

  fmt.Println(<-messages)
  fmt.Println(<-messages)

  // again this next line would break the program
  // fmt.Println(<-messages)
}


text: pub mod greeter;


text:
'use strict';

var DraftStringKey = require('./DraftStringKey');
var UnicodeUtils = require('fbjs/lib/UnicodeUtils');

var strlen = UnicodeUtils.strlen;

/**
 * Convert to UTF-8 character counts for storage.
 */
function encodeEntityRanges(block, storageMap) {
  var encoded = [];
  block.findEntityRanges(function (character) {
    return !!character.getEntity();
  }, function ( /*number*/start, /*number*/end) {
    var text = block.getText();
    var key = block.getEntityAt(start);
    encoded.push({
      offset: strlen(text.slice(0, start)),
      length: strlen(text.slice(start, end)),
      // Encode the key as a number for range storage.
      key: Number(storageMap[DraftStringKey.stringify(key)])
    });
  });
  return encoded;
}

module.exports = encodeEntityRanges;


text:
---
layout: post
title: 认识postgresql的BGW
date: 2016-07-11 21:07
categories:
    - PostgreSQL
typora-root-url: ../../layamon.github.io
---

* TOC
{:toc}
```bash
/home/liuyangming/postgresql-9.5.3/build/bin/postgres -D data
postgres: checkpointer process
postgres: writer process
postgres: wal writer process
postgres: autovacuum launcher process
postgres: stats collector process
postgres: liuyangming tpcds [local] EXPLAIN // 响应客户端请求fork的进程,其他为常驻的后台辅助服务进程
```

### 1.2. 对应文件

```
autovacuum.c     // 系统自动清理进程的源文件
bgworker.c       // 维护一个BackgroundWorkerArray,其中维护着后台工作进程的列表
		  		// 各个进程都可以访问,postmaster无锁访问,其他进程要或得排它锁才能写,共享锁才能读
bgwriter.c        // 后台写进程的源文件
checkpointer.c    // 检查点进程,掌控系统的所有的检查点,pg 9.2后新加的
fork_process.c    // 启动进程工具函数
pgarch.c          // 预写式日志归档进程的源文件
pgstat.c          // 统计数据收集进程的源文件
postmaster.c      // Postmaster
startup.c
syslogger.c       // 系统日志进程的源文件
walwriter.c       // 预写式日志写进程的源文件
```
看了一天进程启动的代码,想看看在哪个地方可以修改,从而创建一个新的后台进程,
最终没想到在postgresql 中已经提供了一个Custom Background Workers,这是在 postgresql 9.3中新加的新特性[background worker][bwp],开始没有把bgworker.c和进程对应上,没注意看源文件里的注释啊!!!

```
// POSTGRES pluggable background workers implementation
```

### 1.3. postgresql 启动流程
> postgresql 9.5 版本不同顺序不同

虽然找到了接口,附带追了一下postgresql启动创建进程的流程,以下是我简单画了一个流程图,供君指点 :)
![pgstartup](/image/pg-bgw/postgres启动.jpg)

## 2. background worker

**postgresql 9.3 commit**

```
commit da07a1e856511dca59cbb1357616e26baa64428e
Author: Alvaro Herrera <alvherre@alvh.no-ip.org>
Date:   Thu Dec 6 14:57:52 2012 -0300

Background worker processes

Background workers are postmaster subprocesses that run arbitrary
user-specified code.  They can request shared memory access as well as
backend database connections; or they can just use plain libpq frontend
database connections.

Modules listed in shared_preload_libraries can register background
workers in their _PG_init() function; this is early enough that it's not
necessary to provide an extra GUC option, because the necessary extra
resources can be allocated early on.  Modules can install more than one
bgworker, if necessary.

Care is taken that these extra processes do not interfere with other
postmaster tasks: only one such process is started on each ServerLoop
iteration.  This means a large number of them could be waiting to be
started up and postmaster is still able to quickly service external
connection requests.  Also, shutdown sequence should not be impacted by
a worker process that's reasonably well behaved (i.e. promptly responds
        to termination signals.)

The current implementation lets worker processes specify their start
time, i.e. at what point in the server startup process they are to be
started: right after postmaster start (in which case they mustn't ask
        for shared memory access), when consistent state has been reached
(useful during recovery in a HOT standby server), or when recovery has
terminated (i.e. when normal backends are allowed).

In case of a bgworker crash, actions to take depend on registration
data: if shared memory was requested, then all other connections are
taken down (as well as other bgworkers), just like it were a regular
backend crashing.  The bgworker itself is restarted, too, within a
configurable timeframe (which can be configured to be never).

More features to add to this framework can be imagined without much
effort, and have been discussed, but this seems good enough as a useful
unit already.

An elementary sample module is supplied.
```

我们将想要添加的功能编译成一个共享库,添加到pg的lib里,配置好,pg启动一个新的bg worker运行我们的程序
可以申请访问share_memory的权限,访问数据库的数据,或者直接使用libpg来访问数据库
添加这一个feature,我们就可以利用这一特性做一些我们想要的功能,特别是后台维护性质的任务

### 2.1. 编写一个custome background worker

#### 2.1.1 bgw相关数据结构代码

##### BackgroundWorker结构体

``` c
typedetruct BackgroundWorker
{
    char        bgw_name[BGW_MAXLEN];
    int         bgw_flags;
    BgWorkerStartTime bgw_start_time;
    int         bgw_restart_time;       /* in seconds, or BGW_NEVER_RESTART */
    bgworker_main_type bgw_main;
    char        bgw_library_name[BGW_MAXLEN];   /* only if bgw_main is NULL */
    char        bgw_function_name[BGW_MAXLEN];  /* only if bgw_main is NULL */
    Datum       bgw_main_arg;
    char        bgw_extra[BGW_EXTRALEN];
    pid_t       bgw_notify_pid; /* SIGUSR1 this backend on start/stop */
} BackgroundWorker;
```

##### BackgroundWorker调用执行

``` c
/*
     * If bgw_main is set, we use that value as the initial entrypoint.
     * However, if the library containing the entrypoint wasn't loaded at
     * postmaster startup time, passing it as a direct function pointer is not
     * possible.  To work around that, we allow callers for whom a function
     * pointer is not available to pass a library name (which will be loaded,
     * if necessary) and a function name (which will be looked up in the named
     * library).
     */
    if (worker->bgw_main != NULL)
        entrypt = worker->bgw_main;
    else
        entrypt = (bgworker_main_type)
            load_external_function(worker->bgw_library_name,
                                   worker->bgw_function_name,
                                   true, NULL);

    /*
     * Note that in normal processes, we would call InitPostgres here.  For a
     * worker, however, we don't know what database to connect to, yet; so we
     * need to wait until the user code does it via
     * BackgroundWorkerInitializeConnection().
     */

    /*
     * Now invoke the user-defined worker code
     */
    entrypt(worker->bgw_main_arg);
```

#### 2.1.2. 一个例子 Hello world
> 创建一个 custome background worker ,循环输出 "hello world"

##### Header

``` c
/*  编写bgw,最少需要添加的头文件,如果需要别的功能再添加别的头文件
    比如,如果想对数据库进程操作,借助spi manager就需要添加spi.h*/
#include "postgres.h"
#include "postmaster/bgworker.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/proc.h"
#include "fmgr.h"
```

##### Declaration

``` c
/* Essential for shared libs! */
PG_MODULE_MAGIC;

/* Entry point of library loading */
void _PG_init(void);

/* Signal handling */
static bool got_sigterm = false;
```

##### Initialization

``` c
void
_PG_init(void)
{
    BackgroundWorker    worker;

    /* Register the worker processes */
    worker.bgw_flags = BGWORKER_SHMEM_ACCESS;
    worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
    worker.bgw_main = hello_main;
    worker.bgw_sighup = NULL;
    worker.bgw_sigterm = hello_sigterm;
    worker.bgw_name = "hello world";
    worker.bgw_restart_time = BGW_NEVER_RESTART;
    worker.bgw_main_arg = NULL;
    RegisterBackgroundWorker(&worker);
}
```

##### Main loop

``` c
static void
hello_main(void *main_arg)
{
    /* ready to receive signals */
    BackgroundWorkerUnblockSignals();
    while (!got_sigterm)
    {
        int     rc;
        /* Wait 10s */
        rc = WaitLatch(&MyProc-;>procLatch,
                WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
                10000L);
        ResetLatch(&MyProc-;>procLatch);
        elog(LOG, "Hello World!"); 	/* Say Hello to the world */
    }
    proc_exit(0);
}
```

##### SIGTERM handler

``` c
static void
hello_sigterm(SIGNAL_ARGS)
{
    int         save_errno = errno;
    got_sigterm = true;
    if (MyProc)
        SetLatch(&MyProc-;>procLatch);
    errno = save_errno;
}
```

#####  Makefile

```
MODULES = hello_world
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
```

#### New feature

除此之外,在pg9.4之后添加了新的特性,动态加载bgworker,以插件的方式, create extension 具体例子可以参考源码的 src/test/modules/worker_spi

### 2.2 一句话

在没有这个特性之前,如果我们自己需要创建一个新的后台维护任务,就要自己额外启动一个进程,
并管理好该进程的生命周期。有了bgworker之后,pg启动的时候顺带启动了我们自定义的后台任务进程
并且pgstop顺带stop,更加有整体性

[bwp]: https://wiki.postgresql.org/wiki/What&#39;s_new_in_PostgreSQL_9.3#Custom_Background_Workers

### 3. bgw开发指导 in osx

#### 3.1 安装开发包

osx上brew没有找到postgresql-server-dev-all包,直接cmm源码安装

```bash
» pg_config
BINDIR = /usr/local/pgsql/bin
DOCDIR = /usr/local/pgsql/share/doc
HTMLDIR = /usr/local/pgsql/share/doc
INCLUDEDIR = /usr/local/pgsql/include
PKGINCLUDEDIR = /usr/local/pgsql/include
INCLUDEDIR-SERVER = /usr/local/pgsql/include/server
LIBDIR = /usr/local/pgsql/lib
PKGLIBDIR = /usr/local/pgsql/lib
LOCALEDIR = /usr/local/pgsql/share/locale
MANDIR = /usr/local/pgsql/share/man
SHAREDIR = /usr/local/pgsql/share
SYSCONFDIR = /usr/local/pgsql/etc
PGXS = /usr/local/pgsql/lib/pgxs/src/makefiles/pgxs.mk
CONFIGURE =
CC = gcc
CPPFLAGS = -DFRONTEND
CFLAGS = -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -Wno-unused-command-line-argument -O2
CFLAGS_SL =
LDFLAGS = -L../../src/common -Wl,-dead_strip_dylibs
LDFLAGS_EX =
LDFLAGS_SL =
LIBS = -lpgcommon -lpgport -lz -lreadline -lm
VERSION = PostgreSQL 10.3
```

#### 3.2 写makefile

简单期间,直接把源码中的例子拿过来

```bash
cd  ~/go/src/github.com/layamon/patrol/commander
cp ~/src/postgresql-10.3/src/test/modules/worker_spi/* .
USE_PGXS=1 make
ll worker_spi.so
-rwxr-xr-x  1 liuyangming  staff    16K  7 27 13:00 worker_spi.so
```

#### 3.3 按照自己的需求参考文档开干吧


text:
set(DLIB_CMAKE_ARGS
  DLIB_HEADER_ONLY=OFF #all previous builds were header on, so that is the default
  DLIB_ENABLE_ASSERTS=OFF #must be set on/off or debug/release build will differ and config will not match one
  HUNTER_INSTALL_LICENSE_FILES=dlib/LICENSE.txt
  )

hunter_config(dlib VERSION ${HUNTER_dlib_VERSION} CMAKE_ARGS "${DLIB_CMAKE_ARGS}")


text:
<?php

namespace Lib\JSON;

use \stdClass;

class JsonHelper
{
    function jsonInputReader($convertedToAssocArray = false)
    {
        $data = file_get_contents('php://input');
        $data = json_decode($data, $convertedToAssocArray);

        return $data;
    }

    function responseDefaultError()
    {
        $error = $this->defaultError();
        $this->responseJsonMessage($error);
    }

    function defaultError()
    {
        $error = $this->generateError(\Enum\ResponseError::INVALID_REQUEST, i18n::$texts['invalidData']);

        return $error;
    }

    function generateError($HTTPCODE, $message)
    {
        $error = new stdClass();
        $error->HTTPCODE = $HTTPCODE;
        $error->message = $message;

        return $error;
    }

    function responseCustomError($HTTPCODE, $message) {
        $message = $this->generateError($HTTPCODE, $message);

        $this->responseJsonMessage($message);
    }

    function generateSuccessCode()
    {
        $message = new stdClass();
        $message->HTTPCODE = 200;

        return $message;
    }

    function responseJsonMessageByKeyAndValues($key, $values) {
        $message = $this->generateSuccessCode();
        $message->{$key} = $values;

        $this->responseJsonMessage($message);
    }

    function responseJsonMessage($message)
    {
        header('HTTP/1.1 ' . $message->HTTPCODE);
        header('Content-type: application/json');

        echo json_encode($message);
    }
}

?>


text:
FROM iimuz/cpp-dev:v1.1.1
LABEL maintainer iimuz

USER root

RUN apt-get update && \
  apt-get install -y --no-install-recommends \
    pkg-config && \
  apt-get clean && \
  rm -rf /var/lib/apt/lists/*

RUN cd /opt && \
  git clone --recursive --depth 1 -b boost-1.66.0 https://github.com/boostorg/boost.git && \
  cd /opt/boost && \
  sh bootstrap.sh \
    --with-toolset=clang && \
  ./b2 -j`expr $(grep processor /proc/cpuinfo | wc -l) + 1` \
    --toolset=clang \
    install \
    --libdir=/usr/local/lib \
    --without-python && \
  ./b2 -j`expr $(grep processor /proc/cpuinfo | wc -l) + 1` \
    --toolset=clang \
    install \
    --libdir=/usr/local/lib \
    --includedir=/usr/local/include \
    --without-python && \
  ./b2 tools/boostdep/build && \
  ./dist/bin/boostdep --list-modules | xargs -IXX sh -c \
    './dist/bin/boostdep --pkgconfig XX 1.6.3 prefix=/usr/local includedir='${prefix}/include' libdir='${prefix}/lib' > /usr/lib/x86_64-linux-gnu/pkgconfig/boost_XX.pc' && \
  cd /opt && \
  rm -rf boost && \
  ldconfig

USER dev


text:
using System;
using System.Collections.Generic;
using OAuth.Core.Interfaces;
using OAuth.Core.Provider.Inspectors;
using OAuth.Core.Storage;
using OAuth.Core.Storage.Interfaces;

namespace OAuth.Core.Provider
{
    public class OAuthProvider : IOAuthProvider
    {
        readonly List<IContextInspector> _inspectors = new List<IContextInspector>();
        readonly ITokenStore _tokenStore;

        public OAuthProvider(ITokenStore tokenStore, params IContextInspector[] inspectors)
        {
            if (tokenStore == null) throw new ArgumentNullException("tokenStore");
            _tokenStore = tokenStore;

            if (inspectors != null) _inspectors.AddRange(inspectors);
        }

        #region IOAuthProvider Members

        public virtual IToken GrantRequestToken(IOAuthContext context)
        {
            InspectRequest(context);

            return _tokenStore.CreateRequestToken(context);
        }

        public virtual IToken ExchangeRequestTokenForAccessToken(IOAuthContext context)
        {
            var token = _tokenStore.GetToken(context);
            if (token != null)
                context.TokenSecret = token.TokenSecret;
            InspectRequest(context);

            _tokenStore.ConsumeRequestToken(context);

            switch (_tokenStore.GetStatusOfRequestForAccess(context))
            {
                case RequestForAccessStatus.Granted:
                    break;
                case RequestForAccessStatus.Unknown:
                    throw Error.ConsumerHasNotBeenGrantedAccessYet(context);
                default:
                    throw Error.ConsumerHasBeenDeniedAccess(context);
            }

            return _tokenStore.GetAccessTokenAssociatedWithRequestToken(context);
        }

        public virtual void AccessProtectedResourceRequest(IOAuthContext context)
        {
            var token = _tokenStore.GetToken(context);
            if (token != null)
                context.TokenSecret = token.TokenSecret;
            InspectRequest(context);

            _tokenStore.ConsumeAccessToken(context);
        }

        #endregion

        public void AddInspector(IContextInspector inspector)
        {
            _inspectors.Add(inspector);
        }

        protected virtual void InspectRequest(IOAuthContext context)
        {
            foreach (IContextInspector inspector in _inspectors)
            {
                inspector.InspectContext(context);
            }
        }
    }
}


text:
#include "saiga/core/image/managedImage.h"

#include "saiga/core/util/BinaryFile.h"
#include "saiga/core/util/assert.h"
#include "saiga/core/util/file.h"
#include "saiga/core/util/zlib.h"

// for the load and save function
#include "saiga/core/image/freeimage.h"
#include "saiga/core/image/png_wrapper.h"
#include "saiga/core/image/templatedImage.h"
#include "saiga/core/math/imath.h"
#include "saiga/core/util/color.h"
#include "saiga/core/util/fileChecker.h"
#include "saiga/core/util/tostring.h"

#include "internal/noGraphicsAPI.h"
#include "internal/stb_image_read_wrapper.h"
#include "internal/stb_image_write_wrapper.h"

#include <fstream>
namespace Saiga
{
Image::Image(int h, int w, ImageType type)
    : ImageBase(h, w, iAlignUp(elementSize(type) * w, DEFAULT_ALIGNMENT)), type(type)
{
    create();
}

Image::Image(ImageDimensions dimensions, ImageType type) : Image(dimensions.h, dimensions.w, type) {}

void Image::create()
{
    SAIGA_ASSERT(width > 0 && height > 0 && type != TYPE_UNKNOWN);

    if (pitchBytes == 0)
    {
        pitchBytes = iAlignUp(elementSize(type) * width, DEFAULT_ALIGNMENT);
    }

    vdata.resize(size());

    SAIGA_ASSERT(valid());
}

void Image::create(ImageDimensions dimensions)
{
    create(dimensions.h, dimensions.w);
}

void Image::create(int h, int w)
{
    pitchBytes = 0;
    height     = h;
    width      = w;
    create();
}

void Image::create(int h, int w, ImageType t)
{
    pitchBytes = 0;
    height     = h;
    width      = w;
    type       = t;
    create();
}

void Image::create(int h, int w, int p, ImageType t)
{
    pitchBytes = p;
    create(h, w, t);
}

void Image::clear()
{
    (*this) = Image();
}

void Image::free()
{
    pitchBytes = 0;
    vdata.clear();
    vdata.shrink_to_fit();
}

void Image::makeZero()
{
    std::fill(vdata.begin(), vdata.end(), 0);
}

bool Image::valid() const
{
    return width > 0 && height > 0 && pitchBytes > 0 && type != TYPE_UNKNOWN && size() == vdata.size();
}

bool Image::load(const std::string& _path)
{
    clear();

    auto path = SearchPathes::image(_path);

    if (path.empty())
    {
        //        std::cout << "could not find " << _path << std::endl;
        return false;
    }

    bool erg         = false;
    std::string type = fileEnding(path);

    if (type == "saigai")
    {
        // saiga raw image format
        return loadRaw(path);
    }

    // use libpng for png images
    if (type == "png")
    {
#ifdef SAIGA_USE_PNG
        ImageIOLibPNG io;
        auto result = io.LoadFromFile(path);
        if (result.has_value())
        {
            *this = result.value();
            return true;
        }
        else
        {
            return false;
        }

#else
        std::cerr << "Warning: Using .png without libpng. This might be slow." << std::endl;
#endif
    }

    // use libfreeimage if available
#ifdef SAIGA_USE_FREEIMAGE
    {
        ImageIOLibFreeimage io;
        auto result = io.LoadFromFile(path);
        if (result.has_value())
        {
            *this = result.value();
            return true;
        }
        else
        {
            return false;
        }
    }
#endif

    // as a last resort use stb_image.h from the internals directory
    erg = loadImageSTB(path, *this);
    return erg;
}

bool Image::loadFromMemory(ArrayView<const char> data, const std::string& hint)
{
    bool erg = false;

    if (hint == "png")
    {
#ifdef SAIGA_USE_PNG

#endif
    }
#ifdef SAIGA_USE_FREEIMAGE
    SAIGA_EXIT_ERROR("not implemented");
    // erg = FIP::loadFromMemory(data, *this);
    // return erg;
#endif

    return erg;
}

std::vector<unsigned char> Image::saveToMemory(std::string file_extension) const
{
    std::vector<unsigned char> result;

    if (file_extension == "png")
    {
#ifdef SAIGA_USE_PNG

        ImageIOLibPNG io;
        return io.Save2Memory(*this);
        SAIGA_EXIT_ERROR("png not implemneted");
#endif
    }
#ifdef SAIGA_USE_FREEIMAGE
    SAIGA_EXIT_ERROR("not implemented");
    // return Saiga::FIP::saveToMemory(*this, file_extension);
#endif

    return result;
}

bool Image::save(const std::string& path) const
{
    SAIGA_ASSERT(valid());

    std::string output_type = fileEnding(path);

    if (output_type == "saigai")
    {
        // saiga raw image format
        return saveRaw(path);
    }

    if (output_type == "jpg" && channels(this->type) != 3)
    {
        std::cerr << "jpg is only supported with 3 channels" << std::endl;
        return false;
    }

    if (output_type == "png")
    {
#ifdef SAIGA_USE_PNG
        // return LibPNG::save(path, *this, false);

        ImageIOLibPNG io;
        return io.Save2File(path, *this);

#else
        std::cerr << "Warning: Using .png without libpng. This might be slow." << std::endl;
#endif
    }

#ifdef SAIGA_USE_FREEIMAGE
    {
        ImageIOLibFreeimage io;
        return io.Save2File(path, *this);
    }
    // return FIP::save(path, *this);
#endif

    // as a last resort use stb_image.h from the internals directory
    return saveImageSTB(path, *this);
}

constexpr int saiga_image_magic_number            = 8574385;
constexpr int saiga_compressed_image_magic_number = 198760233;
constexpr size_t saiga_image_header_size          = 4 * sizeof(int);

bool Image::loadRaw(const std::string& path)
{
    clear();

    auto data = File::loadFileBinary(path);
    BinaryInputVector stream(data.data(), data.size());

    int magic;
    stream >> magic >> width >> height >> type;

    bool compress = false;
    if (magic == saiga_image_magic_number)
    {
        compress = false;
    }
    else if (magic == saiga_compressed_image_magic_number)
    {
        compress = true;
    }
    else
    {
        SAIGA_EXIT_ERROR("invalid magic number");
    }

    pitchBytes = 0;
    create();
    SAIGA_ASSERT(type != TYPE_UNKNOWN);
    int es = elementSize(type);

    if (compress)
    {
#ifdef SAIGA_USE_ZLIB
        auto uncompressed = Saiga::uncompress(stream.data + stream.current);
        size_t line_size  = width * es;
        for (int i = 0; i < height; ++i)
        {
            size_t offset = i * width * es;
            memcpy(rowPtr(i), uncompressed.data() + offset, line_size);
        }
#else
        SAIGA_EXIT_ERROR("zlib required!");
#endif
    }
    else
    {
        for (int i = 0; i < height; ++i)
        {
            stream.read((char*)rowPtr(i), width * es);
        }
    }

    return true;
}

bool Image::saveRaw(const std::string& path, bool do_compress) const
{
    BinaryOutputVector stream;

    int magic = do_compress ? saiga_compressed_image_magic_number : saiga_image_magic_number;
    stream << magic << width << height << type;
    SAIGA_ASSERT(stream.data.size() == saiga_image_header_size);

    int es = elementSize(type);
    for (int i = 0; i < height; ++i)
    {
        // store it compact
        stream.write((char*)rowPtr(i), width * es);
    }

#ifdef SAIGA_USE_ZLIB
    if (do_compress)
    {
        auto compressed_data =
            Saiga::compress(stream.data.data() + saiga_image_header_size, stream.data.size() - saiga_image_header_size);

        std::ofstream is(path, std::ios::binary | std::ios::out);
        is.write(stream.data.data(), saiga_image_header_size);
        is.write((const char*)compressed_data.data(), compressed_data.size());
    }
    else
#endif
    {
        File::saveFileBinary(path, stream.data.data(), stream.data.size());
    }
    return true;
}

bool Image::saveConvert(const std::string& path, float minValue, float maxValue)
{
    if (type == ImageType::F1)
    {
        Saiga::TemplatedImage<ucvec4> i(h, w);
        Saiga::ImageTransformation::depthToRGBA(getImageView<float>(), i.getImageView(), minValue, maxValue);
        i.save(path);
    }

    return false;
}

std::vector<uint8_t> Image::compress()
{
    return compressImageSTB(*this);
}

void Image::decompress(std::vector<uint8_t> data)
{
    decompressImageSTB(*this, data);
}

std::ostream& operator<<(std::ostream& os, const Image& f)
{
    os << "Image " << f.width << "x" << f.height << " "
       << " pitch " << f.pitchBytes << " "
       << " channels/elementType " << channels(f.type) << "/" << (int)elementType(f.type)
       << " BPP: " << bitsPerPixel(f.type);
    return os;
}
vec4 Image::texture(vec2 uv)
{
    switch (type)
    {
        case ImageType::UC3:
            return make_vec4(getImageView<ucvec3>().interUVGL(uv(0), uv(1)).cast<float>() * (1.f / 255.f), 1);
            break;
        case ImageType::UC4:
            return getImageView<ucvec4>().interUVGL(uv(0), uv(1)).cast<float>() * (1.f / 255.f);
            break;
        default:
            SAIGA_EXIT_ERROR("texture not implemented for this image type");
    }
    return Saiga::vec4(0, 0, 0, 0);
}

}  // namespace Saiga


text:
import pandas as pd

train_value = pd.read_csv("train_value.csv")
train_label = pd.read_csv("train_label.csv")
test = pd.read_csv("test.csv")

train_data = train_value.merge(train_label, how = "outer", on = "id", sort = True)
train_data = train_data.fillna(train_data.median())

train_data.to_csv("train_data.csv", index = False)


text:
from django.conf.urls import patterns, include, url
from apps.core import views

urlpatterns = patterns(
    'apps.core',

    url(r'^$', views.HomePageView.as_view(), name="home_page"),
    url(r'^about/?$', views.AboutPageView.as_view(), name="about_page"),
)


text:
<!DOCTYPE html>

     <title>Catálogo Closet For Girls PMW</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

        INÍCIO
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Sobre

              Contato

                Disponível para pedido

                Blusas
                Bodys
                Calças
                Saias
                Vestidos
                Macacões

          Previous

          Next

Welcome to Modern Business

Card Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente esse necessitatibus neque.

              Learn More

Card Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis ipsam eos, nam perspiciatis natus commodi similique totam consectetur praesentium molestiae atque exercitationem ut consequuntur, sed eveniet, magni nostrum sint fuga.

              Learn More

Card Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente esse necessitatibus neque.

              Learn More

Portfolio Heading

                Project One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur eum quasi sapiente nesciunt? Voluptatibus sit, repellat sequi itaque deserunt, dolores in, nesciunt, illum tempora ex quae? Nihil, dolorem!

                Project Two

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.

                Project Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos quisquam, error quod sed cumque, odio distinctio velit nostrum temporibus necessitatibus et facere atque iure perspiciatis mollitia recusandae vero vel quam!

                Project Four

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.

                Project Five

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.

                Project Six

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque earum nostrum suscipit ducimus nihil provident, perferendis rem illo, voluptate atque, sit eius in voluptates, nemo repellat fugiat excepturi! Nemo, esse.

Modern Business Features

The Modern Business template by Start Bootstrap includes:

              Bootstrap v4

jQuery

Font Awesome

Working contact form with validation

Unstyled page elements for easy customization

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis, omnis doloremque non cum id reprehenderit, quisquam totam aspernatur tempora minima unde aliquid ea culpa sunt. Reiciendis quia dolorum ducimus unde.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias, expedita, saepe, vero rerum deleniti beatae veniam harum neque nemo praesentium cum alias asperiores commodi.

          Call to Action

Copyright © Your Website 2017


text:
define(["js/data/Entity"], function(Model) {

    var mimeTypeMap = {
        "xml": "application/xml",
        "js": "text/javascript",
        "json": "application/json"
    };

    return Model.inherit("try.entity.File", {

        defaults: {
            path: "",
            content: ""
        },

        schema: {
            path: String,
            content: String
        },

        mimeType: function() {
            var extension = this.extension().toLowerCase();

            if (mimeTypeMap.hasOwnProperty(extension)) {
                return mimeTypeMap[extension];
            }

            return null;

        }.onChange("path"),

        extension: function() {
            var ret = /\.([^.]+)$/.exec(this.$.path || "");

            if (ret) {
                return ret[1];
            } else {
                return "";
            }
        }.onChange("path"),

        isXaml: function() {
            return /\.xml$/i.test(this.$.path);
        }.onChange("path")

    });
});


text:
.. _ide_visualstudio:

Visual Studio
=============

The `Microsoft Visual Studio (Free) <http://visualstudio.com/free>`_ is an integrated development environment (IDE) from Microsoft. Visual Studio includes a code editor supporting IntelliSense (the code completion component) as well as code refactoring.

This software can be used with:

* all availalbe :ref:`platforms`
* all availalbe :ref:`frameworks`

Refer to the `Visual Studio Documentation <https://msdn.microsoft.com/library/vstudio>`_
page for more detailed information.

.. contents::

Integration
-----------

Setup New Project
^^^^^^^^^^^^^^^^^

First of all, let's create new project from Visual Studio Start Page: ``Start → New Project`` or using ``Menu: File → New → Project``, then select project with ``Makefile`` type (``Visual C++ → General → Makefile Project``), fill ``Project name``, ``Solution name``, ``Location`` fields and press OK button.

.. image:: ../_static/ide-vs-platformio-newproject.png

Secondly, we need to configure project with PlatformIO source code builder:

.. image:: ../_static/ide-vs-platformio-newproject-2.png

If we want to use native AVR programming, we have to specify additional preprocessor symbol ("Preprocessor definitions" field) about your MCU. For example, an Arduino Uno is based on the ATmega328 MCU. In this case We will add new definition  ``__AVR_ATmega328__``.

.. image:: ../_static/ide-vs-platformio-newproject-2-1.png

Release Configuration is the same as Debug, so on the next step we check "Same as Debug Configuration" and click "Finish" button.

.. image:: ../_static/ide-vs-platformio-newproject-3.png

Thirdly, we need to add directories with header files using project properties (right click on the project name or ``Alt-Enter`` shortcut) and add two directories to ``Configuration Properties → NMake → Include Search Path``:

.. code-block:: none

    $(HOMEDRIVE)$(HOMEPATH)\.platformio\packages\toolchain-atmelavr\avr\include
    $(HOMEDRIVE)$(HOMEPATH)\.platformio\packages\framework-arduinoavr\cores\arduino

.. image:: ../_static/ide-vs-platformio-newproject-5.png

First program in Visual Studio
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Simple "Blink" project will consist from two files:

1. Main "C" source file named ``main.c`` must be located in the ``src`` directory.
Let's create new file named ``main.c`` using ``Menu: File → New File`` or shortcut ``Ctrl+N``:

.. image:: ../_static/ide-vs-platformio-newproject-6.png

Copy the source code which is described below to file ``main.c``.

.. code-block:: c

    #include "Arduino.h"
    #define WLED    13  // Most Arduino boards already have an LED attached to pin 13 on the board itself

    void setup()
    {
      pinMode(WLED, OUTPUT);  // set pin as output
    }

    void loop()
    {
      digitalWrite(WLED, HIGH);  // set the LED on
      delay(1000);               // wait for a second
      digitalWrite(WLED, LOW);   // set the LED off
      delay(1000);               // wait for a second
    }

2. Project Configuration File named ``platformio.ini`` must be located in the project root directory.

.. image:: ../_static/ide-vs-platformio-newproject-7.png

Copy the source code which is described below to it.

.. code-block:: none

    #
    # Project Configuration File
    #
    # A detailed documentation with the EXAMPLES is located here:
    # http://docs.platformio.org/en/latest/projectconf.html
    #

    # A sign `#` at the beginning of the line indicates a comment
    # Comment lines are ignored.

    [env:arduino_uno]
    platform = atmelavr
    framework = arduino
    board = uno

Conclusion
----------

Taking everything into account, we can build project with shortcut ``Ctrl+Shift+B`` or using ``Menu: Build → Build Solution``:

.. image:: ../_static/ide-vs-platformio-newproject-8.png


text:
package org.kuali.kfs.module.purap.document.validation.impl;

import org.kuali.kfs.module.purap.PurapKeyConstants;
import org.kuali.kfs.module.purap.PurapPropertyConstants;
import org.kuali.kfs.module.purap.document.PurchasingDocument;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.document.AmountTotaling;
import org.kuali.kfs.sys.document.validation.GenericValidation;
import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.ObjectUtils;

public class RequisitionProcessAdditionalValidation extends GenericValidation {

    /**
     * Validate that if the PurchaseOrderTotalLimit is not null then the TotalDollarAmount cannot be greater than the
     * PurchaseOrderTotalLimit.
     *
     * @param purDocument the requisition document to be validated
     * @return boolean true if the TotalDollarAmount is less than the PurchaseOrderTotalLimit and false otherwise.
     */
    public boolean validate(AttributedDocumentEvent event) {
        boolean valid = true;
        PurchasingDocument purDocument = (PurchasingDocument)event.getDocument();
        GlobalVariables.getMessageMap().clearErrorPath();
        GlobalVariables.getMessageMap().addToErrorPath(KFSPropertyConstants.DOCUMENT);
        if (ObjectUtils.isNotNull(purDocument.getPurchaseOrderTotalLimit()) && ObjectUtils.isNotNull(((AmountTotaling) purDocument).getTotalDollarAmount())) {
            if (((AmountTotaling) purDocument).getTotalDollarAmount().isGreaterThan(purDocument.getPurchaseOrderTotalLimit())) {
                valid &= false;
                GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_TOTAL_LIMIT, PurapKeyConstants.ERROR_PURCHASE_ORDER_EXCEEDING_TOTAL_LIMIT);
            }
        }
        GlobalVariables.getMessageMap().clearErrorPath();

        return valid;
    }

}


text:
require 'action_controller'
require "sp_authentication/version"
require 'sp_authentication/configuration'
require 'sp_authentication/generator'
require 'sp_authentication/core'
#require 'pry-debugger'
require 'sp_authentication/custom_error'

module SpAuthentication
  extend Configuration
  include Core

  def self.extended(obj)
    obj.sp_authentication
  end
end

ActionController::Base.send(:extend, SpAuthentication) if defined?(ActionController)


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.orc.metadata;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Longs;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.airlift.units.DataSize;
import io.trino.orc.metadata.ColumnEncoding.ColumnEncodingKind;
import io.trino.orc.metadata.OrcType.OrcTypeKind;
import io.trino.orc.metadata.PostScript.HiveWriterVersion;
import io.trino.orc.metadata.Stream.StreamKind;
import io.trino.orc.metadata.statistics.BinaryStatistics;
import io.trino.orc.metadata.statistics.BloomFilter;
import io.trino.orc.metadata.statistics.BooleanStatistics;
import io.trino.orc.metadata.statistics.ColumnStatistics;
import io.trino.orc.metadata.statistics.DateStatistics;
import io.trino.orc.metadata.statistics.DecimalStatistics;
import io.trino.orc.metadata.statistics.DoubleStatistics;
import io.trino.orc.metadata.statistics.IntegerStatistics;
import io.trino.orc.metadata.statistics.StringStatistics;
import io.trino.orc.metadata.statistics.StripeStatistics;
import io.trino.orc.metadata.statistics.TimestampStatistics;
import io.trino.orc.proto.OrcProto;
import io.trino.orc.proto.OrcProto.RowIndexEntry;
import io.trino.orc.protobuf.ByteString;
import io.trino.orc.protobuf.CodedInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.ByteOrder;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.airlift.slice.SliceUtf8.lengthOfCodePoint;
import static io.airlift.slice.SliceUtf8.tryGetCodePointAt;
import static io.airlift.units.DataSize.Unit.GIGABYTE;
import static io.trino.orc.metadata.CompressionKind.LZ4;
import static io.trino.orc.metadata.CompressionKind.NONE;
import static io.trino.orc.metadata.CompressionKind.SNAPPY;
import static io.trino.orc.metadata.CompressionKind.ZLIB;
import static io.trino.orc.metadata.CompressionKind.ZSTD;
import static io.trino.orc.metadata.PostScript.HiveWriterVersion.ORC_HIVE_8732;
import static io.trino.orc.metadata.PostScript.HiveWriterVersion.ORIGINAL;
import static io.trino.orc.metadata.statistics.BinaryStatistics.BINARY_VALUE_BYTES_OVERHEAD;
import static io.trino.orc.metadata.statistics.BooleanStatistics.BOOLEAN_VALUE_BYTES;
import static io.trino.orc.metadata.statistics.DateStatistics.DATE_VALUE_BYTES;
import static io.trino.orc.metadata.statistics.DecimalStatistics.DECIMAL_VALUE_BYTES_OVERHEAD;
import static io.trino.orc.metadata.statistics.DoubleStatistics.DOUBLE_VALUE_BYTES;
import static io.trino.orc.metadata.statistics.IntegerStatistics.INTEGER_VALUE_BYTES;
import static io.trino.orc.metadata.statistics.ShortDecimalStatisticsBuilder.SHORT_DECIMAL_VALUE_BYTES;
import static io.trino.orc.metadata.statistics.StringStatistics.STRING_VALUE_BYTES_OVERHEAD;
import static io.trino.orc.metadata.statistics.TimestampStatistics.TIMESTAMP_VALUE_BYTES;
import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;
import static java.lang.Math.toIntExact;

public class OrcMetadataReader
        implements MetadataReader
{
    private static final int REPLACEMENT_CHARACTER_CODE_POINT = 0xFFFD;
    private static final int PROTOBUF_MESSAGE_MAX_LIMIT = toIntExact(DataSize.of(1, GIGABYTE).toBytes());

    @Override
    public PostScript readPostScript(InputStream inputStream)
            throws IOException
    {
        CodedInputStream input = CodedInputStream.newInstance(inputStream);
        OrcProto.PostScript postScript = OrcProto.PostScript.parseFrom(input);

        return new PostScript(
                postScript.getVersionList(),
                postScript.getFooterLength(),
                postScript.getMetadataLength(),
                toCompression(postScript.getCompression()),
                postScript.getCompressionBlockSize(),
                toHiveWriterVersion(postScript.getWriterVersion()));
    }

    private static HiveWriterVersion toHiveWriterVersion(int writerVersion)
    {
        if (writerVersion >= 1) {
            return ORC_HIVE_8732;
        }
        return ORIGINAL;
    }

    @Override
    public Metadata readMetadata(HiveWriterVersion hiveWriterVersion, InputStream inputStream)
            throws IOException
    {
        CodedInputStream input = CodedInputStream.newInstance(inputStream);
        input.setSizeLimit(PROTOBUF_MESSAGE_MAX_LIMIT);
        OrcProto.Metadata metadata = OrcProto.Metadata.parseFrom(input);
        return new Metadata(toStripeStatistics(hiveWriterVersion, metadata.getStripeStatsList()));
    }

    private static List<Optional<StripeStatistics>> toStripeStatistics(HiveWriterVersion hiveWriterVersion, List<OrcProto.StripeStatistics> types)
    {
        return types.stream()
                .map(stripeStatistics -> toStripeStatistics(hiveWriterVersion, stripeStatistics))
                .collect(toImmutableList());
    }

    private static Optional<StripeStatistics> toStripeStatistics(HiveWriterVersion hiveWriterVersion, OrcProto.StripeStatistics stripeStatistics)
    {
        return toColumnStatistics(hiveWriterVersion, stripeStatistics.getColStatsList(), false)
                .map(StripeStatistics::new);
    }

    @Override
    public Footer readFooter(HiveWriterVersion hiveWriterVersion, InputStream inputStream)
            throws IOException
    {
        CodedInputStream input = CodedInputStream.newInstance(inputStream);
        input.setSizeLimit(PROTOBUF_MESSAGE_MAX_LIMIT);
        OrcProto.Footer footer = OrcProto.Footer.parseFrom(input);
        return new Footer(
                footer.getNumberOfRows(),
                footer.getRowIndexStride() == 0 ? OptionalInt.empty() : OptionalInt.of(footer.getRowIndexStride()),
                toStripeInformation(footer.getStripesList()),
                toType(footer.getTypesList()),
                toColumnStatistics(hiveWriterVersion, footer.getStatisticsList(), false),
                toUserMetadata(footer.getMetadataList()),
                Optional.of(footer.getWriter()));
    }

    private static List<StripeInformation> toStripeInformation(List<OrcProto.StripeInformation> types)
    {
        return types.stream()
                .map(OrcMetadataReader::toStripeInformation)
                .collect(toImmutableList());
    }

    private static StripeInformation toStripeInformation(OrcProto.StripeInformation stripeInformation)
    {
        return new StripeInformation(
                toIntExact(stripeInformation.getNumberOfRows()),
                stripeInformation.getOffset(),
                stripeInformation.getIndexLength(),
                stripeInformation.getDataLength(),
                stripeInformation.getFooterLength());
    }

    @Override
    public StripeFooter readStripeFooter(ColumnMetadata<OrcType> types, InputStream inputStream, ZoneId legacyFileTimeZone)
            throws IOException
    {
        CodedInputStream input = CodedInputStream.newInstance(inputStream);
        OrcProto.StripeFooter stripeFooter = OrcProto.StripeFooter.parseFrom(input);
        return new StripeFooter(
                toStream(stripeFooter.getStreamsList()),
                toColumnEncoding(stripeFooter.getColumnsList()),
                Optional.ofNullable(emptyToNull(stripeFooter.getWriterTimezone()))
                        .map(ZoneId::of)
                        .orElse(legacyFileTimeZone));
    }

    private static Stream toStream(OrcProto.Stream stream)
    {
        return new Stream(new OrcColumnId(stream.getColumn()), toStreamKind(stream.getKind()), toIntExact(stream.getLength()), true);
    }

    private static List<Stream> toStream(List<OrcProto.Stream> streams)
    {
        return streams.stream()
                .map(OrcMetadataReader::toStream)
                .collect(toImmutableList());
    }

    private static ColumnEncoding toColumnEncoding(OrcProto.ColumnEncoding columnEncoding)
    {
        return new ColumnEncoding(toColumnEncodingKind(columnEncoding.getKind()), columnEncoding.getDictionarySize());
    }

    private static ColumnMetadata<ColumnEncoding> toColumnEncoding(List<OrcProto.ColumnEncoding> columnEncodings)
    {
        return new ColumnMetadata<>(columnEncodings.stream()
                .map(OrcMetadataReader::toColumnEncoding)
                .collect(toImmutableList()));
    }

    @Override
    public List<RowGroupIndex> readRowIndexes(HiveWriterVersion hiveWriterVersion, InputStream inputStream)
            throws IOException
    {
        CodedInputStream input = CodedInputStream.newInstance(inputStream);
        OrcProto.RowIndex rowIndex = OrcProto.RowIndex.parseFrom(input);
        return rowIndex.getEntryList().stream()
                .map(rowIndexEntry -> toRowGroupIndex(hiveWriterVersion, rowIndexEntry))
                .collect(toImmutableList());
    }

    @Override
    public List<BloomFilter> readBloomFilterIndexes(InputStream inputStream)
            throws IOException
    {
        CodedInputStream input = CodedInputStream.newInstance(inputStream);
        OrcProto.BloomFilterIndex bloomFilter = OrcProto.BloomFilterIndex.parseFrom(input);
        List<OrcProto.BloomFilter> bloomFilterList = bloomFilter.getBloomFilterList();
        ImmutableList.Builder<BloomFilter> builder = ImmutableList.builder();
        for (OrcProto.BloomFilter orcBloomFilter : bloomFilterList) {
            if (orcBloomFilter.hasUtf8Bitset()) {
                ByteString utf8Bitset = orcBloomFilter.getUtf8Bitset();
                long[] bits = new long[utf8Bitset.size() / 8];
                utf8Bitset.asReadOnlyByteBuffer().order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().get(bits);
                builder.add(new BloomFilter(bits, orcBloomFilter.getNumHashFunctions()));
            }
            else {
                builder.add(new BloomFilter(Longs.toArray(orcBloomFilter.getBitsetList()), orcBloomFilter.getNumHashFunctions()));
            }
        }
        return builder.build();
    }

    private static RowGroupIndex toRowGroupIndex(HiveWriterVersion hiveWriterVersion, RowIndexEntry rowIndexEntry)
    {
        List<Long> positionsList = rowIndexEntry.getPositionsList();
        ImmutableList.Builder<Integer> positions = ImmutableList.builder();
        for (int index = 0; index < positionsList.size(); index++) {
            long longPosition = positionsList.get(index);

            @SuppressWarnings("NumericCastThatLosesPrecision")
            int intPosition = (int) longPosition;
            checkArgument(intPosition == longPosition, "Expected checkpoint position [%s] value [%s] to be an integer", index, longPosition);

            positions.add(intPosition);
        }
        return new RowGroupIndex(positions.build(), toColumnStatistics(hiveWriterVersion, rowIndexEntry.getStatistics(), true));
    }

    private static ColumnStatistics toColumnStatistics(HiveWriterVersion hiveWriterVersion, OrcProto.ColumnStatistics statistics, boolean isRowGroup)
    {
        long minAverageValueBytes;

        if (statistics.hasBucketStatistics()) {
            minAverageValueBytes = BOOLEAN_VALUE_BYTES;
        }
        else if (statistics.hasIntStatistics()) {
            minAverageValueBytes = INTEGER_VALUE_BYTES;
        }
        else if (statistics.hasDoubleStatistics()) {
            minAverageValueBytes = DOUBLE_VALUE_BYTES;
        }
        else if (statistics.hasStringStatistics()) {
            minAverageValueBytes = STRING_VALUE_BYTES_OVERHEAD;
            if (statistics.hasNumberOfValues() && statistics.getNumberOfValues() > 0) {
                minAverageValueBytes += statistics.getStringStatistics().getSum() / statistics.getNumberOfValues();
            }
        }
        else if (statistics.hasDateStatistics()) {
            minAverageValueBytes = DATE_VALUE_BYTES;
        }
        else if (statistics.hasTimestampStatistics()) {
            minAverageValueBytes = TIMESTAMP_VALUE_BYTES;
        }
        else if (statistics.hasDecimalStatistics()) {
            // could be 8 or 16; return the smaller one given it is a min average
            minAverageValueBytes = DECIMAL_VALUE_BYTES_OVERHEAD + SHORT_DECIMAL_VALUE_BYTES;
        }
        else if (statistics.hasBinaryStatistics()) {
            // offset and value length
            minAverageValueBytes = BINARY_VALUE_BYTES_OVERHEAD;
            if (statistics.hasNumberOfValues() && statistics.getNumberOfValues() > 0) {
                minAverageValueBytes += statistics.getBinaryStatistics().getSum() / statistics.getNumberOfValues();
            }
        }
        else {
            minAverageValueBytes = 0;
        }

        // To handle an existing issue of Hive writer during minor compaction (HIVE-20604):
        // After minor compaction, stripe stats don't have column statistics and bit field of numberOfValues
        // is set to 1, but the value is wrongly set to default 0 which implies there is something wrong with
        // the stats. Drop the column statistics altogether.
        if (statistics.hasHasNull() && statistics.getNumberOfValues() == 0 && !statistics.getHasNull()) {
            return new ColumnStatistics(null, 0, null, null, null, null, null, null, null, null, null);
        }

        return new ColumnStatistics(
                statistics.getNumberOfValues(),
                minAverageValueBytes,
                statistics.hasBucketStatistics() ? toBooleanStatistics(statistics.getBucketStatistics()) : null,
                statistics.hasIntStatistics() ? toIntegerStatistics(statistics.getIntStatistics()) : null,
                statistics.hasDoubleStatistics() ? toDoubleStatistics(statistics.getDoubleStatistics()) : null,
                statistics.hasStringStatistics() ? toStringStatistics(hiveWriterVersion, statistics.getStringStatistics(), isRowGroup) : null,
                statistics.hasDateStatistics() ? toDateStatistics(hiveWriterVersion, statistics.getDateStatistics(), isRowGroup) : null,
                statistics.hasTimestampStatistics() ? toTimestampStatistics(hiveWriterVersion, statistics.getTimestampStatistics(), isRowGroup) : null,
                statistics.hasDecimalStatistics() ? toDecimalStatistics(statistics.getDecimalStatistics()) : null,
                statistics.hasBinaryStatistics() ? toBinaryStatistics(statistics.getBinaryStatistics()) : null,
                null);
    }

    private static Optional<ColumnMetadata<ColumnStatistics>> toColumnStatistics(HiveWriterVersion hiveWriterVersion, List<OrcProto.ColumnStatistics> columnStatistics, boolean isRowGroup)
    {
        if (columnStatistics == null || columnStatistics.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(new ColumnMetadata<>(columnStatistics.stream()
                .map(statistics -> toColumnStatistics(hiveWriterVersion, statistics, isRowGroup))
                .collect(toImmutableList())));
    }

    private static Map<String, Slice> toUserMetadata(List<OrcProto.UserMetadataItem> metadataList)
    {
        ImmutableMap.Builder<String, Slice> mapBuilder = ImmutableMap.builder();
        for (OrcProto.UserMetadataItem item : metadataList) {
            mapBuilder.put(item.getName(), byteStringToSlice(item.getValue()));
        }
        return mapBuilder.build();
    }

    private static BooleanStatistics toBooleanStatistics(OrcProto.BucketStatistics bucketStatistics)
    {
        if (bucketStatistics.getCountCount() == 0) {
            return null;
        }

        return new BooleanStatistics(bucketStatistics.getCount(0));
    }

    private static IntegerStatistics toIntegerStatistics(OrcProto.IntegerStatistics integerStatistics)
    {
        return new IntegerStatistics(
                integerStatistics.hasMinimum() ? integerStatistics.getMinimum() : null,
                integerStatistics.hasMaximum() ? integerStatistics.getMaximum() : null,
                integerStatistics.hasSum() ? integerStatistics.getSum() : null);
    }

    private static DoubleStatistics toDoubleStatistics(OrcProto.DoubleStatistics doubleStatistics)
    {
        // TODO remove this when double statistics are changed to correctly deal with NaNs
        // if either min, max, or sum is NaN, ignore the stat
        if ((doubleStatistics.hasMinimum() && Double.isNaN(doubleStatistics.getMinimum())) ||
                (doubleStatistics.hasMaximum() && Double.isNaN(doubleStatistics.getMaximum())) ||
                (doubleStatistics.hasSum() && Double.isNaN(doubleStatistics.getSum()))) {
            return null;
        }

        return new DoubleStatistics(
                doubleStatistics.hasMinimum() ? doubleStatistics.getMinimum() : null,
                doubleStatistics.hasMaximum() ? doubleStatistics.getMaximum() : null);
    }

    static StringStatistics toStringStatistics(HiveWriterVersion hiveWriterVersion, OrcProto.StringStatistics stringStatistics, boolean isRowGroup)
    {
        if (hiveWriterVersion == ORIGINAL && !isRowGroup) {
            return null;
        }

        Slice maximum = stringStatistics.hasMaximum() ? maxStringTruncateToValidRange(byteStringToSlice(stringStatistics.getMaximumBytes()), hiveWriterVersion) : null;
        Slice minimum = stringStatistics.hasMinimum() ? minStringTruncateToValidRange(byteStringToSlice(stringStatistics.getMinimumBytes()), hiveWriterVersion) : null;
        long sum = stringStatistics.hasSum() ? stringStatistics.getSum() : 0;
        return new StringStatistics(minimum, maximum, sum);
    }

    private static DecimalStatistics toDecimalStatistics(OrcProto.DecimalStatistics decimalStatistics)
    {
        BigDecimal minimum = decimalStatistics.hasMinimum() ? new BigDecimal(decimalStatistics.getMinimum()) : null;
        BigDecimal maximum = decimalStatistics.hasMaximum() ? new BigDecimal(decimalStatistics.getMaximum()) : null;

        // could be long (16 bytes) or short (8 bytes); use short for estimation
        return new DecimalStatistics(minimum, maximum, SHORT_DECIMAL_VALUE_BYTES);
    }

    private static BinaryStatistics toBinaryStatistics(OrcProto.BinaryStatistics binaryStatistics)
    {
        if (!binaryStatistics.hasSum()) {
            return null;
        }

        return new BinaryStatistics(binaryStatistics.getSum());
    }

    private static Slice byteStringToSlice(ByteString value)
    {
        return Slices.wrappedBuffer(value.toByteArray());
    }

    @VisibleForTesting
    public static Slice maxStringTruncateToValidRange(Slice value, HiveWriterVersion version)
    {
        if (value == null) {
            return null;
        }

        if (version != ORIGINAL) {
            return value;
        }

        int index = findStringStatisticTruncationPositionForOriginalOrcWriter(value);
        if (index == value.length()) {
            return value;
        }
        // Append 0xFF so that it is larger than value
        Slice newValue = Slices.copyOf(value, 0, index + 1);
        newValue.setByte(index, 0xFF);
        return newValue;
    }

    @VisibleForTesting
    public static Slice minStringTruncateToValidRange(Slice value, HiveWriterVersion version)
    {
        if (value == null) {
            return null;
        }

        if (version != ORIGINAL) {
            return value;
        }

        int index = findStringStatisticTruncationPositionForOriginalOrcWriter(value);
        if (index == value.length()) {
            return value;
        }
        return Slices.copyOf(value, 0, index);
    }

    @VisibleForTesting
    static int findStringStatisticTruncationPositionForOriginalOrcWriter(Slice utf8)
    {
        int length = utf8.length();

        int position = 0;
        while (position < length) {
            int codePoint = tryGetCodePointAt(utf8, position);

            // stop at invalid sequences
            if (codePoint < 0) {
                break;
            }

            // The original ORC writers round trip string min and max values through java.lang.String which
            // replaces invalid UTF-8 sequences with the unicode replacement character.  This can cause the min value to be
            // greater than expected which can result in data sections being skipped instead of being processed. As a work around,
            // the string stats are truncated at the first replacement character.
            if (codePoint == REPLACEMENT_CHARACTER_CODE_POINT) {
                break;
            }

            // The original writer performs comparisons using java Strings to determine the minimum and maximum
            // values. This results in weird behaviors in the presence of surrogate pairs and special characters.
            //
            // For example, unicode code point 0x1D403 has the following representations:
            // UTF-16: [0xD835, 0xDC03]
            // UTF-8: [0xF0, 0x9D, 0x90, 0x83]
            //
            // while code point 0xFFFD (the replacement character) has the following representations:
            // UTF-16: [0xFFFD]
            // UTF-8: [0xEF, 0xBF, 0xBD]
            //
            // when comparisons between strings containing these characters are done with Java Strings (UTF-16),
            // 0x1D403 < 0xFFFD, but when comparisons are done using raw codepoints or UTF-8, 0x1D403 > 0xFFFD
            //
            // We use the following logic to ensure that we have a wider range of min-max
            // * if a min string has a surrogate character, the min string is truncated
            //   at the first occurrence of the surrogate character (to exclude the surrogate character)
            // * if a max string has a surrogate character, the max string is truncated
            //   at the first occurrence the surrogate character and 0xFF byte is appended to it.
            if (codePoint >= MIN_SUPPLEMENTARY_CODE_POINT) {
                break;
            }

            position += lengthOfCodePoint(codePoint);
        }
        return position;
    }

    private static DateStatistics toDateStatistics(HiveWriterVersion hiveWriterVersion, OrcProto.DateStatistics dateStatistics, boolean isRowGroup)
    {
        if (hiveWriterVersion == ORIGINAL && !isRowGroup) {
            return null;
        }

        return new DateStatistics(
                dateStatistics.hasMinimum() ? dateStatistics.getMinimum() : null,
                dateStatistics.hasMaximum() ? dateStatistics.getMaximum() : null);
    }

    private static TimestampStatistics toTimestampStatistics(HiveWriterVersion hiveWriterVersion, OrcProto.TimestampStatistics timestampStatistics, boolean isRowGroup)
    {
        if (hiveWriterVersion == ORIGINAL && !isRowGroup) {
            return null;
        }

        return new TimestampStatistics(
                timestampStatistics.hasMinimumUtc() ? timestampStatistics.getMinimumUtc() : null,
                timestampStatistics.hasMaximumUtc() ? timestampStatistics.getMaximumUtc() : null);
    }

    private static OrcType toType(OrcProto.Type type)
    {
        Optional<Integer> length = Optional.empty();
        if (type.getKind() == OrcProto.Type.Kind.VARCHAR || type.getKind() == OrcProto.Type.Kind.CHAR) {
            length = Optional.of(type.getMaximumLength());
        }
        Optional<Integer> precision = Optional.empty();
        Optional<Integer> scale = Optional.empty();
        if (type.getKind() == OrcProto.Type.Kind.DECIMAL) {
            precision = Optional.of(type.getPrecision());
            scale = Optional.of(type.getScale());
        }
        return new OrcType(toTypeKind(type.getKind()), toOrcColumnId(type.getSubtypesList()), type.getFieldNamesList(), length, precision, scale, toMap(type.getAttributesList()));
    }

    private static List<OrcColumnId> toOrcColumnId(List<Integer> columnIds)
    {
        return columnIds.stream()
                .map(OrcColumnId::new)
                .collect(toImmutableList());
    }

    private static ColumnMetadata<OrcType> toType(List<OrcProto.Type> types)
    {
        return new ColumnMetadata<>(types.stream()
                .map(OrcMetadataReader::toType)
                .collect(toImmutableList()));
    }

    private static OrcTypeKind toTypeKind(OrcProto.Type.Kind typeKind)
    {
        switch (typeKind) {
            case BOOLEAN:
                return OrcTypeKind.BOOLEAN;
            case BYTE:
                return OrcTypeKind.BYTE;
            case SHORT:
                return OrcTypeKind.SHORT;
            case INT:
                return OrcTypeKind.INT;
            case LONG:
                return OrcTypeKind.LONG;
            case FLOAT:
                return OrcTypeKind.FLOAT;
            case DOUBLE:
                return OrcTypeKind.DOUBLE;
            case STRING:
                return OrcTypeKind.STRING;
            case BINARY:
                return OrcTypeKind.BINARY;
            case TIMESTAMP:
                return OrcTypeKind.TIMESTAMP;
            case TIMESTAMP_INSTANT:
                return OrcTypeKind.TIMESTAMP_INSTANT;
            case LIST:
                return OrcTypeKind.LIST;
            case MAP:
                return OrcTypeKind.MAP;
            case STRUCT:
                return OrcTypeKind.STRUCT;
            case UNION:
                return OrcTypeKind.UNION;
            case DECIMAL:
                return OrcTypeKind.DECIMAL;
            case DATE:
                return OrcTypeKind.DATE;
            case VARCHAR:
                return OrcTypeKind.VARCHAR;
            case CHAR:
                return OrcTypeKind.CHAR;
        }
        throw new IllegalStateException(typeKind + " stream type not implemented yet");
    }

    // This method assumes type attributes have no duplicate key
    private static Map<String, String> toMap(List<OrcProto.StringPair> attributes)
    {
        ImmutableMap.Builder<String, String> results = new ImmutableMap.Builder<>();
        if (attributes != null) {
            for (OrcProto.StringPair attribute : attributes) {
                if (attribute.hasKey() && attribute.hasValue()) {
                    results.put(attribute.getKey(), attribute.getValue());
                }
            }
        }
        return results.build();
    }

    private static StreamKind toStreamKind(OrcProto.Stream.Kind streamKind)
    {
        switch (streamKind) {
            case PRESENT:
                return StreamKind.PRESENT;
            case DATA:
                return StreamKind.DATA;
            case LENGTH:
                return StreamKind.LENGTH;
            case DICTIONARY_DATA:
                return StreamKind.DICTIONARY_DATA;
            case DICTIONARY_COUNT:
                return StreamKind.DICTIONARY_COUNT;
            case SECONDARY:
                return StreamKind.SECONDARY;
            case ROW_INDEX:
                return StreamKind.ROW_INDEX;
            case BLOOM_FILTER:
                return StreamKind.BLOOM_FILTER;
            case BLOOM_FILTER_UTF8:
                return StreamKind.BLOOM_FILTER_UTF8;
            case ENCRYPTED_INDEX:
            case ENCRYPTED_DATA:
            case STRIPE_STATISTICS:
            case FILE_STATISTICS:
                // unsupported
                break;
        }
        throw new IllegalStateException(streamKind + " stream type not implemented yet");
    }

    private static ColumnEncodingKind toColumnEncodingKind(OrcProto.ColumnEncoding.Kind columnEncodingKind)
    {
        switch (columnEncodingKind) {
            case DIRECT:
                return ColumnEncodingKind.DIRECT;
            case DIRECT_V2:
                return ColumnEncodingKind.DIRECT_V2;
            case DICTIONARY:
                return ColumnEncodingKind.DICTIONARY;
            case DICTIONARY_V2:
                return ColumnEncodingKind.DICTIONARY_V2;
        }
        throw new IllegalStateException(columnEncodingKind + " stream encoding not implemented yet");
    }

    private static CompressionKind toCompression(OrcProto.CompressionKind compression)
    {
        switch (compression) {
            case NONE:
                return NONE;
            case ZLIB:
                return ZLIB;
            case SNAPPY:
                return SNAPPY;
            case LZO:
                // TODO unsupported
                break;
            case LZ4:
                return LZ4;
            case ZSTD:
                return ZSTD;
        }
        throw new IllegalStateException(compression + " compression not implemented yet");
    }
}


text:
/* eslint-disable no-console */

import {Answers,} from 'react-native-fabric';

import * as appActionTypes from '../actionTypes/app';
import * as homeTabsActionTypes from '../actionTypes/homeTabs';
import * as homeTabsSelectors from '../selectors/homeTabs';
import * as onboardingActionTypes from '../actionTypes/onboarding';
import * as pubsActionTypes from '../actionTypes/pubs';
import * as pubsSelectors from '../selectors/pubs';

export const middleware = (store) => (next) => (action) => {
  switch (action.type) {
  case appActionTypes.SHOW_OPTIONS: {
    Answers.logContentView('Settings');
    console.info('logContentView', 'Settings');
    break;
  }
  case appActionTypes.RESET: {
    Answers.logCustom('Reset app');
    console.info('logCustom', 'Reset app');
    break;
  }

  case homeTabsActionTypes.CHANGE_TAB: {
    const tabName = homeTabsSelectors.tabName(store.getState());
    Answers.logContentView('Home tab', tabName);
    console.info('logContentView', 'Home tab', tabName);
    break;
  }

  case onboardingActionTypes.SELECT_CITY: {
    Answers.logCustom('Select city', {id: action.cityId, name: action.name,});
    console.info('logCustom', 'Select city', {id: action.cityId, name: action.name,});
    break;
  }

  case pubsActionTypes.SELECT_PUB: {
    Answers.logContentView('Pub', action.name, action.id);
    console.info('logContentView', 'Pub', action.name, action.id);
    break;
  }

  case pubsActionTypes.TOGGLE_FAVORITE_PUB: {
    const pub = pubsSelectors.pub(store.getState(), action.id);
    const name = `Pub ${pub.favorited ? 'unfavourite' : 'favorite'}`;
    Answers.logCustom(name, {name: pub.name, id: pub.id,});
    console.info('logCustom', name, {name: pub.name, id: pub.id,});
    break;
  }
  }
  return next(action);
};


text:
package com.amlinv.jmxutil.polling;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.Attribute;
import javax.management.ObjectName;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * Inject attribute values into an object based on field names and setters.
 *
 * Created by art on 8/22/15.
 */
public class AttributeInjector {
    private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(AttributeInjector.class);

    private Logger log = DEFAULT_LOGGER;

    public Logger getLog() {
        return log;
    }

    public void setLog(Logger log) {
        this.log = log;
    }

    /**
     * For a JMX MBean idenfitied by an ObjectName, copy the values of the given attributes into the target object
     * using the specified setter methods mapped by attribute name.
     *
     * @param target object into which values are injected.
     * @param jmxAttributeValues values of the attributes to inject.
     * @param attributeSetters map of attribute name to setter used to determine how to inject each attribute's value.
     * @param objectName name of the MBean involved - used only for logging.
     */
    public void copyOutAttributes(Object target, List<Attribute> jmxAttributeValues,
                                  Map<String, Method> attributeSetters, ObjectName objectName) {

        this.copyOutAttributes(target, jmxAttributeValues, attributeSetters, "oname", objectName);
    }

    /**
     * Copy the values of the given attributes into the target object using the specified setter methods mapped by
     * attribute name.
     *
     * @param target object into which values are injected.
     * @param jmxAttributeValues values of the attributes to inject.
     * @param attributeSetters map of attribute name to setter used to determine how to inject each attribute's value.
     * @param identifierKey key, or name, of the identifier - used only for logging purposes.
     * @param identifier identifier to include in the output - used only for logging purposes.
     */
    protected void copyOutAttributes(Object target, List<Attribute> jmxAttributeValues,
                                     Map<String, Method> attributeSetters, String identifierKey, Object identifier) {

        for (Attribute oneAttribute : jmxAttributeValues) {
            String attributeName = oneAttribute.getName();

            Method setter = attributeSetters.get(attributeName);
            Object value = oneAttribute.getValue();

            try {
                //
                // Automatically down-convert longs to integers as-needed.
                //
                if ((setter.getParameterTypes()[0].isAssignableFrom(Integer.class)) ||
                    (setter.getParameterTypes()[0].isAssignableFrom(int.class))) {
                    if (value instanceof Long) {
                        value = ((Long) value).intValue();
                    }
                }
                setter.invoke(target, value);
            } catch (InvocationTargetException invocationExc) {
                this.log.info("invocation exception storing mbean results: {}={}; attributeName={}", identifierKey,
                        identifier, attributeName, invocationExc);
            } catch (IllegalAccessException illegalAccessExc) {
                this.log.info("illegal access exception storing mbean results: {}={}; attributeName={}", identifierKey,
                        identifier, attributeName, illegalAccessExc);
            } catch (IllegalArgumentException illegalArgumentExc) {
                this.log.info("illegal argument exception storing mbean results: {}={}; attributeName={}",
                        identifierKey, identifier, attributeName, illegalArgumentExc);
            }
        }
    }
}


text:
class AcDbObjectId;
class AcDbSubentId;
class AcEdSelectedTransientImp;
class AcGsDCRect;
class AcEdSolidSubentitySelector
{
public:
  AcEdSolidSubentitySelector();
  ~AcEdSolidSubentitySelector();
  Acad::ErrorStatus selectFaces(AcDbObjectId& selectedSolidId, AcArray<AcDbSubentId *>& faceSet);
};
class AcEdSelectedTransient
{
public:
  AcEdSelectedTransient();
  AcEdSelectedTransient(const AcEdSelectedTransient& source);
  AcEdSelectedTransient& operator=(const AcEdSelectedTransient& source);
  ~AcEdSelectedTransient();
  AcGiDrawable* parent();
  AcGiDrawable* drawable();
  Adesk::GsMarker marker();
  AcGiTransientDrawingMode mode();
  int subDrawingMode();
protected:
  AcEdSelectedTransientImp* mImp;
  friend class AcEdTransientSelectionInternals;
};
//This function returns all transients that draw any geometry inside the pickbox.
Acad::ErrorStatus acedSelectTransients(const AcGsDCRect& rect, int viewportNumber, AcArray<AcEdSelectedTransient>& result);
#  pragma  pack (pop)
#endif


text:
class Gallerist::ModelResource < Gallerist::ImageProxiesModel

  self.table_name = 'RKModelResource'

  belongs_to :photo

  alias_attribute :file_name, :filename
  alias_attribute :model_type, :attachedModelType
  alias_attribute :uuid, :resourceUuid

  default_scope { select(:attachedModelType, :filename, :modelId, :resourceUuid) }

  def inspect
    "#<#{self.class} id=#{id} uuid=#{uuid} file_name=#{file_name}>"
  end

end


text:
<?php

class Pimcore_Controller_Plugin_AdminButton extends Zend_Controller_Plugin_Abstract {

    /**
     *
     */
    public function dispatchLoopShutdown() {

        if(!Pimcore_Tool::isHtmlResponse($this->getResponse())) {
            return;
        }

        if(!Pimcore_Tool::useFrontendOutputFilters($this->getRequest()) && !$this->getRequest()->getParam("pimcore_preview")) {
            return;
        }

        if(isset($_COOKIE["pimcore_admin_sid"])) {

            $user = Pimcore_Tool_Authentication::authenticateSession();
            if($user instanceof User) {
                $body = $this->getResponse()->getBody();

                if($this->getRequest()->getParam("document") && !Staticroute::getCurrentRoute()) {
                    $documentId =    $this->getRequest()->getParam("document")->getId();
                }

                $config = Pimcore_Config::getSystemConfig();
                $contactEnabled = false;
                if($config->general->contactemail) {
                    $contactEnabled = true;
                }

                if(!$documentId) {
                    $documentId = "null";
                }

                $code = "\n\n\n\n";
                $code .= '';

                $code .= '';
                $code .= '<link rel="stylesheet" type="text/css" href="/pimcore/static/js/frontend/admin/admin.css" />' . "\n\n\n";

                // search for the end  tag, and insert the google analytics code before
                // this method is much faster than using simple_html_dom and uses less memory
                $bodyEndPosition = stripos($body, "");
                if($bodyEndPosition !== false) {
                    $body = substr_replace($body, $code . "\n\n\n", $bodyEndPosition, 7);
                }

                $this->getResponse()->setBody($body);
            }
        }
    }
}


text:
from string import ascii_uppercase

def get_triangle_number(string):

    data = list(string)
    sum_of_indices = sum([char_to_index[key] for key in data])

    return sum_of_indices

def get_nth_triangle_number(n):

    return int(1/2*n*(n+1))

def get_maximum_triangle_number_with_n_character(n):

    k = 2
    triangle_number_candidates = [1]

    largest_alphabet_index = ascii_uppercase.index('Z')+1
    largest_sum_of_alphabet = largest_alphabet_index * n

    while max(triangle_number_candidates) < largest_sum_of_alphabet:
        value = get_nth_triangle_number(k)
        triangle_number_candidates.append(value)
        k += 1

    return triangle_number_candidates

def main():

    global char_to_index
    char_to_index = {letter:idx+1 for idx, letter in enumerate(ascii_uppercase)}

    # read file and create a tuple of words
    with open('../../data/p042_words.txt', 'r') as f:
        word_raw = eval(f.read().split()[0])
        word_list = sorted(word_raw, key=len)

    max_char_in_word_list = len(word_list[-1])
    triangle_number_candidate_list = get_maximum_triangle_number_with_n_character(max_char_in_word_list)
    answer = sum([1 for word in word_list if get_triangle_number(word) in triangle_number_candidate_list])

    return answer

if __name__ == "__main__":
   print(main())


text:
<?php

namespace Abds\MaincoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Abds\MaincoreBundle\Entity\Album
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Abds\MaincoreBundle\Entity\AlbumRepository")
 */
class Album
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $name
     *
     * @ORM\Column(name="name", type="string", length=50)
     */
    private $name;

    /**
     * @var integer $user_id
     *
     * @ORM\Column(name="user_id", type="integer")
     */
    private $user_id;

    /**
     * @var date $creation_date
     *
     * @ORM\Column(name="creation_date", type="date")
     */
    private $creation_date;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set user_id
     *
     * @param integer $userId
     */
    public function setUserId($userId)
    {
        $this->user_id = $userId;
    }

    /**
     * Get user_id
     *
     * @return integer
     */
    public function getUserId()
    {
        return $this->user_id;
    }

    /**
     * Set creation_date
     *
     * @param date $creationDate
     */
    public function setCreationDate($creationDate)
    {
        $this->creation_date = $creationDate;
    }

    /**
     * Get creation_date
     *
     * @return date
     */
    public function getCreationDate()
    {
        return $this->creation_date;
    }
}


text:
namespace cc {

SynchronousTaskGraphRunner::SynchronousTaskGraphRunner() {}

SynchronousTaskGraphRunner::~SynchronousTaskGraphRunner() {
  DCHECK(!work_queue_.HasReadyToRunTasks());
}

NamespaceToken SynchronousTaskGraphRunner::GetNamespaceToken() {
  return work_queue_.GetNamespaceToken();
}

void SynchronousTaskGraphRunner::ScheduleTasks(NamespaceToken token,
                                               TaskGraph* graph) {
  TRACE_EVENT2("cc", "SynchronousTaskGraphRunner::ScheduleTasks", "num_nodes",
               graph->nodes.size(), "num_edges", graph->edges.size());

  DCHECK(token.IsValid());
  DCHECK(!TaskGraphWorkQueue::DependencyMismatch(graph));

  work_queue_.ScheduleTasks(token, graph);
}

void SynchronousTaskGraphRunner::WaitForTasksToFinishRunning(
    NamespaceToken token) {
  TRACE_EVENT0("cc", "SynchronousTaskGraphRunner::WaitForTasksToFinishRunning");

  DCHECK(token.IsValid());
  auto* task_namespace = work_queue_.GetNamespaceForToken(token);

  if (!task_namespace)
    return;

  while (
      !TaskGraphWorkQueue::HasFinishedRunningTasksInNamespace(task_namespace)) {
    RunTask();
  }
}

void SynchronousTaskGraphRunner::CollectCompletedTasks(
    NamespaceToken token,
    Task::Vector* completed_tasks) {
  TRACE_EVENT0("cc", "SynchronousTaskGraphRunner::CollectCompletedTasks");

  DCHECK(token.IsValid());
  work_queue_.CollectCompletedTasks(token, completed_tasks);
}

void SynchronousTaskGraphRunner::RunUntilIdle() {
  while (work_queue_.HasReadyToRunTasks())
    RunTask();
}

void SynchronousTaskGraphRunner::RunTask() {
  TRACE_EVENT0("toplevel", "SynchronousTaskGraphRunner::RunTask");

  auto prioritized_task = work_queue_.GetNextTaskToRun();

  Task* task = prioritized_task.task;
  task->WillRun();
  task->RunOnWorkerThread();
  task->DidRun();

  work_queue_.CompleteTask(prioritized_task);
}

}  // namespace cc