text:
package org.elasticsearch.index.mapper.ttl;

import org.apache.lucene.index.IndexOptions;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.mapper.internal.TTLFieldMapper;
import org.elasticsearch.test.ESSingleNodeTestCase;

import java.io.IOException;

import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;

public class TTLMappingTests extends ESSingleNodeTestCase {
    public void testSimpleDisabled() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").endObject().endObject().string();
        DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
        BytesReference source = XContentFactory.jsonBuilder()
                .startObject()
                .field("field", "value")
                .endObject()
                .bytes();
        ParsedDocument doc = docMapper.parse(SourceToParse.source("test", "type", "1", source).ttl(Long.MAX_VALUE));

        assertThat(doc.rootDoc().getField("_ttl"), equalTo(null));
    }

    public void testEnabled() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_ttl").field("enabled", "yes").endObject()
                .endObject().endObject().string();
        DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
        BytesReference source = XContentFactory.jsonBuilder()
                .startObject()
                .field("field", "value")
                .endObject()
                .bytes();
        ParsedDocument doc = docMapper.parse(SourceToParse.source("test", "type", "1", source).ttl(Long.MAX_VALUE));

        assertThat(doc.rootDoc().getField("_ttl").fieldType().stored(), equalTo(true));
        assertNotSame(IndexOptions.NONE, doc.rootDoc().getField("_ttl").fieldType().indexOptions());
        assertThat(doc.rootDoc().getField("_ttl").tokenStream(docMapper.mappers().indexAnalyzer(), null), notNullValue());
    }

    public void testDefaultValues() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").endObject().endObject().string();
        DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
        assertThat(docMapper.TTLFieldMapper().enabled(), equalTo(TTLFieldMapper.Defaults.ENABLED_STATE.enabled));
        assertThat(docMapper.TTLFieldMapper().fieldType().stored(), equalTo(TTLFieldMapper.Defaults.TTL_FIELD_TYPE.stored()));
        assertThat(docMapper.TTLFieldMapper().fieldType().indexOptions(), equalTo(TTLFieldMapper.Defaults.TTL_FIELD_TYPE.indexOptions()));
    }

    public void testThatEnablingTTLFieldOnMergeWorks() throws Exception {
        String mappingWithoutTtl = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("properties").field("field").startObject().field("type", "text").endObject().endObject()
                .endObject().endObject().string();

        String mappingWithTtl = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_ttl")
                .field("enabled", "yes")
                .endObject()
                .startObject("properties").field("field").startObject().field("type", "text").endObject().endObject()
                .endObject().endObject().string();

        MapperService mapperService = createIndex("test").mapperService();
        DocumentMapper mapperWithoutTtl = mapperService.merge("type", new CompressedXContent(mappingWithoutTtl), MapperService.MergeReason.MAPPING_UPDATE, false);
        DocumentMapper mapperWithTtl = mapperService.merge("type", new CompressedXContent(mappingWithTtl), MapperService.MergeReason.MAPPING_UPDATE, false);

        assertThat(mapperWithoutTtl.TTLFieldMapper().enabled(), equalTo(false));
        assertThat(mapperWithTtl.TTLFieldMapper().enabled(), equalTo(true));
    }

    public void testThatChangingTTLKeepsMapperEnabled() throws Exception {
        String mappingWithTtl = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_ttl")
                .field("enabled", "yes")
                .endObject()
                .startObject("properties").field("field").startObject().field("type", "text").endObject().endObject()
                .endObject().endObject().string();

        String updatedMapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_ttl")
                .field("default", "1w")
                .endObject()
                .startObject("properties").field("field").startObject().field("type", "text").endObject().endObject()
                .endObject().endObject().string();

        MapperService mapperService = createIndex("test").mapperService();
        DocumentMapper initialMapper = mapperService.merge("type", new CompressedXContent(mappingWithTtl), MapperService.MergeReason.MAPPING_UPDATE, false);
        DocumentMapper updatedMapper = mapperService.merge("type", new CompressedXContent(updatedMapping), MapperService.MergeReason.MAPPING_UPDATE, false);

        assertThat(initialMapper.TTLFieldMapper().enabled(), equalTo(true));
        assertThat(updatedMapper.TTLFieldMapper().enabled(), equalTo(true));
    }

    public void testThatDisablingTTLReportsConflict() throws Exception {
        String mappingWithTtl = getMappingWithTtlEnabled().string();
        String mappingWithTtlDisabled = getMappingWithTtlDisabled().string();
        MapperService mapperService = createIndex("test").mapperService();
        DocumentMapper initialMapper = mapperService.merge("type", new CompressedXContent(mappingWithTtl), MapperService.MergeReason.MAPPING_UPDATE, false);

        try {
            mapperService.merge("type", new CompressedXContent(mappingWithTtlDisabled), MapperService.MergeReason.MAPPING_UPDATE, false);
            fail();
        } catch (IllegalArgumentException e) {
            // expected
        }

        assertThat(initialMapper.TTLFieldMapper().enabled(), equalTo(true));
    }

    public void testThatDisablingTTLReportsConflictOnCluster() throws Exception {
        String mappingWithTtl = getMappingWithTtlEnabled().string();
        String mappingWithTtlDisabled = getMappingWithTtlDisabled().string();
        assertAcked(client().admin().indices().prepareCreate("testindex").addMapping("type", mappingWithTtl));
        GetMappingsResponse mappingsBeforeUpdateResponse = client().admin().indices().prepareGetMappings("testindex").addTypes("type").get();
        try {
            client().admin().indices().preparePutMapping("testindex").setSource(mappingWithTtlDisabled).setType("type").get();
            fail();
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage(), containsString("_ttl cannot be disabled once it was enabled."));
        }
        GetMappingsResponse mappingsAfterUpdateResponse = client().admin().indices().prepareGetMappings("testindex").addTypes("type").get();
        assertThat(mappingsBeforeUpdateResponse.getMappings().get("testindex").get("type").source(), equalTo(mappingsAfterUpdateResponse.getMappings().get("testindex").get("type").source()));
    }

    public void testThatEnablingTTLAfterFirstDisablingWorks() throws Exception {
        String mappingWithTtl = getMappingWithTtlEnabled().string();
        String withTtlDisabled = getMappingWithTtlDisabled().string();
        assertAcked(client().admin().indices().prepareCreate("testindex").addMapping("type", withTtlDisabled));
        GetMappingsResponse mappingsAfterUpdateResponse = client().admin().indices().prepareGetMappings("testindex").addTypes("type").get();
        assertThat(mappingsAfterUpdateResponse.getMappings().get("testindex").get("type").sourceAsMap().get("_ttl").toString(), equalTo("{enabled=false}"));
        client().admin().indices().preparePutMapping("testindex").setSource(mappingWithTtl).setType("type").get();
        mappingsAfterUpdateResponse = client().admin().indices().prepareGetMappings("testindex").addTypes("type").get();
        assertThat(mappingsAfterUpdateResponse.getMappings().get("testindex").get("type").sourceAsMap().get("_ttl").toString(), equalTo("{enabled=true}"));
    }

    public void testNoConflictIfNothingSetAndDisabledLater() throws Exception {
        IndexService indexService = createIndex("testindex", Settings.builder().build(), "type");
        XContentBuilder mappingWithTtlDisabled = getMappingWithTtlDisabled("7d");
        indexService.mapperService().merge("type", new CompressedXContent(mappingWithTtlDisabled.string()), MapperService.MergeReason.MAPPING_UPDATE, false);
    }

    public void testNoConflictIfNothingSetAndEnabledLater() throws Exception {
        IndexService indexService = createIndex("testindex", Settings.builder().build(), "type");
        XContentBuilder mappingWithTtlEnabled = getMappingWithTtlEnabled("7d");
        indexService.mapperService().merge("type", new CompressedXContent(mappingWithTtlEnabled.string()), MapperService.MergeReason.MAPPING_UPDATE, false);
    }

    public void testMergeWithOnlyDefaultSet() throws Exception {
        XContentBuilder mappingWithTtlEnabled = getMappingWithTtlEnabled("7d");
        IndexService indexService = createIndex("testindex", Settings.builder().build(), "type", mappingWithTtlEnabled);
        XContentBuilder mappingWithOnlyDefaultSet = getMappingWithOnlyTtlDefaultSet("6m");
        indexService.mapperService().merge("type", new CompressedXContent(mappingWithOnlyDefaultSet.string()), MapperService.MergeReason.MAPPING_UPDATE, false);
        CompressedXContent mappingAfterMerge = indexService.mapperService().documentMapper("type").mappingSource();
        assertThat(mappingAfterMerge, equalTo(new CompressedXContent("{\"type\":{\"_ttl\":{\"enabled\":true,\"default\":360000},\"properties\":{\"field\":{\"type\":\"text\"}}}}")));
    }

    public void testMergeWithOnlyDefaultSetTtlDisabled() throws Exception {
        XContentBuilder mappingWithTtlEnabled = getMappingWithTtlDisabled("7d");
        IndexService indexService = createIndex("testindex", Settings.builder().build(), "type", mappingWithTtlEnabled);
        CompressedXContent mappingAfterCreation = indexService.mapperService().documentMapper("type").mappingSource();
        assertThat(mappingAfterCreation, equalTo(new CompressedXContent("{\"type\":{\"_ttl\":{\"enabled\":false},\"properties\":{\"field\":{\"type\":\"text\"}}}}")));
        XContentBuilder mappingWithOnlyDefaultSet = getMappingWithOnlyTtlDefaultSet("6m");
        indexService.mapperService().merge("type", new CompressedXContent(mappingWithOnlyDefaultSet.string()), MapperService.MergeReason.MAPPING_UPDATE, false);
        CompressedXContent mappingAfterMerge = indexService.mapperService().documentMapper("type").mappingSource();
        assertThat(mappingAfterMerge, equalTo(new CompressedXContent("{\"type\":{\"_ttl\":{\"enabled\":false},\"properties\":{\"field\":{\"type\":\"text\"}}}}")));
    }

    public void testIncludeInObjectNotAllowed() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
            .startObject("_ttl").field("enabled", true).endObject()
            .endObject().endObject().string();
        DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));

        try {
            docMapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
                .startObject().field("_ttl", "2d").endObject().bytes());
            fail("Expected failure to parse metadata field");
        } catch (MapperParsingException e) {
            assertTrue(e.getMessage(), e.getMessage().contains("Field [_ttl] is a metadata field and cannot be added inside a document"));
        }
    }

    private org.elasticsearch.common.xcontent.XContentBuilder getMappingWithTtlEnabled() throws IOException {
        return getMappingWithTtlEnabled(null);
    }

    private org.elasticsearch.common.xcontent.XContentBuilder getMappingWithTtlDisabled() throws IOException {
        return getMappingWithTtlDisabled(null);
    }

    private org.elasticsearch.common.xcontent.XContentBuilder getMappingWithTtlEnabled(String defaultValue) throws IOException {
        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_ttl")
                .field("enabled", true);
        if (defaultValue != null) {
            mapping.field("default", defaultValue);
        }
        return mapping.endObject()
                .startObject("properties").field("field").startObject().field("type", "text").endObject().endObject()
                .endObject().endObject();
    }

    private org.elasticsearch.common.xcontent.XContentBuilder getMappingWithTtlDisabled(String defaultValue) throws IOException {
        XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_ttl")
                .field("enabled", false);
        if (defaultValue != null) {
            mapping.field("default", defaultValue);
        }
        return mapping.endObject()
                .startObject("properties").field("field").startObject().field("type", "text").endObject().endObject()
                .endObject().endObject();
    }

    private org.elasticsearch.common.xcontent.XContentBuilder getMappingWithOnlyTtlDefaultSet(String defaultValue) throws IOException {
        return XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_ttl").field("default", defaultValue).endObject()
                .startObject("properties").field("field").startObject().field("type", "text").endObject().endObject()
                .endObject().endObject();
    }
}


