text:
package com.oembedler.moon.graphql.boot.test.springGraphqlCommon;

import com.oembedler.moon.graphql.GraphQLSchemaBeanFactory;
import com.oembedler.moon.graphql.boot.SpringGraphQLCommonAutoConfiguration;
import com.oembedler.moon.graphql.boot.test.AbstractAutoConfigurationTest;
import com.oembedler.moon.graphql.engine.GraphQLSchemaBuilder;
import com.oembedler.moon.graphql.engine.GraphQLSchemaConfig;
import graphql.schema.GraphQLSchema;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @author oEmbedler Inc.
 */
@Ignore
public class SpringGraphQLCommonAutoConfigurationTest extends AbstractAutoConfigurationTest {

    public SpringGraphQLCommonAutoConfigurationTest() {
        super(SpringGraphQLCommonAutoConfiguration.class);
    }

    @Configuration
    @ComponentScan("com.oembedler.moon.graphql.boot.test.springGraphqlCommon")
    static class EmptyConfiguration {
    }

    @Test
    public void appContextLoads() {
        load(EmptyConfiguration.class);
        GraphQLSchemaBeanFactory graphQLSchemaBeanFactory = this.getContext().getBean(GraphQLSchemaBeanFactory.class);
        GraphQLSchemaConfig graphQLSchemaConfig = this.getContext().getBean(GraphQLSchemaConfig.class);
        GraphQLSchemaBuilder graphQLSchemaBuilder = this.getContext().getBean(GraphQLSchemaBuilder.class);

        Assert.assertNotNull(this.getContext().getBean(GraphQLSchema.class));
        Assert.assertTrue(graphQLSchemaBeanFactory.containsBean(GraphQLSchemaBeanFactory.class));
        Assert.assertEquals(graphQLSchemaBeanFactory, graphQLSchemaBeanFactory.getBeanByType(GraphQLSchemaBeanFactory.class));
        Assert.assertEquals(graphQLSchemaBeanFactory, graphQLSchemaBuilder.getGraphQLSchemaBeanFactory());
        Assert.assertEquals(graphQLSchemaConfig, graphQLSchemaBuilder.getGraphQLSchemaConfig());
    }
}


text:
import * as mod0 from "./mod0"
import * as mod1 from "./mod1"
import * as mod2 from "./mod2"

declare var log: any

export function test() {
  log("indexed: index")
  mod0.test()
  mod1.test()
  mod2.test()
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
* Shift management controller
*/
class Shift extends CI_Controller
{
    /**
    * Constructor
    *
    * Requires user to be logged in
    */
    function __construct()
    {
        parent::__construct();
        if ($this->session->userdata('username') == false) {
            redirect('/user/login');
        }

        $this->lang->load('shift', $this->session->userdata('language'));
    }

    /**
    * Add shift action
    *
    * Add or update shift.
    * Requires 'start' and 'end' or 'bonus' and 'date', 'note' in $_POST
    * If 'shift_id' is set in $_POST it preforms db update
    */
    function add($ajax = false)
    {
        if ($this->input->post() != false) {

            // grab user input
            $shift_info = array(
                'shift_id' => $this->input->post('shift_id'),
                'date' => $this->input->post('date'),
                'start' => $this->input->post('start'),
                'end' => $this->input->post('end'),
                'bonus' => $this->input->post('bonus'),
                'note' => $this->input->post('note')
            );
            if ($shift_info['shift_id'] == false) {
                unset($shift_info['shift_id']);
            }

            // validate input
            if ($shift_info['date'] == false) {
                $data['notify'] = 'Date must be set';
            } else {
                $date = new DateTime($shift_info['date']);
                $shift_info['date'] = $date->format('Y-m-d');
            }
            $using_hours = ($shift_info['start'] != false
                && $shift_info['end'] != false) ? true : false;
            $using_bonus = ($shift_info['bonus'] != false) ? true : false;
            if ($using_hours == false && $using_bonus == false) {
                $data['notify'] = 'Set working hours or bonus';
            }

            // save shift info
            if (isset($data['notify']) == false) {
                $this->load->model('Shift_model');
                $shift_info['user_id_fk'] = $this->session->userdata('user_id');

                // bonus only
                if ($using_bonus == true) {
                    unset($shift_info['start']);
                    unset($shift_info['end']);
                    $shift_info['total'] = $shift_info['bonus'];

                    if ($this->Shift_model->save($shift_info) == false) {
                        $data['notify'] = 'Something went wrong';
                    } else {
                        $data['details'] = array('bonus' => $shift_info['bonus']);
                        $data['total'] = $shift_info['total'];
                        $data['note'] = $shift_info['note'];
                    }
                } else {
                    // using hours
                    unset($shift_info['bonus']);
                    $shift_details = $this->Shift_model->split($shift_info);
                    $total = $this->Shift_model->calculate(
                        $this->session->userdata('rate_id_fk'),
                        $shift_details);

                    $shift_info = array_merge($shift_info, $shift_details);
                    $shift_info['total'] = $total;
                    if ($this->Shift_model->save($shift_info) == false) {
                        $data['notify'] = 'Something went wrong';
                    } else {
                        $data['details'] = $shift_details;
                        $data['total'] = $total;
                        $data['note'] = $shift_info['note'];
                    }
                }
            }

            if (isset($shift_info['shift_id']) == true) {
                $url = $_SERVER['HTTP_REFERER']; // Ugly
                $url = str_replace($this->config->item('base_url'), '', $url);
                redirect($url);
            }

        }

        $data['canonical'] = 'shift/add';
        $data['title'] = 'Add shift';
        $data['ajax'] = $ajax;
        $data['username'] = $this->session->userdata('username');
        if ($ajax == false) $this->load->view('header', $data);
        $this->load->view('shift/add', $data);
        if ($ajax == false) $this->load->view('footer');
    }

    /**
    * Select period for report
    *
    * @param string $target Which action should be called afterwards
    * @param bool $ajax Render output without header and footer for ajax calls
    */
    function report_period($target, $ajax = false)
    {
        // generate report
        if ($this->input->post() != false) {
            $month = $this->input->post('month');
            redirect('/shift/report/' . $month);
        }

        // render view
        $data['canonical'] = 'shift/report';
        $data['title'] = lang('title_report_period');
        $data['username'] = $this->session->userdata('username');
        $data['target'] = $target;
        if ($ajax == false) $this->load->view('header', $data);
        $this->load->view('shift/period_select', $data);
        if ($ajax == false) $this->load->view('footer');
    }

    /**
    * PDF version of report()
    *
    * @param string $start Starting date or month (optional)
    * @param string $end Report end date (optional)
    */
    function pdf($start = false, $end = false)
    {
        // create report
        $this->load->model('Shift_model');
        $report = $this->Shift_model->generate_report(
            $start, $end,$this->session->userdata('user_id'));

        // render view
        $data['title'] = lang('title_report');;
        $data['username'] = $this->session->userdata('username');
        $data['report'] = $report;

        $html = $this->load->view('shift/pdf', $data, true);
        $this->load->helper('dompdf');
        pdf_create($html, '', true);
    }

    /**
    * Display shift summary
    *
    * @param string $start Starting date or month (optional)
    * @param string $end Report end date (optional)
    */
    function report($start = false, $end = false)
    {
        // create report
        $this->load->model('Shift_model');
        $report = $this->Shift_model->generate_report(
            $start, $end,$this->session->userdata('user_id'));

        // render view
        $data['canonical'] = 'shift/report';
        $data['title'] = lang('title_report');;
        $data['username'] = $this->session->userdata('username');
        $data['report'] = $report;
        $this->load->view('header', $data);
        $this->load->view('shift/report', $data);
        $this->load->view('footer');
    }

    /**
    * Delete shift
    *
    * Requires 'shift_id' in post
    */
    function delete()
    {
        if ($this->input->post() != false) {
            $id = $this->input->post('shift_id');

            if ($id != false) {
                $this->load->model('Shift_model');
                $this->Shift_model->delete($id);
            }
        }

        $url = $_SERVER['HTTP_REFERER']; // Ugly
        $url = str_replace($this->config->item('base_url'), '', $url);
        redirect($url);
    }

    /**
    * Display shift and user statistics
    */
    function stats()
    {
        $this->load->model('Shift_model');

        // grab data
        $id = $this->session->userdata('user_id');
        $data['summary_t'] = $this->Shift_model->summary_total($id);
        $data['summary_h'] = $this->Shift_model->summary_hours($id);
        $data['summary_a'] = $this->Shift_model->summary_avg_ph($id);

        // render view
        $data['canonical'] = 'shift/stats';
        $data['title'] = lang('title_report');;
        $data['username'] = $this->session->userdata('username');
        $this->load->view('header', $data);
        $this->load->view('shift/stats', $data);
        $this->load->view('footer');
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Reflection;
using DeveloperExperience = Internal.DeveloperExperience.DeveloperExperience;

#if FEATURE_RELIABILITY_CONTRACTS
using System.Runtime.ConstrainedExecution;
#endif
#if FEATURE_UNTRUSTED_CALLERS
using System.Security;
using System.Security.Permissions;
#endif

namespace System.Diagnostics.Contracts
{
    public static partial class Contract
    {
        #region Private Methods

        [ThreadStatic]
        private static bool t_assertingMustUseRewriter;

        /// <summary>
        /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly.
        /// It is NEVER used to indicate failure of actual contracts at runtime.
        /// </summary>
#if FEATURE_UNTRUSTED_CALLERS
#endif
        static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind)
        {
            //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite

            if (t_assertingMustUseRewriter)
            {
                System.Diagnostics.Debug.Assert(false, "Asserting that we must use the rewriter went reentrant. Didn't rewrite this System.Private.CoreLib?");
                return;
            }
            t_assertingMustUseRewriter = true;

            //// For better diagnostics, report which assembly is at fault.  Walk up stack and
            //// find the first non-mscorlib assembly.
            //Assembly thisAssembly = typeof(Contract).Assembly;  // In case we refactor mscorlib, use Contract class instead of Object.
            //StackTrace stack = new StackTrace();
            //Assembly probablyNotRewritten = null;
            //for (int i = 0; i < stack.FrameCount; i++)
            //{
            //    Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly;
            //    if (caller != thisAssembly)
            //    {
            //        probablyNotRewritten = caller;
            //        break;
            //    }
            //}

            //if (probablyNotRewritten == null)
            //    probablyNotRewritten = thisAssembly;
            //String simpleName = probablyNotRewritten.GetName().Name;
            String simpleName = "System.Private.CoreLib";
            System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null);

            t_assertingMustUseRewriter = false;
        }

        #endregion Private Methods

        #region Failure Behavior

        /// <summary>
        /// Without contract rewriting, failing Assert/Assumes end up calling this method.
        /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call
        /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by
        /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure.
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
        static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
        {
            if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
                throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
            Contract.EndContractBlock();

            // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message
            String displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException);

            if (displayMessage == null) return;

            System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException);
        }

#if !FEATURE_CORECLR
        /// <summary>
        /// Allows a managed application environment such as an interactive interpreter (IronPython)
        /// to be notified of contract failures and
        /// potentially "handle" them, either by throwing a particular exception type, etc.  If any of the
        /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
        /// not pop up an assert dialog box or trigger escalation policy.  Hooking this event requires
        /// full trust, because it will inform you of bugs in the appdomain and because the event handler
        /// could allow you to continue execution.
        /// </summary>
        public static event EventHandler<ContractFailedEventArgs> ContractFailed
        {
#if FEATURE_UNTRUSTED_CALLERS
#if FEATURE_LINK_DEMAND
            [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
            add
            {
                System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value;
            }
#if FEATURE_UNTRUSTED_CALLERS
#if FEATURE_LINK_DEMAND
            [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
            remove
            {
                System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value;
            }
        }
#endif // !FEATURE_CORECLR

        #endregion FailureBehavior
    }

#if !FEATURE_CORECLR  // Not usable on Silverlight by end users due to security, and full trust users have not yet expressed an interest.
    public sealed class ContractFailedEventArgs : EventArgs
    {
        private ContractFailureKind _failureKind;
        private String _message;
        private String _condition;
        private Exception _originalException;
        private bool _handled;
        private bool _unwind;

        internal Exception thrownDuringHandler;

#if FEATURE_RELIABILITY_CONTRACTS
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
        public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException)
        {
            Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException);
            _failureKind = failureKind;
            _message = message;
            _condition = condition;
            _originalException = originalException;
        }

        public String Message { get { return _message; } }
        public String Condition { get { return _condition; } }
        public ContractFailureKind FailureKind { get { return _failureKind; } }
        public Exception OriginalException { get { return _originalException; } }

        // Whether the event handler "handles" this contract failure, or to fail via escalation policy.
        public bool Handled
        {
            get { return _handled; }
        }

#if FEATURE_UNTRUSTED_CALLERS
#if FEATURE_LINK_DEMAND
        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
        public void SetHandled()
        {
            _handled = true;
        }

        public bool Unwind
        {
            get { return _unwind; }
        }

#if FEATURE_UNTRUSTED_CALLERS
#if FEATURE_LINK_DEMAND
        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
        public void SetUnwind()
        {
            _unwind = true;
        }
    }
