text:
@interface ASPOSECWorksheetTestCase : XCTestCase
@property(nonatomic, strong) ASPOSECWorksheet *worksheet;
@end

@implementation ASPOSECWorksheetTestCase

- (void)setUp
{
    [super setUp];
    // Put setup code here; it will be run once, before the first test case.
    self.worksheet = [[ASPOSECWorksheet alloc] initWithFileName:@"myworkbook.xlsx" andWorksheetName:@"Sheet1"];
}

- (void)tearDown
{
    // Put teardown code here; it will be run once, after the last test case.
    [super tearDown];
}

- (void) testConvertWorksheetToImage
{
    NSString *localFilePath = [self.worksheet convertWorksheetToImage:@"jpeg" andSaveAs:@"Sheet1.jpeg"];
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:localFilePath];
    XCTAssertTrue(isFileExists, @"Failed to convert a worksheet to designated image format");
}

- (void) testAddANewWorksheet
{
    ASPOSECWorksheetResponse *worksheetResponse = [self.worksheet addANewWorksheet:@"Sheet2"];
    XCTAssertNil(worksheetResponse.message);
    XCTAssertNotNil(worksheetResponse.worksheets, @"Failed to add a new worksheet in a workbook");
}

- (void) testGetWorksheetCount
{
    ASPOSECWorksheetResponse *worksheetResponse = [self.worksheet getWorksheetCount];
    XCTAssertNil(worksheetResponse.message);
    XCTAssertTrue(worksheetResponse.worksheets.worksheetList.count, @"Failed to get worksheet count");
}

- (void) testHideAWorksheetInAWorkbook
{
    BOOL isWorksheetHideSuccessfully = [self.worksheet hideAWorksheetInAWorkbook];
    XCTAssertTrue(isWorksheetHideSuccessfully, @"Failed to hide a worksheet in a workbook");
}

- (void) testUnhideAWorksheetInAWorkbook
{
    BOOL isWorksheetUnHideSuccessfully = [self.worksheet unhideAWorksheetInAWorkbook];
    XCTAssertTrue(isWorksheetUnHideSuccessfully, @"Failed to unhide a worksheet in a workbook");
}

- (void) testMoveAWorksheetToANewLocationInAWorkbook
{
    ASPOSECWorksheetMovingRequest *worksheetMovingRequest = [[ASPOSECWorksheetMovingRequest alloc] init];
    worksheetMovingRequest.destinationWorksheet = @"Feb";
    worksheetMovingRequest.position = @"AFTER";
    BOOL isWorksheetMovedSuccessfully = [self.worksheet moveAWorksheetToANewLocationInAWorkbook:worksheetMovingRequest];
    XCTAssertTrue(isWorksheetMovedSuccessfully, @"Failed to move a worksheet to a new location in a workbook");
}

- (void) testRemoveAWorksheetFromAWorkbook
{
    BOOL isWorksheetRemovedSuccessfully = [self.worksheet removeAWorksheetFromAWorkbook];
    XCTAssertTrue(isWorksheetRemovedSuccessfully, @"Failed to remove a worksheet from a workbook");
}

- (void) testGetAutoshapeFromAWorksheet
{
    ASPOSECGetAutoshapeFromAWorksheetResponse *getAutoshapeResponse = [self.worksheet getAutoshapeFromAWorksheet:0];
    XCTAssertNil(getAutoshapeResponse.message);
    XCTAssertNotNil(getAutoshapeResponse.autoShape, @"Failed to get autoshape from a worksheet");
}

- (void) testGetCommentFromAWorksheet
{
    ASPOSECGetCommentFromAWorksheetResponse *getCommentFromAWorksheetResponse = [self.worksheet getCommentFromAWorksheet:@"A1"];
    XCTAssertNil(getCommentFromAWorksheetResponse.message);
    XCTAssertNotNil(getCommentFromAWorksheetResponse.comment, @"Failed to get a comment from a worksheet");
}

- (void) testGetValidationFromAWorksheet
{
    ASPOSECGetValidationFromAWorksheetResponse *getValidationResponse = [self.worksheet getValidationFromAWorksheet:0];
    XCTAssertNil(getValidationResponse.message);
    XCTAssertNotNil(getValidationResponse.validation, @"Failed to get validation from a worksheet");
}

- (void) testCalculateFormulaInAWorksheet
{
    ASPOSECCalculateFormulaResponse *calculateFormulaResponse = [self.worksheet calculateFormulaInAWorksheet:@"sum(b2:b6)"];
    XCTAssertNil(calculateFormulaResponse.message);
    XCTAssertNotNil(calculateFormulaResponse.value, @"Failed to calculate formula in a worksheet");
}

- (void) testSortWorksheetData
{
    ASPOSECDataSort *dataSort = [[ASPOSECDataSort alloc] init];
    dataSort.HasHeaders = NO;
    dataSort.CaseSensitive = NO;
    dataSort.SortLeftToRight = YES;

    ASPOSECSortKey *sort = [[ASPOSECSortKey alloc] init];
    sort.Key = 4;
    sort.SortOrder = @"descending";
    NSArray *KeyList = [NSArray arrayWithObject:sort];

    dataSort.KeyList = (NSArray<ASPOSECSortKey> *)KeyList;

    BOOL isWorksheetDataSortedSuccessfully = [self.worksheet sortWorksheetDataInCellArea:@"A1:C13" sortProperties:dataSort];
    XCTAssertTrue(isWorksheetDataSortedSuccessfully, @"Failed to sort worksheet data");
}

- (void) testGetColumnFromAWorksheet
{
    ASPOSECGetColumnFromAWorksheetResponse *columnFromAWorksheetResponse = [self.worksheet getColumnFromAWorksheet:0];
    XCTAssertNil(columnFromAWorksheetResponse.message);
    XCTAssertNotNil(columnFromAWorksheetResponse.column, @"Failed to get column from a worksheet");
}

- (void) testCopyAWorksheet
{
    BOOL isWorksheetCopiedSuccessfully = [self.worksheet copyAWorksheet:@"srcSheetName"];
    XCTAssertTrue(isWorksheetCopiedSuccessfully, @"Failed to copy a worksheet");
}

- (void) testRenameAWorksheet
{
    BOOL isWorksheetRenamedSuccessfully = [self.worksheet renameAWorksheet:@"newSheetName"];
    XCTAssertTrue(isWorksheetRenamedSuccessfully, @"Failed to rename a worksheet");
}

- (void) testUpdatePropertiesOfAWorksheet
{
    NSString *xmlData =
                        @"<Worksheet>"
                            "<Type>Worksheet</Type>"
                            "<Name>sheet1</Name>"
                            "<IsGridlinesVisible>True</IsGridlinesVisible>"
                            "<IsRowColumnHeadersVisible>True</IsRowColumnHeadersVisible>"
                            "<DisplayZeros>True</DisplayZeros>"
                            "<DisplayRightToLeft>True</DisplayRightToLeft>"
                            "<IsOutlineShown>True</IsOutlineShown>"
                            "<IsSelected>True</IsSelected>"
                            "<HasAutofilter>True</HasAutofilter>"
                            "<TransitionEvaluation>True</TransitionEvaluation>"
                            "<TransitionEntry>True</TransitionEntry>"
                            "<VisibilityType>Visible</VisibilityType>"
                            "<IsVisible>True</IsVisible>"
                            "<Index>0</Index>"
                            "<FirstVisibleRow>1</FirstVisibleRow>"
                            "<FirstVisibleColumn>1</FirstVisibleColumn>"
                            "<Zoom>80</Zoom>"
                            "<ViewType>PageBreakPreview</ViewType>"
                            "<IsPageBreakPreview>True</IsPageBreakPreview>"
                            "<IsRulerVisible>True</IsRulerVisible>"
                        "</Worksheet>";

    BOOL isWorksheetPropertiesUpdatedSuccessfully = [self.worksheet updatePropertiesOfAWorksheet:xmlData];
    XCTAssertTrue(isWorksheetPropertiesUpdatedSuccessfully, @"Failed to update properties of a worksheet");
}

- (void) testSetABackgroundImageOrWatermarkImageForAWorksheet
{
    BOOL isBackgroundImageSetSuccessfully = [self.worksheet setABackgroundImageOrWatermarkImageForAWorksheet:@"IMG_0004.PNG"];
    XCTAssertTrue(isBackgroundImageSetSuccessfully, @"Failed to set a background image or watermark image for a worksheet");
}

- (void) testFreezePanesInAWorksheet
{
    BOOL isPanesFreezedSuccessfully = [self.worksheet freezePanesInAWorksheet:1 columnNumber:1 freezedRows:1 freezedColumns:1];
    XCTAssertTrue(isPanesFreezedSuccessfully, @"Failed to freeze panes in a worksheet");
}

- (void) testUnFreezePanesInAWorksheet
{
    BOOL isPanesFreezedSuccessfully = [self.worksheet unFreezePanesInAWorksheet:1 columnNumber:1 freezedRows:1 freezedColumns:1];
    XCTAssertTrue(isPanesFreezedSuccessfully, @"Failed to unfreeze panes in a worksheet");
}

- (void) testDeleteABackgroundOrWatermarkImageOfAWorksheet
{
    BOOL isBackgroundImageDeletedSuccessfully = [self.worksheet deleteABackgroundOrWatermarkImageOfAWorksheet];
    XCTAssertTrue(isBackgroundImageDeletedSuccessfully, @"Failed to delete a background or watermark image of a worksheet");
}

@end

redpajama_set_name: RedPajamaGithub


