text:
package at.tugraz.sss.servs.friend.impl;

import at.tugraz.sss.serv.datatype.*;
import at.kc.tugraz.ss.friend.api.SSFriendClientI;
import at.kc.tugraz.ss.friend.api.SSFriendServerI;
import at.kc.tugraz.ss.friend.datatypes.SSFriend;
import at.kc.tugraz.ss.friend.datatypes.par.SSFriendAddPar;
import at.kc.tugraz.ss.friend.datatypes.par.SSFriendGetPar;
import at.kc.tugraz.ss.friend.datatypes.par.SSFriendsGetPar;
import at.kc.tugraz.ss.friend.datatypes.ret.SSFriendAddRet;
import at.kc.tugraz.ss.friend.datatypes.ret.SSFriendsGetRet;
import at.tugraz.sss.serv.entity.api.*;
import at.tugraz.sss.serv.datatype.par.SSEntityGetPar;
import at.kc.tugraz.ss.service.user.datatypes.SSUser;
import at.tugraz.sss.serv.datatype.enums.SSClientE;
import at.tugraz.sss.serv.datatype.par.SSServPar;
import at.tugraz.sss.serv.db.api.SSDBSQLI;
import at.tugraz.sss.serv.conf.api.SSConfA;
import at.tugraz.sss.serv.db.api.SSDBNoSQLI;
import at.tugraz.sss.serv.datatype.SSEntity;
import at.tugraz.sss.serv.datatype.par.SSEntityDescriberPar;
import at.tugraz.sss.serv.datatype.SSErr;
import at.tugraz.sss.serv.datatype.enums.SSErrE;
import at.tugraz.sss.serv.reg.SSServErrReg;
import at.tugraz.sss.serv.impl.api.SSServImplWithDBA;
import at.tugraz.sss.serv.reg.*;
import at.tugraz.sss.serv.datatype.ret.SSServRetI;
import at.tugraz.sss.serv.util.*;
import at.tugraz.sss.servs.common.impl.user.SSUserCommons;
import java.util.ArrayList;
import java.util.List;

public class SSFriendImpl
extends
  SSServImplWithDBA
implements
  SSFriendClientI,
  SSFriendServerI,
  SSDescribeEntityI{

  private final SSUserCommons  userCommons = new SSUserCommons();
  private final SSFriendSQL    sql;

  public SSFriendImpl(final SSConfA conf) throws SSErr{
    super(conf, (SSDBSQLI) SSServReg.getServ(SSDBSQLI.class), (SSDBNoSQLI) SSServReg.getServ(SSDBNoSQLI.class));

    this.sql      = new SSFriendSQL(dbSQL);
  }

  @Override
  public SSEntity describeEntity(
    final SSServPar servPar,
    final SSEntity             entity,
    final SSEntityDescriberPar par) throws SSErr{

    try{

      if(!par.setFriends){
        return entity;
      }

      switch(entity.type){

        case user: {

          final SSUser userEntity = SSUser.get(entity);

          userEntity.friends.addAll(
            friendsGet(
              new SSFriendsGetPar(
                servPar,
                par.user)));

          return userEntity;
        }

        default: return entity;
      }

    }catch(Exception error){
      SSServErrReg.regErrThrow(error);
      return null;
    }
  }

  @Override
  public SSFriend friendGet(final SSFriendGetPar par) throws SSErr{

    try{

      if(par.friend == null){
        throw SSErr.get(SSErrE.parameterMissing);
      }

      final SSEntityServerI entityServ  = (SSEntityServerI) SSServReg.getServ(SSEntityServerI.class);

      return SSFriend.get(
        sql.getFriend(par, par.friend),
        entityServ.entityGet(
          new SSEntityGetPar(
            par,
            par.user,
            par.friend,
            par.withUserRestriction, //withUserRestriction,
            null))); //descPar));

    }catch(Exception error){
      SSServErrReg.regErrThrow(error);
      return null;
    }
  }

  @Override
  public SSServRetI friendsGet(final SSClientE clientType, final SSServPar parA) throws SSErr {

    try{

      userCommons.checkKeyAndSetUser(parA);

    final SSFriendsGetPar par = (SSFriendsGetPar) parA.getFromClient(clientType, parA, SSFriendsGetPar.class);

    return SSFriendsGetRet.get(friendsGet(par));

    }catch(Exception error){
      SSServErrReg.regErrThrow(error);
      return null;
    }
  }

  @Override
  public List<SSEntity> friendsGet(final SSFriendsGetPar par) throws SSErr{

    try{

      final List<SSEntity> result = new ArrayList<>();

      for(SSUri friend : sql.getFriends(par, par.user)){

        SSEntity.addEntitiesDistinctWithoutNull(
          result,
          friendGet(
            new SSFriendGetPar(
              par,
              par.user,
              friend)));
      }

      return result;

    }catch(Exception error){
      SSServErrReg.regErrThrow(error);
      return null;
    }
  }

  @Override
  public SSServRetI friendAdd(final SSClientE clientType, final SSServPar parA) throws SSErr {

    try{

      userCommons.checkKeyAndSetUser(parA);

      final SSFriendAddPar par = (SSFriendAddPar) parA.getFromClient(clientType, parA, SSFriendAddPar.class);

      return SSFriendAddRet.get(friendAdd(par));

    }catch(Exception error){
      SSServErrReg.regErrThrow(error);
      return null;
    }
  }

  @Override
  public SSUri friendAdd(final SSFriendAddPar par) throws SSErr{

    try{

      dbSQL.startTrans(par, par.shouldCommit);

      sql.addFriend(par, par.user, par.friend);

      dbSQL.commit(par, par.shouldCommit);

      return par.friend;

    }catch(Exception error){

      try{
        dbSQL.rollBack(par, par.shouldCommit);
      }catch(Exception error2){
        SSLogU.err(error2);
      }

      SSServErrReg.regErrThrow(error);
      return null;
    }
  }
}


text:
require 'test_helper'

class Gonzales::Adapter::RegisteredTest < ActiveSupport::TestCase
  context 'Registered adapter' do
    should 'call speedy' do
      Gonzales::Factories.expects(:speedy).with(:elmer, :fudd)
      Gonzales::Adapter::Registered.create(:elmer, :fudd)
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
import java.util.List;
class GetClassTest {
    interface GetCl {
        Class<? extends List> _();
    }

    interface GetClReturnTypeProblems {
        Class<List<String>> _();
    }

    void test(int[] iarr, List<String> ls) {
        GetCl c4 = ls::getClass;
        <error descr="Incompatible types. Found: '<method reference>', required: 'GetClassTest.GetClReturnTypeProblems'">GetClReturnTypeProblems c5 = ls::getClass;</error>
    }
}


text:
package org.apache.hadoop.tools.rumen.serializers;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * A JSON serializer for Strings.
 */
public class BlockingSerializer extends JsonSerializer<String> {

  public void serialize(String object, JsonGenerator jGen, SerializerProvider sProvider)
  throws IOException, JsonProcessingException {
    jGen.writeNull();
  };
}


text:
"""
Product info handlers
"""

from nailgun.api.v1.handlers.base import BaseHandler
from nailgun.api.v1.handlers.base import content_json
from nailgun.settings import settings
from nailgun import utils

class VersionHandler(BaseHandler):
    """Version info handler
    """

    release_versions = "/etc/fuel/release_versions/*.yaml"

    @content_json
    def GET(self):
        """:returns: FUEL/FUELWeb commit SHA, release version.
        :http: * 200 (OK)
        """
        version = settings.VERSION
        method = settings.AUTH['AUTHENTICATION_METHOD']
        version['auth_required'] = method in ['fake', 'keystone']

        version['release_versions'] = utils.get_fuel_release_versions(
            self.release_versions)
        return version


text:
import Drawable from './Drawable';
import SkyboxCommand from '../Renderers/Commands/SkyboxCommand';

/**
 * A Skybox
 *
 * @category Drawables
 * @extends {Drawable}
 */
class Skybox extends Drawable {
    /**
     * Constructor
     */
    constructor() {
        super();

        /**
         * Program
         *
         * @type {Program}
         * @private
         */
        this.customProgram = null;

        /**
         * Texture cube linked
         *
         * @type {TextureCube}
         * @private
         */
        this.texture = null;
    }

    /**
     * Draw the element
     *
     * @param {RenderTarget} renderTarget Renderer who called this method
     */
    draw(renderTarget) {
        if (this.texture) {
            renderTarget.getActiveTask().addCommand(new SkyboxCommand(this));
        }
    }

    /**
     * Set program to use
     *
     * @param {Program} program A Program instance
     * @return {Skybox} A reference to the instance
     */
    setCustomProgram(program) {
        this.customProgram = program;

        return this;
    }

    /**
     * Set texture
     *
     * @param {TextureCube} texture A TextureCube instance
     * @return {Skybox} A reference to the instance
     */
    setTexture(texture) {
        this.texture = texture;

        return this;
    }

    /**
     * Get program
     *
     * @return {?Program} A Program instance or null if the Skybox use the default program
     */
    getCustomProgram() {
        return this.customProgram;
    }

    /**
     * Get the linked TextureCube instance
     *
     * @return {TextureCube} A TextureCube instances
     */
    getTexture() {
        return this.texture;
    }
}

export default Skybox;


text:
package org.sparkcommerce.openadmin.server.service.persistence;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * @author Jeff Fischer
 */