#endif // !FEATURE_CORECLR

#if FEATURE_SERIALIZATION
    [Serializable]
#else
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")]
#endif
    [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")]
    internal sealed class ContractException : Exception
    {
        private readonly ContractFailureKind _Kind;
        private readonly string _UserMessage;
        private readonly string _Condition;

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public ContractFailureKind Kind { get { return _Kind; } }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public string Failure { get { return this.Message; } }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public string UserMessage { get { return _UserMessage; } }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public string Condition { get { return _Condition; } }

        // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT.
        private ContractException()
        {
            HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
        }

        public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException)
            : base(failure, innerException)
        {
            HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
            _Kind = kind;
            _UserMessage = userMessage;
            _Condition = condition;
        }
#if FEATURE_SERIALIZATION
        private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
            _Kind = (ContractFailureKind)info.GetInt32("Kind");
            _UserMessage = info.GetString("UserMessage");
            _Condition = info.GetString("Condition");
        }
#endif // FEATURE_SERIALIZATION

#if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION
#if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
#endif // FEATURE_LINK_DEMAND
#endif // FEATURE_UNTRUSTED_CALLERS
#if FEATURE_SERIALIZATION
        public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
        {
            base.GetObjectData(info, context);

            info.AddValue("Kind", _Kind);
            info.AddValue("UserMessage", _UserMessage);
            info.AddValue("Condition", _Condition);
        }
#endif
    }
}

namespace System.Runtime.CompilerServices
{
    public static partial class ContractHelper
    {
        #region Private fields

#if !FEATURE_CORECLR
        private static volatile EventHandler<ContractFailedEventArgs> s_contractFailedEvent;
        private static readonly Object s_lockObject = new Object();
#endif // !FEATURE_CORECLR
        internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542);

        #endregion

#if !FEATURE_CORECLR
        /// <summary>
        /// Allows a managed application environment such as an interactive interpreter (IronPython) or a
        /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and
        /// potentially "handle" them, either by throwing a particular exception type, etc.  If any of the
        /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
        /// not pop up an assert dialog box or trigger escalation policy.  Hooking this event requires
        /// full trust.
        /// </summary>
        internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed
        {
#if FEATURE_UNTRUSTED_CALLERS
#endif
            add
            {
                // Eagerly prepare each event handler _marked with a reliability contract_, to
                // attempt to reduce out of memory exceptions while reporting contract violations.
                // This only works if the new handler obeys the constraints placed on
                // constrained execution regions.  Eagerly preparing non-reliable event handlers
                // would be a perf hit and wouldn't significantly improve reliability.
                // UE: Please mention reliable event handlers should also be marked with the
                // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed.
                //#if !FEATURE_CORECLR
                //                System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value);
                //#endif
                lock (s_lockObject)
                {
                    s_contractFailedEvent += value;
                }
            }
#if FEATURE_UNTRUSTED_CALLERS
#endif
            remove
            {
                lock (s_lockObject)
                {
                    s_contractFailedEvent -= value;
                }
            }
        }
#endif // !FEATURE_CORECLR

        /// <summary>
        /// Rewriter will call this method on a contract failure to allow listeners to be notified.
        /// The method should not perform any failure (assert/throw) itself.
        /// This method has 3 functions:
        /// 1. Call any contract hooks (such as listeners to Contract failed events)
        /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null)
        /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently.
        /// </summary>
        /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough.
        /// On exit: null if the event was handled and should not trigger a failure.
        ///          Otherwise, returns the localized failure message</param>
        [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        [System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
#endif
        static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage)
        {
            if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
                throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
            Contract.EndContractBlock();

            string returnValue;
            String displayMessage = "contract failed.";  // Incomplete, but in case of OOM during resource lookup...
#if !FEATURE_CORECLR
            ContractFailedEventArgs eventArgs = null;  // In case of OOM.
#endif // !FEATURE_CORECLR
#if FEATURE_RELIABILITY_CONTRACTS
            System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
            try
            {
                displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText);
#if !FEATURE_CORECLR
                if (s_contractFailedEvent != null)
                {
                    eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException);
                    foreach (EventHandler<ContractFailedEventArgs> handler in s_contractFailedEvent.GetInvocationList())
                    {
                        try
                        {
                            handler(null, eventArgs);
                        }
                        catch (Exception e)
                        {
                            eventArgs.thrownDuringHandler = e;
                            eventArgs.SetUnwind();
                        }
                    }
                    if (eventArgs.Unwind)
                    {
                        //if (Environment.IsCLRHosted)
                        //    TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException);

                        // unwind
                        if (innerException == null) { innerException = eventArgs.thrownDuringHandler; }
                        throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException);
                    }
                }
