text:
Ruby API for AethLabs microAeth® model AE51

### Description

This Gem provides and easy to use API for sending
and receiving data and commands for the microAeth model AE51.

This library is not complete but encompasses the most
common commands for interfacing with the device.

## Installation

Install the Ruby Gem:

    $ gem install micro_aeth-ae51-ruby

Include it in your Ruby application:

    require 'micro_aeth-ae51'

## Documentation

Documentation for this project may be accessed through it's RubyGems Site [here](https://rubygems.org/gems/micro_aeth-ae51-ruby).

## Bugs

Please report any bugs found in microAeth-AE51-Ruby [here](https://github.com/RudyComputing/microAeth-AE51-Ruby/issues), we appreciate your help improving microAeth-AE51-Ruby.

## Future Work

The core of this gem was originally used to build portable combustion emissions testing devices (see [here](https://github.com/RudyComputing/CombustionEmissionsTesting)).  The project is no longer under development and work has stopped on this gem as well.


text:
package org.bbreak.excella.core.exporter.book;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

/**
 * エクスポータのテストスイート
 *
 * @since 1.0
 */
@RunWith(Suite.class)
@SuiteClasses({
    ConsoleExporterTest.class,
    TextFileExporterTest.class,
    WorkbookExporterTest.class
})
public class ExporterBookTestSuite {

}

redpajama_set_name: RedPajamaGithub


text:
// ***************************************************************************
// BamAux.h (c) 2009 Derek Barnett, Michael Str�mberg
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 25 October 2011 (DB)
// ---------------------------------------------------------------------------
// Provides data structures & utility methods that are used throughout the API.
// ***************************************************************************

#ifndef BAMAUX_H
#define BAMAUX_H

#include <cstddef>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "api/api_global.h"

/*! \file BamAux.h

    Provides data structures & utility methods that are used throughout the API.
*/

/*! \namespace BamTools
    \brief Contains all BamTools classes & methods.

    The BamTools API contained in this namespace contains classes and methods
    for reading, writing, and manipulating BAM alignment files.
*/
namespace BamTools {

// ----------------------------------------------------------------
// CigarOp

/*! \struct BamTools::CigarOp
    \brief Represents a CIGAR alignment operation.

    \sa \samSpecURL for more details on using CIGAR operations.
*/
struct API_EXPORT CigarOp
{

    char Type;        //!< CIGAR operation type (MIDNSHPX=)
    uint32_t Length;  //!< CIGAR operation length (number of bases)

    //! constructor
    CigarOp(const char type = '\0', const uint32_t& length = 0)
        : Type(type)
        , Length(length)
    {}
};

// ----------------------------------------------------------------
// RefData

/*! \struct BamTools::RefData
    \brief Represents a reference sequence entry
*/
struct API_EXPORT RefData
{

    std::string RefName;  //!< name of reference sequence
    int32_t RefLength;    //!< length of reference sequence

    //! constructor
    RefData(const std::string& name = std::string(), const int32_t& length = 0)
        : RefName(name)
        , RefLength(length)
    {}
};

//! convenience typedef for vector of RefData entries
typedef std::vector<RefData> RefVector;

// ----------------------------------------------------------------
// BamRegion

/*! \struct BamTools::BamRegion
    \brief Represents a sequential genomic region

    Allowed to span multiple (sequential) references.

    \warning BamRegion now represents a zero-based, HALF-OPEN interval.
    In previous versions of BamTools (0.x & 1.x) all intervals were treated
    as zero-based, CLOSED.
*/
struct API_EXPORT BamRegion
{

    int LeftRefID;      //!< reference ID for region's left boundary
    int LeftPosition;   //!< position for region's left boundary
    int RightRefID;     //!< reference ID for region's right boundary
    int RightPosition;  //!< position for region's right boundary

    //! constructor
    BamRegion(const int& leftID = -1, const int& leftPos = -1, const int& rightID = -1,
              const int& rightPos = -1)
        : LeftRefID(leftID)
        , LeftPosition(leftPos)
        , RightRefID(rightID)
        , RightPosition(rightPos)
    {}

    //! copy constructor
    BamRegion(const BamRegion& other)
        : LeftRefID(other.LeftRefID)
        , LeftPosition(other.LeftPosition)
        , RightRefID(other.RightRefID)
        , RightPosition(other.RightPosition)
    {}

    //! Clears region boundaries
    void clear()
    {
        LeftRefID = -1;
        LeftPosition = -1;
        RightRefID = -1;
        RightPosition = -1;
    }

    //! Returns true if region has a left boundary
    bool isLeftBoundSpecified() const
    {
        return (LeftRefID >= 0 && LeftPosition >= 0);
    }

    //! Returns true if region boundaries are not defined
    bool isNull() const
    {
        return (!isLeftBoundSpecified() && !isRightBoundSpecified());
    }

    //! Returns true if region has a right boundary
    bool isRightBoundSpecified() const
    {
        return (RightRefID >= 0 && RightPosition >= 1);
    }
};

struct CustomHeaderTag
{
    std::string TagName;
    std::string TagValue;
};

// ----------------------------------------------------------------
// General utility methods

/*! \fn bool FileExists(const std::string& filename)
    \brief returns true if the file exists
*/
API_EXPORT inline bool FileExists(const std::string& filename)
{
    std::ifstream f(filename.c_str(), std::ifstream::in);
    return !f.fail();
}

/*! \fn void SwapEndian_16(int16_t& x)
    \brief swaps endianness of signed 16-bit integer, in place
*/
API_EXPORT inline void SwapEndian_16(int16_t& x)
{
    x = ((x >> 8) | (x << 8));
}

/*! \fn void SwapEndian_16(uint16_t& x)
    \brief swaps endianness of unsigned 16-bit integer, in place
*/
API_EXPORT inline void SwapEndian_16(uint16_t& x)
{
    x = ((x >> 8) | (x << 8));
}

/*! \fn void SwapEndian_32(int32_t& x)
    \brief swaps endianness of signed 32-bit integer, in place
*/
API_EXPORT inline void SwapEndian_32(int32_t& x)
{
    x = ((x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24));
}

/*! \fn void SwapEndian_32(uint32_t& x)
    \brief swaps endianness of unsigned 32-bit integer, in place
*/
API_EXPORT inline void SwapEndian_32(uint32_t& x)
{
    x = ((x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24));
}

/*! \fn void SwapEndian_64(int64_t& x)
    \brief swaps endianness of signed 64-bit integer, in place
*/
API_EXPORT inline void SwapEndian_64(int64_t& x)
{
    x = ((x >> 56) | ((x << 40) & 0x00FF000000000000ll) | ((x << 24) & 0x0000FF0000000000ll) |
         ((x << 8) & 0x000000FF00000000ll) | ((x >> 8) & 0x00000000FF000000ll) |
         ((x >> 24) & 0x0000000000FF0000ll) | ((x >> 40) & 0x000000000000FF00ll) | (x << 56));
}

/*! \fn void SwapEndian_64(uint64_t& x)
    \brief swaps endianness of unsigned 64-bit integer, in place
*/
API_EXPORT inline void SwapEndian_64(uint64_t& x)
{
    x = ((x >> 56) | ((x << 40) & 0x00FF000000000000ll) | ((x << 24) & 0x0000FF0000000000ll) |
         ((x << 8) & 0x000000FF00000000ll) | ((x >> 8) & 0x00000000FF000000ll) |
         ((x >> 24) & 0x0000000000FF0000ll) | ((x >> 40) & 0x000000000000FF00ll) | (x << 56));
}

/*! \fn void SwapEndian_16p(char* data)
    \brief swaps endianness of the next 2 bytes in a buffer, in place
*/
API_EXPORT inline void SwapEndian_16p(char* data)
{
    uint16_t& value = (uint16_t&)*data;
    SwapEndian_16(value);
}

/*! \fn void SwapEndian_32p(char* data)
    \brief swaps endianness of the next 4 bytes in a buffer, in place
*/
API_EXPORT inline void SwapEndian_32p(char* data)
{
    uint32_t& value = (uint32_t&)*data;
    SwapEndian_32(value);
}

/*! \fn void SwapEndian_64p(char* data)
    \brief swaps endianness of the next 8 bytes in a buffer, in place
*/
API_EXPORT inline void SwapEndian_64p(char* data)
{
    uint64_t& value = (uint64_t&)*data;
    SwapEndian_64(value);
}

/*! \fn bool SystemIsBigEndian()
    \brief checks host architecture's byte order
    \return \c true if system uses big-endian ordering
*/
API_EXPORT inline bool SystemIsBigEndian()
{
    const uint16_t one = 0x0001;
    return ((*(char*)&one) == 0);
}

/*! \fn void PackUnsignedInt(char* buffer, unsigned int value)
    \brief stores unsigned integer value in a byte buffer

    \param[out] buffer destination buffer
    \param[in]  value  value to 'pack' in buffer
*/
API_EXPORT inline void PackUnsignedInt(char* buffer, unsigned int value)
{
    buffer[0] = (char)value;
    buffer[1] = (char)(value >> 8);
    buffer[2] = (char)(value >> 16);
    buffer[3] = (char)(value >> 24);
}

/*! \fn void PackUnsignedShort(char* buffer, unsigned short value)
    \brief stores unsigned short integer value in a byte buffer

    \param[out] buffer destination buffer
    \param[in]  value  value to 'pack' in buffer
*/
API_EXPORT inline void PackUnsignedShort(char* buffer, unsigned short value)
{
    buffer[0] = (char)value;
    buffer[1] = (char)(value >> 8);
}

/*! \fn double UnpackDouble(const char* buffer)
    \brief reads a double value from byte buffer

    \param[in] buffer source byte buffer
    \return the (double) value read from the buffer
*/
API_EXPORT inline double UnpackDouble(const char* buffer)
{
    union
    {
        double value;
        unsigned char valueBuffer[sizeof(double)];
    } un;
    un.value = 0;
    un.valueBuffer[0] = buffer[0];
    un.valueBuffer[1] = buffer[1];
    un.valueBuffer[2] = buffer[2];
    un.valueBuffer[3] = buffer[3];
    un.valueBuffer[4] = buffer[4];
    un.valueBuffer[5] = buffer[5];
    un.valueBuffer[6] = buffer[6];
    un.valueBuffer[7] = buffer[7];
    return un.value;
}

/*! \fn double UnpackDouble(char* buffer)
    \brief reads a double value from byte buffer

    This is an overloaded function.

    \param[in] buffer source byte buffer
    \return the (double) value read from the buffer
*/
API_EXPORT inline double UnpackDouble(char* buffer)
{
    return UnpackDouble((const char*)buffer);
}

/*! \fn double UnpackFloat(const char* buffer)
    \brief reads a float value from byte buffer

    \param[in] buffer source byte buffer
    \return the (float) value read from the buffer
*/
API_EXPORT inline float UnpackFloat(const char* buffer)
{
    union
    {
        float value;
        unsigned char valueBuffer[sizeof(float)];
    } un;
    un.value = 0;
    un.valueBuffer[0] = buffer[0];
    un.valueBuffer[1] = buffer[1];
    un.valueBuffer[2] = buffer[2];
    un.valueBuffer[3] = buffer[3];
    return un.value;
}

/*! \fn double UnpackFloat(char* buffer)
    \brief reads a float value from byte buffer

    This is an overloaded function.

    \param[in] buffer source byte buffer
    \return the (float) value read from the buffer
*/
API_EXPORT inline float UnpackFloat(char* buffer)
{
    return UnpackFloat((const char*)buffer);
}

/*! \fn signed int UnpackSignedInt(const char* buffer)
    \brief reads a signed integer value from byte buffer

    \param[in] buffer source byte buffer
    \return the (signed int) value read from the buffer
*/
API_EXPORT inline signed int UnpackSignedInt(const char* buffer)
{
    union
    {
        signed int value;
        unsigned char valueBuffer[sizeof(signed int)];
    } un;
    un.value = 0;
    un.valueBuffer[0] = buffer[0];
    un.valueBuffer[1] = buffer[1];
    un.valueBuffer[2] = buffer[2];
    un.valueBuffer[3] = buffer[3];
    return un.value;
}

/*! \fn signed int UnpackSignedInt(char* buffer)
    \brief reads a signed integer value from byte buffer

    This is an overloaded function.

    \param[in] buffer source byte buffer
    \return the (signed int) value read from the buffer
*/
API_EXPORT inline signed int UnpackSignedInt(char* buffer)
{
    return UnpackSignedInt((const char*)buffer);
}

/*! \fn signed short UnpackSignedShort(const char* buffer)
    \brief reads a signed short integer value from byte buffer

    \param[in] buffer source byte buffer
    \return the (signed short) value read from the buffer
*/
API_EXPORT inline signed short UnpackSignedShort(const char* buffer)
{
    union
    {
        signed short value;
        unsigned char valueBuffer[sizeof(signed short)];
    } un;
    un.value = 0;
    un.valueBuffer[0] = buffer[0];
    un.valueBuffer[1] = buffer[1];
    return un.value;
}

/*! \fn signed short UnpackSignedShort(char* buffer)
    \brief reads a signed short integer value from byte buffer

    This is an overloaded function.

    \param[in] buffer source byte buffer
    \return the (signed short) value read from the buffer
*/
API_EXPORT inline signed short UnpackSignedShort(char* buffer)
{
    return UnpackSignedShort((const char*)buffer);
}

/*! \fn unsigned int UnpackUnsignedInt(const char* buffer)
    \brief reads an unsigned integer value from byte buffer

    \param[in] buffer source byte buffer
    \return the (unsigned int) value read from the buffer
*/
API_EXPORT inline unsigned int UnpackUnsignedInt(const char* buffer)
{
    union
    {
        unsigned int value;
        unsigned char valueBuffer[sizeof(unsigned int)];
    } un;
    un.value = 0;
    un.valueBuffer[0] = buffer[0];
    un.valueBuffer[1] = buffer[1];
    un.valueBuffer[2] = buffer[2];
    un.valueBuffer[3] = buffer[3];
    return un.value;
}

/*! \fn unsigned int UnpackUnsignedInt(char* buffer)
    \brief reads an unsigned integer value from byte buffer

    This is an overloaded function.

    \param[in] buffer source byte buffer
    \return the (unsigned int) value read from the buffer
*/
API_EXPORT inline unsigned int UnpackUnsignedInt(char* buffer)
{
    return UnpackUnsignedInt((const char*)buffer);
}

/*! \fn unsigned short UnpackUnsignedShort(const char* buffer)
    \brief reads an unsigned short integer value from byte buffer

    \param[in] buffer source byte buffer
    \return the (unsigned short) value read from the buffer
*/
API_EXPORT inline unsigned short UnpackUnsignedShort(const char* buffer)
{
    union
    {
        unsigned short value;
        unsigned char valueBuffer[sizeof(unsigned short)];
    } un;
    un.value = 0;
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    un.valueBuffer[0] = buffer[0];
    un.valueBuffer[1] = buffer[1];
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    un.valueBuffer[0] = buffer[1];
    un.valueBuffer[1] = buffer[0];
#else
#error "Unsupported hardware"
#endif
    return un.value;
}

/*! \fn unsigned short UnpackUnsignedShort(char* buffer)
    \brief reads an unsigned short integer value from byte buffer

    This is an overloaded function.

    \param[in] buffer source byte buffer
    \return the (unsigned short) value read from the buffer
*/
API_EXPORT inline unsigned short UnpackUnsignedShort(char* buffer)
{
    return UnpackUnsignedShort((const char*)buffer);
}

// ----------------------------------------------------------------
// 'internal' helper structs

/*! \struct RaiiBuffer
    \internal
*/
struct RaiiBuffer
{

    // data members
    char* Buffer;
    const std::size_t NumBytes;

    // ctor & dtor
    RaiiBuffer(const std::size_t n)
        : Buffer(new char[n]())
        , NumBytes(n)
    {}

    ~RaiiBuffer()
    {
        delete[] Buffer;
    }

    // add'l methods
    void Clear()
    {
        memset(Buffer, 0, NumBytes);
    }
};

}  // namespace BamTools

#endif  // BAMAUX_H


text:
import crypt
from hashlib import sha1 as sha
import hmac
import time
import os

from PLC.Faults import *
from PLC.Parameter import Parameter, Mixed
from PLC.Persons import Persons
from PLC.Nodes import Node, Nodes
from PLC.Interfaces import Interface, Interfaces
from PLC.Sessions import Session, Sessions
from PLC.Peers import Peer, Peers
from PLC.Keys import Keys
from PLC.Boot import notify_owners
from PLC.Logger import logger

class Auth(Parameter):
    """
    Base class for all API authentication methods, as well as a class
    that can be used to represent all supported API authentication
    methods.
    """

    def __init__(self, auth=None):
        if auth is None:
            auth = {'AuthMethod': Parameter(str, "Authentication method to use",
                                            optional=False)}
        Parameter.__init__(self, auth, "API authentication structure")

    def check(self, method, auth, *args):
        global auth_methods

        # Method.type_check() should have checked that all of the
        # mandatory fields were present.
        assert 'AuthMethod' in auth

        if auth['AuthMethod'] in auth_methods:
            expected = auth_methods[auth['AuthMethod']]()
        else:
            sm = "'" + "', '".join(list(auth_methods.keys())) + "'"
            raise PLCInvalidArgument("must be " + sm, "AuthMethod")

        # Re-check using the specified authentication method
        method.type_check("auth", auth, expected, (auth,) + args)

class GPGAuth(Auth):
    """
    Proposed PlanetLab federation authentication structure.
    """

    def __init__(self):
        Auth.__init__(self, {
            'AuthMethod': Parameter(str, "Authentication method to use, always 'gpg'", optional=False),
            'name': Parameter(str, "Peer or user name", optional=False),
            'signature': Parameter(str, "Message signature", optional=False)
        })

    def check(self, method, auth, *args):
        try:
            peers = Peers(method.api, [auth['name']])
            if peers:
                if 'peer' not in method.roles:
                    raise PLCAuthenticationFailure(
                        "GPGAuth: Not allowed to call method, missing 'peer' role")

                method.caller = peer = peers[0]
                gpg_keys = [peer['key']]
            else:
                persons = Persons(
                    method.api, {'email': auth['name'], 'enabled': True, 'peer_id': None})
                if not persons:
                    raise PLCAuthenticationFailure(
                        "GPGAuth: No such user '%s'" % auth['name'])

                method.caller = person = persons[0]
                if not set(person['roles']).intersection(method.roles):
                    raise PLCAuthenticationFailure(
                        "GPGAuth: Not allowed to call method, missing role")

                keys = Keys(
                    method.api, {'key_id': person['key_ids'], 'key_type': "gpg", 'peer_id': None})
                gpg_keys = [key['key'] for key in keys]

            if not gpg_keys:
                raise PLCAuthenticationFailure(
                    "GPGAuth: No GPG key on record for peer or user '%s'" % auth['name'])

            for gpg_key in gpg_keys:
                try:
                    from PLC.GPG import gpg_verify
                    gpg_verify(args, gpg_key, auth['signature'], method.name)
                    return
                except PLCAuthenticationFailure as fault:
                    pass

            raise fault

        except PLCAuthenticationFailure as fault:
            # XXX Send e-mail
            raise fault

class SessionAuth(Auth):
    """
    Secondary authentication method. After authenticating with a
    primary authentication method, call GetSession() to generate a
    session key that may be used for subsequent calls.
    """

    def __init__(self):
        Auth.__init__(self, {
            'AuthMethod': Parameter(str, "Authentication method to use, always 'session'", optional=False),
            'session': Parameter(str, "Session key", optional=False)
        })

    def check(self, method, auth, *args):
        # Method.type_check() should have checked that all of the
        # mandatory fields were present.
        assert 'session' in auth

        # Get session record
        sessions = Sessions(method.api, [auth['session']], expires=None)
        if not sessions:
            raise PLCAuthenticationFailure("SessionAuth: No such session")
        session = sessions[0]

        try:
            if session['node_id'] is not None:
                nodes = Nodes(
                    method.api, {'node_id': session['node_id'], 'peer_id': None})
                if not nodes:
                    raise PLCAuthenticationFailure("SessionAuth: No such node")
                node = nodes[0]

                if 'node' not in method.roles:
                    # using PermissionDenied rather than AuthenticationFailure here because
                    # if that fails we don't want to delete the session..
                    raise PLCPermissionDenied(
                        "SessionAuth: Not allowed to call method %s, missing 'node' role" % method.name)

                method.caller = node

            elif session['person_id'] is not None and session['expires'] > time.time():
                persons = Persons(method.api, {
                                  'person_id': session['person_id'], 'enabled': True, 'peer_id': None})
                if not persons:
                    raise PLCAuthenticationFailure(
                        "SessionAuth: No such enabled account")
                person = persons[0]

                if not set(person['roles']).intersection(method.roles):
                    method_message = "method %s has roles [%s]" % (
                        method.name, ','.join(method.roles))
                    person_message = "caller %s has roles [%s]" % (
                        person['email'], ','.join(person['roles']))
                    # not PLCAuthenticationFailure b/c that would end the session..
                    raise PLCPermissionDenied(
                        "SessionAuth: missing role, %s -- %s" % (method_message, person_message))

                method.caller = person

            else:
                raise PLCAuthenticationFailure("SessionAuth: Invalid session")

        except PLCAuthenticationFailure as fault:
            session.delete()
            raise fault

class BootAuth(Auth):
    """
    PlanetLab version 3.x node authentication structure. Used by the
    Boot Manager to make authenticated calls to the API based on a
    unique node key or boot nonce value.
    """

    def __init__(self):
        Auth.__init__(self, {
            'AuthMethod': Parameter(str, "Authentication method to use, always 'hmac'", optional=False),
            'node_id': Parameter(int, "Node identifier", optional=False),
            'value': Parameter(str, "HMAC of node key and method call", optional=False)
        })

    def canonicalize(self, args):
        values = []

        for arg in args:
            if isinstance(arg, list) or isinstance(arg, tuple):
                # The old implementation did not recursively handle
                # lists of lists. But neither did the old API itself.
                values += self.canonicalize(arg)
            elif isinstance(arg, dict):
                # Yes, the comments in the old implementation are
                # misleading. Keys of dicts are not included in the
                # hash.
                values += self.canonicalize(list(arg.values()))
            else:
                # We use unicode() instead of str().
                values.append(str(arg))

        return values

    def check(self, method, auth, *args):
        # Method.type_check() should have checked that all of the
        # mandatory fields were present.
        assert 'node_id' in auth

        if 'node' not in method.roles:
            raise PLCAuthenticationFailure(
                "BootAuth: Not allowed to call method, missing 'node' role")

        try:
            nodes = Nodes(
                method.api, {'node_id': auth['node_id'], 'peer_id': None})
            if not nodes:
                raise PLCAuthenticationFailure("BootAuth: No such node")
            node = nodes[0]

            # Jan 2011 : removing support for old boot CDs
            if node['key']:
                key = node['key']
            else:
                raise PLCAuthenticationFailure("BootAuth: No node key")

            # Yes, this is the "canonicalization" method used.
            args = self.canonicalize(args)
            args.sort()
            msg = "[" + "".join(args) + "]"

            digest = hmac.new(key.encode('utf-8'), msg.encode('utf-8'), sha).hexdigest()

            if digest != auth['value']:
                raise PLCAuthenticationFailure(
                    "BootAuth: Call could not be authenticated")

            method.caller = node

        except PLCAuthenticationFailure as fault:
            if nodes:
                notify_owners(method, node, 'authfail',
                              include_pis=True, include_techs=True, fault=fault)
            raise fault

class AnonymousAuth(Auth):
    """
    PlanetLab version 3.x anonymous authentication structure.
    """

    def __init__(self):
        Auth.__init__(self, {
            'AuthMethod': Parameter(str, "Authentication method to use, always 'anonymous'", False),
        })

    def check(self, method, auth, *args):
        if 'anonymous' not in method.roles:
            raise PLCAuthenticationFailure(
                "AnonymousAuth: method cannot be called anonymously")

        method.caller = None

class PasswordAuth(Auth):
    """
    PlanetLab version 3.x password authentication structure.
    """

    def __init__(self):
        Auth.__init__(self, {
            'AuthMethod': Parameter(str, "Authentication method to use, always 'password' or 'capability'", optional=False),
            'Username': Parameter(str, "PlanetLab username, typically an e-mail address", optional=False),
            'AuthString': Parameter(str, "Authentication string, typically a password", optional=False),
        })

    def check(self, method, auth, *args):
        # Method.type_check() should have checked that all of the
        # mandatory fields were present.
        assert 'Username' in auth

        # Get record (must be enabled)
        normalized = auth['Username'].lower()
        persons = Persons(method.api, {
                          'email': normalized, 'enabled': True, 'peer_id': None})
        if len(persons) != 1:
            logger.info(f"PasswordAuth failed with {normalized}, got {len(persons)} matches")
            raise PLCAuthenticationFailure("PasswordAuth: No such account")

        person = persons[0]

        if auth['Username'] == method.api.config.PLC_API_MAINTENANCE_USER:
            # "Capability" authentication, whatever the hell that was
            # supposed to mean. It really means, login as the special
            # "maintenance user" using password authentication. Can
            # only be used on particular machines (those in a list).
            sources = method.api.config.PLC_API_MAINTENANCE_SOURCES.split()
            if method.source is not None and method.source[0] not in sources:
                raise PLCAuthenticationFailure(
                    "PasswordAuth: Not allowed to login to maintenance account")

            # Not sure why this is not stored in the DB
            password = method.api.config.PLC_API_MAINTENANCE_PASSWORD

            if auth['AuthString'] != password:
                raise PLCAuthenticationFailure(
                    "PasswordAuth: Maintenance account password verification failed")
        else:
            # Compare encrypted plaintext against encrypted password stored in the DB
            plaintext = auth['AuthString']
            password = person['password']

            # Protect against blank passwords in the DB
            if password is None or password[:12] == "" or \
               crypt.crypt(plaintext, password[:12]) != password:
                raise PLCAuthenticationFailure(
                    "PasswordAuth: Password verification failed")

        if not set(person['roles']).intersection(method.roles):
            method_message = "method %s has roles [%s]" % (
                method.name, ','.join(method.roles))
            person_message = "caller %s has roles [%s]" % (
                person['email'], ','.join(person['roles']))
            raise PLCAuthenticationFailure(
                "PasswordAuth: missing role, %s -- %s" % (method_message, person_message))

        method.caller = person

auth_methods = {'session': SessionAuth,
                'password': PasswordAuth,
                'capability': PasswordAuth,
                'gpg': GPGAuth,
                'hmac': BootAuth,
                'hmac_dummybox': BootAuth,
                'anonymous': AnonymousAuth}

path = os.path.dirname(__file__) + "/Auth.d"
try:
    extensions = os.listdir(path)
except OSError as e:
    extensions = []
for extension in extensions:
    if extension.startswith("."):
        continue
    if not extension.endswith(".py"):
        continue
    exec(compile(open("%s/%s" % (path, extension)).read(),
                 "%s/%s" % (path, extension), 'exec'))
del extensions


text:
'use strict';

const webpack = require('webpack');
const path = require('path');
const rxPaths = require('rxjs/_esm5/path-mapping');

const globals = require('./globals');
const plugins = require('./plugins');
const rules = require('./rules');

module.exports = {
  resolve: {
    modules: [
      globals.NodeModulesDirectory,
      globals.SourceDirectory
    ],
    extensions: ['.ts', '.js'],
    alias: rxPaths()
  },

  output: {
    path: globals.DistDirectory,
    filename: '[name].bundle.js'
  },

  entry: {
    'main': './src/main.ts',
    'polyfills': './src/polyfills.ts',
    'style': './src/global.scss'
  },

  module: {
    rules: [
      rules.html,
      rules.sass,
      rules.sassGlobal,
      rules.assets,
      rules.fonts,
      rules.woff
    ]
  },

  plugins: plugins.commonPlugins,

  stats: globals.stats
};


text:
static const char* vertexShaderSource =
    "#version 400\n"
    "\n"
    "uniform mat4 model;\n"
    "uniform mat4 modelNormal;\n"
    "uniform mat4 lightView;\n"
    "uniform mat4 lightProjection;\n"
    "\n"
    "in vec3 position;\n"
    "in vec3 normal;\n"
    "in vec2 uv;\n"
    "\n"
    "out vec3 worldPosition;"
    "out vec3 worldNormal;"
    "out vec2 worldUv;"
    "out vec4 lightFrustumPosition4;"
    "\n"
    "void main()\n"
    "{\n"
    "	vec4 worldPosition4 = model * vec4(position, 1.0);\n"
    "	vec4 worldNormal4 = modelNormal * vec4(normal, 1.0);\n"
    "	worldPosition = worldPosition4.xyz / worldPosition4.w;\n"
    "	worldNormal = worldNormal4.xyz / worldNormal4.w;\n"
    "	worldUv = uv;\n"
    ""
    "	lightFrustumPosition4 = lightProjection * lightView * worldPosition4;\n"
    ""
    "	gl_Position = vec4(worldPosition, 1.0);\n"
    "}\n";

GLuint shovelerShaderProgramModelVertexScreenspaceCreate() {
  return shovelerShaderProgramCompileFromString(vertexShaderSource, GL_VERTEX_SHADER);
}


text:
import logging
from collections import deque

import mock
import unittest2 as unittest

from akanda.rug import event
from akanda.rug import state
from akanda.rug import vm_manager
from akanda.rug.api.quantum import RouterGone

class BaseTestStateCase(unittest.TestCase):
    state_cls = state.State

    def setUp(self):
        self.ctx = mock.Mock()  # worker context
        log = logging.getLogger(__name__)
        vm_mgr_cls = mock.patch('akanda.rug.vm_manager.VmManager').start()
        self.addCleanup(mock.patch.stopall)
        self.vm = vm_mgr_cls.return_value
        self.params = state.StateParams(
            vm=self.vm,
            log=log,
            queue=deque(),
            bandwidth_callback=mock.Mock(),
            reboot_error_threshold=3,
            router_image_uuid='GLANCE-IMAGE-123'
        )
        self.state = self.state_cls(self.params)

    def _test_transition_hlpr(self, action, expected_class,
                              vm_state=state.vm_manager.UP):
        self.vm.state = vm_state
        result = self.state.transition(action, self.ctx)
        self.assertIsInstance(result, expected_class)
        return result

class TestBaseState(BaseTestStateCase):
    def test_execute(self):
        self.assertEqual(
            self.state.execute('action', self.ctx),
            'action'
        )

    def test_transition(self):
        self.assertEqual(
            self.state.transition('action', self.ctx),
            self.state
        )

class TestCalcActionState(BaseTestStateCase):
    state_cls = state.CalcAction

    def _test_hlpr(self, expected_action, queue_states,
                   leftover=0, initial_action=event.POLL):
        self.params.queue = deque(queue_states)
        self.assertEqual(
            self.state.execute(initial_action, self.ctx),
            expected_action
        )
        self.assertEqual(len(self.params.queue), leftover)

    def test_execute_empty_queue(self):
        self._test_hlpr('testaction', [], initial_action='testaction')

    def test_execute_delete_in_queue(self):
        self._test_hlpr(event.DELETE, [event.CREATE, event.DELETE], 2)

    def test_none_start_action_update(self):
        self._test_hlpr(expected_action=event.UPDATE,
                        queue_states=[event.UPDATE, event.UPDATE],
                        leftover=0,
                        initial_action=None)

    def test_none_start_action_poll(self):
        self._test_hlpr(expected_action=event.POLL,
                        queue_states=[event.POLL, event.POLL],
                        leftover=0,
                        initial_action=None)

    def test_execute_ignore_pending_update_follow_create(self):
        self._test_hlpr(event.CREATE, [event.CREATE, event.UPDATE])

    def test_execute_upgrade_to_create_follow_update(self):
        self._test_hlpr(event.CREATE, [event.UPDATE, event.CREATE])

    def test_execute_collapse_same_events(self):
        events = [event.UPDATE, event.UPDATE, event.UPDATE]
        self._test_hlpr(event.UPDATE, events, 0)

    def test_execute_collapse_mixed_events(self):
        events = [
            event.UPDATE,
            event.POLL,
            event.UPDATE,
            event.POLL,
            event.UPDATE,
            event.READ,
        ]
        self._test_hlpr(event.UPDATE, events, 1)

    def test_execute_events_ending_with_poll(self):
        events = [
            event.UPDATE,
            event.UPDATE,
            event.POLL,
            event.POLL,
        ]
        self._test_hlpr(event.UPDATE, events, 0)

    def test_transition_update_missing_router_down(self):
        self.ctx.neutron = mock.Mock()
        self.ctx.neutron.get_router_detail.side_effect = RouterGone
        self._test_transition_hlpr(
            event.UPDATE,
            state.CheckBoot,
            vm_manager.BOOTING
        )

    def test_transition_update_missing_router_not_down(self):
        self.ctx.neutron = mock.Mock()
        self.ctx.neutron.get_router_detail.side_effect = RouterGone
        self._test_transition_hlpr(
            event.UPDATE,
            state.CheckBoot,
            vm_manager.BOOTING
        )

    def test_transition_delete_missing_router_down(self):
        self.ctx.neutron = mock.Mock()
        self.ctx.neutron.get_router_detail.side_effect = RouterGone
        self._test_transition_hlpr(
            event.DELETE,
            state.StopVM,
            vm_manager.DOWN
        )

    def test_transition_delete_missing_router_not_down(self):
        self.ctx.neutron = mock.Mock()
        self.ctx.neutron.get_router_detail.side_effect = RouterGone
        self._test_transition_hlpr(
            event.DELETE,
            state.StopVM,
            vm_manager.BOOTING
        )

    def test_transition_delete_down_vm(self):
        self._test_transition_hlpr(event.DELETE, state.StopVM, vm_manager.DOWN)

    def test_transition_delete_up_vm(self):
        self._test_transition_hlpr(event.DELETE, state.StopVM)

    def test_transition_create_down_vm(self):
        for evt in [event.POLL, event.READ, event.UPDATE, event.CREATE]:
            self._test_transition_hlpr(evt, state.CreateVM, vm_manager.DOWN)

    def test_transition_poll_up_vm(self):
        self._test_transition_hlpr(event.POLL, state.Alive, vm_manager.UP)

    def test_transition_poll_configured_vm(self):
        self._test_transition_hlpr(
            event.POLL,
            state.Alive,
            vm_manager.CONFIGURED
        )

    def test_transition_other_up_vm(self):
        for evt in [event.READ, event.UPDATE, event.CREATE]:
            self._test_transition_hlpr(evt, state.Alive)

    def test_transition_update_error_vm(self):
        self.vm.error_cooldown = False
        result = self._test_transition_hlpr(
            event.UPDATE,
            state.ClearError,
            vm_manager.ERROR,
        )
        self.assertIsInstance(result._next_state, state.Alive)

    def test_transition_update_error_vm_in_error_cooldown(self):
        self.vm.error_cooldown = True
        self._test_transition_hlpr(
            event.UPDATE,
            state.CalcAction,
            vm_manager.ERROR,
        )

    def test_transition_poll_error_vm(self):
        self._test_transition_hlpr(
            event.POLL,
            state.CalcAction,
            vm_manager.ERROR,
        )

class TestAliveState(BaseTestStateCase):
    state_cls = state.Alive

    def test_execute(self):
        self.assertEqual(
            self.state.execute('passthrough', self.ctx),
            'passthrough'
        )
        self.vm.update_state.assert_called_once_with(self.ctx)

    def test_transition_vm_down(self):
        for evt in [event.POLL, event.READ, event.UPDATE, event.CREATE]:
            self._test_transition_hlpr(evt, state.CreateVM, vm_manager.DOWN)

    def test_transition_poll_vm_configured(self):
        self._test_transition_hlpr(
            event.POLL,
            state.CalcAction,
            vm_manager.CONFIGURED
        )

    def test_transition_read_vm_configured(self):
        self._test_transition_hlpr(
            event.READ,
            state.ReadStats,
            vm_manager.CONFIGURED
        )

    def test_transition_up_to_configured(self):
        self._test_transition_hlpr(
            event.CREATE,
            state.ConfigureVM,
            vm_manager.UP
        )

    def test_transition_configured_vm_configured(self):
        self._test_transition_hlpr(
            event.CREATE,
            state.ConfigureVM,
            vm_manager.CONFIGURED
        )

class TestCreateVMState(BaseTestStateCase):
    state_cls = state.CreateVM

    def test_execute(self):
        self.vm.attempts = 0
        self.assertEqual(
            self.state.execute('passthrough', self.ctx),
            'passthrough'
        )
        self.vm.boot.assert_called_once_with(self.ctx, 'GLANCE-IMAGE-123')

    def test_execute_too_many_attempts(self):
        self.vm.attempts = self.params.reboot_error_threshold
        self.assertEqual(
            self.state.execute('passthrough', self.ctx),
            'passthrough'
        )
        self.assertEqual([], self.vm.boot.mock_calls)
        self.vm.set_error.assert_called_once_with(self.ctx)

    def test_transition_vm_down(self):
        self._test_transition_hlpr(
            event.READ,
            state.CheckBoot,
            vm_manager.BOOTING
        )

    def test_transition_vm_up(self):
        self._test_transition_hlpr(
            event.READ,
            state.CheckBoot,
            vm_state=state.vm_manager.BOOTING
        )

    def test_transition_vm_missing(self):
        self._test_transition_hlpr(
            event.READ,
            state.CreateVM,
            vm_state=state.vm_manager.DOWN
        )

    def test_transition_vm_error(self):
        self._test_transition_hlpr(event.READ, state.CalcAction,
                                   vm_state=state.vm_manager.ERROR)

class TestRebuildVMState(BaseTestStateCase):
    state_cls = state.RebuildVM

    def test_execute(self):
        self.assertEqual(
            self.state.execute('ignored', self.ctx),
            event.CREATE,
        )
        self.vm.stop.assert_called_once_with(self.ctx)

    def test_execute_gone(self):
        self.vm.state = vm_manager.GONE
        self.assertEqual(
            self.state.execute('ignored', self.ctx),
            event.DELETE,
        )
        self.vm.stop.assert_called_once_with(self.ctx)

class TestClearErrorState(BaseTestStateCase):
    state_cls = state.ClearError

    def test_execute(self):
        self.assertEqual(
            self.state.execute('passthrough', self.ctx),
            'passthrough',
        )
        self.vm.clear_error.assert_called_once_with(self.ctx)

    def test_execute_after_error(self):
        self.vm.state = vm_manager.ERROR
        self.assertEqual(
            self.state.execute('passthrough', self.ctx),
            'passthrough',
        )
        self.vm.clear_error.assert_called_once_with(self.ctx)

    def test_transition_default(self):
        st = self.state_cls(self.params)
        self.assertIsInstance(
            st.transition('passthrough', self.ctx),
            state.CalcAction,
        )

    def test_transition_override(self):
        st = self.state_cls(self.params, state.Alive(self.params))
        self.assertIsInstance(
            st.transition('passthrough', self.ctx),
            state.Alive,
        )

class TestCheckBootState(BaseTestStateCase):
    state_cls = state.CheckBoot

    def test_execute(self):
        self.assertEqual(
            self.state.execute('passthrough', self.ctx),
            'passthrough'
        )
        self.vm.check_boot.assert_called_once_with(self.ctx)
        assert list(self.params.queue) == ['passthrough']

    def test_transition_vm_configure(self):
        self._test_transition_hlpr(
            event.UPDATE,
            state.ConfigureVM,
            vm_manager.UP
        )

    def test_transition_vm_booting(self):
        self._test_transition_hlpr(
            event.UPDATE,
            state.CalcAction,
            vm_manager.BOOTING
        )

class TestStopVMState(BaseTestStateCase):
    state_cls = state.StopVM

    def test_execute(self):
        self.assertEqual(
            self.state.execute('passthrough', self.ctx),
            'passthrough'
        )
        self.vm.stop.assert_called_once_with(self.ctx)

    def test_transition_vm_still_up(self):
        self._test_transition_hlpr(event.DELETE, state.StopVM)

    def test_transition_delete_vm_down(self):
        self._test_transition_hlpr(event.DELETE, state.Exit, vm_manager.DOWN)

    def test_transition_restart_vm_down(self):
        self._test_transition_hlpr(event.READ, state.CreateVM, vm_manager.DOWN)

class TestReplugState(BaseTestStateCase):
    state_cls = state.ReplugVM

    def test_execute(self):
        self.assertEqual(
            self.state.execute('update', self.ctx),
            'update'
        )
        self.vm.replug.assert_called_once_with(self.ctx)

    def test_transition_hotplug_succeeded(self):
        self._test_transition_hlpr(
            event.UPDATE,
            state.ConfigureVM,
            vm_manager.REPLUG
        )

    def test_transition_hotplug_failed(self):
        self._test_transition_hlpr(
            event.UPDATE,
            state.StopVM,
            vm_manager.RESTART
        )

class TestExitState(TestBaseState):
    state_cls = state.Exit

class TestConfigureVMState(BaseTestStateCase):
    state_cls = state.ConfigureVM

    def test_execute_read_configure_success(self):
        self.vm.state = vm_manager.CONFIGURED
        self.assertEqual(self.state.execute(event.READ, self.ctx),
                         event.READ)
        self.vm.configure.assert_called_once_with(self.ctx)

    def test_execute_update_configure_success(self):
        self.vm.state = vm_manager.CONFIGURED
        self.assertEqual(self.state.execute(event.UPDATE, self.ctx),
                         event.POLL)
        self.vm.configure.assert_called_once_with(self.ctx)

    def test_execute_configure_failure(self):
        self.assertEqual(
            self.state.execute(event.CREATE, self.ctx),
            event.CREATE
        )
        self.vm.configure.assert_called_once_with(self.ctx)

    def test_transition_not_configured_down(self):
        self._test_transition_hlpr(event.READ, state.StopVM, vm_manager.DOWN)

    def test_transition_not_configured_restart(self):
        self._test_transition_hlpr(event.READ, state.StopVM,
                                   vm_manager.RESTART)

    def test_transition_not_configured_up(self):
        self._test_transition_hlpr(event.READ, state.PushUpdate,
                                   vm_manager.UP)

    def test_transition_read_configured(self):
        self._test_transition_hlpr(
            event.READ,
            state.ReadStats,
            vm_manager.CONFIGURED
        )

    def test_transition_other_configured(self):
        self._test_transition_hlpr(
            event.POLL,
            state.CalcAction,
            vm_manager.CONFIGURED
        )

class TestReadStatsState(BaseTestStateCase):
    state_cls = state.ReadStats

    def test_execute(self):
        self.vm.read_stats.return_value = 'foo'

        self.assertEqual(
            self.state.execute(event.READ, self.ctx),
            event.POLL
        )
        self.vm.read_stats.assert_called_once_with()
        self.params.bandwidth_callback.assert_called_once_with('foo')

    def test_transition(self):
        self._test_transition_hlpr(event.POLL, state.CalcAction)

class TestAutomaton(unittest.TestCase):
    def setUp(self):
        super(TestAutomaton, self).setUp()

        self.ctx = mock.Mock()  # worker context

        self.vm_mgr_cls = mock.patch('akanda.rug.vm_manager.VmManager').start()
        self.addCleanup(mock.patch.stopall)

        self.delete_callback = mock.Mock()
        self.bandwidth_callback = mock.Mock()

        self.sm = state.Automaton(
            router_id='9306bbd8-f3cc-11e2-bd68-080027e60b25',
            tenant_id='tenant-id',
            delete_callback=self.delete_callback,
            bandwidth_callback=self.bandwidth_callback,
            worker_context=self.ctx,
            queue_warning_threshold=3,
            reboot_error_threshold=5,
        )

    def test_send_message(self):
        message = mock.Mock()
        message.crud = 'update'
        with mock.patch.object(self.sm, 'log') as logger:
            self.sm.send_message(message)
            self.assertEqual(len(self.sm._queue), 1)
            logger.debug.assert_called_with(
                'incoming message brings queue length to %s',
                1,
            )

    def test_send_message_over_threshold(self):
        message = mock.Mock()
        message.crud = 'update'
        for i in range(3):
            self.sm.send_message(message)
        with mock.patch.object(self.sm, 'log') as logger:
            self.sm.send_message(message)
            logger.warning.assert_called_with(
                'incoming message brings queue length to %s',
                4,
            )

    def test_send_message_deleting(self):
        message = mock.Mock()
        message.crud = 'update'
        self.sm.deleted = True
        self.sm.send_message(message)
        self.assertEqual(len(self.sm._queue), 0)
        self.assertFalse(self.sm.has_more_work())

    def test_send_message_in_error(self):
        vm = self.vm_mgr_cls.return_value
        vm.state = state.vm_manager.ERROR
        message = mock.Mock()
        message.crud = 'poll'
        self.sm.send_message(message)
        self.assertEqual(len(self.sm._queue), 0)
        self.assertFalse(self.sm.has_more_work())

        # Non-POLL events should *not* be ignored for routers in ERROR state
        message.crud = 'create'
        with mock.patch.object(self.sm, 'log') as logger:
            self.sm.send_message(message)
            self.assertEqual(len(self.sm._queue), 1)
            logger.debug.assert_called_with(
                'incoming message brings queue length to %s',
                1,
            )

    def test_send_rebuild_message_with_custom_image(self):
        vm = self.vm_mgr_cls.return_value
        vm.state = state.vm_manager.DOWN
        with mock.patch.object(vm_manager.cfg, 'CONF') as conf:
            conf.router_image_uuid = 'DEFAULT'
            self.sm.state.params.router_image_uuid = conf.router_image_uuid

            message = mock.Mock()
            message.crud = 'rebuild'
            message.body = {'router_image_uuid': 'ABC123'}
            self.assertEqual(self.sm.router_image_uuid, conf.router_image_uuid)
            self.sm.send_message(message)
            self.assertEqual(self.sm.router_image_uuid, 'ABC123')

            message = mock.Mock()
            message.crud = 'rebuild'
            message.body = {}
            self.sm.send_message(message)
            self.assertEqual(self.sm.router_image_uuid, 'DEFAULT')

    def test_has_more_work(self):
        with mock.patch.object(self.sm, '_queue') as queue:  # noqa
            self.assertTrue(self.sm.has_more_work())

    def test_has_more_work_deleting(self):
        self.sm.deleted = True
        with mock.patch.object(self.sm, '_queue') as queue:  # noqa
            self.assertFalse(self.sm.has_more_work())

    def test_update_no_work(self):
        with mock.patch.object(self.sm, 'state') as state:
            self.sm.update(self.ctx)
            self.assertFalse(state.called)

    def test_update_exit(self):
        message = mock.Mock()
        message.crud = event.UPDATE
        self.sm.send_message(message)
        self.sm.state = state.Exit(mock.Mock())
        self.sm.update(self.ctx)
        self.delete_callback.called_once_with()

    def test_update_exception_during_excute(self):
        message = mock.Mock()
        message.crud = 'fake'
        self.sm.send_message(message)

        fake_state = mock.Mock()
        fake_state.execute.side_effect = Exception
        fake_state.transition.return_value = state.Exit(mock.Mock())
        self.sm.action = 'fake'
        self.sm.state = fake_state

        with mock.patch.object(self.sm, 'log') as log:
            self.sm.update(self.ctx)

            log.exception.assert_called_once_with(mock.ANY, fake_state, 'fake')

            fake_state.assert_has_calls(
                [
                    mock.call.execute('fake', self.ctx),
                    mock.call.transition('fake', self.ctx)
                ]
            )

    def test_update_calc_action_args(self):
        message = mock.Mock()
        message.crud = event.UPDATE
        self.sm.send_message(message)

        with mock.patch.object(self.sm.state, 'execute',
                               self.ctx) as execute:
            with mock.patch.object(self.sm.state, 'transition',
                                   self.ctx) as transition:
                transition.return_value = state.Exit(mock.Mock())
                self.sm.update(self.ctx)

                execute.called_once_with(
                    event.POLL,
                    self.vm_mgr_cls.return_value,
                    self.ctx,
                    self.sm._queue
                )
                self.delete_callback.called_once_with()

    def test_update_read_stats_args(self):
        message = mock.Mock()
        message.crud = event.READ
        self.sm.send_message(message)

        self.sm.state = state.ReadStats(mock.Mock())
        with mock.patch.object(self.sm.state, 'execute', self.ctx) as execute:
            execute.return_value = state.Exit(mock.Mock())
            self.sm.update(self.ctx)

            execute.called_once_with(
                event.POLL,
                self.vm_mgr_cls.return_value,
                self.ctx,
                self.bandwidth_callback
            )

    def test_has_error(self):
        with mock.patch.object(self.sm, 'vm') as vm:
            vm.state = vm_manager.ERROR
            self.assertTrue(self.sm.has_error())

    def test_has_no_error(self):
        with mock.patch.object(self.sm, 'vm') as vm:
            vm.state = vm_manager.UP
            self.assertFalse(self.sm.has_error())


text:
package org.visallo.webster.testApp;

import org.visallo.webster.ParameterizedHandler;
import org.visallo.webster.annotations.Handle;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

public class ImageHandler implements ParameterizedHandler {
    @Handle
    public void handle(HttpServletResponse response) throws IOException {
        byte[] data = new byte[1000];
        int read;
        InputStream in = ImageHandler.class.getResourceAsStream("webster.jpg");
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("image/jpg");
        while ((read = in.read(data)) > 0) {
            out.write(data, 0, read);
        }
    }
}


text:
/*	$NetBSD: krpc_subr.c,v 1.12.4.1 1996/06/07 00:52:26 cgd Exp $	*/
/*	$Id: krpc_subr.c,v 1.11 1998/08/23 03:07:16 wollman Exp $	*/

/*
 * Copyright (c) 1995 Gordon Ross, Adam Glass
 * Copyright (c) 1992 Regents of the University of California.
 * All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory and its contributors.
 * 4. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``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 REGENTS 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.
 *
 * partially based on:
 *      libnetboot/rpc.c
 *               @(#) Header: rpc.c,v 1.12 93/09/28 08:31:56 leres Exp  (LBL)
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/uio.h>

#include <net/if.h>
#include <netinet/in.h>

#include <nfs/rpcv2.h>
#include <nfs/krpc.h>
#include <nfs/xdr_subs.h>

/*
 * Kernel support for Sun RPC
 *
 * Used currently for bootstrapping in nfs diskless configurations.
 */

/*
 * Generic RPC headers
 */

struct auth_info {
	u_int32_t 	authtype;	/* auth type */
	u_int32_t	authlen;	/* auth length */
};

struct auth_unix {
	int32_t   ua_time;
	int32_t   ua_hostname;	/* null */
	int32_t   ua_uid;
	int32_t   ua_gid;
	int32_t   ua_gidlist;	/* null */
};

struct rpc_call {
	u_int32_t	rp_xid;		/* request transaction id */
	int32_t 	rp_direction;	/* call direction (0) */
	u_int32_t	rp_rpcvers;	/* rpc version (2) */
	u_int32_t	rp_prog;	/* program */
	u_int32_t	rp_vers;	/* version */
	u_int32_t	rp_proc;	/* procedure */
	struct	auth_info rpc_auth;
	struct	auth_unix rpc_unix;
	struct	auth_info rpc_verf;
};

struct rpc_reply {
	u_int32_t rp_xid;		/* request transaction id */
	int32_t  rp_direction;		/* call direction (1) */
	int32_t  rp_astatus;		/* accept status (0: accepted) */
	union {
		u_int32_t rpu_errno;
		struct {
			struct auth_info rok_auth;
			u_int32_t	rok_status;
		} rpu_rok;
	} rp_u;
};
#define rp_errno  rp_u.rpu_errno
#define rp_auth   rp_u.rpu_rok.rok_auth
#define rp_status rp_u.rpu_rok.rok_status

#define MIN_REPLY_HDR 16	/* xid, dir, astat, errno */

/*
 * What is the longest we will wait before re-sending a request?
 * Note this is also the frequency of "RPC timeout" messages.
 * The re-send loop count sup linearly to this maximum, so the
 * first complaint will happen after (1+2+3+4+5)=15 seconds.
 */
#define	MAX_RESEND_DELAY 5	/* seconds */

/*
 * Call portmap to lookup a port number for a particular rpc program
 * Returns non-zero error on failure.
 */
int
krpc_portmap(sin,  prog, vers, portp, procp)
	struct sockaddr_in *sin;		/* server address */
	u_int prog, vers;	/* host order */
	u_int16_t *portp;	/* network order */
	struct proc *procp;
{
	struct sdata {
		u_int32_t prog;		/* call program */
		u_int32_t vers;		/* call version */
		u_int32_t proto;	/* call protocol */
		u_int32_t port;		/* call port (unused) */
	} *sdata;
	struct rdata {
		u_int16_t pad;
		u_int16_t port;
	} *rdata;
	struct mbuf *m;
	int error;

	/* The portmapper port is fixed. */
	if (prog == PMAPPROG) {
		*portp = htons(PMAPPORT);
		return 0;
	}

	m = m_get(M_WAIT, MT_DATA);
	if (m == NULL)
		return ENOBUFS;
	sdata = mtod(m, struct sdata *);
	m->m_len = sizeof(*sdata);

	/* Do the RPC to get it. */
	sdata->prog = txdr_unsigned(prog);
	sdata->vers = txdr_unsigned(vers);
	sdata->proto = txdr_unsigned(IPPROTO_UDP);
	sdata->port = 0;

	sin->sin_port = htons(PMAPPORT);
	error = krpc_call(sin, PMAPPROG, PMAPVERS,
					  PMAPPROC_GETPORT, &m, NULL, procp);
	if (error)
		return error;

	if (m->m_len < sizeof(*rdata)) {
		m = m_pullup(m, sizeof(*rdata));
		if (m == NULL)
			return ENOBUFS;
	}
	rdata = mtod(m, struct rdata *);
	*portp = rdata->port;

	m_freem(m);
	return 0;
}

/*
 * Do a remote procedure call (RPC) and wait for its reply.
 * If from_p is non-null, then we are doing broadcast, and
 * the address from whence the response came is saved there.
 */
int
krpc_call(sa, prog, vers, func, data, from_p, procp)
	struct sockaddr_in *sa;
	u_int prog, vers, func;
	struct mbuf **data;	/* input/output */
	struct sockaddr **from_p;	/* output */
	struct proc *procp;
{
	struct socket *so;
	struct sockaddr_in *sin, ssin;
	struct sockaddr *from;
	struct mbuf *m, *nam, *mhead;
	struct rpc_call *call;
	struct rpc_reply *reply;
	struct sockopt sopt;
	struct timeval tv;
	struct uio auio;
	int error, rcvflg, timo, secs, len;
	static u_int32_t xid = ~0xFF;
	u_int16_t tport;

	/*
	 * Validate address family.
	 * Sorry, this is INET specific...
	 */
	if (sa->sin_family != AF_INET)
		return (EAFNOSUPPORT);

	/* Free at end if not null. */
	nam = mhead = NULL;
	from = NULL;

	/*
	 * Create socket and set its recieve timeout.
	 */
	if ((error = socreate(AF_INET, &so, SOCK_DGRAM, 0, procp)))
		goto out;

	tv.tv_sec = 1;
	tv.tv_usec = 0;
	bzero(&sopt, sizeof sopt);
	sopt.sopt_level = SOL_SOCKET;
	sopt.sopt_name = SO_RCVTIMEO;
	sopt.sopt_val = &tv;
	sopt.sopt_valsize = sizeof tv;

	if (error = sosetopt(so, &sopt))
		goto out;

	/*
	 * Enable broadcast if necessary.
	 */
	if (from_p) {
		int on = 1;
		sopt.sopt_name = SO_BROADCAST;
		sopt.sopt_val = &on;
		sopt.sopt_valsize = sizeof on;
		if (error = sosetopt(so, &sopt))
			goto out;
	}

	/*
	 * Bind the local endpoint to a reserved port,
	 * because some NFS servers refuse requests from
	 * non-reserved (non-privileged) ports.
	 */
	sin = &ssin;
	bzero(sin, sizeof *sin);
	sin->sin_len = sizeof(*sin);
	sin->sin_family = AF_INET;
	sin->sin_addr.s_addr = INADDR_ANY;
	tport = IPPORT_RESERVED;
	do {
		tport--;
		sin->sin_port = htons(tport);
		error = sobind(so, (struct sockaddr *)sin, procp);
	} while (error == EADDRINUSE &&
			 tport > IPPORT_RESERVED / 2);
	if (error) {
		printf("bind failed\n");
		goto out;
	}

	/*
	 * Setup socket address for the server.
	 */

	/*
	 * Prepend RPC message header.
	 */
	mhead = m_gethdr(M_WAIT, MT_DATA);
	mhead->m_next = *data;
	call = mtod(mhead, struct rpc_call *);
	mhead->m_len = sizeof(*call);
	bzero((caddr_t)call, sizeof(*call));
	/* rpc_call part */
	xid++;
	call->rp_xid = txdr_unsigned(xid);
	/* call->rp_direction = 0; */
	call->rp_rpcvers = txdr_unsigned(2);
	call->rp_prog = txdr_unsigned(prog);
	call->rp_vers = txdr_unsigned(vers);
	call->rp_proc = txdr_unsigned(func);
	/* rpc_auth part (auth_unix as root) */
	call->rpc_auth.authtype = txdr_unsigned(RPCAUTH_UNIX);
	call->rpc_auth.authlen  = txdr_unsigned(sizeof(struct auth_unix));
	/* rpc_verf part (auth_null) */
	call->rpc_verf.authtype = 0;
	call->rpc_verf.authlen  = 0;

	/*
	 * Setup packet header
	 */
	len = 0;
	m = mhead;
	while (m) {
		len += m->m_len;
		m = m->m_next;
	}
	mhead->m_pkthdr.len = len;
	mhead->m_pkthdr.rcvif = NULL;

	/*
	 * Send it, repeatedly, until a reply is received,
	 * but delay each re-send by an increasing amount.
	 * If the delay hits the maximum, start complaining.
	 */
	timo = 0;
	for (;;) {
		/* Send RPC request (or re-send). */
		m = m_copym(mhead, 0, M_COPYALL, M_WAIT);
		if (m == NULL) {
			error = ENOBUFS;
			goto out;
		}
		error = sosend(so, (struct sockaddr *)sa, NULL, m,
			       NULL, 0, 0);
		if (error) {
			printf("krpc_call: sosend: %d\n", error);
			goto out;
		}
		m = NULL;

		/* Determine new timeout. */
		if (timo < MAX_RESEND_DELAY)
			timo++;
		else
			printf("RPC timeout for server 0x%lx\n",
			       (u_long)ntohl(sa->sin_addr.s_addr));

		/*
		 * Wait for up to timo seconds for a reply.
		 * The socket receive timeout was set to 1 second.
		 */
		secs = timo;
		while (secs > 0) {
			if (from) {
				FREE(from, M_SONAME);
				from = NULL;
			}
			if (m) {
				m_freem(m);
				m = NULL;
			}
			bzero(&auio,sizeof(auio));
			auio.uio_resid = len = 1<<16;
			rcvflg = 0;
			error = soreceive(so, &from, &auio, &m, NULL, &rcvflg);
			if (error == EWOULDBLOCK) {
				secs--;
				continue;
			}
			if (error)
				goto out;
			len -= auio.uio_resid;

			/* Does the reply contain at least a header? */
			if (len < MIN_REPLY_HDR)
				continue;
			if (m->m_len < MIN_REPLY_HDR)
				continue;
			reply = mtod(m, struct rpc_reply *);

			/* Is it the right reply? */
			if (reply->rp_direction != txdr_unsigned(RPC_REPLY))
				continue;

			if (reply->rp_xid != txdr_unsigned(xid))
				continue;

			/* Was RPC accepted? (authorization OK) */
			if (reply->rp_astatus != 0) {
				error = fxdr_unsigned(u_int32_t, reply->rp_errno);
				printf("rpc denied, error=%d\n", error);
				continue;
			}

			/* Did the call succeed? */
			if (reply->rp_status != 0) {
				error = fxdr_unsigned(u_int32_t, reply->rp_status);
				if (error == RPC_PROGMISMATCH) {
				  error = EBADRPC;
				  goto out;
				}
				printf("rpc denied, status=%d\n", error);
				continue;
			}

			goto gotreply;	/* break two levels */

		} /* while secs */
	} /* forever send/receive */

	error = ETIMEDOUT;
	goto out;

 gotreply:

	/*
	 * Get RPC reply header into first mbuf,
	 * get its length, then strip it off.
	 */
	len = sizeof(*reply);
	if (m->m_len < len) {
		m = m_pullup(m, len);
		if (m == NULL) {
			error = ENOBUFS;
			goto out;
		}
	}
	reply = mtod(m, struct rpc_reply *);
	if (reply->rp_auth.authtype != 0) {
		len += fxdr_unsigned(u_int32_t, reply->rp_auth.authlen);
		len = (len + 3) & ~3; /* XXX? */
	}
	m_adj(m, len);

	/* result */
	*data = m;
	if (from_p) {
		*from_p = from;
		from = NULL;
	}

 out:
	if (mhead) m_freem(mhead);
	if (from) free(from, M_SONAME);
	soclose(so);
	return error;
}

/*
 * eXternal Data Representation routines.
 * (but with non-standard args...)
 */

/*
 * String representation for RPC.
 */
struct xdr_string {
	u_int32_t len;		/* length without null or padding */
	char data[4];	/* data (longer, of course) */
    /* data is padded to a long-word boundary */
};

struct mbuf *
xdr_string_encode(str, len)
	char *str;
	int len;
{
	struct mbuf *m;
	struct xdr_string *xs;
	int dlen;	/* padded string length */
	int mlen;	/* message length */

	dlen = (len + 3) & ~3;
	mlen = dlen + 4;

	if (mlen > MCLBYTES)		/* If too big, we just can't do it. */
		return (NULL);

	m = m_get(M_WAIT, MT_DATA);
	if (mlen > MLEN) {
		MCLGET(m, M_WAIT);
		if ((m->m_flags & M_EXT) == 0) {
			(void) m_free(m);	/* There can be only one. */
			return (NULL);
		}
	}
	xs = mtod(m, struct xdr_string *);
	m->m_len = mlen;
	xs->len = txdr_unsigned(len);
	bcopy(str, xs->data, len);
	return (m);
}


text: "use strict";import"../../modules/sonification/sonification.js";


text:
var nextplex = angular.module('nextplex', ['EventModel', 'UserModel', 'CivicOrganizationModel', 'ngTouch', 'ngSanitize']);

document.addEventListener("deviceready", onDeviceReady, false);

// Set page background color
steroids.view.setBackgroundColor("#f0eff4");

// device APIs are available
//
function onDeviceReady() {
    document.body.className += device.platform.toLowerCase();
}


text:
#import <XcodeEdit/XCRegExScanner.h>

@interface XCNumberScanner : XCRegExScanner
{
}

- (long long)tokenForString:(id)arg1 forRange:(struct _NSRange *)arg2 subItems:(id *)arg3;

@end


text:
var chai = require('chai');

chai.use(require('chai-express-handler'));
chai.use(require('sinon-chai'));

global.expect = chai.expect;


text:
package org.reasm.m68k.assembly.internal;

import java.io.IOException;

import javax.annotation.Nonnull;

import org.reasm.Value;
import org.reasm.m68k.messages.MinusOneDistanceShortBranchErrorMessage;
import org.reasm.m68k.messages.ZeroDistanceShortBranchErrorMessage;

/**
 * The Bcc instructions.
 *
 * @author Francis Gagné
 */
class BranchInstruction extends Instruction {

    @Nonnull
    static final BranchInstruction BCC = new BranchInstruction(IntegerConditionCode.CC);
    @Nonnull
    static final BranchInstruction BCS = new BranchInstruction(IntegerConditionCode.CS);
    @Nonnull
    static final BranchInstruction BEQ = new BranchInstruction(IntegerConditionCode.EQ);
    @Nonnull
    static final BranchInstruction BGE = new BranchInstruction(IntegerConditionCode.GE);
    @Nonnull
    static final BranchInstruction BGT = new BranchInstruction(IntegerConditionCode.GT);
    @Nonnull
    static final BranchInstruction BHI = new BranchInstruction(IntegerConditionCode.HI);
    @Nonnull
    static final BranchInstruction BHS = new BranchInstruction(IntegerConditionCode.HS);
    @Nonnull
    static final BranchInstruction BLE = new BranchInstruction(IntegerConditionCode.LE);
    @Nonnull
    static final BranchInstruction BLO = new BranchInstruction(IntegerConditionCode.LO);
    @Nonnull
    static final BranchInstruction BLS = new BranchInstruction(IntegerConditionCode.LS);
    @Nonnull
    static final BranchInstruction BLT = new BranchInstruction(IntegerConditionCode.LT);
    @Nonnull
    static final BranchInstruction BMI = new BranchInstruction(IntegerConditionCode.MI);
    @Nonnull
    static final BranchInstruction BNE = new BranchInstruction(IntegerConditionCode.NE);
    @Nonnull
    static final BranchInstruction BPL = new BranchInstruction(IntegerConditionCode.PL);
    @Nonnull
    static final BranchInstruction BRA = new BranchInstruction(IntegerConditionCode.T);
    @Nonnull
    static final BranchInstruction BSR = new BranchInstruction(IntegerConditionCode.F);
    @Nonnull
    static final BranchInstruction BVC = new BranchInstruction(IntegerConditionCode.VC);
    @Nonnull
    static final BranchInstruction BVS = new BranchInstruction(IntegerConditionCode.VS);

    @Nonnull
    private final IntegerConditionCode cc;

    private BranchInstruction(@Nonnull IntegerConditionCode cc) {
        this.cc = cc;
    }

    @Override
    void assemble2(final M68KAssemblyContext context) throws IOException {
        InstructionSize size = context.parseIntegerInstructionSize();
        if (size == InstructionSize.INVALID) {
            if ("S".equalsIgnoreCase(context.attribute)) {
                size = InstructionSize.BYTE;
            } else {
                context.addInvalidSizeAttributeErrorMessage();
                size = InstructionSize.DEFAULT;
            }
        }

        if (context.requireNumberOfOperands(1)) {
            final Value value = evaluateExpressionOperand(context, 0);
            final BranchLabelValueVisitor visitor = context.branchLabelValueVisitor;
            visitor.reset(size);
            short leadWord = (short) (0b01100000_00000000 | this.cc.ordinal() << 8);
            final InstructionSize outputSize;
            switch (size) {
            case DEFAULT:
            default:
                if (context.optimizeUnsizedBranches) {
                    outputSize = InstructionSize.BYTE;
                } else {
                    outputSize = InstructionSize.WORD;
                }

                break;

            case BYTE:
                outputSize = InstructionSize.BYTE;
                break;

            case WORD:
                outputSize = InstructionSize.WORD;
                break;

            case LONG:
                outputSize = InstructionSize.LONG;
                break;
            }

            visitor.outputSize = outputSize;

            // By default, generate a branch to self (BRA.B *-2).
            // For a byte-sized branch, putting 0 in the lower byte would turn the instruction into a word-sized branch (BRA.W).
            visitor.distance = -2;

            Value.accept(value, visitor);

            switch (visitor.outputSize) {
            case BYTE:
                short distance = (short) (visitor.distance & 0x00FF);
                if (distance == 0) {
                    context.addTentativeMessage(new ZeroDistanceShortBranchErrorMessage());
                    distance = 0x00FE;
                } else if (distance == 0x00FF && InstructionSetCheck.MC68020_OR_LATER.isSupported(context.instructionSet)) {
                    context.addTentativeMessage(new MinusOneDistanceShortBranchErrorMessage());
                    distance = 0x00FE;
                }

                leadWord |= distance;
                context.appendWord(leadWord);
                checkInstructionSet(InstructionSetCheck.M68000_FAMILY, context);
                break;

            case WORD:
            default:
                context.appendWord(leadWord);
                context.appendWord((short) visitor.distance);
                checkInstructionSet(InstructionSetCheck.M68000_FAMILY, context);
                break;

            case LONG:
                leadWord |= 0xFF;
                context.appendWord(leadWord);
                context.appendLong(visitor.distance);
                checkInstructionSet(InstructionSetCheck.MC68020_OR_LATER, context);
                break;
            }
        }
    }

    @Override
    void checkInstructionSet(M68KAssemblyContext context) {
        // Don't check here: depends on the effective instruction size.
    }

}


text:
package org.ndexbio.common.persistence;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.google.common.io.Files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.*;
import org.ndexbio.cx2.aspect.element.core.CxMetadata;
import org.ndexbio.cx2.converter.AspectAttributeStat;
import org.ndexbio.cxio.aspects.datamodels.NetworkAttributesElement;
import org.ndexbio.cxio.core.AspectIterator;
import org.ndexbio.cxio.metadata.MetaDataCollection;
import org.ndexbio.model.exceptions.NdexException;

/**
 *
 * @author churas
 */
public class TestCXToCX2ServerSideConverter {

	@Rule
    public TemporaryFolder _tmpFolder = new TemporaryFolder();

	/**
	 * Copies aspect files from resource path passed in to destPath directory
	 * @param resourceDirName resource path ie /wntsingaling
	 * @param destPath destination directory
	 * @throws Exception
	 */
	public void copyNetworkAspects(final String resourceDirName,
			final String destPath) throws Exception {
		List<String> aspects = Arrays.asList("cartesianLayout",
										"cyVisualProperties",
										"edgeAttributes",
										"edges",
										"networkAttributes",
										"nodeAttributes",
										"nodes",
										"cyHiddenAttributes",
										"cyTableColumn");
		TestUtil.copyNetworkAspects(this.getClass(), resourceDirName, aspects, destPath);
	}

	@Test
	public void testConvertWntSignalingNetwork() throws Exception {
		File tmpFolder = _tmpFolder.newFolder();
		String configFile = tmpFolder.getCanonicalPath() + File.separator + "config";
		TestUtil.writeSimpleConfigToFile(configFile, tmpFolder.getCanonicalPath());
		String networkIdStr = UUID.randomUUID().toString();

		// Load the meta data from file in resources
		MetaDataCollection mdc = TestUtil.getNetworkMetaData(this.getClass(), "/wntsignaling/metadata");

		CXToCX2ServerSideConverter converter = new CXToCX2ServerSideConverter(tmpFolder.getAbsolutePath() + File.separator,
				mdc, networkIdStr, null, true);

		// copy over network aspect files used by conversion
		copyNetworkAspects("/wntsignaling", tmpFolder.getAbsolutePath() + File.separator + networkIdStr);

		// run conversion
		List<CxMetadata> metaDataList = converter.convert();

		//verify metaDataList returns valid values
		assertEquals(6, metaDataList.size());

		for (CxMetadata mData : metaDataList){
			if (mData.getName().equals("networkAttributes") ||
			    mData.getName().equals("visualProperties") ||
				mData.getName().equals("visualEditorProperties") ||
			    mData.getName().equals("attributeDeclarations")){
				assertEquals((long)1, (long)mData.getElementCount());
			} else if (mData.getName().equals("nodes")){
				assertEquals((long)31, (long)mData.getElementCount());
			} else if (mData.getName().equals("edges")){
				assertEquals((long)72, (long)mData.getElementCount());
			} else {
				fail("Unexpected meta data: " + mData.getName());
			}
		}

		//verify we got a network.cx2 file
		File cx2File = new File(tmpFolder.getAbsolutePath()
				+ File.separator + networkIdStr + File.separator
		         + CX2NetworkLoader.cx2NetworkFileName);
		assertTrue(cx2File.isFile());
		assertTrue(cx2File.length() > 0);

		//verify aspect files for cx2 are properly created
		File a2Dir = new File(tmpFolder.getAbsolutePath()
				+ File.separator + networkIdStr + File.separator + CX2NetworkLoader.cx2AspectDirName);
		List<String> cx2AspectFileNames = new ArrayList<>();
		for (String entry : a2Dir.list()){
			cx2AspectFileNames.add(entry);
			File fileCheck = new File(a2Dir.getAbsolutePath() + File.separator + entry);
			assertTrue(entry + " file has 0 size", fileCheck.length() > 0);
		}
		assertEquals(6, cx2AspectFileNames.size());
		assertTrue(cx2AspectFileNames.contains("visualProperties"));
		assertTrue(cx2AspectFileNames.contains("visualEditorProperties"));
		assertTrue(cx2AspectFileNames.contains("nodes"));
		assertTrue(cx2AspectFileNames.contains("edges"));
		assertTrue(cx2AspectFileNames.contains("networkAttributes"));
		assertTrue(cx2AspectFileNames.contains("attributeDeclarations"));

		List<String> warnings = converter.getWarning();
		assertEquals(1, warnings.size());
		assertTrue(warnings.get(0).startsWith(
				"CX2-CONVERTER: Corrupted data found in DISCRETE mapping on NODE_LABEL_POSITION. Please upgrade your cyNDEx-2 and Cytoscape to the latest version and reload this network. " +
				"Cause: Failed to parse mapping segment 'C' in mapping COL=type,T=string,K=0=smallmolecule,V=0=C,C,c,0.00,0.00,K=1=antibody,V=1=C,C,c,0.00,0.00,K=2=rna,V=2=C,C,c,0.00,0.00,K=3=chemical,V=3=C,C,c,0.00,0.00,K=4=stimulus,V=4=C,C,c,0.00,0.00,K=5=mirna,V=5=C,C,c,0.00,0.00,K=6=mrna,V=6=C,C,c,0.00,0.00,K=7=signal,V=7="));
	}

	@Test
	public void testConvertWntSignalingNetworkAlwaysCreateFalse() throws Exception {
		File tmpFolder = _tmpFolder.newFolder();
		String configFile = tmpFolder.getCanonicalPath() + File.separator + "config";
		TestUtil.writeSimpleConfigToFile(configFile, tmpFolder.getCanonicalPath());
		String networkIdStr = UUID.randomUUID().toString();

		// Load the meta data from file in resources
		MetaDataCollection mdc = TestUtil.getNetworkMetaData(this.getClass(), "/wntsignaling/metadata");

		CXToCX2ServerSideConverter converter = new CXToCX2ServerSideConverter(tmpFolder.getAbsolutePath() + File.separator,
				mdc, networkIdStr, null, false);

		// copy over network aspect files used by conversion
		copyNetworkAspects("/wntsignaling", tmpFolder.getAbsolutePath() + File.separator + networkIdStr);

		//try {
			converter.convert();
		//	fail("Expected IOException");
		//} catch(IOException e){
		//	assertTrue(e.getMessage().startsWith("Failed to parse mapping string 'C' in mapping COL=type"));
		//}

		List<String> warnings = converter.getWarning();

		assertTrue (warnings.get(0).startsWith("CX2-CONVERTER: Corrupted data found in DISCRETE mapping on NODE_LABEL_POSITION. Please upgrade your cyNDEx-2 and Cytoscape to the latest version and reload this network. " +
"Cause: Failed to parse mapping segment 'C' in mapping COL=type,T=string,K=0=smallmolecule,V=0=C,C,c,0.00,0.00,K=1=antibody,V=1=C,C,c,0.00,0.00,K=2=rna,V=2=C,C,c,0.00,0.00,K=3=chemical,V=3=C,C,c,0.00,0.00,K=4=stimulus,V=4=C,C,c,0.00,0.00,K=5=mirna,V=5=C,C,c,0.00,0.00,K=6=mrna,V=6=C,C,c,0.00,0.00,K=7=signal,V=7=C,C,c,0.00,0.00"));
		//TODO Question if conversion fails should files such as network.cx2 remain?
		//     They seem to still exist after a failure
	}

	@Test
	public void testConvertCDAPSHierarchyNetwork() throws Exception {
		File tmpFolder = _tmpFolder.newFolder();
		String configFile = tmpFolder.getCanonicalPath() + File.separator + "config";
		TestUtil.writeSimpleConfigToFile(configFile, tmpFolder.getCanonicalPath());
		String networkIdStr = UUID.randomUUID().toString();

		// Load the meta data from file in resources
		MetaDataCollection mdc = TestUtil.getNetworkMetaData(this.getClass(), "/cdapshier/metadata");

		CXToCX2ServerSideConverter converter = new CXToCX2ServerSideConverter(tmpFolder.getAbsolutePath() + File.separator,
				mdc, networkIdStr, null, true);

		// copy over network aspect files used by conversion
		copyNetworkAspects("/cdapshier", tmpFolder.getAbsolutePath() + File.separator + networkIdStr);

		// run conversion
		List<CxMetadata> metaDataList = converter.convert();

		//verify metaDataList returns valid values
		assertEquals(9, metaDataList.size());

		for (CxMetadata mData : metaDataList){
			if (mData.getName().equals("networkAttributes") ||
			    mData.getName().equals("visualProperties") ||
				mData.getName().equals("visualEditorProperties") ||
			    mData.getName().equals("attributeDeclarations")){
				assertEquals((long)1, (long)mData.getElementCount());
			} else if (mData.getName().equals("nodes")){
				assertEquals((long)43, (long)mData.getElementCount());
			} else if (mData.getName().equals("edges")){
				assertEquals((long)37, (long)mData.getElementCount());
			} else if (mData.getName().equals("edgeBypasses")){
				assertEquals((long)2, (long)mData.getElementCount());
			} else if (mData.getName().equals("cyHiddenAttributes")){
				assertEquals((long)3, (long)mData.getElementCount());
			} else if (mData.getName().equals("cyTableColumn")){
				assertEquals((long)27, (long)mData.getElementCount());
			} else {
				fail("Unexpected meta data: " + mData.getName());
			}
		}

		//verify we got a network.cx2 file
		File cx2File = new File(tmpFolder.getAbsolutePath()
				+ File.separator + networkIdStr + File.separator
		         + CX2NetworkLoader.cx2NetworkFileName);
		assertTrue(cx2File.isFile());
		assertTrue(cx2File.length() > 0);

		//verify aspect files for cx2 are properly created
		File a2Dir = new File(tmpFolder.getAbsolutePath()
				+ File.separator + networkIdStr + File.separator + CX2NetworkLoader.cx2AspectDirName);
		List<String> cx2AspectFileNames = new ArrayList<>();
		for (String entry : a2Dir.list()){
			cx2AspectFileNames.add(entry);
			File fileCheck = new File(a2Dir.getAbsolutePath() + File.separator + entry);
			assertTrue(entry + " file has 0 size", fileCheck.length() > 0);
		}
		assertEquals(9, cx2AspectFileNames.size());
		assertTrue(cx2AspectFileNames.contains("visualProperties"));
		assertTrue(cx2AspectFileNames.contains("visualEditorProperties"));
		assertTrue(cx2AspectFileNames.contains("nodes"));
		assertTrue(cx2AspectFileNames.contains("edges"));
		assertTrue(cx2AspectFileNames.contains("networkAttributes"));
		assertTrue(cx2AspectFileNames.contains("attributeDeclarations"));
		assertTrue(cx2AspectFileNames.contains("cyHiddenAttributes"));
		assertTrue(cx2AspectFileNames.contains("cyTableColumn"));
		assertTrue(cx2AspectFileNames.contains("edgeBypasses"));

		List<String> warnings = converter.getWarning();
		assertEquals(1, warnings.size());
		assertEquals("CX2-CONVERTER: Duplicated network attribute 'version' found.", warnings.get(0));

	}

	@Test
	public void testConvertCDAPSHierarchyNetworkAlwaysCreateFalse() throws Exception {
		File tmpFolder = _tmpFolder.newFolder();
		String configFile = tmpFolder.getCanonicalPath() + File.separator + "config";
		TestUtil.writeSimpleConfigToFile(configFile, tmpFolder.getCanonicalPath());
		String networkIdStr = UUID.randomUUID().toString();

		// Load the meta data from file in resources
		MetaDataCollection mdc = TestUtil.getNetworkMetaData(this.getClass(), "/cdapshier/metadata");

		CXToCX2ServerSideConverter converter = new CXToCX2ServerSideConverter(tmpFolder.getAbsolutePath() + File.separator,
				mdc, networkIdStr, null, false);

		// copy over network aspect files used by conversion
		copyNetworkAspects("/cdapshier", tmpFolder.getAbsolutePath() + File.separator + networkIdStr);

		// run conversion
		//try {
			converter.convert();
			assertEquals(1, converter.getWarning().size());
			assertEquals("CX2-CONVERTER: Duplicated network attribute 'version' found.",
					converter.getWarning().get(0));
			//fail("Expected NdexException");
		//} catch(NdexException ne){
		//	assertEquals("Duplicated network attribute 'version' found.", ne.getMessage());
		//}
	}

	@Test
	public void testRudiMappings() throws Exception {
		File tmpFolder = _tmpFolder.newFolder();
		String configFile = tmpFolder.getCanonicalPath() + File.separator + "config";
		TestUtil.writeSimpleConfigToFile(configFile, tmpFolder.getCanonicalPath());
		String networkIdStr = UUID.randomUUID().toString();

		// Load the meta data from file in resources
		MetaDataCollection mdc = TestUtil.getNetworkMetaData(this.getClass(),"/rudimappings/metadata");

		CXToCX2ServerSideConverter converter = new CXToCX2ServerSideConverter(tmpFolder.getAbsolutePath() + File.separator,
				mdc, networkIdStr, null, true);

		// copy over network aspect files used by conversion
		copyNetworkAspects("/rudimappings", tmpFolder.getAbsolutePath() + File.separator + networkIdStr);

		// run conversion
		List<CxMetadata> metaDataList = converter.convert();

		//verify metaDataList returns valid values
		assertEquals(8, metaDataList.size());

		for (CxMetadata mData : metaDataList){
			if (mData.getName().equals("networkAttributes") ||
			    mData.getName().equals("visualProperties") ||
				mData.getName().equals("visualEditorProperties") ||
			    mData.getName().equals("attributeDeclarations")){
				assertEquals((long)1, (long)mData.getElementCount());
			} else if (mData.getName().equals("nodes")){
				assertEquals((long)488, (long)mData.getElementCount());
			} else if (mData.getName().equals("edges")){
				assertEquals((long)487, (long)mData.getElementCount());
			} else if (mData.getName().equals("edgeBypasses")){
				assertEquals((long)1, (long)mData.getElementCount());
			} else if (mData.getName().equals("cyHiddenAttributes")){
				assertEquals((long)1, (long)mData.getElementCount());
			} else if (mData.getName().equals("cyTableColumn")){
				assertEquals((long)33, (long)mData.getElementCount());
			} else if (mData.getName().equals("nodeBypasses")){
				assertEquals((long)1, (long)mData.getElementCount());
			} else {
				fail("Unexpected meta data: " + mData.getName());
			}
		}

		//verify we got a network.cx2 file
		File cx2File = new File(tmpFolder.getAbsolutePath()
				+ File.separator + networkIdStr + File.separator
		         + CX2NetworkLoader.cx2NetworkFileName);
		assertTrue(cx2File.isFile());
		assertTrue(cx2File.length() > 0);

		//verify aspect files for cx2 are properly created
		File a2Dir = new File(tmpFolder.getAbsolutePath()
				+ File.separator + networkIdStr + File.separator + CX2NetworkLoader.cx2AspectDirName);
		List<String> cx2AspectFileNames = new ArrayList<>();
		for (String entry : a2Dir.list()){
			cx2AspectFileNames.add(entry);
			File fileCheck = new File(a2Dir.getAbsolutePath() + File.separator + entry);
			assertTrue(entry + " file has 0 size", fileCheck.length() > 0);
		}
		assertEquals(8, cx2AspectFileNames.size());
		assertTrue(cx2AspectFileNames.contains("visualProperties"));
		assertTrue(cx2AspectFileNames.contains("visualEditorProperties"));
		assertTrue(cx2AspectFileNames.contains("nodes"));
		assertTrue(cx2AspectFileNames.contains("edges"));
		assertTrue(cx2AspectFileNames.contains("networkAttributes"));
		assertTrue(cx2AspectFileNames.contains("attributeDeclarations"));
		assertTrue(cx2AspectFileNames.contains("cyTableColumn"));
		assertTrue(cx2AspectFileNames.contains("cyHiddenAttributes"));

		// @TODO The converter reports duplicate warnings about duplicate network
		//       attribute cause its checked in analyzeAttributes and again in convert()
		List<String> warnings = converter.getWarning();
		assertEquals(0, warnings.size());
	}
}


text:
using System.Web.Http;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace Taskever.Web.Dependency.Installers
{
    public class TaskeverWebInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            //TODO: Write a custom Web API to be a sample?
            container.Register(

                //All Web Api Controllers
                Classes.FromThisAssembly().BasedOn<ApiController>().LifestyleTransient() //TODO: No need in fact

                );
        }
    }
}


text:
package org.colorcoding.ibas.bobas.data.measurement;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

import org.colorcoding.ibas.bobas.MyConfiguration;
import org.colorcoding.ibas.bobas.i18n.I18N;

/**
 * 货币
 */
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "Currency", namespace = MyConfiguration.NAMESPACE_BOBAS_DATA)
public class Currency extends MeasurementDecimal<String> {