text:
/*!
  Knockout paged extender v0.1.0
  By: Erik Schierboom (C) 2015
  License: Apache 2

  Adds the paged extender that can add paging functionality to an
  observable array.
*/
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['knockout'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('knockout'));
  } else {
    root.KnockoutElse = factory(root.ko);
  }
}(this, function (ko) {
// index.js
// --------
// paged extender.
// --------
"use strict";

// Utilities
function isObservableArray(value) {
  return ko.isObservable(value) && 'push' in value;
}

// This extender adds paging functionality to a Knockout observable array.
// The target must be an observable array, otherwise an error is thrown.
// The options parameter can contain two values: the page number and/or
// the page size:
// { pageNumber: the current page number, pageSize: the page size }
ko.extenders.paged = function(target, options) {

  if (!isObservableArray(target)) {
    throw new Error('The paged extender can only be applied to observable arrays.');
  }

  if (options && options['pageNumber'] < 1) {
    throw new Error('The page number must be greater than zero.');
  }

  if (options && options['pageSize'] < 1) {
    throw new Error('The page size must be greater than zero.');
  }

  target.pageNumber = ko.observable(options && options['pageNumber'] || 1);
  target.pageSize = ko.observable(options && options['pageSize'] || 50);

  target.pageItems = ko.pureComputed(function() {
    return target().slice(target.firstItemOnPage() - 1, target.lastItemOnPage());
  });

  target.pageCount = ko.pureComputed(function() {
    if (target.itemCount() <= 0) {
        return 1;
    }

    return Math.ceil(target.itemCount() / target.pageSize());
  });

  target.itemCount = ko.pureComputed(function() {
    return target().length;
  });

  target.firstItemOnPage = ko.pureComputed(function() {
    return (target.pageNumber() - 1) * target.pageSize() + 1;
  });

  target.lastItemOnPage = ko.pureComputed(function() {
    if (target.itemCount() == 0) {
      return 1;
    }

    return Math.min(target.pageNumber() * target.pageSize(), target.itemCount());
  });

  target.hasPreviousPage = ko.pureComputed(function() {
    return !target.isFirstPage();
  });

  target.hasNextPage = ko.pureComputed(function() {
    return !target.isLastPage();
  });

  target.isFirstPage = ko.pureComputed(function() {
    return target.pageNumber() == 1;
  });

  target.isLastPage = ko.pureComputed(function() {
    return target.pageNumber() == target.pageCount();
  });

  target.toNextPage = function() {
    if (target.hasNextPage()) {
      target.pageNumber(target.pageNumber() + 1);
    }
  };

  target.toPreviousPage = function() {
    if (target.hasPreviousPage()) {
      target.pageNumber(target.pageNumber() - 1);
    }
  };

  target.toFirstPage = function() {
    if (!target.isFirstPage()) {
      target.pageNumber(1);
    }
  };

  target.toLastPage = function() {
    if (!target.isLastPage()) {
      target.pageNumber(target.pageCount());
    }
  };

  return target;
};}));


text:
int dns_ip_version_indexer(const void *);
int dns_ip_version_iterator(char **label);
void dns_ip_version_reset(void);


text:
<?php
namespace Kahlan\Reporter;

class Reporter
{
    /**
     * Starting time.
     *
     * @var float
     */
    protected $_start = 0;

    /**
     * Total of items to reach.
     *
     * @var integer
     */
    protected $_total = 0;

    /**
     * Current position.
     *
     * @var integer
     */
    protected $_current = 0;

    /**
     * The Constructor.
     *
     * @param array $config The config array. Possible values are:
     *                      - `'start' _integer_: A microtime value.
     */
    public function __construct($config = [])
    {
        $defaults = ['start' => microtime(true)];
        $config += $defaults;
        $this->_start = $config['start'];
    }

    /**
     * Callback called before any specs processing.
     *
     * @param array $args The suite arguments.
     */
    public function start($args)
    {
        $this->_start = $this->_start ?: microtime(true);
        $this->_total = max(1, $args['total']);
    }

    /**
     * Callback called on a suite start.
     *
     * @param object $suite The suite instance.
     */
    public function suiteStart($suite = null)
    {
    }

    /**
     * Callback called on a spec start.
     *
     * @param object $spec The spec object of the whole spec.
     */
    public function specStart($spec = null)
    {
    }

    /**
     * Callback called on successful expect.
     *
     * @param object $log An expect log object.
     */
    public function passed($log = null)
    {
    }

    /**
     * Callback called on failure.
     *
     * @param object $log An expect log object.
     */
    public function failed($log = null)
    {
    }

    /**
     * Callback called after a spec execution.
     *
     * @param object $log The log object of the whole spec.
     */
    public function specEnd($log = null)
    {
        $this->_current++;
    }

    /**
     * Callback called after a suite execution.
     *
     * @param object $suite The suite instance.
     */
    public function suiteEnd($suite = null)
    {
    }

    /**
     * Callback called at the end of specs processing.
     *
     * @param object $summary The execution summary instance.
     */
    public function end($summary)
    {
    }

    /**
     * Callback called at the end of the process.
     *
     * @param object $summary The execution summary instance.
     */
    public function stop($summary)
    {
    }
}


text:
layout: page
title: Mr. Wei Fu submits his paper to ICSE'16
author: Admin
excerpt: Tuning for Software Analytics
---
Wei Fu submits his paper titled "Tuning for Software Analytics: is it Really Necessary?" to ICSE 2016. This is a joint work with [Dr. Xipeng Shen](http://people.engr.ncsu.edu/xshen5/). For more see [notes](/projects/2015/08/31/Tuning/).


text:
namespace android_webview {

namespace {

const void* const kRequestAlreadyHasJobDataKey = &kRequestAlreadyHasJobDataKey;

class StreamReaderJobDelegateImpl
    : public AndroidStreamReaderURLRequestJob::Delegate {
 public:
  StreamReaderJobDelegateImpl(
      scoped_ptr<AwWebResourceResponse> aw_web_resource_response)
      : aw_web_resource_response_(std::move(aw_web_resource_response)) {
    DCHECK(aw_web_resource_response_);
  }

  scoped_ptr<InputStream> OpenInputStream(JNIEnv* env,
                                          const GURL& url) override {
    return aw_web_resource_response_->GetInputStream(env);
  }

  void OnInputStreamOpenFailed(net::URLRequest* request,
                               bool* restart) override {
    *restart = false;
  }

  bool GetMimeType(JNIEnv* env,
                   net::URLRequest* request,
                   android_webview::InputStream* stream,
                   std::string* mime_type) override {
    return aw_web_resource_response_->GetMimeType(env, mime_type);
  }

  bool GetCharset(JNIEnv* env,
                  net::URLRequest* request,
                  android_webview::InputStream* stream,
                  std::string* charset) override {
    return aw_web_resource_response_->GetCharset(env, charset);
  }

  void AppendResponseHeaders(JNIEnv* env,
                             net::HttpResponseHeaders* headers) override {
    int status_code;
    std::string reason_phrase;
    if (aw_web_resource_response_->GetStatusInfo(
            env, &status_code, &reason_phrase)) {
      std::string status_line("HTTP/1.1 ");
      status_line.append(base::IntToString(status_code));
      status_line.append(" ");
      status_line.append(reason_phrase);
      headers->ReplaceStatusLine(status_line);
    }
    aw_web_resource_response_->GetResponseHeaders(env, headers);
  }

 private:
  scoped_ptr<AwWebResourceResponse> aw_web_resource_response_;
};

class ShouldInterceptRequestAdaptor
    : public AndroidStreamReaderURLRequestJob::DelegateObtainer {
 public:
  explicit ShouldInterceptRequestAdaptor(
      scoped_ptr<AwContentsIoThreadClient> io_thread_client)
      : io_thread_client_(std::move(io_thread_client)), weak_factory_(this) {}
   ~ShouldInterceptRequestAdaptor() override {}

  void ObtainDelegate(net::URLRequest* request,
                      const Callback& callback) override {
    callback_ = callback;
    io_thread_client_->ShouldInterceptRequestAsync(
        // The request is only used while preparing the call, not retained.
        request,
        base::Bind(&ShouldInterceptRequestAdaptor::WebResourceResponseObtained,
                   // The lifetime of the DelegateObtainer is managed by
                   // AndroidStreamReaderURLRequestJob, it might get deleted.
                   weak_factory_.GetWeakPtr()));
  }

 private:
  void WebResourceResponseObtained(
      scoped_ptr<AwWebResourceResponse> response) {
    if (response) {
      callback_.Run(make_scoped_ptr(
          new StreamReaderJobDelegateImpl(std::move(response))));
    } else {
      callback_.Run(nullptr);
    }
  }

  scoped_ptr<AwContentsIoThreadClient> io_thread_client_;
  Callback callback_;
  base::WeakPtrFactory<ShouldInterceptRequestAdaptor> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(ShouldInterceptRequestAdaptor);
};

scoped_ptr<AwContentsIoThreadClient> GetCorrespondingIoThreadClient(
    net::URLRequest* request) {
  if (content::ResourceRequestInfo::OriginatedFromServiceWorker(request))
    return AwContentsIoThreadClient::GetServiceWorkerIoThreadClient();

  int render_process_id, render_frame_id;
  if (!content::ResourceRequestInfo::GetRenderFrameForRequest(
      request, &render_process_id, &render_frame_id)) {
    return nullptr;
  }

  return AwContentsIoThreadClient::FromID(render_process_id, render_frame_id);
}

}  // namespace

AwRequestInterceptor::AwRequestInterceptor() {}

AwRequestInterceptor::~AwRequestInterceptor() {}

net::URLRequestJob* AwRequestInterceptor::MaybeInterceptRequest(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate) const {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);

  // MaybeInterceptRequest can be called multiple times for the same request.
  if (request->GetUserData(kRequestAlreadyHasJobDataKey))
    return nullptr;

  scoped_ptr<AwContentsIoThreadClient> io_thread_client =
      GetCorrespondingIoThreadClient(request);

  if (!io_thread_client)
    return nullptr;

  GURL referrer(request->referrer());
  if (referrer.is_valid() &&
      (!request->is_pending() || request->is_redirecting())) {
    request->SetExtraRequestHeaderByName(net::HttpRequestHeaders::kReferer,
                                         referrer.spec(), true);
  }
  request->SetUserData(kRequestAlreadyHasJobDataKey,
                       new base::SupportsUserData::Data());
  return new AndroidStreamReaderURLRequestJob(
      request, network_delegate,
      make_scoped_ptr(
          new ShouldInterceptRequestAdaptor(std::move(io_thread_client))),
      true);
}

}  // namespace android_webview


text:
from flask import redirect
from . import main
from ..api_client.error import APIError

@main.app_errorhandler(APIError)
def api_error_handler(e):
    return _render_error_page(e.status_code)

@main.app_errorhandler(404)
def page_not_found(e):
    return _render_error_page(404)

@main.app_errorhandler(410)
def page_not_found(e):
    return _render_error_page(410)

@main.app_errorhandler(500)
def internal_server_error(e):
    return _render_error_page(500)

@main.app_errorhandler(503)
def service_unavailable(e):
    return _render_error_page(503, e.response)

def _render_error_page(status_code, error_message=None):
    return redirect('/', 301)


text:
package com.starquestminecraft.bukkit.cardboardbox.utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.bukkit.potion.PotionEffect;

public class CardboardPotionEffect implements Serializable {

	private static final long serialVersionUID = 2101802611618393055L;
	private final CardboardPotionType effectType;
	private final int amplifier;
	private final int duration;

	public CardboardPotionEffect(PotionEffect effect) {

		this.effectType = new CardboardPotionType(effect.getType());
		this.amplifier = effect.getAmplifier();
		this.duration = effect.getDuration();
	}

