text:
package me.makram.weatherpp.app;

import android.app.Application;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

import net.danlew.android.joda.JodaTimeAndroid;

import okhttp3.OkHttpClient;

/**
 * Extend the Application class to provide an environment
 * to create the OkHttpClient object (though this may not
 * be enough if we want to make a service).
 */
public class AppController extends Application {
    private final String TAG = AppController.class.getCanonicalName();

    private OkHttpClient client;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    @Override
    public void onCreate() {
        super.onCreate();

        JodaTimeAndroid.init(this);

        client = new OkHttpClient();
        requestQueue = Volley.newRequestQueue(getApplicationContext());
        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    public OkHttpClient getClient() {
        return client;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }

    public RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public <T> void addToRequestQueue(Request<T> request) {
        request.setTag(TAG);
        requestQueue.add(request);
    }
}


text:
const do_all_promises = function (promises) {
  return new Promise(function (resolve, reject) {
    Promise.all(promises.map(definitely_do_promise))
      .then(resolve)
  })
}

// accepts a promise that might reject or resolve
// returns a promise that always resolve but will sometimes resolve an error
// essentially turns .reject(error_message) into .resolve(error_message)
// use carefully
const definitely_do_promise = function (promise) {
  return new Promise(function (resolve, reject) {
    promise
      .then(resolve)
      .catch(resolve)
  })
}

export default do_all_promises

redpajama_set_name: RedPajamaGithub


text:
package org.apache.catalina.core;

import java.io.IOException;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
import org.apache.coyote.ContinueResponseTiming;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.res.StringManager;

/**
 * Valve that implements the default basic behavior for the
 * StandardContext container implementation.
 *

 * USAGE CONSTRAINT:  This implementation is likely to be useful only
 * when processing HTTP requests.
 *
 * @author Craig R. McClanahan
 */
final class StandardContextValve extends ValveBase {

    private static final StringManager sm = StringManager.getManager(StandardContextValve.class);

    public StandardContextValve() {
        super(true);
    }

    /**
     * Select the appropriate child Wrapper to process this request,
     * based on the specified request URI.  If no matching Wrapper can
     * be found, return an appropriate HTTP error.
     *
     * @param request Request to be processed
     * @param response Response to be produced
     *
     * @exception IOException if an input/output error occurred
     * @exception ServletException if a servlet error occurred
     */
    @Override
    public final void invoke(Request request, Response response)
        throws IOException, ServletException {

        // Disallow any direct access to resources under WEB-INF or META-INF
        MessageBytes requestPathMB = request.getRequestPathMB();
        if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0))
                || (requestPathMB.equalsIgnoreCase("/META-INF"))
                || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0))
                || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // Select the Wrapper to be used for this Request
        Wrapper wrapper = request.getWrapper();
        if (wrapper == null || wrapper.isUnavailable()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // Acknowledge the request
        try {
            response.sendAcknowledgement(ContinueResponseTiming.IMMEDIATELY);
        } catch (IOException ioe) {
            container.getLogger().error(sm.getString(
                    "standardContextValve.acknowledgeException"), ioe);
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        if (request.isAsyncSupported()) {
            request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported());
        }
        wrapper.getPipeline().getFirst().invoke(request, response);
    }
}


text:
package libsvm;

public class svm_problem implements java.io.Serializable
{
	public int l;
	public double[] y;
	public svm_node[][] x;
}


text:
==============================================================================
Data Description Language
==============================================================================

Introduction
===============================

An RDF language for describing which predicates are derived and which are not.

For reference, the **ddl** prefix is bound to the URI:
*http://code.google.com/p/fuxi/wiki/`DataDescriptionLanguage# </p/fuxi/wiki/DataDescriptionLanguage>`_*

Details
=====================

The following classes and classes can be used to assign one or more URIs
as `derived or base
predicates <http://code.google.com/p/fuxi/wiki/Overview#Base_and_Derived_Predicates>`_

ddl:DerivedClassList and ddl:DerivedPropertyList
------------------------------------------------------------------------------

The class of RDF `lists <http://www.w3.org/TR/rdf-mt/#collections>`_
whose members are each URIs of derived predicates

ddl:BaseClassList
------------------------------------------

Same structure as
ddl:DerivedClassList`? </p/fuxi/w/edit/DerivedClassList>`_ except the
members are URIs of base predicates

ddl:DerivedPropertyPrefix
----------------------------------------------------------

The class of RDF `lists <http://www.w3.org/TR/rdf-mt/#collections>`_
whose members are each URIs that are a common prefix for the URIs of
derived, binary predicates and is a good way to specify an entire
terminology (which shares a common namespace URI) as derived

ddl:DerivedClassPrefix
----------------------------------------------------

Same as
ddl:DerivedPropertyPrefix`? </p/fuxi/w/edit/DerivedPropertyPrefix>`_
except the prefix identifies URIs of derived unary predicates

ddl:BaseClassPrefix
----------------------------------------------

Similar to ddl:DerivedClassPrefix except the prefix identifies URIs of
base unary predicates

ddl:BasePropertyPrefix
----------------------------------------------------

Similar to ddl:DerivedPropertyPrefix except it provides a common prefix
for base binary predicates

ddl:DerivedClassQuery
--------------------------------------------------

The class of RDF strings that are SPARQL queries which when evaluated
against a given OWL graph returns the URIs of derived, unary predicates


text:
package ru.stqa.training.selenium.pageObject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

/**
 * Created by Андрей on 09.02.2017.
 */
public class CheckoutPage extends Page {

    public CheckoutPage (WebDriver driver){
        super(driver);
        PageFactory.initElements(driver, this);
    }

    public CheckoutPage open(){
        driver.navigate().to("http://localhost/litecart/en/checkout");
        return this;
    }

    @FindBy(css = ".shortcut a")
    private WebElement productPicker;

    @FindBy(css = "[name=remove_cart_item]")
    private WebElement removeButton;

}


text:
"""
Main RenderChan package
"""


text:
package ec2

import ec2_service "github.com/aws/aws-sdk-go/service/ec2"

type Ec2Instance struct {
	InstanceID       string
	InstanceType     string
	PublicIP         string
	PrivateIP        string
	Component        string
	Environment      string
	Service          string
	AutoScalingGroup string
	State            string
	Key              string
	WorkingVersion   string
}

func NewEc2Instance(res *ec2_service.Instance) (*Ec2Instance, error) {

	instance := &Ec2Instance{
		InstanceID:   *res.InstanceId,
		State:        *res.State.Name,
		Key:          *res.KeyName,
		InstanceType: *res.InstanceType,
	}

	if res.PrivateIpAddress != nil {
		instance.PrivateIP = *res.PrivateIpAddress
	}

	if res.PublicIpAddress != nil {
		instance.PublicIP = *res.PublicIpAddress
	}
	for _, keys := range res.Tags {
		switch tag := *keys.Key; tag {
		case "working_version":
			instance.WorkingVersion = *keys.Value
		case "aws:autoscaling:groupName":
			instance.AutoScalingGroup = *keys.Value
		case "component":
			instance.Component = *keys.Value
		case "environment":
			instance.Environment = *keys.Value
		case "service":
			instance.Service = *keys.Value
		}
	}

	return instance, nil
}


text:
#include "SkRefCnt.h"
#include "SkThreadUtils.h"
#include "SkTypes.h"
#include "SkWeakRefCnt.h"
#include "Test.h"

class InstCounterClass {
public:
    InstCounterClass() { fCount = gInstCounter++; }
    InstCounterClass(const InstCounterClass& src) {
        fCount = src.fCount;
        gInstCounter += 1;
    }
    virtual ~InstCounterClass() { gInstCounter -= 1; }

    static int gInstCounter;
    int fCount;
};

int InstCounterClass::gInstCounter;

static void bounce_ref(void* data) {
    SkRefCnt* ref = static_cast<SkRefCnt*>(data);
    for (int i = 0; i < 100000; ++i) {
        ref->ref();
        ref->unref();
    }
}

static void test_refCnt(skiatest::Reporter* reporter) {
    SkRefCnt* ref = new SkRefCnt();

    SkThread thing1(bounce_ref, ref);
    SkThread thing2(bounce_ref, ref);

    thing1.setProcessorAffinity(0);
    thing2.setProcessorAffinity(23);

    SkASSERT(thing1.start());
    SkASSERT(thing2.start());

    thing1.join();
    thing2.join();

    REPORTER_ASSERT(reporter, ref->unique());
    ref->unref();
}

static void bounce_weak_ref(void* data) {
    SkWeakRefCnt* ref = static_cast<SkWeakRefCnt*>(data);
    for (int i = 0; i < 100000; ++i) {
        if (ref->try_ref()) {
            ref->unref();
        }
    }
}

static void bounce_weak_weak_ref(void* data) {
    SkWeakRefCnt* ref = static_cast<SkWeakRefCnt*>(data);
    for (int i = 0; i < 100000; ++i) {
        ref->weak_ref();
        ref->weak_unref();
    }
}

static void test_weakRefCnt(skiatest::Reporter* reporter) {
    SkWeakRefCnt* ref = new SkWeakRefCnt();

    SkThread thing1(bounce_ref, ref);
    SkThread thing2(bounce_ref, ref);
    SkThread thing3(bounce_weak_ref, ref);
    SkThread thing4(bounce_weak_weak_ref, ref);

    thing1.setProcessorAffinity(0);
    thing2.setProcessorAffinity(23);
    thing3.setProcessorAffinity(2);
    thing4.setProcessorAffinity(17);

    SkASSERT(thing1.start());
    SkASSERT(thing2.start());
    SkASSERT(thing3.start());
    SkASSERT(thing4.start());

    thing1.join();
    thing2.join();
    thing3.join();
    thing4.join();

    REPORTER_ASSERT(reporter, ref->unique());
    REPORTER_ASSERT(reporter, ref->getWeakCnt() == 1);
    ref->unref();
}

DEF_TEST(RefCnt, reporter) {
    test_refCnt(reporter);
    test_weakRefCnt(reporter);
}


text:
package de.fau.cs.mad.kwikshop.server;

import de.fau.cs.mad.kwikshop.common.User;
import de.fau.cs.mad.kwikshop.server.dao.UserDAO;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by Andreas Kumlehn on 4/9/15.
 */
public class UserFacade {

    private final UserDAO dao;

