text:
/**
 * @file downstream.c
 *
 * @description This describes functions required to manage downstream messages.
 *
 */

#include "downstream.h"
#include "upstream.h"
#include "connection.h"
#include "partners_check.h"
#include "ParodusInternal.h"
#include "crud_interface.h"
/*----------------------------------------------------------------------------*/
/*                             Function Prototypes                            */
/*----------------------------------------------------------------------------*/
static void createNewMsgForCRUD(wrp_msg_t *message, wrp_msg_t **crudMessage );
/*----------------------------------------------------------------------------*/
/*                             External Functions                             */
/*----------------------------------------------------------------------------*/

/**
 * @brief listenerOnMessage function to create WebSocket listener to receive connections
 *
 * @param[in] msg The message received from server for various process requests
 * @param[in] msgSize message size
 */
void listenerOnMessage(void * msg, size_t msgSize)
{
    int rv =0;
    wrp_msg_t *message;
    wrp_msg_t *crudMessage= NULL;
    char* destVal = NULL;
    char dest[32] = {'\0'};
    int msgType;
    int bytes =0;
    int destFlag =0;
    size_t size = 0;
    int resp_size = -1 ;
    const char *recivedMsg = NULL;
    char *str= NULL;
    wrp_msg_t *resp_msg = NULL;
    void *resp_bytes;
    cJSON *response = NULL;
    reg_list_item_t *temp = NULL;

    recivedMsg =  (const char *) msg;

    ParodusInfo("Received msg from server\n");
    if(recivedMsg!=NULL)
    {
        /*** Decoding downstream recivedMsg to check destination ***/
        rv = wrp_to_struct(recivedMsg, msgSize, WRP_BYTES, &message);

        if(rv > 0)
        {
            ParodusPrint("\nDecoded recivedMsg of size:%d\n", rv);
            msgType = message->msg_type;
            ParodusInfo("msgType received:%d\n", msgType);

            switch( message->msg_type )
            {
                case WRP_MSG_TYPE__AUTH:
                {
                    ParodusInfo("Authorization Status received with Status code :%d\n", message->u.auth.status);
                    break;
                }

                case WRP_MSG_TYPE__EVENT:
                case WRP_MSG_TYPE__REQ:
                case WRP_MSG_TYPE__CREATE:
                case WRP_MSG_TYPE__UPDATE:
                case WRP_MSG_TYPE__RETREIVE:
                case WRP_MSG_TYPE__DELETE:
                {
                    ParodusPrint("numOfClients registered is %d\n", get_numOfClients());
                    int ret = validate_partner_id(message, NULL);
                    if(ret < 0)
                    {
                        response = cJSON_CreateObject();
                        cJSON_AddNumberToObject(response, "statusCode", 403);
                        cJSON_AddStringToObject(response, "message", "Invalid partner_id");
                    }

                    destVal = strdup(((WRP_MSG_TYPE__EVENT == msgType) ? message->u.event.dest :
                              ((WRP_MSG_TYPE__REQ   == msgType) ? message->u.req.dest : message->u.crud.dest)));

                    if( (destVal != NULL) && (ret >= 0) )
                    {
						char *newDest = NULL;
						char *tempDest = strtok(destVal , "/");
						if(tempDest != NULL)
						{
							newDest = strtok(NULL , "/");
						}
						if(newDest != NULL)
						{
							parStrncpy(dest,newDest, sizeof(dest));
						}
						else
						{
							parStrncpy(dest,destVal, sizeof(dest));
						}
                        ParodusInfo("Received downstream dest as :%s and transaction_uuid :%s\n", dest,
                            ((WRP_MSG_TYPE__REQ   == msgType) ? message->u.req.transaction_uuid :
                            ((WRP_MSG_TYPE__EVENT == msgType) ? "NA" : message->u.crud.transaction_uuid)));
			OnboardLog("Received downstream dest as :%s and transaction_uuid :%s\n", dest,
                            ((WRP_MSG_TYPE__REQ   == msgType) ? message->u.req.transaction_uuid :
                            ((WRP_MSG_TYPE__EVENT == msgType) ? "NA" : message->u.crud.transaction_uuid)));

                        free(destVal);

                        temp = get_global_node();
                        //Checking for individual clients & Sending to each client

                        while (NULL != temp)
                        {
                            ParodusPrint("node is pointing to temp->service_name %s \n",temp->service_name);
                            // Sending message to registered clients
                            if( strcmp(dest, temp->service_name) == 0)
                            {
                                ParodusPrint("sending to nanomsg client %s\n", dest);
                                bytes = nn_send(temp->sock, recivedMsg, msgSize, 0);
                                ParodusInfo("sent downstream message to reg_client '%s'\n",temp->url);
                                ParodusPrint("downstream bytes sent:%d\n", bytes);
                                destFlag =1;
                                break;
                            }
                            ParodusPrint("checking the next item in the list\n");
                            temp= temp->next;
                        }
                        release_global_node ();

			/* check Downstream dest for CRUD requests */
			if(destFlag ==0 && strcmp("parodus", dest)==0)
			{
							ParodusPrint("Received CRUD request : dest : %s\n", dest);
							if ((message->u.crud.source == NULL) || (message->u.crud.transaction_uuid == NULL))
							{
								ParodusError("Invalid request\n");
								response = cJSON_CreateObject();
								cJSON_AddNumberToObject(response, "statusCode", 400);
								cJSON_AddStringToObject(response, "message", "Invalid Request");
								ret = -1;
							}
							else
							{
							    createNewMsgForCRUD(message, &crudMessage);
							    addCRUDmsgToQueue(crudMessage);
							}
							destFlag =1;
			}
			//if any unknown dest received sending error response to server
                        if(destFlag ==0)
                        {
                            ParodusError("Unknown dest:%s\n", dest);
                            response = cJSON_CreateObject();
                            cJSON_AddNumberToObject(response, "statusCode", 531);
                            cJSON_AddStringToObject(response, "message", "Service Unavailable");
                        }
                    }

                    if( (WRP_MSG_TYPE__EVENT != msgType) &&
                        ((destFlag == 0) || (ret < 0)) )
                    {
                        resp_msg = (wrp_msg_t *)malloc(sizeof(wrp_msg_t));
                        memset(resp_msg, 0, sizeof(wrp_msg_t));

                        resp_msg ->msg_type = msgType;
                        if( WRP_MSG_TYPE__REQ == msgType )
                        {
                            resp_msg ->u.req.source = message->u.req.dest;
                            resp_msg ->u.req.dest = message->u.req.source;
                            resp_msg ->u.req.transaction_uuid=message->u.req.transaction_uuid;
                        }
                        else
                        {
                            resp_msg ->u.crud.source = message->u.crud.dest;
				if(message->u.crud.source !=NULL)
				{
					resp_msg ->u.crud.dest = message->u.crud.source;
				}
				else
				{
					resp_msg ->u.crud.dest = "unknown";
				}
                            resp_msg ->u.crud.transaction_uuid = message->u.crud.transaction_uuid;
                            resp_msg ->u.crud.path =             message->u.crud.path;
                        }

                        if(response != NULL)
                        {
                            str = cJSON_PrintUnformatted(response);
                            ParodusInfo("Payload Response: %s\n", str);

                            if( WRP_MSG_TYPE__REQ == msgType )
                            {
                                resp_msg ->u.req.payload = (void *)str;
                                resp_msg ->u.req.payload_size = strlen(str);
                            }
                            else
                            {
                                resp_msg ->u.crud.payload = (void *)str;
                                resp_msg ->u.crud.payload_size = strlen(str);
                            }

                            ParodusPrint("msgpack encode\n");
                            resp_size = wrp_struct_to( resp_msg, WRP_BYTES, &resp_bytes );
                            if(resp_size > 0)
                            {
                                size = (size_t) resp_size;
                                sendUpstreamMsgToServer(&resp_bytes, size);
                            }
                            free(str);
                            cJSON_Delete(response);
                            free(resp_bytes);
                            resp_bytes = NULL;
                        }
                        free(resp_msg);
                    }
                    break;
                }

                case WRP_MSG_TYPE__SVC_REGISTRATION:
                case WRP_MSG_TYPE__SVC_ALIVE:
                case WRP_MSG_TYPE__UNKNOWN:
                default:
                    break;
            }
            ParodusPrint("free for downstream decoded msg\n");
            wrp_free_struct(message);
            message = NULL;
        }
        else
        {
            ParodusError( "Failure in msgpack decoding for receivdMsg: rv is %d\n", rv );
        }
    }
}
/*----------------------------------------------------------------------------*/
/*                             Internal Functions                             */
/*----------------------------------------------------------------------------*/
/**
 * @brief createNewMsgForCRUD function to create new message for processing CRUD requests
 *
 * @param[in] message The message received from server
 * @param[out] crudMessage New message for processing CRUD requests
 */
