text:
//------------------------------------------------------------------------------
// <copyright file="AspCompat.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.Util {
    using System.Runtime.InteropServices;
    using System.Threading;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Text;
    using System.Web;
    using System.Web.SessionState;
    using System.Security.Permissions;
    using System.Runtime.Remoting.Messaging;
    using Microsoft.Win32;
    using System.Globalization;
    using System.Web.Caching;

//
// Interface for unmanaged call to call back into managed code for
// intrinsics implementation
//

internal enum RequestString {
    QueryString = 1,
    Form = 2,
    Cookies = 3,
    ServerVars = 4
}

[ComImport, Guid("a1cca730-0e36-4870-aa7d-ca39c211f99d"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
internal interface IManagedContext {

    [return: MarshalAs(UnmanagedType.I4)]   int     Context_IsPresent();

                                            void    Application_Lock();
                                            void    Application_UnLock();
    [return: MarshalAs(UnmanagedType.BStr)] String  Application_GetContentsNames();
    [return: MarshalAs(UnmanagedType.BStr)] String  Application_GetStaticNames();
                                            Object  Application_GetContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
                                            void    Application_SetContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In] Object obj);
                                            void    Application_RemoveContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
                                            void    Application_RemoveAllContentsObjects();
                                            Object  Application_GetStaticObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);

    [return: MarshalAs(UnmanagedType.BStr)] String  Request_GetAsString([In, MarshalAs(UnmanagedType.I4)] int what);
    [return: MarshalAs(UnmanagedType.BStr)] String  Request_GetCookiesAsString();
    [return: MarshalAs(UnmanagedType.I4)]   int     Request_GetTotalBytes();
    [return: MarshalAs(UnmanagedType.I4)]   int     Request_BinaryRead([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] bytes, int size);

    [return: MarshalAs(UnmanagedType.BStr)] String  Response_GetCookiesAsString();
                                            void    Response_AddCookie([In, MarshalAs(UnmanagedType.LPWStr)] String name);
                                            void    Response_SetCookieText([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String text);
                                            void    Response_SetCookieSubValue([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String key, [In, MarshalAs(UnmanagedType.LPWStr)] String value);
                                            void    Response_SetCookieExpires([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.R8)] double dtExpires);
                                            void    Response_SetCookieDomain([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String domain);
                                            void    Response_SetCookiePath([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String path);
                                            void    Response_SetCookieSecure([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.I4)] int secure);
                                            void    Response_Write([In, MarshalAs(UnmanagedType.LPWStr)] String text);
                                            void    Response_BinaryWrite([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), In] byte[] bytes, int size);
                                            void    Response_Redirect([In, MarshalAs(UnmanagedType.LPWStr)] String url);
                                            void    Response_AddHeader([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String value);
                                            void    Response_Pics([In, MarshalAs(UnmanagedType.LPWStr)] String value);
                                            void    Response_Clear();
                                            void    Response_Flush();
                                            void    Response_End();
                                            void    Response_AppendToLog([In, MarshalAs(UnmanagedType.LPWStr)] String entry);
    [return: MarshalAs(UnmanagedType.BStr)] String  Response_GetContentType();
                                            void    Response_SetContentType([In, MarshalAs(UnmanagedType.LPWStr)] String contentType);
    [return: MarshalAs(UnmanagedType.BStr)] String  Response_GetCharSet();
                                            void    Response_SetCharSet([In, MarshalAs(UnmanagedType.LPWStr)] String charSet);
    [return: MarshalAs(UnmanagedType.BStr)] String  Response_GetCacheControl();
                                            void    Response_SetCacheControl([In, MarshalAs(UnmanagedType.LPWStr)] String cacheControl);
    [return: MarshalAs(UnmanagedType.BStr)]         String  Response_GetStatus();
                                            void    Response_SetStatus([In, MarshalAs(UnmanagedType.LPWStr)] String status);
    [return: MarshalAs(UnmanagedType.I4)]   int     Response_GetExpiresMinutes();
                                            void    Response_SetExpiresMinutes([In, MarshalAs(UnmanagedType.I4)] int expiresMinutes);
    [return: MarshalAs(UnmanagedType.R8)]   double  Response_GetExpiresAbsolute();
                                            void    Response_SetExpiresAbsolute([In, MarshalAs(UnmanagedType.R8)] double dtExpires);
    [return: MarshalAs(UnmanagedType.I4)]   int     Response_GetIsBuffering();
                                            void    Response_SetIsBuffering([In, MarshalAs(UnmanagedType.I4)] int isBuffering);
    [return: MarshalAs(UnmanagedType.I4)]   int     Response_IsClientConnected();

    [return: MarshalAs(UnmanagedType.Interface)] Object Server_CreateObject([In, MarshalAs(UnmanagedType.LPWStr)] String progId);
    [return: MarshalAs(UnmanagedType.BStr)] String  Server_MapPath([In, MarshalAs(UnmanagedType.LPWStr)] String logicalPath);
    [return: MarshalAs(UnmanagedType.BStr)] String  Server_HTMLEncode([In, MarshalAs(UnmanagedType.LPWStr)] String str);
    [return: MarshalAs(UnmanagedType.BStr)] String  Server_URLEncode([In, MarshalAs(UnmanagedType.LPWStr)] String str);
    [return: MarshalAs(UnmanagedType.BStr)] String  Server_URLPathEncode([In, MarshalAs(UnmanagedType.LPWStr)] String str);
    [return: MarshalAs(UnmanagedType.I4)]   int     Server_GetScriptTimeout();
                                            void    Server_SetScriptTimeout([In, MarshalAs(UnmanagedType.I4)] int timeoutSeconds);
                                            void    Server_Execute([In, MarshalAs(UnmanagedType.LPWStr)] String url);
                                            void    Server_Transfer([In, MarshalAs(UnmanagedType.LPWStr)] String url);

    [return: MarshalAs(UnmanagedType.I4)]   int     Session_IsPresent();
    [return: MarshalAs(UnmanagedType.BStr)] String  Session_GetID();
    [return: MarshalAs(UnmanagedType.I4)]   int     Session_GetTimeout();
                                            void    Session_SetTimeout([In, MarshalAs(UnmanagedType.I4)] int value);
    [return: MarshalAs(UnmanagedType.I4)]   int     Session_GetCodePage();
                                            void    Session_SetCodePage([In, MarshalAs(UnmanagedType.I4)] int value);
    [return: MarshalAs(UnmanagedType.I4)]   int     Session_GetLCID();
                                            void    Session_SetLCID([In, MarshalAs(UnmanagedType.I4)] int value);
                                            void    Session_Abandon();
    [return: MarshalAs(UnmanagedType.BStr)] String  Session_GetContentsNames();
    [return: MarshalAs(UnmanagedType.BStr)] String  Session_GetStaticNames();
                                            Object  Session_GetContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
                                            void    Session_SetContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In]Object obj);
                                            void    Session_RemoveContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
                                            void    Session_RemoveAllContentsObjects();
                                            Object  Session_GetStaticObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
}

/// <devdoc>
///    <para>[To be supplied.]</para>
/// </devdoc>

//
//  Delegate to the code executing on within ASP compat context
//  (provided by the caller and used internally to wrap it)
//

internal delegate void AspCompatCallback();

//
//  Utility class for AspCompat work
//

internal class AspCompatApplicationStep : HttpApplication.IExecutionStep, IManagedContext {

    private GCHandle          _rootedThis;      // for the duration of async
    private HttpContext       _context;         // context for callback
    private HttpApplication   _app;             // app instance to run the code under
    private String            _sessionId;       // to run session on the same STA thread
    private AspCompatCallback _code;            // the code to run in asp compat mode
    private EventHandler      _codeEventHandler;// alt to running _code is to raise event
    private Object            _codeEventSource;
    private EventArgs         _codeEventArgs;
    private Exception         _error;           // error during the execution
    private HttpAsyncResult   _ar;              // async result returned to the caller
    private bool              _syncCaller;      // called synchronously?
    private AspCompatCallback _execCallback;    // keep delegate as a member (not gc it)
    private WorkItemCallback  _compCallback;    // keep delegate as a member (not gc it)
    private ArrayList         _staComponents;   // list of STA components to be released

