text:
package org.onosproject.cpman;

import com.google.common.base.MoreObjects;

/**
 * Primitive Metric Value.
 */
public final class MetricValue {

    private final long rate;
    private final long load;
    private final long count;

    /**
     * Constructs a metric value using the given rate, load and count.
     *
     * @param rate rate
     * @param load load
     * @param count count
     */
    private MetricValue(long rate, long load, long count) {
        this.rate = rate;
        this.load = load;
        this.count = count;
    }

    /**
     * Returns rate value.
     *
     * @return rate
     */
    public long getRate() {
        return rate;
    }

    /**
     * Returns load value.
     *
     * @return load
     */
    public long getLoad() {
        return load;
    }

    /**
     * Returns count value.
     *
     * @return cound
     */
    public long getCount() {
        return count;
    }

    /**
     * MetricValue builder class.
     */
    public static final class Builder {
        private long rate;
        private long load;
        private long count;

        /**
         * Sets rate value.
         *
         * @param rate rate value
         * @return Builder object
         */
        public Builder rate(long rate) {
            this.rate = rate;
            return this;
        }

        /**
         * Sets load value.
         *
         * @param load load value
         * @return Builder object
         */
        public Builder load(long load) {
            this.load = load;
            return this;
        }

        /**
         * Sets count value.
         *
         * @param count count value
         * @return Builder object
         */
        public Builder count(long count) {
            this.count = count;
            return this;
        }