@Service("blPersistenceManagerFactory")
public class PersistenceManagerFactory implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    public static final String DEFAULTPERSISTENCEMANAGERREF = "blPersistenceManager";
    protected static String persistenceManagerRef = DEFAULTPERSISTENCEMANAGERREF;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        PersistenceManagerFactory.applicationContext = applicationContext;
    }

    public static PersistenceManager getPersistenceManager() {
        if (PersistenceManagerContext.getPersistenceManagerContext() != null) {
            return PersistenceManagerContext.getPersistenceManagerContext().getPersistenceManager();
        }
        throw new IllegalStateException("PersistenceManagerContext is not set on ThreadLocal. If you want to use the " +
                "non-cached version, try getPersistenceManager(TargetModeType)");
    }

    public static PersistenceManager getPersistenceManager(TargetModeType targetModeType) {
        PersistenceManager persistenceManager = (PersistenceManager) applicationContext.getBean(persistenceManagerRef);
        persistenceManager.setTargetMode(targetModeType);

        return persistenceManager;
    }

    public static boolean isPersistenceManagerActive() {
        return applicationContext.containsBean(getPersistenceManagerRef());
    }

    public static void startPersistenceManager(TargetModeType targetModeType) {
        PersistenceManagerContext context = PersistenceManagerContext.getPersistenceManagerContext();
        if (context == null) {
            context = new PersistenceManagerContext();
            PersistenceManagerContext.addPersistenceManagerContext(context);
        }
        context.addPersistenceManager(getPersistenceManager(targetModeType));
    }

    public static void endPersistenceManager() {
        PersistenceManagerContext context = PersistenceManagerContext.getPersistenceManagerContext();
        if (context != null) {
            context.remove();
        }
    }

    public static String getPersistenceManagerRef() {
        return persistenceManagerRef;
    }

    public static void setPersistenceManagerRef(String persistenceManagerRef) {
        PersistenceManagerFactory.persistenceManagerRef = persistenceManagerRef;
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Azure.Devices.Client.Test.ConnectionString
{
    using System;

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.Azure.Devices.Client;

    [TestClass]
    public class DeviceClientConnectionStringExceptionTests
    {
        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentException))]
        public void DeviceClient_ConnectionString_DefaultScope_DefaultCredentialType_MissingEndpoint_ExceptionTest()
        {
            string connectionString = "SharedAccessKeyName=AllAccessKey;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentException))]
        public void DeviceClient_ConnectionString_DefaultScope_DefaultCredentialType_MissingDeviceId_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentException))]
        public void DeviceClient_ConnectionString_DefaultScope_DefaultCredentialType_MissingSharedAccessKey_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKeyName=AllAccessKey";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentException))]
        public void DeviceClient_ConnectionString_DefaultScope_DefaultCredentialType_MissingSharedAccessKeyNameAndKey_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentException))]
        public void DeviceClient_ConnectionString_IotHubScope_SharedAccessSignatureCredentialType_MissingSharedAccessKey_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;CredentialScope=IotHub;CredentialType=SharedAccessSignature;DeviceId=device1;SharedAccessKeyName=AllAccessKey";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentException))]
        public void DeviceClient_ConnectionString_IotHubScope_SharedAccessKeyCredentialType_MissingSharedAccessKeyNameAndKey_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;CredentialScope=IotHub;CredentialType=SharedAccessKey;DeviceId=device1";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentException))]
        public void DeviceClient_ConnectionString_DeviceScope_SharedAccessKeyCredentialType_MissingSharedAccessKey_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;CredentialType=SharedAccessKey;DeviceId=device1";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentException))]
        public void DeviceClient_ConnectionString_DeviceScope_SharedAccessKeyCredentialType_NotAllowedSharedAccessKeyName_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;CredentialType=SharedAccessKey;SharedAccessKeyName=AllAccessKey;DeviceId=device1";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(FormatException))]
        public void DeviceClient_ConnectionString_DeviceScope_SharedAccessSignatureCredentialType_InvalidSharedAccessKey_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;CredentialType=SharedAccessKey;SharedAccessKey=INVALID;DeviceId=device1";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        public void DeviceClient_MalformedConnectionStringTest()
        {
            string connectionString = "TODO: IoT Hub connection string to connect to";
            try
            {
                var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
            }
            catch (FormatException fe)
            {
                Assert.IsTrue(fe.Message.Contains("Malformed Token"), "Exception should mention 'Malformed Token' Actual :" + fe.Message);
            }
         }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(FormatException))]
        public void DeviceClient_ConnectionString_DeviceScope_ImplicitSharedAccessSignatureCredentialType_InvalidSharedAccessSignature_ExceptionTest()
        {
            string connectionString = "HostName=acme.azure-devices.net;CredentialScope=Device;CredentialType=SharedAccessKey;SharedAccessSignature=INVALID;DeviceId=device1";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentNullException))]
        public void DeviceClient_ConnectionString_EmptyConnectionString_ExceptionTest()
        {
            string connectionString = "";
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }

        [TestMethod]
        [TestCategory("CIT")]
        [ExpectedException(typeof(ArgumentNullException))]
        public void DeviceClient_ConnectionString_NullConnectionString_ExceptionTest()
        {
            string connectionString = null;
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
        }
    }
}


text:
#pragma once
#include <aws/awstransfer/Transfer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Transfer
{
namespace Model
{
  class AWS_TRANSFER_API ImportCertificateResult
  {
  public:
    ImportCertificateResult();
    ImportCertificateResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ImportCertificateResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
An array of identifiers for the imported certificates. You use this
     * identifier for working with profiles and partner profiles.

     */
    inline const Aws::String& GetCertificateId() const{ return m_certificateId; }

    /**
     *
An array of identifiers for the imported certificates. You use this
     * identifier for working with profiles and partner profiles.

     */
    inline void SetCertificateId(const Aws::String& value) { m_certificateId = value; }

    /**
     *
An array of identifiers for the imported certificates. You use this
     * identifier for working with profiles and partner profiles.

     */
    inline void SetCertificateId(Aws::String&& value) { m_certificateId = std::move(value); }

    /**
     *
An array of identifiers for the imported certificates. You use this
     * identifier for working with profiles and partner profiles.

     */
    inline void SetCertificateId(const char* value) { m_certificateId.assign(value); }

    /**
     *
An array of identifiers for the imported certificates. You use this
     * identifier for working with profiles and partner profiles.

     */
    inline ImportCertificateResult& WithCertificateId(const Aws::String& value) { SetCertificateId(value); return *this;}

    /**
     *
An array of identifiers for the imported certificates. You use this
     * identifier for working with profiles and partner profiles.

     */
    inline ImportCertificateResult& WithCertificateId(Aws::String&& value) { SetCertificateId(std::move(value)); return *this;}

    /**
     *
An array of identifiers for the imported certificates. You use this
     * identifier for working with profiles and partner profiles.

     */
    inline ImportCertificateResult& WithCertificateId(const char* value) { SetCertificateId(value); return *this;}

  private:

    Aws::String m_certificateId;
  };

} // namespace Model
} // namespace Transfer
} // namespace Aws


text:
package io.github.binaryfoo.res;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ClasspathIO {

    public static List<String> readLines(String fileName) {
        try (InputStream in = open(fileName)) {
            return IOUtils.readLines(in);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read " + fileName, e);
        }
    }

    public static InputStream open(String fileName) {
        return ClasspathIO.class.getClassLoader().getResourceAsStream(fileName);
    }
}


text:
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {watchEvents, unWatchEvents} from './actions'
import { isEqual, differenceBy } from 'lodash'

const defaultEvent = {
    path: '',
    type: 'value',
    isListenOnlyOnDelta: false,
    setFunc: undefined,
    setOptions: undefined,
    isAggregation: false,
    isSkipClean: false,
    isSkipCleanOnUnmount: false,
}

const fixPath = (path) =>  ((path.substring(0,1) == '/') ? '': '/') + path

const ensureCallable = maybeFn =>
    typeof maybeFn === 'function' ? maybeFn : _ => maybeFn

const flatMap = arr => (arr && arr.length) ? arr.reduce((a, b) => a.concat(b)) : []

const createEvents = ({type, path, isSkipClean=false, isSkipCleanOnUnmount=false,
    isListenOnlyOnDelta=false, isAggregation=false, setFunc=undefined, setOptions=undefined}) => {
    switch (type) {

        case 'value':
            return [{name: 'value', path, isSkipClean, isSkipCleanOnUnmount, setFunc, setOptions}]

        case 'once':
            return [{name: 'once', path, isSkipClean, isSkipCleanOnUnmount, setFunc, setOptions}]

        case 'all':
            return [
                //{name: 'first_child', path},
                {name: 'child_added', path, isSkipClean, isSkipCleanOnUnmount, isListenOnlyOnDelta, isAggregation, setFunc, setOptions},
                {name: 'child_removed', path, isSkipClean, isSkipCleanOnUnmount, isListenOnlyOnDelta, isAggregation, setFunc, setOptions},
                {name: 'child_moved', path, isSkipClean, isSkipCleanOnUnmount, isListenOnlyOnDelta, isAggregation, setFunc, setOptions},
                {name: 'child_changed', path, isSkipClean, isSkipCleanOnUnmount, isListenOnlyOnDelta, isAggregation, setFunc, setOptions}
            ]

        default:
            return []
    }
}

const transformEvent = event => Object.assign({}, defaultEvent, event)

const getEventsFromDefinition = def => flatMap(def.map(path => {
    if (typeof path === 'string' || path instanceof String) {
        return createEvents(transformEvent({ path }))
    }

    if (typeof path === 'array' || path instanceof Array) { // eslint-disable-line
        return createEvents(transformEvent({ type: 'all', path: path[0] }))
    }

    if (typeof path === 'object' || path instanceof Object) {
        const type = path.type || 'value'
        switch (type) {
            case 'value':
                return createEvents(transformEvent({ path: path.path, isSkipClean:!!path.isSkipClean, isSkipCleanOnUnmount:!!path.isSkipCleanOnUnmount, setFunc:path.setFunc, setOptions:path.setOptions}))

            case 'once':
                return createEvents(transformEvent({ type: 'once', path: path.path, isSkipClean:!!path.isSkipClean, isSkipCleanOnUnmount:!!path.isSkipCleanOnUnmount, setFunc:path.setFunc, setOptions:path.setOptions }))

            case 'array':
            case 'all':
                return createEvents(transformEvent({ type: 'all', path: path.path, isSkipClean:!!path.isSkipClean,
                    isSkipCleanOnUnmount:!!path.isSkipCleanOnUnmount, isListenOnlyOnDelta:!!path.isListenOnlyOnDelta,
                    isAggregation:!!path.isAggregation, setFunc:path.setFunc, setOptions:path.setOptions }))
        }
    }

    return []
}))