static void createNewMsgForCRUD(wrp_msg_t *message, wrp_msg_t **crudMessage )
{
    wrp_msg_t *msg;
    msg = ( wrp_msg_t * ) malloc( sizeof( wrp_msg_t ) );
    size_t i;
    if(msg != NULL)
    {
        memset( msg, 0, sizeof( wrp_msg_t ) );
        msg->msg_type = message->msg_type;
        if(message->u.crud.source != NULL)
        {
            ParodusPrint("message->u.crud.source = %s\n",message->u.crud.source);
            msg->u.crud.source = strdup(message->u.crud.source);
        }

        if(message->u.crud.dest!= NULL)
        {
            ParodusPrint("message->u.crud.dest = %s\n",message->u.crud.dest);
            msg->u.crud.dest = strdup(message->u.crud.dest);
        }

        if(message->u.crud.transaction_uuid != NULL)
        {
            ParodusPrint("message->u.crud.transaction_uuid = %s\n",message->u.crud.transaction_uuid);
            msg->u.crud.transaction_uuid = strdup(message->u.crud.transaction_uuid);
        }

        if(message->u.crud.partner_ids!= NULL && message->u.crud.partner_ids->count >0)
        {
            msg->u.crud.partner_ids = ( partners_t * ) malloc( sizeof( partners_t ) +
                                                              sizeof( char * ) * message->u.crud.partner_ids->count );
            if(msg->u.crud.partner_ids != NULL)
            {
                msg->u.crud.partner_ids->count = message->u.crud.partner_ids->count;
                for(i = 0; i<message->u.crud.partner_ids->count; i++)
                {
                    ParodusPrint("message->u.crud.partner_ids->partner_ids[%d] = %s\n",i,message->u.crud.partner_ids->partner_ids[i]);
                    msg->u.crud.partner_ids->partner_ids[i] = strdup(message->u.crud.partner_ids->partner_ids[i]);
                }
            }
        }

        if(message->u.crud.headers!= NULL && message->u.crud.headers->count >0)
        {
            msg->u.crud.headers = ( headers_t * ) malloc( sizeof( headers_t ) +
                                                                sizeof( char * ) * message->u.crud.headers->count );
            if(msg->u.crud.headers != NULL)
            {
                msg->u.crud.headers->count = message->u.crud.headers->count;
                for(i = 0; i<message->u.crud.headers->count; i++)
                {
                    ParodusPrint("message->u.crud.headers->headers[%d] = %s\n",i,message->u.crud.headers->headers[i]);
                    msg->u.crud.headers->headers[i] = strdup(message->u.crud.headers->headers[i]);
                }
            }
        }

        if(message->u.crud.metadata != NULL && message->u.crud.metadata->count > 0)
        {
            msg->u.crud.metadata = (data_t *) malloc( sizeof( data_t ) );
            if(msg->u.crud.metadata != NULL)
            {
                memset( msg->u.crud.metadata, 0, sizeof( data_t ) );
                msg->u.crud.metadata->count = message->u.crud.metadata->count;
                msg->u.crud.metadata->data_items = ( struct data* )malloc( sizeof( struct data ) * ( message->u.crud.metadata->count ) );
                for(i=0; i<message->u.crud.metadata->count; i++)
                {
                    if(message->u.crud.metadata->data_items[i].name != NULL)
                    {
                        ParodusPrint("message->u.crud.metadata->data_items[%d].name : %s\n",i,message->u.crud.metadata->data_items[i].name);
                        msg->u.crud.metadata->data_items[i].name = strdup(message->u.crud.metadata->data_items[i].name);
                    }
                    if(message->u.crud.metadata->data_items[i].value != NULL)
                    {
                        ParodusPrint("message->u.crud.metadata->data_items[%d].value : %s\n",i,message->u.crud.metadata->data_items[i].value);
                        msg->u.crud.metadata->data_items[i].value = strdup(message->u.crud.metadata->data_items[i].value);
                    }
                }
            }
        }
        msg->u.crud.include_spans = message->u.crud.include_spans;
        if(message->u.crud.content_type != NULL)
        {
            ParodusPrint("message->u.crud.content_type : %s\n",message->u.crud.content_type);
            msg->u.crud.content_type = strdup(message->u.crud.content_type);
        }
        msg->u.crud.spans.spans = NULL;   /* not supported */
        msg->u.crud.spans.count = 0;     /* not supported */
        msg->u.crud.status = message->u.crud.status;
        msg->u.crud.rdr = message->u.crud.rdr;
        if(message->u.crud.payload != NULL)
        {
            ParodusPrint("message->u.crud.payload = %s\n", (char *)message->u.crud.payload);
            msg->u.crud.payload = strdup((char *)message->u.crud.payload);
        }
        msg->u.crud.payload_size = message->u.crud.payload_size;
        if(message->u.crud.path != NULL)
        {
            ParodusPrint("message->u.crud.path = %s\n", message->u.crud.path);
            msg->u.crud.path = strdup(message->u.crud.path);
        }
        *crudMessage = msg;
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>GLFW: GLFW Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

		GLFW

Documentation

Download

Media

Community

external

glfw-3.2.1

include

GLFW

GLFW Directory Reference

Files

file  	glfw3.h [code]

 	The header of the GLFW 3 API.

file  	glfw3native.h [code]

 	The header of the native access functions.

<address class="footer">

Last update on Wed May 24 2017 for GLFW 3.2.1

</address>

redpajama_set_name: RedPajamaGithub


text:
class UserSweeper < ActionController::Caching::Sweeper
  observe User

  def after_save(user)
    ['newest_users'].each do |fragment|
      expire_fragment "#{fragment}_html"
    end
  end

  def self.expire_user_all user
    puts "Sweeping newswires"
    controller = ActionController::Base.new
    controller.expire_fragment "newest_users"
    ['newest_users', 'recent_users', 'active_users', 'moderator_users', 'sidebar_top_users_weekly'].each do |fragment|
      controller.expire_fragment "#{fragment}_html"
    end
    NewscloudSweeper.expire_instance(user)
  end

end


text:
package org.apache.samza.config

import scala.collection.JavaConversions._
import org.apache.samza.util.Logging

object SystemConfig {
  // system config constants
  val SYSTEM_PREFIX = "systems.%s."
  val SYSTEM_FACTORY = "systems.%s.samza.factory"
  val KEY_SERDE = "systems.%s.samza.key.serde"
  val MSG_SERDE = "systems.%s.samza.msg.serde"
  val CONSUMER_OFFSET_DEFAULT = SYSTEM_PREFIX + "samza.offset.default"

  implicit def Config2System(config: Config) = new SystemConfig(config)
}

class SystemConfig(config: Config) extends ScalaMapConfig(config) with Logging {
  def getSystemFactory(name: String) = getOption(SystemConfig.SYSTEM_FACTORY format name)

  def getSystemKeySerde(name: String) = getOption(SystemConfig.KEY_SERDE format name)

  def getSystemMsgSerde(name: String) = getOption(SystemConfig.MSG_SERDE format name)

  def getDefaultSystemOffset(systemName: String) = getOption(SystemConfig.CONSUMER_OFFSET_DEFAULT format (systemName))

  /**
   * Returns a list of all system names from the config file. Useful for
   * getting individual systems.
   */
  def getSystemNames() = {
    val subConf = config.subset("systems.", true)
    // find all .samza.factory keys, and strip the suffix
    subConf.keys.filter(k => k.endsWith(".samza.factory")).map(_.replace(".samza.factory", ""))
  }
}


text:
#include <iostream>

#include "tensorflow/lite/tools/benchmark/benchmark_tflite_model.h"
#include "tensorflow/lite/tools/benchmark/logging.h"

namespace tflite {
namespace benchmark {

int Main(int argc, char** argv) {
  TFLITE_LOG(INFO) << "STARTING!";
  BenchmarkTfLiteModel benchmark;
  BenchmarkLoggingListener listener;
  benchmark.AddListener(&listener);
  if (benchmark.Run(argc, argv) != kTfLiteOk) {
    TFLITE_LOG(ERROR) << "Benchmarking failed.";
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
}  // namespace benchmark
}  // namespace tflite

int main(int argc, char** argv) { return tflite::benchmark::Main(argc, argv); }


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

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /><title>LocalVariablesInfo xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />

View Javadoc

1
17  package org.apache.bcel.verifier.statics;
18
19
20  import org.apache.bcel.generic.Type;
21  import org.apache.bcel.verifier.exc.AssertionViolatedException;
22  import org.apache.bcel.verifier.exc.LocalVariableInfoInconsistentException;
23
24  /***
25   * A utility class holding the information about
26   * the names and the types of the local variables in
27   * a given method.
28   *
29   * @version $Id: LocalVariablesInfo.java 386056 2006-03-15 11:31:56Z tcurdt $
30   * @author Enver Haase
31   */
32  public class LocalVariablesInfo{
33
34  	/*** The information about the local variables is stored here. */
35  	private LocalVariableInfo[] localVariableInfos;
36
37  	/*** The constructor. */
38  	LocalVariablesInfo(int max_locals){
39  		localVariableInfos = new LocalVariableInfo[max_locals];
40  		for (int i=0; i<max_locals; i++){
41  			localVariableInfos[i] = new LocalVariableInfo();
42  		}
43  	}
44
45  	/*** Returns the LocalVariableInfo for the given slot. */
46  	public LocalVariableInfo getLocalVariableInfo(int slot){
47  		if (slot < 0 || slot >= localVariableInfos.length){
48  			throw new AssertionViolatedException("Slot number for local variable information out of range.");
49  		}
50  		return localVariableInfos[slot];
51  	}
52
53  	/***
54  	 * Adds information about the local variable in slot 'slot'. Automatically
55  	 * adds information for slot+1 if 't' is Type.LONG or Type.DOUBLE.
56  	 * @throws LocalVariableInfoInconsistentException if the new information conflicts
57  	 *         with already gathered information.
58  	 */
59  	public void add(int slot, String name, int startpc, int length, Type t) throws LocalVariableInfoInconsistentException{
60  		// The add operation on LocalVariableInfo may throw the '...Inconsistent...' exception, we don't throw it explicitely here.
61
62  		if (slot < 0 || slot >= localVariableInfos.length){
63  			throw new AssertionViolatedException("Slot number for local variable information out of range.");
64  		}
65
66  		localVariableInfos[slot].add(name, startpc, length, t);
67  		if (t == Type.LONG) {
68              localVariableInfos[slot+1].add(name, startpc, length, LONG_Upper.theInstance());
69          }
70  		if (t == Type.DOUBLE) {
71              localVariableInfos[slot+1].add(name, startpc, length, DOUBLE_Upper.theInstance());
72          }
73  	}
74  }

This page was automatically generated by Maven


text:
#include "VisualBench.h"

#include "ProcStats.h"
#include "SkApplication.h"
#include "SkCanvas.h"
#include "SkCommandLineFlags.h"
#include "SkForceLinking.h"
#include "SkGraphics.h"
#include "SkGr.h"
#include "SkImageDecoder.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "Stats.h"
#include "gl/GrGLInterface.h"

__SK_FORCE_IMAGE_DECODER_LINKING;

// Between samples we reset context
// Between frames we swap buffers
// Between flushes we call flush on GrContext

DEFINE_int32(gpuFrameLag, 5, "Overestimate of maximum number of frames GPU allows to lag.");
DEFINE_int32(samples, 10, "Number of times to time each skp.");
DEFINE_int32(frames, 5, "Number of frames of each skp to render per sample.");
DEFINE_double(flushMs, 20, "Target flush time in millseconds.");
DEFINE_double(loopMs, 5, "Target loop time in millseconds.");
DEFINE_int32(msaa, 0, "Number of msaa samples.");
DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
DEFINE_bool2(verbose, v, false, "enable verbose output from the test driver.");
DEFINE_string(key, "", "");  // dummy to enable gm tests that have platform-specific names

static SkString humanize(double ms) {
    if (FLAGS_verbose) {
        return SkStringPrintf("%llu", (uint64_t)(ms*1e6));
    }
    return HumanizeMs(ms);
}

#define HUMANIZE(time) humanize(time).c_str()

VisualBench::VisualBench(void* hwnd, int argc, char** argv)
    : INHERITED(hwnd)
    , fCurrentSample(0)
    , fCurrentFrame(0)
    , fFlushes(1)
    , fLoops(1)
    , fState(kPreWarmLoops_State)
    , fBenchmark(NULL) {
    SkCommandLineFlags::Parse(argc, argv);

    this->setTitle();
    this->setupBackend();

    fBenchmarkStream.reset(SkNEW(VisualBenchmarkStream));

    // Print header
    SkDebugf("curr/maxrss\tloops\tflushes\tmin\tmedian\tmean\tmax\tstddev\tbench\n");
}

VisualBench::~VisualBench() {
    INHERITED::detach();
}

void VisualBench::setTitle() {
    SkString title("VisualBench");
    INHERITED::setTitle(title.c_str());
}

SkSurface* VisualBench::createSurface() {
    if (!fSurface) {
        SkSurfaceProps props(INHERITED::getSurfaceProps());
        fSurface.reset(SkSurface::NewRenderTargetDirect(fRenderTarget, &props));
    }

    // The caller will wrap the SkSurface in an SkAutoTUnref
    return SkRef(fSurface.get());
}

bool VisualBench::setupBackend() {
    this->setColorType(kRGBA_8888_SkColorType);
    this->setVisibleP(true);
    this->setClipToBounds(false);

    if (FLAGS_fullscreen) {
        if (!this->makeFullscreen()) {
            SkDebugf("Could not go fullscreen!");
        }
    }
    if (!this->attach(kNativeGL_BackEndType, FLAGS_msaa, &fAttachmentInfo)) {
        SkDebugf("Not possible to create backend.\n");
        INHERITED::detach();
        return false;
    }

    this->setVsync(false);
    this->resetContext();
    return true;
}

void VisualBench::resetContext() {
    fSurface.reset(NULL);

    fInterface.reset(GrGLCreateNativeInterface());
    SkASSERT(fInterface);

    // setup contexts
    fContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext)fInterface.get()));
    SkASSERT(fContext);

    // setup rendertargets
    this->setupRenderTarget();
}

void VisualBench::setupRenderTarget() {
    if (fContext) {
        fRenderTarget.reset(this->renderTarget(fAttachmentInfo, fInterface, fContext));
    }
}

inline void VisualBench::renderFrame(SkCanvas* canvas) {
    for (int flush = 0; flush < fFlushes; flush++) {
        fBenchmark->draw(fLoops, canvas);
        canvas->flush();
    }
    INHERITED::present();
}

void VisualBench::printStats() {
    const SkTArray<double>& measurements = fRecords.back().fMeasurements;
    const char* shortName = fBenchmark->getUniqueName();
    if (FLAGS_verbose) {
        for (int i = 0; i < measurements.count(); i++) {
            SkDebugf("%s  ", HUMANIZE(measurements[i]));
        }
        SkDebugf("%s\n", shortName);
    } else {
        SkASSERT(measurements.count());
        Stats stats(measurements);
        const double stdDevPercent = 100 * sqrt(stats.var) / stats.mean;
        SkDebugf("%4d/%-4dMB\t%d\t%d\t%s\t%s\t%s\t%s\t%.0f%%\t%s\n",
                 sk_tools::getCurrResidentSetSizeMB(),
                 sk_tools::getMaxResidentSetSizeMB(),
                 fLoops,
                 fFlushes,
                 HUMANIZE(stats.min),
                 HUMANIZE(stats.median),
                 HUMANIZE(stats.mean),
                 HUMANIZE(stats.max),
                 stdDevPercent,
                 shortName);
    }
}

bool VisualBench::advanceRecordIfNecessary(SkCanvas* canvas) {
    if (fBenchmark) {
        return true;
    }

    fBenchmark.reset(fBenchmarkStream->next());
    if (!fBenchmark) {
        return false;
    }

    canvas->clear(0xffffffff);
    fBenchmark->preDraw();
    fRecords.push_back();
    return true;
}

inline void VisualBench::nextState(State nextState) {
    fState = nextState;
}

void VisualBench::perCanvasPreDraw(SkCanvas* canvas, State nextState) {
    fBenchmark->perCanvasPreDraw(canvas);
    fCurrentFrame = 0;
    this->nextState(nextState);
}

void VisualBench::preWarm(State nextState) {
    if (fCurrentFrame >= FLAGS_gpuFrameLag) {
        // we currently time across all frames to make sure we capture all GPU work
        this->nextState(nextState);
        fCurrentFrame = 0;
        fTimer.start();
    } else {
        fCurrentFrame++;
    }
}

void VisualBench::draw(SkCanvas* canvas) {
    if (!this->advanceRecordIfNecessary(canvas)) {
        this->closeWindow();
        return;
    }
    this->renderFrame(canvas);
    switch (fState) {
        case kPreWarmLoopsPerCanvasPreDraw_State: {
            this->perCanvasPreDraw(canvas, kPreWarmLoops_State);
            break;
        }
        case kPreWarmLoops_State: {
            this->preWarm(kTuneLoops_State);
            break;
        }
        case kTuneLoops_State: {
            this->tuneLoops();
            break;
        }
        case kPreWarmTimingPerCanvasPreDraw_State: {
            this->perCanvasPreDraw(canvas, kPreWarmTiming_State);
            break;
        }
        case kPreWarmTiming_State: {
            this->preWarm(kTiming_State);
            break;
        }
        case kTiming_State: {
            this->timing(canvas);
            break;
        }
    }

    // Invalidate the window to force a redraw. Poor man's animation mechanism.
    this->inval(NULL);
}

inline double VisualBench::elapsed() {
    fTimer.end();
    return fTimer.fWall;
}

void VisualBench::resetTimingState() {
    fCurrentFrame = 0;
    fTimer = WallTimer();
    this->resetContext();
}

void VisualBench::scaleLoops(double elapsedMs) {
    // Scale back the number of loops
    fLoops = (int)ceil(fLoops * FLAGS_loopMs / elapsedMs);
    fFlushes = (int)ceil(FLAGS_flushMs / elapsedMs);
}

inline void VisualBench::tuneLoops() {
    if (1 << 30 == fLoops) {
        // We're about to wrap.  Something's wrong with the bench.
        SkDebugf("InnerLoops wrapped\n");
        fLoops = 0;
    } else {
        double elapsedMs = this->elapsed();
        if (elapsedMs > FLAGS_loopMs) {
            this->scaleLoops(elapsedMs);
            this->nextState(kPreWarmTimingPerCanvasPreDraw_State);
        } else {
            fLoops *= 2;
            this->nextState(kPreWarmLoops_State);
        }
        this->resetTimingState();
    }
}

void VisualBench::recordMeasurement() {
    double measurement = this->elapsed() / (FLAGS_frames * fLoops * fFlushes);
    fRecords.back().fMeasurements.push_back(measurement);
}

void VisualBench::postDraw(SkCanvas* canvas) {
    fBenchmark->perCanvasPostDraw(canvas);
    fBenchmark.reset(NULL);
    fCurrentSample = 0;
    fFlushes = 1;
    fLoops = 1;
}

inline void VisualBench::timing(SkCanvas* canvas) {
    if (fCurrentFrame >= FLAGS_frames) {
        this->recordMeasurement();
        if (fCurrentSample++ >= FLAGS_samples) {
            this->printStats();
            this->postDraw(canvas);
            this->nextState(kPreWarmLoopsPerCanvasPreDraw_State);
        } else {
            this->nextState(kPreWarmTimingPerCanvasPreDraw_State);
        }
        this->resetTimingState();
    } else {
        fCurrentFrame++;
    }
}

void VisualBench::onSizeChange() {
    this->setupRenderTarget();
}

bool VisualBench::onHandleChar(SkUnichar unichar) {
    return true;
}

// Externally declared entry points
void application_init() {
    SkGraphics::Init();
    SkEvent::Init();
}

void application_term() {
    SkEvent::Term();
    SkGraphics::Term();
}

SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
    return new VisualBench(hwnd, argc, argv);
}


