text:
// Copyright (C) 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#include "unicode/localpointer.h"
#include "unicode/ucnv.h"
#include "filestrm.h"

#if !UCONFIG_NO_CONVERSION

#ifndef UCBUF_H
#define UCBUF_H 1

typedef struct UCHARBUF UCHARBUF;
/**
 * End of file value
 */
#define U_EOF 0xFFFFFFFF
/**
 * Error value if a sequence cannot be unescaped
 */
#define U_ERR 0xFFFFFFFE

typedef struct ULine ULine;

struct  ULine {
    UChar     *name;
    int32_t   len;
};

/**
 * Opens the UCHARBUF with the given file stream and code page for conversion
 * @param fileName  Name of the file to open.
 * @param codepage  The encoding of the file stream to convert to Unicode.
 *                  If *codepoge is NULL on input the API will try to autodetect
 *                  popular Unicode encodings
 * @param showWarning Flag to print out warnings to STDOUT
 * @param buffered  If TRUE performs a buffered read of the input file. If FALSE reads
 *                  the whole file into memory and converts it.
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 * @return pointer to the newly opened UCHARBUF
 */
U_CAPI UCHARBUF* U_EXPORT2
ucbuf_open(const char* fileName,const char** codepage,UBool showWarning, UBool buffered, UErrorCode* err);

/**
 * Gets a UTF-16 code unit at the current position from the converted buffer
 * and increments the current position
 * @param buf Pointer to UCHARBUF structure
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 */
U_CAPI int32_t U_EXPORT2
ucbuf_getc(UCHARBUF* buf,UErrorCode* err);

/**
 * Gets a UTF-32 code point at the current position from the converted buffer
 * and increments the current position
 * @param buf Pointer to UCHARBUF structure
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 */
U_CAPI int32_t U_EXPORT2
ucbuf_getc32(UCHARBUF* buf,UErrorCode* err);

/**
 * Gets a UTF-16 code unit at the current position from the converted buffer after
 * unescaping and increments the current position. If the escape sequence is for UTF-32
 * code point (\\Uxxxxxxxx) then a UTF-32 codepoint is returned
 * @param buf Pointer to UCHARBUF structure
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 */
U_CAPI int32_t U_EXPORT2
ucbuf_getcx32(UCHARBUF* buf,UErrorCode* err);

/**
 * Gets a pointer to the current position in the internal buffer and length of the line.
 * It imperative to make a copy of the returned buffer before performing operations on it.
 * @param buf Pointer to UCHARBUF structure
 * @param len Output param to receive the len of the buffer returned till end of the line
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 *        Error: U_TRUNCATED_CHAR_FOUND
 * @return Pointer to the internal buffer, NULL if EOF
 */
U_CAPI const UChar* U_EXPORT2
ucbuf_readline(UCHARBUF* buf,int32_t* len, UErrorCode* err);

/**
 * Resets the buffers and the underlying file stream.
 * @param buf Pointer to UCHARBUF structure
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 */
U_CAPI void U_EXPORT2
ucbuf_rewind(UCHARBUF* buf,UErrorCode* err);

/**
 * Returns a pointer to the internal converted buffer
 * @param buf Pointer to UCHARBUF structure
 * @param len Pointer to int32_t to receive the lenth of buffer
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 * @return Pointer to internal UChar buffer
 */
U_CAPI const UChar* U_EXPORT2
ucbuf_getBuffer(UCHARBUF* buf,int32_t* len,UErrorCode* err);

/**
 * Closes the UCHARBUF structure members and cleans up the malloc'ed memory
 * @param buf Pointer to UCHARBUF structure
 */
U_CAPI void U_EXPORT2
ucbuf_close(UCHARBUF* buf);

#if U_SHOW_CPLUSPLUS_API

U_NAMESPACE_BEGIN

/**
 * \class LocalUCHARBUFPointer
 * "Smart pointer" class, closes a UCHARBUF via ucbuf_close().
 * For most methods see the LocalPointerBase base class.
 *
 * @see LocalPointerBase
 * @see LocalPointer
 */
U_DEFINE_LOCAL_OPEN_POINTER(LocalUCHARBUFPointer, UCHARBUF, ucbuf_close);

U_NAMESPACE_END

#endif

/**
 * Rewinds the buffer by one codepoint. Does not rewind over escaped characters.
 */
U_CAPI void U_EXPORT2
ucbuf_ungetc(int32_t ungetChar,UCHARBUF* buf);

/**
 * Autodetects the encoding of the file stream. Only Unicode charsets are autodectected.
 * Some Unicode charsets are stateful and need byte identifiers to be converted also to bring
 * the converter to correct state for converting the rest of the stream. So the UConverter parameter
 * is necessary.
 * If the charset was autodetected, the caller must close both the input FileStream
 * and the converter.
 *
 * @param fileName The file name to be opened and encoding autodected
 * @param conv  Output param to receive the opened converter if autodetected; NULL otherwise.
 * @param cp Output param to receive the detected encoding
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 * @return The input FileStream if its charset was autodetected; NULL otherwise.
 */
U_CAPI FileStream * U_EXPORT2
ucbuf_autodetect(const char* fileName, const char** cp,UConverter** conv,
int32_t* signatureLength, UErrorCode* status);

/**
 * Autodetects the encoding of the file stream. Only Unicode charsets are autodectected.
 * Some Unicode charsets are stateful and need byte identifiers to be converted also to bring
 * the converter to correct state for converting the rest of the stream. So the UConverter parameter
 * is necessary.
 * If the charset was autodetected, the caller must close the converter.
 *
 * @param fileStream The file stream whose encoding is to be detected
 * @param conv  Output param to receive the opened converter if autodetected; NULL otherwise.
 * @param cp Output param to receive the detected encoding
 * @param err is a pointer to a valid UErrorCode value. If this value
 *        indicates a failure on entry, the function will immediately return.
 *        On exit the value will indicate the success of the operation.
 * @return Boolean whether the Unicode charset was autodetected.
 */

U_CAPI UBool U_EXPORT2
ucbuf_autodetect_fs(FileStream* in, const char** cp, UConverter** conv, int32_t* signatureLength, UErrorCode* status);

/**
 * Returns the approximate size in UChars required for converting the file to UChars
 */
U_CAPI int32_t U_EXPORT2
ucbuf_size(UCHARBUF* buf);

U_CAPI const char* U_EXPORT2
ucbuf_resolveFileName(const char* inputDir, const char* fileName, char* target, int32_t* len, UErrorCode* status);

#endif
#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ScheduledTasksBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ScheduledTasksBundle extends Bundle
{
}


text:
"""This module implements a plane object and related functions
"""
from .line import Line3d
from .vector3d import Vector3d
from .point3d import Point3d
from .core import isRoughlyZero

class Plane3d(object):
    """A 3d plane object
    This plane class has an infinite size.

    A plane can be initialized with point on the plane and a vector normal to
    the plane, or with three points

    Planes are infinite and currently have no origin.
    """
    def __init__(self, *args, **kwargs):

        if len(args) == 2:
            # assume we have a point and vector
            self.point = args[0]
            self.normal = args[1]

        elif len(args) == 3:
            # assume we have 3 points
            v1 = args[2] - args[1]
            v2 = args[1] - args[0]
            normal = v1.cross( v2 )
            self.point = args[0]
            self.normal = normal

        self.d = -(self.normal.dot(self.point))

    def angleTo(self, other):
        """measures the angle between this plane and another plane. This uses
        that angle between two normal vectors.
        Units expressed in radians.
        """
        if isinstance(other, Plane3d):
            otherVect = other.normal
        elif isinstance(other, Vector3d):
            otherVect = other
        return self.normal.angleTo(otherVect)

    def intersect(self, other):
        """Finds the intersection of this plane with another object.
        """
        if isinstance(other, Plane3d):
            # return the line intersection of two planes
            # first, get the cross product of the two plane normals
            # which is a vector parallel to L
            vector = self.normal.cross(other.normal)
            absCoords = [abs(c) for c in vector]
            if isRoughlyZero(sum(absCoords)):
                # the planes are parallel and do not intersect
                return None
            else:
                # the planes intersect in a line
                # first find the largest coordinate in the vector
                cNum = None
                cMax = 0
                for i, c in enumerate(absCoords):
                    if c > cMax:
                        cMax = c
                        cNum = i
                dims = ["x","y","z"]
                biggestDim = dims.pop(cNum)
                p = {}
                p[biggestDim] = 0
                if biggestDim == "x":
                    p["y"] = (other.d * self.normal.z - self.d * other.normal.z)/vector.x
                    p["z"] = (self.d * other.normal.y - other.d * self.normal.y)/vector.x
                elif biggestDim == "y":
                    p["x"] = (self.d * other.normal.z - other.d * self.normal.z)/vector.y
                    p["z"] = (other.d * self.normal.x - self.d * other.normal.x)/vector.y
                else: # biggest dim is z
                    p["x"] = (other.d * self.normal.y - self.d * other.normal.y)/vector.z
                    p["y"] = (self.d * other.normal.x - other.d * self.normal.x)/vector.z
                point = Point3d(**p)
                return Line3d(vector, point)

        elif isinstance(other, Line3d):
            # return the point intersection of a line and a plane
            pass
        pass

    def __repr__(self):
        return 'Plane3d( %s, %s )' % (self.point, self.normal)


text:
package com.google.android.exoplayer.smoothstreaming;

import android.test.InstrumentationTestCase;
import java.io.IOException;
import java.io.InputStream;

/**
 * Unit tests for {@link SmoothStreamingManifestParser}.
 */
public class SmoothStreamingManifestParserTest extends InstrumentationTestCase {

    private static final String SAMPLE_ISMC_1 = "smoothstreaming/sample_ismc_1";
    private static final String SAMPLE_ISMC_2 = "smoothstreaming/sample_ismc_2";