text:
/**
 * @file
 *   This file includes definitions for manipulating MeshCoP timestamps.
 *
 */

#ifndef MESHCOP_TIMESTAMP_HPP_
#define MESHCOP_TIMESTAMP_HPP_

#include <string.h>

#include <openthread/platform/toolchain.h>

#include "common/encoding.hpp"

using ot::Encoding::BigEndian::HostSwap16;

namespace ot {
namespace MeshCoP {

/**
 * This class implements Timestamp generation and parsing.
 *
 */
OT_TOOL_PACKED_BEGIN
class Timestamp
{
public:
    /**
     * This method initializes the Timestamp
     *
     */
    void Init(void) { memset(mSeconds, 0, sizeof(mSeconds)); mTicks = 0; }

    /**
     * This method compares this timestamp to another.
     *
     * @param[in]  aCompare  A reference to the timestamp to compare.
     *
     * @retval -1  if @p aCompare is less than this timestamp.
     * @retval  0  if @p aCompare is equal to this timestamp.
     * @retval  1  if @p aCompare is greater than this timestamp.
     *
     */
    int Compare(const Timestamp &aCompare) const;

    /**
     * This method returns the Seconds value.
     *
     * @returns The Seconds value.
     *
     */
    uint64_t GetSeconds(void) const {
        uint64_t seconds = 0;

        for (size_t i = 0; i < sizeof(mSeconds); i++) {
            seconds = (seconds << 8) | mSeconds[i];
        }

        return seconds;
    }

    /**
     * This method sets the Seconds value.
     *
     * @param[in]  aSeconds  The Seconds value.
     *
     */
    void SetSeconds(uint64_t aSeconds) {
        for (size_t i = 0; i < sizeof(mSeconds); i++, aSeconds >>= 8) {
            mSeconds[sizeof(mSeconds) - 1 - i] = aSeconds & 0xff;
        }
    }

    /**
     * This method returns the Ticks value.
     *
     * @returns The Ticks value.
     *
     */
    uint16_t GetTicks(void) const { return HostSwap16(mTicks) >> kTicksOffset; }

    /**
     * This method sets the Ticks value.
     *
     * @param[in]  aTicks  The Ticks value.
     *
     */
    void SetTicks(uint16_t aTicks) {
        mTicks = HostSwap16((HostSwap16(mTicks) & ~kTicksMask) | ((aTicks << kTicksOffset) & kTicksMask));
    }

    /**
     * This method returns the Authoritative value.
     *
     * @returns The Authoritative value.
     *
     */
    bool GetAuthoritative(void) const { return (HostSwap16(mTicks) & kAuthoritativeMask) != 0; }

    /**
     * This method sets the Authoritative value.
     *
     * @param[in]  aAuthoritative  The Authoritative value.
     *
     */
    void SetAuthoritative(bool aAuthoritative) {
        mTicks = HostSwap16((HostSwap16(mTicks) & kTicksMask) | ((aAuthoritative << kAuthoritativeOffset) &
                                                                 kAuthoritativeMask));
    }

private:
    uint8_t mSeconds[6];

    enum
    {
        kTicksOffset         = 1,
        kTicksMask           = 0x7fff << kTicksOffset,
        kAuthoritativeOffset = 0,
        kAuthoritativeMask   = 1 << kAuthoritativeOffset,
    };
    uint16_t mTicks;
} OT_TOOL_PACKED_END;

}  // namespace MeshCoP
}  // namespace ot

#endif  // MESHCOP_TIMESTAMP_HPP_

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TimePicker
        android:id="@+id/TimePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="64dp" />

</RelativeLayout>


text:
<?php
class UsersController extends AppController {
	public $theme="Book";
	public function beforeFilter(){
		$this->Auth->allow('create','login','confirm', 'lost_password', 'reset_password');
	    //$this->Auth->fields = array('username'=>'email', 'password'=>'password');
	}

	public function create(){

		if($this->request->is('post')){
			$data=$this->request->data;
			$data['User']['password'] = AuthComponent::password($data['User']['password']);
			$data['User']['username'] = $data['User']['email'];
			$this->User->create();
			if($saved=$this->User->save($data)){
		    $opts = array('name'=>$saved['User']['name'], 'email'=>$saved['User']['email'], 'site'=>null);
			// send the user confirmation email
			            $id = $saved['User']['id'];
			            $email = $saved['User']['email'];
			            $name = $saved['User']['name'];
			            $hash = md5(sprintf('%s%s%s', $id, $email, $name));
			            $opts['hash'] = $hash;
			$this->Session->setFlash('User Saved!');
			$this->User->sendAccountCreated($opts);
			$this->redirect('');
			}

		}

	}

	public function edit(){

	}

	public function admin_login(){
	$this->autoRender=false;
	$this->Session->setFlash('You are not authorized to access this page');
	$this->redirect(array('controller'=>'users','action'=>'login', 'admin'=>false));
	}

	public function admin_logout(){
	$this->autoRender=false;
	$this->redirect($this->Auth->logout());
	}

	public function login() {
	    $this->layout = 'default';
	    if($this->request->is('post')) {
	      // try and hash the password
	      if($this->Auth->login()) {
	        $id = $this->Auth->user('id');
	        $user = $this->User->findById($id);
	        $confirmed = $user['User']['confirmed'];
	        if($confirmed == 1) {
	         $this->redirect($this->Auth->redirect());
	        } else {
	          // user is not confirmed
	          $this->Session->setFlash('Your account is not yet confirmed. Please ' .
	                                   'check your email for the confirmation link.');
	        }
	      } else {
	        $this->Session->setFlash('Username or password is incorrect.');
	      }
	    }
	  }

	public function logout() {
	    $this->redirect($this->Auth->logout());
	  }

	public function confirm($hash = null) {
		$this->autoRender = false;
		//$this->autoLayout=false;
	    // grab the user account info with the hash
	    $conditions = array('md5(concat(User.id, User.email, User.name))'=>$hash);
	    $user = $this->User->find('first', array('conditions'=>$conditions));

	    if($user == null || sizeof($user) == 0) {
	      $this->Session->setFlash('Error: invalid confirmation link.');
	    } else {

	      // Unset validation and confirm the user in the database
	     /*unset($this->User->validate['email']);
	      unset($this->User->validate['password']);
	      unset($this->User->validate['email2']);
	      unset($this->User->validate['password2']);*/

	      $user['User']['confirmed'] = 1;
	      $user = $this->User->save($user);

	      // send the "you're confirmed" email
	      $opts = array('name'=>$user['User']['name'], 'email'=>$user['User']['email']);
	      $this->User->sendAccountConfirmed($opts);

			$this->Session->setFlash('User Confirmed!');
		  // log the user in and redirect them
		  $this->Auth->login($user['User']);
	      $this->redirect(array('controller'=>'stories', 'action' => 'index'));
	    }
	  }

	public function logged_in(){
	echo "You are logged in!";
	$user=$this->User->findById($this->Auth->user());
	pr($user);
	}

}


text:
<?php

class Element extends XHTMLElement {

  function getElements($expression){
    $local = array();
    return Selectors_Utils::search($this, $expression, $local);
  }

  function getElement($expression){
    return current($this->getElements($expression));
  }

  function match($selector) {
    if(!$selector || $selector == $this) return true;

    $tree = Selectors_Utils::tokenize($selector);  $selector = $tree[0][0]['members'];

    if( (($tag = $selector[0]['tag']) || ($id = $selector[0]['id']))
        && !(Selectors_Filters::ById($this, $id) && Selectors_Filters::byTag($this, $tag)))
            return false;

    $parsed = Selectors_Utils::parseSelector($selector);
    return $parsed ? Selectors_Utils::filter($this, $parsed, array() ):true;
  }

  function clean(){
    $c=0; $name = $this->getName();
    foreach ($this->getParent()->$name as $node) {
        if($node == $this) {
            unset($this->getParent()->{$name}[$c]);
            return $this;
        } $c++;
    }
  }

//get("text:first/clean");
  function get($path){
    $extras = explode("/", $path);
    $path = explode(':', array_shift($extras));
    $key  = array_shift($path);

    if($key=="tag")
        return strtolower($this->getName());

    if($key=="text") {
        $clean = in_array("clean", $extras);
        $part  = array_shift($path);
        $dom = dom_import_simplexml($this);
        if($part == "first") $dom = $dom->firstChild;
        $str = $dom->textContent;
        if($clean) $str = preg_replace("#[\s\r\n]+#"," ", trim($str));
        return $str;
    } elseif($key=="html")
        return $this->asXML();
    elseif($key=="innerHTML")
        return innerHTML($this->asXML());

    return (string)$this[$key];
  }
}


text:
//
//  SQLiteStructureTable.m
//  SQLiteKit
//
//  Created by Pascal Pfiffner on 11.09.10.
//  This sourcecode is released under the Apache License, Version 2.0
//  http://www.apache.org/licenses/LICENSE-2.0.html
//

#import "SQLKTableStructure.h"
#import "sqlk.h"
#import "SQLKStructure.h"
#import "SQLKColumnStructure.h"
#import "FMDatabase.h"

#define DEBUG_SCANNING 0
#ifndef SLog
# if DEBUG_SCANNING
#  define SLog(fmt, ...) NSLog((@"%s (line %d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
# else
#  define SLog(...)
# endif
#endif

@implementation SQLKTableStructure

@synthesize structure;
@synthesize name, columns, constraints;
@synthesize originalQuery;

+ (SQLKTableStructure *)tableForStructure:(SQLKStructure *)aStructure
{
	SQLKTableStructure *t = [self new];
	t.structure = aStructure;

	return t;
}

/**
 *	Instantiates an object from a given SQLite query
 *	See http://www.sqlite.org/syntaxdiagrams.html for diagrams
 */
