text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Text;
using System.Xml;
using System.Linq;
using Svg.ExCSS;
using Svg.Css;
using System.Threading;
using System.Globalization;
using Svg.Exceptions;
using System.Runtime.InteropServices;

namespace Svg
{
    /// <summary>
    /// The class used to create and load SVG documents.
    /// </summary>
    public class SvgDocument : SvgFragment, ITypeDescriptorContext
    {
        public static readonly int PointsPerInch = GetSystemDpi();
        private SvgElementIdManager _idManager;

        private Dictionary<string, IEnumerable<SvgFontFace>> _fontDefns = null;

        private static int GetSystemDpi()
        {
            IntPtr hDC = GetDC(IntPtr.Zero);
            const int LOGPIXELSY = 90;
            int result = GetDeviceCaps(hDC, LOGPIXELSY);
            ReleaseDC(IntPtr.Zero, hDC);
            return result;
        }

        [DllImport("gdi32.dll")]
        private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

        [DllImport("user32.dll")]
        private static extern IntPtr GetDC(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        internal Dictionary<string, IEnumerable<SvgFontFace>> FontDefns()
        {
            if (_fontDefns == null)
            {
                _fontDefns = (from f in Descendants().OfType<SvgFontFace>()
                              group f by f.FontFamily into family
                              select family).ToDictionary(f => f.Key, f => (IEnumerable<SvgFontFace>)f);
            }
            return _fontDefns;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SvgDocument"/> class.
        /// </summary>
        public SvgDocument()
        {
            Ppi = PointsPerInch;
        }

        public Uri BaseUri { get; set; }

        /// <summary>
        /// Gets an <see cref="SvgElementIdManager"/> for this document.
        /// </summary>
        protected internal virtual SvgElementIdManager IdManager
        {
            get
            {
                if (_idManager == null)
                {
                    _idManager = new SvgElementIdManager(this);
                }

                return _idManager;
            }
        }

        /// <summary>
        /// Overwrites the current IdManager with a custom implementation.
        /// Be careful with this: If elements have been inserted into the document before,
        /// you have to take care that the new IdManager also knows of them.
        /// </summary>
        /// <param name="manager"></param>
        public void OverwriteIdManager(SvgElementIdManager manager)
        {
            _idManager = manager;
        }

        /// <summary>
        /// Gets or sets the Pixels Per Inch of the rendered image.
        /// </summary>
        public int Ppi { get; set; }

        /// <summary>
        /// Gets or sets an external Cascading Style Sheet (CSS)
        /// </summary>
        public string ExternalCSSHref { get; set; }

        #region ITypeDescriptorContext Members

        IContainer ITypeDescriptorContext.Container
        {
            get { throw new NotImplementedException(); }
        }

        object ITypeDescriptorContext.Instance
        {
            get { return this; }
        }

        void ITypeDescriptorContext.OnComponentChanged()
        {
            throw new NotImplementedException();
        }

        bool ITypeDescriptorContext.OnComponentChanging()
        {
            throw new NotImplementedException();
        }

        PropertyDescriptor ITypeDescriptorContext.PropertyDescriptor
        {
            get { throw new NotImplementedException(); }
        }

        object IServiceProvider.GetService(Type serviceType)
        {
            throw new NotImplementedException();
        }

        #endregion

        /// <summary>
        /// Retrieves the <see cref="SvgElement"/> with the specified ID.
        /// </summary>
        /// <param name="id">A <see cref="string"/> containing the ID of the element to find.</param>
        /// <returns>An <see cref="SvgElement"/> of one exists with the specified ID; otherwise false.</returns>
        public virtual SvgElement GetElementById(string id)
        {
            return IdManager.GetElementById(id);
        }

        /// <summary>
        /// Retrieves the <see cref="SvgElement"/> with the specified ID.
        /// </summary>
        /// <param name="id">A <see cref="string"/> containing the ID of the element to find.</param>
        /// <returns>An <see cref="SvgElement"/> of one exists with the specified ID; otherwise false.</returns>
        public virtual TSvgElement GetElementById<TSvgElement>(string id) where TSvgElement : SvgElement
        {
            return (this.GetElementById(id) as TSvgElement);
        }

        /// <summary>
        /// Opens the document at the specified path and loads the SVG contents.
        /// </summary>
        /// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
        /// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
        /// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
        public static SvgDocument Open(string path)
        {
            return Open<SvgDocument>(path, null);
        }

        /// <summary>
        /// Opens the document at the specified path and loads the SVG contents.
        /// </summary>
        /// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
        /// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
        /// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
        public static T Open<T>(string path) where T : SvgDocument, new()
        {
            return Open<T>(path, null);
        }

        /// <summary>
        /// Opens the document at the specified path and loads the SVG contents.
        /// </summary>
        /// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
        /// <param name="entities">A dictionary of custom entity definitions to be used when resolving XML entities within the document.</param>
        /// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
        /// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
        public static T Open<T>(string path, Dictionary<string, string> entities) where T : SvgDocument, new()
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            if (!File.Exists(path))
            {
                throw new FileNotFoundException("The specified document cannot be found.", path);
            }

            using (var stream = File.OpenRead(path))
            {
                var doc = Open<T>(stream, entities);
                doc.BaseUri = new Uri(System.IO.Path.GetFullPath(path));
                return doc;
            }
        }

        /// <summary>
        /// Attempts to open an SVG document from the specified <see cref="Stream"/>.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
        public static T Open<T>(Stream stream) where T : SvgDocument, new()
        {
            return Open<T>(stream, null);
        }

        /// <summary>
        /// Attempts to create an SVG document from the specified string data.
        /// </summary>
        /// <param name="svg">The SVG data.</param>
        public static T FromSvg<T>(string svg) where T : SvgDocument, new()
        {
            if (string.IsNullOrEmpty(svg))
            {
                throw new ArgumentNullException("svg");
            }

            using (var strReader = new System.IO.StringReader(svg))
            {
                var reader = new SvgTextReader(strReader, null);
                reader.XmlResolver = new SvgDtdResolver();
                reader.WhitespaceHandling = WhitespaceHandling.None;
                return Open<T>(reader);
            }
        }

        /// <summary>
        /// Opens an SVG document from the specified <see cref="Stream"/> and adds the specified entities.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
        /// <param name="entities">Custom entity definitions.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="stream"/> parameter cannot be <c>null</c>.</exception>
        public static T Open<T>(Stream stream, Dictionary<string, string> entities) where T : SvgDocument, new()
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            // Don't close the stream via a dispose: that is the client's job.
            var reader = new SvgTextReader(stream, entities);
            reader.XmlResolver = new SvgDtdResolver();
            reader.WhitespaceHandling = WhitespaceHandling.None;
            return Open<T>(reader);
        }