    public UserFacade(UserDAO dao) {

        this.dao = dao;
    }

    public User getUserById(String id) {
        return this.dao.findById(id);
    }

    public User createNewUser(User user) {
        return this.dao.create(user);
    }

    public User updateUser(String id, User user) {
        return this.dao.updateOrCreate(id, user);
    }

    public boolean deleteUser(String id) {
        User toDelete = dao.findById(id);

        if (toDelete == null) {
            return false;
        }

        this.dao.delete(toDelete);
        return false;
    }

    public List<User> searchBySessionToken(String sessionToken) {
        return dao.findBySessionToken(sessionToken);
    }

    public List<User> searchUsers(List<String> ids) {
        return this.searchUsersByIds(ids);
    }

    private List<User> searchUsersByIds(List<String> ids) {
        if (ids == null || ids.size() == 0) {
            return this.dao.listAll();
        } else {
            return this.searchUsersByIdList(ids);
        }
    }

    public List<User> searchUsersByIdList(List<String> ids) {
        List<User> result = new LinkedList<User>();

        for (String id : ids) {
            result.add(this.getUserById(id));
        }

        return result;
    }

}


text:
package com.nowellpoint.mongodb.persistence.test.model;

import com.nowellpoint.mongodb.persistence.BaseDocument;
import com.nowellpoint.mongodb.persistence.annotation.Collection;
import com.nowellpoint.mongodb.persistence.annotation.Document;
import com.nowellpoint.mongodb.persistence.annotation.Property;

@Document
@Collection(name = "properties")
public class NameValuePair extends BaseDocument {

	/**
	 *
	 */

	private static final long serialVersionUID = -7838064767547511748L;

	/**
	 *
	 */

	@Property(name = "name")
	private String name;

	/**
	 *
	 */

	@Property(name = "value")
	private String value;

	public NameValuePair() {

	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}


text:
int main(int argc, const char * argv[]) {
    DeadReckoner dead = DeadReckoner();
    return 0;
}


text:
namespace blink {

namespace {

const char kUTF16TextMimeType[] = "text/plain; charset=utf-16";

}  // namespace

TEST(TextResourceDecoderTest, BasicUTF16) {
  std::unique_ptr<TextResourceDecoder> decoder =
      TextResourceDecoder::create(kUTF16TextMimeType);
  WTF::String decoded;

  const unsigned char fooLE[] = {0xff, 0xfe, 0x66, 0x00,
                                 0x6f, 0x00, 0x6f, 0x00};
  decoded =
      decoder->decode(reinterpret_cast<const char*>(fooLE), sizeof(fooLE));
  decoded = decoded + decoder->flush();
  EXPECT_EQ("foo", decoded);

  decoder = TextResourceDecoder::create(kUTF16TextMimeType);
  const unsigned char fooBE[] = {0xfe, 0xff, 0x00, 0x66,
                                 0x00, 0x6f, 0x00, 0x6f};
  decoded =
      decoder->decode(reinterpret_cast<const char*>(fooBE), sizeof(fooBE));
  decoded = decoded + decoder->flush();
  EXPECT_EQ("foo", decoded);
}

TEST(TextResourceDecoderTest, UTF16Pieces) {
  std::unique_ptr<TextResourceDecoder> decoder =
      TextResourceDecoder::create(kUTF16TextMimeType);

  WTF::String decoded;
  const unsigned char foo[] = {0xff, 0xfe, 0x66, 0x00, 0x6f, 0x00, 0x6f, 0x00};
  for (char c : foo)
    decoded = decoded + decoder->decode(reinterpret_cast<const char*>(&c), 1);
  decoded = decoded + decoder->flush();
  EXPECT_EQ("foo", decoded);
}

}  // namespace blink


text:
export interface ParsedImage {
  width: number;
  height: number;
  bpp: number;
  buffer: ArrayBuffer;
}

export function isICO(source: ArrayBuffer | Buffer): Boolean;

export function parse(
  buffer: ArrayBuffer | Buffer,
  mime?: string
): Promise<Array<ParsedImage>>;


text:
from sftpproxydocker.storageredis import  StorageRedis
sredis = StorageRedis()

pubkey=open("/home/rauburtin/.ssh/id_rsa.pub","r").read()
if pubkey.endswith("\n"):
    pubkey = pubkey[:-1]
if len(pubkey.split())==3:
    pubkey = ' '.join(pubkey.split()[:-1])
if len(pubkey.split())==2:
    pubkey = pubkey.split()[1]
username="rauburtin"

sredis.add_username(pubkey,username)
sredis.add_userinfo(username,"tst-usambot-01.moovapps.local","32784","root","/")


text:
from __future__ import absolute_import
from pychron.graph.stacked_graph import StackedGraph

class MassSpecGraph(StackedGraph):
    pass


text:
__version__ = '0.4.2'
from .validators import *  # NOQA
from .models import *  # NOQA


text:
package treeton.core;

import treeton.core.model.TrnType;

public interface Token extends Treenotation, Comparable {
    public int compareTo(Token anotherToken);

    public int compareTo(Fraction f);

    public int compareTo(double f);

    public boolean corrupted(TrnType type);

    public Token getNextToken();

    public Token getPreviousToken();

    public boolean hasParentOfType(TrnType tp);
}


text:
package org.apache.wink.itest.lifecycles;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import junit.framework.TestCase;

import org.apache.commons.httpclient.HttpException;
import org.apache.wink.client.ClientResponse;
import org.apache.wink.client.RestClient;
import org.apache.wink.test.integration.ServerEnvironmentInfo;

public class WinkClientLifeCycleTest extends TestCase {

    public static String getBaseURI() {
        if (ServerEnvironmentInfo.isRestFilterUsed()) {
            return ServerEnvironmentInfo.getBaseURI();
        }
        return ServerEnvironmentInfo.getBaseURI() + "/lifecycles";
    }

    protected RestClient client;

    @Override
    public void setUp() {
        client = new RestClient();
    }

    /**
     * Tests that providers are singletons no matter what.
     *
     * @throws HttpException
     * @throws IOException
     * @throws URISyntaxException
     */
    public void testProvidersAreSingleton() throws URISyntaxException {
        StringBuffer sb = new StringBuffer();
        for (long c = 0; c < 5000; ++c) {
            sb.append("a");
        }

        ClientResponse response =
            client.resource(getBaseURI() + "/jaxrs/tests/lifecycles").delete();
        assertEquals(204, response.getStatusCode());

        for (int counter = 0; counter < 100; ++counter) {
            String responseBody =
                client.resource(new URI(getBaseURI() + "/jaxrs/tests/lifecycles"))
                    .contentType("text/plain").post(String.class, sb.toString());
            assertEquals(sb.toString(), responseBody);
        }

        response = client.resource(getBaseURI() + "/jaxrs/tests/lifecycles").get();
        assertEquals(200, response.getStatusCode());
        assertEquals("1:100:100:101:100:1", response.getEntity(String.class));
    }
}


text:
I represent an unpacking object that is able to receive serialized objects, e.g., FUEL or STON, and tries all available packing systems to unpack the serialized objects.

Others can ask me for materializing an object by sending me #unpack:. I resent the request to GTEventPacking objects and if anyone is able to materialize it, I will return the materialized object. Otherwise, I raise an error.

Collaborators Part: GTEventPacking, GTEventInitializationError, GTEventUnpackingError.

Public API and Key Messages

- unpack: aByteArray
- addPacking: aGTEventPacking
- how to create instances: #default on the class side.

Example:
	(GTEventUnpacking default
		unpack: (GTEventPacking ston
					pack: (GTEventCollector new
							add: 1; add: 2; add: 3; yourself))
			data) unpackedData

Internal Representation and Key Implementation Points.

    Instance Variables
	packings:		<OrderedCollection>


text:
'use strict';

const errors = require('../../deployment_hooks/lib/errors');
const proxyquire = require('proxyquire');

describe('action', function () {
  describe('JSExecutor', function () {
    let sandbox, processExitStub, initialProcessArgv, proxyLibs, consoleErrorStub;
    before(function () {
      sandbox = sinon.sandbox.create();
    });
    beforeEach(function () {
      processExitStub = sandbox.stub(process, 'exit');
      consoleErrorStub = sandbox.stub(console, 'error');
      initialProcessArgv = process.argv;
      process.argv = [];
    });
    afterEach(function () {
      processExitStub.reset();
      processExitStub.restore();
      consoleErrorStub.reset();
      consoleErrorStub.restore();
      process.argv = initialProcessArgv;
    });
    it('should print correct action response', function () {
      proxyLibs = {};
      process.argv[2] = 'ReserveIps';
      process.argv[3] = 'PreCreate';
      process.argv[4] = '{}';
      return proxyquire('../../deployment_hooks/lib/actions/JSExecutor', proxyLibs)
        .then(() => {
          expect(consoleErrorStub.callCount).to.equal(0);
          expect(processExitStub.callCount).to.equal(0);
        });
    });
    it('should throw error', function () {
      proxyLibs = {
        './js/ReserveIps': {
          'executePreCreate': function () {
            throw new errors.InternalServerError(`error in script`);
          }
        }
      };
      process.argv[2] = 'ReserveIps';
      process.argv[3] = 'PreCreate';
      process.argv[4] = 'context';
      return proxyquire('../../deployment_hooks/lib/actions/JSExecutor', proxyLibs)
        .then(() => {
          expect(consoleErrorStub.callCount).to.equal(2);
          expect(processExitStub.callCount).to.equal(1);
        });
    });
    it('should exit if args are invalid', function () {
      proxyLibs = {};
      process.argv[2] = 'ReserveIps';
      return proxyquire('../../deployment_hooks/lib/actions/JSExecutor', proxyLibs)
        .then(() => {
          expect(consoleErrorStub.callCount).to.equal(1);
          expect(processExitStub.callCount).to.equal(1);
        });
    });
  });
});


text:
var logfmt = require('../logfmt'),
    assert = require('assert');

var OutStream = require('./outstream');
var mock_sink = new OutStream;

suite('logfmt.log', function() {
  test("logs simple key value pairs", function(){
    var data = {foo: 'bar', a: 14}
    logfmt.log(data, mock_sink);
    assert.equal("foo=bar a=14\n", mock_sink.logline)
  })

  test("logs true and false as strings", function(){
    var data = {foo: true, bar: false}
    logfmt.log(data, mock_sink);
    assert.equal("foo=true bar=false\n", mock_sink.logline)
  })

  test("quotes strings with spaces in them", function(){
    var data = {foo: "hello kitty"}
    logfmt.log(data, mock_sink);
    assert.equal("foo=\"hello kitty\"\n", mock_sink.logline)
  })

  test("quotes strings with equals in them", function(){
    var data = {foo: "hello=kitty"}
    logfmt.log(data, mock_sink);
    assert.equal("foo=\"hello=kitty\"\n", mock_sink.logline)
  })

  test("escapes quotes within strings with spaces in them", function(){
    var data = {foo: 'hello my "friend"'}
    logfmt.log(data, mock_sink);
    assert.equal('foo="hello my \\"friend\\""\n', mock_sink.logline)
    var data = {foo: 'hello my "friend" whom I "love"'}
    logfmt.log(data, mock_sink);
    assert.equal('foo="hello my \\"friend\\" whom I \\"love\\""\n', mock_sink.logline)
  })

  test("undefined is logged as nothing", function(){
    var data = {foo: undefined}
    logfmt.log(data, mock_sink);
    assert.equal("foo=\n", mock_sink.logline)
  })

  test("null is logged as nothing", function(){
    var data = {foo: null}
    logfmt.log(data, mock_sink);
    assert.equal("foo=\n", mock_sink.logline)
  })

  test("setting sink at object level", function(){
    var data = {foo: "hello kitty"}
    var stream = logfmt.stream;
    logfmt.stream = mock_sink;
    logfmt.log(data);
    assert.equal("foo=\"hello kitty\"\n", mock_sink.logline)
    logfmt.stream = stream;
  })
})


text:
#region Licence

#endregion

using System;
using System.Linq;
using FluentAssertions;
using Paramore.Brighter.MessagingGateway.RMQ;
using Xunit;

namespace Paramore.Brighter.RMQ.Tests.MessagingGateway
{
    [Trait("Category", "RMQ")]
    public class RmqMessageProducerSendMessageTests : IDisposable
    {
        private readonly IAmAMessageProducerSync _messageProducer;
        private readonly IAmAMessageConsumer _messageConsumer;
        private readonly Message _message;

