text:
using AjaxControlToolkit.Design;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Drawing;

namespace AjaxControlToolkit {
    ///
    /// AsyncFileUpload is an ASP.NET AJAX Control that allows you to asynchronously upload files to the server.
    /// The file uploading results can be checked both on the server and client sides.
    ///
    [Designer(typeof(AsyncFileUploadDesigner))]
    [RequiredScript(typeof(CommonToolkitScripts))]
    [ClientScriptResource("Sys.Extended.UI.AsyncFileUpload", AjaxControlToolkit.Constants.AsyncFileUploadName)]
    [ToolboxBitmap(typeof(ToolboxIcons.Accessor), AjaxControlToolkit.Constants.AsyncFileUploadName + AjaxControlToolkit.Constants.IconPostfix)]
    public class AsyncFileUpload : ScriptControlBase {

        public static class Constants {
            public const string
                FileUploadIDKey = "AsyncFileUploadID",
                InternalErrorInvalidIFrame = "The ExtendedFileUpload control has encountered an error with the uploader in this page. Please refresh the page and try again.",
                fileUploadGUID = "b3b89160-3224-476e-9076-70b500c816cf";

            public static class Errors {
                public const string
                    NoFiles = "No files are attached to the upload.",
                    FileNull = "The file attached is invalid.",
                    NoFileName = "The file attached has an invalid filename.",
                    InputStreamNull = "The file attached could not be read.",
                    EmptyContentLength = "The file attached is empty.";
            }

            public static class StatusMessages {
                public const string UploadSuccessful = "The file uploaded successfully.";
            }
        }

        HttpPostedFile _postedFile = null;
        HtmlInputFile _inputFile = null;
        string _lastError = String.Empty;
        string _hiddenFieldID = String.Empty;
        string _innerTBID = String.Empty;
        bool _persistFile = false;
        bool _failedValidation = false;
        AsyncFileUploaderStyle _controlStyle = AsyncFileUploaderStyle.Traditional;

        public AsyncFileUpload()
            : base(true, HtmlTextWriterTag.Div) {
        }

        ///
        /// Fires when the file is successfully uploaded.
        ///
        [Bindable(true)]
        [Category("Server Events")]
        public event EventHandler<AsyncFileUploadEventArgs> UploadedComplete;

        ///
        /// Fires when the uploaded file is corrupted.
        ///
        [Bindable(true)]
        [Category("Server Events")]
        public event EventHandler<AsyncFileUploadEventArgs> UploadedFileError;

        bool IsDesignMode {
            get { return (HttpContext.Current == null); }
        }

        HttpPostedFile CurrentFile {
            get { return _persistFile ? PersistentStoreManager.Instance.GetFileFromSession(ClientID) : _postedFile; }
        }

        ///
        /// The name of a javascript function executed on the client side if the file upload started.
        ///
        [DefaultValue("")]
        [Category("Behavior")]
        [ExtenderControlEvent]
        [ClientPropertyName("uploadStarted")]
        public string OnClientUploadStarted {
            get { return (string)(ViewState["OnClientUploadStarted"] ?? String.Empty); }
            set { ViewState["OnClientUploadStarted"] = value; }
        }

        ///
        /// The name of a javascript function executed on the client side after a file is successfully uploaded.
        ///
        [DefaultValue("")]
        [Category("Behavior")]
        [ExtenderControlEvent]
        [ClientPropertyName("uploadComplete")]
        public string OnClientUploadComplete {
            get { return (string)(ViewState["OnClientUploadComplete"] ?? String.Empty); }
            set { ViewState["OnClientUploadComplete"] = value; }
        }

        ///
        /// The name of a javascript function executed on the client side if the file upload failed.
        ///
        [DefaultValue("")]
        [Category("Behavior")]
        [ExtenderControlEvent]
        [ClientPropertyName("uploadError")]
        public string OnClientUploadError {
            get { return (string)(ViewState["OnClientUploadError"] ?? String.Empty); }
            set { ViewState["OnClientUploadError"] = value; }
        }

        ///
        /// Uploaded file bytes
        ///
        [BrowsableAttribute(false)]
        public byte[] FileBytes {
            get {
                PopulateObjectPriorToRender(ClientID);
                var file = CurrentFile;
                if(file != null) {
                    try {
                        return GetBytesFromStream(file.InputStream);
                    } catch { }
                }
                return null;
            }
        }

        ///
        /// ID of a control that is shown while the file is being uploaded.
        ///
        [Category("Behavior")]
        [Description("ID of Throbber")]
        [DefaultValue("")]
        public string ThrobberID {
            get { return (string)(ViewState["ThrobberID"] ?? string.Empty); }
            set { ViewState["ThrobberID"] = value; }
        }

        ///
        /// The control's background color on upload complete. The default value is Lime.
        ///
        [Category("Appearance")]
        [TypeConverter(typeof(WebColorConverter))]
        [Description("Control's background color on upload complete.")]
        [DefaultValue(typeof(Color), "Lime")]
        public Color CompleteBackColor {
            get { return (Color)(ViewState["CompleteBackColor"] ?? Color.Lime); }
            set { ViewState["CompleteBackColor"] = value; }
        }

        ///
        /// The control's background color when uploading is in progress.
        /// The default value is White.
        ///
        [Category("Appearance")]
        [TypeConverter(typeof(WebColorConverter))]
        [Description("Control's background color when uploading is in progress.")]
        [DefaultValue(typeof(Color), "White")]
        public Color UploadingBackColor {
            get { return (Color)(ViewState["UploadingBackColor"] ?? Color.White); }
            set { ViewState["UploadingBackColor"] = value; }
        }

        ///
        /// The control's background color on an upload error.
        /// The default value is Red.
        ///
        [Category("Appearance")]
        [TypeConverter(typeof(WebColorConverter))]
        [Description("Control's background color on upload error.")]
        [DefaultValue(typeof(Color), "Red")]
        public Color ErrorBackColor {
            get { return (Color)(ViewState["ErrorBackColor"] ?? Color.Red); }
            set { ViewState["ErrorBackColor"] = value; }
        }

        ///
        /// The control's width (Unit).
        /// The default value is 355px.
        ///
        [DefaultValue(typeof(Unit), "")]
        [Category("Layout")]
        public override Unit Width {
            get { return base.Width; }
            set { base.Width = value; }
        }

        ///
        /// Whether validation is failed
        ///
        [BrowsableAttribute(false)]
        public bool FailedValidation {
            get { return _failedValidation; }
            set { _failedValidation = value; }
        }

        ///
        /// The control's appearance style (Traditional, Modern). The default value is Traditional.
        ///
        [Bindable(true)]
        [Category("Appearance")]
        [BrowsableAttribute(true)]
        [DefaultValue(AsyncFileUploaderStyle.Traditional)]
        public AsyncFileUploaderStyle UploaderStyle {
            get { return _controlStyle; }
            set { _controlStyle = value; }
        }

        ///
        /// A HttpPostedFile object that provides access to the uploaded file
        ///
        [BrowsableAttribute(false)]
        public HttpPostedFile PostedFile {
            get {
                PopulateObjectPriorToRender(ClientID);
                return CurrentFile;
            }
        }

        ///
        /// A bool value indicating whether the control contains a file
        ///
        [BrowsableAttribute(false)]
        public bool HasFile {
            get {
                PopulateObjectPriorToRender(ClientID);
                if(_persistFile) {
                    return PersistentStoreManager.Instance.FileExists(ClientID);
                }
                return (_postedFile != null);
            }
        }

        ///
        /// Gets the name of a file on the client that is uploaded using the control.
        ///
        [BrowsableAttribute(false)]
        public string FileName {
            get {
                PopulateObjectPriorToRender(ClientID);
                if(_persistFile) {
                    return Path.GetFileName(PersistentStoreManager.Instance.GetFileName(ClientID));
                } else if(_postedFile != null) {
                    return Path.GetFileName(_postedFile.FileName);
                }
                return String.Empty;
            }
        }

        ///
        /// Gets the name of a file on the client that is uploaded using the control.
        ///
        [BrowsableAttribute(false)]
        public string ContentType {
            get {
                PopulateObjectPriorToRender(ClientID);
                if(_persistFile) {
                    return PersistentStoreManager.Instance.GetContentType(ClientID);
                } else if(_postedFile != null) {
                    return _postedFile.ContentType;
                }
                return String.Empty;
            }
        }

        ///
        /// Gets a Stream object that points to an uploaded file to prepare for reading the content of the file.
        ///
        [BrowsableAttribute(false)]
        public Stream FileContent {
            get {
                PopulateObjectPriorToRender(ClientID);
                var file = CurrentFile;
                if(file == null || file.InputStream == null)
                    return null;

                return file.InputStream;
            }
        }

        ///
        /// Whether a file is being uploaded.
        ///
        [BrowsableAttribute(false)]
        public bool IsUploading {
            get { return (Page.Request.QueryString[Constants.FileUploadIDKey] != null); }
        }

        ///
        /// Whether a file is stored in session.
        /// The default value is false.
        ///
        [Bindable(true)]
        [BrowsableAttribute(true)]
        [DefaultValue(false)]
        public bool PersistFile {
            get { return _persistFile; }
            set { _persistFile = value; }
        }

        ///
        /// Clears all uploaded files of a current control from session.
        ///
        public void ClearAllFilesFromPersistedStore() {
            PersistentStoreManager.Instance.ClearAllFilesFromSession(this.ClientID);
        }

