text:
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using RoonApiLib.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RoonApiLib
{
    public class RoonApi : BindableBase
    {
        public const string ServiceRegistry     = "com.roonlabs.registry:1";
        public const string ServiceTransport    = "com.roonlabs.transport:1";
        public const string ServiceStatus       = "com.roonlabs.status:1";
        public const string ServicePairing      = "com.roonlabs.pairing:1";
        public const string ServicePing         = "com.roonlabs.ping:1";
        public const string ServiceImage        = "com.roonlabs.image:1";
        public const string ServiceBrowse       = "com.roonlabs.browse:1";
        public const string ServiceSettings     = "com.roonlabs.settings:1";
        public const string ControlVolume       = "com.roonlabs.volumecontrol:1";
        public const string ControlSource       = "com.roonlabs.sourcecontrol:1";

        public const string MessageRequest      = "REQUEST";
        public const string MessageComplete     = "COMPLETE";
        public const string MessageContinue     = "CONTINUE";

        public class RoonRequest
        {
            public RoonRequest()
            {
                OnReceived = null;
                Event = new TaskCompletionSource<bool>();
                StringResult = null;
                DataResult = null;
                StartTime = DateTime.UtcNow;
            }
            public RoonRequest(OnRoonReceived onReceived)
            {
                OnReceived = onReceived;
                Event = null;
                StringResult = null;
                DataResult = null;
                StartTime = DateTime.UtcNow;
            }
            public OnRoonReceived OnReceived;
            public TaskCompletionSource<bool> Event;
            public string StringResult;
            public byte[] DataResult;
            public DateTime StartTime;
        }
        public class RoonReply
        {
            [JsonProperty("core_id")]
            public string CoreId { get; set; }
            [JsonProperty("display_name")]
            public string DisplayName { get; set; }
            [JsonProperty("display_version")]
            public string DisplayVersion { get; set; }
        }
        public class RoonRegisterReply : RoonReply
        {
            [JsonProperty("token")]
            public string Token { get; set; }
            [JsonProperty("provided_services")]
            public string[] ProvidedServices { get; set; }
            [JsonProperty("http_port")]
            public string HttpPort { get; set; }
        }
        public class RoonRegister
        {
            [JsonProperty("extension_id")]
            public string ExtensionId { get; set; }
            [JsonProperty("display_name")]
            public string DisplayName { get; set; }
            [JsonProperty("display_version")]
            public string DisplayVersion { get; set; }
            [JsonProperty("publisher")]
            public string Publisher { get; set; }
            [JsonProperty("email")]
            public string Email { get; set; }
            [JsonProperty("required_services")]
            public string[] RequiredServices { get; set; }
            [JsonProperty("optional_services")]
            public string[] OptionalServices { get; set; }
            [JsonProperty("provided_services")]
            public string[] ProvidedServices { get; set; }
            [JsonProperty("token")]
            public string Token { get; set; }
            [JsonProperty("website")]
            public string WebSite { get; set; }
        }
        public class RoonState
        {
            public RoonState()
            {
                Tokens = new Dictionary<string, string>();
            }
            [JsonProperty("tokens")]
            public Dictionary<string, string> Tokens;
            [JsonProperty("paired_core_id")]
            public string PairedCoreId { get; set; }
        }
        public class RoonPaired
        {
            [JsonProperty("paired_core_id")]
            public string PairedCoreId { get; set; }
        }
        public class RoonSavings
        {
            public RoonSavings()
            {
                RoonState = new RoonState();
            }
            [JsonProperty("roonstate")]
            public RoonState RoonState { get; set; }
        }

        public delegate Task<bool> OnRoonReceived(string information, int requestId, string body);

        ClientWebSocket                     _webSocket;
        CancellationTokenSource             _cancellationTokenSource;
        int                                 _requestId;
        string                              _configPath;
        Dictionary<int, RoonRequest>        _requests;
        ILogger                             _logger;
        JsonSerializerSettings              _jsonSettings;
        RoonSavings                         _savings;
        string                              _coreId;
        bool                                _paired;
        AsyncLock                           _lock;
        Dictionary<string, object>          _configuration;
        Dictionary<string, OnRoonReceived>  _services;
        Dictionary<int, OnRoonReceived>     _subscriptions;
        public Func<string, Task>           _onPaired;
        public Func<string, Task>           _onUnPaired;
        RoonApiSubscriptionHandler          _subscriptionHandler;
        int                                 _receiveCount;
        RoonRegister                        _registration;
        Action                              _onRegistration;

        class ReceivedContent
        {
            public int ContentLength;
            public string ContentType;
            public string MessageType;
            public string Information;
            public string Body;
            public byte[] Data;
        }

        public RoonApi(Func<string, Task> onPaired, Func<string, Task> onUnPaired, string configPath = "C:\\Temp\\", ILogger logger = null)
        {
            _onPaired = onPaired;
            _onUnPaired = onUnPaired;
            _logger = logger == null ? NullLogger.Instance : logger;
            _requestId = 0;
            if (!configPath.EndsWith("\\"))
            {
                configPath += "\\";
            }
            _configPath = configPath;
            _coreId = null;
            _requests = new Dictionary<int, RoonRequest>();
            _jsonSettings = new JsonSerializerSettings();
            _jsonSettings.NullValueHandling = NullValueHandling.Ignore;
            _lock = new AsyncLock();
            _services = new Dictionary<string, OnRoonReceived>();
            _subscriptions = new Dictionary<int, OnRoonReceived>();
            _subscriptionHandler = new RoonApiSubscriptionHandler();
            _configuration = new Dictionary<string, object>();

            _savings = LoadRoonSettings();
        }
        public ILogger Logger { get => _logger; }
        public bool Paired
        {
            get => _paired;
            set => SetProperty(ref _paired, value);
        }
        internal void AddService (string service, OnRoonReceived handler)
        {
            _services.Add(service, handler);
        }
        internal void AddSubscription(int requestId, OnRoonReceived handler)
        {
            _subscriptions.Add(requestId, handler);
        }
        public void StartReceiver (string ip, int port, RoonRegister roonRegister, Action onRegistration = null)
        {
            string uri = $"ws://{ip}:{port}/api";
            _registration = roonRegister;
            _onRegistration = onRegistration;
            Task.Run(async() => await ReceiveLoop(uri));
        }
        public async Task ReceiveLoop (string uri)
        {
            do
            {
                try
                {
                    _receiveCount = 0;
                    _logger.LogInformation($"Start Receiving at '{uri}'");
                    var webSocket = new ClientWebSocket();
                    _cancellationTokenSource = new CancellationTokenSource();
                    await webSocket.ConnectAsync(new Uri(uri), _cancellationTokenSource.Token);
                    _webSocket = webSocket;     // For the senders
                    await Receive();
                    _webSocket = null;
                    webSocket.Dispose();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"ReceiveLoop error {ex.Message}, {_receiveCount} received");
                }
                if (_receiveCount > 10)
                    await Task.Delay(1000);
                else
                    await Task.Delay(60000);
                _requests.Clear();
            } while (!_cancellationTokenSource.IsCancellationRequested);
            _logger.LogError("ReceiveLoop exit");
        }

        public async Task<RoonReply> GetRegistryInfo ()
        {
            var info = await SendReceive<RoonReply>(ServiceRegistry + "/info");
            _coreId = info.CoreId;
            return info;
        }
        public async Task<bool> GetRegistryInfo (Action<RoonReply> action)
        {
            RoonRequest request = new RoonRequest((info, id, body) =>
            {
                RoonReply reply = JsonConvert.DeserializeObject<RoonReply>(body);
                action(reply);
                return Task.FromResult(true);
            });
            int requestId = _requestId++;
            _requests.Add(requestId, request);
            return await Send(ServiceRegistry + "/info", requestId);
        }
        public async Task<bool> RegisterService(RoonRegister service)
        {
            string token;

            _savings.RoonState.Tokens.TryGetValue(_coreId, out token);
            service.Token = token;
            string bodyString = JsonConvert.SerializeObject(service, _jsonSettings);
            int requestId = _requestId++;
            AddSubscription(requestId, OnRegistrationReceived);
            bool rc = await Send(ServiceRegistry + "/register", requestId, bodyString);
            return rc;
        }
        internal Task<bool> OnRegistrationReceived (string information, int requestId, string body)
        {
            switch (information)
            {
                case "Registered":
                    string token;
                    _savings.RoonState.Tokens.TryGetValue(_coreId, out token);
                    RoonRegisterReply registration = JsonConvert.DeserializeObject<RoonRegisterReply>(body);
                    _logger.LogInformation($"Registration done {registration.DisplayName}");
                    if (registration.Token != null && (token == null || token != registration.Token))
                    {
                        if (token != null)
                            _savings.RoonState.Tokens[_coreId] = registration.Token;
                        else
                            _savings.RoonState.Tokens.Add(_coreId, registration.Token);
                        SaveRoonSettings(_savings);
                    }
                    if (_onRegistration != null)
                        _onRegistration();
                    break;
            }
            return Task.FromResult(true);
        }
        internal async Task<int> SendSubscription (string command, int subscriptionKey)
        {
            string bodyString = JsonConvert.SerializeObject(new RoonApiSubscriptionHandler.Subscription { SubscriptionKey = subscriptionKey  }, _jsonSettings);
            int requestId = _requestId++;
            bool rc = await Send(command, requestId, bodyString);
            return rc ? requestId : -1;

        }
        internal async Task<RESULT> SendReceive<RESULT,REQUEST>(string command, REQUEST body)
        {
            string bodyString = JsonConvert.SerializeObject(body, _jsonSettings);
            return await SendReceive<RESULT>(command, bodyString);
        }
        internal async Task<RESULT> SendReceive<RESULT> (string command, string body = null, string contentType = "application/json")
        {
            RoonRequest request = new RoonRequest();
            int requestId = _requestId++;
            _requests.Add(requestId, request);

            bool rc = await Send(command, requestId, body, contentType);

            await request.Event.Task;
            RESULT obj = default(RESULT);
            if (typeof(RESULT) == typeof(byte[]))
            {
                obj = (RESULT)(object)request.DataResult;
            }
            else if (typeof(RESULT) == typeof(bool))
            {
                obj = (RESULT)(object)rc;
            }
            else
            {
                string str = request.StringResult;
                obj = JsonConvert.DeserializeObject<RESULT>(str);
            }
            _requests.Remove(requestId);
            return obj;
        }
        async Task<bool> Send(string command, int requestId, string body = null, string contentType = "application/json")
        {
            using (var release = await _lock.LockAsync())
            {
                try
                {
                    string send;
                    if (body == null)
                        send = $"MOO/1 REQUEST {command}\nRequest-Id: {requestId}\n\n";
                    else
                        send = $"MOO/1 REQUEST {command}\nRequest-Id: {requestId}\nContent-Length: {body.Length}\nContent-Type: {contentType}\n\n" + body;

                    _logger.LogTrace(send);

                    return await SendData(send);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Send error {ex.Message} at {command}");
                    return false;
                }
            }
        }
        public async Task<bool> Reply(string command, int requestId, bool cont = false, string body = null, bool silent = false, string contentType = "application/json")
        {
            using (var release = await _lock.LockAsync())
            {
                try
                {
                    string send;
                    if (body == null)
                        send = $"MOO/1 {(cont ? "CONTINUE" : "COMPLETE")} {command}\nRequest-Id: {requestId}\n\n";
                    else
                        send = $"MOO/1 {(cont ? "CONTINUE" : "COMPLETE")} {command}\nRequest-Id: {requestId}\nContent-Length: {body.Length}\nContent-Type: {contentType}\n\n" + body;

                    if (!silent)
                        _logger.LogTrace(send);

                    return await SendData(send);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Reply error {ex.Message} at {command}");
                    return false;
                }
            }
        }
        private async Task<bool> SendData (string data, int timeout = 120000)
        {
            for (int i = 0; i < timeout; i++)
            {
                if (_webSocket != null)
                {
                    ArraySegment<byte> dataSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(data));
                    await _webSocket.SendAsync(dataSend, WebSocketMessageType.Binary, true, _cancellationTokenSource.Token);
                    return true;
                }
                await Task.Delay(100);
            }
            _logger.LogError("Wait for socket timed out");
            return false;
        }
        async Task ParseResult(byte[] data, int byteCount, ReceivedContent content,  Dictionary<string, string> headerDict)
        {
            content.Body = null;
            content.Data = null;
            content.ContentLength = 0;
            content.ContentType = null;

            int index = ParseHeader(data, out content.MessageType, out content.Information, headerDict);
            string help;

            if (headerDict.TryGetValue("Content-Length", out help))
            {
                content.ContentLength = Int32.Parse(help);
                int copiedLength = 0;
                int dataLength = byteCount - index;
                byte[] buffer = new byte[content.ContentLength];
                Array.Copy(data, index, buffer, copiedLength, dataLength);
                copiedLength += dataLength;
                while (copiedLength < content.ContentLength)
                {
                    ArraySegment<byte> dataRecv = new ArraySegment<byte>(data);
                    var result = await _webSocket.ReceiveAsync(dataRecv, _cancellationTokenSource.Token);
                    Array.Copy(data, 0, buffer, copiedLength, result.Count);
                    copiedLength += result.Count;
                }
                content.Data = buffer;
                if (headerDict.TryGetValue("Content-Type", out content.ContentType) && content.ContentType.StartsWith ("image"))
                {
                    _logger.LogTrace($"{content.MessageType} {content.Information} : image[{content.ContentLength}]");
                }
                else
                {
                    content.Body = Encoding.UTF8.GetString(buffer);
                    _logger.LogTrace($"{content.MessageType} {content.Information} [{content.ContentLength}]: {content.Body}");
                }
            }
            else
            {
                if (!content.Information.Contains ("ping"))
                _logger.LogTrace($"{content.MessageType} {content.Information}");
            }
        }
        int ParseHeader (byte[]data, out string messageType, out string information, Dictionary<string, string> headerDict)
        {
            int end, start;
            string line1 = null;
            messageType = information = null;
            for (end = start = 0; end < data.Length; end++)
            {
                if (data[end] == 0xa)
                {
                    int count = end - start;
                    if (count == 0)     // \n\n detected
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(data, start, count);
                    if (line1 == null)
                        line1 = str;
                    else
                    {
                        string[] header = str.Split(new char[] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        if (header.Length >= 2)
                            headerDict.Add(header[0], header[1]);
                    }
                    start = end + 1;
                }
            }
            string[] split = line1.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (split.Length > 1)
                messageType = split[1];
            if (split.Length > 2)
                information = split[2];
            return end + 1;
        }
        public async Task Receive ()
        {
            Dictionary<string, string> headerDict = new Dictionary<string, string>();
            ReceivedContent content = new ReceivedContent();
            byte[] buffer = new byte[10000];
            int requestId = 0;
            bool rc;

            _coreId = null;
            rc = await GetRegistryInfo(async (reply) =>
            {
                _logger.LogInformation($"Registry Info {reply.DisplayName} ID {reply.CoreId}");
                _coreId = reply.CoreId;
                rc = await RegisterService(_registration);
            });
            while (!_cancellationTokenSource.Token.IsCancellationRequested)
            {
                try
                {
                    // Initialisation
                    ArraySegment<byte> dataRecv = new ArraySegment<byte>(buffer);
                    var result = await _webSocket.ReceiveAsync(dataRecv, _cancellationTokenSource.Token);
                    headerDict.Clear();
                    await ParseResult (dataRecv.Array, result.Count, content, headerDict);
                    string requestIdString;
                    if (headerDict.TryGetValue("Request-Id", out requestIdString))
                    {
                        Int32.TryParse(requestIdString, out requestId);
                    }
                    switch (content.MessageType)
                    {
                        case MessageRequest:
                            string replyBody;
                            switch (content.Information)
                            {
                                case ServicePing + "/ping":
                                    rc = await Reply("Success", requestId, false, null, true);
                                    break;
                                case ServicePairing + "/subscribe_pairing":
                                    _subscriptionHandler.AddSubscription(content.Body, requestId);
                                    replyBody = JsonConvert.SerializeObject(new RoonPaired { PairedCoreId = _coreId });
                                    rc = await Reply("Subscribed", requestId, false, replyBody);
                                    _savings.RoonState.PairedCoreId = _coreId;
                                    SaveRoonSettings(_savings);
                                    Paired = true;
                                    if (_onPaired != null)
                                        await _onPaired(_coreId);
                                    break;
                                case ServicePairing + "/unsubscribe_pairing":
                                    _subscriptionHandler.RemoveSubscription(content.Body);
                                    rc = await Reply("Unsubscribed", requestId);
                                    _savings.RoonState.PairedCoreId = string.Empty;
                                    SaveRoonSettings(_savings);
                                    Paired = false;
                                    if (_onUnPaired != null)
                                        await _onUnPaired(_coreId);
                                    break;
                                default:
                                    int idx = content.Information.IndexOf('/');
                                    if (idx > 0)
                                    {
                                        string service = content.Information.Substring(0, idx);
                                        OnRoonReceived onRequestReceived;
                                        if (_services.TryGetValue(service, out onRequestReceived))
                                        {
                                            rc = await onRequestReceived(content.Information, requestId, content.Body);
                                            break;
                                        }
                                    }
                                    _logger.LogError($"REQUEST {content.Information}");
                                    break;
                            }
                            break;
                        case MessageComplete:
                            RoonRequest request;
                            if (_requests.TryGetValue(requestId, out request))
                            {
                                if (request.OnReceived != null)
                                {
                                    _requests.Remove(requestId);
                                    await request.OnReceived(content.Information, requestId, content.Body);
                                }
                                else
                                {
                                    request.StringResult = content.Body;
                                    request.DataResult = content.Data;
                                    request.Event.SetResult(true);
                                }
                            }
                            else
                                _logger.LogError($"COMPLETE {content.Information}");
                            break;
                        case MessageContinue:
                            OnRoonReceived onContinueReceived;
                            if (_subscriptions.TryGetValue(requestId, out onContinueReceived))
                            {
                                rc = await onContinueReceived(content.Information, requestId, content.Body);
                                break;
                            }
                            else
                                _logger.LogError($"CONTINUE {content.Information}");

                            break;
                    }
                    _receiveCount++;
                }
                catch (TaskCanceledException)
                {
                    _logger.LogTrace("Receive Cancelled");
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Receive error {ex.Message}");
                    break;
                }
            }
            _logger.LogInformation($"Stop Receiving, {_receiveCount} received");
        }
        public void Close()
        {
            if (_webSocket == null)
                return;
            try
            {
                _logger.LogTrace("Closing");
                //await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Shutdown", CancellationToken.None);
                _cancellationTokenSource.Cancel();
                _requests.Clear();
                _webSocket.Dispose();
                _logger.LogTrace("Closed");
            }
            catch (Exception ex)
            {
                _logger.LogError($"Close Error {ex.Message}");
            }
        }
        public void SaveRoonSettings (RoonSavings settings)
        {
            SaveConfig(typeof(RoonSavings).Name, settings);
        }
        public RoonSavings LoadRoonSettings ()
        {
            RoonSavings settings = LoadConfig<RoonSavings>(typeof(RoonSavings).Name);
            if (settings == null)
                settings = new RoonSavings();
            return settings;
        }
        public object LoadConfig (string key)
        {
            object config;
            if (_configuration.Count == 0)
            {
                if (!LoadConfiguration())
                    return null;
            }
            _configuration.TryGetValue(key, out config);
            return config;
        }
        public T LoadConfig<T> (string key)
        {
            object config = LoadConfig(key);
            if (config == null)
                return default(T);
            if (config.GetType() == typeof(T))
                return (T)config;
            string str = JsonConvert.SerializeObject(config);
            T result = JsonConvert.DeserializeObject<T>(str);
            _configuration[key] = result;
            return result;
        }
        public void SaveConfig<T> (string key, T config)
        {
            lock (this)
            {
                object oldConfig;
                if (_configuration.TryGetValue(key, out oldConfig))
                    _configuration[key] = config;
                else
                    _configuration.Add(key, config);
            }
            SaveConfiguration();
        }
        bool LoadConfiguration()
        {
            lock (this)
            {
                try
                {
                    string str = File.ReadAllText(_configPath + "Configuration.json");
                    _logger.LogTrace($"LoadConfiguration : {str}");
                    _configuration = JsonConvert.DeserializeObject<Dictionary<string, object>>(str);
                    return true;
                }
                catch (Exception ex)
                {
                    _logger.LogError($"LoadRoonSettings : Error {ex.Message}");
                    _configuration = new Dictionary<string, object>();
                    return false;
                }
            }
        }
        void SaveConfiguration()
        {
            lock (this)
            {
                string str = JsonConvert.SerializeObject(_configuration);
                _logger.LogTrace($"SaveConfiguration : {str}");
                File.WriteAllText(_configPath + "Configuration.json", str);
            }
        }
    }
}