    private static char[]     TabOrBackSpace =  new char[] { '\t', '\b' };

    internal AspCompatApplicationStep(HttpContext context, AspCompatCallback code) {
        _code = code;
        Init(context, context.ApplicationInstance);
    }

    private AspCompatApplicationStep(HttpContext context, HttpApplication app, String sessionId, EventHandler codeEventHandler, Object codeEventSource, EventArgs codeEventArgs) {
        _codeEventHandler   = codeEventHandler;
        _codeEventSource    = codeEventSource;
        _codeEventArgs      = codeEventArgs;
        _sessionId          = sessionId;
        Init(context, app);
    }

    private void Init(HttpContext context, HttpApplication app) {
        _context = context;
        _app = app;
        _execCallback = new AspCompatCallback(this.OnAspCompatExecution);
        _compCallback = new WorkItemCallback(this.OnAspCompatCompletion);

        if (_sessionId == null && _context != null && _context.Session != null)
            _sessionId = _context.Session.SessionID;
    }

    private void MarkCallContext(AspCompatApplicationStep mark) {
         CallContext.SetData("AspCompat", mark);
    }

    private static AspCompatApplicationStep Current {
        get { return (AspCompatApplicationStep)CallContext.GetData("AspCompat"); }
    }

    internal static bool IsInAspCompatMode {
        get { return (Current != null); }
    }

    // IExecutionStep implementation

    void HttpApplication.IExecutionStep.Execute() {
        SynchronizationContextUtil.ValidateModeForAspCompat();

        if (_code != null) {
            _code();
        }
        else if (_codeEventHandler != null) {
            _codeEventHandler(_codeEventSource, _codeEventArgs);
        }
    }

    bool HttpApplication.IExecutionStep.CompletedSynchronously {
        get { return true; }
    }

    bool HttpApplication.IExecutionStep.IsCancellable {
        get { return (_context != null); }
    }

    // OnPageStart / OnPageEnd support

    private void RememberStaComponent(Object component) {
        if (_staComponents == null)
            _staComponents = new ArrayList();
        _staComponents.Add(component);
    }

    private bool IsStaComponentInSessionState(Object component) {
        if (_context == null)
            return false;
        HttpSessionState session = _context.Session;
        if (session == null)
            return false;

        // enumerate objects and call OnPageStart
        int numObjects = session.Count;
        for (int i = 0; i < numObjects; i++) {
            if (component == session[i])
                return true;
        }

        return false;
    }

    internal static bool AnyStaObjectsInSessionState(HttpSessionState session) {
        if (session == null)
            return false;

        int numObjects = session.Count;

        for (int i = 0; i < numObjects; i++) {
            Object component = session[i];

            if (component != null && component.GetType().FullName == "System.__ComObject") {
                if (UnsafeNativeMethods.AspCompatIsApartmentComponent(component) != 0)
                    return true;
            }
        }

        return false;
    }

    internal static void OnPageStart(Object component) {
        // has to be in asp compat mode
        if (!IsInAspCompatMode)
            return;

        int rc = UnsafeNativeMethods.AspCompatOnPageStart(component);
        if (rc != 1)
            throw new HttpException(SR.GetString(SR.Error_onpagestart));

        if (UnsafeNativeMethods.AspCompatIsApartmentComponent(component) != 0)
            Current.RememberStaComponent(component);
    }

    internal static void OnPageStartSessionObjects() {
        // has to be in asp compat mode
        if (!IsInAspCompatMode)
            return;

        // get session state if any
        HttpContext context = Current._context;
        if (context == null)
            return;
        HttpSessionState session = context.Session;
        if (session == null)
            return;

        // enumerate objects and call OnPageStart
        int numObjects = session.Count;
        for (int i = 0; i < numObjects; i++) {
            Object component = session[i];

            if (component != null && !(component is string)) {
                int rc = UnsafeNativeMethods.AspCompatOnPageStart(component);
                if (rc != 1)
                    throw new HttpException(SR.GetString(SR.Error_onpagestart));
            }
        }
    }

    // Disallow Apartment components in when ASPCOMPAT is off

    internal static void CheckThreadingModel(String progidDisplayName, Guid clsid) {
        if (IsInAspCompatMode)
            return;

        // try cache first
        CacheInternal cacheInternal = HttpRuntime.CacheInternal;
        String key = CacheInternal.PrefixAspCompatThreading + progidDisplayName;
        String threadingModel = (String)cacheInternal.Get(key);
        RegistryKey regKey = null;

        if (threadingModel == null) {
            try {
                regKey = Registry.ClassesRoot.OpenSubKey("CLSID\\{" + clsid + "}\\InprocServer32" );
                if (regKey != null)
                    threadingModel = (String)regKey.GetValue("ThreadingModel");
            }
            catch {
            }
            finally {
                if (regKey != null)
                    regKey.Close();
            }

            if (threadingModel == null)
                threadingModel = String.Empty;

            cacheInternal.UtcInsert(key, threadingModel);
        }

        if (StringUtil.EqualsIgnoreCase(threadingModel, "Apartment")) {
            throw new HttpException(
                SR.GetString(SR.Apartment_component_not_allowed, progidDisplayName));
        }
    }

    // Async patern