        ///
        /// Clears all uploaded files of current control from session
        ///
        public void ClearFileFromPersistedStore() {
            PersistentStoreManager.Instance.RemoveFileFromSession(this.ClientID);
        }

        ///
        /// Saves the content of an uploaded file.
        ///
        /// <param name="fileName" type="String">Uploaded file name</param>
        public void SaveAs(string fileName) {
            PopulateObjectPriorToRender(this.ClientID);
            var file = CurrentFile;
            file.SaveAs(fileName);
        }

        void PopulateObjectPriorToRender(string controlId) {
            bool exists;
            if(_persistFile)
                exists = PersistentStoreManager.Instance.FileExists(controlId);
            else
                exists = (_postedFile != null);

            if((!exists) && (this.Page != null && this.Page.Request.Files.Count != 0))
                ReceivedFile(controlId);
        }

        protected virtual void OnUploadedFileError(AsyncFileUploadEventArgs e) {
            if(UploadedFileError != null)
                UploadedFileError(this, e);
        }

        protected virtual void OnUploadedComplete(AsyncFileUploadEventArgs e) {
            if(UploadedComplete != null)
                UploadedComplete(this, e);
        }

        void ReceivedFile(string sendingControlID) {
            AsyncFileUploadEventArgs eventArgs = null;
            _lastError = String.Empty;

            if(this.Page.Request.Files.Count > 0) {
                HttpPostedFile file = null;
                if(sendingControlID == null || sendingControlID == String.Empty) {
                    file = this.Page.Request.Files[0];
                } else {
                    foreach(string uploadedFile in this.Page.Request.Files) {
                        var fileToUse = uploadedFile;
                        var straggler = "$ctl02";
                        if(fileToUse.EndsWith(straggler))
                            fileToUse = fileToUse.Remove(fileToUse.Length - straggler.Length);

                        if(fileToUse.Replace("$", "_").EndsWith(sendingControlID)) {
                            file = this.Page.Request.Files[uploadedFile];
                            break;
                        }
                    }
                }
                if(file == null) {
                    _lastError = Constants.Errors.FileNull;
                    eventArgs = new AsyncFileUploadEventArgs(
                        AsyncFileUploadState.Failed,
                        Constants.Errors.FileNull,
                        String.Empty,
                        String.Empty
                    );

                    OnUploadedFileError(eventArgs);
                } else if(file.FileName == String.Empty) {
                    _lastError = Constants.Errors.NoFileName;

                    eventArgs = new AsyncFileUploadEventArgs(
                       AsyncFileUploadState.Unknown,
                       Constants.Errors.NoFileName,
                       file.FileName,
                       file.ContentLength.ToString()
                    );

                    OnUploadedFileError(eventArgs);
                } else if(file.InputStream == null) {
                    _lastError = Constants.Errors.NoFileName;

                    eventArgs = new AsyncFileUploadEventArgs(
                        AsyncFileUploadState.Failed,
                        Constants.Errors.NoFileName,
                        file.FileName,
                        file.ContentLength.ToString()
                    );

                    OnUploadedFileError(eventArgs);
                } else if(file.ContentLength < 1) {
                    _lastError = Constants.Errors.EmptyContentLength;

                    eventArgs = new AsyncFileUploadEventArgs(
                        AsyncFileUploadState.Unknown,
                        Constants.Errors.EmptyContentLength,
                        file.FileName,
                        file.ContentLength.ToString()
                    );

                    OnUploadedFileError(eventArgs);
                } else {
                    eventArgs = new AsyncFileUploadEventArgs(
                        AsyncFileUploadState.Success,
                        String.Empty,
                        file.FileName,
                        file.ContentLength.ToString()
                    );

                    if(_persistFile) {
                        GC.SuppressFinalize(file);
                        PersistentStoreManager.Instance.AddFileToSession(this.ClientID, file.FileName, file);
                    } else {
                        _postedFile = file;
                    }
                    OnUploadedComplete(eventArgs);
                }
            }
        }

        public byte[] GetBytesFromStream(Stream stream) {
            var buffer = new byte[32768];
            using(var ms = new MemoryStream()) {
                stream.Seek(0, SeekOrigin.Begin);
                while(true) {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if(read <= 0) {
                        return ms.ToArray();
                    }
                    ms.Write(buffer, 0, read);
                }
            }
        }

        protected override void OnPreRender(EventArgs e) {
            base.OnPreRender(e);

            string sendingControlID = this.Page.Request.QueryString[Constants.FileUploadIDKey];

            if(sendingControlID == null || sendingControlID == this.ClientID) {
                ReceivedFile(this.ClientID);
                if(sendingControlID != null && sendingControlID.StartsWith(this.ClientID)) {
                    string result;
                    if(_lastError == String.Empty) {
                        var bytes = this.FileBytes;
                        if(bytes != null)
                            result = bytes.Length.ToString() + "------" + ContentType;
                        else
                            result = String.Empty;
                    } else {
                        result = "error------" + _lastError;
                    }

                    TextWriter output = Page.Response.Output;
                    output.Write("
");
                    output.Write(result);
                    output.Write("
");
                }
            }
        }

        internal void CreateChilds() {
            Controls.Clear();
            CreateChildControls();
        }

        protected override void CreateChildControls() {
            PersistentStoreManager.Instance.ExtendedFileUploadGUID = Constants.fileUploadGUID;
            string sendingControlID = null;
            if(!IsDesignMode)
                sendingControlID = this.Page.Request.QueryString[Constants.FileUploadIDKey];

            if(IsDesignMode || String.IsNullOrEmpty(sendingControlID)) {
                this._hiddenFieldID = GenerateHtmlInputHiddenControl();
                string lastFileName = String.Empty;
                if(_persistFile) {
                    if(PersistentStoreManager.Instance.FileExists(this.ClientID))
                        lastFileName = PersistentStoreManager.Instance.GetFileName(this.ClientID);
                } else if(_postedFile != null) {
                    lastFileName = _postedFile.FileName;
                }
                GenerateHtmlInputFileControl(lastFileName);
            }
        }

        protected string GenerateHtmlInputHiddenControl() {
            var field = new HiddenField();
            Controls.Add(field);
            return field.ClientID;
        }

        protected string GenerateHtmlInputFileControl(string lastFileName) {
            var div = new HtmlGenericControl("div");
            Controls.Add(div);

            if(this.UploaderStyle == AsyncFileUploaderStyle.Modern) {
                var bgImageUrl = ToolkitResourceManager.GetImageHref(AjaxControlToolkit.Constants.AsyncFileUploadImage, this);

                var style = "background:url(" + bgImageUrl + ") no-repeat 100% 1px; height:24px; margin:0px; text-align:right;";
                if(!Width.IsEmpty)
                    style += "min-width:" + Width.ToString() + ";width:" + Width.ToString() + " !important;";
                else
                    style += "width:355px;";

                div.Attributes.Add("style", style);
            }

            if(!(this.UploaderStyle == AsyncFileUploaderStyle.Modern && IsDesignMode)) {
                _inputFile = new HtmlInputFile();
                if(!this.Enabled)
                    _inputFile.Disabled = true;
                div.Controls.Add(_inputFile);
                _inputFile.Attributes.Add("id", _inputFile.Name.Replace("$", "_"));
                if(this.UploaderStyle != AsyncFileUploaderStyle.Modern) {
                    if(BackColor != Color.Empty)
                        _inputFile.Style[HtmlTextWriterStyle.BackgroundColor] = ColorTranslator.ToHtml(BackColor);

                    if(!Width.IsEmpty)
                        _inputFile.Style[HtmlTextWriterStyle.Width] = Width.ToString();
                    else
                        _inputFile.Style[HtmlTextWriterStyle.Width] = "355px";
                }
            }

            if(this.UploaderStyle == AsyncFileUploaderStyle.Modern) {
                var style = "opacity:0.0; -moz-opacity: 0.0; filter: alpha(opacity=00); font-size:14px;";
                if(!Width.IsEmpty)
                    style += "width:" + Width.ToString() + ";";

                if(_inputFile != null)
                    _inputFile.Attributes.Add("style", style);
                var textBox = new TextBox();

                if(!IsDesignMode) {
                    var div1 = new HtmlGenericControl("div");
                    div.Controls.Add(div1);
                    style = "margin-top:-23px;text-align:left;";
                    div1.Attributes.Add("style", style);
                    div1.Attributes.Add("type", "text");
                    div1.Controls.Add(textBox);
                    style = "height:17px; font-size:12px; font-family:Tahoma;";
                } else {
                    div.Controls.Add(textBox);
                    style = "height:23px; font-size:12px; font-family:Tahoma;";
                }
                if(!Width.IsEmpty && Width.ToString().IndexOf("px") > 0)
                    style += "width:" + (int.Parse(Width.ToString().Substring(0, Width.ToString().IndexOf("px"))) - 107).ToString() + "px;";
                else
                    style += "width:248px;";

                if(lastFileName != String.Empty || this._failedValidation) {
                    if((this.FileBytes != null && this.FileBytes.Length > 0) && (!this._failedValidation)) {
                        style += "background-color:#00FF00;";
                    } else {
                        this._failedValidation = false;
                        style += "background-color:#FF0000;";
                    }
                    textBox.Text = lastFileName;
                } else if(BackColor != Color.Empty) {
                    style += "background-color:" + ColorTranslator.ToHtml(BackColor) + ";";
                }
                textBox.ReadOnly = true;
                textBox.Attributes.Add("style", style);
                this._innerTBID = textBox.ClientID;
            } else if(IsDesignMode) {
                Controls.Clear();
                Controls.Add(_inputFile);
            }

            return div.ClientID;
        }

        protected override void DescribeComponent(ScriptComponentDescriptor descriptor) {
            base.DescribeComponent(descriptor);
            if(!IsDesignMode) {
                if(this._hiddenFieldID != String.Empty) descriptor.AddElementProperty("hiddenField", this._hiddenFieldID);
                if(this._innerTBID != String.Empty) descriptor.AddElementProperty("innerTB", this._innerTBID);
                if(this._inputFile != null) descriptor.AddElementProperty("inputFile", this._inputFile.Name.Replace("$", "_"));
                descriptor.AddProperty("postBackUrl", Page.Response.ApplyAppPathModifier(Page.Request.RawUrl));
                descriptor.AddProperty("formName", Path.GetFileName(this.Page.Form.Name));
                if(CompleteBackColor != Color.Empty)
                    descriptor.AddProperty("completeBackColor", ColorTranslator.ToHtml(CompleteBackColor));

                if(ErrorBackColor != Color.Empty)
                    descriptor.AddProperty("errorBackColor", ColorTranslator.ToHtml(ErrorBackColor));

                if(UploadingBackColor != Color.Empty)
                    descriptor.AddProperty("uploadingBackColor", ColorTranslator.ToHtml(UploadingBackColor));

                if(ThrobberID != string.Empty) {
                    var control = this.FindControl(ThrobberID);
                    if(control != null)
                        descriptor.AddElementProperty("throbber", control.ClientID);
                }
            }
        }

        protected override Style CreateControlStyle() {
            return new AsyncFileUploadStyleWrapper(ViewState);
        }

        sealed class AsyncFileUploadStyleWrapper : Style {
            public AsyncFileUploadStyleWrapper(StateBag state)
                : base(state) {
            }

            protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) {
                base.FillStyleAttributes(attributes, urlResolver);

                attributes.Remove(HtmlTextWriterStyle.BackgroundColor);
                attributes.Remove(HtmlTextWriterStyle.Width);
            }
        }
    }

}


text:
declare namespace Fuzzysort {
  interface Result {
    /**
    * Higher is better
    *
    * 0 is a perfect match; -1000 is a bad match
    */
    readonly score: number

