text:
CREATE TABLE `SITE_DB`.`system_maillists` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `description` text DEFAULT NULL,

  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Virtlink.Utilib.Collections;
using Xunit;

namespace Virtlink.Utilib
{
    /// <summary>
    /// Tests the <see cref="SmartList{T}"/> class.
    /// </summary>
    public partial class SmartListTests
    {
        private class CheckingEnumerable<T> : IEnumerable<T>
        {
            private readonly IEnumerable<T> enumerable;

            /// <summary>
            /// Gets the number of times <see cref="GetEnumerator"/> was called.
            /// </summary>
            private int enumerationCount;

            /// <summary>
            /// Gets the next index to be returned by <see cref="GetEnumerator"/>.
            /// </summary>
            public int NextIndex { get; private set; }

            public bool Enumerated => this.enumerationCount > 0;

            public CheckingEnumerable(IEnumerable<T> enumerable)
            {
                this.enumerable = enumerable;
            }

            public IEnumerator<T> GetEnumerator()
            {
                if (this.enumerationCount != 0)
                    throw new InvalidOperationException("Multiple enumeration.");
                this.enumerationCount += 1;
                int index = 0;
                this.NextIndex = index;
                foreach (var element in this.enumerable)
                {
                    index += 1;
                    this.NextIndex = index;
                    yield return element;
                }
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
        }

        private class CheckingCollection<T> : CheckingEnumerable<T>, IReadOnlyCollection<T>
        {
            private readonly IReadOnlyCollection<T> collection;

            public int Count => this.collection.Count;

            public CheckingCollection(IReadOnlyCollection<T> collection)
                : base(collection)
            {
                this.collection = collection;
            }
        }

        private class CheckingList<T> : CheckingCollection<T>, IReadOnlyList<T>
        {
            private readonly IReadOnlyList<T> list;

            public T this[int index] => this.list[index];

            public CheckingList(IReadOnlyList<T> list)
                : base(list)
            {
                this.list = list;
            }
        }
    }
}


text:
package library.java7.option;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import library.java7.function.ExceptionalBlock;
import library.java7.function.ExceptionalSupplier;

public class Attempt {
  private List<Class<? extends Exception>> anticipatedExceptions;

  public Attempt() {
    anticipatedExceptions = new ArrayList<>();
  }

  public void anticipate(Class<? extends Exception> exception) {
    anticipatedExceptions.add(exception);
  }

  public <A> Option<A> attempt(ExceptionalSupplier<A> func) {
    try {
      return Option.wrap(func.get());
    } catch (Exception e) {
      for (Class<? extends Exception> anticipatedException : anticipatedExceptions) {
        if (anticipatedException == e.getClass())
          return new None<A>();
      }
      throw new AttemptException(e);
    }
  }

  public Option<Boolean> attempt(ExceptionalBlock block) {
    return attempt(new ExceptionalSupplier<Boolean>() {
      @Override
      public Boolean get() throws Exception { block.execute(); return true; }
    });
  }

  public static <A> Option<A> get(A[] arr, int index) {
    Attempt attempt = new Attempt();
    attempt.anticipate(ArrayIndexOutOfBoundsException.class);
    return attempt.attempt(new ExceptionalSupplier<A>() {
      @Override
      public A get() { return arr[index]; }
    });
  }

  public static <A> Option<A> get(List<A> list, int index) {
    Attempt attempt = new Attempt();
    attempt.anticipate(IndexOutOfBoundsException.class);
    return attempt.attempt(new ExceptionalSupplier<A>() {
      @Override
      public A get() { return list.get(index); }
    });
  }

  public static <A, B> Option<B> get(Map<A, B> map, A key) {
    return Option.wrap(map.get(key));
  }

  public static <A, B> Option<B> cast(A value, Class<B> toClass) {
    Attempt attempt = new Attempt();
    attempt.anticipate(ClassCastException.class);
    return attempt.attempt(new ExceptionalSupplier<B>() {
      @Override
      public B get() { return toClass.cast(value); }
    });
  }
}

class AttemptException extends RuntimeException {
  private static final long serialVersionUID = 1L;
  public AttemptException(Exception e) {
    super(e);
  }
}


text:
package org.foxbpm.engine.sqlsession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.foxbpm.engine.db.PersistentObject;
import org.foxbpm.engine.impl.agent.AgentDetailsEntity;
import org.foxbpm.engine.impl.agent.AgentEntity;
import org.foxbpm.engine.impl.entity.DeploymentEntity;
import org.foxbpm.engine.impl.entity.IdentityLinkEntity;
import org.foxbpm.engine.impl.entity.ProcessDefinitionEntity;
import org.foxbpm.engine.impl.entity.ProcessInstanceEntity;
import org.foxbpm.engine.impl.entity.ProcessOperatingEntity;
import org.foxbpm.engine.impl.entity.ResourceEntity;
import org.foxbpm.engine.impl.entity.RunningTrackEntity;
import org.foxbpm.engine.impl.entity.TaskEntity;
import org.foxbpm.engine.impl.entity.TokenEntity;
import org.foxbpm.engine.impl.entity.VariableInstanceEntity;

public class StatementMap {

	protected static Map<Class<?>,String>  insertStatements = new ConcurrentHashMap<Class<?>, String>();
	protected static Map<Class<?>,String>  updateStatements = new ConcurrentHashMap<Class<?>, String>();
	protected static Map<Class<?>,String>  deleteStatements = new ConcurrentHashMap<Class<?>, String>();
	protected static Map<Class<?>,String>  selectStatements = new ConcurrentHashMap<Class<?>, String>();
	static{

		insertStatements.put(ProcessInstanceEntity.class, "insertProcessInstance");
		insertStatements.put(TaskEntity.class, "insertTask");
		insertStatements.put(TokenEntity.class, "insertToken");
		insertStatements.put(DeploymentEntity.class, "insertDeployment");
		insertStatements.put(ProcessDefinitionEntity.class, "insertProcessDefinition");
		insertStatements.put(ResourceEntity.class, "insertResource");
		insertStatements.put(IdentityLinkEntity.class, "insertIdentityLink");
		insertStatements.put(VariableInstanceEntity.class, "insertVariable");
		insertStatements.put(AgentEntity.class, "insertAgent");
		insertStatements.put(AgentDetailsEntity.class, "insertAgentDetails");
		insertStatements.put(RunningTrackEntity.class, "insertRunningTrack");
		insertStatements.put(ProcessOperatingEntity.class, "insertProcessOperating");

		updateStatements.put(ProcessInstanceEntity.class, "updateProcessInstance");
		updateStatements.put(TaskEntity.class, "updateTask");
		updateStatements.put(TokenEntity.class, "updateToken");
		updateStatements.put(DeploymentEntity.class, "updateDeployment");
		updateStatements.put(ProcessDefinitionEntity.class, "updateProcessDefinition");
		updateStatements.put(ResourceEntity.class, "updateResource");
		updateStatements.put(VariableInstanceEntity.class, "updateVariable");
		updateStatements.put(AgentEntity.class, "updateAgentEntity");
		updateStatements.put(AgentDetailsEntity.class, "updateAgentDetailsEntity");
		updateStatements.put(ProcessOperatingEntity.class, "updateProcessOperatingById");

		selectStatements.put(ProcessInstanceEntity.class, "selectProcessInstanceById");
		selectStatements.put(TaskEntity.class, "selectTaskById");
		selectStatements.put(TokenEntity.class, "selectTokenById");
		selectStatements.put(DeploymentEntity.class, "selectDeploymentById");
		selectStatements.put(ProcessDefinitionEntity.class, "selectProcessDefinitionById");
		selectStatements.put(ResourceEntity.class, "selectResourceById");
		selectStatements.put(IdentityLinkEntity.class, "selectIdentityLinkById");
		selectStatements.put(VariableInstanceEntity.class, "selectVariableById");
		selectStatements.put(RunningTrackEntity.class, "selectRunningTrackByInstanceId");
		selectStatements.put(ProcessOperatingEntity.class, "selectProcessOperatingById");

	}
	public static String getInsertStatement(PersistentObject object) {
	    return insertStatements.get(object.getClass());
	}