const cleanPaths = def => {
    return def.filter(path => {
        return !(path === undefined ||
            ((typeof path === 'array' || path instanceof Array) && (path[0] === undefined)) ||
            ((typeof path === 'object' || path instanceof Object) && (path.path === undefined))
        )
    })
}

const __guid = () => {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return s4() + '-' + s4() + '-' + s4() + '-' +
        s4() + '-' + s4() + s4() + s4();
};

export default (dataOrFn = []) => WrappedComponent => {
    class FirebaseConnect extends Component {

        static WrappedComponent = WrappedComponent;

        constructor (props, context) {
            super(props, context)
            this._firebaseEvents = []
            this._pathsToListen = undefined;
            this._id = __guid();
            this.firebase = null
        }

        static contextTypes = {
            store: PropTypes.object.isRequired
        };

        componentWillMount () {
            const {firebase, dispatch} = this.context.store

            const linkFn = ensureCallable(dataOrFn)
            this._pathsToListen = cleanPaths(linkFn(this.props, firebase))

            const {ref, helpers, storage, database, auth} = firebase
            this.firebase = {ref, storage, database, auth, ...helpers}

            this._firebaseEvents = getEventsFromDefinition(this._pathsToListen)

            if (this._firebaseEvents.length > 0) {
                if (!!firebase.auth().currentUser) {
                    watchEvents(firebase, dispatch, this._firebaseEvents, this._id)
                } else {
                    if (!firebase._.firebasePendingEvents) {
                        firebase._.firebasePendingEvents = {}
                    }

                    firebase._.firebasePendingEvents[this._id] = this._firebaseEvents;
                }
            }
        }

        componentWillReceiveProps(nextProps) {
            const {firebase, dispatch} = this.context.store

            const linkFn = ensureCallable(dataOrFn)
            const newPathsToListen = cleanPaths(linkFn(nextProps, firebase))

            if (!isEqual(newPathsToListen, this._pathsToListen)) {
                let oldPaths = differenceBy(this._pathsToListen, newPathsToListen, (a)=>{
                    let ret = a;
                    if (typeof a === 'object') {
                        ret = a.path + a.type + a.isListenOnlyOnDelta + a.isAggregation + a.isSkipClean + a.isSkipCleanOnUnmount
                    }

                    return ret
                });
                let newPaths = differenceBy(newPathsToListen, this._pathsToListen, (a)=>{
                    let ret = a;
                    if (typeof a === 'object') {
                        ret = a.path + a.type + a.isListenOnlyOnDelta + a.isAggregation + a.isSkipClean + a.isSkipCleanOnUnmount
                    }

                    return ret
                });

                let oldFirebaseEvents = getEventsFromDefinition(oldPaths)
                let newFirebaseEvents = getEventsFromDefinition(newPaths)

                const events = getEventsFromDefinition(newPathsToListen);

                if (!!firebase.auth().currentUser) {
                    const isUnmount = oldFirebaseEvents.length > 0 && newFirebaseEvents.length===0;

                    if (oldFirebaseEvents.length > 0) {
                        unWatchEvents(firebase, dispatch, oldFirebaseEvents, this._id, isUnmount);
                    }

                    if (newFirebaseEvents.length>0) {
                        watchEvents(firebase, dispatch, newFirebaseEvents, this._id);
                    }
                } else if (events.length > 0){
                    if (!firebase._.firebasePendingEvents) {
                        firebase._.firebasePendingEvents = {}
                    }

                    firebase._.firebasePendingEvents[this._id] = events;
                }

                this._pathsToListen = newPathsToListen;
                this._firebaseEvents = events;
            }
        }

        componentWillUnmount () {
            const {firebase, dispatch} = this.context.store;

            unWatchEvents(firebase, dispatch, this._firebaseEvents, this._id, true)
        }

        render () {
            return (
                <WrappedComponent
                    {...this.props}
                    {...this.state}
                    firebase={this.firebase}
                />
            )
        }
    }
    return FirebaseConnect
}


text:
"use strict";

var isValue = require("./is-value");

var forEach = Array.prototype.forEach, create = Object.create;

var process = function (src, obj) {
	var key;
	for (key in src) obj[key] = src[key];
};

// eslint-disable-next-line no-unused-vars
module.exports = function (opts1/*, …options*/) {
	var result = create(null);
	forEach.call(arguments, function (options) {
		if (!isValue(options)) return;
		process(Object(options), result);
	});
	return result;
};


text:
package openstack

import (
	"strings"

	"github.com/cloudfoundry/bosh-bootloader/storage"
	"github.com/gobuffalo/packr/v2"
)

const templatesPath = "./templates"

type templates struct {
	providerVars     string
	provider         string
	resourcesOutputs string
	resourcesVars    string
	resources        string
}

type TemplateGenerator struct {
	box *packr.Box
}

func NewTemplateGenerator() TemplateGenerator {
	return TemplateGenerator{
		box: packr.New("openstack-templates", templatesPath),
	}
}

func (t TemplateGenerator) Generate(state storage.State) string {
	tmpls := t.readTemplates()
	template := strings.Join([]string{tmpls.providerVars, tmpls.provider, tmpls.resourcesOutputs, tmpls.resourcesVars, tmpls.resources}, "\n")
	return template
}

func (t TemplateGenerator) readTemplates() templates {
	listings := map[string]string{
		"provider-vars.tf":     "",
		"provider.tf":          "",
		"resources-outputs.tf": "",
		"resources-vars.tf":    "",
		"resources.tf":         "",
	}

	var errors []error
	for item := range listings {
		content, err := t.box.FindString(item)
		if err != nil {
			errors = append(errors, err)
			continue
		}

		listings[item] = content
	}

	if errors != nil {
		panic(errors)
	}

	return templates{
		providerVars:     listings["provider-vars.tf"],
		provider:         listings["provider.tf"],
		resourcesOutputs: listings["resources-outputs.tf"],
		resourcesVars:    listings["resources-vars.tf"],
		resources:        listings["resources.tf"],
	}
}


text:
require 'hallmonitor/outputter'

module Hallmonitor
  class Middleware
    def initialize(app)
      @app = app
    end

    def call(env)
      request = Rack::Request.new(env)
      @event_base_name = "http.#{request.path_info.gsub('/', '.')}.#{request.request_method}"
      if !request.path_info.match(/^\/?assets/)
        @event = Hallmonitor::TimedEvent.new("#{@event_base_name}.response_time")
        @event.start = Time.now
      else
        @event = nil
      end

      response = @app.call(env)

      if @event
        @event.stop = Time.now
        Hallmonitor::Outputter.output(@event)
        Hallmonitor::Outputter.output(Hallmonitor::Event.new("#{@event_base_name}.count"))
      end
      response
    end
  end
end


text:
package io.netty.handler.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;

public class ByteToMessageDecoderTest {

    @Test
    public void testRemoveItself() {
        EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
            private boolean removed;

            @Override
            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                Assert.assertFalse(removed);
                in.readByte();
                ctx.pipeline().remove(this);
                removed = true;
            }
        });

        ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'a', 'b', 'c'});
        channel.writeInbound(buf.copy());
        ByteBuf b = (ByteBuf) channel.readInbound();
        Assert.assertEquals(b, buf.skipBytes(1));
        b.release();
        buf.release();
    }

    @Test
    public void testRemoveItselfWriteBuffer() {
        final ByteBuf buf = Unpooled.buffer().writeBytes(new byte[]{'a', 'b', 'c'});
        EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
            private boolean removed;

            @Override
            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                Assert.assertFalse(removed);
                in.readByte();
                ctx.pipeline().remove(this);

                // This should not let it keep call decode
                buf.writeByte('d');
                removed = true;
            }
        });

        channel.writeInbound(buf.copy());
        ByteBuf b = (ByteBuf) channel.readInbound();
        Assert.assertEquals(b, Unpooled.wrappedBuffer(new byte[] { 'b', 'c'}));
        buf.release();
        b.release();
    }
}


text:
export class ServerMessage {
  numpp    : number;
  msg      : string;
  recieved : Date;
}

export interface IModuleState {
  messages: ServerMessage[]
}


text:
public class QueueUnderflowException extends RuntimeException
{
  public QueueUnderflowException()
  {
    super();
  }

  public QueueUnderflowException(String message)
  {
    super(message);
  }
}


text:
<?php
# USTA/MemberBundle/DoctrineExtensions/MatchAgainstFunction.php
namespace USTA\MemberBundle\DoctrineExtensions;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;

/**
 * MatchAgainstFunction ::=
 *  "MATCH" "(" StateFieldPathExpression {"," StateFieldPathExpression}* ")" "AGAINST" "("
 *      StringPrimary ["BOOLEAN"] ["EXPAND"] ")"
 */
class MatchAgainstFunction extends FunctionNode {

  /** @var array list of \Doctrine\ORM\Query\AST\PathExpression */
  protected $pathExp = null;

  /** @var string */
  protected $against = null;

  /** @var boolean */
  protected $booleanMode = false;

  /** @var boolean */
  protected $queryExpansion = false;

  public function parse(Parser $parser) {
    // match
    $parser->match(Lexer::T_IDENTIFIER);
    $parser->match(Lexer::T_OPEN_PARENTHESIS);

    // first Path Expression is mandatory
    $this->pathExp = array();
    $this->pathExp[] = $parser->StateFieldPathExpression();

    // Subsequent Path Expressions are optional
    $lexer = $parser->getLexer();
    while ($lexer->isNextToken(Lexer::T_COMMA)) {
      $parser->match(Lexer::T_COMMA);
      $this->pathExp[] = $parser->StateFieldPathExpression();
    }

    $parser->match(Lexer::T_CLOSE_PARENTHESIS);

    // against
    if (strtolower($lexer->lookahead['value']) !== 'against') {
      $parser->syntaxError('against');
    }

    $parser->match(Lexer::T_IDENTIFIER);
    $parser->match(Lexer::T_OPEN_PARENTHESIS);
    $this->against = $parser->StringPrimary();

    if (strtolower($lexer->lookahead['value']) === 'boolean') {
      $parser->match(Lexer::T_IDENTIFIER);
      $this->booleanMode = true;
    }

    if (strtolower($lexer->lookahead['value']) === 'expand') {
      $parser->match(Lexer::T_IDENTIFIER);
      $this->queryExpansion = true;
    }

    $parser->match(Lexer::T_CLOSE_PARENTHESIS);
  }