        public RmqMessageProducerSendMessageTests()
        {
            _message = new Message(
                new MessageHeader(Guid.NewGuid(), Guid.NewGuid().ToString(), MessageType.MT_COMMAND),
                new MessageBody("test content"));

            var rmqConnection = new RmqMessagingGatewayConnection
            {
                AmpqUri = new AmqpUriSpecification(new Uri("amqp://guest:guest@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange")
            };

            _messageProducer = new RmqMessageProducer(rmqConnection);
            _messageConsumer = new RmqMessageConsumer(rmqConnection, _message.Header.Topic, _message.Header.Topic, false, false);

            new QueueFactory(rmqConnection, _message.Header.Topic).Create(3000);
        }

        [Fact]
        public void When_posting_a_message_via_the_messaging_gateway()
        {
            _messageProducer.Send(_message);

            var result = _messageConsumer.Receive(10000).First();

            //_should_send_a_message_via_rmq_with_the_matching_body
            result.Body.Value.Should().Be(_message.Body.Value);
       }

        public void Dispose()
        {
            _messageProducer.Dispose();
        }
    }
}


text:
class Post < ActiveRecord::Base
  extra_sanitize :columns => :all
end


text:
package cz.znj.kvr.sw.exp.java.corejava.stream;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Optional;
import java.util.stream.Stream;

/**
 * Optional.findFirst tests.
 */
public class OptionalTest
{
    @Test(expectedExceptions = NullPointerException.class)
    public void findFirstNull() {
        Optional<Integer> result = Stream.of(null, 1)
                .findFirst();
    }

    @Test
    public void findFirstNull_flatMap()
    {
        Optional<Integer> result = Stream.of(null, 1)
                .map(Optional::ofNullable)
                .findFirst()
                .orElseGet(Optional::empty);

        Assert.assertEquals(result, Optional.ofNullable(null));
    }
}


text:
package com.camunda.consulting.changeJobRetry;

import java.util.logging.Logger;

import org.camunda.bpm.engine.OptimisticLockingException;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;

/**
 * @author Ingo Richtsmeier
 *
 */
public class RepairableDelegate implements JavaDelegate {

  private final static Logger log = Logger.getLogger(RepairableDelegate.class.getName());

  @Override
  public void execute(DelegateExecution execution) throws Exception {
    String fail = (String) execution.getVariable("fail");
    if (fail == null) {
      fail = "true";
    }
    log.info("execute Repairable Service Task with fail = " + fail);
    if ("true".equals(fail)) {
      throw new ProcessEngineException("Repairable Service Task should fail");
    } else if ("optimisticLockingException".equals(fail)) {
      throw new OptimisticLockingException("Service Task throws OptimisticLockingException");
    }
  }

}


text:
namespace SampleFramework11
{

class App
{

public:

    App(const wchar* appName, const wchar* iconResource = NULL);
    virtual ~App();

    int32 Run();

    void RenderText(const std::wstring& text, Float2 pos);
    void RenderCenteredText(const std::wstring& text);

protected:

    virtual void Initialize();
    virtual void Update(const Timer& timer) = 0;
    virtual void Render(const Timer& timer) = 0;

    virtual void BeforeReset();
    virtual void AfterReset();

    void Exit();
    void ToggleFullScreen(bool fullScreen);
    void CalculateFPS();

    static LRESULT OnWindowResized(void* context, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

    Window window;
    DeviceManager deviceManager;
    Timer timer;

    BlendStates blendStates;
    RasterizerStates rasterizerStates;
    DepthStencilStates depthStencilStates;
    SamplerStates samplerStates;

    SpriteFont font;
    SpriteRenderer spriteRenderer;

    static const uint32 NumTimeDeltaSamples = 64;
    float timeDeltaBuffer[NumTimeDeltaSamples];
    uint32 currentTimeDeltaSample;
    uint32 fps;

    TwBar* tweakBar;

    std::wstring applicationName;

    bool createConsole;
    bool showWindow;
    int32 returnCode;

public:

    // Accessors
    Window& Window() { return window; }
    DeviceManager& DeviceManager() { return deviceManager; }
    SpriteFont& Font() { return font; }
    SpriteRenderer& SpriteRenderer() { return spriteRenderer; }
    TwBar* TweakBar() { return tweakBar; }
};

extern App* GlobalApp;

}


text:
<?php

namespace TaskntagBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class TaskntagBundle extends Bundle
{
}


text:
package com.blp.minotaurus;

import com.blp.minotaurus.arena.ArenaManager;
import com.blp.minotaurus.bukkit.Config;
import com.blp.minotaurus.bukkit.Locales;
import com.blp.minotaurus.commands.MinotaurusCommand;
import com.blp.minotaurus.database.Database;
import com.blp.minotaurus.database.MySQL;
import com.blp.minotaurus.database.SQLite;
import com.blp.minotaurus.listener.BukkitBlockEvent;
import com.blp.minotaurus.listener.BukkitCommandEvent;
import com.blp.minotaurus.listener.BukkitDamageEvent;
import com.blp.minotaurus.listener.BukkitDeathEvent;
import com.blp.minotaurus.listener.BukkitInventoryEvent;
import com.blp.minotaurus.listener.BukkitJoinEvent;
import com.blp.minotaurus.listener.BukkitMoveEvent;
import com.blp.minotaurus.listener.BukkitQuitEvent;
import com.blp.minotaurus.listener.BukkitSignEvent;
import com.blp.minotaurus.reflection.Manager;
import com.blp.minotaurus.utils.EconomyManager;
import com.blp.minotaurus.utils.MCStats;
import com.blp.minotaurus.utils.SqlHelper;
import de.thejeterlp.bukkit.updater.ReleaseType;
import de.thejeterlp.bukkit.updater.UpdateType;
import de.thejeterlp.bukkit.updater.Updater;
import java.sql.SQLException;
import org.bukkit.plugin.java.JavaPlugin;

/**
 * Project: Minotaurus

 *
 * Class: Minotaurus
 *
 * @author  BossLetsPlays in corporation with  TheJeterLP
 *
 */
public class Minotaurus extends JavaPlugin {

    private static Minotaurus INSTANCE;
    private static Database db = null;

    private boolean vaultFound = false;

    @Override
    public void onEnable() {
        INSTANCE = this;

        Config.load(this, "config.yml");
        Locales.load(this, "locales.yml");

        db = Config.USE_MYSQL.getBoolean() ? new MySQL() : new SQLite();
        SqlHelper.init();

        vaultFound = EconomyManager.setupEconomy();

        ArenaManager.setupArenas();
        Manager.registerListener(BukkitBlockEvent.class);
        Manager.registerListener(BukkitDeathEvent.class);
        Manager.registerListener(BukkitQuitEvent.class);
        Manager.registerListener(BukkitSignEvent.class);
        Manager.registerListener(BukkitCommandEvent.class);
        Manager.registerListener(BukkitDamageEvent.class);
        Manager.registerListener(BukkitJoinEvent.class);
        Manager.registerListener(BukkitInventoryEvent.class);
        Manager.registerListener(BukkitMoveEvent.class);
        Manager.registerCommand(MinotaurusCommand.class);

        MCStats.init();

        //will be changed when the project is on dev.bukkit.org to the project id
        Updater u = new Updater(this, -1, "minotaurus", Config.OPTIONS_CHECK_UPDATES.getBoolean(), UpdateType.DOWNLOAD, ReleaseType.BETA);
        u.search();

    }