    /** Your original target string */
    readonly target: string
  }
  interface Results extends ReadonlyArray<Result> {
    /** Total matches before limit */
    readonly total: number
  }

  interface KeyResult<T> extends Result {
    /** Your original object */
    readonly obj: T
  }
  interface KeysResult<T> extends ReadonlyArray<Result> {
    /**
    * Higher is better
    *
    * 0 is a perfect match; -1000 is a bad match
    */
   readonly score: number

    /** Your original object */
    readonly obj: T
  }
  interface KeyResults<T> extends ReadonlyArray<KeyResult<T>> {
    /** Total matches before limit */
    readonly total: number
  }
  interface KeysResults<T> extends ReadonlyArray<KeysResult<T>> {
    /** Total matches before limit */
    readonly total: number
  }

  interface Prepared {
    /** Your original target string */
    readonly target: string
  }

  interface Options {
    /** Don't return matches worse than this (higher is faster) */
    threshold?: number

    /** Don't return more results than this (lower is faster) */
    limit?: number

    /** If true, returns all results for an empty search */
    all?: boolean
  }
  interface KeyOptions extends Options {
    key: string | ReadonlyArray<string>
  }
  interface KeysOptions<T> extends Options {
    keys: ReadonlyArray<string | ReadonlyArray<string>>
    scoreFn?: (keysResult:ReadonlyArray<KeyResult<T>>) => number | null
  }

  interface HighlightCallback<T> { (match: string, index: number): T }

  interface Fuzzysort {

    single(search: string, target: string | Prepared): Result | null

    go(search: string, targets: ReadonlyArray<string | Prepared | undefined>, options?: Options): Results
    go<T>(search: string, targets: ReadonlyArray<T | undefined>, options: KeyOptions): KeyResults<T>
    go<T>(search: string, targets: ReadonlyArray<T | undefined>, options: KeysOptions<T>): KeysResults<T>

    highlight(result?: Result, highlightOpen?: string, highlightClose?: string): string | null
    highlight<T>(result: Result, callback: HighlightCallback<T>): (string | T)[] | null

    indexes(result: Result): ReadonlyArray<Number>
    cleanup(): void

    /**
    * Help the algorithm go fast by providing prepared targets instead of raw strings
    */
    prepare(target: string): Prepared

  }
}

declare module "fuzzysort" {
  const fuzzysort:Fuzzysort.Fuzzysort
  export = fuzzysort
}

redpajama_set_name: RedPajamaGithub


text:
package ru.job4j.iterators;

import java.util.Iterator;

public class Converter {

    Iterator<Integer> convert(Iterator<Iterator<Integer>> it) {

        return new Iterator<Integer>() {

            Iterator<Integer> innerIterator = it.next();

            @Override
            public boolean hasNext() {
                return innerIterator.hasNext() || it.hasNext();
            }

            @Override
            public Integer next() {
                if (!innerIterator.hasNext()) {
                    innerIterator = it.next();
                }
                return innerIterator.next();
            }
        };
    }
}


text:
(function(){
  $(window).load(function(){
    setTimeout(function(){
      $('.container-logo').addClass('fadeIn')
    }, 300)
    setTimeout(function(){
      $('.blog-description').addClass('fadeIn')
      $('.btn-about').addClass('fadeIn')
    }, 600)
  });
})();


text:
<?php

namespace Nails\Cli\Exceptions\System;

use Nails\Cli\Exceptions\SystemException;

class CommandFailedException extends SystemException
{
}


text:
__version__ = "0.4"

import argparse
import cgi
import datetime
import errno
import io
import logging
import multiprocessing
import os
import re
import signal
import socket
import sys
import time
import traceback
import urllib

# Python2/3 module disambiguation
if sys.version[0] == '3':
    import configparser
    import http.server as http_server
    import urllib.request as urllib2
    import urllib.parse as urlparse
else:
    import ConfigParser as configparser
    import BaseHTTPServer as http_server
    import urllib2
    import urlparse

# Gracefully exit if PIL is missing
try:
    from PIL import Image, ImageFile, ImageColor, ImageChops, ImageDraw
except:
    print("Missing the PIL module; consult https://github.com/redfin/dirpy " +
        "for instructions on how to install PIL.")
    sys.exit(1)

# Workaround for truncated images
ImageFile.LOAD_TRUNCATED_IMAGES = True

# The dirpy image class.  Defines the various operations that can be performed
# on images loaded by dirpy
class DirpyImage: ############################################################

    def __init__(self, http_root):
        self.logger         = logging.getLogger("dirpy")
        self.local_file     = None
        self.file_path      = None
        self.req_dims       = [None, None]
        self.num_dims       = 0
        self.gravity        = None
        self.im_in          = None
        self.in_fmt         = None
        self.in_info        = {}
        self.out_fmt        = None
        self.out_buf        = None
        self.out_size       = 0
        self.save_opts      = {}
        self.trans          = None
        self.modified       = False
        self.http_root      = http_root

    # Run a command, provided that it is value
    def run(self, cmd, opts):
        if cmd.startswith("_"):
            raise DirpyUserError("Internal method not run()-able: %s" % cmd)
        try:
            method = getattr(self, cmd)
        except AttributeError:
            raise DirpyUserError("Unknown command: %s" % cmd)

        method(opts)

    # Load an image file, either from disk or a local HTTP(S) server
    def load(self, opts, rel_file, req_post_data): ###########################

        # A file-like object to store the result of our BytesIO
        # output (in the event of a proxied result) or the contents
        # of the local file read from disk
        file_obj = None

        # Normalize our path (and prevent directory traversal)
        self.local_file = os.path.normpath(cfg.http_root +
            os.path.normpath("/" + rel_file))

        # Parse our options
        proxy       = opts["proxy"] if "proxy" in opts else None
        fallback    = "fallback" in opts
        from_post   = "post" in opts

        # Try to open our file
        try:
            # Load a file via POST data if the stars are aligned
            if from_post and req_post_data:
                if cfg.allow_post:
                    self.logger.debug("Loading post data: %s" % str(opts))
                    file_obj = req_post_data
                    self.file_path = "POST_file"
                else:
                    raise DirpyUserError("POST prohibited.")

            # Proxy a file from a remote server, if requested
            elif proxy and not (fallback and os.path.isfile(self.local_file)):
                self.file_path = proxy + rel_file
                self.logger.debug("Loading image %s: %s" %
                    (self.file_path, str(opts)))
                proxy_req = urllib2.Request(self.file_path,
                    headers={"User-Agent": "Dirpy/" + __version__})
                proxy_res = urllib2.urlopen(proxy_req)
                file_obj = io.BytesIO(proxy_res.read())

            # Otherwise read it locally
            else:
                self.file_path = self.local_file
                self.logger.debug("Loading image %s: %s" %
                    (self.file_path, str(opts)))
                file_obj = open(self.file_path, "rb")

            self.logger.debug("Serving file: %s" % self.file_path)
        except Exception as e:
            err_code = e.code if hasattr(e, "code") else 404
            raise DirpyUserError("Error reading file: %s" % e, err_code)

        # Read in the image from the file object
        try:
            self.im_in = Image.open(file_obj)

            # Record our input format and dimensions
            self.in_fmt = self.im_in.format.lower()
            self.in_info = self.im_in.info
            self.in_x, self.in_y = self.im_in.size
            self.orig_x, self.orig_y = self.im_in.size