  public function getSql(SqlWalker $walker) {
    $fields = array();
    foreach ($this->pathExp as $pathExp) {
      $fields[] = $pathExp->dispatch($walker);
    }

    $against = $walker->walkStringPrimary($this->against)
        . ($this->booleanMode ? ' IN BOOLEAN MODE' : '')
        . ($this->queryExpansion ? ' WITH QUERY EXPANSION' : '');

    return sprintf('MATCH (%s) AGAINST (%s)', implode(', ', $fields), $against);
  }
}


text:
#include <aws/sagemaker/model/ModelConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SageMaker
{
namespace Model
{

ModelConfiguration::ModelConfiguration() :
    m_inferenceSpecificationNameHasBeenSet(false),
    m_environmentParametersHasBeenSet(false)
{
}

ModelConfiguration::ModelConfiguration(JsonView jsonValue) :
    m_inferenceSpecificationNameHasBeenSet(false),
    m_environmentParametersHasBeenSet(false)
{
  *this = jsonValue;
}

ModelConfiguration& ModelConfiguration::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("InferenceSpecificationName"))
  {
    m_inferenceSpecificationName = jsonValue.GetString("InferenceSpecificationName");

    m_inferenceSpecificationNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("EnvironmentParameters"))
  {
    Aws::Utils::Array<JsonView> environmentParametersJsonList = jsonValue.GetArray("EnvironmentParameters");
    for(unsigned environmentParametersIndex = 0; environmentParametersIndex < environmentParametersJsonList.GetLength(); ++environmentParametersIndex)
    {
      m_environmentParameters.push_back(environmentParametersJsonList[environmentParametersIndex].AsObject());
    }
    m_environmentParametersHasBeenSet = true;
  }

  return *this;
}