    public void testParseSmoothStreamingManifest() throws IOException {
        SmoothStreamingManifestParser parser = new SmoothStreamingManifestParser();
        // Simple test to ensure that the sample manifest parses without throwing any exceptions.
        // SystemID UUID in the manifest is not wrapped in braces.
        InputStream inputStream1 =
                getInstrumentation().getContext().getResources().getAssets().open(SAMPLE_ISMC_1);
        parser.parse("https://example.com/test.ismc", inputStream1);
        // Simple test to ensure that the sample manifest parses without throwing any exceptions.
        // SystemID UUID in the manifest is wrapped in braces.
        InputStream inputStream2 =
                getInstrumentation().getContext().getResources().getAssets().open(SAMPLE_ISMC_2);
        parser.parse("https://example.com/test.ismc", inputStream2);
    }
}


text:
#ifndef __MXFPP_IDENTIFICATION_H__
#define __MXFPP_IDENTIFICATION_H__

#include <libMXF++/metadata/base/IdentificationBase.h>

namespace mxfpp
{

class Identification : public IdentificationBase
{
public:
    friend class MetadataSetFactory<Identification>;

public:
    Identification(HeaderMetadata *headerMetadata);
    virtual ~Identification();

    void initialise(std::string companyName, std::string productName, std::string versionString, mxfUUID productUID);

protected:
    Identification(HeaderMetadata *headerMetadata, ::MXFMetadataSet *cMetadataSet);
};

};

#endif


text:
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

#include "ignite/common/common.h"
#include "ignite/common/utils.h"

#include "ignite/odbc/utility.h"
#include "ignite/odbc/config/configuration.h"

namespace ignite
{
    namespace odbc
    {
        namespace config
        {
            const std::string Configuration::Key::dsn               = "dsn";
            const std::string Configuration::Key::driver            = "driver";
            const std::string Configuration::Key::cache             = "cache";
            const std::string Configuration::Key::address           = "address";
            const std::string Configuration::Key::server            = "server";
            const std::string Configuration::Key::port              = "port";
            const std::string Configuration::Key::distributedJoins  = "distributed_joins";
            const std::string Configuration::Key::enforceJoinOrder  = "enforce_join_order";
            const std::string Configuration::Key::protocolVersion   = "protocol_version";

            const std::string Configuration::DefaultValue::dsn             = "Apache Ignite DSN";
            const std::string Configuration::DefaultValue::driver          = "Apache Ignite";
            const std::string Configuration::DefaultValue::cache           = "";
            const std::string Configuration::DefaultValue::address         = "";
            const std::string Configuration::DefaultValue::server          = "";

            const uint16_t Configuration::DefaultValue::port = 10800;

            const bool Configuration::DefaultValue::distributedJoins = false;
            const bool Configuration::DefaultValue::enforceJoinOrder = false;

            const ProtocolVersion& Configuration::DefaultValue::protocolVersion = ProtocolVersion::GetCurrent();

            Configuration::Configuration() :
                arguments()
            {
                ParseAddress(DefaultValue::address, endPoint);
            }

            Configuration::~Configuration()
            {
                // No-op.
            }

            void Configuration::FillFromConnectString(const char* str, size_t len)
            {
                // Initializing map.
                arguments.clear();

                // Initializing DSN to empty string.
                arguments[Key::dsn].clear();

                // Ignoring terminating zero byte if present.
                // Some Driver Managers pass zero-terminated connection string
                // while others don't.
                if (len && !str[len - 1])
                    --len;

                ParseAttributeList(str, len, ';', arguments);

                ArgumentMap::const_iterator it = arguments.find(Key::address);
                if (it != arguments.end())
                {
                    // Parsing address.
                    ParseAddress(it->second, endPoint);
                }
                else
                {
                    endPoint.host = GetStringValue(Key::server, DefaultValue::server);
                    endPoint.port = static_cast<uint16_t>(GetIntValue(Key::port, DefaultValue::port));
                }
            }

            void Configuration::FillFromConnectString(const std::string& str)
            {
                FillFromConnectString(str.data(), str.size());
            }

            std::string Configuration::ToConnectString() const
            {
                std::stringstream connect_string_buffer;

                for (ArgumentMap::const_iterator it = arguments.begin(); it != arguments.end(); ++it)
                {
                    const std::string& key = it->first;
                    const std::string& value = it->second;

                    if (value.empty())
                        continue;

                    if (value.find(' ') == std::string::npos)
                        connect_string_buffer << key << '=' << value << ';';
                    else
                        connect_string_buffer << key << "={" << value << "};";
                }

                return connect_string_buffer.str();
            }

            void Configuration::FillFromConfigAttributes(const char * attributes)
            {
                // Initializing map.
                arguments.clear();

                size_t len = 0;

                // Getting list length. List is terminated by two '\0'.
                while (attributes[len] || attributes[len + 1])
                    ++len;

                ++len;

                ParseAttributeList(attributes, len, '\0', arguments);

                ArgumentMap::const_iterator it = arguments.find(Key::address);
                if (it != arguments.end())
                {
                    // Parsing address.
                    ParseAddress(it->second, endPoint);
                }
                else
                {
                    endPoint.host = GetStringValue(Key::server, DefaultValue::server);
                    endPoint.port = static_cast<uint16_t>(GetIntValue(Key::port, DefaultValue::port));
                }
            }

            ProtocolVersion Configuration::GetProtocolVersion() const
            {
                ArgumentMap::const_iterator it = arguments.find(Key::protocolVersion);

                if (it != arguments.end())
                    return ProtocolVersion::FromString(it->second);

                return DefaultValue::protocolVersion;
            }

            const std::string& Configuration::GetStringValue(const std::string& key, const std::string& dflt) const
            {
                ArgumentMap::const_iterator it = arguments.find(common::ToLower(key));

                if (it != arguments.end())
                    return it->second;

                return dflt;
            }

            int64_t Configuration::GetIntValue(const std::string& key, int64_t dflt) const
            {
                ArgumentMap::const_iterator it = arguments.find(common::ToLower(key));

                if (it != arguments.end())
                {
                    const std::string& val = it->second;

                    if (!common::AllOf(val.begin(), val.end(), isdigit))
                        IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_GENERIC,
                            "Invalid argument value: Integer value is expected.", "key", key);

                    return common::LexicalCast<int64_t>(val);
                }

                return dflt;
            }

            bool Configuration::GetBoolValue(const std::string& key, bool dflt) const
            {
                ArgumentMap::const_iterator it = arguments.find(common::ToLower(key));

                if (it != arguments.end())
                {
                    std::string lowercaseVal = common::ToLower(it->second);

                    if (lowercaseVal != "true" && lowercaseVal != "false")
                        IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_GENERIC,
                            "Invalid argument value: Boolean value is expected (true or false).", "key", key);

                    return lowercaseVal == "true";
                }

                return dflt;
            }

            void Configuration::ParseAttributeList(const char * str, size_t len, char delimeter, ArgumentMap & args)
            {
                std::string connect_str(str, len);

                while (!connect_str.empty())
                {
                    size_t attr_begin = connect_str.rfind(delimeter);

                    if (attr_begin == std::string::npos)
                        attr_begin = 0;
                    else
                        ++attr_begin;

                    size_t attr_eq_pos = connect_str.rfind('=');

                    if (attr_eq_pos == std::string::npos)
                        attr_eq_pos = 0;

                    if (attr_begin < attr_eq_pos)
                    {
                        const char* key_begin = connect_str.data() + attr_begin;
                        const char* key_end = connect_str.data() + attr_eq_pos;

                        const char* value_begin = connect_str.data() + attr_eq_pos + 1;
                        const char* value_end = connect_str.data() + connect_str.size();

                        std::string key = utility::RemoveSurroundingSpaces(key_begin, key_end);
                        std::string value = utility::RemoveSurroundingSpaces(value_begin, value_end);

                        utility::IntoLower(key);

                        if (value.front() == '{' && value.back() == '}')
                            value = value.substr(1, value.size() - 2);

                        args[key] = value;
                    }

                    if (!attr_begin)
                        break;

                    connect_str.erase(attr_begin - 1);
                }
            }

            void Configuration::ParseAddress(const std::string& address, EndPoint& res)
            {
                int64_t colonNum = std::count(address.begin(), address.end(), ':');

                if (colonNum == 0)
                {
                    res.host = address;
                    res.port = DefaultValue::port;
                }
                else if (colonNum == 1)
                {
                    size_t pos = address.find(':');

                    if (pos == address.size() - 1)
                        throw IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                            "Invalid address format: no port after colon");

                    res.host = address.substr(0, pos);

                    std::string port = address.substr(pos + 1);

                    if (!common::AllOf(port.begin(), port.end(), isdigit))
                        throw IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                            "Invalid address format: port can only contain digits");

                    int32_t intPort = common::LexicalCast<int32_t>(port);

                    if (port.size() > sizeof("65535") - 1 || intPort > UINT16_MAX)
                    {
                        throw IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                            "Invalid address format: Port value is too large,"
                            " valid value should be in range from 1 to 65535");
                    }

                    if (intPort == 0)
                        throw IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                            "Invalid address format: Port value can not be zero");

                    res.port = static_cast<uint16_t>(intPort);
                }
                else
                    throw IgniteError(IgniteError::IGNITE_ERR_GENERIC,
                        "Invalid address format: too many colons");
            }
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>kr.co.313</groupId>
		<artifactId>supports</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>template</artifactId>
	<packaging>pom</packaging>
	<name>template</name>
	<url>http://maven.apache.org</url>
</project>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GameRes.Utility;

namespace GameRes.Formats.PS2
{
    [Export(typeof(ArchiveFormat))]
    public class AfsOpener : ArchiveFormat
    {
        public override string         Tag { get { return "AFS"; } }
        public override string Description { get { return "PS2 resource archive"; } }
        public override uint     Signature { get { return 0x00534641; } } // "AFS"
        public override bool  IsHierarchic { get { return false; } }
        public override bool     CanCreate { get { return false; } }