        private static T Open<T>(XmlReader reader) where T : SvgDocument, new()
        {
            var elementStack = new Stack<SvgElement>();
            bool elementEmpty;
            SvgElement element = null;
            SvgElement parent;
            T svgDocument = null;
			var elementFactory = new SvgElementFactory();

            var styles = new List<ISvgNode>();

            while (reader.Read())
            {
                try
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            // Does this element have a value or children
                            // (Must do this check here before we progress to another node)
                            elementEmpty = reader.IsEmptyElement;
                            // Create element
                            if (elementStack.Count > 0)
                            {
                                element = elementFactory.CreateElement(reader, svgDocument);
                            }
                            else
                            {
                                svgDocument = elementFactory.CreateDocument<T>(reader);
                                element = svgDocument;
                            }

                            // Add to the parents children
                            if (elementStack.Count > 0)
                            {
                                parent = elementStack.Peek();
                                if (parent != null && element != null)
                                {
                                    parent.Children.Add(element);
                                    parent.Nodes.Add(element);
                                }
                            }

                            // Push element into stack
                            elementStack.Push(element);

                            // Need to process if the element is empty
                            if (elementEmpty)
                            {
                                goto case XmlNodeType.EndElement;
                            }

                            break;
                        case XmlNodeType.EndElement:

                            // Pop the element out of the stack
                            element = elementStack.Pop();

                            if (element.Nodes.OfType<SvgContentNode>().Any())
                            {
                                element.Content = (from e in element.Nodes select e.Content).Aggregate((p, c) => p + c);
                            }
                            else
                            {
                                element.Nodes.Clear(); // No sense wasting the space where it isn't needed
                            }

                            var unknown = element as SvgUnknownElement;
                            if (unknown != null && unknown.ElementName == "style")
                            {
                                styles.Add(unknown);
                            }
                            break;
                        case XmlNodeType.CDATA:
                        case XmlNodeType.Text:
                            element = elementStack.Peek();
                            element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
                            break;
                        case XmlNodeType.EntityReference:
                            reader.ResolveEntity();
                            element = elementStack.Peek();
                            element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
                            break;
                    }
                }
                catch (Exception exc)
                {
                    Trace.TraceError(exc.Message);
                }
            }

            if (styles.Any())
            {
                var cssTotal = styles.Select((s) => s.Content).Aggregate((p, c) => p + Environment.NewLine + c);
                var cssParser = new Parser();
                var sheet = cssParser.Parse(cssTotal);
                AggregateSelectorList aggList;
                IEnumerable<BaseSelector> selectors;
                IEnumerable<SvgElement> elemsToStyle;

                foreach (var rule in sheet.StyleRules)
                {
                    aggList = rule.Selector as AggregateSelectorList;
                    if (aggList != null && aggList.Delimiter == ",")
                    {
                        selectors = aggList;
                    }
                    else
                    {
                        selectors = Enumerable.Repeat(rule.Selector, 1);
                    }

                    foreach (var selector in selectors)
                    {
                        elemsToStyle = svgDocument.QuerySelectorAll(rule.Selector.ToString(), elementFactory);
                        foreach (var elem in elemsToStyle)
                        {
                            foreach (var decl in rule.Declarations)
                            {
                                elem.AddStyle(decl.Name, decl.Term.ToString(), rule.Selector.GetSpecificity());
                            }
                        }
                    }
                }
            }