#endif // !FEATURE_CORECLR
            }
            finally
            {
#if !FEATURE_CORECLR
                if (eventArgs != null && eventArgs.Handled)
                {
                    returnValue = null; // handled
                }
                else
#endif // !FEATURE_CORECLR
                {
                    returnValue = displayMessage;
                }
            }
            resultFailureMessage = returnValue;
        }

        /// <summary>
        /// Rewriter calls this method to get the default failure behavior.
        /// </summary>
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")]
        [System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR
#endif
        static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
        {
            // If we're here, our intent is to pop up a dialog box (if we can).  For developers
            // interacting live with a debugger, this is a good experience.  For Silverlight
            // hosted in Internet Explorer, the assert window is great.  If we cannot
            // pop up a dialog box, throw an exception (consider a library compiled with
            // "Assert On Failure" but used in a process that can't pop up asserts, like an
            // NT Service).  For the CLR hosted by server apps like SQL or Exchange, we should
            // trigger escalation policy.
            //#if !FEATURE_CORECLR
            //            if (Environment.IsCLRHosted)
            //            {
            //                TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException);
            //                // Hosts like SQL may choose to abort the thread, so we will not get here in all cases.
            //                // But if the host's chosen action was to throw an exception, we should throw an exception
            //                // here (which is easier to do in managed code with the right parameters).
            //                throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
            //            }
            //#endif // !FEATURE_CORECLR

            //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite

            String stackTrace = null; //@todo: Any reasonable way to get a stack trace here?
            bool userSelectedIgnore = DeveloperExperience.Default.OnContractFailure(stackTrace, kind, displayMessage, userMessage, conditionText, innerException);
            if (userSelectedIgnore)
                return;

            //if (!Environment.UserInteractive) {
            throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
            //}
            //// May need to rethink Assert.Fail w/ TaskDialogIndirect as a model.  Window title.  Main instruction.  Content.  Expanded info.
            //// Optional info like string for collapsed text vs. expanded text.
            //String windowTitle = SR.Format(GetResourceNameForFailure(kind));
            //const int numStackFramesToSkip = 2;  // To make stack traces easier to read

            //System.Diagnostics.Debug.Assert(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip);
            // If we got here, the user selected Ignore.  Continue.
        }

        private static String GetFailureMessage(ContractFailureKind failureKind, String conditionText)
        {
            bool hasConditionText = !String.IsNullOrEmpty(conditionText);
            switch (failureKind)
            {
                case ContractFailureKind.Assert:
                    return hasConditionText ? SR.Format(SR.AssertionFailed_Cnd, conditionText) : SR.AssertionFailed;

                case ContractFailureKind.Assume:
                    return hasConditionText ? SR.Format(SR.AssumptionFailed_Cnd, conditionText) : SR.AssumptionFailed;

                case ContractFailureKind.Precondition:
                    return hasConditionText ? SR.Format(SR.PreconditionFailed_Cnd, conditionText) : SR.PreconditionFailed;

                case ContractFailureKind.Postcondition:
                    return hasConditionText ? SR.Format(SR.PostconditionFailed_Cnd, conditionText) : SR.PostconditionFailed;

                case ContractFailureKind.Invariant:
                    return hasConditionText ? SR.Format(SR.InvariantFailed_Cnd, conditionText) : SR.InvariantFailed;

                case ContractFailureKind.PostconditionOnException:
                    return hasConditionText ? SR.Format(SR.PostconditionOnExceptionFailed_Cnd, conditionText) : SR.PostconditionOnExceptionFailed;

                default:
                    Contract.Assume(false, "Unreachable code");
                    return SR.AssumptionFailed;
            }
        }

#if FEATURE_RELIABILITY_CONTRACTS
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
        private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText)
        {
            // Well-formatted English messages will take one of four forms.  A sentence ending in
            // either a period or a colon, the condition string, then the message tacked
            // on to the end with two spaces in front.
            // Note that both the conditionText and userMessage may be null.  Also,
            // on Silverlight we may not be able to look up a friendly string for the
            // error message.  Let's leverage Silverlight's default error message there.
            String failureMessage = GetFailureMessage(failureKind, conditionText);
            // Now add in the user message, if present.
            if (!String.IsNullOrEmpty(userMessage))
            {
                return failureMessage + "  " + userMessage;
            }
            else
            {
                return failureMessage;
            }
        }
        //#if !FEATURE_CORECLR
        //        // Will trigger escalation policy, if hosted and the host requested us to do something (such as
        //        // abort the thread or exit the process).  Starting in Dev11, for hosted apps the default behavior
        //        // is to throw an exception.
        //        // Implementation notes:
        //        // We implement our default behavior of throwing an exception by simply returning from our native
        //        // method inside the runtime and falling through to throw an exception.
        //        // We must call through this method before calling the method on the Environment class
        //        // because our security team does not yet support SecuritySafeCritical on P/Invoke methods.
        //        // Note this can be called in the context of throwing another exception (EnsuresOnThrow).
        //#if FEATURE_UNTRUSTED_CALLERS
        //#endif
        //#if FEATURE_RELIABILITY_CONTRACTS
        //        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        //#endif
        //        [DebuggerNonUserCode]
        //        private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException)
        //        {
        //            String exceptionAsString = null;
        //            if (innerException != null)
        //                exceptionAsString = innerException.ToString();
        //            Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString);
        //        }
        //#endif // !FEATURE_CORECLR
    }
}  // namespace System.Runtime.CompilerServices


text:
<?php

namespace App\Controllers\User;

use \Phalcon\Http\Response,

    \PhRest\Controller\Simple as SimpleController,
    \PhRest\Exception\User as UserException,

    \App\Models\User;

/**
 * Class ViewController
 * @package App\Controllers\User
 * @method int getId()
 */
class ViewController extends SimpleController {

    /**
     * @return Response
     * @throws UserException
     */
    public function runAction() {
        /** @var User $user */
        $user = User::findFirstById($this->getId());

        if ($user) {
            return $this->response($user);
        } else {
            throw new UserException('User not found', 404);
        }
    }

}


text:
(function (exports) {
  exports.balihoo = exports.balihoo || {};

  var version = "v1.0";
  var defaultUrl = "{{baseUrl}}";   // this is replaced at build time

  /**
   * constructor for a LocationApi object
   * @param clientId  the client id received from the genClientAPIKey call
   * @param clientApiKey the client apiKey received from the genClientAPIKey call
   * @param config optional configuration options to provide overrides to the defaults (typically the defaultUrl)
   */
  var LocationApi = function (clientId, clientApiKey, config) {
    config = config || {};

    if (typeof clientId == 'undefined' || clientId == "") {
      throw new Error("localConnection requires a client id");
    }
    if (typeof clientApiKey == 'undefined' || clientApiKey == "") {
      throw new Error("localConnection requires a client api key");
    }

    var baseApiConfig =
    {
      clientId: clientId,
      clientApiKey: clientApiKey,
      baseUrl: defaultUrl
    };

    //baseApiConfig settings can be overridden by given config object
    this.config = ($.extend(baseApiConfig, config));

    this.lastEventId = null;  // we track the last access to blip. Used with the update functionality
  };

  /**
   * convenience wrapper for makeCall (private)
   * (private, hidden in anonymous function scope)
   * @param url
   */
  function get(config, url) {
    return makeCall("GET", config, url)
  }

  /**
   * convenience wrapper for makeCall
   * (private, hidden in anonymous function scope)
   * @param url
   * @param data
   */
  function post(config, url, data) {
    return makeCall("POST", config, url, data)
  }

  /**
   * convenience wrapper for makeCall
   * (private, hidden in anonymous function scope)
   * @param url
   * @param data
   */
  function put(config, url, data) {
    return makeCall("PUT", config, url, data)
  }

  /**
   * return a jquery promise to a Local Partner connect endpoint
   * with the correct method and url
   * (private, hidden in anonymous function scope)
   * @param config
   * @param method
   * @param url
   * @param data
   * @returns {*}
   */
  function makeCall(method, config, url, data) {

    url = config.baseUrl + "/localdata/" + version + '/' + url;

    var ajaxOptions = {
      method: method,
      dataType: "json",
      headers: {
        "X-ClientId": config.clientId,
        "X-ClientApiKey": config.clientApiKey
      },
      url: url
    };

    if (data) {
      ajaxOptions.contentType = "text/json";
      ajaxOptions.data = JSON.stringify(data);
    }

    return $.ajax(ajaxOptions);
  }

  /**
   * Turns a list of keys into an URL query parameter string.
   * @param keys List of location identifiers (key).
   * @returns {string} A locations query parameter string.
   */
  function locationKeysArgToParam(keys) {
    if (keys) {
      var keysArray = [];
      keysArray.push(keys);
      return 'locations=' + keysArray.join(',');
    }
  }

  /**
   * Format a date into API compatible format.
   * @param aDate The date to format.
   * @returns {string} Formatted date.
   */
  function formatDate(aDate) {
    var y = aDate.getFullYear(),
        m = aDate.getMonth()+1,
        d = aDate.getDate();
    return [
      y,
      m < 10 ? '0' + m : m,
      d < 10 ? '0' + d : d
    ].join('-');
  }

  /**
   * Turns a date into an URL query parameter string.
   * @param param Name of parameter.
   * @param aDate Date to format as parameter value.
   * @returns {string} A date query parameter string.
   */
  function dateToParam(param, aDate) {
    if (aDate && aDate instanceof Date)
      return param + '=' + formatDate(aDate);
  }

  /**
   * Turns options into an URL query string.
   * @param opts Options for API call.
   * @returns {string} URL query string.
   */
  function argsToParamString(opts) {
    opts = opts || {};

    var p1 = locationKeysArgToParam(opts.locations);
    var p2 = dateToParam('from', opts.from);
    var p3 = dateToParam('to', opts.to);

    var params = [];
    if (p1) params.push(p1);
    if (p2) params.push(p2);
    if (p3) params.push(p3);
    if (opts.tacticId) params.push('tacticId='+opts.tacticId);

    if (params.length > 0) {
      return '?' + params.join('&');
    } else {
      return '';
    }
  }

  /**
   * Gets all the campaigns for your location
   */
  LocationApi.prototype.getAllCampaigns = function (opts) {
    return get(this.config, "campaigns" + argsToParamString(opts));
  };

  /**
   * Gets all tactics for the given campaign for your location
   */
  LocationApi.prototype.getAllTactics = function (campaignId, opts) {
    if (typeof campaignId == 'undefined') {
      throw new Error("getAllTactics requires a campaign id");
    }

    return get(this.config, "campaign/"+campaignId+"/tactics" + argsToParamString(opts));
  };

  /**
   * Gets all campaigns with expanded tactics for your location(s)
   */
  LocationApi.prototype.getAllCampaignsAndTactics = function (opts) {
    return get(this.config, "campaignswithtactics" + argsToParamString(opts));
  };

  /**
   * Gets all metrics for a specific tactic
   */
  LocationApi.prototype.getMetricsForTactic = function (tacticId, opts) {
    if (typeof tacticId == 'undefined') {
      throw new Error("getMetricsForTactic requires a tactic id");
    }

    return get(this.config, "tactic/"+tacticId+"/metrics" + argsToParamString(opts));
  };

  /**
   * Gets the local website information for your location(s)
   */
  LocationApi.prototype.getWebsiteMetrics = function (opts) {
    return get(this.config, "websitemetrics" + argsToParamString(opts));
  };

  /**
   * Gets the local website information for your location(s)
   */
  LocationApi.prototype.getReportData = function (reportType, opts) {
    var found = false;
    for (var i in ReportTypes) {
      if (ReportTypes[i] === reportType) {
        found = true;
        break;
      }
    }

    if (!found)
      throw new Error('unsupported report name: '+reportType);

    return get(this.config, 'report/'+reportType+'/export' + argsToParamString(opts));
  };

  var ReportTypes = [ 'EmailSentEvent' ];

  /***************************************
   *
   * Profile Tab Endpoints
   *
   ***************************************/

  /**
   * returns a json object that contains the code
   * for the current brands profile tabs form
   * The current brand is determined from the
   * clientId sent in the request header
   */
  LocationApi.prototype.getProfileForm = function() {
    return get(this.config, "profile/form");
  };

  /**
   * returns the current profile information from
   * blip for the current location. Location is
   * extracted from the clientId sent in the
   * request header
   */
  LocationApi.prototype.getProfileData = function() {
    var self = this;  // for the closure below
    return get(this.config, "profile/data")
      .then(function(profile) {
        self.lastEventId = profile.lastEventId;  // extract the eventId from the json data
        return profile.document;  // return the actual document object
      });
  };

  /**
   * updates the profile information for the given
   * brand with the given profile data for the
   * current location. The location is
   * extracted from the clientId sent in the
   * request header
   */
  LocationApi.prototype.updateProfileData = function(profileData) {
    if (typeof profileData == 'undefined') {
      throw new Error("updateProfileData requires a profile data object");
    }

    if (this.lastEventId == null) {
      throw new Error("getProfileData must be run before this call to obtain and lastEventId");
    }

    return put(this.config, "profile/data", {profileData: profileData, lastEventId: this.lastEventId});
  };

  /**
   * Configuration options
   *
   *   baseUrl
   *     default - "//bac.balihoo-cloud.com"
   *     The scheme,domain and port without a trailing slash that the requests should use
   */

  /**
   *
   * Creates a connection object that can call the following location api endpoints:
   *   getAllCampaigns()
   *   getAllTactics(campaignId)
   *   getAllCampaignsAndTactics()
   *   getMetricsForTactic(tacticId)
   *   getWebsiteMetrics()
   *
   * @param clientId - id created for specific brand
   * @param clientApiKey - associated key for client id
   * @param config - additional configuration options object
   * @constructor
   */
  exports.balihoo.LocalConnection = LocationApi

})(window);

