text:
=========================
Release 322 (16 Oct 2019)
=========================

General
-------

* Improve performance of certain join queries by reducing the amount of data
  that needs to be scanned. (:issue:`1673`)

Server RPM
----------

* Fix a regression that caused zero-length files in the RPM. (:issue:`1767`)

Other connectors
----------------

These changes apply to MySQL, PostgreSQL, Redshift, and SQL Server.

* Add support for providing credentials using a keystore file. This can be enabled
  by setting the ``credential-provider.type`` configuration property to ``KEYSTORE``
  and by setting the ``keystore-file-path``, ``keystore-type``, ``keystore-password``,
  ``keystore-user-credential-password``, ``keystore-password-credential-password``,
  ``keystore-user-credential-name``, and ``keystore-password-credential-name``
  configuration properties. (:issue:`1521`)


text:
/*
The sum of a range

The introduction of this book alluded to the following as a nice way to compute the sum of a range of numbers:

console.log(sum(range(1, 10)));
Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.

Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.

As a bonus assignment, modify your range function to take an optional third argument that indicates the "step" value used to build up the array. If no step is given, the array elements go up by increments of one, corresponding to the old behavior. The function call range(1, 10, 2) should return [1, 3, 5, 7, 9]. Make sure it also works with negative step values so that range(5, 2, -1) produces [5, 4, 3, 2].
*/

// Your code here.
function range(start, end, step) {
  if (arguments.length < 3) step = 1;
  var array = [];

  if (step > 0) {
    for (var i = start; i <= end; i += step) {
      array.push(i);
    }
  } else {
    for (var i = start; i >= end; i += step) {
      array.push(i);
    }
  } return array;
}

function sum(array) {
  var counter = 0;
  for (var i = 0; i < array.length; i++) {
    counter += array[i];
  } return counter;
}

console.log(sum(range(1, 10)));
// → 55
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using ApiContractGenerator.Model.TypeReferences;

namespace ApiContractGenerator.Model
{
    public interface IMetadataEvent : IMetadataSymbol
    {
        IReadOnlyList<IMetadataAttribute> Attributes { get; }
        MetadataTypeReference HandlerType { get; }
        IMetadataMethod AddAccessor { get; }
        IMetadataMethod RemoveAccessor { get; }
        IMetadataMethod RaiseAccessor { get; }
    }
}


text:
import type {ReactPriorityLevel} from './ReactInternalTypes';

// Intentionally not named imports because Rollup would use dynamic dispatch for
// CommonJS interop named imports.
import * as Scheduler from 'scheduler';
import {__interactionsRef} from 'scheduler/tracing';
import {enableSchedulerTracing} from 'shared/ReactFeatureFlags';
import invariant from 'shared/invariant';

const {
  unstable_runWithPriority: Scheduler_runWithPriority,
  unstable_scheduleCallback: Scheduler_scheduleCallback,
  unstable_cancelCallback: Scheduler_cancelCallback,
  unstable_shouldYield: Scheduler_shouldYield,
  unstable_requestPaint: Scheduler_requestPaint,
  unstable_now: Scheduler_now,
  unstable_getCurrentPriorityLevel: Scheduler_getCurrentPriorityLevel,
  unstable_ImmediatePriority: Scheduler_ImmediatePriority,
  unstable_UserBlockingPriority: Scheduler_UserBlockingPriority,
  unstable_NormalPriority: Scheduler_NormalPriority,
  unstable_LowPriority: Scheduler_LowPriority,
  unstable_IdlePriority: Scheduler_IdlePriority,
} = Scheduler;

if (enableSchedulerTracing) {
  // Provide explicit error message when production+profiling bundle of e.g.
  // react-dom is used with production (non-profiling) bundle of
  // scheduler/tracing
  invariant(
    __interactionsRef != null && __interactionsRef.current != null,
    'It is not supported to run the profiling version of a renderer (for ' +
      'example, `react-dom/profiling`) without also replacing the ' +
      '`scheduler/tracing` module with `scheduler/tracing-profiling`. Your ' +
      'bundler might have a setting for aliasing both modules. Learn more at ' +
      'http://fb.me/react-profiling',
  );
}

export type SchedulerCallback = (isSync: boolean) => SchedulerCallback | null;

type SchedulerCallbackOptions = {timeout?: number, ...};

const fakeCallbackNode = {};

// Except for NoPriority, these correspond to Scheduler priorities. We use
// ascending numbers so we can compare them like numbers. They start at 90 to
// avoid clashing with Scheduler's priorities.
export const ImmediatePriority: ReactPriorityLevel = 99;
export const UserBlockingPriority: ReactPriorityLevel = 98;
export const NormalPriority: ReactPriorityLevel = 97;
export const LowPriority: ReactPriorityLevel = 96;
export const IdlePriority: ReactPriorityLevel = 95;
// NoPriority is the absence of priority. Also React-only.
export const NoPriority: ReactPriorityLevel = 90;

export const shouldYield = Scheduler_shouldYield;
export const requestPaint =
  // Fall back gracefully if we're running an older version of Scheduler.
  Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : () => {};

let syncQueue: Array<SchedulerCallback> | null = null;
let immediateQueueCallbackNode: mixed | null = null;
let isFlushingSyncQueue: boolean = false;
const initialTimeMs: number = Scheduler_now();

// If the initial timestamp is reasonably small, use Scheduler's `now` directly.
// This will be the case for modern browsers that support `performance.now`. In
// older browsers, Scheduler falls back to `Date.now`, which returns a Unix
// timestamp. In that case, subtract the module initialization time to simulate
// the behavior of performance.now and keep our times small enough to fit
// within 32 bits.
// TODO: Consider lifting this into Scheduler.
export const now =
  initialTimeMs < 10000 ? Scheduler_now : () => Scheduler_now() - initialTimeMs;

export function getCurrentPriorityLevel(): ReactPriorityLevel {
  switch (Scheduler_getCurrentPriorityLevel()) {
    case Scheduler_ImmediatePriority:
      return ImmediatePriority;
    case Scheduler_UserBlockingPriority:
      return UserBlockingPriority;
    case Scheduler_NormalPriority:
      return NormalPriority;
    case Scheduler_LowPriority:
      return LowPriority;
    case Scheduler_IdlePriority:
      return IdlePriority;
    default:
      invariant(false, 'Unknown priority level.');
  }
}

function reactPriorityToSchedulerPriority(reactPriorityLevel) {
  switch (reactPriorityLevel) {
    case ImmediatePriority:
      return Scheduler_ImmediatePriority;
    case UserBlockingPriority:
      return Scheduler_UserBlockingPriority;
    case NormalPriority:
      return Scheduler_NormalPriority;
    case LowPriority:
      return Scheduler_LowPriority;
    case IdlePriority:
      return Scheduler_IdlePriority;
    default:
      invariant(false, 'Unknown priority level.');
  }
}

export function runWithPriority<T>(
  reactPriorityLevel: ReactPriorityLevel,
  fn: () => T,
): T {
  const priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
  return Scheduler_runWithPriority(priorityLevel, fn);
}

export function scheduleCallback(
  reactPriorityLevel: ReactPriorityLevel,
  callback: SchedulerCallback,
  options: SchedulerCallbackOptions | void | null,
) {
  const priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
  return Scheduler_scheduleCallback(priorityLevel, callback, options);
}

export function scheduleSyncCallback(callback: SchedulerCallback) {
  // Push this callback into an internal queue. We'll flush these either in
  // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
  if (syncQueue === null) {
    syncQueue = [callback];
    // Flush the queue in the next tick, at the earliest.
    immediateQueueCallbackNode = Scheduler_scheduleCallback(
      Scheduler_ImmediatePriority,
      flushSyncCallbackQueueImpl,
    );
  } else {
    // Push onto existing queue. Don't need to schedule a callback because
    // we already scheduled one when we created the queue.
    syncQueue.push(callback);
  }
  return fakeCallbackNode;
}

export function cancelCallback(callbackNode: mixed) {
  if (callbackNode !== fakeCallbackNode) {
    Scheduler_cancelCallback(callbackNode);
  }
}

export function flushSyncCallbackQueue() {
  if (immediateQueueCallbackNode !== null) {
    const node = immediateQueueCallbackNode;
    immediateQueueCallbackNode = null;
    Scheduler_cancelCallback(node);
  }
  flushSyncCallbackQueueImpl();
}

function flushSyncCallbackQueueImpl() {
  if (!isFlushingSyncQueue && syncQueue !== null) {
    // Prevent re-entrancy.
    isFlushingSyncQueue = true;
    let i = 0;
    try {
      const isSync = true;
      const queue = syncQueue;
      runWithPriority(ImmediatePriority, () => {
        for (; i < queue.length; i++) {
          let callback = queue[i];
          do {
            callback = callback(isSync);
          } while (callback !== null);
        }
      });
      syncQueue = null;
    } catch (error) {
      // If something throws, leave the remaining callbacks on the queue.
      if (syncQueue !== null) {
        syncQueue = syncQueue.slice(i + 1);
      }
      // Resume flushing in the next tick
      Scheduler_scheduleCallback(
        Scheduler_ImmediatePriority,
        flushSyncCallbackQueue,
      );
      throw error;
    } finally {
      isFlushingSyncQueue = false;
    }
  }
}


text:
Reporter:

---

Dein Issue hier


text:
#include <aws/servicecatalog/model/ListPortfoliosForProductResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::ServiceCatalog::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

ListPortfoliosForProductResult::ListPortfoliosForProductResult()
{
}