        /**
         * Builds a MetricValue object.
         *
         * @return MetricValue object
         */
        public MetricValue add() {
            return new MetricValue(rate, load, count);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof MetricValue) {
            MetricValue other = (MetricValue) obj;
            if (this.rate == other.rate &&
                    this.load == other.load &&
                    this.count == other.count) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        final int prime = 1004;
        int result = super.hashCode();
        result = prime * result + (int) this.rate;
        result = prime * result + (int) this.load;
        result = prime * result + (int) this.count;
        return result;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(getClass())
                .add("rate", Long.toHexString(rate))
                .add("load", Long.toHexString(load))
                .add("count", Long.toHexString(count)).toString();
    }
}


text:
#include <QtNetwork>

#include "httpsupload.h"
#include <log/clog.h>

HttpsUpload::HttpsUpload(QObject *parent): QObject(parent),
    _authRequestCnt(0),
    _lastError(QSslError::NoError),
    _openConnections(0),
    _maxOpenConnections(1)
{
    connect(&_nwAccMngr, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
            this, SLOT(processAuthenticationRequired(QNetworkReply*,QAuthenticator*)));
    connect(&_nwAccMngr, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
            this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
}

void HttpsUpload::startRequests(QUrl url, QStringList fileNames, QMap<QString, QString> params)
{
    foreach( QString fileName, fileNames)
        startRequest(url, fileName , params);
}

void HttpsUpload::startRequest(QUrl url, QString fileName, QMap<QString, QString> params)
{
    _pendingRequests.append( RequestData( fileName, url, params ) );
    _progressInfo[ fileName ] = 0;
    if ( _openConnections < _maxOpenConnections )
    {
        processNextRequest( );
    }
}

void HttpsUpload::processNextRequest( )
{
	/*
    if ( _openConnections < _maxOpenConnections )
        ++_openConnections;

    if ( _pendingRequests.isEmpty() )
    {
        emit completed();
        return;
    }
    RequestData rd = _pendingRequests.takeFirst();
    if ( _lastUrl != rd._url )
    {
        _authRequestCnt=0;
        _lastError=0;
        _lastUrl = rd._url;
    }

    QFile file( rd._file, this );
    if ( file.open(QIODevice::ReadOnly) )
    {
        QNetworkRequest request(rd._url);
        request.setRawHeader("Host", rd._url.encodedHost());
//        request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.2.22) Gecko/20110902 Firefox/3.6.22 ( .NET CLR 3.5.30729; .NET4.0C)");
//        request.setRawHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
//        request.setRawHeader("Accept-Encoding", "gzip,deflate");
//        request.setRawHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
//        request.setRawHeader("Keep-Alive", "115");
//        request.setRawHeader("Connection", "keep-alive");
         request.setRawHeader("Content-Type", "image\png" );
	  QByteArray data = file.readAll();
	  request.setRawHeader("Content-Length", QString::number( data.length() ) );
    	  request.setRawHeader("Expect", "100-continue" );

        QNetworkReply * reply = _nwAccMngr.put( request, data);
        reply->setProperty( "_uploadFile", rd._file );
        connect(reply, SIGNAL(finished()),
                this, SLOT(uploadFinished()));
        connect(reply, SIGNAL(uploadProgress(qint64,qint64)),
                this, SLOT(updateUploadProgress(qint64,qint64)));
        _replyList.append( reply );
    }*/
}

void HttpsUpload::uploadFinished()
{
    if ( _openConnections > 0 )
        --_openConnections;

    QNetworkReply * finishedReply = qobject_cast<QNetworkReply*>( sender() );
    QString file = finishedReply->property( "_uploadFile" ).toString();
    _progressInfo.remove( file );
    removeReply(finishedReply);
    if ( _lastError == 0 )
    {
        emit message( QString ("Finished: %1").arg(file) );
        if (_progressInfo.isEmpty())
        {
            emit message( "Completed" );
            emit completed();
        }
    }
    updateProgress();
    processNextRequest( );
}

void HttpsUpload::updateUploadProgress(qint64 bytesRead, qint64 totalBytes)
{
    QNetworkReply * reply = qobject_cast<QNetworkReply*>( sender() );
    QString file = reply->property( "_uploadFile" ).toString();
    if ( bytesRead != 0  )
        _progressInfo[ file ] = (bytesRead / totalBytes) *100;

    updateProgress();
}

/*! Finds reply object in list and removes it

*/
void HttpsUpload::removeReply( QNetworkReply* removeReply )
{
    int idx=-1;
    int i=0;

    foreach ( QNetworkReply *reply, _replyList ){
        if ( reply ==  removeReply ){
            idx = i;
            break;
        } else ++i;
    }

    if ( idx >= 0 )
    {
        QNetworkReply * reply = _replyList.takeAt(idx);
        reply->deleteLater();
    }
    else
    {
        C_ERROR( "Internal error. Inconsistent data-structures" )
        return;
    }
}

void HttpsUpload::updateProgress( )
{
    int row=0;
    _progressModel.clear();
    for ( QMap<QString, int>::Iterator it =_progressInfo.begin(); it !=_progressInfo.end(); ++it )
    {
        _progressModel.setItem(row, 0, new QStandardItem(it.key()) );
        _progressModel.setItem(row, 1, new QStandardItem( QString("%1%").arg( it.value() ) ) );
        ++row;
    }
}

void HttpsUpload::processAuthenticationRequired(QNetworkReply* reply,QAuthenticator *authenticator)
{
  (void) reply; // avoid unused parameter warning
    _authRequestCnt++;
    if ( _authRequestCnt > 3)
    {
        return;
    }
    else if ( _authRequestCnt > 2)
    {
        emit uploadError( "Authentification error" );
        return;
    }
    authenticator->setUser(_userName);
    authenticator->setPassword(_password);
}

void HttpsUpload::sslErrors(QNetworkReply*reply,const QList<QSslError> &errors)
{
    QString errorString;
    foreach (const QSslError &error, errors) {
        _lastError |= QSslError::NoError; //required in finished for skipping invalid replies
        if ( error.error() != QSslError::NoError )
        {
            if (!errorString.isEmpty())
                errorString += "\n";
            errorString += error.errorString();
        }
    }

    if ( !errorString.isEmpty() )
    {
        emit uploadError( errorString );
    }
    reply->ignoreSslErrors();
}

redpajama_set_name: RedPajamaGithub


text:
package javaeetutorial.taskcreator;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Logger;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/* The tasks just notify the JAX-RS web service in the EJB */
public class Task implements Runnable {

    private static final Logger log = Logger.getLogger("Task");
    private static final String WS_URL =
            "http://localhost:8080/taskcreator/jaxrs/taskinfo";

    private final String name;
    private final String type;
    private final DateFormat dateFormat;
    private final Client client;
    private int counter;

    public Task(String n, String t) {
        name = n;
        type = t;
        counter = 1;
        dateFormat = new SimpleDateFormat("HH:mm:ss");
        client = ClientBuilder.newClient();
        /* For delayed tasks, send
        /* Send: 14:15:45 - DELAYED Task ABCDE submitted */
        if (type.compareTo("DELAYED") == 0)
            sendToWebService("submitted");
    }

    @Override
    public void run() {
        /* Send: 14:15:45 - TASKTYPE Task ABCDE started */
        if (type.compareTo("PERIODIC") == 0)
            sendToWebService("started run #" + counter);
        else
            sendToWebService("started");

        try {
            Thread.sleep(1500);
        } catch (Exception e) { }

        /* Send: 14:15:47 - TASKTYPE Task ABCDE finished */
        if (type.compareTo("PERIODIC") == 0)
            sendToWebService("finished run #" + (counter++));
        else
            sendToWebService("finished");
    }

    /* Send: 14:15:47 - TASKTYPE Task ABCDE [details] */
    private void sendToWebService(String details) {
        String time = dateFormat.format(Calendar.getInstance().getTime());
        String msg = time + " - "  + type + " Task " + name + " " + details;
        Response resp = client.target(WS_URL)
                              .request(MediaType.TEXT_PLAIN)
                              .post(Entity.html(msg));
    }

    public String getName() {
        return name;
    }

}


text:
/*
 * This source code is public domain.
 *
 * Authors: Rani Assaf <rani@magic.metawire.com>,
 *          Olivier Lapicque <olivierl@jps.net>,
 *          Adam Goode       <adam@evdebs.org> (endian and char fixes for PPC)
*/

#ifndef _STDAFX_H_
#define _STDAFX_H_

#ifdef MSC_VER

#pragma warning (disable:4201)
#pragma warning (disable:4514)
#include <windows.h>
#include <windowsx.h>
#include <mmsystem.h>
#include <stdio.h>

inline void ProcessPlugins(int n) {}

#else

#if defined(HAVE_CONFIG_H) && !defined(CONFIG_H_INCLUDED)
# include "config.h"
# define CONFIG_H_INCLUDED 1
#endif
#ifdef HAVE_INTTYPES_H
# include <inttypes.h>
#endif
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef int8_t CHAR;
typedef uint8_t UCHAR;
typedef uint8_t* PUCHAR;
typedef uint16_t USHORT;
typedef uint32_t ULONG;
typedef uint32_t UINT;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef int64_t LONGLONG;
typedef int32_t* LPLONG;
typedef uint32_t* LPDWORD;
typedef uint16_t WORD;
typedef uint8_t BYTE;
typedef uint8_t* LPBYTE;
typedef bool BOOL;
typedef char* LPSTR;
typedef void* LPVOID;
typedef uint16_t* LPWORD;
typedef const char* LPCSTR;
typedef void* PVOID;
typedef void VOID;

inline LONG MulDiv (long a, long b, long c)
{
  // if (!c) return 0;
  return ((uint64_t) a * (uint64_t) b ) / c;
}

#define MODPLUG_NO_FILESAVE
#define NO_AGC
#define LPCTSTR LPCSTR
#define lstrcpyn strncpy
#define lstrcpy strcpy
#define lstrcmp strcmp
#define WAVE_FORMAT_PCM 1
//#define ENABLE_EQ

#define  GHND   0

inline int8_t * GlobalAllocPtr(unsigned int, size_t size)
{
  int8_t * p = (int8_t *) malloc(size);

  if (p != NULL) memset(p, 0, size);
  return p;
}

inline void ProcessPlugins(int n) {}

#define GlobalFreePtr(p) free((void *)(p))

#define strnicmp(a,b,c)		strncasecmp(a,b,c)
#define wsprintf			sprintf

#ifndef FALSE
#define FALSE	false
#endif

#ifndef TRUE
#define TRUE	true
#endif

#endif // MSC_VER

#endif


text:
CKEDITOR.plugins.setLang( 'flash', 'bs', {
	access: 'Script Access', // MISSING
	accessAlways: 'Always', // MISSING
	accessNever: 'Never', // MISSING
	accessSameDomain: 'Same domain', // MISSING
	alignAbsBottom: 'Abs dole',
	alignAbsMiddle: 'Abs sredina',
	alignBaseline: 'Bazno',
	alignTextTop: 'Vrh teksta',
	bgcolor: 'Boja pozadine',
	chkFull: 'Allow Fullscreen', // MISSING
	chkLoop: 'Loop', // MISSING
	chkMenu: 'Enable Flash Menu', // MISSING
	chkPlay: 'Auto Play', // MISSING
	flashvars: 'Variables for Flash', // MISSING
	hSpace: 'HSpace',
	properties: 'Flash Properties', // MISSING
	propertiesTab: 'Properties', // MISSING
	quality: 'Quality', // MISSING
	qualityAutoHigh: 'Auto High', // MISSING
	qualityAutoLow: 'Auto Low', // MISSING
	qualityBest: 'Best', // MISSING
	qualityHigh: 'High', // MISSING
	qualityLow: 'Low', // MISSING
	qualityMedium: 'Medium', // MISSING
	scale: 'Scale', // MISSING
	scaleAll: 'Show all', // MISSING
	scaleFit: 'Exact Fit', // MISSING
	scaleNoBorder: 'No Border', // MISSING
	title: 'Flash Properties', // MISSING
	vSpace: 'VSpace',
	validateHSpace: 'HSpace must be a number.', // MISSING
	validateSrc: 'Molimo ukucajte URL link',
	validateVSpace: 'VSpace must be a number.', // MISSING
	windowMode: 'Window mode', // MISSING
	windowModeOpaque: 'Opaque', // MISSING
	windowModeTransparent: 'Transparent', // MISSING
	windowModeWindow: 'Window' // MISSING
} );


text:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cadre - L'entreprise </title>
<meta charset="UTF-8"/>

<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/bootstrapSite.css">
<link rel="stylesheet" href="css/bootstrap-responsiveSite.css">
<link rel="stylesheet" href="css/flexslider.css" />
<link rel="stylesheet" href="css/custom-styleS.css">

<link rel="shortcut icon" href="img/favicon.png.ico">

Historique

Cadre et EDF

Nos equipes

Penly

Paluel

Ils nous font confiance

Nos Engagements

Nos engagements premiers envers tous nos clients sont la qualite et la disponibilite. Chacun des produits et des services fourni aux clients repond aux exigences de ce dernier et aux normes, codes et reglements applicables.

Nos
 valeurs

Back to Top


text:
/// <reference path="../typings/tsd.d.ts"/>

import * as Router from 'koa-router';

import commonParser from '../utils/common-parser';
import nateParser from '../utils/nate-parser';
import naverParam from '../models/params/naver-param';
import daumParam from '../models/params/daum-param';
import { paramZum } from '../models/params/zum-param';

import async = Q.async;
const parser = commonParser.Instance;

const router = new Router({ prefix: '/v1/rank' });

/* GET home page. */

router.get('/naver', async (ctx, next) => {
  parser.param = naverParam;
  ctx.body = await parser.getRank();
});

router.get('/daum', async (ctx, next) => {
  parser.param = daumParam;
  ctx.body = await parser.getRank();
});

router.get('/nate', async (ctx, next) => {
  ctx.body = await nateParser.getNateRank();
});

router.get('/zum', async (ctx, next) => {
  parser.param = paramZum;
  ctx.body = await parser.getRank();
});

router.get('/all', async (ctx, next) => {

  const response = {};
  parser.param = naverParam;
  response['naver'] = (await parser.getRank()).data;
  parser.param = daumParam;
  response['daum'] = (await parser.getRank()).data;
  response['nate'] = (await nateParser.getNateRank()).data;
  parser.param = paramZum;
  response['zum'] = (await parser.getRank()).data;

  ctx.body = response;
});

export default router;


text:
<?php

namespace Secourut\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SecourutAdminBundle extends Bundle
{
}


text:
module Elasticsearch
  module API
    module Actions

      # Return information if and how well a document matches a query.
      #
      # The returned information contains a `_score` and its explanation, if the document matches the query.
      #
      # @example Passing the query in the Lucene query syntax as the `:q` URL parameter
      #
      #     client.explain index: 'myindex', type: 'mytype', id: '1', q: 'test'
      #
      # @example Passing the query in the Query DSL as the request `:body`
      #
      #     client.explain index: 'myindex', type: 'mytype', id: '1',
      #                    body: { query: { match: { title: 'test' } } }
      #
      # @option arguments [String] :id The document ID (*Required*)
      # @option arguments [String] :index The name of the index (*Required*)
      # @option arguments [String] :type The type of the document (*Required*)
      # @option arguments [Hash] :body The query definition using the Query DSL (*Required*)
      # @option arguments [Boolean] :analyze_wildcard Specify whether wildcards and prefix queries in the query string
      #                                               query should be analyzed (default: false)
      # @option arguments [String] :analyzer The analyzer for the query string query
      # @option arguments [String] :default_operator The default operator for query string query (AND or OR)
      #                                              (options: AND, OR)
      # @option arguments [String] :df The default field for query string query (default: _all)
      # @option arguments [List] :fields A comma-separated list of fields to return in the response
      # @option arguments [Boolean] :lenient Specify whether format-based query failures
      #                                      (such as providing text to a numeric field) should be ignored
      # @option arguments [Boolean] :lowercase_expanded_terms Specify whether query terms should be lowercased
      # @option arguments [String] :parent The ID of the parent document
      # @option arguments [String] :preference Specify the node or shard the operation should be performed on
      #                                        (default: random)
      # @option arguments [String] :q Query in the Lucene query string syntax
      # @option arguments [String] :routing Specific routing value
      # @option arguments [String] :source The URL-encoded query definition (instead of using the request body)
      # @option arguments [String] :_source Specify whether the _source field should be returned,
      #                                     or a list of fields to return
      # @option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field
      # @option arguments [String] :_source_include A list of fields to extract and return from the _source field
      #
      # @see http://elasticsearch.org/guide/reference/api/explain/
      #
      def explain(arguments={})
        raise ArgumentError, "Required argument 'index' missing" unless arguments[:index]
        raise ArgumentError, "Required argument 'type' missing"  unless arguments[:type]
        raise ArgumentError, "Required argument 'id' missing"    unless arguments[:id]

        valid_params = [
          :analyze_wildcard,
          :analyzer,
          :default_operator,
          :df,
          :fields,
          :lenient,
          :lowercase_expanded_terms,
          :parent,
          :preference,
          :q,
          :routing,
          :source,
          :_source,
          :_source_include,
          :_source_exclude ]

        method = 'GET'
        path   = Utils.__pathify Utils.__escape(arguments[:index]),
                                 Utils.__escape(arguments[:type]),
                                 Utils.__escape(arguments[:id]),
                                 '_explain'

        params = Utils.__validate_and_extract_params arguments, valid_params
        body   = arguments[:body]

        params[:fields] = Utils.__listify(params[:fields]) if params[:fields]

        perform_request(method, path, params, body).body
      end
    end
  end
end


text:
@interface OZLModelIssueStatus () <OZLEnumerationFormFieldValue>

@end

@implementation OZLModelIssueStatus

+ (NSString *)primaryKey {
    return @"statusId";
}

- (id)initWithAttributeDictionary:(NSDictionary *)attributes {

    if (self = [super init]) {
        [self applyAttributeDictionary:attributes];
    }

    return self;
}

- (void)applyAttributeDictionary:(NSDictionary *)attributes {
    self.statusId = [[attributes objectForKey:@"id"] integerValue];
    self.name = [attributes objectForKey:@"name"];
}

- (NSString *)stringValue {
    return self.name;
}

@end


text:
module BrNfe
	module Product
		module Nfe
			module ItemTax
				class Cofins < BrNfe::ActiveModelBase
					# CÓDIGO DA SITUAÇÃO TRIBUTÁRIA do COFINS
					#  01 = Operação Tributável (base de cálculo = valor da operação alíquota normal (cumulativo/não cumulativo));
					#  02 = Operação Tributável (base de cálculo = valor da operação (alíquota diferenciada));
					#  03 = Operação Tributável (base de cálculo = quantidade vendida x alíquota por unidade de produto);
					#  04 = Operação Tributável (tributação monofásica, alíquota zero);
					#  05 = Operação Tributável (Substituição Tributária);
					#  06 = Operação Tributável (alíquota zero);
					#  07 = Operação Isenta da Contribuição;
					#  08 = Operação Sem Incidência da Contribuição;
					#  09 = Operação com Suspensão da Contribuição;
					#  49 = Outras Operações de Saída;
					#  50 = Operação com Direito a Crédito - Vinculada Exclusivamente a Receita Tributada no Mercado Interno;
					#  51 = Operação com Direito a Crédito - Vinculada Exclusivamente a Receita Não Tributada no Mercado Interno;
					#  52 = Operação com Direito a Crédito – Vinculada Exclusivamente a Receita de Exportação;
					#  53 = Operação com Direito a Crédito - Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno;
					#  54 = Operação com Direito a Crédito - Vinculada a Receitas Tributadas no Mercado Interno e de Exportação;
					#  55 = Operação com Direito a Crédito - Vinculada a Receitas Não- Tributadas no Mercado Interno e de Exportação;
					#  56 = Operação com Direito a Crédito - Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno, e de Exportação;
					#  60 = Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita Tributada no Mercado Interno;
					#  61 = Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita Não-Tributada no Mercado Interno;
					#  62 = Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita de Exportação;
					#  63 = Crédito Presumido - Operação de Aquisição Vinculada Receitas Tributadas e Não-Tributadas no Mercado Interno;
					#  64 = Crédito Presumido - Operação de Aquisição Vinculada a Receitas Tributadas no Mercado Interno e de Exportação;
					#  65 = Crédito Presumido - Operação de Aquisição Vinculada a Receitas Não-Tributadas no Mercado Interno e de Exportação;
					#  66 = Crédito Presumido - Operação de Aquisição Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno, e de Exportação;
					#  67 = Crédito Presumido - Outras Operações;
					#  70 = Operação de Aquisição sem Direito a Crédito;
					#  71 = Operação de Aquisição com Isenção;
					#  72 = Operação de Aquisição com Suspensão;
					#  73 = Operação de Aquisição a Alíquota Zero;
					#  74 = Operação de Aquisição; sem Incidência da Contribuição;
					#  75 = Operação de Aquisição por Substituição Tributária;
					#  98 = Outras Operações de Entrada;
					#  99 = Outras Operações;
					#
					# <b>Type:     </b> _Number_ <- string
					# <b>Required: </b> _Yes_
					# <b>Example:  </b> _00_
					# <b>Length:   </b> _2_
					# <b>tag:      </b> CST
					#
					attr_accessor :codigo_cst
					def codigo_cst
						"#{@codigo_cst}".rjust(2, '0') if @codigo_cst.present?
					end
					alias_attribute :CST, :codigo_cst

					# VALOR DA BASE DE CÁLCULO DO COFINS
					#
					# <b>Type:     </b> _Float_
					# <b>Required: </b> _No_ (Yes if cst in [01 02])
					# <b>Example:  </b> _350.47_
					# <b>tag:      </b> vBC
					#
					attr_accessor :total_base_calculo
					alias_attribute :vBC, :total_base_calculo

					# ALÍQUOTA DO COFINS (EM PERCENTUAL)
					#
					# <b>Type:     </b> _Float_
					# <b>Required: </b> _No_ (Yes if cst in [01 02])
					# <b>Example:  </b> _350.47_
					# <b>tag:      </b> pCOFINS
					#
					attr_accessor :aliquota
					alias_attribute :pCOFINS, :aliquota

					# VALOR DO COFINS
					#
					# <b>Type:     </b> _Float_
					# <b>Required: </b> _Yes_ (No if cst in [04 05 06 07 08 09])
					# <b>Example:  </b> _350.47_
					# <b>tag:      </b> vCOFINS
					#
					attr_accessor :total
					alias_attribute :vCOFINS, :total

					# QUANTIDADE VENDIDA
					#
					# <b>Type:     </b> _Float_
					# <b>Required: </b> _No_ (Yes if cst is 03)
					# <b>Example:  </b> _10.0_
					# <b>Length:   </b> _12v0-4_
					# <b>tag:      </b> qBCProd
					#
					attr_accessor :quantidade_vendida
					alias_attribute :qBCProd, :quantidade_vendida

					# ALÍQUOTA DO COFINS (EM REAIS)
					#
					# <b>Type:     </b> _Float_
					# <b>Required: </b> _No_ (Yes if cst is 03)
					# <b>Example:  </b> _10.0_
					# <b>Length:   </b> _11v0-4_
					# <b>tag:      </b> vAliqProd
					#
					attr_accessor :total_aliquota
					alias_attribute :vAliqProd, :total_aliquota

					def default_values
						{
							codigo_cst: '07'
						}
					end

					validates :codigo_cst, presence: true
					validates :codigo_cst, inclusion: {in: %w[01 02 03 04 05 06 07 08 09 49 50 51 52 53 54 55 56 60 61 62 63 64 65 66 67 70 71 72 73 74 75 98 99]}

					with_options if: lambda{ |r| r.codigo_cst.in?(%w[01 02]) } do |record|
						record.validates :total_base_calculo, presence: true
						record.validates :total_base_calculo, numericality: {greater_than_or_equal_to: 0.0}, allow_blank: true
						record.validates :aliquota,           presence: true
						record.validates :aliquota,           numericality: {greater_than_or_equal_to: 0.0}, allow_blank: true
						record.validates :total,              presence: true
						record.validates :total,              numericality: {greater_than_or_equal_to: 0.0}, allow_blank: true
					end
					with_options if: lambda{ |r| r.codigo_cst == '03' } do |record|
						record.validates :quantidade_vendida, presence: true
						record.validates :quantidade_vendida, numericality: {greater_than_or_equal_to: 0.0}, allow_blank: true
						record.validates :total_aliquota,     presence: true
						record.validates :total_aliquota,     numericality: {greater_than_or_equal_to: 0.0}, allow_blank: true
						record.validates :total,              presence: true
						record.validates :total,              numericality: {greater_than_or_equal_to: 0.0}, allow_blank: true
					end
					with_options if: lambda{ |r| r.codigo_cst.in?(%w[49 50 51 52 53 54 55 56 60 61 62 63 64 65 66 67 70 71 72 73 74 75 98 99]) } do |record|
						record.validates :total,              presence: true
						record.validates :total,              numericality: {greater_than_or_equal_to: 0.0}, allow_blank: true
					end
				end
			end
		end
	end
end


text:
#include "postgres.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <glob.h>

#include "lib/stringinfo.h"

#include "access/heapam.h"
#include "access/appendonlywriter.h"
#include "access/aocssegfiles.h"
#include "catalog/catalog.h"
#include "catalog/catquery.h"
#include "catalog/namespace.h"
#include "catalog/pg_tablespace.h"
#include "commands/dbcommands.h"
#include "commands/tablespace.h"
#include "executor/spi.h"
#include "miscadmin.h"
#include "storage/fd.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/int8.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/relcache.h"
#include "utils/syscache.h"

#include "cdb/cdbvars.h"
#include "cdb/cdbpersistenttablespace.h"

static int64
get_size_from_segDBs(const char * cmd)
{
	int			spiresult;
	bool		succeeded = false;
	int64		result = 0;
	volatile bool connected = false;

	Assert(Gp_role == GP_ROLE_DISPATCH);

	PG_TRY();
	{
		HeapTuple	tup;
		TupleDesc	tupdesc;
		bool		isnull;
		Datum		size;

		do
		{
			/* Establish an SPI session as a client of myself. */
			if (SPI_connect() != SPI_OK_CONNECT)
				break;

			connected = true;

			/* Do the query. */
			spiresult = SPI_execute(cmd, false, 0);

			/* Did the query succeed? */
			if (spiresult != SPI_OK_SELECT)
				break;

			if (SPI_processed < 1)
				break;

			tup = SPI_tuptable->vals[0];
			tupdesc = SPI_tuptable->tupdesc;

			size = heap_getattr(SPI_tuptable->vals[0], 1, SPI_tuptable->tupdesc, &isnull);
			if (isnull)
				break;

			result = DatumGetInt64(size);

			succeeded = true;
		}
		while (0);

		/* End recursive session. */
		connected = false;
		SPI_finish();

		if (!succeeded)
			elog(ERROR, "Unable to get sizes from segments");
	}
	/* Clean up in case of error. */
	PG_CATCH();
	{
		/* End recursive session. */
		if (connected)
			SPI_finish();

		/* Carry on with error handling. */
		PG_RE_THROW();
	}
	PG_END_TRY();

	return result;
}

/* Return physical size of directory contents, or 0 if dir doesn't exist */
int64
db_dir_size(const char *path)
{
	int64		dirsize = 0;
	struct dirent *direntry;
	DIR		   *dirdesc;
	char		filename[MAXPGPATH];

	dirdesc = AllocateDir(path);

	if (!dirdesc)
		return 0;

	while ((direntry = ReadDir(dirdesc, path)) != NULL)
	{
		struct stat fst;

		if (strcmp(direntry->d_name, ".") == 0 ||
			strcmp(direntry->d_name, "..") == 0)
			continue;

		snprintf(filename, MAXPGPATH, "%s/%s", path, direntry->d_name);

		if (stat(filename, &fst) < 0)
		{
			if (errno == ENOENT)
				continue;
			else
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not stat file \"%s\": %m", filename)));
		}
		dirsize += fst.st_size;
	}

	FreeDir(dirdesc);
	return dirsize;
}