            # Guard against decompression bombs
            if cfg.max_pixels and self.in_x * self.in_y > cfg.max_pixels:
                raise DirpyUserError("Image exceeds maximum pixel limit")

        except Exception as e:
            raise DirpyUserError("Error opening image: %s" % e, 400)

    # Resize an image
    def resize(self, opts): ##################################################

        self.logger.debug(
            "Resizing image %s: %s" % (self.file_path, str(opts)))

        # Fetch our percentage resize value (if any)
        try:
            pct = int(opts["pct"]) if "pct" in opts else None
        except ValueError:
            raise DirpyUserError("Percent size must be an integer: %s" %
                opts["pct"])

        # Get our dimensions (if specified)
        dim_set = self._get_req_dims(opts)
        if len(self.req_dims) != 2 and not pct:
            raise DirpyUserError("Resize requires either 1 or 2 dimensions")
        req_x, req_y = self.req_dims

        # Set our boolean operators
        unlock      = "unlock" in opts          # remove aspect ratio locking
        fill        = "fill" in opts            # use smaller dim. as limit
        shrink      = "shrink" in opts          # only shrink images
        grow        = "grow" in opts            # only grow images
        landscape   = "landscape" in opts       # resize using landscape mode
        portrait    = "portrait" in opts        # resize using portrait mode

        # Determine if we have any missing or conflicting options
        if not (req_x or req_y or pct):
            raise DirpyUserError("Need height and/or width or pct for resize")
        if dim_set and pct:
            raise DirpyUserError("Height/width & pct are mutually exclusive")
        if unlock + fill + landscape + portrait > 1:
            raise DirpyUserError("Unlock/fill/landscape/portrait "
                "are mutually exclusive")
        if (unlock or fill or landscape) and not (req_x and req_y):
            raise dirpyerror("Unlock/fill/landscape/portrait "
                "need both width and height")
        if shrink and grow:
            raise DirpyUserError("Shrink and grow are mutually exclusive")
        if pct and (unlock or fill):
            raise DirpyUserError("Unlock/fill/landscape/portrait "
                "not used for pct resize")
        if pct and (shrink or grow):
            raise DirpyUserError("Shrink/grow not used for pct-based resize")

        # Set our resampling filter
        filter_name = opts["filter"] if "filter" in opts else None
        if filter_name == "nearest":
            filter_type = Image.NEAREST
        elif filter_name == "bilinear":
            filter_type = Image.BILINEAR
        elif filter_name == "bicubic":
            filter_type = Image.BICUBIC
        else:
            filter_name = "antialias";
            filter_type = Image.ANTIALIAS

        # Calculate height and width resize rations based on original image
        # dimensions, user-requested dimensions, and aspect ratio options
        new_x = new_y = None
        if pct:
            resize_ratio = float(pct)/100
        elif unlock:
            resize_ratio = min(float(req_x)/self.in_x,
                float(req_y)/self.in_y)
            new_x, new_y = req_x, req_y
        elif landscape:
            if self.in_x > self.in_y:
                resize_ratio = max(float(req_x)/self.in_x,
                    float(req_y)/self.in_y)
            else:
                resize_ratio = min(float(req_x)/self.in_x,
                    float(req_y)/self.in_y)
        elif portrait:
            if self.in_x < self.in_y:
                resize_ratio = max(float(req_x)/self.in_x,
                    float(req_y)/self.in_y)
            else:
                resize_ratio = min(float(req_x)/self.in_x,
                    float(req_y)/self.in_y)
        else:
            if not req_y:
                resize_ratio = float(req_x)/self.in_x
            elif not req_x:
                resize_ratio = float(req_y)/self.in_y
            elif fill:
                resize_ratio = max(float(req_x)/self.in_x,
                    float(req_y)/self.in_y)
            else:
                resize_ratio = min(float(req_x)/self.in_x,
                    float(req_y)/self.in_y)

            # Evaluate our target dimensions to preserve aspect ratio
        if new_x is None:
            new_x = int(self.in_x * resize_ratio)
        if new_y is None:
            new_y = int(self.in_y * resize_ratio)

        self.logger.debug(
            "Resize: in_x=%s in_y=%s new_x=%s new_y=%s ratio=%s" %
            (self.in_x, self.in_y, new_x, new_y, resize_ratio))

        # Now do the actual resize
        try:
            if not shrink and resize_ratio > 1:
                self.im_in = self.im_in.resize((new_x, new_y), filter_type)
                self.modified = True
            elif not grow and resize_ratio < 1:
                self.im_in.draft(None,(new_x,new_y))
                self.im_in = self.im_in.resize((new_x, new_y), filter_type)
                self.modified = True
            self.in_x, self.in_y = self.im_in.size
        except Exception as e:
            raise DirpyFatalError("Error resizing: %s" % e)

    # Crop an image
    def crop(self, opts): ####################################################

        self.logger.debug("Cropping image %s: %s"
            % (self.file_path, str(opts)))

        # Make sure that we have an appropriate dimension set
        self._get_req_dims(opts)

        # Handle automatic border cropping
        if "border" in opts:

            # Allow fuziness modification
            if opts["border"] is True:
                fuzz = 100
            else:
                try:
                    fuzz = int(opts["border"])
                    if not 0 < fuzz < 255:
                        raise Exception
                except:
                    raise DirpyUserError(
                        "Crop fuzz must be an integer between 0 and 255: %s"
                        % opts["border"])

            # Do an image channel difference, and then get the bounding box
            # to determine where the border is
            bg = Image.new(self.im_in.mode, self.im_in.size,
                self.im_in.getpixel((0,0)))
            diff = ImageChops.difference(self.im_in, bg)
            new_dims = list(ImageChops.add(diff, diff, 2.0, -fuzz).getbbox())

            # Make border cropping symmetric, if requested
            if "symmetric" in opts:
                if new_dims[0] > self.in_x - new_dims[2]:
                    new_dims[0] = self.in_x - new_dims[2]
                elif new_dims[2] < self.in_x - new_dims[0]:
                    new_dims[2] = self.in_x - new_dims[0]

                if new_dims[1] > self.in_y - new_dims[3]:
                    new_dims[1] = self.in_y - new_dims[3]
                elif new_dims[3] < self.in_y - new_dims[1]:
                    new_dims[3] = self.in_y - new_dims[1]

        # Handle gravity crop (i.e. a dimension-based crop)
        elif self.num_dims == 2:
            # Unlike coordinate-based cropping, we correct crop boundaries
            # outside our image boundary, as we can inherit crop dimensions
            # from previous commands which may have shrank the image
            # boundary below the specified dimensions

            if self.req_dims[0] > self.in_x:
                self.req_dims[0] = self.in_x
            if self.req_dims[1] > self.in_y:
                self.req_dims[1] = self.in_y

            # Don't bother cropping if our image is the same size as our
            # requested crop size
            if (self.req_dims[1] == self.in_y
                    and self.req_dims[0] == self.in_x):
                return

            new_dims = self._get_new_dims(opts)

        # Handle the exact crop (i.e. a coordinate-based crop)
        elif self.num_dims == 4:

            # Sanity checks
            if "gravity" in opts:
                raise DirpyUserError("Gravity only used for dimension crops")

            if None in self.req_dims:
                raise DirpyUserError(
                    "All values required in a cordinate-based crop: %s" %
                    str(self.req_dims))

            if not (self.req_dims[0] < self.req_dims[2] and
                    self.req_dims[1] < self.req_dims[3]):
                raise DirpyUserError(
                    "Coordinates a,b,c,d should have a < c and b < d: " %
                    str(self.req_dims))

            if (self.req_dims[0] < 0 or self.req_dims[1] < 0 or
                    self.req_dims[2] > self.in_x or
                    self.req_dims[3] > self.in_y):
                raise DirpyUserError(
                    "Crop corners must be inside source image border: %s" %
                    str(self.req_dims))

            new_dims = self.req_dims

        # Handle invalid # of crop dims
        else:
            raise DirpyUserError("Crop requires dimensions or coordinates")

        self.logger.debug("Crop: in_x=%s in_y=%s crop_box=%s, grav=%s" %
            (self.in_x, self.in_y, str(new_dims), self.gravity))

        # Now crop the image
        try:
            self.im_in = self.im_in.crop(new_dims)
            self.im_in.load()
            self.in_x, self.in_y = self.im_in.size
            self.modified = True
        except Exception as e:
            raise DirpyFatalError("Error cropping: %s" % e)

    # Pad an image
    def pad(self, opts): #####################################################

        self.logger.debug("Padding image %s: %s"
            % (self.file_path, str(opts)))

        # Make sure that we have an appropriate dimension set
        self._get_req_dims(opts)
        if self.num_dims != 2:
            raise DirpyUserError("Pad requires no more than 2 dimensions")

        # Sanity check
        if (self.req_dims[0] < self.in_x or
                self.req_dims[1] < self.in_y):
            raise DirpyUserError(
                "Pad area must be larger than source image: %s < [%s,%s]" %
                (str(self.req_dims), self.in_x, self.in_y))

        # Process transparency request
        if "trans" in opts:
            try:
                self.trans = int(opts["trans"])
                assert 0 <= self.trans <= 255
            except Exception as e:
                raise DirpyUserError("Transparency must be an integer "
                    "between 0 and 255, inclusive")

        # Determine what our background color tuple will be
        try:
            if "bg" in opts:
                req_color = opts["bg"]
            else:
                req_color = "white"