        public override ArcFile TryOpen (ArcView file)
        {
            int count = file.View.ReadInt32 (4);
            if (count <= 0 || count > 0xfffff)
                return null;
            uint index_offset = 8;
            var dir = new List<Entry> (count);
            for (int i = 0; i < count; ++i)
            {
                uint offset = file.View.ReadUInt32 (index_offset);
                uint size = file.View.ReadUInt32 (index_offset+4);
                var entry = new Entry { Offset = offset, Size = size };
                if (!entry.CheckPlacement (file.MaxOffset))
                    return null;
                dir.Add (entry);
                index_offset += 8;
            }
            var last_entry = dir[count-1];
            index_offset = (uint)AlignOffset (last_entry.Offset + last_entry.Size);
            for (int i = 0; i < count; ++i)
            {
                var name = file.View.ReadString (index_offset, 0x20);
                if (string.IsNullOrEmpty (name))
                    return null;
                dir[i].Name = name;
                dir[i].Type = FormatCatalog.Instance.GetTypeFromName (name);
                index_offset += 0x30;
            }
            return new ArcFile (file, this, dir);
        }

        long AlignOffset (long offset, uint block_size = 0x800)
        {
            offset += block_size - 1;
            return offset & ~(long)(block_size - 1);
        }
    }

    [Export(typeof(AudioFormat))]
    public class AdxAudio : OggAudio
    {
        public override string         Tag { get { return "ADX"; } }
        public override string Description { get { return "PS2 audio format (Ogg/Vorbis)"; } }
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <errno.h>
#include <string.h>
#include <lib.h>
#include <sys/stat.h>
#include <dirent.h>
#include <assert.h>
#include <signal.h>
#include <minix/dmap.h>
#include "usb_driver.h"
#include "proto.h"

#define SERVICE_BINARY "/bin/service"

#define DEVMAN_TYPE_NAME "dev_type"
#define PATH_LEN 256
#define INVAL_MAJOR -1
#define MAX_CONFIG_DIRS 4

static void main_loop();
static void handle_event();
static void cleanup();
static void parse_config();
static void display_usage();
static enum dev_type determine_type(char *path);
static int get_major();
static void create_pid_file();
static void put_major(int major);
static struct devmand_usb_driver* match_usb_driver(struct usb_device_id *id);
static struct devmand_driver_instance *find_instance(int dev_id);

#define dbg(fmt, ... ) \
	if (args.verbose) \
	printf("%8s:%4d: %13s()| "fmt"\n", __FILE__, __LINE__, __func__,  ##__VA_ARGS__ )

static LIST_HEAD(usb_driver_head, devmand_usb_driver) drivers =
    LIST_HEAD_INITIALIZER(drivers);
static LIST_HEAD(usb_driver_inst_head, devmand_driver_instance) instances =
    LIST_HEAD_INITIALIZER(instances);

static int _run = 1;
struct global_args {
	char *path;
	char *config_dirs[MAX_CONFIG_DIRS];
	int config_dir_count ;
	int major_offset;
	int verbose;
	int check_config;
};

enum dev_type {
	DEV_TYPE_USB_DEVICE,
	DEV_TYPE_USB_INTF,
	DEV_TYPE_UNKOWN
};

extern FILE *yyin;

static struct global_args args = {
	.path = NULL,
	.config_dirs = {NULL,NULL,NULL,NULL},
	.config_dir_count = 0,
	.major_offset = USB_BASE_MAJOR,
	.verbose = 0,
	.check_config = 0};

static struct option options[] =
{
	{"dir"   ,    required_argument, NULL, 'd'},
	{"path",      required_argument, NULL, 'p'},
	{"verbose",    required_argument, NULL, 'v'},
	{"check-config", no_argument,       NULL, 'x'},
	{0,0,0,0} /* terminating entry */
};

static char major_bitmap[16]; /* can store up to 128 major number states */

/*===========================================================================*
 *             run_upscript                                                  *
 *===========================================================================*/
int run_upscript(struct devmand_driver_instance *inst)
{
	char cmdl[1024];
	cmdl[0] = 0;
	int ret;

	assert(inst->drv->upscript);
	assert(inst->label);

	snprintf(cmdl, 1024, "%s up %s %d %d",
	    inst->drv->upscript, inst->label, inst->major, inst->dev_id);
	dbg("Running Upscript:  \"%s\"", cmdl);
	ret = system(cmdl);
	if (ret != 0) {
		return EINVAL;
	}
	return 0;
}

/*===========================================================================*
 *             run_cleanscript                                               *
 *===========================================================================*/
int run_cleanscript(struct devmand_usb_driver *drv)
{
	char cmdl[1024];
	cmdl[0] = 0;
	int ret;

	assert(drv->upscript);
	assert(drv->devprefix);

	snprintf(cmdl, 1024, "%s clean %s ",
		drv->upscript, drv->devprefix);
	dbg("Running Upscript:  \"%s\"", cmdl);
	ret = system(cmdl);

	if (ret != 0) {
		return EINVAL;
	}

	return 0;
}

/*===========================================================================*
 *             run_downscript                                                *
 *===========================================================================*/
int run_downscript(struct devmand_driver_instance *inst)
{
	char cmdl[1024];
	cmdl[0] = 0;
	int ret;

	assert(inst->drv->downscript);
	assert(inst->label);

	snprintf(cmdl, 1024, "%s down %s %d",
	    inst->drv->downscript, inst->label, inst->major);

	dbg("Running Upscript:  \"%s\"", cmdl);

	ret = system(cmdl);

	if (ret != 0) {
		return EINVAL;
	}

	return 0;
}

/*===========================================================================*
 *             stop_driver                                                   *
 *===========================================================================*/
int stop_driver(struct devmand_driver_instance *inst)
{
	char cmdl[1024];
	cmdl[0] = 0;
	int ret;

	assert(inst->label);

	snprintf(cmdl, 1024, "%s down %s %d",
	    SERVICE_BINARY, inst->label, inst->dev_id);
	dbg("executing service: \"%s\"", cmdl);
	ret = system(cmdl);
	if (ret != 0)
	{
		return EINVAL;
	}
	printf("Stopped driver %s with label %s for device %d.\n",
		inst->drv->binary, inst->label, inst->dev_id);

	return 0;
}

/*===========================================================================*
 *             start_driver                                                  *
 *===========================================================================*/
int start_driver(struct devmand_driver_instance *inst)
{
	char cmdl[1024];
	cmdl[0] = 0;
	int ret;

	/* generate label */
	ret = snprintf(inst->label, 32,  "%s%d", inst->drv->devprefix,
		inst->dev_id);
	if (ret < 0 || ret > DEVMAND_DRIVER_LABEL_LEN) {
		dbg("label too long");
		return ENOMEM;
	}

	assert(inst->drv->binary);
	assert(inst->label);

	snprintf(cmdl, 1024, "%s up %s  -major %d -devid %d -label %s",
	    SERVICE_BINARY, inst->drv->binary, inst->major, inst->dev_id,
		inst->label);
	dbg("executing service: \"%s\"", cmdl);

	ret = system(cmdl);

	if (ret != 0) {
		return EINVAL;
	}

	printf("Started driver %s with label %s for device %d.\n",
		inst->drv->binary, inst->label, inst->dev_id);

	return 0;
}

/*===========================================================================*
 *             find_instance                                                 *
 *===========================================================================*/
static struct devmand_driver_instance *
find_instance(int dev_id)
{
	struct devmand_driver_instance *inst;

	LIST_FOREACH(inst, &instances, list) {
		if (inst->dev_id == dev_id) {
			return inst;
		}
	}
	return NULL;
}

/*===========================================================================*
 *              match_usb_driver                                             *
 *===========================================================================*/
static int
match_usb_id(struct devmand_usb_match_id *mid, struct usb_device_id *id)
{
	int res = 1;
	unsigned long match = mid->match_flags;
	struct usb_device_id *_id = &mid->match_id;

	if (match & USB_MATCH_ID_VENDOR)
		if (id->idVendor != _id->idVendor) res = 0;
	if (match & USB_MATCH_ID_PRODUCT)
		if (id->idProduct != _id->idProduct) res = 0;
	if (match & USB_MATCH_BCD_DEVICE)
		if (id->bcdDevice != _id->bcdDevice) res = 0;
	if (match & USB_MATCH_DEVICE_PROTOCOL)
		if (id->bDeviceProtocol != _id->bDeviceProtocol) res = 0;
	if (match & USB_MATCH_DEVICE_SUBCLASS)
		if (id->bDeviceSubClass != _id->bDeviceSubClass) res = 0;
	if (match & USB_MATCH_DEVICE_PROTOCOL)
		if (id->bDeviceProtocol != _id->bDeviceProtocol) res = 0;
	if (match & USB_MATCH_INTERFACE_CLASS)
		if (id->bInterfaceClass != _id->bInterfaceClass) res = 0;
	if (match & USB_MATCH_INTERFACE_SUBCLASS)
		if (id->bInterfaceSubClass != _id->bInterfaceSubClass) res = 0;
	if (match & USB_MATCH_INTERFACE_PROTOCOL)
		if (id->bInterfaceProtocol != _id->bInterfaceProtocol) res = 0;

	if (match == 0UL) {
		res = 0;
	}

	return res;
}

/*===========================================================================*
 *              match_usb_driver                                             *
 *===========================================================================*/
static struct devmand_usb_driver*
match_usb_driver(struct usb_device_id *id)
{
	struct devmand_usb_driver *driver;
	struct devmand_usb_match_id *mid;

	LIST_FOREACH(driver, &drivers, list) {
		LIST_FOREACH(mid, &driver->ids, list) {
			if (match_usb_id(mid, id)) {
				return driver;
			}
		}
	}
	return NULL;
}

/*===========================================================================*
 *              add_usb_match_id                                             *
 *===========================================================================*/
struct devmand_usb_driver * add_usb_driver(char *name)
{
	struct devmand_usb_driver *udrv = (struct devmand_usb_driver*)
	    malloc(sizeof(struct devmand_usb_driver));

	LIST_INSERT_HEAD(&drivers, udrv, list);
	LIST_INIT(&udrv->ids);

	udrv->name = name;
	return udrv;
}

/*===========================================================================*
 *              add_usb_match_id                                             *
 *===========================================================================*/
struct devmand_usb_match_id *
add_usb_match_id
(struct devmand_usb_driver *drv)
{
	struct devmand_usb_match_id *id = (struct devmand_usb_match_id*)
	    malloc(sizeof(struct devmand_usb_match_id));

	memset(id, 0, sizeof(struct devmand_usb_match_id));

	LIST_INSERT_HEAD(&drv->ids, id, list);

	return id;
}

/*===========================================================================*
 *           parse_config                                                    *
 *===========================================================================*/
static void parse_config()
{
	int i, status, error;
	struct stat stats;
	char * dirname;

	DIR * dir;
	struct dirent entry;
	struct dirent *result;
	char config_file[PATH_MAX];

	dbg("Parsing configuration directories... ");
	/* Next parse the configuration directories */
	for(i=0; i < args.config_dir_count; i++){
		dirname = args.config_dirs[i];
		dbg("Parsing config dir %s ", dirname);
		status = stat(dirname,&stats);
		if (status == -1){
			error = errno;
			dbg("Failed to read directory '%s':%s (skipping) \n",
			    dirname,strerror(error));
			continue;
		}
		if (!S_ISDIR(stats.st_mode)){
			dbg("Parse configuration skipping %s "
			    "(not a directory) \n",dirname);
			continue;
		}
		dir = opendir(dirname);
		if (dir == NULL){
			error = errno;
			dbg("Parse configuration failed to read dir '%s'"
			    "(skipping) :%s\n",dirname, strerror(error));
			continue;
		}
		while( (status = readdir_r(dir,&entry,&result)) == 0 ){
			if (result == NULL){ /* last entry */
				closedir(dir);
				break;
			}

			/* concatenate dir and file name to open it */
			snprintf(config_file,PATH_MAX, "%s/%s",
				 dirname,entry.d_name);
			status = stat(config_file, &stats);
			if (status == -1){
				error = errno;
				dbg("Parse configuration Failed to stat file "
				    "'%s': %s (skipping)\n", config_file,
				    strerror(error));
			}
			if (S_ISREG(stats.st_mode)){
				dbg("Parsing file %s",config_file);
				yyin = fopen(config_file, "r");

				if (yyin < 0) {
					dbg("Can not open config file:"
				 	       " %d.\n", errno);
				}
				yyparse();
				dbg("Done.");
				fclose(yyin);
			}
		}
	}
	dbg("Parsing configuration directories done... ");

}

/*===========================================================================*
 *           cleanup                                                        *
 *===========================================================================*/
static void cleanup() {
	struct devmand_driver_instance *inst;
	/* destroy fifo */
	dbg("cleaning up... ");
	/* quit all running drivers */
	LIST_FOREACH(inst, &instances, list) {
		dbg("stopping driver %s", inst->label);
		if(inst->drv->downscript) {
			run_downscript (inst);
		}
		stop_driver(inst);
	}
	unlink("/var/run/devmand.pid");
}

static void sig_int(int sig) {
	dbg("devman: Received SIGINT... cleaning up.");
	_run = 0;
}

/*===========================================================================*
 *           create_pid_file                                                 *
 *===========================================================================*/
void create_pid_file()
{
	FILE *fd;

	fd = fopen("/var/run/devmand.pid", "r");
	if(fd) {
		fprintf(stderr, "devmand: /var/run/devmand.pid exists... "
		                "another devmand running?\n");
		fclose(fd);
		exit(1);
	} else {
		fd = fopen("/var/run/devmand.pid","w");
		fprintf(fd, "%d", getpid());
		fclose(fd);
	}
}

/*===========================================================================*
 *           main                                                            *
 *===========================================================================*/
int main(int argc, char *argv[])
{
	int opt, optindex;
	struct devmand_usb_driver *driver;

	/* get command line arguments */
	while ((opt = getopt_long(argc, argv, "d:p:vxh?", options, &optindex))
			!= -1) {
		switch (opt) {
			case 'd':/* config directory */
				if (args.config_dir_count >= MAX_CONFIG_DIRS){
				 	fprintf(stderr,"Parse arguments: Maximum"
					        " of %i configuration directories"
						" reached skipping directory '%s'\n"
						, MAX_CONFIG_DIRS, optarg);
				 	break;
				}
				args.config_dirs[args.config_dir_count] = optarg;
				args.config_dir_count++;
				break;
			case 'p': /* sysfs path */
				args.path = optarg;
				break;
			case 'v': /* verbose */
				args.verbose = 1;
				break;
			case 'x': /* check config */
				args.check_config = 1;
				break;
			case 'h': /* help */
			case '?': /* help */
			default:
				display_usage(argv[0]);
				return 0;
		}
	}

	/* is path set? */
	if (args.path == NULL) {
		args.path = "/sys/";
	}

	/* is the configuration directory set? */
	if (args.config_dir_count == 0) {
		dbg("Using default configuration directory");
		args.config_dirs[0] = "/etc/devmand";
		args.config_dir_count = 1;
	}

	/* If we only check the configuration run and exit imediately */
	if (args.check_config == 1){
		fprintf(stdout, "Only parsing configuration\n");
		parse_config();
		exit(0);
	}

	create_pid_file();

	parse_config();
	LIST_FOREACH(driver, &drivers, list) {
		if (driver->upscript) {
			run_cleanscript(driver);
		}
	}

	signal(SIGINT, sig_int);

	main_loop();

	cleanup();

	return 0;
}

/*===========================================================================*
 *           determine_type                                                  *
 *===========================================================================*/
static enum dev_type determine_type (char *path)
{
	FILE * fd;
	char *mypath;
	char buf[256];
	int res;

	mypath = (char *) calloc(1, strlen(path)+strlen(DEVMAN_TYPE_NAME)+1);

	if (mypath == NULL) {
		fprintf(stderr, "ERROR: out of mem\n");
		cleanup();
		exit(1);
	}

	strcat(mypath, path);
	strcat(mypath, DEVMAN_TYPE_NAME);

	fd = fopen(mypath, "r");
	free(mypath);

	if (fd == NULL) {
		fprintf(stderr, "WARN: could not open %s\n", mypath);
		return DEV_TYPE_UNKOWN;
	}

	res = fscanf(fd , "%s\n", buf);
	fclose(fd);

	if (res != 1) {
		fprintf(stderr, "WARN: could not parse %s\n", mypath);
		return DEV_TYPE_UNKOWN;
	}

	if (strcmp(buf, "USB_DEV") == 0) {
		return DEV_TYPE_USB_DEVICE;
	} else if (strcmp(buf, "USB_INTF") == 0) {
		return DEV_TYPE_USB_INTF;
	}

	return  DEV_TYPE_UNKOWN;
}

/*===========================================================================*
 *           read_hex_uint                                                   *
 *===========================================================================*/
static int read_hex_uint(char *base_path, char *name, unsigned int* val )
{
	char my_path[PATH_LEN];
	FILE *fd;
	memset(my_path,0,PATH_LEN);
	int ret = 0;

	strcat(my_path, base_path);
	strcat(my_path, name);

	fd = fopen(my_path, "r");

	if (fd == NULL) {
		fprintf(stderr, "WARN: could not open %s\n", my_path);
		return EEXIST;
	} else	if (fscanf(fd, "0x%x\n", val ) != 1) {
		fprintf(stderr, "WARN: could not parse %s\n", my_path);
		ret = EINVAL;
	}
	fclose(fd);

	return ret;
}

/*===========================================================================*
 *               get_major                                                   *
 *===========================================================================*/
static int get_major() {
	int i, ret = args.major_offset;

	for (i=0; i < 16; i++) {
		int j;
		for (j = 0; j < 8; j++ ) {
			if ((major_bitmap[i] & (1 << j))) {
				major_bitmap[i] &= !(1 << j);
				return ret;
			}
			ret++;
		}
	}
	return INVAL_MAJOR;
}

/*===========================================================================*
 *               put_major                                                   *
 *===========================================================================*/
static void put_major(int major) {
	int i;
	major -= args.major_offset;
	assert(major >= 0);

	for (i=0; i < 16; i++) {
		int j;
		for (j = 0; j < 8; j++ ) {
			if (major==0) {
				assert(!(major_bitmap[i] & (1 <<j)));
				major_bitmap[i] |= (1 << j);
				return;
			}
			major--;
		}
	}
}

/*===========================================================================*
 *          generate_usb_device_id                                           *
 *===========================================================================*/
static struct usb_device_id *
generate_usb_device_id(char * path, int is_interface)
{
	struct usb_device_id *ret;
	int res;
	unsigned int val;

	ret = (struct usb_device_id *)
	    calloc(1,sizeof (struct usb_device_id));

	if (is_interface) {

		res = read_hex_uint(path, "../idVendor", &val);
		if (res) goto err;
		ret->idVendor = val;

		res = read_hex_uint(path, "../idProduct", &val);
		if (res) goto err;
		ret->idProduct = val;
#if 0
		res = read_hex_uint(path, "../bcdDevice", &val);
		if (res) goto err;
		ret->bcdDevice = val;
#endif
		res = read_hex_uint(path, "../bDeviceClass", &val);
		if (res) goto err;
		ret->bDeviceClass = val;

		res = read_hex_uint(path, "../bDeviceSubClass", &val);
		if (res) goto err;
		ret->bDeviceSubClass = val;

		res = read_hex_uint(path, "../bDeviceProtocol", &val);
		if (res) goto err;
		ret->bDeviceProtocol = val;

		res = read_hex_uint(path, "/bInterfaceClass", &val);
		if (res) goto err;
		ret->bInterfaceClass = val;

		res = read_hex_uint(path, "/bInterfaceSubClass", &val);
		if (res) goto err;
		ret->bInterfaceSubClass = val;

		res = read_hex_uint(path, "/bInterfaceProtocol", &val);
		if (res) goto err;
		ret->bInterfaceProtocol = val;
	}

	return ret;

err:
	free(ret);
	return NULL;
}

/*===========================================================================*
 *            usb_intf_add_even                                              *
 *===========================================================================*/
static void usb_intf_add_event(char *path, int dev_id)
{
	struct usb_device_id *id;
	struct devmand_usb_driver *drv;
	struct devmand_driver_instance *drv_inst;
	int major, ret;

	/* generate usb_match_id */
	id = generate_usb_device_id(path,TRUE);
	if (id == NULL) {
		fprintf(stderr, "WARN: could not create usb_device id...\n"
		                "      ommiting event\n");
		free(id);
		return;
	}

	/* find suitable driver */
	drv = match_usb_driver(id);
	free (id);

	if (drv == NULL) {
		dbg("INFO: could not find a suitable driver for %s", path);
		return;
	}

	/* create instance */
	drv_inst = (struct devmand_driver_instance *)
	    calloc(1,sizeof(struct devmand_driver_instance));

	if (drv_inst == NULL) {
		fprintf(stderr, "ERROR: out of memory");
		return; /* maybe better quit here. */
	}

	/* allocate inode number, if device files needed */
	major = get_major();
	if (major == INVAL_MAJOR) {
		fprintf(stderr, "WARN: ran out of major numbers\n"
		                "      cannot start driver %s for %s\n",
							   drv->name, path);
		return;
	}

	drv_inst->major  = major;
	drv_inst->drv    = drv;
	drv_inst->dev_id = dev_id;

	/* start driver (invoke service) */
	start_driver(drv_inst);

	/*
	 * run the up action
	 *
	 * An up action can be any executable. Before running it devmand
	 * will set certain environment variables so the script can configure
	 * the device (or generate device files, etc). See up_action() for that.
	 */
	if (drv->upscript) {
		ret = run_upscript(drv_inst);
		if (ret) {
			stop_driver(drv_inst);
			fprintf(stderr, "devmand: warning, could not run up_action\n");
			free(drv_inst);
			return;
		}
	}

	LIST_INSERT_HEAD(&instances,drv_inst,list);
}

/*===========================================================================*
 *            usb_intf_remove_event                                          *
 *===========================================================================*/
static void usb_intf_remove_event(char *path, int dev_id)
{
	struct devmand_driver_instance *inst;
	struct devmand_usb_driver *drv;
	int ret;

	/* find the driver instance */
	inst = find_instance(dev_id);

	if (inst == NULL) {
		dbg("No driver running for id: %d", dev_id);
		return;
	}
	drv = inst->drv;

	/* run the down script */
	if (drv->downscript) {
		ret = run_downscript(inst);
		if (ret) {
			fprintf(stderr, "WARN: error running up_action");
		}
	}

	/* stop the driver */
	stop_driver(inst);

	/* free major */
	put_major(inst->major);

	/* free instance */
	LIST_REMOVE(inst,list);
	free(inst);
}

/*===========================================================================*
 *           handle_event                                                    *
 *===========================================================================*/
static void handle_event(char *event)
{
	enum dev_type type;
	char path[PATH_LEN];
	char tmp_path[PATH_LEN];
	int dev_id, res;

	path[0]=0;

	if (strncmp("ADD ", event, 4) == 0) {

		/* read data from event */
		res = sscanf(event, "ADD %s 0x%x", tmp_path, &dev_id);

		if (res != 2) {
			fprintf(stderr, "WARN: could not parse event: %s", event);
			fprintf(stderr, "WARN: omitting event: %s", event);
		}

		strcpy(path, args.path);
		strcat(path, tmp_path);

		/* what kind of device is added? */
		type = determine_type(path);

		switch (type) {
			case DEV_TYPE_USB_DEVICE:
				dbg("USB device added: ommited....");
				/* ommit usb devices for now */
				break;
			case DEV_TYPE_USB_INTF:
				dbg("USB interface added: (%s, devid: = %d)",path, dev_id);
				usb_intf_add_event(path, dev_id);
				return;
			default:
				dbg("default");
				fprintf(stderr, "WARN: ommiting event\n");
		}
	} else if (strncmp("REMOVE ", event, 7) == 0) {

		/* read data from event */
		res = sscanf(event,"REMOVE %s 0x%x", tmp_path, &dev_id);

		if (res != 2) {
			fprintf(stderr, "WARN: could not parse event: %s", event);
			fprintf(stderr, "WARN: omitting event: %s", event);
		}

		usb_intf_remove_event(path, dev_id);

#if 0
		strcpy(path, args.path);
		strcat(path, tmp_path);

		/* what kind of device is added? */
		type = determine_type(path);

		switch (type) {
			case DEV_TYPE_USB_DEVICE:
				/* ommit usb devices for now */
				break;
			case DEV_TYPE_USB_INTF:
				usb_intf_remove_event(path, dev_id);
				return;
			default:
				fprintf(stderr, "WARN: ommiting event\n");
		}
#endif

	}
}

/*===========================================================================*
 *           main_loop                                                       *
 *===========================================================================*/
static void main_loop()
{
	char ev_path[128];
	char buf[256];
	int len;
	FILE* fd;
	len = strlen(args.path);

	/* init major numbers */

	memset(&major_bitmap, 0xff, 16);

	if (len > 128 - 7 /*len of "events" */) {
		fprintf(stderr, "pathname to long\n");
		cleanup();
		exit(1);
	}

	strcpy(ev_path, args.path);
	strcat(ev_path, "events");

	while (_run) {

		char *res;

		fd = fopen(ev_path, "r");
		if (fd == NULL) {
			/*
			 * ENFILE is a temporary failure, often caused by
			 * running the test set.  Don't die from that..
			 */
			if (errno == ENFILE) {
				usleep(50000);
				continue;
			}

			fprintf(stderr,"devmand error: could not open event "
				"file %s bailing out\n", ev_path);
			cleanup();
			exit(1);
		}

		res = fgets(buf, 256, fd);
		fclose(fd);

		if (res == NULL) {
			usleep(50000);
			continue;
		}
		dbg("handle_event:  %s", buf);
		handle_event(buf);
	}
}

/*===========================================================================*
 *           display_usage                                                   *
 *===========================================================================*/
static void display_usage(const char *name)
{
	printf("Usage: %s [{-p|--pathname} PATH_TO_SYS}"
	       " [{-d|--config-dir} CONFIG_DIR] [-v|--verbose]"
	       " [[x||--check-config]\n", name);
}


text:
package dnars.siebog.agents;

import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateful;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import siebog.SiebogClient;
import siebog.agents.Agent;
import siebog.agents.AgentBuilder;
import siebog.agents.AgentInitArgs;
import siebog.interaction.ACLMessage;
import dnars.base.Statement;
import dnars.siebog.DNarsAgent;
import dnars.siebog.annotations.BeliefAdded;
import dnars.siebog.annotations.BeliefUpdated;
import dnars.siebog.annotations.Beliefs;
import dnars.siebog.annotations.Domain;

@Stateful
@Remote(Agent.class)
// knowledge domain for this agent is Hello
@Domain(name = "Hello")
public class HelloDNars extends DNarsAgent {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HelloDNars.class);

	@Override
	protected void doInit(AgentInitArgs args) {
	}

	@Beliefs
	public String[] initialBeliefs() { // set of initial beliefs
		return new String[] { "tiger -> animal (1.0, 0.9)" };
	}

	@BeliefAdded
	public void anyBeliefAdded(List<Statement> beliefs) {
		LOG.info("anyBeliefAdded: {}", beliefs);
	}

	@BeliefAdded(subj = "tiger", copula = "->", pred = "animal")
	public void tigerIsTypeOfAnimal(List<Statement> beliefs) {
		LOG.info("tiger is a type of animal: {}", beliefs);
		// this will change the belief's truth-value, which in turn will invoke the next method
		graph().include(beliefs.toArray(new Statement[0]));
	}

	@BeliefUpdated
	public void anyBeliefUpdated(List<Statement> beliefs) {
		LOG.info("anyBeliefUpdated: {}", beliefs);
	}

	@Override
	protected void onAclMessage(ACLMessage msg) {
	}

	public static void main(String[] args) {
		SiebogClient.connect("localhost");
		AgentBuilder.module("dnars-web").ejb(HelloDNars.class).randomName().start();
	}
}


text:
/*
 * ==================================================================================
 *
 *          Filename: httpresponse.h
 *
 *       Description:
 *
 *            Verson: 1.0
 *           Created: 2016-03-12
 *          Compiler: g++
 *
 *            Author: Jiewei Wei <weijieweijerry@163.com>
 *           Company: Sun Yat-sen University
 *
 * ==================================================================================
 */

#ifndef __LNET_HTTPRESPONSE_H__
#define __LNET_HTTPRESPONSE_H__

#include "lnethttp.h"

LNET_NAMESPACE_BEGIN

class HttpResponse {
public:
    HttpResponse();
    HttpResponse(int code, const Headers &headers = Headers(), const std::string &pbody = "");
    ~HttpResponse();