	public static String getUpdateStatement(PersistentObject object) {
	    return updateStatements.get(object.getClass());
	}

	public static String getDeleteStatement(PersistentObject object) {
	    return deleteStatements.get(object.getClass());
	}

	public static String getSelectStatement(Class<?> object) {
		  return selectStatements.get(object);
	}
}


text:
package quasar.datagen

import slamdata.Predef.Option
import quasar.ejson.EJson
import quasar.sst.{PopulationSST, SST}

import fs2.Stream
import fs2.util.Suspendable
import matryoshka.{Corecursive, Recursive}
import scalaz.{\/, Equal, Order}
import scalaz.Scalaz._
import spire.algebra.{Field, IsReal, NRoot}
import spire.math.ConvertableFrom
import spire.random.{Gaussian, Generator}

object generate {
  object ejson {
    def apply[F[_]] = new PartiallyApplied[F]
    final class PartiallyApplied[F[_]] {
      def apply[J: Order, A: ConvertableFrom: Equal: Field: Gaussian: IsReal: NRoot](
          maxCollLen: A,
          sst: PopulationSST[J, A] \/ SST[J, A])(
          implicit
          F: Suspendable[F],
          JC: Corecursive.Aux[J, EJson],
          JR: Recursive.Aux[J, EJson])
          : Option[Stream[F, J]] =
        sst
          .fold(
            dist.population[J, A](maxCollLen, _),
            dist.sample[J, A](maxCollLen, _))
          .map(d => Stream.repeatEval(F.delay(d(Generator.rng))))
    }
  }
}


text:
'''
Created on Feb 18, 2014

@author: sean
'''
from __future__ import unicode_literals
import unittest
import mock
from binstar_client.scripts.cli import main
from binstar_client.tests.fixture import CLITestCase
from binstar_client.tests.urlmock import urlpatch
import json

class Test(CLITestCase):

    @urlpatch
    def test_whoami_anon(self, urls):

        user = urls.register(method='GET', path='/user', status=401)

        main(['--show-traceback', 'whoami'], False)
        self.assertIn('Anonymous User', self.stream.getvalue())

        user.assertCalled()

    @urlpatch
    def test_whoami(self, urls):

        content = json.dumps({'login': 'eggs', 'created_at':'1/2/2000'})
        user = urls.register(method='GET', path='/user', content=content)

        main(['--show-traceback', 'whoami'], False)
        self.assertIn('eggs', self.stream.getvalue())

        user.assertCalled()

if __name__ == '__main__':
    unittest.main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Gama.Socios.Wpf.Views
{
    /// <summary>
    /// Interaction logic for PersonasContentView.xaml
    /// </summary>
    public partial class SociosContentView : UserControl
    {
        public SociosContentView()
        {
            InitializeComponent();
        }
    }
}


text:
using namespace std;

#include "CWTime.h"
#include "CWThreadPool.h"

#include "_GenerateTmh.h"
#include "TestCWThreadPool.tmh"

#define MAX_THREAD_ID 0x10000

#define MAX_JOB_CNT 100000
#define DATA_CNT 1000

typedef struct _WORKER_THREAD_ARGS
{
    UINT uDataCnt;
    UINT * pData;
} WORKER_THREAD_ARGS;

volatile LONGLONG g_llSum = 0;
UINT * g_pThreadStatistics = NULL;

DWORD CALLBACK CrazyAdd( VOID * aArgs, OVERLAPPED * aOverlapped );

VOID TestThreadPoolIOCP()
{
    wprintf_s( L"\n========== TestThreadPoolIOCP() Enter ==========\n" );

    CWUtils::CThreadPoolIOCP manager;
    UINT uJobCnt = 0;

    g_pThreadStatistics = new ( std::nothrow ) UINT[MAX_THREAD_ID];
    if ( NULL == g_pThreadStatistics )
    {
        wprintf_s( L"Failed to allocate g_pThreadStatistics\n" );
        goto exit;
    }
    ZeroMemory( g_pThreadStatistics, sizeof( UINT ) * MAX_THREAD_ID );

    //Input worker count
    INT nRet = 0;
    UINT uWorkerCnt = 0;
    wprintf_s( L"Please input worker count: " );
    wscanf_s( L"%d", &uWorkerCnt, sizeof( uWorkerCnt ) );

    //Prepare common arguments between threads
    WORKER_THREAD_ARGS * args = new ( std::nothrow ) WORKER_THREAD_ARGS[MAX_JOB_CNT];
    ZeroMemory( args, sizeof( WORKER_THREAD_ARGS ) * MAX_JOB_CNT );
    for ( UINT i = 0; i < MAX_JOB_CNT; i++ )
    {
        args[i].pData = new ( std::nothrow ) UINT[DATA_CNT];
        if ( NULL != args[i].pData )
        {
            args[i].uDataCnt = DATA_CNT;
            ZeroMemory( args[i].pData, sizeof( UINT ) * DATA_CNT );
            for ( UINT j = 0; j < DATA_CNT; j++ )
            {
                args[i].pData[j] += i * j;
            }
            uJobCnt++;
        }
        else
        {
            break;
        }
    }
    wprintf_s( L"Total job count=%u\n", uJobCnt );

    //Start thread pool
    wprintf_s( L"Start thread pool\n" );
    if ( FALSE == manager.Start( uWorkerCnt, CrazyAdd, args ) )
    {
        wprintf_s( L"Failed to start thread pool. GetLastError()=%lu\n", GetLastError() );
        goto exit;
    }

    //Give new jobs
    wprintf_s( L"Dispatching jobs\n" );
    for ( UINT i = 0; i < uJobCnt; i++ )
    {
        manager.NotifyNewJob( (OVERLAPPED *)i );
    }
    wprintf_s( L"All jobs are dispatched\n" );

    //Wait some time for jobs to be done, or jobs will be cancelled if we call Stop() immediately
    wprintf_s( L"WaitAllJobs() return %d\n", manager.WaitAllJobs( INFINITE ) );
    manager.Stop();

    //Print the result and statistics
    wprintf_s( L"\n" );
    UINT uThreadCnt = 0;
    UINT uJobSolved = 0;
    for ( UINT i = 0; i < MAX_THREAD_ID; i++ )
    {
        if ( 0 != g_pThreadStatistics[i] )
        {
            wprintf_s( L"%2u. Thread 0x%04X processed %u requests\n", ++uThreadCnt, i, g_pThreadStatistics[i] );
            uJobSolved += g_pThreadStatistics[i];
        }
    }
    wprintf_s( L"g_llSum=%I64u\n", g_llSum );
    wprintf_s( L"Solved job count / Total job count = %u / %u (%.1lf%%)\n\n", uJobSolved, uJobCnt,
               (DOUBLE)uJobSolved * 100 / (DOUBLE)uJobCnt );

exit:
    if ( NULL != args )
    {
        for ( UINT i = 0; i < MAX_JOB_CNT; i++ )
        {
            if ( NULL != args[i].pData )
            {
                delete[] args[i].pData;
            }
            else
            {
                break;
            }
        }
        delete[] args;
    }
    if ( NULL != g_pThreadStatistics )
    {
        delete[] g_pThreadStatistics;
    }

    wprintf_s( L"\n========== TestThreadPoolIOCP() Leave ==========\n" );
}

INT wmain( INT aArgc, WCHAR * aArgv[] )
{
    WPP_INIT_TRACING( L"TestCWThreadPool" );
    DbgOut( INFO, DBG_TEST, "Enter" );
    for ( int i = 0; i < aArgc; i++ )
    {
        wprintf_s( L"aArgv[%d]=%ws\n", i, aArgv[i] );
    }
    wprintf_s( L"Start\n" );

    CWUtils::CStopWatch stopWatch;
    stopWatch.Start();

    do
    {
        TestThreadPoolIOCP();
    } while ( 0 );

    stopWatch.Stop();
    wprintf_s( L"%I64u micro-sec\n", stopWatch.GetTotalIntervalInMicro() );
    wprintf_s( L"End of the program\n" );
    DbgOut( INFO, DBG_TEST, "Leave" );
    WPP_CLEANUP();
    system( "pause" );
    return 0;
}

DWORD CALLBACK CrazyAdd( VOID * aArgs, OVERLAPPED * aOverlapped )
{
    WORKER_THREAD_ARGS * args = (WORKER_THREAD_ARGS *)aArgs;
    UINT uJobId = (UINT)aOverlapped;

    UINT64 uResult = 0;
    for ( UINT i = 0; i < args[uJobId].uDataCnt; i++ )
    {
        uResult += ( UINT64 )( (DOUBLE)args[uJobId].pData[i] * 1.5 );
    }

    //Users are responsible for freeing memory they allocated
    delete[] args[uJobId].pData;
    args[uJobId].pData = NULL;

    InterlockedExchangeAdd64( &g_llSum, (LONGLONG)uResult );
    InterlockedIncrement( (volatile LONG *)&g_pThreadStatistics[GetCurrentThreadId()] );

    return GetLastError();
}


text:
#include <FslBase/String/StringParseUtil.hpp>
#include <FslBase/Exceptions.hpp>
#include <FslBase/Log/Log.hpp>
#include <cassert>
#include <cerrno>
#include <cmath>
#include <cstring>
#include <climits>
#include <limits>

namespace Fsl
{
  namespace
  {
    uint32_t ParseUInt32(const char* const psz, const std::size_t startIndex, const std::size_t length)
    {
      if (psz == nullptr)
      {
        throw std::invalid_argument("psz can not be null");
      }

      const auto actualLength = strlen(psz);
      const auto endIndex = startIndex + length;
      if (endIndex > actualLength)
      {
        throw std::invalid_argument("startIndex or length out of bounds");
      }
      if (length < 1)
      {
        throw FormatException("array not in the correct format");
      }

      // Check the string contains a digit as expected
      const char* pszSrc = psz + startIndex;
      if ((pszSrc[0] >= '0' && pszSrc[0] <= '9') || (length >= 2 && pszSrc[0] == '+' && (pszSrc[1] >= '0' && pszSrc[1] <= '9')))
      {
        char* pEnd = nullptr;
        errno = 0;
        auto value = strtoul(pszSrc, &pEnd, 0);
        if ((value == ULONG_MAX && errno == ERANGE) || value > std::numeric_limits<uint32_t>::max())
        {
          throw OverflowException("The number is outside than the expected value range");
        }

        if (pEnd != (pszSrc + length))
        {
          throw FormatException("number not in the correct format");
        }

        return static_cast<uint32_t>(value);
      }
      throw FormatException("number not in the correct format");
    }