/**
 *
 * Example usage
 *
 * var clientId = "myClientId"
 * var clientApiKey = "myApiKey"
 *
 * var connection = new balihoo.LocalConnection(clientId,clientApiKey)
 *
 * connection.getAllCampaigns().done(function (allCampaigns) {
 *   console.log(JSON.stringify(allCampaigns));
 * });
 *
 *
 */


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.super_bits</groupId>
    <artifactId>SB_FRAMEWORK</artifactId>
    <version>0.9-SNAPSHOT</version>

    <packaging>pom</packaging>

    <name>FRAME WORK SUPER-BITS</name>

    <modules>
        <module>SBCore</module>
        <module>../utilitarios/EditorImagem</module>
        <module>SBPersistencia</module>
        <module>SBAcessosModel</module>
        <module>SBWebPaginas</module>
        <module>clienteRest</module>

        <module>SBController/SBController</module>

    </modules>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
            <type>jar</type>
        </dependency>

    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

</project>


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxEventsGridPricesView extends BxBaseModGroupsGridPricesView
{
    public function __construct ($aOptions, $oTemplate = false)
    {
        $this->_sModule = 'bx_events';

        parent::__construct ($aOptions, $oTemplate);
    }
}

/** @} */


text:
Reports String.equals() calls on a CharSequence argument
as String.equals() can only return true for String arguments.
To compare the contents of a String for equality with a non-String CharSequence argument,
use the contentEquals() method.

Example:

  boolean equals(String s, CharSequence ch) {
    return s.equals(ch);
  }

After quick-fix is applied, the result will be:

  boolean equals(String s, CharSequence ch) {
    return s.contentEquals(ch);
  }

New in 2017.3


text:
from . import get_session_store
from ..app import app
from mock import MagicMock
import os
import re
import tempfile
import unittest

class SessionViewTestCase(unittest.TestCase):

    session_key = 'some id'
    session_data = {'foo': 'bar'}

    def setUp(self):
        self.db_fd, app.config['DATABASE'] = tempfile.mkstemp()
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % app.config['DATABASE']
        app.config['TESTING'] = True
        self.client = app.test_client()
        with app.app_context():
            self.store = get_session_store()
            # self.store = get_session_store()
            # self.store.backend.create_all()
            db = self.store.args[0]
            db.create_all()

    def tearDown(self):
        with app.app_context():
            # the session keeps some objects that were used during the test run
            # even if the db changes, the session connection stays the same
            # here we make sure that the session will be recreated
            # using `self.store` here to ensure that we refresh the exact session
            # that is used for `SessionStore`
            session = self.store.args[0].session
            session.remove()
            # self.store.backend.session.remove()
        os.close(self.db_fd)
        os.unlink(app.config['DATABASE'])

    def test_no_cookie_data(self):
        """Shared session view returns empty response
        if there is no cookies.
        """
        rv = self.client.get('/session/')
        self.assertEqual('{}', rv.data)

    def test_content_type(self):
        """Shared session view returns correct
        `Content-Type` header.
        """
        rv = self.client.get('/session/')
        self.assertEqual('application/json', rv.content_type)

    def test_session_id_in_db(self):
        """Shared session view returns correct session data."""
        self.create_session()
        with self.client as c:
            c.set_cookie('*', app.config['SESSION_COOKIE_NAME'], self.session_key)
            rv = c.get('/session/')
            self.assertEqual(self.session_data, self.store('').serializer().loads(rv.data))

    def test_session_id_not_in_db(self):
        """Shared session view returns empty response
        if the session not in the db.
        """
        with self.client as c:
            c.set_cookie('*', app.config['SESSION_COOKIE_NAME'], self.session_key)
            rv = c.get('/session/')
            self.assertEqual('{}', rv.data)

    def create_session(self):
        """Helper that puts the session in the database."""
        with app.app_context():
            self.store(self.session_key).put(self.session_data)

    def strip_line(self, line):
        """Helper that strips all the whitespaces from the given string.

        :param line: string to strip
        :type line: str or unicode
        :return: stripped string
        :rtype: str or unicode
        """
        return re.sub(r'\s+', '', line)

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(SessionViewTestCase))
    return suite


text:
'use strict';

/* Services */

var richardplatzServices = angular.module('richardplatzServices', ['ngResource']);

richardplatzServices.factory('$userComment', ['$resource',
  function($resource){
    return $resource('phones/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
  }]);


text:
package info.archinnov.achilles.internals.dsl.options;

import static java.lang.String.format;
import static java.util.Arrays.asList;

import java.util.List;
import java.util.Optional;

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

import info.archinnov.achilles.internals.metamodel.AbstractEntityProperty;
import info.archinnov.achilles.internals.types.OverridingOptional;
import info.archinnov.achilles.type.lightweighttransaction.LWTResultListener;
import info.archinnov.achilles.type.strategy.InsertStrategy;

public abstract class AbstractOptionsForCRUDInsert<T extends AbstractOptionsForCRUDInsert<T>>
        extends AbstractOptionsForSelect<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractOptionsForCRUDInsert.class);

    protected Optional<InsertStrategy> insertStrategy = Optional.empty();
    protected Optional<Boolean> ifNotExists = Optional.empty();
    protected Optional<List<LWTResultListener>> lwtResultListeners = Optional.empty();

    /**
     * Generate a ... IF NOT EXISTS if true
     */
    public T ifNotExists(boolean ifNotExists) {
        this.ifNotExists = Optional.of(ifNotExists);
        return getThis();
    }

    /**
     * Generate a ... IF NOT EXISTS
     */
    public T ifNotExists() {
        this.ifNotExists = Optional.of(true);
        return getThis();
    }

    /**
     * Add a list of LWT result listeners. Example of usage:
     *

     * LWTResultListener lwtListener = new LWTResultListener() {
     *
     *  public void onError(LWTResult lwtResult) {
     *
     *      //Get type of LWT operation that fails
     *      LWTResult.Operation operation = lwtResult.operation();
     *
     *      // Print out current values
     *      TypedMap currentValues = lwtResult.currentValues();
     *      currentValues
     *          .entrySet()
     *          .forEach(entry -> System.out.println(String.format("%s = %s",entry.getKey(), entry.getValue())));
     *  }
     * };
     *

     */
    public T withLwtResultListeners(List<LWTResultListener> lwtResultListeners) {
        this.lwtResultListeners = Optional.of(lwtResultListeners);
        return getThis();
    }

    /**
     * Add a single LWT result listeners. Example of usage:
     *

     * LWTResultListener lwtListener = new LWTResultListener() {
     *
     *  public void onError(LWTResult lwtResult) {
     *
     *      //Get type of LWT operation that fails
     *      LWTResult.Operation operation = lwtResult.operation();
     *
     *      // Print out current values
     *      TypedMap currentValues = lwtResult.currentValues();
     *          currentValues
     *          .entrySet()
     *          .forEach(entry -> System.out.println(String.format("%s = %s",entry.getKey(), entry.getValue())));
     *       }
     * };
     *

     */
    public T withLwtResultListener(LWTResultListener lwtResultListener) {
        this.lwtResultListeners = Optional.of(asList(lwtResultListener));
        return getThis();
    }

    /**
     * Generate a USING TIMESTAMP ?
     */
    public T usingTimestamp(long timestamp) {
        getOptions().setDefaultTimestamp(Optional.of(timestamp));
        return getThis();
    }

    /**
     * Generate a USING TTL ?
     */
    public T usingTimeToLive(int timeToLive) {
        getOptions().setTimeToLive(Optional.of(timeToLive));
        return getThis();
    }

    /**
     * Bind values to prepared statement and avoid null if
     * InsertStrategy.NOT_NULL_FIELDS is chosen
     */
    public T withInsertStrategy(InsertStrategy insertStrategy) {
        this.insertStrategy = Optional.of(insertStrategy);
        return getThis();
    }

    /**
     * Determine the insert strategy for the given
     * entity using static configuration and runtime option
     *
     * @param property entity property
     * @return overriden InsertStrategy
     */
    public InsertStrategy getOverridenStrategy(AbstractEntityProperty<?> property) {

        final InsertStrategy insertStrategy = OverridingOptional
                .from(this.insertStrategy)
                .defaultValue(property.insertStrategy())
                .get();

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(format("Get runtime insert strategy for entity %s : %s",
                    property.entityClass.getCanonicalName(), insertStrategy.name()));
        }

        return insertStrategy;
    }
}


text:
// Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: mphoward

#include "CellList.h"

#ifdef ENABLE_MPI
#include "Communicator.h"
#include "hoomd/Communicator.h"
#endif // ENABLE_MPI

/*!
 * \file mpcd/CellList.cc
 * \brief Definition of mpcd::CellList
 */