text:
#include "clar_libgit2.h"
#include "git2/refdb.h"
#include "refdb.h"

static git_repository *g_repo;
static int g_expected = 0;

#ifdef GIT_WIN32
static bool concurrent_compress = false;
#else
static bool concurrent_compress = true;
#endif

void test_threads_refdb__initialize(void)
{
	g_repo = NULL;
}

void test_threads_refdb__cleanup(void)
{
	cl_git_sandbox_cleanup();
	g_repo = NULL;
}

#define REPEAT 20
#define THREADS 20
/* Number of references to create or delete in each thread */
#define NREFS 10

struct th_data {
	cl_git_thread_err error;
	int id;
	const char *path;
};

static void *iterate_refs(void *arg)
{
	struct th_data *data = (struct th_data *) arg;
	git_reference_iterator *i;
	git_reference *ref;
	int count = 0, error;
	git_repository *repo;

	cl_git_thread_pass(data, git_repository_open(&repo, data->path));
	do {
		error = git_reference_iterator_new(&i, repo);
	} while (error == GIT_ELOCKED);
	cl_git_thread_pass(data, error);

	for (count = 0; !git_reference_next(&ref, i); ++count) {
		cl_assert(ref != NULL);
		git_reference_free(ref);
	}

	if (g_expected > 0)
		cl_assert_equal_i(g_expected, count);

	git_reference_iterator_free(i);

	git_repository_free(repo);
	git_error_clear();
	return arg;
}