ListPortfoliosForProductResult::ListPortfoliosForProductResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ListPortfoliosForProductResult& ListPortfoliosForProductResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  const JsonValue& jsonValue = result.GetPayload();
  if(jsonValue.ValueExists("PortfolioDetails"))
  {
    Array<JsonValue> portfolioDetailsJsonList = jsonValue.GetArray("PortfolioDetails");
    for(unsigned portfolioDetailsIndex = 0; portfolioDetailsIndex < portfolioDetailsJsonList.GetLength(); ++portfolioDetailsIndex)
    {
      m_portfolioDetails.push_back(portfolioDetailsJsonList[portfolioDetailsIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("NextPageToken"))
  {
    m_nextPageToken = jsonValue.GetString("NextPageToken");

  }

  return *this;
}


text:
#ifndef SKSL_VARDECLARATIONS
#define SKSL_VARDECLARATIONS

#include "SkSLExpression.h"
#include "SkSLProgramElement.h"
#include "SkSLStatement.h"
#include "SkSLVariable.h"

namespace SkSL {

/**
 * A single variable declaration within a var declaration statement. For instance, the statement
 * 'int x = 2, y[3];' is a VarDeclarations statement containing two individual VarDeclaration
 * instances.
 */
struct VarDeclaration : public Statement {
    VarDeclaration(const Variable* var,
                   std::vector<std::unique_ptr<Expression>> sizes,
                   std::unique_ptr<Expression> value)
    : INHERITED(var->fOffset, Statement::kVarDeclaration_Kind)
    , fVar(var)
    , fSizes(std::move(sizes))
    , fValue(std::move(value)) {}

    std::unique_ptr<Statement> clone() const override {
        std::vector<std::unique_ptr<Expression>> sizesClone;
        for (const auto& s : fSizes) {
            if (s) {
                sizesClone.push_back(s->clone());
            } else {
                sizesClone.push_back(nullptr);
            }
        }
        return std::unique_ptr<Statement>(new VarDeclaration(fVar, std::move(sizesClone),
                                                             fValue ? fValue->clone() : nullptr));
    }

    String description() const override {
        String result = fVar->fName;
        for (const auto& size : fSizes) {
            if (size) {
                result += "[" + size->description() + "]";
            } else {
                result += "[]";
            }
        }
        if (fValue) {
            result += " = " + fValue->description();
        }
        return result;
    }

    const Variable* fVar;
    std::vector<std::unique_ptr<Expression>> fSizes;
    std::unique_ptr<Expression> fValue;

    typedef Statement INHERITED;
};

/**
 * A variable declaration statement, which may consist of one or more individual variables.
 */
struct VarDeclarations : public ProgramElement {
    VarDeclarations(int offset, const Type* baseType,
                    std::vector<std::unique_ptr<VarDeclaration>> vars)
    : INHERITED(offset, kVar_Kind)
    , fBaseType(*baseType) {
        for (auto& var : vars) {
            fVars.push_back(std::unique_ptr<Statement>(var.release()));
        }
    }

    std::unique_ptr<ProgramElement> clone() const override {
        std::vector<std::unique_ptr<VarDeclaration>> cloned;
        for (const auto& v : fVars) {
            cloned.push_back(std::unique_ptr<VarDeclaration>(
                                                           (VarDeclaration*) v->clone().release()));
        }
        return std::unique_ptr<ProgramElement>(new VarDeclarations(fOffset, &fBaseType,
                                                                     std::move(cloned)));
    }

    String description() const override {
        if (!fVars.size()) {
            return String();
        }
        String result = ((VarDeclaration&) *fVars[0]).fVar->fModifiers.description() +
                fBaseType.description() + " ";
        String separator;
        for (const auto& var : fVars) {
            result += separator;
            separator = ", ";
            result += var->description();
        }
        return result;
    }

    const Type& fBaseType;
    // this *should* be a vector of unique_ptr<VarDeclaration>, but it significantly simplifies the
    // CFG to only have to worry about unique_ptr<Statement>
    std::vector<std::unique_ptr<Statement>> fVars;

    typedef ProgramElement INHERITED;
};

} // namespace

#endif


text:
% Script generated by Brainstorm (29-Sep-2017)
%% THE AIM of this script is to back import in raw files the bad trials (as determined in trial phase)
% this is done to import later the epochs time-locked to the second
% stimulus. I'm not performing a complete stript as this is just an
% adjustment for a single subject (the trial rejection was not performed in the analysis,
% probably forgotten (and I notice it).

sFiles = {...
    'sj0007/@rawsj0007_scale_bandpass/data_0raw_sj0007_scale_bandpass.mat'};

RawFiles = {...
    '/Users/giorgioarcara/Documents/MATLAB/p_s_qualche_inc_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_s_qualche_con_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_s_alcuni_inc_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_s_alcuni_con_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_s_un_inc_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_s_un_con_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_m_alcuni_sg_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_m_alcuni_pl_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_m_qualche_sg_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_m_qualche_pl_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_m_un_sg_BadTrials.mat', ...
    '/Users/giorgioarcara/Documents/MATLAB/p_m_un_pl_BadTrials.mat'};

% Start a new report
bst_report('Start', RawFiles);

for iRaw=1:length(RawFiles);

    % Process: Import from file
    sFiles = bst_process('CallProcess', 'process_evt_import', sFiles, [], ...
        'evtfile', {RawFiles{iRaw}, 'ARRAY-TIMES'}, ...
        'evtname', 'BAD_trial');
end

% Save and display report
ReportFile = bst_report('Save', sFiles);
bst_report('Open', ReportFile);
% bst_report('Export', ReportFile, ExportDir);


text:
import React from 'react';
import {IconButton, Popover, Typography} from "@material-ui/core";
import WarningIcon from '@material-ui/icons/Warning';
import CloseIcon from '@material-ui/icons/Close';
import {mount} from "enzyme";
import {act} from "react-dom/test-utils";
import {UnavailableFilterPopup} from "../../components/DataPackPage/UnavailableFilterPopup";

jest.mock('../../styles/eventkit_theme.js', () => 'colors');

describe('UnavailableFilterPopup component', () => {
    const getProps = () => ({
        classes: {},
        theme: {},
        ...(global as any).eventkit_test_props,
    });

    let wrapper;
    let instance;
    const setup = (propsOverride = {}) => {
        const props = {
            ...getProps(),
            ...propsOverride,
        };
        wrapper = mount(<UnavailableFilterPopup {...props} />);
        instance = wrapper.instance();
    };

    beforeEach(setup);

    it('should render the initial collapsed elements', () => {
        expect(wrapper.find(IconButton)).toHaveLength(1);
        expect(wrapper.find(WarningIcon)).toHaveLength(1);
        expect(wrapper.find(Popover)).toHaveLength(1);
        expect(wrapper.find(CloseIcon)).toHaveLength(0);
    });
    it('handlePopoverOpen should open the popover', () => {
        expect(wrapper.find(Popover).props().open).toBe(false);
        expect(wrapper.find(IconButton).at(0).exists()).toBe(true);

        act(() => {
            wrapper
                .find(IconButton)
                .first()
                .simulate("click");
        });
        wrapper.update();
        console.log(wrapper.debug());
        expect(wrapper.find(Popover).props().open).toBe(true);
    });
    it('handleCloseExpand should close the popover', () => {
        expect(wrapper.find(IconButton).at(1).exists()).toBe(false);
        act(() => {
            wrapper
                .find(IconButton)
                .first()
                .simulate("click");
        });
        wrapper.update();
        expect(wrapper.find(IconButton).at(1).exists()).toBe(true);

        act(() => {
            wrapper
                .find(IconButton)
                .at(1)
                .simulate("click");
        });
        wrapper.update();
        expect(wrapper.find(Popover).props().open).toBe(false);
    });
});


text:
package logger

import (
	"fmt"
	"io"

	slack "github.com/monochromegane/slack-incoming-webhooks"
)

type Logger struct {
	Cluster         string
	ServiceName     string
	Out             io.Writer
	SlackWebhookUrl string
}

func NewLogger(cluster, serviceName, slackWebhookUrl string, out io.Writer) *Logger {
	return &Logger{
		Cluster:         cluster,
		ServiceName:     serviceName,
		SlackWebhookUrl: slackWebhookUrl,
		Out:             out,
	}
}

func (l *Logger) Log(message string) {
	if l.Out != nil {
		fmt.Fprintf(l.Out, message)
	}
}

func (l *Logger) Slack(messageType string, message string) {
	if l.SlackWebhookUrl == "" {
		return
	}

	switch messageType {
	case "normal":
		client := &slack.Client{WebhookURL: l.SlackWebhookUrl}
		payload := &slack.Payload{
			Username: "deploy-bot",
			Text:     fmt.Sprintf("cluster: %s, serviceName: %s\n%s", l.Cluster, l.ServiceName, message),
		}
		client.Post(payload)
	case "good":
	case "danger":
		client := &slack.Client{WebhookURL: l.SlackWebhookUrl}
		attachment := &slack.Attachment{
			Color: messageType,
			Text:  fmt.Sprintf("cluster: %s, serviceName: %s\n%s", l.Cluster, l.ServiceName, message),
		}
		payload := &slack.Payload{
			Username:    "deploy-bot",
			Attachments: []*slack.Attachment{attachment},
		}
		client.Post(payload)
	}
}


text:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if (p == NULL && q == NULL)
        return true;
    if (p == NULL && q != NULL || p != NULL && q == NULL)
        return false;
    if (p->val != q->val)
        return false;
    return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}


text:
import Ember from 'ember';
import DS from 'ember-data';
import SessionService from 'ember-simple-auth/services/session';

export default SessionService.extend({
  store: Ember.inject.service(),
  user_id: function() {
    return this.get('session.content.authenticated.userId');
  }.property('isAuthenticated'),
  account: function() {
    var userId = this.get('session.content.authenticated.userId');

    if (userId && this.get('isAuthenticated')) {
      var user = true;

      return DS.PromiseObject.create({
               promise: this.get('store').find('user', userId)
             });
    }
  }.property('isAuthenticated')
});


text:
module Fontina::Formats::OpenType

  class OT_TableDirectoryEntry < BinData::Record
    endian :big
    search_prefix :ot
    hide :checksum

    string :tag, length: 4
    uint32 :checksum
    uint32 :addr
    uint32 :len

    delayed_io :table, read_abs_offset: :addr do
      buffer type: :table, length: :len
    end
  end

  class OT_TableDirectory < BinData::Array
    search_prefix :ot

    default_parameter initial_length: -> { offset_table.table_count }

    table_directory_entry
  end

end


text:
// CkTarProgress.h: interface for the CkTarProgress class.
//
//////////////////////////////////////////////////////////////////////

#ifndef _CKTARPROGRESSW_H
#define _CKTARPROGRESSW_H

#include "CkBaseProgressW.h"

#include "ck_inttypes.h"

// When creating an application class that inherits the CkTarProgressW base class, use the CK_TARPROGRESSW_API
// definition to declare the overrides in the class header.  This has the effect that if for
// some unforeseen and unlikely reason the Chilkat event callback API changes, or if new
// callback methods are added in a future version, then you'll discover them at compile time
// after updating to the new Chilkat version.
// For example:
/*
    class MyProgress : public CkTarProgressW
    {
	public:
	    CK_TARPROGRESSW_API

	...
    };
*/
#define CK_TARPROGRESSW_API \
	void NextTarFile(const wchar_t *path, __int64 fileSize,bool bIsDirectory, bool *skip);

#ifndef __sun__
#pragma pack (push, 8)
#endif

class CkTarProgressW : public CkBaseProgressW
{
    public:
	CkTarProgressW() { }
	virtual ~CkTarProgressW() { }

	// These event callbacks are now defined in CkBaseProgressW.
	//virtual void PercentDone(int pctDone, bool *abort) { }
	//virtual void AbortCheck(bool *abort) { }
	//virtual void ProgressInfo(const wchar_t *name, const wchar_t *value) { }

	// Called just before appending to TAR when writing a .tar, and just before
	// extracting during untar.
	virtual void NextTarFile(const wchar_t *path,
	    __int64 fileSize,
	    bool bIsDirectory,
	    bool *skip) { }

};
#ifndef __sun__
#pragma pack (pop)
#endif

#endif


text:
set -e

etckeeper_commit (){
  if dpkg-query -W etckeeper 1>/dev/null 2>/dev/null; then
    if etckeeper unclean; then
      etckeeper commit "$1" 1>/dev/null 2>/dev/null
    fi
  fi
}

REPO_HOST=repo.stackdriver.com
APP_HOST=app.stackdriver.com

##
## add apt-line, GPG key, and apt-get update
##
debian_release=`cat /etc/debian_version`
case ${debian_release} in
  8.*|stretch/sid)
    curl -s -S -f -o /etc/apt/sources.list.d/stackdriver.list "https://${REPO_HOST}/jessie.list"
    ;;
  7.*)
    curl -s -S -f -o /etc/apt/sources.list.d/stackdriver.list "https://${REPO_HOST}/wheezy.list"
    ;;
esac
curl -s -f https://${APP_HOST}/RPM-GPG-KEY-stackdriver | apt-key add -
etckeeper_commit "apt: add google-fluentd repository and GPG key"
apt-get -qq update

##
## do not auto-start google-fluentd
##
tmp_policy_script=`mktemp`
cat <<SCRIPT > $tmp_policy_script
#!/bin/sh

# This script prevents starting daemons during installation of package.
# see https://people.debian.org/~hmh/invokerc.d-policyrc.d-specification.txt

exit 101
SCRIPT
install -m 755 -o root -g root -p $tmp_policy_script /usr/sbin/policy-rc.d
rm $tmp_policy_script

##
## install packages
##
apt-get install --no-install-recommends -y google-fluentd google-fluentd-catch-all-config

rm /usr/sbin/policy-rc.d

##
## configure
##
tmp_conf=`mktemp`
cat <<CONF > $tmp_conf
# Master configuration file for google-fluentd