mpcd::CellList::CellList(std::shared_ptr<SystemDefinition> sysdef,
                         std::shared_ptr<mpcd::ParticleData> mpcd_pdata)
    : Compute(sysdef), m_mpcd_pdata(mpcd_pdata), m_cell_size(1.0), m_cell_np_max(4),
      m_cell_np(m_exec_conf), m_cell_list(m_exec_conf), m_embed_cell_ids(m_exec_conf),
      m_conditions(m_exec_conf), m_needs_compute_dim(true), m_particles_sorted(false),
      m_virtual_change(false)
    {
    assert(m_mpcd_pdata);
    m_exec_conf->msg->notice(5) << "Constructing MPCD CellList" << std::endl;

    // by default, grid shifting is initialized to zeroes
    m_cell_dim = make_uint3(0, 0, 0);
    m_global_cell_dim = make_uint3(0, 0, 0);

    m_grid_shift = make_scalar3(0.0, 0.0, 0.0);
    m_max_grid_shift = 0.5 * m_cell_size;
    m_origin_idx = make_int3(0, 0, 0);

    resetConditions();

#ifdef ENABLE_MPI
    m_decomposition = m_pdata->getDomainDecomposition();
    m_num_extra = 0;
    m_cover_box = m_pdata->getBox();
#endif // ENABLE_MPI

    m_mpcd_pdata->getSortSignal().connect<mpcd::CellList, &mpcd::CellList::sort>(this);
    m_mpcd_pdata->getNumVirtualSignal().connect<mpcd::CellList, &mpcd::CellList::slotNumVirtual>(
        this);
    m_pdata->getParticleSortSignal().connect<mpcd::CellList, &mpcd::CellList::slotSorted>(this);
    m_pdata->getBoxChangeSignal().connect<mpcd::CellList, &mpcd::CellList::slotBoxChanged>(this);
    }

mpcd::CellList::~CellList()
    {
    m_exec_conf->msg->notice(5) << "Destroying MPCD CellList" << std::endl;
    m_mpcd_pdata->getSortSignal().disconnect<mpcd::CellList, &mpcd::CellList::sort>(this);
    m_mpcd_pdata->getNumVirtualSignal().disconnect<mpcd::CellList, &mpcd::CellList::slotNumVirtual>(
        this);
    m_pdata->getParticleSortSignal().disconnect<mpcd::CellList, &mpcd::CellList::slotSorted>(this);
    m_pdata->getBoxChangeSignal().disconnect<mpcd::CellList, &mpcd::CellList::slotBoxChanged>(this);
    }

void mpcd::CellList::compute(uint64_t timestep)
    {
    Compute::compute(timestep);
    if (m_prof)
        m_prof->push(m_exec_conf, "MPCD cell list");

    if (m_virtual_change)
        {
        m_virtual_change = false;
        m_force_compute = true;
        }

    if (m_particles_sorted)
        {
        m_particles_sorted = false;
        m_force_compute = true;
        }

    if (m_needs_compute_dim)
        {
        computeDimensions();
        m_force_compute = true;
        }

    if (peekCompute(timestep))
        {
#ifdef ENABLE_MPI
        if (m_prof)
            m_prof->pop(m_exec_conf);

        // exchange embedded particles if necessary
        if (m_comm && needsEmbedMigrate(timestep))
            {
            m_comm->forceMigrate();
            m_comm->communicate(timestep);
            }
        if (m_prof)
            m_prof->push(m_exec_conf, "MPCD cell list");
#endif // ENABLE_MPI

        // resize to be able to hold the number of embedded particles
        if (m_embed_group)
            {
            m_embed_cell_ids.resize(m_embed_group->getNumMembers());
            }

        bool overflowed = false;
        do
            {
            buildCellList();

            overflowed = checkConditions();

            if (overflowed)
                {
                reallocate();
                resetConditions();
                }
            } while (overflowed);

        // we are finished building, explicitly mark everything (rather than using shouldCompute)
        m_first_compute = false;
        m_force_compute = false;
        m_last_computed = timestep;

        // signal to the ParticleData that the cell list cache is now valid
        m_mpcd_pdata->validateCellCache();
        }

    if (m_prof)
        m_prof->pop(m_exec_conf);
    }

void mpcd::CellList::reallocate()
    {
    m_exec_conf->msg->notice(6) << "Allocating MPCD cell list, " << m_cell_np_max
                                << " particles in " << m_cell_indexer.getNumElements() << " cells."
                                << std::endl;
    m_cell_list_indexer = Index2D(m_cell_np_max, m_cell_indexer.getNumElements());
    m_cell_list.resize(m_cell_list_indexer.getNumElements());
    }

void mpcd::CellList::updateGlobalBox()
    {
    // triclinic boxes are not allowed
    const BoxDim& global_box = m_pdata->getGlobalBox();
    if (global_box.getTiltFactorXY() != Scalar(0.0) || global_box.getTiltFactorXZ() != Scalar(0.0)
        || global_box.getTiltFactorYZ() != Scalar(0.0))
        {
        m_exec_conf->msg->error() << "mpcd: box must be orthorhombic" << std::endl;
        throw std::runtime_error("Box must be orthorhombic");
        }

    // box must be evenly divisible by cell size
    const Scalar3 L = global_box.getL();
    m_global_cell_dim = make_uint3((unsigned int)round(L.x / m_cell_size),
                                   (unsigned int)round(L.y / m_cell_size),
                                   (unsigned int)round(L.z / m_cell_size));
    if (m_sysdef->getNDimensions() == 2)
        {
        if (m_global_cell_dim.z > 1)
            {
            m_exec_conf->msg->error()
                << "mpcd: In 2d simulations, box width must be smaller than cell size" << std::endl;
            throw std::runtime_error("Lz bigger than cell size in 2D!");
            }

        // force to be only one cell along z in 2d
        m_global_cell_dim.z = 1;
        }

    const double eps = 1e-5;
    if (fabs((double)L.x - m_global_cell_dim.x * (double)m_cell_size) > eps * m_cell_size
        || fabs((double)L.y - m_global_cell_dim.y * (double)m_cell_size) > eps * m_cell_size
        || (m_sysdef->getNDimensions() == 3
            && fabs((double)L.z - m_global_cell_dim.z * (double)m_cell_size) > eps * m_cell_size))
        {
        m_exec_conf->msg->error() << "mpcd: Box size must be even multiple of cell size"
                                  << std::endl;
        throw std::runtime_error("MPCD cell size must evenly divide box");
        }
    }

void mpcd::CellList::computeDimensions()
    {
    if (!m_needs_compute_dim)
        return;

    // first update / validate the global box
    updateGlobalBox();

#ifdef ENABLE_MPI
    uchar3 communicating = make_uchar3(0, 0, 0);
    if (m_decomposition)
        {
        const Index3D& di = m_decomposition->getDomainIndexer();
        communicating.x = (di.getW() > 1);
        communicating.y = (di.getH() > 1);
        communicating.z = (di.getD() > 1);
        }

    // Only do complicated sizing if some direction is being communicated
    if (communicating.x || communicating.y || communicating.z)
        {
        // Global simulation box for absolute position referencing
        const BoxDim& global_box = m_pdata->getGlobalBox();
        const Scalar3 global_lo = global_box.getLo();
        const Scalar3 global_L = global_box.getL();

        // if global box is valid (no triclinic skew), then local box also has no skew,
        // so assume orthorhombic in all subsequent calculations
        const BoxDim& box = m_pdata->getBox();

        // setup lo bin
        const Scalar3 delta_lo = box.getLo() - global_lo;
        int3 my_lo_bin = make_int3((int)std::floor((delta_lo.x - m_max_grid_shift) / m_cell_size),
                                   (int)std::floor((delta_lo.y - m_max_grid_shift) / m_cell_size),
                                   (int)std::floor((delta_lo.z - m_max_grid_shift) / m_cell_size));
        int3 lo_neigh_bin
            = make_int3((int)std::ceil((delta_lo.x + m_max_grid_shift) / m_cell_size),
                        (int)std::ceil((delta_lo.y + m_max_grid_shift) / m_cell_size),
                        (int)std::ceil((delta_lo.z + m_max_grid_shift) / m_cell_size));

        // setup hi bin
        const Scalar3 delta_hi = box.getHi() - global_lo;
        int3 my_hi_bin = make_int3((int)std::ceil((delta_hi.x + m_max_grid_shift) / m_cell_size),
                                   (int)std::ceil((delta_hi.y + m_max_grid_shift) / m_cell_size),
                                   (int)std::ceil((delta_hi.z + m_max_grid_shift) / m_cell_size));
        int3 hi_neigh_bin
            = make_int3((int)std::floor((delta_hi.x - m_max_grid_shift) / m_cell_size),
                        (int)std::floor((delta_hi.y - m_max_grid_shift) / m_cell_size),
                        (int)std::floor((delta_hi.z - m_max_grid_shift) / m_cell_size));

        // initially size the grid assuming one rank in each direction, and then resize based on
        // communication
        m_cell_dim = m_global_cell_dim;
        m_origin_idx = make_int3(0, 0, 0);
        std::fill(m_num_comm.begin(), m_num_comm.end(), 0);

        // Compute size of the box with diffusion layer
        Scalar3 cover_lo = box.getLo();
        Scalar3 cover_hi = box.getHi();
        uchar3 cover_periodic = box.getPeriodic();

        if (communicating.x)
            {
            // number of cells and cell origin, padding with extra cells in diffusion layer
            m_cell_dim.x = my_hi_bin.x - my_lo_bin.x + 2 * m_num_extra;
            m_origin_idx.x = my_lo_bin.x - m_num_extra;

            // number of communication cells along each direction
            m_num_comm[static_cast<unsigned int>(mpcd::detail::face::east)]
                = my_hi_bin.x - hi_neigh_bin.x + m_num_extra;
            m_num_comm[static_cast<unsigned int>(mpcd::detail::face::west)]
                = lo_neigh_bin.x - my_lo_bin.x + m_num_extra;

            // "safe" size of the diffusion layer
            cover_lo.x = m_origin_idx.x * m_cell_size + m_max_grid_shift - 0.5 * global_L.x;
            cover_hi.x = (m_origin_idx.x + m_cell_dim.x) * m_cell_size - m_max_grid_shift
                         - 0.5 * global_L.x;
            cover_periodic.x = 0;
            }

        if (communicating.y)
            {
            m_cell_dim.y = my_hi_bin.y - my_lo_bin.y + 2 * m_num_extra;
            m_origin_idx.y = my_lo_bin.y - m_num_extra;

            m_num_comm[static_cast<unsigned int>(mpcd::detail::face::north)]
                = my_hi_bin.y - hi_neigh_bin.y + m_num_extra;
            m_num_comm[static_cast<unsigned int>(mpcd::detail::face::south)]
                = lo_neigh_bin.y - my_lo_bin.y + m_num_extra;

            cover_lo.y = m_origin_idx.y * m_cell_size + m_max_grid_shift - 0.5 * global_L.y;
            cover_hi.y = (m_origin_idx.y + m_cell_dim.y) * m_cell_size - m_max_grid_shift
                         - 0.5 * global_L.y;
            cover_periodic.y = 0;
            }

        if (m_sysdef->getNDimensions() == 3 && communicating.z)
            {
            m_cell_dim.z = my_hi_bin.z - my_lo_bin.z + 2 * m_num_extra;
            m_origin_idx.z = my_lo_bin.z - m_num_extra;

            m_num_comm[static_cast<unsigned int>(mpcd::detail::face::up)]
                = my_hi_bin.z - hi_neigh_bin.z + m_num_extra;
            m_num_comm[static_cast<unsigned int>(mpcd::detail::face::down)]
                = lo_neigh_bin.z - my_lo_bin.z + m_num_extra;

            cover_lo.z = m_origin_idx.z * m_cell_size + m_max_grid_shift - 0.5 * global_L.z;
            cover_hi.z = (m_origin_idx.z + m_cell_dim.z) * m_cell_size - m_max_grid_shift
                         - 0.5 * global_L.z;
            cover_periodic.z = 0;
            }

        // set the box covered by this cell list
        m_cover_box = BoxDim(cover_lo, cover_hi, cover_periodic);

        checkDomainBoundaries();
        }
    else
#endif // ENABLE_MPI
        {
        m_cell_dim = m_global_cell_dim;
        m_origin_idx = make_int3(0, 0, 0);
        }

    // resize the cell indexers and per-cell counter
    m_global_cell_indexer = Index3D(m_global_cell_dim.x, m_global_cell_dim.y, m_global_cell_dim.z);
    m_cell_indexer = Index3D(m_cell_dim.x, m_cell_dim.y, m_cell_dim.z);
    m_cell_np.resize(m_cell_indexer.getNumElements());

    // reallocate per-cell memory
    reallocate();

    // dimensions are now current
    m_needs_compute_dim = false;
    notifySizeChange();
    }