	private static final long serialVersionUID = 1010546725622041464L;

	public Currency() {

	}

	public Currency(BigDecimal value, String unit) {
		super(value);
		this.setUnit(unit);
	}

	public Currency(double value, String unit) {
		super(value);
		this.setUnit(unit);
	}

	private String unit;

	@Override
	@XmlElement(name = "Unit")
	public String getUnit() {
		if (this.unit == null) {
			this.unit = "";
		}
		return this.unit;
	}

	@Override
	public void setUnit(Object value) {
		this.setUnit((String) value);
	}

	public void setUnit(String value) {
		String oldValue = this.unit;
		this.unit = value;
		this.firePropertyChange("Unit", oldValue, this.unit);
	}

	@Override
	public int compareTo(IMeasurement<BigDecimal, String> o) {
		if (!this.getUnit().equals(o.getUnit())) {
			throw new ClassCastException(I18N.prop("msg_bobas_measurement_unit_not_match"));
		}
		return this.getValue().compareTo(o.getValue());
	}

}


text:
'use strict';

var babel = require('babel');
var babelPluginModules = require('fbjs/scripts/babel/rewrite-modules');
var objectAssign = require('object-assign');

var babelOpts = {
  nonStandard: true,
  stage: 1,
  plugins: [babelPluginModules],
  _moduleMap: {
    'React': 'react',
  }
};