text:
package com.snowplowanalytics.snowplow.rdbloader
package config

import cats.data._
import cats.implicits._

import java.util.Base64
import java.nio.charset.StandardCharsets

// This project
import LoaderError._
import generated.ProjectMetadata
import utils.{ Common, Compat }

/**
 * Validated and parsed result application config
 *
 * @param configYaml decoded Snowplow config.yml
 * @param target decoded target to load
 * @param steps collected steps
 */
case class CliConfig(
  configYaml: SnowplowConfig,
  target: StorageTarget,
  steps: Set[Step],
  logKey: S3.Key)

object CliConfig {

  val parser = new scopt.OptionParser[RawConfig]("rdb-loader") {
    head("Relational Database Loader", ProjectMetadata.version)

    opt[String]('c', "config").required().valueName("<config.yml>").
      action((x, c) ⇒ c.copy(config = x)).
      text("base64-encoded string with config.yml content")

    opt[String]('t', "target").required().valueName("<target.json>").
      action((x, c) => c.copy(target = x)).
      text("base64-encoded string with single storage target configuration JSON")

    opt[String]('r', "resolver").required().valueName("<resolver.json>").
      action((x, c) => c.copy(resolver = x)).
      text("base64-encoded string with Iglu resolver configuration JSON")

    opt[String]('l', "logkey").required().valueName("<name>").
      action((x, c) => c.copy(logkey = x)).
      text("base64-encoded string with Iglu resolver configuration JSON")

    opt[Seq[Step.IncludeStep]]('i', "include").action((x, c) ⇒
      c.copy(include = x)).text("include optional work steps")

    opt[Seq[Step.SkipStep]]('s', "skip").action((x, c) =>
      c.copy(skip = x)).text("skip default steps")

    help("help").text("prints this usage text")

  }

  /**
   * Parse raw CLI arguments into validated and transformed application config
   * This is side-effecting function, it'll print to stdout all errors
   *
   * @param argv list of command-line arguments
   * @return none if not all required arguments were passed
   *         or unknown arguments provided,
   *         some config error if arguments could not be transformed
   *         into application config
   *         some application config if everything was validated
   *         correctly
   */
  def parse(argv: Seq[String]): Option[ValidatedNel[ConfigError, CliConfig]] =
    parser.parse(argv, rawCliConfig).map(transform)

  /**
   * Initial raw configuration parsed from CLI arguments
   * Could be invalid, supposed to be validated and transformed
   * into `CliConfig`
   *
   * @param config base64-encoded Snowplow config.yml
   * @param target base64-encoded storage target JSON
   * @param resolver base64-encoded Iglu Resolver JSON
   * @param include sequence of of decoded steps to include
   * @param skip sequence of of decoded steps to skip
   * @param logkey filename, where RDB log dump will be saved
   */
  private[config] case class RawConfig(
    config: String,
    target: String,
    resolver: String,
    include: Seq[Step.IncludeStep],
    skip: Seq[Step.SkipStep],
    logkey: String)

  // Always invalid initial parsing configuration
  private[this] val rawCliConfig = RawConfig("", "", "", Nil, Nil, "")

  /**
   * Validated and transform initial raw cli arguments into
   * ready-to-use `CliConfig`, aggregating errors if any
   *
   * @param cliConfig initial raw arguments
   * @return application config in case of success or
   *         non empty list of config errors in case of failure
   */
  private[config] def transform(cliConfig: RawConfig): ValidatedNel[ConfigError, CliConfig] = {
    val config = base64decode(cliConfig.config).flatMap(SnowplowConfig.parse).toValidatedNel
    val logkey = S3.Key.parse(cliConfig.logkey).leftMap(DecodingError).toValidatedNel
    val target = loadTarget(cliConfig.resolver, cliConfig.target)
    val steps = Step.constructSteps(cliConfig.skip.toSet, cliConfig.include.toSet)

    (target |@| config |@| logkey).map { case (t, c, l) => CliConfig(c, t, steps, l) }
  }

  /**
   * Safely decode base64 string into plain-text string
   *
   * @param string string, supposed to be base64-encoded
   * @return either error with full desciption or
   *         plain string in case of success
   */
  private def base64decode(string: String): Either[ConfigError, String] = {
    try {
      Right(new String(Base64.getDecoder.decode(string), StandardCharsets.UTF_8))
    } catch {
      case e: IllegalArgumentException =>
        Left(ParseError(e.getMessage))
    }
  }

  /**
   * Decode and validate base64-encoded storage target config JSON
   *
   * @param resolverConfigB64 base64-encoded Iglu resolver config
   * @param targetConfigB64 base64-encoded storage target JSON
   * @return either aggregated list of errors (from both resolver and target)
   *         or successfuly decoded storage target
   */
  private def loadTarget(resolverConfigB64: String, targetConfigB64: String) = {
    val json = base64decode(resolverConfigB64).flatMap(Common.safeParse).toValidatedNel
    val resolver = json.andThen(Compat.convertIgluResolver)
    val decodedTarget = base64decode(targetConfigB64).toValidatedNel
    (resolver |@| decodedTarget).tupled.andThen {
      case (r, t) => StorageTarget.parseTarget(r, t)
    }
  }
}


text:
extract:
	${tooldir}/ecore2bgf WTIP_SimpleClass.ecore grammar.bgf

include ../../Makefile.grammar