# Include any configuration files in the config.d directory.
#
# An example "catch-all" configuration can be found at
# https://github.com/GoogleCloudPlatform/fluentd-catch-all-config
@include config.d/*.conf

# Do not collect fluentd's own logs to avoid infinite loops.
<match fluent.**>
  type null
</match>

# Configure all sources to output to Google Cloud Logging
<match **>
  type google_cloud
  # Set the chunk limit conservatively to avoid exceeding the limit
  # of 2MB per write request.
  buffer_chunk_limit 512K
  flush_interval 5s
  # Never wait longer than 5 minutes between retries.
  max_retry_wait 300
  # Disable the limit on the number of retries (retry forever).
  disable_retry_limit

  # Uncomment the following lines to use service account authentication for
  # the logging agent.
  # See the documentation at https://cloud.google.com/logging/docs
  #
  # After obtaining and installing your private key file, uncomment the
  # following lines and set 'private_key_email' to the service account address.
  #
  # auth_method xxx
  # private_key_email xxx
  # private_key_path xxx
  # private_key_passphrase xxx
  # use_metadata_service xxx
  # project_id xxx
  # zone xxx
  # vm_id xxx
</match>
CONF

set_param (){
  local param=$1
  local var=$2
  if [ -n "${var}" ]; then
     sed -i -e "s!# ${param} xxx!${param} ${var}!" ${tmp_conf}
  fi
}

if [ -n "${GOOGLE_FLUENTD_PRIVATE_KEY_CONTENT_BASE64}" ]; then
  t1=`mktemp`
  t2=`mktemp`
  echo "${GOOGLE_FLUENTD_PRIVATE_KEY_CONTENT_BASE64}" > ${t1}
  base64 -d ${t1} > ${t2}
  if [ -z "${GOOGLE_FLUENTD_PRIVATE_KEY_PATH}" ]; then
    GOOGLE_FLUENTD_PRIVATE_KEY_PATH=/etc/google-fluentd/${GOOGLE_FLUENTD_PROJECT_ID:-default}.p12
  fi
  install -m 600 -o root -g  root -p ${t2} ${GOOGLE_FLUENTD_PRIVATE_KEY_PATH}
  rm ${t1} ${t2}
fi

if [ "${GOOGLE_FLUENTD_USE_METADATA_SERVICE}" = false ]; then
  if [ -z "${GOOGLE_FLUENTD_VM_ID}" ]; then
    GOOGLE_FLUENTD_VM_ID=`hostname`
  fi
fi

set_param auth_method             ${GOOGLE_FLUENTD_AUTH_METHOD}
set_param private_key_email       ${GOOGLE_FLUENTD_PRIVATE_KEY_EMAIL}
set_param private_key_path        ${GOOGLE_FLUENTD_PRIVATE_KEY_PATH}
set_param private_key_passphrase  ${GOOGLE_FLUENTD_PRIVATE_KEY_PASSPHRASE}

if [ "${GOOGLE_FLUENTD_USE_METADATA_SERVICE}" = false ]; then
  set_param use_metadata_service    ${GOOGLE_FLUENTD_USE_METADATA_SERVICE}
  set_param project_id              ${GOOGLE_FLUENTD_PROJECT_ID}
  set_param zone                    ${GOOGLE_FLUENTD_ZONE}
  set_param vm_id                   ${GOOGLE_FLUENTD_VM_ID}
fi

install -m 644 -o root -g root -p ${tmp_conf} /etc/google-fluentd/google-fluentd.conf
etckeeper_commit "configured google-fluentd.conf with env vars"
rm ${tmp_conf}

## restart google-fluentd
service google-fluentd restart


text:
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdio.h>

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/core/framework/api_def.pb.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/framework/op_gen_lib.h"
#include "google/protobuf/unknown_field_set.h"

namespace tensorflow {
namespace java {

const char kUsageHeader[] =
    "\n\nExporter of operation and API defs, for use in Java op generation.\n\n"
    "This executable exports the op def and api def protos for all operations "
    "registered in the provided list of libraries. The proto will be printed "
    "to stdout in binary format. It is an OpList proto, with each OpDef having"
    " the associated ApiDef attached as unknown field 100\n\n"
    "The first argument is the location of the tensorflow binary built for TF-"
    "Java.\nFor example, `bazel-out/k8-opt/bin/external/org_tensorflow/tensorfl"
    "ow/libtensorflow_cc.so`.\n\n"
    "The second and third arguments are the binary and text output files, respectively.\n"
    "The text output file will not include ApiDefs, like tensorflow's ops.pbtxt.\n\n"
    "Finally, the rest of the arguments are used as "
    "directories of API definitions can be provided to override default\n"
    "values found in the ops definitions. Directories are ordered by priority "
    "(the last having precedence over the first).\nFor example, `bazel-tensorf"
    "low-core-api/external/org_tensorflow/tensorflow/core/api_def/base_api,src"
    "/bazel/api_def`\n\n";

void Write(OpDef* op_def, const ApiDef& api_def){
  auto *refl = op_def->GetReflection();
  refl->MutableUnknownFields(op_def)->AddLengthDelimited(100, api_def.SerializeAsString());
}

Status UpdateOpDefs(OpList* op_list, const std::vector<tensorflow::string>& api_dirs_, Env* env_) {
  ApiDefMap api_map(*op_list);
  if (!api_dirs_.empty()) {
    // Only load api files that correspond to the requested "op_list"
    for (const auto& op : op_list->op()) {
      for (const auto& api_def_dir : api_dirs_) {
        const std::string api_def_file_pattern =
            io::JoinPath(api_def_dir, "api_def_" + op.name() + ".pbtxt");
        if (env_->FileExists(api_def_file_pattern).ok()) {
          TF_CHECK_OK(api_map.LoadFile(env_, api_def_file_pattern))
              << api_def_file_pattern;
        }
      }
    }
  }
  api_map.UpdateDocs();

  for (int i = 0 ; i < op_list->op_size() ; i++) {
    OpDef *op_def = op_list->mutable_op(i);
    const ApiDef* api_def = api_map.GetApiDef(op_def->name());
  	Write(op_def, *api_def);
  }
  return Status::OK();
}

}
}

// See usage header.
// Writes an OpList proto to stdout, with each OpDef having its ApiDef in field 100
int main(int argc, char* argv[]) {
  tensorflow::port::InitMain(tensorflow::java::kUsageHeader, &argc, &argv);
  std::vector<tensorflow::string> api_dirs;

  if(argc < 4) {
      std::cerr << "Must specify <library_path> <binary_output> <text_output>" << "\n";
      std::cerr << tensorflow::java::kUsageHeader;
      return 1;
  }

  for(int i = 4 ; i < argc ; i++){
    api_dirs.push_back(argv[i]);
  }

  std::ofstream binary_output (argv[2], std::ios::out | std::ios::trunc | std::ios::binary);
  std::ofstream text_output  (argv[3], std::ios::out | std::ios::trunc);

  if(!binary_output.is_open()){
    std::cerr << "Error opening file " << argv[2] << "\n";
    return 1;
  }

  if(!text_output.is_open()){
    std::cerr << "Error opening file " << argv[3] << "\n";
    return 1;
  }

  tensorflow::Env* env = tensorflow::Env::Default();
  void* ops_libs_handles[1];
  TF_CHECK_OK(env->LoadDynamicLibrary(argv[1], &ops_libs_handles[0]));
  tensorflow::OpList ops;
  tensorflow::OpRegistry::Global()->Export(false, &ops);

  text_output << ops.DebugString();
  text_output.close();

  TF_CHECK_OK(tensorflow::java::UpdateOpDefs(&ops, api_dirs, env));

  ops.SerializeToOstream(&binary_output);
  binary_output.close();

  return 0;
}


text:
package org.stagemonitor.core.metrics.metrics2;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import org.stagemonitor.core.util.GraphiteSanitizer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Represents a metrics 2.0 name that consists of a name and arbitrary tags (a set of key-value-pairs).
 *

 * To create a new {@link MetricName}, use the static {@link MetricName}.{@link #name(String)} method. Example:
 * name("api_request_duration").tag("stage", "transform").build()
 *

 * This is needed for example for InfluxDB's data model (see https://influxdb.com/docs/v0.9/concepts/schema_and_data_layout.html)
 * and to store metrics into Elasticsearch (see https://www.elastic.co/blog/elasticsearch-as-a-time-series-data-store).
 * See also http://metrics20.org/
 *

 * The cool thing is that it is completely backwards compatible to graphite metric names and can also automatically
 * replace characters disallowed in graphite (see {@link #toGraphiteName()}).
 *

 * This class is immutable
 */
public class MetricName {

	@JsonIgnore
	private int hashCode;

	private final String name;

	// The insertion order is important for the correctness of #toGraphiteName
	private final LinkedHashMap<String, String> tags;

	private MetricName(String name, LinkedHashMap<String, String> tags) {
		this.name = name;
		this.tags = tags;
	}

	@JsonCreator
	private MetricName(@JsonProperty("name") String name, @JsonProperty("tags") Map<String, String> tags) {
		this.name = name;
		this.tags = new LinkedHashMap<String, String>(tags);
	}

	/**
	 * Returns a copy of this name and appends a single tag
	 *

	 * Note that this method does not override existing tags
	 *
	 * @param key   the key of the tag
	 * @param value the value of the tag
	 * @return a copy of this name including the provided tag
	 */
	public MetricName withTag(String key, String value) {
		return name(name).tags(tags).tag(key, value).build();
	}

	/**
	 * Constructs a new {@link Builder} with the provided name.
	 *

	 * After adding tags with {@link Builder#tag(String, String)}, call {@link Builder#build()} to get the
	 * immutable {@link MetricName}
	 *

	 * The metric name should only contain alphanumerical chars and underscores.
	 *

	 * When in doubt how to name a metic, take a look at https://prometheus.io/docs/practices/naming/
	 *
	 * @param name the metric name
	 * @return a {@link Builder} with the provided name
	 */
	public static Builder name(String name) {
		return new Builder(name);
	}

	public String getName() {
		return name;
	}

	public Map<String, String> getTags() {
		return Collections.unmodifiableMap(tags);
	}

	@JsonIgnore
	public List<String> getTagKeys() {
		return new ArrayList<String>(tags.keySet());
	}

	@JsonIgnore
	public List<String> getTagValues() {
		return new ArrayList<String>(tags.values());
	}

	/**
	 * Converts a metrics 2.0 name into a graphite compliant name by appending all tag values to the metric name
	 *
	 * @return A graphite compliant name
	 */
	public String toGraphiteName() {
		StringBuilder sb = new StringBuilder(GraphiteSanitizer.sanitizeGraphiteMetricSegment(name));
		for (String value : tags.values()) {
			sb.append('.').append(GraphiteSanitizer.sanitizeGraphiteMetricSegment(value));
		}
		return sb.toString();
	}

	/**
	 * A {@link MetricName} is only considered equal to another {@link MetricName} if the tags are in the same order.
	 */
	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		MetricName that = (MetricName) o;