            hex_match = re.match(r"[0-9a-fA-F]{3,6}", req_color)
            if hex_match:
                req_color = "#" + req_color

            if self.trans is not None:
                pad_mode = "RGBA"
            else:
                pad_mode = self.im_in.mode

            pad_color = ImageColor.getcolor(req_color, pad_mode)

        except Exception as e:
            raise DirpyUserError("Not a valid color: %s, %s" % (req_color,e))

        # Get our interior dimension locations
        new_dims = self._get_new_dims(opts)

        # Create the padded image and insert our old image into it and
        # then overwrite our existing input image with the paddded one
        try:
            im_pad = Image.new(pad_mode, self.req_dims, pad_color)
            im_pad.paste(self.im_in, new_dims)

            if self.trans is not None:
                mask_dims=(
                    new_dims[0], new_dims[1], new_dims[2]-1, new_dims[3]-1)
                im_mask = Image.new('L', self.req_dims, color=self.trans)
                ImageDraw.Draw(im_mask).rectangle(mask_dims, fill=255)
                im_pad.putalpha(im_mask)

            self.im_in = im_pad
            self.in_x, self.in_y = self.im_in.size
            self.modified = True
        except Exception as e:
            raise DirpyFatalError(
                "Error padding image %s: %s" % (self.file_path,e))

    # Transpose an image
    def transpose(self, opts): ###############################################

        self.logger.debug("Transposing image %s: %s"
            % (self.file_path, str(opts)))

        # Parse possible arguments
        num_args = 0
        if "flipvert" in opts:
            method = Image.FLIP_LEFT_RIGHT
            num_args += 1
        if "fliphorz" in opts:
            method = Image.FLIP_TOP_BOTTOM
            num_args += 1
        if "rotate90" in opts:
            method = Image.ROTATE_90
            num_args += 1
        if "rotate180" in opts:
            method = Image.ROTATE_180
            num_args += 1
        if "rotate270" in opts:
            method = Image.ROTATE_270
            num_args += 1

        if num_args != 1:
            raise DirpyUserError(
                "Transpose requires exactly one option: %s" % str(opts))

        # Now rotate
        try:
            self.im_in = self.im_in.transpose(method)
            self.in_x, self.in_y = self.im_in.size
            self.modified = True
        except Exception as e:
            raise DirpyFatalError(
                "Error transposing image %s: %s" % (self.file_path,e))

    # Write an image to a BytesIO output buffer
    def save(self, opts): ####################################################

        self.logger.debug("Saving image %s: %s" % (self.file_path, str(opts)))

        # Handle save options
        noicc       = "noicc" in opts
        progressive = "progressive" in opts
        optimize    = "optimize" in opts
        noshow      = "noshow" in opts

        # Determine if we are being asked to save the result to disk locally
        # (and if we are permitted to)
        if "todisk" in opts:
            if not cfg.allow_todisk:
                raise DirpyUserError(
                    "Saving to disk forbidden: %s" % str(opts))
            if not cfg.todisk_root:
                raise DirpyUserError(
                    "Save to disk path unset: %s" % str(opts))
            todisk_path = os.path.normpath(cfg.todisk_root +
                os.path.normpath("/" + opts["todisk"]))
        else:
            todisk_path = False

        # Set and spot-check our output format
        if "fmt" in opts:
            self.out_fmt = opts["fmt"].lower()
        elif self.in_fmt:
            self.out_fmt = self.in_fmt
        else:
            self.logger.debug("Can't determine encoder; falling back to jpeg")
            self.out_fmt = "jpeg" # Fall back to jpeg

        # Fix any attempts to use the non-existant "jpg" output plugin
        if self.out_fmt == "jpg":
            self.out_fmt = "jpeg"

        # Set output quality (only affects jpeg/webp formats)
        if self.out_fmt in ("jpeg", "webp"):
            try:
                if "qual" in opts:
                    qual_val = int(opts["qual"])
                else:
                    qual_val = cfg.def_quality
            except:
                raise DirpyUserError("Quality must be an integer")

            # Make sure we got a valid quality percentage
            if not 0 < qual_val < 101:
                raise Exception("Invalid quality")

            # Dont recompress input images that are less than this size
            if self.in_x * self.in_y < cfg.min_recompress_pixels:
                self.logger.debug("Not recompressing image: %s < %s" %
                    (self.in_x * self.in_y,
                    cfg.min_recompress_pixels))
                qual_val=95

        else:
            qual_val = None

        # Handle pallette-style transparency
        if self.out_fmt in ("gif"):
            if self.trans is not None:
                self.save_opts["transparency"] = 0

        # Preserve our ICC profile if this is a JPEG, unless explicitly
        # requested otherwise
        icc_prof = None
        if self.in_fmt == "jpeg" and not noicc:
            icc_prof = self.im_in.info.get("icc_profile")

        # Convert pallette mode to RGB, if this is a jpeg, since JPEG
        # doesn't support mode P
        if self.out_fmt == "jpeg" and self.im_in.mode == "P":
            self.im_in = self.im_in.convert("RGB")

        # Maintain the encoder subsampling to prevent jpeg->jpeg size bloat
        # (although this only works on un-modified images)
        if self.in_fmt == self.out_fmt == "jpeg" and not self.modified:
            self.im_in.format = "JPEG"
            qual_val = "keep"
            self.logger.debug("Preventing JPEG recompression.")

        # Now write the converted image to a buffer
        try:
            # set up our bytesIO object, since PIL refuses to write
            # directly to a string
            self.out_buf = io.BytesIO()

            # Our output arguments.  We have to to use a kwargs pointer, as
            # the save function will sometimes interpret the presence of
            # an argument (regardless of its value) to mean a true value

            # Bump up the ImageFile.MAXBLOCK size when writing optimized or
            # progressive images to avoid a legacy PIL bug
            self.save_opts["format"] = self.out_fmt
            if progressive or optimize:
                ImageFile.MAXBLOCK =  max(
                    self.orig_x * self.orig_y,
                    self.in_x * self.in_y, 2097152)
                self.logger.debug("MAXBLOCK set to: %s" % ImageFile.MAXBLOCK)
            if optimize:
                self.save_opts["optimize"] = True
            if progressive:
                self.save_opts["progressive"] = True
            if icc_prof is not None:
                self.save_opts["icc_profile"] = icc_prof
            if qual_val is not None:
                self.save_opts["quality"] = qual_val

            # Save our image to the bytesIO buffer, with all of our
            # various user-defined or default config options
            # Note that any "failed to suspend" errors here are typically
            # caused by your MAXBLOCK variable being too small
            try:
                self.im_in.save(self.out_buf, **self.save_opts)
            except Exception as e:
                raise DirpyFatalError("Failed to save image: %s" % e)

            # If we are being asked to write to disk, do so
            if todisk_path:

                # Verify that the file doesn't exist on disk already and/or
                # that we are allowed to overwrite it
                if os.path.exists(todisk_path) and not cfg.allow_overwrite:
                    raise DirpyUserError("Can't overwrite %s" % todisk_path)

                # Make the subdirectory if necessary (and permitted)
                this_dir = os.path.dirname(todisk_path)
                if os.path.exists(this_dir):
                    if not os.path.isdir(this_dir):
                        raise DirpyUserError(
                            "%s exists and is not a directory" % this_dir)
                elif not cfg.allow_mkdir:
                    raise DirpyUserError(
                        "%s doesn't exist and allow_mkdir is False"
                        % this_dir)
                else:
                    try:
                        os.makedirs(this_dir)
                    except OSError as e:
                        if (e.errno == errno.EEXIST
                                and os.path.isdir(this_dir)):
                            pass
                        else:
                            raise DirpyFatalError(
                                "Can't mkdir %s: %s" % (this_dir, e))

                # Now write the BytesIO buffer to disk
                try:
                    self.logger.debug("Saving to disk at '%s'" % todisk_path)
                    with open(todisk_path, 'w') as out_file:
                        self.out_buf.seek(0,os.SEEK_SET)
                        out_file.write(self.out_buf.read())
                except Exception as e:
                    raise DirpyFatalError("Can't save image to disk: %s" % e)

            # If the user has requested "noshow", we don't want to return the
            # image back to them (presumably because we have saved it to disk
            # and that is all they care about, so we don't have to waste
            # network overhead sending the image back to them)
            if noshow:
                logger.debug("Not showing %s, as requested" % self.file_path)
                self.out_buf = io.BytesIO()

            # Seek to the end of the buffer so we can get our content
            # size without allocating to a string (which we don't want
            # to do if this is a HEAD request).  Then seek back to the
            # beginning so we can read the string later
            self.out_buf.seek(0,os.SEEK_END)
            self.out_size = self.out_buf.tell()
            self.out_buf.seek(0)

        except DirpyFatalError:
            raise
        except DirpyUserError:
            raise
        except Exception as e:
            raise DirpyFatalError("Error converting image '%s': %s" %
                (self.file_path, e))

    # Iterate through our options keys and see if any of them match the NxN
    # pattern for image dimensions.  Dropping one of the two image dimensions
    # is permitted (i.e. '640x480',' '640x' & 'x480' are valid dimensions).
    def _get_req_dims(self, opts): ###########################################

        dims = []

        for o in [ n for n in opts if "x" in n]:
            try:
                o_dims = [None if x == "" else int(x) for x in o.split("x",3)]
            except ValueError:
                continue

            # Expand our final dimension array to be as large as the
            # one that we are currently inspecting
            dims += [None]*(len(o_dims)-len(dims))