#ifdef ENABLE_MPI
void mpcd::CellList::checkDomainBoundaries()
    {
    if (!m_decomposition)
        return;

    MPI_Comm mpi_comm = m_exec_conf->getMPICommunicator();

    for (unsigned int dir = 0; dir < m_num_comm.size(); ++dir)
        {
        mpcd::detail::face d = static_cast<mpcd::detail::face>(dir);
        if (!isCommunicating(d))
            continue;

        // receive in the opposite direction from which we send
        unsigned int send_neighbor = m_decomposition->getNeighborRank(dir);
        unsigned int recv_neighbor;
        if (dir % 2 == 0)
            recv_neighbor = m_decomposition->getNeighborRank(dir + 1);
        else
            recv_neighbor = m_decomposition->getNeighborRank(dir - 1);

        // first make sure each dimension is sending and receiving the same size data
        MPI_Request reqs[2];
        MPI_Status status[2];

        // check that the number received is the same as that being sent from neighbor
        unsigned int n_send = m_num_comm[dir];
        unsigned int n_expect_recv;
        if (dir % 2 == 0)
            n_expect_recv = m_num_comm[dir + 1];
        else
            n_expect_recv = m_num_comm[dir - 1];

        unsigned int n_recv;
        MPI_Isend(&n_send, 1, MPI_UNSIGNED, send_neighbor, 0, mpi_comm, &reqs[0]);
        MPI_Irecv(&n_recv, 1, MPI_UNSIGNED, recv_neighbor, 0, mpi_comm, &reqs[1]);
        MPI_Waitall(2, reqs, status);

        // check if any rank errored out
        unsigned int recv_error = 0;
        if (n_expect_recv != n_recv)
            {
            recv_error = 1;
            }
        unsigned int any_error = 0;
        MPI_Allreduce(&recv_error, &any_error, 1, MPI_UNSIGNED, MPI_SUM, mpi_comm);
        if (any_error)
            {
            if (recv_error)
                {
                m_exec_conf->msg->error() << "mpcd: expected to communicate " << n_expect_recv
                                          << " cells, but only receiving " << n_recv << std::endl;
                }
            throw std::runtime_error("Error setting up MPCD cell list");
            }

        // check that the same cell ids are communicated
        std::vector<int> send_cells(n_send), recv_cells(n_recv);
        for (unsigned int i = 0; i < n_send; ++i)
            {
            if (d == mpcd::detail::face::east)
                {
                send_cells[i] = m_origin_idx.x + m_cell_dim.x - m_num_extra - n_send + i;
                }
            else if (d == mpcd::detail::face::west)
                {
                send_cells[i] = m_origin_idx.x + i;
                }
            else if (d == mpcd::detail::face::north)
                {
                send_cells[i] = m_origin_idx.y + m_cell_dim.y - m_num_extra - n_send + i;
                }
            else if (d == mpcd::detail::face::south)
                {
                send_cells[i] = m_origin_idx.y + i;
                }
            else if (d == mpcd::detail::face::up)
                {
                send_cells[i] = m_origin_idx.z + m_cell_dim.z - m_num_extra - n_send + i;
                }
            else if (d == mpcd::detail::face::down)
                {
                send_cells[i] = m_origin_idx.z + i;
                }
            }

        MPI_Isend(&send_cells[0], n_send, MPI_INT, send_neighbor, 1, mpi_comm, &reqs[0]);
        MPI_Irecv(&recv_cells[0], n_recv, MPI_INT, recv_neighbor, 1, mpi_comm, &reqs[1]);
        MPI_Waitall(2, reqs, status);

        unsigned int overlap_error = 0;
        std::array<int, 2> err_pair {0, 0};
        for (unsigned int i = 0; i < n_recv && !overlap_error; ++i)
            {
            // wrap the received cell back into the global box
            // only two of the entries will be valid, the others are dummies
            int3 recv_cell = make_int3(0, 0, 0);
            if (d == mpcd::detail::face::east || d == mpcd::detail::face::west)
                {
                recv_cell.x = recv_cells[i];
                }
            else if (d == mpcd::detail::face::north || d == mpcd::detail::face::south)
                {
                recv_cell.y = recv_cells[i];
                }
            else if (d == mpcd::detail::face::up || d == mpcd::detail::face::down)
                {
                recv_cell.z = recv_cells[i];
                }
            recv_cell = wrapGlobalCell(recv_cell);

            // compute the expected cell to receive, also wrapped
            int3 expect_recv_cell = make_int3(0, 0, 0);
            if (d == mpcd::detail::face::east)
                {
                expect_recv_cell.x = m_origin_idx.x + i;
                }
            else if (d == mpcd::detail::face::west)
                {
                expect_recv_cell.x = m_origin_idx.x + m_cell_dim.x - m_num_extra - n_recv + i;
                }
            else if (d == mpcd::detail::face::north)
                {
                expect_recv_cell.y = m_origin_idx.y + i;
                }
            else if (d == mpcd::detail::face::south)
                {
                expect_recv_cell.y = m_origin_idx.y + m_cell_dim.y - m_num_extra - n_recv + i;
                }
            else if (d == mpcd::detail::face::up)
                {
                expect_recv_cell.z = m_origin_idx.z + i;
                }
            else if (d == mpcd::detail::face::down)
                {
                expect_recv_cell.z = m_origin_idx.z + m_cell_dim.z - m_num_extra - n_recv + i;
                }
            expect_recv_cell = wrapGlobalCell(expect_recv_cell);

            if (recv_cell.x != expect_recv_cell.x || recv_cell.y != expect_recv_cell.y
                || recv_cell.z != expect_recv_cell.z)
                {
                overlap_error = i;
                if (d == mpcd::detail::face::east || d == mpcd::detail::face::west)
                    {
                    err_pair[0] = recv_cell.x;
                    err_pair[1] = expect_recv_cell.x;
                    }
                else if (d == mpcd::detail::face::north || d == mpcd::detail::face::south)
                    {
                    err_pair[0] = recv_cell.y;
                    err_pair[1] = expect_recv_cell.y;
                    }
                else if (d == mpcd::detail::face::up || d == mpcd::detail::face::down)
                    {
                    err_pair[0] = recv_cell.z;
                    err_pair[1] = expect_recv_cell.z;
                    }
                }
            }

        // check if anyone reported an error, then race to see who gets to write it out
        any_error = 0;
        MPI_Allreduce(&overlap_error, &any_error, 1, MPI_UNSIGNED, MPI_SUM, mpi_comm);
        if (any_error)
            {
            if (overlap_error)
                {
                m_exec_conf->msg->error()
                    << "mpcd: communication grid does not overlap. "
                    << "Expected to receive cell " << err_pair[1] << " from rank " << recv_neighbor
                    << ", but got cell " << err_pair[0] << "." << std::endl;
                }
            throw std::runtime_error("Error setting up MPCD cell list");
            }
        }
    }

/*!
 * \param dir Direction of communication
 * \returns True if communication is occurring along \a dir
 *
 * The size of the domain indexer is checked along the direction of communication
 * to see if there are multiple ranks that must communicate.
 */
bool mpcd::CellList::isCommunicating(mpcd::detail::face dir)
    {
    if (!m_decomposition)
        return false;

    const Index3D& di = m_decomposition->getDomainIndexer();
    bool result = true;
    if ((dir == mpcd::detail::face::east || dir == mpcd::detail::face::west) && di.getW() == 1)
        result = false;
    else if ((dir == mpcd::detail::face::north || dir == mpcd::detail::face::south)
             && di.getH() == 1)
        result = false;
    else if ((dir == mpcd::detail::face::up || dir == mpcd::detail::face::down) && di.getD() == 1)
        result = false;

    return result;
    }