text:
CREATE TABLE IF NOT EXISTS `kwc_newsletter_subscribers` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `gender` enum('','female','male') NOT NULL,
  `title` varchar(255) NOT NULL,
  `firstname` varchar(255) NOT NULL,
  `lastname` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `format` enum('','html','text') NOT NULL,
  `subscribe_date` datetime NOT NULL,
  `unsubscribed` tinyint(1) NOT NULL,
  `activated` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `kwc_newsletter_subscribers_to_pool` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `subscriber_id` int(10) unsigned NOT NULL,
  `pool_id` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `subscriber_id` (`subscriber_id`),
  KEY `pool_id` (`pool_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;


text:
/*
Deployment script for ObservationsTest

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/

GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;

SET NUMERIC_ROUNDABORT OFF;

GO
:setvar DatabaseName "ObservationsTest"
:setvar DefaultFilePrefix "ObservationsTest"
:setvar DefaultDataPath "C:\Program Files\Microsoft SQL Server\MSSQL13.SAEON\MSSQL\DATA\"
:setvar DefaultLogPath "C:\Program Files\Microsoft SQL Server\MSSQL13.SAEON\MSSQL\DATA\"

GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
    BEGIN
        PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
        SET NOEXEC ON;
    END

GO
--IF (SELECT is_default
--    FROM   [$(DatabaseName)].[sys].[filegroups]
--    WHERE  [name] = N'Documents') = 0
--    BEGIN
--        ALTER DATABASE [$(DatabaseName)]
--            MODIFY FILEGROUP [Documents] DEFAULT;
--    END

GO
USE [$(DatabaseName)];

GO
/*
The column [dbo].[Sensor].[StationID] is being dropped, data loss could occur.
*/

--IF EXISTS (select top 1 1 from [dbo].[Sensor])
--    RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT

GO
PRINT N'Dropping [dbo].[Sensor].[IX_Sensor_StationID]...';

GO
DROP INDEX [IX_Sensor_StationID]
    ON [dbo].[Sensor];

GO
PRINT N'Dropping [dbo].[FK_Sensor_Station]...';

GO
ALTER TABLE [dbo].[Sensor] DROP CONSTRAINT [FK_Sensor_Station];

GO
PRINT N'Altering [dbo].[Sensor]...';

GO
ALTER TABLE [dbo].[Sensor] DROP COLUMN [StationID];

GO
PRINT N'Altering [dbo].[vDataLog]...';

GO
--> Changed 2.0.3 20160503 TimPN
--Renamed SensorProcedure to Sensor
--< Changed 2.0.3 20160503 TimPN
ALTER VIEW [dbo].[vDataLog]
AS

SELECT
d.ID,
d.ImportDate,

--> Added 2.0.17 20161128 TimPN
Site.Name SiteName,
Station.Name StationName,
Instrument.Name InstrumentName,
--< Added 2.0.17 20161128 TimPN
--> Removed 2.0.17 20161128 TimPN
--org.Name Organisation,
--ps.[Description] ProjectSite,
--st.Name StationName,
--< Removed 2.0.17 20161128 TimPN
d.SensorID,
Sensor.Name SensorName,
CASE
    WHEN d.SensorID is null then 1
    ELSE 0
END SensorInvalid,

d.ValueDate,
d.InvalidDateValue,
CASE
    WHEN ValueDate is null then 1
    ELSE 0
END DateValueInvalid,

d.InvalidTimeValue,
CASE
    WHEN InvalidTimeValue is not null then 1
    ELSE 0
END TimeValueInvalid,

CASE
    WHEN InvalidDateValue is null AND InvalidTimeValue IS NULL Then ValueDate
    WHEN ValueTime is not null then ValueTime
END ValueTime,

d.RawValue,
d.ValueText,
CASE
    WHEN d.RawValue is null then 1
    ELSE 0
END RawValueInvalid,

d.DataValue,
d.TransformValueText,
CASE
    WHEN d.DataValue is null then 1
    ELSE 0
END DataValueInvalid,

d.PhenomenonOfferingID,
CASE
    WHEN d.PhenomenonOfferingID is null then 1
    ELSE 0
END OfferingInvalid,

--> Changed 2.0.3 20160421 TimPN
--d.PhenonmenonUOMID,
d.PhenomenonUOMID,
--< Changed 2.0.3 20160421 TimPN
CASE
--> Changed 2.0.3 20160421 TimPN
--    WHEN d.PhenonmenonUOMID is null then 1
    WHEN d.PhenomenonUOMID is null then 1
--< Changed 2.0.3 20160421 TimPN
    ELSE 0
END UOMInvalid,

p.Name PhenomenonName,
o.Name OfferingName,
uom.Unit,

d.DataSourceTransformationID,
tt.Name Transformation,
d.StatusID,
s.Name [Status],
d.ImportBatchID,
d.RawFieldValue,
d.Comment

FROM DataLog d
--> Removed 2.0.17 20161128 TimPN
--LEFT JOIN Sensor sp
--    on d.SensorID = sp.ID
--LEFT JOIN Station st
--    on sp.StationID = st.ID
--LEFT JOIN ProjectSite ps
--    on st.ProjectSiteID = ps.ID
--LEFT JOIN Organisation org
--    on ps.OrganisationID = org.ID
--< Removed 2.0.17 20161128 TimPN
--> Added 2.0.17 20161128 TimPN
  inner join Sensor
    on (d.SensorID = Sensor.ID)
  inner join Instrument_Sensor
    on (Instrument_Sensor.SensorID = Sensor.ID) and
	   ((Instrument_Sensor.StartDate is null) or (d.ValueDate >= Instrument_Sensor.StartDate)) and
	   ((Instrument_Sensor.EndDate is null) or (d.ValueDate <= Instrument_Sensor.EndDate))
  inner join Instrument
    on (Instrument_Sensor.InstrumentID = Instrument.ID) and
	   ((Instrument.StartDate is null) or (d.ValueDate >= Instrument.StartDate )) and
	   ((Instrument.EndDate is null) or (d.ValueDate <= Instrument.EndDate))
  inner join Station_Instrument
    on (Station_Instrument.InstrumentID = Instrument.ID) and
	   ((Station_Instrument.StartDate is null) or (d.ValueDate >= Station_Instrument.StartDate)) and
	   ((Station_Instrument.EndDate is null) or (d.ValueDate <= Station_Instrument.EndDate))
  inner join Station
    on (Station_Instrument.StationID = Station.ID) and
	   ((Station.StartDate is null) or (Cast(d.ValueDate as Date) >= Cast(Station.StartDate as Date))) and
	   ((Station.EndDate is null) or (Cast(d.ValueDate as Date) <= Cast(Station.EndDate as Date)))
  inner join Site
    on (Station.SiteID = Site.ID) and
	   ((Site.StartDate is null) or  (Cast(d.ValueDate as Date) >= Cast(Site.StartDate as Date))) and
	   ((Site.EndDate is null) or  (Cast(d.ValueDate as Date) <= Cast(Site.EndDate as Date)))
--< Added 2.0.17 20161128 TimPN
LEFT JOIN PhenomenonOffering po
 ON d.PhenomenonOfferingID = po.ID
LEFT JOIN Phenomenon p
    on po.PhenomenonID = p.ID
LEFT JOIN Offering o
    on po.OfferingID = o.ID
LEFT JOIN PhenomenonUOM pu
--> Changed 2.0.3 20160421 TimPN
--    on d.PhenonmenonUOMID = pu.ID
    on d.PhenomenonUOMID = pu.ID
--< Changed 2.0.3 20160421 TimPN
LEFT JOIN UnitOfMeasure uom
    on pu.UnitOfMeasureID = uom.ID
LEFT JOIN DataSourceTransformation ds
    on d.DataSourceTransformationID = ds.ID
LEFT JOIN TransformationType tt
    on ds.TransformationTypeID = tt.ID
INNER JOIN [Status] s
    on d.StatusID = s.ID
GO
PRINT N'Altering [dbo].[vDataQuery]...';

GO
--> Changed 2.0.3 20160503 TimPN
--Renamed SensorProcedure to Sensor
--< Changed 2.0.3 20160503 TimPN
ALTER VIEW [dbo].[vDataQuery]
AS
--> Removed 2.0.17 20161128 TimPN
--SELECT     TOP (100) PERCENT NEWID()ID, Organisation.IDOrganisationID, Organisation.NameOrganisation,
--                      Organisation.DescriptionOrganisationDesc, ProjectSite.IDProjectSiteID, ProjectSite.NameProjectSite,
--                      ProjectSite.DescriptionProjectSiteDesc, Station.IDStationID, Station.NameStation, Station.DescriptionStationDesc,
--                      Sensor.IDSensorID, Sensor.NameSensor, Sensor.DescriptionSensorDesc,
--                      Phenomenon.IDPhenomenonID, Phenomenon.NamePhenomenon, Phenomenon.DescriptionPhenomenonDesc, Offering.IDOfferingID,
--                      Offering.NameOffering, Offering.DescriptionOfferingDesc
--FROM         Station INNER JOIN
--                      Sensor ON Sensor.StationID = Station.ID INNER JOIN
--                      Phenomenon ON Phenomenon.ID = Sensor.PhenomenonID INNER JOIN
--                      PhenomenonOffering ON PhenomenonOffering.PhenomenonID = Phenomenon.ID INNER JOIN
--                      Offering ON Offering.ID = PhenomenonOffering.OfferingID INNER JOIN
--                      ProjectSite ON ProjectSite.ID = Station.ProjectSiteID INNER JOIN
--                      Organisation ON Organisation.ID = ProjectSite.OrganisationID
--ORDER BY Organisation, ProjectSite, Station, Sensor, Phenomenon, Offering
--< Removed 2.0.17 20161128 TimPN
--> Added 2.0.17 20161128 TimPN
SELECT Top (100) Percent
  Site.ID SiteID, Site.Name SiteName, Site.Description SiteDesc,
  Station.ID StationID, Station.Name StationName, Station.Description StationDesc,
  Instrument.ID InstrumentID, Instrument.Name InstrumentName, Instrument.Description InstrumentDesc,
  Sensor.ID SensorID, Sensor.Name Sensor, Sensor.Description SensorDesc,
  Phenomenon.ID PhenomenonID, Phenomenon.Name Phenomenon, Phenomenon.Description PhenomenonDesc,
  Offering.ID OfferingID, Offering.Name Offering, Offering.Description OfferingDesc
FROM
	Sensor
	inner join Instrument_Sensor
	  on (Instrument_Sensor.SensorID = Sensor.ID)
	inner join Instrument
	  on (Instrument_Sensor.InstrumentID = Instrument.ID)
	inner join Station_Instrument
	  on (Station_Instrument.InstrumentID = Instrument.ID)
	inner join Station
	  on (Station_Instrument.StationID = Station.ID)
	inner join Site
	  on (Station.SiteID = Site.ID)
	INNER JOIN Phenomenon ON Phenomenon.ID = Sensor.PhenomenonID
	INNER JOIN PhenomenonOffering ON PhenomenonOffering.PhenomenonID = Phenomenon.ID
	INNER JOIN Offering ON Offering.ID = PhenomenonOffering.OfferingID
ORDER BY
  Site.Name, Station.Name, Instrument.Name, Sensor, Phenomenon, Offering
--< Added 2.0.17 20161128 TimPN
GO
PRINT N'Refreshing [dbo].[vInstrumentSensor]...';

GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;

GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vInstrumentSensor]';

GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;

GO
PRINT N'Altering [dbo].[vInventory]...';

GO
--> Changed 2.0.3 20160503 TimPN
--Renamed SensorProcedure to Sensor
--< Changed 2.0.3 20160503 TimPN
--> Removed 2.0.17 20161128 TimPN
--CREATE VIEW [dbo].[vInventory]
--AS
--Select
-- ps.Name Site,
-- s.Name Station,
-- sp.Name Sensor,
-- p.Name Phenomenon,
-- d.StartDate,
-- d.EndDate
--FROM Station s with (nolock)
-- INNER Join ProjectSite ps with (nolock)
-- on  ps.ID=  s.ProjectSiteID
--INNER Join Sensor sp with (nolock)
-- on s.ID = sp.StationID
--INNER Join Phenomenon p with (nolock)
-- on  sp.PhenomenonID = p.ID

--INNER JOIN
--(
-- SELECT SensorID,MIN(ValueDate) StartDate,MAX(ValueDate) EndDate
--  FROM Observation with (nolock)
-- Group By SensorID
--)d
--ON sp.ID = d.SensorID
--< Removed 2.0.17 20161128 TimPN
--> Added 2.0.17 20161128 TimPN
ALTER VIEW [dbo].[vInventory]
AS
Select
  Site.Name Site,
  Station.Name Station,
  Instrument.Name Instrument,
  Sensor.Name Sensor,
  p.Name Phenomenon,
  d.StartDate,
  d.EndDate
from
  Sensor
  INNER JOIN
  (
     SELECT SensorID,MIN(ValueDate) StartDate,MAX(ValueDate) EndDate
     FROM Observation
     Group By SensorID
  ) d
    ON (Sensor.ID = d.SensorID)
  inner join Instrument_Sensor
    on (Instrument_Sensor.SensorID = Sensor.ID) and
	   ((Instrument_Sensor.StartDate is null) or (d.StartDate >= Instrument_Sensor.StartDate)) and
	   ((Instrument_Sensor.EndDate is null) or (d.EndDate <= Instrument_Sensor.EndDate))
  inner join Instrument
    on (Instrument_Sensor.InstrumentID = Instrument.ID) and
	   ((Instrument.StartDate is null) or (d.StartDate >= Instrument.StartDate )) and
	   ((Instrument.EndDate is null) or (d.EndDate <= Instrument.EndDate))
  inner join Station_Instrument
    on (Station_Instrument.InstrumentID = Instrument.ID) and
	   ((Station_Instrument.StartDate is null) or (d.StartDate >= Station_Instrument.StartDate)) and
	   ((Station_Instrument.EndDate is null) or (d.EndDate >= Station_Instrument.EndDate))
  inner join Station
    on (Station_Instrument.StationID = Station.ID) and
	   ((Station.StartDate is null) or (Cast(d.StartDate as Date) >= Cast(Station.StartDate as Date))) and
	   ((Station.EndDate is null) or (Cast(d.EndDate as Date) >= Cast(Station.EndDate as Date)))
  inner join Site
    on (Station.SiteID = Site.ID) and
	   ((Site.StartDate is null) or  (Cast(d.StartDate as Date) >= Cast(Site.StartDate as Date))) and
	   ((Site.EndDate is null) or  (Cast(d.EndDate as Date) >= Cast(Site.EndDate as Date)))
  inner join Phenomenon p
   on (Sensor.PhenomenonID = p.ID )
--< Added 2.0.17 20161128 TimPN
GO
PRINT N'Altering [dbo].[vObservation]...';

GO
--> Changed 2.0.3 20160503 TimPN
--Renamed SensorProcedure to Sensor
--< Changed 2.0.3 20160503 TimPN
ALTER VIEW [dbo].[vObservation]
AS
--> Changed 2.0.16 20161107 TimPN
--> Changed 2.0.3 20160421 TimPN
--SELECT     o.ID, o.SensorID, o.PhenonmenonOfferingID, o.PhenonmenonUOMID, o.UserId, o.RawValue, o.DataValue, o.ImportBatchID, o.ValueDate,
--SELECT     o.ID, o.SensorID, o.PhenomenonOfferingID, o.PhenomenonUOMID, o.UserId, o.RawValue, o.DataValue, o.ImportBatchID, o.ValueDate,
--< Changed 2.0.3 20160421 TimPN
--                      sp.Code AS spCode, sp.Description AS spDesc, sp.Name AS spName, sp.Url AS spURL, sp.DataSchemaID, sp.DataSourceID, sp.PhenomenonID, sp.StationID,
--                      ph.Name AS phName, st.Name AS stName, ds.Name AS dsName, ISNULL(dschema.Name,dschema1.Name) AS dschemaName, offer.Name AS offName, offer.ID AS offID, ps.Name AS psName,
--                      ps.ID AS psID, org.Name AS orgName, org.ID AS orgID, uom.Unit AS uomUnit, uom.UnitSymbol AS uomSymbol, users.UserName,
--                      o.Comment
--FROM         dbo.Observation AS o INNER JOIN
--                      dbo.Sensor AS sp ON sp.ID = o.SensorID INNER JOIN
--                      dbo.Phenomenon AS ph ON ph.ID = sp.PhenomenonID INNER JOIN
--> Changed 2.0.3 20160421 TimPN
--                      dbo.PhenomenonOffering AS phOff ON phOff.ID = o.PhenonmenonOfferingID INNER JOIN
--                      dbo.PhenomenonOffering AS phOff ON phOff.ID = o.PhenomenonOfferingID INNER JOIN
--< Changed 2.0.3 20160421 TimPN
--                      dbo.Offering AS offer ON offer.ID = phOff.OfferingID INNER JOIN
--> Changed 2.0.3 20160421 TimPN
--                      dbo.PhenomenonUOM AS puom ON puom.ID = o.PhenonmenonUOMID INNER JOIN
--                      dbo.PhenomenonUOM AS puom ON puom.ID = o.PhenomenonUOMID INNER JOIN
--< Changed 2.0.3 20160421 TimPN
--                      dbo.Station AS st ON st.ID = sp.StationID INNER JOIN
--                      dbo.DataSource AS ds ON ds.ID = sp.DataSourceID LEFT JOIN
--                      dbo.DataSchema AS dschema1 ON dschema1.ID = ds.DataSchemaID LEFT JOIN
--                      dbo.DataSchema AS dschema ON dschema.ID = sp.DataSchemaID INNER JOIN
--                      dbo.ProjectSite AS ps ON ps.ID = st.ProjectSiteID INNER JOIN
--                      dbo.Organisation AS org ON org.ID = ps.OrganisationID INNER JOIN
--                      dbo.UnitOfMeasure AS uom ON uom.ID = puom.UnitOfMeasureID INNER JOIN
--                      dbo.aspnet_Users AS users ON users.UserId = o.UserId
SELECT
  o.ID, o.SensorID, o.PhenomenonOfferingID, o.PhenomenonUOMID, o.RawValue, o.DataValue, o.ImportBatchID, o.ValueDate, o.Comment,
  o.UserId, aspnet_Users.UserName,
  Status.Name StatusName,
  StatusReason.Name StatusReasonName,
  Offering.ID OfferingID,
  Offering.Name OfferingName,
  UnitOfMeasure.ID UnitOfMeasureID,
  UnitOfMeasure.Unit UnitOfMeasureUnit,
  UnitOfMeasure.UnitSymbol UnitOfMeasureSymbol,
  Sensor.Name SensorName,
  Phenomenon.ID PhenomenonID,
  Phenomenon.Name PhenomenonName,
  DataSource.ID DataSourceID,
  DataSource.Name DataSourceName,
  IsNull(SensorSchema.Name, DataSourceSchema.Name) DataSchemaName,
  Instrument.ID InstrumentID,
  Instrument.Name InstrumentName,
  Station.ID StationID,
  Station.Name StationName,
  Site.ID SiteID,
  Site.Name SiteName,
  Organisation.ID OrganisationID,
  Organisation.Name OrganisationName
FROM
  Observation o
  left join Status
    on (o.StatusID = Status.ID)
  left join StatusReason
    on (o.StatusReasonID = StatusReason.ID)
  inner join PhenomenonOffering
    on (o.PhenomenonOfferingID = PhenomenonOffering.ID)
  inner join Offering
    on (PhenomenonOffering.OfferingID = Offering.ID)
  inner join PhenomenonUOM
    on (o.PhenomenonUOMID = PhenomenonUOM.ID)
  inner join UnitOfMeasure
    on (PhenomenonUOM.UnitOfMeasureID = UnitOfMeasure.ID)
  inner join Sensor
    on (o.SensorID = Sensor.ID)
  inner join Phenomenon
    on (Sensor.PhenomenonID = Phenomenon.ID)
  left join DataSchema SensorSchema
    on (Sensor.DataSchemaID = SensorSchema.ID)
  inner join DataSource
    on (Sensor.DataSourceID = DataSource.ID)
  left join DataSchema DataSourceSchema
    on (DataSource.DataSchemaID = DataSourceSchema.ID)
  inner join Instrument_Sensor
    on (Instrument_Sensor.SensorID = Sensor.ID) and
	   ((Instrument_Sensor.StartDate is null) or (o.ValueDate >= Instrument_Sensor.StartDate)) and
	   ((Instrument_Sensor.EndDate is null) or (o.ValueDate <= Instrument_Sensor.EndDate))
  inner join Instrument
    on (Instrument_Sensor.InstrumentID = Instrument.ID) and
	   ((Instrument.StartDate is null) or (o.ValueDate >= Instrument.StartDate )) and
	   ((Instrument.EndDate is null) or (o.ValueDate <= Instrument.EndDate))
  inner join Station_Instrument
    on (Station_Instrument.InstrumentID = Instrument.ID) and
	   ((Station_Instrument.StartDate is null) or (o.ValueDate >= Station_Instrument.StartDate)) and
	   ((Station_Instrument.EndDate is null) or (o.ValueDate < Station_Instrument.EndDate))
  inner join Station
    on (Station_Instrument.StationID = Station.ID) and
	   ((Station.StartDate is null) or (Cast(o.ValueDate as Date) >= Cast(Station.StartDate as Date))) and
	   ((Station.EndDate is null) or (Cast(o.ValueDate as Date) <= Cast(Station.EndDate as Date)))
  inner join Site
    on (Station.SiteID = Site.ID) and
	   ((Site.StartDate is null) or  (Cast(o.ValueDate as Date) >= Cast(Site.StartDate as Date))) and
	   ((Site.EndDate is null) or  (Cast(o.ValueDate as Date) <= Cast(Site.EndDate as Date)))
  inner join Organisation_Site
    on (Organisation_Site.SiteID = Site.ID) and
	   ((Organisation_Site.StartDate is null) or (Cast(o.ValueDate as Date) >= Cast(Organisation_Site.StartDate as Date))) and
	   ((Organisation_Site.EndDate is null) or (Cast(o.ValueDate as Date) <= Cast(Organisation_Site.EndDate as Date)))
  inner join Organisation
    on (Organisation_Site.OrganisationID = Organisation.ID)
  inner join aspnet_Users
    on (o.UserId = aspnet_Users.UserId)
--< Changed 2.0.16 20161107 TimPN
GO
PRINT N'Refreshing [dbo].[vObservationsList]...';

GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;

GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vObservationsList]';

GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;

GO
PRINT N'Altering [dbo].[vSensor]...';

GO
--> Changed 2.0.3 20160503 TimPN
--Renamed SensorProcedure to Sensor
--< Changed 2.0.3 20160503 TimPN
--> Removed 2.0.17 20161128 TimPN
--CREATE VIEW [dbo].[vSensor]
--AS
--SELECT
--s.ID,
--s.Code,
--s.Name,
--s.[Description],
--s.Url,
--s.StationID,
--s.DataSourceID,
--s.PhenomenonID,
----> Added 2.0.7 20160609 TimPN
--  [Phenomenon].Name PhenomenonName,
----< Added 2.0.7 20160609 TimPN
--s.UserId,
--st.Name AS StationName,
--d.Name AS DataSourceName,
----> Added 20161110 TimPN
--s.DataSchemaID,
----< Added 20161110 TimPN
----> Changed 20161110 TimPN
----ds.[Description] DataSchemaName
--ds.[Name] DataSchemaName
----< Changed 20161110 TimPN
--FROM Sensor s
--INNER JOIN DataSource d
--    on s.DataSourceID = d.ID
--INNER JOIN Station st
--    on s.StationID = st.ID
--LEFT JOIN DataSchema ds
--    on s.DataSchemaID = ds.ID
----> Added 2.0.7 20160609 TimPN
--  inner join [Phenomenon]
--    on (s.PhenomenonID = [Phenomenon].ID)
----< Added 2.0.7 20160609 TimPN
--< Removed 2.0.17 20161128 TimPN
--> Added 2.0.17 20161128 TimPN
ALTER VIEW [dbo].[vSensor]
AS
SELECT
  Sensor.ID,
  Sensor.Code,
  Sensor.Name,
  Sensor.[Description],
  Sensor.Url,
  Sensor.DataSourceID,
  Sensor.PhenomenonID,
  [Phenomenon].Name PhenomenonName,
  Sensor.UserId,
  Site.Name Site,
  Station.Name Station,
  Instrument.Name Instrument,
  d.Name AS DataSourceName,
  Sensor.DataSchemaID,
  ds.[Name] DataSchemaName
FROM
  Sensor
  inner join Instrument_Sensor
	on (Instrument_Sensor.SensorID = Sensor.ID)
  inner join Instrument
	on (Instrument_Sensor.InstrumentID = Instrument.ID)
  inner join Station_Instrument
    on (Station_Instrument.InstrumentID = Instrument.ID)
  inner join Station
    on (Station_Instrument.StationID = Station.ID)
  inner join Site
    on (Station.SiteID = Site.ID)
INNER JOIN DataSource d
    on Sensor.DataSourceID = d.ID
LEFT JOIN DataSchema ds
    on Sensor.DataSchemaID = ds.ID
  inner join [Phenomenon]
    on (Sensor.PhenomenonID = [Phenomenon].ID)
--< Added 2.0.17 20161128 TimPN
GO
PRINT N'Altering [dbo].[vObservationRoles]...';

GO
--> Changed 2.0.3 20160503 TimPN
--Renamed SensorProcedure to Sensor
--< Changed 2.0.3 20160503 TimPN
ALTER VIEW [dbo].[vObservationRoles]
AS
--> Changed 2.0.16 20161107 TimPN
----> Changed 2.0.3 20160421 TimPN
----SELECT     vo.ID, vo.SensorID, vo.PhenonmenonOfferingID, vo.PhenonmenonUOMID, vo.UserId, vo.RawValue, vo.DataValue, vo.ImportBatchID, vo.ValueDate,
--SELECT     vo.ID, vo.SensorID, vo.PhenomenonOfferingID, vo.PhenomenonUOMID, vo.UserId, vo.RawValue, vo.DataValue, vo.ImportBatchID, vo.ValueDate,
----> Changed 2.0.3 20160421 TimPN
--                      vo.spCode, vo.spDesc, vo.spName, vo.spURL, vo.DataSchemaID, vo.DataSourceID, vo.PhenomenonID, vo.StationID, vo.phName, vo.stName, vo.dsName,
--                      vo.dschemaName, vo.offName, vo.offID, vo.psName, vo.psID, vo.orgName, vo.orgID, vo.uomUnit, vo.uomSymbol, vo.UserName,
--                      dr.DataSourceID AS Expr2, dr.DateStart, dr.DateEnd,
--                      ur.UserId AS Expr5, vo.Comment
--FROM         dbo.vObservation AS vo
--INNER JOIN
--(
-- SELECT dr.DataSourceID,
--        ur.UserId,
--        MIN(dr.DateStart) DateStart,
--        MAX(dr.DateEnd) DateEnd
-- FROM DataSourceRole dr
-- INNER JOIN    dbo.aspnet_Roles AS ar ON dr.RoleId = ar.RoleId INNER JOIN
--               dbo.aspnet_UsersInRoles AS ur ON ar.RoleId = ur.RoleId
-- GROUP By dr.DataSourceID,ur.UserId
--) dr
--ON vo.DataSourceID = dr.DataSourceID
--AND vo.ValueDate >= dr.DateStart AND vo.ValueDate <= dr.DateEnd
--INNER JOIN aspnet_Users ur
-- ON dr.UserId = ur.UserId
	Select
		vObservation.*, DataSourceRoles.RoleUserId
	from
		vObservation
		inner join
        (
			Select
				dsr.DataSourceID, aspnet_UsersInRoles.UserId RoleUserId, Min(dsr.DateStart) DateStart, Max(dsr.DateEnd) DateEnd
			from
				DataSourceRole dsr
			inner join aspnet_UsersInRoles
				on (dsr.RoleId = aspnet_UsersInRoles.RoleId)
			group by
				dsr.DataSourceID, aspnet_UsersInRoles.UserId
		) DataSourceRoles
		on (vObservation.DataSourceID = DataSourceRoles.DataSourceID) and
		   (vObservation.ValueDate >= DataSourceRoles.DateStart) and (vObservation.ValueDate <= DataSourceRoles.DateEnd)

--< Changed 2.0.16 20161107 TimPN
GO
PRINT N'Update complete.';

GO


text:
@interface LoopTypeTwoCell : CustomInfiniteLoopViewCell

@end


text:
Template.tmp_msg_line.msg = function(){
    return Messages.find({},{sort:{Sort_by_Date:-1}});
};
Template.tmp_msg_box.events({
    'submit' : function(){
        var jkt = moment().tz("Asia/Jakarta").format('MMMM Do YYYY, h:mm:ss a');
        console.log("dari update" + Session.get(Lookup.Session.activeUserName));
        var un = Session.get(Lookup.Session.activeUserName);
        Messages.insert({Username:un, Message: $('#tbxMsg').val(),Created_Date : jkt, Sort_by_Date : Date.now()});
        $('#tbxMsg').val("");
    }

});

Template.tmp_auth_signup.events({
    'submit' : function(){

        var newId =  Users.insert({Username : $('#tbxSignupUsername').val(), Email : $('#tbxSignupUserEmail').val(), Gender : $('#tbxSignupUserGender').val(), Password : $('#tbxSignupUserPwd').val()});
        console.log(newId);
        if(newId !== undefined){
            $('#modalSignUp').modal('hide');
        }
    }
});

Template.tmp_auth_signin.events({
    'submit' : function(){

        var us = Users.findOne({Username: $('#tbxSigninUsername').val(), Password : $('#tbxSigninUserPwd').val()});
        console.log(us.Username);
        console.log(us._id);
        if(us !== undefined){
            Session.set(Lookup.Session.isSessionActive, true);
            Session.set(Lookup.Session.activeUserId, us._id);
            Session.set(Lookup.Session.activeUserName, us.Username);
            $('#tbxMsg').removeAttr('disabled');
            $('#btnUpdate').removeAttr('disabled');
            $('#ddlStatusType').removeAttr('disabled');
            $('#modalSignIn').modal('hide');
        }
    }
});

//Template.tmp_navbar.Username = function(){
//    return Session.get(Lookup.Session.activeUser);
//}

Template.tmp_navbar.loggedInUser = function(){
    var us = Users.findOne(Session.get(Lookup.Session.activeUserId));
    console.log(this._id);
    console.log(this.Username);
    return us && us.Username;
}

Template.tmp_navbar.events({
    'click #btnSignOut' : function(e){
        e.preventDefault();
        location.reload();
    }
});

$( "form" ).live( "submit", function(e) {
    e.preventDefault();
});

Meteor.startup(function () {
    var isSessionActive = Session.get(Lookup.Session.isSessionActive);
    if(isSessionActive === undefined || isSessionActive === false){
        $('#tbxMsg').attr('disabled','disabled');
        $('#btnUpdate').attr('disabled','disabled');
        $('#ddlStatusType').attr('disabled','disabled');
    }
});


text:
<?php

namespace mdm\admin\models;

use Yii;
use yii\rbac\Item;
use yii\helpers\Json;

/**
 * This is the model class for table "tbl_auth_item".
 *
 * @property string $name
 * @property int $type
 * @property string $description
 * @property string $ruleName
 * @property string $data
 * @property Item $item
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 *
 * @since 1.0
 */
class AuthItem extends \yii\base\Model
{
    public $name;
    public $type;
    public $description;
    public $ruleName;
    public $data;

    /**
     * @var Item
     */
    private $_item;

    /**
     * Initialize object.
     *
     * @param Item  $item
     * @param array $config
     */
    public function __construct($item, $config = [])
    {
        $this->_item = $item;
        if ($item !== null) {
            $this->name = $item->name;
            $this->type = $item->type;
            $this->description = $item->description;
            $this->ruleName = $item->ruleName;
            $this->data = $item->data === null ? null : Json::encode($item->data);
        }
        parent::__construct($config);
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['ruleName'], 'in',
                'range' => array_keys(Yii::$app->authManager->getRules()),
                'message' => 'Rule not exists', ],
            [['name', 'type'], 'required'],
            [['name'], 'unique', 'when' => function () {
                return $this->isNewRecord || ($this->_item->name != $this->name);
            }],
            [['type'], 'integer'],
            [['description', 'data', 'ruleName'], 'default'],
            [['name'], 'string', 'max' => 64],
        ];
    }

    public function unique()
    {
        $authManager = Yii::$app->authManager;
        $value = $this->name;
        if ($authManager->getRole($value) !== null || $authManager->getPermission($value) !== null) {
            $message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
            $params = [
                'attribute' => $this->getAttributeLabel('name'),
                'value' => $value,
            ];
            $this->addError('name', Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'name' => Yii::t('rbac-admin', 'Name'),
            'type' => Yii::t('rbac-admin', 'Type'),
            'description' => Yii::t('rbac-admin', 'Description'),
            'ruleName' => Yii::t('rbac-admin', 'Rule Name'),
            'data' => Yii::t('rbac-admin', 'Data'),
        ];
    }

    /**
     * Check if is new record.
     *
     * @return bool
     */
    public function getIsNewRecord()
    {
        return $this->_item === null;
    }

    /**
     * Find role.
     *
     * @param string $id
     *
     * @return null|\self
     */
    public static function find($id)
    {
        $item = Yii::$app->authManager->getRole($id);
        if ($item !== null) {
            return new self($item);
        }

        return;
    }

    /**
     * Save role to [[\yii\rbac\authManager]].
     *
     * @return bool
     */
    public function save()
    {
        if ($this->validate()) {
            $manager = Yii::$app->authManager;
            if ($this->_item === null) {
                if ($this->type == Item::TYPE_ROLE) {
                    $this->_item = $manager->createRole($this->name);
                } else {
                    $this->_item = $manager->createPermission($this->name);
                }
                $isNew = true;
            } else {
                $isNew = false;
                $oldName = $this->_item->name;
            }
            $this->_item->name = $this->name;
            $this->_item->description = $this->description;
            $this->_item->ruleName = $this->ruleName;
            $this->_item->data = $this->data === null || $this->data === '' ? null : Json::decode($this->data);
            if ($isNew) {
                $manager->add($this->_item);
            } else {
                $manager->update($oldName, $this->_item);
            }

            return true;
        } else {
            return false;
        }
    }

    /**
     * Get item.
     *
     * @return Item
     */
    public function getItem()
    {
        return $this->_item;
    }

    /**
     * Get type name.
     *
     * @param mixed $type
     *
     * @return string|array
     */
    public static function getTypeName($type = null)
    {
        $result = [
            Item::TYPE_PERMISSION => 'Permission',
            Item::TYPE_ROLE => 'Role',
        ];
        if ($type === null) {
            return $result;
        }

        return $result[$type];
    }
}


text:
export PowerDivergenceTest, ChisqTest, MultinomialLRT

const Levels{T} = Tuple{UnitRange{T},UnitRange{T}}

function boundproportion(x::T) where T<:Real
    max(min(convert(Float64,x),1.0),0.0)
end

struct PowerDivergenceTest <: HypothesisTest
    lambda::Float64
    theta0::Vector{Float64}
    stat::Float64
    df::Int64
    observed::Matrix{Int64}
    n::Int64
    thetahat::Vector{Float64}

    expected::Matrix{Float64}
    residuals::Matrix{Float64}
    stdresiduals::Matrix{Float64}
end

#test name
function testname(x::PowerDivergenceTest)
    if x.lambda == 1
        return "Pearson's Chi-square Test"
    elseif x.lambda == 0
        return "Multinomial Likelihood Ratio Test"
    elseif x.lambda == -1
        return "Minimum Discrimination Information Test"
    elseif x.lambda == -2
        return "Neyman Modified Chi-square Test"
    elseif x.lambda == -0.5
        return "Freeman-Tukey Test"
    else
        return "Power Divergence Test"
    end
end

# parameter of interest: name, value under h0, point estimate
population_param_of_interest(x::PowerDivergenceTest) = ("Multinomial Probabilities", x.theta0, x.thetahat)
default_tail(test::PowerDivergenceTest) = :right

pvalue(x::PowerDivergenceTest; tail=:right) = pvalue(Chisq(x.df),x.stat; tail=tail)

"""
    confint(test::PowerDivergenceTest, alpha = 0.05; tail = :both, method = :sison_glaz)

Compute a confidence interval with coverage 1-`alpha` for multinomial proportions using
one of the following methods. Possible values for `method` are:

  - `:sison_glaz` (default): Sison-Glaz intervals
  - `:bootstrap`: Bootstrap intervals
  - `:quesenberry_hurst`: Quesenberry-Hurst intervals
  - `:gold`: Gold intervals (asymptotic simultaneous intervals)

# References

  * Agresti, Alan. Categorical Data Analysis, 3rd Edition. Wiley, 2013.
  * Sison, C.P and Glaz, J. Simultaneous confidence intervals and sample size determination
    for multinomial proportions. Journal of the American Statistical Association,
    90:366-369, 1995.
  * Quesensberry, C.P. and Hurst, D.C. Large Sample Simultaneous Confidence Intervals for
    Multinational Proportions. Technometrics, 6:191-195, 1964.
  * Gold, R. Z. Tests Auxiliary to ``χ^2`` Tests in a Markov Chain. Annals of
    Mathematical Statistics, 30:56-74, 1963.
"""
function StatsBase.confint(x::PowerDivergenceTest, alpha::Float64=0.05;
                           tail::Symbol=:both, method::Symbol=:sison_glaz, correct::Bool=true,
                           bootstrap_iters::Int64=10000, GC::Bool=true)
    check_alpha(alpha)

    m  = length(x.thetahat)

    if tail == :left
        i = StatsBase.confint(x, alpha*2,method=method, GC=GC)
        Tuple{Float64,Float64}[(0.0, i[j][2]) for j in 1:m]
    elseif tail == :right
        i = StatsBase.confint(x, alpha*2,method=method, GC=GC)
        Tuple{Float64,Float64}[(i[j][1], 1.0) for j in 1:m]
    elseif tail == :both
        if method == :gold
            ci_gold(x,alpha,correct=correct,GC=GC)
        elseif method == :sison_glaz
            ci_sison_glaz(x,alpha, skew_correct=correct)
        elseif method == :quesenberry_hurst
            ci_quesenberry_hurst(x,alpha,GC=GC)
        elseif method == :bootstrap
            ci_bootstrap(x,alpha,bootstrap_iters)
        else
            throw(ArgumentError("method=$(method) is invalid or not implemented yet"))
        end
    else
        throw(ArgumentError("tail=$(tail) is invalid"))
    end
end

# Bootstrap
function ci_bootstrap(x::PowerDivergenceTest,alpha::Float64, iters::Int64)
    m = mapslices(x -> quantile(x, [alpha / 2, 1 - alpha / 2]), rand(Multinomial(x.n, convert(Vector{Float64}, x.thetahat)),iters) / x.n, 2)
    Tuple{Float64,Float64}[(boundproportion(m[i,1]), boundproportion(m[i,2])) for i in 1:length(x.thetahat)]
end

# Quesenberry, Hurst (1964)
function ci_quesenberry_hurst(x::PowerDivergenceTest,alpha::Float64; GC::Bool=true)
    m  = length(x.thetahat)
    cv = GC ? quantile(Chisq(1), 1 - alpha / m) : quantile(Chisq(m - 1), 1 - alpha)

    u = (cv + 2*x.observed + sqrt.(cv * (cv + 4 * x.observed .* (x.n - x.observed) / x.n))) / (2*(x.n + cv))
    l = (cv + 2*x.observed - sqrt.(cv * (cv + 4 * x.observed .* (x.n - x.observed) / x.n))) / (2*(x.n + cv))
    Tuple{Float64,Float64}[(boundproportion(l[j]), boundproportion(u[j])) for j in 1:m]
end

# asymptotic simultaneous confidence interval
# Gold (1963)
function ci_gold(x::PowerDivergenceTest, alpha::Float64; correct::Bool=true, GC::Bool=true)
    m  = length(x.thetahat)
    cv = GC ? quantile(Chisq(1), 1 - alpha / 2m) : quantile(Chisq(m - 1), 1 - alpha / 2)

    u = [x.thetahat[j] + sqrt.(cv * x.thetahat[j] * (1 - x.thetahat[j]) / x.n) + ifelse(correct, inv(2x.n), 0) for j in 1:m]
    l = [x.thetahat[j] - sqrt.(cv * x.thetahat[j] * (1 - x.thetahat[j]) / x.n) - ifelse(correct, inv(2x.n), 0) for j in 1:m]
    Tuple{Float64,Float64}[ (boundproportion(l[j]), boundproportion(u[j])) for j in 1:m]
end

# Simultaneous confidence interval
# Sison, Glaz (1995)
# adapted from SAS macro by May, Johnson (2000)
function ci_sison_glaz(x::PowerDivergenceTest, alpha::Float64; skew_correct::Bool=true)
    k = length(x.thetahat)
    probn = inv(pdf(Poisson(x.n), x.n))

    c = 0
    p = 0.0
    p_old = 0.0
    m1, m2, m3, m4, m5 = zeros(k), zeros(k), zeros(k), zeros(k), zeros(k)
    mu = zeros(4)

    for c in 1:x.n
        #run truncpoi
        for i in 1:k
            lambda = x.observed[i]
            #run moments
            a = lambda + c
            b = max(lambda - c, 0)
            poislama = cdf(Poisson(lambda), a)
            poislamb = cdf(Poisson(lambda), b - 1)
            den = b > 0.0 ? poislama-poislamb : poislama

            for r in 1:4
                plar = cdf(Poisson(lambda), a - r)
                plbr = cdf(Poisson(lambda), b - r - 1)

                poisA = ifelse( (a - r) >= 0, poislama - plar, poislama)
                poisB = 0.0
                if  (b - r - 1) >= 0
                    poisB = poislamb - plbr
                end
                if (b - r - 1) < 0 && b - 1 >= 0
                    poisB = poislamb
                end
                if (b - r - 1) < 0 && (b - 1) < 0
                    poisB = 0.0
                end
                mu[r] = lambda^r * (1 - (poisA - poisB) / den)
            end
            # end of moments
            m1[i] = mu[1]
            m2[i] = mu[2] + mu[1] - mu[1]^2
            m3[i] = mu[3] + mu[2] * (3 - 3mu[1]) + (mu[1] - 3mu[1]^2 + 2mu[1]^3)
            m4[i] = mu[4] + mu[3] * (6 - 4mu[1]) + mu[2] * (7 - 12mu[1] + 6mu[1]^2) + mu[1] - 4mu[1]^2 + 6mu[1]^3 - 3mu[1]^4
            m5[i] = den
        end
        for i in 1:k
            m4[i] -= 3m2[i]^2
        end
        s1, s2, s3, s4 = sum(m1), sum(m2), sum(m3), sum(m4)
        z  = (x.n - s1) / sqrt(s2)
        g1 = s3 / s2^(3/2)
        g2 = s4 / s2^2

        poly = 1 + g1 * (z^3 - 3z) / 6 + g2 * (z^4 - 6z^2 + 3) / 24 + g1^2 * (z^6 - 15z^4 + 45z^2 - 15) / 72
        f = poly * exp(-z^2 / 2) / sqrt(2π)
        probx = prod(m5)

        p = probn * probx * f / sqrt(s2)
        # end of truncpoi

        p > 1 - alpha && p_old < 1 - alpha && break
        p_old = p
    end

    delta = (1 - alpha - p_old) / (p - p_old)
    out = zeros(k, 5)
    num = zeros(k, 1)

    c -= 1

    vol1 = 1
    vol2 = 1
    for i in 1:k
        num[i,1] = i
        cn = c / x.n
        onen = 1 / x.n
        out[i,1] = x.thetahat[i]

        out[i,2] = max(x.thetahat[i] - cn, 0)
        out[i,3] = min(x.thetahat[i] + cn + 2delta / x.n, 1)

        out[i,4] = max(x.thetahat[i] - cn - onen, 0)
        out[i,5] = min(x.thetahat[i] + cn + onen, 1)
    end
    if skew_correct
        return Tuple{Float64,Float64}[(boundproportion(out[i,2]), boundproportion(out[i,3])) for i in 1:k]
    else
        return Tuple{Float64,Float64}[(boundproportion(out[i,4]), boundproportion(out[i,5])) for i in 1:k]
    end
end

# power divergence statistic for testing goodness of fit
# Cressie and Read 1984; Read and Cressie 1988
# lambda    =  1: Pearson's Chi-square statistic
# lambda ->  0: Converges to Likelihood Ratio test stat
# lambda -> -1: Converges to minimum discrimination information statistic (Gokhale, Kullback 1978)
# lambda =  -2: Neyman Modified chi-squared statistic (Neyman 1949)
# lambda = -.5: Freeman-Tukey statistic (Freeman, Tukey 1950)

# Under regularity conditions, their asymptotic distributions are all the same (Drost 1989)
# Chi-squared null approximation works best for lambda near 2/3
"""
    PowerDivergenceTest(x[, y]; lambda = 1.0, theta0 = ones(length(x))/length(x))

Perform a Power Divergence test.

If `y` is not given and `x` is a matrix with one row or column, or `x` is a vector, then
a goodness-of-fit test is performed (`x` is treated as a one-dimensional contingency
table). In this case, the hypothesis tested is whether the population probabilities equal
those in `theta0`, or are all equal if `theta0` is not given.

If `x` is a matrix with at least two rows and columns, it is taken as a two-dimensional
contingency table. Otherwise, `x` and `y` must be vectors of the same length. The contingency
table is calculated using the `counts` function from the `StatsBase` package. Then the power
divergence test is conducted under the null hypothesis that the joint distribution of the
cell counts in a 2-dimensional contingency table is the product of the row and column
marginals.

Note that the entries of `x` (and `y` if provided) must be non-negative integers.

The power divergence test is given by
```math
    \\dfrac{2}{λ(λ+1)}\\sum_{i=1}^I \\sum_{j=1}^J n_{ij} \\left[(n_{ij}
    /\\hat{n}_{ij})^λ -1\\right]
```
where ``n_{ij}`` is the cell count in the ``i`` th row and ``j`` th column and ``λ`` is a
real number determining the nature of the test to be performed:

  * ``λ = 1``: equal to Pearson's chi-squared statistic
  * ``λ \\to 0``: converges to the likelihood ratio test statistic
  * ``λ \\to -1``: converges to the minimum discrimination information statistic
    (Gokhale and Kullback, 1978)
  * ``λ = -2``: equals Neyman modified chi-squared (Neyman, 1949)
  * ``λ = -1/2``: equals the Freeman-Tukey statistic (Freeman and Tukey, 1950).

Under regularity conditions, the asymptotic distributions are identical (see Drost et. al.
1989). The ``χ^2`` null approximation works best for ``λ`` near ``2/3``.

Implements: [`pvalue`](@ref), [`confint(::PowerDivergenceTest)`](@ref)

# References

  * Agresti, Alan. Categorical Data Analysis, 3rd Edition. Wiley, 2013.
"""
function PowerDivergenceTest(x::AbstractMatrix{T}; lambda::U=1.0, theta0::Vector{U} = ones(length(x))/length(x)) where {T<:Integer,U<:AbstractFloat}

    nrows, ncols = size(x)
    n = sum(x)

    #validate date
    (any(x .< 0) || any(!isfinite, x)) && throw(ArgumentError("all entries must be nonnegative and finite"))
    n == 0 && throw(ArgumentError("at least one entry must be positive"))
    (!isfinite(nrows) || !isfinite(ncols) || !isfinite(nrows*ncols)) && throw(ArgumentError("invalid number of rows or columns"))

    if nrows > 1 && ncols > 1
        rowsums = sum(x, 2)
        colsums = sum(x, 1)
        df = (nrows - 1) * (ncols - 1)
        thetahat = x ./ n
        xhat = rowsums * colsums / n
        theta0 = xhat / n
        V = Float64[(colsums[j]/n) * (rowsums[i]/n) * (1 - rowsums[i]/n) * (n - colsums[j]) for i in 1:nrows, j in 1:ncols]
    elseif nrows == 1 || ncols == 1
        df = length(x) - 1
        xhat = reshape(n * theta0, size(x))
        thetahat = x / n
        V = reshape(n * theta0 .* (1 - theta0), size(x))

        abs(1 - sum(theta0)) <= sqrt(eps()) || throw(ArgumentError("Probabilities must sum to one"))
    else
        throw(ArgumentError("Number of rows or columns must be at least 1"))
    end

    stat = 0
    if lambda == 0
        for i in 1:length(x)
            stat += x[i] * (log(x[i]) - log(xhat[i]))
        end
        stat *= 2
    elseif lambda == -1
        for i in 1:length(x)
            stat += xhat[i] * (log(xhat[i]) - log(x[i]))
        end
        stat *= 2
    else
        for i in 1:length(x)
            stat += x[i] * ((x[i] / xhat[i])^lambda - 1)
        end
        stat *= 2 / (lambda * (lambda + 1))
    end

    PowerDivergenceTest(lambda, vec(theta0), stat, df, x, n, vec(thetahat), xhat, (x - xhat) ./ sqrt.(xhat), (x - xhat) ./ sqrt.(V))
end

#convenience functions

#PDT
function PowerDivergenceTest(x::AbstractVector{T}, y::AbstractVector{T}, levels::Levels{T}; lambda::U=1.0) where {T<:Integer,U<:AbstractFloat}
    d = counts(x, y, levels)
    PowerDivergenceTest(d, lambda=lambda)
end

function PowerDivergenceTest(x::AbstractVector{T}, y::AbstractVector{T}, k::T; lambda::U=1.0) where {T<:Integer,U<:AbstractFloat}
    d = counts(x, y, k)
    PowerDivergenceTest(d, lambda=lambda)
end

PowerDivergenceTest(x::AbstractVector{T}; lambda::U=1.0, theta0::Vector{U} = ones(length(x))/length(x)) where {T<:Integer,U<:AbstractFloat} =
    PowerDivergenceTest(reshape(x, length(x), 1), lambda=lambda, theta0=theta0)

#ChisqTest
"""
    ChisqTest(x[, y][, theta0 = ones(length(x))/length(x)])

Perform a Pearson chi-squared test (equivalent to a [`PowerDivergenceTest`](@ref)
with ``λ = 1``).

If `y` is not given and `x` is a matrix with one row or column, or `x` is a vector, then
a goodness-of-fit test is performed (`x` is treated as a one-dimensional contingency
table). In this case, the hypothesis tested is whether the population probabilities equal
those in `theta0`, or are all equal if `theta0` is not given.

If `x` is a matrix with at least two rows and columns, it is taken as a two-dimensional
contingency table. Otherwise, `x` and `y` must be vectors of the same length. The contingency
table is calculated using `counts` function from the `StatsBase` package. Then the power
divergence test is conducted under the null hypothesis that the joint distribution of the
cell counts in a 2-dimensional contingency table is the product of the row and column
marginals.

Note that the entries of `x` (and `y` if provided) must be non-negative integers.

Implements: [`pvalue`](@ref), [`confint`](@ref)
"""
function ChisqTest(x::AbstractMatrix{T}) where T<:Integer
    PowerDivergenceTest(x, lambda=1.0)
end

function ChisqTest(x::AbstractVector{T}, y::AbstractVector{T}, levels::Levels{T}) where T<:Integer
    d = counts(x, y, levels)
    PowerDivergenceTest(d, lambda=1.0)
end

function ChisqTest(x::AbstractVector{T}, y::AbstractVector{T}, k::T) where T<:Integer
    d = counts(x, y, k)
    PowerDivergenceTest(d, lambda=1.0)
end

ChisqTest(x::AbstractVector{T}, theta0::Vector{U} = ones(length(x))/length(x)) where {T<:Integer,U<:AbstractFloat} =
    PowerDivergenceTest(reshape(x, length(x), 1), lambda=1.0, theta0=theta0)

#MultinomialLRT
"""
    MultinomialLRT(x[, y][, theta0 = ones(length(x))/length(x)])

Perform a multinomial likelihood ratio test (equivalent to a [`PowerDivergenceTest`](@ref)
with ``λ = 0``).

If `y` is not given and `x` is a matrix with one row or column, or `x` is a vector, then
a goodness-of-fit test is performed (`x` is treated as a one-dimensional contingency
table). In this case, the hypothesis tested is whether the population probabilities equal
those in `theta0`, or are all equal if `theta0` is not given.

If `x` is a matrix with at least two rows and columns, it is taken as a two-dimensional
contingency table. Otherwise, `x` and `y` must be vectors of the same length. The contingency
table is calculated using `counts` function from the `StatsBase` package. Then the power
divergence test is conducted under the null hypothesis that the joint distribution of the
cell counts in a 2-dimensional contingency table is the product of the row and column
marginals.

Note that the entries of `x` (and `y` if provided) must be non-negative integers.

Implements: [`pvalue`](@ref), [`confint`](@ref)
"""
function MultinomialLRT(x::AbstractMatrix{T}) where T<:Integer
    PowerDivergenceTest(x, lambda=0.0)
end

function MultinomialLRT(x::AbstractVector{T}, y::AbstractVector{T}, levels::Levels{T}) where T<:Integer
    d = counts(x, y, levels)
    PowerDivergenceTest(d, lambda=0.0)
end

function MultinomialLRT(x::AbstractVector{T}, y::AbstractVector{T}, k::T) where T<:Integer
    d = counts(x, y, k)
    PowerDivergenceTest(d, lambda=0.0)
end

MultinomialLRT(x::AbstractVector{T}, theta0::Vector{U} = ones(length(x))/length(x)) where {T<:Integer,U<:AbstractFloat} =
    PowerDivergenceTest(reshape(x, length(x), 1), lambda=0.0, theta0=theta0)

function show_params(io::IO, x::PowerDivergenceTest, ident="")
    println(io, ident, "Sample size:        $(x.n)")
    println(io, ident, "statistic:          $(x.stat)")
    println(io, ident, "degrees of freedom: $(x.df)")
    println(io, ident, "residuals:          $(vec(x.residuals))")
    println(io, ident, "std. residuals:     $(vec(x.stdresiduals))")
end


text:
'use strict';

var gulp = tars.packages.gulp;
var gutil = tars.packages.gutil;
var svgspritesheet = tars.packages.svgspritesheet;
var plumber = tars.packages.plumber;
var notifier = tars.helpers.notifier;

var staticFolderName = tars.config.fs.staticFolderName;
var imagesFolderName = tars.config.fs.imagesFolderName;

/**
 * Make sprite for svg and less for this sprite
 * Return pipe with less for sprite
 */
module.exports = function () {

    return gulp.task('css:make-sprite-for-svg', function (cb) {
        if (tars.config.useSVG) {
            return gulp.src('./dev/' + staticFolderName + '/' + imagesFolderName + '/minified-svg/*.svg')
                .pipe(plumber({
                    errorHandler: function (error) {
                        notifier.error('An error occurred while making fallback for svg.', error);
                        this.emit('end');
                    }
                }))
                .pipe(svgspritesheet({
                    cssPathSvg: '',
                    templateSrc: './markup/' + staticFolderName + '/stylus/sprite-generator-templates/stylus.svg-sprite.mustache',
                    templateDest: './markup/' + staticFolderName + '/stylus/sprites-stylus/svg-sprite.styl'
                }))
                .pipe(gulp.dest('./dev/' + staticFolderName + '/' + imagesFolderName + '/svg-sprite/sprite.svg'))
                .pipe(
                    notifier.success('Stylus for svg-sprite is ready')
                );
        } else {
            gutil.log('!SVG is not used!');
            cb(null);
        }
    });
};


text:
#
#
# /* Revised by Paul Mensonides (2002) */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_LOGICAL_HPP
# define BOOST_PREPROCESSOR_LOGICAL_HPP
#
# include <boost/preprocessor/logical/and.hpp>
# include <boost/preprocessor/logical/bitand.hpp>
# include <boost/preprocessor/logical/bitnor.hpp>
# include <boost/preprocessor/logical/bitor.hpp>
# include <boost/preprocessor/logical/bitxor.hpp>
# include <boost/preprocessor/logical/bool.hpp>
# include <boost/preprocessor/logical/compl.hpp>
# include <boost/preprocessor/logical/nor.hpp>
# include <boost/preprocessor/logical/not.hpp>
# include <boost/preprocessor/logical/or.hpp>
# include <boost/preprocessor/logical/xor.hpp>
#
# endif