static void *create_refs(void *arg)
{
	int i, error;
	struct th_data *data = (struct th_data *) arg;
	git_oid head;
	char name[128];
	git_reference *ref[NREFS];
	git_repository *repo;

	cl_git_thread_pass(data, git_repository_open(&repo, data->path));

	do {
		error = git_reference_name_to_id(&head, repo, "HEAD");
	} while (error == GIT_ELOCKED);
	cl_git_thread_pass(data, error);

	for (i = 0; i < NREFS; ++i) {
		p_snprintf(name, sizeof(name), "refs/heads/thread-%03d-%02d", data->id, i);
		do {
			error = git_reference_create(&ref[i], repo, name, &head, 0, NULL);
		} while (error == GIT_ELOCKED);
		cl_git_thread_pass(data, error);

		if (concurrent_compress && i == NREFS/2) {
			git_refdb *refdb;
			cl_git_thread_pass(data, git_repository_refdb(&refdb, repo));
			do {
				error = git_refdb_compress(refdb);
			} while (error == GIT_ELOCKED);
			cl_git_thread_pass(data, error);
			git_refdb_free(refdb);
		}
	}

	for (i = 0; i < NREFS; ++i)
		git_reference_free(ref[i]);

	git_repository_free(repo);

	git_error_clear();
	return arg;
}

static void *delete_refs(void *arg)
{
	int i, error;
	struct th_data *data = (struct th_data *) arg;
	git_reference *ref;
	char name[128];
	git_repository *repo;

	cl_git_thread_pass(data, git_repository_open(&repo, data->path));

	for (i = 0; i < NREFS; ++i) {
		p_snprintf(
			name, sizeof(name), "refs/heads/thread-%03d-%02d", (data->id) & ~0x3, i);

		if (!git_reference_lookup(&ref, repo, name)) {
			do {
				error = git_reference_delete(ref);
			} while (error == GIT_ELOCKED);
			/* Sometimes we race with other deleter threads */
			if (error == GIT_ENOTFOUND)
				error = 0;

			cl_git_thread_pass(data, error);
			git_reference_free(ref);
		}

		if (concurrent_compress && i == NREFS/2) {
			git_refdb *refdb;
			cl_git_thread_pass(data, git_repository_refdb(&refdb, repo));
			do {
				error = git_refdb_compress(refdb);
			} while (error == GIT_ELOCKED);
			cl_git_thread_pass(data, error);
			git_refdb_free(refdb);
		}
	}

	git_repository_free(repo);
	git_error_clear();
	return arg;
}

void test_threads_refdb__edit_while_iterate(void)
{
	int r, t;
	struct th_data th_data[THREADS];
	git_oid head;
	git_reference *ref;
	char name[128];
	git_refdb *refdb;

#ifdef GIT_THREADS
	git_thread th[THREADS];
#endif

	g_repo = cl_git_sandbox_init("testrepo2");

	cl_git_pass(git_reference_name_to_id(&head, g_repo, "HEAD"));

	/* make a bunch of references */

	for (r = 0; r < 50; ++r) {
		p_snprintf(name, sizeof(name), "refs/heads/starter-%03d", r);
		cl_git_pass(git_reference_create(&ref, g_repo, name, &head, 0, NULL));
		git_reference_free(ref);
	}

	cl_git_pass(git_repository_refdb(&refdb, g_repo));
	cl_git_pass(git_refdb_compress(refdb));
	git_refdb_free(refdb);

	g_expected = -1;

	g_repo = cl_git_sandbox_reopen(); /* reopen to flush caches */

	for (t = 0; t < THREADS; ++t) {
		void *(*fn)(void *arg);

		switch (t & 0x3) {
		case 0:  fn = create_refs;  break;
		case 1:  fn = delete_refs;  break;
		default: fn = iterate_refs; break;
		}

		th_data[t].id = t;
		th_data[t].path = git_repository_path(g_repo);

#ifdef GIT_THREADS
		cl_git_pass(git_thread_create(&th[t], fn, &th_data[t]));
#else
		fn(&th_data[t]);
#endif
	}

#ifdef GIT_THREADS
	for (t = 0; t < THREADS; ++t) {
		cl_git_pass(git_thread_join(&th[t], NULL));
		cl_git_thread_check(&th_data[t]);
	}

	memset(th, 0, sizeof(th));

	for (t = 0; t < THREADS; ++t) {
		th_data[t].id = t;
		cl_git_pass(git_thread_create(&th[t], iterate_refs, &th_data[t]));
	}

	for (t = 0; t < THREADS; ++t) {
		cl_git_pass(git_thread_join(&th[t], NULL));
		cl_git_thread_check(&th_data[t]);
	}
#endif
}

redpajama_set_name: RedPajamaGithub


text:
apt_update 'update' if platform_family?('debian')

# install the old gems to make sure the uninstall works
chef_gem 'di-ruby-lvm' do
  compile_time true
end

chef_gem 'di-ruby-lvm-attrib' do
  compile_time true
end

include_recipe 'lvm'

# The test device to use
devices = [
  '/dev/loop0',
  '/dev/loop1',
  '/dev/loop2',
  '/dev/loop3',
  '/dev/loop4',
  '/dev/loop5',
  '/dev/loop6',
  '/dev/loop7',
]

extend Chef::Mixin::ShellOut
# Creates the loop back device
LvmTest::Helper.create_loop_devices(devices) unless shell_out('pvs | grep -c /dev/loop1').stdout.to_i == 1

# Creates the physical device

log 'Creating physical volume for test'
devices.each do |device|
  lvm_physical_volume device
end

# Verify that the create action is idempotent
lvm_physical_volume devices.first

# Creates the volume group
#
lvm_volume_group 'vg-data' do
  physical_volumes ['/dev/loop0', '/dev/loop1', '/dev/loop2', '/dev/loop3']

  logical_volume 'logs' do
    size '10M'
    filesystem 'ext2'
    mount_point location: '/mnt/logs', options: 'noatime,nodiratime'
    stripes 2
  end

  logical_volume 'home' do
    size '5M'
    filesystem 'ext2'
    mount_point '/mnt/home'
    stripes 1
    mirrors 2
  end
end

lvm_volume_group 'vg-test' do
  physical_volumes ['/dev/loop4', '/dev/loop5', '/dev/loop6']
end

lvm_volume_group 'vg-test-extend' do
  action :extend
  name 'vg-test'
  physical_volumes ['/dev/loop4', '/dev/loop5', '/dev/loop6', '/dev/loop7']
end
# Creates the logical volume
#
lvm_logical_volume 'test' do
  group 'vg-test'
  size '50%VG'
  filesystem 'ext3'
  mount_point '/mnt/test'
end

# Creates a small logical volume
#
lvm_logical_volume 'small' do
  group 'vg-test'
  size '2%VG'
  filesystem 'ext3'
  mount_point '/mnt/small'
end

# Set the directory attributes of the mounted volume
#
directory '/mnt/small' do
  mode '0555'
  owner 1
  group 1
  only_if { File.stat('/mnt/small') != 0100555 }
end

# Creates a small logical volume
#
lvm_logical_volume 'small' do
  group 'vg-test'
  size '2%VG'
  filesystem 'ext3'
  mount_point '/mnt/small'
end


text:
require 'trollop'

opts = Trollop::options do
  version "v0.0.1a"
  opt :fastq, "Fastq file to deinterleave", :required => true, :type => String
  opt :output, "Output prefix", :required => true, :type => String
  opt :verbose, "Be verbose"
end
Trollop::die :fastq, "must exist" if !File.exist?(opts[:fastq]) if opts[:fastq]

fastq = File.open("#{opts.fastq}", "r")

output_left = File.open("#{opts.output}.left.fastq", "w")
output_right= File.open("#{opts.output}.right.fastq", "w")

name1 = fastq.readline rescue nil
seq1 = fastq.readline rescue nil
plus1 = fastq.readline rescue nil
qual1 = fastq.readline rescue nil
name2 = fastq.readline rescue nil
seq2 = fastq.readline rescue nil
plus2 = fastq.readline rescue nil
qual2 = fastq.readline rescue nil

while name1 != nil and name2 != nil
  if name1.split(":").first == name2.split(":").first
    if seq1.length!=qual1.length
      abort "error: seq1.length != qual1.length at #{name1}"
    end
    if seq2.length!=qual2.length
      abort "error: seq2.length != qual2.length at #{name2}"
    end
    output_left.write(name1)
    output_left.write(seq1)
    output_left.write(plus1)
    output_left.write(qual1)
    output_right.write(name2)
    output_right.write(seq2)
    output_right.write(plus2)
    output_right.write(qual2)
  else
    abort "We have a problem"
  end

  name1 = fastq.readline rescue nil
  seq1 = fastq.readline rescue nil
  plus1 = fastq.readline rescue nil
  qual1 = fastq.readline rescue nil
  name2 = fastq.readline rescue nil
  seq2 = fastq.readline rescue nil
  plus2 = fastq.readline rescue nil
  qual2 = fastq.readline rescue nil