            # Iterate over each dimension in this list and make sure that we
            # haven't set it in a previous iteration
            for i in range(0, len(dims)):
                if o_dims[i] is not None:
                    if dims[i] is not None:
                        raise DirpyUserError(
                            "Each dimension must be defined only once")
                    dims[i] = o_dims[i]

        # If we were able to find some dimensions in our options array,
        # assign them to your req_dims classvar
        if len(dims) and dims != [None] * len(dims):
            self.req_dims = dims + [None]*(2-len(dims))
            self.num_dims = len(dims)
            return True

        return False

    # Get the post-gravity adjusted dimensions.  These can be bigger or
    # smaller than the originally requested dimensions,
    def _get_new_dims(self,opts): ############################################

        # Get our gravity, if any
        self.gravity = opts["gravity"] if "gravity" in opts else "c"

        # Check our gravity setting
        if self.gravity not in ("n","ne","e","se","s","sw","w","nw","c"):
            raise DirpyUserError("Unknown gravity: %s" % self.gravity)

        new_dims = [None, None, None, None]

        # Account for requested dimensions with only a single value set
        req_x = self.req_dims[0] or self.in_x
        req_y = self.req_dims[1] or self.in_y

        # Now calculate dimensions based on gravity
        if "w" in self.gravity:
            new_dims[0] = 0
        elif "e" in self.gravity:
            new_dims[0] = abs(self.in_x - req_x)
        else:
            new_dims[0]  = abs(self.in_x - req_x)/2

        if "n" in self.gravity:
            new_dims[1] = 0
        elif "s" in self.gravity:
            new_dims[1] = abs(self.in_y - req_y)
        else:
            new_dims[1]  = abs(self.in_y - req_y)/2

        new_dims[2] = new_dims[0] + min(req_x, self.in_x)
        new_dims[3] = new_dims[1] + min(req_y, self.in_y)

        return new_dims

# HTTP Result code w/ matching string
class HttpResult(): ##########################################################
    codes = {
        200: "OK",
        204: "No Content",
        301: "Moved Permanently",
        302: "Found",
        304: "Not Modified",
        400: "Bad Request",
        401: "Unauthorized",
        403: "Forbidden",
        404: "Not Found",
        405: "Method Not Allowed",
        500: "Internal Server Error",
        501: "Not Implemented",
        502: "Bad Gateway",
        503: "Service Unavailable"
    }

    def __init__(self, http_code):
        self.http_code = http_code
        if http_code in self.codes:
            self.resultTxt = "%s %s" % (http_code, self.codes[http_code])
        else:
            self.resultTxt = str(http_code)

# Base Dirpy Error class
class DirpyError(Exception): #################################################
    def __init__(self, err_str, err_code=500):
        self.err_str = err_str
        self.err_code = err_code

    def __str__(self):
        return self.err_str

# Dirpy Fatal Error class
class DirpyFatalError(DirpyError): ###########################################
    pass

# Dirpy User Error class
class DirpyUserError(DirpyError): ############################################
    pass

# Result returned by DirpyWorker
class DirpyResult(): #########################################################

    def __init__(self, http_code, err_msg=None, dirpy_obj=None):
        self.http_code  = http_code
        self.err_msg    = err_msg
        self.dirpy_obj  = dirpy_obj

# Our HTTP Request handler class
class HttpHandler(http_server.BaseHTTPRequestHandler): #######################

    server_version = "Dirpy/" + __version__
    protocol_version = "HTTP/1.1"

    # Override log output (to stdout) and pass to our logger instance
    def log_message(self, format, *args):
        logger.debug("[%s] %s" % (
            multiprocessing.current_process().name, format % args))

    # Direct GET queries to http_worker
    def do_GET(self):
        http_worker(self)

    # Direct HEAD queries to http_worker
    def do_HEAD(self):
        http_worker(self, method="HEAD")

    # Direct POST queries to http_worker
    def do_POST(self):
        http_worker(self, method="POST")

    # Gracefully handle session failures
    def handle_one_request(self):
        try:
            http_server.BaseHTTPRequestHandler.handle_one_request(self)
        except:
            pass

    # Gracefully handle disconnects
    def finish(self,*args,**kw):
        try:
            if not self.wfile.closed:
                self.wfile.flush()
                self.wfile.close()
        except Exception:
            pass
        self.rfile.close()

# Our webserver class.  Implements timeouts
class HttpTimeoutServer(http_server.HTTPServer): ############################

    # Extend the HTTPServer constructor, so we can grab our timeout at init
    def __init__(self, server, handler, timeout=None):
        self.timeout = timeout
        http_server.HTTPServer.__init__(self, server, handler)

    # Bind our server and set our socket timeout before we accept connects
    def server_bind(self):
        try:
            http_server.HTTPServer.server_bind(self)
            self.socket.settimeout(self.timeout)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        except Exception as e:
            fatal("Failed to bind server: %s" % e)

# Store POST data in a BytesIO object instead of a temp file
class BytesIoStorage(cgi.FieldStorage):
    def make_file(self, binary=None):
        return io.BytesIO()

# Encapsulate our POST data and file
class PostData:
    def _init_(self, fp, env):
        self.form = BytesIoStorage(fq=fq, env=env)
        if not self.form['file'].filename:
            raise Excepton
        self.file_data = self.form['file']
        self.file_name = self.form['file'].filename

# The dirpy_worker wrapper function called when running in standalone mode
def http_worker(req, method="GET"): ##########################################

    # Read request URI as defined by the http_server path
    req_uri_obj = urlparse.urlparse(req.path)

    # Read post data, if need be
    if method == "POST":
        try:
            form = BytesIoStorage(
                fp=req.rfile,
                environ={'REQUEST_METHOD':'POST',
                         'CONTENT_TYPE':req.headers['Content-Type'],
                         })
            req_post_data = form['file'].file
        except Exception as e:
            return req.send_error(400, "Failed to read POST data: %s" % e)
    else:
        req_post_data = None

    # Call the dirpy worker
    result = dirpy_worker(req_uri_obj, req_post_data)

    # Throw an error if required
    if result.http_code == 204:
        return req.send_response(204)
    elif result.err_msg is not None:
        return req.send_error(result.http_code, result.err_msg)

    # Now fire off a response to our client
    req.send_response(200)
    req.send_header("Content-Type", "image/%s" % result.dirpy_obj.out_fmt)
    req.send_header("Content-Length", result.dirpy_obj.out_size)
    req.end_headers()

    # Don't send actual data if this is a HEAD request
    if method == "HEAD":
        return

    # Guard against a broken TCP connection raising an exception
    # by wrapping the output buffer read/write loop in a try block
    try:
        while True:
            buf = result.dirpy_obj.out_buf.read(4096)
            if not buf:
                break
            req.wfile.write(buf)
    except:
        pass

    return

# The dirpy_worker wrapper function called when running in uwsgi mode
def application(env, resp): ##################################################

    # Read request URI from the UWSGI environment variable
    try:
        req_uri_obj = urlparse.urlparse(env["REQUEST_URI"])
    except Exception as e:
        resp("400 Bad Request", [("Content-Type","text/html")])
        return "Failure reading request data: %s" % e

    # Handle POST data, if any
    if "REQUEST_METHOD" in env and env["REQUEST_METHOD"].upper() == "POST":
        try:
            form = BytesIoStorage(fp=env['wsgi.input'], environ=env)
            req_post_data = form['file'].file
        except Exception as e:
            resp("400 Bad Request", [("Content-Type","text/html")])
            return "Failure reading POST data: %s" % e
    else:
        req_post_data = None

    # Call the dirpy worker
    result = dirpy_worker(req_uri_obj, req_post_data)
    http_res = HttpResult(result.http_code)

    # Throw an error if required
    if result.http_code == 204:
        resp(http_res.resultTxt, [("Content-Type","text/html")])
        return ""
    elif result.err_msg is not None:
        resp(http_res.resultTxt, [("Content-Type","text/html")])
        return result.err_msg

    # Now fire off a response to our client
    resp("200 OK", [
        ("Content-Type", "image/%s" % result.dirpy_obj.out_fmt),
        ("Content-Length", str(result.dirpy_obj.out_size)) ]
    )

    if result.dirpy_obj.out_buf is not None:
        return result.dirpy_obj.out_buf.read()

    return ""

# Our dirpy function.  This is where all the heavy lifting is done
def dirpy_worker(req_uri_obj, req_post_data): ################################

    # Extract relative file path from request URI object
    file_path = req_uri_obj.path

    # Ignore favicons
    if file_path == "/favicon.ico":
        return DirpyResult(204)

    # Non-positional arguments
    args = { "load": {}, "save": {} }

    # Positional-based commands
    cmds = get_cmds(req_uri_obj, args)

    # Instatiate our dirpy image object
    dirpy_obj = DirpyImage(cfg.http_root)

    # Catch dirpy-related errors
    try:
        # Load our image
        dirpy_obj.load(args["load"], file_path, req_post_data)

        # Now run our requested commands & options against the dirpy image
        for cmd, opts in cmds:
            dirpy_obj.run(cmd, opts)

        # Now save it to an output buffer
        dirpy_obj.save(args["save"])

    except DirpyFatalError as e:
        logger.warning(str(e))
        return DirpyResult(e.err_code, "Fatal Dirpy Error")
    except DirpyUserError as e:
        logger.debug(str(e))
        return DirpyResult(e.err_code, e.err_str)
    except Exception as e:
        logger.warning(traceback.format_exc())
        return DirpyResult(503, "Uncaught Dirpy Error")