    @Override
    public void onDisable() {
        try {
            ArenaManager.updateArenas();
            db.closeConnection();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public static Minotaurus getInstance() {
        return INSTANCE;
    }

    public static Database getDB() {
        return db;
    }

    public boolean isVaultEnabled() {
        return Config.OPTIONS_MONEY_ENABLED.getBoolean() && vaultFound;
    }
}


text:
<?php

class CM_Paging_Log_Javascript extends CM_Paging_Log {

    public function __construct(array $filterLevelList, $aggregate = false, $ageMax = null) {
        parent::__construct($filterLevelList, self::getTypeStatic(), $aggregate, $ageMax);
    }
}


text:
/*
 * A directive to view published Google Docs documents.
 *
 * Usage: ('!' indicates the attribute is watched for changes)
 *   <g-docs-viewer !url="String expr"></g-docs-viewer>
 */
angular.module('GDocsViewer', [])
  .directive('gDocsViewer', [
    '$sce',
    function ($sce) {
      return {
        restrict: 'E',
        templateUrl: 'shared/directives/g_docs_viewer.html',

        scope: {
          url: '<'
        },

        link: function (scope, element, attrs) {
          scope.trustedUrl = null;

          scope.$watch('url', function (value) {
            if (value) {
              var embeddedUrl = (_.endsWith(value, '/pub'))
                ? value + '?embedded=true'
                : value;

              scope.trustedUrl = $sce.trustAsResourceUrl(embeddedUrl);
            } else {
              scope.trustedUrl = null;
            }
          });
        }
      };
    }]);


text:
#pragma once
#include <vector>
#include <string>
#include <iostream>
#include "ForexConnect/ForexConnect.h"

#ifndef id
typedef struct objc_object *id;
#endif

typedef struct objc_selector    *SEL;
typedef void (*objc_call)(id, SEL, signed char);

typedef struct
{
    id target;
    SEL selector;
    objc_call call;
    signed char param;
} idWrapper;

class COffersController : private IO2GSessionStatus, IO2GResponseListener
{
 public:

    static COffersController* getInstance();

    double getLow(size_t index) const;
    double getHigh(size_t index) const;
    double getBid(size_t index) const;
    double getAsk(size_t index) const;
    const char * getInstrumentText(size_t index);
    int getBidDirection(size_t index) const;
    int getAskDirection(size_t index) const;
    int getDigits(size_t index) const;
    const char * getStatusText();

    bool isCellChanged(size_t index);

    void setLoginData(const char *user, const char *pwd, const char *url, const char *connection);
    void login();
    void logout();
    void setTradingSessionDescriptors(const char *sessionID, const char *pin);
    void setProxy(const char *pname, int port, const char *user, const char *password);
    void setCAInfo(const char *caFilePath);

    size_t size() const
        { return mRows.size(); }

    void setData(IO2GOffersTableResponseReader *pOffersReader);

    void subscribe(void *pListener);

    void unsubscribe()
        { mIdWrapper = NULL; }

    void createOrder(int offerIndex, bool isBuy, int nAmount, double fRate, int orderType);

    // Thread safe implementation.
    long addRef();
    long release();

protected:

    COffersController();
    ~COffersController();

    void onOffersRecieved(IO2GResponse *response);
    void onTableUpdateReceive(IO2GResponse *response);
    void onAccountsReceived(IO2GResponse *response);

    void onRequestCompleted(const char * requestId, IO2GResponse  *response = 0)
    {}
    void onRequestFailed(const char *requestId , const char *error)
    {}
    void onTablesUpdates(IO2GResponse *data);

    /** Log string to console.*/
    void logString(const char *logmessage);

    void onSessionStatusChanged(O2GSessionStatus status);
    void onLoginFailed(const char *error);

    void notify();

    static unsigned long getTickCount();

    typedef struct COfferRow
    {
        double fBid;
        double fAsk;
        double fLow;
        double fHigh;
        std::string sOfferId;
        std::string sInstrument;
        bool isChanged;
        int nBidDirection;
        int nAskDirection;
        int nDigits;
        unsigned int dropDirectionCount;
    };

    static COffersController* inst;
    std::vector<COfferRow*> mRows;
    pthread_mutex_t mRowsLock;
    IO2GSession *mSession;

    std::string mUserName;
    std::string mPassword;
    std::string mConnection;
    std::string mHost;
    std::string mSessionID;
    std::string mPin;

    std::string msFirstAccountID;
    std::string mStatusText;

    idWrapper *mIdWrapper;
    volatile long dwRef;
};


text:
require 'minitest/mock'
require 'test_helper'
require 'cocaine'

@command = MiniTest::Mock.new

Cocaine::CommandLine.stub(:new, @command) do
  @command.expect(:run, fixture("iw/help"))
  require 'omf_rc/util/iw'

  describe OmfRc::Util::Iw do
    describe "when included in the resource instance" do
      before do
        @command = MiniTest::Mock.new

        module OmfRc::ResourceProxy::IwTest
          include OmfRc::ResourceProxyDSL
          register_proxy :iw_test
          utility :iw
        end

        @xmpp = MiniTest::Mock.new
        @xmpp.expect(:subscribe, true, [Array])

        OmfCommon.stub :comm, @xmpp do
          @wlan00 = OmfRc::ResourceFactory.new(:iw_test, hrn: 'wlan00', property: { phy: 'phy00' })
        end
      end

      it "must provide features defined in proxy" do
        %w(request_link configure_name configure_channel configure_bitrates).each do |m|
          OmfRc::Util::Iw.method_defined?(m).must_equal true
        end
      end

      it "could request properties of the wifi interface" do
        Cocaine::CommandLine.stub(:new, @command) do
          @command.expect(:run, fixture("iw/link"))
          @wlan00.request_link.keys.must_include "ssid"
          @command.verify
        end
      end

      it "could request info of the wifi interface" do
        Cocaine::CommandLine.stub(:new, @command) do
          @command.expect(:run, fixture("iw/info"))
          @wlan00.request_info.keys.must_equal ["ifindex", "type", "wiphy"]
          @command.verify
        end
      end

      it "could configure the device's prorperty" do
        Cocaine::CommandLine.stub(:new, @command) do
          @command.expect(:run, true)
          @wlan00.configure_power_save(true)
          @command.verify
        end
      end

      it "must could initialise wpa config/pid file path" do
        @wlan00.init_ap_conf_pid
        @wlan00.request_ap_conf.must_match /tmp\/hostapd\.wlan00.+\.conf/
        @wlan00.request_ap_pid.must_match /tmp\/hostapd\.wlan00.+\.pid/
      end

      it "must could initialise wpa config/pid file path" do
        @wlan00.init_wpa_conf_pid
        @wlan00.request_wpa_conf.must_match /tmp\/wpa\.wlan00.+\.conf/
        @wlan00.request_wpa_pid.must_match /tmp\/wpa\.wlan00.+\.pid/
      end

      it "could delete current interface" do
        Cocaine::CommandLine.stub(:new, @command) do
          @command.expect(:run, true)
          @wlan00.delele_interface
          @command.verify
        end
      end

      it "could add a new interface" do
        Cocaine::CommandLine.stub(:new, @command) do
          @command.expect(:run, true)
          @wlan00.add_interface(:managed)
          @command.verify
        end
      end

      it "must be able to validate iw parameters when setting up mode" do
        lambda { @wlan00.configure_mode(mode: 'master') }.must_raise ArgumentError
        lambda { @wlan00.configure_mode(mode: 'bob') }.must_raise ArgumentError
        lambda { @wlan00.configure_mode(mode: 'master', hw_mode: 'x') }.must_raise ArgumentError
        lambda { @wlan00.configure_mode(hw_mode: 'x') }.must_raise ArgumentError
      end

      it "must be able to configure as master mode" do
        Cocaine::CommandLine.stub(:new, @command) do
          3.times { @command.expect(:run, true) }

          @wlan00.configure_mode(mode: 'master', channel: 1, essid: 'bob', hw_mode: 'b')
          File.open(@wlan00.property.ap_conf) do |f|
            f.read.must_match "driver=nl80211\ninterface=wlan00\nssid=bob\nchannel=1\nhw_mode=b\n"
          end

          3.times { @command.expect(:run, true) }

          @wlan00.configure_mode(mode: 'master', channel: 1, essid: 'bob', hw_mode: 'n')
          File.open(@wlan00.property.ap_conf) do |f|
            f.read.must_match "driver=nl80211\ninterface=wlan00\nssid=bob\nchannel=1\nhw_mode=g\nwmm_enabled=1\nieee80211n=1\nht_capab=\[HT20\-\]\n"
          end

          3.times { @command.expect(:run, true) }

          @wlan00.configure_mode(mode: 'master', channel: 16, essid: 'bob', hw_mode: 'n')
          File.open(@wlan00.property.ap_conf) do |f|
            f.read.must_match "driver=nl80211\ninterface=wlan00\nssid=bob\nchannel=16\nhw_mode=a\nwmm_enabled=1\nieee80211n=1\nht_capab=\[HT20\-\]\n"
          end

          @command.verify
        end
      end

      it "must be able to configure as managed mode" do
        Cocaine::CommandLine.stub(:new, @command) do
          3.times { @command.expect(:run, true) }

          @wlan00.configure_mode(mode: 'managed', essid: 'bob')
          File.open(@wlan00.property.wpa_conf) do |f|
            f.read.must_match "network={\n  ssid=\"bob\"\n  scan_ssid=1\n  key_mgmt=NONE\n}"
          end

          @command.verify
        end
      end

      it "must be able to configure as adhoc/ibss mode" do
        Cocaine::CommandLine.stub(:new, @command) do
          4.times { @command.expect(:run, true) }

          @wlan00.configure_mode(mode: 'adhoc', essid: 'bob', frequency: 2412)
          @command.verify
        end
      end

      it "must be able to configure as monitor mode" do
        Cocaine::CommandLine.stub(:new, @command) do
          3.times { @command.expect(:run, true) }

          @wlan00.configure_mode(mode: 'monitor')
          @command.verify
        end
      end
    end
  end
end


text:
require 'test_helper'

class StaticPagesTest < ActionDispatch::IntegrationTest

  test "get the home page" do
    visit("/")
    within("h1") do
      assert has_content?('Your personal swedish vocabulary app')
    end
  end

  test "get the help page" do
    visit("/static_pages/help")
    within("h1") do
      assert has_content?('Help')
    end
  end

end


text:
@interface XMGPictureViewController : UITableViewController

@end


text:
package code.model

import _root_.org.specs._
import _root_.org.specs.runner.JUnit4
import _root_.org.specs.runner.ConsoleRunner
import _root_.net.liftweb.common._
import _root_.net.liftweb.util._
import _root_.net.liftweb.mapper._

import Helpers._

class ActivitySpecsAsTest extends JUnit4(UserSpecs)
//object UserSpecsRunner extends ConsoleRunner(UserSpecs)

object ActivitySpecs extends Specification {
  val provider = DBProviders.PostgreSqlProvider

  private def ignoreLogger(f: => AnyRef): Unit = ()

  def setupDB {
    MapperRules.createForeignKeys_? = c => false
    provider.setupDB
    Schemifier.destroyTables_!!(ignoreLogger _,  User, Activity, ActivityType)
    Schemifier.schemify(true, ignoreLogger _, User, Activity, ActivityType)

    val userNovak = createUser("Novak", "Dokovic")
    userNovak.save

    val userRoger = createUser("Roger", "Federer")
    userRoger.save

    val userAndy = createUser("Andy", "Murray")
    userAndy.save

    val userGael = createUser("Gael", "Monfils")
    userGael.save

    val userDavid = createUser("David", "Nalbandian")
    userDavid.save

    val userTsonga = createUser("Wilfried", "Tsonga")
    userTsonga.save

    val userLukas = createUser("Lukas", "Lacko")
    userLukas.save

    val userLlodra = createUser("Michael", "Llodra")
    userLlodra.save
  }

  def createUser(name: String, surname: String) : User = {
    var user = User.create
    user.firstName(name)
    user.lastName(surname)
    user.email(name + '.' + surname + "@gmail.com")
    user.password("password")
    user.aboutMe("tenisac")
    user.validated(true)
  }

  def createType(s: String): ActivityType = {
    var activityType = ActivityType.create
    activityType.typeString(s)
  }

  "Activity" should {
    "create posts" in {
      setupDB

      // unsuccessful because ActicityType doesn't exist
      var userNovak = User.find(By(User.firstName, "Novak"))
      var activity = Activity.createPost("Ovo je moj prvi blog post")

      for {u <- userNovak
	   a <- activity} {
	u.addActivity(a)
      }

      var found = Activity.findAll(By(Activity.user, userNovak))
      found.length must be(0)

      for {u <- userNovak} {
	found = u.getActivities()
	found.length must be(0)
      }

      // successful creation of post
      var t = createType("post")
      t.save

      activity = Activity.createPost("Ovo je moj prvi blog post")
      for {u <- userNovak
	   a <- activity} {
	u.addActivity(a)
      }

      for {u <- userNovak} {
	found = u.getActivities()
	found.length must be(1)
      }

      found = Activity.findAll(By(Activity.user, userNovak))
      found.length must be(1)

      found = Activity.findAll(By(Activity.text, "Ovo je moj prvi blog post"))
      found.length must be(1)

      found = Activity.findAll(By(Activity.activityType, t))
      found.length must be(1)

      // removing activity
      for {u <- userNovak
	   a <- activity} {
	u.removeActivity(a)
      }

      for {u <- userNovak} {
	found = u.getActivities()
	found.length must be(0)
      }

      found = Activity.findAll(By(Activity.user, userNovak))
      found.length must be(0)

      provider.vendor.releaseConnection(provider.vendor.mkConn)
    }

    "create blog posts" in {
      setupDB

      // unsuccessful because ActicityType doesn't exist
      var userNovak = User.find(By(User.firstName, "Novak"))
      var activity = Activity.createBlogPost("Prva tema",
					     "Ovo je moj prvi blog post", Empty, Nil)

      for {u <- userNovak
	   a <- activity} {
	u.addActivity(a)
      }

      var found = Activity.findAll(By(Activity.user, userNovak))
      found.length must be(0)

      for {u <- userNovak} {
	found = u.getActivities()
	found.length must be(0)
      }

      // successful creation of post
      var t = createType("blog")
      t.save

      activity = Activity.createBlogPost("Prva tema", "Ovo je moj prvi blog post", Empty, Nil)
      for {u <- userNovak
	   a <- activity} {
	u.addActivity(a)
      }

      for {u <- userNovak} {
	found = u.getActivities()
	found.length must be(1)
      }

      found = Activity.findAll(By(Activity.user, userNovak))
      found.length must be(1)

      found = Activity.findAll(By(Activity.text, "Ovo je moj prvi blog post"))
      found.length must be(1)

      found = Activity.findAll(By(Activity.activityType, t))
      found.length must be(1)

      // removing activity
      for {u <- userNovak
	   a <- activity} {
	u.removeActivity(a)
      }

      for {u <- userNovak} {
	found = u.getActivities()
	found.length must be(0)
      }

      found = Activity.findAll(By(Activity.user, userNovak))
      found.length must be(0)

      provider.vendor.releaseConnection(provider.vendor.mkConn)
    }
  }
}


text:
public class CheckingAccount {
}


text:
\echo --start_ignore
set gp_enable_column_oriented_table=on;
\echo --end_ignore
SELECT COUNT(*) FROM dml_heap_pt_p;
DELETE FROM dml_heap_pt_p USING dml_heap_pt_r WHERE dml_heap_pt_p.b::int = dml_heap_pt_r.b::int and dml_heap_pt_p.a = dml_heap_pt_r.a;
SELECT COUNT(*) FROM dml_heap_pt_p;


text:
Thanks for your interest in contributing to Pivotal's Open Source projects!

This project is maintained by the Pivotal Cloud Foundry RabbitMQ team.

**At the moment, the team is not actively reviewing contributions to this project.**

We will aim to review or close existing pull requests and issues as of August 2017 as soon as we are able.
We do not have an expected turnaround timeframe for new PRs or issues.

If you are a PCF customer, please do not use this repository to flag issues. Please use normal customer support channels.

## Legal

The following guidelines apply to all contributions:

- Contributors must sign the [Pivotal Contributor License Agreement](https://cla.pivotal.io/sign/pivotal)
- Agree to terms of the [Cloud Foundry Code of Conduct](https://www.cloudfoundry.org/code-of-conduct/)

## General Code Contribution Guidelines

PCF Open-Source projects prefer that contributions contain:

- Descriptive and understandable tests
- Helpful [commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
- Small improvements that leave the code base better than it was before, aka the [Boy Scout
  Rule](http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule)


text:
% AutoassociativeNetwork class:  extends HebbMarrNetwork
% for auto-association by adding recurrent connections from outputs
% from period t as the inputs to period t+1, as proposed in:
% McNaughton, B. L., & Nadel, L. (1990). "Hebb-Marr networks and the neurobiological
% representation of action in space" Neuroscience and connectionist theory, 1{63.
classdef AutoassociativeNetwork < HebbMarrNetwork

    properties
        wiring
        currentInputX
        currentOutput
        matchThreshold
    end
    methods
        function obj = AutoassociativeNetwork(dimension)
            obj = obj@HebbMarrNetwork(dimension);
            obj.wiring = SequentialWiring(dimension);
            obj.currentInputX = zeros(1,dimension);
            obj.matchThreshold = 0;
        end
        function fired = step(obj, inputX, inputY)
            if sum(inputX) == 0
                inputX = obj.currentInputX;
            end
            fired = step@HebbMarrNetwork(obj, inputX, inputY);
            obj.currentInputX = obj.wiring.connect(fired);
            obj.currentOutput = fired;
        end
        function retrieved = read(obj, inputX)
            retrieved = zeros(1,obj.nNeurons);
            verifyInputs(obj,inputX,[]);
            totalActivation = sum(inputX);
            product = inputX*obj.network;
            while ((totalActivation > obj.matchThreshold) && (sum(retrieved) == 0))
                if totalActivation > obj.matchThreshold
                    retrieved = fix(product/totalActivation); % round toward 0
                    disp(['totalActivation: ',num2str(totalActivation),' retrieved: ', ...
                        mat2str(find(retrieved >= 1))]);
                end
                totalActivation = totalActivation - 1;
            end
            obj.currentOutput = retrieved;

        end
        function inputX = getCurrentInputX(obj)
            inputX = obj.currentInputX;
        end
        function shortOutput = outputIndices(obj)
            shortOutput = find(obj.currentOutput == 1);
        end
    end
end


text:
package com.github.dozermapper.core.inject;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.github.dozermapper.core.MappingException;
import com.github.dozermapper.core.util.ReflectionUtils;

public class DozerBeanContainer implements BeanRegistry {

    private Map<Class<?>, Object[]> beans = new ConcurrentHashMap<>();

    public void register(Class<?> type) {
        beans.put(type, new Object[1]);
    }

    public <T> T getBean(Class<T> type) {
        Collection<T> result = getBeans(type);
        if (result.isEmpty()) {
            throw new IllegalStateException("Bean is not registered : " + type.getName());
        }
        if (result.size() > 1) {
            throw new IllegalStateException("More than one bean found of type : " + type.getName());
        }

        return result.iterator().next();
    }

    public <T> Collection<T> getBeans(Class<T> type) {
        HashSet<T> result = new HashSet<>();
        for (Map.Entry<Class<?>, Object[]> entry : beans.entrySet()) {
            if (type.isAssignableFrom(entry.getKey())) {
                Object[] value = entry.getValue();
                if (value[0] == null) {
                    value[0] = wireBean(entry.getKey());
                }
                result.add((T)value[0]);
            }
        }
        return result;
    }

    private <T> T wireBean(Class<T> type) {
        final T bean = ReflectionUtils.newInstance(type);

        Field[] destFields = type.getDeclaredFields();
        for (Field field : destFields) {
            Inject inject = field.getAnnotation(Inject.class);
            if (inject != null) {
                Class<?> fieldType = field.getType();
                try {
                    if (field.get(bean) == null) {
                        Object dependency = wireBean(fieldType);
                        field.set(bean, dependency);
                    }
                } catch (IllegalAccessException e) {
                    throw new MappingException("Field annotated with @Inject is not accessible : " + field.getName(), e);
                }
            }
        }

        Object[] instance = beans.get(type);
        if (instance == null) {
            instance = new Object[1];
            beans.put(type, instance);
        }
        instance[0] = bean;
        return bean;
    }

}


text:
using namespace llvm;
using namespace llvm::X86Disassembler;

void x86DisassemblerDebug(const char *file,
                          unsigned line,
                          const char *s) {
  dbgs() << file << ":" << line << ": " << s;
}

const char *x86DisassemblerGetInstrName(unsigned Opcode, const void *mii) {
  const MCInstrInfo *MII = static_cast<const MCInstrInfo *>(mii);
  return MII->getName(Opcode);
}

#define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));

namespace llvm {

// Fill-ins to make the compiler happy.  These constants are never actually
//   assigned; they are just filler to make an automatically-generated switch
//   statement work.
namespace X86 {
  enum {
    BX_SI = 500,
    BX_DI = 501,
    BP_SI = 502,
    BP_DI = 503,
    sib   = 504,
    sib64 = 505
  };
}

extern Target TheX86_32Target, TheX86_64Target;

}

static bool translateInstruction(MCInst &target,
                                InternalInstruction &source,
                                const MCDisassembler *Dis);

X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,
                                               DisassemblerMode mode,
                                               const MCInstrInfo *MII)
  : MCDisassembler(STI), MII(MII), fMode(mode) {}

X86GenericDisassembler::~X86GenericDisassembler() {
  delete MII;
}

/// regionReader - a callback function that wraps the readByte method from
///   MemoryObject.
///
/// @param arg      - The generic callback parameter.  In this case, this should
///                   be a pointer to a MemoryObject.
/// @param byte     - A pointer to the byte to be read.
/// @param address  - The address to be read.
static int regionReader(const void* arg, uint8_t* byte, uint64_t address) {
  const MemoryObject* region = static_cast<const MemoryObject*>(arg);
  return region->readByte(address, byte);
}

/// logger - a callback function that wraps the operator<< method from
///   raw_ostream.
///
/// @param arg      - The generic callback parameter.  This should be a pointe
///                   to a raw_ostream.
/// @param log      - A string to be logged.  logger() adds a newline.
static void logger(void* arg, const char* log) {
  if (!arg)
    return;

  raw_ostream &vStream = *(static_cast<raw_ostream*>(arg));
  vStream << log << "\n";
}

//
// Public interface for the disassembler
//

MCDisassembler::DecodeStatus
X86GenericDisassembler::getInstruction(MCInst &instr,
                                       uint64_t &size,
                                       const MemoryObject &region,
                                       uint64_t address,
                                       raw_ostream &vStream,
                                       raw_ostream &cStream) const {
  CommentStream = &cStream;

  InternalInstruction internalInstr;

  dlog_t loggerFn = logger;
  if (&vStream == &nulls())
    loggerFn = 0; // Disable logging completely if it's going to nulls().

  int ret = decodeInstruction(&internalInstr,
                              regionReader,
                              (const void*)&region,
                              loggerFn,
                              (void*)&vStream,
                              (const void*)MII,
                              address,
                              fMode);

  if (ret) {
    size = internalInstr.readerCursor - address;
    return Fail;
  }
  else {
    size = internalInstr.length;
    return (!translateInstruction(instr, internalInstr, this)) ?
            Success : Fail;
  }
}

//
// Private code that translates from struct InternalInstructions to MCInsts.
//

/// translateRegister - Translates an internal register to the appropriate LLVM
///   register, and appends it as an operand to an MCInst.
///
/// @param mcInst     - The MCInst to append to.
/// @param reg        - The Reg to append.
static void translateRegister(MCInst &mcInst, Reg reg) {
#define ENTRY(x) X86::x,
  uint8_t llvmRegnums[] = {
    ALL_REGS
    0
  };
#undef ENTRY

  uint8_t llvmRegnum = llvmRegnums[reg];
  mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
}

/// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the
/// immediate Value in the MCInst.
///
/// @param Value      - The immediate Value, has had any PC adjustment made by
///                     the caller.
/// @param isBranch   - If the instruction is a branch instruction
/// @param Address    - The starting address of the instruction
/// @param Offset     - The byte offset to this immediate in the instruction
/// @param Width      - The byte width of this immediate in the instruction
///
/// If the getOpInfo() function was set when setupForSymbolicDisassembly() was
/// called then that function is called to get any symbolic information for the
/// immediate in the instruction using the Address, Offset and Width.  If that
/// returns non-zero then the symbolic information it returns is used to create
/// an MCExpr and that is added as an operand to the MCInst.  If getOpInfo()
/// returns zero and isBranch is true then a symbol look up for immediate Value
/// is done and if a symbol is found an MCExpr is created with that, else
/// an MCExpr with the immediate Value is created.  This function returns true
/// if it adds an operand to the MCInst and false otherwise.
static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
                                     uint64_t Address, uint64_t Offset,
                                     uint64_t Width, MCInst &MI,
                                     const MCDisassembler *Dis) {
  return Dis->tryAddingSymbolicOperand(MI, Value, Address, isBranch,
                                       Offset, Width);
}

/// tryAddingPcLoadReferenceComment - trys to add a comment as to what is being
/// referenced by a load instruction with the base register that is the rip.
/// These can often be addresses in a literal pool.  The Address of the
/// instruction and its immediate Value are used to determine the address
/// being referenced in the literal pool entry.  The SymbolLookUp call back will
/// return a pointer to a literal 'C' string if the referenced address is an
/// address into a section with 'C' string literals.
static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Value,
                                            const void *Decoder) {
  const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);
  Dis->tryAddingPcLoadReferenceComment(Value, Address);
}

/// translateImmediate  - Appends an immediate operand to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param immediate    - The immediate value to append.
/// @param operand      - The operand, as stored in the descriptor table.
/// @param insn         - The internal instruction.
static void translateImmediate(MCInst &mcInst, uint64_t immediate,
                               const OperandSpecifier &operand,
                               InternalInstruction &insn,
                               const MCDisassembler *Dis) {
  // Sign-extend the immediate if necessary.

  OperandType type = (OperandType)operand.type;

  bool isBranch = false;
  uint64_t pcrel = 0;
  if (type == TYPE_RELv) {
    isBranch = true;
    pcrel = insn.startLocation +
            insn.immediateOffset + insn.immediateSize;
    switch (insn.displacementSize) {
    default:
      break;
    case 1:
      type = TYPE_MOFFS8;
      break;
    case 2:
      type = TYPE_MOFFS16;
      break;
    case 4:
      type = TYPE_MOFFS32;
      break;
    case 8:
      type = TYPE_MOFFS64;
      break;
    }
  }
  // By default sign-extend all X86 immediates based on their encoding.
  else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
           type == TYPE_IMM64) {
    uint32_t Opcode = mcInst.getOpcode();
    switch (operand.encoding) {
    default:
      break;
    case ENCODING_IB:
      // Special case those X86 instructions that use the imm8 as a set of
      // bits, bit count, etc. and are not sign-extend.
      if (Opcode != X86::BLENDPSrri && Opcode != X86::BLENDPDrri &&
          Opcode != X86::PBLENDWrri && Opcode != X86::MPSADBWrri &&
          Opcode != X86::DPPSrri && Opcode != X86::DPPDrri &&
          Opcode != X86::INSERTPSrr && Opcode != X86::VBLENDPSYrri &&
          Opcode != X86::VBLENDPSYrmi && Opcode != X86::VBLENDPDYrri &&
          Opcode != X86::VBLENDPDYrmi && Opcode != X86::VPBLENDWrri &&
          Opcode != X86::VMPSADBWrri && Opcode != X86::VDPPSYrri &&
          Opcode != X86::VDPPSYrmi && Opcode != X86::VDPPDrri &&
          Opcode != X86::VINSERTPSrr)
        type = TYPE_MOFFS8;
      break;
    case ENCODING_IW:
      type = TYPE_MOFFS16;
      break;
    case ENCODING_ID:
      type = TYPE_MOFFS32;
      break;
    case ENCODING_IO:
      type = TYPE_MOFFS64;
      break;
    }
  }