/*
 * calculate size of database in all tablespaces
 */
static int64
calculate_database_size(Oid dbOid)
{
	int64		 totalsize = 0;
	char		 pathname[MAXPGPATH];
	Relation     rel;
	HeapScanDesc scandesc;
	HeapTuple    tuple;
	AclResult	 aclresult;

	/* User must have connect privilege for target database */
	aclresult = pg_database_aclcheck(dbOid, GetUserId(), ACL_CONNECT);
	if (aclresult != ACLCHECK_OK)
		aclcheck_error(aclresult, ACL_KIND_DATABASE,
					   get_database_name(dbOid));

	/* Scan through all tablespaces */
	rel = heap_open(TableSpaceRelationId, AccessShareLock);
	scandesc = heap_beginscan(rel, SnapshotNow, 0, NULL);
	tuple = heap_getnext(scandesc, ForwardScanDirection);
	while (HeapTupleIsValid(tuple))
	{
		char *priFilespace, *mirFilespace;
		Oid   tsOid;

		tsOid = HeapTupleGetOid(tuple);

		/* Don't include shared relations */
		if (tsOid != GLOBALTABLESPACE_OID)
		{
			/* Find the filespace path for this tablespace */
			PersistentTablespace_GetPrimaryAndMirrorFilespaces(
				tsOid, &priFilespace, &mirFilespace);

			/* Build the path for this database in this tablespace */
			FormDatabasePath(pathname, priFilespace, tsOid, dbOid);

			totalsize += db_dir_size(pathname);
		}

		tuple = heap_getnext(scandesc, ForwardScanDirection);
	}
	heap_endscan(scandesc);
	heap_close(rel, AccessShareLock);

	/* Complain if we found no trace of the DB at all */
	if (totalsize == 0)
		ereport(ERROR,
				(ERRCODE_UNDEFINED_DATABASE,
				 errmsg("database with OID %u does not exist", dbOid)));

	return totalsize;
}

