text:
package com.moilioncircle.redis.replicator.cmd.impl;

import java.io.Serializable;

/**
 * @author Leon Chen
 * @since 3.5.0
 */
public class ByBox implements Serializable {
    private static final long serialVersionUID = 1L;

    private double width;
    private double height;
    private UnitType unitType;

    public ByBox() {
    }

    public ByBox(double width, double height, UnitType unitType) {
        this.width = width;
        this.height = height;
        this.unitType = unitType;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public UnitType getUnitType() {
        return unitType;
    }

    public void setUnitType(UnitType unitType) {
        this.unitType = unitType;
    }
}


text:
autocommit off;
create class foo ( m int);
create trigger foo_trigger
	before update on foo(m)
	execute print 'foo(m) trigger';
rollback work;
rollback;

redpajama_set_name: RedPajamaGithub


text:
package adhoc
import language.adhocExtensions
class B extends A
class B2 extends Abs


text:
'use strict'
/**
 * Created by Dominic Böttger on 10.06.2015
 * INSPIRATIONlabs GmbH
 * http://www.inspirationlabs.com
 */
var wsfedsaml2 = require('passport-wsfed-saml2').Strategy;
var _ = require('lodash');

var molecuel;

class mlcl_auth_saml2 {
  molecuel:any;
  mlcl_user:any;
  usermodel:any;
  passport:any;
  jwt:any;
  app:any;

  constructor() {
    this.molecuel = molecuel;
    this.molecuel.on('mlcl::user::init:post', (usermodule:any) => {
      this.mlcl_user = usermodule;
      this.usermodel = usermodule.model;
      this.passport = usermodule.passport;
      this.jwt = usermodule.jwt;
      this.registerPassportfunction();
    });
  }
  registerPassportfunction() {
    if(this.molecuel.config.user.authtypes && this.molecuel.config.user.authtypes.saml2) {
      var conf = this.molecuel.config.user;
      this.passport.use(new wsfedsaml2(
      {
        path: '/login/saml2/callback',
        realm: conf.authtypes.saml2.realm,
        identityProviderUrl: conf.authtypes.saml2.identityProviderUrl,
        protocol: 'samlp',
        cert: conf.authtypes.saml2.cert
      },(profile, done) => {
        let unamefield = 'username';
        if(conf.authtypes.saml2.fieldmappings && conf.authtypes.saml2.fieldmappings.username) {
          unamefield = conf.authtypes.saml2.fieldmappings.username;
        }
        let susername = profile[unamefield];
        this.usermodel.findOne({ username: susername}, (err, doc) => {
          let userfieldmapping = (user) => {
            if(conf.authtypes.saml2.fieldmappings) {
              let reverseMappings = {};
              _.each(Object.keys(conf.authtypes.saml2.fieldmappings), (fieldname) => {
                reverseMappings[conf.authtypes.saml2.fieldmappings[fieldname]] = fieldname;
              });
              _.each(reverseMappings, (fieldname) => {
                this.molecuel.log.debug('mlcl_auth_saml2', fieldname + ' ' + conf.authtypes.saml2.fieldmappings[fieldname] + ' ' + profile[conf.authtypes.saml2.fieldmappings[fieldname]]);
                _.set(user, fieldname, profile[conf.authtypes.saml2.fieldmappings[fieldname]]);
              });
            } else {
              // use predefined fieldmappings (this possibly fails)
              user.username = profile.username;
              user.name.first = profile.firstname;
              user.name.last = profile.lastname;
              user.email = profile.email;
            }
            user.lastlogin = new Date();
          }
          if(doc) {
            userfieldmapping(doc);
            doc.save(function(err) {
              if(err) {
                molecuel.log.error('mlcl_auth_saml2', err.message, err);
              }
              done(err, doc.toObject());
            });
          } else {
            let user = new this.usermodel();
            user.authtype = 'saml2';
            userfieldmapping(user);
            user.save(function(err) {
              if(err) {
                molecuel.log.error('mlcl_auth_saml2', err.message, err);
              }
              done(err, user.toObject());
            });
          }
        });
      }));
    }
  }

  middleware(config, app) {
    let usermodule = molecuel.modules.user.module;
    let passport = usermodule.passport;
    app.get('/login/saml2/pre',
      function(req, res) {
        res.status(200).send(
          `

          `
        )
      }
    );
    app.get('/login/saml2',
      passport.authenticate('wsfed-saml2', { failureRedirect: '/', failureFlash: false, session: false }),
      function(req, res) {
        res.redirect('/');
      }
    );
    app.post('/login/saml2/callback',
      passport.authenticate('wsfed-saml2', { failureRedirect: '/', failureFlash: false, session: false }),
      function(req, res) {
        usermodule.getUserObjectFromRequest(req, function(err, userObject) {
          molecuel.log.info('mlcl_user', 'authenticated', {username: userObject.name, _id: userObject._id, method: 'saml2'});
          molecuel.log.info('mlcl_auth_saml2', 'authenticated', {username: userObject.name, _id: userObject._id, method: 'saml2'});
          res.status(200).send(`

            `);
        });
      }
    );
  }
}

/* ************************************************************************
 SINGLETON CLASS DEFINITION
 ************************************************************************ */
var instance = null;

var getInstance = function(){
  return instance || (instance = new mlcl_auth_saml2());
};

var init = function (m) {
  molecuel = m;
  // store molecuel instance
  return getInstance();
};

module.exports = init;


text:
<?php

namespace Krillzip\Diatheke;

/**
 * Description of Configuration
 *
 * @author krillzip
 */
class Configuration implements \ArrayAccess {

    protected static $searchType = array('regex', 'multiword', 'phrase');
    protected static $optionFilters = array('n', 'f', 'm', 'h', 'c', 'v', 'a',
        'p', 'l', 's', 'r', 'b', 'x');
    protected static $outputFormat = array('GBF', 'ThML', 'RTF', 'HTML',
        'OSIS', 'CGI', 'plain');
    protected static $outputEncoding = array('Latin1', 'UTF8', 'UTF16', 'HTML',
        'RTF');
    protected static $keys = array('module', 'search', 'range', 'filter',
        'limit', 'output', 'format', 'encoding', 'script', 'variant', 'locale');
    protected $options;

    public function __construct(array $config = array()) {
        $config = array_filter($config);
        $diff = array_diff(array_keys($config), self::$keys);

        if (!empty($diff)) {
            throw new Exception\ConfigurationException('Configuration option(s) "' . implode(', ', $diff) . '" is not legal.');
        }

        if (isset($config['search'])) {
            self::validateSearchType($config['search']);
        }

        if (isset($config['filter'])) {
            self::validateOptionFilters($config['filter']);
        }

        if (isset($config['format'])) {
            self::validateOutputFormat($config['format']);
        }

        if (isset($config['encoding'])) {
            self::validateOutputEncoding($config['encoding']);
        }

        $this->options = $config;
    }

    public static function validateSearchType($input) {
        if (!in_array($input, self::$searchType)) {
            throw new Exception\ConfigurationException('Expected input value to be one of "' . implode(', ', self::$searchType) . '"');
        }

        return true;
    }

    public static function validateOptionFilters($input) {
        if (!in_array($input, self::$optionFilters)) {
            throw new Exception\ConfigurationException('Expected input value to be one of "' . implode(', ', self::$optionFilters) . '"');
        }

        return true;
    }

    public static function validateOutputFormat($input) {
        if (!in_array($input, self::$outputFormat)) {
            throw new Exception\ConfigurationException('Expected input value to be one of "' . implode(', ', self::$outputFormat) . '"');
        }

        return true;
    }

    public static function validateOutputEncoding($input) {
        if (!in_array($input, self::$outputEncoding)) {
            throw new Exception\ConfigurationException('Expected input value to be one of "' . implode(', ', self::$outputEncoding) . '"');
        }

        return true;
    }

    public static function getSearchType(){
        return self::$searchType;
    }

    public static function getOptionFilters(){
        return self::$optionFilters;
    }

    public static function getOutputFormats(){
        return self::$outputFormat;
    }

    public static function getOutputEncodings(){
        return self::$outputEncoding;
    }

    public function toArray() {
        return $this->options;
    }

    public function offsetExists($offset) {
        return key_exists($this->options, $offset);
    }

    public function offsetGet($offset) {
        return $this->options[$offset];
    }

    public function offsetSet($offset, $value) {

    }

    public function offsetUnset($offset) {

    }

}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.Search.Documents.Indexes.Models
{
    public partial class WordDelimiterTokenFilter : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(GenerateWordParts))
            {
                writer.WritePropertyName("generateWordParts");
                writer.WriteBooleanValue(GenerateWordParts.Value);
            }
            if (Optional.IsDefined(GenerateNumberParts))
            {
                writer.WritePropertyName("generateNumberParts");
                writer.WriteBooleanValue(GenerateNumberParts.Value);
            }
            if (Optional.IsDefined(CatenateWords))
            {
                writer.WritePropertyName("catenateWords");
                writer.WriteBooleanValue(CatenateWords.Value);
            }
            if (Optional.IsDefined(CatenateNumbers))
            {
                writer.WritePropertyName("catenateNumbers");
                writer.WriteBooleanValue(CatenateNumbers.Value);
            }
            if (Optional.IsDefined(CatenateAll))
            {
                writer.WritePropertyName("catenateAll");
                writer.WriteBooleanValue(CatenateAll.Value);
            }
            if (Optional.IsDefined(SplitOnCaseChange))
            {
                writer.WritePropertyName("splitOnCaseChange");
                writer.WriteBooleanValue(SplitOnCaseChange.Value);
            }
            if (Optional.IsDefined(PreserveOriginal))
            {
                writer.WritePropertyName("preserveOriginal");
                writer.WriteBooleanValue(PreserveOriginal.Value);
            }
            if (Optional.IsDefined(SplitOnNumerics))
            {
                writer.WritePropertyName("splitOnNumerics");
                writer.WriteBooleanValue(SplitOnNumerics.Value);
            }
            if (Optional.IsDefined(StemEnglishPossessive))
            {
                writer.WritePropertyName("stemEnglishPossessive");
                writer.WriteBooleanValue(StemEnglishPossessive.Value);
            }
            if (Optional.IsCollectionDefined(ProtectedWords))
            {
                writer.WritePropertyName("protectedWords");
                writer.WriteStartArray();
                foreach (var item in ProtectedWords)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WritePropertyName("@odata.type");
            writer.WriteStringValue(ODataType);
            writer.WritePropertyName("name");
            writer.WriteStringValue(Name);
            writer.WriteEndObject();
        }

