text:
package es.tid.rsvp.objects;

import java.net.Inet6Address;
import java.net.UnknownHostException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import es.tid.protocol.commons.ByteHandler;
import es.tid.rsvp.RSVPProtocolViolationException;

/*
 *

RFC 3209  RSVP-TE

 4.6.1.1. LSP_TUNNEL_IPv6 Session Object

   Class = SESSION, LSP_TUNNEL_IPv6 C_Type = 8

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                                                               +
   |                   IPv6 tunnel end point address               |
   +                                                               +
   |                            (16 bytes)                         |
   +                                                               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |  MUST be zero                 |      Tunnel ID                |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                                                               +
   |                       Extended Tunnel ID                      |
   +                                                               +
   |                            (16 bytes)                         |
   +                                                               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

      IPv6 tunnel end point address

         IPv6 address of the egress node for the tunnel.

      Tunnel ID

         A 16-bit identifier used in the SESSION that remains constant
         over the life of the tunnel.

      Extended Tunnel ID

         A 16-byte identifier used in the SESSION that remains constant
         over the life of the tunnel.  Normally set to all zeros.
         Ingress nodes that wish to narrow the scope of a SESSION to the
         ingress-egress pair may place their IPv6 address here as a
         globally unique identifier.

 */

public class SessionLSPTunnelIPv6 extends Session{

	/**
	 * IPv6 address of the egress node for the tunnel.
	 */

	protected Inet6Address egressNodeAddress;

	/**
	 *   A 16-bit identifier used in the SESSION that remains constant
         over the life of the tunnel.
	 */

	protected int tunnelId;

	/**
	 *   A 16-byte identifier used in the SESSION that remains constant
         over the life of the tunnel.  Normally set to all zeros.
         Ingress nodes that wish to narrow the scope of a SESSION to the
         ingress-egress pair may place their IPv6 address here as a
         globally unique identifier.
	 */

	protected Inet6Address extendedTunnelId;

	/**
	 * Log
	 */

  private static final Logger log = LoggerFactory.getLogger("ROADM");

	/**
	 * Constructor to be used when a new Session LSP Tunnel IPv6 Object wanted to be
	 * attached to a new message
	 */

	public SessionLSPTunnelIPv6(){

		classNum = 1;
		cType = 8;

		log.debug("Session LSP Tunnel IPv6 Object Created");

	}

	/**
	 * Constructor to be used when a new Session LSP Tunnel IPv6 Object wanted to be
	 * attached to a new message
	 * @param egressNodeAddress egressNodeAddress
	 * @param extendedTunnelId extendedTunnelId
	 * @param tunnelId tunnelID
	 */

	public SessionLSPTunnelIPv6(Inet6Address egressNodeAddress, int tunnelId, Inet6Address extendedTunnelId){

		classNum = 1;
		cType = 8;

		this.egressNodeAddress = egressNodeAddress;
		this.tunnelId = tunnelId;
		this.extendedTunnelId = extendedTunnelId;

		log.debug("Session LSP Tunnel IPv6 Object Created");

	}

	/**
	 * Constructor to be used when a new Session LSP Tunnel IPv6 Object wanted to be decoded from a received
	 * message.
	 * @param bytes bytes
	 * @param offset offset
	 * @throws RSVPProtocolViolationException RSVP Protocol Violation Exception
	 */

	public SessionLSPTunnelIPv6(byte[] bytes, int offset) throws RSVPProtocolViolationException{

		super(bytes, offset);
		decode();

		log.debug("Session LSP Tunnel IPv6 Object Created");
	}

	/**
    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                                                               +
   |                   IPv6 tunnel end point address               |
   +                                                               +
   |                            (16 bytes)                         |
   +                                                               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |  MUST be zero                 |      Tunnel ID                |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                                                               +
   |                       Extended Tunnel ID                      |
   +                                                               +
   |                            (16 bytes)                         |
   +                                                               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

	 */

	public void encode(){
		length = RSVPObjectParameters.RSVP_OBJECT_COMMON_HEADER_SIZE + 36;
		bytes = new byte[length];
		encodeHeader();

		byte[] addr = egressNodeAddress.getAddress();

		int currentIndex =  RSVPObjectParameters.RSVP_OBJECT_COMMON_HEADER_SIZE;

		System.arraycopy(addr,0, getBytes(), currentIndex, addr.length);
		currentIndex = currentIndex + addr.length;

		bytes[currentIndex] = (byte) 0;
		bytes[currentIndex+1] = (byte) 0;
		bytes[currentIndex+2] = (byte)((tunnelId>>8) & 0xFF);
		bytes[currentIndex+3] = (byte)(tunnelId & 0xFF);
		currentIndex = currentIndex + 4;
		addr = extendedTunnelId.getAddress();
		System.arraycopy(addr,0, getBytes(), currentIndex, addr.length);
	}

	public void decode() throws RSVPProtocolViolationException{
		try{
		int offset=0;
		byte[] receivedAddress = new byte[16];
		System.arraycopy(bytes,offset+4,receivedAddress,0,16);

			egressNodeAddress = (Inet6Address) Inet6Address.getByAddress(receivedAddress);

		offset = offset + 20;
		tunnelId = ByteHandler.decode2bytesInteger(bytes,offset+2);
		offset = offset + 4;
		System.arraycopy(bytes,offset,receivedAddress,0,16);
		extendedTunnelId = (Inet6Address) Inet6Address.getByAddress(receivedAddress);
		}catch(Exception e){
			throw new RSVPProtocolViolationException();
		}

	}

	public Inet6Address getEgressNodeAddress() {
		return egressNodeAddress;
	}

	public void setEgressNodeAddress(Inet6Address egressNodeAddress) {
		this.egressNodeAddress = egressNodeAddress;
	}

	public int getTunnelId() {
		return tunnelId;
	}

	public void setTunnelId(int tunnelId) {
		this.tunnelId = tunnelId;
	}

	public Inet6Address getExtendedTunnelId() {
		return extendedTunnelId;
	}

	public void setExtendedTunnelId(Inet6Address extendedTunnelId) {
		this.extendedTunnelId = extendedTunnelId;
	}

}


text:
Exercism is spread across two locations:

1. **Your local computer**:
   Download an exercise, write your solution locally, and submit it to the site.
1. **http://exercism.io**:
   Once you've submitted a solution, people can discuss it with you on the site.
   They might ask questions, make suggestions, or simply muse out loud about things that are interesting.

Fetching exercises and submitting solutions is done via the Exercism command-line client.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Leap Year Program</title>

    <input type="text" id="year" >
    <button type="button" name="button" onclick="leapyear()">Submit</button>


text:
<?php

namespace app\components;
use app\models\File;
use app\models\FileUsage;
use Yii;
use yii\base\Component;
use yii\web\ForbiddenHttpException;
use yii\web\UploadedFile;

/**
 * Class FileService
 *
 * @package app\components
 * @author Jerry Hsia<jerry9916@qq.com>
 */
class FileService extends Component
{
    /**
     * Get a file
     *
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getFile($id)
    {
        return File::find()->andWhere(['id' => $id])->one();
    }

    /**
     * Get multiple files
     *
     * @param $filters
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getFiles($filters)
    {
        $query = File::find();

        if (isset($filters['id'])) {
            $query->andFilterWhere(['id' => $filters['id']]);
        }

        return $query->all();
    }

    /**
     * Save an uploaded file
     *
     * @param UploadedFile $uploadedFile
     * @return File
     * @throws \Exception
     */
    public function save(UploadedFile $uploadedFile)
    {
        $file = new File();
        $file->setAttribute('name', $uploadedFile->name);
        $file->setAttribute('size', $uploadedFile->size);
        $file->setAttribute('type', $uploadedFile->type);

        $result = $file->save();

        if ($result) {
            $uploadPath = Yii::getAlias('@app').'/web/uploads';
            try {
                if (!is_writable($uploadPath)) {
                    throw new ForbiddenHttpException(Yii::t('app', 'File upload path is not writeable'));
                }
                $yearPath = $uploadPath.'/'.date('Y');
                $monthPath = $yearPath.'/'.date('m');

                $result1 = true;
                $result2 = true;
                if (!file_exists($yearPath)) {
                    $result1 = mkdir($yearPath, 0777);
                }

                if (!file_exists($monthPath)) {
                   $result2 =  mkdir($monthPath, 0777);
                }

                if (!$result1 || !$result2) {
                    throw new ForbiddenHttpException(Yii::t('app', 'File saved failed'));
                }

                if (!copy($uploadedFile->tempName, $file->getSavePath())) {
                    throw new ForbiddenHttpException(Yii::t('app', 'File saved failed'));
                }
            } catch (\Exception $e) {
                $file->delete();
                @unlink($uploadedFile->tempName);
                throw $e;
            }
        }

        @unlink($uploadedFile->tempName);
        return $file;
    }