    [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
    internal /*public*/ IAsyncResult BeginAspCompatExecution(AsyncCallback cb, object extraData) {
        SynchronizationContextUtil.ValidateModeForAspCompat();

        if (IsInAspCompatMode) {
            // already in AspCompatMode -- execute synchronously
            bool sync = true;
            Exception error = _app.ExecuteStep(this, ref sync);
            _ar = new HttpAsyncResult(cb, extraData, true, null, error);
            _syncCaller = true;
        }
        else {
            _ar = new HttpAsyncResult(cb, extraData);
            _syncCaller = (cb == null);
            _rootedThis = GCHandle.Alloc(this);

            // send requests from the same session to the same STA thread
            bool sharedActivity = (_sessionId != null);
            int    activityHash = sharedActivity ? _sessionId.GetHashCode() : 0;

            if (UnsafeNativeMethods.AspCompatProcessRequest(_execCallback, this, sharedActivity, activityHash) != 1) {
                // failed to queue up the execution in ASP compat mode
                _rootedThis.Free();
                _ar.Complete(true, null, new HttpException(SR.GetString(SR.Cannot_access_AspCompat)));
            }
        }

        return _ar;
    }

    internal /*public*/ void EndAspCompatExecution(IAsyncResult ar) {
        Debug.Assert(_ar == ar);
        _ar.End();
    }

    // helpers to raise event on STA threads in ASPCOMAP mode

    internal static void RaiseAspCompatEvent(HttpContext context, HttpApplication app, String sessionId, EventHandler eventHandler, Object source, EventArgs eventArgs) {
        AspCompatApplicationStep step = new AspCompatApplicationStep(context, app, sessionId, eventHandler, source, eventArgs);
        IAsyncResult ar = step.BeginAspCompatExecution(null, null);

        // wait until done
        if (!ar.IsCompleted) {
            WaitHandle h = ar.AsyncWaitHandle;

            if (h != null) {
                h.WaitOne();
            }
            else {
                while (!ar.IsCompleted)
                    Thread.Sleep(1);
            }
        }

        step.EndAspCompatExecution(ar);
    }

    private void ExecuteAspCompatCode() {
        MarkCallContext(this);

        try {
            bool sync = true;

            if (_context != null) {
                ThreadContext threadContext = null;
                try {
                    threadContext = _app.OnThreadEnter();
                    _error = _app.ExecuteStep(this, ref sync);
                }
                finally {
                    if (threadContext != null) {
                        threadContext.DisassociateFromCurrentThread();
                    }
                }
            }
            else {
                _error = _app.ExecuteStep(this, ref sync);
            }
        }
        finally {
            MarkCallContext(null);
        }
    }

    private void OnAspCompatExecution() {
        try {
            if (_syncCaller) {
                // for synchronous caller don't take the app lock (could dead lock because we switched threads)
                ExecuteAspCompatCode();
            }
            else {
                lock (_app) {
                    ExecuteAspCompatCode();
                }
            }
        }
        finally {
            // call PageEnd
            UnsafeNativeMethods.AspCompatOnPageEnd();

            // release all STA components not in session
            if (_staComponents != null) {
                foreach (Object component in _staComponents) {
                    if (!IsStaComponentInSessionState(component))
                        Marshal.ReleaseComObject(component);
                }
            }

            // notify any code polling for completion before QueueUserWorkItem to avoid deadlocks
            // (the completion work item could be help up by the threads doing polling)
            _ar.SetComplete();

            // reschedule execution back to the regular thread pool
            WorkItem.PostInternal(_compCallback);
        }
    }

    private void OnAspCompatCompletion() {
        _rootedThis.Free();
        _ar.Complete(false, null, _error); // resume the application execution
    }

    //
    // Implemenation of IManagedContext
    //

    // As we use tab as separator, marshaling data will be corrupted
    // when user inputs contain any tabs. Therefore, we have tabs in user
    // inputs encoded before marshaling (Dev10 #692392)
    private static String EncodeTab(String value) {
        if (String.IsNullOrEmpty(value) || value.IndexOfAny(TabOrBackSpace) < 0) {
            return value;
        }
        return value.Replace("\b", "\bB").Replace("\t", "\bT");
    }

    private static String EncodeTab(object value) {
        return EncodeTab((String)value);
    }

    private static String CollectionToString(NameValueCollection c) {
        // 'easy' marshalling format key, # of strings, strings, ... (all '\t' separated)
        int n = c.Count;
        if (n == 0)
           return String.Empty;

        StringBuilder sb = new StringBuilder(256);

        for (int i = 0; i < n; i++) {
            String key = EncodeTab(c.GetKey(i));
            String[] vv = c.GetValues(i);
            int len = (vv != null) ? vv.Length : 0;
            sb.Append(key + "\t" + len + "\t");
            for (int j = 0; j < len; j++) {
                sb.Append(EncodeTab(vv[j]));
                if (j < vv.Length-1)
                    sb.Append("\t");
            }
            if (i < n-1)
                sb.Append("\t");
        }

        return sb.ToString();
    }

    private static String CookiesToString(HttpCookieCollection cc) {
        // marshalling of cookies as string (all '\t' separated):
        // all cookies as one ';' separated string
        // # of cookies
        // [for each cookie] name, text, # of keys, key, value, ...
        StringBuilder sb = new StringBuilder(256);  // resulting string (per above)
        StringBuilder st = new StringBuilder(128);  // all cookies string

        int numCookies = cc.Count;
        sb.Append(numCookies.ToString() + "\t");

        for (int i = 0; i < numCookies; i++) {
            HttpCookie c = cc[i];
            String name = EncodeTab(c.Name);
            String value = EncodeTab(c.Value);

            sb.Append(name + "\t" + value + "\t");

            if (i > 0)
                st.Append(";" + name + "=" + value);
            else
                st.Append(name + "=" + value);

            NameValueCollection cv = c.Values;
            int ncv = cv.Count;
            bool hasNotEmptyKeys = false;

            if (cv.HasKeys()) {
                for (int j = 0; j < ncv; j++) {
                    String key = cv.GetKey(j);
                    if (!String.IsNullOrEmpty(key)) {
                        hasNotEmptyKeys = true;
                        break;
                    }
                }
            }

            if (hasNotEmptyKeys) {
                sb.Append(ncv + "\t");
                for (int j = 0; j < ncv; j++)
                    sb.Append(EncodeTab(cv.GetKey(j)) + "\t" + EncodeTab(cv.Get(j)) + "\t");
            }
            else {
                sb.Append("0\t");
            }
        }

        // append the contructed text to the all cookies string
        st.Append("\t");
        st.Append(sb.ToString());
        return st.ToString();
    }

    private static String StringArrayToString(String[] ss) {
        // construct tab separeted string for marshalling
        StringBuilder sb = new StringBuilder(256);

        if (ss != null) {
            for (int i = 0; i < ss.Length; i++) {
                if (i > 0)
                    sb.Append("\t");
                sb.Append(EncodeTab(ss[i]));
            }
        }

        return sb.ToString();
    }

    private static String EnumKeysToString(IEnumerator e) {
        StringBuilder sb = new StringBuilder(256);

        if (e.MoveNext()) {
            sb.Append(EncodeTab(e.Current));
            while (e.MoveNext()) {
                sb.Append("\t");
                sb.Append(EncodeTab(e.Current));
            }
        }

        return sb.ToString();
    }

    private static String DictEnumKeysToString(IDictionaryEnumerator e) {
        StringBuilder sb = new StringBuilder(256);

        if (e.MoveNext()) {
            sb.Append(EncodeTab(e.Key));
            while (e.MoveNext()) {
                sb.Append("\t");
                sb.Append(EncodeTab(e.Key));
            }
        }

        return sb.ToString();
    }

    int IManagedContext.Context_IsPresent() {
        return (_context != null) ? 1 : 0;
    }

    void IManagedContext.Application_Lock() {
        _context.Application.Lock();
    }

    void IManagedContext.Application_UnLock() {
        _context.Application.UnLock();
    }

    String IManagedContext.Application_GetContentsNames() {
        return StringArrayToString(_context.Application.AllKeys);
    }

    String IManagedContext.Application_GetStaticNames() {
        return DictEnumKeysToString((IDictionaryEnumerator)_context.Application.StaticObjects.GetEnumerator());
    }

    Object IManagedContext.Application_GetContentsObject(String name) {
        return _context.Application[name];
    }

    void IManagedContext.Application_SetContentsObject(String name, Object obj) {
        _context.Application[name] = obj;
    }

    void IManagedContext.Application_RemoveContentsObject(String name) {
        _context.Application.Remove(name);
    }

    void IManagedContext.Application_RemoveAllContentsObjects() {
        _context.Application.RemoveAll();
    }

    Object IManagedContext.Application_GetStaticObject(String name) {
        return _context.Application.StaticObjects[name];
    }

    String IManagedContext.Request_GetAsString(int what) {
        String s = String.Empty;

        switch ((RequestString)what) {
            case RequestString.QueryString:
                return CollectionToString(_context.Request.QueryString);
            case RequestString.Form:
                return CollectionToString(_context.Request.Form);
            case RequestString.Cookies:
                return String.Empty;
            case RequestString.ServerVars:
                return CollectionToString(_context.Request.ServerVariables);
        }

        return s;
    }

    String IManagedContext.Request_GetCookiesAsString() {
        return CookiesToString(_context.Request.Cookies);
    }

    int IManagedContext.Request_GetTotalBytes() {
        return _context.Request.TotalBytes;
    }

    int IManagedContext.Request_BinaryRead(byte[] bytes, int size) {
        return _context.Request.InputStream.Read(bytes, 0, size);
    }

    String IManagedContext.Response_GetCookiesAsString() {
        return CookiesToString(_context.Response.Cookies);
    }

    void IManagedContext.Response_AddCookie(String name) {
        _context.Response.Cookies.Add(new HttpCookie(name));
    }

    void IManagedContext.Response_SetCookieText(String name, String text) {
        _context.Response.Cookies[name].Value = text;
    }

    void IManagedContext.Response_SetCookieSubValue(String name, String key, String value) {
        _context.Response.Cookies[name].Values[key] = value;
    }

    void IManagedContext.Response_SetCookieExpires(String name, double dtExpires) {
        _context.Response.Cookies[name].Expires = DateTime.FromOADate(dtExpires);
    }

    void IManagedContext.Response_SetCookieDomain(String name, String domain) {
        _context.Response.Cookies[name].Domain = domain;
    }

    void IManagedContext.Response_SetCookiePath(String name, String path) {
        _context.Response.Cookies[name].Path = path;
    }

    void IManagedContext.Response_SetCookieSecure(String name, int secure) {
        _context.Response.Cookies[name].Secure = (secure != 0);
    }

    void IManagedContext.Response_Write(String text) {
        _context.Response.Write(text);
    }

    void IManagedContext.Response_BinaryWrite(byte[] bytes, int size) {
        _context.Response.OutputStream.Write(bytes, 0, size);
    }

    void IManagedContext.Response_Redirect(String url) {
        _context.Response.Redirect(url);
    }

    void IManagedContext.Response_AddHeader(String name, String value) {
        _context.Response.AppendHeader(name, value);
    }

    void IManagedContext.Response_Pics(String value) {
        _context.Response.Pics(value);
    }

    void IManagedContext.Response_Clear() {
        _context.Response.Clear();
    }

    void IManagedContext.Response_Flush() {
        _context.Response.Flush();
    }

    void IManagedContext.Response_End() {
        _context.Response.End();
    }

    void IManagedContext.Response_AppendToLog(String entry) {
        _context.Response.AppendToLog(entry);
    }

    String IManagedContext.Response_GetContentType() {
        return _context.Response.ContentType;
    }

    void IManagedContext.Response_SetContentType(String contentType) {
        _context.Response.ContentType = contentType;
    }

    String IManagedContext.Response_GetCharSet() {
        return _context.Response.Charset;
    }

    void IManagedContext.Response_SetCharSet(String charSet) {
        _context.Response.Charset = charSet;
    }

    String IManagedContext.Response_GetCacheControl() {
        return _context.Response.CacheControl;
    }

    void IManagedContext.Response_SetCacheControl(String cacheControl) {
        _context.Response.CacheControl = cacheControl;
    }

    String IManagedContext.Response_GetStatus() {
        return _context.Response.Status;
    }

    void IManagedContext.Response_SetStatus(String status) {
        _context.Response.Status = status;
    }

    int IManagedContext.Response_GetExpiresMinutes() {
        return _context.Response.Expires;
    }

    void IManagedContext.Response_SetExpiresMinutes(int expiresMinutes) {
        _context.Response.Expires = expiresMinutes;
    }

    double IManagedContext.Response_GetExpiresAbsolute() {
        return _context.Response.ExpiresAbsolute.ToOADate();
    }

    void IManagedContext.Response_SetExpiresAbsolute(double dtExpires) {
        _context.Response.ExpiresAbsolute = DateTime.FromOADate(dtExpires);
    }

    int IManagedContext.Response_GetIsBuffering() {
        return _context.Response.BufferOutput ? 1 : 0;
    }

    void IManagedContext.Response_SetIsBuffering(int isBuffering) {
        _context.Response.BufferOutput = (isBuffering != 0);
    }

    int IManagedContext.Response_IsClientConnected() {
        return _context.Response.IsClientConnected ? 1 : 0;
    }

    Object IManagedContext.Server_CreateObject(String progId) {
        return _context.Server.CreateObject(progId);
    }

    String IManagedContext.Server_MapPath(String logicalPath) {
        return _context.Server.MapPath(logicalPath);
    }

    String IManagedContext.Server_HTMLEncode(String str) {
        return HttpUtility.HtmlEncode(str);
    }

    String IManagedContext.Server_URLEncode(String str) {
        return _context.Server.UrlEncode(str);
    }

    String IManagedContext.Server_URLPathEncode(String str) {
        return _context.Server.UrlPathEncode(str);
    }

    int IManagedContext.Server_GetScriptTimeout() {
        return _context.Server.ScriptTimeout;
    }

    void IManagedContext.Server_SetScriptTimeout(int timeoutSeconds) {
        _context.Server.ScriptTimeout = timeoutSeconds;
    }

    void IManagedContext.Server_Execute(String url) {
        _context.Server.Execute(url);
    }

    void IManagedContext.Server_Transfer(String url) {
        _context.Server.Transfer(url);
    }

    int IManagedContext.Session_IsPresent() {
        return (_context.Session != null) ? 1 : 0;
    }

    String IManagedContext.Session_GetID() {
        return _context.Session.SessionID;
    }

    int IManagedContext.Session_GetTimeout() {
        return _context.Session.Timeout;
    }

    void IManagedContext.Session_SetTimeout(int value) {
        _context.Session.Timeout = value;
    }

    int IManagedContext.Session_GetCodePage() {
        return _context.Session.CodePage;
    }

    void IManagedContext.Session_SetCodePage(int value) {
        _context.Session.CodePage = value;
    }

    int IManagedContext.Session_GetLCID() {
        return _context.Session.LCID;
    }

    void IManagedContext.Session_SetLCID(int value) {
        _context.Session.LCID = value;
    }

    void IManagedContext.Session_Abandon() {
        _context.Session.Abandon();
    }

    String IManagedContext.Session_GetContentsNames() {
        return EnumKeysToString(_context.Session.GetEnumerator());
    }

    String IManagedContext.Session_GetStaticNames() {
        return DictEnumKeysToString((IDictionaryEnumerator)_context.Session.StaticObjects.GetEnumerator());
    }

    Object IManagedContext.Session_GetContentsObject(String name) {
        return _context.Session[name];
    }

    void IManagedContext.Session_SetContentsObject(String name, Object obj) {
        _context.Session[name] = obj;
    }

    void IManagedContext.Session_RemoveContentsObject(String name) {
        _context.Session.Remove(name);
    }

    void IManagedContext.Session_RemoveAllContentsObjects() {
        _context.Session.RemoveAll();
    }

    Object IManagedContext.Session_GetStaticObject(String name) {
        return _context.Session.StaticObjects[name];
    }

}

}