            if (svgDocument != null) FlushStyles(svgDocument);
            return svgDocument;
        }

        private static void FlushStyles(SvgElement elem)
        {
            elem.FlushStyles();
            foreach (var child in elem.Children)
            {
                FlushStyles(child);
            }
        }

        /// <summary>
        /// Opens an SVG document from the specified <see cref="XmlDocument"/>.
        /// </summary>
        /// <param name="document">The <see cref="XmlDocument"/> containing the SVG document XML.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="document"/> parameter cannot be <c>null</c>.</exception>
        public static SvgDocument Open(XmlDocument document)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            var reader = new SvgNodeReader(document.DocumentElement, null);
            return Open<SvgDocument>(reader);
        }

        public static Bitmap OpenAsBitmap(string path)
        {
            return null;
        }

        public static Bitmap OpenAsBitmap(XmlDocument document)
        {
            return null;
        }

        /// <summary>
        /// Renders the <see cref="SvgDocument"/> to the specified <see cref="ISvgRenderer"/>.
        /// </summary>
        /// <param name="renderer">The <see cref="ISvgRenderer"/> to render the document with.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="renderer"/> parameter cannot be <c>null</c>.</exception>
        public void Draw(ISvgRenderer renderer)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

            renderer.SetBoundable(this);
            this.Render(renderer);
        }

        /// <summary>
        /// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
        /// </summary>
        /// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
        public void Draw(Graphics graphics)
        {
            Draw(graphics, null);
        }

        /// <summary>
        /// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
        /// </summary>
        /// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
        /// <param name="size">The <see cref="SizeF"/> to render the document. If <c>null</c> document is rendered at the default document size.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
        public void Draw(Graphics graphics, SizeF? size)
        {
            if (graphics == null)
            {
                throw new ArgumentNullException("graphics");
            }

            var renderer = SvgRenderer.FromGraphics(graphics);
            if (size.HasValue)
            {
                renderer.SetBoundable(new GenericBoundable(0, 0, size.Value.Width, size.Value.Height));
            }
            else
            {
                renderer.SetBoundable(this);
            }
            this.Render(renderer);
        }

	    /// <summary>
	    /// Renders the <see cref="SvgDocument"/> and returns the image as a <see cref="Bitmap"/>.
	    /// </summary>
	    /// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
	    public virtual Bitmap Draw()
	    {
		    //Trace.TraceInformation("Begin Render");

		    var size = GetDimensions();
		    Bitmap bitmap = null;
		    try
		    {
			    bitmap = new Bitmap((int) Math.Round(size.Width), (int) Math.Round(size.Height));
		    }
		    catch (ArgumentException e)
		    {
				//When processing too many files at one the system can run out of memory
			    throw new SvgMemoryException("Cannot process SVG file, cannot allocate the required memory", e);
		    }

	    // 	bitmap.SetResolution(300, 300);
            try
            {
                Draw(bitmap);
            }
            catch
            {
                bitmap.Dispose();
                throw;
            }

            //Trace.TraceInformation("End Render");
            return bitmap;
        }

        /// <summary>
        /// Renders the <see cref="SvgDocument"/> into a given Bitmap <see cref="Bitmap"/>.
        /// </summary>
        public virtual void Draw(Bitmap bitmap)
        {
            //Trace.TraceInformation("Begin Render");

            try
            {
				using (var renderer = SvgRenderer.FromImage(bitmap))
				{
					renderer.SetBoundable(new GenericBoundable(0, 0, bitmap.Width, bitmap.Height));

					//EO, 2014-12-05: Requested to ensure proper zooming out (reduce size). Otherwise it clip the image.
					this.Overflow = SvgOverflow.Auto;

					this.Render(renderer);
				}
            }
            catch
            {
                throw;
            }

            //Trace.TraceInformation("End Render");
        }

        /// <summary>
        /// Renders the <see cref="SvgDocument"/> in given size and returns the image as a <see cref="Bitmap"/>.
        /// If one of rasterWidth and rasterHeight is zero, the image is scaled preserving aspect ratio,
        /// otherwise the aspect ratio is ignored.
        /// </summary>
        /// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
        public virtual Bitmap Draw(int rasterWidth, int rasterHeight)
        {
            var imageSize = GetDimensions();
            var bitmapSize = imageSize;
            RasterizeDimensions(ref bitmapSize, rasterWidth, rasterHeight);

            if (bitmapSize.Width == 0 || bitmapSize.Height == 0)
                return null;

            var bitmap = new Bitmap((int)Math.Round(bitmapSize.Width), (int)Math.Round(bitmapSize.Height));
            try
            {
                var renderer = SvgRenderer.FromImage(bitmap);
                renderer.ScaleTransform(bitmapSize.Width / imageSize.Width, bitmapSize.Height / imageSize.Height);
                Draw(renderer);
            }
            catch
            {
                bitmap.Dispose();
                throw;
            }

            return bitmap;
        }

        /// <summary>
        /// If both or one of raster height and width is not given (0), calculate that missing value from original SVG size
        /// while keeping original SVG size ratio
        /// </summary>
        /// <param name="size"></param>
        /// <param name="rasterWidth"></param>
        /// <param name="rasterHeight"></param>
        public virtual void RasterizeDimensions(ref SizeF size, int rasterWidth, int rasterHeight)
        {
          if (size == null || size.Width == 0)
            return;

          // Ratio of height/width of the original SVG size, to be used for scaling transformation
          float ratio = size.Height / size.Width;

          size.Width = rasterWidth > 0 ? (float)rasterWidth : size.Width;
          size.Height = rasterHeight > 0 ? (float)rasterHeight : size.Height;

          if (rasterHeight == 0 && rasterWidth > 0)
          {
            size.Height = (int)(rasterWidth * ratio);
          }
          else if (rasterHeight > 0 && rasterWidth == 0)
          {
            size.Width = (int)(rasterHeight / ratio);
          }
        }

        public override void Write(XmlTextWriter writer)
        {
            //Save previous culture and switch to invariant for writing
            var previousCulture = Thread.CurrentThread.CurrentCulture;
            try {
                Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
                base.Write(writer);
            }
            finally
            {
                // Make sure to set back the old culture even an error occurred.
                //Switch culture back
                Thread.CurrentThread.CurrentCulture = previousCulture;
            }
        }

        public void Write(Stream stream, bool useBom = true)
        {

            var xmlWriter = new XmlTextWriter(stream, useBom ? Encoding.UTF8 : new System.Text.UTF8Encoding(false));
            xmlWriter.Formatting = Formatting.Indented;
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteDocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", null);

            if (!String.IsNullOrEmpty(this.ExternalCSSHref))
                xmlWriter.WriteProcessingInstruction("xml-stylesheet", String.Format("type=\"text/css\" href=\"{0}\"", this.ExternalCSSHref));

            this.Write(xmlWriter);

            xmlWriter.Flush();
        }

        public void Write(string path, bool useBom = true)
        {
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                this.Write(fs, useBom);
            }
        }
    }
}