Datum
pg_database_size_oid(PG_FUNCTION_ARGS)
{
	int64		size = 0;
	Oid			dbOid = PG_GETARG_OID(0);
	size = calculate_database_size(dbOid);

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		StringInfoData buffer;

		initStringInfo(&buffer);

		appendStringInfo(&buffer, "select sum(pg_database_size(%u))::int8 from gp_dist_random('gp_id');", dbOid);

		size += get_size_from_segDBs(buffer.data);
	}

	PG_RETURN_INT64(size);
}

Datum
pg_database_size_name(PG_FUNCTION_ARGS)
{
	int64		size = 0;
	Name		dbName = PG_GETARG_NAME(0);
	Oid			dbOid = get_database_oid(NameStr(*dbName));

	if (!OidIsValid(dbOid))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_DATABASE),
				 errmsg("database \"%s\" does not exist",
						NameStr(*dbName))));

	size = calculate_database_size(dbOid);

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		StringInfoData buffer;

		initStringInfo(&buffer);

		appendStringInfo(&buffer, "select sum(pg_database_size('%s'))::int8 from gp_dist_random('gp_id');", NameStr(*dbName));

		size += get_size_from_segDBs(buffer.data);
	}

	PG_RETURN_INT64(size);
}

/*
 * calculate total size of tablespace
 */
static int64
calculate_tablespace_size(Oid tblspcOid)
{
	char		tblspcPath[MAXPGPATH];
	char		pathname[MAXPGPATH];
	int64		totalsize = 0;
	DIR		   *dirdesc;
	struct dirent *direntry;
	AclResult	aclresult;

	/*
	 * User must have CREATE privilege for target tablespace, either
	 * explicitly granted or implicitly because it is default for current
	 * database.
	 */
	if (tblspcOid != MyDatabaseTableSpace)
	{
		aclresult = pg_tablespace_aclcheck(tblspcOid, GetUserId(), ACL_CREATE);
		if (aclresult != ACLCHECK_OK)
			aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
						   get_tablespace_name(tblspcOid));
	}

	if (tblspcOid == DEFAULTTABLESPACE_OID)
		snprintf(tblspcPath, MAXPGPATH, "base");
	else if (tblspcOid == GLOBALTABLESPACE_OID)
		snprintf(tblspcPath, MAXPGPATH, "global");
	else
		snprintf(tblspcPath, MAXPGPATH, "pg_tblspc/%u", tblspcOid);

	dirdesc = AllocateDir(tblspcPath);

	if (!dirdesc)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not open tablespace directory \"%s\": %m",
						tblspcPath)));

	while ((direntry = ReadDir(dirdesc, tblspcPath)) != NULL)
	{
		struct stat fst;

		if (strcmp(direntry->d_name, ".") == 0 ||
			strcmp(direntry->d_name, "..") == 0)
			continue;

		snprintf(pathname, MAXPGPATH, "%s/%s", tblspcPath, direntry->d_name);

		if (stat(pathname, &fst) < 0)
		{
			if (errno == ENOENT)
				continue;
			else
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not stat file \"%s\": %m", pathname)));
		}

		if (S_ISDIR(fst.st_mode))
			totalsize += db_dir_size(pathname);

		totalsize += fst.st_size;
	}

	FreeDir(dirdesc);

	return totalsize;
}

Datum
pg_tablespace_size_oid(PG_FUNCTION_ARGS)
{
	int64		size = 0;
	Oid			tblspcOid = PG_GETARG_OID(0);

	size = calculate_tablespace_size(tblspcOid);

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		StringInfoData buffer;

		initStringInfo(&buffer);

		appendStringInfo(&buffer, "select sum(pg_tablespace_size(%u))::int8 from gp_dist_random('gp_id');", tblspcOid);

		size += get_size_from_segDBs(buffer.data);
	}

	PG_RETURN_INT64(size);
}