  switch (type) {
  case TYPE_XMM32:
  case TYPE_XMM64:
  case TYPE_XMM128:
    mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
    return;
  case TYPE_XMM256:
    mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
    return;
  case TYPE_XMM512:
    mcInst.addOperand(MCOperand::CreateReg(X86::ZMM0 + (immediate >> 4)));
    return;
  case TYPE_REL8:
    isBranch = true;
    pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
    // fall through to sign extend the immediate if needed.
  case TYPE_MOFFS8:
    if(immediate & 0x80)
      immediate |= ~(0xffull);
    break;
  case TYPE_MOFFS16:
    if(immediate & 0x8000)
      immediate |= ~(0xffffull);
    break;
  case TYPE_REL32:
  case TYPE_REL64:
    isBranch = true;
    pcrel = insn.startLocation + insn.immediateOffset + insn.immediateSize;
    // fall through to sign extend the immediate if needed.
  case TYPE_MOFFS32:
    if(immediate & 0x80000000)
      immediate |= ~(0xffffffffull);
    break;
  case TYPE_MOFFS64:
  default:
    // operand is 64 bits wide.  Do nothing.
    break;
  }

  if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLocation,
                               insn.immediateOffset, insn.immediateSize,
                               mcInst, Dis))
    mcInst.addOperand(MCOperand::CreateImm(immediate));
}

/// translateRMRegister - Translates a register stored in the R/M field of the
///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
/// @param mcInst       - The MCInst to append to.
/// @param insn         - The internal instruction to extract the R/M field
///                       from.
/// @return             - 0 on success; -1 otherwise
static bool translateRMRegister(MCInst &mcInst,
                                InternalInstruction &insn) {
  if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
    debug("A R/M register operand may not have a SIB byte");
    return true;
  }