	public PotionEffect unbox() {

		return new PotionEffect(this.effectType.unbox(), this.duration, this.amplifier, false);
	}

	public static List<CardboardPotionEffect> boxPotions(Collection<PotionEffect> effects) {

		List<CardboardPotionEffect> returnPotions = new ArrayList<CardboardPotionEffect>();
		for (PotionEffect e : effects) {
			returnPotions.add(new CardboardPotionEffect(e));
		}
		return returnPotions;
	}

	public static List<PotionEffect> unboxPotions(Collection<CardboardPotionEffect> effects) {

		List<PotionEffect> returnPotions = new ArrayList<PotionEffect>();
		for (CardboardPotionEffect e : effects) {
			returnPotions.add(e.unbox());
		}
		return returnPotions;
	}
}


text:
package org.zaproxy.zap.extension.ascanrulesBeta;

import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.InvalidRedirectLocationException;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.AbstractAppParamPlugin;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.Category;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.model.Tech;
import org.zaproxy.zap.model.TechSet;

/**
 * The SqlInjectionSqLiteScanRule identifies SQLite specific SQL Injection vulnerabilities using
 * SQLite specific syntax. If it doesn't use SQLite specific syntax, it belongs in the generic
 * SQLInjection class!
 *
 * @author 70pointer
 */
public class SqlInjectionSqLiteScanRule extends AbstractAppParamPlugin {

    // Some relevant notes about SQLite's support for various functions, which will affect what SQL
    // is valid,
    // and can be used to exploit each particular version :)
    // some of the functions noted here are *very* useful in exploiting the system hosting the
    // SQLite instance,
    // but I won't give the game away too easily. Go have a play!
    // 3.8.6       (2014-08-15) - hex integer literals supported, likely(X) supported, readfile(X)
    // and writefile(X,Y) supported (if extension loading enabled)
    // 3.8.3       (2014-02-03) - common table subexpressions supported ("WITH" keyword), printf
    // function supported
    // 3.8.1       (2013-10-17) - unlikely() and likelihood() functions supported
    // 3.8.0       (2013-08-26) - percentile() function added as loadable extension
    // 3.7.17      (2013-05-20) - new loadable extensions: including amatch, closure, fuzzer,
    // ieee754, nextchar, regexp, spellfix, and wholenumber
    // 3.7.16      (2013-03-18) - unicode(A) and char(X1,...,XN) supported
    // 3.7.15      (2012-12-12) - instr() supported
    // 3.6.8       (2009-01-12) - nested transactions supported
    // 3.5.7       (2008-03-17) - ALTER TABLE uses double-quotes instead of single-quotes for
    // quoting filenames (why filenames????).
    // 3.3.13      (2007-02-13) - randomBlob() and hex() supported
    // 3.3.8       (2006-10-09) - IF EXISTS on CREATE/DROP TRIGGER/VIEW
    // 3.3.7       (2006-08-12) - virtual tables, dynamically loaded extensions, MATCH operator
    // supported
    // 3.2.6       (2005-09-17) - COUNT(DISTINCT expr) supported
    // 3.2.3       (2005-08-21) - CAST operator, grave-accent quoting supported
    // 3.2.0       (2005-03-21) - ALTER TABLE ADD COLUMN supported
    // 3.1.0 ALPHA (2005-01-21) - ALTER TABLE ... RENAME TABLE, CURRENT_TIME, CURRENT_DATE, and
    // CURRENT_TIMESTAMP, EXISTS clause, correlated subqueries supported
    // 3.0.0 alpha (2004-06-18) - dropped support for COPY function, possibly added
    // sqlite_source_id(), replace() (which were not in 2.8.17)
    // 2.8.6       (2003-08-21) - date functions added
    // 2.8.5       (2003-07-22) - supports LIMIT on a compound SELECT statement
    // 2.8.1       (2003-05-16) - ATTACH and DETACH commands supported
    // 2.5.0       (2002-06-17) - Double-quoted strings interpreted as column names not text
    // literals,
    //                           SQL-92 compliant handling of NULLs, full SQL-92 join syntax and
    // LEFT OUTER JOINs supported
    // 2.4.7       (2002-04-06) - "select TABLE.*", last_insert_rowid() supported
    // 2.4.4       (2002-03-24) - CASE expressions supported
    // 2.4.0       (2002-03-10) - coalesce(), lower(), upper(), and random() supported
    // 2.3.3       (2002-02-18) - Allow identifiers to be quoted in square brackets, "CREATE TABLE
    // AS SELECT" supported
    // 2.2.0       (2001-12-22) - "SELECT rowid, * FROM table1" supported
    // 2.0.3       (2001-10-13) - &, |,~,<<,>>,round() and abs() supported
    // 2.0.1       (2001-10-02) - "expr NOT NULL", "expr NOTNULL" supported
    // 1.0.32      (2001-07-23) - quoted strings supported as table and column names in expressions
    // 1.0.28      (2001-04-04) - special column names ROWID, OID, and _ROWID_ supported (with
    // random values)
    // 1.0.4       (2000-08-28) - length() and substr() supported
    // 1.0         (2000-08-17) - covers lots of unversioned releases.  ||, fcnt(), UNION, UNION
    // ALL, INTERSECT, and EXCEPT, LIKE, GLOB, COPY supported

    private boolean doTimeBased = false;

    private int doTimeMaxRequests = 0;

    private boolean doUnionBased = false;
    private int doUnionMaxRequests = 0;

    /** SQLite one-line comment */
    public static final String SQL_ONE_LINE_COMMENT = "--";

    /**
     * SQLite specific time based injection strings, where each tries to cause a measurable delay
     */

    // Note: <<<<ORIGINALVALUE>>>> is replaced with the original parameter value at runtime in these
    // examples below
    // TODO: maybe add support for ')' after the original value, before the sleeps
    // Note: randomblob is supported from SQLite 3.3.13 (2007-02-13)
    //		case statement is supported from SQLite 2.4.4 (2002-03-24)
    private static String[] SQL_SQLITE_TIME_REPLACEMENTS = {
        // omitting original param
        "case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then 1 else 1 end ", // integer
        "' | case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then \"\" else \"\" end | '", // character/string (single quote)
        "\" | case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then \"\" else \"\" end | \"", // character/string (double quote)
        "case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then 1 else 1 end "
                + SQL_ONE_LINE_COMMENT, // integer
        "' | case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then \"\" else \"\" end "
                + SQL_ONE_LINE_COMMENT, // character/string (single quote)
        "\" | case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then \"\" else \"\" end "
                + SQL_ONE_LINE_COMMENT, // character/string (double quote)

        // with the original parameter
        "<<<<ORIGINALVALUE>>>> * case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then 1 else 1 end ", // integer
        "<<<<ORIGINALVALUE>>>>' | case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then \"\" else \"\" end | '", // character/string (single quote)
        "<<<<ORIGINALVALUE>>>>\" | case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then \"\" else \"\" end | \"", // character/string (double quote)
        "<<<<ORIGINALVALUE>>>> * case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then 1 else 1 end "
                + SQL_ONE_LINE_COMMENT, // integer
        "<<<<ORIGINALVALUE>>>>' | case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then \"\" else \"\" end "
                + SQL_ONE_LINE_COMMENT, // character/string (single quote)
        "<<<<ORIGINALVALUE>>>>\" | case randomblob(<<<<NUMBLOBBYTES>>>>) when not null then \"\" else \"\" end "
                + SQL_ONE_LINE_COMMENT, // character/string (double quote)
    };

    /** if the following errors occur during the attack, it's a SQL injection vuln */
    private Pattern errorMessagePatterns[] = {
        Pattern.compile(
                "no such function: randomblob",
                Pattern.CASE_INSENSITIVE) // this one is specific to the time-based attack
        // attempted here, and is indicative of SQLite versions <
        // 3.3.13, and >= 2.4.4 (because the CASE statement is
        // used)
        ,
        Pattern.compile("near \\\".+\\\": syntax error", Pattern.CASE_INSENSITIVE)
    };

    /** a template that defines how a UNION statement is built up, to find the SQLite version */
    private static String UNION_ATTACK_TEMPLATE =
            "<<<<VALUE>>>><<<<SYNTACTIC_PREVIOUS_STATEMENT_TYPE_CLOSER>>>><<<<SYNTACTIC_PREVIOUS_STATEMENT_CLAUSE_CLOSER>>>> <<<<UNIONSTATEMENT>>>> select <<<<SQLITE_VERSION_FUNCTION>>>><<<<UNIONADDITIONALCOLUMNS>>>><<<<SYNTACTIC_NEXT_STATEMENT_COMMENTER>>>>";

    private static String SYNTACTIC_PREVIOUS_STATEMENT_TYPE_CLOSERS[] = {
        "" // closing off an int parameter in the SQL statement
        ,
        "'" // closing off a char/string parameter in the SQL statement
        ,
        "\"" // closing off a string parameter in the SQL statement
    };
    private static String SYNTACTIC_PREVIOUS_STATEMENT_CLAUSE_CLOSERS[] = {
        "", ")", "))", ")))", "))))", ")))))"
    };
    private static String SYNTACTIC_UNION_STATEMENTS[] = {"UNION"
        // ,"UNION ALL"  Not necessary
    };
    private static String SQLITE_VERSION_FUNCTIONS[] = {
        "sqlite_version()" // string type - gets the version in the form of "3.7.16.2", for instance
        ,
        "sqlite_version()+0" // numeric type - SQLite does implicit casting to convert "3.7.16.2" to
        // 3.7 in numeric form.
        ,
        "sqlite_source_id()" // string type - this function was added in 3.6.18.  it gets the
        // version in the form of "2013-04-12 11:52:43
        // cbea02d93865ce0e06789db95fd9168ebac970c7"
        // there may not be much point in running this one, since it gives much the same info as
        // "sqlite_version()" and cannot be converted to an int.
        // maybe it's useful in the case that a WAF is detecting / blocking "sqlite_version()"
        // though?
    };
    private static String UNION_ADDITIONAL_COLUMNS[] = {
        "",
        ",null",
        ",null,null",
        ",null,null,null",
        ",null,null,null,null",
        ",null,null,null,null,null",
        ",null,null,null,null,null,null",
        ",null,null,null,null,null,null,null",
        ",null,null,null,null,null,null,null,null",
        ",null,null,null,null,null,null,null,null,null"
    };
    private static String SYNTACTIC_NEXT_STATEMENT_COMMENTER[] = {SQL_ONE_LINE_COMMENT
        // ,""				//this isn't useful at all
    };

    /** set depending on the attack strength / threshold */
    private long maxBlobBytes = 0;