+ (SQLKTableStructure *)tableFromQuery:(NSString *)aQuery
{
	SQLKTableStructure *t = [self new];
	if ([aQuery length] > 0) {
		t.originalQuery = aQuery;
		SLog(@"Parsing:  %@", aQuery);

		NSString *errorString = nil;
		NSScanner *scanner = [NSScanner scannerWithString:aQuery];
		[scanner setCaseSensitive:NO];
		[scanner setCharactersToBeSkipped:nil];

		NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
		NSCharacterSet *letterSet = [NSCharacterSet letterCharacterSet];
		NSCharacterSet *closeBracketOrComma = [NSCharacterSet characterSetWithCharactersInString:@"),"];

		// scan table name
		if ([scanner scanUpToString:@"TABLE" intoString:NULL] && [scanner scanString:@"TABLE" intoString:NULL]) {
			[scanner scanCharactersFromSet:whiteSpace intoString:NULL];
			//[scanner scanString:@"EXISTS" intoString:NULL];				/// @todo skip potential "IF NOT EXISTS"

			NSString *tblName = nil;
			[scanner scanUpToCharactersFromSet:whiteSpace intoString:&tblName];
			//[scanner scanUpToString:@"(" intoString:&tblName];
			if ([tblName length] > 0) {
				NSMutableArray *newColumns = [NSMutableArray array];
				NSMutableArray *newConstraints = [NSMutableArray array];

				t.name = tblName;
				[scanner scanUpToString:@"(" intoString:NULL];				// check for "AS", this is also a possible encounter here
				[scanner scanString:@"(" intoString:NULL];

				// scan columns and table constraints
				BOOL atConstraints = NO;
				BOOL noMoreColumns = NO;
				while (![scanner isAtEnd]) {
					NSString *scanString = nil;
					[scanner scanCharactersFromSet:whiteSpace intoString:NULL];
					if ([scanner scanString:@")" intoString:&scanString]) {
						noMoreColumns = YES;
					}

					// separate constraints from columns
					if (!noMoreColumns) {
						[scanner scanUpToCharactersFromSet:whiteSpace intoString:&scanString];
						SLog(@" -->  %@", scanString);

						// ** looks like we found a constraint
						if (atConstraints
							|| ([@"CONSTRAINT" isEqualToString:scanString]
								|| [@"UNIQUE" isEqualToString:scanString]
								|| [@"PRIMARY" isEqualToString:scanString]
								|| [@"FOREIGN" isEqualToString:scanString]
								|| [@"CHECK" isEqualToString:scanString]))
						{
							atConstraints = YES;
							SLog(@"==>  Interpreting as constraint");

							NSMutableString *constraint = [scanString mutableCopy];
							if ([scanner scanUpToString:@"(" intoString:&scanString]) {
								[constraint appendString:scanString];
								if ([scanner scanUpToString:@")" intoString:&scanString]) {
									[constraint appendString:scanString];
									if ([scanner scanString:@")" intoString:&scanString]) {
										[constraint appendString:scanString];
									}
								}
							}

							if ([scanner scanUpToCharactersFromSet:closeBracketOrComma intoString:&scanString]) {
								[constraint appendString:scanString];
							}
							[scanner scanString:@"," intoString:NULL];

							[newConstraints addObject:constraint];
						}

						// ** we most likely found a column
						else {
							SLog(@"==>  Interpreting as column");
							SQLKColumnStructure *column = [SQLKColumnStructure columnForTable:t];
							column.name = scanString;

							// type
							[scanner scanCharactersFromSet:whiteSpace intoString:NULL];
							if ([scanner scanCharactersFromSet:letterSet intoString:&scanString]) {
								[scanner scanCharactersFromSet:whiteSpace intoString:NULL];
								column.type = scanString;
							}

							// there might my MySQL-type type lengths, we just ignore them
							if ([scanner scanString:@"(" intoString:NULL]) {
								[scanner scanUpToString:@")" intoString:NULL];
								[scanner scanString:@")" intoString:NULL];
							}

							/// @todo Scan column constraints more sophisticated (scan up to either "(" or "," and see what we've got, then decide whether next
							// column is starting or we're in brackets). Not sure if it's worth the effort since this "feature" is only useful if parsing the
							// structure from one sqlite database and wanting to create a blank copy of it, without access to an XML structure.

							// scan column constraints and defaults
							if ([scanner scanUpToString:@"," intoString:&scanString]) {
								SLog(@"==>  name: %@  type: %@  constraints/defaults: \"%@\"", column.name, column.type, scanString);

								// unique column
								column.isUnique = (NSNotFound != [scanString rangeOfString:@"UNIQUE"].location);

								// column is primary key
								column.isPrimaryKey = (NSNotFound != [scanString rangeOfString:@"PRIMARY KEY"].location);

								// column has a default defined - for now we assume everything behind DEFAULT is the default value
								if (NSNotFound != [scanString rangeOfString:@"DEFAULT"].location) {
									NSMutableArray *parts = [[scanString componentsSeparatedByCharactersInSet:whiteSpace] mutableCopy];
									NSUInteger defaultIndex = [parts indexOfObject:@"DEFAULT"];
									if ([parts count] > defaultIndex + 1) {
										NSIndexSet *remove = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, defaultIndex + 1)];
										[parts removeObjectsAtIndexes:remove];
										column.defaultString = [parts componentsJoinedByString:@" "];
									}
								}
							}

							// remember column and skip to next item
							if ([column.name length] > 0) {
								[newColumns addObject:column];
							}

							[scanner scanString:@"," intoString:NULL];
						}
					}
				}

				t.columns = newColumns;
				t.constraints = ([newConstraints count] > 0) ? newConstraints : nil;
			}
			else {
				errorString = @"Could not find table name";
			}
		}
		else {
			errorString = @"Could not find CREATE TABLE hook";
		}

#if DEBUG_SCANNING
		[t log];
#endif

		if (errorString) {
			DLog(@"Error parsing: %@\nSQL: %@", errorString, aQuery);
		}
	}
	else {
		DLog(@"Query was empty");
	}

	return t;
}

#pragma mark - Creating
/**
 *	Creates the receiver's structure in the given database
 *	@param database A handle to the database
 *	@param error A pointer to an array object
 */
- (BOOL)createInDatabase:(FMDatabase *)database error:(NSError **)error
{
	if ([database open]) {
		NSString *query = [self creationQuery];
		[database executeUpdate:query];

		if (![database hadError]) {
			return YES;
		}
		NSString *errorString = [NSString stringWithFormat:@"Error executing query: (%d) %@\n%@", [database lastErrorCode], [database lastErrorMessage], query];
		SQLK_ERR(error, errorString, 0)
	}
	else {
		NSString *errorString = database ? [NSString stringWithFormat:@"Could not open database: (%d) %@", [database lastErrorCode], [database lastErrorMessage]] : @"No database given";
		SQLK_ERR(error, errorString, 0)
	}
	return NO;
}

/**
 *	Returns the SQLite query needed in order to create a table representing the receiver's structure
 */
- (NSString *)creationQuery
{
	if ([columns count] > 0) {
		NSMutableArray *colStrings = [NSMutableArray arrayWithCapacity:[columns count]];

		// collect columns
		for (SQLKColumnStructure *column in columns) {
			NSString *colQuery = [column creationQuery];
			if (colQuery) {
				[colStrings addObject:colQuery];
			}
		}

		// collect constraints
		for (NSString *constraint in constraints) {
			if ([constraint length] > 0) {
				[colStrings addObject:constraint];
			}
		}

		return [NSString stringWithFormat:@"CREATE TABLE %@ (%@)", name, [colStrings componentsJoinedByString:@", "]];
	}

	DLog(@"Can't create a table without columns");
	return nil;
}

#pragma mark - Comparing
/**
 *	Tables are equal if they have the same structure, i.e. "isEqualToTable:error:" also returns YES
 */
- (BOOL)isEqual:(id)object
{
	if (self == object) {
		return YES;
	}
	if ([object isKindOfClass:[self class]] && [name isEqualToString:[object name]]) {
		return [self isEqualToTable:(SQLKTableStructure *)object error:NULL];
	}
	return NO;
}

/**
 *	This method is used by SQLKStructure to compare a table structure described in an XML to a table structure inferred from the
 *	actual SQLite database.
 */
- (BOOL)isEqualToTable:(SQLKTableStructure *)refTable error:(NSError **)error
{
	NSString *errorString = nil;
	NSUInteger errorCode = 0;

	if (refTable) {

		// check name
		if ([name isEqualToString:refTable.name]) {
			NSMutableArray *existingColumns = [columns mutableCopy];

			// compare columns
			if ([existingColumns count] > 0) {
				NSMutableArray *errors = [NSMutableArray array];

				// compare existing columns
				for (SQLKColumnStructure *refColumn in refTable.columns) {
					if (![self hasColumnWithStructure:refColumn]) {
						NSError *myError = nil;
						NSString *errorMessage = [NSString stringWithFormat:@"Differring column: %@", refColumn.name];
						SQLK_ERR(&myError, errorMessage, 0)
						[errors addObject:myError];
					}
					else {
						[existingColumns removeObject:refColumn];
					}
				}

				// leftover columns?
				if ([existingColumns count] > 0) {
					for (SQLKColumnStructure *sup in existingColumns) {
						NSError *myError = nil;
						NSString *myErrorString = [NSString stringWithFormat:@"Superfluuous column: %@", sup.name];
						SQLK_ERR(&myError, myErrorString, 0)
						[errors addObject:myError];
					}
				}

				// report specific errors
				if ([errors count] > 0) {
					errorString = [NSString stringWithFormat:@"%d errors occurred while comparing columns to table \"%@\". See \"SQLKErrors\" in this errors' userInfo.", (unsigned int)[errors count], refTable.name];
					errorCode = 673;
				}
				else {
					return YES;
				}
			}
			else if ([refTable.columns count] > 0) {
				errorString = @"This table is missing all columns";
				errorCode = 641;
			}
			else {
				DLog(@"Note: Both tables don't have any columns");
				return YES;
			}
		}
		//else {
		//	errorString = @"Table names don't match";
		//}
	}
	else {
		errorString = @"No other table given";
		errorCode = 675;
	}

	// report generic errors
	if (errorString) {
		SQLK_ERR(error, errorString, errorCode)
	}

	return NO;
}

/**
 *	@return The column with the given name
 */
- (SQLKColumnStructure *)columnNamed:(NSString *)columnName
{
	if (columnName) {
		for (SQLKColumnStructure *column in columns) {
			if ([column.name isEqualToString:columnName]) {
				return column;
			}
		}
	}
	return nil;
}

/**
 *	@return YES if the receiver has a column with the given name
 */
- (BOOL)hasColumnNamed:(NSString *)columnName
{
	return (nil != [self columnNamed:columnName]);
}

/**
 *	Returns YES if the receiver has a column with the given structure
 */
- (BOOL)hasColumnWithStructure:(SQLKColumnStructure *)columnStructure
{
	if (columnStructure) {
		for (SQLKColumnStructure *column in columns) {
			if ([column.name isEqualToString:columnStructure.name]) {
				return [column isEqual:columnStructure];
			}
		}
	}
	return NO;
}

#pragma mark - Updating

/**
 *	Updates the table to match the structure given in the reference table.
 *	The receiver's parent structure must have an open handle to the actual database. Remember SQLite can't drop columns, so if you remove them from your schema,
 *	they will still persist in the database.
 *	We don't use transactions within this method as a transaction is openend by updateDatabaseAt:dropTables:error:
 */