    void clear() {
        code = 200;
        body.clear();
        headers.clear();
    }

    void setContentType(const std::string &contentType);
    void setKeepAlive(bool on = true);
    void enableDate();
    std::string dump();

    int code;
    Headers headers;
    std::string body;

}; /* end of class HttpResponse */

LNET_NAMESPACE_END

#endif /* end of define __LNET_HTTPRESPONSE_H__ */


text:
package org.pipservices.commons.refer;

import org.pipservices.commons.errors.ConfigException;

/**
 * Interface for components that requires references to other components
 */
public interface IReferenceable {
	/**
	 * Sets references to other components.
	 * Using locators the component can find required dependencies
	 * @param references component references
	 * @throws ConfigException
	 */
	void setReferences(IReferences references) throws ReferenceException, ConfigException;
}


text:
<?php

// no direct access
defined('_JEXEC') or die;

JHtml::_('behavior.keepalive');
?>
<form action="<?php echo JRoute::_('index.php', true, $params->get('usesecure')); ?>" method="post" id="login-form">
<?php if ($params->get('greeting')) : ?>

	<?php if ($params->get('name') == 0) : ?>
		<?php echo JText::sprintf('MOD_LOGIN_HINAME', htmlspecialchars($user->get('name'), ENT_COMPAT, 'UTF-8')); ?>
	<?php else : ?>
	 	<?php echo JText::sprintf('MOD_LOGIN_HINAME', htmlspecialchars($user->get('username'), ENT_COMPAT, 'UTF-8')); ?>
	<?php endif; ?>

<?php endif; ?>