    /**
     * Attach a file to data
     *
     * @param $fileId
     * @param $type
     * @param $dataId
     * @param null $fieldId
     */
    public function attach($fileId, $type, $dataId, $fieldId = null)
    {
        $fileUsage = new FileUsage();
        $fileUsage->file_id = $fileId;
        $fileUsage->type = $type;
        $fileUsage->data_id = $dataId;
        $fileUsage->field_id = $fieldId;

        $fileUsage->save();
    }

    /**
     * Romove a file from data
     *
     * @param $fileId
     * @param $type
     * @param $dataId
     * @param null $fieldId
     * @throws \Exception
     */
    public function detach($fileId, $type, $dataId, $fieldId = null)
    {
        $where['file_id'] = $fileId;
        $where['type'] = $type;
        $where['data_id'] = $dataId;

        if ($fieldId) {
            $where['field_id'] = $fieldId;
        }

        if (FileUsage::deleteAll($where)) {
            if (FileUsage::find()->andWhere(['file_id' => $fileId])->count() == 0) {
                $file = self::getFile($fileId);
                if ($file) $file->delete();
            }
        }
    }
}


text:
package org.apache.pulsar.client.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ThreadFactory;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandAckHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandCloseConsumerHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandCloseProducerHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandConnectHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandFlowHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandPartitionLookupHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandProducerHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandSendHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandSubscribeHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandTopicLookupHook;
import org.apache.pulsar.client.api.MockBrokerServiceHooks.CommandUnsubscribeHook;
import org.apache.pulsar.common.api.proto.CommandAck;
import org.apache.pulsar.common.api.proto.CommandCloseConsumer;
import org.apache.pulsar.common.api.proto.CommandCloseProducer;
import org.apache.pulsar.common.api.proto.CommandConnect;
import org.apache.pulsar.common.api.proto.CommandFlow;
import org.apache.pulsar.common.api.proto.CommandLookupTopic;
import org.apache.pulsar.common.api.proto.CommandLookupTopicResponse.LookupType;
import org.apache.pulsar.common.api.proto.CommandPartitionedTopicMetadata;
import org.apache.pulsar.common.api.proto.CommandPing;
import org.apache.pulsar.common.api.proto.CommandPong;
import org.apache.pulsar.common.api.proto.CommandProducer;
import org.apache.pulsar.common.api.proto.CommandSend;
import org.apache.pulsar.common.api.proto.CommandSubscribe;
import org.apache.pulsar.common.api.proto.CommandUnsubscribe;
import org.apache.pulsar.common.lookup.data.LookupData;
import org.apache.pulsar.common.partition.PartitionedTopicMetadata;
import org.apache.pulsar.common.protocol.Commands;
import org.apache.pulsar.common.protocol.PulsarDecoder;
import org.apache.pulsar.common.protocol.schema.SchemaVersion;
import org.apache.pulsar.common.util.netty.EventLoopUtil;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 */
public class MockBrokerService {
    private LookupData lookupData;

    private class genericResponseHandler extends AbstractHandler {
        private final ObjectMapper objectMapper = new ObjectMapper();
        private final String lookupURI = "/lookup/v2/destination/persistent";
        private final String partitionMetadataURI = "/admin/persistent";
        private final PartitionedTopicMetadata singlePartitionedTopicMetadata = new PartitionedTopicMetadata(1);
        private final PartitionedTopicMetadata multiPartitionedTopicMetadata = new PartitionedTopicMetadata(4);
        private final PartitionedTopicMetadata nonPartitionedTopicMetadata = new PartitionedTopicMetadata();
        // regex to find a partitioned topic
        private final Pattern singlePartPattern = Pattern.compile(".*/part-.*");
        private final Pattern multiPartPattern = Pattern.compile(".*/multi-part-.*");

        @Override
        public void handle(String s, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            String responseString;
            log.info("Received HTTP request {}", baseRequest.getRequestURI());
            if (baseRequest.getRequestURI().startsWith(lookupURI)) {
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_OK);
                responseString = objectMapper.writeValueAsString(lookupData);
            } else if (baseRequest.getRequestURI().startsWith(partitionMetadataURI)) {
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_OK);
                if (singlePartPattern.matcher(baseRequest.getRequestURI()).matches()) {
                    responseString = objectMapper.writeValueAsString(singlePartitionedTopicMetadata);
                } else if (multiPartPattern.matcher(baseRequest.getRequestURI()).matches()) {
                    responseString = objectMapper.writeValueAsString(multiPartitionedTopicMetadata);
                } else {
                    responseString = objectMapper.writeValueAsString(nonPartitionedTopicMetadata);
                }
            } else {
                response.setContentType("text/html;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                responseString = "URI NOT DEFINED";
            }
            baseRequest.setHandled(true);
            response.getWriter().println(responseString);
            log.info("Sent response: {}", responseString);
        }
    }

    private class MockServerCnx extends PulsarDecoder {
        // local state
        ChannelHandlerContext ctx;
        long producerId = 0;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            this.ctx = ctx;
        }

        @Override
        protected void messageReceived() {
        }

        @Override
        protected void handleConnect(CommandConnect connect) {
            if (handleConnect != null) {
                handleConnect.apply(ctx, connect);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newConnected(connect.getProtocolVersion(), false));
        }

        @Override
        protected void handlePartitionMetadataRequest(CommandPartitionedTopicMetadata request) {
            if (handlePartitionlookup != null) {
                handlePartitionlookup.apply(ctx, request);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newPartitionMetadataResponse(0, request.getRequestId()));
        }

        @Override
        protected void handleLookup(CommandLookupTopic lookup) {
            if (handleTopiclookup != null) {
                handleTopiclookup.apply(ctx, lookup);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newLookupResponse(getBrokerAddress(), null, true,
                    LookupType.Connect, lookup.getRequestId(), false));
        }

        @Override
        protected void handleSubscribe(CommandSubscribe subscribe) {
            if (handleSubscribe != null) {
                handleSubscribe.apply(ctx, subscribe);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newSuccess(subscribe.getRequestId()));
        }

        @Override
        protected void handleProducer(CommandProducer producer) {
            producerId = producer.getProducerId();
            if (handleProducer != null) {
                handleProducer.apply(ctx, producer);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newProducerSuccess(producer.getRequestId(), "default-producer", SchemaVersion.Empty));
        }

        @Override
        protected void handleSend(CommandSend send, ByteBuf headersAndPayload) {
            if (handleSend != null) {
                handleSend.apply(ctx, send, headersAndPayload);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newSendReceipt(producerId, send.getSequenceId(), 0, 0, 0));
        }

        @Override
        protected void handleAck(CommandAck ack) {
            if (handleAck != null) {
                handleAck.apply(ctx, ack);
            }
            // default: do nothing
        }

        @Override
        protected void handleFlow(CommandFlow flow) {
            if (handleFlow != null) {
                handleFlow.apply(ctx, flow);
            }
            // default: do nothing
        }

        @Override
        protected void handleUnsubscribe(CommandUnsubscribe unsubscribe) {
            if (handleUnsubscribe != null) {
                handleUnsubscribe.apply(ctx, unsubscribe);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newSuccess(unsubscribe.getRequestId()));
        }

        @Override
        protected void handleCloseProducer(CommandCloseProducer closeProducer) {
            if (handleCloseProducer != null) {
                handleCloseProducer.apply(ctx, closeProducer);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newSuccess(closeProducer.getRequestId()));
        }

        @Override
        protected void handleCloseConsumer(CommandCloseConsumer closeConsumer) {
            if (handleCloseConsumer != null) {
                handleCloseConsumer.apply(ctx, closeConsumer);
                return;
            }
            // default
            ctx.writeAndFlush(Commands.newSuccess(closeConsumer.getRequestId()));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            log.warn("Got exception", cause);
            ctx.close();
        }

        @Override
        final protected void handlePing(CommandPing ping) {
            // Immediately reply success to ping requests
            ctx.writeAndFlush(Commands.newPong());
        }

        @Override
        final protected void handlePong(CommandPong pong) {
        }
    }

    private final Server server;
    EventLoopGroup workerGroup;
    private Channel listenChannel;

    private CommandConnectHook handleConnect = null;
    private CommandTopicLookupHook handleTopiclookup = null;
    private CommandPartitionLookupHook handlePartitionlookup = null;
    private CommandSubscribeHook handleSubscribe = null;
    private CommandProducerHook handleProducer = null;
    private CommandSendHook handleSend = null;
    private CommandAckHook handleAck = null;
    private CommandFlowHook handleFlow = null;
    private CommandUnsubscribeHook handleUnsubscribe = null;
    private CommandCloseProducerHook handleCloseProducer = null;
    private CommandCloseConsumerHook handleCloseConsumer = null;

    public MockBrokerService() {
        server = new Server(0);
        server.setHandler(new genericResponseHandler());
    }

    public void start() {
        try {
            server.start();
            log.info("Started web service on {}", getHttpAddress());

            startMockBrokerService();
            log.info("Started mock Pulsar service on {}", getBrokerAddress());

            lookupData = new LookupData(getBrokerAddress(), null,
                    getHttpAddress(), null);
        } catch (Exception e) {
            log.error("Error starting mock service", e);
        }
    }

    public void stop() {
        try {
            server.stop();
            workerGroup.shutdownGracefully();
        } catch (Exception e) {
            log.error("Error stopping mock service", e);
        }
    }

    public void startMockBrokerService() throws Exception {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("mock-pulsar-%s").build();
        final int numThreads = 2;

        final int MaxMessageSize = 5 * 1024 * 1024;

        try {
            workerGroup = EventLoopUtil.newEventLoopGroup(numThreads, false, threadFactory);

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(workerGroup, workerGroup);
            bootstrap.channel(EventLoopUtil.getServerSocketChannelClass(workerGroup));
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
                    ch.pipeline().addLast("handler", new MockServerCnx());
                }
            });
            // Bind and start to accept incoming connections.
            listenChannel = bootstrap.bind(0).sync().channel();
        } catch (Exception e) {
            throw e;
        }
    }

    public void setHandleConnect(CommandConnectHook hook) {
        handleConnect = hook;
    }

    public void resetHandleConnect() {
        handleConnect = null;
    }

    public void setHandlePartitionLookup(CommandPartitionLookupHook hook) {
        handlePartitionlookup = hook;
    }

    public void resetHandlePartitionLookup() {
        handlePartitionlookup = null;
    }

    public void setHandleLookup(CommandTopicLookupHook hook) {
        handleTopiclookup = hook;
    }

    public void resetHandleLookup() {
        handleTopiclookup = null;
    }

    public void setHandleSubscribe(CommandSubscribeHook hook) {
        handleSubscribe = hook;
    }

    public void resetHandleSubscribe() {
        handleSubscribe = null;
    }

    public void setHandleProducer(CommandProducerHook hook) {
        handleProducer = hook;
    }

    public void resetHandleProducer() {
        handleProducer = null;
    }

    public void setHandleSend(CommandSendHook hook) {
        handleSend = hook;
    }

    public void resetHandleSend() {
        handleSend = null;
    }

    public void setHandleAck(CommandAckHook hook) {
        handleAck = hook;
    }

    public void resetHandleAck() {
        handleAck = null;
    }

    public void setHandleFlow(CommandFlowHook hook) {
        handleFlow = hook;
    }

    public void resetHandleFlow() {
        handleFlow = null;
    }

    public void setHandleUnsubscribe(CommandUnsubscribeHook hook) {
        handleUnsubscribe = hook;
    }

    public void resetHandleUnsubscribe() {
        handleUnsubscribe = null;
    }

    public void setHandleCloseProducer(CommandCloseProducerHook hook) {
        handleCloseProducer = hook;
    }

    public void resetHandleCloseProducer() {
        handleCloseProducer = null;
    }

    public void setHandleCloseConsumer(CommandCloseConsumerHook hook) {
        handleCloseConsumer = hook;
    }

    public void resetHandleCloseConsumer() {
        handleCloseConsumer = null;
    }

    public String getHttpAddress() {
        return String.format("http://localhost:%d", server.getURI().getPort());
    }

    public String getBrokerAddress() {
        return String.format("pulsar://localhost:%d", ((InetSocketAddress) listenChannel.localAddress()).getPort());
    }

    private static final Logger log = LoggerFactory.getLogger(MockBrokerService.class);
}