    int32_t ParseInt32(const char* const psz, const std::size_t startIndex, const std::size_t length)
    {
      if (psz == nullptr)
      {
        throw std::invalid_argument("psz can not be null");
      }

      const auto actualLength = strlen(psz);
      const auto endIndex = startIndex + length;
      if (endIndex > actualLength)
      {
        throw std::invalid_argument("startIndex or length out of bounds");
      }
      if (length < 1)
      {
        throw FormatException("array not in the correct format");
      }

      // Check the string contains a digit as expected
      const char* pszSrc = psz + startIndex;
      if ((pszSrc[0] >= '0' && pszSrc[0] <= '9') || (length >= 2 && (pszSrc[0] == '+' || pszSrc[0] == '-') && (pszSrc[1] >= '0' && pszSrc[1] <= '9')))
      {
        char* pEnd = nullptr;
        errno = 0;

        if (length >= 32)
        {
          throw std::invalid_argument("string is too long");
        }
        char tmpBuffer[32];
        for (std::size_t i = 0; i < length; ++i)
        {
          tmpBuffer[i] = psz[startIndex + i];
        }
        tmpBuffer[length] = 0;

        const auto value = strtol(tmpBuffer, &pEnd, 0);
        if (((value == LONG_MIN || value == LONG_MAX) && errno == ERANGE) || value < std::numeric_limits<int32_t>::min() ||
            value > std::numeric_limits<int32_t>::max())
        {
          throw OverflowException("The number is outside than the expected value range");
        }

        if (pEnd != (tmpBuffer + length))
        {
          throw FormatException("number not in the correct format");
        }

        return static_cast<int32_t>(value);
      }
      throw FormatException("number not in the correct format");
    }

    double ParseDouble(const char* const psz, const std::size_t startIndex, const std::size_t length)
    {
      if (psz == nullptr)
      {
        throw std::invalid_argument("psz can not be null");
      }

      const auto actualLength = strlen(psz);
      const auto endIndex = startIndex + length;
      if (endIndex > actualLength)
      {
        throw std::invalid_argument("startIndex or length out of bounds");
      }
      if (length < 1)
      {
        throw FormatException("array not in the correct format");
      }

      // Check the string doesn't start with a white space
      const char* pszSrc = psz + startIndex;
      if (pszSrc[0] != ' ')
      {
        char* pEnd = nullptr;
        errno = 0;
        const double value = strtod(pszSrc, &pEnd);
        if (value == HUGE_VAL && errno == ERANGE)
        {
          throw OverflowException("The number is outside than the expected value range");
        }

        if (pEnd != (pszSrc + length))
        {
          throw FormatException("number not in the correct format");
        }

        return value;
      }
      throw FormatException("number not in the correct format");
    }

    template <typename T>
    std::size_t DoParseArray(T* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex, const std::size_t length)
    {
      if (psz == nullptr)
      {
        throw std::invalid_argument("psz can not be null");
      }

      const auto actualLength = strlen(psz);
      const auto endIndex = startIndex + length;
      if (endIndex > actualLength)
      {
        throw std::invalid_argument("startIndex or length out of bounds");
      }
      if (length < 1)
      {
        throw FormatException("array not in the correct format");
      }

      const char* pszCurrent = psz + startIndex;
      const char* const pszEnd = pszCurrent + length;
      if (length < 3 || *pszCurrent != '[' || *(pszEnd - 1) != ']')
      {
        throw FormatException("array not in the correct format");
      }

      ++pszCurrent;
      std::size_t index = 0;
      while (pszCurrent < pszEnd && index < dstLength)
      {
        const auto count = strcspn(pszCurrent, ",]");
        if (index >= dstLength)
        {
          throw FormatException("array not in the correct format");
        }
        const auto charactersConsumed = StringParseUtil::Parse(*(pDst + index), pszCurrent, 0, count);
        assert(charactersConsumed == count);
        pszCurrent += charactersConsumed + 1;
        ++index;
      }

      if (pszCurrent != pszEnd)
      {
        throw FormatException("array not in the correct format");
      }
      return index;
    }
  }