text:
using json = nlohmann::json;
using namespace nlohmann::literals;

int main()
{
    // create a JSON object with different entry types
    json j =
    {
        {"integer", 1},
        {"floating", 42.23},
        {"string", "hello world"},
        {"boolean", true},
        {"object", {{"key1", 1}, {"key2", 2}}},
        {"array", {1, 2, 3}}
    };

    // access existing values
    int v_integer = j.value("/integer"_json_pointer, 0);
    double v_floating = j.value("/floating"_json_pointer, 47.11);

    // access nonexisting values and rely on default value
    std::string v_string = j.value("/nonexisting"_json_pointer, "oops");
    bool v_boolean = j.value("/nonexisting"_json_pointer, false);

    // output values
    std::cout << std::boolalpha << v_integer << " " << v_floating
              << " " << v_string << " " << v_boolean << "\n";
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Load JS and CSS for remark.js
 */
namespace MarkNotes\Plugins\Page\HTML;

defined('_MARKNOTES') or die('No direct access allowed');

class Remark extends \MarkNotes\Plugins\Page\HTML\Plugin
{
	protected static $me = __CLASS__;
	protected static $json_settings = 'plugins.page.html.remark';
	protected static $json_options = 'plugins.options.page.html.remark';

	/**
	 * Provide additionnal javascript
	 */
	public static function addJS(&$js = null) : bool
	{
		$aeFiles = \MarkNotes\Files::getInstance();
		$aeFunctions = \MarkNotes\Functions::getInstance();
		$aeSession = \MarkNotes\Session::getInstance();
		$aeSettings = \MarkNotes\Settings::getInstance();

		$url = rtrim($aeFunctions->getCurrentURL(), '/');
		$url .= '/marknotes/plugins/page/html/remark/';

		$task = $aeSession->get('task', '');

		if ($task==='task.export.remark') {
			$script = "<script ".
				"src=\"".$url."libs/remark/remark.min.js\" ".
				"defer=\"defer\"></script>\n";

			$arrOptions = self::getOptions('duration', array('minutes'=>60, 'bar_height'=>3));

			// Get settings
			$minutes = intval($arrOptions['minutes']) ?? 60;
			$barHeight = intval($arrOptions['bar_height']) ?? 3;

			// Get the note URL
			$url = rtrim($aeFunctions->getCurrentURL(), '/').'/'.rtrim($aeSettings->getFolderDocs(false), DS).'/';

			$filename = $aeSession->get('filename');
			$urlHTML = $url.str_replace(DS, '/', $aeFiles->replaceExtension($filename, 'html'));

			$script .=
				"<script>\n".
				"marknotes.note = {};\n".
				"marknotes.note.url = '".$urlHTML."';\n".
				"marknotes.slideshow = {};\n".
				"marknotes.slideshow.durationMinutes=".$minutes.";\n".
				"marknotes.slideshow.durationBarHeight=".$barHeight.";\n".
				"</script>";

		} else {
			$script = "<script src=\"".$url."button.js\" ".
				"defer=\"defer\"></script>";
		}

		$js .= $aeFunctions->addJavascriptInline($script);

		return true;
	}

	/**
	 * Provide additionnal stylesheets
	 */
	public static function addCSS(&$css = null) : bool
	{
		return true;
	}

	/**
	 * Add/modify the HTML content
	 */
	public static function doIt(&$html = null) : bool
	{
		return true;
	}
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('sponsors', '0065_auto_20211223_1309'),
    ]

    operations = [
        migrations.AlterField(
            model_name='sponsorshippackage',
            name='slug',
            field=models.SlugField(help_text='Internal identifier used to reference this package.'),
        ),
    ]


text: {% include 'articles/article_page.html' %}


text:
var mongoose = require('mongoose');
var SHA3 = require("crypto-js/sha3");
var async = require("async");
var fs=require('fs');
var sys=require('sys');

var Application = require('../models/application').Application;
var Volunteer = require('../models/volunteer').Volunteer;
var Review = require('../models/review').Review;
var Question = require('../models/question').Question;
var Achievement = require('../models/achievement').Achievement;
var credentials = require("../config.json");
var sendgrid  = require('sendgrid')('hack4impact', 'dhruvmadethis1');
var request = require('request');
var ObjectId= mongoose.Types.ObjectId;

/*--------------  Admin Functions ------------------ */

/***** Admin Pages ****/

/*
 *  Temporary: Page to submit organizations
 */
exports.submit_application = function(req, res) {
    res.render("admin_submit.ejs", {error: "lalal", name: req.session.fullname});
};

/*
 * loads admin dashboard page
 */

exports.view_applications = function(req, res) {
    res.render("main.ejs", {error: "lalal", name: req.session.fullname});
};

/*
 * renders page for single organization
 * @params organization id
 */

exports.view_one_application = function(req, res) {

    Application.findById(req.params.id, function(err, application) {
        if(err) {
            res.send(404);
        } else {
            res.render('single_org.ejs', {app_id: req.params.id, name: req.session.fullname});
        }
    });

};

/*
 * Loads admin signup page
 */

 exports.admin_signup_page = function(req, res) {
    var error = '';

    if (req.session.email_duplicate) {
        error = 'This email has already been registered.';
        req.session.email_duplicate = null;
    }

    res.render("admin_signup.ejs", {error: error, name: req.session.fullname});
};

/**** Admin Helper Methods ****/

/*
 * loads the applications that have been shortlisted
 * @return list of application objects
 */

exports.send_applications_short= function(req, res) {
    Application.find( {"shortlisted": true}, {"_id": 1, "organization_name": 1, "reviews_in_progress": 1,
        "score_sum": 1, "reviews_submitted": 1, "kiva_fit_count":1, "sustainable_model_count": 1,
        "clear_social_impact_count": 1, "num_reviews": 1, "open_to_review": 1},
        function(err, applications) {
            console.log(applications);
            res.send(applications);
        });
};

/*
 * loads the applications that have been not yet been shortlisted
 * @return list of application objects
 */

exports.send_applications_rest= function(req, res) {
    Application.find( {"shortlisted": false}, {"_id": 1, "organization_name": 1, "reviews_in_progress": 1,
        "score_sum": 1, "reviews_submitted": 1, "kiva_fit_count":1, "sustainable_model_count": 1,
        "clear_social_impact_count": 1, "num_reviews": 1, "open_to_review": 1},
        function(err, applications) {
        console.log(applications);
        res.send(applications);
    });
};

/*
 * loads approved/unapproved volunteers
 * @params approval value (0 or 1)
 * @return list of volunteer objects
 */

exports.send_volunteers= function(req, res) {
    var approval = req.params.approval;
    Volunteer.find( {approved: approval},
        function(err, volunteers) {
        res.send(volunteers);
    });

};

/*
 * loads single organization/application
 * @params organization id
 * @return application object
 */

exports.load_single_application = function(req, res) {
    Application.findById(req.params.id, function(err, application) {
        if(err) {
            console.log(err);
            res.send(404);
        } else {
            res.send(application);
        }
    });
};

/*
 * When application is shortlisted, update achievements associated with reviews
 * @params organization id
 */

exports.save_application_changes = function(req, res) {
    Application.findById(req.params.id, function(err, application) {
        if(!application.shortlisted && req.body.shortlisted){
            for (var i = 0; i < application.volunteer_list.length; i++) {
                var achievement = create_achievement(4, application.volunteer_list[i], application.organization_name);
                achievement.save(function(err, achiev) {
                    if (err) {console.log(err)};
                    console.log("achievement saved ");
                });
            };
            for (var i = 0; i < application.reviews_submitted.length; i++) {
                Review.findById(application.reviews_submitted[i], function(err, review) {
                    if (review.recommend_rating > 3){
                        var achievement = create_achievement(5, review.reviewer_id, application.organization_name);
                        achievement.save(function(err, achiev) {
                            if (err) {console.log(err)};
                            console.log("achievement saved ");
                            Volunteer.update({"_id": review.reviewer_id},
                            {$inc: {num_points: achievement.points}}, function(err) {
                                if (err) {return callback(err)};
                                console.log("points updated");
                            })
                        });
                    }
                })
            };
        }
        application.organization_name = req.body.organization_name;
        application.description = req.body.description;
        application.token = req.body.token;
        application.organization_address = req.body.organization_address;
        application.organization_url = req.body.organization_url;
        application.open_to_review = req.body.open_to_review;
        application.shortlisted = req.body.shortlisted;
        application.save();
        if(err) {
            console.log(err);
            res.send(404);
        } else {
            console.log("submission complete");
            res.redirect('/admin_applications');
        }
    });
};

/*
 * Creates application/organization
 * @params form data
 */

exports.create_application = function(req, res) {
    console.log("does this work");
    var application = new Application({
        organization_name: req.body.organization_name,
        description: req.body.description,
        token: req.body.token,
        url: req.body.url,
        organization_address: req.body.organization_address,
        organization_url: req.body.organization_url,
        volunteer_list: []
    });

    application.save(function(err, application) {
        console.log(application);
        if(err) {console.log(err);}
        else {
            res.redirect('/admin_applications');
        }
    });
};

/*
 * Updates volunteer to approved
 * @params volunteer id
 */

exports.approve_volunteer = function(req, res) {
    Volunteer.findOneAndUpdate({"_id": new ObjectId(req.body.id)},
        {approved: 1}, function(err, data) {
        if(!err) {
            var email = new sendgrid.Email({
                    to: data.email_address,
                    from: 'kiva@kiva.com',
                    bcc: 'dhwari@gmail.com',
                    subject:'Volunteer Approved!',
                });
            email.setHtml('
Dear'  + data.first_name + '
 Thanks for signing up to be a volunteer! '+
                        'Feel free to visit the app and login to get started. The first two things to do are to' +
                        'go through the tutorials and fill out the confidentiality form.' +
                        '
 Thanks,
 Folks at Kiva
');
            sendgrid.send(email, function(err, json) {
                if (err) { return res.send(err); }
                console.log(json);
                console.log('done with the request!');
                res.send(200);
            });
        } else {
            console.log("error found: " + err);
            res.send(err);
        }
        });
};

/*
 * Denies volunteer
 * @params volunteer id
 */

exports.deny_volunteer = function(req, res) {
    Volunteer.findOneAndUpdate({"_id": new ObjectId(req.body.id)},
        {approved: null}, function(err, data) {
        if(!err) {
            console.log(data);
            // Send a rejection email?
            console.log('done with the deny request!');
            res.send(200);
        } else {
            res.send(err);
        };
    });
};

/*
 * Allows volunteer to sign up
 * @params form data
 */

 exports.create_admin = function(req, res) {
    var email = req.body.email_address;

    Volunteer.findOne({'email_address': email},
        function(err, volunteer) {
            if(volunteer != null) {
                //this is a duplicate entry
                console.log('duplicate');
                req.session.email_duplicate = true;
                res.redirect('/admin/sign-up');
            } else {
    var admin = new Volunteer({
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        email_address: req.body.email_address,
        password: SHA3(req.body.password).toString(),
        is_admin: true
        //add support for confirm password
    });
    /*if (password.value != password2.value) {
        console.log('Passwords do not match.');
        res.render('/');
    } else {*/
        admin.save(function(err, admin) {
            console.log(admin);
            if(err) {console.log(err);}
            else {
                req.session.admin = admin.is_admin;
                req.session.logged = true;
                console.log("Volunteer_id to string: " + (admin._id).toString());
                req.session.volunteerId = ObjectId(admin._id.toString());
                req.session.email = admin.email_address;
                res.redirect('/admin_applications');
            }
        });
        }
    });
    //}
};


text:
type SortedDict{K, D, Ord <: Ordering} <: Associative{K,D}
    bt::BalancedTree23{K,D,Ord}

## Zero-argument constructor, or possibly one argument to specify order.

    function SortedDict(o::Ord=Forward)
        bt1 = BalancedTree23{K,D,Ord}(o)
        new(bt1)
    end

end

## external constructor to take an associative and infer
## argument types

function SortedDict{K, D, Ord <: Ordering}(d::Associative{K,D}, o::Ord=Forward)
    h = SortedDict{K,D,Ord}(o)
    for (k,v) in d
        h[k] = v
    end
    h
end

if VERSION >= v"0.4.0-dev"

    ## More constructors based on those in dict.jl:
    ## Take pairs and infer argument
    ## types.  Note:  this works only for the Forward ordering.

    function SortedDict{K,D}(ps::Pair{K,D}...)
        h = SortedDict{K,D,ForwardOrdering}()
        for p in ps
            h[p.first] = p.second
        end
        h
    end

    ## Take pairs and infer argument
    ## types.  Ordering parameter must be explicit first argument.

    function SortedDict{K,D, Ord <: Ordering}(o::Ord, ps::Pair{K,D}...)
        h = SortedDict{K,D,Ord}(o)
        for p in ps
            h[p.first] = p.second
        end
        h
    end

    ## This one takes an iterable; ordering type is optional.

    SortedDict{Ord <: Ordering}(kv, o::Ord=Forward) =
    sorteddict_with_eltype(kv, eltype(kv), o)

    function sorteddict_with_eltype{K,D,Ord}(kv, ::Type{Tuple{K,D}}, o::Ord)
        h = SortedDict{K,D,Ord}(o)
        for (k,v) in kv
            h[k] = v
        end
        h
    end

else   #if VERSION < v"0.4.0-dev"
    function SortedDict{K,D,Ord <: Ordering}(ks::AbstractArray{K},
                                             vs::AbstractArray{D},
                                             o::Ord = Forward)
        h = SortedDict{K,D,Ord}(o)
        l = length(ks)
        if length(vs) != l
            error("ks and vs arrays in two-array SortedDict constructor must have the same length")
        end
        for i = 1 : l
            h[ks[i]] = vs[i]
        end
        h
    end

    function SortedDict{K,D,Ord <: Ordering}(kv::AbstractArray{(K,D),1},
                                             o::Ord = Forward)
        h = SortedDict{K,D,Ord}(o)
        for pr in kv
            h[pr[1]] = pr[2]
        end
        h
    end
end

typealias SDSemiToken IntSemiToken

typealias SDToken @compat Tuple{SortedDict,IntSemiToken}

## This function implements m[k]; it returns the
## data item associated with key k.

@inline function getindex(m::SortedDict, k_)
    i, exactfound = findkey(m.bt, convert(keytype(m),k_))
    !exactfound && throw(KeyError(k_))
    return m.bt.data[i].d
end

## This function implements m[k]=d; it sets the
## data item associated with key k equal to d.

@inline function setindex!{K, D, Ord <: Ordering}(m::SortedDict{K,D,Ord}, d_, k_)
    insert!(m.bt, convert(K,k_), convert(D,d_), false)
    m
end

## This function looks up a key in the tree;
## if not found, then it returns a marker for the
## end of the tree.

@inline function find(m::SortedDict, k_)
    ll, exactfound = findkey(m.bt, convert(keytype(m),k_))
    IntSemiToken(exactfound? ll : 2)
end

## This function inserts an item into the tree.
## Unlike m[k]=d, it also returns a bool and a token.
## The bool is true if the inserted item is new.
## It is false if there was already an item
## with that key.
## The token points to the newly inserted item.

@inline function insert!{K,D, Ord <: Ordering}(m::SortedDict{K,D,Ord}, k_, d_)
    b, i = insert!(m.bt, convert(K,k_), convert(D,d_), false)
    b, IntSemiToken(i)
end

## First and last return the first and last (key,data) pairs
## in the SortedDict.  It is an error to invoke them on an
## empty SortedDict.

@inline function first(m::SortedDict)
    i = beginloc(m.bt)
    i == 2 && throw(BoundsError())
    return m.bt.data[i].k, m.bt.data[i].d
end

@inline function last(m::SortedDict)
    i = endloc(m.bt)
    i == 1 && throw(BoundsError())
    return m.bt.data[i].k, m.bt.data[i].d
end

@inline function in{K,D,Ord <: Ordering}(pr::(@compat Tuple{Any,Any}), m::SortedDict{K,D,Ord})
    i, exactfound = findkey(m.bt,convert(K,pr[1]))
    return exactfound && isequal(m.bt.data[i].d,convert(D,pr[2]))
end

@inline eltype{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord}) = @compat Tuple{K,D}
@inline eltype{K,D,Ord <: Ordering}(::Type{SortedDict{K,D,Ord}}) = @compat Tuple{K,D}
@inline orderobject(m::SortedDict) = m.bt.ord
@inline keytype{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord}) = K
@inline datatype{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord}) = D