  switch (insn.eaBase) {
  default:
    debug("Unexpected EA base register");
    return true;
  case EA_BASE_NONE:
    debug("EA_BASE_NONE for ModR/M base");
    return true;
#define ENTRY(x) case EA_BASE_##x:
  ALL_EA_BASES
#undef ENTRY
    debug("A R/M register operand may not have a base; "
          "the operand must be a register.");
    return true;
#define ENTRY(x)                                                      \
  case EA_REG_##x:                                                    \
    mcInst.addOperand(MCOperand::CreateReg(X86::x)); break;
  ALL_REGS
#undef ENTRY
  }

  return false;
}

/// translateRMMemory - Translates a memory operand stored in the Mod and R/M
///   fields of an internal instruction (and possibly its SIB byte) to a memory
///   operand in LLVM's format, and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param insn         - The instruction to extract Mod, R/M, and SIB fields
///                       from.
/// @return             - 0 on success; nonzero otherwise
static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
                              const MCDisassembler *Dis) {
  // Addresses in an MCInst are represented as five operands:
  //   1. basereg       (register)  The R/M base, or (if there is a SIB) the
  //                                SIB base
  //   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified
  //                                scale amount
  //   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
  //                                the index (which is multiplied by the
  //                                scale amount)
  //   4. displacement  (immediate) 0, or the displacement if there is one
  //   5. segmentreg    (register)  x86_registerNONE for now, but could be set
  //                                if we have segment overrides

  MCOperand baseReg;
  MCOperand scaleAmount;
  MCOperand indexReg;
  MCOperand displacement;
  MCOperand segmentReg;
  uint64_t pcrel = 0;

  if (insn.eaBase == EA_BASE_sib || insn.eaBase == EA_BASE_sib64) {
    if (insn.sibBase != SIB_BASE_NONE) {
      switch (insn.sibBase) {
      default:
        debug("Unexpected sibBase");
        return true;
#define ENTRY(x)                                          \
      case SIB_BASE_##x:                                  \
        baseReg = MCOperand::CreateReg(X86::x); break;
      ALL_SIB_BASES
#undef ENTRY
      }
    } else {
      baseReg = MCOperand::CreateReg(0);
    }

    // Check whether we are handling VSIB addressing mode for GATHER.
    // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
    // we should use SIB_INDEX_XMM4|YMM4 for VSIB.
    // I don't see a way to get the correct IndexReg in readSIB:
    //   We can tell whether it is VSIB or SIB after instruction ID is decoded,
    //   but instruction ID may not be decoded yet when calling readSIB.
    uint32_t Opcode = mcInst.getOpcode();
    bool IndexIs128 = (Opcode == X86::VGATHERDPDrm ||
                       Opcode == X86::VGATHERDPDYrm ||
                       Opcode == X86::VGATHERQPDrm ||
                       Opcode == X86::VGATHERDPSrm ||
                       Opcode == X86::VGATHERQPSrm ||
                       Opcode == X86::VPGATHERDQrm ||
                       Opcode == X86::VPGATHERDQYrm ||
                       Opcode == X86::VPGATHERQQrm ||
                       Opcode == X86::VPGATHERDDrm ||
                       Opcode == X86::VPGATHERQDrm);
    bool IndexIs256 = (Opcode == X86::VGATHERQPDYrm ||
                       Opcode == X86::VGATHERDPSYrm ||
                       Opcode == X86::VGATHERQPSYrm ||
                       Opcode == X86::VPGATHERQQYrm ||
                       Opcode == X86::VPGATHERDDYrm ||
                       Opcode == X86::VPGATHERQDYrm);
    if (IndexIs128 || IndexIs256) {
      unsigned IndexOffset = insn.sibIndex -
                         (insn.addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
      SIBIndex IndexBase = IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;
      insn.sibIndex = (SIBIndex)(IndexBase +
                           (insn.sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
    }

    if (insn.sibIndex != SIB_INDEX_NONE) {
      switch (insn.sibIndex) {
      default:
        debug("Unexpected sibIndex");
        return true;
#define ENTRY(x)                                          \
      case SIB_INDEX_##x:                                 \
        indexReg = MCOperand::CreateReg(X86::x); break;
      EA_BASES_32BIT
      EA_BASES_64BIT
      REGS_XMM
      REGS_YMM
      REGS_ZMM
#undef ENTRY
      }
    } else {
      indexReg = MCOperand::CreateReg(0);
    }

    scaleAmount = MCOperand::CreateImm(insn.sibScale);
  } else {
    switch (insn.eaBase) {
    case EA_BASE_NONE:
      if (insn.eaDisplacement == EA_DISP_NONE) {
        debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
        return true;
      }
      if (insn.mode == MODE_64BIT){
        pcrel = insn.startLocation +
                insn.displacementOffset + insn.displacementSize;
        tryAddingPcLoadReferenceComment(insn.startLocation +
                                        insn.displacementOffset,
                                        insn.displacement + pcrel, Dis);
        baseReg = MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
      }
      else
        baseReg = MCOperand::CreateReg(0);

      indexReg = MCOperand::CreateReg(0);
      break;
    case EA_BASE_BX_SI:
      baseReg = MCOperand::CreateReg(X86::BX);
      indexReg = MCOperand::CreateReg(X86::SI);
      break;
    case EA_BASE_BX_DI:
      baseReg = MCOperand::CreateReg(X86::BX);
      indexReg = MCOperand::CreateReg(X86::DI);
      break;
    case EA_BASE_BP_SI:
      baseReg = MCOperand::CreateReg(X86::BP);
      indexReg = MCOperand::CreateReg(X86::SI);
      break;
    case EA_BASE_BP_DI:
      baseReg = MCOperand::CreateReg(X86::BP);
      indexReg = MCOperand::CreateReg(X86::DI);
      break;
    default:
      indexReg = MCOperand::CreateReg(0);
      switch (insn.eaBase) {
      default:
        debug("Unexpected eaBase");
        return true;
        // Here, we will use the fill-ins defined above.  However,
        //   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
        //   sib and sib64 were handled in the top-level if, so they're only
        //   placeholders to keep the compiler happy.
#define ENTRY(x)                                        \
      case EA_BASE_##x:                                 \
        baseReg = MCOperand::CreateReg(X86::x); break;
      ALL_EA_BASES
#undef ENTRY
#define ENTRY(x) case EA_REG_##x:
      ALL_REGS
#undef ENTRY
        debug("A R/M memory operand may not be a register; "
              "the base field must be a base.");
        return true;
      }
    }

    scaleAmount = MCOperand::CreateImm(1);
  }

  displacement = MCOperand::CreateImm(insn.displacement);

  static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
    0,        // SEG_OVERRIDE_NONE
    X86::CS,
    X86::SS,
    X86::DS,
    X86::ES,
    X86::FS,
    X86::GS
  };

  segmentReg = MCOperand::CreateReg(segmentRegnums[insn.segmentOverride]);

  mcInst.addOperand(baseReg);
  mcInst.addOperand(scaleAmount);
  mcInst.addOperand(indexReg);
  if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
                               insn.startLocation, insn.displacementOffset,
                               insn.displacementSize, mcInst, Dis))
    mcInst.addOperand(displacement);
  mcInst.addOperand(segmentReg);
  return false;
}