	<input type="submit" name="Submit" class="button" value="<?php echo JText::_('JLOGOUT'); ?>" />
	<input type="hidden" name="option" value="com_users" />
	<input type="hidden" name="task" value="user.logout" />
	<input type="hidden" name="return" value="<?php echo $return; ?>" />
	<?php echo JHtml::_('form.token'); ?>

</form>


text:
import * as React from 'react';

declare module 'primereact/inplace' {

    interface ToggleParams {
        originalEvent: React.SyntheticEvent;
        value: boolean;
    }
    export interface InplaceProps {
        style?: object;
        className?: string;
        active?: boolean;
        closable?: boolean;
        disabled?: boolean;
        tabIndex?: number;
        ariaLabel?: string;
        onOpen?(event: React.MouseEvent<HTMLElement>): void;
        onClose?(event: React.MouseEvent<HTMLElement>): void;
        onToggle?(e: ToggleParams): void;
    }

    export class Inplace extends React.Component<InplaceProps, any> { }
}

// tslint:disable-next-line:max-classes-per-file
export declare class InplaceDisplay extends React.Component { }

// tslint:disable-next-line:max-classes-per-file
export declare class InplaceContent extends React.Component { }


text:
"""Function namespace."""
from __future__ import absolute_import

import sys
import ctypes
from .base import _LIB, check_call, py_str, c_str, string_types, _FFI_MODE
from . import vmobj as _vmobj

IMPORT_EXCEPT = RuntimeError if _FFI_MODE == "cython" else ImportError

try:
    # pylint: disable=wrong-import-position
    if _FFI_MODE == "ctypes":
        raise ImportError()
    if sys.version_info >= (3, 0):
        from ._cy3.core import _set_class_function, _set_class_module
        from ._cy3.core import FunctionBase as _FunctionBase
        from ._cy3.core import convert_to_tvm_func
    else:
        from ._cy2.core import _set_class_function, _set_class_module
        from ._cy2.core import FunctionBase as _FunctionBase
        from ._cy2.core import convert_to_tvm_func
except IMPORT_EXCEPT:
    # pylint: disable=wrong-import-position
    from ._ctypes.function import _set_class_function, _set_class_module
    from ._ctypes.function import FunctionBase as _FunctionBase
    from ._ctypes.function import convert_to_tvm_func

FunctionHandle = ctypes.c_void_p

class Function(_FunctionBase):
    """The PackedFunc object used in TVM.

    Function plays an key role to bridge front and backend in TVM.
    Function provide a type-erased interface, you can call function with positional arguments.

    The compiled module returns Function.
    TVM backend also registers and exposes its API as Functions.
    For example, the developer function exposed in tvm.ir_pass are actually
    C++ functions that are registered as PackedFunc

    The following are list of common usage scenario of tvm.Function.

    - Automatic exposure of C++ API into python
    - To call PackedFunc from python side
    - To call python callbacks to inspect results in generated code
    - Bring python hook into C++ backend

    See Also
    --------
    tvm.register_func: How to register global function.
    tvm.get_global_func: How to get global function.
    """

class ModuleBase(object):
    """Base class for module"""
    __slots__ = ["handle", "_entry", "entry_name"]