    # Return 204/No CoNTENT if the file is zero length.  This should
    # only happen using the "noshow" option for the save command
    if str(dirpy_obj.out_size) == "0":
        return DirpyResult(204)

    return DirpyResult(200, None, dirpy_obj)

# Read in the command line and file based configuration parameters
def read_config(uwsgi_cfg=None): #############################################

    # Build our config parser
    parser = argparse.ArgumentParser(
        description="DIRPY: the Dynamic Image Resizing Program, Yay!")
    parser.add_argument("-c", "--config-file",
        help="Path to the Dirpy config file")
    parser.add_argument("-d", "--debug", action="store_true",
        help="Emit debug output")
    parser.add_argument("-f", "--foreground", action="store_true",
        help="Don't daemonize; run program in the foreground")

    # Parse command line
    global cfg
    cfg = parser.parse_args()

    # Config file precedence:
    # uwsgi_cfg >> cfg.config_file >> "/etc/dirpy.conf"
    # If a user-defined config file (i.e. uwsgi_cfg or cfg.config_file) is
    # defined but not exist, we should throw a fatal error
    cfg_file = uwsgi_cfg or cfg.config_file or "/etc/dirpy.conf"
    cfg_parser = configparser.RawConfigParser()
    try:
        if cfg_parser.read(cfg_file):
            cfg.defaults = False
        else:
            cfg.defaults = True
    except Exception as e:
        fatal("Unable to load config file '%s': %s" % (cfg_file, e))

    # Read in all of our global / default options
    cfg.pid_file     = cfg_str(cfg_parser,
        "global", "pid_file", False, "/var/run/dirpy.pid")
    cfg.log_file     = cfg_str(cfg_parser,
        "global", "log_file", False, "/var/log/dirpy.log")
    cfg.log_max_line = cfg_int(cfg_parser,
        "global", "log_max_line", False, 300)
    cfg.bind_addr    = cfg_str(cfg_parser,
        "global", "bind_addr", False,  "0.0.0.0")
    cfg.bind_port    = cfg_int(cfg_parser,
        "global", "bind_port", False,  3000)
    cfg.http_root    = cfg_str(cfg_parser,
        "global", "http_root", False,  "/var/www/html")
    cfg.num_workers  = cfg_int(cfg_parser,
        "global", "num_workers", False,  multiprocessing.cpu_count()*2)
    cfg.max_pixels   = cfg_int(cfg_parser,
        "global", "max_pixels", False,  90000000)
    cfg.def_quality  = cfg_int(cfg_parser,
        "global", "def_quality", False,  95)
    cfg.min_recompress_pixels  = cfg_int(cfg_parser,
        "global", "min_recompress_pixels", False,  0)
    cfg.req_timeout  = cfg_int(cfg_parser,
        "global", "req_timeout", False, None)
    cfg.allow_post   = cfg_bool(cfg_parser,
        "global", "allow_post", False,  False)
    cfg.allow_todisk  = cfg_bool(cfg_parser,
        "global", "allow_todisk", False, False)
    cfg.allow_mkdir  = cfg_bool(cfg_parser,
        "global", "allow_mkdir", False, False)
    cfg.allow_overwrite  = cfg_bool(cfg_parser,
        "global", "allow_overwrite", False, False)
    cfg.todisk_root  = cfg_str(cfg_parser,
        "global", "todisk_root", False,  "")
    cfg.debug        = cfg_bool(cfg_parser,
        "global", "debug", False, cfg.debug)

# Extract dirpy arguments and positional commands/options from the
# parsed query string
def get_cmds(parsedPath, args): ##############################################

    # Now parse the query string and turn it into our command/option data
    # structure.  This should allow for commands and their options to be
    # passed in the format: cmd1=opt1:val1,opt2,opt3:val3&cmd2=opt4:val4
    # Note that option/value pairs are comma delimited, and the actual
    # options and values are semi-colon delimited.  Option values are
    # optional, with a True value being subsitituted if they do not exist.
    # Also, commands are not uniquely constained (i.e. they can be repeated)

    cmds = []

    for fv_pair in parsedPath.query.split("&"):
        fv_norm = urllib.unquote(fv_pair).decode("utf-8")
        oper = None
        opts = {}
        if "=" in fv_pair:
            oper, all_opts = fv_norm.split("=",1)
            for opt_str in all_opts.split(","):
                if ":" in opt_str:
                    opt_pair = opt_str.split(":",1)
                    opts[opt_pair[0]] = opt_pair[1]
                else:
                    opts[opt_str] = True
        else:
            oper, opts = fv_norm, {}

        if oper in args:
            args[oper] = opts
        else:
            cmds.append([oper, opts])

    return cmds

# Grab an string from our config
def cfg_str(cfg, section, name, required=True, default=None): ################
    try:
        return cfg.get(section, name)
    except configparser.Error:
        if not required:
            return default
        fatal("Missing required config parameter %s:%s." % (section, name))

# Grab an int from our config, complain if it isn't valid
def cfg_int(cfg, section, name, required=True, default=None): ################
    try:
        # Allow a string if they match the default value
        return cfg.getint(section, name)
    except ValueError:
        fatal("Config parameter %s:%s must be an integer." % (section, name))
    except configparser.Error:
        if not required:
            return default
        fatal("Missing required config parameter %s:%s." % (section, name))

# Grab an int from our config, complain if it isn't valid
def cfg_bool(cfg, section, name, required=True, default=False): ##############
    try:
        # Allow a string if they match the default value
        return cfg.getboolean(section, name)
    except ValueError:
        fatal("Config parameter %s:%s must be a boolean." % (section, name))
    except configparser.Error:
        if not required:
            return default
        fatal("Missing required config parameter %s:%s." % (section, name))

# Grab an network address from our config, complain if it isn't valid
def cfg_addr(cfg, section, name, required=True, default=None): ###############
    # Fetch and validate a hostname/ip address config option
    try:
        addr = cfg.get(section, name)
        socket.gethostbyname(addr)
        return addr
    except configparser.Error:
        if not required:
            return default
        fatal("Missing required config parameter %s:%s." % (section, name))
    except socket.gaierror:
        fatal("Invalid address for config parameter %s:%s" % (section, name))

# Make outgoing log messages printable and enforce a maximum line length
class DirpyLogFilter(logging.Filter): ########################################
    def __init__(self, log_max_line):
        self.log_max_line = log_max_line
    def filter(self, rec):
        rec.msg = rec.msg.encode('utf_8').decode('unicode_escape')
        if len(rec.msg) > self.log_max_line:
            rec.msg = rec.msg[:self.log_max_line-3] + "..."

        return True

# Set up our global logger
def logger_setup(): ##########################################################

    # Set our maximum severity level to log (i.e. debug or not)
    logLevel = logging.DEBUG if cfg.debug else logging.INFO
    if cfg.foreground:
        logFh = sys.stdout
    else:
        try:
            logFh = open(cfg.log_file, "a")
        except IOError as e:
            fatal("Unable to log to %s (%s)" % (cfg.log_file, e.strerror))

    logging.basicConfig(
        stream=logFh,
        level=logLevel,
        format="%(asctime)s %(levelname)s: [%(process)d] %(message)s",
        datefmt="[%Y-%m-%d@%H:%M:%S]"
    )

    global logger
    logger = logging.getLogger("dirpy")
    log_filter = DirpyLogFilter(cfg.log_max_line)
    logger.addFilter(log_filter)

    # Make the logger emit all unhandled exceptions
    # sys.excepthook = lambda t, v, x: logger.exception(str(v))

    if cfg.defaults:
        logger.info("Can't read config file %s; using default values" %
            cfg.config_file)

# Throw a fatal message and exit
def fatal(msg): ##############################################################

    try:
        logger
    # If our logger isnt defined, print directly to stdout
    except:
        ts = datetime.datetime.now().strftime("%Y-%m-%d@%H:%M:%S")
        print("[%s] CRITICAL: %s" % (ts, msg))
    # Otherwise, just use the logger
    else:
        logger.critical(msg)

    sys.exit(1)

# Launch our process as a daemon
def daemonize(): #############################################################

    UMASK = 0
    MAXFD = 1024

    # Fork once
    try:
        pid = os.fork()
    except OSError as e:
        fatal("Unable to fork: %s [%d]" % (e.strerror, e.errno))

    # In the first child process
    if (pid == 0):
        os.setsid()

        try:
            pid = os.fork()
        except OSError as e:
            fatal("Unable to fork: %s [%d]" % (e.strerror, e.errno))

        if (pid == 0):
            os.chdir("/")
            os.umask(UMASK)
        else:
            os._exit(0)
    else:
        os._exit(0)

    # Close all open file descriptors
    for fd in range(0, MAXFD):
        try:
            os.close(fd)
        except OSError:
            pass

    # DUP our stdout & stderr filehandles to dev null
    os.open(os.devnull, os.O_RDWR)
    os.dup2(0, 1)
    os.dup2(0, 2)

    return

# Spawn a worker process, along with the time that it was started
def spawn_worker(target, args): ##############################################

    # Try three times to start a worker, and then give up
    attempts = 3
    while attempts > 0:
        try:
            worker = multiprocessing.Process(target=target, args=args)
            worker.daemon = True
            worker.start()
            return [worker, time.time()]

        # Sad lack of Python documentation for multiprocessing exceptions...
        except Exception as e:
            attempts -= 1
            logger.info("Failed to spawn worker (%s); %s more attempt(s)" %
                (e, attempts))
            time.sleep(1)

