text:
package com.ircclouds.irc.api;

import com.ircclouds.irc.api.commands.ChangeModeCmd;
import com.ircclouds.irc.api.commands.ChangeNickCmd;
import com.ircclouds.irc.api.commands.ChangeTopicCmd;
import com.ircclouds.irc.api.commands.ConnectCmd;
import com.ircclouds.irc.api.commands.JoinChanCmd;
import com.ircclouds.irc.api.commands.KickUserCmd;
import com.ircclouds.irc.api.commands.PartChanCmd;
import com.ircclouds.irc.api.commands.QuitCmd;
import com.ircclouds.irc.api.commands.SendActionMessage;
import com.ircclouds.irc.api.commands.SendNoticeMessage;
import com.ircclouds.irc.api.commands.SendPrivateMessage;
import com.ircclouds.irc.api.commands.SendRawMessage;
import com.ircclouds.irc.api.commands.interfaces.ICapCmd;
import com.ircclouds.irc.api.commands.interfaces.ICommand;
import com.ircclouds.irc.api.dcc.DCCManager;
import com.ircclouds.irc.api.domain.IRCChannel;
import com.ircclouds.irc.api.domain.IRCServerOptions;
import com.ircclouds.irc.api.domain.WritableIRCChannel;
import com.ircclouds.irc.api.interfaces.Callback;
import com.ircclouds.irc.api.interfaces.IIRCApi;
import com.ircclouds.irc.api.interfaces.IIRCSession;
import com.ircclouds.irc.api.interfaces.IServerParameters;
import com.ircclouds.irc.api.listeners.AbstractExecuteCommandListener;
import com.ircclouds.irc.api.listeners.ExecuteCommandListenerImpl;
import com.ircclouds.irc.api.listeners.PingVersionListenerImpl;
import com.ircclouds.irc.api.negotiators.CapabilityNegotiator;
import com.ircclouds.irc.api.state.AbstractIRCStateUpdater;
import com.ircclouds.irc.api.state.DisconnectedIRCState;
import com.ircclouds.irc.api.state.IIRCState;
import com.ircclouds.irc.api.state.IRCState;
import com.ircclouds.irc.api.state.IStateAccessor;
import com.ircclouds.irc.api.utils.NetUtils;

import net.engio.mbassy.bus.MBassador;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import static com.ircclouds.irc.api.dcc.DCCManager.DCC_SEND_TIMEOUT;

/**
 * The main implementation of {@link IIRCApi}. It offers the ability to save the
 * IRC state, and allows for extensibility through {@link #getIRCSession()}.
 *
 * This implementation provides logging via slf4j.
 *
 * @author miguel@lebane.se
 *
 */
public class IRCApi implements IIRCApi
{
	private static final Logger LOG = LoggerFactory.getLogger(IRCApi.class);

	private final IIRCSession session;
	private final AbstractExecuteCommandListener executeCmdListener;
	private IIRCState state;
	private int asyncId = 0;

	private final DCCManager dccManager;

	/**
	 *
	 * @param aSaveIRCState
	 *            A flag to allow saving the IRC state that will be obtained by
	 *            {@link #connect(IServerParameters, Callback)}
	 */
	public IRCApi(Boolean aSaveIRCState)
	{
		state = new DisconnectedIRCState();
		session = new AbstractIRCSession()
		{
			@Override
			protected IRCServerOptions getIRCServerOptions()
			{
				return state.getServerOptions();
			}
		};

		session.register(
				executeCmdListener = new ExecuteCommandListenerImpl(session, getStateUpdater(aSaveIRCState)),
				new PingVersionListenerImpl(session)
		);

		dccManager = new DCCManager(this);
	}

	@Override
	public void connect(final IServerParameters aServerParameters, final Callback<IIRCState> aCallback)
	{
		connect(aServerParameters, aCallback, null);
	}

	@Override
	public void connect(final IServerParameters aServerParameters, final Callback<IIRCState> aCallback, final CapabilityNegotiator negotiator)
	{
		if (state.isConnected())
		{
			aCallback.onFailure(new ApiException("Already connected!"));
			return;
		}

		Dirty _d = new Dirty();
		Callback<IIRCState> _connectCallback = newConnectCallback(aCallback, _d);
		executeCmdListener.submitConnectCallback(_connectCallback, aServerParameters);

		boolean _isOpen = false;
		try
		{
			if (_isOpen = session.open(aServerParameters.getServer(), _connectCallback))
			{
				final ICapCmd initCmd;
				if (negotiator == null)
				{
					initCmd = null;
				}
				else
				{
					session.register(negotiator);
					initCmd = negotiator.initiate(this);
				}
				executeAsync(new ConnectCmd(aServerParameters, initCmd), aCallback, _d);
			}
			else
			{
				aCallback.onFailure(new ApiException("Failed to open connection to [" + aServerParameters.getServer().toString() + "]"));
			}
		}
		catch (IOException aExc)
		{
			_isOpen = true;
			LOG.error("Error opening session", aExc);

			tryInvokeCallback(aCallback, _d, aExc);
		}
		finally
		{
			if (!_isOpen)
			{
				closeSession(aCallback, _d);
			}
		}
	}

	@Override
	public void disconnect(String aQuitMessage)
	{
		checkConnected();

		execute(new QuitCmd(aQuitMessage));
	}

	@Override
	public void disconnect()
	{
		checkConnected();

		execute(new QuitCmd());
	}

	@Override
	public void joinChannel(String aChannelName)
	{
		joinChannel(aChannelName, "");
	}

	@Override
	public void joinChannel(String aChannelName, Callback<IRCChannel> aCallback)
	{
		joinChannel(aChannelName, "", aCallback);
	}

	@Override
	public void joinChannel(String aChannelName, String aKey)
	{
		checkConnected();

		execute(new JoinChanCmd(prependChanType(aChannelName), aKey));
	}

	@Override
	public void joinChannel(String aChannelName, String aKey, final Callback<IRCChannel> aCallback)
	{
		if (!state.isConnected())
		{
			aCallback.onFailure(new ApiException("Not connected!"));
			return;
		}

		aChannelName = prependChanType(aChannelName).toLowerCase();

		Dirty _d = new Dirty();
		executeCmdListener.submitJoinChannelCallback(aChannelName, getDirtyCallback(aCallback, _d));
		executeAsync(new JoinChanCmd(aChannelName, aKey), aCallback, _d);
	}

	@Override
	public void leaveChannel(String aChannelName)
	{
		leaveChannel(aChannelName, "");
	}

	@Override
	public void leaveChannel(String aChannelName, Callback<String> aCallback)
	{
		leaveChannel(aChannelName, "", aCallback);
	}

	@Override
	public void leaveChannel(String aChannelName, String aPartMessage)
	{
		checkConnected();

		execute(new PartChanCmd(aChannelName, aPartMessage));
	}

	@Override
	public void leaveChannel(String aChannelName, String aPartMessage, Callback<String> aCallback)
	{
		if (!state.isConnected())
		{
			aCallback.onFailure(new ApiException("Not connected!"));
			return;
		}

		aChannelName = prependChanType(aChannelName).toLowerCase();

		Dirty _d = new Dirty();
		executeCmdListener.submitPartChannelCallback(aChannelName, getDirtyCallback(aCallback, _d));
		executeAsync(new PartChanCmd(aChannelName, aPartMessage), aCallback, _d);
	}

	@Override
	public void message(String aTarget, String aMessage)
	{
		checkConnected();

		execute(new SendPrivateMessage(aTarget, aMessage));
	}

	@Override
	public void message(String aTarget, String aMessage, Callback<String> aCallback)
	{
		if (!state.isConnected())
		{
			aCallback.onFailure(new ApiException("Not connected!"));
			return;
		}

		Dirty _d = new Dirty();
		executeCmdListener.submitSendMessageCallback(asyncId, getDirtyCallback(aCallback, _d));

		executeAsync(new SendPrivateMessage(aTarget, aMessage, asyncId++), aCallback, _d);
	}

	@Override
	public void act(String aTarget, String aActionMessage)
	{
		checkConnected();

		execute(new SendActionMessage(aTarget, aActionMessage));
	}

	@Override
	public void act(String aTarget, String aActionMessage, Callback<String> aCallback)
	{
		if (!state.isConnected())
		{
			aCallback.onFailure(new ApiException("Not connected!"));
			return;
		}

		Dirty _d = new Dirty();
		executeCmdListener.submitSendMessageCallback(asyncId, getDirtyCallback(aCallback, _d));

		executeAsync(new SendActionMessage(aTarget, aActionMessage, asyncId++), aCallback, _d);
	}

	@Override
	public void notice(String aTarget, String aText)
	{
		checkConnected();

		execute(new SendNoticeMessage(aTarget, aText));
	}

	@Override
	public void notice(String aTarget, String aText, Callback<String> aCallback)
	{
		if (!state.isConnected())
		{
			aCallback.onFailure(new ApiException("Not connected!"));
			return;
		}

		Dirty _d = new Dirty();
		executeCmdListener.submitSendMessageCallback(asyncId, getDirtyCallback(aCallback, _d));

		executeAsync(new SendNoticeMessage(aTarget, aText, asyncId++), aCallback, _d);
	}

	@Override
	public void kick(String aChannel, String aNick)
	{
		kick(aChannel, aNick, "");
	}

	@Override
	public void kick(String aChannel, String aNick, Callback<String> aCallback)
	{
		kick(aChannel, aNick, "", aCallback);
	}

	@Override
	public void kick(String aChannel, String aNick, String aKickMessage)
	{
		checkConnected();

		execute(new KickUserCmd(aChannel, aNick, aKickMessage));
	}

	@Override
	public void kick(String aChannel, String aNick, String aKickMessage, Callback<String> aCallback)
	{
		if (!state.isConnected())
		{
			aCallback.onFailure(new ApiException("Not connected!"));
			return;
		}

		Dirty _d = new Dirty();
		executeCmdListener.submitKickUserCallback(aChannel, getDirtyCallback(aCallback, _d));

		executeAsync(new KickUserCmd(aChannel, aNick, aKickMessage), aCallback, _d);
	}

	@Override
	public void changeNick(String aNewNick)
	{
		checkConnected();

		execute(new ChangeNickCmd(aNewNick));
	}

	@Override
	public void changeNick(String aNewNickname, final Callback<String> aCallback)
	{
		if (!state.isConnected())
		{
			aCallback.onFailure(new ApiException("Not connected!"));
			return;
		}

		Dirty _d = new Dirty();
		executeCmdListener.submitChangeNickCallback(aNewNickname, getDirtyCallback(aCallback, _d));

		executeAsync(new ChangeNickCmd(aNewNickname), aCallback, _d);
	}

	@Override
	public void changeTopic(final String aChannel, final String aSuggestedTopic)
	{
		checkConnected();

		execute(new ChangeTopicCmd(aChannel, aSuggestedTopic));
	}

	@Override
	public void changeMode(String aModeString)
	{
		checkConnected();

		execute(new ChangeModeCmd(aModeString));
	}

	@Override
	public void rawMessage(String aMessage)
	{
		execute(new SendRawMessage(aMessage));
	}

	@Override
	public void rawMessage(ICommand aMessage) {
		execute(new SendRawMessage(aMessage.toString()));
	}