text:
package com.rootmc.timothy.RootMC.commands;

import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.rootmc.timothy.RootMC.main.Main;
import com.rootmc.timothy.RootMC.main.messages.MainFormat;

public class admin implements CommandExecutor {
	public static Main plugin;
	public admin (Main instance){
		plugin = instance;
	}
	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String lable,
			String[] args) {
		Player p= (Player) sender;
		if(p.hasPermission("admin") || (p.hasPermission("owner"))){
			p.sendMessage(MainFormat.MainColor()+"<-- ADMIN Commands -->");
			p.sendMessage(MainFormat.MainColor()+"/trevor");
			p.sendMessage(MainFormat.MainColor()+"/rainbows");
			p.sendMessage(MainFormat.MainColor()+"/crash <target> <ErrorType>");
			p.sendMessage(MainFormat.MainColor()+"/damage <target>");
			p.sendMessage(MainFormat.MainColor()+"/staff");
			p.sendMessage(MainFormat.MainColor()+"/mod");
			p.sendMessage(MainFormat.MainColor()+"/pink");
			p.sendMessage(MainFormat.MainColor()+"/countdown");
			p.sendMessage(MainFormat.MainColor()+"<-- END OF ADMIN COMMANDS -->");
			p.playSound(p.getLocation(), Sound.NOTE_PLING, 1, 1);
		}else{
			p.sendMessage(Main.Admin.permissionError());
			p.playSound(p.getLocation(), Sound.ITEM_BREAK, 1, 1);
		}
		return true;
	}

}


text:
typedef unsigned short  NE_16;
typedef unsigned long   NE_32;

// ================================================================
// "Network" byte ordering is the same as big-endianness.
// "Host"    byte ordering is the same as the processor endianness.
//
// So, for big-endian processors, converting back and forth between network and
// host ordering is a no-op.  For little-endian processors, the conversion
// simply amounts to reversing bytes.
//
// Macros provided by this file:
//
// * ntohs -- Network-to-host ordering conversion, for shorts (16-bit integers).
// * htons -- Host-to-network ordering conversion, for shorts (16-bit integers).
// * ntohl -- Network-to-host ordering conversion, for longs  (32-bit integers).
// * htonl -- Host-to-network ordering conversion, for longs  (32-bit integers).

// ----------------------------------------------------------------
#ifdef PROCESSOR_IS_LITTLE_ENDIAN

#define htons(x) ntohs(x)

#define ntohs(x) \
	((((NE_16)(x) & 0x00ff) << 8) | \
	 (((NE_16)(x) & 0xff00) >> 8))

#define htonl(x) ntohl(x)

#define ntohl(x) \
	((((NE_32)(x) & 0x000000ff) << 24) | \
	 (((NE_32)(x) & 0x0000ff00) << 8)  | \
	 (((NE_32)(x) & 0x00ff0000) >> 8)  | \
	 (((NE_32)(x) & 0xff000000) >> 24))

// ----------------------------------------------------------------
#else // Processor is big-endian.
#define htons(x) (x)
#define ntohs(x) (x)
#define htonl(x) (x)
#define ntohl(x) (x)
#endif

// ----------------------------------------------------------------
#endif // NETORDER_H