    def __init__(self, handle):
        self.handle = handle
        self._entry = None
        self.entry_name = "__tvm_main__"

    def __del__(self):
        check_call(_LIB.TVMModFree(self.handle))

    @property
    def entry_func(self):
        """Get the entry function

        Returns
        -------
        f : Function
            The entry function if exist
        """
        if self._entry:
            return self._entry
        self._entry = self.get_function(self.entry_name)
        return self._entry

    def get_function(self, name, query_imports=False):
        """Get function from the module.

        Parameters
        ----------
        name : str
            The name of the function

        query_imports : bool
            Whether also query modules imported by this module.

        Returns
        -------
        f : Function
            The result function.
        """
        ret_handle = FunctionHandle()
        check_call(_LIB.TVMModGetFunction(
            self.handle, c_str(name),
            ctypes.c_int(query_imports),
            ctypes.byref(ret_handle)))
        if not ret_handle.value:
            raise AttributeError(
                "Module has no function '%s'" %  name)
        return Function(ret_handle, False)

    def import_module(self, module):
        """Add module to the import list of current one.

        Parameters
        ----------
        module : Module
            The other module.
        """
        check_call(_LIB.TVMModImport(self.handle, module.handle))

    def __getitem__(self, name):
        if not isinstance(name, string_types):
            raise ValueError("Can only take string as function name")
        return self.get_function(name)

    def __call__(self, *args):
        if self._entry:
            return self._entry(*args)
        f = self.entry_func
        return f(*args)

def register_func(func_name, f=None, override=False):
    """Register global function

    Parameters
    ----------
    func_name : str or function
        The function name

    f : function, optional
        The function to be registered.

    override: boolean optional
        Whether override existing entry.

    Returns
    -------
    fregister : function
        Register function if f is not specified.

    Examples
    --------
    The following code registers my_packed_func as global function.
    Note that we simply get it back from global function table to invoke
    it from python side. However, we can also invoke the same function
    from C++ backend, or in the compiled TVM code.

    .. code-block:: python

      targs = (10, 10.0, "hello")
      @tvm.register_func
      def my_packed_func(*args):
          assert(tuple(args) == targs)
          return 10
      # Get it out from global function table
      f = tvm.get_global_func("my_packed_func")
      assert isinstance(f, tvm.nd.Function)
      y = f(*targs)
      assert y == 10
    """
    if callable(func_name):
        f = func_name
        func_name = f.__name__

    if not isinstance(func_name, str):
        raise ValueError("expect string function name")

    ioverride = ctypes.c_int(override)
    def register(myf):
        """internal register function"""
        if not isinstance(myf, Function):
            myf = convert_to_tvm_func(myf)
        check_call(_LIB.TVMFuncRegisterGlobal(
            c_str(func_name), myf.handle, ioverride))
        return myf
    if f:
        return register(f)
    return register

def get_global_func(name, allow_missing=False):
    """Get a global function by name

    Parameters
    ----------
    name : str
        The name of the global function

    allow_missing : bool
        Whether allow missing function or raise an error.

    Returns
    -------
    func : tvm.Function
        The function to be returned, None if function is missing.
    """
    handle = FunctionHandle()
    check_call(_LIB.TVMFuncGetGlobal(c_str(name), ctypes.byref(handle)))
    if handle.value:
        return Function(handle, False)

    if allow_missing:
        return None

    raise ValueError("Cannot find global function %s" % name)

def list_global_func_names():
    """Get list of global functions registered.

    Returns
    -------
    names : list
       List of global functions names.
    """
    plist = ctypes.POINTER(ctypes.c_char_p)()
    size = ctypes.c_uint()

    check_call(_LIB.TVMFuncListGlobalNames(ctypes.byref(size),
                                           ctypes.byref(plist)))
    fnames = []
    for i in range(size.value):
        fnames.append(py_str(plist[i]))
    return fnames

def extract_ext_funcs(finit):
    """
    Extract the extension PackedFuncs from a C module.

    Parameters
    ----------
    finit : ctypes function
        a ctypes that takes signature of TVMExtensionDeclarer

    Returns
    -------
    fdict : dict of str to Function
        The extracted functions
    """
    fdict = {}
    def _list(name, func):
        fdict[name] = func
    myf = convert_to_tvm_func(_list)
    ret = finit(myf.handle)
    _ = myf
    if ret != 0:
        raise RuntimeError("cannot initialize with %s" % finit)
    return fdict

def _get_api(f):
    flocal = f
    flocal.is_global = True
    return flocal

def _init_api(namespace, target_module_name=None):
    """Initialize api for a given module name

    namespace : str
       The namespace of the source registry

    target_module_name : str
       The target module name if different from namespace
    """
    target_module_name = (
        target_module_name if target_module_name else namespace)
    if namespace.startswith("tvm."):
        _init_api_prefix(target_module_name, namespace[4:])
    else:
        _init_api_prefix(target_module_name, namespace)

def _init_api_prefix(module_name, prefix):
    module = sys.modules[module_name]

    for name in list_global_func_names():
        if prefix == "api":
            fname = name
            if name.startswith("_"):
                target_module = sys.modules["tvm._api_internal"]
            else:
                target_module = module
        else:
            if not name.startswith(prefix):
                continue
            fname = name[len(prefix)+1:]
            target_module = module

        if fname.find(".") != -1:
            continue
        f = get_global_func(name)
        ff = _get_api(f)
        ff.__name__ = fname
        ff.__doc__ = ("TVM PackedFunc %s. " % fname)
        setattr(target_module, ff.__name__, ff)

_set_class_function(Function)


text:
@protocol ToolbarUI<NSObject>

// The minimum height of the toolbar relative to the browser content area.
// This should be broadcast using |-broadcastCollapsedToolbarHeight:|.
@property(nonatomic, readonly) CGFloat collapsedHeight;

// The minimum height of the toolbar relative to the browser content area.
// This should be broadcast using |-broadcastExpandedToolbarHeight:|.
@property(nonatomic, readonly) CGFloat expandedHeight;

// The height of the bottom toolbar relative to the browser content area.
// This should be broadcast using |-broadcastBottomToolbarHeight:|.
@property(nonatomic, readonly) CGFloat bottomToolbarHeight;

@end

// Simple implementation of ToolbarUI that allows readwrite access to broadcast
// properties.
@interface ToolbarUIState : NSObject<ToolbarUI>

// Redefine properties as readwrite.
@property(nonatomic, assign) CGFloat collapsedHeight;
@property(nonatomic, assign) CGFloat expandedHeight;
@property(nonatomic, assign) CGFloat bottomToolbarHeight;

@end

#endif  // IOS_CHROME_BROWSER_UI_TOOLBAR_FULLSCREEN_TOOLBAR_UI_H_


text:
package com.planet_ink.coffee_mud.core.intermud.cm1.commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.intermud.cm1.RequestHandler;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.io.*;
import java.util.concurrent.atomic.*;

public class MUDInfo extends CM1Command
{
	@Override public String getCommandWord(){ return "MUDINFO";}
	public MUDInfo(RequestHandler req, String parameters)
	{
		super(req, parameters);
	}