@inline function haskey(m::SortedDict, k_)
    i, exactfound = findkey(m.bt,convert(keytype(m),k_))
    exactfound
end

@inline function get{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord}, k_, default_)
    i, exactfound = findkey(m.bt, convert(K,k_))
   return exactfound? m.bt.data[i].d : convert(D,default_)
end

function get!{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord}, k_, default_)
    k = convert(K,k_)
    i, exactfound = findkey(m.bt, k)
    if exactfound
        return m.bt.data[i].d
    else
        default = convert(D,default_)
        insert!(m.bt,k, default, false)
        return default
    end
end

function getkey{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord}, k_, default_)
    i, exactfound = findkey(m.bt, convert(K,k_))
    exactfound? m.bt.data[i].k : convert(K, default_)
end

## Function delete! deletes an item at a given
## key

@inline function delete!(m::SortedDict, k_)
    i, exactfound = findkey(m.bt,convert(keytype(m),k_))
    !exactfound && throw(KeyError(k_))
    delete!(m.bt, i)
    m
end

@inline function pop!(m::SortedDict, k_)
    i, exactfound = findkey(m.bt,convert(keytype(m),k_))
    !exactfound && throw(KeyError(k_))
    d = m.bt.data[i].d
    delete!(m.bt, i)
    d