text:
This repository, [croquet-australia](https://github.com/croquet-australia/croquet-australia), contains an overview of all Croquet Australia repositories & services.

This branch, `phase2/master`, is the current development branch.

## Repositories

The current list of repositories only includes those required by `phase2`. todo: Add all Croquet Australia repositories.

### auth.croquet-australia.com.au

Handles authorisation and authentication for all Croquet Australia resources.

### croquet-australia-domain

- This is the Domain/Model layer.
- It depends on no other Croquet Australia repository.

### croquet-australia-domain-implementation

- Implements interfaces in `croquet-australia-domain` repository.
- It depends on `croquet-australia-domain` repository.
- Microsoft Azure Table Storage is the primary persistence technology.


text:
/**
 * TO DO
 *    Separate the display to include a 'board' and a 'hud'.
 *    The 'board' is intended to display the active game.
 *    The hud displays the user interaction tools.  EG, weapon slots,
 *    spells, potions, etc...
 *
 *    Consider having the display 'listen' for changes to the keyboard state.
 */

"use strict"

var graphics = (function(graphics){
	console.log("display.js loaded");

	/**
	 * Description
	 * @method Display
	 * @param {} canvasID
	 * @return
	 */
	function Display(canvasID){
		this.canvas 	= document.getElementById(canvasID);
		this.context	= this.canvas.getContext("2d");
		this.scale      = 1;
		this.cellSize   = 64;
		this.offset     = {"x" : 0, "y" : 0};
	}

	/**
	 * Description
	 * @method clear
	 * @return
	 */
	Display.prototype.clear = function(){
		this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
	};

	/**
	 * Description
	 * @method getMouseToCell
	 * @param {} x
	 * @param {} y
	 * @return pos
	 */
	Display.prototype.getMouseToCell = function(x, y){
		var pos = {};

		pos.x = Math.floor((x-this.offset.x)/(this.cellSize*this.scale));
		pos.y = Math.floor((y-this.offset.y)/(this.cellSize*this.scale));

		return pos;
	}

	Display.prototype.handleInput = function(input){
		// display scale input
		if(input.keyboard.isPressed(input.keyboard.PLUS)){
			input.keyboard.key[input.keyboard.PLUS].pressed = false;
			this.scale += 0.05;
		}
		if(input.keyboard.isPressed(input.keyboard.MINUS)){
			input.keyboard.key[input.keyboard.MINUS].pressed = false;
			this.scale -= 0.05;
			if(this.scale < 0.2){
				this.scale = 0.2;
			}
		}

		// display location input
		//if(input.keyboard.key[input.keyboard.UP]){
		if(input.keyboard.isPressed(input.keyboard.UP)){
			this.offset.y -= 5;
		}
		//if(input.keyboard.key[input.keyboard.DOWN]){
		if(input.keyboard.isPressed(input.keyboard.DOWN)){
			this.offset.y += 5;
		}
		//if(input.keyboard.key[input.keyboard.LEFT]){
		if(input.keyboard.isPressed(input.keyboard.LEFT)){
			this.offset.x -= 5;
		}
		//if(input.keyboard.key[input.keyboard.RIGHT]){
		if(input.keyboard.isPressed(input.keyboard.RIGHT)){
			this.offset.x += 5;
		}

	};

	graphics.Display = Display

	return graphics;
})(graphics || {});


text:
angular.module('zuluApp.field', []).factory('Field', [function FieldFactory() {
    //Constructor
    var Field = function(input) {
        //input fields
        this.name = input.name;
        this.type = input.type;
        this.length = input.length;

        this.allowNull = !!input.allowNull;

        if (typeof input.defaultValue != undefined) {
            this.defaultValue = input.defaultValue;
        } else {
            this.defaultValue = "";
        }
        this.hasDefaultValue = !!input.hasDefaultValue;
    };

    Field.constants = {};
    Field.constants.dataTypes = [
        { name: "STRING", lengthField: true, isText: true },
        { name: "INTEGER", lengthField: true, unsignable: true, zerofillable: true, isInt: true },
        { name: "BIGINT", lengthField: true, unsignable: true, zerofillable: true, isInt: true },
        { name: "FLOAT", lengthField: true, decimalLengthField: true, unsignable: true, zerofillable: true, isDecimal: true },
        { name: "DECIMAL", lengthField: true, decimalLengthField: true, isDecimal: true },
        { name: "DATE", isDate: true, custom: true },
        { name: "BOOLEAN", isBool: true, custom: true },
        { name: "ENUM", isEnum: true, custom: true }
    ];

    Field.prototype.changeType = function() {

        this.defaultValue='';
    }

    Field.constants.date = {
        dateOptions: {
            formatYear: 'yy',
            startingDay: 1
        },
        formats: ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']
    };

    Field.constants.date.format = Field.constants.date.formats[1]

    Field.constants.getDataTypeByObject = function(input) {
        var output = {};
        for (var i = 0; i < Field.constants.dataTypes.length; i++) {
            if (input.name == Field.constants.dataTypes[i].name) {
                output = Field.constants.dataTypes[i];
                break;
            }
        }
        return output;
    };

    //DATES ONLY
    //for defaultValue -- TODO rename these so it makes sense for defaultValue
    Field.prototype.today = function() {
        this.defaultValue = new Date();
    };

    Field.prototype.clear = function () {
        this.defaultValue = null;
    };

    // Disable weekend selection
    Field.prototype.disabled = function(date, mode) {
        return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
    };

    Field.prototype.toggleMin = function() {
        this.minDate = this.minDate ? null : new Date();
    };

    Field.prototype.open = function($event) {
        $event.preventDefault();
        $event.stopPropagation();

        this.opened = true;
    };

    return Field;
}]);


text:
@(message: String)

@js = {
  @helper.requireJs(core = routes.Assets.at("javascripts/require.js").url, module = routes.Assets.at("js/graphApp").url)
}

@main("Feed", js) {

}


text:
# A0163848R-reused
###### /java/seedu/task/logic/parser/UnmarkCommandParser.java
``` java
/**
 * Parses input arguments and creates a new UnmarkCommand object
 */
public class UnmarkCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the UnmarkCommand
     * and returns an UnmarkCommand object for execution.
     */
    public Command parse(String args) {
        assert args != null;
        ArgumentTokenizer argsTokenizer = new ArgumentTokenizer();
        argsTokenizer.tokenize(args);
        List<Optional<String>> preambleFields = ParserUtil.splitPreamble(argsTokenizer.getPreamble().orElse(""), 2);

        Optional<Integer> index = preambleFields.get(0).flatMap(ParserUtil::parseIndex);
        if (!index.isPresent()) {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE));
        }

        return new UnmarkCommand(index.get());
    }
}
```
###### /java/seedu/task/logic/parser/UndoCommandParser.java
``` java
/**
 * Parses input arguments and creates a new DeleteCommand object
 */
public class UndoCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the UndoCommand
     * and returns an UndoCommand object for execution.
     */
    public Command parse(String args) {
        try {
            return new UndoCommand();
        } catch (NoSuchElementException nsee) {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
        }
    }

}
```
###### /java/seedu/task/logic/commands/ThemeCommand.java
``` java
/**
 * Format full help instructions for every command for display.
 */
public class ThemeCommand extends Command {

    public static final String COMMAND_WORD = "theme";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Shows program theme manager.\n"
            + "Example: " + COMMAND_WORD;

    public static final String SHOWING_THEME_MESSAGE = "Opened theme manager window.";

    @Override
    public CommandResult execute() {
        EventsCenter.getInstance().post(new ShowThemeWindowRequestEvent());
        return new CommandResult(SHOWING_THEME_MESSAGE);
    }
}
```
###### /java/seedu/task/logic/commands/AddCommand.java
``` java
    /**
     * Extracts group from keywords
     * @param keywords to search
     * @return group if found
     */
    private static Optional<Group> getGroup(List<String> keywords) {
        if (keywords.contains(GROUP_KEYWORD)) {
            String inner = StringUtil.extract(keywords, keywords.lastIndexOf(GROUP_KEYWORD) + 1, SPECIAL_KEYWORDS);
            if (!inner.isEmpty()) {
                try {
                    return Optional.of(new Group(inner));
                } catch (IllegalValueException e) {
                }
            }
        }
        return Optional.empty();
    }

    /**
     * Extracts start date from keywords
     * @param keywords to search
     * @return start date if found
     */
    private static Optional<StartDate> getStartDate(List<String> keywords) {
        if (keywords.contains(STARTDATE_KEYWORD)) {
            String inner = StringUtil.extract(keywords, keywords.lastIndexOf(STARTDATE_KEYWORD) + 1, SPECIAL_KEYWORDS);
            if (!inner.isEmpty()) {
                try {
                    return Optional.of(new StartDate(inner));
                } catch (IllegalValueException e) {
                }
            }
        }
        return Optional.empty();
    }

    /**
     * Extracts end date from keywords
     * @param keywords to search
     * @return end date if found
     */
    private static Optional<EndDate> getEndDate(List<String> keywords) {
        if (keywords.contains(ENDDATE_KEYWORD)) {
            String inner = StringUtil.extract(keywords, keywords.lastIndexOf(ENDDATE_KEYWORD) + 1, SPECIAL_KEYWORDS);
            if (!inner.isEmpty()) {
                try {
                    return Optional.of(new EndDate(inner));
                } catch (IllegalValueException e) {
                }
            }
        }
        return Optional.empty();
    }
```
###### /java/seedu/task/logic/commands/UndoCommand.java
``` java
/**
 * Command that undoes changes caused by the last command.
 */
public class UndoCommand extends Command {

    public static final String COMMAND_WORD = "undo";
    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": Undoes the changes made by the last command.\n";
    public static final String UNDO_SUCCESS = "Undo!";
    public static final String UNDO_FAILURE = "Nothing to undo!";

    public UndoCommand() {
    }

    @Override
    public CommandResult execute() throws CommandException {
        boolean result = model.undoLastModification();

        return new CommandResult(result ? UNDO_SUCCESS : UNDO_FAILURE);
    }

}
```
###### /java/seedu/task/logic/commands/UnmarkCommand.java
``` java
/**
 * Command that marks task as incomplete
 */
public class UnmarkCommand extends Command {

    public static final String COMMAND_WORD = "unmark";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Marks as incomplete the task identified "
            + "by the index number used in the last task listing.\n"
            + "Parameters: INDEX (must be a positive integer)\n"
            + "Example: " + COMMAND_WORD + " 1";

```
###### /java/seedu/task/commons/events/storage/LoadRequestEvent.java
``` java
/**
* Represents a request to retrieve the file at the stored path.
*/
public class LoadRequestEvent extends BaseEvent {

    private File target;

    public LoadRequestEvent(File target) {
        this.target = target;
    }

    public File getTargetFile() {
        return target;
    }

    @Override
    public String toString() {
        return "Imported YTomorrow: " + target.toString();
    }
}
```
###### /java/seedu/task/commons/events/storage/LoadResultAvailableEvent.java
``` java
/**
 * Indicates that a new result is available.
 */
public class LoadResultAvailableEvent extends BaseEvent {

    private final Optional<ReadOnlyTaskManager> imported;
    private final File origin;

    public LoadResultAvailableEvent(Optional<ReadOnlyTaskManager> imported, File origin) {
        this.imported = imported;
        this.origin = origin;
    }

    public Optional<ReadOnlyTaskManager> getImported() {
        return imported;
    }

    public File getFile() {
        return origin;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }

}
```


text:
'use strict';

var path = require('chai');
var expect = require('chai').expect;
var parsePath = require('..');

describe('parsePath()', function() {
  describe('when options.ext is defined:', function() {
    var options = {ext: '.js', normalize: true};

    it('should change the extension.', function () {
      var actual = 'foo/bar.json';
      var expected = 'foo/bar.js';
      expect(parsePath(actual, options)).to.eql(expected);
    });

    it('should overwrite multi-extensions with the one defined', function() {
      var fixture = 'foo/bar/baz.min.js';
      var expected = 'foo/bar/baz.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });

    it('should add an extension if one doesn\'t already exist', function() {
      var fixture = 'foo/bar/baz';
      var expected = 'foo/bar/baz.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });
  });

  describe('when options.flatten is defined:', function() {
    var options = {flatten: true, normalize: true};

    it('should strip the dirname from the generated path.', function () {
      var fixture = 'foo/bar.js';
      var expected = 'bar.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });
  });

  describe('when options.destBase is defined:', function() {
    var options = {destBase: 'dist', normalize: true};

    it('should prepend the destBase to the generated path.', function () {
      var fixture = 'foo/bar.js';
      var expected = 'dist/foo/bar.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });
  });

  describe('when options.prefixBase is defined:', function() {
    var options = {prefixBase: true, normalize: true};

    it('should prepend the src dirname to the generated path.', function () {
      var fixture = 'a/b/c/d/e/f/g.js';
      var expected = 'a/b/c/d/e/f/g.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });
  });

  describe('when options.srcBase is defined:', function() {
    var options = {srcBase: 'a/b/c', prefixBase: false, normalize: true};

    it('should strip the srcBase from the file path.', function () {
      var fixture = 'd/e/f/g.js';
      var expected = 'd/e/f/g.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });
  });

  describe('when options.srcBase and prefixBase are defined:', function() {
    var options = {srcBase: 'a/b/c', prefixBase: true, normalize: true};

    it('should prefix the srcBase to the dest path.', function () {
      var fixture = 'd/e/f/g.js';
      var expected = 'a/b/c/d/e/f/g.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });
  });

  describe('when destBase is defined:', function() {
    var options = {prefixBase: true, destBase: 'dist', normalize: true};

    it('should prepend the destBase to the generated path', function () {
      var fixture = 'a/b/c/d/e/f/g.js';
      var expected = 'dist/a/b/c/d/e/f/g.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });
  });

  describe('when prefixBase and destBase are defined:', function() {
    var options = {prefixBase: true, srcBase: 'src', destBase: 'dist', normalize: true};

    it('should prefix the destBase/srcBase to the generated path', function () {
      var fixture = 'a/b/c/d/e/f/g.js';
      var expected = 'dist/src/a/b/c/d/e/f/g.js';
      expect(parsePath(fixture, options)).to.eql(expected);
    });
  });
});

describe('basic mapping', function () {
  it('default options should create same-to-same src-dest mappings.', function (done) {
    var actual = ['a.txt', 'b.txt', 'c.txt'].map(function (filepath) {
      return parsePath(filepath, {
        destBase: 'dist',
        normalize: true
      });
    });
    var expected = ['dist/a.txt', 'dist/b.txt', 'dist/c.txt'];
    expect(actual).to.eql(expected);
    done();
  });
});

describe('options.srcBase', function () {
  it('default options should create same-to-same src-dest mappings.', function (done) {
    var actual = ['a.txt', 'bar/b.txt', 'bar/baz/c.txt'].map(function(filepath) {
      return parsePath(filepath, {srcBase: 'foo', prefixBase: true, normalize: true});
    });

    var expected = ['foo/a.txt', 'foo/bar/b.txt', 'foo/bar/baz/c.txt'];
    expect(actual).to.eql(expected);
    done();
  });
});

describe('options.destBase', function () {
  it('should prefix destBase with a trailing slash', function (done) {
    var actual = ['a.txt', 'bar/b.txt', 'bar/baz/c.txt'].map(function(filepath) {
      return parsePath(filepath, {destBase: 'foo/', normalize: true});
    });

    var expected = ['foo/a.txt', 'foo/bar/b.txt', 'foo/bar/baz/c.txt'];
    expect(actual).to.eql(expected);
    done();
  });

  it('should prefix destBase without a trailing slash', function (done) {
    var actual = ['a.txt', 'bar/b.txt', 'bar/baz/c.txt'].map(function(filepath) {
      return parsePath(filepath, {destBase: 'foo', normalize: true});
    });

    var expected = ['foo/a.txt', 'foo/bar/b.txt', 'foo/bar/baz/c.txt'];
    expect(actual).to.eql(expected);
    done();
  });
});

describe('options.flatten', function () {
  it('should remove the dirname', function (done) {
    var actual = ['a.txt', 'bar/b.txt', 'bar/baz/c.txt'].map(function(filepath) {
      return parsePath(filepath, {flatten: true});
    });

    var expected = ['a.txt', 'b.txt', 'c.txt'];
    expect(actual).to.eql(expected);
    done();
  });
});

describe('options.flatten + options.destBase', function () {
  it('should remove the dirname', function (done) {
    var actual = ['a.txt', 'bar/b.txt', 'bar/baz/c.txt'].map(function (filepath) {
      return parsePath(filepath, {
        flatten: true,
        destBase: 'blah',
        normalize: true
      });
    });

    var expected = ['blah/a.txt', 'blah/b.txt', 'blah/c.txt'];
    expect(actual).to.eql(expected);
    done();
  });
});

describe('options.ext', function () {
  it('should remove the dirname', function (done) {
    var actual = ['a.txt', 'bar/b.txt', 'bar/baz/c.txt'].map(function (filepath) {
      return parsePath(filepath, {
        flatten: true,
        destBase: 'blah',
        ext: '.js',
        normalize: true
      });
    });

    var expected = ['blah/a.js', 'blah/b.js', 'blah/c.js'];
    expect(actual).to.eql(expected);
    done();
  });
});

describe('options.extDot', function () {
  it('should use the first extension', function (done) {
    var actual = ['x/a.js.bar', 'x.y/b.bbb.min.js', 'x.y/z.z/c.js.foo'].map(function(filepath) {
      return parsePath(filepath, {extDot: 'first'});
    });

    var expected = ['x/a.js', 'x.y/b.bbb', 'x.y/z.z/c.js'];
    expect(actual).to.eql(expected);
    done();
  });

  it('should use the last extension', function (done) {
    var actual = ['x/a.js.bar', 'x.y/b.bbb.min.js', 'x.y/z.z/c.js.foo'].map(function(filepath) {
      return parsePath(filepath, {extDot: 'last'});
    });

    var expected = ['x/a.bar', 'x.y/b.js', 'x.y/z.z/c.foo'];
    expect(actual).to.eql(expected);
    done();
  });
});

describe('options.rename', function () {
  it('should use the last extension', function (done) {
    var actual = ['x/a.js.bar', 'x.y/b.bbb.min.js', 'x.y/z.z/c.js.foo'].map(function(filepath) {
      return parsePath(filepath, {
        arbitraryProp: 'ARBITRARY',
        rename: function(filepath) {
          return this.arbitraryProp + '/' + filepath.toUpperCase();
        }
      });
    });

    var expected = ['ARBITRARY/X/A.JS', 'ARBITRARY/X.Y/B.BBB', 'ARBITRARY/X.Y/Z.Z/C.JS'];
    expect(actual).to.eql(expected);
    done();
  });
});


text:
package org.apache.ignite.spi.collision.priorityqueue;

import org.apache.ignite.testframework.junits.spi.GridSpiAbstractConfigTest;
import org.apache.ignite.testframework.junits.spi.GridSpiTest;

/**
 * Priority queue collision SPI config test.
 */
@GridSpiTest(spi = PriorityQueueCollisionSpi.class, group = "Collision SPI")
public class GridPriorityQueueCollisionSpiConfigSelfTest
    extends GridSpiAbstractConfigTest<PriorityQueueCollisionSpi> {
    /**
     * @throws Exception If failed.
     */
    public void testNegativeConfig() throws Exception {
        checkNegativeSpiProperty(new PriorityQueueCollisionSpi(), "parallelJobsNumber", 0);
        checkNegativeSpiProperty(new PriorityQueueCollisionSpi(), "waitingJobsNumber", -1);
        checkNegativeSpiProperty(new PriorityQueueCollisionSpi(), "starvationIncrement", -1);
        checkNegativeSpiProperty(new PriorityQueueCollisionSpi(), "priorityAttributeKey", null);
        checkNegativeSpiProperty(new PriorityQueueCollisionSpi(), "jobPriorityAttributeKey", null);
    }
}


text:
using namespace Eugenix;

class Example : public App
{
protected:
	virtual bool OnInit()
	{
		_camera = Perspective(glm::radians(45.0f), (float)Runtime::Setup().width / (float)Runtime::Setup().height, 0.1f, 100.0f);
		_camera->LookAt(glm::vec3(0, -3, -3), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
		_camera->SetClearMask(ClearBits::All);
		_camera->SetClearColor(Color{ 0.2f, 0.3f, 0.3f, 1.0f });

		_projView = _camera->GetProjection() * _camera->GetView();

		auto texture = std::make_shared<Texture>();
		texture->UploadData(ImageLoader::LoadImage("texture.tga"));

		auto renderObject = std::make_shared<RenderObject>();
		renderObject->mesh = MeshBuilder::CreateCube();
		renderObject->program = ShaderEnv::Defaults::SimpleDiffuse();
		renderObject->texture = texture;
		renderObject->transform.model = glm::rotate(renderObject->transform.model, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
		renderObject->transform.model = glm::translate(renderObject->transform.model, glm::vec3(1.0f, 0.0f, 0.0f));
		_renderQueue.Push(renderObject);

		auto renderObject2 = std::make_shared<RenderObject>();
		renderObject2->mesh = MeshBuilder::CreateCube();
		renderObject2->program = ShaderEnv::Defaults::SimpleDiffuse();
		renderObject2->texture = texture;
		renderObject2->transform.model = glm::rotate(renderObject2->transform.model, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
		renderObject2->transform.model = glm::translate(renderObject2->transform.model, glm::vec3(-1.0f, 0.0f, 0.0f));
		_renderQueue.Push(renderObject2);

		glEnable(GL_DEPTH_TEST);

		return true;
	}

	virtual void OnShutdown()
	{
	}

	virtual void OnRender()
	{
		_renderer.Draw(_camera, _renderQueue);
	}

private:

	CameraPtr _camera;
	Renderer _renderer;
	RenderQueue _renderQueue;

	glm::mat4 _projView;
};

int main()
{
	Example app;
	return app.Run();
}


text:
package cz.krtinec.telka.images;

import android.graphics.drawable.BitmapDrawable;
import android.util.DisplayMetrics;

public class CompatibilityUtils {
	public static boolean hasSettingTargetDensityOnBitmapDrawable(){
		//check if device platform has following method BitmapDrawable.setTargetDensity
		try {
			BitmapDrawable.class.getMethod("setTargetDensity", DisplayMetrics.class);
			return true;
		} catch (SecurityException e) {
		} catch (NoSuchMethodException e) {
		}
		return false;
	}
}


text:
Did you ever have that problem where you needed "production data" to find a bug
or do performance tests outside of the client's production environment? Are
you worried about protecting that data? Do you add screenshots to your bug
reports? Can you live with surrogate data with the same properties? Then this
tool is for you.

Running Anonimatron is as simple as downloading, unzipping and running
`anonimatron.sh` or `anonimatron.bat`.

Please find all documentation, downloads and quickstarts at the
[Anonimatron official homepage](https://realrolfje.github.io/anonimatron/).


text:
import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';

@Directive({
  selector: 'cubx-date-input'
})
export class DateInputDirective {
  private _cifReady: boolean;

  private _value: string;
  private _label: number;
  private _disabled: number;
  private _required: number;

  @Output('valueChanged')
  valueChangedEvent: EventEmitter<string> = new EventEmitter();

  constructor(private elementRef: ElementRef) {
    this._cifReady = false;
  }

  @HostListener('window:cifDomUpdateReady', ['$event'])
  @HostListener('window:cifReady', ['$event'])
  onCifReady(event) {
    this._cifReady = true;
    this.updateElement();

    const self = this;

    // send init value
    self.valueChangedEvent.emit(self.elementRef.nativeElement.getValue());

    // after cubbles propagate data, send new value
    this.elementRef.nativeElement.addEventListener('cifModelChange', function(evt){
      if (evt.detail.slot === 'value') {
        self.valueChangedEvent.emit(evt.detail.payload);
      }
    });
  }

  updateElement() {
    if (this._cifReady) {
      this.elementRef.nativeElement.setValue(this._value);
      this.elementRef.nativeElement.setLabel(this._label);
      this.elementRef.nativeElement.setDisabled(this._disabled);
      this.elementRef.nativeElement.setRequired(this._required);
    }
  }

  @Input()
  set value(value: string) {
    this._value = value;
    this.updateElement();
  }

  @Input()
  set label(value: number) {
    this._label = value;
    this.updateElement();
  }

  @Input()
  set disabled(value: number) {
    this._disabled = value;
    this.updateElement();
  }

  @Input()
  set required(value: number) {
    this._required = value;
    this.updateElement();
  }
}


text:
<?php

namespace SMW\MediaWiki\Hooks;

use File;
use ParserOptions;
use SMW\ApplicationFactory;
use SMW\Localizer;
use Title;
use User;

/**
 * Fires when a local file upload occurs
 *
 * @see https://www.mediawiki.org/wiki/Manual:Hooks/FileUpload
 *
 * @license GNU GPL v2+
 * @since 1.9.1
 *
 * @author mwjames
 */
class FileUpload {

	/**
	 * @var File
	 */
	private $file = null;

	/**
	 * @var ApplicationFactory
	 */
	private $applicationFactory = null;

	private $fileReUploadStatus = false;

	/**
	 * @since  1.9.1
	 *
	 * @param File $file
	 * @param boolean $fileReUploadStatus
	 */
	public function __construct( File $file, $fileReUploadStatus = false ) {
		$this->file = $file;
		$this->fileReUploadStatus = $fileReUploadStatus;
	}

	/**
	 * @since 1.9.1
	 *
	 * @return true
	 */
	public function process() {
		return $this->canPerformUpdate() ? $this->performUpdate() : true;
	}

	private function canPerformUpdate() {

		if ( $this->file->getTitle() !== null && $this->isSemanticEnabledNamespace( $this->file->getTitle() ) ) {
			return true;
		}

		return false;
	}

	private function performUpdate() {

		$this->applicationFactory = ApplicationFactory::getInstance();

		$filePage = $this->makeFilePage();

		$parserData = $this->applicationFactory
			->newParserData(
				$this->file->getTitle(),
				$filePage->getParserOutput( $this->makeCanonicalParserOptions() ) );

		$pageInfoProvider = $this->applicationFactory
			->newMwCollaboratorFactory()
			->newPageInfoProvider( $filePage );

		$propertyAnnotator = $this->applicationFactory
			->newPropertyAnnotatorFactory()
			->newPredefinedPropertyAnnotator( $parserData->getSemanticData(), $pageInfoProvider );

		$propertyAnnotator->addAnnotation();

		$parserData->pushSemanticDataToParserOutput();
		$parserData->updateStore();

		return true;
	}

	private function makeFilePage() {

		$filePage = $this->applicationFactory->newPageCreator()->createFilePage( $this->file->getTitle() );
		$filePage->setFile( $this->file );

		$filePage->smwFileReUploadStatus = $this->fileReUploadStatus;

		return $filePage;
	}

	/**
	 * Anonymous user with default preferences and content language
	 */
	private function makeCanonicalParserOptions() {
		return ParserOptions::newFromUserAndLang(
			new User(),
			Localizer::getInstance()->getContentLanguage()
		);
	}

	private function isSemanticEnabledNamespace( Title $title ) {
		return ApplicationFactory::getInstance()->getNamespaceExaminer()->isSemanticEnabled( $title->getNamespace() );
	}

}


text:
using BinarySearchTree;

BstTester.Test(new BstNonRecursive<string, int>());


text:
copyright:
  years: 2016
lastupdated: "2016-10-26"

---

{:new_window: target="\_blank"}
{:shortdesc: .shortdesc}
{:screen:.screen}
{:codeblock:.codeblock}

# Cómo funciona el servicio
{{site.data.keyword.iotinsurance_full}} crea un flujo para recopilar, gestionar y analizar datos de los asegurados conectados.
{:shortdesc}

El proveedor del seguro crea una instancia de {{site.data.keyword.iotinsurance_short}} en la organización de {{site.data.keyword.Bluemix_notm}}. Los clientes del asegurador tienen sensores en sus casas, conectados a la nube del proveedor del sensor. Desde sus dispositivos móviles, los clientes autorizan al servicio {{site.data.keyword.iotinsurance_short}} para recibir datos de sensor. El transformador {{site.data.keyword.iotinsurance_short}} se conecta a la nube del proveedor del sensor y extrae datos para cada usuario y los envía al servidor de {{site.data.keyword.iot_short_notm}}. Si el sensor muestra que se cumplen los parámetros especificados en las coberturas del asegurador en el hogar del cliente, las notificaciones se enviarán al panel de control del asegurador y al dispositivo del cliente.

Un sensor conectado detecta un suceso, como una fuga de agua, y envía la información a un proveedor de hogares inteligentes, como Wink. {{site.data.keyword.iotinsurance_short}} detecta la señal utilizando su conexión con la nube del proveedor de hogares inteligentes y crea una carga útil de la alerta. La carga útil se envía a través de MQTT al motor de coberturas {{site.data.keyword.iotinsurance_short}} para su procesamiento. El motor de coberturas analiza si la carga útil coincide con los criterios que se definen en las reglas de cobertura. Si coincide, el motor de coberturas emite una carga útil de riesgo a través de MQTT al motor de acción {{site.data.keyword.iotinsurance_short}}. El motor de acción realiza acciones que define la cobertura para ese tipo de riesgo, por ejemplo, enviar un mensaje de texto al propietario del hogar.

{{site.data.keyword.iotinsurance_short}} confía en {{site.data.keyword.iot_full}} para pasar cargas útiles de alerta y riesgo entre sus componentes. Un sistema de trabajo completo requiere usuarios, coberturas y asociaciones entre usuarios y coberturas.

![Proceso {{site.data.keyword.iotinsurance_short}}. En este diagrama se describe el cuerpo principal del tema.](images/IoT4I_process.svg "Proceso {{site.data.keyword.iotinsurance_short}}")

# Enlaces relacionados
{: #rellinks}

## Guías de aprendizaje y ejemplos
{: #samples}
* [Código de app para móvil de ejemplo en GitHub](https://github.com/ibm-watson-iot/ioti-mobile){:new_window}

## Referencia de API
{: #api}
* [API de {{site.data.keyword.iotinsurance_short}}](https://iot4i-api-docs.mybluemix.net/){:new_window}
* [Ejemplos de API de {{site.data.keyword.iotinsurance_short}}](https://github.com/IBM-Bluemix/iot4i-api-examples-nodejs/#iot-for-insurance-api-examples){:new_window}

## Enlaces relacionados
{: #general}
* [Documentación de {{site.data.keyword.iot_full}}](https://console.ng.bluemix.net/docs/services/IoT/index.html)
* [Foro de soporte para desarrolladores](https://developer.ibm.com/answers/search.html?f=&type=question&redirect=search%2Fsearch&sort=relevance&q=%2B[iot]%20%2B[bluemix])
* [Foro de soporte de Stack Overflow](http://stackoverflow.com/questions/tagged/ibm-bluemix)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.workloads.models;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;

/** Resource collection API of SapCentralInstances. */
public interface SapCentralInstances {
    /**
     * Gets the SAP Central Instance.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param sapVirtualInstanceName The name of the Virtual Instances for SAP.
     * @param centralInstanceName Central Instance name string modeled as parameter for auto generation to work
     *     correctly.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the SAP Central Instance.
     */
    SapCentralServerInstance get(String resourceGroupName, String sapVirtualInstanceName, String centralInstanceName);

    /**
     * Gets the SAP Central Instance.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param sapVirtualInstanceName The name of the Virtual Instances for SAP.
     * @param centralInstanceName Central Instance name string modeled as parameter for auto generation to work
     *     correctly.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the SAP Central Instance along with {@link Response}.
     */
    Response<SapCentralServerInstance> getWithResponse(
        String resourceGroupName, String sapVirtualInstanceName, String centralInstanceName, Context context);

    /**
     * Deletes the SAP Central Instance.

This will be used by service only. Delete by end user will
     * return a Bad Request error.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param sapVirtualInstanceName The name of the Virtual Instances for SAP.
     * @param centralInstanceName Central Instance name string modeled as parameter for auto generation to work
     *     correctly.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the current status of an async operation.
     */
    OperationStatusResult delete(String resourceGroupName, String sapVirtualInstanceName, String centralInstanceName);

    /**
     * Deletes the SAP Central Instance.

This will be used by service only. Delete by end user will
     * return a Bad Request error.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param sapVirtualInstanceName The name of the Virtual Instances for SAP.
     * @param centralInstanceName Central Instance name string modeled as parameter for auto generation to work
     *     correctly.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the current status of an async operation.
     */
    OperationStatusResult delete(
        String resourceGroupName, String sapVirtualInstanceName, String centralInstanceName, Context context);

    /**
     * Lists the SAP Central Instances in an SVI.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param sapVirtualInstanceName The name of the Virtual Instances for SAP.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return defines the collection of SAP Central Instances as paginated response with {@link PagedIterable}.
     */
    PagedIterable<SapCentralServerInstance> list(String resourceGroupName, String sapVirtualInstanceName);

    /**
     * Lists the SAP Central Instances in an SVI.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param sapVirtualInstanceName The name of the Virtual Instances for SAP.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return defines the collection of SAP Central Instances as paginated response with {@link PagedIterable}.
     */
    PagedIterable<SapCentralServerInstance> list(
        String resourceGroupName, String sapVirtualInstanceName, Context context);

    /**
     * Gets the SAP Central Instance.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the SAP Central Instance along with {@link Response}.
     */
    SapCentralServerInstance getById(String id);

    /**
     * Gets the SAP Central Instance.
     *
     * @param id the resource ID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the SAP Central Instance along with {@link Response}.
     */
    Response<SapCentralServerInstance> getByIdWithResponse(String id, Context context);

    /**
     * Deletes the SAP Central Instance.

This will be used by service only. Delete by end user will
     * return a Bad Request error.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the current status of an async operation.
     */
    OperationStatusResult deleteById(String id);

    /**
     * Deletes the SAP Central Instance.

This will be used by service only. Delete by end user will
     * return a Bad Request error.
     *
     * @param id the resource ID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the current status of an async operation.
     */
    OperationStatusResult deleteByIdWithResponse(String id, Context context);

    /**
     * Begins definition for a new SapCentralServerInstance resource.
     *
     * @param name resource name.
     * @return the first stage of the new SapCentralServerInstance definition.
     */
    SapCentralServerInstance.DefinitionStages.Blank define(String name);
}


text:
package org.xdi.oxauth.ws.rs;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.xdi.oxauth.BaseTest;
import org.xdi.oxauth.client.*;
import org.xdi.oxauth.model.common.*;
import org.xdi.oxauth.model.crypto.signature.RSAPublicKey;
import org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm;
import org.xdi.oxauth.model.jws.RSASigner;
import org.xdi.oxauth.model.jwt.Jwt;
import org.xdi.oxauth.model.jwt.JwtClaimName;
import org.xdi.oxauth.model.jwt.JwtHeaderName;
import org.xdi.oxauth.model.register.ApplicationType;
import org.xdi.oxauth.model.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import static org.testng.Assert.*;

/**
 * Functional tests for Sector Identifier URI Verification (HTTP)
 *
 * @author Javier Rojas Blum
 * @version August 21, 2015
 */
public class SectorIdentifierUrlVerificationHttpTest extends BaseTest {

    @Parameters({"redirectUris", "sectorIdentifierUri", "redirectUri", "userId", "userSecret"})
    @Test // This test requires a place to publish a sector identifier JSON array of redirect URIs via HTTPS
    public void requestAuthorizationCodeWithSectorIdentifier(
            final String redirectUris, final String sectorIdentifierUri, final String redirectUri,
            final String userId, final String userSecret) throws Exception {
        showTitle("requestAuthorizationCodeWithSectorIdentifier");

        List<ResponseType> responseTypes = Arrays.asList(
                ResponseType.CODE,
                ResponseType.ID_TOKEN);

        // 1. Register client with Sector Identifier URL
        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
        registerRequest.setResponseTypes(responseTypes);
        registerRequest.setSubjectType(SubjectType.PAIRWISE);
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
        registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse registerResponse = registerClient.exec();

        showClient(registerClient);
        assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
        assertNotNull(registerResponse.getClientId());
        assertNotNull(registerResponse.getClientSecret());
        assertNotNull(registerResponse.getRegistrationAccessToken());
        assertNotNull(registerResponse.getClientSecretExpiresAt());

        String clientId = registerResponse.getClientId();
        String clientSecret = registerResponse.getClientSecret();

        // 2. Request authorization and receive the authorization code.
        List<String> scopes = Arrays.asList(
                "openid",
                "profile",
                "address",
                "email");
        String state = UUID.randomUUID().toString();
        String nonce = UUID.randomUUID().toString();

        AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
        authorizationRequest.setState(state);
        authorizationRequest.setAuthUsername(userId);
        authorizationRequest.setAuthPassword(userSecret);
        authorizationRequest.getPrompts().add(Prompt.NONE);

        AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
        authorizeClient.setRequest(authorizationRequest);
        AuthorizationResponse authorizationResponse = authorizeClient.exec();

        showClient(authorizeClient);
        assertEquals(authorizationResponse.getStatus(), 302, "Unexpected response code: " + authorizationResponse.getStatus());
        assertNotNull(authorizationResponse.getLocation(), "The location is null");
        assertNotNull(authorizationResponse.getCode(), "The authorization code is null");
        assertNotNull(authorizationResponse.getState(), "The state is null");
        assertNotNull(authorizationResponse.getScope(), "The scope is null");
        assertEquals(authorizationResponse.getState(), state);

        String authorizationCode = authorizationResponse.getCode();
        String idToken = authorizationResponse.getIdToken();

        // 3. Validate id_token
        Jwt jwt = Jwt.parse(idToken);
        assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
        assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));

        RSAPublicKey publicKey = JwkClient.getRSAPublicKey(
                jwksUri,
                jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
        RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);

        assertTrue(rsaSigner.validate(jwt));

        // 4. Request access token using the authorization code.
        TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
        tokenRequest.setCode(authorizationCode);
        tokenRequest.setRedirectUri(redirectUri);
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

        TokenClient tokenClient = new TokenClient(tokenEndpoint);
        tokenClient.setRequest(tokenRequest);
        TokenResponse tokenResponse = tokenClient.exec();

        showClient(tokenClient);
        assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
        assertNotNull(tokenResponse.getEntity(), "The entity is null");
        assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
        assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null");
        assertNotNull(tokenResponse.getTokenType(), "The token type is null");
        assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");

        String accessToken = tokenResponse.getAccessToken();

        // 5. Request user info
        UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
        UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);

        showClient(userInfoClient);
        assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus());
        assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
        assertNotNull(userInfoResponse.getClaim(JwtClaimName.NAME));
        assertNotNull(userInfoResponse.getClaim(JwtClaimName.GIVEN_NAME));
        assertNotNull(userInfoResponse.getClaim(JwtClaimName.FAMILY_NAME));
        assertNotNull(userInfoResponse.getClaim(JwtClaimName.EMAIL));
        assertNotNull(userInfoResponse.getClaim(JwtClaimName.ZONEINFO));
        assertNotNull(userInfoResponse.getClaim(JwtClaimName.LOCALE));
    }

    @Parameters({"redirectUris"})
    @Test
    public void sectorIdentifierUrlVerificationFail1(final String redirectUris) throws Exception {
        showTitle("sectorIdentifierUrlVerificationFail1");

        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
        registerRequest.setSectorIdentifierUri("https://INVALID_SECTOR_IDENTIFIER_URL");

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse response = registerClient.exec();

        showClient(registerClient);
        assertEquals(response.getStatus(), 400, "Unexpected response code: " + response.getEntity());
        assertNotNull(response.getEntity(), "The entity is null");
        assertNotNull(response.getErrorType(), "The error type is null");
        assertNotNull(response.getErrorDescription(), "The error description is null");
    }

    @Parameters({"sectorIdentifierUri"})
    @Test // This test requires a place to publish a sector identifier JSON array of redirect URIs via HTTPS
    public void sectorIdentifierUrlVerificationFail2(final String sectorIdentifierUri) throws Exception {
        showTitle("sectorIdentifierUrlVerificationFail2");

        String redirectUris = "https://INVALID_REDIRECT_URI https://client.example.com/cb https://client.example.com/cb1 https://client.example.com/cb2";

        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
        registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse response = registerClient.exec();

        showClient(registerClient);
        assertEquals(response.getStatus(), 400, "Unexpected response code: " + response.getEntity());
        assertNotNull(response.getEntity(), "The entity is null");
        assertNotNull(response.getErrorType(), "The error type is null");
        assertNotNull(response.getErrorDescription(), "The error description is null");
    }

    /**
     * Register with pairwise Subject Type and without Sector Identifier URI must fail because there are multiple
     * hostnames in the Redirect URI list.
     */
    @Parameters({"redirectUris"})
    @Test
    public void sectorIdentifierUrlVerificationFail3(final String redirectUris) throws Exception {
        showTitle("sectorIdentifierUrlVerificationFail3");

        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                StringUtils.spaceSeparatedToList(redirectUris));
        registerRequest.setSubjectType(SubjectType.PAIRWISE);
        registerRequest.setSectorIdentifierUri(null);

        RegisterClient registerClient = new RegisterClient(registrationEndpoint);
        registerClient.setRequest(registerRequest);
        RegisterResponse response = registerClient.exec();

        showClient(registerClient);
        assertEquals(response.getStatus(), 400, "Unexpected response code: " + response.getEntity());
        assertNotNull(response.getEntity(), "The entity is null");
        assertNotNull(response.getErrorType(), "The error type is null");
        assertNotNull(response.getErrorDescription(), "The error description is null");
    }
}


text:
// Author: Jonathan Park
#include <bgpparser.h>

#include "AttributeTypeOriginatorID.h"

using namespace std;
namespace io = boost::iostreams;

log4cxx::LoggerPtr AttributeTypeOriginatorID::Logger =
  log4cxx::Logger::getLogger("bgpparser.AttributeTypeOriginatorID");

AttributeTypeOriginatorID::AttributeTypeOriginatorID(AttributeType& header, istream& input)
  : AttributeType(header)
{
  LOG4CXX_TRACE(Logger, "");

  bool error = sizeof(originator_id)
               != io::read(input, reinterpret_cast<char*>(&originator_id), sizeof(originator_id));

  if (error) {
    LOG4CXX_ERROR(Logger, "Parsing error");
    throw BGPError();
  }
}

AttributeTypeOriginatorID::~AttributeTypeOriginatorID(void)
{
  /* nothing */
}
//
// void AttributeTypeOriginatorID::printMe() {
//	IPAddress addr;
//	memcpy(&addr,&originator_id,sizeof(uint32_t));
//	std::cout << "ORIGINATOR-ID: ";
//	PRINT_IP_ADDR(addr.ipv4);
//}
//
// void AttributeTypeOriginatorID::printMeCompact() {
//	IPAddress addr;
//	memcpy(&addr,&originator_id,sizeof(uint32_t));
//	std::cout << "ORIGINATOR-ID: ";
//	PRINT_IP_ADDR(addr.ipv4);
//}


text:
#pragma once

#include <array>
#include <cstring>
#include <functional>
#include <memory>
#include <sstream>
#include <string>
#include <typeinfo>
#include <type_traits>

#pragma warning(disable: 4091)
#include <cor.h>
#pragma warning(default: 4091)
#include <ppltasks.h>
#include <CppUnitTest.h>

#include <simply/assert.h>
#include <simply/com.h>
#include <simply/utility.h>

#include <unconstrained/clr/metadata.h>


text:
@implementation DottedSeparatorView

#define MARGIN_LEFT		22
#define MARGIN_RIGHT	10

- (id) initWithFrame: (NSRect) frame
{
	self = [super initWithFrame: frame];
	if (self)
	{
		[self setAutoresizingMask: NSViewWidthSizable];
	}
	return self;
}

- (void) dealloc
{
	[path release];
	[super dealloc];
}

- (void) drawRect: (NSRect) frame
{
	if (path == nil)
	{
		CGFloat y = (int) frame.size.height / 2;

		path = [[NSBezierPath bezierPath] retain];
		[path moveToPoint: NSMakePoint(MARGIN_LEFT, y + 0.5)];
		[path lineToPoint: NSMakePoint(frame.size.width - MARGIN_LEFT - MARGIN_RIGHT, y + 0.5)];
		[path setLineWidth: 1];

		CGFloat dash[2] = {1, 4};
		[path setLineDash: dash count: 2 phase: 0];
	}

	[[NSColor colorWithCalibratedWhite: 0 alpha: 0.3] set];
	[path stroke];
}

@end


text:
:Description: This model is the same as ToyMMB with an extra link from PI3K to NFkB.
:Model: **PKN-ToyMMB_added_link**
:Data: use MD-ToyMMB.csv

References
===========

.. [1] **M. K. Morris, I. Melas, J. Saez-Rodriguez.**
   *Construction of cell type-specific logic models of signaling networks
   using CellNetOptimizer.*
   to appear in Methods in Molecular Biology:Computational Toxicology, Ed.
   B. Reisfeld and A. Mayeno, Humana Press.

Notes
=======

Was named **ToyMMB_bis** in cellnopt.data package. Changed the name to make
clear the different with **ToyMMB*.