end


text:
package com.google.gerrit.server.api.changes;

import com.google.common.collect.ImmutableSet;
import com.google.gerrit.common.errors.EmailException;
import com.google.gerrit.extensions.api.changes.ChangeApi;
import com.google.gerrit.extensions.api.changes.Changes;
import com.google.gerrit.extensions.api.changes.CherryPickInput;
import com.google.gerrit.extensions.api.changes.CommentApi;
import com.google.gerrit.extensions.api.changes.DraftApi;
import com.google.gerrit.extensions.api.changes.DraftInput;
import com.google.gerrit.extensions.api.changes.FileApi;
import com.google.gerrit.extensions.api.changes.RebaseInput;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.api.changes.RevisionApi;
import com.google.gerrit.extensions.api.changes.SubmitInput;
import com.google.gerrit.extensions.common.CommentInfo;
import com.google.gerrit.extensions.common.FileInfo;
import com.google.gerrit.extensions.common.MergeableInfo;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.server.change.CherryPick;
import com.google.gerrit.server.change.Comments;
import com.google.gerrit.server.change.CreateDraftComment;
import com.google.gerrit.server.change.DeleteDraftPatchSet;
import com.google.gerrit.server.change.DraftComments;
import com.google.gerrit.server.change.FileResource;
import com.google.gerrit.server.change.Files;
import com.google.gerrit.server.change.ListComments;
import com.google.gerrit.server.change.ListDraftComments;
import com.google.gerrit.server.change.Mergeable;
import com.google.gerrit.server.change.PostReview;
import com.google.gerrit.server.change.PublishDraftPatchSet;
import com.google.gerrit.server.change.Rebase;
import com.google.gerrit.server.change.Reviewed;
import com.google.gerrit.server.change.RevisionResource;
import com.google.gerrit.server.change.Submit;
import com.google.gerrit.server.changedetail.RebaseChange;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

class RevisionApiImpl implements RevisionApi {
  interface Factory {
    RevisionApiImpl create(RevisionResource r);
  }

  private final Changes changes;
  private final CherryPick cherryPick;
  private final DeleteDraftPatchSet deleteDraft;
  private final Rebase rebase;
  private final RebaseChange rebaseChange;
  private final Submit submit;
  private final PublishDraftPatchSet publish;
  private final Reviewed.PutReviewed putReviewed;
  private final Reviewed.DeleteReviewed deleteReviewed;
  private final RevisionResource revision;
  private final Provider<Files> files;
  private final Provider<Files.ListFiles> listFiles;
  private final Provider<PostReview> review;
  private final Provider<Mergeable> mergeable;
  private final FileApiImpl.Factory fileApi;
  private final ListComments listComments;
  private final ListDraftComments listDrafts;
  private final CreateDraftComment createDraft;
  private final DraftComments drafts;
  private final DraftApiImpl.Factory draftFactory;
  private final Comments comments;
  private final CommentApiImpl.Factory commentFactory;

  @Inject
  RevisionApiImpl(Changes changes,
      CherryPick cherryPick,
      DeleteDraftPatchSet deleteDraft,
      Rebase rebase,
      RebaseChange rebaseChange,
      Submit submit,
      PublishDraftPatchSet publish,
      Reviewed.PutReviewed putReviewed,
      Reviewed.DeleteReviewed deleteReviewed,
      Provider<Files> files,
      Provider<Files.ListFiles> listFiles,
      Provider<PostReview> review,
      Provider<Mergeable> mergeable,
      FileApiImpl.Factory fileApi,
      ListComments listComments,
      ListDraftComments listDrafts,
      CreateDraftComment createDraft,
      DraftComments drafts,
      DraftApiImpl.Factory draftFactory,
      Comments comments,
      CommentApiImpl.Factory commentFactory,
      @Assisted RevisionResource r) {
    this.changes = changes;
    this.cherryPick = cherryPick;
    this.deleteDraft = deleteDraft;
    this.rebase = rebase;
    this.rebaseChange = rebaseChange;
    this.review = review;
    this.submit = submit;
    this.publish = publish;
    this.files = files;
    this.putReviewed = putReviewed;
    this.deleteReviewed = deleteReviewed;
    this.listFiles = listFiles;
    this.mergeable = mergeable;
    this.fileApi = fileApi;
    this.listComments = listComments;
    this.listDrafts = listDrafts;
    this.createDraft = createDraft;
    this.drafts = drafts;
    this.draftFactory = draftFactory;
    this.comments = comments;
    this.commentFactory = commentFactory;
    this.revision = r;
  }

  @Override
  public void review(ReviewInput in) throws RestApiException {
    try {
      review.get().apply(revision, in);
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot post review", e);
    }
  }

  @Override
  public void submit() throws RestApiException {
    SubmitInput in = new SubmitInput();
    in.waitForMerge = true;
    submit(in);
  }

  @Override
  public void submit(SubmitInput in) throws RestApiException {
    try {
      submit.apply(revision, in);
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot submit change", e);
    }
  }

  @Override
  public void publish() throws RestApiException {
    try {
      publish.apply(revision, new PublishDraftPatchSet.Input());
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot publish draft patch set", e);
    }
  }

  @Override
  public void delete() throws RestApiException {
    try {
      deleteDraft.apply(revision, null);
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot delete draft ps", e);
    }
  }

  @Override
  public ChangeApi rebase() throws RestApiException {
    RebaseInput in = new RebaseInput();
    return rebase(in);
  }

  @Override
  public ChangeApi rebase(RebaseInput in) throws RestApiException {
    try {
      return changes.id(rebase.apply(revision, in)._number);
    } catch (OrmException | EmailException e) {
      throw new RestApiException("Cannot rebase ps", e);
    }
  }

  @Override
  public boolean canRebase() {
    return rebaseChange.canRebase(revision);
  }

  @Override
  public ChangeApi cherryPick(CherryPickInput in) throws RestApiException {
    try {
      return changes.id(cherryPick.apply(revision, in)._number);
    } catch (OrmException | EmailException | IOException e) {
      throw new RestApiException("Cannot cherry pick", e);
    }
  }