		return name.equals(that.name) && tags.equals(that.tags);
	}

	@Override
	public int hashCode() {
		int result = hashCode;
		if (result == 0) {
			result = name.hashCode();
			result = 31 * result + tags.hashCode();
			hashCode = result;
		}
		return result;
	}

	public boolean matches(MetricName other) {
		return name.equals(other.name) && containsAllTags(other.tags);
	}

	private boolean containsAllTags(Map<String, String> tags) {
		for (Map.Entry<String, String> entry : tags.entrySet()) {
			if (!entry.getValue().equals(this.tags.get(entry.getKey()))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * A {@link MetricNameTemplate} lets you efficiently create similar {@link MetricName}s so that if a {@link
	 * MetricName} has already been {@link #build(String)} for the same value(s), the previous instance is reused.
	 *

	 * In other words, this is a cache for {@link MetricName}s
	 *

	 * Example:
	 *

	 *     MetricName.MetricNameTemplate timerMetricNameTemplate = name("response_time")
	 *             .operationName("")
	 *             .layer("All")
	 *             .templateFor("operation_name");
	 *     MetricName metricName = timerMetricNameTemplate.build("Search Products");
	 *

	 */
	public static class MetricNameTemplate {
		private final ConcurrentMap<Object, MetricName> metricNameCache = new ConcurrentHashMap<Object, MetricName>();
		private final MetricName template;
		private final String key;
		private final List<String> keys;

		private MetricNameTemplate(MetricName template, String key) {
			this.template = template;
			this.key = key;
			this.keys = null;
		}

		private MetricNameTemplate(MetricName template, String... keys) {
			this.template = template;
			this.key = null;
			this.keys = Arrays.asList(keys);
		}

		/**
		 * Creates a new or reused {@link MetricName} according to the {@link #template} with the given {@link #key}
		 * and the provided value
		 *
		 * @param value The tag value
		 * @return A {@link MetricName} according to the {@link #template}
		 * @throws IllegalArgumentException When this template is intended for multiple values i.e. was initialized via
		 *                                  {@link MetricNameTemplate#MetricNameTemplate(MetricName, String...)}
		 */
		public MetricName build(String value) {
			if (key == null) {
				throw new IllegalArgumentException("Size of key does not match size of values");
			}
			MetricName metricName = metricNameCache.get(value);
			if (metricName == null) {
				metricName = template.withTag(key, value);
				metricNameCache.put(value, metricName);
			}
			return metricName;
		}

		/**
		 * Creates a new or reused {@link MetricName} according to the {@link #template} with the given {@link #keys}
		 * and the provided values
		 *
		 * @param values The tag values (must match the size of {@link #keys}
		 * @return A {@link MetricName} according to the {@link #template}
		 * @throws IllegalArgumentException When number of {@link #keys} does not match the number of provided values or
		 *                                  this template is intended for a single value i.e. was initialized via {@link
		 *                                  MetricNameTemplate#MetricNameTemplate(MetricName, String)}
		 */
		public MetricName build(String... values) {
			if (keys == null || keys.size() != values.length) {
				throw new IllegalArgumentException("Size of key does not match size of values");
			}
			List<String> valuesList = Arrays.asList(values);
			MetricName metricName = metricNameCache.get(valuesList);
			if (metricName == null) {
				Builder builder = name(template.name).tags(template.tags);
				for (int i = 0; i < keys.size(); i++) {
					builder.tag(keys.get(i), valuesList.get(i));
				}
				metricName = builder.build();
				metricNameCache.put(valuesList, metricName);
			}
			return metricName;
		}
	}

	public static class Builder {

		private final String name;

		private final LinkedHashMap<String, String> tags = new LinkedHashMap<String, String>(8);

		public Builder(String name) {
			this.name = name;
		}

		/**
		 * Adds a tag to the metric name.
		 *
		 * @param key   The key should only contain alphanumerical chars and underscores.
		 * @param value The value can contain unicode characters, but it is recommended to not use white spaces.
		 * @return this for chaining
		 */
		public Builder tag(String key, String value) {
			this.tags.put(key, value);
			return this;
		}

		public Builder type(String value) {
			return tag("type", value);
		}

		public Builder operationType(String value) {
			return tag("operation_type", value);
		}

		public Builder operationName(String value) {
			return tag("operation_name", value);
		}

		public Builder tier(String value) {
			return tag("tier", value);
		}

		public Builder layer(String value) {
			return tag("layer", value);
		}

		public Builder unit(String value) {
			return tag("unit", value);
		}

		public Builder tags(Map<String, String> tags) {
			this.tags.putAll(tags);
			return this;
		}

		public MetricName build() {
			return new MetricName(name, tags);
		}

		/**
		 * Creates a {@link MetricNameTemplate} with a single tag
		 *
		 * @param key The template tag key
		 * @return The {@link MetricNameTemplate}
		 */
		public MetricNameTemplate templateFor(String key) {
			return new MetricNameTemplate(build(), key);
		}

		/**
		 * Creates a {@link MetricNameTemplate} with multiple tags
		 *
		 * @param keys The template tag keys
		 * @return The {@link MetricNameTemplate}
		 */
		public MetricNameTemplate templateFor(String... keys) {
			return new MetricNameTemplate(build(), keys);
		}

	}

	@Override
	public String toString() {
		return "name='" + name + '\'' + ", tags=" + getTags();
	}

}


text:
<title>html5 backend: boxes</title>

Node types:

Black: leaf

Red: horizontal box

Green: vertical box

Magenta: list

Output:

<canvas id="canvas"/>

<contents id="contents">
<Top>
  <VBox refname="child">
    <HBox refname="childs">
        <Leaf refname="childs"></Leaf>
        <HBox refname="childs">
          <Leaf refname="childs"></Leaf>
          <Leaf refname="childs"></Leaf>
        </HBox>
        <Leaf refname="childs"></Leaf>
        <HBox refname="childs"></HBox>
        <VBox refname="childs">
          <Leaf refname="childs"></Leaf>
          <Leaf refname="childs"></Leaf>
          <Leaf refname="childs"></Leaf>
          <Leaf refname="childs"></Leaf>
          <Leaf refname="childs"></Leaf>
          <Leaf refname="childs"></Leaf>
          <Leaf refname="childs"></Leaf>
          <Leaf refname="childs"></Leaf>
          <HBox refname="childs">
            <Leaf refname="childs"></Leaf>
            <Leaf refname="childs"></Leaf>
          </HBox>
        </VBox>
    </HBox>
    <HBox refname="childs">
        <Leaf refname="childs"></Leaf>
        <HBox refname="childs"></HBox>
        <VBox refname="childs"></VBox>
    </HBox>
    <HBox refname="childs">
        <Leaf refname="childs"></Leaf>
        <HBox refname="childs"></HBox>
        <VBox refname="childs"></VBox>
    </HBox>
    <HBox refname="childs">
        <Leaf refname="childs"></Leaf>
        <HBox refname="childs"></HBox>
        <VBox refname="childs"></VBox>
    </HBox>
    <HBox refname="childs">some text
    </HBox>

  </VBox>
</Top>
</contents>


text:
'use strict';

const fs = require('fs');

const globby = require('globby');

const loaders = require('./loaders');

const formatPathsArrayToIgnore = require('./utils').formatPathsArrayToIgnore;
const setConfigDefaults = require('./utils').setConfigDefaults;

const DEFAULT_IGNORE_PATHS = [
    '!./{node_modules,bower_components,test,tests}/**',
    '!./Gruntfile.js',
    '!./Gulpfile.js'
];

const REPLACE_FILENAME_REGEXP = new RegExp(`^(${process.cwd()}/|./)`, 'u');

/**
 * Parse a file with custom parser.
 *
 *     parseFile('src/main.js', {'parser': 'dox'}).then(files => {});
 *
 * @param {String} input File to parse.
 * @param {Object} config Configuration object.
 * @param {String} config.parser String representing the parser to be used.
 * @return {Object} Promise
 * @public
 */

const parseFile = (input, config) =>
    loaders.loadParser(setConfigDefaults(config)).then(parser =>
        new Promise((resolve, reject) => {

            fs.readFile(input, 'utf8', (err, data) => {

                if (err) {

                    return reject(err);

                }

                const filename = input.replace(REPLACE_FILENAME_REGEXP, '');

                return resolve({
                    'methods': parser(data, filename),
                    'name': filename
                });

            });

        }));

/**
 * Parse array of files, and then render the parsed data through the defined layout plugin.
 *
 *     parseFiles(['src/main.js'], {'ignore': [], 'parser': 'dox', 'layout': 'markdown'}).then(content => {});
 *
 * @param {Array} inputs Array of directory globs and/or files.
 * @param {Object} config Configuration object.
 * @param {String} config.ignore Array of paths to ignore.
 * @param {String} config.parser String representing the parser to be used.
 * @param {String} config.layout String representing the layout plugin to be used.
 * @return {Object} Promise
 * @public
 */

const parseFiles = (files, config) =>
    loaders.loadPlugin(setConfigDefaults(config)).then(plugin =>
        Promise.all(files.map(input => parseFile(input, config))).then(files =>
            plugin({
                'files': files.filter(file => file.methods.length),
                ...setConfigDefaults(config)
            })));

/**
 * Parse array of directory globs and/or files, and then render the parsed data through the defined layout plugin.
 *
 *     parseInputs(['src/*.js'], {'ignore': [], 'parser': 'dox', 'layout': 'markdown'}).then(content => {});
 *
 * @param {Array} inputs Array of directory globs and/or files.
 * @param {Object} config Configuration object.
 * @param {String} config.ignore Array of paths to ignore.
 * @param {String} config.parser String representing the parser to be used.
 * @param {String} config.layout String representing the layout plugin to be used.
 * @return {Object} Promise
 * @public
 */

const parseInputs = (inputs, config) =>
    globby(inputs.concat(
        DEFAULT_IGNORE_PATHS,
        formatPathsArrayToIgnore(setConfigDefaults(config).ignore)
    )).then(files => parseFiles(files, config));

module.exports = {
    parseFile,
    parseFiles,
    parseInputs
};


text:
<?php namespace estvoyage\risingsun\comparison\binary;

use estvoyage\risingsun\comparison;

class identical
	implements
		comparison\binary
{
	function recipientOfComparisonBetweenOperandAndReferenceIs($operand, $reference, comparison\recipient $recipient)
	{
		$recipient->nbooleanIs($operand === $reference);
	}
}


text:
class RobotOp;

class GLWidgetMaster : public QGLWidget
{
    Q_OBJECT

public:
    GLWidgetMaster(QWidget *parent = 0);
    ~GLWidgetMaster();

    RobotOp *robotop;

    int xRotationMaster() const { return xRot; }
    int yRotationMaster() const { return yRot; }
    int zRotationMaster() const { return zRot; }

public slots:
    void setXRotationMaster(int angle);
    void setYRotationMaster(int angle);
    void setZRotationMaster(int angle);

signals:
    void xRotationChangedMaster(int angle);
    void yRotationChangedMaster(int angle);
    void zRotationChangedMaster(int angle);

protected:
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);

private:
    void normalizeAngleMaster(int *angle);

    int xRot;
    int yRot;
    int zRot;

    QPoint lastPos;

};

#endif // GLWIDGETMASTER_H


text:
<?php

namespace Opteck\Tests;

use Opteck\Exception;
use Opteck\Exceptions\EmailAlreadyExistsException;
use Opteck\Payload;
use Opteck\Requests\CreateLead as CreateLeadRequest;
use Opteck\Responses\CreateLead as CreateLeadResponse;

class CreateLeadTest extends TestCase
{
    public function testForbiddenCountries()
    {
        $countries = $this->apiClient->getForbiddenCountries();
        $this->assertNotEmpty($countries);
    }

    public function testSuccessfulResponse()
    {
        $json = <<<'JSON'
{"returnCode":1,"description":"Successful call","timestampGenerated":"2016-04-22T15:54:56+03:00","data":{"leadID":"160422888612","dateRegistered":"2016-04-22T15:54:55+03:00","campaign":"test_campaign","subcampaign":"test_sub_campaign","status":"New","languageCode":"EN","countryCode":"GB","currencyCode":"GBP"}}
JSON;
        $response = new CreateLeadResponse(new Payload($json));
        $this->assertTrue($response->isSuccess());
        $this->assertEquals(160422888612, $response->getLeadId());
    }

    public function testWrongRequest()
    {
        $json = <<<'JSON'
{"returnCode":3,"description":"Field not valid","invalidFields":["email"],"timestampGenerated":"2016-04-22T16:16:28+03:00"}
JSON;

        try {
            new CreateLeadResponse(new Payload($json));
        } catch (Exception $e) {
            $response = $e->getResponse();
            $this->assertFalse($response->isSuccess());
            $this->assertNotEmpty($response->getInvalidFields());
        }
    }

    public function testEmailAlreadyExists()
    {
        /** @var \Opteck\Requests\CreateLead $request */
        $request = new CreateLeadRequest([
            'email'       => 'test@gmail.com',
            'firstName'   => 'John',
            'lastName'    => 'Smith',
            'language'    => 'EN',
            'country'     => 'GB',
            'phone'       => '442088963321', // Pizza Hut Restaurant
            'campaign'    => 'campaign_test_1',
            'subCampaign' => 'sub_campaign_1',
        ]);

        /* @var \Opteck\Responses\CreateLead $response */
        try {
            $this->apiClient->createLead($request);
            $this->assertTrue(false, 'Lead with email "test@gmail.com" must not be created...');
        } catch (EmailAlreadyExistsException $e) {
            $this->assertTrue(true, 'Email already exists error handled perfectly.');
        }
    }
}


text:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

#ifndef PX_PHYSICS_GEOMUTILS_PX_TRIANGLE
#define PX_PHYSICS_GEOMUTILS_PX_TRIANGLE
/** \addtogroup geomutils
  @{
*/

#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVec3.h"

#if !PX_DOXYGEN
namespace physx
{
#endif

/**
\brief Triangle class.
*/
class PxTriangle
{
	public:
	/**
	\brief Constructor
	*/
	PX_FORCE_INLINE			PxTriangle() {}

	/**
	\brief Constructor

	\param[in] p0 Point 0
	\param[in] p1 Point 1
	\param[in] p2 Point 2
	*/
	PX_FORCE_INLINE			PxTriangle(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2)
	{
		verts[0] = p0;
		verts[1] = p1;
		verts[2] = p2;
	}

	/**
	\brief Copy constructor

	\param[in] triangle Tri to copy
	*/
	PX_FORCE_INLINE			PxTriangle(const PxTriangle& triangle)
	{
		verts[0] = triangle.verts[0];
		verts[1] = triangle.verts[1];
		verts[2] = triangle.verts[2];
	}

	/**
	\brief Destructor
	*/
	PX_FORCE_INLINE			~PxTriangle() {}

	/**
	\brief Assignment operator
	*/
	PX_FORCE_INLINE void operator=(const PxTriangle& triangle)
	{
		verts[0] = triangle.verts[0];
		verts[1] = triangle.verts[1];
		verts[2] = triangle.verts[2];
	}

	/**
	\brief Compute the normal of the Triangle.

	\param[out] _normal Triangle normal.
	*/
	PX_FORCE_INLINE	void	normal(PxVec3& _normal) const
	{
		_normal = (verts[1]-verts[0]).cross(verts[2]-verts[0]);
		_normal.normalize();
	}

	/**
	\brief Compute the unnormalized normal of the triangle.

	\param[out] _normal Triangle normal (not normalized).
	*/
	PX_FORCE_INLINE	void	denormalizedNormal(PxVec3& _normal) const
	{
		_normal = (verts[1]-verts[0]).cross(verts[2]-verts[0]);
	}

	/**
	\brief Compute the area of the triangle.

	\return Area of the triangle.
	*/
	PX_FORCE_INLINE	PxReal	area() const
	{
		const PxVec3& p0 = verts[0];
		const PxVec3& p1 = verts[1];
		const PxVec3& p2 = verts[2];
		return ((p0 - p1).cross(p0 - p2)).magnitude() * 0.5f;
	}

	/**
	\return Computes a point on the triangle from u and v barycentric coordinates.
	*/
	PxVec3 pointFromUV(PxReal u, PxReal v) const { return (1.0f-u-v)*verts[0] + u*verts[1] + v*verts[2]; }

	/**
	\brief Array of Vertices.
	*/
	PxVec3		verts[3];

};

#if !PX_DOXYGEN
}
#endif

/** @} */
#endif


text:
package ch.qos.logback.core.rolling.helper;

import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.junit.Before;
import org.junit.Test;

import ch.qos.logback.core.Context;
import ch.qos.logback.core.ContextBase;
import ch.qos.logback.core.status.StatusChecker;
import ch.qos.logback.core.util.Compare;
import ch.qos.logback.core.util.CoreTestConstants;

/**
 * @author Ceki Gulcu
 */
public class CompressTest {

  Context context = new ContextBase();

  @Before
  public void setUp() throws IOException {
    // Copy source files
    // Delete output files
    {
      File source = new File(CoreTestConstants.TEST_SRC_PREFIX
          + "input/compress1.copy");
      File dest = new File(CoreTestConstants.TEST_SRC_PREFIX
          + "input/compress1.txt");

      copy(source, dest);
      File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX
          + "compress1.txt.gz");
      target.mkdirs();
      target.delete();
    }
    {
      File source = new File(CoreTestConstants.TEST_SRC_PREFIX
          + "input/compress2.copy");
      File dest = new File(CoreTestConstants.TEST_SRC_PREFIX
          + "input/compress2.txt");
      copy(source, dest);
      File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX
          + "compress2.txt.gz");
      target.mkdirs();
      target.delete();
    }
    {
      File source = new File(CoreTestConstants.TEST_SRC_PREFIX
          + "input/compress3.copy");
      File dest = new File(CoreTestConstants.TEST_SRC_PREFIX
          + "input/compress3.txt");
      copy(source, dest);
      File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX
          + "compress3.txt.zip");
      target.mkdirs();
      target.delete();
    }
  }

  @Test
  public void test1() throws Exception {
    Compressor compressor = new Compressor(CompressionMode.GZ);
    compressor.setContext(context);
    compressor.compress(CoreTestConstants.TEST_SRC_PREFIX
        + "input/compress1.txt", CoreTestConstants.OUTPUT_DIR_PREFIX
        + "compress1.txt.gz", null);

    StatusChecker checker = new StatusChecker(context);
    assertTrue(checker.isErrorFree(0));
    assertTrue(Compare.gzCompare(CoreTestConstants.OUTPUT_DIR_PREFIX
        + "compress1.txt.gz", CoreTestConstants.TEST_SRC_PREFIX
        + "witness/compress1.txt.gz"));
  }

  @Test
  public void test2() throws Exception {
    Compressor compressor = new Compressor(CompressionMode.GZ);
    compressor.setContext(context);
    compressor.compress(CoreTestConstants.TEST_SRC_PREFIX
        + "input/compress2.txt", CoreTestConstants.OUTPUT_DIR_PREFIX
        + "compress2.txt", null);

    StatusChecker checker = new StatusChecker(context);
    assertTrue(checker.isErrorFree(0));

    assertTrue(Compare.gzCompare(CoreTestConstants.OUTPUT_DIR_PREFIX
        + "compress2.txt.gz", CoreTestConstants.TEST_SRC_PREFIX
        + "witness/compress2.txt.gz"));
  }

  @Test
  public void test3() throws Exception {
    Compressor compressor = new Compressor(CompressionMode.ZIP);
    compressor.setContext(context);
    compressor.compress(CoreTestConstants.TEST_SRC_PREFIX
        + "input/compress3.txt", CoreTestConstants.OUTPUT_DIR_PREFIX
        + "compress3.txt", "compress3.txt");
    StatusChecker checker = new StatusChecker(context);
    assertTrue(checker.isErrorFree(0));

    // we don't know how to compare .zip files
    // assertTrue(Compare.compare(CoreTestConstants.OUTPUT_DIR_PREFIX
    // + "compress3.txt.zip", CoreTestConstants.TEST_SRC_PREFIX
    // + "witness/compress3.txt.zip"));
  }

  private void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
      out.write(buf, 0, len);
    }
    in.close();
    out.close();
  }

}