- (BOOL)updateTableWith:(SQLKTableStructure *)refTable error:(NSError **)error
{
	FMDatabase *db = structure.database;
	if ([db open]) {

		// compare existing columns
		if ([refTable.columns count] > 0) {
			for (SQLKColumnStructure *refColumn in refTable.columns) {
				SQLKColumnStructure *existing = [self columnNamed:refColumn.name];

				// column is missing, add it
				if (!existing) {

					// TODO: New columns may not: ( http://www.sqlite.org/lang_altertable.html )
					//		- be PRIMARY
					//		- be UNIQUE
					//		- have CURRENT_[TIME|DATE|TIMESTAMP] as default
					//		- if it is NOT NULL, must have a non-null default value
					//		- if it has a REFERENCES clause, must have a null default value
					NSString *query = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@", refTable.name, [refColumn creationQuery]];
					if (![db executeUpdate:query]) {
						NSString *errorString = [NSString stringWithFormat:@"Failed to: %@: (%d) %@", query, [db lastErrorCode], [db lastErrorMessage]];
						SQLK_ERR(error, errorString, 601)
						return NO;
					}
				}

				// TODO: To drop columns, we have to recreate the table without the column to be dropped
			}
		}

		return YES;
	}
	else if (db) {
		NSString *errorString = [NSString stringWithFormat:@"Could not open database: (%d) %@", [db lastErrorCode], [db lastErrorMessage]];
		SQLK_ERR(error, errorString, 621)
	}
	else if (structure) {
		SQLK_ERR(error, @"We don't have a database handle to update the table", 620)
	}
	else {
		SQLK_ERR(error, @"The table doesn't have a db structure, can't update the table", 640)
	}
	return NO;
}

#pragma mark - Destruction
/**
 *	Drops the receiver's representation from the given database
 */
- (BOOL)dropFromDatabase:(FMDatabase *)database error:(NSError **)error
{
	if ([database open]) {
		NSString *query = [NSString stringWithFormat:@"DROP TABLE \"%@\"", self.name];
		[database executeUpdate:query];

		if (![database hadError]) {
			return YES;
		}
		NSString *errorString = [NSString stringWithFormat:@"Error executing query: (%d) %@\n%@", [database lastErrorCode], [database lastErrorMessage], query];
		SQLK_ERR(error, errorString, 0)
	}
	else {
		NSString *errorString = database ? [NSString stringWithFormat:@"Could not open database: (%d) %@", [database lastErrorCode], [database lastErrorMessage]] : @"No database given";
		SQLK_ERR(error, errorString, 0)
	}
	return NO;
}

#pragma mark - Utilities
- (void)log
{
	NSLog(@"--  %@", self);
	for (SQLKColumnStructure *column in self.columns) {
		NSLog(@"----  %@", column);
	}
	for (NSString *constraint in self.constraints) {
		NSLog(@"---|  %@", constraint);
	}
}

- (NSString *) description
{
	return [NSString stringWithFormat:@"%@ <%p> \"%@\", %i columns, %i constraints", NSStringFromClass([self class]), self, name, (unsigned int)[columns count], (unsigned int)[constraints count]];
}

@end


text:
const L = require('../leaflet.js');
const rasterlayer = require('./RasterLayer.js');
const layer = require('./Layer.js');

export class LeafletHeatmapModel extends rasterlayer.LeafletRasterLayerModel {
  defaults() {
    return {
      ...super.defaults(),
      _view_name: 'LeafletHeatmapView',
      _model_name: 'LeafletHeatmapModel',
      locations: [],
      minOpacity: 0.05,
      maxZoom: 18,
      max: 1.0,
      radius: 25.0,
      blur: 15.0,
      gradient: {
        0.4: 'blue',
        0.6: 'cyan',
        0.7: 'lime',
        0.8: 'yellow',
        1.0: 'red'
      }
    };
  }
}

export class LeafletHeatmapView extends layer.LeafletLayerView {
  create_obj() {
    this.obj = L.heatLayer(this.model.get('locations'), this.get_options());
  }

  model_events() {
    super.model_events();

    this.listenTo(
      this.model,
      'change:locations',
      function() {
        this.obj.setLatLngs(this.model.get('locations'));
      },
      this
    );
  }
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/views/payments/payment_request_browsertest_base.h"
#include "chrome/browser/ui/views/payments/payment_request_dialog_view_ids.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace payments {

class PaymentRequestNoUpdateWithTest : public PaymentRequestBrowserTestBase {
 protected:
  PaymentRequestNoUpdateWithTest() {}

  void RunJavaScriptFunctionToOpenPaymentRequestUI(
      const std::string& function_name) {
    ResetEventWaiterForDialogOpened();

    content::WebContents* web_contents = GetActiveWebContents();
    ASSERT_TRUE(content::ExecuteScript(web_contents, function_name + "();"));

    WaitForObservedEvent();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(PaymentRequestNoUpdateWithTest);
};

// A merchant that does not listen to shipping address update events will not
// cause timeouts in UI.
IN_PROC_BROWSER_TEST_F(PaymentRequestNoUpdateWithTest, BuyWithoutListeners) {
  NavigateTo("/payment_request_no_update_with_test.html");
  autofill::AutofillProfile billing_address = autofill::test::GetFullProfile();
  AddAutofillProfile(billing_address);
  AddAutofillProfile(autofill::test::GetFullProfile2());
  autofill::CreditCard card = autofill::test::GetCreditCard();
  card.set_billing_address_id(billing_address.guid());
  AddCreditCard(card);

  RunJavaScriptFunctionToOpenPaymentRequestUI("buyWithoutListeners");

  OpenShippingAddressSectionScreen();
  ResetEventWaiterForSequence({DialogEvent::PROCESSING_SPINNER_SHOWN,
                               DialogEvent::PROCESSING_SPINNER_HIDDEN,
                               DialogEvent::SPEC_DONE_UPDATING,
                               DialogEvent::BACK_NAVIGATION});
  ClickOnChildInListViewAndWait(
      /* child_index=*/1, /*total_num_children=*/2,
      DialogViewID::SHIPPING_ADDRESS_SHEET_LIST_VIEW,
      /*wait_for_animation=*/false);
  // Wait for the animation here explicitly, otherwise
  // ClickOnChildInListViewAndWait tries to install an AnimationDelegate before
  // the animation is kicked off (since that's triggered off of the spec being
  // updated) and this hits a DCHECK.
  WaitForAnimation();

  PayWithCreditCardAndWait(base::ASCIIToUTF16("123"));

  ExpectBodyContains({"freeShipping"});
}

// A merchant that listens to shipping address update events, but does not call
// updateWith() on the event, will not cause timeouts in UI.
IN_PROC_BROWSER_TEST_F(PaymentRequestNoUpdateWithTest,
                       BuyWithoutCallingUpdateWith) {
  NavigateTo("/payment_request_no_update_with_test.html");
  autofill::AutofillProfile billing_address = autofill::test::GetFullProfile();
  AddAutofillProfile(billing_address);
  AddAutofillProfile(autofill::test::GetFullProfile2());
  autofill::CreditCard card = autofill::test::GetCreditCard();
  card.set_billing_address_id(billing_address.guid());
  AddCreditCard(card);

  RunJavaScriptFunctionToOpenPaymentRequestUI("buyWithoutCallingUpdateWith");

  OpenShippingAddressSectionScreen();
  ResetEventWaiterForSequence({DialogEvent::PROCESSING_SPINNER_SHOWN,
                               DialogEvent::PROCESSING_SPINNER_HIDDEN,
                               DialogEvent::SPEC_DONE_UPDATING,
                               DialogEvent::BACK_NAVIGATION});
  ClickOnChildInListViewAndWait(
      /* child_index=*/1, /*total_num_children=*/2,
      DialogViewID::SHIPPING_ADDRESS_SHEET_LIST_VIEW,
      /*wait_for_animation=*/false);
  // Wait for the animation here explicitly, otherwise
  // ClickOnChildInListViewAndWait tries to install an AnimationDelegate before
  // the animation is kicked off (since that's triggered off of the spec being
  // updated) and this hits a DCHECK.
  WaitForAnimation();

  PayWithCreditCardAndWait(base::ASCIIToUTF16("123"));

  ExpectBodyContains({"freeShipping"});
}

// A merchant that invokes updateWith() directly without using a promise will
// not cause timeouts in UI.
IN_PROC_BROWSER_TEST_F(PaymentRequestNoUpdateWithTest, BuyWithoutPromises) {
  NavigateTo("/payment_request_no_update_with_test.html");
  autofill::AutofillProfile billing_address = autofill::test::GetFullProfile();
  AddAutofillProfile(billing_address);
  AddAutofillProfile(autofill::test::GetFullProfile2());
  autofill::CreditCard card = autofill::test::GetCreditCard();
  card.set_billing_address_id(billing_address.guid());
  AddCreditCard(card);

  RunJavaScriptFunctionToOpenPaymentRequestUI("buyWithoutPromises");

  OpenOrderSummaryScreen();
  EXPECT_EQ(base::ASCIIToUTF16("$5.00"),
            GetLabelText(DialogViewID::ORDER_SUMMARY_TOTAL_AMOUNT_LABEL));
  ClickOnBackArrow();

  OpenShippingAddressSectionScreen();
  ResetEventWaiterForSequence({DialogEvent::PROCESSING_SPINNER_SHOWN,
                               DialogEvent::PROCESSING_SPINNER_HIDDEN,
                               DialogEvent::SPEC_DONE_UPDATING,
                               DialogEvent::BACK_NAVIGATION});
  ClickOnChildInListViewAndWait(
      /* child_index=*/1, /*total_num_children=*/2,
      DialogViewID::SHIPPING_ADDRESS_SHEET_LIST_VIEW,
      /*wait_for_animation=*/false);
  // Wait for the animation here explicitly, otherwise
  // ClickOnChildInListViewAndWait tries to install an AnimationDelegate before
  // the animation is kicked off (since that's triggered off of the spec being
  // updated) and this hits a DCHECK.
  WaitForAnimation();

  OpenOrderSummaryScreen();
  EXPECT_EQ(base::ASCIIToUTF16("$10.00"),
            GetLabelText(DialogViewID::ORDER_SUMMARY_TOTAL_AMOUNT_LABEL));
  ClickOnBackArrow();

  PayWithCreditCardAndWait(base::ASCIIToUTF16("123"));

  ExpectBodyContains({"updatedShipping"});
}

}  // namespace payments


text:
<?php

use yii\db\Migration;

/**
 * Handles the creation for table `cashflow`.
 */
class m161112_142140_create_cashflow_table extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {
        $this->createTable('{{%cashflow}}', [
            'id' => $this->primaryKey(),
            'type' => $this->smallInteger()->defaultValue(0)->comment('0-Затраты, 1-Приход'),
            'description' => $this->string()->comment('Краткое описание действия'),
            'order_id' => $this->integer()->notNull()->comment('Номер заказа'),
            'value' => $this->float()->defaultValue(0)->comment('Сумма(руб.)')
        ], 'CHARACTER SET utf8');
        $this->createIndex('cashflow_order_id', '{{%cashflow}}', 'order_id');
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        $this->dropTable('{{%cashflow}}');
    }
}


text:
package presence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.symphonyoss.client.SymphonyClient;
import org.symphonyoss.client.SymphonyClientConfig;
import org.symphonyoss.client.SymphonyClientFactory;
import org.symphonyoss.symphony.clients.model.SymPresence;

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