  @Override
  public void setReviewed(String path, boolean reviewed) throws RestApiException {
    try {
      RestModifyView<FileResource, Reviewed.Input> view;
      if (reviewed) {
        view = putReviewed;
      } else {
        view = deleteReviewed;
      }
      view.apply(
          files.get().parse(revision, IdString.fromDecoded(path)),
          new Reviewed.Input());
    } catch (Exception e) {
      throw new RestApiException("Cannot update reviewed flag", e);
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public Set<String> reviewed() throws RestApiException {
    try {
      return ImmutableSet.copyOf((Iterable<String>) listFiles
          .get().setReviewed(true)
          .apply(revision).value());
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot list reviewed files", e);
    }
  }

  @Override
  public MergeableInfo mergeable() throws RestApiException {
    try {
      return mergeable.get().apply(revision);
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot check mergeability", e);
    }
  }

  @Override
  public MergeableInfo mergeableOtherBranches() throws RestApiException {
    try {
      Mergeable m = mergeable.get();
      m.setOtherBranches(true);
      return m.apply(revision);
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot check mergeability", e);
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public Map<String, FileInfo> files() throws RestApiException {
    try {
      return (Map<String, FileInfo>)listFiles.get().apply(revision).value();
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot retrieve files", e);
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public Map<String, FileInfo> files(String base) throws RestApiException {
    try {
      return (Map<String, FileInfo>) listFiles.get().setBase(base)
          .apply(revision).value();
    } catch (OrmException | IOException e) {
      throw new RestApiException("Cannot retrieve files", e);
    }
  }

  @Override
  public FileApi file(String path) {
    return fileApi.create(files.get().parse(revision,
        IdString.fromDecoded(path)));
  }

  @Override
  public Map<String, List<CommentInfo>> comments() throws RestApiException {
    try {
      return listComments.apply(revision);
    } catch (OrmException e) {
      throw new RestApiException("Cannot retrieve comments", e);
    }
  }

  @Override
  public Map<String, List<CommentInfo>> drafts() throws RestApiException {
    try {
      return listDrafts.apply(revision);
    } catch (OrmException e) {
      throw new RestApiException("Cannot retrieve drafts", e);
    }
  }

  @Override
  public DraftApi draft(String id) throws RestApiException {
    try {
      return draftFactory.create(drafts.parse(revision,
          IdString.fromDecoded(id)));
    } catch (OrmException e) {
      throw new RestApiException("Cannot retrieve draft", e);
    }
  }

  @Override
  public DraftApi createDraft(DraftInput in) throws RestApiException {
    try {
      return draft(createDraft.apply(revision, in).value().id);
    } catch (IOException | OrmException e) {
      throw new RestApiException("Cannot create draft", e);
    }
  }

  @Override
  public CommentApi comment(String id) throws RestApiException {
    try {
      return commentFactory.create(comments.parse(revision,
          IdString.fromDecoded(id)));
    } catch (OrmException e) {
      throw new RestApiException("Cannot retrieve comment", e);
    }
  }
}


text:
/*
 * Dallas Semiconductors 1603 RTC driver
 *
 * Brian Murphy <brian@murphy.dk>
 *
 */
#ifndef __DS1603_H
#define __DS1603_H

struct ds_defs {
	volatile u32 *reg;
	volatile u32 *data_reg;
	u32 rst;
	u32 clk;
	u32 data;
	u32 data_read_shift;
	char data_reversed;
	u32 huge_delay;
};

extern struct ds_defs *ds1603;

unsigned long ds1603_read(void);
int ds1603_set(unsigned long);
void ds1603_set_trimmer(unsigned int);
void ds1603_enable(void);
void ds1603_disable(void);
void ds1603_init(struct ds_defs *);

#define TRIMMER_DEFAULT	3
#define TRIMMER_DISABLE_RTC 0

#endif


text:
=pod

=head1 NAME

RSA_private_encrypt, RSA_public_decrypt - low level signature operations

=head1 SYNOPSIS

 #include <openssl/rsa.h>

 int RSA_private_encrypt(int flen, unsigned char *from,
    unsigned char *to, RSA *rsa, int padding);

 int RSA_public_decrypt(int flen, unsigned char *from,
    unsigned char *to, RSA *rsa, int padding);

=head1 DESCRIPTION

These functions handle RSA signatures at a low level.

RSA_private_encrypt() signs the B<flen> bytes at B<from> (usually a
message digest with an algorithm identifier) using the private key
B<rsa> and stores the signature in B<to>. B<to> must point to
B<RSA_size(rsa)> bytes of memory.

B<padding> denotes one of the following modes:

=over 4

=item RSA_PKCS1_PADDING

PKCS #1 v1.5 padding. This function does not handle the B<algorithmIdentifier>
specified in PKCS #1. When generating or verifying PKCS #1 signatures,
L<RSA_sign(3)|RSA_sign(3)> and L<RSA_verify(3)|RSA_verify(3)> should be used.

=item RSA_NO_PADDING

Raw RSA signature. This mode should I<only> be used to implement
cryptographically sound padding modes in the application code.
Signing user data directly with RSA is insecure.

=back

RSA_public_decrypt() recovers the message digest from the B<flen>
bytes long signature at B<from> using the signer's public key
B<rsa>. B<to> must point to a memory section large enough to hold the
message digest (which is smaller than B<RSA_size(rsa) -
11>). B<padding> is the padding mode that was used to sign the data.

=head1 RETURN VALUES

RSA_private_encrypt() returns the size of the signature (i.e.,
RSA_size(rsa)). RSA_public_decrypt() returns the size of the
recovered message digest.

On error, -1 is returned; the error codes can be
obtained by L<ERR_get_error(3)|ERR_get_error(3)>.

=head1 SEE ALSO

L<ERR_get_error(3)|ERR_get_error(3)>, L<rsa(3)|rsa(3)>,
L<RSA_sign(3)|RSA_sign(3)>, L<RSA_verify(3)|RSA_verify(3)>

=head1 HISTORY

The B<padding> argument was added in SSLeay 0.8. RSA_NO_PADDING is
available since SSLeay 0.9.0.

=cut


text:
package com.facebook.litho.stateupdates;

import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.Size;
import com.facebook.litho.SizeSpec;
import com.facebook.litho.annotations.LayoutSpec;
import com.facebook.litho.annotations.OnCreateLayout;
import com.facebook.litho.annotations.Prop;

@LayoutSpec
public class ComponentWithMeasureCallSpec {

  @OnCreateLayout
  public static Component onCreateLayout(
      ComponentContext c,
      @Prop Component component,
      @Prop boolean shouldCacheResult,
      @Prop(optional = true) int widthSpec,
      @Prop(optional = true) int heightSpec) {

    component.measure(
        c,
        widthSpec != 0 ? widthSpec : SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY),
        heightSpec != 0 ? heightSpec : SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY),
        new Size(),
        shouldCacheResult);

    return component;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace HouraiTeahouse {

    /// <summary> A set of extention methods for all components. </summary>
    public static class ComponentExtensions {

        /// <summary> Gets the GameObjects of all </summary>
        /// <typeparam name="T"> </typeparam>
        /// <param name="components"> </param>
        /// <returns> </returns>
        public static IEnumerable<GameObject> GetGameObject<T>(this IEnumerable<T> components) where T : Component {
            return from component in components.IgnoreNulls() select component.gameObject;
        }

        /// <summary> Gets a component of a certain type. If one doesn't exist, one will be added and returned. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="component" /> is null </exception>
        /// <typeparam name="T"> the type of the component to retrieve </typeparam>
        /// <param name="component"> the Component attached to the GameObject to retrieve the Component </param>
        /// <returns> the retrieved Component </returns>
        public static T GetOrAddComponent<T>(this Component component) where T : Component {
            return Argument.NotNull(component).gameObject.GetOrAddComponent<T>();
        }

        /// <summary> Gets a component of a certain type on a GameObject. Works exactly like the normal GetComponent, but also logs
        /// an error in the console if one is not found. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="component" /> is null </exception>
        /// <typeparam name="T"> the type of the component to retrieve </typeparam>
        /// <param name="component"> the GameObject to retrieve the Component </param>
        /// <returns> the retrieved Component </returns>
        public static T SafeGetComponent<T>(this Component component) where T : class {
            return Argument.NotNull(component).gameObject.SafeGetComponent<T>();
        }

        public static T SafeGetComponentInChildren<T>(this Component component) where T : class {
            return Argument.NotNull(component).gameObject.SafeGetComponentInChildren<T>();
        }

        public static T SafeGetComponentInParent<T>(this Component component) where T : class {
            return Argument.NotNull(component).gameObject.SafeGetComponentInParent<T>();
        }

    }

}


text:
package com.maxdemarzi;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.neo4j.graphdb.*;

import javax.ws.rs.*;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Path("/service")
public class Service {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @GET
    @Path("/friends/{user_id}")
    @Produces({"application/json"})
    public Response Friends(
            @PathParam("user_id") final String userId,
            @Context final GraphDatabaseService db) throws IOException {
        List<Map<String, Object>> results = new ArrayList<>();

        try (Transaction tx = db.beginTx()) {
            final Node user = db.findNode(Labels.User, "user_id", userId);

            if (user != null) {
                for (Relationship r : user.getRelationships(Direction.OUTGOING, RelationshipTypes.FRIENDS)) {
                    Node friend = r.getEndNode();
                    HashMap properties = new HashMap();
                    for (String key : friend.getPropertyKeys()) {
                        properties.put(key, friend.getProperty(key));
                    }
                    results.add(properties);
                }
            }
        }

        return Response.ok().entity(objectMapper.writeValueAsString(results)).build();
    }

    @GET
    @Path("/friends2/{user_id}")
    @Produces({"application/json"})
    public Response Friends2(
            @PathParam("user_id") final String userId,
            @Context final GraphDatabaseService db) throws IOException {

        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream os) throws IOException, WebApplicationException
            {
                JsonGenerator jg = objectMapper.getJsonFactory().createJsonGenerator( os, JsonEncoding.UTF8 );
                jg.writeStartArray();

                try (Transaction tx = db.beginTx()) {
                    final Node user = db.findNode(Labels.User, "user_id", userId);

                    if (user != null) {
                        for (Relationship r : user.getRelationships(Direction.OUTGOING, RelationshipTypes.FRIENDS)) {
                            Node friend = r.getEndNode();
                            jg.writeStartObject();
                            for (String key : friend.getPropertyKeys()) {
                                jg.writeObjectField(key, friend.getProperty(key));
                            }
                            jg.writeEndObject();
                        }
                    }
                }
                    jg.writeEndArray();
                    jg.flush();
                    jg.close();
                }
            };

        return Response.ok().entity(stream).type(MediaType.APPLICATION_JSON).build();
    }

}


text:
<?php

namespace WellCommerce\Bundle\AppBundle\Form\Admin;

use WellCommerce\Bundle\CoreBundle\Form\AbstractFormBuilder;
use WellCommerce\Component\Form\Elements\FormInterface;

/**
 * Class CompanyFormBuilder
 *
 * @author Adam Piotrowski <adam@wellcommerce.org>
 */
class CompanyFormBuilder extends AbstractFormBuilder
{
    public function getAlias(): string
    {
        return 'admin.company';
    }

    public function buildForm(FormInterface $form)
    {
        $requiredData = $form->addChild($this->getElement('nested_fieldset', [
            'name'  => 'required_data',
            'label' => 'common.fieldset.general'
        ]));

        $requiredData->addChild($this->getElement('text_field', [
            'name'  => 'name',
            'label' => 'company.label.name',
            'rules' => [
                $this->getRule('required')
            ],
        ]));

        $requiredData->addChild($this->getElement('text_field', [
            'name'  => 'shortName',
            'label' => 'company.label.short_name',
            'rules' => [
                $this->getRule('required')
            ],
        ]));

        $addressData = $form->addChild($this->getElement('nested_fieldset', [
            'name'  => 'address_data',
            'label' => 'company.label.addresses'
        ]));

        $addressData->addChild($this->getElement('text_field', [
            'name'  => 'line1',
            'label' => 'common.label.line1',
        ]));

        $addressData->addChild($this->getElement('text_field', [
            'name'  => 'line2',
            'label' => 'common.label.line2',
        ]));

        $addressData->addChild($this->getElement('text_field', [
            'name'  => 'state',
            'label' => 'common.label.state',
        ]));

        $addressData->addChild($this->getElement('text_field', [
            'name'  => 'postalCode',
            'label' => 'common.label.postal_code',
        ]));

        $addressData->addChild($this->getElement('text_field', [
            'name'  => 'city',
            'label' => 'common.label.city',
        ]));

        $addressData->addChild($this->getElement('select', [
            'name'    => 'country',
            'label'   => 'common.label.country',
            'options' => $this->get('country.repository')->all()
        ]));

        $form->addFilter($this->getFilter('no_code'));
        $form->addFilter($this->getFilter('trim'));
        $form->addFilter($this->getFilter('secure'));
    }
}


text:
package edu.northwestern.bioinformatics.studycalendar.restlets;

import org.restlet.data.Form;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException;

/**
 * @author Rhett Sutphin
 */
public class FormParametersTest extends RestletTestCase {
    private Form form;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        form = new Form();
    }

    public void testAttributeNameIsHyphenatedAndLowerCase() throws Exception {
        assertEquals("activity-code", FormParameters.ACTIVITY_CODE.attributeName());
    }

    public void testGetStringValueFromForm() throws Exception {
        form.add("day", "12");
        assertEquals("12", FormParameters.DAY.extractFirstFrom(form));
    }

    public void testGetStringValueFromFormForWeight() throws Exception {
        form.add("weight", "2");
        assertEquals("2", FormParameters.WEIGHT.extractFirstFrom(form));
    }

    public void testGetStringValueFromFormWhenNotSet() throws Exception {
        assertNull(FormParameters.DAY.extractFirstFrom(form));
    }

    public void testGetStringValueFromFormWhenNotSetForWeight() throws Exception {
        assertNull(FormParameters.WEIGHT.extractFirstFrom(form));
    }

    public void testGetIntegerValueFromForm() throws Exception {
        form.add("day", "12");
        assertEquals(12, (int) FormParameters.DAY.extractFirstAsIntegerFrom(form));
    }

    public void testGetIntegerValueFromFormForWeight() throws Exception {
        form.add("weight", "2");
        assertEquals(2, (int) FormParameters.WEIGHT.extractFirstAsIntegerFrom(form));
    }

    public void testGetIntegerValueFromFormWhenNotSet() throws Exception {
        assertNull(FormParameters.DAY.extractFirstAsIntegerFrom(form));
    }

    public void testGetIntegerValueFromFormWhenNotInteger() throws Exception {
        form.add("day", "twelve");
        try {
            FormParameters.DAY.extractFirstAsIntegerFrom(form);
            fail("Exception not thrown");
        } catch (StudyCalendarValidationException ve) {
            assertEquals("Expected day parameter value to be an integer, not 'twelve'",
                ve.getMessage());
        }
    }
}


text:
Follow the instructions for getting started with Emscripten [here](http://kripken.github.io/emscripten-site/docs/getting_started/downloads.html).

Then you can run

```bash
source ./emsdk_env.sh
cd {micropython directory}/emscripten
make EMSCRIPTEN=1 -j
node build/firmware.js
```


text:
from django.shortcuts import render
import django.forms as forms

import six
from six.moves import intern

from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django import db
from django.contrib import messages
from django import http

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

from pytools.lex import RE as REBase  # noqa

from pieces.models import PieceTag, Piece
from coding.models import AssignmentTag, Sample, CodingAssignment
from django.contrib.auth.models import User

# {{{ parsing

# {{{ lexer data

_and = intern("and")
_or = intern("or")
_not = intern("not")
_openpar = intern("openpar")
_closepar = intern("closepar")
_id = intern("id")
_study_id = intern("study_id")
_sample_id = intern("sample_id")
_tag = intern("tag")
_assignment_tag = intern("_assignment_tag")
_meta = intern("_meta")
_pub_before = intern("_pub_before")
_pub_after = intern("_pub_after")
_regex = intern("regex")
_word = intern("word")
_near = intern("near")
_fulltext = intern("fulltext")
_whitespace = intern("whitespace")

# }}}

class RE(REBase):
    def __init__(self, s):
        import re
        super(RE, self).__init__(s, re.UNICODE)

_LEX_TABLE = [
    (_and, RE(r"and\b")),
    (_or, RE(r"or\b")),
    (_not, RE(r"not\b")),
    (_openpar, RE(r"\(")),
    (_closepar, RE(r"\)")),

    # TERMINALS
    (_id, RE(r"id:([0-9]+)")),
    (_study_id, RE(r"study\-id:([0-9]+)")),
    (_sample_id, RE(r"sample\-id:([0-9]+)")),
    (_tag, RE(r"tag:([-\w]+)")),
    (_assignment_tag, RE(r"atag:([-\w]+)")),
    (_meta, RE(r"meta:([-._\w]+)")),
    (_pub_before, RE(r"pubbefore:([0-9]{4,4})\-([0-9]{2,2})\-([0-9]{2,2})")),
    (_pub_after, RE(r"pubafter:([0-9]{4,4})\-([0-9]{2,2})\-([0-9]{2,2})")),
    (_regex, RE(r"regex:(\S+)")),
    (_word, RE(r"word:(\S+)")),
    (_near, RE(r"near:([0-9]),(\w+),(\w+)")),
    (_fulltext, RE(r'".*?(?!\\\\)"')),

    (_whitespace, RE("[ \t]+")),
    ]

_TERMINALS = ([
    _id, _study_id, _sample_id, _tag, _assignment_tag, _regex,
    _word, _near, _fulltext])

# {{{ operator precedence

_PREC_OR = 10
_PREC_AND = 20
_PREC_NOT = 30

# }}}

# {{{ parser

def parse_query(expr_str):
    from django.db.backends.sqlite3.base import DatabaseWrapper as SQLite3DB
    if isinstance(db.connections["default"], SQLite3DB):
        WORD_BDRY = r"\b"
    else:
        WORD_BDRY = r"\y"

    from django.db.models import Q

    def parse_terminal(pstate):
        next_tag = pstate.next_tag()
        if next_tag is _tag:
            tag = PieceTag.objects.get(
                    name=pstate.next_match_obj().group(1))
            result = Q(tags__id=tag.id)
            pstate.advance()
            return result
        if next_tag is _assignment_tag:
            atag_ids = [
                    atag.id for atag in
                    AssignmentTag.objects.filter(
                        name=pstate.next_match_obj().group(1))]
            result = Q(coding_assignments__tags__id__in=atag_ids)
            pstate.advance()
            return result
        elif next_tag is _meta:
            text = pstate.next_match_obj().group(1)
            result = (
                    Q(title__icontains=text)
                    | Q(notes__icontains=text)
                    | Q(pub_date_unparsed__icontains=text)
                    | Q(byline__icontains=text)
                    | Q(url__icontains=text)
                    | Q(extra_data_json__icontains=text)
                    | Q(venue__name__icontains=text)
                    )

            pstate.advance()
            return result

        elif next_tag in [_pub_before, _pub_after]:
            import datetime
            mo = pstate.next_match_obj()
            date = datetime.date(
                    year=int(mo.group(1)),
                    month=int(mo.group(2)),
                    day=int(mo.group(3)),
                    )

            if next_tag is _pub_before:
                result = Q(pub_date__lt=date)
            else:
                result = Q(pub_date__gt=date)

            pstate.advance()
            return result
        elif next_tag is _regex:
            re_value = pstate.next_match_obj().group(1)
            pstate.advance()
            return Q(content__iregex=re_value) | Q(title__iregex=re_value)
        elif next_tag is _word:
            re_value = r"{wb}{word}{wb}".format(
                    wb=WORD_BDRY,
                    word=pstate.next_match_obj().group(1))
            pstate.advance()
            return Q(content__iregex=re_value) | Q(title__iregex=re_value)
        elif next_tag is _near:
            match_obj = pstate.next_match_obj()
            dist = int(match_obj.group(1))
            word1 = match_obj.group(2)
            word2 = match_obj.group(3)

            regexes = []

            for i in range(0, dist+1):
                regex = WORD_BDRY+word1
                for j in range(i):
                    regex += "\W+\w+"
                regex += r"\W+" + word2 + WORD_BDRY
                regexes.append(regex)
            re_value = "|".join(regexes)
            pstate.advance()
            return Q(content__iregex=re_value) | Q(title__iregex=re_value)
        elif next_tag is _fulltext:
            text = pstate.next_str_and_advance()[1:-1]
            return Q(content__icontains=text) | Q(title__icontains=text)
        elif next_tag in [_id]:
            result = Q(id=int(pstate.next_match_obj().group(1)))
            pstate.advance()
            return result
        elif next_tag in [_study_id]:
            result = Q(studies__id=int(pstate.next_match_obj().group(1)))
            pstate.advance()
            return result
        elif next_tag in [_sample_id]:
            result = Q(samples__id=int(pstate.next_match_obj().group(1)))
            pstate.advance()
            return result
        else:
            pstate.expected("terminal")

    def inner_parse(pstate, min_precedence=0):
        pstate.expect_not_end()

        if pstate.is_next(_not):
            pstate.advance()
            left_query = ~inner_parse(pstate, _PREC_NOT)
        elif pstate.is_next(_openpar):
            pstate.advance()
            left_query = inner_parse(pstate)
            pstate.expect(_closepar)
            pstate.advance()
        else:
            left_query = parse_terminal(pstate)

        did_something = True
        while did_something:
            did_something = False
            if pstate.is_at_end():
                return left_query

            next_tag = pstate.next_tag()

            if next_tag is _and and _PREC_AND > min_precedence:
                pstate.advance()
                left_query = left_query & inner_parse(pstate, _PREC_AND)
                did_something = True
            elif next_tag is _or and _PREC_OR > min_precedence:
                pstate.advance()
                left_query = left_query | inner_parse(pstate, _PREC_OR)
                did_something = True
            elif (next_tag in _TERMINALS + [_not, _openpar]
                    and _PREC_AND > min_precedence):
                left_query = left_query & inner_parse(pstate, _PREC_AND)
                did_something = True

        return left_query

    from pytools.lex import LexIterator, lex
    pstate = LexIterator(
        [(tag, s, idx, matchobj)
         for (tag, s, idx, matchobj) in lex(_LEX_TABLE, expr_str, match_objects=True)
         if tag is not _whitespace], expr_str)

    if pstate.is_at_end():
        pstate.raise_parse_error("unexpected end of input")

    result = inner_parse(pstate)
    if not pstate.is_at_end():
        pstate.raise_parse_error("leftover input after completed parse")

    return result

# }}}

# }}}

SEARCH_HELP = """
The following search syntax is supported:
"fulltext",
word:someword,
near:3,someword,otherword
('someword' and 'otherword' are separated by at most 3 words,
with 'someword' occurring first),
id:1234,
study-id:1234,
sample-id:1234,
tag:piece-tag,
atag:assignment-tag,
meta:word (word occurs in metadata),
pubbefore:YYYY-MM-DD,
pubafter:YYYY-MM-DD,
regex:
\
regular-expression.
Combining these with parentheses (),
and, or, and not
is supported. Text queries are not case sensitive.
"""

# {{{ search form

class SearchForm(forms.Form):
    def __init__(self, assign_tag_allowed, large_query, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_class = "form-horizontal"
        self.helper.label_class = "col-lg-1"
        self.helper.field_class = "col-lg-8"

        widget = None
        if large_query:
            widget = forms.Textarea

        self.fields["query"] = forms.CharField(min_length=1, widget=widget,
                help_text=SEARCH_HELP)
        if assign_tag_allowed:
            self.fields["tag"] = forms.ModelChoiceField(
                    queryset=PieceTag.objects,
                    help_text="If you click 'Assign tag' or 'Remove tag', this tag "
                    "will be assigned to or removed from every piece in "
                    "the result set",
                    required=False)

        self.fields["query"].widget.attrs["autofocus"] = None

        self.helper.add_input(
                Submit("search", "Search"))
        if assign_tag_allowed:
            self.helper.add_input(
                    Submit("assign_tag", "Assign tag"))
            self.helper.add_input(
                    Submit("remove_tag", "Remove tag"))
            self.helper.add_input(
                    Submit("export_csv", "Export CSV"))

@login_required
def view_search_form(request, large_query=False):
    assign_tag_allowed = request.user.has_perm("tag_by_search")

    pieces = None
    if request.method == "POST":
        form = SearchForm(
                assign_tag_allowed,
                large_query,
                request.POST, request.FILES)
        assign_tag = assign_tag_allowed and "assign_tag" in request.POST
        remove_tag = assign_tag_allowed and "remove_tag" in request.POST
        export_csv = "export_csv" in request.POST

        if form.is_valid():
            try:
                query = parse_query(
                        form.cleaned_data["query"].replace("\n", " "))
                pieces = (Piece.objects
                        .filter(query)
                        .order_by("id")
                        .prefetch_related("tags"))
            except Exception as e:
                messages.add_message(request, messages.ERROR,
                        type(e).__name__+": "+str(e))
            else:
                tag = form.cleaned_data["tag"]

                if assign_tag:
                    count = 0
                    for piece in pieces:
                        if tag not in piece.tags.all():
                            piece.tags.add(tag)
                            piece.save()
                            count += 1
                    messages.add_message(request, messages.INFO,
                            "%d tags assigned." % count)

                if remove_tag:
                    count = 0
                    for piece in pieces:
                        if tag in piece.tags.all():
                            piece.tags.remove(tag)
                            piece.save()
                            count += 1
                    messages.add_message(request, messages.INFO,
                            "%d tags removed." % count)

                if export_csv:
                    from six import StringIO
                    csvfile = StringIO()

                    if six.PY2:
                        import unicodecsv as csv
                    else:
                        import csv

                    fieldnames = ['id', 'title', 'content', 'publication_type',
                            'notes', 'venue__id', 'venue', 'pub_date',
                            'pub_date_unparsed', 'source_load_date', 'byline', 'url',
                            'create_date', 'creator', 'extra_data_json',
                            'tags', 'assignment_tags']

                    writer = csv.writer(csvfile)
                    writer.writerow(fieldnames)

                    def get_formatted_piece_field(piece, fieldname):
                        if fieldname == "tags":
                            return u", ".join(
                                    six.text_type(t)
                                    for t in piece.tags.all())

                        elif fieldname == "assignment_tags":
                            return u", ".join(
                                    six.text_type(t.name)
                                    for a in piece.coding_assignments.all()
                                    for t in a.tags.all())

                        elif fieldname.endswith("__id"):
                            return six.text_type(getattr(piece, fieldname[:-4]).id)

                        else:
                            val = getattr(piece, fieldname)
                            if val is None:
                                return u""
                            else:
                                return six.text_type(val)

                    for piece in pieces:
                        writer.writerow([
                            get_formatted_piece_field(piece, fieldname)
                            for fieldname in fieldnames])

                    data = csvfile.getvalue()
                    if isinstance(data, six.text_type):
                        data = data.encode("utf-8")
                    response = http.HttpResponse(
                            data,
                            content_type="text/plain; charset=utf-8")
                    response['Content-Disposition'] = (
                            'attachment; filename="export.csv"')
                    return response
    else:
        form = SearchForm(assign_tag_allowed, large_query)

    return render(request, 'pieces/search.html', {
        "form": form,
        "pieces": pieces,
        "may_see_non_coder_tags": request.user.has_perm("may_see_non_coder_tags"),
        "count": pieces.count() if pieces is not None else 0,
    })

@login_required
def view_large_search_form(request):
    return view_search_form(request, large_query=True)

# }}}

class UniqueIDData:
    def __init__(self, uid):
        self.uid = uid

        parts = uid.split("-")

        piece = None
        assignment = None
        sample = None
        coder = None

        for part in parts:
            if not part:
                raise ValueError("invalid unique id: %s" % uid)

            kind = part[0]

            try:
                number = int(part[1:])
            except ValueError:
                raise ValueError("invalid unique id: %s" % uid)

            try:
                if kind == "P":
                    piece = Piece.objects.get(id=number)
                elif kind == "A":
                    assignment = CodingAssignment.objects.get(id=number)
                elif kind == "S":
                    sample = Sample.objects.get(id=number)
                elif kind == "C":
                    coder = User.objects.get(id=number)
                else:
                    raise ValueError("invalid unique id: %s" % uid)

            except ObjectDoesNotExist:
                raise ValueError("invalid unique id: %s" % uid)

        if piece is not None and assignment is not None:
            if assignment.piece.id != piece.id:
                raise ValueError("A and P disagree in UID: %s" % uid)

        if coder is not None and assignment is not None:
            if assignment.coder.id != coder.id:
                raise ValueError("A and C disagree in UID: %s" % uid)

        if sample is not None and assignment is not None:
            if assignment.sample.id != sample.id:
                raise ValueError("A and S disagree in UID: %s" % uid)

        if piece is None and self.assignment is not None:
            piece = self.assignment

        self.piece = piece
        self.assignment = assignment
        self.sample = sample
        self.coder = coder

    def expect_piece(self):
        if self.piece is None:
            raise ValueError("piece ref expected in: %s" % self.uid)

        return self

# {{{ completeness checking

class CompletenessCheckingForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(CompletenessCheckingForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_class = "form-horizontal"
        self.helper.label_class = "col-lg-1"
        self.helper.field_class = "col-lg-8"

        self.fields["query"] = forms.CharField(min_length=1, widget=forms.Textarea,
                help_text=SEARCH_HELP)

        self.fields["query"].widget.attrs["autofocus"] = None

        self.fields["validation_uids"] = forms.CharField(
                label="Unique identifiers for set checking",
                widget=forms.Textarea)

        self.helper.add_input(
                Submit("validate", "Check Against Unique Identifiers"))

@login_required
def view_check_completeness(request):
    pieces = None

    if request.method == "POST":
        form = CompletenessCheckingForm(
                request.POST, request.FILES)

        if form.is_valid():
            try:
                query = parse_query(
                        form.cleaned_data["query"].replace("\n", " "))
                pieces = (Piece.objects
                        .filter(query)
                        .order_by("id")
                        .prefetch_related("tags"))
            except Exception as e:
                messages.add_message(request, messages.ERROR,
                        type(e).__name__+": "+str(e))
            else:
                try:
                    uid_data = [UniqueIDData(s).expect_piece()
                            for s in
                            form.cleaned_data["validation_uids"].split()
                            if s]
                except Exception as e:
                    messages.add_message(request, messages.ERROR,
                            type(e).__name__+": "+str(e))

                else:
                    search_ids = set(piece.id for piece in pieces)
                    uid_ids = set(uidd.piece.id for uidd in uid_data)

                    search_m_uid = search_ids - uid_ids
                    uid_m_search = uid_ids - search_ids

                    if search_m_uid:
                        messages.add_message(request, messages.ERROR,
                                "Piece IDs found in search but not by UID: %s"
                                % ", ".join(str(i) for i in search_m_uid))
                    if uid_m_search:
                        messages.add_message(request, messages.ERROR,
                                "Piece IDs found by UID but not by search: %s"
                                % ", ".join(str(i) for i in uid_m_search))

                    if not (search_m_uid or uid_m_search):
                        messages.add_message(request, messages.SUCCESS,
                                "Search matches UID list.")

    else:
        form = CompletenessCheckingForm()

    return render(request, 'generic-form.html', {
        "form_description": "Check Query Result against Unique IDs",
        "form": form,
    })

# }}}
# vim: foldmethod=marker


text:
  (reinterpret_cast<intptr_t>(&(reinterpret_cast<type*>(16)->field)) - 16)

#if V8_OS_NACL

// ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize,
// but can be used on anonymous types or types defined inside
// functions.  It's less safe than arraysize as it accepts some
// (although not all) pointers.  Therefore, you should use arraysize
// whenever possible.
//
// The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type
// size_t.
//
// ARRAYSIZE_UNSAFE catches a few type errors.  If you see a compiler error
//
//   "warning: division by zero in ..."
//
// when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer.
// You should only use ARRAYSIZE_UNSAFE on statically allocated arrays.
//
// The following comments are on the implementation details, and can
// be ignored by the users.
//
// ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in
// the array) and sizeof(*(arr)) (the # of bytes in one array
// element).  If the former is divisible by the latter, perhaps arr is
// indeed an array, in which case the division result is the # of
// elements in the array.  Otherwise, arr cannot possibly be an array,
// and we generate a compiler error to prevent the code from
// compiling.
//
// Since the size of bool is implementation-defined, we need to cast
// !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
// result has type size_t.
//
// This macro is not perfect as it wrongfully accepts certain
// pointers, namely where the pointer size is divisible by the pointee
// size.  Since all our code has to go through a 32-bit compiler,
// where a pointer is 4 bytes, this means all pointers to a type whose
// size is 3 or greater than 4 will be (righteously) rejected.
#define ARRAYSIZE_UNSAFE(a)     \
  ((sizeof(a) / sizeof(*(a))) / \
   static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))  // NOLINT

// TODO(bmeurer): For some reason, the NaCl toolchain cannot handle the correct
// definition of arraysize() below, so we have to use the unsafe version for
// now.
#define arraysize ARRAYSIZE_UNSAFE

#else  // V8_OS_NACL

// The arraysize(arr) macro returns the # of elements in an array arr.
// The expression is a compile-time constant, and therefore can be
// used in defining new arrays, for example.  If you use arraysize on
// a pointer by mistake, you will get a compile-time error.
//
// One caveat is that arraysize() doesn't accept any array of an
// anonymous type or a type defined inside a function.  In these rare
// cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below.  This is
// due to a limitation in C++'s template system.  The limitation might
// eventually be removed, but it hasn't happened yet.
#define arraysize(array) (sizeof(ArraySizeHelper(array)))

// This template function declaration is used in defining arraysize.
// Note that the function doesn't need an implementation, as we only
// use its type.
template <typename T, size_t N>
char (&ArraySizeHelper(T (&array)[N]))[N];

#if !V8_CC_MSVC
// That gcc wants both of these prototypes seems mysterious. VC, for
// its part, can't decide which to use (another mystery). Matching of
// template overloads: the final frontier.
template <typename T, size_t N>
char (&ArraySizeHelper(const T (&array)[N]))[N];
#endif

#endif  // V8_OS_NACL

// The COMPILE_ASSERT macro can be used to verify that a compile time
// expression is true. For example, you could use it to verify the
// size of a static array:
//
//   COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES,
//                  content_type_names_incorrect_size);
//
// or to make sure a struct is smaller than a certain size:
//
//   COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
//
// The second argument to the macro is the name of the variable. If
// the expression is false, most compilers will issue a warning/error
// containing the name of the variable.
#if V8_HAS_CXX11_STATIC_ASSERT

// Under C++11, just use static_assert.
#define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg)

#else

template <bool>
struct CompileAssert {};

#define COMPILE_ASSERT(expr, msg)                \
  typedef CompileAssert<static_cast<bool>(expr)> \
      msg[static_cast<bool>(expr) ? 1 : -1] ALLOW_UNUSED_TYPE

// Implementation details of COMPILE_ASSERT:
//
// - COMPILE_ASSERT works by defining an array type that has -1
//   elements (and thus is invalid) when the expression is false.
//
// - The simpler definition
//
//     #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
//
//   does not work, as gcc supports variable-length arrays whose sizes
//   are determined at run-time (this is gcc's extension and not part
//   of the C++ standard).  As a result, gcc fails to reject the
//   following code with the simple definition:
//
//     int foo;
//     COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
//                               // not a compile-time constant.
//
// - By using the type CompileAssert<static_cast<bool>(expr)>, we ensure that
//   expr is a compile-time constant.  (Template arguments must be
//   determined at compile-time.)
//
// - The array size is (static_cast<bool>(expr) ? 1 : -1), instead of simply
//
//     ((expr) ? 1 : -1).
//
//   This is to avoid running into a bug in MS VC 7.1, which
//   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.

#endif

// bit_cast<Dest,Source> is a template function that implements the
// equivalent of "*reinterpret_cast<Dest*>(&source)".  We need this in
// very low-level functions like the protobuf library and fast math
// support.
//
//   float f = 3.14159265358979;
//   int i = bit_cast<int32>(f);
//   // i = 0x40490fdb
//
// The classical address-casting method is:
//
//   // WRONG
//   float f = 3.14159265358979;            // WRONG
//   int i = * reinterpret_cast<int*>(&f);  // WRONG
//
// The address-casting method actually produces undefined behavior
// according to ISO C++ specification section 3.10 -15 -.  Roughly, this
// section says: if an object in memory has one type, and a program
// accesses it with a different type, then the result is undefined
// behavior for most values of "different type".
//
// This is true for any cast syntax, either *(int*)&f or
// *reinterpret_cast<int*>(&f).  And it is particularly true for
// conversions between integral lvalues and floating-point lvalues.
//
// The purpose of 3.10 -15- is to allow optimizing compilers to assume
// that expressions with different types refer to different memory.  gcc
// 4.0.1 has an optimizer that takes advantage of this.  So a
// non-conforming program quietly produces wildly incorrect output.
//
// The problem is not the use of reinterpret_cast.  The problem is type
// punning: holding an object in memory of one type and reading its bits
// back using a different type.
//
// The C++ standard is more subtle and complex than this, but that
// is the basic idea.
//
// Anyways ...
//
// bit_cast<> calls memcpy() which is blessed by the standard,
// especially by the example in section 3.9 .  Also, of course,
// bit_cast<> wraps up the nasty logic in one place.
//
// Fortunately memcpy() is very fast.  In optimized mode, with a
// constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
// code with the minimal amount of data movement.  On a 32-bit system,
// memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
// compiles to two loads and two stores.
//
// I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
//
// WARNING: if Dest or Source is a non-POD type, the result of the memcpy
// is likely to surprise you.
template <class Dest, class Source>
V8_INLINE Dest bit_cast(Source const& source) {
  COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), VerifySizesAreEqual);

  Dest dest;
  memcpy(&dest, &source, sizeof(dest));
  return dest;
}

// Put this in the private: declarations for a class to be unassignable.
#define DISALLOW_ASSIGN(TypeName) void operator=(const TypeName&)

// A macro to disallow the evil copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
  TypeName(const TypeName&) = delete;      \
  void operator=(const TypeName&) = delete

// A macro to disallow all the implicit constructors, namely the
// default constructor, copy constructor and operator= functions.
//
// This should be used in the private: declarations for a class
// that wants to prevent anyone from instantiating it. This is
// especially useful for classes containing only static methods.
#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
  TypeName() = delete;                           \
  DISALLOW_COPY_AND_ASSIGN(TypeName)

// Newly written code should use V8_INLINE and V8_NOINLINE directly.
#define INLINE(declarator)    V8_INLINE declarator
#define NO_INLINE(declarator) V8_NOINLINE declarator

// Newly written code should use WARN_UNUSED_RESULT.
#define MUST_USE_RESULT WARN_UNUSED_RESULT

// Define V8_USE_ADDRESS_SANITIZER macros.
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
#define V8_USE_ADDRESS_SANITIZER 1
#endif
#endif

// Define DISABLE_ASAN macros.
#ifdef V8_USE_ADDRESS_SANITIZER
#define DISABLE_ASAN __attribute__((no_sanitize_address))
#else
#define DISABLE_ASAN
#endif

#if V8_CC_GNU
#define V8_IMMEDIATE_CRASH() __builtin_trap()
#else
#define V8_IMMEDIATE_CRASH() ((void(*)())0)()
#endif

// Use C++11 static_assert if possible, which gives error
// messages that are easier to understand on first sight.
#if V8_HAS_CXX11_STATIC_ASSERT
#define STATIC_ASSERT(test) static_assert(test, #test)
#else
// This is inspired by the static assertion facility in boost.  This
// is pretty magical.  If it causes you trouble on a platform you may
// find a fix in the boost code.
template <bool> class StaticAssertion;
template <> class StaticAssertion<true> { };
// This macro joins two tokens.  If one of the tokens is a macro the
// helper call causes it to be resolved before joining.
#define SEMI_STATIC_JOIN(a, b) SEMI_STATIC_JOIN_HELPER(a, b)
#define SEMI_STATIC_JOIN_HELPER(a, b) a##b
// Causes an error during compilation of the condition is not
// statically known to be true.  It is formulated as a typedef so that
// it can be used wherever a typedef can be used.  Beware that this
// actually causes each use to introduce a new defined type with a
// name depending on the source line.
template <int> class StaticAssertionHelper { };
#define STATIC_ASSERT(test)                               \
  typedef StaticAssertionHelper<                          \
      sizeof(StaticAssertion<static_cast<bool>((test))>)> \
      SEMI_STATIC_JOIN(__StaticAssertTypedef__, __LINE__) ALLOW_UNUSED_TYPE

#endif

// The USE(x) template is used to silence C++ compiler warnings
// issued for (yet) unused variables (typically parameters).
template <typename T>
inline void USE(T) { }

#define IS_POWER_OF_TWO(x) ((x) != 0 && (((x) & ((x) - 1)) == 0))

// Define our own macros for writing 64-bit constants.  This is less fragile
// than defining __STDC_CONSTANT_MACROS before including <stdint.h>, and it
// works on compilers that don't have it (like MSVC).
#if V8_CC_MSVC
# define V8_UINT64_C(x)   (x ## UI64)
# define V8_INT64_C(x)    (x ## I64)
# if V8_HOST_ARCH_64_BIT
#  define V8_INTPTR_C(x)  (x ## I64)
#  define V8_PTR_PREFIX   "ll"
# else
#  define V8_INTPTR_C(x)  (x)
#  define V8_PTR_PREFIX   ""
# endif  // V8_HOST_ARCH_64_BIT
#elif V8_CC_MINGW64
# define V8_UINT64_C(x)   (x ## ULL)
# define V8_INT64_C(x)    (x ## LL)
# define V8_INTPTR_C(x)   (x ## LL)
# define V8_PTR_PREFIX    "I64"
#elif V8_HOST_ARCH_64_BIT
# if V8_OS_MACOSX || V8_OS_OPENBSD
#  define V8_UINT64_C(x)   (x ## ULL)
#  define V8_INT64_C(x)    (x ## LL)
# else
#  define V8_UINT64_C(x)   (x ## UL)
#  define V8_INT64_C(x)    (x ## L)
# endif
# define V8_INTPTR_C(x)   (x ## L)
# define V8_PTR_PREFIX    "l"
#else
# define V8_UINT64_C(x)   (x ## ULL)
# define V8_INT64_C(x)    (x ## LL)
# define V8_INTPTR_C(x)   (x)
#if V8_OS_AIX
#define V8_PTR_PREFIX "l"
#else
# define V8_PTR_PREFIX    ""
#endif
#endif

#define V8PRIxPTR V8_PTR_PREFIX "x"
#define V8PRIdPTR V8_PTR_PREFIX "d"
#define V8PRIuPTR V8_PTR_PREFIX "u"

// Fix for Mac OS X defining uintptr_t as "unsigned long":
#if V8_OS_MACOSX
#undef V8PRIxPTR
#define V8PRIxPTR "lx"
#endif

// The following macro works on both 32 and 64-bit platforms.
// Usage: instead of writing 0x1234567890123456
//      write V8_2PART_UINT64_C(0x12345678,90123456);
#define V8_2PART_UINT64_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))

// Compute the 0-relative offset of some absolute value x of type T.
// This allows conversion of Addresses and integral types into
// 0-relative int offsets.
template <typename T>
inline intptr_t OffsetFrom(T x) {
  return x - static_cast<T>(0);
}

// Compute the absolute value of type T for some 0-relative offset x.
// This allows conversion of 0-relative int offsets into Addresses and
// integral types.
template <typename T>
inline T AddressFrom(intptr_t x) {
  return static_cast<T>(static_cast<T>(0) + x);
}

// Return the largest multiple of m which is <= x.
template <typename T>
inline T RoundDown(T x, intptr_t m) {
  DCHECK(IS_POWER_OF_TWO(m));
  return AddressFrom<T>(OffsetFrom(x) & -m);
}

// Return the smallest multiple of m which is >= x.
template <typename T>
inline T RoundUp(T x, intptr_t m) {
  return RoundDown<T>(static_cast<T>(x + m - 1), m);
}

namespace v8 {
namespace base {

// TODO(yangguo): This is a poor man's replacement for std::is_fundamental,
// which requires C++11. Switch to std::is_fundamental once possible.
template <typename T>
inline bool is_fundamental() {
  return false;
}

template <>
inline bool is_fundamental<uint8_t>() {
  return true;
}
}
}  // namespace v8::base

#endif   // V8_BASE_MACROS_H_