end

## Check if two SortedDicts are equal in the sense of containing
## the same (K,D) pairs.  This sense of equality does not mean
## that semitokens valid for one are also valid for the other.

function isequal(m1::SortedDict, m2::SortedDict)
    ord = orderobject(m1)
    if !isequal(ord, orderobject(m2)) || !isequal(eltype(m1), eltype(m2))
        error("Cannot use isequal for two SortedDicts unless their element types and ordering objects are equal")
    end
    p1 = startof(m1)
    p2 = startof(m2)
    while true
        if p1 == pastendsemitoken(m1)
            return p2 == pastendsemitoken(m2)
        end
        if p2 == pastendsemitoken(m2)
            return false
        end
        k1,d1 = deref((m1,p1))
        k2,d2 = deref((m2,p2))
        if !eq(ord,k1,k2) || !isequal(d1,d2)
            return false
        end
        p1 = advance((m1,p1))
        p2 = advance((m2,p2))
    end
end

function mergetwo!{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord},
                                        m2::Associative{K,D})
    for (k,v) in m2
        m[convert(K,k)] = convert(D,v)
    end
end

function packcopy{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord})
    w = SortedDict(Dict{K,D}(),orderobject(m))
    mergetwo!(w,m)
    w
end

function packdeepcopy{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord})
    w = SortedDict(Dict{K,D}(),orderobject(m))
    for (k,v) in m
        newk = deepcopy(k)
        newv = deepcopy(v)
        w[newk] = newv
    end
    w