text:
#include "utils.h"
#include "lualib.h"
#include "lerr.h"
#include "l52util.h"
#include "luaodbc.h"

const char
  *LT_STRING  = "string",
  *LT_NUMBER  = "number",
  *LT_BOOLEAN = "boolean",
  *LT_BINARY  = "binary",
  *LT_WSTRING = "string",
  *LT_INTEGER = "integer";

static const char *LODBC_USER_VALUE = "User value storage";
/*
static const int LODBC_NULL_VALUE = -1;
const int *LODBC_NULL = &LODBC_NULL_VALUE;
*/
const int *LODBC_NULL = NULL;

void lodbc_stackdump( lua_State* L ) {
  int top= lua_gettop(L);
  int i;
  fprintf( stderr, "\n\tDEBUG STACK:\n" );
  if (top==0) fprintf( stderr, "\t(none)\n" );
  for( i=1; i<=top; i++ ) {
    int type= lua_type( L, i );
    fprintf( stderr, "\t[%d]= (%s) ", i, lua_typename(L,type) );

    // Print item contents here...
    //
    // Note: this requires 'tostring()' to be defined. If it is NOT,
    //       enable it for more debugging.
    //

    lua_getglobal( L, "tostring" );
    //
    // [-1]: tostring function, or nil
    if (!lua_isfunction(L,-1)) {
      fprintf( stderr, "('tostring' not available)" );
    } else {
      lua_pushvalue( L, i );
      lua_call( L, 1 /*args*/, 1 /*retvals*/ );

      // Don't trust the string contents
      //
      fprintf( stderr, "%s", lua_tostring(L,-1) );
    }
    lua_pop(L,1);
    fprintf( stderr, "\n" );
  }
  fprintf( stderr, "\n" );
}

int lodbc_is_fail(lua_State *L, int nresult){
  if(nresult == 0)return 0;
  return (lua_type(L, -nresult) == LUA_TNIL);
}

// no result or error
int lodbc_is_unknown(lua_State *L, int nresult){
  if(nresult == 0)return 1;
  return (lua_type(L, -nresult) == LUA_TNIL);
}

/*
** Check if is SQL type.
*/
int lodbc_issqltype (const SQLSMALLINT type) {
  switch (type) {
    case SQL_UNKNOWN_TYPE: case SQL_CHAR: case SQL_VARCHAR:
    case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP:
    case SQL_DATE: case SQL_INTERVAL: case SQL_TIMESTAMP:
    case SQL_LONGVARCHAR:
    case SQL_GUID:

    case SQL_NUMERIC: case SQL_DECIMAL:
    case SQL_FLOAT: case SQL_REAL: case SQL_DOUBLE:
    case SQL_BIGINT: case SQL_TINYINT: case SQL_INTEGER: case SQL_SMALLINT:

    case SQL_WCHAR:
    case SQL_WVARCHAR:
    case SQL_WLONGVARCHAR:

    case SQL_INTERVAL_MONTH:
    case SQL_INTERVAL_YEAR:
    case SQL_INTERVAL_YEAR_TO_MONTH:
    case SQL_INTERVAL_DAY:
    case SQL_INTERVAL_HOUR:
    case SQL_INTERVAL_MINUTE:
    case SQL_INTERVAL_SECOND:
    case SQL_INTERVAL_DAY_TO_HOUR:
    case SQL_INTERVAL_DAY_TO_MINUTE:
    case SQL_INTERVAL_DAY_TO_SECOND:
    case SQL_INTERVAL_HOUR_TO_MINUTE:
    case SQL_INTERVAL_HOUR_TO_SECOND:
    case SQL_INTERVAL_MINUTE_TO_SECOND:

    case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY:
    case SQL_BIT:
      return 1;
    default:
      return 0;
  }
}

/*
** Returns the name of an equivalent lua type for a SQL type.
*/
const char *lodbc_sqltypetolua (const SQLSMALLINT type) {
  switch (type) {
    case SQL_UNKNOWN_TYPE: case SQL_CHAR: case SQL_VARCHAR:
    case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP:
    case SQL_DATE: case SQL_INTERVAL: case SQL_TIMESTAMP:
    case SQL_LONGVARCHAR:
    case SQL_GUID:
      return LT_STRING;

    case SQL_NUMERIC: case SQL_DECIMAL:
    case SQL_FLOAT: case SQL_REAL: case SQL_DOUBLE:
      return LT_NUMBER;

  case SQL_INTEGER:
#ifndef LODBC_INT_SIZE_32
      return LT_NUMBER;
#endif

  case SQL_BIGINT:
#ifndef LODBC_INT_SIZE_64
      return LT_NUMBER;
#endif

    case SQL_TINYINT: case SQL_SMALLINT:
      return LT_INTEGER;

    case SQL_INTERVAL_MONTH:          case SQL_INTERVAL_YEAR:
    case SQL_INTERVAL_YEAR_TO_MONTH:  case SQL_INTERVAL_DAY:
    case SQL_INTERVAL_HOUR:           case SQL_INTERVAL_MINUTE:
    case SQL_INTERVAL_SECOND:         case SQL_INTERVAL_DAY_TO_HOUR:
    case SQL_INTERVAL_DAY_TO_MINUTE:  case SQL_INTERVAL_DAY_TO_SECOND:
    case SQL_INTERVAL_HOUR_TO_MINUTE: case SQL_INTERVAL_HOUR_TO_SECOND:
    case SQL_INTERVAL_MINUTE_TO_SECOND:
      return LT_INTEGER;

    case SQL_WCHAR: case SQL_WVARCHAR:case SQL_WLONGVARCHAR:
      return LT_WSTRING;

    case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY:
      return LT_BINARY;

    case SQL_BIT:
      return LT_BOOLEAN;
    default:
      assert(0);
      return NULL;

  }
}

int lodbc_push_column_value(lua_State *L, SQLHSTMT hstmt, SQLUSMALLINT i, const char type){
  int top = lua_gettop(L);

  switch (type) {/* deal with data according to type */
    case 'n': { /* iNteger */
    #ifdef LODBC_USE_INTEGER
      lua_Integer num;
      SQLLEN got;
      SQLRETURN rc = SQLGetData(hstmt, i, LODBC_C_INTEGER, &num, 0, &got);
      if (lodbc_iserror(rc)) return lodbc_fail(L, hSTMT, hstmt);
      if (got == SQL_NULL_DATA) lodbc_pushnull(L);
      else lua_pushinteger(L, num);
      break;
    #endif
    }
    case 'u': { /* nUmber */
      lua_Number num;
      SQLLEN got;
      SQLRETURN rc = SQLGetData(hstmt, i, LODBC_C_NUMBER, &num, 0, &got);
      if (lodbc_iserror(rc)) return lodbc_fail(L, hSTMT, hstmt);
      if (got == SQL_NULL_DATA) lodbc_pushnull(L);
      else lua_pushnumber(L, num);
      break;
    }
    case 'o': { /* bOol */
      unsigned char b;
      SQLLEN got;
      SQLRETURN rc = SQLGetData(hstmt, i, SQL_C_BIT, &b, 0, &got);
      if (lodbc_iserror(rc)) return lodbc_fail(L, hSTMT, hstmt);
      if (got == SQL_NULL_DATA) lodbc_pushnull(L);
      else lua_pushboolean(L, b);
      break;
    }
    case 't': case 'i': {/* sTring, bInary */
      SQLSMALLINT stype = (type == 't') ? SQL_C_CHAR : SQL_C_BINARY;
      SQLLEN got;
      char *buffer;
      luaL_Buffer b;
      SQLRETURN rc;
      luaL_buffinit(L, &b);
      buffer = luaL_prepbuffer(&b);
      rc = SQLGetData(hstmt, i, stype, buffer, LUAL_BUFFERSIZE, &got);
      if (got == SQL_NULL_DATA){
        lodbc_pushnull(L);
        break;
      }
      while (rc == SQL_SUCCESS_WITH_INFO) {/* concat intermediary chunks */
        if (got >= LUAL_BUFFERSIZE || got == SQL_NO_TOTAL) {
          got = LUAL_BUFFERSIZE;
          /* get rid of null termination in string block */
          if (stype == SQL_C_CHAR) got--;
        }
        luaL_addsize(&b, got);
        buffer = luaL_prepbuffer(&b);
        rc = SQLGetData(hstmt, i, stype, buffer, LUAL_BUFFERSIZE, &got);
      }
      if (rc == SQL_SUCCESS) {/* concat last chunk */
        if (got >= LUAL_BUFFERSIZE || got == SQL_NO_TOTAL) {
          got = LUAL_BUFFERSIZE;
          /* get rid of null termination in string block */
          if (stype == SQL_C_CHAR) got--;
        }
        luaL_addsize(&b, got);
      }
      if (lodbc_iserror(rc)) return lodbc_fail(L, hSTMT, hstmt);
      /* return everything we got */
      luaL_pushresult(&b);
      break;
    }
    default:{
      // unsupported type ?
      assert(0);
    }
  }

  assert(1 == (lua_gettop(L)-top));
  return 0;
}

/*
** Retrieves data from the i_th column in the current row
** Input
**   types: index in sack of column types table
**   hstmt: statement handle
**   i: column number
** Returns:
**   0 if successfull, non-zero otherwise;
*/
int lodbc_push_column(lua_State *L, int coltypes, const SQLHSTMT hstmt, SQLUSMALLINT i) {
  const char *tname;
  char type;
  lua_rawgeti (L, coltypes, i);   /* typename of the column */
  tname = lua_tostring(L, -1);
  if (!tname) return lodbc_faildirect(L, "invalid type in table.");
  type = tname[1];
  lua_pop(L, 1); /* pops type name */
  return lodbc_push_column_value(L,hstmt,i,type);
}