	@Override
	public void register(Object aListener)
	{
		session.register(aListener);
	}

	@Override
	public void unregister(Object aListener)
	{
		session.unregister(aListener);
	}

	@Override
	public void dccSend(final String aNick, final File aFile) throws UnknownHostException
	{
		dccSend(aNick, aFile, NetUtils.getLocalAddressRepresentation(), NetUtils.getRandDccPort(), DCC_SEND_TIMEOUT);
	}

	@Override
	public void dccSend(String aNick, String aListeningAddress, Integer aListeningPort, File aFile)
	{
		dccSend(aNick, aFile, aListeningAddress, aListeningPort, DCC_SEND_TIMEOUT);
	}

	@Override
	public void dccSend(String aNick, File aFile, Integer aTimeout)
	{
		dccSend(aNick, aFile, aTimeout);
	}

	@Override
	public void dccSend(String aNick, File aFile, String aListeningAddress, Integer aListeningPort, Integer aTimeout)
	{
		dccManager.sendFile(aNick, aFile, aListeningAddress, aListeningPort, aTimeout);
	}

	@Override
	public void dccAccept(String aNick, File aFile, Integer aPort, Long aResumePosition)
	{
		dccAccept(aNick, aFile, aPort, aResumePosition, DCC_SEND_TIMEOUT);
	}

	@Override
	public void dccAccept(String aNick, File aFile, Integer aPort, Long aResumePosition, Integer aTimeout)
	{
		dccManager.acceptFile(aNick, aFile, aPort, aResumePosition, aTimeout);
	}

	@Override
	public void dccReceive(File aFile, Long aSize, SocketAddress aAddress)
	{
		dccResume(aFile, 0L, aSize, aAddress);
	}

	@Override
	public void dccReceive(File aFile, Long aSize, SocketAddress aAddress, Proxy aProxy)
	{
		dccResume(aFile, 0L, aSize, aAddress, aProxy);
	}

	@Override
	public void dccResume(File aFile, Long aResumePosition, Long aSize, SocketAddress aAddress)
	{
		dccManager.resumeFile(aFile, aResumePosition, aSize, aAddress);
	}

	@Override
	public void dccResume(File aFile, Long aResumePosition, Long aSize, SocketAddress aAddress, Proxy aProxy)
	{
		dccManager.resumeFile(aFile, aResumePosition, aSize, aAddress, aProxy);
	}

	@Override
	public DCCManager getDCCManager()
	{
		return dccManager;
	}

	@Override
	public MBassador getEventBus() {
		return session.getEventBus();
	}

	/**
	 * Returns the interface responsible for executing IRC commands
	 *
	 * @return {@link IIRCSession}
	 */
	protected IIRCSession getIRCSession()
	{
		return session;
	}

	private String prependChanType(String aChannelName)
	{
		for (Character _c : state.getServerOptions().getChanTypes())
		{
			if (_c.equals(aChannelName.charAt(0)))
			{
				return aChannelName;
			}
		}

		return state.getServerOptions().getChanTypes().iterator().next() + aChannelName;
	}

	private void closeSession(Callback<IIRCState> aCallback, Dirty _d)
	{
		try
		{
			session.close();
		}
		catch (IOException aExc)
		{
			tryInvokeCallback(aCallback, _d, aExc);
			LOG.error("Error Closing Session.", aExc);
		}
	}

    @Override
    public void secureConnection(final SSLContext aContext, final String aHostname, final int aPort) throws SSLException
    {
        this.session.secureConnection(aContext, aHostname, aPort);
    }

	private void checkConnected()
	{
		if (!state.isConnected())
		{
			throw new ApiException("Not connected!");
		}
	}

	private Callback<IIRCState> newConnectCallback(final Callback<IIRCState> aCallback, final Dirty aDirty)
	{
		return new Callback<IIRCState>()
		{
			@Override
			public void onSuccess(IIRCState aConnectedState)
			{
				state = aConnectedState;

				((IRCState) (state)).setConnected(true);

				aCallback.onSuccess(aConnectedState);
			}

			@Override
			public void onFailure(Exception aExc)
			{
				tryInvokeCallback(aCallback, aDirty, aExc);
			}
		};
	}

	private void tryInvokeCallback(final Callback<?> aCallback, Dirty aDirty, Exception aExc)
	{
		synchronized (aDirty)
		{
			if (!aDirty.isDirty())
			{
				aCallback.onFailure(aExc);
				aDirty.setDirty();
			}
		}
	}

	private void execute(ICommand aCommand)
	{
		try
		{
			session.execute(aCommand);
		}
		catch (SocketException aExc)
		{
			((IRCState) this.state).setConnected(false);
			dispatchError(aExc);
			throw new RuntimeException(aExc);
		}
		catch (IOException aExc)
		{
			LOG.error("Error executing command", aExc);
			throw new RuntimeException(aExc);
		}
	}

	private IStateAccessor getStateUpdater(Boolean aSaveIRCState)
	{
		if (aSaveIRCState)
		{
			AbstractIRCStateUpdater _stateUpdater = new AbstractIRCStateUpdater()
			{
				@Override
				public IIRCState getIRCState()
				{
					return state;
				}
			};

			session.register(_stateUpdater);

			return _stateUpdater;
		}
		else
		{
			return new IStateAccessor()
			{
				@Override
				public void saveChan(WritableIRCChannel aChannel)
				{
					// NOP
				}

				@Override
				public IIRCState getIRCState()
				{
					return state;
				}

				@Override
				public void deleteChan(String aChannelName)
				{
					// NOP
				}

				@Override
				public void updateNick(String aNewNick)
				{
					// NOP
				}

				@Override
				public void deleteNickFromChan(String aChan, String aNick)
				{
					// NOP
				}
			};
		}
	}

	private void executeAsync(ICommand aCommand, Callback<?> aCallback, Dirty aDirty)
	{
		try
		{
			getIRCSession().execute(aCommand);
		}
		catch (SocketException aExc)
		{
			((IRCState) this.state).setConnected(false);
			dispatchError(aExc);
			tryInvokeCallback(aCallback, aDirty, aExc);
		}
		catch (IOException aExc)
		{
			LOG.error("Error executing command", aExc);

			tryInvokeCallback(aCallback, aDirty, aExc);
		}
	}

	private void dispatchError(final Exception aExc)
	{
		LOG.debug("Connectivity error: socket exception are non-recoverable, dispatching error message.", aExc);
		this.session.dispatchClientError(aExc);
	}

	private <R> Callback<R> getDirtyCallback(final Callback<R> aCallback, final Dirty aDirty)
	{
		return new Callback<R>()
		{
			@Override
			public void onSuccess(R aObject)
			{
				aCallback.onSuccess(aObject);
			}

			@Override
			public void onFailure(Exception aExc)
			{
				LOG.info("", aExc);

				tryInvokeCallback(aCallback, aDirty, aExc);
			}
		};
	}

	private class Dirty
	{
		boolean dirty;

		void setDirty()
		{
			dirty = true;
		}

		boolean isDirty()
		{
			return dirty == true;
		}
	}
}


text:
#region License
//   Copyright 2011-2016 Kastellanos Nikolaos
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
#endregion

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;
using tainicom.Aether.Graphics;

namespace tainicom.Aether.Animation.Content
{
    public class CpuAnimatedVertexBufferReader : ContentTypeReader<CpuAnimatedVertexBuffer>
    {
        protected override CpuAnimatedVertexBuffer Read(ContentReader input, CpuAnimatedVertexBuffer buffer)
        {
            IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));
            var device = graphicsDeviceService.GraphicsDevice;

            // read standard VertexBuffer
            var declaration = input.ReadRawObject<VertexDeclaration>();
            var vertexCount = (int)input.ReadUInt32();
            // int dataSize = vertexCount * declaration.VertexStride;
            //byte[] data = new byte[dataSize];
            //input.Read(data, 0, dataSize);

            //read data
            var channels = declaration.GetVertexElements();
            var cpuVertices = new VertexIndicesWeightsPositionNormal[vertexCount];
            var gpuVertices = new VertexPositionNormalTexture[vertexCount];

            for (int i = 0; i < vertexCount; i++)
            {
                foreach (var channel in channels)
                {
                    switch (channel.VertexElementUsage)
                    {
                        case VertexElementUsage.Position:
                            System.Diagnostics.Debug.Assert(channel.VertexElementFormat == VertexElementFormat.Vector3);
                            var pos = input.ReadVector3();
                            if (channel.UsageIndex == 0)
                            {
                                cpuVertices[i].Position = pos;
                                gpuVertices[i].Position = pos;
                            }
                            break;

                        case VertexElementUsage.Normal:
                            System.Diagnostics.Debug.Assert(channel.VertexElementFormat == VertexElementFormat.Vector3);
                            var nor = input.ReadVector3();
                            if (channel.UsageIndex == 0)
                            {
                                cpuVertices[i].Normal = nor;
                                gpuVertices[i].Normal = nor;
                            }
                            break;

                        case VertexElementUsage.TextureCoordinate:
                            System.Diagnostics.Debug.Assert(channel.VertexElementFormat == VertexElementFormat.Vector2);
                            var tex = input.ReadVector2();
                            if (channel.UsageIndex == 0)
                            {
                                gpuVertices[i].TextureCoordinate = tex;
                            }
                            break;

                        case VertexElementUsage.BlendWeight:
                            System.Diagnostics.Debug.Assert(channel.VertexElementFormat == VertexElementFormat.Vector4);
                            var wei = input.ReadVector4();
                            if (channel.UsageIndex == 0)
                            {
                                cpuVertices[i].BlendWeights = wei;
                            }
                            break;

                        case VertexElementUsage.BlendIndices:
                            System.Diagnostics.Debug.Assert(channel.VertexElementFormat == VertexElementFormat.Byte4);
                            var i0 = input.ReadByte();
                            var i1 = input.ReadByte();
                            var i2 = input.ReadByte();
                            var i3 = input.ReadByte();
                            if (channel.UsageIndex == 0)
                            {
                                cpuVertices[i].BlendIndex0 = i0;
                                cpuVertices[i].BlendIndex1 = i1;
                                cpuVertices[i].BlendIndex2 = i2;
                                cpuVertices[i].BlendIndex3 = i3;
                            }
                            break;

                        default:
                            throw new Exception();
                    }
                }
            }

            // read extras
            bool IsWriteOnly = input.ReadBoolean();

            if (buffer == null)
            {
                BufferUsage usage = (IsWriteOnly) ? BufferUsage.WriteOnly : BufferUsage.None;
                buffer = new CpuAnimatedVertexBuffer(device, VertexPositionNormalTexture.VertexDeclaration, vertexCount, usage);
            }

            buffer.SetData(gpuVertices, 0, vertexCount);
            buffer.SetGpuVertices(gpuVertices);
            buffer.SetCpuVertices(cpuVertices);