end

function merge!{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord},
                                     others::Associative{K,D}...)
    for o in others
        mergetwo!(m,o)
    end
end

function merge{K,D,Ord <: Ordering}(m::SortedDict{K,D,Ord},
                                    others::Associative{K,D}...)
    result = packcopy(m)
    merge!(result, others...)
    result
end

similar{K,D,Ord<:Ordering}(m::SortedDict{K,D,Ord}) =
SortedDict{K,D,Ord}(orderobject(m))


text:
#ifndef _ARM_TYPES_H
#define _ARM_TYPES_H

typedef unsigned long long uint64;
typedef long long           int64;
typedef unsigned int       uint32;
typedef int                 int32;
typedef unsigned short     uint16;
typedef short               int16;
typedef unsigned char      uint8;
typedef char                int8;

#endif


text:
<?php

namespace HogLog;

/**
 * Class HogLogPlanB
 * Browse directories and files via API
 * Used when your Laravel/Lumen installation does not boot
 * HogLog\PlanB::getInstance()->view(string $jailDir[, array $whitelist])
 * HogLog\PlanB::getInstance()->view('../', ['.log', '.txt']);
 */
class PlanB
{
    /**
     * @var PlanB The reference to *HogLog\PlanB* instance of this class
     */
    private static $instance;

    /**
     * @var string Directory path browsing is limited to
     */
    private static $jailDir;

    /**
     * @var array List of allowed filenames
     */
    private static $whitelist = null;

    /**
     * @var array current url
     */
    private static $urlInfo;

    /**
     * @var array Reference to either $_GET or $_POST
     */
    private static $requestMethod;