#endif // ENABLE_MPI

/*!
 * \param timestep Current simulation timestep
 */
void mpcd::CellList::buildCellList()
    {
    const BoxDim& box = m_pdata->getBox();
    const uchar3 periodic = box.getPeriodic();

    ArrayHandle<unsigned int> h_cell_list(m_cell_list,
                                          access_location::host,
                                          access_mode::overwrite);
    ArrayHandle<unsigned int> h_cell_np(m_cell_np, access_location::host, access_mode::overwrite);
    // zero the cell counter
    memset(h_cell_np.data, 0, sizeof(unsigned int) * m_cell_indexer.getNumElements());

    uint3 conditions = make_uint3(0, 0, 0);

    ArrayHandle<Scalar4> h_pos(m_mpcd_pdata->getPositions(),
                               access_location::host,
                               access_mode::read);
    ArrayHandle<Scalar4> h_vel(m_mpcd_pdata->getVelocities(),
                               access_location::host,
                               access_mode::readwrite);
    unsigned int N_mpcd = m_mpcd_pdata->getN() + m_mpcd_pdata->getNVirtual();
    unsigned int N_tot = N_mpcd;

    // we can't modify the velocity of embedded particles, so we only read their position
    std::unique_ptr<ArrayHandle<unsigned int>> h_embed_cell_ids;
    std::unique_ptr<ArrayHandle<Scalar4>> h_pos_embed;
    std::unique_ptr<ArrayHandle<unsigned int>> h_embed_member_idx;
    if (m_embed_group)
        {
        h_embed_cell_ids.reset(new ArrayHandle<unsigned int>(m_embed_cell_ids,
                                                             access_location::host,
                                                             access_mode::overwrite));
        h_pos_embed.reset(new ArrayHandle<Scalar4>(m_pdata->getPositions(),
                                                   access_location::host,
                                                   access_mode::read));
        h_embed_member_idx.reset(new ArrayHandle<unsigned int>(m_embed_group->getIndexArray(),
                                                               access_location::host,
                                                               access_mode::read));
        N_tot += m_embed_group->getNumMembers();
        }

    // total effective number of cells in the global box, optionally padded by
    // extra cells in MPI simulations
    uint3 n_global_cells = m_global_cell_dim;
#ifdef ENABLE_MPI
    if (isCommunicating(mpcd::detail::face::east))
        n_global_cells.x += 2 * m_num_extra;
    if (isCommunicating(mpcd::detail::face::north))
        n_global_cells.y += 2 * m_num_extra;
    if (isCommunicating(mpcd::detail::face::up))
        n_global_cells.z += 2 * m_num_extra;
#endif // ENABLE_MPI

    const Scalar3 global_lo = m_pdata->getGlobalBox().getLo();

    for (unsigned int cur_p = 0; cur_p < N_tot; ++cur_p)
        {
        Scalar4 postype_i;
        if (cur_p < N_mpcd)
            {
            postype_i = h_pos.data[cur_p];
            }
        else
            {
            postype_i = h_pos_embed->data[h_embed_member_idx->data[cur_p - N_mpcd]];
            }
        Scalar3 pos_i = make_scalar3(postype_i.x, postype_i.y, postype_i.z);

        if (std::isnan(pos_i.x) || std::isnan(pos_i.y) || std::isnan(pos_i.z))
            {
            conditions.y = cur_p + 1;
            continue;
            }

        // bin particle assuming orthorhombic box (already validated)
        const Scalar3 delta = (pos_i - m_grid_shift) - global_lo;
        int3 global_bin = make_int3((int)std::floor(delta.x / m_cell_size),
                                    (int)std::floor(delta.y / m_cell_size),
                                    (int)std::floor(delta.z / m_cell_size));

        // wrap cell back through the boundaries (grid shifting may send +/- 1 outside of range)
        // this is done using periodic from the "local" box, since this will be periodic
        // only when there is one rank along the dimension
        if (periodic.x)
            {
            if (global_bin.x == (int)n_global_cells.x)
                global_bin.x = 0;
            else if (global_bin.x == -1)
                global_bin.x = n_global_cells.x - 1;
            }
        if (periodic.y)
            {
            if (global_bin.y == (int)n_global_cells.y)
                global_bin.y = 0;
            else if (global_bin.y == -1)
                global_bin.y = n_global_cells.y - 1;
            }
        if (periodic.z)
            {
            if (global_bin.z == (int)n_global_cells.z)
                global_bin.z = 0;
            else if (global_bin.z == -1)
                global_bin.z = n_global_cells.z - 1;
            }

        // compute the local cell
        int3 bin = make_int3(global_bin.x - m_origin_idx.x,
                             global_bin.y - m_origin_idx.y,
                             global_bin.z - m_origin_idx.z);

        // validate and make sure no particles blew out of the box
        if ((bin.x < 0 || bin.x >= (int)m_cell_dim.x) || (bin.y < 0 || bin.y >= (int)m_cell_dim.y)
            || (bin.z < 0 || bin.z >= (int)m_cell_dim.z))
            {
            conditions.z = cur_p + 1;
            continue;
            }

        unsigned int bin_idx = m_cell_indexer(bin.x, bin.y, bin.z);
        unsigned int offset = h_cell_np.data[bin_idx];
        if (offset < m_cell_np_max)
            {
            h_cell_list.data[m_cell_list_indexer(offset, bin_idx)] = cur_p;
            }
        else
            {
            // overflow
            conditions.x = std::max(conditions.x, offset + 1);
            }

        // stash the current particle bin into the velocity array
        if (cur_p < N_mpcd)
            {
            h_vel.data[cur_p].w = __int_as_scalar(bin_idx);
            }
        else
            {
            h_embed_cell_ids->data[cur_p - N_mpcd] = bin_idx;
            }

        // increment the counter always
        ++h_cell_np.data[bin_idx];
        }

    // write out the conditions
    m_conditions.resetFlags(conditions);
    }

/*!
 * \param timestep Timestep that the sorting occurred
 * \param order Mapping of sorted particle indexes onto old particle indexes
 * \param rorder Mapping of old particle indexes onto sorted particle indexes
 */
void mpcd::CellList::sort(uint64_t timestep,
                          const GPUArray<unsigned int>& order,
                          const GPUArray<unsigned int>& rorder)
    {
    // no need to do any sorting if we can still be called at the current timestep
    if (peekCompute(timestep))
        return;

    // if mapping is not valid, signal that we need to force a recompute next time
    // that the cell list is needed. We don't call forceCompute() directly because this always
    // runs compute(), and we just want to defer to the next compute() call.
    if (rorder.isNull())
        {
        m_force_compute = true;
        return;
        }

    // iterate through particles in cell list, and update their indexes using reverse mapping
    ArrayHandle<unsigned int> h_rorder(rorder, access_location::host, access_mode::read);
    ArrayHandle<unsigned int> h_cell_np(m_cell_np, access_location::host, access_mode::read);
    ArrayHandle<unsigned int> h_cell_list(m_cell_list,
                                          access_location::host,
                                          access_mode::readwrite);
    const unsigned int N_mpcd = m_mpcd_pdata->getN();

    for (unsigned int idx = 0; idx < getNCells(); ++idx)
        {
        const unsigned int np = h_cell_np.data[idx];
        for (unsigned int offset = 0; offset < np; ++offset)
            {
            const unsigned int cl_idx = m_cell_list_indexer(offset, idx);
            const unsigned int pid = h_cell_list.data[cl_idx];
            // only update indexes of MPCD particles, not virtual or embedded particles
            if (pid < N_mpcd)
                {
                h_cell_list.data[cl_idx] = h_rorder.data[pid];
                }
            }
        }
    }

#ifdef ENABLE_MPI
bool mpcd::CellList::needsEmbedMigrate(uint64_t timestep)
    {
    // no migrate needed if no embedded particles
    if (!m_embed_group)
        return false;

    // ensure that the cell list has been sized first
    computeDimensions();

    // coverage box dimensions, assuming orthorhombic
    const Scalar3 lo = m_cover_box.getLo();
    const Scalar3 hi = m_cover_box.getHi();
    const uchar3 periodic = m_cover_box.getPeriodic();
    const unsigned int ndim = m_sysdef->getNDimensions();

    // particle data
    ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::read);
    ArrayHandle<unsigned int> h_group(m_embed_group->getIndexArray(),
                                      access_location::host,
                                      access_mode::read);
    const unsigned int N = m_embed_group->getNumMembers();

    // check if any particle lies outside of the box on this rank
    char migrate = 0;
    for (unsigned int i = 0; i < N && !migrate; ++i)
        {
        const unsigned int idx = h_group.data[i];
        const Scalar4 postype = h_pos.data[idx];
        const Scalar3 pos = make_scalar3(postype.x, postype.y, postype.z);

        if ((!periodic.x && (pos.x >= hi.x || pos.x < lo.x))
            || (!periodic.y && (pos.y >= hi.y || pos.y < lo.y))
            || (!periodic.z && ndim == 3 && (pos.z >= hi.z || pos.z < lo.z)))
            {
            migrate = 1;
            }
        }

    // reduce across all ranks
    MPI_Allreduce(MPI_IN_PLACE, &migrate, 1, MPI_CHAR, MPI_MAX, m_exec_conf->getMPICommunicator());

    return static_cast<bool>(migrate);
    }
#endif // ENABLE_MPI