typedef SQLRETURN (SQL_API*get_attr_ptr)(SQLHANDLE, SQLUSMALLINT, SQLPOINTER);
typedef SQLRETURN (SQL_API*set_attr_ptr)(SQLHANDLE, SQLUSMALLINT, SQLULEN);

static get_attr_ptr select_get_attr(SQLSMALLINT HandleType){
    switch(HandleType){
        case hDBC:  return SQLGetConnectOption;
        case hSTMT: return SQLGetStmtOption;
    }
    assert(0);
    return NULL;
}

static set_attr_ptr select_set_attr(SQLSMALLINT HandleType){
    switch(HandleType){
        case hDBC:  return SQLSetConnectOption;
        case hSTMT: return SQLSetStmtOption;
    }
    assert(0);
    return NULL;
}

typedef SQLRETURN (SQL_API*get_attr_ptr_v3)(SQLHANDLE, SQLINTEGER, SQLPOINTER, SQLINTEGER, SQLINTEGER*);
typedef SQLRETURN (SQL_API*set_attr_ptr_v3)(SQLHANDLE, SQLINTEGER, SQLPOINTER, SQLINTEGER);

static get_attr_ptr_v3 select_get_attr_v3(SQLSMALLINT HandleType){
    switch(HandleType){
        case hENV:  return SQLGetEnvAttr;
        case hDBC:  return SQLGetConnectAttr;
        case hSTMT: return SQLGetStmtAttr;
    }
    assert(0);
    return NULL;
}

static set_attr_ptr_v3 select_set_attr_v3(SQLSMALLINT HandleType){
    switch(HandleType){
        case hENV:  return SQLSetEnvAttr;
        case hDBC:  return SQLSetConnectAttr;
        case hSTMT: return SQLSetStmtAttr;
    }
    assert(0);
    return NULL;
}

int lodbc_get_uint_attr_(lua_State*L, SQLSMALLINT HandleType, SQLHANDLE Handle, SQLINTEGER optnum){
    SQLUINTEGER res;
    SQLRETURN ret;
#if (LODBC_ODBCVER >= 0x0300)
    SQLINTEGER dummy;
    ret = select_get_attr_v3(HandleType)(Handle, optnum, (SQLPOINTER)&res, sizeof(res), &dummy);
#else
    if(HandleType == hENV) return lodbc_faildirect(L, "not supported.");
    ret = select_get_attr   (HandleType)(Handle, optnum, (SQLPOINTER)&res);
#endif

    if(ret == LODBC_ODBC3_C(SQL_NO_DATA,SQL_NO_DATA_FOUND)) return 0;
    if(lodbc_iserror(ret)) return lodbc_fail(L, HandleType, Handle);
    lua_pushnumber(L,res);
    return 1;
}

int lodbc_get_str_attr_(lua_State*L, SQLSMALLINT HandleType, SQLHANDLE Handle, SQLINTEGER optnum){
#if (LODBC_ODBCVER >= 0x0300)
    SQLINTEGER got;
    char buffer[256];
#else
    char buffer[SQL_MAX_OPTION_STRING_LENGTH+1];
#endif
    SQLRETURN ret;

#if (LODBC_ODBCVER >= 0x0300)
    ret = select_get_attr_v3(HandleType)(Handle, optnum, (SQLPOINTER)buffer, 255, &got);
#else
    if(HandleType == hENV) return lodbc_faildirect(L, "not supported.");
    ret = select_get_attr   (HandleType)(Handle, optnum, (SQLPOINTER)&buffer);
#endif

    if(ret == LODBC_ODBC3_C(SQL_NO_DATA,SQL_NO_DATA_FOUND)) return 0;
    if(lodbc_iserror(ret)) return lodbc_fail(L, HandleType, Handle);

#if (LODBC_ODBCVER >= 0x0300)
    if(got > 255){
        char* tmp = malloc(got+1);
        if(!tmp)
            return LODBC_ALLOCATE_ERROR(L);
        ret = select_get_attr_v3(HandleType)(Handle, optnum, (SQLPOINTER)tmp, got, &got);
        if(lodbc_iserror(ret)){
            free(tmp);
            if(ret == SQL_NO_DATA) return 0;
            return lodbc_fail(L, HandleType, Handle);
        }
        lua_pushstring(L, tmp);
        free(tmp);
    }
    else
#endif
    lua_pushstring(L, buffer);

    return 1;
}

int lodbc_set_uint_attr_(lua_State*L, SQLSMALLINT HandleType, SQLHANDLE Handle,
    SQLINTEGER optnum, SQLUINTEGER value)
{
    SQLRETURN ret;
#if (LODBC_ODBCVER >= 0x0300)
    ret = select_set_attr_v3(HandleType)(Handle,optnum,(SQLPOINTER)value,SQL_IS_UINTEGER);
#else
    if(HandleType == hENV) return lodbc_faildirect(L, "not supported.");
    ret = select_set_attr   (HandleType)(Handle,optnum,value);
#endif

    if(lodbc_iserror(ret)) return lodbc_fail(L, HandleType, Handle);
    return lodbc_pass(L);
}

int lodbc_set_str_attr_(lua_State*L, SQLSMALLINT HandleType, SQLHANDLE Handle,
    SQLINTEGER optnum, const char* value, size_t len)
{
    SQLRETURN ret;
#if (LODBC_ODBCVER >= 0x0300)
    ret = select_set_attr_v3(HandleType)(Handle,optnum,(SQLPOINTER)value,len);
#else
    if(HandleType == hENV) return lodbc_faildirect(L, "not supported.");
    ret = select_set_attr   (HandleType)(Handle,optnum,(SQLUINTEGER)value);
#endif
    if(lodbc_iserror(ret)) return lodbc_fail(L, HandleType, Handle);
    return lodbc_pass(L);
}

int lodbc_iscallable(lua_State*L, int idx){
  int ret, top = lua_gettop(L);
  if(lua_isfunction(L, idx)) return 1;
  lua_getmetatable(L, idx);
  if(lua_isnil(L, -1)){
    lua_pop(L, 1);
    return 0;
  }
  lua_getfield(L, -1, "__call");
  // ret = lodbc_iscallable(L, -1);
  ret = lua_isfunction(L, -1);
  lua_pop(L, 2);
  assert(top == lua_gettop(L));
  return ret;
}

#ifdef LODBC_USE_NULL_AS_NIL

void lodbc_pushnull(lua_State*L){
  lua_pushnil(L);
}

int lodbc_isnull(lua_State*L, int idx){
  return (lua_type(L, idx) == LUA_TNIL)?1:0;
}

#else

void lodbc_pushnull(lua_State*L){
  lua_pushlightuserdata(L, (void*)LODBC_NULL);
}

int lodbc_isnull(lua_State*L, int idx){
  if(lua_islightuserdata(L, idx)){
    return lua_touserdata(L, idx) == (void*)LODBC_NULL?1:0;
  }
  return 0;
}

#endif

#ifdef LODBC_USE_UDPTR_AS_KEY

void lodbc_init_user_value(lua_State*L){
}

void lodbc_get_user_value(lua_State *L, int keyindex){
  int top = lua_gettop(L);
  void *key = lua_touserdata(L, keyindex);
  assert(key);
  lua_rawgetp(L, LODBC_LUA_REGISTRY, key);
  assert((top+1) == lua_gettop(L));
}

void lodbc_set_user_value(lua_State *L, int keyindex){
  int top = lua_gettop(L);
  void *key = lua_touserdata(L, keyindex);
  assert(lua_gettop(L) >= 2); // ... key, ..., value
  assert(key);
  lua_rawsetp(L, LODBC_LUA_REGISTRY, key);
  assert((top-1) == lua_gettop(L));
}

#else

void lodbc_init_user_value(lua_State*L){
  int top = lua_gettop(L);
  lua_newtable(L);
  lua_newtable(L);
  lua_pushliteral(L, "k");
  lua_setfield(L, -2, "__mode");
  lua_setmetatable(L, -2);
  lua_rawsetp(L, LUA_REGISTRYINDEX, LODBC_USER_VALUE);
  assert(top == lua_gettop(L));
}

void lodbc_get_user_value(lua_State*L, int keyindex){
  int top = lua_gettop(L);
  lua_rawgetp(L, LUA_REGISTRYINDEX, LODBC_USER_VALUE);
  lua_pushvalue(L, keyindex);
  lua_rawget(L, -2);
  lua_remove(L, -2);
  assert((top+1) == lua_gettop(L));
}

void lodbc_set_user_value(lua_State*L, int keyindex){
  int top = lua_gettop(L);
  assert(top >= 2);                                     // ... key, ..., value
  lua_rawgetp(L, LUA_REGISTRYINDEX, LODBC_USER_VALUE);  // ... key, ..., value, tbl
  assert((top+1) == lua_gettop(L));                     //                -3      -2     -1
  lua_pushvalue(L, keyindex);                           // ... key, ..., value , tbl   , key
  lua_insert(L, -3);                                    // ... key, ..., key   , value , tbl
  lua_insert(L, -3);                                    // ... key, ..., tbl   , key   , value
  lua_rawset(L, -3);                                    // ... key, ..., tbl
  lua_pop(L, 1);                                        // ... key, ...
  assert((top-1) == lua_gettop(L));
}

#endif

int lodbc_test_state(const SQLSMALLINT type, const SQLHANDLE handle, const char** states, int n){
  SQLCHAR State[6];
  SQLSMALLINT i, j;

  i = 1;
  while (1) {
    SQLRETURN ret = SQLGetDiagRec(type, handle, i, State, NULL, NULL, 0, NULL);
    if (ret == LODBC_ODBC3_C(SQL_NO_DATA,SQL_NO_DATA_FOUND)) return -1;
    for(j = 0;j<n;++j){
      if (0 == strcmp(states[j], (char*)State)){
        return j;
      }
    }
    i++;
  }
}

int lodbc_make_weak_table(lua_State*L, const char *mode){
  int top = lua_gettop(L);
  lua_newtable(L);
  lua_newtable(L);
  lua_pushstring(L, mode);
  lua_setfield(L, -2, "__mode");
  lua_setmetatable(L,-2);
  assert((top+1) == lua_gettop(L));
  return 1;
}

int lodbc_pcall_method(lua_State *L, const char *name, int nargs, int nresults, int errfunc){
  int obj_index = -nargs - 1;
  lua_getfield(L, obj_index, name);
  lua_insert(L, obj_index - 1);
  return lua_pcall(L, nargs + 1, nresults, errfunc);
}


text:
package com.iancaffey.x86.io;

import java.io.IOException;

/**
 * StringVisitor
 *

 * MOVS/MOVSB Move string/Move byte string.
 * MOVS/MOVSW Move string/Move word string.
 * MOVS/MOVSD Move string/Move doubleword string.
 * SCAS/SCASB Scan string/Scan byte string.
 * SCAS/SCASW Scan string/Scan word string.
 * SCAS/SCASD Scan string/Scan doubleword string.
 * LODS/LODSB Load string/Load byte string.
 * LODS/LODSW Load string/Load word string.
 * LODS/LODSD Load string/Load doubleword string.
 * STOS/STOSB Store string/Store byte string.
 * STOS/STOSW Store string/Store word string.
 * STOS/STOSD Store string/Store doubleword string.
 * REP Repeat while ECX not zero.
 * REPE/REPZ Repeat while equal/Repeat while zero.
 * REPNE/REPNZ Repeat while not equal/Repeat while not zero.
 *
 * @author Ian Caffey
 * @see Intel Developer's Manual
 * @since 1.0
 */
public interface StringVisitor {
    /**
     * Compare String Operands
     *

     * Compares the byte, word, doubleword, or quadword specified with the first source operand with the byte, word,
     * doubleword, or quadword specified with the second source operand and sets the status flags in the EFLAGS register
     * according to the results.
     *

     * Both source operands are located in memory. The address of the first source operand is read from DS:SI, DS:ESI
     * or RSI (depending on the address-size attribute of the instruction is 16, 32, or 64, respectively). The address of the
     * second source operand is read from ES:DI, ES:EDI or RDI (again depending on the address-size attribute of the
     * instruction is 16, 32, or 64). The DS segment may be overridden with a segment override prefix, but the ES
     * segment cannot be overridden.
     *
     * @throws IOException indicating an error occurred while reading/writing the instruction
     */
    public void cmps() throws IOException;

    /**
     * Compare String Operands (byte)
     *

     * Compares the byte specified with the first source operand with the byte specified with the second source operand
     * and sets the status flags in the EFLAGS register according to the results.
     *

     * Both source operands are located in memory. The address of the first source operand is read from DS:SI, DS:ESI
     * or RSI (depending on the address-size attribute of the instruction is 16, 32, or 64, respectively). The address of the
     * second source operand is read from ES:DI, ES:EDI or RDI (again depending on the address-size attribute of the
     * instruction is 16, 32, or 64). The DS segment may be overridden with a segment override prefix, but the ES
     * segment cannot be overridden.
     *
     * @throws IOException indicating an error occurred while reading/writing the instruction
     */
    public void cmpsb() throws IOException;