Datum
pg_tablespace_size_name(PG_FUNCTION_ARGS)
{
	int64		size = 0;
	Name		tblspcName = PG_GETARG_NAME(0);
	Oid			tblspcOid = get_tablespace_oid(NameStr(*tblspcName));

	if (!OidIsValid(tblspcOid))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("tablespace \"%s\" does not exist",
						NameStr(*tblspcName))));

	size = calculate_tablespace_size(tblspcOid);

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		StringInfoData buffer;

		initStringInfo(&buffer);

		appendStringInfo(&buffer, "select sum(pg_tablespace_size('%s'))::int8 from gp_dist_random('gp_id');", NameStr(*tblspcName));

		size += get_size_from_segDBs(buffer.data);
	}

	PG_RETURN_INT64(size);
}

/*
 * calculate size of a relation
 *
 * Iterator over all files belong to the relation and do stat.
 * The obviously better way is to use glob.  For whatever reason,
 * glob is extremely slow if there are lots of relations in the
 * database.  So we handle all cases, instead.
 */
static int64
calculate_relation_size(Relation rel)
{
	int64		totalsize = 0;
	char	   *relationpath;
	char		pathname[MAXPGPATH];

    struct stat fst;
    int i;

	relationpath = relpath(rel->rd_node);

    if(RelationIsHeap(rel))
    {
        /* Ordinary relation, including heap and index.
         * They take form of relationpath, or relationpath.%d
         * There will be no holes, therefore, we can stop we
         * we reach the first non-exist file.
         */
        for(i=0; ; ++i)
        {
            if (i==0)
                snprintf(pathname, MAXPGPATH, "%s", relationpath);
            else
                snprintf(pathname, MAXPGPATH, "%s.%d", relationpath, i);

            if (stat(pathname, &fst) >= 0)
                totalsize += fst.st_size;
            else
            {
                if (errno == ENOENT)
                    break;
                else
                    ereport(ERROR, (errcode_for_file_access(),
                                    errmsg("could not stat file %s: %m", pathname)
                                ));
            }
        }
    }
	else if (RelationIsAoRows(rel))
		totalsize = GetAOTotalBytes(rel, SnapshotNow);
	else if (RelationIsAoCols(rel))
		totalsize = GetAOCSTotalBytes(rel, SnapshotNow);

    /* RELSTORAGE_VIRTUAL has no space usage */
    return totalsize;
}

Datum
pg_relation_size_oid(PG_FUNCTION_ARGS)
{
	Oid			relOid = PG_GETARG_OID(0);
	Relation	rel;
	int64		size = 0;

	/**
	 * This function is peculiar in that it does its own dispatching.
	 * It does not work on entry db since we do not support dispatching
	 * from entry-db currently.
	 */
	if (Gp_role == GP_ROLE_EXECUTE && Gp_segment == -1)
	{
		elog(ERROR, "This query is not currently supported by GPDB.");
	}

	rel = try_relation_open(relOid, AccessShareLock, false);

	/*
	 * While we scan pg_class with an MVCC snapshot,
 	 * someone else might drop the table. It's better to return NULL for
	 * already-dropped tables than throw an error and abort the whole query.
	 */
	if (!RelationIsValid(rel))
  		PG_RETURN_NULL();

	if (relOid == 0 || rel->rd_node.relNode == 0)
		size = 0;
	else
		size = calculate_relation_size(rel);

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		StringInfoData buffer;
		char *schemaName;
		char *relName;

		schemaName = get_namespace_name(get_rel_namespace(relOid));
		if (schemaName == NULL)
		{
			elog(ERROR, "Cannot find schema for oid %d", relOid);
		}

		relName = get_rel_name(relOid);
		if (relName == NULL)
		{
			elog(ERROR, "Cannot find relation for oid %d", relOid);
		}

		initStringInfo(&buffer);

		appendStringInfo(&buffer, "select sum(pg_relation_size('%s.%s'))::int8 from gp_dist_random('gp_id');", quote_identifier(schemaName), quote_identifier(relName));

		size += get_size_from_segDBs(buffer.data);
	}

	relation_close(rel, AccessShareLock);

	PG_RETURN_INT64(size);
}

Datum
pg_relation_size_name(PG_FUNCTION_ARGS)
{
	text	   *relname = PG_GETARG_TEXT_P(0);
	RangeVar   *relrv;
	Relation	rel;
	int64		size;

	/**
	 * This function is peculiar in that it does its own dispatching.
	 * It does not work on entry db since we do not support dispatching
	 * from entry-db currently.
	 */
	if (Gp_role == GP_ROLE_EXECUTE && Gp_segment == -1)
	{
		elog(ERROR, "This query is not currently supported by GPDB.");
	}

	relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));

	if (Gp_role == GP_ROLE_EXECUTE && relrv->schemaname != NULL)
	{
		Oid namespaceId;
		Oid relOid;
		/*
		 * Do this the hard way, because the optimizer wants to be
		 * able to use this function on relations the user might not
		 * have direct access to.
		 */

		AcceptInvalidationMessages();

		namespaceId = caql_getoid(
				NULL,
				cql("SELECT oid FROM pg_namespace "
					" WHERE nspname = :1 ",
					CStringGetDatum(relrv->schemaname)));

		relOid = get_relname_relid(relrv->relname, namespaceId);

		if (!OidIsValid(relOid))
		{
			size = 0;
			PG_RETURN_INT64(size);
		}

		/* Let relation_open do the rest */
		rel = try_relation_open(relOid, AccessShareLock, false);
	}
	else
		rel = try_relation_openrv(relrv, AccessShareLock, false);

	/*
	 * While we scan pg_class with an MVCC snapshot,
	 * someone else might drop the table. It's better to return NULL for
	 * already-dropped tables than throw an error and abort the whole query.
	 */
	if (!RelationIsValid(rel))
  		PG_RETURN_NULL();

	if (rel->rd_node.relNode == 0)
		size = 0;
	else
		size = calculate_relation_size(rel);

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		char * rawname;
		StringInfoData buffer;

		initStringInfo(&buffer);

		rawname = DatumGetCString(DirectFunctionCall1(textout,
													  PointerGetDatum(relname)));

		initStringInfo(&buffer);

		appendStringInfo(&buffer, "select sum(pg_relation_size('%s'))::int8 from gp_dist_random('gp_id');", rawname);

		size += get_size_from_segDBs(buffer.data);
	}

	relation_close(rel, AccessShareLock);

	PG_RETURN_INT64(size);
}

/*
 *	Compute the on-disk size of files for the relation according to the
 *	stat function, including heap data, index data, toast data, aoseg data,
 *  aoblkdir data, and aovisimap data.
 */
static int64
calculate_total_relation_size(Oid Relid)
{
	Relation	heapRel;
	Oid			toastOid;
	AppendOnlyEntry *aoEntry = NULL;
	int64		size;
	ListCell   *cell;

	heapRel = try_relation_open(Relid, AccessShareLock, false);

	if (!RelationIsValid(heapRel))
		return 0;

	toastOid = heapRel->rd_rel->reltoastrelid;

	if (RelationIsAoRows(heapRel) || RelationIsAoCols(heapRel))
		aoEntry = GetAppendOnlyEntry(Relid, SnapshotNow);

	/* Get the heap size */
	if (Relid == 0 || heapRel->rd_node.relNode == 0)
		size = 0;
	else
		size = calculate_relation_size(heapRel);

	/* Include any dependent indexes */
	if (heapRel->rd_rel->relhasindex)
	{
		List	   *index_oids = RelationGetIndexList(heapRel);

		foreach(cell, index_oids)
		{
			Oid			idxOid = lfirst_oid(cell);
			Relation	iRel;

			iRel = try_relation_open(idxOid, AccessShareLock, false);

			if (RelationIsValid(iRel))
			{
				size += calculate_relation_size(iRel);

				relation_close(iRel, AccessShareLock);
			}
		}

		list_free(index_oids);
	}

	/* Recursively include toast table (and index) size */
	if (OidIsValid(toastOid))
		size += calculate_total_relation_size(toastOid);

	if (aoEntry != NULL)
	{
		Assert(OidIsValid(aoEntry->segrelid));
		size += calculate_total_relation_size(aoEntry->segrelid);

        /* block directory may not exist, post upgrade or new table that never has indexes */
   		if (OidIsValid(aoEntry->blkdirrelid))
        {
     		size += calculate_total_relation_size(aoEntry->blkdirrelid);
        }
		if (OidIsValid(aoEntry->visimaprelid))
		{
			size += calculate_total_relation_size(aoEntry->visimaprelid);
		}
	}

	if (aoEntry != NULL)
		pfree(aoEntry);

	relation_close(heapRel, AccessShareLock);

	return size;
}