	@Override
	public void run()
	{
		try
		{
			if((parameters.length()==0)||(parameters.equalsIgnoreCase("STATUS")))
				req.sendMsg("[OK "+CMProps.getVar(CMProps.Str.MUDSTATUS)+"]");
			else
			if(parameters.equalsIgnoreCase("PORTS"))
				req.sendMsg("[OK "+CMProps.getVar(CMProps.Str.MUDPORTS)+"]");
			else
			if(parameters.equalsIgnoreCase("VERSION"))
				req.sendMsg("[OK "+CMProps.getVar(CMProps.Str.MUDVER)+"]");
			else
			if(parameters.equalsIgnoreCase("DOMAIN"))
				req.sendMsg("[OK "+CMProps.getVar(CMProps.Str.MUDDOMAIN)+"]");
			else
			if(parameters.equalsIgnoreCase("NAME"))
				req.sendMsg("[OK "+CMProps.getVar(CMProps.Str.MUDNAME)+"]");
			else
				req.sendMsg("[FAIL "+getHelp(req.getUser(), null, null)+"]");
		}
		catch(final java.io.IOException ioe)
		{
			Log.errOut(className,ioe);
			req.close();
		}
	}
	@Override public boolean passesSecurityCheck(MOB user, PhysicalAgent target){return true;}
	@Override
	public String getHelp(MOB user, PhysicalAgent target, String rest)
	{
		return "USAGE: MUDINFO STATUS, PORTS, VERSION, DOMAIN, NAME";
	}
}


text:
Class PriorityPrinter implements the example of the dynamic priority printer. (Each group of users gets assigned some priority. This priority may be reassigned dynamically).
Note that method updatePriorityOf:to: has no method body. It is pure synchronization.
See associated activity class PriorityPrinterActivity.

This solution has been initially described in the report on Synchronization Variables (see class InvocationActivity comment).


text:
namespace osquery {

const std::string kRealTestPath = "/tmp/osquery-inotify-trigger";
const std::string kRealTestDir = "/tmp/osquery-inotify-triggers";
const std::string kRealTestDirPath = "/tmp/osquery-inotify-triggers/1";
const std::string kRealTestSubDir = "/tmp/osquery-inotify-triggers/2";
const std::string kRealTestSubDirPath = "/tmp/osquery-inotify-triggers/2/1";

int kMaxEventLatency = 3000;

class INotifyTests : public testing::Test {
 protected:
  void TearDown() {
    EventFactory::deregisterEventPublishers();
    boost::filesystem::remove_all(kRealTestPath);
    boost::filesystem::remove_all(kRealTestDir);
  }

  void StartEventLoop() {
    event_pub_ = std::make_shared<INotifyEventPublisher>();
    EventFactory::registerEventPublisher(event_pub_);
    FILE* fd = fopen(kRealTestPath.c_str(), "w");
    fclose(fd);

    temp_thread_ = boost::thread(EventFactory::run, "INotifyEventPublisher");
  }

  void SubscriptionAction(const std::string& path,
                          uint32_t mask = 0,
                          EventCallback ec = 0) {
    auto mc = std::make_shared<INotifySubscriptionContext>();
    mc->path = path;
    mc->mask = mask;

    EventFactory::addSubscription("INotifyEventPublisher", mc, ec);
  }

  bool WaitForEvents(int max, int num_events = 0) {
    int delay = 0;
    while (delay <= max * 1000) {
      if (num_events > 0 && event_pub_->numEvents() >= num_events) {
        return true;
      } else if (num_events == 0 && event_pub_->numEvents() > 0) {
        return true;
      }
      delay += 50;
      ::usleep(50);
    }
    return false;
  }

  void TriggerEvent(const std::string& path) {
    FILE* fd = fopen(path.c_str(), "w");
    fputs("inotify", fd);
    fclose(fd);
  }

  void EndEventLoop() {
    EventFactory::end();
    event_pub_->tearDown();
    temp_thread_.join();
    EventFactory::end(false);
  }

  std::shared_ptr<INotifyEventPublisher> event_pub_;
  boost::thread temp_thread_;
};

TEST_F(INotifyTests, test_register_event_pub) {
  auto status = EventFactory::registerEventPublisher<INotifyEventPublisher>();
  EXPECT_TRUE(status.ok());

  // Make sure only one event type exists
  EXPECT_EQ(EventFactory::numEventPublishers(), 1);
}

TEST_F(INotifyTests, test_inotify_init) {
  // Handle should not be initialized during ctor.
  auto event_pub = std::make_shared<INotifyEventPublisher>();
  EXPECT_FALSE(event_pub->isHandleOpen());

  // Registering the event type initializes inotify.
  EventFactory::registerEventPublisher(event_pub);
  EXPECT_TRUE(event_pub->isHandleOpen());

  // Similarly deregistering closes the handle.
  EventFactory::deregisterEventPublishers();
  EXPECT_FALSE(event_pub->isHandleOpen());
}

TEST_F(INotifyTests, test_inotify_add_subscription_missing_path) {
  EventFactory::registerEventPublisher<INotifyEventPublisher>();

  // This subscription path is fake, and will succeed.
  auto mc = std::make_shared<INotifySubscriptionContext>();
  mc->path = "/this/path/is/fake";

  auto subscription = Subscription::create(mc);
  auto status =
      EventFactory::addSubscription("INotifyEventPublisher", subscription);
  EXPECT_TRUE(status.ok());
}

TEST_F(INotifyTests, test_inotify_add_subscription_success) {
  EventFactory::registerEventPublisher<INotifyEventPublisher>();

  // This subscription path *should* be real.
  auto mc = std::make_shared<INotifySubscriptionContext>();
  mc->path = "/";

  auto subscription = Subscription::create(mc);
  auto status =
      EventFactory::addSubscription("INotifyEventPublisher", subscription);
  EXPECT_TRUE(status.ok());
}

TEST_F(INotifyTests, test_inotify_run) {
  // Assume event type is registered.
  event_pub_ = std::make_shared<INotifyEventPublisher>();
  EventFactory::registerEventPublisher(event_pub_);

  // Create a temporary file to watch, open writeable
  FILE* fd = fopen(kRealTestPath.c_str(), "w");

  // Create a subscriptioning context
  auto mc = std::make_shared<INotifySubscriptionContext>();
  mc->path = kRealTestPath;
  EventFactory::addSubscription("INotifyEventPublisher",
                                Subscription::create(mc));

  // Create an event loop thread (similar to main)
  boost::thread temp_thread(EventFactory::run, "INotifyEventPublisher");
  EXPECT_TRUE(event_pub_->numEvents() == 0);

  // Cause an inotify event by writing to the watched path.
  fputs("inotify", fd);
  fclose(fd);

  // Wait for the thread's run loop to select.
  WaitForEvents(kMaxEventLatency);
  EXPECT_TRUE(event_pub_->numEvents() > 0);

  // Cause the thread to tear down.
  EventFactory::end();
  temp_thread.join();
  // Reset the event factory state.
  EventFactory::end(false);
}

class TestINotifyEventSubscriber : public EventSubscriber {
  DECLARE_EVENTSUBSCRIBER(TestINotifyEventSubscriber, INotifyEventPublisher);
  DECLARE_CALLBACK(SimpleCallback, INotifyEventContext);
  DECLARE_CALLBACK(Callback, INotifyEventContext);

 public:
  void init() { callback_count_ = 0; }
  Status SimpleCallback(const INotifyEventContextRef ec) {
    callback_count_ += 1;
    return Status(0, "OK");
  }

  Status Callback(const INotifyEventContextRef ec) {
    Row r;
    r["action"] = ec->action;
    r["path"] = ec->path;

    // Normally would call Add here.
    actions_.push_back(ec->action);
    callback_count_ += 1;
    return Status(0, "OK");
  }

  static void WaitForEvents(int max, int num_events = 1) {
    int delay = 0;
    while (delay < max * 1000) {
      if (getInstance()->callback_count_ >= num_events) {
        return;
      }
      ::usleep(50);
      delay += 50;
    }
  }

  static std::vector<std::string> actions() { return getInstance()->actions_; }

  static int count() { return getInstance()->callback_count_; }