/// translateRM - Translates an operand stored in the R/M (and possibly SIB)
///   byte of an instruction to LLVM form, and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param operand      - The operand, as stored in the descriptor table.
/// @param insn         - The instruction to extract Mod, R/M, and SIB fields
///                       from.
/// @return             - 0 on success; nonzero otherwise
static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
                        InternalInstruction &insn, const MCDisassembler *Dis) {
  switch (operand.type) {
  default:
    debug("Unexpected type for a R/M operand");
    return true;
  case TYPE_R8:
  case TYPE_R16:
  case TYPE_R32:
  case TYPE_R64:
  case TYPE_Rv:
  case TYPE_MM:
  case TYPE_MM32:
  case TYPE_MM64:
  case TYPE_XMM:
  case TYPE_XMM32:
  case TYPE_XMM64:
  case TYPE_XMM128:
  case TYPE_XMM256:
  case TYPE_XMM512:
  case TYPE_DEBUGREG:
  case TYPE_CONTROLREG:
    return translateRMRegister(mcInst, insn);
  case TYPE_M:
  case TYPE_M8:
  case TYPE_M16:
  case TYPE_M32:
  case TYPE_M64:
  case TYPE_M128:
  case TYPE_M256:
  case TYPE_M512:
  case TYPE_Mv:
  case TYPE_M32FP:
  case TYPE_M64FP:
  case TYPE_M80FP:
  case TYPE_M16INT:
  case TYPE_M32INT:
  case TYPE_M64INT:
  case TYPE_M1616:
  case TYPE_M1632:
  case TYPE_M1664:
  case TYPE_LEA:
    return translateRMMemory(mcInst, insn, Dis);
  }
}

/// translateFPRegister - Translates a stack position on the FPU stack to its
///   LLVM form, and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param stackPos     - The stack position to translate.
/// @return             - 0 on success; nonzero otherwise.
static bool translateFPRegister(MCInst &mcInst,
                               uint8_t stackPos) {
  if (stackPos >= 8) {
    debug("Invalid FP stack position");
    return true;
  }

  mcInst.addOperand(MCOperand::CreateReg(X86::ST0 + stackPos));

  return false;
}

/// translateOperand - Translates an operand stored in an internal instruction
///   to LLVM's format and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param operand      - The operand, as stored in the descriptor table.
/// @param insn         - The internal instruction.
/// @return             - false on success; true otherwise.
static bool translateOperand(MCInst &mcInst, const OperandSpecifier &operand,
                             InternalInstruction &insn,
                             const MCDisassembler *Dis) {
  switch (operand.encoding) {
  default:
    debug("Unhandled operand encoding during translation");
    return true;
  case ENCODING_REG:
    translateRegister(mcInst, insn.reg);
    return false;
  case ENCODING_RM:
    return translateRM(mcInst, operand, insn, Dis);
  case ENCODING_CB:
  case ENCODING_CW:
  case ENCODING_CD:
  case ENCODING_CP:
  case ENCODING_CO:
  case ENCODING_CT:
    debug("Translation of code offsets isn't supported.");
    return true;
  case ENCODING_IB:
  case ENCODING_IW:
  case ENCODING_ID:
  case ENCODING_IO:
  case ENCODING_Iv:
  case ENCODING_Ia:
    translateImmediate(mcInst,
                       insn.immediates[insn.numImmediatesTranslated++],
                       operand,
                       insn,
                       Dis);
    return false;
  case ENCODING_RB:
  case ENCODING_RW:
  case ENCODING_RD:
  case ENCODING_RO:
    translateRegister(mcInst, insn.opcodeRegister);
    return false;
  case ENCODING_I:
    return translateFPRegister(mcInst, insn.opcodeModifier);
  case ENCODING_Rv:
    translateRegister(mcInst, insn.opcodeRegister);
    return false;
  case ENCODING_VVVV:
    translateRegister(mcInst, insn.vvvv);
    return false;
  case ENCODING_DUP:
    return translateOperand(mcInst, insn.operands[operand.type - TYPE_DUP0],
                            insn, Dis);
  }
}