Datum
pg_total_relation_size_oid(PG_FUNCTION_ARGS)
{
	int64		size = 0;
	Oid			relOid = PG_GETARG_OID(0);

	/*
	 * While we scan pg_class with an MVCC snapshot,
	 * someone else might drop the table. It's better to return NULL for
	 * already-dropped tables than throw an error and abort the whole query.
	 */
	if (!OidIsValid(get_rel_name(relOid)))
		PG_RETURN_NULL();

	size = calculate_total_relation_size(relOid);

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		StringInfoData buffer;
		char *schemaName;
		char *relName;

		schemaName = get_namespace_name(get_rel_namespace(relOid));
		if (schemaName == NULL)
		{
			elog(ERROR, "Cannot find schema for oid %d", relOid);
		}

		relName = get_rel_name(relOid);
		if (relName == NULL)
		{
			elog(ERROR, "Cannot find relation for oid %d", relOid);
		}

		initStringInfo(&buffer);

		appendStringInfo(&buffer, "select sum(pg_total_relation_size('%s.%s'))::int8 from gp_dist_random('gp_id');", quote_identifier(schemaName), quote_identifier(relName));

		size += get_size_from_segDBs(buffer.data);
	}

	PG_RETURN_INT64(size);
}

Datum
pg_total_relation_size_name(PG_FUNCTION_ARGS)
{
	int64		size = 0;
	text	   *relname = PG_GETARG_TEXT_P(0);
	RangeVar   *relrv;
	Oid			relid;

	relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));

	if (Gp_role == GP_ROLE_EXECUTE && relrv->schemaname != NULL)
	{
		Oid namespaceId;
		/*
		 * Do this the hard way to avoid access check we don't want
		 */
		AcceptInvalidationMessages();

		namespaceId = caql_getoid(
				NULL,
				cql("SELECT oid FROM pg_namespace "
					" WHERE nspname = :1 ",
					CStringGetDatum(relrv->schemaname)));

		relid = get_relname_relid(relrv->relname, namespaceId);
	}
	else
		relid = RangeVarGetRelid(relrv, true);

	if (!OidIsValid(relid))
		PG_RETURN_NULL();

	size = calculate_total_relation_size(relid);

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		char * rawname;
		StringInfoData buffer;

		initStringInfo(&buffer);

		rawname = DatumGetCString(DirectFunctionCall1(textout,
													  PointerGetDatum(relname)));

		appendStringInfo(&buffer, "select sum(pg_total_relation_size('%s'))::int8 from gp_dist_random('gp_id');", rawname);

		size += get_size_from_segDBs(buffer.data);
	}

	PG_RETURN_INT64(size);
}

/*
 * formatting with size units
 */
Datum
pg_size_pretty(PG_FUNCTION_ARGS)
{
	int64		size = PG_GETARG_INT64(0);
	char	   *result = palloc(50 + VARHDRSZ);
	int64		limit = 10 * 1024;
	int64		mult = 1;

	if (size < limit * mult)
		snprintf(VARDATA(result), 50, INT64_FORMAT " bytes", size);
	else
	{
		mult *= 1024;
		if (size < limit * mult)
			snprintf(VARDATA(result), 50, INT64_FORMAT " kB",
					 (size + mult / 2) / mult);
		else
		{
			mult *= 1024;
			if (size < limit * mult)
				snprintf(VARDATA(result), 50, INT64_FORMAT " MB",
						 (size + mult / 2) / mult);
			else
			{
				mult *= 1024;
				if (size < limit * mult)
					snprintf(VARDATA(result), 50, INT64_FORMAT " GB",
							 (size + mult / 2) / mult);
				else
				{
					mult *= 1024;
					snprintf(VARDATA(result), 50, INT64_FORMAT " TB",
							 (size + mult / 2) / mult);
				}
			}
		}
	}

	SET_VARSIZE(result, strlen(VARDATA(result)) + VARHDRSZ);

	PG_RETURN_TEXT_P(result);
}


text:
原文链接:https://dzone.com/articles/spring-webflux-first-steps