bool mpcd::CellList::checkConditions()
    {
    bool result = false;

    uint3 conditions = m_conditions.readFlags();

    if (conditions.x > m_cell_np_max)
        {
        m_cell_np_max = conditions.x;
        result = true;
        }
    if (conditions.y)
        {
        unsigned int n = conditions.y - 1;
        if (n < m_mpcd_pdata->getN())
            m_exec_conf->msg->errorAllRanks()
                << "MPCD particle " << n << " has position NaN" << std::endl;
        else if (n < m_mpcd_pdata->getNVirtual())
            m_exec_conf->msg->errorAllRanks()
                << "MPCD virtual particle " << n << " has position NaN" << std::endl;
        else
            {
            ArrayHandle<unsigned int> h_embed_member_idx(m_embed_group->getIndexArray(),
                                                         access_location::host,
                                                         access_mode::read);
            m_exec_conf->msg->errorAllRanks()
                << "Embedded particle "
                << h_embed_member_idx.data[n - (m_mpcd_pdata->getN() + m_mpcd_pdata->getNVirtual())]
                << " has position NaN" << std::endl;
            }
        throw std::runtime_error("Error computing cell list");
        }
    if (conditions.z)
        {
        unsigned int n = conditions.z - 1;
        Scalar4 pos_empty_i;
        if (n < m_mpcd_pdata->getN() + m_mpcd_pdata->getNVirtual())
            {
            ArrayHandle<Scalar4> h_pos(m_mpcd_pdata->getPositions(),
                                       access_location::host,
                                       access_mode::read);
            pos_empty_i = h_pos.data[n];
            if (n < m_mpcd_pdata->getN())
                m_exec_conf->msg->errorAllRanks()
                    << "MPCD particle is no longer in the simulation box" << std::endl;
            else
                m_exec_conf->msg->errorAllRanks()
                    << "MPCD virtual particle is no longer in the simulation box" << std::endl;
            }
        else
            {
            ArrayHandle<Scalar4> h_pos_embed(m_pdata->getPositions(),
                                             access_location::host,
                                             access_mode::read);
            ArrayHandle<unsigned int> h_embed_member_idx(m_embed_group->getIndexArray(),
                                                         access_location::host,
                                                         access_mode::read);
            pos_empty_i
                = h_pos_embed
                      .data[h_embed_member_idx
                                .data[n - (m_mpcd_pdata->getN() + m_mpcd_pdata->getNVirtual())]];
            m_exec_conf->msg->errorAllRanks()
                << "Embedded particle is no longer in the simulation box" << std::endl;
            }

        Scalar3 pos = make_scalar3(pos_empty_i.x, pos_empty_i.y, pos_empty_i.z);
        m_exec_conf->msg->errorAllRanks()
            << "Cartesian coordinates: " << std::endl
            << "x: " << pos.x << " y: " << pos.y << " z: " << pos.z << std::endl
            << "Grid shift: " << std::endl
            << "x: " << m_grid_shift.x << " y: " << m_grid_shift.y << " z: " << m_grid_shift.z
            << std::endl;

        const BoxDim& cover_box = getCoverageBox();
        Scalar3 lo = cover_box.getLo();
        Scalar3 hi = cover_box.getHi();
        uchar3 periodic = cover_box.getPeriodic();
        m_exec_conf->msg->errorAllRanks()
            << "Covered box lo: (" << lo.x << ", " << lo.y << ", " << lo.z << ")" << std::endl
            << "            hi: (" << hi.x << ", " << hi.y << ", " << hi.z << ")" << std::endl
            << "      periodic: (" << ((periodic.x) ? "1" : "0") << " "
            << ((periodic.y) ? "1" : "0") << " " << ((periodic.z) ? "1" : "0") << ")" << std::endl;
        throw std::runtime_error("Error computing cell list");
        }

    return result;
    }

void mpcd::CellList::resetConditions()
    {
    m_conditions.resetFlags(make_uint3(0, 0, 0));
    }

void mpcd::CellList::getCellStatistics() const
    {
    unsigned int min_np(0xffffffff), max_np(0);
    ArrayHandle<unsigned int> h_cell_np(m_cell_np, access_location::host, access_mode::read);
    for (unsigned int cur_cell = 0; cur_cell < m_cell_indexer.getNumElements(); ++cur_cell)
        {
        const unsigned int np = h_cell_np.data[cur_cell];
        if (np < min_np)
            min_np = np;
        if (np > max_np)
            max_np = np;
        }
    m_exec_conf->msg->notice(2) << "MPCD cell list stats:" << std::endl;
    m_exec_conf->msg->notice(2) << "Min: " << min_np << " Max: " << max_np << std::endl;
    }

/*!
 * \param global Global cell index to shift into the local box
 * \returns Local cell index
 *
 * \warning The returned cell index may lie outside the local grid. It is the
 *          caller's responsibility to check that the index is valid.
 */
const int3 mpcd::CellList::getLocalCell(const int3& global) const
    {
    int3 local = make_int3(global.x - m_origin_idx.x,
                           global.y - m_origin_idx.y,
                           global.z - m_origin_idx.z);

    return local;
    }

/*!
 * \param local Local cell index to shift into the global box
 * \returns Global cell index
 *
 * Local cell coordinates are wrapped around the global box so that a valid global
 * index is computed.
 */
const int3 mpcd::CellList::getGlobalCell(const int3& local) const
    {
    int3 global
        = make_int3(local.x + m_origin_idx.x, local.y + m_origin_idx.y, local.z + m_origin_idx.z);
    return wrapGlobalCell(global);
    }

/*!
 * \param cell Cell coordinates to wrap back into the global box
 *
 * \warning Only up to one global box size is wrapped. This method is intended
 *          to be used for wrapping cells off by only one or two from the global boundary.
 */
const int3 mpcd::CellList::wrapGlobalCell(const int3& cell) const
    {
    int3 wrap = cell;

    if (wrap.x >= (int)m_global_cell_dim.x)
        wrap.x -= m_global_cell_dim.x;
    else if (wrap.x < 0)
        wrap.x += m_global_cell_dim.x;

    if (wrap.y >= (int)m_global_cell_dim.y)
        wrap.y -= m_global_cell_dim.y;
    else if (wrap.y < 0)
        wrap.y += m_global_cell_dim.y;

    if (wrap.z >= (int)m_global_cell_dim.z)
        wrap.z -= m_global_cell_dim.z;
    else if (wrap.z < 0)
        wrap.z += m_global_cell_dim.z;

    return wrap;
    }

void mpcd::detail::export_CellList(pybind11::module& m)
    {
    namespace py = pybind11;

    py::class_<mpcd::CellList, Compute, std::shared_ptr<mpcd::CellList>>(m, "CellList")
        .def(py::init<std::shared_ptr<SystemDefinition>, std::shared_ptr<mpcd::ParticleData>>())
        .def_property("cell_size", &mpcd::CellList::getCellSize, &mpcd::CellList::setCellSize)
        .def("setEmbeddedGroup", &mpcd::CellList::setEmbeddedGroup)
        .def("removeEmbeddedGroup", &mpcd::CellList::removeEmbeddedGroup);
    }


text:
Students participated in annual Inter-year sports championship Aagaaz
====================================================================

Sports society of IIT Mandi organized Annual Year sports championship "Aagaaz" from 18th-19th May. Teams from different years participated in various sports like Football, Hockey, Cricket, Basketball.

Event started with prelims of all the sports on Day 1  with basketball being organized at Mandi Campus and all other sports being organized at Kamand Campus. Semi-Finals and Finals were organized on Day 2.

2nd Year won the General Championship.


text:
// TC WinForms Library
// Copyright © 2008-2021 Tommy Carlier
// https://github.com/tommy-carlier/tc-libs/
// License: MIT License (MIT): https://github.com/tommy-carlier/tc-libs/blob/master/LICENSE

using System;
using System.Xml;
using System.Xml.XPath;

namespace TC.WinForms.Settings
{
	/// The abstract base class for the settings of a <see cref="T:TDocumentForm"/>.
	public abstract class DocumentFormSettings : BaseFormSettings
	{
		/// Initializes a new instance of the <see cref="DocumentFormSettings"/> class.
		/// <param name="xmlElementName">The name of the XML-element that represents this instance.</param>
		protected DocumentFormSettings(string xmlElementName)
			: base(xmlElementName) { }

		/// Loads the settings from the specified <see cref="T:XPathNavigator"/>.
		/// <param name="xml">The <see cref="T:XPathNavigator"/> to load the settings from.</param>
		protected override void LoadCore(XPathNavigator xml)
		{
			base.LoadCore(xml);
			CurrentDocumentFolder = xml.GetAttribute("folder", String.Empty);
			SelectedFilterIndex = xml.GetAttribute("filter", String.Empty).ToInt32();
		}

		/// Saves the settings to the specified <see cref="T:XmlWriter"/>.
		/// <param name="writer">The <see cref="T:XmlWriter"/> to save the settings to.</param>
		protected override void SaveCore(XmlWriter writer)
		{
			base.SaveCore(writer);

			if (CurrentDocumentFolder.IsNotNullOrEmpty())
				writer.WriteAttributeString("folder", CurrentDocumentFolder);

			if (SelectedFilterIndex > 0)
				writer.WriteAttributeString("filter", SelectedFilterIndex.ToDataString());
		}

		/// Gets or sets the initial folder in file dialogs.
		/// <value>The initial folder in file dialogs.</value>
		public string CurrentDocumentFolder { get; set; }

		/// Gets or sets the index of the selected filter in file dialogs.
		/// <value>The index of the selected filter in file dialogs.</value>
		public int SelectedFilterIndex { get; set; }
	}
}


text:
package org.gluu.model.custom.script.conf;

import java.util.Map;

import org.gluu.model.SimpleCustomProperty;
import org.gluu.model.custom.script.model.CustomScript;
import org.gluu.model.custom.script.type.BaseExternalType;

/**
 * Custom script configuration
 *
 * @author Yuriy Movchan Date: 12/04/2014
 */
public class CustomScriptConfiguration {
    private CustomScript customScript;
    private BaseExternalType externalType;
    private Map<String, SimpleCustomProperty> configurationAttributes;

    public CustomScriptConfiguration(CustomScript customScript, BaseExternalType externalType,
            Map<String, SimpleCustomProperty> configurationAttributes) {
        this.customScript = customScript;
        this.externalType = externalType;
        this.configurationAttributes = configurationAttributes;
    }

    public String getInum() {
        return customScript.getInum();
    }

    public CustomScript getCustomScript() {
        return customScript;
    }

    public BaseExternalType getExternalType() {
        return externalType;
    }

    public Map<String, SimpleCustomProperty> getConfigurationAttributes() {
        return configurationAttributes;
    }

    public String getName() {
        return this.customScript.getName();
    }

    public int getLevel() {
        return this.customScript.getLevel();
    }

}