        internal static WordDelimiterTokenFilter DeserializeWordDelimiterTokenFilter(JsonElement element)
        {
            Optional<bool> generateWordParts = default;
            Optional<bool> generateNumberParts = default;
            Optional<bool> catenateWords = default;
            Optional<bool> catenateNumbers = default;
            Optional<bool> catenateAll = default;
            Optional<bool> splitOnCaseChange = default;
            Optional<bool> preserveOriginal = default;
            Optional<bool> splitOnNumerics = default;
            Optional<bool> stemEnglishPossessive = default;
            Optional<IList<string>> protectedWords = default;
            string odataType = default;
            string name = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("generateWordParts"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    generateWordParts = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("generateNumberParts"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    generateNumberParts = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("catenateWords"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    catenateWords = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("catenateNumbers"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    catenateNumbers = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("catenateAll"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    catenateAll = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("splitOnCaseChange"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    splitOnCaseChange = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("preserveOriginal"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    preserveOriginal = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("splitOnNumerics"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    splitOnNumerics = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("stemEnglishPossessive"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    stemEnglishPossessive = property.Value.GetBoolean();
                    continue;
                }
                if (property.NameEquals("protectedWords"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    protectedWords = array;
                    continue;
                }
                if (property.NameEquals("@odata.type"))
                {
                    odataType = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
            }
            return new WordDelimiterTokenFilter(odataType, name, Optional.ToNullable(generateWordParts), Optional.ToNullable(generateNumberParts), Optional.ToNullable(catenateWords), Optional.ToNullable(catenateNumbers), Optional.ToNullable(catenateAll), Optional.ToNullable(splitOnCaseChange), Optional.ToNullable(preserveOriginal), Optional.ToNullable(splitOnNumerics), Optional.ToNullable(stemEnglishPossessive), Optional.ToList(protectedWords));
        }
    }
}


text:
Imports System.Resources

Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices

' Общие сведения об этой сборке предоставляются следующим набором
' атрибутов. Отредактируйте значения этих атрибутов, чтобы изменить
' общие сведения об этой сборке.

' Проверьте значения атрибутов сборки

<Assembly: AssemblyTitle("WWTBAM Control Program")>
<Assembly: AssemblyDescription("Program for organising WWTBAM game")>
<Assembly: AssemblyCompany("CherCom")>
<Assembly: AssemblyProduct("WWTBAM Control Program")>
<Assembly: AssemblyCopyright("Copyright CherCom ©  2015")>
<Assembly: AssemblyTrademark("")>

<Assembly: ComVisible(False)>

'Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
<Assembly: Guid("cbcb6089-c036-4701-aa4c-16b1cd95aa54")>

' Сведения о версии сборки состоят из следующих четырех значений:
'
'      Основной номер версии
'      Дополнительный номер версии
'   Номер сборки
'      Редакция
'
' Можно задать все значения или принять номера сборки и редакции по умолчанию
' используя "*", как показано ниже:
' <Assembly: AssemblyVersion("1.0.*")>

<Assembly: AssemblyVersion("1.1.1.72")>
<Assembly: AssemblyFileVersion("1.1.1.72")>

<Assembly: NeutralResourcesLanguageAttribute("en")>


text:
require 'forwardable'
require 'socket'
require 'timeout'

module Dalli
  module Protocol
    ##
    # Access point for a single Memcached server, accessed via Memcached's meta
    # protocol.  Contains logic for managing connection state to the server (retries, etc),
    # formatting requests to the server, and unpacking responses.
    ##
    class Meta < Base
      TERMINATOR = "\r\n"

      def response_processor
        @response_processor ||= ResponseProcessor.new(@connection_manager, @value_marshaller)
      end

      # NOTE: Additional public methods should be overridden in Dalli::Threadsafe

      private

      # Retrieval Commands
      def get(key, options = nil)
        encoded_key, base64 = KeyRegularizer.encode(key)
        req = RequestFormatter.meta_get(key: encoded_key, base64: base64)
        write(req)
        response_processor.meta_get_with_value(cache_nils: cache_nils?(options))
      end

      def quiet_get_request(key)
        encoded_key, base64 = KeyRegularizer.encode(key)
        RequestFormatter.meta_get(key: encoded_key, return_cas: true, base64: base64, quiet: true)
      end

      def gat(key, ttl, options = nil)
        ttl = TtlSanitizer.sanitize(ttl)
        encoded_key, base64 = KeyRegularizer.encode(key)
        req = RequestFormatter.meta_get(key: encoded_key, ttl: ttl, base64: base64)
        write(req)
        response_processor.meta_get_with_value(cache_nils: cache_nils?(options))
      end

      def touch(key, ttl)
        ttl = TtlSanitizer.sanitize(ttl)
        encoded_key, base64 = KeyRegularizer.encode(key)
        req = RequestFormatter.meta_get(key: encoded_key, ttl: ttl, value: false, base64: base64)
        write(req)
        response_processor.meta_get_without_value
      end

      # TODO: This is confusing, as there's a cas command in memcached
      # and this isn't it.  Maybe rename?  Maybe eliminate?
      def cas(key)
        encoded_key, base64 = KeyRegularizer.encode(key)
        req = RequestFormatter.meta_get(key: encoded_key, value: true, return_cas: true, base64: base64)
        write(req)
        response_processor.meta_get_with_value_and_cas
      end

      # Storage Commands
      def set(key, value, ttl, cas, options)
        write_storage_req(:set, key, value, ttl, cas, options)
        response_processor.meta_set_with_cas unless quiet?
      end

      def add(key, value, ttl, options)
        write_storage_req(:add, key, value, ttl, nil, options)
        response_processor.meta_set_with_cas unless quiet?
      end

      def replace(key, value, ttl, cas, options)
        write_storage_req(:replace, key, value, ttl, cas, options)
        response_processor.meta_set_with_cas unless quiet?
      end

      # rubocop:disable Metrics/ParameterLists
      def write_storage_req(mode, key, raw_value, ttl = nil, cas = nil, options = {})
        (value, bitflags) = @value_marshaller.store(key, raw_value, options)
        ttl = TtlSanitizer.sanitize(ttl) if ttl
        encoded_key, base64 = KeyRegularizer.encode(key)
        req = RequestFormatter.meta_set(key: encoded_key, value: value,
                                        bitflags: bitflags, cas: cas,
                                        ttl: ttl, mode: mode, quiet: quiet?, base64: base64)
        write(req)
      end
      # rubocop:enable Metrics/ParameterLists

      def append(key, value)
        write_append_prepend_req(:append, key, value)
        response_processor.meta_set_append_prepend unless quiet?
      end

      def prepend(key, value)
        write_append_prepend_req(:prepend, key, value)
        response_processor.meta_set_append_prepend unless quiet?
      end

      # rubocop:disable Metrics/ParameterLists
      def write_append_prepend_req(mode, key, value, ttl = nil, cas = nil, _options = {})
        ttl = TtlSanitizer.sanitize(ttl) if ttl
        encoded_key, base64 = KeyRegularizer.encode(key)
        req = RequestFormatter.meta_set(key: encoded_key, value: value, base64: base64,
                                        cas: cas, ttl: ttl, mode: mode, quiet: quiet?)
        write(req)
      end
      # rubocop:enable Metrics/ParameterLists

      # Delete Commands
      def delete(key, cas)
        encoded_key, base64 = KeyRegularizer.encode(key)
        req = RequestFormatter.meta_delete(key: encoded_key, cas: cas,
                                           base64: base64, quiet: quiet?)
        write(req)
        response_processor.meta_delete unless quiet?
      end

      # Arithmetic Commands
      def decr(key, count, ttl, initial)
        decr_incr false, key, count, ttl, initial
      end

      def incr(key, count, ttl, initial)
        decr_incr true, key, count, ttl, initial
      end

      def decr_incr(incr, key, delta, ttl, initial)
        ttl = initial ? TtlSanitizer.sanitize(ttl) : nil # Only set a TTL if we want to set a value on miss
        encoded_key, base64 = KeyRegularizer.encode(key)
        write(RequestFormatter.meta_arithmetic(key: encoded_key, delta: delta, initial: initial, incr: incr, ttl: ttl,
                                               quiet: quiet?, base64: base64))
        response_processor.decr_incr unless quiet?
      end

      # Other Commands
      def flush(delay = 0)
        write(RequestFormatter.flush(delay: delay))
        response_processor.flush unless quiet?
      end

      # Noop is a keepalive operation but also used to demarcate the end of a set of pipelined commands.
      # We need to read all the responses at once.
      def noop
        write_noop
        response_processor.consume_all_responses_until_mn
      end

      def stats(info = nil)
        write(RequestFormatter.stats(info))
        response_processor.stats
      end

      def reset_stats
        write(RequestFormatter.stats('reset'))
        response_processor.reset
      end

      def version
        write(RequestFormatter.version)
        response_processor.version
      end

      def write_noop
        write(RequestFormatter.meta_noop)
      end

      def authenticate_connection
        raise Dalli::DalliError, 'Authentication not supported for the meta protocol.'
      end

      require_relative 'meta/key_regularizer'
      require_relative 'meta/request_formatter'
      require_relative 'meta/response_processor'
    end
  end
end


text:
/**
 * Model de la Base de Dades - Usuari
 */

module.exports = function(sequelize, DataTypes) {

	var Usuari = sequelize.define('Usuari', {
		email : {
			type: DataTypes.STRING(255),
			primaryKey: true
		},
		password : DataTypes.STRING(100),
		nom: DataTypes.STRING(20),
		cognoms: DataTypes.STRING(60),
		connect: DataTypes.BOOLEAN()
	}, {
		classMethods : {
			associate : function(models) {
				Usuari.hasMany(models.Video),
				Usuari.belongsTo(models.Sala,{constraints: false}),
                Usuari.hasMany(models.Video)
			}
		}
	});

	return Usuari;
};


text:
<?php

declare(strict_types=1);

namespace Comely\Knit\Compiler\Parser;

/**
 * Trait ParseCount
 * @package Comely\Knit\Compiler\Parser
 */
trait ParseCount
{
    /**
     * @return string
     */
    private function parseCount(): string
    {
        // exp: count $i 1 to 100
        $pieces = preg_split('/\s/', $this->token);
        $index = $pieces[1];

        // Reserve variable
        $this->reserveVariable($index);

        // Return count statement
        $this->clauses["count"][] = ["close" => 1, "var" => $index];
        return sprintf(
            '<?php for(%1$s=%2$d;%1$s<=%3$d;%1$s++) { ?>',
            $index,
            intval($pieces[2]),
            intval($pieces[4])
        );
    }

    /**
     * @return string
     */
    private function parseCountClose(): string
    {
        if (empty($this->clauses["count"])) {
            throw $this->exception('No count loop was found');
        }

        $clause = array_pop($this->clauses["count"]);
        $this->releaseVariable($clause["var"]);

        return sprintf('<?php } unset(%1$s); ?>', $clause["var"]);
    }
}


text:
package org.soya.ast.expr;

import java.util.List;

/**
 * @author: Jun Gong
 */
public class TupleExpression extends ListExpression {

	private boolean isPair;

	public TupleExpression(List<Expression> items, boolean isPair) {
		super(items);
		this.isPair = isPair;
    }

	public boolean isPair() {
		return isPair;
	}

	public String toString() {
		return "[tuple " + this.getItems().toString() + "]";
	}
}


text:
<?php
class DepartamentosModel extends CI_Model{

	public function obtener_departamentos(){
    	$query = $this->db->get('departamentos');
        return $query->result_array();
	}

	public function obtener_departamento($id){
		$this->db->where("departamento_id",$id);
		$query = $this->db->get('departamentos');
        return $query->result_array();
	}

	public function guardar_departamento($data){
		return $this->db->insert('departamentos', $data);
	}

	public function editar_departamento($id,$data){
		$this->db->where("departamento_id",$id);
        return $this->db->update('departamentos',$data);
	}

	public function eliminar_departamento($id){
		$this->db->where("departamento_id",$id);
        return $this->db->delete('departamentos');
	}

	}
?>


text:
#include "Common/Common.h"

#include "NetInterface.h"

namespace RemotePC
{

	NetInterface::NetInterface()
	    : ip_()
	    , port_()
	{
	}

	NetInterface::NetInterface(const std::string& ip, const std::string& port)
		: ip_(ip)
		, port_(port)
	{
	}

	void NetInterface::SetIp(const std::string& ip)
	{
		ip_ = ip;
	}

	std::string NetInterface::GetIp() const
	{
		return ip_;
	}

	void NetInterface::SetPort(const std::string& port)
	{
		port_ = port;
	}

	std::string NetInterface::GetPort() const
	{
		return port_;
	}

}


text:
package org.lifenoodles.jargparse;

import junit.framework.TestCase;

/**
 * @author Donagh Hatton
 *         created on 8/8/14.
 */
public class OptionSetTest extends TestCase {
    private OptionParser parser;

    public void setUp() {
        parser = new OptionParser();
        parser.add(Option.of("-h", "--help").arguments(0));
        parser.add(Option.of("-v", "--verbose").arguments("?")
                .matches(x -> x.matches("[0-2]")));
        parser.add(Positional.of("files").arguments("*"));
    }

    public void testGetArgument() {
        try {
            OptionSet optionSet = parser.parse("-v", "2");
            assertTrue(optionSet.get("--verbose").orElse("")
                    .equals("2"));
        } catch (Exception e) {
            fail();
        }
    }

    public void testGetArguments() {
        try {
            OptionSet optionSet = parser.parse("file1", "file2", "file3");
            assertTrue(optionSet.getArguments("files").size() == 3);
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    public void testIsOptionPresent() {
        try {
            OptionSet optionSet = parser.parse("--help");
            assertTrue(optionSet.contains("-h"));
            assertTrue(optionSet.contains("--help"));
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }
}


text:
using testing::Return;

class MockStatusIcon : public StatusIcon {
  virtual void SetImage(const SkBitmap& image) {}
  virtual void SetPressedImage(const SkBitmap& image) {}
  virtual void SetToolTip(const string16& tool_tip) {}
  virtual void DisplayBalloon(const string16& title,
                              const string16& contents) {}
  virtual void UpdatePlatformContextMenu(ui::MenuModel* menu) {}
  virtual void AddObserver(StatusIcon::Observer* observer) {}
  virtual void RemoveObserver(StatusIcon::Observer* observer) {}
};

class TestStatusTray : public StatusTray {
 public:
  MOCK_METHOD0(CreatePlatformStatusIcon, StatusIcon*());
  MOCK_METHOD1(UpdatePlatformContextMenu, void(ui::MenuModel*));
};

TEST(StatusTrayTest, Create) {
  // Check for creation and leaks.
  TestStatusTray tray;
  EXPECT_CALL(tray,
      CreatePlatformStatusIcon()).WillOnce(Return(new MockStatusIcon()));
  tray.CreateStatusIcon();
}

// Make sure that removing an icon removes it from the list.
TEST(StatusTrayTest, CreateRemove) {
  TestStatusTray tray;
  EXPECT_CALL(tray,
      CreatePlatformStatusIcon()).WillOnce(Return(new MockStatusIcon()));
  StatusIcon* icon = tray.CreateStatusIcon();
  EXPECT_EQ(1U, tray.status_icons_.size());
  tray.RemoveStatusIcon(icon);
  EXPECT_EQ(0U, tray.status_icons_.size());
  // Calling again should do nothing.
  tray.RemoveStatusIcon(icon);
}


text:
[![NPM version](https://badge.fury.io/js/seltron.png)](http://badge.fury.io/js/seltron)
[![Build Status](https://secure.travis-ci.org/vesln/seltron.png)](http://travis-ci.org/vesln/seltron)
[![Coverage Status](https://coveralls.io/repos/vesln/seltron/badge.png?branch=master)](https://coveralls.io/r/vesln/seltron?branch=master)
[![Code Climate](https://codeclimate.com/github/vesln/seltron.png)](https://codeclimate.com/github/vesln/seltron)

# Important Notice

I'm no longer actively maintaining this project. If you are interested supporting it - [ping me on twitter](https://twitter.com/vesln).
The only thing that I will ask you is to not change the API drastically. If you are planning on doing that - better start a brand new project.

If you want me to transfer you only the name on npm, I'd be happy to only if the project **does not have any downloads on npm lately**. In case it's being
downloaded, there are people that depend on it and might step up and start maintaining, so I will not transfer it to you, regardless if you want to release
a new major version etc.

If you have any other questions, let me know.

Thanks!

Veselin

# seltron

## Synopsis

Tiny Selenium spawner.

## Supported drivers

- Chrome (chrome)
- Firefox (firefox)
- Phantomjs (phantomjs)

## Requirements

- java (to run Selenium)
- wget (to download Selenium)
- phantomjs, Firefox, Chrome (pick what you want to use)

## Usage

```js
seltron('phantomjs', 9002, function(err, process) {
  if (err) throw err;
  // start testing!

  // done? kill it!
  process.kill();
});
```

You can skip `port` if you wish, it will run Selenium on 4444.

## Installation

```bash
npm install seltron
```

## Installing Selenium & ChromeDriver

```bash
$ ./node_modules/seltron/bin/install-selenium
```

## Tests

### Running the tests

```bash
$ npm test
```

### Test coverage

```bash
$ npm run-script coverage
```

## License

(The MIT License)

Copyright (c) 2013 Veselin Todorov <hi@vesln.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
/*jslint browser, this, for*/
/*global window, $, Morris, Helper, confirm*/
var Main = (function () {
    'use strict';

    var publicMethods = {};

    publicMethods.init = function (CONFIG, TRANSLATIONS) {
        var refreshData;

        var LOADING_ICON_CLASS_NAME = 'loading-icon';
        var LOCAL_STORAGE_USERNAME = 'underpressure_username';
        var LOCAL_STORAGE_PASSWORD = 'underpressure_password';

        var $WINDOW = $(window);
        var $CHART = $('#chart');
        var $LOG = $('#log');
        var $TABLE = $('#table');
        var $LOGGED_OUT_PANEL = $('#logged-out-panel');
        var $LOGGED_IN_PANEL = $('#logged-in-panel');

        var IS_MOBILE_DEVICE = Helper.isMobileDevice();

        var DATA_DATETIME_ATTR = 'data-dateTime';

        var RGB_COLORS = {
            sys: [234, 27, 19],
            dia: [230, 100, 19],
            pulse: [110, 110, 245]
        };

        var GOALS = [120, 80, 60];

        var GOAL_OPACITY = 0.6;

        var MEASUREMENT_THRESHOLDS = {
            sys: [120, 130, 140, 160, 180],
            dia: [80, 85, 90, 100, 110],
            pulse: [60, 70, 85, 90, 95]
        };

        var MEASUREMENT_THRESHOLD_CLASSES = ['th-optimal', 'th-normal', 'th-normalhigh', 'th-high1', 'th-high2', 'th-high3'];

        var MORRIS_OPTIONS = {
            element: 'chart',
            data: [],
            xkey: CONFIG.keys.dateTime,
            ykeys: [CONFIG.keys.sys, CONFIG.keys.dia, CONFIG.keys.pulse],
            labels: [TRANSLATIONS.sys, TRANSLATIONS.dia, TRANSLATIONS.pulse],
            lineColors: [Helper.getRgbaColor(RGB_COLORS.sys), Helper.getRgbaColor(RGB_COLORS.dia), Helper.getRgbaColor(RGB_COLORS.pulse)],
            lineWidth: 1,
            pointSize: 0,
            smooth: false,
            resize: true,
            continuousLine: true,
            grid: false,
            goals: GOALS,
            goalStrokeWidth: 1,
            goalLineColors: [
                Helper.getRgbaColor(RGB_COLORS.sys, GOAL_OPACITY),
                Helper.getRgbaColor(RGB_COLORS.dia, GOAL_OPACITY),
                Helper.getRgbaColor(RGB_COLORS.pulse, GOAL_OPACITY)
            ],
            eventStrokeWidth: 1,
            eventLineColors: ['rgba(255, 255, 255, 0.1)'],
            dateFormat: function (utcTimeStampInMsAsLocal) {
                return Helper.formatDate(Helper.getLocalDateAsUtc(new Date(utcTimeStampInMsAsLocal)));
            }
        };

        function showLoadingIcon(jElement) {
            jElement.css('position', 'relative');
            jElement.append($('<div>', {class: LOADING_ICON_CLASS_NAME}));
        }

        function hideLoadingIcon(jElement) {
            jElement.find('.' + LOADING_ICON_CLASS_NAME).remove();
            jElement.css('position', 'initial');
        }

        function ajaxSetup(username, password) {
            $.ajaxSetup({
                async: true,
                cache: false,
                headers: {
                    'Authorization': 'Basic ' + Helper.b64EncodeUnicode(username + ':' + password)
                }
            });
        }

        function getMeasurementThresholdClass(categoryValues, value) {
            var idx, measurementThresholdClass;
            for (idx = categoryValues.length - 1; idx >= 0; idx -= 1) {
                if (value >= categoryValues[idx]) {
                    measurementThresholdClass = MEASUREMENT_THRESHOLD_CLASSES[idx + 1];
                    break;
                }
            }
            return measurementThresholdClass || MEASUREMENT_THRESHOLD_CLASSES[0];
        }

        function createLogEntryRow(sys, dia, pulse, rowClass, text) {
            var sysClass = getMeasurementThresholdClass(MEASUREMENT_THRESHOLDS.sys, sys);
            var diaClass = getMeasurementThresholdClass(MEASUREMENT_THRESHOLDS.dia, dia);
            var pulseClass = getMeasurementThresholdClass(MEASUREMENT_THRESHOLDS.pulse, pulse);
            var logRow = $('<tr>', {class: rowClass});

            logRow.append($('<td>', {text: text}));
            logRow.append($('<td>', {text: Math.round(sys), class: sysClass}));
            logRow.append($('<td>', {text: Math.round(dia), class: diaClass}));
            logRow.append($('<td>', {text: Math.round(pulse), class: pulseClass}));

            return logRow;
        }

        function addEventsToTable(table) {
            table.find('tr.editable').on('click', function () {
                var self = $(this);
                var tempEditRow = table.find('.tempEditRow');

                if (self.next().hasClass('tempEditRow')) {
                    tempEditRow.remove();
                    return;
                }

                tempEditRow.remove();

                var inputSys = $('<input>', {type: 'text', value: self.children()[1].innerText});
                var inputDia = $('<input>', {type: 'text', value: self.children()[2].innerText});
                var inputPulse = $('<input>', {type: 'text', value: self.children()[3].innerText});

                var btnDelete = $('<button>', {type: 'button', text: TRANSLATIONS.delete});
                btnDelete.on('click', function () {
                    if (!confirm(TRANSLATIONS.sure_delete)) {
                        return;
                    }

                    $.post(CONFIG.api.endPoints.deleteLog, {dateTime: self.attr(DATA_DATETIME_ATTR)}).done(function () {
                        refreshData();
                    }).fail(function () {
                        $.toast({
                            position: 'top-center',
                            heading: 'Log',
                            text: TRANSLATIONS.could_not_delete,
                            icon: 'error'
                        });
                    });
                });

                var btnSave = $('<button>', {type: 'button', text: TRANSLATIONS.save});
                btnSave.on('click', function () {
                    if (!confirm(TRANSLATIONS.sure_save)) {
                        return;
                    }

                    var requestData = {
                        dateTime: self.attr(DATA_DATETIME_ATTR),
                        sys: inputSys.val(),
                        dia: inputDia.val(),
                        pulse: inputPulse.val()
                    };
                    $.post(CONFIG.api.endPoints.putLog, requestData).done(function () {
                        refreshData();
                    }).fail(function () {
                        $.toast({
                            position: 'top-center',
                            heading: 'Log',
                            text: TRANSLATIONS.could_not_save,
                            icon: 'error'
                        });
                    });
                });

                var editRow = $('<tr>', {class: 'tempEditRow'});
                editRow.append($('<td>').append(btnDelete).append(btnSave));
                editRow.append($('<td>').append(inputSys));
                editRow.append($('<td>').append(inputDia));
                editRow.append($('<td>').append(inputPulse));

                self.after(editRow);
            });
        }

        function setTableData(logData) {
            $TABLE.empty();

            if (logData.length <= 0) {
                return;
            }

            var table = $('<table>');

            var firstRow = $('<tr>');
            firstRow.append($('<th>'));
            firstRow.append($('<th>', {html: TRANSLATIONS.sys}));
            firstRow.append($('<th>', {html: TRANSLATIONS.dia}));
            firstRow.append($('<th>', {html: TRANSLATIONS.pulse}));
            table.append(firstRow);

            var sysValues = Helper.selectValuesByKey(logData, CONFIG.keys.sys);
            var diaValues = Helper.selectValuesByKey(logData, CONFIG.keys.dia);
            var pulseValues = Helper.selectValuesByKey(logData, CONFIG.keys.pulse);

            table.append(createLogEntryRow(Helper.getAvgOfArray(sysValues), Helper.getAvgOfArray(diaValues), Helper.getAvgOfArray(pulseValues), 'special', TRANSLATIONS.avg));
            table.append(createLogEntryRow(Math.min.apply(null, sysValues), Math.min.apply(null, diaValues), Math.min.apply(null, pulseValues), 'special', TRANSLATIONS.min));
            table.append(createLogEntryRow(Math.max.apply(null, sysValues), Math.max.apply(null, diaValues), Math.max.apply(null, pulseValues), 'special', TRANSLATIONS.max));

            table.append($('<tr>', {class: 'separator'}));

            logData.forEach(function (entry) {
                var logRow = createLogEntryRow(entry[CONFIG.keys.sys], entry[CONFIG.keys.dia], entry[CONFIG.keys.pulse], '', Helper.formatDate(Helper.parseSpaceSeparatedDateTimeString(entry[CONFIG.keys.dateTime])));

                logRow.addClass('editable');
                logRow.attr(DATA_DATETIME_ATTR, entry[CONFIG.keys.dateTime]);

                table.append(logRow);
            });

            addEventsToTable(table);

            $TABLE.append(table);
        }

        function getExtremeValueIncludingGoals(extremeFn, logData, keys, goals) {
            var extremeValue = Helper.getExtremeOfObjectsArray(logData, extremeFn, keys);
            var extremeValueIncludingGoals = extremeFn(extremeValue, extremeFn.apply(null, goals));
            return extremeValueIncludingGoals;
        }

        function getEventLineDates(logData) {
            if (logData.length <= 0) {
                return [];
            }

            var firstDateString = logData[0][CONFIG.keys.dateTime].split(' ')[0];
            var firstDate = Helper.parseSpaceSeparatedDateTimeString(firstDateString);

            var lastDateString = logData.slice(-1)[0][CONFIG.keys.dateTime].split(' ')[0];
            var lastDate = Helper.addDays(Helper.parseSpaceSeparatedDateTimeString(lastDateString), 1);

            var dayDates = [];
            var currentDate = Helper.addDays(firstDate, 0);
            while (currentDate <= lastDate) {
                dayDates.push(currentDate.toISOString().split('T')[0]);
                currentDate = Helper.addDays(currentDate, 1);
            }

            return dayDates;
        }

        refreshData = function () {
            showLoadingIcon($CHART);
            var keys = [CONFIG.keys.sys, CONFIG.keys.dia, CONFIG.keys.pulse];

            $.getJSON(CONFIG.api.endPoints.getLog).done(function (logData) {
                MORRIS_OPTIONS.ymin = Helper.round(getExtremeValueIncludingGoals(Math.min, logData, keys, GOALS), -1, Math.floor);
                MORRIS_OPTIONS.ymax = Helper.round(getExtremeValueIncludingGoals(Math.max, logData, keys, GOALS), -1, Math.ceil);
                MORRIS_OPTIONS.events = getEventLineDates(logData);

                $CHART.empty();
                Morris.Line(MORRIS_OPTIONS).setData(logData);

                setTableData(JSON.parse(JSON.stringify(logData)).reverse());

                if (logData.length <= 0) {
                    var numShowLastRecordedString = CONFIG.numShowLastRecordedDays % 7 === 0
                        ? '' + (CONFIG.numShowLastRecordedDays / 7) + ' ' + TRANSLATIONS.weeks
                        : '' + (CONFIG.numShowLastRecordedDays) + ' ' + TRANSLATIONS.days;

                    $.toast({
                        position: 'top-center',
                        heading: TRANSLATIONS.welcome + '! ❤',
                        text: TRANSLATIONS.welcome_text_pre + ' ' + numShowLastRecordedString + ' ' + TRANSLATIONS.welcome_text_post,
                        icon: 'info',
                        hideAfter: 15000
                    });
                }
            }).always(function () {
                hideLoadingIcon($CHART);
            });
        };

        function resizeUI() {
            $CHART.height($WINDOW.innerHeight() - $LOG.innerHeight());
        }

        function authenticate() {
            var username = localStorage[LOCAL_STORAGE_USERNAME];
            var password = localStorage[LOCAL_STORAGE_PASSWORD];

            if (username === undefined || password === undefined) {
                $LOGGED_IN_PANEL.hide();
                $LOGGED_OUT_PANEL.show();
                $CHART.hide();
                $LOG.hide();
                $TABLE.hide();

                if (!IS_MOBILE_DEVICE) {
                    $LOGGED_OUT_PANEL.find('input[name=username]').focus();
                }

                return;
            }

            $CHART.show();
            $LOG.show();
            $TABLE.show();
            $LOGGED_OUT_PANEL.hide();
            $LOGGED_IN_PANEL.show();

            $LOGGED_IN_PANEL.find('.username').text(username);

            if (!IS_MOBILE_DEVICE) {
                $LOG.find('input[name=' + CONFIG.keys.sys + ']').focus();
            }

            ajaxSetup(username, password);

            refreshData();
        }

        $LOG.on('submit', function () {
            var nowAsUtc = Helper.getLocalDateAsUtc(new Date());
            var isoDateTimeString = nowAsUtc.toISOString().substr(0, 19);
            var dateTimeString = isoDateTimeString.split('T').join(' ');

            var jSys = $(this).find('input[name=' + CONFIG.keys.sys + ']');
            var jDia = $(this).find('input[name=' + CONFIG.keys.dia + ']');
            var jPulse = $(this).find('input[name=' + CONFIG.keys.pulse + ']');

            var requestData = {};
            requestData[CONFIG.keys.sys] = jSys.val();
            requestData[CONFIG.keys.dia] = jDia.val();
            requestData[CONFIG.keys.pulse] = jPulse.val();
            requestData[CONFIG.keys.dateTime] = dateTimeString;

            $.post(CONFIG.api.endPoints.postLog, requestData).done(function () {
                $.toast({
                    position: 'top-center',
                    heading: TRANSLATIONS.log,
                    text: TRANSLATIONS.logged_successfully,
                    icon: 'success'
                });

                jSys.val('');
                jDia.val('');
                jPulse.val('');
                refreshData();
            }).fail(function () {
                $.toast({
                    position: 'top-center',
                    heading: TRANSLATIONS.log,
                    text: TRANSLATIONS.could_not_log,
                    icon: 'error'
                });
            });

            return false;
        });

        $LOGGED_OUT_PANEL.on('submit', function () {
            var jUsername = $(this).find('input[name=username]');
            var jPassword = $(this).find('input[name=password]');

            ajaxSetup(jUsername.val(), jPassword.val());

            $.getJSON(CONFIG.api.endPoints.getLog).done(function () {
                localStorage[LOCAL_STORAGE_USERNAME] = jUsername.val();
                localStorage[LOCAL_STORAGE_PASSWORD] = jPassword.val();

                authenticate();
            }).fail(function () {
                jPassword.val('');
                $.toast({
                    position: 'top-center',
                    heading: TRANSLATIONS.log_in,
                    text: TRANSLATIONS.invalid_credentials,
                    icon: 'error'
                });
            });

            return false;
        });

        $LOGGED_IN_PANEL.on('submit', function () {
            localStorage.removeItem(LOCAL_STORAGE_USERNAME);
            localStorage.removeItem(LOCAL_STORAGE_PASSWORD);

            location.reload();

            return false;
        });

        $WINDOW.resize(resizeUI);

        $WINDOW.resize();

        authenticate();
    };

    return publicMethods;
}());


text:
//
#ifndef ANDROID_IINTERFACE_H
#define ANDROID_IINTERFACE_H

#include <utils/Binder.h>

namespace android {

// ----------------------------------------------------------------------

class IInterface : public virtual RefBase
{
public:
            sp<IBinder>         asBinder();
            sp<const IBinder>   asBinder() const;

protected:
    virtual IBinder*            onAsBinder() = 0;
};

// ----------------------------------------------------------------------

template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
    return INTERFACE::asInterface(obj);
}

// ----------------------------------------------------------------------

template<typename INTERFACE>
class BnInterface : public INTERFACE, public BBinder
{
public:
    virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
    virtual String16            getInterfaceDescriptor() const;

protected:
    virtual IBinder*            onAsBinder();
};

// ----------------------------------------------------------------------

template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
{
public:
                                BpInterface(const sp<IBinder>& remote);

protected:
    virtual IBinder*            onAsBinder();
};

// ----------------------------------------------------------------------

#define DECLARE_META_INTERFACE(INTERFACE)                               \
    static const String16 descriptor;                                   \
    static sp<I##INTERFACE> asInterface(const sp<IBinder>& obj);        \
    virtual String16 getInterfaceDescriptor() const;                    \

#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
    const String16 I##INTERFACE::descriptor(NAME);                      \
    String16 I##INTERFACE::getInterfaceDescriptor() const {             \
        return I##INTERFACE::descriptor;                                \
    }                                                                   \
    sp<I##INTERFACE> I##INTERFACE::asInterface(const sp<IBinder>& obj)  \
    {                                                                   \
        sp<I##INTERFACE> intr;                                          \
        if (obj != NULL) {                                              \
            intr = static_cast<I##INTERFACE*>(                          \
                obj->queryLocalInterface(                               \
                        I##INTERFACE::descriptor).get());               \
            if (intr == NULL) {                                         \
                intr = new Bp##INTERFACE(obj);                          \
            }                                                           \
        }                                                               \
        return intr;                                                    \
    }                                                                   \

// ----------------------------------------------------------------------
// No user-servicable parts after this...

template<typename INTERFACE>
inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(
        const String16& _descriptor)
{
    if (_descriptor == INTERFACE::descriptor) return this;
    return NULL;
}

template<typename INTERFACE>
inline String16 BnInterface<INTERFACE>::getInterfaceDescriptor() const
{
    return INTERFACE::getInterfaceDescriptor();
}

template<typename INTERFACE>
IBinder* BnInterface<INTERFACE>::onAsBinder()
{
    return this;
}

template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
    : BpRefBase(remote)
{
}

template<typename INTERFACE>
inline IBinder* BpInterface<INTERFACE>::onAsBinder()
{
    return remote();
}

// ----------------------------------------------------------------------

}; // namespace android

#endif // ANDROID_IINTERFACE_H


text:
**Age:** 33

**Occupation:** Stay at home Mom

**Location:** Boston, Massachusetts

> "My kids are my everything; I go the extra mile to help them be safe."

##Goals:
- Keep her children safe
- Be the first to know about food safety news

##Bio:
Ann has a hectic and full schedule. She is a stay at home Mom taking care of her two children, Jennifer (6) and John (3), who both suffer of allergies. Ann is very concerned that her children aren't exposed to harmful foods. She does her groceries in local supermarkets but also relies on frozen food when time runs short. She keeps track of her errands through her mobile phone with very little time to go and look at web sites.

Ann has a full and hectic schedule. She is a stay at home Mom taking care of her two children, Jennifer (6) and John (3), both of whom suffer from allergies. Ann is very concerned that her children aren't exposed to harmful foods. She does her grocery shopping in local supermarkets but also relies on frozen food when time runs short. She keeps track of her errands through her mobile phone with very little time to go and look at web sites.
Ann is looking for a way to get relevant food safety information quickly and easily.


text:
package com.redshape.io.net.auth.impl;

import com.redshape.io.interactors.ServiceID;
import com.redshape.io.net.auth.IPasswordCredentials;

/**
 * @author nikelin
 */
public class SimpleCredentials implements IPasswordCredentials {
	private ServiceID serviceID;
	private String login;
	private String password;

	public SimpleCredentials() {
		this(ServiceID.NONE, "", "");
	}

	public SimpleCredentials( ServiceID serviceID, String login, String password ) {
		this.serviceID = serviceID;
		this.login = login;
		this.password = password;
	}

	@Override
	public ServiceID getServiceID() {
		return this.serviceID;
	}

	public void setUsername( String login ) {
		this.login = login;
	}

	@Override
	public String getUsername() {
		return this.login;
	}

	public void setPassword( String password ) {
		this.password = password;
	}

	@Override
	public String getPassword() {
		return this.password;
	}

}


text:
CLASS({
  package: 'foam.ui',
  name: 'TabbedViewChoiceView',
  extends: 'foam.ui.DetailView',
  requires: [
    'foam.ui.md.HaloView',
  ],
  help: 'A view that typically takes a ViewChoiceController and renders the ' +
      'labels of the ViewChoices as tabs and highlights the selected choice.',
  properties: [
    {
      name: 'className',
      defaultValue: 'TabbedViewChoiceView',
    },
    {
      name: 'preferredHeight',
      defaultValue: 54,
    },
  ],
  methods: {
    setCurrentLinePosition: function() {
      var line = document.getElementById(this.id + '-line');
      var selectedElement = this.$ && this.$.children[this.data.choice];
      if (line && selectedElement) {
        line.style.left = selectedElement.offsetLeft;
        line.style.width = selectedElement.offsetWidth + 'px';
      }
    },
    initHTML: function() {
      this.SUPER();
      this.setCurrentLinePosition();
      var self = this;
      var destructor = Events.dynamic(
          function() { self.data.choice; },
          this.setCurrentLinePosition.bind(this));
      this.addDestructor(destructor.destroy.bind(destructor));
      this.preferredHeight = this.$.clientHeight;
    },
  },
  templates: [
    function CSS() {/*
      .TabbedViewChoiceView {
        white-space: nowrap;
        background-color: #36474F;
      }
      .TabbedViewChoiceView .item:hover,
      .TabbedViewChoiceView .item.item-selected {
        color: white;
      }
      .TabbedViewChoiceView .item {
        -webkit-user-select: none;
        color: #B2B8BB;
        cursor: pointer;
        display: inline-block;
        padding: 20px;
        position: relative;
      }
      .TabbedViewChoiceView .line-container {
        height: 3px;
      }
      .TabbedViewChoiceView .line {
        background-color: #00A7F2;
        display: inline-block;
        height: 100%;
        position: relative;
        transition: left 0.5s cubic-bezier(0.35, 0, 0.25, 1), width 0.225s cubic-bezier(0.35, 0, 0.25, 1);
      }
      .TabbedViewChoiceView .halo {
        position: absolute;
        left: 0;
        top: 0;
      }
    */},
    function choiceButton(_, i, choice) {/*
      <%
        var id = this.on('click', function() { self.data.choice = i; });
        this.setClass('item-selected', function() {
          return self.data.choice == i;
        }, id);
      %>
      <div id="<%= id %>" class="item">
        <%= choice.label.toUpperCase() %>
        <%= this.HaloView.create({
          className: 'halo',
          color: 'rgb(241, 250, 65)',
          finishAlpha: 0,
          pressedAlpha: 0.2,
          recentering: false,
          startAlpha: 0.2,
        }) %>

    */},
    function toHTML() {/*
      <div id="%%id" <%= this.cssClassAttr() %>>
        <% for ( var i = 0, choice; choice = this.data.views[i]; i++ ) {
             this.choiceButton(out, i, choice);
         } %>

    */}
  ]
});


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using MonJobs.Peek;
using NUnit.Framework;

namespace MonJobs.Tests
{
    internal class MongoJobPeekNextServiceTests : MongoTestBase
    {
        [Test]
        public async Task PeekFor_NewJobs_ReturnsAvailableJobs()
        {
            var exampleQueueId = QueueId.Parse("ExampleQueue");
            var exampleQuery = new PeekNextOptions
            {
                QueueId = exampleQueueId
            };

            var newlyCreatedJobId = JobId.Generate();
            var existingJobs = new[] { new Job
            {
                Id = JobId.Generate(),
                QueueId = exampleQueueId,
                Result = new JobResult {
                    { "Result", "Success"}
                },
                Acknowledgment = new JobAcknowledgment
                {
                    { "RunnerId", Guid.NewGuid().ToString("N") }
                }
            }, new Job
            {
                Id = JobId.Generate(),
                QueueId = exampleQueueId,
                Acknowledgment = new JobAcknowledgment
                {
                    { "RunnerId", Guid.NewGuid().ToString("N") }
                }
            }, new Job
            {
                Id = newlyCreatedJobId,
                QueueId = exampleQueueId
            } };

            await RunInMongoLand(async database =>
            {
                var jobs = database.GetJobCollection();

                await jobs.InsertManyAsync(existingJobs).ConfigureAwait(false);

                var sut = new MongoJobPeekNextService(new MongoJobQueryService(database));

                var results = (await sut.PeekFor(exampleQuery).ConfigureAwait(false))?.ToList();

                Assert.That(results, Is.Not.Null);
                Assert.That(results, Has.Count.EqualTo(1));

                Assert.That(results?.First()?.Id, Is.EqualTo(newlyCreatedJobId));
            }).ConfigureAwait(false);

        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Chenolea tricornis Benth.

### Remarks
null


text:
import { AsyncPipe, I18nPluralPipe } from '@angular/common';
import { ChangeDetectorRef, Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { getTimePipeValue, TIME_DURATION_MAPPING, TimePipeTranslationMapping } from './time-pipe-data';

@Pipe({
  name: 'timeDuration',
  pure: false,
})
export class TimeDurationPipe implements PipeTransform {
  private value: number;
  private observable: Observable<string>;
  private readonly asyncPipe: AsyncPipe;

  constructor(private ref: ChangeDetectorRef,
              private translate: TranslateService,
              private i18nPluralPipe: I18nPluralPipe) {
    this.asyncPipe = new AsyncPipe(ref);
  }

  public transform(timeDuration: number): string | null {
    this.value = timeDuration;
    if (!this.observable) {
      this.observable = this.getObservable();
    }
    return this.asyncPipe.transform(this.observable);
  }

  ngOnDestroy() {
    this.asyncPipe.ngOnDestroy();
  }

  private getTranslationKey(value: number, timeType: keyof TimePipeTranslationMapping) {
    return this.i18nPluralPipe.transform(value, TIME_DURATION_MAPPING[ timeType ]);
  }

  private getObservable(): Observable<string> {
    const { value, timeType } = getTimePipeValue(this.value);
    return this.translate.stream(this.getTranslationKey(value, timeType), { value });
  }
}


text:
package teleport

import (
	"time"
)

// ForeverTTL means that object TTL will not expire unless deleted
const ForeverTTL time.Duration = 0

const (
	// Component indicates a component of teleport, used for logging
	Component = "component"

	// ComponentFields stores component-specific fields
	ComponentFields = "fields"

	// ComponentReverseTunnel is reverse tunnel agent and server
	// that together establish a bi-directional SSH revers tunnel
	// to bypass firewall restrictions
	ComponentReverseTunnel = "reversetunnel"

	// ComponentAuth is the cluster CA node (auth server API)
	ComponentAuth = "auth"

	// ComponentNode is SSH node (SSH server serving requests)
	ComponentNode = "node"

	// ComponentProxy is SSH proxy (SSH server forwarding connections)
	ComponentProxy = "proxy"

	// ComponentTunClient is a tunnel client
	ComponentTunClient = "tunclient"

	// DebugEnvVar tells tests to use verbose debug output
	DebugEnvVar = "DEBUG"

	// VerboseLogEnvVar forces all logs to be verbose (down to DEBUG level)
	VerboseLogsEnvVar = "TELEPORT_DEBUG"

	// DefaultTerminalWidth defines the default width of a server-side allocated
	// pseudo TTY
	DefaultTerminalWidth = 80

	// DefaultTerminalHeight defines the default height of a server-side allocated
	// pseudo TTY
	DefaultTerminalHeight = 25

	// SafeTerminalType is the fall-back TTY type to fall back to (when $TERM
	// is not defined)
	SafeTerminalType = "xterm"

	// ConnectorOIDC means connector type OIDC
	ConnectorOIDC = "oidc"

	// DataDirParameterName is the name of the data dir configuration parameter passed
	// to all backends during initialization
	DataDirParameterName = "data_dir"

	// SSH request type to keep the connection alive. A client and a server keep
	// pining each other with it:
	KeepAliveReqType = "keepalive@openssh.com"

	// OTP means One-time Password Algorithm.
	OTP = "otp"

	// TOTP means Time-based One-time Password Algorithm.
	TOTP = "totp"

	// HOTP means HMAC-based One-time Password Algorithm.
	HOTP = "hotp"

	// U2F means Universal 2nd Factor.
	U2F = "u2f"

	// OIDC means OpenID Connect.
	OIDC = "oidc"
)


text:
var jsnums = require('./js-numbers/js-numbers');

// Unicode character for non-breaking space
var NBSP = '\u00A0';

/**
 * A token is a value, and a boolean indicating whether or not it is "marked".
 * Marking is done for two different reasons.
 * (1) We're comparing two expressions and want to mark where they differ.
 * (2) We're looking at a single expression and want to mark the deepest
 *     subexpression.
 * @param {string|jsnumber} val
 * @param {boolean} marked
 */
var Token = function (val, marked) {
  this.val_ = val;
  this.marked_ = marked;

  // Store string representation of value. In most cases this is just a
  // non repeated portion. In the case of something like 1/9 there will be both
  // a non repeated portion "0." and a repeated portion "1" - i.e. 0.1111111...
  /** @type {string} */
  this.nonRepeated_ = null;
  /** @type {string} */
  this.repeated_ = null;
  this.setStringRepresentation_();
};
module.exports = Token;

Token.prototype.isParenthesis = function () {
  return this.val_ === '(' || this.val_ === ')';
};

/**
 * Add the given token to the parent element.
 * @param {HTMLElement} element Parent element to add to
 * @param {number} xPos X position to place element at
 * @param {string?} markClass Class name to use if token is marked
 * @returns {number} the length of the added text element
 */
Token.prototype.renderToParent = function (element, xPos, markClass) {
  var text, textLength;

  text = document.createElementNS(Blockly.SVG_NS, 'text');

  var tspan = document.createElementNS(Blockly.SVG_NS, 'tspan');
  // Replace spaces with 2x nonbreaking space
  tspan.textContent = this.nonRepeated_.replace(/ /g, NBSP + NBSP);
  text.appendChild(tspan);

  if (this.repeated_) {
    tspan = document.createElementNS(Blockly.SVG_NS, 'tspan');
    tspan.setAttribute('style', 'text-decoration: overline');
    // Replace spaces with 2x nonbreaking space
    tspan.textContent = this.repeated_.replace(/ /g, NBSP + NBSP);
    text.appendChild(tspan);
  }

  element.appendChild(text);

  // FF doesnt have offsetWidth
  // getBoundingClientRect undercalculates width on iPad
  if (text.offsetWidth !== undefined) {
    textLength = text.offsetWidth;
  } else {
    textLength = text.getBoundingClientRect().width;
  }

  text.setAttribute('x', xPos);
  if (this.marked_ && markClass) {
    text.setAttribute('class', markClass);
  }

  return textLength;
};

/**
 * Sets string representation of value.
 */
Token.prototype.setStringRepresentation_ = function () {
  if (!jsnums.isSchemeNumber(this.val_) || typeof(this.val_) === 'number') {
    this.nonRepeated_ = this.val_;
    return;
  }

  // at this point we know we have a jsnumber
  if (this.val_.isInteger()) {
    this.nonRepeated_ = Token.numberWithCommas_(this.val_.toFixnum());
    return;
  }

  // Gives us three values: Number before decimal, non-repeating portion,
  // repeating portion. If we don't have the last bit, there's no repitition.
  var numerator = jsnums.toExact(this.val_.numerator());
  var denominator = jsnums.toExact(this.val_.denominator());
  var repeater = jsnums.toRepeatingDecimal(numerator, denominator);
  if (!repeater[2] || repeater[2] === '0') {
    this.nonRepeated_ = Token.numberWithCommas_(this.val_.toFixnum());
    return;
  }

  this.nonRepeated_ = Token.numberWithCommas_(repeater[0]) + '.' + repeater[1];
  this.repeated_ = repeater[2];
};

/**
 * From http://stackoverflow.com/a/2901298/2506748
 * @param {number} x
 * @returns {string} the number with commas inserted in thousandth's place
 */
Token.numberWithCommas_ = function (x) {
  var parts = x.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
};


text:
/* File: "guideuihighlighterscheme.cpp", Time-stamp: <2005-04-28 12:02:08 feeley> */

/* Copyright (C) 1994-2005 by Marc Feeley, All Rights Reserved. */

/*---------------------------------------------------------------------------*/

#include "guide.h"
#include "guideuihighlighterscheme.h"
#include <qtextedit.h>
#include <qvaluestack.h>

/*---------------------------------------------------------------------------*/

GuideUiCodeFormat* GuideUiHighlighterScheme::schemeCodeFormat = 0;

GuideUiHighlighterScheme::GuideUiHighlighterScheme (QTextEdit *textEdit)
  : GuideUiHighlighter (textEdit)
{
  if (schemeCodeFormat == 0)
    {
      // Add the default format elements to the code format
      schemeCodeFormat = codeFormat = new GuideUiCodeFormat();
      codeFormat->addElement(QColor(0  ,0  ,0  ), "Normal");
      codeFormat->addElement(QColor(128,0  ,128), "Parenthesis");
      codeFormat->addElement(QColor(128,128,128), "Comment");
      codeFormat->addElement(QColor(0  ,0  ,255), "Number");
      codeFormat->addElement(QColor(255,0  ,0  ), "String");
      codeFormat->addElement(QColor(0  ,128,0  ), "Identifier");
      codeFormat->addElement(QColor(128,128,0  ), "Keyword");
      codeFormat->addElement(QColor(0  ,128,128), "Constant");
      codeFormat->addElement(QColor(255,128,255), "Highlight");
    }
  else
    codeFormat = schemeCodeFormat;
  highlightPara[0] = highlightPara[1] = -1;
}

// Create a syntax highlighter to apply on 'text'
void GuideUiHighlighterScheme::applyTo (QTextEdit *text)
{
  new GuideUiHighlighterScheme(text);
}

// Returns the length of the pointed token
int GuideUiHighlighterScheme::tokenLength (int para, int index)
{
  QValueVector<TokenType> *tokens;
  QString text = textEdit()->text(para);
  int endState = getEndState(para);
  tokens = getTokens(text, endState);
  TokenType t;

  // Search for the pointed token
  int tokenNb = -1;
  for (uint i=0; i<tokens->size(); i++)
    {
      t = (*tokens)[i];
      if (index >= t.start && index < t.start + t.length)
        {
          tokenNb = i;
          break;
        }
    }

  if (tokenNb == -1) return 1;
  t = (*tokens)[tokenNb];
  if (t.type != T_OPEN_PARENT)
    return t.length;

  // If there is a parenthesis
  int parent = 1;
  tokenNb++;
  while ((uint)tokenNb < tokens->size() && parent > 0)
    {
      t = (*tokens)[tokenNb];
      if (t.type == T_OPEN_PARENT)
        parent++;
      if (t.type == T_CLOSE_PARENT)
        parent--;

      tokenNb++;
    }

  if (parent == 0)
    {
      t = (*tokens)[--tokenNb];
      return t.start + t.length - index;
    }
  return text.length() - index;
}

int GuideUiHighlighterScheme::highlightParagraph (const QString &text, int endStateOfLastPara)
{
  if (!schemeCodeFormat->highlighterEnabled)
    {
      // No highlighting
      setFormat (0, text.length (), 0);
      return 0;
    }

  QString text2 = text;

  // If it is a console, alter 'text' to highlight only the typed text
  if (consoleInfo)
    {
      int startCol;
      if (currentParagraph() == textEdit()->paragraphs()-1)
        startCol = consoleInfo->nbReadOnlyChars;
      else
        startCol = consoleInfo->getStartCol(currentParagraph());
      if (startCol == -1)
        {
          text2 = "";
          setFormat(0, text.length(), 0);
        }
      else
        {
          text2 = QString().fill(' ',startCol);
          text2 += text.right(text.length()-startCol);
          setFormat(0, startCol, 0);
        }
    }

  QValueVector<TokenType> *tokens;
  tokens = getTokens(text2, endStateOfLastPara);
  TokenType t;

  // Search for the first caracter to highlight in the current paragraph
  int highlightIndex = 0;
  while (highlightIndex < 2 && currentParagraph() != highlightPara[highlightIndex])
    highlightIndex++;

  for (uint i=0; i<tokens->size(); i++)
    {
      t = (*tokens)[i];
      int colorNb;
      switch(t.type)
        {
        case T_IDENT:
          colorNb = 5; break;
        case T_KEYWORD:
          colorNb = 6; break;
        case T_OPEN_PARENT: case T_CLOSE_PARENT:
          colorNb = 1; break;
        case T_NUMBER:
          colorNb = 3; break;
        case T_STRING:
          colorNb = 4; break;
        case T_OPEN_COMMENT: case T_CLOSE_COMMENT: case T_COMMENT:
          colorNb = 2; break;
        case T_CONSTANT:
          colorNb = 7; break;
        default:
          colorNb = 0; break;
        }
      setFormat(t.start, t.length, colorNb);

      // Highlight designated characters
      if (highlightIndex < 2) {
        if (highlightColumn[highlightIndex] >= t.start && highlightColumn[highlightIndex] < t.start + t.length)
          {
            setFormat(highlightColumn[highlightIndex], 1, 8);
            highlightIndex++;
            while (highlightIndex < 2 && currentParagraph() != highlightPara[highlightIndex])
              highlightIndex++;
          }
      }
    }

  delete tokens;

  setEndState(currentParagraph(), endStateOfLastPara);
  return endStateOfLastPara;
}

// Get a list of syntaxic tokens from paragraph Text
QValueVector<GuideUiHighlighterScheme::TokenType>* GuideUiHighlighterScheme::getTokens (const QString &text, int &endStateOfLastPara)
{
  QValueVector<TokenType> *tokens = new QValueVector<TokenType>;
  TokenType t;
  int current = 0;
  int length = text.length();
  if (endStateOfLastPara == S_FIRST_PARA)
    endStateOfLastPara = S_NORMAL;

  // Find all the tokens in this paragraph
  while (current < length)
    {
      int last = current;
      t.type = T_NO_TOKEN;

      if (endStateOfLastPara == S_IN_STRING || endStateOfLastPara == S_IN_STRING_2)
        {
          while ((last < length) && (text[last] != ((endStateOfLastPara == S_IN_STRING)?'\"':'|')))
            {
              if (text[last] == '\\') last++;
              last++;
            }
          if (last >= length) // Non-terminated string
            last = length;
          else
            endStateOfLastPara = S_NORMAL;
          t.type = T_STRING;
        }
      // If it is on the comment state
      else if (endStateOfLastPara >= S_COMMENT)
        {
          int index1 = text.find("|#", current);
          int index2 = text.find("#|", current);
          if (index1 == -1 && index2 == -1)
            {
              last = length-1;
              t.type = T_COMMENT;
            }
          else if (index1 == current)
            {
              last = current+1;
              t.type = T_CLOSE_COMMENT;
              endStateOfLastPara--;
              if (endStateOfLastPara < S_COMMENT)
                endStateOfLastPara = S_NORMAL;
            }
          else if (index2 == current)
            {
              last = current+1;
              t.type = T_OPEN_COMMENT;
              endStateOfLastPara++;
            }
          else if (index1 == -1)
            {
              last = index2-1;
              t.type = T_COMMENT;
            }
          else if (index2 == -1)
            {
              last = index1-1;
              t.type = T_COMMENT;
            }
          else
            {
              last = min(index1, index2)-1;
              t.type = T_COMMENT;
            }
        }
      else
        {
          char c = getCharType(text[current]);

          // Open parenthesis
          if (text[last] == '(' ||
              text[last] == '{' ||
              text[last] == '[')
            {
              t.type = T_OPEN_PARENT;
            }
          // Close parenthesis
          else if (text[last] == ')' ||
                   text[last] == '}' ||
                   text[last] == ']')
            {
              t.type = T_CLOSE_PARENT;
            }
          // String
          else if (text[last] == '\"' ||
                   text[last] == '|')
            {
              last++;
              while (last < length && text[current] != text[last])
                {
                  if (text[last] == '\\') last++;
                  last++;
                }
              if (last >= length) // Non-terminated string
                {
                  last = length;
                  endStateOfLastPara = (text[last]=='\"')?S_IN_STRING:S_IN_STRING_2;
                }
              t.type = T_STRING;
            }
          // Line comment
          else if (text[last] == ';')
            {
              last = length;
              t.type = T_COMMENT;
            }
          // Sharp
          else if (text[last] == '#')
            {
              last++;
              if (text[last] == '|') // Block comment
                {
                  t.type = T_OPEN_COMMENT;
                  endStateOfLastPara = S_COMMENT;
                }
              // Boolean constant
              else if (toupper(text[last]) == 'T' ||
                       toupper(text[last]) == 'F')
                {
                  t.type = T_CONSTANT;
                }
              // Text constant
              else if (text[last] == '!' ||
                       text[last] == '\\' ||
                       text[last] == '#')
                {
                  last++;
                  char c2 = getCharType(text[last]);
                  while (last < length && c2 == C_LETTER) {
                    last++;
                    if (last < length)
                      {
                        c2 = getCharType(text[last]);
                        if (c2 != C_LETTER)
                          last--;
                      }
                  }
                  t.type = T_CONSTANT;
                }
              // Number
              else if (toupper(text[last]) == 'E' ||
                       toupper(text[last]) == 'I' ||
                       toupper(text[last]) == 'B' ||
                       toupper(text[last]) == 'D' ||
                       toupper(text[last]) == 'O' ||
                       toupper(text[last]) == 'X')
                {
                  last = last;
                  t.type = T_NUMBER;
                  parseNumber(last, text);
                }
              // Vector
              else if (text[last] == '(') {
                last = last;
                t.type = T_CONSTANT;
              }
            }
          // Identifier
          else if (c == C_LETTER || c == C_INIT)
            {
              c = getCharType(text[last]);
              while (last < length && (c == C_LETTER || c == C_NUMBER ||
                                       c == C_INIT || c == C_NEXT))
                {
                  last++;
                  c = getCharType(text[last]);
                }
              last--;

              if (searchKeyword(text.mid(current, last-current+1)))
                t.type = T_KEYWORD;
              else t.type = T_IDENT;
            }
          else if (c == C_NEXT)
            {
              if (text[last] != '@')
                {
                  if (last+1 == length || getCharType(text[last+1])==C_SPACE)
                    t.type = T_IDENT;
                  if (text[last] == '.' && length > last+2 &&
                      text[last+1] == '.' && text[last+2] == '.')
                    t.type = T_IDENT;
                }
            }
          // Number
          else if (c == C_NUMBER)
            {
              parseNumber(last, text);
              t.type = T_NUMBER;
            }
          // Other
          else
            {
              if (text[last] == '=')
                t.type = T_IDENT;
              if (text[last] == '\'')
                t.type = T_CONSTANT;
            }
        }

      if (t.type != T_NO_TOKEN)
        {
          // Add a token to the vector
          t.start = current;
          t.length = last-current+1;
          tokens->append(t);
        }

      current = last+1;
    }

  return tokens;
}

// DEBUG: print a vector of tokens
void GuideUiHighlighterScheme::printTokens (QValueVector<TokenType>* tokens)
{
  for (uint i=0; i<tokens->size(); i++)
    {
      TokenType t = (*tokens)[i];
      switch(t.type)
        {
        case T_NO_TOKEN: printf("NOTOK"); break;
        case T_IDENT: printf("IDENT"); break;
        case T_KEYWORD: printf("KEYWO"); break;
        case T_OPEN_PARENT: printf("OPENP"); break;
        case T_CLOSE_PARENT: printf("CLOSP"); break;
        case T_NUMBER: printf("NUMBE"); break;
        case T_STRING: printf("STRIN"); break;
        case T_CONSTANT: printf("CONST"); break;
        case T_OPEN_COMMENT: printf("OPENC"); break;
        case T_CLOSE_COMMENT: printf("CLOSC"); break;
        case T_COMMENT: printf("COMME"); break;
        default: printf("XXX%02d", t.type);
        }
      printf("%02d,%02d ",t.start,t.length);
    }
  printf("\n\n");
}

// Parse number from current position
void GuideUiHighlighterScheme::parseNumber (int& last, const QString &text)
{
  bool ok = true;
  int length = text.length();

  while (last < length && ok) {
    CharType c = getCharType(text[last]);
    if (c != C_NUMBER && c != C_LETTER)
      {
        switch (text[last])
          {
          case '#': case '.': case '/': case '@': case '+': case '-': break;
          default: ok = false; last--; return;
          }
      }
    last++;
  }
  last--;
}

// Returns the character type
GuideUiHighlighterScheme::CharType GuideUiHighlighterScheme::getCharType (char c)
{
  if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
    return C_LETTER;
  if (c >= '0' && c <= '9')
    return C_NUMBER;

  switch (c)
    {
    case '!': case '$': case '%': case '&': case '*': case '/':
    case ':': case '<': case '>': case '?': case '^': case '_':
    case '~':
      return C_INIT;
    case '+': case '-': case '.': case '@':
      return C_NEXT;
    case ' ': case '\t': case '\n': case '\r':
      return C_SPACE;
    default:
      return C_OTHER;
    }
}

// Search if text is a keyword
bool GuideUiHighlighterScheme::searchKeyword (QString text)
{
  for (int i=0; i<nbKeywords; i++)
    {
      if (text.compare(keywords[i]) == 0)
        return true;
    }
  return false;
}

// When cursor position changed, balance parentheses if the cursor is near of a parenthesis
void GuideUiHighlighterScheme::cursorPositionChanged (int para, int col)
{
  highlightPara[0] = -1;
  highlightColumn[0] = -1;
  highlightPara[1] = -1;
  highlightColumn[1] = -1;

  if (!schemeCodeFormat->matchParent)
    {
      rehighlight();
      return;
    }

  int tokenIndex[2];
  QString text = textEdit()->text(para);
  int endState = getEndState(para-1);
  QValueVector<TokenType> *tokens = getTokens(text, endState);

  highlightPara[0] = highlightPara[1] = -1;

  // Search for parenthesis near the cursor position
  for (uint i=0; i<tokens->size(); i++)
    {
      TokenType t = (*tokens)[i];
      if (t.type == T_OPEN_PARENT &&
          highlightPara[0] == -1 &&
          t.start <= col && t.start >= col-1)
        {
          highlightPara[0] = para;
          highlightColumn[0] = t.start;
          tokenIndex[0] = i;
        }
      if (t.type == T_CLOSE_PARENT &&
          highlightPara[1] == -1 &&
          t.start <= col && t.start >= col-1)
        {
          highlightPara[1] = para;
          highlightColumn[1] = t.start;
          tokenIndex[1] = i;
        }
    }

  if (highlightPara[0] < 0 && highlightPara[1] < 0)
    {
      rehighlight();
      return;
    }

  int paraNb = para, tokenNb;
  if (highlightPara[1] >= 0)
    tokenNb = tokenIndex[1];
  else
    tokenNb = tokenIndex[0];

  int colNb = searchOtherParenthesis(paraNb, tokenNb);

  if (colNb >= 0)
    {
      if (highlightPara[1] >= 0)
        {
          highlightPara[0] = paraNb;
          highlightColumn[0] = colNb;
        }
      else
        {
          highlightPara[1] = paraNb;
          highlightColumn[1] = colNb;
        }
    }

  rehighlight();
}

// Get the indent length of the next paragraph
int GuideUiHighlighterScheme::getIndentLength (int para)
{
  if (!schemeCodeFormat->autoIndent) return -1;
  QValueVector<TokenType> *tokens;

  // Search for the open parenthesis which belongs to this line
  int row = para-1;
  QString text = textEdit()->text(row);
  int endState = getEndState(row-1);
  tokens = getTokens(text, endState);
  int tokenNb = tokens->size()-1;
  int level = 0; // Parenthesis level
  while (level >= 0 && row >= 0)
    {
      // Check the current token
      if (tokenNb >= 0)
        {
          TokenType t = (*tokens)[tokenNb];
          if (t.type == T_OPEN_PARENT)
            level--;
          else if (t.type == T_CLOSE_PARENT)
            level++;
        }
      if (level < 0) continue;

      // Go to next token
      tokenNb--;
      if (tokenNb < 0)
        {
          delete tokens;
          row--;
          text = textEdit()->text(row);
          endState = getEndState(row-1);
          tokens = getTokens(text, endState);
          tokenNb = tokens->size()-1;
        }
    }

  if (level >= 0)
    {
      delete tokens;
      return -1;
    }

  // Calculates the indent length
  int indent;
  switch (tokens->size()-tokenNb-1)
    {
    case 0: indent = (*tokens)[tokenNb].start+1; break;
    case 1: indent = (*tokens)[tokenNb].start+2; break;
    default:
      if ((*tokens)[tokenNb+1].type == T_KEYWORD)
        indent = (*tokens)[tokenNb].start+2;
      else
        indent = (*tokens)[tokenNb+2].start;
      break;
    }
  delete tokens;
  return indent;
}

// When the user double-clicks the textEdit, selects the pointed expression
void GuideUiHighlighterScheme::doubleClicked (int para, int index)
{
  int paraStart = para, paraEnd = para,
    colStart = index, colEnd = index + 1;

  QString text = textEdit()->text(para);
  int endState = getEndState(para-1);
  QValueVector<TokenType> *tokens = getTokens(text, endState);
  TokenType t;

  // Search the double-clicked token
  for (uint i=0; i<tokens->size(); i++)
    {
      t = (*tokens)[i];
      if (index < t.start || index >= t.start + t.length)
        continue;

      // If it is a parenthesis, selects the entire expression
      if (t.type == T_OPEN_PARENT ||
          t.type == T_CLOSE_PARENT)
        {
          int paraNb = para;
          int tokenNb = i;
          int colNb = searchOtherParenthesis(paraNb, tokenNb);
          if (t.type == T_OPEN_PARENT)
            {
              paraStart = para;
              colStart = t.start;
              paraEnd = paraNb;
              colEnd = colNb + 1;
            }
          else
            {
              paraStart = paraNb;
              colStart = colNb;
              paraEnd = para;
              colEnd = t.start + 1;
            }
        }
      else
        {
          paraStart = paraEnd = para;
          colStart = t.start;
          colEnd = t.start + t.length;
        }
      break;
    }

  textEdit()->setSelection(paraStart, colStart, paraEnd, colEnd);
}

// Search for the related parenthesis of the pointed parenthesis
int GuideUiHighlighterScheme::searchOtherParenthesis (int &paraNb, int &tokenNb)
{
  int level = 0;
  QString text = textEdit()->text(paraNb);
  int endState = getEndState(paraNb-1);
  QValueVector<TokenType> *tokens = getTokens(text, endState);
  if (tokenNb > (int)tokens->size()) {
    delete tokens;
    return -1;
  }
  TokenType t = (*tokens)[tokenNb];
  int parentType = t.type;
  // Ensure this is a parenthesis
  if (parentType != T_OPEN_PARENT &&
      parentType != T_CLOSE_PARENT)
    {
      delete tokens;
      return -1;
    }

  // Search for the corresponding open parenthesis
  if (parentType == T_CLOSE_PARENT)
    {
      do
        {
          // Check the current token
          if (tokenNb >= 0)
            {
              t = (*tokens)[tokenNb];
              if (t.type == T_OPEN_PARENT)
                level--;
              if (t.type == T_CLOSE_PARENT)
                level++;
            }
          if (level == 0) continue;

          // Go to the next token
          tokenNb--;
          if (tokenNb < 0)
            {
              paraNb--;
              if (paraNb < 0)
                {
                  if (level > 0) level = -1;
                  tokenNb = 0;
                }
              else
                {
                  delete tokens;
                  text = textEdit()->text(paraNb);
                  endState = getEndState(paraNb-1);
                  tokens = getTokens(text, endState);
                  tokenNb = tokens->size()-1;
                }
            }
        } while (level > 0);

      // If the parenthesis is not found
      if (level != 0)
        paraNb = -1;
    }

  // Search for the corresponding close parenthesis
  else if (highlightPara[0] >= 0)
    {
      do
        {
          // Check the current token
          if (tokenNb < (int)tokens->size())
            {
              t = (*tokens)[tokenNb];
              if (t.type == T_OPEN_PARENT)
                level++;
              if (t.type == T_CLOSE_PARENT)
                level--;
            }
          if (level == 0) continue;

          // Go to the next token
          tokenNb++;
          if (tokenNb >= (int)tokens->size())
            {
              paraNb++;
              tokenNb = 0;
              if (paraNb >= textEdit()->paragraphs())
                {
                  if (level > 0) level = -1;
                }
              else
                {
                  delete tokens;
                  text = textEdit()->text(paraNb);
                  endState = getEndState(paraNb-1);
                  tokens = getTokens(text, endState);
                }
            }
        } while (level > 0);

      // If the parenthesis is not found
      if (level != 0)
        paraNb = -1;
    }

  delete tokens;

  if (paraNb == -1) return -1;
  return t.start;
}

// Sets the end state of the current paragraph
void GuideUiHighlighterScheme::setEndState (int para, int endState)
{
  if (para < 0) return;
  if (para >= (int)endStates.size())
    endStates.resize(para+1, 0);
  endStates[para] = endState;
}

// Returns the end state of the paragraph
int GuideUiHighlighterScheme::getEndState (int para)
{
  if (para < 0)
    return -2;
  if (para >= (int)endStates.size())
    return 0;
  return endStates[para];
}

/*---------------------------------------------------------------------------*/

/* Local Variables: */
/* mode: C++ */
/* End: */


text:
"""
Post Class
for lap_joint script

Post:
	.id             int         Post identifier
	.brep           Brep        Brep representing Post
	.profile        Curve       Curve defining end profile of post
	.axis           Line        Line between centers of end faces
	.origin         Point       start of axis Line
	.orientation    Plane       plane with normal along axis and x-axis towards
									center of one face
	.pockets        list        list of Pockets on this Post
	.isConnected    Bool        true if this post is part of a joint
	.selfToGlobal   Transform   convert local coordinates to global
	.globalToSelf   Transform   convert global coordinates to local
	.millToGlobal   Transform   convert unrotated mill coordinates to global
"""

import Rhino
import scriptcontext as sc
import rhinoscriptsyntax as rs

import math

import common
from toolpath import *

class Post:
	"""A single post in the system."""

	def __init__(self, axis=None, obRef=None, roll=None, group=None, width=None, height=None, id=None):
		"""Initialize a Post.

		Gathers all information about this Post

		Offers multiple ways to describe a Post:
			Start with Rhino object:
				obRef: reference to a Rhino object

			Start with lines:
				group: obRef of one object in a group
				OR
				axis: central axis of the post
				roll: (optional), line normal to axis, defines roll of post

				For a rectangular Post:
					width: width along roll axis
					height: other short dimension of Post
		"""

		self.isConnected = False
		self.brep = None
		#not sure about this. id is None until assigned by the Structure?
		self.id = id

		if group: #creating Post with axis and roll lines grouped together
			#find group this object belongs to
			groups = group.Object().Attributes.GetGroupList()
			if len(groups) < 1:
				raise NameError("Object does not belong to a group.")
			group_id = groups[0]

			#get all objects in the group
			objects = rs.ObjectsByGroup(sc.doc.Groups.GroupName(group_id))
			if len(objects) != 2:
				raise NameError("Group does not have two objects (axis, roll).")
			#get actual curves
			curves = [sc.doc.Objects.Find(ob).CurveGeometry for ob in objects]
			#convert to lines
			lines = [Rhino.Geometry.Line(c.PointAtStart, c.PointAtEnd) for c in curves]
			#roll is shorter than axis
			roll, axis = sorted(lines, key=lambda l: l.Length)

		if axis: #creating Post based on lines
			if not (width and height): #currently only rectangular solids.
				raise NameError("Height and width required if an object is not given.")

			if type(axis) is Rhino.DocObjects.ObjRef: #axis is objref to a curve
				#find actual curve geometry
				axis = axis.Geometry()

			if type(axis) is Rhino.DocObjects.ObjectType.Curve:
				self.axis = Rhino.Geometry.Line(axis.PointAtStart, axis.PointAtEnd)
			else: #assume for now axis is either curve or internal line object
				self.axis = axis

			if roll:
				#if roll is a curve, convert it to a Line
				if type(roll) == Rhino.DocObjects.ObjectType.Curve:
					roll = Rhino.Geometry.Line(roll.PointAtStart, roll.PointAtEnd)

				self.orientation = rs.PlaneFromNormal(self.axis.From,
					self.axis.UnitTangent, roll.UnitTangent)

			else:
				#construct orientation with default roll angle
				self.orientation = rs.PlaneFromNormal(self.axis.From,
				self.axis.UnitTangent)

			#construct rectangular profile curve
			self.profile = self.makeRectProfile(width, height)

		elif obRef: #no axis, need obRef
			object = obRef.Object()
			if object is None:
				raise NameError("No object found corresponding to reference " + str(obRef))

			#actual object geometry
			self.brep = common.getBrep(object)

			#assume smallest faces are the ends of the Post
			endFaces = sorted(self.brep.Faces, key=rs.SurfaceArea)[0:2]
			#get curve defining post profile
			self.profile = Rhino.Geometry.Curve.JoinCurves(endFaces[0].DuplicateFace(False).DuplicateEdgeCurves())
			#axis is a Line between centers of smallest faces.
			self.axis = Rhino.Geometry.Line(
				*[rs.SurfaceAreaCentroid(face)[0] for face in endFaces])

		else : #no axis and no obRef
			raise NameError('No valid axis or obRef given.')

		#just for convenience and simplicity
		self.origin = self.axis.From

		#get orientation of Post
		self.orientation = self.findOrientation()

		#store conversions to and from Post's orientation

		#rotate 90 degrees about y axis to align posts with x instead of z axis
		self.globalToSelf = Rhino.Geometry.Transform.Rotation(1,0,
			Rhino.Geometry.Vector3d.YAxis, Rhino.Geometry.Point3d.Origin)
		#transform global coordinates to post's local coordinates
		self.globalToSelf *= Rhino.Geometry.Transform.ChangeBasis(
			Rhino.Geometry.Plane.WorldXY, self.orientation)
		#go the other way
		self.selfToGlobal = self.globalToSelf.TryGetInverse()[1]

		#initialize list of this Post's Pockets
		self.pockets = []

	###########
	#Post Class Functions

	def info(self):
		"""Displays a text summary of this post."""

		print "Post: " + self.printId() + \
		"\n Length: " + str(round(self.axis.Length, 2)) + \
		"\n Origin: " + common.printPoint3d(self.origin) + \
		"\n----"

	def display(self, objects=None):
		"""Create objects in viewport to display information about this post.
			'objects' determines which objects to display

		Creates:
			label       text dot with post id
			orientation aligned plane with corner on post origin
			profile     profile curve
			object      post object, if not using obrefs
			axis        axis Line

		Returns:    list of guids of added objects
		"""

		guids = []

		if objects == None:
			objects = ['label', 'orientation']

		if 'label' in objects:
			guids.append(rs.AddTextDot(self.printId(), self.origin))
		if 'orientation' in objects:
			guids.append(common.displayPlane(self.orientation))
		if 'profile' in objects:
			guids.append(sc.doc.Objects.AddCurve(self.profile))
		if 'object' in objects:
			if not self.brep:
				vector = Rhino.Geometry.Vector3d(self.axis.To - self.axis.From)
				guids.append(sc.doc.Objects.AddBrep(
					Rhino.Geometry.Surface.CreateExtrusion(self.profile, vector).ToBrep()))
				rs.CapPlanarHoles(guids[-1])
		if 'axis' in objects:
			guids.append(sc.doc.Objects.AddLine(self.axis))
		if 'xAxis' in objects:
			guids.append(sc.doc.Objects.AddLine(self.origin, self.origin + self.orientation.XAxis))

		return guids

	def printId(self):
		"""return id with type letter"""

		return 'p' + str(self.id)

	def findOrientation(self):
		"""Find the orientation (direction and roll) of a post.

		Returns: plane with normal along axis and x-axis towards center of one face.

		"""

		#grab one edge of profile arbitrarily
		if type(self.profile) is Rhino.Geometry.PolyCurve:
			one_edge = self.profile.Explode()[0]
		else:
			raise NameError("Profile is wrong type of curve: " + str(type(self.profile)))

		middle_of_edge = one_edge.PointAtNormalizedLength(.5)
		#create plane from origin, normal vector, and x-axis vector
		return rs.PlaneFromNormal(self.origin,
			self.axis.UnitTangent,
			rs.VectorCreate(self.origin, middle_of_edge))

	def makeRoll(self):
		"""Construct a default horizontal roll angle"""

		#get plane normal to axis at arbitrary rotation
		plane = rs.PlaneFromNormal(self.axis.From, self.axis.UnitTangent)

		#set roll to horizontal component of x axis
		roll = Rhino.Geometry.Vector3d(plane.XAxis.X, plane.XAxis.Y, 0)

		if roll.IsZero:
			roll = plane.YAxis

		return Rhino.Geometry.Line(self.axis.From, plane.XAxis)

	def makeRectProfile(self, width, height):
		"""create a Post profile using the Post's orientation

		Returns: rectangular PolyCurve boundary
		"""

		#get corner uv coordinates
		corners = [[width/2, height/2], [width/2, -height/2],
			[-width/2, -height/2], [-width/2, height/2]]
		#close curve
		corners.append(corners[0])
		#convert local uvs to global points
		points = [self.orientation.PointAt(c[0], c[1]) for c in corners]
		#create polylinecurve
		polyline = Rhino.Geometry.Polyline(points)
		#get list of edge curves
		curves = [Rhino.Geometry.LineCurve(line) for line in polyline.GetSegments()]
		#join as polycurve
		return Rhino.Geometry.Curve.JoinCurves(curves)[0]

	def makeGcode(self, gcode=False):
		"""Convert mill paths of each pocket into Gcode for the entire Post

			Returns: gcode string for milling post
		"""

		if not gcode:
			gcode = common.Gcode()

		gcode.text += common.settings.gcode['preamble'] + "\n"

		gcode.text += "(Starting Post {0})\n".format(self.printId())

		for p in self.pockets:
			p.makeGcode(gcode=gcode)

		#get coordinates of home point
		home = str(common.settings.gcode['home']).split(',')
		home = [round(float(x), common.settings.gcode['precision']) for x in home]
		#return to home point when finished
		Rapid(Rhino.Geometry.Point3d(*home[0:3]), A=home[3], clear=True).makeGcode(gcode=gcode)

		return gcode

# End Post Class #