    /**
     * Returns the instance of this class.
     * @return PlanB singleton instance.
     */
    public static function getInstance()
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    /**
     * @param string $jailDir
     * @param array  $whitelist
     */
    public static function view($jailDir = './', $whitelist = [])
    {
        self::$jailDir   = $jailDir;
        self::$whitelist = $whitelist;

        try {
            self::setupRequestMethod();
            self::$urlInfo = self::parseUrl();
            echo self::output();
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * @return string Prepared HTML output
     * @throws \Exception
     */
    protected static function output()
    {
        $browse = self::$urlInfo['browse'];
        $html   = self::readOrWheep(__DIR__ . '/' . $browse);
        return $html;
    }

    /**
     * Compare users selected path with jaildir path
     * @param string $path
     * @return bool
     */
    protected static function isInsideJailDir($path)
    {
        $jailDir = __DIR__ . '/' . self::$jailDir;
        return strpos(realpath($path), realpath($jailDir)) !== false;
    }

    /**
     * Compare users selected filename against whitelist
     * @param string $file filename + extension
     * @return bool
     */
    protected static function isWhitelisted($file)
    {
        if (!is_array(self::$whitelist) || count(self::$whitelist) === 0) {
            return true;
        }
        foreach (self::$whitelist as $fileName) {
            if (strpos($file, $fileName)) {
                return true;
            }
        }
        return false;
    }

    protected static function readOrWheep($path)
    {
        if (!self::isInsideJailDir($path)) {
            throw new \Exception("Restricted directory $path");
        }

        if (!file_exists($path)) {
            throw new \Exception("Directory/file does not exist $path");
        }

        if (is_file($path)) {
            if (!self::isWhitelisted($path)) {
                throw new \Exception("File is blacklisted $path");
            }
            $contents = self::readFile($path);
        } elseif (is_dir($path)) {
            $contents = self::readDir($path, "Directory $path contents:
");
        } else {
            $contents = 'Directory/file not recognised';
        }

        return $contents;
    }

    /**
     * @param string $path
     * @param string $html
     * @return string
     * @throws Exception
     */
    protected static function readFile($path, $html = '')
    {
        $handle = fopen($path, "r");
        if ($handle) {
            while (($line = fgets($handle)) !== false) {
                $html .= '
' . $line . '
';
            }
            fclose($handle);
        } else {
            throw new \Exception("Error reading file $path");
        }

        return $html;
    }

    /**
     * @param        $path
     * @param string $html
     * @return string
     */
    protected static function readDir($path, $html = '')
    {
        $html .= '
' . implode('

', scandir($path)) . '
';
        return $html;
    }

    /**
     * Pare URL into array
     * @param $url string URL to parse, protocol is optional
     * @return array $url
     *             ["host" => "www.example.com",
     *             "path" => "/path",
     *             "query" => "name=value",
     *             "browse" => "../app/storage/logs/"]
     */
    protected static function parseUrl($url)
    {
        $url           = isset($url) ? $url : "//$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url           = parse_url($url);
        $url['browse'] = './';
        if (array_key_exists('browse', self::$requestMethod)
            && !empty(self::$requestMethod['browse'])
        ) {
            $url['browse'] = self::$requestMethod['browse'];
        }
        return $url;
    }

    /**
     * Sets up request method as reference to ether $_GET or $_POST
     * @return array
     */
    protected static function setupRequestMethod()
    {
        switch ($_SERVER['REQUEST_METHOD']) {
            case 'GET':
                self::$requestMethod = &$_GET;
                break;
            case 'POST':
                self::$requestMethod = &$_POST;
                break;
            default:
        }
        return self::$requestMethod;
    }

    /**
     * Protected constructor to prevent creating a new instance of the
     * *HogLogPlanB* via the `new` operator from outside of this class.
     */
    protected function __construct()
    {
    }

    /**
     * Private clone method to prevent cloning of the instance of the
     * *HogLogPlanB* instance.
     * @return void
     */
    private function __clone()
    {
    }

    /**
     * Private unserialise method to prevent unserialising of the HogLogPlanB
     * instance.
     * @return void
     */
    private function __wakeup()
    {
    }
}


text:
=========
PBWrapper
=========

:Subtitle: A wrapper for pacman and PKGBUILDer.
:Author: Chris Warrick <chris@chriswarrick.com>
:Copyright: © 2011-2015, Chris Warrick.
:License: BSD (see /LICENSE or Appendix B.)
:Date: 2015-08-08
:Version: 4.2.0
:Wrapper Version: 0.5.0
:Manual section: 8
:Manual group: PKGBUILDer manual

SYNOPSIS
========

*pb* <operation> [options] [targets]

DESCRIPTION
===========

*PBWrapper* (also known as just *pb*) is a wrapper for pacman and
PKGBUILDer, i.e. an application which handles checking if a package is
in the official repos or in the AUR and installs them according to that
information.

It is a part of PKGBUILDer and is included since version 2.1.4.0 of
PKGBUILDer.

Notice: Running PKGBUILDer and/or PBWrapper as root can deal catastrophic
damage to your system.  Run it as a regular user, you will be prompted for
the root password when one will be required (i.e. to run **pacman**).

OPERATIONS AND OPTIONS
======================

All operations and options from pacman and PKGBUILDer work.  Operations
other than **-S, --sync** are passed as-is to pacman.  The **-S,
--sync** switch activates a check for other parameters.  If one of
**-syu** (**--search --refresh --sysupgrade**) is present, the requests
are passed to pacman and PKGBUILDer, in that order, with arguments that
apply to the manager and nothing else.  If any other operations are
present (including **-i, --info**), the **targets** provided are checked
for presence in the AUR.  If a package is in the AUR, it is addded to
the queue that will be passed to PKGBUILDer, otherwise it is added to a
pacman queue.  Please note that brand new options will not work until
the next PKGBUILDer/PBWrapper release.

The **--debug** option enables additional debug information from
PBWrapper.

An additional option is **--unlock**, which unlocks the pacman database.

EXAMPLES
========

pb -S python hello
    Installs the Python interpreter from the repos (which is already on
    your system, especially if you have installed PKGBUILDer/PBWrapper)
    and GNU Hello from the AUR.  Note that, if you used ``pkgbuilder`` instead
    of ``pb``, the Python package would be fetched from the ABS (instead of the
    repositories) and built locally.

pb -Si python hello
    Shows information for the python and hello packages.

pb -Syu
    Checks for repo and AUR updates (in that order) and offers
    installing them.

SEE ALSO
========
**pacman(8)**, **pkgbuilder(8)**, **makepkg(8)**, **PKGBUILD(5)**

You can visit the git repo at <https://github.com/Kwpolska/pkgbuilder>
or the documentation at <https://pkgbuilder.readthedocs.org>
for more info.

BUGS
====
Bugs should be reported at the GitHub page (<https://github.com/Kwpolska/pkgbuilder/issues>).
You can also send mail to <chris@chriswarrick.com>.