 public:
  int callback_count_;
  std::vector<std::string> actions_;
};

TEST_F(INotifyTests, test_inotify_fire_event) {
  // Assume event type is registered.
  StartEventLoop();
  TestINotifyEventSubscriber::getInstance()->init();

  // Create a subscriptioning context, note the added Event to the symbol
  SubscriptionAction(
      kRealTestPath, 0, TestINotifyEventSubscriber::EventSimpleCallback);
  TriggerEvent(kRealTestPath);

  TestINotifyEventSubscriber::WaitForEvents(kMaxEventLatency);

  // Make sure our expected event fired (aka subscription callback was called).
  EXPECT_TRUE(TestINotifyEventSubscriber::count() > 0);

  // Cause the thread to tear down.
  EndEventLoop();
}

TEST_F(INotifyTests, test_inotify_event_action) {
  // Assume event type is registered.
  StartEventLoop();
  TestINotifyEventSubscriber::getInstance()->init();

  SubscriptionAction(
      kRealTestPath, 0, TestINotifyEventSubscriber::EventCallback);
  TriggerEvent(kRealTestPath);

  TestINotifyEventSubscriber::WaitForEvents(kMaxEventLatency, 4);

  // Make sure the inotify action was expected.
  EXPECT_EQ(TestINotifyEventSubscriber::actions().size(), 4);
  EXPECT_EQ(TestINotifyEventSubscriber::actions()[0], "UPDATED");
  EXPECT_EQ(TestINotifyEventSubscriber::actions()[1], "OPENED");
  EXPECT_EQ(TestINotifyEventSubscriber::actions()[2], "UPDATED");
  EXPECT_EQ(TestINotifyEventSubscriber::actions()[3], "UPDATED");

  // Cause the thread to tear down.
  EndEventLoop();
}

TEST_F(INotifyTests, test_inotify_optimization) {
  // Assume event type is registered.
  StartEventLoop();

  boost::filesystem::create_directory(kRealTestDir);

  // Adding a descriptor to a directory will monitor files within.
  SubscriptionAction(kRealTestDir);
  EXPECT_TRUE(event_pub_->isPathMonitored(kRealTestDirPath));

  // Adding a subscription to a file within a monitored directory is fine
  // but this will NOT cause an additional INotify watch.
  SubscriptionAction(kRealTestDirPath);
  EXPECT_EQ(event_pub_->numDescriptors(), 1);

  // Cause the thread to tear down.
  EndEventLoop();
}

TEST_F(INotifyTests, test_inotify_recursion) {
  StartEventLoop();
  TestINotifyEventSubscriber::getInstance()->init();

  boost::filesystem::create_directory(kRealTestDir);
  boost::filesystem::create_directory(kRealTestSubDir);

  // Subscribe to the directory inode
  auto mc = std::make_shared<INotifySubscriptionContext>();
  mc->path = kRealTestDir;
  mc->recursive = true;

  EventFactory::addSubscription(
      "INotifyEventPublisher", mc, TestINotifyEventSubscriber::EventCallback);
  // Trigger on a subdirectory's file.
  TriggerEvent(kRealTestSubDirPath);

  TestINotifyEventSubscriber::WaitForEvents(kMaxEventLatency, 1);
  EXPECT_TRUE(TestINotifyEventSubscriber::count() > 0);

  EndEventLoop();
}
}

int main(int argc, char* argv[]) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
#include "TokenSource.h"
#include "CharStream.h"
#include "Recognizer.h"
#include "Vocabulary.h"

#include "misc/Interval.h"

#include "support/CPPUtils.h"
#include "support/StringUtils.h"

#include "CommonToken.h"

using namespace antlr4;
using namespace antlr4::misc;

using namespace antlrcpp;

const std::pair<TokenSource*, CharStream*> CommonToken::EMPTY_SOURCE;

CommonToken::CommonToken(size_t type) {
  InitializeInstanceFields();
  _type = type;
}

CommonToken::CommonToken(std::pair<TokenSource*, CharStream*> source, size_t type, size_t channel, size_t start, size_t stop) {
  InitializeInstanceFields();
  _source = source;
  _type = type;
  _channel = channel;
  _start = start;
  _stop = stop;
  if (_source.first != nullptr) {
    _line = static_cast<int>(source.first->getLine());
    _charPositionInLine = source.first->getCharPositionInLine();
  }
}

CommonToken::CommonToken(size_t type, const std::string &text) {
  InitializeInstanceFields();
  _type = type;
  _channel = DEFAULT_CHANNEL;
  _text = text;
  _source = EMPTY_SOURCE;
}

CommonToken::CommonToken(Token *oldToken) {
  InitializeInstanceFields();
  _type = oldToken->getType();
  _line = oldToken->getLine();
  _index = oldToken->getTokenIndex();
  _charPositionInLine = oldToken->getCharPositionInLine();
  _channel = oldToken->getChannel();
  _start = oldToken->getStartIndex();
  _stop = oldToken->getStopIndex();

  if (is<CommonToken *>(oldToken)) {
    _text = (static_cast<CommonToken *>(oldToken))->_text;
    _source = (static_cast<CommonToken *>(oldToken))->_source;
  } else {
    _text = oldToken->getText();
    _source = { oldToken->getTokenSource(), oldToken->getInputStream() };
  }
}

size_t CommonToken::getType() const {
  return _type;
}

void CommonToken::setLine(size_t line) {
  _line = line;
}

std::string CommonToken::getText() const {
  if (!_text.empty()) {
    return _text;
  }

  CharStream *input = getInputStream();
  if (input == nullptr) {
    return "";
  }
  size_t n = input->size();
  if (_start < n && _stop < n) {
    return input->getText(misc::Interval(_start, _stop));
  } else {
    return "<EOF>";
  }
}

void CommonToken::setText(const std::string &text) {
  _text = text;
}

size_t CommonToken::getLine() const {
  return _line;
}

size_t CommonToken::getCharPositionInLine() const {
  return _charPositionInLine;
}

void CommonToken::setCharPositionInLine(size_t charPositionInLine) {
  _charPositionInLine = charPositionInLine;
}

size_t CommonToken::getChannel() const {
  return _channel;
}

void CommonToken::setChannel(size_t channel) {
  _channel = channel;
}

void CommonToken::setType(size_t type) {
  _type = type;
}

size_t CommonToken::getStartIndex() const {
  return _start;
}

void CommonToken::setStartIndex(size_t start) {
  _start = start;
}

size_t CommonToken::getStopIndex() const {
  return _stop;
}

void CommonToken::setStopIndex(size_t stop) {
  _stop = stop;
}

size_t CommonToken::getTokenIndex() const {
  return _index;
}

void CommonToken::setTokenIndex(size_t index) {
  _index = index;
}

antlr4::TokenSource *CommonToken::getTokenSource() const {
  return _source.first;
}

antlr4::CharStream *CommonToken::getInputStream() const {
  return _source.second;
}

std::string CommonToken::toString() const {
  return toString(nullptr);
}

std::string CommonToken::toString(Recognizer *r) const {
  std::stringstream ss;

  std::string channelStr;
  if (_channel > 0) {
    channelStr = ",channel=" + std::to_string(_channel);
  }
  std::string txt = getText();
  if (!txt.empty()) {
    txt = antlrcpp::escapeWhitespace(txt);
  } else {
    txt = "<no text>";
  }

  std::string typeString = std::to_string(symbolToNumeric(_type));
  if (r != nullptr)
    typeString = r->getVocabulary().getDisplayName(_type);

  ss << "[@" << symbolToNumeric(getTokenIndex()) << "," << symbolToNumeric(_start) << ":" << symbolToNumeric(_stop)
    << "='" << txt << "',<" << typeString << ">" << channelStr << "," << _line << ":"
    << getCharPositionInLine() << "]";

  return ss.str();
}

void CommonToken::InitializeInstanceFields() {
  _type = 0;
  _line = 0;
  _charPositionInLine = INVALID_INDEX;
  _channel = DEFAULT_CHANNEL;
  _index = INVALID_INDEX;
  _start = 0;
  _stop = 0;
  _source = EMPTY_SOURCE;
}


text:
import {ComponentPortal, Portal, CdkPortal, DomPortal, PortalModule} from '@angular/cdk/portal';
import {Component, QueryList, ViewChildren, ElementRef, ViewChild} from '@angular/core';

@Component({
  selector: 'science-joke',
  template: `<p> 100 kilopascals go into a bar. </p>`,
  standalone: true,
})
export class ScienceJoke {}

@Component({
  selector: 'portal-demo',
  templateUrl: 'portal-demo.html',
  styleUrls: ['portal-demo.css'],
  standalone: true,
  imports: [PortalModule, ScienceJoke],
})
export class PortalDemo {
  @ViewChildren(CdkPortal) templatePortals: QueryList<Portal<any>>;
  @ViewChild('domPortalSource') domPortalSource: ElementRef<HTMLElement>;

  selectedPortal: Portal<any>;

  get programmingJoke() {
    return this.templatePortals.first;
  }

  get mathJoke() {
    return this.templatePortals.last;
  }

  get scienceJoke() {
    return new ComponentPortal(ScienceJoke);
  }

  get dadJoke() {
    return new DomPortal(this.domPortalSource);
  }
}


text:
package io.fabric8.openshift.api.model.monitoring.v1;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.ObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.BuildableReference;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "apiVersion",
    "kind",
    "metadata",
    "lookbackDelta",
    "maxConcurrency",
    "maxSamples",
    "timeout"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
    "_",
    ""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = {
    @BuildableReference(ObjectMeta.class),
    @BuildableReference(LabelSelector.class),
    @BuildableReference(Container.class),
    @BuildableReference(PodTemplateSpec.class),
    @BuildableReference(ResourceRequirements.class),
    @BuildableReference(IntOrString.class),
    @BuildableReference(ObjectReference.class),
    @BuildableReference(LocalObjectReference.class),
    @BuildableReference(PersistentVolumeClaim.class)
})
public class QuerySpec implements KubernetesResource
{

    @JsonProperty("lookbackDelta")
    private String lookbackDelta;
    @JsonProperty("maxConcurrency")
    private Integer maxConcurrency;
    @JsonProperty("maxSamples")
    private Integer maxSamples;
    @JsonProperty("timeout")
    private String timeout;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * No args constructor for use in serialization
     *
     */
    public QuerySpec() {
    }

    /**
     *
     * @param maxSamples
     * @param lookbackDelta
     * @param timeout
     * @param maxConcurrency
     */
    public QuerySpec(String lookbackDelta, Integer maxConcurrency, Integer maxSamples, String timeout) {
        super();
        this.lookbackDelta = lookbackDelta;
        this.maxConcurrency = maxConcurrency;
        this.maxSamples = maxSamples;
        this.timeout = timeout;
    }

    @JsonProperty("lookbackDelta")
    public String getLookbackDelta() {
        return lookbackDelta;
    }

    @JsonProperty("lookbackDelta")
    public void setLookbackDelta(String lookbackDelta) {
        this.lookbackDelta = lookbackDelta;
    }

    @JsonProperty("maxConcurrency")
    public Integer getMaxConcurrency() {
        return maxConcurrency;
    }

    @JsonProperty("maxConcurrency")
    public void setMaxConcurrency(Integer maxConcurrency) {
        this.maxConcurrency = maxConcurrency;
    }

    @JsonProperty("maxSamples")
    public Integer getMaxSamples() {
        return maxSamples;
    }

    @JsonProperty("maxSamples")
    public void setMaxSamples(Integer maxSamples) {
        this.maxSamples = maxSamples;
    }

    @JsonProperty("timeout")
    public String getTimeout() {
        return timeout;
    }

    @JsonProperty("timeout")
    public void setTimeout(String timeout) {
        this.timeout = timeout;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}