    # Uh oh, can't spawn a worker.  Time to shut down
    fatal("Unable to spawn worker after %s attempts" % attempts)

# The serve_forever wrapper, called by multiprocessing.Process
def server_wrapper(server): ##################################################
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass

# Our main loop, used in standalone mode
def dirpy_main(): ############################################################

    # Read command line parameters and config file
    read_config()

    # Daemonize, unless requested otherwise
    if not cfg.foreground:
        daemonize()

    # Start our logger
    logger_setup()

    # Catch SIGINTs
    signal.signal(signal.SIGINT, lambda s, f: os._exit(1))

    # Drop our pid file if we are daemonized
    if not cfg.foreground:
        try:
            with open(cfg.pid_file, "w") as fh:
                fh.write(str(os.getpid()))
        except IOError as e:
            fatal("Unable to write to pidfile %s (%s)" % (cfg.pid_file, e))

    # Initialize our http server class
    http_server = HttpTimeoutServer(
        (cfg.bind_addr, cfg.bind_port), HttpHandler, cfg.req_timeout)

    # Start our worker pool.  We dont use multiprocessing.pool, since we want
    # to be able to watchdog our server processes
    workers = []
    for i in range(cfg.num_workers):
        workers.append(spawn_worker(server_wrapper, (http_server,)))

    # We're up and running; let the world know about it
    logger.info("Dirpy daemon started! Herp da dirp!")
    logger.info("Listing on %s:%s, using %s worker(s) " %
        (cfg.bind_addr, cfg.bind_port, cfg.num_workers))

    # Enter watchdog mode
    while True:
        time.sleep(1)

        # Check to see if any workers have died/exited unexpectedly
        for i in range(cfg.num_workers):

            # If a worker exited; clean up after it and then restart it
            if not workers[i][0].is_alive():
                logger.error("Worker %s died; restarting it." % (i+1,))
                workers[i][0].join()
                workers[i] = spawn_worker(server_wrapper, (http_server,))

    # Shouldn't ever get this far, but just in case...
    sys.exit(1)

# Handle being launched via UWSGI
def uwsgi_prep(): ###########################################################

    import uwsgi

    # Read command line args
    if "dirpy_cfg" in uwsgi.opt:
        read_config(uwsgi.opt["dirpy_cfg"])
    else:
        read_config()

    # Set up our logger
    logger_setup()


text:
div.phpdebugbar-widgets-templates div.phpdebugbar-widgets-status {
  font-family: monospace;
  padding: 6px 6px;
  border-bottom: 1px solid #ddd;
  font-weight: bold;
  color: #555;
  background: #fafafa;
}

div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-render-time,
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-memory,
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-param-count,
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-type {
  float: right;
  margin-left: 8px;
  color: #888;
}
div.phpdebugbar-widgets-templates div.phpdebugbar-widgets-status span.phpdebugbar-widgets-render-time,
div.phpdebugbar-widgets-templates div.phpdebugbar-widgets-status span.phpdebugbar-widgets-memory,
div.phpdebugbar-widgets-templates div.phpdebugbar-widgets-status span.phpdebugbar-widgets-param-count,
div.phpdebugbar-widgets-templates div.phpdebugbar-widgets-status span.phpdebugbar-widgets-type {
  color: #555;
}
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-render-time:before,
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-memory:before,
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-param-count:before,
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-type:before {
  font-family: FontAwesome;
  margin-right: 4px;
  font-size: 12px;
}
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-render-time:before {
  content: "\f017";
}
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-memory:before {
  content: "\f085";
}
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-param-count:before {
  content: "\f0ce";
}
div.phpdebugbar-widgets-templates span.phpdebugbar-widgets-type:before {
  content: "\f121";
}
div.phpdebugbar-widgets-templates table.phpdebugbar-widgets-params {
  display: none;
  width: 70%;
  margin: 10px;
  border: 1px solid #ddd;
  font-family: monospace;
  border-collapse: collapse;
}
div.phpdebugbar-widgets-templates table.phpdebugbar-widgets-params td {
  border: 1px solid #ddd;
  padding: 0 5px;
}
div.phpdebugbar-widgets-templates table.phpdebugbar-widgets-params .phpdebugbar-widgets-name {
  width: 20%;
  font-weight: bold;
}


text:
using System;

namespace Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml.Contracts
{
    internal sealed class Variable : IVariable
    {
        internal String Name { get; set; }

        internal String Value { get; set; }
    }
}


text:
package com.blazebit.persistence.impl.function.jsonget;

import com.blazebit.persistence.impl.util.JpqlFunctionUtil;
import com.blazebit.persistence.spi.FunctionRenderContext;

/**
 * @author Moritz Becker
 * @since 1.5.0
 */
public class PostgreSQLJsonGetFunction extends AbstractJsonGetFunction {

    @Override
    protected void render0(FunctionRenderContext context) {
        context.addChunk("cast(");
        context.addArgument(0);
        context.addChunk(" as json)");
        context.addChunk("#>>'{");
        addUnquotedArgument(context, 1);
        for (int i = 2; i < context.getArgumentsSize(); i++) {
            context.addChunk(",");
            addUnquotedArgument(context, i);
        }
        context.addChunk("}'");
    }

    private void addUnquotedArgument(FunctionRenderContext context, int argIndex) {
        context.addChunk(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(argIndex)));
    }
}


text:
exports.versions = {
    UNKNOWN: 'unknown'
};


text:
require 'test_helper'
require 'devise/parameter_sanitizer'

class BaseSanitizerTest < ActiveSupport::TestCase
  def sanitizer
    Devise::BaseSanitizer.new(User, :user, { user: { "email" => "jose" } })
  end

  test 'returns chosen params' do
    assert_equal({ "email" => "jose" }, sanitizer.for(:sign_in))
  end
end

if defined?(ActionController::StrongParameters)
  require 'active_model/forbidden_attributes_protection'

  class ParameterSanitizerTest < ActiveSupport::TestCase
    def sanitizer(params)
      params = ActionController::Parameters.new(params)
      Devise::ParameterSanitizer.new(User, :user, params)
    end

    test 'filters some parameters on sign in by default' do
      sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid", "remember_me" => "1" })
      assert_equal({ "email" => "jose", "password" => "invalid", "remember_me" => "1" }, sanitizer.for(:sign_in))
    end

    test 'handles auth keys as a hash' do
      swap Devise, :authentication_keys => {:email => true} do
        sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" })
        assert_equal({ "email" => "jose", "password" => "invalid" }, sanitizer.for(:sign_in))
      end
    end

    test 'filters some parameters on sign up by default' do
      sanitizer = sanitizer(user: { "email" => "jose", "role" => "invalid" })
      assert_equal({ "email" => "jose" }, sanitizer.for(:sign_up))
    end

    test 'filters some parameters on account update by default' do
      sanitizer = sanitizer(user: { "email" => "jose", "role" => "invalid" })
      assert_equal({ "email" => "jose" }, sanitizer.for(:account_update))
    end

    test 'allows custom hooks' do
      sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" })
      sanitizer.for(:sign_in) { |user| user.permit(:email, :password) }
      assert_equal({ "email" => "jose", "password" => "invalid" }, sanitizer.for(:sign_in))
    end

    test 'raises on unknown hooks' do
      sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" })
      assert_raise NotImplementedError do
        sanitizer.for(:unknown)
      end
    end
  end
end


text:
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.AppPlatform.Models;
using Azure.ResourceManager.Models;

namespace Azure.ResourceManager.AppPlatform
{
    public partial class GatewayResourceData : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Properties))
            {
                writer.WritePropertyName("properties");
                writer.WriteObjectValue(Properties);
            }
            if (Optional.IsDefined(Sku))
            {
                writer.WritePropertyName("sku");
                writer.WriteObjectValue(Sku);
            }
            writer.WriteEndObject();
        }

        internal static GatewayResourceData DeserializeGatewayResourceData(JsonElement element)
        {
            Optional<GatewayProperties> properties = default;
            Optional<AppPlatformSku> sku = default;
            ResourceIdentifier id = default;
            string name = default;
            ResourceType type = default;
            Optional<SystemData> systemData = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    properties = GatewayProperties.DeserializeGatewayProperties(property.Value);
                    continue;
                }
                if (property.NameEquals("sku"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sku = AppPlatformSku.DeserializeAppPlatformSku(property.Value);
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
                    continue;
                }
            }
            return new GatewayResourceData(id, name, type, systemData.Value, properties.Value, sku.Value);
        }
    }
}


text:
namespace triton { namespace common {

// Generic fixed-size Thread Pool to execute tasks asynchronously

class ThreadPool {
 public:
  explicit ThreadPool(std::size_t thread_count);
  ~ThreadPool();
  ThreadPool(const ThreadPool&) = delete;
  ThreadPool& operator=(const ThreadPool&) = delete;

  using Task = std::function<void(void)>;
  // Assigns "task" to the task queue for a worker thread to execute when
  // available. This will not track the return value of the task.
  void Enqueue(Task&& task);
  // Returns the number of threads in thread pool
  size_t Size() { return workers_.size(); }

 private:
  std::queue<Task> task_queue_;
  std::mutex queue_mtx_;
  std::condition_variable cv_;
  std::vector<std::thread> workers_;
  // If true, tells pool to stop accepting work and tells awake worker threads
  // to exit when no tasks are left on the queue.
  bool stop_ = false;
};

}}  // namespace triton::common


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace SaveTheDate.iOS.CustomControls
{
	[Register ("NotifyButton")]
	partial class NotifyButton
	{
		void ReleaseDesignerOutlets ()
		{
		}
	}
}