  std::size_t StringParseUtil::Parse(bool& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(uint8_t& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(int8_t& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(uint16_t& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(int16_t& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(uint32_t& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(int32_t& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  // int StringParseUtil::Parse(uint64_t& rResult, const char*const psz)
  //{
  // if (psz == nullptr)
  //  throw std::invalid_argument("psz can not be null");
  // return Parse(rResult, psz, 0, strlen(psz));
  //}

  // int StringParseUtil::Parse(int64_t& rResult, const char*const psz)
  //{
  // if (psz == nullptr)
  //  throw std::invalid_argument("psz can not be null");
  // return Parse(rResult, psz, 0, strlen(psz));
  //}

  std::size_t StringParseUtil::Parse(float& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(double& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(Point2& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(Rectangle& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return Parse(rResult, psz, 0, strlen(psz));
  }

  std::size_t StringParseUtil::Parse(bool& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    rResult = false;
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }

    const auto actualLength = strlen(psz);
    const char* pszSrc = psz + startIndex;
    int charactersConsumed = 0;

    if ((startIndex + length) > actualLength)
    {
      throw std::invalid_argument("startIndex or length out of bounds");
    }
    if (length < 1)
    {
      throw FormatException("length too small to contain a bool");
    }

    if (length == 4 && strncmp(pszSrc, "true", 4) == 0)
    {
      rResult = true;
      charactersConsumed = 4;
    }
    else if (length == 1 && strncmp(pszSrc, "1", 1) == 0)
    {
      rResult = true;
      charactersConsumed = 1;
    }
    else if (length == 1 && strncmp(pszSrc, "0", 1) == 0)
    {
      rResult = false;
      charactersConsumed = 1;
    }
    else if (length == 5 && strncmp(pszSrc, "false", 5) == 0)
    {
      rResult = false;
      charactersConsumed = 5;
    }
    else
    {
      throw FormatException("not a valid 'bool' string");
    }
    return charactersConsumed;
  }

  std::size_t StringParseUtil::Parse(uint8_t& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    const uint32_t result = ParseUInt32(psz, startIndex, length);
    if (result > std::numeric_limits<uint8_t>::max())
    {
      throw OverflowException("overflow");
    }
    rResult = static_cast<uint8_t>(result);
    return length;
  }

  std::size_t StringParseUtil::Parse(int8_t& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    const int32_t result = ParseInt32(psz, startIndex, length);
    if (result < std::numeric_limits<int8_t>::min() || result > std::numeric_limits<int8_t>::max())
    {
      throw OverflowException("overflow");
    }
    rResult = static_cast<int8_t>(result);
    return length;
  }

  std::size_t StringParseUtil::Parse(uint16_t& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    const uint32_t result = ParseUInt32(psz, startIndex, length);
    if (result > std::numeric_limits<uint16_t>::max())
    {
      throw OverflowException("overflow");
    }
    rResult = static_cast<uint16_t>(result);
    return length;
  }

  std::size_t StringParseUtil::Parse(int16_t& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    const int32_t result = ParseInt32(psz, startIndex, length);
    if (result < std::numeric_limits<int16_t>::min() || result > std::numeric_limits<int16_t>::max())
    {
      throw OverflowException("overflow");
    }
    rResult = static_cast<int16_t>(result);
    return length;
  }

  std::size_t StringParseUtil::Parse(uint32_t& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    rResult = ParseUInt32(psz, startIndex, length);
    return length;
  }

  std::size_t StringParseUtil::Parse(int32_t& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    rResult = ParseInt32(psz, startIndex, length);
    return length;
  }

  // int StringParseUtil::Parse(uint64_t& rResult, const char*const psz, const std::size_t startIndex, const std::size_t length)
  //{
  //  throw NotImplementedException();
  //}

  // int StringParseUtil::Parse(int64_t& rResult, const char*const psz, const std::size_t startIndex, const std::size_t length)
  //{
  //  throw NotImplementedException();
  //}

  std::size_t StringParseUtil::Parse(float& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    const double result = ParseDouble(psz, startIndex, length);
    if (result < std::numeric_limits<float>::lowest() || result > std::numeric_limits<float>::max())
    {
      throw OverflowException("overflow");
    }
    rResult = static_cast<float>(result);
    return length;
  }

  std::size_t StringParseUtil::Parse(double& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    rResult = ParseDouble(psz, startIndex, length);
    return length;
  }

  std::size_t StringParseUtil::Parse(Point2& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    int32_t values[2]{};
    StringParseArrayResult res = ParseArray(values, 2, psz, startIndex, length);
    if (res.ArrayEntries != 2)
    {
      throw FormatException("Point2 not in the correct format");
    }
    rResult = Point2(values[0], values[1]);
    return res.CharactersConsumed;
  }

  std::size_t StringParseUtil::Parse(Rectangle& rResult, const char* const psz, const std::size_t startIndex, const std::size_t length)
  {
    int32_t values[4]{};
    StringParseArrayResult res = ParseArray(values, 4, psz, startIndex, length);
    if (res.ArrayEntries != 4)
    {
      throw FormatException("Rectangle not in the correct format");
    }
    if (values[2] < 0 || values[3] < 0)
    {
      throw FormatException("Rectangle not in the correct format, width and height can not be negative");
    }
    rResult = Rectangle(values[0], values[1], values[2], values[3]);
    return res.CharactersConsumed;
  }

  const StringParseArrayResult StringParseUtil::ParseArray(bool* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  const StringParseArrayResult StringParseUtil::ParseArray(uint8_t* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  const StringParseArrayResult StringParseUtil::ParseArray(int8_t* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  const StringParseArrayResult StringParseUtil::ParseArray(uint16_t* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  const StringParseArrayResult StringParseUtil::ParseArray(int16_t* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  const StringParseArrayResult StringParseUtil::ParseArray(uint32_t* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  const StringParseArrayResult StringParseUtil::ParseArray(int32_t* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  // const StringParseArrayResult StringParseUtil::ParseArray(uint64_t* pDst, const std::size_t dstLength, const char*const psz)
  //{
  // if (pDst == nullptr)
  //  throw std::invalid_argument("pDst can not be null");
  // if (psz == nullptr)
  //  throw std::invalid_argument("psz can not be null");
  // return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  //}

  // const StringParseArrayResult StringParseUtil::ParseArray(int64_t* pDst, const std::size_t dstLength, const char*const psz)
  //{
  // if (pDst == nullptr)
  //  throw std::invalid_argument("pDst can not be null");
  // if (psz == nullptr)
  //  throw std::invalid_argument("psz can not be null");
  // return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  //}

  const StringParseArrayResult StringParseUtil::ParseArray(float* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  const StringParseArrayResult StringParseUtil::ParseArray(double* pDst, const std::size_t dstLength, const char* const psz)
  {
    if (pDst == nullptr)
    {
      throw std::invalid_argument("pDst can not be null");
    }
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }
    return ParseArray(pDst, dstLength, psz, 0, strlen(psz));
  }

  StringParseArrayResult StringParseUtil::ParseArray(bool* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  StringParseArrayResult StringParseUtil::ParseArray(uint8_t* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  StringParseArrayResult StringParseUtil::ParseArray(int8_t* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  StringParseArrayResult StringParseUtil::ParseArray(uint16_t* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  StringParseArrayResult StringParseUtil::ParseArray(int16_t* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  StringParseArrayResult StringParseUtil::ParseArray(uint32_t* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  StringParseArrayResult StringParseUtil::ParseArray(int32_t* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  // StringParseArrayResult StringParseUtil::ParseArray(uint64_t* pDst, const std::size_t dstLength, const char*const psz, const std::size_t
  // startIndex, const std::size_t length)
  //{
  // const int arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
  // return StringParseArrayResult(length, arrayEntries);
  //}

  // StringParseArrayResult StringParseUtil::ParseArray(int64_t* pDst, const std::size_t dstLength, const char*const psz, const std::size_t
  // startIndex, const std::size_t length)
  //{
  // const int arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
  // return StringParseArrayResult(length, arrayEntries);
  //}

  StringParseArrayResult StringParseUtil::ParseArray(float* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  StringParseArrayResult StringParseUtil::ParseArray(double* pDst, const std::size_t dstLength, const char* const psz, const std::size_t startIndex,
                                                     const std::size_t length)
  {
    const auto arrayEntries = DoParseArray(pDst, dstLength, psz, startIndex, length);
    return StringParseArrayResult(length, arrayEntries);
  }

  bool StringParseUtil::TryParse(int32_t& rValue, const char* const psz, const std::size_t startIndex, const std::size_t length, const int32_t radix)
  {
    rValue = 0;
    if (psz == nullptr)
    {
      FSLLOG_DEBUG_WARNING("psz can not be null");
      return false;
    }

    const auto actualLength = strlen(psz);
    const auto endIndex = startIndex + length;
    if (endIndex > actualLength)
    {
      FSLLOG_DEBUG_WARNING("startIndex or length out of bounds");
      return false;
    }
    if (length < 1)
    {
      FSLLOG_DEBUG_WARNING("length too small to contain a int32");
      return false;
    }

    // Check the string contains a digit as expected
    const char* pszSrc = psz + startIndex;

    bool ch1Extended = false;
    bool ch2Extended = false;
    if (radix > 10)
    {
      const int32_t radixAbove10 = radix - 10;
      ch1Extended = (pszSrc[0] >= 'a' && (pszSrc[0] - 'a') < radixAbove10) || (pszSrc[0] >= 'A' && (pszSrc[0] - 'A') < radixAbove10);
      ch2Extended = length >= 2 && ((pszSrc[1] >= 'a' && (pszSrc[1] - 'a') < radixAbove10) || (pszSrc[1] >= 'A' && (pszSrc[1] - 'A') < radixAbove10));
    }

    if ((pszSrc[0] >= '0' && (pszSrc[0] <= '9' || ch1Extended)) ||
        (length >= 2 && (pszSrc[0] == '+' || pszSrc[0] == '-') && (pszSrc[1] >= '0' && (pszSrc[1] <= '9' || ch2Extended))))
    {
      char* pEnd = nullptr;
      errno = 0;

      if (length >= 32)
      {
        FSLLOG_DEBUG_WARNING("string is too long");
        return false;
      }
      char tmpBuffer[32];
      for (std::size_t i = 0; i < length; ++i)
      {
        tmpBuffer[i] = psz[startIndex + i];
      }
      tmpBuffer[length] = 0;

      const auto value = strtol(tmpBuffer, &pEnd, radix);
      if (((value == LONG_MIN || value == LONG_MAX) && errno == ERANGE) || value < std::numeric_limits<int32_t>::min() ||
          value > std::numeric_limits<int32_t>::max())
      {
        return false;
      }

      if (pEnd != (tmpBuffer + length))
      {
        return false;
      }

      rValue = static_cast<int32_t>(value);
      return true;
    }
    return false;
  }

  std::size_t StringParseUtil::ParseTime(std::chrono::seconds& rResult, const char* const psz)
  {
    if (psz == nullptr)
    {
      throw std::invalid_argument("psz can not be null");
    }

    // 012345678
    // HH:MM:SS
    const std::size_t expectedLength = 8;
    if (strlen(psz) != expectedLength || psz[2] != ':' || psz[5] != ':')
    {
      throw FormatException("time not in the expected HH:MM:SS format");
    }

    const uint32_t hh = ParseUInt32(psz, 0, 2);
    const uint32_t mm = ParseUInt32(psz, 3, 2);
    const uint32_t ss = ParseUInt32(psz, 6, 2);

    if (ss >= 60 || mm >= 60 || hh > 24)
    {
      throw FormatException("number not in the correct format");
    }

    rResult = std::chrono::seconds((hh * 60 * 60) + (mm * 60) + ss);
    return expectedLength;
  }
}


text:
package com.couchbase.lite.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class NativeLibraryUtils {
    private static final Map<String, Boolean> LOADED_LIBRARIES = new HashMap<String, Boolean>();

    public static boolean loadLibrary(String libraryName) {
        if (LOADED_LIBRARIES.containsKey(libraryName))
            return true;

        try {
            File libraryFile;
            String libraryPath = getConfiguredLibraryPath(libraryName);
            if (libraryPath != null)
                libraryFile = new File(libraryPath);
            else
                libraryFile = extractLibrary(libraryName);

            if (libraryFile != null) {
                System.load(libraryFile.getAbsolutePath());
                LOADED_LIBRARIES.put(libraryName, true);
            } else {
                Log.e(Log.TAG, "Cannot find library: " + libraryName);
                return false;
            }
        } catch (Exception e) {
            Log.e(Log.TAG, "Error loading library: " + libraryName, e);
            return false;
        }

        return true;
    }

    private static String getConfiguredLibraryPath(String libraryName) {
        String key = String.format(Locale.ENGLISH, "com.couchbase.lite.lib.%s.path", libraryName);
        return System.getProperty(key);
    }

    private static String getLibraryFullName(String libraryName) {
        String name = System.mapLibraryName(libraryName);
        // Workaround discrepancy issue between OSX Java6 (.jnilib)
        // and Java7 (.dylib) native library file extension.
        if (name.endsWith(".jnilib")) {
            name = name.replace(".jnilib", ".dylib");
        }
        return name;
    }

    private static File extractLibrary(String libraryName) throws IOException {
        String libraryResourcePath = getLibraryResourcePath(libraryName);
        String targetFolder = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
        File targetFile = new File(targetFolder, getLibraryFullName(libraryName));

        // If the target already exists, and it's unchanged, then use it, otherwise delete it and
        // it will be replaced.
        if (targetFile.exists()) {
            // Remove old native library file:
            if (!targetFile.delete()) {
                // If we can't remove the old library file then log a warning and try to use it:
                Log.w(Log.TAG, "Failed to delete existing library file: " + targetFile.getAbsolutePath());
                return targetFile;
            }
        }

        // Extract the library to the target directory:
        InputStream libraryReader = NativeLibraryUtils.class.getResourceAsStream(libraryResourcePath);
        if (libraryReader == null) {
            System.err.println("Library not found: " + libraryResourcePath);
            return null;
        }

        FileOutputStream libraryWriter = new FileOutputStream(targetFile);
        try {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = libraryReader.read(buffer)) != -1) {
                libraryWriter.write(buffer, 0, bytesRead);
            }
        } finally {
            libraryWriter.close();
            libraryReader.close();
        }

        // On non-windows systems set up permissions for the extracted native library.
        if (!System.getProperty("os.name").toLowerCase().contains("windows")) {
            try {
                Runtime.getRuntime().exec(
                        new String[]{"chmod", "755", targetFile.getAbsolutePath()}).waitFor();
            } catch (Throwable e) {
                Log.e(Log.TAG, "Error executing 'chmod 755' on extracted native library", e);
            }
        }
        return targetFile;
    }

    private static String getLibraryResourcePath(String libraryName) {
        // Root native folder.
        String path = "/native";

        // OS part of path.
        String osName = System.getProperty("os.name");
        if (osName.contains("Linux")) {
            path += "/linux";
        } else if (osName.contains("Mac")) {
            path += "/osx";
        } else if (osName.contains("Windows")) {
            path += "/windows";
        } else {
            path += '/' + osName.replaceAll("\\W", "").toLowerCase();
        }

        // Architecture part of path.
        String archName = System.getProperty("os.arch");
        archName = archName.replaceAll("\\W", "");
        archName = archName.replace("-", "_");
        path += '/' + archName;

        // Platform specific name part of path.
        path += '/' + getLibraryFullName(libraryName);
        return path;
    }
}


text:
class UsersController < ApplicationController
  before_action :authenticate_user!

  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
    unless @user == current_user
      redirect_to root_path, :alert => "Access denied."
    end
  end

end


text:
#if _JHC_GC == _JHC_GC_JGC

#ifdef JHC_HEADER

struct s_arena;
struct s_cache;
static void *s_alloc(gc_t gc, struct s_cache *sc) A_UNUSED;
static struct s_cache *find_cache(struct s_cache **rsc, struct s_arena *arena,
                                  unsigned short size, unsigned short num_ptrs) A_UNUSED;
static bool s_set_used_bit(void *val) A_UNUSED;
static void clear_used_bits(struct s_arena *arena) A_UNUSED;

#define S_BLOCK(val) ((struct s_block *)((uintptr_t)(val) & ~ (BLOCK_SIZE - 1)))
#define BLOCK_SIZE     (1UL << 12)
#define MEGABLOCK_SIZE (1UL << 20)

#else

#include "sys/bitarray.h"
#include "sys/queue.h"

struct s_arena {
        struct s_megablock *current_megablock;
        SLIST_HEAD(, s_block) free_blocks;
        unsigned block_used;
        unsigned block_threshold;
        SLIST_HEAD(, s_cache) caches;
        SLIST_HEAD(, s_megablock) megablocks;
};

struct s_megablock {
        void *base;
        unsigned next_free;
        SLIST_ENTRY(s_megablock) next;
};

struct s_block_info {
        unsigned char color;
        unsigned char size;
        unsigned char num_ptrs;
        unsigned char flags;
};

struct s_block {
        SLIST_ENTRY(s_block) link;
        struct s_block_info pi;
        unsigned short num_free;
        unsigned short next_free;
        bitarray_t used[];
};

struct s_cache {
        SLIST_ENTRY(s_cache) next;
        SLIST_HEAD(, s_block) blocks;
        SLIST_HEAD(, s_block) full_blocks;
        struct s_block_info pi;
        unsigned short num_entries;
        struct s_arena *arena;
};

/* This finds a bit that isn't set, sets it, then returns its index.  It
 * assumes that a bit is available to be found, otherwise it goes into an
 * infinite loop. */

static unsigned
bitset_find_free(unsigned *next_free, int n, bitarray_t ba[static n])
{
        assert(*next_free < (unsigned)n);
        unsigned i = *next_free;
        do {
                int o = __builtin_ffsl(~ba[i]);
                if (__predict_true(o)) {
                        ba[i] |= (1UL << (o - 1));
                        *next_free = i;
                        return (i * BITS_PER_UNIT + (o - 1));
                }
                i = (i + 1) % n;
                assert(i != *next_free);
        } while (1);
}

struct s_megablock *
s_new_megablock(struct s_arena *arena)
{
        struct s_megablock *mb = malloc(sizeof(*mb));
#if defined(__WIN32__)
        mb->base = _aligned_malloc(MEGABLOCK_SIZE, BLOCK_SIZE);
        int ret = !mb->base;
#elif defined(__ARM_EABI__)
        mb->base = memalign(BLOCK_SIZE, MEGABLOCK_SIZE);
        int ret = !mb->base;
#elif (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <  1060)
        assert(sysconf(_SC_PAGESIZE) == BLOCK_SIZE);
        mb->base = valloc(MEGABLOCK_SIZE);
        int ret = !mb->base;
#else
        int ret = posix_memalign(&mb->base, BLOCK_SIZE, MEGABLOCK_SIZE);
#endif
        if (ret != 0) {
                fprintf(stderr, "Unable to allocate memory for megablock\n");
                abort();
        }
        VALGRIND_MAKE_MEM_NOACCESS(mb->base, MEGABLOCK_SIZE);
        //VALGRIND_FREELIKE_BLOCK(mb->base,0);
        mb->next_free = 0;
        return mb;
}

/* block allocator */

static struct s_block *
get_free_block(gc_t gc, struct s_arena *arena)
{
        arena->block_used++;
        if (__predict_true(SLIST_FIRST(&arena->free_blocks))) {
                struct s_block *pg = SLIST_FIRST(&arena->free_blocks);
                SLIST_REMOVE_HEAD(&arena->free_blocks, link);
                return pg;
        } else {
                if ((arena->block_used >= arena->block_threshold)) {
                        gc_perform_gc(gc);
                        // if we are still using 80% of the heap after a gc, raise the threshold.
                        if (__predict_false
                            ((unsigned)arena->block_used * 10 >=
                             arena->block_threshold * 9)) {
                                arena->block_threshold *= 2;
                        }
                }
                if (__predict_false(!arena->current_megablock))
                        arena->current_megablock = s_new_megablock(arena);
                struct s_megablock *mb = arena->current_megablock;
                struct s_block *pg = mb->base + BLOCK_SIZE * mb->next_free;
                mb->next_free++;
                if (mb->next_free == MEGABLOCK_SIZE / BLOCK_SIZE) {
                        SLIST_INSERT_HEAD(&arena->megablocks, mb, next);
                        arena->current_megablock = NULL;
                }
                VALGRIND_MAKE_MEM_UNDEFINED(pg, sizeof(struct s_block));
                pg->num_free = 0;
                return pg;
        }
}

static void
s_cleanup_blocks(struct s_arena *arena)
{
        struct s_cache *sc = SLIST_FIRST(&arena->caches);
        for (; sc; sc = SLIST_NEXT(sc, next)) {
                // 'best' keeps track of the block with the fewest free spots
                // and percolates it to the front, effectively a single pass
                // of a bubblesort to help combat fragmentation. It does
                // not increase the complexity of the cleanup algorithm as
                // we had to scan every block anyway, but over many passes
                // of the GC it will eventually result in a more sorted list
                // than would occur by chance.
                struct s_block *best = NULL;
                int free_best = 4096;
                struct s_block *pg = SLIST_FIRST(&sc->blocks);
                struct s_block *fpg = SLIST_FIRST(&sc->full_blocks);
                SLIST_INIT(&sc->blocks);
                SLIST_INIT(&sc->full_blocks);
                if (!pg) {
                        pg = fpg;
                        fpg = NULL;
                }
                while (pg) {
                        struct s_block *npg = SLIST_NEXT(pg, link);
                        if (__predict_false(pg->num_free == 0)) {
                                SLIST_INSERT_HEAD(&sc->full_blocks, pg, link);
                        } else if (__predict_true(pg->num_free == sc->num_entries)) {
                                arena->block_used--;
                                VALGRIND_MAKE_MEM_NOACCESS((char *)pg +
                                                           sizeof(struct
                                                                  s_block),
                                                           BLOCK_SIZE -
                                                           sizeof(struct
                                                                  s_block));
                                SLIST_INSERT_HEAD(&arena->free_blocks, pg,
                                                  link);
                        } else {
                                if (!best) {
                                        free_best = pg->num_free;
                                        best = pg;
                                } else {
                                        if (pg->num_free < free_best) {
                                                struct s_block *tmp = best;
                                                best = pg;
                                                pg = tmp;
                                                free_best = pg->num_free;
                                        }
                                        SLIST_INSERT_HEAD(&sc->blocks, pg,
                                                          link);
                                }
                        }
                        if (!npg && fpg) {
                                pg = fpg;
                                fpg = NULL;
                        } else
                                pg = npg;
                }
                if (best)
                        SLIST_INSERT_HEAD(&sc->blocks, best, link);
        }
}

inline static void
clear_block_used_bits(unsigned num_entries, struct s_block *pg)
{
        pg->num_free = num_entries;
        memset(pg->used, 0,
               BITARRAY_SIZE_IN_BYTES(num_entries) - sizeof(pg->used[0]));
        int excess = num_entries % BITS_PER_UNIT;
        pg->used[BITARRAY_SIZE(num_entries) - 1] = ~((1UL << excess) - 1);
#if JHC_VALGRIND
        unsigned header =
                sizeof(struct s_block) + BITARRAY_SIZE_IN_BYTES(num_entries);
        VALGRIND_MAKE_MEM_NOACCESS((char *)pg + header, BLOCK_SIZE - header);
#endif
}

static void *
s_alloc(gc_t gc, struct s_cache *sc)
{
        struct s_block *pg = SLIST_FIRST(&sc->blocks);
        if (__predict_false(!pg)) {
                pg = get_free_block(gc, sc->arena);
                VALGRIND_MAKE_MEM_NOACCESS(pg, BLOCK_SIZE);
                VALGRIND_MAKE_MEM_DEFINED(pg, sizeof(struct s_block));
                if (sc->num_entries != pg->num_free)
                        VALGRIND_MAKE_MEM_UNDEFINED((char *)pg->used,
                                                    BITARRAY_SIZE_IN_BYTES
                                                    (sc->num_entries));
                else
                        VALGRIND_MAKE_MEM_DEFINED((char *)pg->used,
                                                  BITARRAY_SIZE_IN_BYTES
                                                  (sc->num_entries));
                assert(pg);
                pg->pi = sc->pi;
                pg->next_free = 0;
                SLIST_INSERT_HEAD(&sc->blocks, pg, link);
                if (sc->num_entries != pg->num_free)
                        clear_block_used_bits(sc->num_entries, pg);
                pg->used[0] = 1;        //set the first bit
                pg->num_free = sc->num_entries - 1;
                return (uintptr_t *) pg + pg->pi.color;
        } else {
                __builtin_prefetch(pg->used, 1);
                pg->num_free--;
                unsigned next_free = pg->next_free;
                unsigned found =
                        bitset_find_free(&next_free, BITARRAY_SIZE(sc->num_entries),
                                         pg->used);
                pg->next_free = next_free;
                void *val =
                        (uintptr_t *) pg + pg->pi.color + found * pg->pi.size;
                if (__predict_false(0 == pg->num_free)) {
                        assert(pg == SLIST_FIRST(&sc->blocks));
                        SLIST_REMOVE_HEAD(&sc->blocks, link);
                        SLIST_INSERT_HEAD(&sc->full_blocks, pg, link);
                }
                assert(S_BLOCK(val) == pg);
                //printf("s_alloc: val: %p s_block: %p size: %i color: %i found: %i num_free: %i\n", val, pg, pg->pi.size, pg->pi.color, found, pg->num_free);
                return val;
        }
}

/*
static void
s_free(void *val)
{
        assert(val);
        struct s_block *pg = s_block(val);
        unsigned int offset = ((uintptr_t *)val - (uintptr_t *)pg) - pg->pi.color;
//        printf("s_free:  val: %p s_block: %p size: %i color: %i num_free: %i offset: %i bit: %i\n", val, pg, pg->pi.size, pg->pi.color, pg->num_free, offset, offset/pg->pi.size);
        assert(BIT_VALUE(pg->used,offset/(pg->pi.size)));
        BIT_UNSET(pg->used,offset/(pg->pi.size));
        pg->num_free++;
}
*/

static struct s_cache *
new_cache(struct s_arena *arena, unsigned short size, unsigned short num_ptrs)
{
        struct s_cache *sc = malloc(sizeof(*sc));
        sc->arena = arena;
        sc->pi.size = size;
        sc->pi.num_ptrs = num_ptrs;
        sc->pi.flags = 0;
        size_t excess = BLOCK_SIZE - sizeof(struct s_block);
        sc->num_entries = (8 * excess) / (8 * sizeof(uintptr_t) * size + 1) - 1;
        //sc->num_entries = (8*excess) / (8*size*sizeof(uintptr_t) + 1);
        sc->pi.color =
                (sizeof(struct s_block) + BITARRAY_SIZE_IN_BYTES(sc->num_entries) +
                 sizeof(uintptr_t) - 1) / sizeof(uintptr_t);
        SLIST_INIT(&sc->blocks);
        SLIST_INIT(&sc->full_blocks);
        SLIST_INSERT_HEAD(&arena->caches, sc, next);
        //print_cache(sc);
        return sc;
}

// clear all used bits, must be followed by a marking phase.
static void
clear_used_bits(struct s_arena *arena)
{
        struct s_cache *sc = SLIST_FIRST(&arena->caches);
        for (; sc; sc = SLIST_NEXT(sc, next)) {
                struct s_block *pg = SLIST_FIRST(&sc->blocks);
                struct s_block *fpg = SLIST_FIRST(&sc->full_blocks);
                do {
                        for (; pg; pg = SLIST_NEXT(pg, link))
                                clear_block_used_bits(sc->num_entries, pg);
                        pg = fpg;
                        fpg = NULL;
                } while (pg);
        }
}

// set a used bit. returns true if the
// tagged node should be scanned by the GC.
// this happens when the used bit was not previously set
// and the node contains internal pointers.

static bool
s_set_used_bit(void *val)
{
        assert(val);
        struct s_block *pg = S_BLOCK(val);
        unsigned int offset =
                ((uintptr_t *) val - (uintptr_t *) pg) - pg->pi.color;
        if (__predict_true(BIT_IS_UNSET(pg->used, offset / pg->pi.size))) {
                BIT_SET(pg->used, offset / pg->pi.size);
                pg->num_free--;
                return (bool) pg->pi.num_ptrs;
        }
        return false;
}

static struct s_cache *
find_cache(struct s_cache **rsc, struct s_arena *arena, unsigned short size,
           unsigned short num_ptrs)
{
        if (__predict_true(rsc && *rsc))
                return *rsc;
        struct s_cache *sc = SLIST_FIRST(&arena->caches);
        for (; sc; sc = SLIST_NEXT(sc, next)) {
                if (sc->pi.size == size && sc->pi.num_ptrs == num_ptrs)
                        goto found;
        }
        sc = new_cache(arena, size, num_ptrs);
found:
        if (rsc)
                *rsc = sc;
        return sc;
}

struct s_arena *
new_arena(void)
{
        struct s_arena *arena = malloc(sizeof(struct s_arena));
        SLIST_INIT(&arena->caches);
        SLIST_INIT(&arena->free_blocks);
        SLIST_INIT(&arena->megablocks);
        arena->block_used = 0;
        arena->block_threshold = 8;
        arena->current_megablock = NULL;
        return arena;
}

void
print_cache(struct s_cache *sc)
{
        fprintf(stderr, "num_entries: %i\n", (int)sc->num_entries);
//        printf("  entries: %i words\n",(int)(sc->num_entries*sc->pi.size));
        fprintf(stderr, "  header: %lu bytes\n",
                sizeof(struct s_block) +
                BITARRAY_SIZE_IN_BYTES(sc->num_entries));
        fprintf(stderr, "  size: %i words\n", (int)sc->pi.size);
//        printf("  color: %i words\n",(int)sc->pi.color);
        fprintf(stderr, "  nptrs: %i words\n", (int)sc->pi.num_ptrs);
//        printf("  end: %i bytes\n",(int)(sc->pi.color+ sc->num_entries*sc->pi.size)*sizeof(uintptr_t));
        fprintf(stderr, "%20s %9s %9s %s\n", "block", "num_free", "next_free",
                "status");
        struct s_block *pg;
        SLIST_FOREACH(pg, &sc->blocks, link) {
                fprintf(stderr, "%20p %9i %9i %c\n", pg, pg->num_free,
                        pg->next_free, 'P');
        }
        fprintf(stderr, "  full_blocks:\n");
        SLIST_FOREACH(pg, &sc->full_blocks, link) {
                fprintf(stderr, "%20p %9i %9i %c\n", pg, pg->num_free,
                        pg->next_free, 'F');
        }
}

#endif
#endif


text:
<?php

namespace ONGR\FilterManagerBundle\Filter\Helper;

/**
 * This trait defines methods for Elasticsearch field value aware filters.
 */
trait RequestFieldAwareTrait
{
    /**
     * @var string
     */
    private $requestField;

    /**
     * @return string
     */
    public function getRequestField()
    {
        return $this->requestField;
    }

    /**
     * @param string $requestField
     */
    public function setRequestField($requestField)
    {
        $this->requestField = $requestField;
    }
}


text:
package org.apache.commons.math3.distribution;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.exception.NotANumberException;
import org.apache.commons.math3.exception.NotFiniteNumberException;
import org.apache.commons.math3.exception.NotPositiveException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.Well19937c;
import org.apache.commons.math3.util.Pair;

/**
 *
Implementation of a real-valued {@link EnumeratedDistribution}.
 *
 *
Values with zero-probability are allowed but they do not extend the
 * support.

 * Duplicate values are allowed. Probabilities of duplicate values are combined
 * when computing cumulative probabilities and statistics.

 *
 * @version $Id: EnumeratedRealDistribution.java 1566274 2014-02-09 11:21:28Z tn $
 * @since 3.2
 */
public class EnumeratedRealDistribution extends AbstractRealDistribution {

    /** Serializable UID. */
    private static final long serialVersionUID = 20130308L;

    /**
     * {@link EnumeratedDistribution} (using the {@link Double} wrapper)
     * used to generate the pmf.
     */
    protected final EnumeratedDistribution<Double> innerDistribution;

    /**
     * Create a discrete distribution using the given probability mass function
     * enumeration.
     *
     * @param singletons array of random variable values.
     * @param probabilities array of probabilities.
     * @throws DimensionMismatchException if
     * {@code singletons.length != probabilities.length}
     * @throws NotPositiveException if any of the probabilities are negative.
     * @throws NotFiniteNumberException if any of the probabilities are infinite.
     * @throws NotANumberException if any of the probabilities are NaN.
     * @throws MathArithmeticException all of the probabilities are 0.
     */
    public EnumeratedRealDistribution(final double[] singletons, final double[] probabilities)
    throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
           NotFiniteNumberException, NotANumberException {
        this(new Well19937c(), singletons, probabilities);
    }

    /**
     * Create a discrete distribution using the given random number generator
     * and probability mass function enumeration.
     *
     * @param rng random number generator.
     * @param singletons array of random variable values.
     * @param probabilities array of probabilities.
     * @throws DimensionMismatchException if
     * {@code singletons.length != probabilities.length}
     * @throws NotPositiveException if any of the probabilities are negative.
     * @throws NotFiniteNumberException if any of the probabilities are infinite.
     * @throws NotANumberException if any of the probabilities are NaN.
     * @throws MathArithmeticException all of the probabilities are 0.
     */
    public EnumeratedRealDistribution(final RandomGenerator rng,
                                    final double[] singletons, final double[] probabilities)
        throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
               NotFiniteNumberException, NotANumberException {
        super(rng);
        if (singletons.length != probabilities.length) {
            throw new DimensionMismatchException(probabilities.length, singletons.length);
        }

        List<Pair<Double, Double>> samples = new ArrayList<Pair<Double, Double>>(singletons.length);

        for (int i = 0; i < singletons.length; i++) {
            samples.add(new Pair<Double, Double>(singletons[i], probabilities[i]));
        }

        innerDistribution = new EnumeratedDistribution<Double>(rng, samples);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double probability(final double x) {
        return innerDistribution.probability(x);
    }

    /**
     * For a random variable {@code X} whose values are distributed according to
     * this distribution, this method returns {@code P(X = x)}. In other words,
     * this method represents the probability mass function (PMF) for the
     * distribution.
     *
     * @param x the point at which the PMF is evaluated
     * @return the value of the probability mass function at point {@code x}
     */
    public double density(final double x) {
        return probability(x);
    }

    /**
     * {@inheritDoc}
     */
    public double cumulativeProbability(final double x) {
        double probability = 0;

        for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
            if (sample.getKey() <= x) {
                probability += sample.getValue();
            }
        }

        return probability;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double inverseCumulativeProbability(final double p) throws OutOfRangeException {
        if (p < 0.0 || p > 1.0) {
            throw new OutOfRangeException(p, 0, 1);
        }

        double probability = 0;
        double x = getSupportLowerBound();
        for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
            if (sample.getValue() == 0.0) {
                continue;
            }

            probability += sample.getValue();
            x = sample.getKey();

            if (probability >= p) {
                break;
            }
        }

        return x;
    }

    /**
     * {@inheritDoc}
     *
     * @return {@code sum(singletons[i] * probabilities[i])}
     */
    public double getNumericalMean() {
        double mean = 0;

        for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
            mean += sample.getValue() * sample.getKey();
        }

        return mean;
    }

    /**
     * {@inheritDoc}
     *
     * @return {@code sum((singletons[i] - mean) ^ 2 * probabilities[i])}
     */
    public double getNumericalVariance() {
        double mean = 0;
        double meanOfSquares = 0;

        for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
            mean += sample.getValue() * sample.getKey();
            meanOfSquares += sample.getValue() * sample.getKey() * sample.getKey();
        }

        return meanOfSquares - mean * mean;
    }

    /**
     * {@inheritDoc}
     *
     * Returns the lowest value with non-zero probability.
     *
     * @return the lowest value with non-zero probability.
     */
    public double getSupportLowerBound() {
        double min = Double.POSITIVE_INFINITY;
        for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
            if (sample.getKey() < min && sample.getValue() > 0) {
                min = sample.getKey();
            }
        }

        return min;
    }

    /**
     * {@inheritDoc}
     *
     * Returns the highest value with non-zero probability.
     *
     * @return the highest value with non-zero probability.
     */
    public double getSupportUpperBound() {
        double max = Double.NEGATIVE_INFINITY;
        for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
            if (sample.getKey() > max && sample.getValue() > 0) {
                max = sample.getKey();
            }
        }

        return max;
    }

    /**
     * {@inheritDoc}
     *
     * The support of this distribution includes the lower bound.
     *
     * @return {@code true}
     */
    public boolean isSupportLowerBoundInclusive() {
        return true;
    }

    /**
     * {@inheritDoc}
     *
     * The support of this distribution includes the upper bound.
     *
     * @return {@code true}
     */
    public boolean isSupportUpperBoundInclusive() {
        return true;
    }

    /**
     * {@inheritDoc}
     *
     * The support of this distribution is connected.
     *
     * @return {@code true}
     */
    public boolean isSupportConnected() {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double sample() {
        return innerDistribution.sample();
    }
}