    /**
     * Compare String Operands (word)
     *

     * Compares the word specified with the first source operand with the word specified with the second source operand
     * and sets the status flags in the EFLAGS register according to the results.
     *

     * Both source operands are located in memory. The address of the first source operand is read from DS:SI, DS:ESI
     * or RSI (depending on the address-size attribute of the instruction is 16, 32, or 64, respectively). The address of the
     * second source operand is read from ES:DI, ES:EDI or RDI (again depending on the address-size attribute of the
     * instruction is 16, 32, or 64). The DS segment may be overridden with a segment override prefix, but the ES
     * segment cannot be overridden.
     *
     * @throws IOException indicating an error occurred while reading/writing the instruction
     */
    public void cmpsw() throws IOException;

    /**
     * Compare String Operands (doubleword)
     *

     * Compares the doubleword specified with the first source operand with the doubleword specified with the second source operand
     * and sets the status flags in the EFLAGS register according to the results.
     *

     * Both source operands are located in memory. The address of the first source operand is read from DS:SI, DS:ESI
     * or RSI (depending on the address-size attribute of the instruction is 16, 32, or 64, respectively). The address of the
     * second source operand is read from ES:DI, ES:EDI or RDI (again depending on the address-size attribute of the
     * instruction is 16, 32, or 64). The DS segment may be overridden with a segment override prefix, but the ES
     * segment cannot be overridden.
     *
     * @throws IOException indicating an error occurred while reading/writing the instruction
     */
    public void cmpsd() throws IOException;

    /**
     * Compare String Operands (quadword)
     *

     * Compares the quadword specified with the first source operand with the quadword specified with the second source operand
     * and sets the status flags in the EFLAGS register according to the results.
     *

     * Both source operands are located in memory. The address of the first source operand is read from DS:SI, DS:ESI
     * or RSI (depending on the address-size attribute of the instruction is 16, 32, or 64, respectively). The address of the
     * second source operand is read from ES:DI, ES:EDI or RDI (again depending on the address-size attribute of the
     * instruction is 16, 32, or 64). The DS segment may be overridden with a segment override prefix, but the ES
     * segment cannot be overridden.
     *
     * @throws IOException indicating an error occurred while reading/writing the instruction
     */
    public void cmpsq() throws IOException;
}


text:
package jade.content.onto;

import jade.content.*;
import jade.content.schema.*;
import jade.content.abs.*;
import jade.content.ContentElementList;
import jade.content.onto.basic.*;
import jade.content.lang.sl.SL0Vocabulary;
import jade.core.AID;
import jade.core.CaseInsensitiveString;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.ISO8601;
import jade.util.leap.*;

import java.util.Date;

/**
 * This class implements an ontology containing schemas for
 * Primitive types and SL0 operators i.e. basic ontological elements
 * required for minimal agent interaction.
 * Users should always extend this ontology when defining their
 * ontologies.
 * @author Federico Bergenti - Universita` di Parma
 * @author Giovanni Caire - TILAB
 */
public class BasicOntology extends Ontology implements SL0Vocabulary {

	// The singleton instance of this ontology
	private static final BasicOntology theInstance = new BasicOntology();
	static {
		theInstance.initialize();
	}

	// Primitive types names
	public static final String         STRING = "BO_String";
	public static final String         FLOAT = "BO_Float";
	public static final String         INTEGER = "BO_Integer";
	public static final String         BOOLEAN = "BO_Boolean";
	public static final String         DATE = "BO_Date";
	public static final String         BYTE_SEQUENCE = "BO_Byte-sequence";

	// Content element list
	public static final String         CONTENT_ELEMENT_LIST = ContentElementListSchema.BASE_NAME;

	//#MIDP_EXCLUDE_BEGIN
	private transient Map primitiveSchemas;
	//#MIDP_EXCLUDE_END

	/**
	 * Constructor
	 */
	private BasicOntology() {
		super("BASIC_ONTOLOGY", (Ontology) null, null);
	}

	private void initialize() {
		// Note that the association between schemas and classes is not
		// necessary for the elements of the BasicOntology as the
		// BasicOntology does not use schemas to translate between
		// Java objects and abstract descriptors, but performs a hardcoded
		// translation
		try {
			// Schemas for primitives
			add(new PrimitiveSchema(FLOAT));
			add(new PrimitiveSchema(INTEGER));
			add(new PrimitiveSchema(BOOLEAN));

			// Schemas for aggregates
			add(new AggregateSchema(SEQUENCE));
			add(new AggregateSchema(SET));

			// Content element list Schema
			add(ContentElementListSchema.getBaseSchema());

			//#MIDP_EXCLUDE_BEGIN
			add(new PrimitiveSchema(STRING), String.class);
			add(new PrimitiveSchema(DATE), Date.class);
			add(new PrimitiveSchema(BYTE_SEQUENCE), byte[].class);
			add(new ConceptSchema(AID), AID.class);
			add(new AgentActionSchema(ACLMSG), ACLMessage.class);
			add(new PredicateSchema(TRUE_PROPOSITION), TrueProposition.class);
			add(new PredicateSchema(FALSE_PROPOSITION), FalseProposition.class);
			add(new AgentActionSchema(ACTION), Action.class);
			add(new PredicateSchema(DONE), Done.class);
			add(new PredicateSchema(RESULT), Result.class);
			add(new PredicateSchema(EQUALS), Equals.class);
			//#MIDP_EXCLUDE_END
			/*#MIDP_INCLUDE_BEGIN
			add(new PrimitiveSchema(STRING));
			add(new PrimitiveSchema(DATE));
			add(new PrimitiveSchema(BYTE_SEQUENCE));
			add(new ConceptSchema(AID));
			add(new AgentActionSchema(ACLMSG));
			add(new PredicateSchema(TRUE_PROPOSITION));
			add(new PredicateSchema(FALSE_PROPOSITION));
			add(new AgentActionSchema(ACTION));
			add(new PredicateSchema(DONE));
			add(new PredicateSchema(RESULT));
			add(new PredicateSchema(EQUALS));
			#MIDP_INCLUDE_END*/

			// AID Schema
			ConceptSchema aidSchema = (ConceptSchema)getSchema(AID);
			aidSchema.add(AID_NAME, (TermSchema) getSchema(STRING));
			aidSchema.add(AID_ADDRESSES, (TermSchema) getSchema(STRING), 0, ObjectSchema.UNLIMITED);
			aidSchema.add(AID_RESOLVERS, aidSchema, 0, ObjectSchema.UNLIMITED);

			// ACLMessage Schema
			AgentActionSchema msgSchema = (AgentActionSchema)getSchema(ACLMSG);
			msgSchema.add(ACLMSG_SENDER, (ConceptSchema) getSchema(AID), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_RECEIVERS, (ConceptSchema) getSchema(AID), 0, ObjectSchema.UNLIMITED);
			msgSchema.add(ACLMSG_REPLY_TO, (ConceptSchema) getSchema(AID), 0, ObjectSchema.UNLIMITED);
			msgSchema.add(ACLMSG_LANGUAGE, (PrimitiveSchema) getSchema(STRING), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_ONTOLOGY, (PrimitiveSchema) getSchema(STRING), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_PROTOCOL, (PrimitiveSchema) getSchema(STRING), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_IN_REPLY_TO, (PrimitiveSchema) getSchema(STRING), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_REPLY_WITH, (PrimitiveSchema) getSchema(STRING), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_CONVERSATION_ID, (PrimitiveSchema) getSchema(STRING), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_REPLY_BY, (PrimitiveSchema) getSchema(DATE), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_CONTENT, (PrimitiveSchema) getSchema(STRING), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_BYTE_SEQUENCE_CONTENT, (PrimitiveSchema) getSchema(BYTE_SEQUENCE), ObjectSchema.OPTIONAL);
			msgSchema.add(ACLMSG_ENCODING, (PrimitiveSchema) getSchema(STRING), ObjectSchema.OPTIONAL);

			// ACTION Schema
			AgentActionSchema actionSchema = (AgentActionSchema)getSchema(ACTION);
			actionSchema.add(ACTION_ACTOR, (TermSchema) getSchema(AID));
			actionSchema.add(ACTION_ACTION, (TermSchema) ConceptSchema.getBaseSchema());
			actionSchema.setEncodingByOrder(true);

			// DONE Schema
			PredicateSchema doneSchema = (PredicateSchema)getSchema(DONE);
			doneSchema.add(DONE_ACTION, (AgentActionSchema) AgentActionSchema.getBaseSchema());
			doneSchema.add(DONE_CONDITION, (PredicateSchema) PredicateSchema.getBaseSchema(), ObjectSchema.OPTIONAL);

			// RESULT Schema
			PredicateSchema resultSchema = (PredicateSchema)getSchema(RESULT);
			resultSchema.add(RESULT_ACTION, (AgentActionSchema) AgentActionSchema.getBaseSchema());
			resultSchema.add(RESULT_VALUE, (TermSchema) TermSchema.getBaseSchema());

			// EQUALS Schema
			PredicateSchema equalsSchema = (PredicateSchema)getSchema(EQUALS);
			equalsSchema.add(EQUALS_LEFT, TermSchema.getBaseSchema());
			equalsSchema.add(EQUALS_RIGHT, TermSchema.getBaseSchema());

			//#MIDP_EXCLUDE_BEGIN
			fillPrimitiveSchemas();
			//#MIDP_EXCLUDE_END
		}
		catch (OntologyException oe) {
			oe.printStackTrace();
		}
	}

	//#MIDP_EXCLUDE_BEGIN
	private void fillPrimitiveSchemas() throws OntologyException {
		// This map is only needed to make the getSchema(Class) method work properly also in the case of java primitives
		primitiveSchemas = new HashMap(10);
		primitiveSchemas.put(boolean.class, getSchema(BasicOntology.BOOLEAN));
		primitiveSchemas.put(java.lang.Boolean.class, getSchema(BasicOntology.BOOLEAN));
		primitiveSchemas.put(int.class, getSchema(BasicOntology.INTEGER));
		primitiveSchemas.put(long.class, getSchema(BasicOntology.INTEGER));
		primitiveSchemas.put(java.lang.Integer.class, getSchema(BasicOntology.INTEGER));
		primitiveSchemas.put(java.lang.Long.class, getSchema(BasicOntology.INTEGER));
		primitiveSchemas.put(float.class, getSchema(BasicOntology.FLOAT));
		primitiveSchemas.put(double.class, getSchema(BasicOntology.FLOAT));
		primitiveSchemas.put(java.lang.Float.class, getSchema(BasicOntology.FLOAT));
		primitiveSchemas.put(java.lang.Double.class, getSchema(BasicOntology.FLOAT));
	}

	private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
		in.defaultReadObject();