text:
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.git;

import java.util.Objects;

/** Indicates a problem with Git based data. */
public class ValidationError {
  private final String message;

  public ValidationError(String file, String message) {
    this(file + ": " + message);
  }

  public ValidationError(String file, int line, String message) {
    this(file + ":" + line + ": " + message);
  }

  public ValidationError(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }

  @Override
  public String toString() {
    return "ValidationError[" + message + "]";
  }

  public interface Sink {
    void error(ValidationError error);
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o instanceof ValidationError) {
      ValidationError that = (ValidationError) o;
      return Objects.equals(this.message, that.message);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(message);
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Gregwar\Formidable\Fields;

/**
 * Checkboxs
 *
 * @author Grégoire Passault <g.passault@gmail.com>
 */
class MulticheckboxField extends Field
{
    /**
     * Source name
     */
    protected $source;

    /**
     * Checkboxes
     */
    protected $checkboxes = array();

    /**
     * Labels
     */
    protected $labels = array();

    /**
     * Push saving
     */
    protected $pushSave = array();

    public function __sleep()
    {
        return array_merge(parent::__sleep(), array(
            'labels', 'source', 'checkboxes', 'pushSave'
        ));
    }

    public function check()
    {
        return;
    }

    public function push($var, $value = null)
    {
        switch ($var) {
        case 'source':
            $this->source = $value;
            break;
        default:
            parent::push($var, $value);
            break;
        }
    }

    public function getSource()
    {
        return $this->source;
    }

    public function source($datas)
    {
        foreach ($datas as $value => $label) {
            $this->checkboxes[$value] = $checkbox = new CheckboxField;
            $checkbox->push('name', $this->nameFor($value));
            $checkbox->push('value', '1');
            $this->labels[$this->nameFor($value)] = $label;

            foreach ($this->pushSave as $var => $val) {
                $checkbox->push($var, $val);
            }
        }
    }

    protected function nameFor($name)
    {
        return $this->getName().'['.$name.']';
    }

    public function setValue($values, $default = false)
    {
        if (!is_array($values)) {
            return;
        }

        $checked = array();

        if ($this->isNumericArray($values)) {
            foreach ($values as $name) {
                $checked[$this->nameFor($name)] = true;
            }
        } else {
            foreach ($values as $name => $one) {
                $checked[$this->nameFor($name)] = true;
            }
        }

        foreach ($this->checkboxes as $checkbox) {
            if (isset($checked[$checkbox->getName()])) {
                $checkbox->setChecked(true);
            } else {
                $checkbox->setChecked(false);
            }
        }
    }

    protected function isNumericArray(array $array)
    {
        $i = 0;

        foreach (array_keys($array) as $key) {
            if ($i !== $key) {
                return false;
            }

            $i++;
        }

        return true;
    }

    public function getValue()
    {
        $values = array();
        foreach ($this->checkboxes as $key => $checkbox) {
            if ($checkbox->isChecked()) {
                $values[] = $key;
            }
        }
        return $values;
    }

    public function getHtml()
    {
        $html = '';

        if ($this->checkboxes) {
            foreach ($this->checkboxes as $checkbox) {
                $html.= '
getAttribute('class').'">';
                $html.= '';
                $html.= $checkbox->getHtml();
                $html.= $this->labels[$checkbox->getName()];
                $html.= '';
                $html.= '
';
            }
        }

        return $html;
    }
}


text:
- Date#strptime Fix %Y issues ([#379](https://github.com/travisjeffery/timecop/pull/379))
- Add Truffleruby support ([#378](https://github.com/travisjeffery/timecop/pull/378))
- Deprecate ruby 2.5 ([#375](https://github.com/travisjeffery/timecop/pull/375))
- Better encapsulation of singleton instance ([#368](https://github.com/travisjeffery/timecop/pull/368))
- Support specifying only dates in Date.parse and Datetime.parse ([#296](https://github.com/travisjeffery/timecop/pull/296))

## v0.9.4

- Add ruby 3.1 support (#288)

## v0.9.3

- Fix returning to previous date after block when `Timecop.thread_safe = true` (#216)
- Fix %s and %Q for Date strptime (#275)
- Fix '%G-%V' for Date strptime (#261)
- Fix default day for strptime (#266)

## v0.9.2

- Make `require 'timecop'` threadsafe (#239)

## v0.9.1

- fix Date.parse when month/year only given (#206)

## v0.9.0

- add thread_safe option (#184)
- in safe mode, when already frozen, allow traveling with no block (#202)
- using Time.travel with a string should AS' Time.zone class (#170)
- fix Timecop being ignored when Date.parse infers year (#171, #158, #133)


text:
package main

import (
	"github.com/gopherjs/gopherjs/js"
	"github.com/slimsag/gfx"
	"github.com/slimsag/gfx/debug"
	"github.com/slimsag/gfx/driver/webgl"
)

func main() {
	// Create the body and canvas.
	document := js.Global.Get("document")
	body := document.Call("createElement", "body")
	document.Set("body", body)
	canvas := document.Call("createElement", "canvas")
	body.Call("appendChild", canvas)

	// Set size of canvas to 640x480
	canvas.Set("width", 640)
	canvas.Set("height", 480)

	// Create a new WebGL context (could also webgl.Wrap an existing one).
	gl, err := webgl.New(canvas, nil)
	if err != nil {
		js.Global.Call("alert", err.Error())
	}

	// Wrap the context to get a debug context.
	gl = debug.Context(gl)

	fb := gl.Framebuffer()
	fb.Load(fb.NewState(
		fb.ClearColor(1, 0, 0, 1),
	))

	// Clear the color buffer to red.
	fb.Clear(gfx.ColorBuffer)
}


text:
Set-StrictMode -Version Latest

InModuleScope Pester {
    Describe "PesterContainExactly" {
        Context "when testing file contents" {
            Setup -File "test.txt" "this is line 1`nPester is awesome"
            It "returns true if the file contains the specified content exactly" {
                Test-PositiveAssertion (PesterContainExactly "$TestDrive\test.txt" "Pester")
            }

            It "returns false if the file does not contain the specified content exactly" {
                Test-NegativeAssertion (PesterContainExactly "$TestDrive\test.txt" "pESTER")
            }
        }
    }
}


text:
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.web.action.protocol;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import gov.nih.nci.caarray.application.GenericDataService;
import gov.nih.nci.caarray.application.GenericDataServiceStub;
import gov.nih.nci.caarray.application.vocabulary.VocabularyService;
import gov.nih.nci.caarray.application.vocabulary.VocabularyServiceStub;
import gov.nih.nci.caarray.domain.protocol.Protocol;
import gov.nih.nci.caarray.domain.vocabulary.TermSource;
import gov.nih.nci.caarray.security.PermissionDeniedException;
import gov.nih.nci.caarray.util.j2ee.ServiceLocatorStub;
import gov.nih.nci.caarray.web.AbstractBaseStrutsTest;

import org.apache.struts2.ServletActionContext;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import com.fiveamsolutions.nci.commons.data.persistent.PersistentObject;
import com.opensymphony.xwork2.Action;

/**
 * @author Scott Miller
 *
 */
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public class ProtocolManagementActionTest extends AbstractBaseStrutsTest {

    private static GenericDataService genericDataService;
    private static VocabularyService vocabularyService;

    ProtocolManagementAction action;

    @BeforeClass
    @SuppressWarnings("PMD")
    public static void beforeClass() {
        genericDataService = new GenericDataServiceStub() {

            /**
             * {@inheritDoc}
             */
            @Override
            @SuppressWarnings({"unchecked", "deprecation"})
            public <T extends PersistentObject> T getPersistentObject(Class<T> entityClass, Long entityId) {
                if (entityClass.equals(Protocol.class) && entityId.equals(new Long(1))) {
                    Protocol p = new Protocol();
                    p.setId(1l);
                    p.setName("test protocol");
                    return (T) p;
                }
                return super.getPersistentObject(entityClass, entityId);
            }

        };

        vocabularyService = new VocabularyServiceStub();
        ServiceLocatorStub stub = ServiceLocatorStub.registerEmptyLocator();
        stub.addLookup(GenericDataService.JNDI_NAME, genericDataService);
        stub.addLookup(VocabularyService.JNDI_NAME, vocabularyService);
    }

    @Before
    public void before() {
        this.action = new ProtocolManagementAction();
    }

    @Test(expected = PermissionDeniedException.class)
    @SuppressWarnings("deprecation")
    public void testPrepare() {
        this.action.prepare();
        assertEquals(null, this.action.getProtocol());
        this.action.setProtocol(new Protocol());
        this.action.prepare();
        assertEquals(null, this.action.getProtocol().getId());
        this.action.setCreateNewSource(true);
        this.action.setNewSource(new TermSource());
        this.action.prepare();
        assertEquals(null, this.action.getProtocol().getId());

        this.action.setCreateNewSource(false);
        this.action.getProtocol().setId(1l);
        this.action.prepare();
        assertEquals("test protocol", this.action.getProtocol().getName());
        assertNull(this.action.getProtocol().getSource());

        this.action.setCreateNewSource(true);
        this.action.setNewSource(new TermSource());
        this.action.prepare();
        assertEquals("test protocol", this.action.getProtocol().getName());
        assertNotNull(this.action.getProtocol().getSource());

        this.action.getProtocol().setId(2l);
        this.action.prepare();
    }

    @Test
    public void testManage() {
        assertEquals(Action.SUCCESS, this.action.manage());
        assertEquals(null, ServletActionContext.getRequest().getSession().getAttribute("returnProjectId"));
    }

    @Test
    public void testStartOnEditPage() throws Exception {
        MockHttpServletRequest mockRequest = (MockHttpServletRequest) ServletActionContext.getRequest();
        mockRequest.addParameter("startWithEdit", "true");
        ServletActionContext.setRequest(mockRequest);
        this.action.setReturnInitialTab1("test1");
        this.action.setReturnInitialTab2("test2");
        this.action.setReturnInitialTab2Url("test2Url");
        this.action.setReturnProjectId(1L);
        this.action.setReturnInitialTab1("test1");

        assertEquals(Action.SUCCESS, this.action.manage());
        assertEquals(1L, ServletActionContext.getRequest().getSession().getAttribute("returnProjectId"));
        assertEquals("test1", ServletActionContext.getRequest().getSession().getAttribute("returnInitialTab1"));
        assertEquals("test2", ServletActionContext.getRequest().getSession().getAttribute("returnInitialTab2"));
        assertEquals("test2Url", ServletActionContext.getRequest().getSession().getAttribute("returnInitialTab2Url"));

        mockRequest.removeParameter("startWithEdit");
        this.action = new ProtocolManagementAction();
        assertEquals(Action.INPUT, this.action.list());
        assertTrue(this.action.isEditMode());
        assertEquals(null, ServletActionContext.getRequest().getSession().getAttribute("returnProjectId"));
        assertEquals(null, ServletActionContext.getRequest().getSession().getAttribute("returnInitialTab1"));
        assertEquals(null, ServletActionContext.getRequest().getSession().getAttribute("returnInitialTab2"));
        assertEquals(null, ServletActionContext.getRequest().getSession().getAttribute("returnInitialTab2Url"));

        assertEquals(1L, this.action.getReturnProjectId().intValue());
        assertEquals("test1", this.action.getReturnInitialTab1());
        assertEquals("test2", this.action.getReturnInitialTab2());
        assertEquals("test2Url", this.action.getReturnInitialTab2Url());
    }

    @Test
    public void testList() throws Exception {
        assertEquals(Action.SUCCESS, this.action.list());
        assertEquals(0, this.action.getProtocols().size());
    }

    @Test
    public void testEditAndDetailsAndProjectEdit() {
        this.action.setEditMode(false);
        assertEquals(Action.INPUT, this.action.edit());
        assertTrue(this.action.isEditMode());
        assertEquals(Action.INPUT, this.action.details());
        assertFalse(this.action.isEditMode());

        assertEquals("projectEdit", this.action.projectEdit());
    }
}


text:
import re
import base64

from anillo.http.responses import Response

class HttpBasicAuthBackend:
    def __init__(self, auth_func):
        self.auth_regex = re.compile(r"^Basic: (.*)$")
        self.auth_func = auth_func

    def parse(self, request):
        authorization = request.headers.get("Authorization", None)
        if authorization is None:
            return None

        match = re.match(self.auth_regex, authorization)
        if match is None:
            return None

        try:
            auth_data = base64.b64decode(match.group(1).encode("utf-8")).decode()
            (username, password) = auth_data.split(":")
            return {"username": username, "password": password}
        except Exception:
            return None

    def authenticate(self, request, data):
        identity = self.auth_func(data["username"], data["password"])
        if isinstance(identity, Response):
            return identity

        request.identity = identity
        return request


text:
gem 'minitest'
require 'minitest/autorun'
require "./lib/isps"
require "./lib/isps/core/product"
require "./lib/isps/data/relation_registry"
include ISPS::Data

# this class need for test protected methods, what are core methods for others
class RelContainer < RelationContainer
  def register(p1, p2, rel); super(p1, p2, rel); end
  def delete(p1, p2, rel); super(p1, p2, rel); end
end

describe RelContainer do

  before do
    @relations = RelContainer.new
  end

  describe ':register method' do
    it 'must raise ISPSRuntimeError if both products are equal' do
      proc {
        @relations.register('P1', 'P1', RelationContainer::COMPATIBILITY)
      }.must_raise ISPS::ISPSRuntimeError
    end

    it 'must add relation to container' do
      @relations.register('P1', 'P2', RelationContainer::COMPATIBILITY)
      @relations.relations.size.must_equal 1
    end

    it 'must raise ISPSRuntimeError if registered relation are exits in container' do
      @relations.register('P1', 'P2', RelationContainer::COMPATIBILITY)
      @relations.register('P1', 'P2', RelationContainer::APPLICABILITY)
      proc {
        @relations.register('P1', 'P2', RelationContainer::COMPATIBILITY)
      }.must_raise ISPS::ISPSRuntimeError
    end
  end

  describe ':delete method' do

    it 'must delete relation' do
      @relations.register('P1', 'P2', RelationContainer::APPLICABILITY)
      @relations.delete('P1', 'P2', RelationContainer::APPLICABILITY)
      @relations.relations.size.must_equal 0
    end

    it 'must raise ISPSRuntimeError if relation is not exist' do
      proc {
        @relations.delete('P1', 'P2', RelationContainer::APPLICABILITY)
      }.must_raise ISPS::ISPSRuntimeError
    end
  end

  describe ':register_xxxx methods' do

    it 'must add relation to container by :register_compatibility method' do
      @relations.register_compatibility('P1', 'P2')
      @relations.relations.size.must_equal 1
    end

    it 'must add relation to container by :register_applicability method' do
      @relations.register_applicability('P1', 'P2')
      @relations.relations.size.must_equal 1
    end

    it 'must add relation to container by :register_replaceability method' do
      @relations.register_replaceability('P1', 'P2')
      @relations.relations.size.must_equal 1
    end
  end

  describe ':get_xxxx_for methods' do

    before do
      @relations.register_compatibility('P1', 'P2')
      @relations.register_compatibility('P1', 'P3')
      @relations.register_compatibility('P0', 'P1')
      @relations.register_applicability('P1', 'P4')
      @relations.register_replaceability('P2', 'P3')
      @relations.register_replaceability('P2', 'P4')
      @relations.register_replaceability('P3', 'P4')
    end

    it ':get_compatible_for must return all compatible products' do
      @relations.get_compatible_for('P1').sort.must_equal ['P0', 'P2', 'P3']
      @relations.get_compatible_for('P2').sort.must_equal ['P1']
    end

    it ':get_applicable_for must return all applicable products' do
      @relations.get_applicable_for('P1').sort.must_equal ['P4']
    end

    it ':get_replaceable_for must return all replaceable products' do
      @relations.get_replaceable_for('P2').sort.must_equal ['P3', 'P4']
      @relations.get_replaceable_for('P4').sort.must_equal ['P2', 'P3']
    end
  end

end

describe ISPS::Data::RelationRegistry do
  before do
    @registry = ISPS::Data::RelationRegistry.instance
    @registry.register_compatibility('P1', 'P2')
    @registry.register_applicability('P1', 'P3')
  end

  it 'must save registry to database and load from it' do
    @registry.save
    @registry.relations.clear

    @registry.load
    @registry.get_compatible_for('P1').sort.must_equal ['P2']
    @registry.get_applicable_for('P1').sort.must_equal ['P3']
  end
end


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('route:analysis', 'Unit | Route | analysis', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
});

test('it exists', function(assert) {
  let route = this.subject();
  assert.ok(route);
});


text:
<?php

namespace Kodify\BlogBundle\Repository;

use Kodify\BlogBundle\Entity\Post;

/**
 * PostRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PostRepository extends AbstractBaseRepository
{

    /**
     * Updates Rate Value
     *
     * @param $id post id
     * @param $star number of stars
     *
     * @return bool true if everything is ok, false if it's not
     */
    public function setRate($id, $star)
    {
        $post = $this->getEntityManager()->getRepository("KodifyBlogBundle:Post")->find($id);
        $rated = false;
        if (Post::MINRATE <= $star && Post::MAXRATE >= $star) {
            $post->setRateClicks($post->getRateClicks() + 1);
            $post->setRateTotal($post->getRateTotal() + $star);
            $post->setRate(floor($post->getRateTotal() / $post->getRateClicks()));
            $this->getEntityManager()->flush($post);
            $rated = true;
        }

        return $rated;
    }

    /**
     * Returns posts ordered by Rate
     *
     * @param null $limit limit of posts per page
     * @param int $offset number of post to start with.
     *
     * @return array of post objects
     */
    public function sortRated($limit = null, $offset = 0)
    {
        if (is_null($limit)) {
            $limit = static::LIST_DEFAULT_LIMIT;
        }

        return $this->findBy([], ['rate' => 'DESC'], $limit, $offset);
    }

    /**
     * Search the post adding Author's name filtering
     *
     * @param $title
     * @param $content
     * @param $author
     *
     * @return array
     */
    public function searchWithAuthor($title, $content, $author)
    {

        $query = $this->getEntityManager()->createQuery(
            "
            SELECT p
            FROM KodifyBlogBundle:Post p
            JOIN  KodifyBlogBundle:Author a
            WHERE p.title = :title
            AND p.content = :content
            AND a.name = :author
            "
        )
            ->setParameter("title", $title)
            ->setParameter("content", $content)
            ->setParameter("author", $author);

        return $query->getOneOrNullResult();
    }

    /**
     * sort by latest
     */
    const SORT_LATEST = "latest";
    /**
     * sort by rate
     */
    const SORT_RATE = "rated";

    /**
     * Sort Selector
     *
     * @param string $sort sort type
     * @param null $limit limit of posts
     * @param int $offset first post to start
     *
     * @return array posts
     */
    public function sortPostsBy($sort = self::SORT_LATEST, $limit = null, $offset = 0)
    {
        switch ($sort) {
            case self::SORT_RATE:
                $posts = $this->sortRated($limit, $offset);
                break;
            default:
            case self::SORT_LATEST:
                $posts = $this->latest($limit, $offset);
                break;
        }

        return $posts;
    }

}


text: Reports unresolved references on properties as well as custom type definitions that cannot be resolved.


text:
package server

import (
	"fmt"
	"strings"

	"github.com/sirupsen/logrus"
	"golang.org/x/net/context"
	pb "k8s.io/kubernetes/pkg/kubelet/apis/cri/v1alpha1/runtime"
)

// RemoveImage removes the image.
func (s *Server) RemoveImage(ctx context.Context, req *pb.RemoveImageRequest) (*pb.RemoveImageResponse, error) {
	logrus.Debugf("RemoveImageRequest: %+v", req)
	image := ""
	img := req.GetImage()
	if img != nil {
		image = img.Image
	}
	if image == "" {
		return nil, fmt.Errorf("no image specified")
	}
	var (
		images  []string
		err     error
		deleted bool
	)
	images, err = s.StorageImageServer().ResolveNames(image)
	if err != nil {
		// This means we got an image ID
		if strings.Contains(err.Error(), "cannot specify 64-byte hexadecimal strings") {
			images = append(images, image)
		} else {
			return nil, err
		}
	}
	for _, img := range images {
		err = s.StorageImageServer().RemoveImage(s.ImageContext(), img)
		if err != nil {
			logrus.Debugf("error deleting image %s: %v", img, err)
			continue
		}
		deleted = true
		break
	}
	if !deleted && err != nil {
		return nil, err
	}
	resp := &pb.RemoveImageResponse{}
	logrus.Debugf("RemoveImageResponse: %+v", resp)
	return resp, nil
}


text:
package edu.uci.ics.asterix.algebra.base;

public interface AsterixOperatorAnnotations {
    public static final String FIELD_ACCESS = "FIELD_ACCESS";
    public static final String PUSHED_FIELD_ACCESS = "PUSHED_FIELD_ACCESS";
    public static final String PUSHED_RUNNABLE_FIELD_ACCESS = "PUSHED_RUNNABLE_FIELD_ACCESS";
    public static final String FIELD_TYPE = "FIELD_TYPE";
}


text:
TreeMapVis = function(_parentElement, _session) {
    var self = this;

    self.parentElement = _parentElement;

    self.treemapVisKeys = [
        'Title',
        'Released',
        'Year',
        'imdbRating',
        'tomatoRating',
        'tomatoUserRating'
    ]

    //Link movie data to timelineVis 'data'
    self.data = filterData(
        _session.get('actorMovies'),
        self.treemapVisKeys
    );

    self.treemapData = self.initData();
    self.displayData = [];
    self.initVis({title: "Co-Actors"}, self.treemapData);
};

TreeMapVis.prototype.initVis = function(o, data) {
    var defaults = {
        margin: {top: 24, right: 0, bottom: 0, left: 0},
        rootname: "Co-Actors",
        format: ",d",
        title: "",
        width: 960,
        height: 500
    };

    var root,
        opts = $.extend(true, {}, defaults, o),
        formatNumber = d3.format(opts.format),
        rname = opts.rootname,
        margin = opts.margin,
        theight = 36 + 16;

    $('#chart').width(opts.width).height(opts.height);
    var width = opts.width - margin.left - margin.right,
        height = opts.height - margin.top - margin.bottom - theight,
        transitioning;

    var color = d3.scale.category20c();

    var x = d3.scale.linear()
        .domain([0, width])
        .range([0, width]);

    var y = d3.scale.linear()
        .domain([0, height])
        .range([0, height]);

    var treemap = d3.layout.treemap()
        .children(function(d, depth) {
            return depth ? null : d._children;
        })
        .sort(function(a, b) {
            return a.value - b.value;
        })
        .ratio(height / width * 0.5 * (1 + Math.sqrt(5)))
        .round(false);

    var svg = d3.select("#chart").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.bottom + margin.top)
        .style("margin-left", -margin.left + "px")
        .style("margin.right", -margin.right + "px")
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .style("shape-rendering", "crispEdges");

    var grandparent = svg.append("g")
        .attr("class", "grandparent");

    grandparent.append("rect")
        .attr("y", -margin.top)
        .attr("width", width)
        .attr("height", margin.top);

    grandparent.append("text")
        .attr("x", 6)
        .attr("y", 6 - margin.top)
        .attr("dy", ".75em");

    // if (opts.title) {
    //     $("#chart").prepend("
" + opts.title + "
");
    // }
    if (data instanceof Array) {
        root = { key: rname, values: data };
    } else {
        root = data;
    }

    initialize(root);
    accumulate(root);
    layout(root);
    console.log(root);
    display(root);

    if (window.parent !== window) {
        var myheight = document.documentElement.scrollHeight || document.body.scrollHeight;
        window.parent.postMessage({height: myheight}, '*');
    }

    function initialize(root) {
        root.x = root.y = 0;
        root.dx = width;
        root.dy = height;
        root.depth = 0;
    }

    // Aggregate the values for internal nodes. This is normally done by the
    // treemap layout, but not here because of our custom implementation.
    // We also take a snapshot of the original children (_children) to avoid
    // the children being overwritten when when layout is computed.
    function accumulate(d) {
    return (d._children = d.values)
        ? d.value = d.values.reduce(function(p, v) { return p + accumulate(v); }, 0)
        : d.value;
    }

    // Compute the treemap layout recursively such that each group of siblings
    // uses the same size (1×1) rather than the dimensions of the parent cell.
    // This optimizes the layout for the current zoom state. Note that a wrapper
    // object is created for the parent node for each group of siblings so that
    // the parent's dimensions are not discarded as we recurse. Since each group
    // of sibling was laid out in 1×1, we must rescale to fit using absolute
    // coordinates. This lets us use a viewport to zoom.
    function layout(d) {
        if (d._children) {
            treemap.nodes({_children: d._children});
            d._children.forEach(function(c) {
                c.x = d.x + c.x * d.dx;
                c.y = d.y + c.y * d.dy;
                c.dx *= d.dx;
                c.dy *= d.dy;
                c.parent = d;
                layout(c);
            });
        }
    }

    function display(d) {
        grandparent
            .datum(d.parent)
            .on("click", transition)
            .select("text")
            .text(name(d));

        var g1 = svg.insert("g", ".grandparent")
            .datum(d)
            .attr("class", "depth");

        var g = g1.selectAll("g")
            .data(d._children)
            .enter().append("g");

        g.filter(function(d) { return d._children; })
            .classed("children", true)
            .on("click", transition);

        var children = g.selectAll(".child")
            .data(function(d) { return d._children || [d]; })
            .enter().append("g");

        children.append("rect")
            .attr("class", "child")
            .call(rect)
          .append("title")
            .text(function(d) { return d.key + " (" + formatNumber(d.value) + ")"; });

        // children.append("text")
        //     .attr("class", "ctext")
        //     .text(function(d) { return d.key; })
        //     .call(text2);

        g.append("rect")
            .attr("class", "parent")
            .call(rect);

        var t = g.append("text")
            .attr("class", "ptext")
            .attr("dy", ".75em")

        t.append("tspan")
            .text(function(d) {
                // var initialsList = d.key.split(" ");
                // var initials = '';
                // initialsList.forEach(function(i) {
                //     initials += i[0]
                //     if (i[1] !== '.') {
                //         initials += '. '
                //     }
                // })
                // return initials;
                return d.key;
            });

        t.append("tspan")
            .attr("dy", "1.0em")
            .text(function(d) {
                return formatNumber(d.value);
            });

        t.append("tspan")
            .attr("dy", "1.0em")
            .text(function(d) {
                return d.Title;
            });

        t.call(text);

        g.selectAll("rect")
            .style("fill", function(d) { return color(d.key); });

        function transition(d) {
            if (transitioning || !d) return;
            transitioning = true;

            var g2 = display(d),
                t1 = g1.transition().duration(750),
                t2 = g2.transition().duration(750);

            // Update the domain only after entering new elements.
            x.domain([d.x, d.x + d.dx]);
            y.domain([d.y, d.y + d.dy]);

            // Enable anti-aliasing during the transition.
            svg.style("shape-rendering", null);

            // Draw child nodes on top of parent nodes.
            svg.selectAll(".depth").sort(function(a, b) {
                return a.depth - b.depth;
            });

            // Fade-in entering text.
            g2.selectAll("text").style("fill-opacity", 0);

            // Transition to the new view.
            t1.selectAll(".ptext").call(text).style("fill-opacity", 0);
            t1.selectAll(".ctext").call(text2).style("fill-opacity", 0);
            t2.selectAll(".ptext").call(text).style("fill-opacity", 1);
            t2.selectAll(".ctext").call(text2).style("fill-opacity", 1);
            t1.selectAll("rect").call(rect);
            t2.selectAll("rect").call(rect);

            // Remove the old node when the transition is finished.
            t1.remove().each("end", function() {
                svg.style("shape-rendering", "crispEdges");
                transitioning = false;
            });
        }

        return g;
    }

    function text(text) {
        text.selectAll("tspan")
            .attr("x", function(d) { return x(d.x) + 6; })
        text.attr("x", function(d) { return x(d.x) + 6; })
            .attr("y", function(d) { return y(d.y) + 6; })
            .style("opacity", function(d) {
                return this.getComputedTextLength() < x(d.x + d.dx) - x(d.x) ? 1 : 0;
            });
    }

    function text2(text) {
        text.attr("x", function(d) { return x(d.x + d.dx) - this.getComputedTextLength() - 6; })
            .attr("y", function(d) { return y(d.y + d.dy) - 6; })
            .style("opacity", function(d) {
                return this.getComputedTextLength() < x(d.x + d.dx) - x(d.x) ? 1 : 0; });
    }

    function rect(rect) {
        rect.attr("x", function(d) { return x(d.x); })
            .attr("y", function(d) { return y(d.y); })
            .attr("width", function(d) {
                return x(d.x + d.dx) - x(d.x); })
            .attr("height", function(d) {
                return y(d.y + d.dy) - y(d.y); });
    }

    function name(d) {
        return d.parent
            ? name(d.parent) + " / " + d.key + " (" + formatNumber(d.value) + ")"
            : d.key + " (" + formatNumber(d.value) + ")";
    }

}

// number of co-workers
// TreeMapVis_.prototype.initData = function() {
//     var self = this;

//     var i;
//     var treemapData = {
//         "key": "coworkers",
//         "values": []
//     }

//     var minVotes = d3.min(self.data, function(d) {
//         return d['imdbVotes'];
//     });

//     var newData = getUniqueActorList(self.data);
//     allActors = newData[0];
//     self.data = newData[1];

//     // finish setting up the data structure
//     allActors.forEach(function(a) {
//         treemapData['values'].push({ key: a, values: [] })
//     })

//     allActors.forEach(function(actor) {

//         // aggregate all movies for actor
//         var coStarred= [];
//         for(i=0; i<self.data.length; i++) {
//             // var movie = self.data[i];
//             var movie = jQuery.extend({}, self.data[i])
//             var actorIdx = movie.Actors.indexOf(actor)
//             if (actorIdx > -1) {
//                 movie['key'] = actor;
//                 var votes = (movie['imdbVotes'] !== 'N/A') ? movie['imdbVotes']: "10";
//                 console.log(votes);
//                 movie['value'] =  (votes.indexOf(',') > -1) ?
//                     parseFloat(votes.replace(',', '')) :
//                     + votes; //1;
//                 coStarred.push(movie);
//             }
//         }

//         for (i=0; i<treemapData.values.length; i++){
//             if (treemapData.values[i].key === actor) {
//                 treemapData.values[i]['values'] = coStarred;
//             }
//         }

//     })

//     return treemapData;

// }

// most worked with
TreeMapVis.prototype.initData = function() {
    var self = this;

    var i;
    var treemapData = {
        "key": "Co-Actors",
        "values": []
    }

    var minVotes = d3.min(self.data, function(d) {
        return d['imdbVotes'];
    });

    var newData = getUniqueActorList(self.data);
    allActors = newData[0];
    self.data = newData[1];

    // finish setting up the data structure
    allActors.forEach(function(a) {
        treemapData['values'].push({ key: a, values: [] })
    })

    allActors.forEach(function(actor) {

        // aggregate all movies for actor
        var coStarred= [];
        for(i=0; i<self.data.length; i++) {
            // var movie = self.data[i];
            var movie = jQuery.extend({}, self.data[i])
            var actorIdx = movie.Actors.indexOf(actor)
            if (actorIdx > -1) {
                movie['key'] = actor;
                // var size = (movie['imdbRating'] !== 0.01) ? movie['imdbRating']: 1;
                movie['value'] = 1;
                coStarred.push(movie);
            }
        }

        for (i=0; i<treemapData.values.length; i++){
            if (treemapData.values[i].key === actor) {
                treemapData.values[i]['values'] = coStarred;
            }
        }

    })

    return treemapData;

}

getUniqueActorList = function(movieData) {
    var actors = [];
    for (var i=0; i<movieData.length; i++){
        var movie = movieData[i];
        var actorString = movie.Actors;

        // parse the actor string
        var actorList = actorString.split(',');
        for (var j=0; j<actorList.length; j++) {
            if (actorList[j][0] === " ") {
                actorList[j] = actorList[j].slice(1)
            }
        }

        movie.Actors = actorList;

        // add the unique actors to the list
        for (var j=0; j<actorList.length; j++) {
            if (actors.indexOf(actorList[j]) === -1) {
                actors.push(actorList[j]);
            }
        }

    }
    aData = Session.get('actorData')
    actors.splice( actors.indexOf(aData.name), 1 );
    return [actors, movieData];
}

// no more use...
// TreeMapVis_.prototype.initData = function() {
//     var self = this;

//     var i;
//     var treemapData = {
//         "key": "flare",
//         "values": []
//     }

//     var minVotes = d3.min(self.data, function(d) {
//         return d['imdbVotes'];
//     });

//     var allYears = getUniqueYearsList(self.data);

//     console.log(minVotes);
//     // finish setting up the data structure
//     allYears.forEach(function(y) {
//         treemapData['values'].push({ key: y, values: [] })
//     })

//     self.data.forEach(function(d) {
//         var name = d['Year'];
//         var size = (d['imdbVotes'] !== 'N/A') ? d['imdbVotes']: minVotes;
//         for (i=0; i<treemapData.values.length; i++){
//             if (treemapData.values[i].key === name) {
//                 d['key'] = name;
//                 d['value'] = parseFloat(size.replace(',', ''));
//                 treemapData.values[i]['values'].push(d);
//             }
//         }
//     })

//     return treemapData;
// }