            return buffer;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{{{
  "title": "Restore Group",
  "date": "02-27-2015",
  "author": "Bryan Friedman",
  "attachments": []
}}}

Sends the restore operation to an archived group. (See [Understanding VM Deployment Options and Power States](http://www.ctl.io/knowledge-base/servers/understanding-vm-deployment-options-and-power-states/#archive) for details on the archive operation.) Calls to this operation must include a token acquired from the authentication endpoint. See the [Login API](../Authentication/login.md) for information on acquiring this token.

### When to Use It

Use this API operation when you want to restore an archived group and its groups and servers.

## URL

### Structure

    POST https://api.ctl.io/v2/groups/{accountAlias}/{groupId}/restore

### Example

    POST https://api.ctl.io/v2/groups/ALIAS/2a5c0b9662cf4fc8bf6180f139facdc0/restore

## Request

### URI Parameters

| Name | Type | Description | Req. |
| --- | --- | --- | --- |
| AccountAlias | string | Short code for a particular account. | Yes |
| GroupID | string | ID of the group to restore. Retrieved from query to parent group, or by looking at the URL on the new UI pages in the Control Portal. | Yes |

### Content Properties

| Name | Type | Description | Req. |
| --- | --- | --- | --- |
| targetGroupId | string | The unique identifier of the target group to restore the group to. | Yes |

## Response

### Entity Definition

| Name | Type | Description |
| --- | --- | --- |
| isQueued | boolean | Boolean indicating whether the operation was successfully added to the queue. |
| links | array | Collection of [entity links](../Getting Started/api-v20-links-framework.md) that point to resources related to this group operation. |
| errorMessage | string | If something goes wrong or the request is not queued, this is the message that contains the details about what happened. |

### Examples

#### JSON

    {
      "isQueued":true,
      "links":[
        {
          "rel":"self",
          "href":"/v2/groups/bryf/2a5c0b9662cf4fc8bf6180f139facdc0?AccountAlias=ALIAS&identifier=2a5c0b9662cf4fc8bf6180f139facdc0"
        },
        {
          "rel":"status",
          "href":"/v2/operations/bryf/status/wa1-12345",
          "id":"wa1-12345"
        }
      ]
    }


text:
<?
class Ajax
{
	public function saveSort ($str, $table, $primary)
	{
		$message = Message::singleton ();

		$return = TRUE;

		try
		{
			parse_str ($str, $array);

			$db = Database::singleton ();

			$sth = $db->prepare ("UPDATE ". $table ." SET _order = :order WHERE ". $primary ." = :id");

			$aux = '';

			foreach ($array ['sortableList'] as $order => $id)
				$sth->execute (array (':order' => $order, ':id' => $id));

			$message->addMessage (__ ('Sort successfully performed!'));
		}
		catch (PDOException $e)
		{
			$message->addWarning ($e->getMessage ());

			$return = FALSE;
		}
		catch (Exception $e)
		{
			$message->addWarning ($e->getMessage ());

			$return = FALSE;
		}

		$message->save ();

		$this->showMessages ();

		return $return;
	}

	public function saveImageSort ($str, $table, $itemId)
	{
		$message = Message::singleton ();

		$return = TRUE;

		try
		{
			parse_str ($str, $array);

			$db = Database::singleton ();

			$sth = $db->prepare ("UPDATE ". $table ." SET _order = :order WHERE _item = '". $itemId ."' AND _media = :id");

			$aux = '';

			foreach ($array ['idGallery'] as $order => $id)
				$sth->execute (array (':order' => $order, ':id' => $id));

			$message->addMessage (__ ('Sort successfully performed!'));
		}
		catch (PDOException $e)
		{
			$message->addWarning ($e->getMessage ());

			$return = FALSE;
		}
		catch (Exception $e)
		{
			$message->addWarning ($e->getMessage ());

			$return = FALSE;
		}

		$message->save ();

		$this->showMessages ();

		return $return;
	}

	public function addFile ($fileId, $itemId)
	{
		if (!$fileId || !$itemId)
			return FALSE;

		$message = Message::singleton ();

		$return = TRUE;

		try
		{
			$form = Form::singleton ('vinculate.xml', 'all.xml');

			$table = $form->getTable () .'_file';

			if (!$this->tableExists ($table))
				throw new Exception (__ ('There is no support for link files in this section. The DSM must contain table [ [1] ] for offer support to this.', $table));

			$db = Database::singleton ();

			$db->exec ("INSERT INTO ". $table ." (_item, _file) VALUES (". $itemId .", ". $fileId .")");

			$message->addMessage (__ ('Archive linked with success!'));
		}
		catch (PDOException $e)
		{
			$message->addWarning ($e->getMessage ());

			$return = FALSE;
		}

		$message->save ();

		$this->showMessages ();

		return $return;
	}

	public function removeFile ($fileId, $itemId)
	{
		if (!$fileId || !$itemId)
			return FALSE;

		$message = Message::singleton ();

		$return = TRUE;

		try
		{
			$form = Form::singleton ('vinculate.xml', 'all.xml');

			$table = $form->getTable () .'_file';

			$db = Database::singleton ();

			$db->exec ("DELETE FROM ". $table ." WHERE _file = ". $fileId ." AND _item = ". $itemId);

			$message->addMessage (__ ('Archive unlinked with success!'));
		}
		catch (PDOException $e)
		{
			$message->addWarning ($e->getMessage ());

			$return = FALSE;
		}

		$message->save ();

		$this->showMessages ();

		return $return;
	}

	public function loadFiles ($itemId)
	{
		$message = Message::singleton ();

		try
		{
			if (!$itemId)
				throw new Exception (__ ('Invalid Document!'));

			$form = Form::singleton ('vinculate.xml', 'all.xml');

			$table = $form->getTable () .'_file';

			if (!$this->tableExists ($table))
				throw new Exception (__ ('There is no support for link files in this section. The DSM must contain table [ [1] ] for offer support to this.', $table));

			$db = Database::singleton ();

			$sth = $db->prepare ("SELECT _file.* FROM ". $table ." AS vinculate LEFT JOIN _file ON _file._id = vinculate._file WHERE vinculate._item = ". $itemId);

			$sth->execute ();

			$aux = '';
			while ($obj = $sth->fetch (PDO::FETCH_OBJ))
			{
				ob_start ();
				?>
				<div id="content_basket_<?= $obj->_id ?>" style="display:; position: relative; width: 300px; height: 124px; border: #CCCCCC 1px solid; margin-top: 2px; background-color: #FFFFFF;">

						<a href="titan.php?target=openFile&fileId=<?= $obj->_id ?>" target="_blank"><img src="titan.php?target=viewThumb&fileId=<?= $obj->_id ?>&width=100&height=100" border="0">

						<?= $obj->_name ?>

						<?= $obj->_size ?> Bytes

						<?= $obj->_mimetype ?>

						<?= $obj->_description ?>

						<a href="#" onclick="JavaScript: ajaxRemoveProduct ('<?= $obj->_id ?>', '<?= $itemId ?>'); return false;" style="color: #FFFFFF;"><?= __ ('Remove') ?>

				<?
				$aux = ob_get_clean ();
			}

			$content = &XOAD_HTML::getElementById ('tiedFiles');

			$content->innerHTML = $aux;

			return TRUE;
		}
		catch (PDOException $e)
		{
			$message->addWarning ($e->getMessage ());
		}
		catch (Exception $e)
		{
			$message->addWarning ($e->getMessage ());
		}

		$message->save ();

		$this->showMessages ();

		return FALSE;
	}

	public function removePhoto ($fileId, $itemId)
	{
		if (!$fileId || !$itemId)
			return FALSE;

		$message = Message::singleton ();

		$return = TRUE;

		try
		{
			$form = Form::singleton ('all.xml', 'view.xml', 'create.xml', 'edit.xml');

			$table = $form->getTable () .'_media';

			$db = Database::singleton ();

			$db->exec ("DELETE FROM ". $table ." WHERE _media = ". $fileId ." AND _item = ". $itemId);

			$message->addMessage (__ ('Archive unlinked with success!'));
		}
		catch (PDOException $e)
		{
			$message->addWarning ($e->getMessage ());

			$return = FALSE;
		}

		$message->save ();

		$this->showMessages ();

		return $return;
	}

	public function getPhotos ($itemId)
	{
		if (!$itemId)
			return '';

		$message = Message::singleton ();

		$result = array ();

		try
		{
			$form = Form::singleton ('all.xml', 'view.xml', 'create.xml', 'edit.xml');

			$table = $form->getTable () .'_media';

			$db = Database::singleton ();

			$sth = $db->prepare ("SELECT _media FROM ". $table ." WHERE _item = ". $itemId);

			$sth->execute ();

			while ($obj = $sth->fetch (PDO::FETCH_OBJ))
				$result [] = $obj->_media;
		}
		catch (PDOException $e)
		{
			$message->addWarning ($e->getMessage ());
		}

		$message->save ();

		$this->showMessages ();

		return "'". implode ("','", $result) ."'";
	}

	public function tableExists ($name)
	{
		$message = Message::singleton ();

		try
		{
			$db = Database::singleton ();

			$array = explode ('.', $name);

			if (sizeof ($array) == 2)
			{
				$schema = $array [0];
				$table = $array [1];
			}
			else
			{
				$schema = $db->getSchema ();
				$table = $array [0];
			}

			$sth = $db->prepare ("SELECT tablename FROM pg_tables WHERE schemaname = '". $schema ."' AND tablename = '". $table ."'");

			$sth->execute ();

			if (!$sth->rowCount ())
				return FALSE;

			return TRUE;
		}
		catch (Exception $e)
		{
			$message->addWarning ($e->getMessage ());
		}
		catch (PDOException $e)
		{
			$message->addWarning ($e->getMessage ());
		}

		$message->save ();

		return FALSE;
	}

	public function delay ()
	{
		sleep (1);
	}

	public function showMessages ()
	{
		$message = Message::singleton ();

		if (!is_object ($message) || !$message->has ())
			return FALSE;

		$str = '';
		while ($msg = $message->get ())
			$str .= $msg;

		$msgs = &XOAD_HTML::getElementById ('labelMessage');

		$msgs->innerHTML = '
'. $str .'
';

		$message->clear ();

		return TRUE;
	}

	public function xoadGetMeta()
	{
		$methods = get_class_methods ($this);

		XOAD_Client::mapMethods ($this, $methods);

		XOAD_Client::publicMethods ($this, $methods);

		XOAD_Client::privateMethods ($this, array ());
	}
}
?>


text:
///////////////////////////////////////////////////////////////////////////
//
// logkafka - Collect logs and send lines to Apache Kafka v0.8+
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Qihoo 360 Technology Co., Ltd. All rights reserved.
//
// Licensed under the MIT License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////
#include "logkafka/memory_position_entry.h"

namespace logkafka {

bool MemoryPositionEntry::update(ino_t inode, off_t pos)
{/*{{{*/
    m_inode = inode;
    m_pos = pos;

    return true;
}/*}}}*/

bool MemoryPositionEntry::updatePos(off_t pos)
{/*{{{*/
    m_pos = pos;

    return true;
}/*}}}*/

ino_t MemoryPositionEntry::readInode()
{/*{{{*/
    return m_inode;
}/*}}}*/

off_t MemoryPositionEntry::readPos()
{/*{{{*/
    return m_pos;
}/*}}}*/

} // namespace logkafka


text:
#include "clotho.h"
#include <cstdlib>

#include "clotho_application.h"
#include "engine/SequentialSimulationManager.hpp"
#include "engine/CentralizedSimulationManager.hpp"
#include "engine/ThreadedCentralizedSimulationManager.hpp"
#include "engine/simulation_stats.h"

#include "rng/rng.hpp"

#include <boost/program_options.hpp>

namespace po=boost::program_options;

bool parse_commandline( int argc, char ** argv, po::variables_map & vm );

const string RUNTIME_K = "total_runtime";

const string HELP_K = "help";
const string VERSION_K = "version";

const string ENGINE_CONFIG_K    = "engine_config";
const string APP_CONFIG_K       = "app_config";

const string SIM_UNTIL_K        = "sim-until";
const string THREAD_COUNT_K     = "thread-count";

const string SEQSM_K = "sequential";
const string CENSM_K = "centralized";
const string TCENSM_K = "threaded-centralized";

const string DISTRIBUTED_ENV_K = "dist-env";
const string FOUNDER_SIZE_K = "founder-size";

static const unsigned int MAX_THREADS = 24;

template <>
void SequentialSimulationManager< pooled_event_set >::routeEvent( const event * evt ) {
    if( insertEvent( evt ) ) {
        notifyNextEvent( evt->getReceiver(), evt->getReceived() );
    }
}

template <>
void CentralizedSimulationManager< pooled_event_set >::routeEvent( const event * evt ) {
    if( insertEvent( evt ) ) {
        notifyNextEvent( evt->getReceiver(), evt->getReceived() );
    }
}

template <>
void ThreadedCentralizedSimulationManager< pooled_event_set >::clearBufferedEvents() {
    for( unsigned int i = 0; i < m_nThreads; ++i ) {
        while( !m_buffers[i]->empty() ) {
            const event * t = m_buffers[i]->back();
            m_buffers[i]->pop_back();

            if( insertEvent( t ) ) {
                notifyNextEvent( t->getReceiver(), t->getReceived() );
            }
        }
    }
}

int main( int argc, char ** argv ) {

    po::variables_map vm;
    if( !parse_commandline( argc, argv, vm ) ) {
        return 0;
    }

    string engine_config( "" );
    string clotho_config( "" );

    SystemClock::vtime_t tUntil = vm[ SIM_UNTIL_K ].as< event::vtime_t >();

    tUntil *= LIFE_CYCLE_PADDING;

    cout << "Simulate until: " << tUntil << endl;

    shared_ptr< iRNG > rng( new GSL_RNG());

    cout << "RNG: " <<  rng->getType() << "; seed: " << rng->getSeed() << endl;

    shared_ptr< application > app;
    shared_ptr< SimulationStats > stats( new SimulationStats() );

    simulation_manager * sim = NULL;

    if( vm.count( CENSM_K ) ) {
        cout << "Using a Centralized Simulation Manager" << endl;
        app.reset( new ClothoApplication( clotho_config, rng, vm[ DISTRIBUTED_ENV_K ].as< unsigned int >() ) );
        sim = new CentralizedSimulationManager< ClothoEventSet >( app, stats );
    } else if( vm.count( TCENSM_K ) ) {
        unsigned int tc = vm[ THREAD_COUNT_K ].as< unsigned int >();

        assert( 0 < tc && tc <= MAX_THREADS );
        cout << "Using a Threaded Centralized Simulation Manager with " << tc << " threads" << endl;

        if( tc > vm[ DISTRIBUTED_ENV_K ].as< unsigned int >() ) {
            app.reset( new ClothoApplication( clotho_config, rng, tc ) );
        } else {
            app.reset( new ClothoApplication( clotho_config, rng, vm[ DISTRIBUTED_ENV_K ].as< unsigned int >() ) );
        }
        sim = new ThreadedCentralizedSimulationManager< ClothoEventSet >( app, stats, tc );

    } else {
        cout << "Using a Sequential Simulation Manager" << endl;
        app.reset( new ClothoApplication( clotho_config, rng, vm[ DISTRIBUTED_ENV_K ].as< unsigned int >() ) );
        sim = new SequentialSimulationManager< ClothoEventSet >( app, stats );
    }

    assert( sim != NULL );

    (std::static_pointer_cast<ClothoApplication>(app))->setSimulationManager( sim );
    (std::static_pointer_cast<ClothoApplication>(app))->setFounderSize( vm[ FOUNDER_SIZE_K ].as<unsigned int>() );

    stats->startPhase( RUNTIME_K );

    sim->initialize();

    sim->simulate( tUntil );

    sim->finalize();

    stats->stopPhase( RUNTIME_K );

    cout << *stats;

    delete sim;

    return 0;
}

bool parse_commandline( int argc, char ** argv, po::variables_map & vm ) {
    po::options_description gen( "General" );
    gen.add_options()
    ( (HELP_K + ",h").c_str(), "Print this" )
    ( (VERSION_K + ",v").c_str(), "Version" )
    ;

    po::options_description simulation( "Simulation Parameters" );
    simulation.add_options()
    ( SIM_UNTIL_K.c_str(), po::value<event::vtime_t>()->default_value( SystemClock::POSITIVE_INFINITY ), "Simulate until time. Default value is positive infinity")
    ( THREAD_COUNT_K.c_str(), po::value< unsigned int >()->default_value( 4 ), "Thread count for thread aware simulation managers are used. Does not apply when --sequential, or --centralized flags are used")
    ( SEQSM_K.c_str(), "Run the simulation with the sequential simulation manager" )
    ( CENSM_K.c_str(), "Run the simulation with the centralized simulation manager" )
    ( TCENSM_K.c_str(), "Run the simulation with the centralized simulation manager (thread aware)")
    ;

    po::options_description clotho_app( "Clotho Application Parameters" );
    clotho_app.add_options()
    ( DISTRIBUTED_ENV_K.c_str(), po::value< unsigned int >()->default_value( 1 ), "Number of environment partitions; Thread aware simulation managers will partition the environment into the max of the number of partitions and thread count" )
    ( FOUNDER_SIZE_K.c_str(), po::value< unsigned int >()->default_value(10000), "Founding population size" )
    ;

    po::options_description cmdline;

    cmdline.add(gen).add(simulation).add( clotho_app );
    po::store( po::command_line_parser( argc, argv ).options( cmdline ).run(), vm );

    bool res = true;
    if( vm.count( HELP_K ) ) {
        cout << cmdline << endl;
        res = false;
    }

    return res;
}


text:
package com.daedafusion.knowledge.trinity.triples.query;

import com.daedafusion.configuration.Configuration;
import com.daedafusion.knowledge.trinity.Query;
import com.daedafusion.knowledge.trinity.TripleMeta;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import org.apache.log4j.Logger;

import java.io.Closeable;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

/**
 * Created by mphilpot on 8/25/14.
 */
public class MultiQueryEngine implements Closeable
{
    private static final Logger log = Logger.getLogger(MultiQueryEngine.class);

    private final QueryEnginePool pool;
    private final ListeningExecutorService service;

    private MultiQueryEngine()
    {
        pool = QueryEnginePool.getInstance();
        service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(Configuration.getInstance().getInteger("multiQueryEngine.threads", 10)));
    }

    public static MultiQueryEngine getInstance()
    {
        MultiQueryEngine mqe = new MultiQueryEngine();
        mqe.init();
        return mqe;
    }

    private void init()
    {

    }

    public class Result
    {
        private Model                          model;
        private Map<String, Map<String, String>> cursorMap;
        private Map<Integer, List<TripleMeta>> metaData;
        private List<ResultSet> resultSet;

        public Result()
        {
            metaData = new HashMap<>();
            cursorMap = new HashMap<>();
            resultSet = new ArrayList<>();
        }

        public Model getModel()
        {
            return model;
        }

        public Map<String, Map<String, String>> getCursorMap()
        {
            return cursorMap;
        }

        public Map<Integer, List<TripleMeta>> getMetaData()
        {
            return metaData;
        }

        public List<ResultSet> getResultSet()
        {
            return resultSet;
        }
    }

    private class QueryCallable implements Callable<Result>
    {
        private final Query q;

        public QueryCallable(Query q)
        {
            this.q = q;
        }

        @Override
        public Result call() throws Exception
        {
            QueryEngine engine = pool.getPool().borrowObject();
            try
            {
                Model model = engine.graphQuery(q);

                Result r = new Result();
                r.model = model;
                r.cursorMap.putAll(engine.getContext().getCursorMap());
                r.metaData.putAll(engine.getContext().getMetadata());

                return r;
            }
            finally
            {
                if (engine != null)
                {
                    pool.getPool().returnObject(engine);
                }
            }
        }
    }

    private class SelectCallable implements Callable<Result>
    {
        private final Query q;

        public SelectCallable(Query q)
        {
            this.q = q;
        }

        @Override
        public Result call() throws Exception
        {
            QueryEngine engine = pool.getPool().borrowObject();
            try
            {
                ResultSet rs = engine.execSelect(q);

                Result r = new Result();
                r.resultSet = Collections.singletonList(rs);
                r.cursorMap.putAll(engine.getContext().getCursorMap());
                r.metaData.putAll(engine.getContext().getMetadata());

                return r;
            }
            finally
            {
                if (engine != null)
                {
                    pool.getPool().returnObject(engine);
                }
            }
        }
    }

    public Result multiQuery(List<Query> queries) throws ExecutionException, InterruptedException
    {
        List<ListenableFuture<Result>> futures = new ArrayList<>();

        for (Query q : queries)
        {
            futures.add(service.submit(new QueryCallable(q)));
        }

        ListenableFuture<List<Result>> fanIn = Futures.allAsList(futures);

        List<Result> list = fanIn.get();

        Result result = new Result();
        result.model = ModelFactory.createDefaultModel();

        for (Result r : list)
        {
            result.model.add(r.model);
            result.cursorMap.putAll(r.cursorMap);

            for(Map.Entry<Integer, List<TripleMeta>> entry : r.getMetaData().entrySet())
            {
                if(result.metaData.containsKey(entry.getKey()))
                {
                    result.metaData.get(entry.getKey()).addAll(entry.getValue());
                }
                else
                {
                    result.metaData.put(entry.getKey(), entry.getValue());
                }
            }
        }

        return result;
    }

    public Result multiSelect(List<Query> queries) throws ExecutionException, InterruptedException
    {
        List<ListenableFuture<Result>> futures = new ArrayList<>();

        for (Query q : queries)
        {
            futures.add(service.submit(new SelectCallable(q)));
        }

        ListenableFuture<List<Result>> fanIn = Futures.allAsList(futures);

        List<Result> list = fanIn.get();

        Result result = new Result();
        result.model = ModelFactory.createDefaultModel();

        for (Result r : list)
        {
            result.resultSet.addAll(r.resultSet);

            result.cursorMap.putAll(r.cursorMap);

            for(Map.Entry<Integer, List<TripleMeta>> entry : r.getMetaData().entrySet())
            {
                if(result.metaData.containsKey(entry.getKey()))
                {
                    result.metaData.get(entry.getKey()).addAll(entry.getValue());
                }
                else
                {
                    result.metaData.put(entry.getKey(), entry.getValue());
                }
            }
        }

        return result;
    }

    public Result multiQuery(Query... queries) throws ExecutionException, InterruptedException
    {
        List<Query> list = new ArrayList<>();
        Collections.addAll(list, queries);
        return multiQuery(list);
    }

    @Override
    public void close() throws IOException
    {
        pool.getPool().close();
        service.shutdown();
    }
}


text:
/*!
 * \file   exceptions.cpp
 * \author Andrey Semashev
 * \date   31.10.2009
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
 */

#include <boost/throw_exception.hpp>
#include <boost/exception/exception.hpp>
#include <boost/exception/errinfo_at_line.hpp>
#include <boost/exception/info.hpp>
#include <boost/log/exceptions.hpp>
#include <boost/log/support/exception.hpp>
#include <boost/log/detail/header.hpp>

#ifdef _MSC_VER
#pragma warning(push)
// conversion from 'size_t' to 'boost::error_info<boost::throw_line_,int>::value_type', possible loss of data
// No idea why line number is stored as a signed integer in the error info...
#pragma warning(disable: 4267)
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

//! Attaches attribute name exception information
BOOST_LOG_API void attach_attribute_name_info(exception& e, attribute_name const& name)
{
    e << attribute_name_info(name);
}

} // namespace aux

runtime_error::runtime_error(std::string const& descr) :
    std::runtime_error(descr)
{
}

runtime_error::~runtime_error() throw()
{
}

missing_value::missing_value() :
    runtime_error("Requested value not found")
{
}

missing_value::missing_value(std::string const& descr) :
    runtime_error(descr)
{
}

missing_value::~missing_value() throw()
{
}

void missing_value::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(missing_value())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void missing_value::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(missing_value(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void missing_value::throw_(const char* file, std::size_t line, std::string const& descr, attribute_name const& name)
{
    boost::throw_exception(boost::enable_error_info(missing_value(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
        << attribute_name_info(name)
    );
}

invalid_type::invalid_type() :
    runtime_error("Requested value has invalid type")
{
}

invalid_type::invalid_type(std::string const& descr) :
    runtime_error(descr)
{
}

invalid_type::~invalid_type() throw()
{
}

void invalid_type::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(invalid_type())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void invalid_type::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(invalid_type(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void invalid_type::throw_(const char* file, std::size_t line, std::string const& descr, attribute_name const& name)
{
    boost::throw_exception(boost::enable_error_info(invalid_type(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
        << attribute_name_info(name)
    );
}

void invalid_type::throw_(const char* file, std::size_t line, std::string const& descr, typeindex::type_index const& type)
{
    boost::throw_exception(boost::enable_error_info(invalid_type(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
        << type_info_info(type)
    );
}

void invalid_type::throw_(const char* file, std::size_t line, std::string const& descr, attribute_name const& name, typeindex::type_index const& type)
{
    boost::throw_exception(boost::enable_error_info(invalid_type(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
        << attribute_name_info(name)
        << type_info_info(type)
    );
}

invalid_value::invalid_value() :
    runtime_error("The value is invalid")
{
}

invalid_value::invalid_value(std::string const& descr) :
    runtime_error(descr)
{
}

invalid_value::~invalid_value() throw()
{
}

void invalid_value::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(invalid_value())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void invalid_value::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(invalid_value(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

parse_error::parse_error() :
    runtime_error("Failed to parse content")
{
}

parse_error::parse_error(std::string const& descr) :
    runtime_error(descr)
{
}

parse_error::~parse_error() throw()
{
}

void parse_error::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(parse_error())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void parse_error::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(parse_error(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void parse_error::throw_(const char* file, std::size_t line, std::string const& descr, std::size_t content_line)
{
    boost::throw_exception(boost::enable_error_info(parse_error(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
        << boost::errinfo_at_line(content_line)
    );
}

void parse_error::throw_(const char* file, std::size_t line, std::string const& descr, attribute_name const& name)
{
    boost::throw_exception(boost::enable_error_info(parse_error(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
        << attribute_name_info(name)
    );
}

conversion_error::conversion_error() :
    runtime_error("Failed to perform conversion")
{
}

conversion_error::conversion_error(std::string const& descr) :
    runtime_error(descr)
{
}

conversion_error::~conversion_error() throw()
{
}

void conversion_error::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(conversion_error())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void conversion_error::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(conversion_error(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

system_error::system_error() :
    runtime_error("Underlying API operation failed")
{
}

system_error::system_error(std::string const& descr) :
    runtime_error(descr)
{
}

system_error::~system_error() throw()
{
}

void system_error::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(system_error())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void system_error::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(system_error(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

logic_error::logic_error(std::string const& descr) :
    std::logic_error(descr)
{
}

logic_error::~logic_error() throw()
{
}

odr_violation::odr_violation() :
    logic_error("ODR violation detected")
{
}

odr_violation::odr_violation(std::string const& descr) :
    logic_error(descr)
{
}

odr_violation::~odr_violation() throw()
{
}

void odr_violation::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(odr_violation())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void odr_violation::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(odr_violation(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

unexpected_call::unexpected_call() :
    logic_error("Invalid call sequence")
{
}

unexpected_call::unexpected_call(std::string const& descr) :
    logic_error(descr)
{
}

unexpected_call::~unexpected_call() throw()
{
}

void unexpected_call::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(unexpected_call())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void unexpected_call::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(unexpected_call(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

setup_error::setup_error() :
    logic_error("The library is not initialized properly")
{
}

setup_error::setup_error(std::string const& descr) :
    logic_error(descr)
{
}

setup_error::~setup_error() throw()
{
}

void setup_error::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(setup_error())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void setup_error::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(setup_error(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

limitation_error::limitation_error() :
    logic_error("Boost.Log library limit reached")
{
}

limitation_error::limitation_error(std::string const& descr) :
    logic_error(descr)
{
}

limitation_error::~limitation_error() throw()
{
}

void limitation_error::throw_(const char* file, std::size_t line)
{
    boost::throw_exception(boost::enable_error_info(limitation_error())
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

void limitation_error::throw_(const char* file, std::size_t line, std::string const& descr)
{
    boost::throw_exception(boost::enable_error_info(limitation_error(descr))
        << boost::throw_file(file)
        << boost::throw_line(line)
    );
}

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <boost/log/detail/footer.hpp>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gbif.ws.server.provider;

import java.util.Locale;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class LocaleHandlerMethodArgumentResolver extends LocaleProvider
    implements HandlerMethodArgumentResolver {

  @Override
  public boolean supportsParameter(MethodParameter parameter) {
    return Locale.class.equals(parameter.getParameterType());
  }

  @Override
  public Object resolveArgument(
      MethodParameter parameter,
      ModelAndViewContainer mavContainer,
      NativeWebRequest webRequest,
      WebDataBinderFactory binderFactory) {
    return getValue(webRequest);
  }
}


text:
layout: page
title: Concepts
---
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

This page gives an introduction to the high-level concepts in Samza.

### Streams

Samza processes *streams*. A stream is composed of immutable *messages* of a similar type or category. For example, a stream could be all the clicks on a website, or all the updates to a particular database table, or all the logs produced by a service, or any other type of event data. Messages can be appended to a stream or read from a stream. A stream can have any number of *consumers*, and reading from a stream doesn't delete the message (so each message is effectively broadcast to all consumers). Messages can optionally have an associated key which is used for partitioning, which we'll talk about in a second.

Samza supports pluggable *systems* that implement the stream abstraction: in [Kafka](https://kafka.apache.org/) a stream is a topic, in a database we might read a stream by consuming updates from a table, in Hadoop we might tail a directory of files in HDFS.

![job](/img/{{site.version}}/learn/documentation/introduction/job.png)

### Jobs

A Samza *job* is code that performs a logical transformation on a set of input streams to append output messages to set of output streams.

If scalability were not a concern, streams and jobs would be all we need. However, in order to scale the throughput of the stream processor, we chop streams and jobs up into smaller units of parallelism: *partitions* and *tasks*.

### Partitions

Each stream is broken into one or more partitions. Each partition in the stream is a totally ordered sequence of messages.

Each message in this sequence has an identifier called the *offset*, which is unique per partition. The offset can be a sequential integer, byte offset, or string depending on the underlying system implementation.

When a message is appended to a stream, it is appended to only one of the stream's partitions. The assignment of the message to its partition is done with a key chosen by the writer. For example, if the user ID is used as the key, that ensures that all messages related to a particular user end up in the same partition.

![stream](/img/{{site.version}}/learn/documentation/introduction/stream.png)

### Tasks

A job is scaled by breaking it into multiple *tasks*. The *task* is the unit of parallelism of the job, just as the partition is to the stream. Each task consumes data from one partition for each of the job's input streams.

A task processes messages from each of its input partitions sequentially, in the order of message offset. There is no defined ordering across partitions. This allows each task to operate independently. The YARN scheduler assigns each task to a machine, so the job as a whole can be distributed across many machines.

The number of tasks in a job is determined by the number of input partitions (there cannot be more tasks than input partitions, or there would be some tasks with no input). However, you can change the computational resources assigned to the job (the amount of memory, number of CPU cores, etc.) to satisfy the job's needs. See notes on *containers* below.

The assignment of partitions to tasks never changes: if a task is on a machine that fails, the task is restarted elsewhere, still consuming the same stream partitions.

![job-detail](/img/{{site.version}}/learn/documentation/introduction/job_detail.png)

### Dataflow Graphs

We can compose multiple jobs to create a dataflow graph, where the edges are streams containing data, and the nodes are jobs performing transformations. This composition is done purely through the streams the jobs take as input and output. The jobs are otherwise totally decoupled: they need not be implemented in the same code base, and adding, removing, or restarting a downstream job will not impact an upstream job.

These graphs are often acyclic—that is, data usually doesn't flow from a job, through other jobs, back to itself. However, it is possible to create cyclic graphs if you need to.

<img src="/img/{{site.version}}/learn/documentation/introduction/dag.png" width="430" alt="Directed acyclic job graph">

### Containers

Partitions and tasks are both *logical* units of parallelism—they don't correspond to any particular assignment of computational resources (CPU, memory, disk space, etc). Containers are the unit of physical parallelism, and a container is essentially a Unix process (or Linux [cgroup](http://en.wikipedia.org/wiki/Cgroups)). Each container runs one or more tasks. The number of tasks is determined automatically from the number of partitions in the input and is fixed, but the number of containers (and the CPU and memory resources associated with them) is specified by the user at run time and can be changed at any time.

## [Architecture »](architecture.html)


text:
/*
 * Name: LineChartStreamUpdater.js
 * Module: DataModel/NorrisChart
 * Location: Norris/Main/DataModel/NorrisChart
 * Date: 2015-04-10
 * Version: v1.00
 *
 * History:
 *
 * ================================================================================
 * Version Date Programmer Changes
 * ================================================================================
 * v1.00 2015-06-15 Carlon Chiara  Approved
 * ================================================================================
 * v0.08 2015-06-01 Dal Bianco Davide   Verify
 * ================================================================================
 * v0.07 2015-05-28 Bigarella Chiara   Edit
 * ================================================================================
 * v0.06 2015-05-21 Bigarella Chiara   Verify
 * ================================================================================
 * v0.05 2015-04-25 Dal Bianco Davide   Edit
 * ================================================================================
 * v0.04 2015-04-27 Carlon Chiara   Verify
 * ================================================================================
 * v0.03 2015-04-25 Bigarella Chiara   Edit
 * ================================================================================
 * v0.02 2015-04-14 Carlon Chiara   Verify
 * ================================================================================
 * v0.01 2015-04-10 Pavanello Fabio Matteo   Creation
 * ===============================================================================
 */
module.exports=LineChartStreamUpdater;

/**
 * Creates a new LineChartStreamUpdater.
 * @constructor
 */
function LineChartStreamUpdater() {
    if(!(this instanceof LineChartStreamUpdater)) return new LineChartStreamUpdater();
}

LineChartStreamUpdater.prototype.instance=new LineChartStreamUpdater(); // static

/**
 * Gets the LineChartStreamUpdater's instance.
 * @returns {LineChartStreamUpdater} the LineChartStreamUpdater's instance.
 */
LineChartStreamUpdater.getInstance = function() { // static
    return LineChartStreamUpdater.prototype.instance;
};

/**
 * Updates a line chart with stream method. The line chart data should not be empty.
 * @param {LineChartImpl} chart - the line chart to update;
 * @param updateData - the updating.
 */
LineChartStreamUpdater.prototype.update = function (chart, updateData) {
    var isEmpty=function(obj) {
        for(var prop in obj) {
            if(obj.hasOwnProperty(prop))
                return false;
        }
        return true;
    };

    if (!isEmpty(updateData)) {
        var data=chart.getData();
        var update=updateData['stream'];
        if (!isEmpty(data)) {
            for(var i=0; i<update.length; i++) {
                if (update[i].data.length==data.datasets.length) {
                    for(var k=0; k<data.datasets.length; k++) {
                        data.datasets[k].values.push(update[i].data[k]);
                        if (data.datasets[k].values.length>chart.getSettings().maxItems) {
                            data.datasets[k].values.shift();
                        }
                    }
                    data.labels.push(update[i].label);
                    if (data.labels.length>chart.getSettings().maxItems) {
                        data.labels.shift();
                    }

                }
                else {
                    console.error("ERROR: wrong updating data.");
                    throw ("LineChartStreamUpdater:wrongUpdatingData");
                }
            }
            chart.setData(data);
        }
        else {
            console.error("ERROR: the chart has no data to update.");
            throw ("LineChartStreamUpdater:emptyChart");
        }
    }
};

/*
 data = {
    labels: ['2010','2011','2012','2013'], // asse indipendente
    datasets: [
        {name: 'pippo', color : '#aaaaaa', values: [1,2,3,4]}, // linea1
        {name: 'pluto', color : '#bbbbbb', values: [1,2,3,4]}, // linea2
        {name: 'paperino', color : '#cccccc' , values: [1,2,3,4]} // linea3
    ]
 }

 linechart:stream
 update = {
    stream: [
        {label: 'foo', data: [1,2,3,4,5]},
        {label: 'bar', data: [1,2,3,4,5]}
    ] // aggiungo 2 valori indipendenti con i rispettivi valori dipendenti per ogni linea
 }
*/


text:
namespace extensions {

// A fake safe browsing database manager for use with extensions tests.
//
// By default it is disabled (returning true and ignoring |unsafe_ids_|);
// call set_enabled to enable it.
class FakeSafeBrowsingDatabaseManager
    : public safe_browsing::TestSafeBrowsingDatabaseManager {
 public:
  explicit FakeSafeBrowsingDatabaseManager(bool enabled);

  // Returns true if synchronously safe, false if not in which case the unsafe
  // IDs taken from |unsafe_ids_| are passed to to |client| on the current
  // message loop.
  bool CheckExtensionIDs(const std::set<std::string>& extension_ids,
                         Client* client) override;

  // Return |this| to chain together SetUnsafe(...).NotifyUpdate() conveniently.
  FakeSafeBrowsingDatabaseManager& Enable();
  FakeSafeBrowsingDatabaseManager& Disable();
  FakeSafeBrowsingDatabaseManager& ClearUnsafe();
  FakeSafeBrowsingDatabaseManager& SetUnsafe(const std::string& a);
  FakeSafeBrowsingDatabaseManager& SetUnsafe(const std::string& a,
                                             const std::string& b);
  FakeSafeBrowsingDatabaseManager& SetUnsafe(const std::string& a,
                                             const std::string& b,
                                             const std::string& c);
  FakeSafeBrowsingDatabaseManager& SetUnsafe(const std::string& a,
                                             const std::string& b,
                                             const std::string& c,
                                             const std::string& d);
  FakeSafeBrowsingDatabaseManager& AddUnsafe(const std::string& a);
  FakeSafeBrowsingDatabaseManager& RemoveUnsafe(const std::string& a);

  // Send the update notification.
  void NotifyUpdate();

 private:
  ~FakeSafeBrowsingDatabaseManager() override;

  // Whether to respond to CheckExtensionIDs immediately with true (indicating
  // that there is definitely no extension ID match).
  bool enabled_;

  // The extension IDs considered unsafe.
  std::set<std::string> unsafe_ids_;
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_FAKE_SAFE_BROWSING_DATABASE_MANAGER_H_


text:
.. _pocl-install:

============
Installation
============

Requirements
------------

In order to build pocl, you need the following support libraries and
tools:

  * Latest released version of LLVM & Clang
  * development files for LLVM & Clang + their transitive dependencies
    (e.g. libclang-dev, libllvm-dev, zlib1g-dev, libtinfo-dev...)
  * CMake
  * GNU make or ninja
  * pkg-config
  * pthread (should be installed by default)
  * hwloc v1.0 or newer (e.g. libhwloc-dev) - optional
  * python3 (for support of LLVM bitcode with SPIR target; optional but enabled by default)
  * python3, llvm-spirv (version-compatible with LLVM) and spirv-tools (optional;
    required for SPIR-V support in CPU / CUDA; Vulkan driver supports SPIR-V through clspv)

Installing requirements for Ubuntu::

Note: The binary packages from https://apt.llvm.org/ are recommended
(and tested for each release) instead of the binary tar balls or
the packages included in the distribution. The following assumes
apt.llvm.org is added to your apt repos::

    apt install -y python3-dev libpython3-dev build-essential ocl-icd-libopencl1 cmake git pkg-config libclang-${LLVM_VERSION}-dev clang llvm-${LLVM_VERSION} make ninja-build ocl-icd-libopencl1 ocl-icd-dev ocl-icd-opencl-dev libhwloc-dev zlib1g zlib1g-dev clinfo dialog apt-utils libxml2-dev libclang-cpp${LLVM_VERSION}-dev libclang-cpp${LLVM_VERSION} llvm-${LLVM_VERSION}-dev

Installing requirements for Arch Linux::

    pacman -S gcc patch hwloc cmake git pkg-config make ninja ocl-icd clang llvm llvm-libs clinfo opencl-headers

Installing requirements for Fedora::

    dnf install gcc gcc-c++ clinfo hwloc-devel hwloc-libs cmake git-core pkgconfig make ninja-build ocl-icd ocl-icd-devel clang clang-devel clang-libs llvm llvm-devel llvm-libs patch redhat-rpm-config findutils

There are also Dockerfiles available for a few most common linux
distributions in ``tools/docker``, looking into them might be helpful.

OpenCL 3.0 support
------------------

If you want PoCL built with ICD and OpenCL 3.0 support at platform level, you will
need sufficiently new ocl-icd (2.3.x). For Ubuntu, it can be installed from
this PPA: https://launchpad.net/~ocl-icd/+archive/ubuntu/ppa
Additionally, if you want the CPU device to report as 3.0 OpenCL,
you will need LLVM 14 or newer.

Clang / LLVM Notes
------------------

**IMPORTANT NOTE!** Some targets (TCE and possibly HSA) require that
you compile & build LLVM with RTTI on. It can be enabled on cmake command
line, as follows::

    cmake [other CMake options] -DLLVM_ENABLE_RTTI=ON -DLLVM_ENABLE_EH=ON <llvm-source-directory>

Supported LLVM versions
~~~~~~~~~~~~~~~~~~~~~~~~

  Note that pocl aims to support **the latest LLVM version** at the time
  of pocl release, **plus the previous** LLVM version. All older LLVM
  versions are supported with "best effort" basis; there might not be
  build bots continuously testing the code base nor anyone fixing their
  possible breakage.

Configure & Build
-----------------

CMake version 3.3 or higher is required.

The build+install is the usual CMake way::

  cd <directory-with-pocl-sources>
  mkdir build
  cd build
  cmake [-D<option>=<value> ...] ..
  make && make install

To see the default detected values, run ``cmake ..`` without any options,
it will produce a summary.

CMake variables
~~~~~~~~~~~~~~~~~~~~~~~~

Since pocl includes a compiler for the kernels, it both compiles (producing
code) and is compiled (it consists of code). This distinction typically called
"host" and "target": The host is where pocl is running, the target is
where the OpenCL code will be running. These two systems can be wildly
different.

Host compiler used to compile pocl can be GCC or Clang; the target
compiler is always Clang+LLVM since pocl uses Clang/LLVM internally.
For host compiler, you should use the one which your LLVM was compiled
with (because the LLVM-related parts of pocl take LLVM's CXXFLAGS from
llvm-config and pass them to the host compiler).

CMake host flags
~~~~~~~~~~~~~~~~~~~~~~~~

Compile C:
  CMAKE_C_FLAGS
  CMAKE_C_FLAGS_<build-type>

Compile C++:
  CMAKE_CXX_FLAGS
  CMAKE_CXX_FLAGS_<build-type>

Building kernels and the kernel library, i.e. target flags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All of these empty by default. There are hardcoded defaults which may
be overridden by setting these variables (rarely needed).

Extra parameters to llc
   EXTRA_HOST_LLC_FLAGS

Extra parameters to clang
   EXTRA_HOST_CLANG_FLAGS

Extra parameters to linker (links kernel to shared library
which is then dlopened):

EXTRA_HOST_LD_FLAGS

EXTRA_KERNEL_FLAGS
  is applied to all kernel library compilation commands, IOW it's for
  language-independent options

EXTRA_KERNEL_{C,CL,CXX}_FLAGS
  cmake variables for per-language options for kernel library compilation

CMake: other options & features
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note that there are a few more packaging-related options described
in ``README.packaging``.

For multiple-item options like KERNELLIB_HOST_CPU_VARIANTS,
use ";" as separator (you'll have to escape it for bash).

- ``-DWITH_LLVM_CONFIG=<path-to-llvm-config>``
  **IMPORTANT** Path to a llvm-config binary.
  This determines the LLVM installation used by pocl.
  If not specified, pocl will try to find and link against
  llvm-config in PATH env var (usually means your system LLVM).

- ``-DSINGLE_LLVM_LIB`` this is deprecated and has no effect (pocl now uses
  llvm-config exclusively to get the LLVM library list)

- ``-DSTATIC_LLVM`` pocl uses ``llvm-config --libs`` to get list of LLVM libraries
  it should link to. With this flag enabled, it additionally passes ``--link-static``
  to ``llvm-config``; otherwise it passes ``--link-shared``. Default is OFF (=shared).

- ``-DENABLE_ICD`` By default pocl's buildsystem will try to find an ICD
  and build pocl as a dynamic library named "libpocl". This option is useful
  if you want to avoid ICD and build pocl directly as libOpenCL library.
  See also :ref:`linking-with-icd`

- ``-DENABLE_FP64`` - for ARM platform only. If your CPU doesn't support any
  doubles (VFP is enough), disable this. Defaults to OFF when LLVM is older
  than 4.0, otherwise defaults to ON.

- ``-DPOCL_INSTALL_<something>_DIR`` The equivalent of ``--bindir``,
  ``--sbindir`` etc fine-tuning of paths for autotools. See the beginning
  of toplevel CMakeLists.txt for all the variables.

  Note that if ``CMAKE_INSTALL_PREFIX`` equals ``/usr`` then pocl.icd is
  installed to ``/etc/OpenCL/vendors``, otherwise it's installed to
  ``${CMAKE_INSTALL_PREFIX}/etc/OpenCL/vendors``.

- ``-DLLC_HOST_CPU=<something>``
  Defaults to auto-detection via ``llc``. Run ``llc -mcpu=help``
  for valid values. The CPU type is required to compile
  the "target" (kernel library) part of CPU backend.

  This variable overrides LLVM's autodetected host CPU at configure time.
  Useful when llc fails to detect the CPU (often happens on non-x86
  platforms, or x86 with CPU newer than LLVM).

  Note that when this is set (set by default) and the
  KERNELLIB_HOST_CPU_VARIANTS variable is not ``distro``,
  pocl will first try to find compiled kernel library
  for runtime-detected CPU then fallback to LLC_HOST_CPU.
  This works well if pocl is run where it was built,
  or the actual CPU is in the KERNELLIB_HOST_CPU_VARIANTS list,
  or the actual CPU is >= LLC_HOST_CPU feature-wise;
  otherwise it will likely fail with illegal instruction at runtime.

- ``-DKERNELLIB_HOST_CPU_VARIANTS`` You can control which CPUs the
  "target" part of CPU backend will be built for.
  Unlike LLC_HOST_CPU, this variable is useful if you plan
  to build for multiple CPUs. Defaults to "native" which is
  automagically replaced by LLC_HOST_CPU.
  Available CPUs are listed by ``llc -mcpu=help``. See above for
  runtime CPU detection rules.

  Note that there's another valid value on x86(64) platforms.
  If set to ``distro``, the KERNELLIB_HOST_CPU_VARIANTS variable will be
  set up with a few preselected sse/avx variants covering 99.99% of x86
  processors, and the runtime CPU detection is slightly altered: pocl
  will find the suitable compiled library based on detected CPU features,
  so it cannot fail (at worst it'll degrade to SSE2 library).

- ``-DLLC_TRIPLE=<something>`` Controls what target triple pocl is built for.
  You can set this manually in case the autodetection fails.
  Example value: ``x86_64-pc-linux-gnu``

- ``-DENABLE_TESTSUITES`` Which external (source outside pocl) testsuites to enable.
  For the list of testsuites, see examples/CMakeLists.txt or the ``examples``
  directory. Set to ``all`` and pocl will try to autodetect & enable everything
  it can.

  Note that you may build testsuites outside pocl's build tree, and test
  multiple pocl builds with a single testsuite directory. To use this,
  run cmake with ``-DTESTSUITE_BASEDIR=<tests-builddir>`` and ``-DTESTSUITE_SOURCE_BASEDIR=<tests-sourcedir>``.
  The directory structure mirrors that of ``pocl/examples``. So to build e.g. AMD SDK 2.9
  with ``-DTESTSUITE_BASEDIR=/home/pocltest-build -DTESTSUITE_SOURCE_BASEDIR=/home/pocltest-src``,
  place the ``AMD-APP-SDK-v2.9-RC-lnx64.tgz`` file into ``/home/pocltest-src/AMDSDK2.9`` directory.

- ``-DENABLE_TESTS=ON/OFF`` enable/disable compilation of internal tests.

- ``-DENABLE_EXAMPLES=ON/OFF`` enable/disable compilation of all examples.
  Disabling this makes ENABLE_TESTSUITES option unavailable.

- ``-DENABLE_POCLCC=ON/OFF`` enable/disable compilation of poclcc.

- ``-DENABLE_CONFORMANCE=ON/OFF``
  Ensures that certain build options which would result in non-conformant pocl
  build stay disabled. Defaults to OFF. Note that this does not quarantee a
  fully conformant build of pocl by itself. See :ref:`pocl-conformance` for details.

- ``-DENABLE_{A,L,T,UB}SAN`` - compiles pocl's host code (and tests
  + examples) with various sanitizers. Using more than one sanitizer at
  a time is untested. Using together with ``-DENABLE_ICD=OFF`` is highly
  recommended to avoid issues with loading order of sanitizer libraries.

- ``-DENABLE_{CUDA,TCE,HSA}=ON/OFF`` - enable various (non-CPU) backends.
  Usually requires some extra setup; see their documentation.

- ``-DPOCL_DEBUG_MESSAGES=ON`` - when disabled, pocl is compiled without
  debug messages (POCL_DEBUG env var) support.

- ``-DEXAMPLES_USE_GIT_MASTER=ON`` - when enabled, examples (external
  programs in ``examples/`` directory) are built from their git branches
  (if available), as opposed to default: building from release tars.

- ``-DENABLE_POCL_FLOAT_CONVERSION=ON/OFF``
  When enabled, OpenCL printf() call's f/e/g formatters are handled by pocl.
  When disabled (default), these are handled by system C library. Can only
  be enabled when Clang's compiler-rt library is present.

- ``-DINTEL_SDE_AVX512=<PATH>``
  Path to Intel® Software Development Emulator. When this option is given,
  the LLVM host CPU is forcibly set to 'skylake-avx512', and the internal
  tests are run through the Emulator. Mostly useful to test AVX512.

.. _pocl-without-llvm:

LLVM-less build
~~~~~~~~~~~~~~~~~~~~~~~~

You can build a runtime-only pocl to run prebuilt pocl binaries on a device.
To do this

* First, build a pocl with LLVM somewhere.
* on that machine, set up env vars required for your device (if any), then
  run ``bin/poclcc -l``. That should print something like::

    LIST OF DEVICES:
    0:
     Vendor:   AuthenticAMD
       Name:   pthread-AMD A10-7800 Radeon R7, 12 Compute Cores 4C+8G
    Version:   OpenCL 2.0 pocl HSTR: pthread-x86_64-unknown-linux-gnu-bdver3

The string after "HSTR:" is the device build hash.

* now build the LLVM-less pocl. You will need the device build hash from
  previous step:

  ``cmake -DENABLE_LLVM=0 -DHOST_DEVICE_BUILD_HASH=<something> ...``

  This is required because pocl binaries contain a device hash, and the LLVM-less
  pocl needs to know which binaries it can load.

Cross-compile pocl
------------------
It's now possible to cross-compile pocl on x86-64 to run on ARM/MIPS/etc,
There is a ToolchainExample.cmake file;
copy it under different name, then follow the instructions in the file.

Known build-time issues
~~~~~~~~~~~~~~~~~~~~~~~~

There are unsolved issues and bugs in pocl. See the bug listing
for a complete listing at https://github.com/pocl/pocl/issues

building / running in Docker
--------------------------------

Install Docker
~~~~~~~~~~~~~~~~~~~~~~~~~~

* install docker for your distribution
* start the docker daemon
* make sure you have enough space (default location is usually ``/var/lib/docker``,
  required storage for standard pocl build is about 1.5 GB per container,
  and more than 10GB for TCE/PHSA builds)

Build & start Pocl container
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* create an empty directory <D>
* copy Dockerfile of your choice (any file from tools/docker/) to ``<D>/Dockerfile``
* ``cd <D> ; sudo docker build -t TAG .`` .. where TAG is a name you can choose for the build.
* ``sudo docker run -t TAG``
* this will by default use master branch of pocl git; to use a different branch/commit,
  run docker build with ``--build-arg GIT_COMMIT=<branch/commit>``

Dockerfiles
~~~~~~~~~~~~~~~~~~~~~~~~~~

Note that some images (e.g. RHEL and PHSA) may be impossible to build,
due to not having a sufficiently new version of LLVM available.

Dockerfiles are named according to what they build, or the release they're based on:

* `default`: builds pocl, then runs the internal tests from build dir.
   Uses latest release of a distribution, with whatever is the default version of LLVM.
* `distro`: does a distribution-friendly build: enables runtime detection of CPU,
   installs pocl into system path, then runs the internal tests
* `<release>`: same as above, except uses specific release and specific LLVM version
  (the latest available in that release).
* `X.32bit`: same as X but sets up i386 environment
* `conformance`: builds & installs Pocl, then runs conformance test suite
  (the shortest version of it)

Some additional notes:

* TCE is built using three stages (LLVM, TCE, pocl)
* PHSA built using three stages (LLVM, PHSA runtime, pocl)


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ChipsInput = void 0;

var _jsxRuntime = require("../../lib/jsxRuntime");

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _FormField = require("../FormField/FormField");

var _ChipsInputBase = require("../ChipsInputBase/ChipsInputBase");

var _excluded = ["style", "className", "getRootRef", "before", "after", "status"];

/**
 * @see https://vkcom.github.io/VKUI/#/ChipsInput
 */
var ChipsInput = function ChipsInput(_ref) {
  var style = _ref.style,
      className = _ref.className,
      getRootRef = _ref.getRootRef,
      before = _ref.before,
      after = _ref.after,
      status = _ref.status,
      restProps = (0, _objectWithoutProperties2.default)(_ref, _excluded);
  return (0, _jsxRuntime.createScopedElement)(_FormField.FormField, {
    getRootRef: getRootRef,
    vkuiClass: "ChipsInput",
    className: className,
    style: style,
    disabled: restProps.disabled,
    before: before,
    after: after,
    role: "application",
    "aria-disabled": restProps.disabled,
    "aria-readonly": restProps.readOnly,
    status: status
  }, (0, _jsxRuntime.createScopedElement)(_ChipsInputBase.ChipsInputBase, restProps));
};

exports.ChipsInput = ChipsInput;
//# sourceMappingURL=ChipsInput.js.map


text:
package com.hectorlopezfernandez.pebblestripes.action;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;

@UrlBinding("/request-attributes.action")
public class RequestAttributesAction extends BaseAction {

	@DefaultHandler
	public Resolution execute() {
		getContext().getRequest().setAttribute("bla", "BLA");
		return new ForwardResolution("/templates/request-attributes.pebble");
	}

}


text:
layout: current
title: Brains, Wolfgang and Warburton Wyrm
---

With many of my characters I like to use names that many seem pretty random at first, but generally they have a meaning, if not instantly obvious. Wolfgang for example is named after Wolfgang Amadeus Mozart the composer, due to his bottom teeth protruding like piano keys.

Sometimes I gave my characters names that will make more sense with the actual story text, for example the worm crawling from Brains's nose is Warburton Wyrm who is the "underworld" crime boss of the city. Brains name may seem more obvious, but in fact he is the stupid one of the trio, but allows me to say...

"He may be called Brains but I'm the real brains of this outfit!!" Warburton Wyrm

Go back


text:
export CFLAGS="-I$PREFIX/include"
export LDFLAGS="-L$PREFIX/lib"
export CPATH=${PREFIX}/include

mkdir -p $PREFIX/bin
sed -i -e 's/-march=native/-msse4.2 -mpopcnt/g' Makefile
make
make install PREFIX=$PREFIX


text:
package xyz.mcex.plugin.util.player;

import java.io.*;
import java.util.UUID;

public class PlayerUtils
{
  public static byte[] uuidToBytes(UUID uuid) throws IOException
  {
    ByteArrayOutputStream ba = new ByteArrayOutputStream(16);
    DataOutputStream os = new DataOutputStream(ba);
    os.writeLong(uuid.getMostSignificantBits());
    os.writeLong(uuid.getLeastSignificantBits());
    return ba.toByteArray();
  }

  public static ByteArrayInputStream uuidToStream(UUID uuid) throws IOException
  {
    return new ByteArrayInputStream(uuidToBytes(uuid));
  }

  public static UUID streamToUuid(InputStream stream) throws IOException
  {
    byte[] uuidBytes = new byte[16];
    stream.read(uuidBytes);

    ByteArrayInputStream ba = new ByteArrayInputStream(uuidBytes);
    DataInputStream is = new DataInputStream(ba);

    return new UUID(is.readLong(), is.readLong());
  }
}


text:
package org.collectionspace.services.authorization;

import org.collectionspace.services.authorization.perms.Permission;
import org.collectionspace.services.authorization.storage.PermissionRoleDocumentHandler;

import org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl;
import org.collectionspace.services.common.context.RemoteServiceContextFactory;
import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.common.context.ServiceContextFactory;
import org.collectionspace.services.common.document.DocumentHandler;
import org.collectionspace.services.common.storage.StorageClient;
import org.collectionspace.services.common.storage.jpa.JpaRelationshipStorageClient;
import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
import org.collectionspace.services.common.context.ServiceContextProperties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * PermissionRoleSubResource is used to manage permission-role relationship
 * @author
 */
public class PermissionRoleSubResource
        extends AbstractCollectionSpaceResourceImpl<PermissionRole, PermissionRole> {

    public final static String ROLE_PERMROLE_SERVICE = "authorization/roles/permroles";
    public final static String PERMISSION_PERMROLE_SERVICE = "authorization/permissions/permroles";
    //this service is never exposed as standalone RESTful service...just use unique
    //service name to identify binding
    /** The service name. */
    private String serviceName = "authorization/permroles";
    /** The logger. */
    final Logger logger = LoggerFactory.getLogger(PermissionRoleSubResource.class);
    /** The storage client. */
    final StorageClient storageClient = new JpaRelationshipStorageClient<PermissionRole>();
    //
    private String permissionRoleCsid = null;

    /**
     * Instantiates a new permission role sub resource.
     *
     * @param serviceName the service name
     */
    public PermissionRoleSubResource(String serviceName) {
        this.serviceName = serviceName;
    }

    /* (non-Javadoc)
     * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getVersionString()
     */
    @Override
    protected String getVersionString() {
        /** The last change revision. */
        final String lastChangeRevision = "$LastChangedRevision: 1165 $";
        return lastChangeRevision;
    }

    /* (non-Javadoc)
     * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getServiceName()
     */
    @Override
    public String getServiceName() {
        return serviceName;
    }

    /* (non-Javadoc)
     * @see org.collectionspace.services.common.CollectionSpaceResource#getCommonPartClass()
     */
    @Override
    public Class<PermissionRole> getCommonPartClass() {
        return PermissionRole.class;
    }

    /* (non-Javadoc)
     * @see org.collectionspace.services.common.CollectionSpaceResource#getServiceContextFactory()
     */
    @Override
    public ServiceContextFactory<PermissionRole, PermissionRole> getServiceContextFactory() {
        return RemoteServiceContextFactory.get();
    }

    /**
     * Creates the service context.
     *
     * @param input the input
     * @param subject the subject
     *
     * @return the service context< permission role, permission role>
     *
     * @throws Exception the exception
     */
    private ServiceContext<PermissionRole, PermissionRole> createServiceContext(PermissionRole input,
            SubjectType subject) throws Exception {
        ServiceContext<PermissionRole, PermissionRole> ctx = createServiceContext(input);
        ctx.setDocumentType(PermissionRole.class.getPackage().getName()); //persistence unit
        ctx.setProperty(ServiceContextProperties.ENTITY_NAME, PermissionRoleRel.class.getName());
        ctx.setProperty(ServiceContextProperties.ENTITY_CLASS, PermissionRoleRel.class);
        //subject name is necessary to indicate if role or permission is a subject
        ctx.setProperty(ServiceContextProperties.SUBJECT, subject);
        //set context for the relationship query
        if (subject == SubjectType.ROLE) {
            ctx.setProperty(ServiceContextProperties.OBJECT_CLASS, Permission.class);
            ctx.setProperty(ServiceContextProperties.OBJECT_ID, "permission_id");
        } else if (subject == SubjectType.PERMISSION) {
            ctx.setProperty(ServiceContextProperties.OBJECT_CLASS, Role.class);
            ctx.setProperty(ServiceContextProperties.OBJECT_ID, "role_id");
        }
        return ctx;
    }

    /* (non-Javadoc)
     * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getStorageClient(org.collectionspace.services.common.context.ServiceContext)
     */
    @Override
    public StorageClient getStorageClient(ServiceContext<PermissionRole, PermissionRole> ctx) {
        //FIXME use ctx to identify storage client
        return storageClient;
    }

//    @Override
//    public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception {
//        DocumentHandler docHandler = ctx.getDocumentHandler();
//        docHandler.setCommonPart(ctx.getInput());
//        return docHandler;
//    }
    /**
     * createPermissionRole creates one or more permission-role relationships
     * between object (permission/role) and subject (role/permission)
     * @param input
     * @param subject
     * @return
     * @throws Exception
     */
    public String createPermissionRole(PermissionRole input, SubjectType subject)
            throws Exception {

        ServiceContext<PermissionRole, PermissionRole> ctx = createServiceContext(input, subject);
        DocumentHandler handler = createDocumentHandler(ctx);
        return getStorageClient(ctx).create(ctx, handler);
    }

    /**
     * Gets the permission role rel.
     *
     * @param csid the csid
     * @param subject the subject
     * @param permissionRoleCsid the permission role csid
     * @return the permission role rel
     * @throws Exception the exception
     */
    public PermissionRoleRel getPermissionRoleRel(String csid,
    		SubjectType subject,
    		String permissionRoleCsid) throws Exception {

        if (logger.isDebugEnabled()) {
            logger.debug("getAccountRole with csid=" + csid);
        }
//        AccountRolesList result = new AccountRolesList();
        ServiceContext<PermissionRole, PermissionRole> ctx = createServiceContext((PermissionRole) null, subject);
        PermissionRoleDocumentHandler handler = (PermissionRoleDocumentHandler)createDocumentHandler(ctx);
        handler.setPermissionRoleCsid(permissionRoleCsid);
        //getStorageClient(ctx).get(ctx, csid, handler);
        PermissionRoleRel permissionRoleRel = (PermissionRoleRel)JpaStorageUtils.getEntity(
        		new Long(permissionRoleCsid).longValue(), PermissionRoleRel.class);
//        List<AccountRoleListItem> accountRoleList = result.getAccountRoleListItems();
//        AccountRoleListItem listItem = new AccountRoleListItem();
//        // fill the item
//        listItem.setCsid(accountRoleRel.getHjid().toString());
//        listItem.setRoleId(accountRoleRel.getRoleId());
//        listItem.setRoleName(accountRoleRel.getRoleName());
        // add item to result list
//        result = (AccountRolesList) ctx.getOutput();

        return permissionRoleRel;
    }

    /**
     * getPermissionRole retrieves permission-role relationships using given
     * csid of object (permission/role) and subject (role/permission)
     * @param csid
     * @param subject
     * @return
     * @throws Exception
     */
    public PermissionRole getPermissionRole(
            String csid, SubjectType subject) throws Exception {

        if (logger.isDebugEnabled()) {
            logger.debug("getPermissionRole with csid=" + csid);
        }
        PermissionRole result = null;
        ServiceContext<PermissionRole, PermissionRole> ctx = createServiceContext((PermissionRole) null, subject);
        DocumentHandler handler = createDocumentHandler(ctx);
        getStorageClient(ctx).get(ctx, csid, handler);
        result = (PermissionRole) ctx.getOutput();

        return result;
    }

    /**
     * deletePermissionRole deletes permission-role relationships using given
     * csid of object (permission/role) and subject (role/permission)
     * @param csid
     * @param subject
     * @return
     * @throws Exception
     */
    public void deletePermissionRole(String csid,
            SubjectType subject) throws Exception {

        if (logger.isDebugEnabled()) {
            logger.debug("deletePermissionRole with csid=" + csid);
        }
        PermissionRole permRole = this.getPermissionRole(csid, subject);
        this.deletePermissionRole(csid, subject, permRole);
    }

    /**
     * deletePermissionRole deletes permission-role relationships using given
     * csid of object (permission/role) and subject (role/permission)
     * @param csid
     * @param subject
     * @param input with role and permission relationships to delete
     * @return
     * @throws Exception
     */
    public void deletePermissionRole(String csid,
            SubjectType subject, PermissionRole input) throws Exception {

        if (logger.isDebugEnabled()) {
            logger.debug("deletePermissionRole(input) with csid=" + csid);
        }
        ServiceContext<PermissionRole, PermissionRole> ctx = createServiceContext(input, subject);
        DocumentHandler handler = createDocumentHandler(ctx);
        getStorageClient(ctx).delete(ctx, csid, handler);
    }
}


text:
"use strict";

describe("Pool Errors", () => {
    const setup = require("../utils/setup");
    const Pool = setup.Pool;
    const abapSystem = setup.abapSystem();
    const poolConfiguration = {
        connectionParameters: abapSystem,
        //clientOptions: { filter: 2, bcd: "number" },
        //poolOptions: { low: 2, high: 4 },
    };

    test("pool error: connection parameters missing", function () {
        expect(() => new Pool({ connectionParameters: {} })).toThrow(
            new TypeError("Client connection parameters missing")
        );
    });

    test("pool error: user credentials w. callback", function (done) {
        //expect.assertions(1);
        const abapSystemWrongUser = Object.assign({}, abapSystem);
        abapSystemWrongUser.user += "#$!";
        const pool = new Pool({ connectionParameters: abapSystemWrongUser });
        pool.acquire((err) => {
            expect(err).toMatchObject({
                name: "RfcLibError",
                group: 3,
                code: 2,
                codeString: "RFC_LOGON_FAILURE",
                key: "RFC_LOGON_FAILURE",
                message: "Name or password is incorrect (repeat logon)",
            });
            done();
        });
    });

    test("pool error: user credentials w. promise", function () {
        expect.assertions(1);
        const abapSystemWrongUser = Object.assign({}, abapSystem);
        abapSystemWrongUser.user += "#$!";
        const pool = new Pool({ connectionParameters: abapSystemWrongUser });
        return expect(pool.acquire()).rejects.toEqual({
            name: "RfcLibError",
            group: 3,
            code: 2,
            codeString: "RFC_LOGON_FAILURE",
            key: "RFC_LOGON_FAILURE",
            message: "Name or password is incorrect (repeat logon)",
        });
    });
});