    private long minBlobBytes = 100000;
    private long parseDelayDifference = 0;
    private long incrementalDelayIncreasesForAlert = 0;

    private char[] RANDOM_PARAMETER_CHARS = "abcdefghijklmnopqrstuvwyxz0123456789".toCharArray();

    /** for logging. */
    private static Logger log = Logger.getLogger(SqlInjectionSqLiteScanRule.class);

    /** determines if we should output Debug level logging */
    private boolean debugEnabled = log.isDebugEnabled();

    @Override
    public int getId() {
        return 40024;
    }

    @Override
    public String getName() {
        return Constant.messages.getString("ascanbeta.sqlinjection.sqlite.name");
    }

    @Override
    public boolean targets(TechSet technologies) {
        return technologies.includes(Tech.SQLite);
    }

    @Override
    public String getDescription() {
        return Constant.messages.getString("ascanbeta.sqlinjection.desc");
    }

    @Override
    public int getCategory() {
        return Category.INJECTION;
    }

    @Override
    public String getSolution() {
        return Constant.messages.getString("ascanbeta.sqlinjection.soln");
    }

    @Override
    public String getReference() {
        return Constant.messages.getString("ascanbeta.sqlinjection.refs");
    }

    @Override
    public void init() {
        if (this.debugEnabled) log.debug("Initialising");

        // set up what we are allowed to do, depending on the attack strength that was set.
        if (this.getAttackStrength() == AttackStrength.LOW) {
            doTimeBased = true;
            doTimeMaxRequests = 15;
            this.maxBlobBytes = 1000000000;
            doUnionBased = false;
            doUnionMaxRequests = 0;
        } else if (this.getAttackStrength() == AttackStrength.MEDIUM) {
            doTimeBased = true;
            doTimeMaxRequests = 35;
            this.maxBlobBytes = 1000000000;
            doUnionBased = false;
            doUnionMaxRequests = 0;
        } else if (this.getAttackStrength() == AttackStrength.HIGH) {
            doTimeBased = true;
            doTimeMaxRequests = 50;
            this.maxBlobBytes = 1000000000;
            doUnionBased = true;
            doUnionMaxRequests = 50;
        } else if (this.getAttackStrength() == AttackStrength.INSANE) {
            doTimeBased = true;
            doTimeMaxRequests = 500;
            this.maxBlobBytes = 1000000000;
            doUnionBased = true;
            doUnionMaxRequests = 5000;
        }

        // the allowable difference between a parse delay and an attack delay is controlled by the
        // threshold
        if (this.getAlertThreshold() == AlertThreshold.LOW) {
            parseDelayDifference = 100;
            incrementalDelayIncreasesForAlert = 1;
        } else if (this.getAlertThreshold() == AlertThreshold.MEDIUM) {
            parseDelayDifference = 200;
            incrementalDelayIncreasesForAlert = 2;
        } else if (this.getAlertThreshold() == AlertThreshold.HIGH) {
            parseDelayDifference = 400;
            incrementalDelayIncreasesForAlert = 3;
        }
    }