JsonValue ModelConfiguration::Jsonize() const
{
  JsonValue payload;

  if(m_inferenceSpecificationNameHasBeenSet)
  {
   payload.WithString("InferenceSpecificationName", m_inferenceSpecificationName);

  }

  if(m_environmentParametersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> environmentParametersJsonList(m_environmentParameters.size());
   for(unsigned environmentParametersIndex = 0; environmentParametersIndex < environmentParametersJsonList.GetLength(); ++environmentParametersIndex)
   {
     environmentParametersJsonList[environmentParametersIndex].AsObject(m_environmentParameters[environmentParametersIndex].Jsonize());
   }
   payload.WithArray("EnvironmentParameters", std::move(environmentParametersJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace SageMaker
} // namespace Aws


text:
ALTER TABLE MFR_TOPIC_T ADD COLUMN POST_ANONYMOUS BIT(1) NOT NULL DEFAULT 0;
ALTER TABLE MFR_TOPIC_T ADD COLUMN REVEAL_IDS_TO_ROLES BIT(1) NOT NULL DEFAULT 0;
ALTER TABLE MFR_PERMISSION_LEVEL_T ADD COLUMN IDENTIFY_ANON_AUTHORS BIT(1) NOT NULL DEFAULT 0;
UPDATE MFR_PERMISSION_LEVEL_T SET IDENTIFY_ANON_AUTHORS = 1 WHERE NAME = 'Owner';


text:
require 'etc'
require 'facter'
require 'puppet/property/list'
require 'puppet/property/ordered_list'
require 'puppet/property/keyvalue'

module Puppet
  newtype(:user) do
    @doc = "Manage users.  This type is mostly built to manage system
      users, so it is lacking some features useful for managing normal
      users.

      This resource type uses the prescribed native tools for creating
      groups and generally uses POSIX APIs for retrieving information
      about them.  It does not directly modify `/etc/passwd` or anything.

      **Autorequires:** If Puppet is managing the user's primary group (as
      provided in the `gid` attribute), the user resource will autorequire
      that group. If Puppet is managing any role accounts corresponding to the
      user's roles, the user resource will autorequire those role accounts."

    feature :allows_duplicates,
      "The provider supports duplicate users with the same UID."

    feature :manages_homedir,
      "The provider can create and remove home directories."

    feature :manages_passwords,
      "The provider can modify user passwords, by accepting a password
      hash."

    feature :manages_password_age,
      "The provider can set age requirements and restrictions for
      passwords."

    feature :manages_solaris_rbac,
      "The provider can manage roles and normal users"

    feature :manages_expiry,
      "The provider can manage the expiry date for a user."

   feature :system_users,
     "The provider allows you to create system users with lower UIDs."

    feature :manages_aix_lam,
      "The provider can manage AIX Loadable Authentication Module (LAM) system."

    newproperty(:ensure, :parent => Puppet::Property::Ensure) do
      newvalue(:present, :event => :user_created) do
        provider.create
      end

      newvalue(:absent, :event => :user_removed) do
        provider.delete
      end

      newvalue(:role, :event => :role_created, :required_features => :manages_solaris_rbac) do
        provider.create_role
      end

      desc "The basic state that the object should be in."

      # If they're talking about the thing at all, they generally want to
      # say it should exist.
      defaultto do
        if @resource.managed?
          :present
        else
          nil
        end
      end

      def retrieve
        if provider.exists?
          if provider.respond_to?(:is_role?) and provider.is_role?
            return :role
          else
            return :present
          end
        else
          return :absent
        end
      end
    end

    newproperty(:home) do
      desc "The home directory of the user.  The directory must be created
        separately and is not currently checked for existence."
    end

    newproperty(:uid) do
      desc "The user ID; must be specified numerically. If no user ID is
        specified when creating a new user, then one will be chosen
        automatically. This will likely result in the same user having
        different UIDs on different systems, which is not recommended. This is
        especially noteworthy when managing the same user on both Darwin and
        other platforms, since Puppet does UID generation on Darwin, but
        the underlying tools do so on other platforms.

        On Windows, this property is read-only and will return the user's
        security identifier (SID)."

      munge do |value|
        case value
        when String
          if value =~ /^[-0-9]+$/
            value = Integer(value)
          end
        end

        return value
      end
    end

    newproperty(:gid) do
      desc "The user's primary group.  Can be specified numerically or by name.

        Note that users on Windows systems do not have a primary group; manage groups
        with the `groups` attribute instead."

      munge do |value|
        if value.is_a?(String) and value =~ /^[-0-9]+$/
          Integer(value)
        else
          value
        end
      end

      def insync?(is)
        # We know the 'is' is a number, so we need to convert the 'should' to a number,
        # too.
        @should.each do |value|
          return true if number = Puppet::Util.gid(value) and is == number
        end

        false
      end

      def sync
        found = false
        @should.each do |value|
          if number = Puppet::Util.gid(value)
            provider.gid = number
            found = true
            break
          end
        end

        fail "Could not find group(s) #{@should.join(",")}" unless found

        # Use the default event.
      end
    end

    newproperty(:comment) do
      desc "A description of the user.  Generally the user's full name."
    end

    newproperty(:shell) do
      desc "The user's login shell.  The shell must exist and be
        executable.

        This attribute cannot be managed on Windows systems."
    end

    newproperty(:password, :required_features => :manages_passwords) do
      desc %q{The user's password, in whatever encrypted format the local
        system requires.

        * Most modern Unix-like systems use salted SHA1 password hashes. You can use
          Puppet's built-in `sha1` function to generate a hash from a password.
        * Mac OS X 10.5 and 10.6 also use salted SHA1 hashes.
        * Mac OS X 10.7 (Lion) uses salted SHA512 hashes. The Puppet Labs [stdlib][]
          module contains a `str2saltedsha512` function which can generate password
          hashes for Lion.
        * Windows passwords can only be managed in cleartext, as there is no Windows API
          for setting the password hash.

        [stdlib]: https://github.com/puppetlabs/puppetlabs-stdlib/

        Be sure to enclose any value that includes a dollar sign ($) in single
        quotes (') to avoid accidental variable interpolation.}

      validate do |value|
        raise ArgumentError, "Passwords cannot include ':'" if value.is_a?(String) and value.include?(":")
      end

      def change_to_s(currentvalue, newvalue)
        if currentvalue == :absent
          return "created password"
        else
          return "changed password"
        end
      end

      def is_to_s( currentvalue )
        return '[old password hash redacted]'
      end
      def should_to_s( newvalue )
        return '[new password hash redacted]'
      end

    end

    newproperty(:password_min_age, :required_features => :manages_password_age) do
      desc "The minimum number of days a password must be used before it may be changed."

      munge do |value|
        case value
        when String
          Integer(value)
        else
          value
        end
      end

      validate do |value|
        if value.to_s !~ /^-?\d+$/
          raise ArgumentError, "Password minimum age must be provided as a number."
        end
      end
    end

    newproperty(:password_max_age, :required_features => :manages_password_age) do
      desc "The maximum number of days a password may be used before it must be changed."

      munge do |value|
        case value
        when String
          Integer(value)
        else
          value
        end
      end

      validate do |value|
        if value.to_s !~ /^-?\d+$/
          raise ArgumentError, "Password maximum age must be provided as a number."
        end
      end
    end

    newproperty(:groups, :parent => Puppet::Property::List) do
      desc "The groups to which the user belongs.  The primary group should
        not be listed, and groups should be identified by name rather than by
        GID.  Multiple groups should be specified as an array."

      validate do |value|
        if value =~ /^\d+$/
          raise ArgumentError, "Group names must be provided, not GID numbers."
        end
        raise ArgumentError, "Group names must be provided as an array, not a comma-separated list." if value.include?(",")
        raise ArgumentError, "Group names must not be empty. If you want to specify \"no groups\" pass an empty array" if value.empty?
      end
    end

    newparam(:name) do
      desc "The user name. While naming limitations vary by operating system,
        it is advisable to restrict names to the lowest common denominator,
        which is a maximum of 8 characters beginning with a letter.

        Note that Puppet considers user names to be case-sensitive, regardless
        of the platform's own rules; be sure to always use the same case when
        referring to a given user."
      isnamevar
    end

    newparam(:membership) do
      desc "Whether specified groups should be considered the **complete list**
        (`inclusive`) or the **minimum list** (`minimum`) of groups to which
        the user belongs. Defaults to `minimum`."

      newvalues(:inclusive, :minimum)

      defaultto :minimum
    end

    newparam(:system, :boolean => true) do
      desc "Whether the user is a system user, according to the OS's criteria;
      on most platforms, a UID less than or equal to 500 indicates a system
      user. Defaults to `false`."

      newvalues(:true, :false)

      defaultto false
    end

    newparam(:allowdupe, :boolean => true) do
      desc "Whether to allow duplicate UIDs. Defaults to `false`."

      newvalues(:true, :false)

      defaultto false
    end

    newparam(:managehome, :boolean => true) do
      desc "Whether to manage the home directory when managing the user.
        Defaults to `false`."

      newvalues(:true, :false)

      defaultto false

      validate do |val|
        if val.to_s == "true"
          raise ArgumentError, "User provider #{provider.class.name} can not manage home directories" unless provider.class.manages_homedir?
        end
      end
    end

    newproperty(:expiry, :required_features => :manages_expiry) do
      desc "The expiry date for this user. Must be provided in
           a zero-padded YYYY-MM-DD format --- e.g. 2010-02-19."

      validate do |value|
        if value !~ /^\d{4}-\d{2}-\d{2}$/
          raise ArgumentError, "Expiry dates must be YYYY-MM-DD"
        end
      end
    end

    # Autorequire the group, if it's around
    autorequire(:group) do
      autos = []

      if obj = @parameters[:gid] and groups = obj.shouldorig
        groups = groups.collect { |group|
          if group =~ /^\d+$/
            Integer(group)
          else
            group
          end
        }
        groups.each { |group|
          case group
          when Integer
            if resource = catalog.resources.find { |r| r.is_a?(Puppet::Type.type(:group)) and r.should(:gid) == group }
              autos << resource
            end
          else
            autos << group
          end
        }
      end

      if obj = @parameters[:groups] and groups = obj.should
        autos += groups.split(",")
      end

      autos
    end

    # Provide an external hook.  Yay breaking out of APIs.
    def exists?
      provider.exists?
    end

    def retrieve
      absent = false
      properties.inject({}) { |prophash, property|
        current_value = :absent

        if absent
          prophash[property] = :absent
        else
          current_value = property.retrieve
          prophash[property] = current_value
        end

        if property.name == :ensure and current_value == :absent
          absent = true
        end
        prophash
      }
    end

    newproperty(:roles, :parent => Puppet::Property::List, :required_features => :manages_solaris_rbac) do
      desc "The roles the user has.  Multiple roles should be
        specified as an array."

      def membership
        :role_membership
      end

      validate do |value|
        if value =~ /^\d+$/
          raise ArgumentError, "Role names must be provided, not numbers"
        end
        raise ArgumentError, "Role names must be provided as an array, not a comma-separated list" if value.include?(",")
      end
    end

    #autorequire the roles that the user has
    autorequire(:user) do
      reqs = []

      if roles_property = @parameters[:roles] and roles = roles_property.should
        reqs += roles.split(',')
      end

      reqs
    end

    newparam(:role_membership) do
      desc "Whether specified roles should be considered the **complete list**
        (`inclusive`) or the **minimum list** (`minimum`) of roles the user
        has. Defaults to `minimum`."

      newvalues(:inclusive, :minimum)

      defaultto :minimum
    end

    newproperty(:auths, :parent => Puppet::Property::List, :required_features => :manages_solaris_rbac) do
      desc "The auths the user has.  Multiple auths should be
        specified as an array."

      def membership
        :auth_membership
      end

      validate do |value|
        if value =~ /^\d+$/
          raise ArgumentError, "Auth names must be provided, not numbers"
        end
        raise ArgumentError, "Auth names must be provided as an array, not a comma-separated list" if value.include?(",")
      end
    end

    newparam(:auth_membership) do
      desc "Whether specified auths should be considered the **complete list**
        (`inclusive`) or the **minimum list** (`minimum`) of auths the user
        has. Defaults to `minimum`."

      newvalues(:inclusive, :minimum)

      defaultto :minimum
    end

    newproperty(:profiles, :parent => Puppet::Property::OrderedList, :required_features => :manages_solaris_rbac) do
      desc "The profiles the user has.  Multiple profiles should be
        specified as an array."

      def membership
        :profile_membership
      end

      validate do |value|
        if value =~ /^\d+$/
          raise ArgumentError, "Profile names must be provided, not numbers"
        end
        raise ArgumentError, "Profile names must be provided as an array, not a comma-separated list" if value.include?(",")
      end
    end

    newparam(:profile_membership) do
      desc "Whether specified roles should be treated as the **complete list**
        (`inclusive`) or the **minimum list** (`minimum`) of roles
        of which the user is a member. Defaults to `minimum`."

      newvalues(:inclusive, :minimum)

      defaultto :minimum
    end

    newproperty(:keys, :parent => Puppet::Property::KeyValue, :required_features => :manages_solaris_rbac) do
      desc "Specify user attributes in an array of key = value pairs."

      def membership
        :key_membership
      end

      validate do |value|
        raise ArgumentError, "Key/value pairs must be separated by an =" unless value.include?("=")
      end
    end

    newparam(:key_membership) do
      desc "Whether specified key/value pairs should be considered the
        **complete list** (`inclusive`) or the **minimum list** (`minimum`) of
        the user's attributes. Defaults to `minimum`."

      newvalues(:inclusive, :minimum)

      defaultto :minimum
    end

    newproperty(:project, :required_features => :manages_solaris_rbac) do
      desc "The name of the project associated with a user."
    end

    newparam(:ia_load_module, :required_features => :manages_aix_lam) do
      desc "The name of the I&A module to use to manage this user."
    end

    newproperty(:attributes, :parent => Puppet::Property::KeyValue, :required_features => :manages_aix_lam) do
      desc "Specify AIX attributes for the user in an array of attribute = value pairs."

      def membership
        :attribute_membership
      end

      def delimiter
        " "
      end

      validate do |value|
        raise ArgumentError, "Attributes value pairs must be separated by an =" unless value.include?("=")
      end
    end

    newparam(:attribute_membership) do
      desc "Whether specified attribute value pairs should be treated as the
        **complete list** (`inclusive`) or the **minimum list** (`minimum`) of
        attribute/value pairs for the user. Defaults to `minimum`."

      newvalues(:inclusive, :minimum)

      defaultto :minimum
    end

  end
end


text:
"""empty message

Revision ID: 43bdec0aeb4
Revises: 1392585412d
Create Date: 2015-09-02 10:43:25.250039

"""

# revision identifiers, used by Alembic.
revision = '43bdec0aeb4'
down_revision = '1392585412d'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('invite_codes',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('department_id', sa.Integer(), nullable=True),
    sa.Column('code', sa.String(length=36), nullable=False),
    sa.Column('used', sa.Boolean(), nullable=True),
    sa.ForeignKeyConstraint(['department_id'], ['departments.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('code')
    )
    op.create_index(op.f('ix_invite_codes_id'), 'invite_codes', ['id'], unique=False)
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_invite_codes_id'), table_name='invite_codes')
    op.drop_table('invite_codes')
    ### end Alembic commands ###


text:
package configs

import (
	"fmt"
	"os"
	"strconv"
)

const (
	Wildcard = -1
)

type Device struct {
	DeviceRule

	// Path to the device.
	Path string `json:"path"`

	// FileMode permission bits for the device.
	FileMode os.FileMode `json:"file_mode"`

	// Uid of the device.
	Uid uint32 `json:"uid"`

	// Gid of the device.
	Gid uint32 `json:"gid"`
}

// DevicePermissions is a cgroupv1-style string to represent device access. It
// has to be a string for backward compatibility reasons, hence why it has
// methods to do set operations.
type DevicePermissions string

const (
	deviceRead uint = (1 << iota)
	deviceWrite
	deviceMknod
)

func (p DevicePermissions) toSet() uint {
	var set uint
	for _, perm := range p {
		switch perm {
		case 'r':
			set |= deviceRead
		case 'w':
			set |= deviceWrite
		case 'm':
			set |= deviceMknod
		}
	}
	return set
}

func fromSet(set uint) DevicePermissions {
	var perm string
	if set&deviceRead == deviceRead {
		perm += "r"
	}
	if set&deviceWrite == deviceWrite {
		perm += "w"
	}
	if set&deviceMknod == deviceMknod {
		perm += "m"
	}
	return DevicePermissions(perm)
}

// Union returns the union of the two sets of DevicePermissions.
func (p DevicePermissions) Union(o DevicePermissions) DevicePermissions {
	lhs := p.toSet()
	rhs := o.toSet()
	return fromSet(lhs | rhs)
}

// Difference returns the set difference of the two sets of DevicePermissions.
// In set notation, A.Difference(B) gives you A\B.
func (p DevicePermissions) Difference(o DevicePermissions) DevicePermissions {
	lhs := p.toSet()
	rhs := o.toSet()
	return fromSet(lhs &^ rhs)
}

// Intersection computes the intersection of the two sets of DevicePermissions.
func (p DevicePermissions) Intersection(o DevicePermissions) DevicePermissions {
	lhs := p.toSet()
	rhs := o.toSet()
	return fromSet(lhs & rhs)
}

// IsEmpty returns whether the set of permissions in a DevicePermissions is
// empty.
func (p DevicePermissions) IsEmpty() bool {
	return p == DevicePermissions("")
}

// IsValid returns whether the set of permissions is a subset of valid
// permissions (namely, {r,w,m}).
func (p DevicePermissions) IsValid() bool {
	return p == fromSet(p.toSet())
}

type DeviceType rune

const (
	WildcardDevice DeviceType = 'a'
	BlockDevice    DeviceType = 'b'
	CharDevice     DeviceType = 'c' // or 'u'
	FifoDevice     DeviceType = 'p'
)

func (t DeviceType) IsValid() bool {
	switch t {
	case WildcardDevice, BlockDevice, CharDevice, FifoDevice:
		return true
	default:
		return false
	}
}

func (t DeviceType) CanMknod() bool {
	switch t {
	case BlockDevice, CharDevice, FifoDevice:
		return true
	default:
		return false
	}
}

func (t DeviceType) CanCgroup() bool {
	switch t {
	case WildcardDevice, BlockDevice, CharDevice:
		return true
	default:
		return false
	}
}

type DeviceRule struct {
	// Type of device ('c' for char, 'b' for block). If set to 'a', this rule
	// acts as a wildcard and all fields other than Allow are ignored.
	Type DeviceType `json:"type"`

	// Major is the device's major number.
	Major int64 `json:"major"`

	// Minor is the device's minor number.
	Minor int64 `json:"minor"`

	// Permissions is the set of permissions that this rule applies to (in the
	// cgroupv1 format -- any combination of "rwm").
	Permissions DevicePermissions `json:"permissions"`

	// Allow specifies whether this rule is allowed.
	Allow bool `json:"allow"`
}

func (d *DeviceRule) CgroupString() string {
	var (
		major = strconv.FormatInt(d.Major, 10)
		minor = strconv.FormatInt(d.Minor, 10)
	)
	if d.Major == Wildcard {
		major = "*"
	}
	if d.Minor == Wildcard {
		minor = "*"
	}
	return fmt.Sprintf("%c %s:%s %s", d.Type, major, minor, d.Permissions)
}


text:
#pragma once

#include <tuple>

#include <sqlpp17/core/clause_fwd.h>
#include <sqlpp17/core/result_row.h>
#include <sqlpp17/core/statement.h>
#include <sqlpp17/core/type_traits.h>
#include <sqlpp17/core/wrapped_static_assert.h>

namespace sqlpp
{
  template <typename... Flags>
  struct select_flags_t
  {
    std::tuple<Flags...> _flags;
  };

  template <typename... Flags>
  struct nodes_of<select_flags_t<Flags...>>
  {
    using type = type_vector<Flags...>;
  };

  template <typename Table>
  constexpr auto clause_tag<select_flags_t<Table>> = ::std::string_view{"select_flags"};

  template <typename... Flags, typename Statement>
  class clause_base<select_flags_t<Flags...>, Statement>
  {
  public:
    template <typename OtherStatement>
    clause_base(const clause_base<select_flags_t<Flags...>, OtherStatement>& s) : _flags(s._flags)
    {
    }

    clause_base(const select_flags_t<Flags...>& f) : _flags(f._flags)
    {
    }

    std::tuple<Flags...> _flags;
  };

  template <typename Context, typename... Flags, typename Statement>
  [[nodiscard]] auto to_sql_string(Context& context, const clause_base<select_flags_t<Flags...>, Statement>& t)
  {
    return (std::string{} + ... + to_sql_string(context, std::get<Flags>(t._flags)));
  }

  SQLPP_WRAPPED_STATIC_ASSERT(assert_select_flags_args_are_valid, "select flags() args must be valid select_flags");
  SQLPP_WRAPPED_STATIC_ASSERT(assert_select_flags_args_are_unique, "select flags() args must have unique");

  template <typename... T>
  constexpr auto check_select_flags_arg(const T&...)
  {
    if constexpr (!(true && ... && is_select_flag_v<T>))
    {
      return failed<assert_select_flags_args_are_valid>{};
    }
    else if constexpr (type_set<T...>().size() != sizeof...(T))
    {
      return failed<assert_select_flags_args_are_unique>{};
    }
    else
      return succeeded{};
  }

  struct no_select_flags_t
  {
  };

  template <typename Statement>
  class clause_base<no_select_flags_t, Statement>
  {
  public:
    template <typename OtherStatement>
    constexpr clause_base(const clause_base<no_select_flags_t, OtherStatement>& s)
    {
    }

    constexpr clause_base() = default;

    template <typename... Fields>
    [[nodiscard]] constexpr auto flags(Fields... flags) const
    {
      constexpr auto _check = check_select_flags_arg(flags...);
      if constexpr (_check)
      {
        return new_statement(*this, select_flags_t<Fields...>{std::tuple(flags...)});
      }
      else
      {
        return ::sqlpp::bad_expression_t{_check};
      }
    }

    template <typename... Fields>
    [[nodiscard]] constexpr auto flags(std::tuple<Fields...> flags) const
    {
      constexpr auto _check = check_select_flags_arg(std::declval<Fields>()...);
      if constexpr (_check)
      {
        return new_statement(*this, select_flags_t<Fields...>{flags});
      }
      else
      {
        return ::sqlpp::bad_expression_t{_check};
      }
    }
  };

  template <typename Context, typename Statement>
  [[nodiscard]] auto to_sql_string(Context& context, const clause_base<no_select_flags_t, Statement>& t)
  {
    return std::string{};
  }

  template <typename... Fields>
  [[nodiscard]] constexpr auto select_flags(Fields&&... flags)
  {
    return statement<no_select_flags_t>{}.flags(std::forward<Fields>(flags)...);
  }
}  // namespace sqlpp


text:
<?php

namespace Vegas;

/**
 * Interface BootstrapInterface
 * @package Vegas
 */
interface BootstrapInterface
{
    /**
     * Executes all bootstrap initialization methods
     * This method can be overloaded to load own initialization method.
     * @return mixed
     */
    public function setup();

    /**
     * @return mixed
     */
    public function getApplication();

    /**
     * @return mixed
     */
    public function getDI();

    /**
     * Runs application
     *
     * @return mixed
     */
    public function run();
}


text:
import {RouterPlugin} from '@dokit/web-core'
import H5Door from './ToolH5Door.vue'

export default new RouterPlugin({
  nameZh: '任意门',
  name: 'h5-door',
  icon: 'https://pt-starimg.didistatic.com/static/starimg/img/FHqpI3InaS1618997548865.png',
  component: H5Door
})


text:
<refentry xmlns="http://docbook.org/ns/docbook"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:xi="http://www.w3.org/2001/XInclude"
          xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          version="5.0" xml:id="region.after.extent">
<refmeta>
<refentrytitle>region.after.extent</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">length</refmiscinfo>
</refmeta>
<refnamediv>
<refname>region.after.extent</refname>
<refpurpose>Specifies the height of the footer.</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment xml:id="region.after.extent.frag">
<xsl:param name="region.after.extent">0.4in</xsl:param>
</src:fragment>
</refsynopsisdiv>

<refsection><info><title>Description</title></info>

<para>The region after extent is the height of the area where footers
are printed.
</para>

</refsection>
</refentry>


text:
package com.amazonaws.services.dynamodbv2.document.internal;

import java.util.Iterator;

import com.amazonaws.services.dynamodbv2.document.Page;

/**
 * @param <T> resource type
 * @param <R> low level result type
 */
class PageIterator<T,R> implements Iterator<Page<T,R>> {

    private Page<T,R> page;
    private final PageBasedCollection<T,R> col;

    PageIterator(PageBasedCollection<T,R> col) {
        this.col = col;
    }

    @Override
    public boolean hasNext() {
        Integer max = col.getMaxResultSize();
        if (max != null && max.intValue() <= 0)
            return false;
        return page == null || page.hasNextPage();
    }

    @Override
    public Page<T,R> next() {
        if (page == null) {
            page = col.firstPage();
        } else {
            page = page.nextPage();
            col.setLastLowLevelResult(page.getLowLevelResult());
        }
        return page;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Collection is read-only");
    }
}


text:
<?php

namespace Functional\Tests;

use ArrayIterator;
use stdClass;

use function Functional\maximum;

class MaximumTest extends AbstractTestCase
{
    public function setUp(): void
    {
        parent::setUp();
        $this->list = [1, "foo", 5.1, 5, "5.2", true, false, [], new stdClass()];
        $this->listIterator = new ArrayIterator($this->list);
        $this->hash = [
            'k1' => 1,
            'k2' => '5.2',
            'k3' => 5,
            'k4' => '5.1',
            'k5' => 10.2,
            'k6' => true,
            'k7' => [],
            'k8' => new stdClass(),
        ];
        $this->hashIterator = new ArrayIterator($this->hash);
    }

    public function testExtractingMaximumValue(): void
    {
        self::assertEquals('5.2', maximum($this->list));
        self::assertEquals('5.2', maximum($this->listIterator));
        self::assertEquals(10.2, maximum($this->hash));
        self::assertEquals(10.2, maximum($this->hashIterator));
    }

    public function testSpecialCaseNull(): void
    {
        self::assertSame(-1, maximum([-1]));
    }

    public function testSpecialCaseSameValueDifferentTypes(): void
    {
        self::assertSame(1, maximum([0, 1, 0.0, 1.0, "0", "1", "0.0", "1.0"]));
    }

    public function testPassNoCollection(): void
    {
        $this->expectArgumentError('Functional\maximum() expects parameter 1 to be array or instance of Traversable');
        maximum('invalidCollection');
    }
}


text:
package io.magentys.cinnamon.webdriver.actions.basic;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.openqa.selenium.WebElement;

import static org.mockito.Mockito.verify;
import static org.mockito.internal.verification.VerificationModeFactory.times;

public class TypeTextActionTest {

    @Mock
    private WebElement mockElement;

    @Before
    public void setUpMocks() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void shouldInvokeSendKeys() {
        TypeTextAction action = new TypeTextAction();
        action.perform(mockElement);
        verify(mockElement, times(1)).sendKeys();
    }
}


text:
package com.cisco.axl.api._8;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for RRouteGroup complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="RRouteGroup">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence minOccurs="0">
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}Name" minOccurs="0"/>
 *         <element name="dialPlanWizardGenld" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
 *         <element name="distributionAlgorithm" type="{http://www.cisco.com/AXL/API/8.0}XDistributeAlgorithm" minOccurs="0"/>
 *         <element name="members" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence minOccurs="0">
 *                   <element name="member" type="{http://www.cisco.com/AXL/API/8.0}RRouteGroupMember" maxOccurs="unbounded" minOccurs="0"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *       <attribute name="uuid" type="{http://www.cisco.com/AXL/API/8.0}XUUID" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RRouteGroup", propOrder = {
    "name",
    "dialPlanWizardGenld",
    "distributionAlgorithm",
    "members"
})
public class RRouteGroup {

    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "Name")
    protected String name;
    protected String dialPlanWizardGenld;
    protected String distributionAlgorithm;
    protected RRouteGroup.Members members;
    @XmlAttribute
    protected String uuid;

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the dialPlanWizardGenld property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDialPlanWizardGenld() {
        return dialPlanWizardGenld;
    }

    /**
     * Sets the value of the dialPlanWizardGenld property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDialPlanWizardGenld(String value) {
        this.dialPlanWizardGenld = value;
    }

    /**
     * Gets the value of the distributionAlgorithm property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDistributionAlgorithm() {
        return distributionAlgorithm;
    }

    /**
     * Sets the value of the distributionAlgorithm property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDistributionAlgorithm(String value) {
        this.distributionAlgorithm = value;
    }

    /**
     * Gets the value of the members property.
     *
     * @return
     *     possible object is
     *     {@link RRouteGroup.Members }
     *
     */
    public RRouteGroup.Members getMembers() {
        return members;
    }

    /**
     * Sets the value of the members property.
     *
     * @param value
     *     allowed object is
     *     {@link RRouteGroup.Members }
     *
     */
    public void setMembers(RRouteGroup.Members value) {
        this.members = value;
    }

    /**
     * Gets the value of the uuid property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUuid() {
        return uuid;
    }

    /**
     * Sets the value of the uuid property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUuid(String value) {
        this.uuid = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence minOccurs="0">
     *         <element name="member" type="{http://www.cisco.com/AXL/API/8.0}RRouteGroupMember" maxOccurs="unbounded" minOccurs="0"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "member"
    })
    public static class Members {

        protected List<RRouteGroupMember> member;

        /**
         * Gets the value of the member property.
         *
         *

         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a set method for the member property.
         *
         *

         * For example, to add a new item, do as follows:
         *

         *    getMember().add(newItem);
         *

         *
         *
         *

         * Objects of the following type(s) are allowed in the list
         * {@link RRouteGroupMember }
         *
         *
         */
        public List<RRouteGroupMember> getMember() {
            if (member == null) {
                member = new ArrayList<RRouteGroupMember>();
            }
            return this.member;
        }

    }

}


text:
/**********************************************************
// Author   : K.(k79k06k02k)
// FileName : AssetBundleOther.cs
**********************************************************/
using UnityEngine;
using UnityEditor;
using System.Text;

public class AssetBundleOther : AssetPostprocessor
{
    public static void ShowAllAssetBundleNames()
    {
        StringBuilder sb = new StringBuilder();
        string[] assetBundleNames = AssetDatabase.GetAllAssetBundleNames();

        foreach (string str in assetBundleNames)
            sb.Append(str + "\n");

        Debug.Log("AssetBundleNames:\n" + sb.ToString());
    }

    void OnPostprocessAssetbundleNameChanged(string path, string previous, string next)
    {
        Debug.Log("AB: " + path + "\told: " + previous + "\tnew: " + next);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#000000</color>
</resources>


text:
package boofcv.alg.feature.detect.squares;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * @author Peter Abeles
 */
public class TestSquareGrid {

	@Test
	public void get() {
		SquareGrid grid = TestSquareGridTools.createGrid(3,4);

		assertTrue(grid.nodes.get(0)==grid.get(0,0));
		assertTrue(grid.nodes.get(3)==grid.get(0,3));
		assertTrue(grid.nodes.get(2*4+1)==grid.get(2,1));
		assertTrue(grid.nodes.get(2*4)==grid.get(-1,0));
		assertTrue(grid.nodes.get(2*4+3)==grid.get(-1,-1));

	}

	@Test
	public void getCornerByIndex() {
		SquareGrid grid = TestSquareGridTools.createGrid(3,4);

		assertTrue(grid.get(0,0)==grid.getCornerByIndex(0));
		assertTrue(grid.get(0,3)==grid.getCornerByIndex(1));
		assertTrue(grid.get(2,3)==grid.getCornerByIndex(2));
		assertTrue(grid.get(2,0) == grid.getCornerByIndex(3));
	}

	@Test
	public void getCornerIndex() {
		SquareGrid grid = TestSquareGridTools.createGrid(3,4);

		assertTrue(0==grid.getCornerIndex(grid.get(0, 0)));
		assertTrue(1==grid.getCornerIndex(grid.get(0, 3)));
		assertTrue(2==grid.getCornerIndex(grid.get(2, 3)));
		assertTrue(3==grid.getCornerIndex(grid.get(2, 0)));
	}
}


text:
package de.pifpafpuf.web.urlparam;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import de.pifpafpuf.web.urlparam.BooleanCodec;
import de.pifpafpuf.web.urlparam.EnumCodec;
import de.pifpafpuf.web.urlparam.IntegerCodec;

public class CodecTest {
  private static enum Num {
    ONE, TWO, THREE;
  }

  @Test
  public void integerTest() {
    int value = IntegerCodec.INSTANCE.get("1111");
    assertEquals(1111, value);
    String encoded = IntegerCodec.INSTANCE.asString(1234);
    assertEquals("1234", encoded);

    Integer nullValue = IntegerCodec.INSTANCE.get("xyz");
    assertNull(nullValue);
  }

  @Test
  public void booleanTest() {
    BooleanCodec codec = BooleanCodec.INSTANCE;
    boolean value = codec.get("true");
    assertTrue(value);
    value = BooleanCodec.INSTANCE.get("1");
    assertTrue(value);

    value = BooleanCodec.INSTANCE.get("false");
    assertFalse(value);
    value = BooleanCodec.INSTANCE.get("0");
    assertFalse(value);

    assertEquals("true", codec.asString(true));
    assertEquals("false", codec.asString(false));

    assertNull(codec.get("blabla"));
  }
  @Test
  public void EnumTest() {
    EnumCodec<Num> codec = new EnumCodec<Num>(Num.values());
    for(String name : new String[] {"ONE", "TWO", "THREE"}) {
      Num value = codec.get(name);
      assertEquals(name, value.toString());
    }
    assertNull(codec.get("faselbla"));
    for(Num n : Num.values()) {
      assertEquals(n.name(), codec.asString(n));
    }
  }

}


text:
namespace OpenApoc
{

class Palette;
class RGBImage;
class RendererImageData;
class ImageSet;

enum class ImageLockUse
{
	Read,
	Write,
	ReadWrite,
};

class Image : public ResObject
{
  protected:
	Image(Vec2<unsigned int> size);

  public:
	virtual ~Image();
	Vec2<unsigned int> size;

	sp<RendererImageData> rendererPrivateData;
	bool dirty;
	Rect<unsigned int> bounds;

	wp<ImageSet> owningSet;
	unsigned indexInSet;
};

class LazyImage : public Image
{
  private:
	sp<Image> realImage;

  public:
	LazyImage();
	~LazyImage() override = default;
	sp<Image> &getRealImage();
};

// A surface is an image you can render to. No SW locking is allowed!
class Surface : public Image
{
  public:
	Surface(Vec2<unsigned int> size);
	~Surface() override;
};

class PaletteImage : public Image
{
  private:
	friend class PaletteImageLock;
	std::unique_ptr<uint8_t[]> indices;

  public:
	PaletteImage(Vec2<unsigned int> size, uint8_t initialIndex = 0);
	~PaletteImage() override;
	sp<RGBImage> toRGBImage(sp<Palette> p);
	static void blit(sp<PaletteImage> src, sp<PaletteImage> dst,
	                 Vec2<unsigned int> srcOffset = {0, 0}, Vec2<unsigned int> dstOffset = {0, 0});

	void calculateBounds();
};

class PaletteImageLock
{
  private:
	sp<PaletteImage> img;
	// Disallow copy
	PaletteImageLock(const PaletteImageLock &) = delete;
	ImageLockUse use;

  public:
	PaletteImageLock(sp<PaletteImage> img, ImageLockUse use = ImageLockUse::Write);
	~PaletteImageLock();
	uint8_t get(const Vec2<unsigned int> &pos) const
	{
		LogAssert(this->use == ImageLockUse::Read || this->use == ImageLockUse::ReadWrite);
		unsigned offset = pos.y * this->img->size.x + pos.x;
		LogAssert(offset < this->img->size.x * this->img->size.y);
		return this->img->indices[offset];
	}
	void set(const Vec2<unsigned int> &pos, const uint8_t idx)
	{
		LogAssert(this->use == ImageLockUse::Write || this->use == ImageLockUse::ReadWrite);
		unsigned offset = pos.y * this->img->size.x + pos.x;
		LogAssert(offset < this->img->size.x * this->img->size.y);
		this->img->indices[offset] = idx;
	}

	// FIXME: Magic backdoor to the index data
	void *getData();
};

class RGBImage : public Image
{
  private:
	friend class RGBImageLock;
	std::unique_ptr<Colour[]> pixels;

  public:
	RGBImage(Vec2<unsigned int> size, Colour initialColour = Colour(0, 0, 0, 0));
	~RGBImage() override;
	void saveBitmap(const UString &filename);
	static void blit(sp<RGBImage> src, sp<RGBImage> dst, Vec2<unsigned int> srcOffset = {0, 0},
	                 Vec2<unsigned int> dstOffset = {0, 0});
};

class RGBImageLock
{
  private:
	sp<RGBImage> img;
	// Disallow copy
	RGBImageLock(const RGBImageLock &) = delete;
	ImageLockUse use;

  public:
	RGBImageLock(sp<RGBImage> img, ImageLockUse use = ImageLockUse::Write);
	~RGBImageLock();
	Colour get(const Vec2<unsigned int> &pos) const
	{
		LogAssert(this->use == ImageLockUse::Read || this->use == ImageLockUse::ReadWrite);
		unsigned offset = pos.y * this->img->size.x + pos.x;
		LogAssert(offset < this->img->size.x * this->img->size.y);
		return this->img->pixels[offset];
	}
	void set(const Vec2<unsigned int> &pos, const Colour &c)
	{
		LogAssert(this->use == ImageLockUse::Write || this->use == ImageLockUse::ReadWrite);
		unsigned offset = pos.y * this->img->size.x + pos.x;
		LogAssert(offset < this->img->size.x * this->img->size.y);
		this->img->pixels[offset] = c;
	}

	// FIXME: Magic backdoor to the RGBA data
	void *getData();
};

class ImageSet : public ResObject
{
  public:
	std::vector<sp<Image>> images;
	Vec2<unsigned int> maxSize;

	sp<RendererImageData> rendererPrivateData;
};

}; // namespace OpenApoc


text:
using System;
using System.Linq;
using System.Collections.Generic;
using p5.exp;
using p5.core;
using p5.mail.helpers;
using MimeKit;
using MailKit.Net.Pop3;

namespace p5.mail
{
    /// <summary>
    ///     Class wrapping the POP3 email features of Phosphorus Five.
    /// </summary>
    public static class Pop3
    {
        // Contains all "standard headers", which we handle in special cases, and should not be handled by generic header handler.
        static List<HeaderId> _excludedHeaders;

        /*
         * Static CTOR to initialize _excludedHeaders, containing list of all headers to not handle in generic handler.
         */
        static Pop3 ()
        {
            _excludedHeaders = new List<HeaderId> (new HeaderId [] {
                HeaderId.Bcc, HeaderId.Cc, HeaderId.Date, HeaderId.From, HeaderId.Importance, HeaderId.InReplyTo, HeaderId.MessageId,
                HeaderId.MimeVersion, HeaderId.Priority, HeaderId.References, HeaderId.ReplyTo, HeaderId.ResentBcc, HeaderId.ResentCc,
                HeaderId.ResentDate, HeaderId.ResentFrom, HeaderId.ResentReplyTo, HeaderId.ResentSender, HeaderId.ResentTo,
                HeaderId.Sender, HeaderId.Subject, HeaderId.To, HeaderId.XPriority});
        }

        /// <summary>
        ///     Retrieves messages from a POP3 server.
        /// </summary>
        /// <param name="context">Application Context</param>
        /// <param name="e">Active Event arguments</param>
        [ActiveEvent (Name = "p5.pop3.get")]
        public static void p5_pop3_get (ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we remove arguments supplied.
            using (new ArgsRemover (e.Args, true)) {

                // Creating our POP3 client.
                using (var client = new Pop3Client ()) {

                    // Connecting to POP3 server using helper from Common class.
                    Common.ConnectServer (context, client, e.Args, "pop3");

                    // Making sure we're able to post QUIT signal when done, regardless of what happens inside of this code.
                    try {

                        // Figuring out how many messages to retrieve, defaulting to "5", if not explicitly told something else by caller,
                        // making sure we never try to retrieve more messages than server actually has.
                        var noMessages = Math.Min (client.Count, e.Args.GetExChildValue ("count", context, 5));

                        // Fetching messages from server, but not any more messages than caller requested, or number of available messages.
                        for (var idxMsg = 0; idxMsg < noMessages; idxMsg++) {

                            // Process message returned from POP3 server by building Node structure wrapping message.
                            var msgNode = ProcessMessage (
                                context,
                                e.Args,
                                client.GetMessage (idxMsg));

                            // Handle message after processing.
                            e.Args.Add (msgNode);

                            // Checking if we should delete message from server.
                            if (e.Args.GetExChildValue ("delete", context, false)) {

                                // Deleting message from server.
                                client.DeleteMessage (idxMsg);
                            }
                        }

                        // Checking to see if caller provided a lambda callback, at which case, we invoke it before exiting scope.
                        var lambda = e.Args [".onfinished"];
                        if (lambda != null) {

                            // Invoking lambda callback, letting caller do his thing.
                            context.RaiseEvent ("eval-mutable", lambda);
                        }

                        // Disconnecting from server, making sure we send the QUIT signal.
                        client.Disconnect (true);

                    } catch {

                        // Disconnecting from server, making sure we do NOT send the QUIT signal.
                        // Otherwise emails will be registered as "read" (or deleted in fact) on POP3 server.
                        client.Disconnect (false);
                        throw;

                    }
                }
            }
        }

        #region [ -- Private helper methods -- ]

        /*
         * Helper to process on message retrieved from POP3 server.
         */
        static Node ProcessMessage (
            ApplicationContext context,
            Node args,
            MimeMessage message)
        {
            // Node structure containing all headers, content, and other properties of message.
            Node msgNode = new Node ("envelope");

            // Processing message, headers first.
            ProcessMessageHeaders (context, msgNode, message);

            // Then content of message, making sure MimeEntity never leaves this method.
            msgNode.Value = message.Body;
            try {
                msgNode.AddRange (args.Children.Where (ix => ix.Name == "attachment-folder" || ix.Name == "decrypt").Select (ix => ix.Clone ()));
                context.RaiseEvent (".p5.mime.parse-native", msgNode);

            } finally {

                msgNode.Value = null;
                msgNode.RemoveAll (ix => ix.Name == "attachment-folder" || ix.Name == "decrypt");
            }

            // Making sure ID of email is value of [envelope] node.
            msgNode.Value = message.MessageId;

            // Return node containing processed message.
            return msgNode;
        }

        /*
         * Adds up all headers into given node.
         */
        static void ProcessMessageHeaders (
            ApplicationContext context,
            Node msgNode,
            MimeMessage message)
        {
            // Subject.
            msgNode.Add ("Subject", message.Subject);

            // All address fields.
            GetAddresses (context, msgNode, message.From, "From");
            GetAddresses (context, msgNode, message.ResentFrom, "Resent-From");
            GetAddresses (context, msgNode, message.Bcc, "Bcc");
            GetAddresses (context, msgNode, message.ResentBcc, "Resent-Bcc");
            GetAddresses (context, msgNode, message.Cc, "Cc");
            GetAddresses (context, msgNode, message.ResentCc, "Resent-Cc");
            GetAddresses (context, msgNode, message.ReplyTo, "Reply-To");
            GetAddresses (context, msgNode, message.ResentReplyTo, "Resent-Reply-To");
            GetAddresses (context, msgNode, message.To, "To");
            GetAddresses (context, msgNode, message.ResentTo, "Resent-To");

            // Other standard headers.
            msgNode.Add ("Date", message.Date.DateTime);

            if (!string.IsNullOrEmpty (message.ResentMessageId))
                msgNode.Add ("Resent-Message-ID", message.ResentMessageId);

            if (message.Sender != null)
                msgNode.Add ("Sender", null, new Node [] { new Node (message.Sender.Name ?? "", message.Sender.Address) });

            if (message.ResentSender != null)
                msgNode.Add ("Resent-Sender", null, new Node [] { new Node (message.ResentSender.Name ?? "", message.ResentSender.Address) });

            if (message.MimeVersion != null)
                msgNode.Add ("MIME-Version", message.MimeVersion.ToString ());

            if (message.ResentDate != DateTimeOffset.MinValue)
                msgNode.Add ("Resent-Date", message.ResentDate.DateTime);

            if (message.Importance != MessageImportance.Normal)
                msgNode.Add ("Importance", message.Importance.ToString ());

            if (!string.IsNullOrEmpty (message.InReplyTo))
                msgNode.Add ("In-Reply-To", message.InReplyTo);

            if (message.Priority != MessagePriority.Normal)
                msgNode.Add ("Priority", message.Priority.ToString ());

            // Looping through and adding all IDs for messages this message is referencing.
            foreach (var id in message.References) {

                // Adding currently iterated References ID back to caller.
                msgNode.FindOrInsert ("References").Add (id);
            }

            // Non-standard headers.
            foreach (var idxHeader in message.Headers.Where (ix => _excludedHeaders.IndexOf (ix.Id) == -1)) {

                // Retrieving currently iterated header
                msgNode.FindOrInsert ("X-Headers").Add (idxHeader.Field, idxHeader.Value);
            }
        }

        /*
         * Returns all addresses from list as name node.
         */
        static void GetAddresses (
            ApplicationContext context,
            Node msgNode,
            InternetAddressList list,
            string name)
        {
            // Looping through each address in list.
            foreach (InternetAddress idxAdr in list) {

                // Appending currently iterated address to args.
                if (idxAdr is MailboxAddress)
                    msgNode.FindOrInsert (name).Add (idxAdr.Name, ((MailboxAddress)idxAdr).Address);
                // TODO: UndisclosedAddress!

            }
        }

        #endregion
    }
}


text:
<?php
namespace Craft;

use Twig_Extension;
use Twig_Filter_Method;

class ImgsrcTwigExtension extends Twig_Extension
{
	public function getName()
	{
		return 'Imgsrc';
	}

	public function getFunctions()
	{
		return array('imgsrc' => new \Twig_Function_Method($this, 'imgsrc'));
	}

	public function imgsrc($width, $height=null, $bgColor='', $txtColor='', $text='') {
		if ($height==null) {
			$height = $width;
		}
		$str = "http://imgsrc.me/{$width}x${height}/{$bgColor}/$txtColor";
		if (strlen($text) > 0) {
			$str .= "$text?showDimensions=0";
		}
		return $str;
	}
}