作者:[Biju Kunjummen](https://dzone.com/users/1229843/biju.kunjummen.html)

译者:[jackzhaiyh](https://github.com/jackzhaiyh)

Spring 5 新增WebFlux——在Spring应用中支持响应式编程实践。下面看一下如何将其引入旧版注解风格Controller中。

Spring WebFlux用于表示Spring web层中对[Reactive programming](https://www.reactivemanifesto.org/)的支持。它为服务端创建响应式web应用、也为客户端消费REST服务提供支持。

本文中,我会演示一个采用Spring WebFlux的示例web应用。Spring 5+中的WebFlux支持两种不同编程风格:传统注解风格和新的函数式风格。本文中,我将坚持传统的注解风格,并尝试在另一篇博客中详细描述类似的应用程序,但是以函数式风格定义endpoints。我的重点将是编程模型。

## 数据和服务层

如下是一个相当简单的REST接口,它支持一个酒店资源的CRUD操作:

```java
public class Hotel {
    private UUID id;
    private String name;
    private String address;
    private String state;
    private String zip;
    ....
}
```

示例中采用Cassandra存储这个entity,并且使用[Spring Data Cassandra](https://spring.io/blog/2016/11/28/going-reactive-with-spring-data)对响应式编程的支持使数据层获得响应式特性,从而可以支持这样的API。我采用两个repositories,一个便于上面酒店entity的存储,另一个维护可以通过酒店第一个字母进行检索的冗余数据。

```java
public interface HotelRepository  {
    Mono<Hotel> save(Hotel hotel);
    Mono<Hotel> update(Hotel hotel);
    Mono<Hotel> findOne(UUID hotelId);
    Mono<Boolean> delete(UUID hotelId);
    Flux<Hotel> findByState(String state);
}
public interface HotelByLetterRepository {
    Flux<HotelByLetter> findByFirstLetter(String letter);
    Mono<HotelByLetter> save(HotelByLetter hotelByLetter);
    Mono<Boolean> delete(HotelByLetterKey hotelByLetterKey);
}
```

返回一个entity实例的操作现在返回一个[Mono](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html)类型,返回多个entity实例的则返回一个[Flux](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html)类型。

鉴于此,我简单介绍一种返回响应类型的方法:当更新一个酒店实体时,我必须先删除HotelByLetter存储库维护的冗余数据,然后重新创建一个。这可以通过使用Flux和Mono类型提供的优秀运算符来完成,如下所示:

```java
public Mono<Hotel> update(Hotel hotel) {
    return this.hotelRepository.findOne(hotel.getId())
            .flatMap(existingHotel ->
                    this.hotelByLetterRepository.delete(new HotelByLetter(existingHotel).getHotelByLetterKey())
                            .then(this.hotelByLetterRepository.save(new HotelByLetter(hotel)))
                            .then(this.hotelRepository.update(hotel))).next();
}
```

## Web层

现在回到文章的焦点:支持Web层中基于注解的响应式编程模型支持!

多年来,[@Controller](https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/stereotype/Controller.html)和[@RestController](https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/bind/annotation/RestController.html)注解一直是Spring MVC的REST endpoint支持的重要组成部分。传统上,他们已经使用多时并返回java POJO。响应模型中的这些控制器已经被调整用来接收和返回Reactive类型——在我的例子中是Mono和Flux——但是另外也支持Rx-java和[Reactive Streams](http://www.reactive-streams.org/)类型。

鉴于此,我的Controller如下所示:

```java
@RestController
@RequestMapping("/hotels")
public class HotelController {
    ....
    @GetMapping(path = "/{id}")
    public Mono<Hotel> get(@PathVariable("id") UUID uuid) {
        return this.hotelService.findOne(uuid);
    }
    @PostMapping
    public Mono<ResponseEntity<Hotel>> save(@RequestBody Hotel hotel) {
        return this.hotelService.save(hotel)
                .map(savedHotel -> new ResponseEntity<>(savedHotel, HttpStatus.CREATED));
    }
    @PutMapping
    public Mono<ResponseEntity<Hotel>> update(@RequestBody Hotel hotel) {
        return this.hotelService.update(hotel)
                .map(savedHotel -> new ResponseEntity<>(savedHotel, HttpStatus.CREATED))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    @DeleteMapping(path = "/{id}")
    public Mono<ResponseEntity<String>> delete(
            @PathVariable("id") UUID uuid) {
        return this.hotelService.delete(uuid).map((Boolean status) ->
                new ResponseEntity<>("Deleted", HttpStatus.ACCEPTED));
    }
    @GetMapping(path = "/startingwith/{letter}")
    public Flux<HotelByLetter> findHotelsWithLetter(
            @PathVariable("letter") String letter) {
        return this.hotelService.findHotelsStartingWith(letter);
    }
    @GetMapping(path = "/fromstate/{state}")
    public Flux<Hotel> findHotelsInState(
            @PathVariable("state") String state) {
        return this.hotelService.findHotelsInState(state);
    }
}
```

传统的@RequestMapping、@GetMapping和@PostMapping并没有被改变,变得是返回类型。比如,预期只有一个结果的,现在返回一个Mono类型,之前预期返回一个列表的,现在则返回一个Flux类型。

通过使用Spring Data Cassandra中的响应式支持,整个Web到服务到后端设置都是响应式的,特别针对本文的关注点,非常直观易见。

简单地尝试这篇文章后面的代码可能会更易于理解,你可以在我的[GitHub仓库](https://github.com/bijukunjummen/sample-webflux-annot-cassandra)中获得这些代码。


text:
package com.linkedin.thirdeye.completeness.checker;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.linkedin.thirdeye.anomaly.job.JobConstants.JobStatus;
import com.linkedin.thirdeye.anomaly.job.JobRunner;
import com.linkedin.thirdeye.anomaly.task.TaskConstants.TaskStatus;
import com.linkedin.thirdeye.anomaly.task.TaskConstants.TaskType;
import com.linkedin.thirdeye.datalayer.dto.AnomalyFunctionDTO;
import com.linkedin.thirdeye.datalayer.dto.DatasetConfigDTO;
import com.linkedin.thirdeye.datalayer.dto.JobDTO;
import com.linkedin.thirdeye.datalayer.dto.TaskDTO;
import com.linkedin.thirdeye.datasource.DAORegistry;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** job runner for data completeness job
 *
 */
public class DataCompletenessJobRunner implements JobRunner {

  private static final Logger LOG = LoggerFactory.getLogger(DataCompletenessJobRunner.class);
  private static final DAORegistry DAO_REGISTRY = DAORegistry.getInstance();
  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

  private DataCompletenessJobContext dataCompletenessJobContext;
  private DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMddHHmm");

  public DataCompletenessJobRunner(DataCompletenessJobContext dataCompletenessJobContext) {
    this.dataCompletenessJobContext = dataCompletenessJobContext;
  }

  @Override
  public void run() {
    DateTime now = new DateTime();
    long checkDurationEndTime = now.getMillis();
    long checkDurationStartTime = now.minus(TimeUnit.MILLISECONDS.convert(
        DataCompletenessConstants.LOOKBACK_TIME_DURATION, DataCompletenessConstants.LOOKBACK_TIMEUNIT)).getMillis();

    String checkerEndTime = dateTimeFormatter.print(checkDurationEndTime);
    String checkerStartTime = dateTimeFormatter.print(checkDurationStartTime);
    String jobName =
        String.format("%s-%s-%s", TaskType.DATA_COMPLETENESS.toString(), checkerStartTime, checkerEndTime);

    dataCompletenessJobContext.setCheckDurationStartTime(checkDurationStartTime);
    dataCompletenessJobContext.setCheckDurationEndTime(checkDurationEndTime);
    dataCompletenessJobContext.setJobName(jobName);

    Set<String> datasetsToCheck = new HashSet<>();
    for (DatasetConfigDTO datasetConfig : DAO_REGISTRY.getDatasetConfigDAO().findActiveRequiresCompletenessCheck()) {
      datasetsToCheck.add(datasetConfig.getDataset());
    }
    for (AnomalyFunctionDTO anomalyFunction : DAO_REGISTRY.getAnomalyFunctionDAO().findAllActiveFunctions()) {
      if (anomalyFunction.isRequiresCompletenessCheck()) {
        datasetsToCheck.add(anomalyFunction.getCollection());
      }
    }
    dataCompletenessJobContext.setDatasetsToCheck(Lists.newArrayList(datasetsToCheck));

    // create data completeness job
    long jobExecutionId = createJob();
    dataCompletenessJobContext.setJobExecutionId(jobExecutionId);

    // create data completeness tasks
    createTasks();

  }

  public Long createJob() {
    Long jobExecutionId = null;
    try {
      LOG.info("Creating data completeness job");
      JobDTO jobSpec = new JobDTO();
      jobSpec.setJobName(dataCompletenessJobContext.getJobName());
      jobSpec.setScheduleStartTime(System.currentTimeMillis());
      jobSpec.setStatus(JobStatus.SCHEDULED);
      jobSpec.setTaskType(TaskType.DATA_COMPLETENESS);
      jobSpec.setConfigId(0); // Data completeness job does not have a config id
      jobExecutionId = DAO_REGISTRY.getJobDAO().save(jobSpec);
      LOG.info("Created JobSpec {} with jobExecutionId {}", jobSpec,
          jobExecutionId);
    } catch (Exception e) {
      LOG.error("Exception in creating data completeness job", e);
    }
    return jobExecutionId;
  }

  protected List<DataCompletenessTaskInfo> createDataCompletenessTasks(DataCompletenessJobContext dataCompletenessJobContext) {
    List<DataCompletenessTaskInfo> tasks = new ArrayList<>();

    // create 1 task, which will get data and perform check
    DataCompletenessTaskInfo dataCompletenessCheck = new DataCompletenessTaskInfo();
    dataCompletenessCheck.setDataCompletenessType(DataCompletenessConstants.DataCompletenessType.CHECKER);
    dataCompletenessCheck.setDataCompletenessStartTime(dataCompletenessJobContext.getCheckDurationStartTime());
    dataCompletenessCheck.setDataCompletenessEndTime(dataCompletenessJobContext.getCheckDurationEndTime());
    dataCompletenessCheck.setDatasetsToCheck(dataCompletenessJobContext.getDatasetsToCheck());
    tasks.add(dataCompletenessCheck);

    // create 1 task, for cleanup
    DataCompletenessTaskInfo cleanup = new DataCompletenessTaskInfo();
    cleanup.setDataCompletenessType(DataCompletenessConstants.DataCompletenessType.CLEANUP);
    tasks.add(cleanup);

    return tasks;
  }

  public List<Long> createTasks() {
    List<Long> taskIds = new ArrayList<>();
    try {
      LOG.info("Creating data completeness checker tasks");
      List<DataCompletenessTaskInfo> dataCompletenessTasks =
          createDataCompletenessTasks(dataCompletenessJobContext);
      LOG.info("DataCompleteness tasks {}", dataCompletenessTasks);
      for (DataCompletenessTaskInfo taskInfo : dataCompletenessTasks) {

        String taskInfoJson = null;
        try {
          taskInfoJson = OBJECT_MAPPER.writeValueAsString(taskInfo);
        } catch (JsonProcessingException e) {
          LOG.error("Exception when converting DataCompletenessTaskInfo {} to jsonString", taskInfo, e);
        }
        TaskDTO taskSpec = new TaskDTO();
        taskSpec.setTaskType(TaskType.DATA_COMPLETENESS);
        taskSpec.setJobName(dataCompletenessJobContext.getJobName());
        taskSpec.setStatus(TaskStatus.WAITING);
        taskSpec.setStartTime(System.currentTimeMillis());
        taskSpec.setTaskInfo(taskInfoJson);
        taskSpec.setJobId(dataCompletenessJobContext.getJobExecutionId());
        long taskId = DAO_REGISTRY.getTaskDAO().save(taskSpec);
        taskIds.add(taskId);
        LOG.info("Created dataCompleteness task {} with taskId {}", taskSpec, taskId);
      }
    } catch (Exception e) {
      LOG.error("Exception in creating data completeness tasks", e);
    }
    return taskIds;

  }

}


text:
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
    void init();
    void updateParentItem(QTreeWidgetItem* item);

private:
    Ui::Widget *ui;
public slots:
    void treeItemChanged(QTreeWidgetItem* item, int column);
};

#endif // WIDGET_H


text:
namespace Plivo.Resource.Call
{
    /// <summary>
    /// Queued call.
    /// </summary>
    public class QueuedCall : Resource
    {
        public string Direction { get; set; }
        public string From { get; set; }
        public string CallStatus { get; set; }
        public string To { get; set; }
        public string CallerName { get; set; }
        public string CallUuid { get; set; }
        public string RequestUuid { get; set; }

        public override string ToString()
        {
            return base.ToString() +
                    "StatusCode: " + StatusCode + "\n" +
                   "Direction: " + Direction + "\n" +
                   "From: " + From + "\n" +
                   "CallStatus: " + CallStatus + "\n" +
                   "To: " + To + "\n" +
                   "CallerName: " + CallerName + "\n" +
                   "CallUuid: " + CallUuid + "\n" +
                   "ApiId: " + ApiId + "\n" +
                   "RequestUuid: " + RequestUuid + "\n";
        }
    }

}


text:
package golaunch

import (
	"context"
	"crypto/tls"
	"time"

	"github.com/funjack/golibbuttplug"
)

const buttplugLaunchName = "Fleshlight Launch"

// buttplugLauch is a Launch connected via Buttplug.
type buttplugLaunch struct {
	ctx    context.Context
	addr   string
	tlscfg *tls.Config
	name   string

	client *golibbuttplug.Client
	device *golibbuttplug.Device

	disconnect chan bool
	wbuffer    chan [2]int
	limiter    <-chan time.Time

	disconnectFunc func()
}

// NewButtplugLaunch creates a new Launch connected via the Buttplug server
// running at addr. Identify with the Buttplug server with the given name.
func NewButtplugLaunch(ctx context.Context, addr, name string, tlscfg *tls.Config) Launch {
	return &buttplugLaunch{
		ctx:        ctx,
		addr:       addr,
		tlscfg:     tlscfg,
		name:       name,
		disconnect: make(chan bool),
		wbuffer:    make(chan [2]int, writeBufferSize),
		limiter:    time.Tick(threshold),
	}
}

// connect to Buttplug.
func (l *buttplugLaunch) connect() error {
	if l.client != nil {
		select {
		case <-l.client.Disconnected():
		default:
			// Still connected to buttplug.
			return nil
		}
	}
	c, err := golibbuttplug.NewClient(l.ctx, l.addr, l.name, l.tlscfg)
	if err != nil {
		return err
	}
	l.client = c
	return nil
}

// Connect sets up a connection with Buttplug and creates a connection with
// a Launch.
func (l *buttplugLaunch) Connect(ctx context.Context) error {
	// Connect to Buttplug
	if err := l.connect(); err != nil {
		return err
	}
	// Still have a device connected
	if l.device != nil {
		select {
		case <-l.device.Disconnected():
		default:
			return nil
		}
	}
	if err := l.client.StartScanning(); err != nil {
		return err
	}
	// Wait for scanning to finish.
	scanctx, cancel := context.WithTimeout(ctx, 30*time.Second)
	err := l.client.WaitOnScanning(scanctx)
	cancel()
	if err == context.DeadlineExceeded {
		// Stop scanning.
		if err := l.client.StopScanning(); err != nil {
			return err
		}
	} else if err != nil {
		return err
	}
	// Get all known devices.
	for _, d := range l.client.Devices() {
		if d.Name() == buttplugLaunchName && d.IsSupported(golibbuttplug.CommandFleshlightLaunchFW12) {
			l.device = d
			break
		}
	}
	if l.device == nil {
		return ErrDiscover
	}
	// Handle disconnects
	stopWriting := make(chan bool)
	go func() {
		select {
		case <-l.device.Disconnected():
		case <-l.client.Disconnected():
			l.client = nil
		case <-l.disconnect:
			l.device.StopDeviceCmd()
			l.client.Close()
			l.client = nil
		}
		stopWriting <- true
		l.device = nil
		if l.disconnectFunc != nil {
			l.disconnectFunc()
		}
	}()
	go l.writeFromBuffer(stopWriting)
	return nil
}

// Disconnect cancels the connection with the Launch and Buttplug.
func (l *buttplugLaunch) Disconnect() {
	select {
	case l.disconnect <- true:
	default:
	}
}

// writeFromBuffer sends commands to the Launch that are stored in the write
// buffer. To stop this function send true on the l.stopWriting channel.
func (l *buttplugLaunch) writeFromBuffer(stopchan <-chan bool) {
	for {
		select {
		case stop := <-stopchan:
			if stop == true {
				return
			}
		case b := <-l.wbuffer:
			// Limit amount of writes to sync behavior with our
			// BLE implementation.
			<-l.limiter
			l.device.FleshlightLaunchFW12Cmd(b[0], b[1])
		}
	}
}

// Move will move to the specified position at the desired speed.
// Position and speed are specified in percent.
func (l *buttplugLaunch) Move(position, speed int) {
	// Make sure we remain in the limits
	if position < 0 {
		position = 0
	} else if position > 99 {
		position = 99
	}
	// Don't go below 20% as very slow speeds seem to crash the Launch
	if speed < 20 {
		speed = 20
	} else if speed > 99 {
		speed = 99
	}

	data := [2]int{position, speed}
	l.wbuffer <- data
}

// HandleDisconnect registers a function that is called when the Launch
// disconnects.
func (l *buttplugLaunch) HandleDisconnect(f func()) {
	l.disconnectFunc = f
}


text:
var fs = require('fs');

if (typeof localStorage === "undefined" || localStorage === null) {
  var LocalStorage = require('node-localstorage').LocalStorage;
  localStorage = new LocalStorage('./scratch');
}

eval(fs.readFileSync('./js/taskstore.js', 'utf8'));

module.exports = taskApp;


text:
cask "font-elstobd" do
  version "1.015"
  sha256 "4cd99be64bd5086e806469ee7c8af5f515d667ad4c5eaaa1bd3e63f38bd23128"

  url "https://github.com/psb1558/Elstob-font/releases/download/v#{version}/Elstob_v#{version.dots_to_underscores}.zip"
  name "ElstobD"
  homepage "https://github.com/psb1558/Elstob-font"

  font "Elstob_font/desktop/ElstobD-10pt.ttf"
  font "Elstob_font/desktop/ElstobD-10ptBold.ttf"
  font "Elstob_font/desktop/ElstobD-10ptBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-10ptItalic.ttf"
  font "Elstob_font/desktop/ElstobD-10ptMedium.ttf"
  font "Elstob_font/desktop/ElstobD-10ptMediumItalic.ttf"
  font "Elstob_font/desktop/ElstobD-10ptSemiBold.ttf"
  font "Elstob_font/desktop/ElstobD-10ptSemiBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-14pt.ttf"
  font "Elstob_font/desktop/ElstobD-14ptBold.ttf"
  font "Elstob_font/desktop/ElstobD-14ptBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-14ptItalic.ttf"
  font "Elstob_font/desktop/ElstobD-14ptMedium.ttf"
  font "Elstob_font/desktop/ElstobD-14ptMediumItalic.ttf"
  font "Elstob_font/desktop/ElstobD-14ptSemiBold.ttf"
  font "Elstob_font/desktop/ElstobD-14ptSemiBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-18pt.ttf"
  font "Elstob_font/desktop/ElstobD-18ptBold.ttf"
  font "Elstob_font/desktop/ElstobD-18ptBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-18ptExtraBold.ttf"
  font "Elstob_font/desktop/ElstobD-18ptExtraBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-18ptItalic.ttf"
  font "Elstob_font/desktop/ElstobD-18ptMedium.ttf"
  font "Elstob_font/desktop/ElstobD-18ptMediumItalic.ttf"
  font "Elstob_font/desktop/ElstobD-18ptSemiBold.ttf"
  font "Elstob_font/desktop/ElstobD-18ptSemiBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-8pt.ttf"
  font "Elstob_font/desktop/ElstobD-8ptBold.ttf"
  font "Elstob_font/desktop/ElstobD-8ptBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-8ptItalic.ttf"
  font "Elstob_font/desktop/ElstobD-8ptMedium.ttf"
  font "Elstob_font/desktop/ElstobD-8ptMediumItalic.ttf"
  font "Elstob_font/desktop/ElstobD-8ptSemiBold.ttf"
  font "Elstob_font/desktop/ElstobD-8ptSemiBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-Bold.ttf"
  font "Elstob_font/desktop/ElstobD-BoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-ExtraBold.ttf"
  font "Elstob_font/desktop/ElstobD-ExtraBoldItalic.ttf"
  font "Elstob_font/desktop/ElstobD-ExtraLight.ttf"
  font "Elstob_font/desktop/ElstobD-ExtraLightItalic.ttf"
  font "Elstob_font/desktop/ElstobD-Italic.ttf"
  font "Elstob_font/desktop/ElstobD-Light.ttf"
  font "Elstob_font/desktop/ElstobD-LightItalic.ttf"
  font "Elstob_font/desktop/ElstobD-Medium.ttf"
  font "Elstob_font/desktop/ElstobD-MediumItalic.ttf"
  font "Elstob_font/desktop/ElstobD-Regular.ttf"
  font "Elstob_font/desktop/ElstobD-SemiBold.ttf"
  font "Elstob_font/desktop/ElstobD-SemiBoldItalic.ttf"
end


text:
class AddProjectToTask < ActiveRecord::Migration
  def change
    add_reference :tasks, :project, index: true, foreign_key: true
  end
end


text:
( this.undefine || require( 'undefine' )( module, require ) )
( { global: 'fib', no_conflict: true } )
( 'fibonacci', [], function() {
  return fibonacci;

  // Naive recursive implementation of a Fibonacci number calculator
  function fibonacci( n ) {
    if ( n < 0 ) return undefined;

    if ( n < 2 ) return n;

    return fibonacci( n - 2 ) + fibonacci( n - 1 );
  }
} );


text:
<?

if (!$_user->logged) {
    header("Location: /login");
    exit;
}

if ($_user->isAdmin()){
	$this->addTwigVars('lastSimulations', $this->loadClass("simulation")->getLastSimulation(10));
} else {
	$this->addTwigVars('lastSimulations', $this->loadClass("simulation")->getLastSimulation(10, $_user->id));
}

switch (@$this->url_var[1]) {
    case('simulation'):
    	$this->addTwigVars('section', $this->url_var[2]);
        require "./controller/envpanel/envpanel.simulation.php";
    	break;
    case('user'):
    	$this->addTwigVars('section', $this->url_var[2]);
    	require "./controller/envpanel/envpanel.user.php";
    	break;
    default:
    	$template = $twig->loadTemplate('envpanel/main.twig');
    	echo $template->render($this->twigVars);
        break;
}


text: DIV