    /**
     * scans for SQL Injection vulnerabilities, using SQLite specific syntax. If it doesn't use
     * specifically SQLite syntax, it does not belong in here, but in TestSQLInjection
     */
    @Override
    public void scan(HttpMessage originalMessage, String paramName, String originalParamValue) {

        try {
            // the original message passed to us never has the response populated. fix that by
            // re-retrieving it..
            sendAndReceive(originalMessage, false); // do not follow redirects

            // Do time based SQL injection checks..
            // Timing Baseline check: we need to get the time that it took the original query, to
            // know if the time based check is working correctly..
            HttpMessage msgTimeBaseline = getNewMsg();
            long originalTimeStarted = System.currentTimeMillis();
            try {
                sendAndReceive(msgTimeBaseline);
            } catch (java.net.SocketTimeoutException e) {
                // to be expected occasionally, if the base query was one that contains some
                // parameters exploiting time based SQL injection?
                if (this.debugEnabled)
                    log.debug(
                            "The Base Time Check timed out on ["
                                    + msgTimeBaseline.getRequestHeader().getMethod()
                                    + "] URL ["
                                    + msgTimeBaseline.getRequestHeader().getURI().getURI()
                                    + "]");
            }
            long originalTimeUsed = System.currentTimeMillis() - originalTimeStarted;
            // if the time was very slow (because JSP was being compiled on first call, for
            // instance)
            // then the rest of the time based logic will fail.  Lets double-check for that scenario
            // by requesting the url again.
            // If it comes back in a more reasonable time, we will use that time instead as our
            // baseline.  If it come out in a slow fashion again,
            // we will abort the check on this URL, since we will only spend lots of time trying
            // request, when we will (very likely) not get positive results.
            if (originalTimeUsed > 5000) {
                long originalTimeStarted2 = System.currentTimeMillis();
                try {
                    sendAndReceive(msgTimeBaseline);
                } catch (java.net.SocketTimeoutException e) {
                    // to be expected occasionally, if the base query was one that contains some
                    // parameters exploiting time based SQL injection?
                    if (this.debugEnabled)
                        log.debug(
                                "Base Time Check 2 timed out on ["
                                        + msgTimeBaseline.getRequestHeader().getMethod()
                                        + "] URL ["
                                        + msgTimeBaseline.getRequestHeader().getURI().getURI()
                                        + "]");
                }
                long originalTimeUsed2 = System.currentTimeMillis() - originalTimeStarted2;
                if (originalTimeUsed2 > 5000) {
                    // no better the second time around.  we need to bale out.
                    if (this.debugEnabled)
                        log.debug(
                                "Both base time checks 1 and 2 for ["
                                        + msgTimeBaseline.getRequestHeader().getMethod()
                                        + "] URL ["
                                        + msgTimeBaseline.getRequestHeader().getURI().getURI()
                                        + "] are way too slow to be usable for the purposes of checking for time based SQL Injection checking.  We are aborting the check on this particular url.");
                    return;
                } else {
                    // phew.  the second time came in within the limits. use the later timing
                    // details as the base time for the checks.
                    originalTimeUsed = originalTimeUsed2;
                    originalTimeStarted = originalTimeStarted2;
                }
            }
            // end of timing baseline check

            int countTimeBasedRequests = 0;
            if (this.debugEnabled)
                log.debug(
                        "Scanning URL ["
                                + getBaseMsg().getRequestHeader().getMethod()
                                + "] ["
                                + getBaseMsg().getRequestHeader().getURI()
                                + "], ["
                                + paramName
                                + "] with value ["
                                + originalParamValue
                                + "] for SQL Injection");

            // SQLite specific time-based SQL injection checks
            boolean foundTimeBased = false;
            for (int timeBasedSQLindex = 0;
                    timeBasedSQLindex < SQL_SQLITE_TIME_REPLACEMENTS.length
                            && doTimeBased
                            && countTimeBasedRequests < doTimeMaxRequests
                            && !foundTimeBased;
                    timeBasedSQLindex++) {
                // since we have no means to create a deterministic delay in SQLite, we need to take
                // a different approach:
                // in each iteration, increase the number of random blobs for SQLite to create.  If
                // we can detect an increasing delay, we know
                // that the payload has been successfully injected.
                int numberOfSequentialIncreases = 0;
                String detectableDelayParameter = null;
                long detectableDelay = 0;
                String maxDelayParameter = null;
                long maxDelay = 0;
                HttpMessage detectableDelayMessage = null;
                long previousDelay = originalTimeUsed;
                boolean potentialTimeBasedSQLInjection = false;
                boolean timeExceeded = false;

                for (long numBlobsToCreate = minBlobBytes;
                        numBlobsToCreate <= this.maxBlobBytes
                                && !timeExceeded
                                && numberOfSequentialIncreases < incrementalDelayIncreasesForAlert;
                        numBlobsToCreate *= 10) {

                    HttpMessage msgDelay = getNewMsg();
                    String newTimeBasedInjectionValue =
                            SQL_SQLITE_TIME_REPLACEMENTS[timeBasedSQLindex].replace(
                                    "<<<<ORIGINALVALUE>>>>", originalParamValue);
                    newTimeBasedInjectionValue =
                            newTimeBasedInjectionValue.replace(
                                    "<<<<NUMBLOBBYTES>>>>", Long.toString(numBlobsToCreate));
                    setParameter(msgDelay, paramName, newTimeBasedInjectionValue);

                    if (this.debugEnabled)
                        log.debug(
                                "\nTrying '"
                                        + newTimeBasedInjectionValue
                                        + "'. The number of Sequential Increases already is "
                                        + numberOfSequentialIncreases);

                    // send it.
                    long modifiedTimeStarted = System.currentTimeMillis();
                    try {
                        sendAndReceive(msgDelay);
                        countTimeBasedRequests++;
                    } catch (java.net.SocketTimeoutException e) {
                        // to be expected occasionally, if the contains some parameters exploiting
                        // time based SQL injection
                        if (this.debugEnabled)
                            log.debug(
                                    "The time check query timed out on ["
                                            + msgTimeBaseline.getRequestHeader().getMethod()
                                            + "] URL ["
                                            + msgTimeBaseline.getRequestHeader().getURI().getURI()
                                            + "] on field: ["
                                            + paramName
                                            + "]");
                    }
                    long modifiedTimeUsed = System.currentTimeMillis() - modifiedTimeStarted;

                    // before we do the time based checking, first check for a known error message
                    // from the atatck, indicating a SQL injection vuln
                    for (Pattern errorMessagePattern : errorMessagePatterns) {
                        Matcher matcher =
                                errorMessagePattern.matcher(msgDelay.getResponseBody().toString());
                        boolean errorFound = matcher.find();
                        if (errorFound) {
                            // Likely an error based SQL Injection. Raise it
                            String extraInfo =
                                    Constant.messages.getString(
                                            "ascanbeta.sqlinjection.sqlite.alert.errorbased.extrainfo",
                                            errorMessagePattern);
                            // raise the alert
                            newAlert()
                                    .setConfidence(Alert.CONFIDENCE_MEDIUM)
                                    .setUri(getBaseMsg().getRequestHeader().getURI().getURI())
                                    .setParam(paramName)
                                    .setAttack(newTimeBasedInjectionValue)
                                    .setOtherInfo(extraInfo)
                                    .setEvidence(errorMessagePattern.toString())
                                    .setMessage(msgDelay)
                                    .raise();

                            if (this.debugEnabled)
                                log.debug(
                                        "A likely Error Based SQL Injection Vulnerability has been found with ["
                                                + msgDelay.getRequestHeader().getMethod()
                                                + "] URL ["
                                                + msgDelay.getRequestHeader().getURI().getURI()
                                                + "] on field: ["
                                                + paramName
                                                + "], by matching for pattern ["
                                                + errorMessagePattern.toString()
                                                + "]");
                            foundTimeBased =
                                    true; // yeah, I know. we found an error based, while looking
                            // for a time based. bale out anyways.
                            break; // out of the loop
                        }
                    }
                    // outta the time based loop..
                    if (foundTimeBased) break;

                    // no error message detected from the time based attack.. continue looking for
                    // time based injection point.

                    // cap the time we will delay by to 10 seconds
                    if (modifiedTimeUsed > 10000) timeExceeded = true;

                    boolean parseTimeEquivalent = false;
                    if (modifiedTimeUsed > previousDelay) {
                        if (this.debugEnabled)
                            log.debug(
                                    "The response time "
                                            + modifiedTimeUsed
                                            + " is > the previous response time "
                                            + previousDelay);
                        // in order to rule out false positives due to the increasing SQL parse time
                        // for longer parameter values
                        // we send a random (alphanumeric only) string value of the same length as
                        // the attack parameter
                        // we expect the response time for the SQLi attack to be greater than or
                        // equal to the response time for
                        // the random alphanumeric string parameter
                        // if this is not the case, then we assume that the attack parameter is not
                        // a potential SQL injection causing payload.
                        HttpMessage msgParseDelay = getNewMsg();
                        String parseDelayCheckParameter =
                                RandomStringUtils.random(
                                        newTimeBasedInjectionValue.length(),
                                        RANDOM_PARAMETER_CHARS);
                        setParameter(msgParseDelay, paramName, parseDelayCheckParameter);
                        long parseDelayTimeStarted = System.currentTimeMillis();
                        sendAndReceive(msgParseDelay);
                        countTimeBasedRequests++;
                        long parseDelayTimeUsed =
                                System.currentTimeMillis() - parseDelayTimeStarted;

                        // figure out if the attack delay and the (non-sql-injection) parse delay
                        // are within X ms of each other..
                        parseTimeEquivalent =
                                (Math.abs(modifiedTimeUsed - parseDelayTimeUsed)
                                        < this.parseDelayDifference);
                        if (this.debugEnabled)
                            log.debug(
                                    "The parse time a random parameter of the same length is "
                                            + parseDelayTimeUsed
                                            + ", so the attack and random parameter are "
                                            + (parseTimeEquivalent ? "" : "NOT ")
                                            + "equivalent (given the user defined attack threshold)");
                    }

                    if (modifiedTimeUsed > previousDelay && !parseTimeEquivalent) {

                        maxDelayParameter = newTimeBasedInjectionValue;
                        maxDelay = modifiedTimeUsed;

                        // potential for SQL injection, detectable with "numBlobsToCreate" random
                        // blobs being created..
                        numberOfSequentialIncreases++;
                        if (!potentialTimeBasedSQLInjection) {
                            if (log.isDebugEnabled())
                                log.debug(
                                        "Setting the Detectable Delay parameter to '"
                                                + newTimeBasedInjectionValue
                                                + "'");
                            detectableDelayParameter = newTimeBasedInjectionValue;
                            detectableDelay = modifiedTimeUsed;
                            detectableDelayMessage = msgDelay;
                        }
                        potentialTimeBasedSQLInjection = true;
                    } else {
                        // either no SQL injection, invalid SQL syntax, or timing difference is not
                        // detectable with "numBlobsToCreate" random blobs being created.
                        // keep trying with larger numbers of "numBlobsToCreate", since that's the
                        // thing we can most easily control and verify
                        // note also: if for some reason, an earlier attack with a smaller number of
                        // blobs indicated there might be a vulnerability
                        // then this case will rule that out if it was a fluke...
                        // the timing delay must keep increasing, as the number of blobs is
                        // increased.
                        potentialTimeBasedSQLInjection = false;
                        numberOfSequentialIncreases = 0;
                        detectableDelayParameter = null;
                        detectableDelay = 0;
                        detectableDelayMessage = null;
                        maxDelayParameter = null;
                        maxDelay = 0;
                        // do not break at this point, since we may simply need to keep increasing
                        // numBlobsToCreate to
                        // a point where we can detect the resulting delay
                    }
                    if (this.debugEnabled)
                        log.debug(
                                "Time Based SQL Injection test for "
                                        + numBlobsToCreate
                                        + " random blob bytes: ["
                                        + newTimeBasedInjectionValue
                                        + "] on field: ["
                                        + paramName
                                        + "] with value ["
                                        + newTimeBasedInjectionValue
                                        + "] took "
                                        + modifiedTimeUsed
                                        + "ms, where the original took "
                                        + originalTimeUsed
                                        + "ms");
                    previousDelay = modifiedTimeUsed;

                    // bale out if we were asked nicely
                    if (isStop()) {
                        if (this.debugEnabled) log.debug("Stopping the scan due to a user request");
                        return;
                    }
                } // end of for loop to increase the number of random blob bytes to create

                // the number of times that we could sequentially increase the delay by increasing
                // the "number of random blob bytes to create"
                // is the basis for the threshold of the alert.  In some cases, the user may want to
                // see a solid increase in delay
                // for say 4 or 5 iterations, in order to be confident the vulnerability exists.  In
                // other cases, the user may be happy with just 2 sequential increases...
                if (this.debugEnabled)
                    log.debug("Number of sequential increases: " + numberOfSequentialIncreases);
                if (numberOfSequentialIncreases >= this.incrementalDelayIncreasesForAlert) {
                    // Likely a SQL Injection. Raise it
                    String extraInfo =
                            Constant.messages.getString(
                                    "ascanbeta.sqlinjection.sqlite.alert.timebased.extrainfo",
                                    detectableDelayParameter,
                                    detectableDelay,
                                    maxDelayParameter,
                                    maxDelay,
                                    originalParamValue,
                                    originalTimeUsed);

                    newAlert()
                            .setConfidence(Alert.CONFIDENCE_MEDIUM)
                            .setUri(getBaseMsg().getRequestHeader().getURI().getURI())
                            .setParam(paramName)
                            .setAttack(detectableDelayParameter)
                            .setOtherInfo(extraInfo)
                            .setEvidence(extraInfo)
                            .setMessage(detectableDelayMessage)
                            .raise();

                    if (this.debugEnabled)
                        log.debug(
                                "A likely Time Based SQL Injection Vulnerability has been found with ["
                                        + detectableDelayMessage.getRequestHeader().getMethod()
                                        + "] URL ["
                                        + detectableDelayMessage
                                                .getRequestHeader()
                                                .getURI()
                                                .getURI()
                                        + "] on field: ["
                                        + paramName
                                        + "]");

                    // outta the time based loop..
                    foundTimeBased = true;
                    break;
                } // the user-define threshold has been exceeded. raise it.

                // outta the time based loop..
                if (foundTimeBased) break;

                // bale out if we were asked nicely
                if (isStop()) {
                    if (this.debugEnabled) log.debug("Stopping the scan due to a user request");
                    return;
                }
            } // for each time based SQL index
            // end of check for SQLite time based SQL Injection

            // TODO: fix this logic, cos it's broken already. it reports version 2.2 and 4.0..
            // (false positives ahoy)
            doUnionBased = false;

            // try to get the version of SQLite, using a UNION based SQL injection vulnerability
            // do this regardless of whether we already found a vulnerability using another
            // technique.
            if (doUnionBased) {
                int unionRequests = 0;
                // catch 3.0, 3.0.1, 3.0.1.1, 3.7.16.2, etc
                Pattern versionNumberPattern =
                        Pattern.compile(
                                "[0-9]{1}\\.[0-9]{1,2}\\.[0-9]{1,2}\\.[0-9]{1,2}|[0-9]{1}\\.[0-9]{1,2}\\.[0-9]{1,2}|[0-9]{1}\\.[0-9]{1,2}",
                                PATTERN_PARAM);
                String candidateValues[] = {"", originalParamValue};
                // shonky break label. labels the loop to break out of.  I believe I just finished a
                // sentence with a preposition too. Oh My.
                unionLoops:
                for (String sqliteVersionFunction : SQLITE_VERSION_FUNCTIONS) {
                    for (String statementTypeCloser : SYNTACTIC_PREVIOUS_STATEMENT_TYPE_CLOSERS) {
                        for (String statementClauseCloser :
                                SYNTACTIC_PREVIOUS_STATEMENT_CLAUSE_CLOSERS) {
                            for (String unionAdditionalColms : UNION_ADDITIONAL_COLUMNS) {
                                for (String nextStatementCommenter :
                                        SYNTACTIC_NEXT_STATEMENT_COMMENTER) {
                                    for (String statementUnionStatement :
                                            SYNTACTIC_UNION_STATEMENTS) {
                                        for (String value : candidateValues) {
                                            // are we out of lives yet?
                                            // TODO: fix so that the logic does not spin through the
                                            // loop headers to get out of all of the nested loops..
                                            // without using the shonky break to label logic
                                            if (unionRequests > doUnionMaxRequests) {
                                                break unionLoops;
                                            }

                                            String unionAttack = UNION_ATTACK_TEMPLATE;
                                            unionAttack =
                                                    unionAttack.replace(
                                                            "<<<<SQLITE_VERSION_FUNCTION>>>>",
                                                            sqliteVersionFunction);
                                            unionAttack =
                                                    unionAttack.replace(
                                                            "<<<<SYNTACTIC_PREVIOUS_STATEMENT_TYPE_CLOSER>>>>",
                                                            statementTypeCloser);
                                            unionAttack =
                                                    unionAttack.replace(
                                                            "<<<<SYNTACTIC_PREVIOUS_STATEMENT_CLAUSE_CLOSER>>>>",
                                                            statementClauseCloser);
                                            unionAttack =
                                                    unionAttack.replace(
                                                            "<<<<UNIONADDITIONALCOLUMNS>>>>",
                                                            unionAdditionalColms);
                                            unionAttack =
                                                    unionAttack.replace(
                                                            "<<<<SYNTACTIC_NEXT_STATEMENT_COMMENTER>>>>",
                                                            nextStatementCommenter);
                                            unionAttack =
                                                    unionAttack.replace(
                                                            "<<<<UNIONSTATEMENT>>>>",
                                                            statementUnionStatement);
                                            unionAttack =
                                                    unionAttack.replace("<<<<VALUE>>>>", value);

                                            if (log.isDebugEnabled())
                                                log.debug(
                                                        "About to try to determine the SQLite version with ["
                                                                + unionAttack
                                                                + "]");
                                            HttpMessage unionAttackMessage = getNewMsg();
                                            setParameter(
                                                    unionAttackMessage, paramName, unionAttack);
                                            sendAndReceive(unionAttackMessage);
                                            unionRequests++;

                                            // check the response for the version information..
                                            Matcher matcher =
                                                    versionNumberPattern.matcher(
                                                            unionAttackMessage
                                                                    .getResponseBody()
                                                                    .toString());
                                            while (matcher.find()) {
                                                String versionNumber = matcher.group();
                                                Pattern actualVersionNumberPattern =
                                                        Pattern.compile(
                                                                "\\Q" + versionNumber + "\\E",
                                                                PATTERN_PARAM);
                                                if (log.isDebugEnabled())
                                                    log.debug(
                                                            "Found a candidate SQLite version number '"
                                                                    + versionNumber
                                                                    + "'. About to look for the absence of '"
                                                                    + actualVersionNumberPattern
                                                                    + "' in the (re-created) original response body (of length "
                                                                    + originalMessage
                                                                            .getResponseBody()
                                                                            .toString()
                                                                            .length()
                                                                    + ") to validate it");

                                                // if the version number was not in the original*
                                                // response, we will call it..
                                                Matcher matcherVersionInOriginal =
                                                        actualVersionNumberPattern.matcher(
                                                                originalMessage
                                                                        .getResponseBody()
                                                                        .toString());
                                                if (!matcherVersionInOriginal.find()) {
                                                    // we have the SQLite version number..
                                                    if (log.isDebugEnabled())
                                                        log.debug(
                                                                "We found SQLite version ["
                                                                        + versionNumber
                                                                        + "]");

                                                    String extraInfo =
                                                            Constant.messages.getString(
                                                                    "ascanbeta.sqlinjection.sqlite.alert.versionnumber.extrainfo",
                                                                    versionNumber);
                                                    newAlert()
                                                            .setConfidence(Alert.CONFIDENCE_MEDIUM)
                                                            .setName(
                                                                    getName()
                                                                            + " - "
                                                                            + versionNumber)
                                                            .setUri(
                                                                    getBaseMsg()
                                                                            .getRequestHeader()
                                                                            .getURI()
                                                                            .getURI())
                                                            .setParam(paramName)
                                                            .setAttack(unionAttack)
                                                            .setOtherInfo(extraInfo)
                                                            .setEvidence(versionNumber)
                                                            .setMessage(unionAttackMessage)
                                                            .raise();
                                                    break unionLoops;
                                                }
                                            }
                                            // bale out if we were asked nicely
                                            if (isStop()) {
                                                if (this.debugEnabled)
                                                    log.debug(
                                                            "Stopping the scan due to a user request");
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } // end of doUnionBased

        } catch (InvalidRedirectLocationException | UnknownHostException | URIException e) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to send HTTP message, cause: " + e.getMessage());
            }
        } catch (Exception e) {
            // Do not try to internationalise this.. we need an error message in any event..
            // if it's in English, it's still better than not having it at all.
            log.error(
                    "An error occurred checking a url for SQLite SQL Injection vulnerabilities", e);
        }
    }

    @Override
    public int getRisk() {
        return Alert.RISK_HIGH;
    }

    @Override
    public int getCweId() {
        return 89;
    }

    @Override
    public int getWascId() {
        return 19;
    }
}


text:
<!doctype html>
Click me


text:
/**
* //Package for Calculator.
*
* @author Alex Karpov (mailto:karpov_aleksey@mail.ru)
* @version $Id$
* @since 0.1
*/
package ru.job4j.calculator;


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.ComponentModel;
using Microsoft.CodeAnalysis.Tags;

namespace Microsoft.CodeAnalysis.Completion
{
    /// <summary>
    /// The set of well known tags used for the <see cref="CompletionItem.Tags"/> property.
    /// These tags influence the presentation of items in the list.
    /// </summary>
    [Obsolete("Use Microsoft.CodeAnalysis.Tags.WellKnownTags instead.")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class CompletionTags
    {
        // accessibility
        public const string Public = WellKnownTags.Public;
        public const string Protected = WellKnownTags.Protected;
        public const string Private = WellKnownTags.Private;
        public const string Internal = WellKnownTags.Internal;

        // project elements
        public const string File = WellKnownTags.File;
        public const string Project = WellKnownTags.Project;
        public const string Folder = WellKnownTags.Folder;
        public const string Assembly = WellKnownTags.Assembly;

        // language elements
        public const string Class = WellKnownTags.Class;
        public const string Constant = WellKnownTags.Constant;
        public const string Delegate = WellKnownTags.Delegate;
        public const string Enum = WellKnownTags.Enum;
        public const string EnumMember = WellKnownTags.EnumMember;
        public const string Event = WellKnownTags.Event;
        public const string ExtensionMethod = WellKnownTags.ExtensionMethod;
        public const string Field = WellKnownTags.Field;
        public const string Interface = WellKnownTags.Interface;
        public const string Intrinsic = WellKnownTags.Intrinsic;
        public const string Keyword = WellKnownTags.Keyword;
        public const string Label = WellKnownTags.Label;
        public const string Local = WellKnownTags.Local;
        public const string Namespace = WellKnownTags.Namespace;
        public const string Method = WellKnownTags.Method;
        public const string Module = WellKnownTags.Module;
        public const string Operator = WellKnownTags.Operator;
        public const string Parameter = WellKnownTags.Parameter;
        public const string Property = WellKnownTags.Property;
        public const string RangeVariable = WellKnownTags.RangeVariable;
        public const string Reference = WellKnownTags.Reference;
        public const string Structure = WellKnownTags.Structure;
        public const string TypeParameter = WellKnownTags.TypeParameter;

        // other
        public const string Snippet = WellKnownTags.Snippet;
        public const string Error = WellKnownTags.Error;
        public const string Warning = WellKnownTags.Warning;
        internal const string StatusInformation = WellKnownTags.StatusInformation;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%5p] %d{HH:mm:ss} %c:%M(line:%L) - %m%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="egovframework" level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
        </Logger>
        <Logger name="ion" level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
        </Logger>
		  <!-- log SQL with timing information, post execution -->
	    <logger name="jdbc.sqltiming" level="INFO" additivity="false">
	        <appender-ref ref="console" />
	    </logger>
	    <logger name="org.springframework" level="INFO" additivity="false">
	        <appender-ref ref="console" />
	    </logger>

		<logger name="java.sql.Connection" level="DEBUG" additivity="false">
			<appender-ref ref="console"/>
		</logger>
		<logger name="java.sql.Statement" level="DEBUG" additivity="false">
			<appender-ref ref="console"/>
		</logger>
		<logger name="java.sql.PreparedStatement" level="DEBUG" additivity="false">
			<appender-ref ref="console"/>
		</logger>
		<logger name="java.sql.ResultSet" level="DEBUG" additivity="false">
			<appender-ref ref="console"/>
		</logger>

        <Root level="ERROR">
            <AppenderRef ref="console" />
        </Root>
    </Loggers>
</Configuration>


text:
from __future__ import absolute_import, unicode_literals

from pipeline.compressors import CompressorBase

from yepes.utils.minifier import minify_css, minify_js

class Minifier(CompressorBase):
    """
    A compressor that utilizes ``yepes.utils.minifier.minify_css()`` for CSS
    files and ``yepes.utils.minifier.minify_js()`` for JS files.
    """
    def compress_css(self, css):
        return minify_css(css)

    def compress_js(self, js):
        return minify_js(js)


text:
#pragma once
#include <aws/clouddirectory/CloudDirectory_EXPORTS.h>
#include <aws/core/Region.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{

namespace CloudDirectory
{
namespace CloudDirectoryEndpoint
{
AWS_CLOUDDIRECTORY_API Aws::String ForRegion(const Aws::String& regionName, bool useDualStack = false);
} // namespace CloudDirectoryEndpoint
} // namespace CloudDirectory
} // namespace Aws


text:
using namespace std;

int main()
{
    cout << "OrbitProlog size: " << sizeof( OrbitProlog ) << endl;
    cout << "OrbitEpilog size: " << sizeof( OrbitEpilog ) << endl;

    MH_Test();

    system("pause");
    return 0;
}


text: Some useful script...


text:
4.2.0 - 06 May 2016

- Added events dispatching before and after running statements and stacks

4.1.1 - 06 May 2016

- Added `registerExistingConnection` in ConnectionManager

4.1.0 - 02 May 2016

- Added `updateStatistics()` method on the ResultCollection for combined statistics of stacks, transactions, etc..

4.0.2 - 28 Apr 2016

- Fixed a bug where relationships deleted count was not hydrated in the http result update statistics

4.0.1 - 27 Apr 2016

- Fixed a bug where `nodeValue` was using a hardcoded identifier [8bf11473c9870c2423de2763622d2674b97216db](8bf11473c9870c2423de2763622d2674b97216db)

4.0.0 - 25 Apr 2016

Initial 4.0 release for support with Neo4j 3.0


text:
var args = arguments[0] || {};
var depts = Alloy.Collections.Dept;
var school = args.school;

fetchDepts(school);
$.schoolLabel.setText(school.get("SOC_SCHOOL_DESCRIPTION"));

//get departments of clicked school
function fetchDepts(school){
	if (school && (school.get("SOC_DEPARTMENT_CODE") == undefined || school.get("SOC_DEPARTMENT_CODE").length == 0)) {
		//refetch the school so that the department can be get
		school.fetch({
			success : function() {
				console.log("get department");
				depts.add(school.get("SOC_DEPARTMENT_CODE"));
			}
		});
	}
	depts.trigger("change");
}

function filter(depts){
	return school ? depts.where({SOC_SCHOOL_CODE:school.get("SOC_SCHOOL_CODE")}) : depts.models;
}

function showCourseList(e){
	//get department model
	var filteredDepts = filter(depts);
	var model = filteredDepts[e.index];
	if(model){
		var args = {
			dept:model
		};
		Titanium.UI.currentTab.open(Alloy.createController("courseList",args).getView());
		//Alloy.createController("courseList",args).getView().open();
	}
}

function close(){
	$.destroy();
}


text:
TinyPub, is a Ruby Sinatra  application written by CrossRef in order to demonstrate how a publisher site should interact with the Text and Data API and Click-Through Service.

For more information on how Text and Data Mining, see [https://apps.crossref.org/docs/tdm](https://apps.crossref.org/docs/tdm). For more information about the Click-Through Service see [https://apps.crossref.org/docs/clickthrough](https://apps.crossref.org/docs/clickthrough)

Version 1.0 of the application was released in July 2013 and has been updated to be compatible with Ruby 1.9.3, Sinatra 1.4.2. It uses sqlite3 as the database backend.

## Installation

Tinypub is a typical Sinatra web application with the following requirements:

* Ruby 1.9.3
* sqlite3 1.7.9

#### Ruby 1.9
ALM requires Ruby 1.9.3. Not all Linux distributions include Ruby 1.9 as a standard install, which makes it more difficult than it should be. [RVM][rvm] and [Rbenv][rbenv] are Ruby version management tools for installing Ruby 1.9. Unfortunately they also introduce additional dependencies.

#### Installation Options
The easiest way to install the application is to use the bundler gem. After the bundler gem is installed, you should just be able to CD to the source directlty and execute:

    bundle install --path vendor/bundle

Copy the sample file config/__application.yml to config/application.yml and adjust the settings to match your environment.

After which running the following should start the server.

    bundle exec rackup

#### Running under Apache/Passenger

If you want to run the application behind Apache using passenger, there is a sample virtual host file in the config directory.

### Note that, to use HTTPS you can easily create a self-signed certificate as follows:

    sudo /usr/sbin/make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/server_name.pem

After which you must direct your above virtual host file to the certificate you just created.

#### Verifying that things are working

You should simply be able to connect to the home page of your virtual host to verify that the site is working and the settings are correct.

#### Add IP addresses for testing subscriptions

To test the system with "subscriptions" enabled, remember that you will need to add the IP address of the client to the access control system. You can do this using the add_subscriber script in the tools folder like this:

    tools/add_subscriber "Name of subscriber" xxx.xxx.xxx.xxx


text:
package net.chwthewke.passman
package engine

import cats.Eq
import java.util.UUID

import cats.Semigroup

sealed abstract class EngineError(val message: String)

abstract class ServiceError(override val message: String) extends EngineError(message)

object ServiceError {
  def unapply(arg: ServiceError): Option[String] = Some(arg.message)
}

case class ExcessiveDerivedBits(required: Int, available: Int)
    extends ServiceError(s"can produce $available bits but $required required")

case class InvalidOutputBase(base: Int) extends ServiceError(s"invalid output character space size of $base")

case class UnknownGeneratorId(id: UUID) extends ServiceError(s"unknown generator id $id")

case class RequestError(override val message: String) extends EngineError(message)

object RequestError {
  implicit val requestErrorSemigroup: Semigroup[RequestError] =
    (x: RequestError, y: RequestError) => RequestError(s"${x.message}, ${y.message}")
}

object NegativeVariant extends RequestError("variant must be positive")

object NullKey extends RequestError("the key cannot be empty")

object NullMasterPassword extends RequestError("the master password cannot be empty")

object EngineError {
  implicit val eq: Eq[EngineError] = Eq.fromUniversalEquals
}


text:
from django.conf.urls import patterns, include, url
from django.contrib import admin

# See: https://docs.djangoproject.com/en/dev/topics/http/urls/
urlpatterns = patterns('',
    # Admin panel and documentation:
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)


text:
package tk.mybatis.mapper.annotation;

import tk.mybatis.mapper.code.Style;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 名字转换样式,注解的优先级高于全局配置
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NameStyle {

    Style value() default Style.normal;

}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-bajuxulida type="text/muj" hafu="../../../../xml/vo/peSezehu.muj"?>

<layout layoutId="degEgimafoHoraci"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../../../xsd/layout.xsd"
    pageTitle="Hasukay Vojiy"
    pageBuilder="com.gs.fw.kaza.puz.vo.tudewax.GoniyopEkavuZurasEyimama"
    showSelection="false">

        <row>

                <row>
                    <uiElement attribute="name"
                        name="gotilIbegi"
                        label="Qokec Vojiy:"
                        renderAs="combobox"/>
                    <button label="Sate Vojiy"
                        name="demeTehix" />
                    <button label="Yejeyo Vojiy"
                        name="fidosaWulaf"/>
                </row>
                <row>
                    <uiElement name="xazuvUsat"
                        label="Vojiy Name"
                        renderAs="textbox"/>
                    <uiElement renderAs="checkbox"
                        name="luriBohudUwitof"
                        label="Sihu Wedaye?"/>
                    <button label="Lage Vojiy"
                        name="nayuGakem" />
                </row>

        </row>

        <row>

                <row>
                    <uiElement label="PUZ Fedukoxa/Qoqunuwa"
                        name="heviyicoRejilele"
                        renderAs="combobox"
                        defaultSelection="Fedukoxa in Pocusox Pezug"/>
                </row>

                <row>
                    <uiElement name="position"
                        label="Fizumurel"
                        renderAs="checkbox"
                        defaultSelection="true"/>
                    <uiElement name="pocusox"
                        label="Kahutuji"
                        renderAs="checkbox"
                        defaultSelection="false"/>
                    <uiElement name="piwe"
                        label="Lexez"
                        renderAs="checkbox"
                        defaultSelection="false"/>
                    <uiElement name="covi"
                        label="Jaleh"
                        renderAs="checkbox"
                        defaultSelection="false"/>
                    <uiElement name="qayamUdoz"
                        label="Bumez Yuniw"
                        renderAs="checkbox"
                        defaultSelection="false"/>
                    <uiElement name="rofibamEkoliyo"
                        label="Podawuv Pocusox"
                        renderAs="checkbox"
                        defaultSelection="false"/>
                </row>

        </row>

        <row>

                <row>
                    <uiElement label="Cuyokujo Date"
                        name="businessDate"
                        renderAs="combobox"
                        transformerClass="com.gs.fw.common.petuhadi.vo.transformer.PorimubeDesaRemohiqujor"
                        sortAscending="false"/>
                    <uiElement label="Qahodoqo"
                        name="qahodoqo"
                        renderAs="combobox"
                        attribute="description"/>
                </row>

                <row>
                    <uiElement label="Cuyokujo Date"
                        name="day2BusinessDate"
                        renderAs="combobox"
                        transformerClass="com.gs.fw.kaza.puz.vo.transformer.LERAzimenizOzovAsoyowefuka"
                        sortAscending="false"
                        defaultSelection=""/>
                    <uiElement label="Qahodoqo"
                        name="day2Qahodoqo"
                        renderAs="combobox"
                        attribute="description"/>
                </row>

        </row>

        <row>
            <uiElement label="Group By:"
                name="hepafiq"
                renderAs="duallistbox"
                attribute="taxobifuNeyo"/>
        </row>

        <row>

                <row>
                    <uiElement name="harimaToki"
                               label="Lozohig List:"
                               renderAs="listbox"
                               style="height=8"
                               transformerClass="com.gs.fw.kaza.yepe.vo.hizuneyel.LugoquLopow.TesiyuCadoSobonujefoc"/>
                </row>

                <row>
                    <button label="Ran >> "
                            name="yulojesoz"/>
                </row>
                <row>
                    <button label=" << Yejeyo"
                            name="vexifehogimi"/>
                </row>

                <row>

                        <column>
                            <uiElement name="wavefaZahe"
                                       label="Mosuku Name"/>
                        </column>
                        <column>
                            <uiElement name="yumivaWehuq"
                                       label="Mosuku Value"
                                       transformerClass="com.gs.fw.common.glui.transformer.JakaQepuzayozix"
                                       renderAs="textbox"/>
                        </column>
                        <column>
                            <uiElement name="vehuloLekareko"
                                       label="Gexale"
                                       transformerClass="com.gs.fw.common.glui.transformer.BoveqorOtogoxuzebe"
                                       renderAs="checkbox"/>
                        </column>
                        <column>
                            <uiElement name="lozineFofanab"
                                       label="Kanoqi"
                                       transformerClass="com.gs.fw.common.glui.transformer.BoveqorOtogoxuzebe"
                                       renderAs="checkbox"/>
                        </column>

                </row>

        </row>

        <row>
            <uiElement name="lanapuLirev"
                label="Modida"
                renderAs="checkbox"
                defaultSelection="false"/>
            <uiElement name="yuladoMalecid"
                label="Hegoji"
                renderAs="combobox"/>
            <uiElement name="puqivej"
                label="Operation"
                renderAs="combobox"
                attribute="description"/>
            <uiElement name="joyupoXawoq"
                label="Value"
                renderAs="textbox"/>
        </row>

        <row>
            <uiElement name="hoxuSuqe"
                label="Tree View"
                renderAs="checkbox"
                defaultSelection="true"/>
        </row>

        <row>
            <button label="Lesihocu"
                name="lesihocu"
                nextLayoutName="puz/hasukay/pukohidOxibedUperi.xml"
                pageBuilder="com.gs.fw.kaza.puz.vo.tudewax.QOJEfuwibaQejiqaSelelOvirati"
                crumbTrail="true"/>
            <button label="Weha Mayina"
                name="sojeTovoveTugeqa"
                downloadContent="true"
                pageBuilder="com.gs.fw.kaza.puz.vo.tudewax.LuqeluhoCowuKojapoFayaCefonuh"
                nextLayoutName="puz/hasukay/vukeposAmunoDicop.xml"
                contentDownloader="com.gs.fw.kaza.puz.vo.xinocepe.XUQImoqUkofanigap"
                refreshPage="true"/>
        </row>

        <row>
            <uiElement name="jiqatitOjedadi"
                renderAs="checkbox"
                hidden="true"
                defaultSelection="true"/>
        </row>

</layout>


text:
Vivian
======

[![Latest Stable Version](https://poser.pugx.org/matks/vivian/v/stable.svg)](https://packagist.org/packages/matks/vivian)
[![Build Status](https://travis-ci.org/matks/Vivian.png)](https://travis-ci.org/matks/Vivian)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/matks/Vivian/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/matks/Vivian/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/matks/Vivian/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/matks/Vivian/?branch=master)
[![Latest Unstable Version](https://poser.pugx.org/matks/vivian/v/unstable.svg)](https://packagist.org/packages/matks/vivian)
[![License](https://poser.pugx.org/matks/vivian/license.svg)](https://packagist.org/packages/matks/vivian)

Tools to provide a pretty console output in ANSI/VT100 terminals

<img src="https://cloud.githubusercontent.com/assets/3830050/5061655/3202b658-6da0-11e4-8211-dce2fef12fc6.png" width="400px"/>

## Installation

Install the dependencies with composer
```bash
composer install
```

## Tests

Install the dev dependencies with composer
```bash
composer install --dev
```

Run the unit tests suite with atoum binary.
```bash
vendor/bin/atoum -bf vendor/autoload.php -d tests/Units/
```

## Usage

### Tool

For simple styles, the class Matks\Vivian\Tools provide a useful call interface, for example:
```php
use Matks\Vivian\Tools as Output;

echo Output::bold('... done.') . PHP_EOL;

if ($success) {
	echo Output::green('Success');
	echo PHP_EOL;
} else {
	echo Output::red('Failure !');
	echo PHP_EOL;
	echo Output::s_list1($errors);
}
```

See the examples in tests/Console:
```bash
php tests/Console/test-color
php tests/Console/test-background-color
php tests/Console/test-style
php tests/Console/test-border
php tests/Console/test-mixed
php tests/Console/test-structure
php tests/Console/test-figlet
```
or
```bash
bash tests/Console/test-all.sh
```

### Elements

For advanced displays, build the Elements you need:

#### Text Element

```php
use Matks\Vivian\Color;
use Matks\Vivian\Style;
use Matks\Vivian\Output;

$textElement = new Output\TextElement('Hello world !');

$boldStyle             = new Style\Style(Style\StyleManager::BASH_BOLD);
$greenColor            = new Color\TextColor(Color\TextColorManager::BASH_FOREGROUND_GREEN);
$cyanBackgroundColor   = new Color\BackgroundColor(Color\BackgroundColorManager::BASH_BACKGROUND_CYAN);

$textElement->setTextColor($greenColor)
            ->setBackgroundColor($cyanBackgroundColor)
            ->addStyle($boldStyle)
;

echo $textElement->render();
```

#### Bordered Element

```php
use Matks\Vivian\Border;
use Matks\Vivian\Color;
use Matks\Vivian\Output;

$yellowColor = new Color\TextColor(Color\TextColorManager::BASH_FOREGROUND_YELLOW);
$border      = new Border\Border(Border\Border::TYPE_FRAME);

$borderedElement = new Output\BorderedElement('Hello world !', $border);
$borderedElement->setTextColor($yellowColor);

echo $borderedElement->render();
```

#### Structured Elements

```php
use Matks\Vivian\Color;
use Matks\Vivian\Output;
use Matks\Vivian\Style;
use Matks\Vivian\Structure;

$greenColor     = new Color\TextColor(Color\TextColorManager::BASH_FOREGROUND_GREEN);
$redColor       = new Color\TextColor(Color\TextColorManager::BASH_FOREGROUND_RED);
$blinkingStyle  = new Style\Style(Style\StyleManager::BASH_BLINK);

$textElement1 = new Output\TextElement('Hello');
$textElement2 = new Output\TextElement('world');
$textElement3 = new Output\TextElement('!');
$textElement1->setTextColor($greenColor);
$textElement2->setTextColor($redColor);
$textElement3->addStyle($blinkingStyle);

$elements = array(
    $textElement1,
    $textElement2,
    $textElement3
);

$structure  = new Structure\Structure(Structure\Structure::TYPE_LIST, '#', '  ');
$structuredElements = new Output\StructuredElements($elements, $structure);
echo $structuredElements->render();
```

## More about ANSI/VT100 terminal control

http://www.termsys.demon.co.uk/vtansi.htm

## License

Vivian is licensed under the MIT License - see the LICENSE file for details

## More advanced features

I found a far more efficient library doing the same purpose: [CLImate](https://github.com/thephpleague/climate). I recommend it.


text:
  <ng-container *ngFor="let column of columns" matColumnDef="{{ column.property }}">

      {{ column.label }}

      {{ format(column, element[column.property]) }}

  </ng-container>


text:
Router.configure({
  layoutTemplate: 'layout'
});

Router.route('/',{
  name: 'postList',
  template: 'postList',
  data: function (){
    var data = {
      posts: Posts.find({}, {sort: {data: -1}})
    }
    return data;
  }
});
Router.route('/post/:_id',{
  name: 'postPagina',
  template:'postPagina',
  data: function() { return Posts.findOne(this.params._id); }
});
Router.route('/categoria/:nomeCategoria',{
  name: 'Categoria',
  template: 'postList',
  data: function(){
    var idCategoria = Categorias.findOne({nome: this.params.nomeCategoria})._id;
    var data = {
      posts: Posts.find({categorias:idCategoria}, {sort: {data: -1}})
    }
    return data;
  }
});


text:
import * as React from 'react';
import { connect } from 'react-redux';
import { IComment, IComments, IStoreState, IWebinar } from '../../interfaces';
import { arrayToMap } from '../../utils';
import './Comment.css';

interface ICommentProps {
  key?: string;
  comment: IComment;
}
export default class Comment extends React.Component<ICommentProps, {}> {
  public render(): JSX.Element | null {
    const { comment } = this.props;
    const { authorName, message } = comment;

    return (

        { authorName }:
        { message }

    );
  }
}


text:
import chai, {expect} from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon from 'sinon';
import delay from 'delay';

import AsyncAF from '../../../dist/async-af';

chai.use(chaiAsPromised);

describe('findIndexAF method', () => {
  it('should have the same arity as native findIndex', () => {
    expect(AsyncAF([]).findIndexAF.length).to.equal([].findIndex.length);
    expect(AsyncAF.prototype.findIndexAF.length)
      .to.equal(Array.prototype.findIndex.length);
  });

  context('should work on an array of non-promises', () => {
    const nums = [1, 2, 3];
    it('and find and resolve to the first index that satisfies the callback', async () => {
      expect(await AsyncAF(nums).findIndexAF(n => n % 2 === 0)).to.equal(1);
    });
    it('and resolve to -1 if no index satisfies the callback', async () => {
      expect(await AsyncAF(nums).findIndexAF(n => n === 5)).to.equal(-1);
    });
    it('and work with the index param', async () => {
      expect(await AsyncAF(nums).findIndexAF((_, i) => i === 2)).to.equal(2);
    });
    it('and work with the array param', async () => {
      expect(await AsyncAF(nums).findIndexAF((n, _, array) => n === array[2])).to.equal(2);
    });
  });

  context('should work on an array of promises', () => {
    const nums = [1, 2, 3].map(n => Promise.resolve(n));
    it('and find and resolve to the first index that satisfies the callback', async () => {
      expect(await AsyncAF(nums).findIndexAF(n => n % 2 === 0)).to.equal(1);
    });
    it('and resolve to -1 if no index satisfies the callback', async () => {
      expect(await AsyncAF(nums).findIndexAF(n => n === 5)).to.equal(-1);
    });
    it('and work with the index param', async () => {
      expect(await AsyncAF(nums).findIndexAF((_, i) => i === 2)).to.equal(2);
    });
    it('and work with the array param', async () => {
      expect(await AsyncAF(nums).findIndexAF((n, _, array) => n === array[2])).to.equal(2);
    });
  });

  it('should process elements in parallel', async () => {
    const clock = sinon.useFakeTimers({shouldAdvanceTime: true});
    const nums = [];
    await AsyncAF([3, 2, 1]).findIndexAF(async n => {
      await delay(n * 100);
      nums.push(n);
    });
    expect(nums).to.eql([1, 2, 3]);
    expect(Date.now()).to.equal(300);
    clock.restore();
  });

  it('should work with thisArg specified', async () => {
    const nums = [1, 2, 3].map(n => Promise.resolve(n));

    class Thing {
      constructor(num) {
        this.sum = num;
      }
      async goodAdd(nums) {
        await AsyncAF(nums).findIndexAF(function (num) {
          this.sum += num;
        }, this); // should work because we're specifying thisArg as this
      }
      async otherGoodAdd(nums) {
        await AsyncAF(nums).findIndexAF(num => {
          this.sum += num;
        }); // should work w/o specifying thisArg because of => funcs' lexical this binding
      }
      async badAdd(nums) {
        await AsyncAF(nums).findIndexAF(function (num) {
          this.sum += num;
        }); // should be rejected w/o specifying thisArg
      }
    }

    const thing = new Thing(6);
    await thing.goodAdd(nums);
    expect(thing.sum).to.equal(12);

    const thing2 = new Thing(6);
    await thing2.otherGoodAdd(nums);
    expect(thing2.sum).to.equal(12);

    const thing3 = new Thing(6);
    expect(thing3.badAdd(nums)).to.be.rejectedWith(TypeError);
  });

  it('should work on an array-like object', async () => {
    const nums = [];
    await (async function () {
      await AsyncAF(arguments).findIndexAF(n => {
        nums.push(n);
      });
    }(1, 2, 3));
    expect(nums).to.eql([1, 2, 3]);
  });

  it('should treat holes in sparse arrays as undefined', async () => {
    expect([, , 0].findIndex(el => el === undefined)).to.equal(0);
    expect(await AsyncAF([, , 0]).findIndexAF(el => el === undefined)).to.equal(0);
  });

  it('should not ignore holes when iterating through sparse arrays', async () => {
    /* eslint-disable array-bracket-spacing */
    const nums = [];
    let count = 0;
    await AsyncAF([, , 1, , 2, , , ]).findIndexAF(n => {
      nums.push(n * 2);
      count++;
    });
    expect(nums).to.eql([NaN, NaN, 2, NaN, 4, NaN, NaN]); // pushes empty slots
    expect(count).to.equal(7); // increments count even when value is empty
  });

  it('should work with index argument in a sparse array', async () => {
    expect(await AsyncAF([, , 1, , 2, , 3, , ]).findIndexAF((_, i) => i === 2)).to.equal(2);
  }); /* eslint-enable */

  it('should resolve to -1 given an empty array', async () => {
    expect([].findIndex(() => true)).to.equal(-1);
    expect(await AsyncAF([]).findIndexAF(() => true)).to.equal(-1);
  });

  it('should throw TypeError when callback is not a function', () => {
    expect(AsyncAF([]).findIndexAF()).to.eventually.be.rejected.and.have.property(
      'message',
      'undefined is not a function',
    );
  });
  it('should reject with TypeError when called on non-array-like objects', async () => {
    for (const value of [null, undefined, {}, true, 2])
      await AsyncAF(value).findIndexAF(() => {}).catch(e => {
        expect(e).to.be.an.instanceOf(TypeError).and.have.property(
          'message',
          `findIndexAF cannot be called on ${value}, only on an Array or array-like Object`,
        );
      });
  });
});


text:
module Glysellin
  class ProductProperty < ActiveRecord::Base
    self.table_name = 'glysellin_product_properties'
    attr_accessible :adjustement, :name, :value, :variant, :variant_id, :type, :type_id

    belongs_to :variant, polymorphic: true, foreign_key: 'variant_id'
    belongs_to :type, class_name: 'Glysellin::ProductPropertyType', foreign_key: 'type_id'

    # validate :check_uniqueness_of_type

    validates_presence_of :type, :value
    # validates_associated :type, :if => Proc.new { |type| !self.variant.properties.map(&:type).include?(type) }

    private

    def check_uniqueness_of_type
      if self.variant.properties.map(&:type).include? self.type
        errors.add(:type, I18n.t("glysellin.controllers.errors.double_property"))
      end
    end
  end
end