/**
 * Simple example to set user presence.
 *

 * It will send a message to a call.home.user and listen/create new Chat sessions.
 *

 *

 *

 * REQUIRED VM Arguments or System Properties:
 *

 * -Dtruststore.file=
 * -Dtruststore.password=password
 * -Dsessionauth.url=https://(hostname)/sessionauth
 * -Dkeyauth.url=https://(hostname)/keyauth
 * -Duser.call.home=frank.tarsillo@markit.com
 * -Duser.cert.password=password
 * -Duser.cert.file=bot.user2.p12
 * -Duser.email=bot.user2@domain.com
 * -Dpod.url=https://(pod host)/pod
 * -Dagent.url=https://(agent server host)/agent
 * -Dreceiver.email=bot.user2@markit.com or bot user email
 *
 * @author Frank Tarsillo
 */
//NOSONAR
public class SetPresenceExample {

    private final Logger logger = LoggerFactory.getLogger(SetPresenceExample.class);
    private SymphonyClient symClient;

    public SetPresenceExample() {

        init();

    }

    public static void main(String[] args) {

        new SetPresenceExample();

    }

    public void init() {

        logger.info("Presence Service example starting...");

        try {

            //Create an initialized client
            symClient = SymphonyClientFactory.getClient(
                    SymphonyClientFactory.TYPE.V4, new SymphonyClientConfig(true));

            List<SymPresence> presences = new ArrayList<>();
            SymPresence symPresence = new SymPresence();
            symPresence.setCategory(SymPresence.Category.BUSY);
            presences.add(symPresence);
            symPresence = new SymPresence();
            symPresence.setCategory(SymPresence.Category.AWAY);
            presences.add(symPresence);
            symPresence = new SymPresence();
            symPresence.setCategory(SymPresence.Category.AVAILABLE);
            presences.add(symPresence);

            for (SymPresence p : presences) {
                symClient.getPresenceClient().setUserPresence(p);

                logger.info("SET PRESENCE TO: {} ", p.getCategory().toString());
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

            symClient.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}


text:
local BaseDao = require "kong.dao.cassandra.base_dao"
local apis_schema = require "kong.dao.schemas.apis"
local query_builder = require "kong.dao.cassandra.query_builder"

local Apis = BaseDao:extend()

function Apis:new(properties)
  self._table = "apis"
  self._schema = apis_schema
  Apis.super.new(self, properties)
end

function Apis:find_all()
  local apis = {}
  local select_q = query_builder.select(self._table)
  for rows, err in Apis.super.execute(self, select_q, nil, nil, {auto_paging=true}) do
    if err then
      return nil, err
    end

    for _, row in ipairs(rows) do
      table.insert(apis, row)
    end
  end

  return apis
end

-- @override
function Apis:delete(where_t)
  local ok, err = Apis.super.delete(self, where_t)
  if not ok then
    return false, err
  end

  -- delete all related plugins configurations
  local plugins_dao = self._factory.plugins_configurations
  local select_q, columns = query_builder.select(plugins_dao._table, {api_id = where_t.id}, plugins_dao._column_family_details)

  for rows, err in plugins_dao:execute(select_q, columns, {api_id = where_t.id}, {auto_paging = true}) do
    if err then
      return nil, err
    end

    for _, row in ipairs(rows) do
      local ok_del_plugin, err = plugins_dao:delete({id = row.id})
      if not ok_del_plugin then
        return nil, err
      end
    end
  end

  return ok
end

return {apis = Apis}


text:
/* -*-C++-*-
 *****************************************************************************
 *
 * File:         Describe.C
 * Description:
 *
 * Created:      4/15/95
 * Language:     C++
 * Status:       $State: Exp $
 *
 *
 *****************************************************************************
 */

#ifndef __CMP_DESCRIBE_H
#define __CMP_DESCRIBE_H

#include "NABoolean.h"
#include "ComVersionDefs.h"

class ExeCliInterface;

short exeImmedOneStmt(const char *stmt);
//short exeImmedOneStmt(void *in_sql_src,
//		      const char *stmt);

short sendAllControls(NABoolean copyCQS,
                      NABoolean sendAllCQDs,
                      NABoolean sendUserCQDs,
                      enum COM_VERSION versionOfCmplrRcvCntrlInfo
                           = COM_VERS_COMPILER_VERSION,
                      NABoolean sendUserCSs = TRUE,
                      CmpContext* prevContext = NULL);

void sendParserFlag (ULng32 flag);

short setParentQidAtSession(NAHeap *heap, const char *parentQid);

#endif


text:
CREATE DATABASE phpesp;

-- # Switch to the mysql database.
USE mysql;

-- # Create a user called 'phpesp', with a password 'phpesp'. The
-- # 'localhost' limits this user to connecting to the database only via
-- # localhost. You may change the password by changing the
-- # PASSWORD('...') clause.
INSERT INTO user (host, user, password) VALUES ( 'localhost',
  'phpesp', PASSWORD('phpesp'));

-- # Grant the 'phpesp' user (from 'localhost') privileges to select,
-- # insert, update, and delete on the database 'phpesp'.
INSERT INTO db (host, db, user, select_priv, insert_priv,
  update_priv, delete_priv) VALUES ( 'localhost', 'phpesp',
  'phpesp', 'Y', 'Y', 'Y', 'Y');

-- # Tell mysql to re-read the privileges tables so the previous two
-- # operations take effect.
FLUSH PRIVILEGES;


text:
class MxitMoneyApi

  def issue_money(params)
    params = Hash[params.map {|k, v| [k.to_s.camelize(:lower), v] }]
    url = URI.parse("#{BASE_URL}/paymentsplatform/rest/v3/push/issue/#{params.delete('phoneNumber')}?#{params.to_query}")
    req = Net::HTTP::Post.new(url.to_s,
                              'Accept'=>'application/json',
                              'Content-Type' =>'application/json')
    req.basic_auth(api_key, 'mxit_money_api'.to_s)
    response = Net::HTTP.start(url.host, url.port,
                               :use_ssl => url.scheme == 'https',
                               :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https|
      https.request(req)
    end
    if response.code == '200' || response.code == '401' || response.code == '500' || response.code == '400'
      @balance = nil
      data = ActiveSupport::JSON.decode(response.body)
      HashWithIndifferentAccess.new(Hash[data.map {|k, v| [k.underscore, v] }])
    end
  end

end


text:
package aot.util;

/**
 * @author Dmitry Kotlyarov
 * @since 1.0
 */
public class XmlBinarilizer<T> extends Binarilizer<T> {
    private static final long serialVersionUID = 1;

    public XmlBinarilizer(Class<T> type) {
        super(type);
    }

    @Override
    public byte[] binarilize(T object) {
        return XmlUtil.toBytes(object);
    }

    @Override
    public T debinarilize(byte[] bytes) {
        return XmlUtil.fromBytes(bytes, type);
    }
}


text:
const express = require('express')
const recipient = require('../../database/recipient')

const router = express.Router()

const getTags = (req, res, next) => {
  recipient.getTags()
  .then(tags => {
    res.json(tags)
  })
  .catch(next)
}

const tag = (req, res, next) => {
  recipient.tag(req.body.accountId, req.body.tag)
  .then(() => res.end())
  .catch(err => res.send(err))
}

const untag = (req, res, next) => {
  recipient.untag(req.body.accountId, req.body.tag)
  .then(() => res.end())
}

router.get('/tags', getTags)
router.put('/tag', tag)
router.delete('/tag', untag)

module.exports = router


text:
layout: post
title: "Test Environment Setup in Visual Studio"
tags: ["test", "nunit", "setup", "vs", "visual studio", "2012", "2013"]
---

Unit testing is good, TDD is even better. To smooth out the workflow in Visual Studio, I will present some of my favourite ways of setting up NUnit in my projects, and hopefully that helps win some skeptics whom think it is too much hassle doing TDD back.

# Project setup

In a typical project setup, you should have one test project per source project with [NUnit](https://www.nuget.org/packages/nunit/) referenced.

{% include image.html url="/media/2014-09-04-test-environment-setup-in-vs/test-01.png" width="100%" description="A typical source and test setup" %}

# NUnit Executable

One way of using NUnit is quite manual, which you need to install [NUnit](http://nunit.org/?p=download) to your system.

By configuring a test runner with `.nunit` extension in the following format,

{% highlight xml %}
<NUnitProject>
  <Settings activeconfig="Debug" />
  <Config name="Debug" binpathtype="Auto">
    <assembly path="Playground.Tests\bin\Debug\Playground.Tests.dll" />
  </Config>
  <Config name="Release" binpathtype="Auto">
    <assembly path="Playground.Tests\bin\Release\Playground.Tests.dll" />
  </Config>
</NUnitProject>
{% endhighlight %}

You now have an executable NUnit file. When opening up the file, you should be one click away from running the tests.

{% include image.html url="/media/2014-09-04-test-environment-setup-in-vs/test-05.png" width="100%" description="NUnit control pannel" %}

Click `Run`, and ta-da.

{% include image.html url="/media/2014-09-04-test-environment-setup-in-vs/test-06.png" width="100%" description="NUnit control pannel after running the tests" %}

# NUnit Extension in Visual Studio

A more seamless way of using NUnit in Visual Studio is: go to `TOOLS` -> `Extensions and Updates`, find the `NUnit Test Adapter` in Visual Studio online gallery and install it.

{% include image.html url="/media/2014-09-04-test-environment-setup-in-vs/test-02.png" width="100%" description="NUnit test adapter plugin" %}

Now again in Visual Studio, if you navigate to `TEST` -> `Windows` -> `Test Explorer`, you should be able to see `Test Explorer` panel hanging over Visual Studio.

{% include image.html url="/media/2014-09-04-test-environment-setup-in-vs/test-03.png" width="100%" description="Test Explorer window with a dummy test I created" %}

With the `Run All` and other execution options available, you should try to push the buttons as often as possible when developing. On a good day or in your dream, you will always get this.

{% include image.html url="/media/2014-09-04-test-environment-setup-in-vs/test-04.png" width="100%" description="Test Explorer window with a dummy test I created" %}

# Resharper

The last and the most expensive way, is to install [Resharper](http://www.jetbrains.com/resharper/download/). It's undeniably costly, yet you are more likely to gain a lot of time in return in the long run.

And since we are in Resharper world, you can either use Reshaper shortcut `Ctrl+ T, R`, or more generic Visual Studio shortcut `Alt+ R, U, N` to execute the tests like a pro.

And you surely will not miss what pops up onto your screen.

{% include image.html url="/media/2014-09-04-test-environment-setup-in-vs/test-07.png" width="100%" description="Resharper Unit Test Session" %}

# Conclusion

In my opinion, even though Resharper is not a cheap option, but you do get a lot of other cool refactor functionalities, and smoother workflow.

If budget is a concern, to setup your own NUnit runners is still going to make your life a lot easier, and I will personally go for the NUnit extension to make testing independent from the PC being used, and save the hassle of re-configuration whenever you need to add a new project.


text:
"""LogPane class."""

import functools
import logging
import re
import time
from typing import (
    Any,
    Callable,
    List,
    Optional,
    TYPE_CHECKING,
    Tuple,
    Union,
)

from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import (
    Condition,
    has_focus,
)
from prompt_toolkit.formatted_text import StyleAndTextTuples
from prompt_toolkit.key_binding import (
    KeyBindings,
    KeyPressEvent,
    KeyBindingsBase,
)
from prompt_toolkit.layout import (
    ConditionalContainer,
    Float,
    FloatContainer,
    FormattedTextControl,
    HSplit,
    UIContent,
    UIControl,
    VerticalAlign,
    VSplit,
    Window,
    WindowAlign,
)
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType, MouseButton

import pw_console.widgets.checkbox
import pw_console.style
from pw_console.log_view import LogView
from pw_console.log_pane_toolbars import (
    LineInfoBar,
    TableToolbar,
)
from pw_console.log_pane_saveas_dialog import LogPaneSaveAsDialog
from pw_console.log_pane_selection_dialog import LogPaneSelectionDialog
from pw_console.log_store import LogStore
from pw_console.search_toolbar import SearchToolbar
from pw_console.filter_toolbar import FilterToolbar
from pw_console.widgets import (
    ToolbarButton,
    WindowPane,
    WindowPaneHSplit,
    WindowPaneToolbar,
)

if TYPE_CHECKING:
    from pw_console.console_app import ConsoleApp

_LOG_OUTPUT_SCROLL_AMOUNT = 5
_LOG = logging.getLogger(__package__)

class LogContentControl(UIControl):
    """LogPane prompt_toolkit UIControl for displaying LogContainer lines."""
    def __init__(self, log_pane: 'LogPane') -> None:
        # pylint: disable=too-many-locals
        self.log_pane = log_pane
        self.log_view = log_pane.log_view

        # Mouse drag visual selection flags.
        self.visual_select_mode_drag_start = False
        self.visual_select_mode_drag_stop = False

        self.uicontent: Optional[UIContent] = None
        self.lines: List[StyleAndTextTuples] = []

        # Key bindings.
        key_bindings = KeyBindings()
        register = log_pane.application.prefs.register_keybinding

        @register('log-pane.shift-line-to-top', key_bindings)
        def _shift_log_to_top(_event: KeyPressEvent) -> None:
            """Shift the selected log line to the top."""
            self.log_view.move_selected_line_to_top()

        @register('log-pane.shift-line-to-center', key_bindings)
        def _shift_log_to_center(_event: KeyPressEvent) -> None:
            """Shift the selected log line to the center."""
            self.log_view.center_log_line()

        @register('log-pane.toggle-wrap-lines', key_bindings)
        def _toggle_wrap_lines(_event: KeyPressEvent) -> None:
            """Toggle log line wrapping."""
            self.log_pane.toggle_wrap_lines()

        @register('log-pane.toggle-table-view', key_bindings)
        def _toggle_table_view(_event: KeyPressEvent) -> None:
            """Toggle table view."""
            self.log_pane.toggle_table_view()

        @register('log-pane.duplicate-log-pane', key_bindings)
        def _duplicate(_event: KeyPressEvent) -> None:
            """Duplicate this log pane."""
            self.log_pane.duplicate()

        @register('log-pane.remove-duplicated-log-pane', key_bindings)
        def _delete(_event: KeyPressEvent) -> None:
            """Remove log pane."""
            if self.log_pane.is_a_duplicate:
                self.log_pane.application.window_manager.remove_pane(
                    self.log_pane)

        @register('log-pane.clear-history', key_bindings)
        def _clear_history(_event: KeyPressEvent) -> None:
            """Clear log pane history."""
            self.log_pane.clear_history()

        @register('log-pane.scroll-to-top', key_bindings)
        def _scroll_to_top(_event: KeyPressEvent) -> None:
            """Scroll to top."""
            self.log_view.scroll_to_top()

        @register('log-pane.scroll-to-bottom', key_bindings)
        def _scroll_to_bottom(_event: KeyPressEvent) -> None:
            """Scroll to bottom."""
            self.log_view.scroll_to_bottom()

        @register('log-pane.toggle-follow', key_bindings)
        def _toggle_follow(_event: KeyPressEvent) -> None:
            """Toggle log line following."""
            self.log_pane.toggle_follow()

        @register('log-pane.toggle-web-browser', key_bindings)
        def _toggle_browser(_event: KeyPressEvent) -> None:
            """View logs in browser."""
            self.log_pane.toggle_websocket_server()

        @register('log-pane.move-cursor-up', key_bindings)
        def _up(_event: KeyPressEvent) -> None:
            """Move cursor up."""
            self.log_view.scroll_up()

        @register('log-pane.move-cursor-down', key_bindings)
        def _down(_event: KeyPressEvent) -> None:
            """Move cursor down."""
            self.log_view.scroll_down()

        @register('log-pane.visual-select-up', key_bindings)
        def _visual_select_up(_event: KeyPressEvent) -> None:
            """Select previous log line."""
            self.log_view.visual_select_up()

        @register('log-pane.visual-select-down', key_bindings)
        def _visual_select_down(_event: KeyPressEvent) -> None:
            """Select next log line."""
            self.log_view.visual_select_down()

        @register('log-pane.scroll-page-up', key_bindings)
        def _pageup(_event: KeyPressEvent) -> None:
            """Scroll the logs up by one page."""
            self.log_view.scroll_up_one_page()

        @register('log-pane.scroll-page-down', key_bindings)
        def _pagedown(_event: KeyPressEvent) -> None:
            """Scroll the logs down by one page."""
            self.log_view.scroll_down_one_page()

        @register('log-pane.save-copy', key_bindings)
        def _start_saveas(_event: KeyPressEvent) -> None:
            """Save logs to a file."""
            self.log_pane.start_saveas()

        @register('log-pane.search', key_bindings)
        def _start_search(_event: KeyPressEvent) -> None:
            """Start searching."""
            self.log_pane.start_search()

        @register('log-pane.search-next-match', key_bindings)
        def _next_search(_event: KeyPressEvent) -> None:
            """Next search match."""
            self.log_view.search_forwards()

        @register('log-pane.search-previous-match', key_bindings)
        def _previous_search(_event: KeyPressEvent) -> None:
            """Previous search match."""
            self.log_view.search_backwards()

        @register('log-pane.visual-select-all', key_bindings)
        def _select_all_logs(_event: KeyPressEvent) -> None:
            """Clear search."""
            self.log_pane.log_view.visual_select_all()

        @register('log-pane.deselect-cancel-search', key_bindings)
        def _clear_search_and_selection(_event: KeyPressEvent) -> None:
            """Clear selection or search."""
            if self.log_pane.log_view.visual_select_mode:
                self.log_pane.log_view.clear_visual_selection()
            elif self.log_pane.search_bar_active:
                self.log_pane.search_toolbar.cancel_search()

        @register('log-pane.search-apply-filter', key_bindings)
        def _apply_filter(_event: KeyPressEvent) -> None:
            """Apply current search as a filter."""
            self.log_pane.search_toolbar.close_search_bar()
            self.log_view.apply_filter()

        @register('log-pane.clear-filters', key_bindings)
        def _clear_filter(_event: KeyPressEvent) -> None:
            """Reset / erase active filters."""
            self.log_view.clear_filters()

        self.key_bindings: KeyBindingsBase = key_bindings

    def is_focusable(self) -> bool:
        return True

    def get_key_bindings(self) -> Optional[KeyBindingsBase]:
        return self.key_bindings

    def preferred_width(self, max_available_width: int) -> int:
        """Return the width of the longest line."""
        line_lengths = [len(l) for l in self.lines]
        return max(line_lengths)

    def preferred_height(
        self,
        width: int,
        max_available_height: int,
        wrap_lines: bool,
        get_line_prefix,
    ) -> Optional[int]:
        """Return the preferred height for the log lines."""
        content = self.create_content(width, None)
        return content.line_count

    def create_content(self, width: int, height: Optional[int]) -> UIContent:
        # Update lines to render
        self.lines = self.log_view.render_content()

        # Create a UIContent instance if none exists
        if self.uicontent is None:
            self.uicontent = UIContent(get_line=lambda i: self.lines[i],
                                       line_count=len(self.lines),
                                       show_cursor=False)

        # Update line_count
        self.uicontent.line_count = len(self.lines)

        return self.uicontent

    def mouse_handler(self, mouse_event: MouseEvent):
        """Mouse handler for this control."""
        mouse_position = mouse_event.position

        # Left mouse button release should:
        # 1. check if a mouse drag just completed.
        # 2. If not in focus, switch focus to this log pane
        #    If in focus, move the cursor to that position.
        if (mouse_event.event_type == MouseEventType.MOUSE_UP
                and mouse_event.button == MouseButton.LEFT):

            # If a drag was in progress and this is the first mouse release
            # press, set the stop flag.
            if (self.visual_select_mode_drag_start
                    and not self.visual_select_mode_drag_stop):
                self.visual_select_mode_drag_stop = True

            if not has_focus(self)():
                # Focus the save as dialog if open.
                if self.log_pane.saveas_dialog_active:
                    get_app().layout.focus(self.log_pane.saveas_dialog)
                # Focus the search bar if open.
                elif self.log_pane.search_bar_active:
                    get_app().layout.focus(self.log_pane.search_toolbar)
                # Otherwise, focus on the log pane content.
                else:
                    get_app().layout.focus(self)
                # Mouse event handled, return None.
                return None

            # Log pane in focus already, move the cursor to the position of the
            # mouse click.
            self.log_pane.log_view.scroll_to_position(mouse_position)
            # Mouse event handled, return None.
            return None

        # Mouse drag with left button should start selecting lines.
        # The log pane does not need to be in focus to start this.
        if (mouse_event.event_type == MouseEventType.MOUSE_MOVE
                and mouse_event.button == MouseButton.LEFT):
            # If a previous mouse drag was completed, clear the selection.
            if (self.visual_select_mode_drag_start
                    and self.visual_select_mode_drag_stop):
                self.log_pane.log_view.clear_visual_selection()
            # Drag select in progress, set flags accordingly.
            self.visual_select_mode_drag_start = True
            self.visual_select_mode_drag_stop = False

            self.log_pane.log_view.visual_select_line(mouse_position)
            # Mouse event handled, return None.
            return None

        # Mouse wheel events should move the cursor +/- some amount of lines
        # even if this pane is not in focus.
        if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
            self.log_pane.log_view.scroll_down(lines=_LOG_OUTPUT_SCROLL_AMOUNT)
            # Mouse event handled, return None.
            return None

        if mouse_event.event_type == MouseEventType.SCROLL_UP:
            self.log_pane.log_view.scroll_up(lines=_LOG_OUTPUT_SCROLL_AMOUNT)
            # Mouse event handled, return None.
            return None

        # Mouse event not handled, return NotImplemented.
        return NotImplemented

class LogPaneWebsocketDialog(ConditionalContainer):
    """Dialog box for showing the websocket URL."""
    # Height of the dialog box contens in lines of text.
    DIALOG_HEIGHT = 2

    def __init__(self, log_pane: 'LogPane'):
        self.log_pane = log_pane

        self._last_action_message: str = ''
        self._last_action_time: float = 0

        info_bar_control = FormattedTextControl(self.get_info_fragments)
        info_bar_window = Window(content=info_bar_control,
                                 height=1,
                                 align=WindowAlign.LEFT,
                                 dont_extend_width=False)

        message_bar_control = FormattedTextControl(self.get_message_fragments)
        message_bar_window = Window(content=message_bar_control,
                                    height=1,
                                    align=WindowAlign.RIGHT,
                                    dont_extend_width=False)

        action_bar_control = FormattedTextControl(self.get_action_fragments)
        action_bar_window = Window(content=action_bar_control,
                                   height=1,
                                   align=WindowAlign.RIGHT,
                                   dont_extend_width=True)

        super().__init__(
            pw_console.widgets.border.create_border(
                HSplit(
                    [
                        info_bar_window,
                        VSplit([message_bar_window, action_bar_window]),
                    ],
                    height=LogPaneWebsocketDialog.DIALOG_HEIGHT,
                    style='class:saveas-dialog',
                ),
                content_height=LogPaneWebsocketDialog.DIALOG_HEIGHT,
                title='Websocket Log Server',
                border_style='class:saveas-dialog-border',
                left_margin_columns=1,
            ),
            filter=Condition(lambda: self.log_pane.websocket_dialog_active),
        )

    def focus_self(self) -> None:
        # Nothing in this dialog can be focused, focus on the parent log_pane
        # instead.
        self.log_pane.application.focus_on_container(self.log_pane)

    def close_dialog(self) -> None:
        """Close this dialog."""
        self.log_pane.toggle_websocket_server()
        self.log_pane.websocket_dialog_active = False
        self.log_pane.application.focus_on_container(self.log_pane)
        self.log_pane.redraw_ui()

    def _set_action_message(self, text: str) -> None:
        self._last_action_time = time.time()
        self._last_action_message = text

    def copy_url_to_clipboard(self) -> None:
        self.log_pane.application.application.clipboard.set_text(
            self.log_pane.log_view.get_web_socket_url())
        self._set_action_message('Copied!')

    def get_message_fragments(self):
        """Return FormattedText with the last action message."""
        # Mouse handlers
        focus = functools.partial(pw_console.widgets.mouse_handlers.on_click,
                                  self.focus_self)
        # Separator should have the focus mouse handler so clicking on any
        # whitespace focuses the input field.
        separator_text = ('', '  ', focus)

        if self._last_action_time + 10 > time.time():
            return [
                ('class:theme-fg-yellow', self._last_action_message, focus),
                separator_text,
            ]
        return [separator_text]

    def get_info_fragments(self):
        """Return FormattedText with current URL info."""
        # Mouse handlers
        focus = functools.partial(pw_console.widgets.mouse_handlers.on_click,
                                  self.focus_self)
        # Separator should have the focus mouse handler so clicking on any
        # whitespace focuses the input field.
        separator_text = ('', '  ', focus)

        fragments = [
            ('class:saveas-dialog-setting', 'URL:  ', focus),
            ('class:saveas-dialog-title',
             self.log_pane.log_view.get_web_socket_url(), focus),
            separator_text,
        ]
        return fragments

    def get_action_fragments(self):
        """Return FormattedText with the action buttons."""
        # Mouse handlers
        focus = functools.partial(pw_console.widgets.mouse_handlers.on_click,
                                  self.focus_self)
        cancel = functools.partial(pw_console.widgets.mouse_handlers.on_click,
                                   self.close_dialog)
        copy = functools.partial(pw_console.widgets.mouse_handlers.on_click,
                                 self.copy_url_to_clipboard)

        # Separator should have the focus mouse handler so clicking on any
        # whitespace focuses the input field.
        separator_text = ('', '  ', focus)

        # Default button style
        button_style = 'class:toolbar-button-inactive'

        fragments = []

        # Action buttons
        fragments.extend(
            pw_console.widgets.checkbox.to_keybind_indicator(
                key=None,
                description='Stop',
                mouse_handler=cancel,
                base_style=button_style,
            ))

        fragments.append(separator_text)
        fragments.extend(
            pw_console.widgets.checkbox.to_keybind_indicator(
                key=None,
                description='Copy to Clipboard',
                mouse_handler=copy,
                base_style=button_style,
            ))

        # One space separator
        fragments.append(('', ' ', focus))

        return fragments

class LogPane(WindowPane):
    """LogPane class."""

    # pylint: disable=too-many-instance-attributes,too-many-public-methods

    def __init__(
        self,
        application: Any,
        pane_title: str = 'Logs',
        log_store: Optional[LogStore] = None,
    ):
        super().__init__(application, pane_title)

        # TODO(tonymd): Read these settings from a project (or user) config.
        self.wrap_lines = False
        self._table_view = True
        self.is_a_duplicate = False

        # Create the log container which stores and handles incoming logs.
        self.log_view: LogView = LogView(self,
                                         self.application,
                                         log_store=log_store)

        # Log pane size variables. These are updated just befor rendering the
        # pane by the LogLineHSplit class.
        self.current_log_pane_width = 0
        self.current_log_pane_height = 0
        self.last_log_pane_width = None
        self.last_log_pane_height = None

        # Search tracking
        self.search_bar_active = False
        self.search_toolbar = SearchToolbar(self)
        self.filter_toolbar = FilterToolbar(self)

        self.saveas_dialog = LogPaneSaveAsDialog(self)
        self.saveas_dialog_active = False
        self.visual_selection_dialog = LogPaneSelectionDialog(self)

        self.websocket_dialog = LogPaneWebsocketDialog(self)
        self.websocket_dialog_active = False

        # Table header bar, only shown if table view is active.
        self.table_header_toolbar = TableToolbar(self)

        # Create the bottom toolbar for the whole log pane.
        self.bottom_toolbar = WindowPaneToolbar(self)
        self.bottom_toolbar.add_button(
            ToolbarButton('/', 'Search', self.start_search))
        self.bottom_toolbar.add_button(
            ToolbarButton('Ctrl-o', 'Save', self.start_saveas))
        self.bottom_toolbar.add_button(
            ToolbarButton('f',
                          'Follow',
                          self.toggle_follow,
                          is_checkbox=True,
                          checked=lambda: self.log_view.follow))
        self.bottom_toolbar.add_button(
            ToolbarButton('t',
                          'Table',
                          self.toggle_table_view,
                          is_checkbox=True,
                          checked=lambda: self.table_view))
        self.bottom_toolbar.add_button(
            ToolbarButton('w',
                          'Wrap',
                          self.toggle_wrap_lines,
                          is_checkbox=True,
                          checked=lambda: self.wrap_lines))
        self.bottom_toolbar.add_button(
            ToolbarButton('C', 'Clear', self.clear_history))

        self.bottom_toolbar.add_button(
            ToolbarButton('Shift-o',
                          'Open in browser',
                          self.toggle_websocket_server,
                          is_checkbox=True,
                          checked=lambda: self.log_view.websocket_running))

        self.log_content_control = LogContentControl(self)

        self.log_display_window = Window(
            content=self.log_content_control,
            # Scrolling is handled by LogScreen
            allow_scroll_beyond_bottom=False,
            # Line wrapping is handled by LogScreen
            wrap_lines=False,
            # Selected line highlighting is handled by LogScreen
            cursorline=False,
            # Don't make the window taller to fill the parent split container.
            # Window should match the height of the log line content. This will
            # also allow the parent HSplit to justify the content to the bottom
            dont_extend_height=True,
            # Window width should be extended to make backround highlighting
            # extend to the end of the container. Otherwise backround colors
            # will only appear until the end of the log line.
            dont_extend_width=False,
            # Needed for log lines ANSI sequences that don't specify foreground
            # or background colors.
            style=functools.partial(pw_console.style.get_pane_style, self),
        )

        # Root level container
        self.container = ConditionalContainer(
            FloatContainer(
                # Horizonal split containing the log lines and the toolbar.
                WindowPaneHSplit(
                    self,  # LogPane reference
                    [
                        self.table_header_toolbar,
                        self.log_display_window,
                        self.filter_toolbar,
                        self.search_toolbar,
                        self.bottom_toolbar,
                    ],
                    # Align content with the bottom of the container.
                    align=VerticalAlign.BOTTOM,
                    height=lambda: self.height,
                    width=lambda: self.width,
                    style=functools.partial(pw_console.style.get_pane_style,
                                            self),
                ),
                floats=[
                    Float(top=0, right=0, height=1, content=LineInfoBar(self)),
                    Float(top=0,
                          right=0,
                          height=LogPaneSelectionDialog.DIALOG_HEIGHT,
                          content=self.visual_selection_dialog),
                    Float(top=3,
                          left=2,
                          right=2,
                          height=LogPaneSaveAsDialog.DIALOG_HEIGHT + 2,
                          content=self.saveas_dialog),
                    Float(top=1,
                          left=2,
                          right=2,
                          height=LogPaneWebsocketDialog.DIALOG_HEIGHT + 2,
                          content=self.websocket_dialog),
                ]),
            filter=Condition(lambda: self.show_pane))

    @property
    def table_view(self):
        if self.log_view.websocket_running:
            return False
        return self._table_view

    @table_view.setter
    def table_view(self, table_view):
        self._table_view = table_view

    def menu_title(self):
        """Return the title to display in the Window menu."""
        title = self.pane_title()

        # List active filters
        if self.log_view.filtering_on:
            title += ' (FILTERS: '
            title += ' '.join([
                log_filter.pattern()
                for log_filter in self.log_view.filters.values()
            ])
            title += ')'
        return title

    def append_pane_subtitle(self, text):
        if not self._pane_subtitle:
            self._pane_subtitle = text
        else:
            self._pane_subtitle = self._pane_subtitle + ', ' + text

    def pane_subtitle(self) -> str:
        if not self._pane_subtitle:
            return ', '.join(self.log_view.log_store.channel_counts.keys())
        logger_names = self._pane_subtitle.split(', ')
        additional_text = ''
        if len(logger_names) > 1:
            additional_text = ' + {} more'.format(len(logger_names))

        return logger_names[0] + additional_text

    def start_search(self):
        """Show the search bar to begin a search."""
        if self.log_view.websocket_running:
            return
        # Show the search bar
        self.search_bar_active = True
        # Focus on the search bar
        self.application.focus_on_container(self.search_toolbar)

    def start_saveas(self, **export_kwargs) -> bool:
        """Show the saveas bar to begin saving logs to a file."""
        # Show the search bar
        self.saveas_dialog_active = True
        # Set export options if any
        self.saveas_dialog.set_export_options(**export_kwargs)
        # Focus on the search bar
        self.application.focus_on_container(self.saveas_dialog)
        return True

    def pane_resized(self) -> bool:
        """Return True if the current window size has changed."""
        return (self.last_log_pane_width != self.current_log_pane_width
                or self.last_log_pane_height != self.current_log_pane_height)

    def update_pane_size(self, width, height):
        """Save width and height of the log pane for the current UI render
        pass."""
        if width:
            self.last_log_pane_width = self.current_log_pane_width
            self.current_log_pane_width = width
        if height:
            # Subtract the height of the bottom toolbar
            height -= WindowPaneToolbar.TOOLBAR_HEIGHT
            if self._table_view:
                height -= TableToolbar.TOOLBAR_HEIGHT
            if self.search_bar_active:
                height -= SearchToolbar.TOOLBAR_HEIGHT
            if self.log_view.filtering_on:
                height -= FilterToolbar.TOOLBAR_HEIGHT
            self.last_log_pane_height = self.current_log_pane_height
            self.current_log_pane_height = height

    def toggle_table_view(self):
        """Enable or disable table view."""
        self._table_view = not self._table_view
        self.log_view.view_mode_changed()
        self.redraw_ui()

    def toggle_wrap_lines(self):
        """Enable or disable line wraping/truncation."""
        self.wrap_lines = not self.wrap_lines
        self.log_view.view_mode_changed()
        self.redraw_ui()

    def toggle_follow(self):
        """Enable or disable following log lines."""
        self.log_view.toggle_follow()
        self.redraw_ui()

    def clear_history(self):
        """Erase stored log lines."""
        self.log_view.clear_scrollback()
        self.redraw_ui()

    def toggle_websocket_server(self):
        """Start or stop websocket server to send logs."""
        if self.log_view.websocket_running:
            self.log_view.stop_websocket_thread()
            self.websocket_dialog_active = False
        else:
            self.search_toolbar.close_search_bar()
            self.log_view.start_websocket_thread()
            self.application.start_http_server()
            self.saveas_dialog_active = False
            self.websocket_dialog_active = True

    def get_all_key_bindings(self) -> List:
        """Return all keybinds for this pane."""
        # Return log content control keybindings
        return [self.log_content_control.get_key_bindings()]

    def get_window_menu_options(
            self) -> List[Tuple[str, Union[Callable, None]]]:
        """Return all menu options for the log pane."""

        options = [
            # Menu separator
            ('-', None),
            (
                'Save/Export a copy',
                self.start_saveas,
            ),
            ('-', None),
            (
                '{check} Line wrapping'.format(
                    check=pw_console.widgets.checkbox.to_checkbox_text(
                        self.wrap_lines, end='')),
                self.toggle_wrap_lines,
            ),
            (
                '{check} Table view'.format(
                    check=pw_console.widgets.checkbox.to_checkbox_text(
                        self._table_view, end='')),
                self.toggle_table_view,
            ),
            (
                '{check} Follow'.format(
                    check=pw_console.widgets.checkbox.to_checkbox_text(
                        self.log_view.follow, end='')),
                self.toggle_follow,
            ),
            (
                '{check} Open in web browser'.format(
                    check=pw_console.widgets.checkbox.to_checkbox_text(
                        self.log_view.websocket_running, end='')),
                self.toggle_websocket_server,
            ),
            # Menu separator
            ('-', None),
            (
                'Clear history',
                self.clear_history,
            ),
            (
                'Duplicate pane',
                self.duplicate,
            ),
        ]
        if self.is_a_duplicate:
            options += [(
                'Remove/Delete pane',
                functools.partial(self.application.window_manager.remove_pane,
                                  self),
            )]

        # Search / Filter section
        options += [
            # Menu separator
            ('-', None),
            (
                'Hide search highlighting',
                self.log_view.disable_search_highlighting,
            ),
            (
                'Create filter from search results',
                self.log_view.apply_filter,
            ),
            (
                'Clear/Reset active filters',
                self.log_view.clear_filters,
            ),
        ]

        return options

    def apply_filters_from_config(self, window_options) -> None:
        if 'filters' not in window_options:
            return

        for field, criteria in window_options['filters'].items():
            for matcher_name, search_string in criteria.items():
                inverted = matcher_name.endswith('-inverted')
                matcher_name = re.sub(r'-inverted$', '', matcher_name)
                if field == 'all':
                    field = None
                if self.log_view.new_search(
                        search_string,
                        invert=inverted,
                        field=field,
                        search_matcher=matcher_name,
                        interactive=False,
                ):
                    self.log_view.install_new_filter()

    def create_duplicate(self) -> 'LogPane':
        """Create a duplicate of this LogView."""
        new_pane = LogPane(self.application, pane_title=self.pane_title())
        # Set the log_store
        log_store = self.log_view.log_store
        new_pane.log_view.log_store = log_store
        # Register the duplicate pane as a viewer
        log_store.register_viewer(new_pane.log_view)

        # Set any existing search state.
        new_pane.log_view.search_text = self.log_view.search_text
        new_pane.log_view.search_filter = self.log_view.search_filter
        new_pane.log_view.search_matcher = self.log_view.search_matcher
        new_pane.log_view.search_highlight = self.log_view.search_highlight

        # Mark new pane as a duplicate so it can be deleted.
        new_pane.is_a_duplicate = True
        return new_pane

    def duplicate(self) -> None:
        new_pane = self.create_duplicate()
        # Add the new pane.
        self.application.window_manager.add_pane(new_pane)

    def add_log_handler(self,
                        logger: Union[str, logging.Logger],
                        level_name: Optional[str] = None) -> None:
        """Add a log handlers to this LogPane."""

        if isinstance(logger, logging.Logger):
            logger_instance = logger
        elif isinstance(logger, str):
            logger_instance = logging.getLogger(logger)

        if level_name:
            if not hasattr(logging, level_name):
                raise Exception(f'Unknown log level: {level_name}')
            logger_instance.level = getattr(logging, level_name, logging.INFO)
        logger_instance.addHandler(self.log_view.log_store  # type: ignore
                                   )
        self.append_pane_subtitle(  # type: ignore
            logger_instance.name)


text:
@echo off

if not exist distrib\bootstrap.bat (
  git submodule init
  git submodule update
)

echo Prepare config...
setlocal
  call scripts\load-config.bat
endlocal

echo Prepare stable version (distrib)...
cd distrib
call bootstrap.bat || exit /b 1
cd ..
if not exist bin\nul mkdir bin

echo Compile sources...
cd src
call make.bat

if not "%1"=="--no-tests" (
  echo Starting autotests...
  cd ..\autotests
  call run.bat
)


text:
package com.example.activity;

import com.example.dialogdemo2.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class MySimpleActivity extends Activity {

	private Button mNextDialog;

	private View back;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity2);
		mNextDialog = (Button) findViewById(R.id.simple_button);
		mNextDialog.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.setClass(MySimpleActivity.this, MySimpleActivity.class);
				startActivity(i);
			}
		});
		back = (View) findViewById(R.id.navi_back);
        back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
	}

}


text:
 - This is a pure javascript XML SAX parser for Node.js.
 - The specificity of this xml parser is that it can parse a document from a Buffer.
 - It relies on iconv-lite to decode the text according to the code page of the document.

## Install

    npm install node-xml-lite

## Simple usage

### Parse a file

    xml = require("node-xml-lite");

    xml.parseFile(filename, function(err, root){
      ...
    });

### Parse a file synchronously

    xml.parseFileSync(filename));

### Parse a string