/// translateInstruction - Translates an internal instruction and all its
///   operands to an MCInst.
///
/// @param mcInst       - The MCInst to populate with the instruction's data.
/// @param insn         - The internal instruction.
/// @return             - false on success; true otherwise.
static bool translateInstruction(MCInst &mcInst,
                                InternalInstruction &insn,
                                const MCDisassembler *Dis) {
  if (!insn.spec) {
    debug("Instruction has no specification");
    return true;
  }

  mcInst.setOpcode(insn.instructionID);
  // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
  // prefix bytes should be disassembled as xrelease and xacquire then set the
  // opcode to those instead of the rep and repne opcodes.
  if (insn.xAcquireRelease) {
    if(mcInst.getOpcode() == X86::REP_PREFIX)
      mcInst.setOpcode(X86::XRELEASE_PREFIX);
    else if(mcInst.getOpcode() == X86::REPNE_PREFIX)
      mcInst.setOpcode(X86::XACQUIRE_PREFIX);
  }

  int index;

  insn.numImmediatesTranslated = 0;

  for (index = 0; index < X86_MAX_OPERANDS; ++index) {
    if (insn.operands[index].encoding != ENCODING_NONE) {
      if (translateOperand(mcInst, insn.operands[index], insn, Dis)) {
        return true;
      }
    }
  }

  return false;
}

static MCDisassembler *createX86_32Disassembler(const Target &T,
                                                const MCSubtargetInfo &STI) {
  return new X86Disassembler::X86GenericDisassembler(STI, MODE_32BIT,
                                                     T.createMCInstrInfo());
}

static MCDisassembler *createX86_64Disassembler(const Target &T,
                                                const MCSubtargetInfo &STI) {
  return new X86Disassembler::X86GenericDisassembler(STI, MODE_64BIT,
                                                     T.createMCInstrInfo());
}

extern "C" void LLVMInitializeX86Disassembler() {
  // Register the disassembler.
  TargetRegistry::RegisterMCDisassembler(TheX86_32Target,
                                         createX86_32Disassembler);
  TargetRegistry::RegisterMCDisassembler(TheX86_64Target,
                                         createX86_64Disassembler);
}


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.browser_ui.widget.async_image;

import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Matrix.ScaleToFit;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnAttachStateChangeListener;
import android.view.View.OnLayoutChangeListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;

import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.view.ViewCompat;

/**
 * A helper class to simulate {@link View#getForeground()} on older versions of Android.  This class
 * requires specific setup to work properly.  The following methods must be overridden and forwarded
 * from the underly {@link View}:
 *
 * 1) {@link View#draw(Canvas)}.
 * 2) {@link View#onVisibilityChanged(View,boolean)}
 * 3) {@link View#drawableStateChanged()}.
 * 4) {@link View#verifyDrawable(Drawable)}.
 *
 * Here is a rough example of how to use this below to extend an ImageView (replace with any View):
 *
 * public class ForegroundEnabledView extends ImageView {
 *     private final ForegroundDrawableCompat mCompat;
 *
 *     public class ForegroundEnabledView(Context context) {
 *         super(context);
 *         mCompat = new ForegroundDrawableCompat(this);
 *     }
 *
 *     public void someHelperMethod(Drawable drawable) {
 *         mCompat.setDrawable(drawable);
 *     }
 *
 *     // ImageView implementation.
 *     @Override
 *     public void draw(Canvas canvas) {
 *         super.draw(canvas);
 *
 *         // It is important to make sure the foreground drawable draws *after* other view content.
 *         mCompat.draw(canvas);
 *     }
 *
 *     @Override
 *     protected void onVisibilityChanged(View changedView, int visibility) {
 *         super.onVisibilityChanged(changedView, visibility);
 *         mCompat.onVisibilityChanged(changedView, visibility);
 *     }
 *
 *     @Override
 *     protected void drawableStateChanged() {
 *         super.drawableStateChanged();
 *         mCompat.drawableStateChanged();
 *     }
 *
 *     @Override
 *     protected boolean verifyDrawable(Drawable dr) {
 *         return super.verifyDrawable(dr) || mCompat.verifyDrawable(dr);
 *     }
 * }
 */
public class ForegroundDrawableCompat
        implements OnAttachStateChangeListener, OnLayoutChangeListener {
    private final RectF mTempSrc = new RectF();
    private final RectF mTempDst = new RectF();
    private final Matrix mDrawMatrix = new Matrix();

    private final View mView;

    private boolean mOnBoundsChanged;
    private Drawable mDrawable;

    private ImageView.ScaleType mScaleType = ImageView.ScaleType.FIT_CENTER;

    /**
     * Builds a {@link ForegroundDrawableCompat} around {@code View}.  This will enable setting a
     * {@link Drawable} to draw on top of {@link View} at draw time.
     * @param view The {@link View} to add foreground {@link Drawable} support to.
     */
    public ForegroundDrawableCompat(View view) {
        mView = view;
        mView.addOnAttachStateChangeListener(this);
        mView.addOnLayoutChangeListener(this);
    }

    /**
     * Sets {@code drawable} to draw on top of the {@link View}.
     * @param drawable The {@link Drawable} to set as a foreground {@link Drawable} on the
     *                 {@link View}.
     */
    public void setDrawable(Drawable drawable) {
        if (mDrawable == drawable) return;

        if (mDrawable != null) {
            if (ViewCompat.isAttachedToWindow(mView)) mDrawable.setVisible(false, false);
            mDrawable.setCallback(null);
            mView.unscheduleDrawable(mDrawable);
            mDrawable = null;
        }

        mDrawable = drawable;

        if (mDrawable != null) {
            mOnBoundsChanged = true;

            DrawableCompat.setLayoutDirection(mDrawable, ViewCompat.getLayoutDirection(mView));
            if (mDrawable.isStateful()) mDrawable.setState(mView.getDrawableState());

            // TODO(dtrainor): Support tint?

            if (ViewCompat.isAttachedToWindow(mView)) {
                mDrawable.setVisible(
                        mView.getWindowVisibility() == View.VISIBLE && mView.isShown(), false);
            }
            mDrawable.setCallback(mView);
        }
        mView.requestLayout();
        mView.invalidate();
    }

    /** @return The currently set foreground {@link Drawable}. */
    public Drawable getDrawable() {
        return mDrawable;
    }

    /**
     * Determines how the foreground {@code Drawable} will be drawn in front of the {@link View}.
     * Right now the only supported types are FIT_* types and the CENTER type.
     *
     * TODO(dtrainor): Add support for more scale types.
     *
     * @param type The type of scale to apply to the {@Drawable} (see {@link ImageView.ScaleType}).
     */
    public void setScaleType(ImageView.ScaleType type) {
        if (mScaleType == type) return;
        mScaleType = type;
        mOnBoundsChanged = true;

        if (mDrawable != null) mView.invalidate();
    }

    /** Meant to be called from {@link View#onDraw(Canvas)}. */
    public void draw(Canvas canvas) {
        if (mDrawable == null) return;

        computeBounds();

        if (mDrawMatrix.isIdentity()) {
            mDrawable.draw(canvas);
        } else {
            final int saveCount = canvas.getSaveCount();
            canvas.save();
            canvas.concat(mDrawMatrix);
            mDrawable.draw(canvas);
            canvas.restoreToCount(saveCount);
        }
    }

    /** Meant to be called from {@link View#onVisibilityChanged(View,visibility)}. */
    public void onVisibilityChanged(View view, int visibility) {
        if (mView != view || mDrawable == null) return;

        ViewParent parent = mView.getParent();
        boolean parentVisible = parent != null
                && (!(parent instanceof ViewGroup) || ((ViewGroup) parent).isShown());

        if (parentVisible && mView.getWindowVisibility() == View.VISIBLE) {
            mDrawable.setVisible(visibility == View.VISIBLE, false);
        }
    }

    /** Meant to be called from {@link View#drawableStateChanged()}. */
    public void drawableStateChanged() {
        if (mDrawable == null) return;
        if (mDrawable.setState(mView.getDrawableState())) mView.invalidate();
    }

    /** Meant to be called from {@link View#verifyDrawable(Drawable)}. */
    public boolean verifyDrawable(Drawable drawable) {
        return drawable != null && mDrawable == drawable;
    }

    // OnAttachStateChangeListener implementation.
    @Override
    public void onViewAttachedToWindow(View v) {
        if (mDrawable == null) return;
        if (mView.isShown() && mView.getWindowVisibility() != View.GONE) {
            mDrawable.setVisible(mView.getVisibility() == View.VISIBLE, false);
        }
    }

    @Override
    public void onViewDetachedFromWindow(View v) {
        if (mDrawable == null) return;
        if (mView.isShown() && mView.getWindowVisibility() != View.GONE) {
            mDrawable.setVisible(false, false);
        }
    }

    // OnLayoutChangeListener implementation.
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
            int oldTop, int oldRight, int oldBottom) {
        if (mDrawable == null) return;

        int width = right - left;
        int height = bottom - top;

        if (width != mDrawable.getBounds().width() || height != mDrawable.getBounds().height()) {
            mOnBoundsChanged = true;
        }
    }

    private void computeBounds() {
        if (mDrawable == null || !mOnBoundsChanged) return;

        mDrawMatrix.reset();

        int drawableWidth = mDrawable.getIntrinsicWidth();
        int drawableHeight = mDrawable.getIntrinsicHeight();

        int viewWidth = mView.getWidth();
        int viewHeight = mView.getHeight();

        mTempSrc.set(0, 0, drawableWidth, drawableHeight);
        mTempDst.set(0, 0, viewWidth, viewHeight);

        if (mScaleType == ImageView.ScaleType.FIT_START) {
            mDrawMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.START);
            mDrawable.setBounds(0, 0, drawableWidth, drawableHeight);
        } else if (mScaleType == ImageView.ScaleType.FIT_CENTER) {
            mDrawMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.CENTER);
            mDrawable.setBounds(0, 0, drawableWidth, drawableHeight);
        } else if (mScaleType == ImageView.ScaleType.FIT_END) {
            mDrawMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.END);
            mDrawable.setBounds(0, 0, drawableWidth, drawableHeight);
        } else if (mScaleType == ImageView.ScaleType.CENTER) {
            mDrawMatrix.setTranslate(Math.round((viewWidth - drawableWidth) * 0.5f),
                    Math.round((viewHeight - drawableHeight) * 0.5f));
            mDrawable.setBounds(0, 0, drawableWidth, drawableHeight);
        } else {
            mDrawable.setBounds(0, 0, viewWidth, viewHeight);
        }

        mOnBoundsChanged = false;
    }
}


text: Integration with Symantec Endpoint Protection Manager using the SEPM REST API.