		try {
			fillPrimitiveSchemas();
		}
		catch (OntologyException oe) {
			// Should never happen
			oe.printStackTrace();
		}
	}
	//#MIDP_EXCLUDE_END

	/**
	 * Returns the singleton instance of the BasicOntology.
	 * @return the singleton instance of the BasicOntology
	 */
	public static Ontology getInstance() {
		return theInstance;
	}

	//#APIDOC_EXCLUDE_BEGIN
	/**
	 * This method is redefined as BasicOntology does not use an
	 * Introspector for performance reason
	 * @see Ontology#toObject(AbsObject)
	 */
	protected Object toObject(AbsObject abs, String lcType, Ontology referenceOnto) throws UngroundedException, OntologyException {
		try {
			if (abs == null) {
				return null;
			}

			// PRIMITIVE
			if (abs.getAbsType() == AbsObject.ABS_PRIMITIVE) {
				return ((AbsPrimitive) abs).getObject();
			}
			// AGGREGATES
			if (abs.getAbsType() == AbsObject.ABS_AGGREGATE) {
				String absTypeName = abs.getTypeName();
				if (BasicOntology.SEQUENCE.equals(absTypeName)) {
					return AbsHelper.internaliseList((AbsAggregate) abs, referenceOnto);
				} else if (BasicOntology.SET.equals(absTypeName)) {
					return AbsHelper.internaliseSet((AbsAggregate) abs, referenceOnto);
			//#MIDP_EXCLUDE_BEGIN
				} else {
					return AbsHelper.internaliseJavaCollection((AbsAggregate) abs, referenceOnto);
			//#MIDP_EXCLUDE_END
				}
			}
			// CONTENT ELEMENT LIST
			if (abs.getAbsType() == AbsObject.ABS_CONTENT_ELEMENT_LIST) {
				return AbsHelper.internaliseContentElementList((AbsContentElementList) abs, referenceOnto);
			}
			//#MIDP_EXCLUDE_BEGIN
			// CONCEPT_SLOT_FUNCTION
			if (abs.getAbsType() == AbsObject.ABS_CONCEPT_SLOT_FUNCTION) {
				AbsObject absConcept = abs.getAbsObject(ConceptSlotFunctionSchema.CONCEPT_SLOT_FUNCTION_CONCEPT);
				return referenceOnto.createConceptSlotFunction(abs.getTypeName(), (Concept) referenceOnto.toObject(absConcept));
			}
			//#MIDP_EXCLUDE_END
			// AID
			if (CaseInsensitiveString.equalsIgnoreCase(abs.getTypeName(), BasicOntology.AID)) {
				return AbsHelper.internaliseAID((AbsConcept) abs);
			}
			// TRUE_PROPOSITION
			if (CaseInsensitiveString.equalsIgnoreCase(abs.getTypeName(), BasicOntology.TRUE_PROPOSITION)) {
				TrueProposition t = new TrueProposition();
				return t;
			}
			// FALSE_PROPOSITION
			if (CaseInsensitiveString.equalsIgnoreCase(abs.getTypeName(), BasicOntology.FALSE_PROPOSITION)) {
				FalseProposition t = new FalseProposition();
				return t;
			}
			// DONE
			if (CaseInsensitiveString.equalsIgnoreCase(abs.getTypeName(), BasicOntology.DONE)) {
				Done d = new Done();
				d.setAction((AgentAction) referenceOnto.toObject(abs.getAbsObject(BasicOntology.DONE_ACTION)));
				AbsPredicate condition = (AbsPredicate) abs.getAbsObject(BasicOntology.DONE_CONDITION);
				if (condition != null) {
					d.setCondition((Predicate) referenceOnto.toObject(abs.getAbsObject(BasicOntology.DONE_CONDITION)));
				}
				return d;
			}
			// RESULT
			if (CaseInsensitiveString.equalsIgnoreCase(abs.getTypeName(), BasicOntology.RESULT)) {
				Result r = new Result();
				r.setAction((AgentAction) referenceOnto.toObject(abs.getAbsObject(BasicOntology.RESULT_ACTION)));
				r.setValue(referenceOnto.toObject(abs.getAbsObject(BasicOntology.RESULT_VALUE)));
				return r;
			}
			// EQUALS
			if (CaseInsensitiveString.equalsIgnoreCase(abs.getTypeName(), BasicOntology.EQUALS)) {
				Equals e = new Equals();
				e.setLeft(referenceOnto.toObject(abs.getAbsObject(BasicOntology.EQUALS_LEFT)));
				e.setRight(referenceOnto.toObject(abs.getAbsObject(BasicOntology.EQUALS_RIGHT)));
				return e;
			}
			// ACTION
			if (CaseInsensitiveString.equalsIgnoreCase(abs.getTypeName(), BasicOntology.ACTION)) {
				Action a = new Action();
				a.internalise(abs, referenceOnto);
				return a;
			}
			// ACLMESSAGE
			if (ACLMessage.getInteger(abs.getTypeName()) != -1) {
				return AbsHelper.internaliseACLMessage((AbsAgentAction) abs, referenceOnto);
			}

			throw new UnknownSchemaException();
		}
		catch (OntologyException oe) {
			// Forward the exception
			throw oe;
		}
		catch (Throwable t) {
			throw new OntologyException("Unexpected error internalising "+abs+".", t);
		}
	}

	/**
	 * This method is redefined as BasicOntology does not use an
	 * Introspector for performance reason
	 * @see Ontology#toObject(AbsObject)
	 */
	protected AbsObject fromObject(Object obj, Ontology referenceOnto) throws OntologyException{
		try {
			if (obj == null) {
				return null;
			}

			if (obj instanceof String) {
				return AbsPrimitive.wrap((String) obj);
			}
			if (obj instanceof Boolean) {
				return AbsPrimitive.wrap(((Boolean) obj).booleanValue());
			}
			if (obj instanceof Integer) {
				return AbsPrimitive.wrap(((Integer) obj).intValue());
			}
			if (obj instanceof Long) {
				return AbsPrimitive.wrap(((Long) obj).longValue());
			}
			//#MIDP_EXCLUDE_BEGIN
			if (obj instanceof Float) {
				return AbsPrimitive.wrap(((Float) obj).floatValue());
			}
			if (obj instanceof Double) {
				return AbsPrimitive.wrap(((Double) obj).doubleValue());
			}
			//#MIDP_EXCLUDE_END
			if (obj instanceof Date) {
				return AbsPrimitive.wrap((Date) obj);
			}
			if (obj instanceof byte[]) {
				return AbsPrimitive.wrap((byte[]) obj);
			}

			if (obj instanceof List) {
				return AbsHelper.externaliseList((List) obj, referenceOnto, SEQUENCE);
			}

			if (obj instanceof Set) {
				return AbsHelper.externaliseSet((Set) obj, referenceOnto, SET);
			}

			if (obj instanceof Iterator) {
				return AbsHelper.externaliseIterator((Iterator) obj, referenceOnto, SEQUENCE);
			}

			if(obj instanceof AID) {
				return AbsHelper.externaliseAID((AID)obj);
			}

			if (obj instanceof ContentElementList) {
				return AbsHelper.externaliseContentElementList((ContentElementList) obj, referenceOnto);
			}

			if(obj instanceof TrueProposition) {
				AbsPredicate absTrueProp = new AbsPredicate(BasicOntology.TRUE_PROPOSITION);
				return absTrueProp;
			}

			if(obj instanceof FalseProposition) {
				AbsPredicate absTrueProp = new AbsPredicate(BasicOntology.FALSE_PROPOSITION);
				return absTrueProp;
			}

			if(obj instanceof Done) {
				AbsPredicate absDone = new AbsPredicate(BasicOntology.DONE);
				absDone.set(BasicOntology.DONE_ACTION, (AbsAgentAction) referenceOnto.fromObject(((Done) obj).getAction()));
				if (((Done) obj).getCondition() != null) {
					absDone.set(BasicOntology.DONE_CONDITION, (AbsPredicate) referenceOnto.fromObject(((Done) obj).getCondition()));
				}
				return absDone;
			}

			if(obj instanceof Result) {
				AbsPredicate absResult = new AbsPredicate(BasicOntology.RESULT);
				absResult.set(BasicOntology.RESULT_ACTION, (AbsAgentAction) referenceOnto.fromObject(((Result) obj).getAction()));
				absResult.set(BasicOntology.RESULT_VALUE, (AbsTerm) referenceOnto.fromObject(((Result) obj).getValue()));
				return absResult;
			}

			if(obj instanceof Equals) {
				AbsPredicate absEquals = new AbsPredicate(BasicOntology.EQUALS);
				absEquals.set(BasicOntology.EQUALS_LEFT, (AbsTerm) referenceOnto.fromObject(((Equals) obj).getLeft()));
				absEquals.set(BasicOntology.EQUALS_RIGHT, (AbsTerm) referenceOnto.fromObject(((Equals) obj).getRight()));
				return absEquals;
			}

			if (obj instanceof Action) {
				AbsAgentAction absAction = new AbsAgentAction(BasicOntology.ACTION);
				((Action) obj).externalise(absAction, referenceOnto);
				return absAction;
			}

			if (obj instanceof ACLMessage) {
				return AbsHelper.externaliseACLMessage((ACLMessage)obj, referenceOnto);
			}

			//#MIDP_EXCLUDE_BEGIN
			if (obj instanceof ConceptSlotFunction) {
				ConceptSlotFunction csf = (ConceptSlotFunction) obj;
				AbsObject absConcept = referenceOnto.fromObject(csf.getConcept());
				AbsConcept absCsf = new AbsConcept(csf.getSlotName());
				absCsf.set(ConceptSlotFunctionSchema.CONCEPT_SLOT_FUNCTION_CONCEPT, absConcept);
				return absCsf;
			}
			//#MIDP_EXCLUDE_END

			throw new UnknownSchemaException();
		}
		catch (OntologyException oe) {
			// Forward the exception
			throw oe;
		}
		catch (Throwable t) {
			throw new OntologyException("Unexpected error externalising "+obj+".", t);
		}
	}
	//#APIDOC_EXCLUDE_END

	/**
	 * Redefine the getSchema() method to take into
	 * account ACL performatives.
	 * @param name the name of the schema in the vocabulary.
	 * @return the schema or null if the schema is not found.
	 * @throws OntologyException
	 */
	public ObjectSchema getSchema(String name) throws OntologyException {
		ObjectSchema ret = super.getSchema(name);
		if (ret == null) {
			int perf = ACLMessage.getInteger(name);
			if (perf != -1) {
				ret = createMsgSchema(name);
			}
		}
		return ret;
	}

	/**
	 * Redefine the getSchema() method to take into
	 * account java primitives.
	 * @param clazz the class whose associated schema must be retrieved.
	 * @return the schema associated to the given class or null if the schema is not found.
	 * @throws OntologyException
	 */
	public ObjectSchema getSchema(Class clazz) throws OntologyException {
		//#MIDP_EXCLUDE_BEGIN
		ObjectSchema schema = (ObjectSchema)primitiveSchemas.get(clazz);
		if (schema == null) {
			schema = super.getSchema(clazz);
		}
		//#MIDP_EXCLUDE_END
		/*#MIDP_INCLUDE_BEGIN
		ObjectSchema schema = super.getSchema(clazz);
		#MIDP_INCLUDE_END*/
		return schema;
	}

	/**
     Note that we don't want to keep 22 different schemas for the 22
     FIPA communicative acts --> We generate the schemas for communicative
     acts on the fly as needed.
	 */
	private ObjectSchema createMsgSchema(String performative) throws OntologyException {
		AgentActionSchema msgSchema = new AgentActionSchema(performative);
		msgSchema.addSuperSchema((AgentActionSchema) getSchema(ACLMSG));
		return msgSchema;
	}

	//#MIDP_EXCLUDE_BEGIN
	/**
	 Convert, if possible, the numeric value srcValue into an instance of destClass
	 */
	public static Object adjustPrimitiveValue(Object srcValue, Class destClass) {
		Object destValue = srcValue;
		if (srcValue != null) {
			Class srcClass = srcValue.getClass();
			// Note that we deal with Integer, int, Long, long... classes only --> we can compare the classes using == and != instead of using instanceof
			if (srcClass != destClass) {
				if (destClass == Integer.class ||
					destClass == int.class) {
					if (srcClass == Long.class) {
						destValue = new Integer(((Long)srcValue).intValue());
					}
					else if (srcClass == String.class) {
						destValue = new Integer(Integer.parseInt((String)srcValue));
					}
				}
				else if (destClass == Long.class ||
						 destClass == long.class) {
					if (srcClass == Integer.class) {
						destValue = new Long(((Integer)srcValue).longValue());
					}
					else if (srcClass == String.class) {
						destValue = new Long(Long.parseLong((String)srcValue));
					}
				}
				else if (destClass == Float.class ||
						 destClass == float.class) {
					if (srcClass == Integer.class) {
						destValue = new Float(((Integer)srcValue).floatValue());
					}
					else if (srcClass == Long.class) {
						destValue = new Float(((Long)srcValue).floatValue());
					}
					else if (srcClass == Double.class) {
						destValue = new Float(((Double)srcValue).floatValue());
					}
					else if (srcClass == String.class) {
						destValue = new Float(Float.parseFloat((String)srcValue));
					}
				}
				else if (destClass == Double.class ||
						 destClass == double.class) {
					if (srcClass == Integer.class) {
						destValue = new Double(((Integer)srcValue).doubleValue());
					}
					else if (srcClass == Long.class) {
						destValue = new Double(((Long)srcValue).doubleValue());
					}
					else if (srcClass == Float.class) {
						destValue = new Double(((Float)srcValue).doubleValue());
					}
					else if (srcClass == String.class) {
						destValue = new Double(Double.parseDouble((String)srcValue));
					}
				}
				else if (destClass == String.class) {
					destValue = srcValue.toString();
				}
				else if (destClass == Boolean.class ||
						 destClass == boolean.class) {
					if (srcClass == String.class) {
						String s = (String) srcValue;
						if (s.equalsIgnoreCase("true")) {
							destValue = new Boolean(true);
						}
						else if (s.equalsIgnoreCase("false")) {
							destValue = new Boolean(false);
						}
					}
				}
				else if (destClass == Date.class) {
					try {
						// Try to convert string from FIPA-ISO8601 format
						destValue = ISO8601.toDate(srcValue.toString());
					} catch (Exception e) {
						try {
							// Try to convert string from W3C-ISO8601 format
							java.text.SimpleDateFormat W3CISO8601DateFormat = new java.text.SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss.SSS");
							destValue = W3CISO8601DateFormat.parse(srcValue.toString());
						} catch (java.text.ParseException e1) {
							// Date format not correct
						}
					}
				}
			}
		}
		return destValue;
	}

	/**
	 * @deprecated Use adjustPrimitiveValue() instead
	 */
	public static Object resolveNumericValue(Object srcValue, Class destClass) {
		return adjustPrimitiveValue(srcValue, destClass);
	}
	//#MIDP_EXCLUDE_END
}