    xml.parseString("<xml>hello</xml>");

### Parse a buffer

    xml.parseBuffer(new Buffer("<xml>hello</xml>"));

## Advanced usage

### parsing a file in SAX mode

    xml.SAXParseFile(filename,
      function(state, a, b) {
        switch (state) {
          case xml.xtOpen:
            // a is node name
            ...
            break;
          case xml.xtClose
            ...
            break;
          case xml.xtAttribute:
            // a is attribute name
            // b is attribute value
            ...
            break;
          case xml.xtText:
            // a is a text value
            break;
          case xml.xtCData:
            // a is a CDATA text value
            ...
            break;
          case xml.xtComment
            // a is a comment text value
            ...
            break;
        };
        // tell the parser to continue
        return true;
      },
      function(err){
        // parser done, check error
        ...
      }
    );

you can also use the sync function,

    xml.SAXParseFileSync(filename, event)

### providing your own data to SAX parser

    var parser = new xml.XMLParser();
    var ret = parser.parserBuffer(buffer, len, event);
    if (ret === true) {
      // stopped by event result
    } else
    if (ret === false) {
      // there is a parsing error at:
      //   parser.line
      //   parser.col
    } else
    if (ret === undefined) {
      // it is ok, continue ...
    }

you can also parse a string

    var ret = parser.parseString(str, event);


text:
Use Aerospike as cache store and/or session store for Rails.
Aerospike easily scales up and besides RAM it also supports SSD for persistency in a highly optimized architecture.
Find out more about [Aerospike](http://www.aerospike.com)

## Dependencies

[Aerospike Ruby Client](https://github.com/aerospike/aerospike-client-ruby)

This gem will be installed using `bundle`.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'aerospike-store'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install aerospike-store

## Usage

### Session Store

Add this line to your `config/initializers/session_store.rb`:

```ruby
YourAppName::Application.config.session_store :aerospike_store
```

It is possible to pass aerospike config options here. Defaults are:

```ruby
AppName::Application.config.session_store :aerospike_store,
		:host => "127.0.0.1",
		:port => 3000,
		:ns => "test",
		:set => "session",
		:bin => "data"
```

Or send in a custom client instance:

```ruby
YourAppName::Application.config.session_store :aerospike_store,
		:client => Aerospike::Client.new("127.0.0.1")
```

Supported data types are:
- Integer
- String
- List
- Hash

Storing other data types requires serialization.

#### Sample code

```ruby
session[:user_id] ||= 42
session[:user_id] += 1
session[:numbers] = [1, 3, 5, 6]
session[:user] = {'title' => 'Amir', 'user_group' => 'root'}
session[:map_list_mix] = [{'r' => 220, 'g' => 0, 'b' => 80}, {'r' => 100, 'g' => 255, 'b' => 25}]
session[:instance] = Marshal.dump(myInstance)
```

### Cache Store

Add this line to your `config/application.rb`:

```ruby
config.cache_store = :aerospike_store
```

It is possible to pass aerospike config options here. Defaults are:

```ruby
config.cache_store = :aerospike_store,
		:host => "127.0.0.1",
		:port => 3000,
		:ns => "test",
		:set => "cache",
		:bin => "entry"
```

Or send in a custom client instance:

```ruby
config.cache_store = :aerospike_store,
		:client => Aerospike::Client.new("127.0.0.1")
```

#### Supported options
- :expires_in
- :raw
- :unless_exist
- Aerospike policies

#### Supported functions
- increment
- decrement

#### Sample code
```ruby
Rails.cache.read('message')   # => nil
Rails.cache.write('message', "Aerospike is great!")
@message = Rails.cache.read('message')    # => "Aerospike is great!"
```

Using fetch:
```ruby
@message = Rails.cache.fetch('LongProcess', :expires_in => 30) {
	sleep (3) # waste some time!
	"Processed in 3 seconds!"
}
```

`increment` and `decrement` functions only work with `:raw` data:
```ruby
Rails.cache.write('hits', 0, {:raw => true, :unless_exist => true})
Rails.cache.increment('hits', 10)
Rails.cache.decrement('hits')
hits = Rails.cache.read('hits', {:raw => true})
```

**Fragment caching:**

Enable in `config/environments/development.rb`:
```ruby
  config.action_controller.perform_caching = true
```

Inside a view:
```ruby
<% cache("RecentPosts", :expires_in => 30) do %>
    <% sleep(3) # waste some time! %>
    <h1> Recent Posts</h1>
    <ul>
    	<li>post 234</li>
    	<li>post 235</li>
    </ul>
<% end %>
```

It is also possible to create and use an AerospikeStore cache instance:
```ruby
cache = ActiveSupport::Cache::AerospikeStore.new
@message = cache.read('message')
```

## Single-Bin
By default an Aerospike namespace supports multiple `bins` per key. As both cache store and session store only use a single bin for stroing data, it is recommended to to enable `single-bin` option in namespace configuration for higher performance.

## Contributing

1. Fork it ( https://github.com/amirrf/aerospike-store-rails/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

## License

The Aerospike Ruby Client is made available under the terms of the Apache License, Version 2, as stated in the file `LICENSE`.