module.exports = {
  process: function(src, path) {
    return babel.transform(src, objectAssign({filename: path}, babelOpts)).code;
  }
};


text:
'use strict';
var assert = require('assert');
var Discovery = require('../index.js').Discovery;
var discover = new Discovery();

var serv = {
    port: 80,
    proto: 'tcp',
    annInterval: 1000,
    addrFamily: 'IPv4',
    moreData: {
        name: 'Edmond',
        day: 2233,
        week: [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday' ]
    }
};

var count = 0;

describe('udp-discovery', function() {
    it('should send a single initial event and then a time out', function(cb) {
        this.timeout(22000);
        discover.on('available', function(name, data, reason) {
            count++;
            assert.ok(count === 1);
            assert.ok(reason==='new');
        });

        discover.on('unavailable', function(name, data, reason) {
            count++;
            assert.ok(count === 2);
            assert.ok(reason==='timedOut');
            cb();
        });

        discover.announce('test', serv, 500, true);
        setTimeout(function() {
            discover.pause('test');
        }, 500);
    });
});


text:
<?php

namespace RegistroEventos\CoreBundle\Helper;

class SubirImagen
{
	public function ValidarImagen($file)
    {
		$uploadedfile = $file->getRealPath();
		$extension = strtolower($file->getClientOriginalExtension());
		switch ($extension){
			case 'jpg':
				break;
			case 'jpeg':
				break;
			case 'png':
				break;
			case 'gif':
				break;
			default:
				return "Solo se permiten fotos con formato JPG, JPEG, PNG, GIF";
			}
	}

    public function SubirImagen($file, $id)
    {
		$uploadedfile = $file->getRealPath();
		$extension = strtolower($file->getClientOriginalExtension());
		switch ($extension){
			case 'jpg':
				$src = imagecreatefromjpeg($uploadedfile);
				break;
			case 'jpeg':
				$src = imagecreatefromjpeg($uploadedfile);
				break;
			case 'png':
				$src = imagecreatefrompng($uploadedfile);
				break;
			case 'gif':
				$src = imagecreatefromgif($uploadedfile);
				break;
			default:
				return "Solo se permiten fotos con formato JPG, JPEG, PNG, GIF";
		}
    	//$file->move('fotos', $id.'.jpg');

	    $nombreNuevo = $id.'.jpg';
		list($width,$height)=getimagesize($uploadedfile);
			if ($width > $height){
				$newwidth = 40;
				$newheight = ($height / $width) * $newwidth;
			}else{
				$newheight = 40;
				$newwidth = ($width / $height) * $newheight;
			}
		$tmp = imagecreatetruecolor ($newwidth, $newheight);
		imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
		if (!file_exists('fotos')) {
			mkdir('fotos', 0777, true);
		}
		$filename = 'fotos/'.$nombreNuevo;

		imagejpeg($tmp, $filename);
		imagedestroy($tmp);

		return null;
    }
}


text:
<!-- Autor Dusan Pantic 533/2010 -->

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 class UserOrder extends CI_Controller {

    var $userID = null;
    var $specialty_id = null;
    var $price = null;

    public function __construct(){

          parent::__construct();
          $this->load->model('user','',TRUE);
          $this->load->helper('url');
    }

    public function index()
    {

        if ($this->session->userdata('logged_in')) {
            $session_data     = $this->session->userdata('logged_in');
            $data['username'] = $session_data['username'];

            if (isset($_POST["foodid"])) {
                $data['foodid'] = $_POST["foodid"];

                $data['order'] = $this->user->selectSpec($data['foodid']);
                $data['address'] = $this->user->selectAddr($session_data['id']);

                $this->load->library('form_validation');
                $this->load->helper(array('form'));
                $this->load->view('header.php');
                $this->load->view('navbar.php', $data);
                $this->load->view('userOrder.php', $data);
                $this->load->view('footer.php');
            }
        }
    }

    public function orderConfirm(){
        $specialty_id = null;
        $session_data = $this->session->userdata('logged_in');

        $userID = $session_data['id'];

        if (isset($_POST["foodid"])) {
            $specialty_id = $_POST["foodid"];
        }

        $order = $this->user->order_db($userID, $specialty_id);
        redirect('userMenu/getOrders','refesh');
    }

}
?>


text:
package edu.buffalo.cse.irf14.index.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({})
public class IndexerSuite {

}


text:
CampaignCriterionReturnValueオブジェクトは、操作結果を含むキャンペーンのクライテリアに関する情報のコンテナを表します。
### Service
+ [CampaignCriterionService](../../services/CampaignCriterionService.md)

### Namespace
[CampaignCriterionService#Namespace](../../services/CampaignCriterionService.md#namespace)

| フィールド | データ型 | 説明 |
|---|---|---|
| ListReturnValue(inherited)|||
| ListReturnValue.Type| xsd:string| このインスタンスの ListReturnValue のサブタイプを示します。 |
| Operation.Type| xsd:string| mutate処理の内容です。 |
| CampaignCriterionReturnValue|||
| value[]| CampaignCriterionValues| キャンペーンのクライテリアに関する情報です。 |

この 作品 は クリエイティブ・コモンズ 表示 - 改変禁止 2.1 日本 ライセンスの下に提供されています。


text:
using System;
using System.Diagnostics;
using NUnit.Framework;

namespace MonoTests.System.Diagnostics
{
	public class DebugTest
	{
		private class DebugTest1 : TestCase
		{
			protected override void SetUp()
			{
				Debug.Listeners.Add(new TextWriterTraceListener(Console.Error));
			}

			protected override void TearDown()
			{

			}

			public void TestAssert()
			{
				Debug.Assert(false, "Testing Assertions");
			}

			public void TestFail()
			{
				Debug.Fail("Testing Fail method");
			}

			public void TestWrite()
			{
				Debug.Write("Testing Write", "Testing the output of the Write method");
			}

			public void TestWriteIf()
			{
				Debug.WriteIf(true, "Testing WriteIf");
				Debug.WriteIf(false, "Testing WriteIf", "Passed false");
			}

			public void TestWriteLine()
			{
				Debug.WriteLine("Testing WriteLine method");
			}

			public void TestWriteLineIf()
			{
				Debug.WriteLineIf(true, "Testing WriteLineIf");
				Debug.WriteLineIf(false, "Testing WriteLineIf", "Passed false");
			}
		}
	}
}


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

    <item android:state_enabled="true" android:drawable="@drawable/shape_bg_point_enable"/>
    <item android:state_enabled="false" android:drawable="@drawable/shape_bg_point_disable"/>

</selector>