text:
var React = require('react');
var CSSCore = require('react/lib/CSSCore');
var Router = require('react-router');
var { Seq } = require('../../../../');
var TypeKind = require('../../../lib/TypeKind');
var defs = require('../../../lib/getTypeDefs');

var InterfaceDef = React.createClass({
  render() {
    var name = this.props.name;
    var def = this.props.def;
    return (

        type
        {name}
        {def.typeParams && [
          '<',
          Seq(def.typeParams)
            .map((t, k) => (

                {t}

            ))
            .interpose(', ')
            .toArray(),
          '>',
        ]}
        {def.extends && [
           extends ,
          Seq(def.extends)
            .map((e, i) => <TypeDef key={i} type={e} />)
            .interpose(', ')
            .toArray(),
        ]}
        {def.implements && [
           implements ,
          Seq(def.implements)
            .map((e, i) => <TypeDef key={i} type={e} />)
            .interpose(', ')
            .toArray(),
        ]}

    );
  },
});

exports.InterfaceDef = InterfaceDef;

var CallSigDef = React.createClass({
  render() {
    var info = this.props.info;
    var module = this.props.module;
    var name = this.props.name;
    var callSig = this.props.callSig || {};

    var shouldWrap = callSigLength(info, module, name, callSig) > 80;

    return (

        {module && [{module}, '.']}
        {name}
        {callSig.typeParams && [
          '<',
          Seq(callSig.typeParams)
            .map(t => {t})
            .interpose(', ')
            .toArray(),
          '>',
        ]}
        {'('}
        {callSig && functionParams(info, callSig.params, shouldWrap)}
        {')'}
        {callSig.type && [': ', <TypeDef info={info} type={callSig.type} />]}

    );
  },
});

exports.CallSigDef = CallSigDef;

var TypeDef = React.createClass({
  render() {
    var info = this.props.info;
    var type = this.props.type;
    var prefix = this.props.prefix;
    switch (type.k) {
      case TypeKind.Never:
        return this.wrap('primitive', 'never');
      case TypeKind.Any:
        return this.wrap('primitive', 'any');
      case TypeKind.This:
        return this.wrap('primitive', 'this');
      case TypeKind.Undefined:
        return this.wrap('primitive', 'undefined');
      case TypeKind.Boolean:
        return this.wrap('primitive', 'boolean');
      case TypeKind.Number:
        return this.wrap('primitive', 'number');
      case TypeKind.String:
        return this.wrap('primitive', 'string');
      case TypeKind.Union:
        return this.wrap('union', [
          Seq(type.types)
            .map(t => <TypeDef info={info} type={t} />)
            .interpose(' | ')
            .toArray(),
        ]);
      case TypeKind.Intersection:
        return this.wrap('intersection', [
          Seq(type.types)
            .map(t => <TypeDef info={info} type={t} />)
            .interpose(' & ')
            .toArray(),
        ]);
      case TypeKind.Tuple:
        return this.wrap('tuple', [
          '[',
          Seq(type.types)
            .map(t => <TypeDef info={info} type={t} />)
            .interpose(', ')
            .toArray(),
          ']',
        ]);
      case TypeKind.Object:
        return this.wrap('object', [
          '{',
          Seq(type.members)
            .map(t => <MemberDef member={t} />)
            .interpose(', ')
            .toArray(),
          '}',
        ]);
      case TypeKind.Indexed:
        return this.wrap('indexed', [
          <TypeDef info={info} type={type.type} />,
          '[',
          <TypeDef info={info} type={type.index} />,
          ']',
        ]);
      case TypeKind.Operator:
        return this.wrap('operator', [
          this.wrap('primitive', type.operator),
          ' ',
          <TypeDef info={info} type={type.type} />,
        ]);
      case TypeKind.Array:
        return this.wrap('array', [
          <TypeDef info={info} type={type.type} />,
          '[]',
        ]);
      case TypeKind.Function:
        var shouldWrap = (prefix || 0) + funcLength(info, type) > 78;
        return this.wrap('function', [
          type.typeParams && [
            '<',
            Seq(type.typeParams)
              .map((t, k) => (

                  {t}

              ))
              .interpose(', ')
              .toArray(),
            '>',
          ],
          '(',
          functionParams(info, type.params, shouldWrap),
          ') => ',
          <TypeDef info={info} type={type.type} />,
        ]);
      case TypeKind.Param:
        return info && info.propMap[info.defining + '<' + type.param] ? (
          <TypeDef type={info.propMap[info.defining + '<' + type.param]} />
        ) : (
          this.wrap('typeParam', type.param)
        );
      case TypeKind.Type:
        var qualifiedType = (type.qualifier || []).concat([type.name]);
        var qualifiedTypeName = qualifiedType.join('.');
        var def = qualifiedTypeName
          .split('.')
          .reduce(
            (def, name) => def && def.module && def.module[name],
            defs.Immutable
          );
        var typeNameElement = [
          type.qualifier && [
            Seq(type.qualifier)
              .map(q => {q})
              .interpose('.')
              .toArray(),
            '.',
          ],
          {type.name},
        ];
        if (def) {
          typeNameElement = (
            <Router.Link to={'/' + qualifiedTypeName}>
              {typeNameElement}
            </Router.Link>
          );
        }
        return this.wrap('type', [
          typeNameElement,
          type.args && [
            '<',
            Seq(type.args)
              .map(a => <TypeDef info={info} type={a} />)
              .interpose(', ')
              .toArray(),
            '>',
          ],
        ]);
    }
    throw new Error('Unknown kind ' + type.k);
  },

  mouseOver(event) {
    CSSCore.addClass(this.getDOMNode(), 'over');
    event.stopPropagation();
  },

  mouseOut() {
    CSSCore.removeClass(this.getDOMNode(), 'over');
  },

  wrap(className, child) {
    return (

        {child}

    );
  },
});

exports.TypeDef = TypeDef;

var MemberDef = React.createClass({
  render() {
    var module = this.props.module;
    var member = this.props.member;
    return (

        {module && [{module}, '.']}
        {member.index ? (
          ['[', functionParams(null, member.params), ']']
        ) : (
          {member.name}
        )}
        {member.type && [': ', <TypeDef type={member.type} />]}

    );
  },
});

exports.MemberDef = MemberDef;

function functionParams(info, params, shouldWrap) {
  var elements = Seq(params)
    .map(t => [
      t.varArgs ? '...' : null,
      {t.name},
      t.optional ? '?: ' : ': ',
      <TypeDef
        prefix={t.name.length + (t.varArgs ? 3 : 0) + (t.optional ? 3 : 2)}
        info={info}
        type={t.type}
      />,
    ])
    .interpose(shouldWrap ? [',',
] : ', ')
    .toArray();
  return shouldWrap ? (

{elements}

  ) : (
    elements
  );
}

function callSigLength(info, module, name, sig) {
  return (module ? module.length + 1 : 0) + name.length + funcLength(info, sig);
}

function funcLength(info, sig) {
  return (
    (sig.typeParams ? 2 + sig.typeParams.join(', ').length : 0) +
    2 +
    (sig.params ? paramLength(info, sig.params) : 0) +
    (sig.type ? 2 + typeLength(info, sig.type) : 0)
  );
}

function paramLength(info, params) {
  return params.reduce(
    (s, p) =>
      s +
      (p.varArgs ? 3 : 0) +
      p.name.length +
      (p.optional ? 3 : 2) +
      typeLength(info, p.type),
    (params.length - 1) * 2
  );
}

function memberLength(info, members) {
  return members.reduce(
    (s, m) =>
      s +
      (m.index ? paramLength(info, m.params) + 4 : m.name + 2) +
      typeLength(info, m.type),
    (members.length - 1) * 2
  );
}

function typeLength(info, type) {
  if (!type) {
    throw new Error('Expected type');
  }
  switch (type.k) {
    case TypeKind.Never:
      return 5;
    case TypeKind.Any:
      return 3;
    case TypeKind.This:
      return 4;
    case TypeKind.Undefined:
      return 9;
    case TypeKind.Boolean:
      return 7;
    case TypeKind.Number:
      return 6;
    case TypeKind.String:
      return 6;
    case TypeKind.Union:
    case TypeKind.Intersection:
      return (
        type.types.reduce((s, t) => s + typeLength(info, t), 0) +
        (type.types.length - 1) * 3
      );
    case TypeKind.Tuple:
      return (
        2 +
        type.types.reduce((s, t) => s + typeLength(info, t), 0) +
        (type.types.length - 1) * 2
      );
    case TypeKind.Object:
      return 2 + memberLength(info, type.members);
    case TypeKind.Indexed:
      return 2 + typeLength(info, type.type) + typeLength(info, type.index);
    case TypeKind.Operator:
      return 1 + type.operator.length + typeLength(info, type.type);
    case TypeKind.Array:
      return typeLength(info, type.type) + 2;
    case TypeKind.Function:
      return 2 + funcLength(info, type);
    case TypeKind.Param:
      return info && info.propMap[info.defining + '<' + type.param]
        ? typeLength(null, info.propMap[info.defining + '<' + type.param])
        : type.param.length;
    case TypeKind.Type:
      return (
        (type.qualifier ? 1 + type.qualifier.join('.').length : 0) +
        type.name.length +
        (!type.args
          ? 0
          : type.args.reduce(
              (s, a) => s + typeLength(info, a),
              type.args.length * 2
            ))
      );
  }
  throw new Error('Type with unknown kind ' + JSON.stringify(type));
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Receiving
 *
 * @author Francis Quintal
 */
class Receiving extends Application {

    public function index() {
        $this->data['header'] = 'header';
        $this->data['pagebody'] = 'receiving/index';

        $this->load->model('supplies');
        $ingredients = $this->supplies->all();

        $supplyList = array();
        foreach($ingredients as $ingredient){
            $supplyList[] = array(
                'id' => $ingredient['id'],
                'name' => $ingredient['name'],
                'perBox' => $ingredient['perBox'],
                'onHand' => $ingredient['onHand'],
                'price' => "$".number_format($ingredient['price'], 2));
        }

        $this->data['supplies'] = $supplyList;
        $this->render();
    }

    public function order() {
        $this->data['header'] = 'header';
        $this->data['pagebody'] = 'welcome_message';

        $this->render();
    }

    public function show($id = 0) {
        $this->load->model('supplies');
        $ingredient = $this->supplies->get($id);

        if (is_null($ingredient))
            show_404();

        $this->data['header'] = 'header';
        $this->data['pagebody'] = 'receiving/show';

        $this->data['id'] = $ingredient['id'];
        $this->data['name'] = $ingredient['name'];
        $this->data['price'] = "$".number_format($ingredient['price'], 2);
        $this->data['type'] = $ingredient['type'];
        $this->data['perBox'] = $ingredient['perBox'];
        $this->data['onHand'] = $ingredient['onHand'];
        $this->data['backUrl'] = base_url() . "receiving";

        $this->render();
    }
    public function receipt()
    {
        $this->load->model('supplies');

        $totalOrderCost = 0;
        $message = "";

        // ... (NULL, TRUE) returns all POST items with XSS filter
        foreach ($this->input->post(NULL, TRUE) as $id => $quantity) {

            if ($quantity == 0)
                continue;

            $supplies = $this->supplies->get($id);

            $supplyName = $supplies['name'];
            $cost = $quantity * $supplies['price'];
            $totalOrderCost = $totalOrderCost + $cost;

            $formattedCost = moneyFormat($cost);
            $message = $message . "Ordered and received $quantity boxes of $supplyName(s) for $formattedCost <br>";
        }

        $this->data['header'] = 'header';
        $this->data['pagebody'] = 'receiving/receipt';
        $this->data['content'] = $message;
        $this->data['totalCost'] = moneyFormat($totalOrderCost);
        $this->data['backUrl'] = base_url() . "receiving";

        $this->render();
    }

}

redpajama_set_name: RedPajamaGithub


text:
using WinrtCrypto.Common;
using WinrtCrypto.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234233

namespace WinrtCrypto
{
    /// <summary>
    /// A page that displays a collection of item previews.  In the Split App this page
    /// is used to display and select one of the available groups.
    /// </summary>
    public sealed partial class ItemsPage : Page
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        public ItemsPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
            this.DefaultViewModel["Items"] = sampleDataGroups;
        }

        /// <summary>
        /// Invoked when an item is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var groupId = ((SampleDataGroup)e.ClickedItem).UniqueId;
            this.Frame.Navigate(typeof(SplitPage), groupId);
        }

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        ///
        /// Page specific logic should be placed in event handlers for the
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion
    }
}


text:
<!DOCTYPE html>

Reviews closed:

Review applications deadline:

                        View competition brief (opens in a new window).

                Applications will be removed from your dashboard if you don't review them before the deadline.

                There are currently no applications for you to review.

Applications for review ()

Interested

Declined

                                    View feedback

                                Review


text:
package me.chris.MoneyManager;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author Chris
 *
 */
public class HelperMethods
{
	public static void ImportGroups()
	{
		Vars.payGroups = new ArrayList<PayGroup>();
		Vars.taxGroups = new ArrayList<TaxGroup>();

		ArrayList<String> payGroups = convertToArrayList(Vars.config.getConfigurationSection("PayGroups.").getKeys(false));
		ArrayList<String> taxGroups = convertToArrayList(Vars.config.getConfigurationSection("TaxGroups.").getKeys(false));

		// PAY GROUPS
		if (payGroups != null)
		{
			for (String groupName : payGroups)
			{
				double amount = -1;
				String type;
				ArrayList<String> members = new ArrayList<String>();

				// GET THE VALUES
				try
				{
					amount = Vars.config.getDouble("PayGroups." + groupName + ".Amount");
				}
				catch (Throwable t)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Amount variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				try
				{
					type = Vars.config.getString("PayGroups." + groupName + ".Type");
				}
				catch (Throwable t)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Type variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				try
				{
					members = convertToArrayList(Vars.config.getStringList("PayGroups." + groupName + ".Members"));
				}
				catch (Throwable t)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Members variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				// IF VALUES DID NOT ASSIGN PROPERLY
				if (amount == -1)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Amount variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}
				if (type == null)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Type variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}
				if (members.isEmpty())
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Members variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				// CHECKS RESTRICTIONS ON VALUES
				if (amount < 0)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Amount variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] Cannot have negative payment amount");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}
				if ((type.equalsIgnoreCase("flat_rate") || type.equalsIgnoreCase("percent") || type.equalsIgnoreCase("$") || type.equalsIgnoreCase("%")) == false)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Type variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] Type values must be: flat, percent, $, %");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				Vars.payGroups.add(new PayGroup(groupName, amount, type, members));
			}
		}

		// TAX GROUPS
		if (taxGroups != null)
		{
			for (String groupName : taxGroups)
			{
				double amount = -1;
				String type;
				ArrayList<String> members = new ArrayList<String>();

				// GET THE VALUES
				try
				{
					amount = Vars.config.getDouble("TaxGroups." + groupName + ".Amount");
				}
				catch (Throwable t)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Amount variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				try
				{
					type = Vars.config.getString("TaxGroups." + groupName + ".Type");
				}
				catch (Throwable t)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Type variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				try
				{
					members = convertToArrayList(Vars.config.getStringList("TaxGroups." + groupName + ".Members"));
				}
				catch (Throwable t)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Members variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				// IF VALUES DID NOT ASSIGN PROPERLY
				if (amount == -1)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Amount variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}
				if (type == null)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Type variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}
				if (members.isEmpty())
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Members variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				// CHECKS RESTRICTIONS ON VALUES
				if (amount < 0)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Amount variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] Cannot have negative tax amount");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}
				if ((type.equalsIgnoreCase("flat_rate") || type.equalsIgnoreCase("percent") || type.equalsIgnoreCase("$") || type.equalsIgnoreCase("%")) == false)
				{
					Vars.log.log(Level.SEVERE, "[MoneyManager] Problem found with the Type variable in your " + groupName + " group.");
					Vars.log.log(Level.SEVERE, "[MoneyManager] Type values must be: flat, percent, $, %");
					Vars.log.log(Level.SEVERE, "[MoneyManager] This group will not be registered until said problem is fixed.");
					continue;
				}

				Vars.taxGroups.add(new TaxGroup(groupName, amount, type, members));
			}
		}
	}

	public static void ExportGroups()
	{
		Vars.config.set("PayGroups", "");
		Vars.config.set("TaxGroups", "");

		if (Vars.payGroups != null)
		{
			for (PayGroup group : Vars.payGroups)
			{
				String name = group.getGroupName();
				double amount = group.getAmount();
				String type = group.getType();
				ArrayList<String> members = group.getMembers();

				Vars.config.set("PayGroups." + name + ".Amount", amount);
				Vars.config.set("PayGroups." + name + ".Type", type);
				Vars.config.set("PayGroups." + name + ".Members", members);
			}
		}

		if (Vars.taxGroups != null)
		{
			for (TaxGroup group : Vars.taxGroups)
			{
				String name = group.getGroupName();
				double amount = group.getAmount();
				String type = group.getType();
				ArrayList<String> members = group.getMembers();

				Vars.config.set("TaxGroups." + name + ".Amount", amount);
				Vars.config.set("TaxGroups." + name + ".Type", type);
				Vars.config.set("TaxGroups." + name + ".Members", members);
			}
		}
	}

	private static ArrayList<String> convertToArrayList(Set<String> original)
	{
		ArrayList<String> newList = new ArrayList<String>();
		for (String str : original)
		{
			newList.add(str);
		}
		return newList;
	}

	private static ArrayList<String> convertToArrayList(List<String> original)
	{
		ArrayList<String> newList = new ArrayList<String>();
		for (String str : original)
		{
			newList.add(str);
		}
		return newList;
	}

	public static String updateCheck() throws Exception
	{
		String pluginUrlString = "http://dev.bukkit.org/server-mods/moneymanager/files.rss";
		String lastestVersion = "";
		try
		{
			URL url = new URL(pluginUrlString);
			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream());
			doc.getDocumentElement().normalize();
			NodeList nodes = doc.getElementsByTagName("item");
			Node firstNode = nodes.item(0);
			if (firstNode.getNodeType() == 1)
			{
				Element firstElement = (Element) firstNode;
				NodeList firstElementTagName = firstElement.getElementsByTagName("title");
				Element firstNameElement = (Element) firstElementTagName.item(0);
				NodeList firstNodes = firstNameElement.getChildNodes();
				lastestVersion = firstNodes.item(0).getNodeValue();
			}
		}
		catch (Exception localException)
		{
		}
		return lastestVersion;
	}
}


text: Slide decks for various talks using the gnab/remark framework


text:
<template name="message">

		{{> avatar username=u.username}}
		{{sender}}

			{{time}}
		{{#if edited}}
			({{_ "edited"}})
		{{/if}}
		{{#if canEdit}}

		{{/if}}
		{{#if canDelete}}

		{{/if}}

			{{{body}}}

</template>


text:
title: Antivirus software and Docker
description: General guidelines for using antivirus software with Docker
keywords: antivirus, security
---

When antivirus software scans files used by Docker, these files may be locked
in a way that causes Docker commands to hang.

One way to reduce these problems is to add the Docker data directory
(`/var/lib/docker` on Linux or `$Env:ProgramData` on Windows Server) to the
antivirus's exclusion list. However, this comes with the trade-off that viruses
or malware in Docker images, writable layers of containers, or volumes are not
detected. If you do choose to exclude Docker's data directory from background
virus scanning, you may want to schedule a recurring task that stops Docker,
scans the data directory, and restarts Docker.


text:
"""
    sphinx.ext.doctest
    ~~~~~~~~~~~~~~~~~~

    Mimic doctest by automatically executing code snippets and checking
    their results.

    :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import doctest
import re
import sys
import time
import warnings
from io import StringIO
from os import path

from docutils import nodes
from docutils.parsers.rst import directives
from packaging.specifiers import SpecifierSet, InvalidSpecifier
from packaging.version import Version

import sphinx
from sphinx.builders import Builder
from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.console import bold  # type: ignore
from sphinx.util.docutils import SphinxDirective
from sphinx.util.nodes import set_source_info
from sphinx.util.osutil import relpath

if False:
    # For type annotation
    from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Type  # NOQA
    from sphinx.application import Sphinx  # NOQA

logger = logging.getLogger(__name__)

blankline_re = re.compile(r'^\s*<BLANKLINE>', re.MULTILINE)
doctestopt_re = re.compile(r'#\s*doctest:.+$', re.MULTILINE)

def doctest_encode(text, encoding):
    # type: (str, str) -> str
    warnings.warn('doctest_encode() is deprecated.',
                  RemovedInSphinx40Warning)
    return text

def is_allowed_version(spec, version):
    # type: (str, str) -> bool
    """Check `spec` satisfies `version` or not.

    This obeys PEP-440 specifiers:
    https://www.python.org/dev/peps/pep-0440/#version-specifiers

    Some examples:

        >>> is_allowed_version('3.3', '<=3.5')
        True
        >>> is_allowed_version('3.3', '<=3.2')
        False
        >>> is_allowed_version('3.3', '>3.2, <4.0')
        True
    """
    return Version(version) in SpecifierSet(spec)

# set up the necessary directives

class TestDirective(SphinxDirective):
    """
    Base class for doctest-related directives.
    """

    has_content = True
    required_arguments = 0
    optional_arguments = 1
    final_argument_whitespace = True

    def run(self):
        # type: () -> List[nodes.Node]
        # use ordinary docutils nodes for test code: they get special attributes
        # so that our builder recognizes them, and the other builders are happy.
        code = '\n'.join(self.content)
        test = None
        if self.name == 'doctest':
            if '<BLANKLINE>' in code:
                # convert <BLANKLINE>s to ordinary blank lines for presentation
                test = code
                code = blankline_re.sub('', code)
            if doctestopt_re.search(code):
                if not test:
                    test = code
                code = doctestopt_re.sub('', code)
        nodetype = nodes.literal_block  # type: Type[nodes.TextElement]
        if self.name in ('testsetup', 'testcleanup') or 'hide' in self.options:
            nodetype = nodes.comment
        if self.arguments:
            groups = [x.strip() for x in self.arguments[0].split(',')]
        else:
            groups = ['default']
        node = nodetype(code, code, testnodetype=self.name, groups=groups)
        set_source_info(self, node)
        if test is not None:
            # only save if it differs from code
            node['test'] = test
        if self.name == 'doctest':
            if self.config.highlight_language in ('py', 'python'):
                node['language'] = 'pycon'
            else:
                node['language'] = 'pycon3'  # default
        elif self.name == 'testcode':
            if self.config.highlight_language in ('py', 'python'):
                node['language'] = 'python'
            else:
                node['language'] = 'python3'  # default
        elif self.name == 'testoutput':
            # don't try to highlight output
            node['language'] = 'none'
        node['options'] = {}
        if self.name in ('doctest', 'testoutput') and 'options' in self.options:
            # parse doctest-like output comparison flags
            option_strings = self.options['options'].replace(',', ' ').split()
            for option in option_strings:
                prefix, option_name = option[0], option[1:]
                if prefix not in '+-':
                    self.state.document.reporter.warning(
                        __("missing '+' or '-' in '%s' option.") % option,
                        line=self.lineno)
                    continue
                if option_name not in doctest.OPTIONFLAGS_BY_NAME:
                    self.state.document.reporter.warning(
                        __("'%s' is not a valid option.") % option_name,
                        line=self.lineno)
                    continue
                flag = doctest.OPTIONFLAGS_BY_NAME[option[1:]]
                node['options'][flag] = (option[0] == '+')
        if self.name == 'doctest' and 'pyversion' in self.options:
            try:
                spec = self.options['pyversion']
                python_version = '.'.join([str(v) for v in sys.version_info[:3]])
                if not is_allowed_version(spec, python_version):
                    flag = doctest.OPTIONFLAGS_BY_NAME['SKIP']
                    node['options'][flag] = True  # Skip the test
            except InvalidSpecifier:
                self.state.document.reporter.warning(
                    __("'%s' is not a valid pyversion option") % spec,
                    line=self.lineno)
        if 'skipif' in self.options:
            node['skipif'] = self.options['skipif']
        return [node]

class TestsetupDirective(TestDirective):
    option_spec = {'skipif': directives.unchanged_required}  # type: Dict

class TestcleanupDirective(TestDirective):
    option_spec = {'skipif': directives.unchanged_required}  # type: Dict

class DoctestDirective(TestDirective):
    option_spec = {
        'hide': directives.flag,
        'options': directives.unchanged,
        'pyversion': directives.unchanged_required,
        'skipif': directives.unchanged_required,
    }

class TestcodeDirective(TestDirective):
    option_spec = {
        'hide': directives.flag,
        'pyversion': directives.unchanged_required,
        'skipif': directives.unchanged_required,
    }

class TestoutputDirective(TestDirective):
    option_spec = {
        'hide': directives.flag,
        'options': directives.unchanged,
        'pyversion': directives.unchanged_required,
        'skipif': directives.unchanged_required,
    }

parser = doctest.DocTestParser()

# helper classes

class TestGroup:
    def __init__(self, name):
        # type: (str) -> None
        self.name = name
        self.setup = []     # type: List[TestCode]
        self.tests = []     # type: List[List[TestCode]]
        self.cleanup = []   # type: List[TestCode]

    def add_code(self, code, prepend=False):
        # type: (TestCode, bool) -> None
        if code.type == 'testsetup':
            if prepend:
                self.setup.insert(0, code)
            else:
                self.setup.append(code)
        elif code.type == 'testcleanup':
            self.cleanup.append(code)
        elif code.type == 'doctest':
            self.tests.append([code])
        elif code.type == 'testcode':
            self.tests.append([code, None])
        elif code.type == 'testoutput':
            if self.tests and len(self.tests[-1]) == 2:
                self.tests[-1][1] = code
        else:
            raise RuntimeError(__('invalid TestCode type'))

    def __repr__(self):
        # type: () -> str
        return 'TestGroup(name=%r, setup=%r, cleanup=%r, tests=%r)' % (
            self.name, self.setup, self.cleanup, self.tests)

class TestCode:
    def __init__(self, code, type, filename, lineno, options=None):
        # type: (str, str, Optional[str], int, Optional[Dict]) -> None
        self.code = code
        self.type = type
        self.filename = filename
        self.lineno = lineno
        self.options = options or {}

    def __repr__(self):
        # type: () -> str
        return 'TestCode(%r, %r, filename=%r, lineno=%r, options=%r)' % (
            self.code, self.type, self.filename, self.lineno, self.options)

class SphinxDocTestRunner(doctest.DocTestRunner):
    def summarize(self, out, verbose=None):  # type: ignore
        # type: (Callable, bool) -> Tuple[int, int]
        string_io = StringIO()
        old_stdout = sys.stdout
        sys.stdout = string_io
        try:
            res = super().summarize(verbose)
        finally:
            sys.stdout = old_stdout
        out(string_io.getvalue())
        return res

    def _DocTestRunner__patched_linecache_getlines(self, filename,
                                                   module_globals=None):
        # type: (str, Any) -> Any
        # this is overridden from DocTestRunner adding the try-except below
        m = self._DocTestRunner__LINECACHE_FILENAME_RE.match(filename)  # type: ignore
        if m and m.group('name') == self.test.name:
            try:
                example = self.test.examples[int(m.group('examplenum'))]
            # because we compile multiple doctest blocks with the same name
            # (viz. the group name) this might, for outer stack frames in a
            # traceback, get the wrong test which might not have enough examples
            except IndexError:
                pass
            else:
                return example.source.splitlines(True)
        return self.save_linecache_getlines(filename, module_globals)  # type: ignore

# the new builder -- use sphinx-build.py -b doctest to run

class DocTestBuilder(Builder):
    """
    Runs test snippets in the documentation.
    """
    name = 'doctest'
    epilog = __('Testing of doctests in the sources finished, look at the '
                'results in %(outdir)s/output.txt.')

    def init(self):
        # type: () -> None
        # default options
        self.opt = self.config.doctest_default_flags

        # HACK HACK HACK
        # doctest compiles its snippets with type 'single'. That is nice
        # for doctest examples but unusable for multi-statement code such
        # as setup code -- to be able to use doctest error reporting with
        # that code nevertheless, we monkey-patch the "compile" it uses.
        doctest.compile = self.compile  # type: ignore

        sys.path[0:0] = self.config.doctest_path

        self.type = 'single'

        self.total_failures = 0
        self.total_tries = 0
        self.setup_failures = 0
        self.setup_tries = 0
        self.cleanup_failures = 0
        self.cleanup_tries = 0

        date = time.strftime('%Y-%m-%d %H:%M:%S')

        self.outfile = open(path.join(self.outdir, 'output.txt'), 'w', encoding='utf-8')
        self.outfile.write(('Results of doctest builder run on %s\n'
                            '==================================%s\n') %
                           (date, '=' * len(date)))

    def _out(self, text):
        # type: (str) -> None
        logger.info(text, nonl=True)
        self.outfile.write(text)

    def _warn_out(self, text):
        # type: (str) -> None
        if self.app.quiet or self.app.warningiserror:
            logger.warning(text)
        else:
            logger.info(text, nonl=True)
        self.outfile.write(text)

    def get_target_uri(self, docname, typ=None):
        # type: (str, str) -> str
        return ''

    def get_outdated_docs(self):
        # type: () -> Set[str]
        return self.env.found_docs

    def finish(self):
        # type: () -> None
        # write executive summary
        def s(v):
            # type: (int) -> str
            return v != 1 and 's' or ''
        repl = (self.total_tries, s(self.total_tries),
                self.total_failures, s(self.total_failures),
                self.setup_failures, s(self.setup_failures),
                self.cleanup_failures, s(self.cleanup_failures))
        self._out('''
Doctest summary
===============
%5d test%s
%5d failure%s in tests
%5d failure%s in setup code
%5d failure%s in cleanup code
''' % repl)
        self.outfile.close()

        if self.total_failures or self.setup_failures or self.cleanup_failures:
            self.app.statuscode = 1

    def write(self, build_docnames, updated_docnames, method='update'):
        # type: (Iterable[str], Sequence[str], str) -> None
        if build_docnames is None:
            build_docnames = sorted(self.env.all_docs)

        logger.info(bold('running tests...'))
        for docname in build_docnames:
            # no need to resolve the doctree
            doctree = self.env.get_doctree(docname)
            self.test_doc(docname, doctree)

    def get_filename_for_node(self, node, docname):
        # type: (nodes.Node, str) -> str
        """Try to get the file which actually contains the doctest, not the
        filename of the document it's included in."""
        try:
            filename = relpath(node.source, self.env.srcdir)\
                .rsplit(':docstring of ', maxsplit=1)[0]
        except Exception:
            filename = self.env.doc2path(docname, base=None)
        return filename

    @staticmethod
    def get_line_number(node):
        # type: (nodes.Node) -> Optional[int]
        """Get the real line number or admit we don't know."""
        # TODO:  Work out how to store or calculate real (file-relative)
        #       line numbers for doctest blocks in docstrings.
        if ':docstring of ' in path.basename(node.source or ''):
            # The line number is given relative to the stripped docstring,
            # not the file.  This is correct where it is set, in
            # `docutils.nodes.Node.setup_child`, but Sphinx should report
            # relative to the file, not the docstring.
            return None
        if node.line is not None:
            # TODO: find the root cause of this off by one error.
            return node.line - 1
        return None

    def skipped(self, node):
        # type: (nodes.Element) -> bool
        if 'skipif' not in node:
            return False
        else:
            condition = node['skipif']
            context = {}  # type: Dict[str, Any]
            if self.config.doctest_global_setup:
                exec(self.config.doctest_global_setup, context)
            should_skip = eval(condition, context)
            if self.config.doctest_global_cleanup:
                exec(self.config.doctest_global_cleanup, context)
            return should_skip

    def test_doc(self, docname, doctree):
        # type: (str, nodes.Node) -> None
        groups = {}  # type: Dict[str, TestGroup]
        add_to_all_groups = []
        self.setup_runner = SphinxDocTestRunner(verbose=False,
                                                optionflags=self.opt)
        self.test_runner = SphinxDocTestRunner(verbose=False,
                                               optionflags=self.opt)
        self.cleanup_runner = SphinxDocTestRunner(verbose=False,
                                                  optionflags=self.opt)

        self.test_runner._fakeout = self.setup_runner._fakeout  # type: ignore
        self.cleanup_runner._fakeout = self.setup_runner._fakeout  # type: ignore

        if self.config.doctest_test_doctest_blocks:
            def condition(node):
                # type: (nodes.Node) -> bool
                return (isinstance(node, (nodes.literal_block, nodes.comment)) and
                        'testnodetype' in node) or \
                    isinstance(node, nodes.doctest_block)
        else:
            def condition(node):
                # type: (nodes.Node) -> bool
                return isinstance(node, (nodes.literal_block, nodes.comment)) \
                    and 'testnodetype' in node
        for node in doctree.traverse(condition):  # type: nodes.Element
            if self.skipped(node):
                continue

            source = node['test'] if 'test' in node else node.astext()
            filename = self.get_filename_for_node(node, docname)
            line_number = self.get_line_number(node)
            if not source:
                logger.warning(__('no code/output in %s block at %s:%s'),
                               node.get('testnodetype', 'doctest'),
                               filename, line_number)
            code = TestCode(source, type=node.get('testnodetype', 'doctest'),
                            filename=filename, lineno=line_number,
                            options=node.get('options'))
            node_groups = node.get('groups', ['default'])
            if '*' in node_groups:
                add_to_all_groups.append(code)
                continue
            for groupname in node_groups:
                if groupname not in groups:
                    groups[groupname] = TestGroup(groupname)
                groups[groupname].add_code(code)
        for code in add_to_all_groups:
            for group in groups.values():
                group.add_code(code)
        if self.config.doctest_global_setup:
            code = TestCode(self.config.doctest_global_setup,
                            'testsetup', filename=None, lineno=0)
            for group in groups.values():
                group.add_code(code, prepend=True)
        if self.config.doctest_global_cleanup:
            code = TestCode(self.config.doctest_global_cleanup,
                            'testcleanup', filename=None, lineno=0)
            for group in groups.values():
                group.add_code(code)
        if not groups:
            return

        self._out('\nDocument: %s\n----------%s\n' %
                  (docname, '-' * len(docname)))
        for group in groups.values():
            self.test_group(group)
        # Separately count results from setup code
        res_f, res_t = self.setup_runner.summarize(self._out, verbose=False)
        self.setup_failures += res_f
        self.setup_tries += res_t
        if self.test_runner.tries:
            res_f, res_t = self.test_runner.summarize(self._out, verbose=True)
            self.total_failures += res_f
            self.total_tries += res_t
        if self.cleanup_runner.tries:
            res_f, res_t = self.cleanup_runner.summarize(self._out,
                                                         verbose=True)
            self.cleanup_failures += res_f
            self.cleanup_tries += res_t

    def compile(self, code, name, type, flags, dont_inherit):
        # type: (str, str, str, Any, bool) -> Any
        return compile(code, name, self.type, flags, dont_inherit)

    def test_group(self, group):
        # type: (TestGroup) -> None
        ns = {}  # type: Dict

        def run_setup_cleanup(runner, testcodes, what):
            # type: (Any, List[TestCode], Any) -> bool
            examples = []
            for testcode in testcodes:
                example = doctest.Example(testcode.code, '', lineno=testcode.lineno)
                examples.append(example)
            if not examples:
                return True
            # simulate a doctest with the code
            sim_doctest = doctest.DocTest(examples, {},
                                          '%s (%s code)' % (group.name, what),
                                          testcodes[0].filename, 0, None)
            sim_doctest.globs = ns
            old_f = runner.failures
            self.type = 'exec'  # the snippet may contain multiple statements
            runner.run(sim_doctest, out=self._warn_out, clear_globs=False)
            if runner.failures > old_f:
                return False
            return True

        # run the setup code
        if not run_setup_cleanup(self.setup_runner, group.setup, 'setup'):
            # if setup failed, don't run the group
            return

        # run the tests
        for code in group.tests:
            if len(code) == 1:
                # ordinary doctests (code/output interleaved)
                try:
                    test = parser.get_doctest(code[0].code, {}, group.name,  # type: ignore
                                              code[0].filename, code[0].lineno)
                except Exception:
                    logger.warning(__('ignoring invalid doctest code: %r'), code[0].code,
                                   location=(code[0].filename, code[0].lineno))
                    continue
                if not test.examples:
                    continue
                for example in test.examples:
                    # apply directive's comparison options
                    new_opt = code[0].options.copy()
                    new_opt.update(example.options)
                    example.options = new_opt
                self.type = 'single'  # as for ordinary doctests
            else:
                # testcode and output separate
                output = code[1] and code[1].code or ''
                options = code[1] and code[1].options or {}
                # disable <BLANKLINE> processing as it is not needed
                options[doctest.DONT_ACCEPT_BLANKLINE] = True
                # find out if we're testing an exception
                m = parser._EXCEPTION_RE.match(output)  # type: ignore
                if m:
                    exc_msg = m.group('msg')
                else:
                    exc_msg = None
                example = doctest.Example(code[0].code, output, exc_msg=exc_msg,
                                          lineno=code[0].lineno, options=options)
                test = doctest.DocTest([example], {}, group.name,
                                       code[0].filename, code[0].lineno, None)
                self.type = 'exec'  # multiple statements again
            # DocTest.__init__ copies the globs namespace, which we don't want
            test.globs = ns
            # also don't clear the globs namespace after running the doctest
            self.test_runner.run(test, out=self._warn_out, clear_globs=False)

        # run the cleanup
        run_setup_cleanup(self.cleanup_runner, group.cleanup, 'cleanup')

def setup(app):
    # type: (Sphinx) -> Dict[str, Any]
    app.add_directive('testsetup', TestsetupDirective)
    app.add_directive('testcleanup', TestcleanupDirective)
    app.add_directive('doctest', DoctestDirective)
    app.add_directive('testcode', TestcodeDirective)
    app.add_directive('testoutput', TestoutputDirective)
    app.add_builder(DocTestBuilder)
    # this config value adds to sys.path
    app.add_config_value('doctest_path', [], False)
    app.add_config_value('doctest_test_doctest_blocks', 'default', False)
    app.add_config_value('doctest_global_setup', '', False)
    app.add_config_value('doctest_global_cleanup', '', False)
    app.add_config_value(
        'doctest_default_flags',
        doctest.DONT_ACCEPT_TRUE_FOR_1 | doctest.ELLIPSIS | doctest.IGNORE_EXCEPTION_DETAIL,
        False)
    return {'version': sphinx.__display_version__, 'parallel_read_safe': True}


text:
package org.apache.directory.server.xdbm.search.evaluator;

import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.filter.ScopeNode;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.server.core.api.partition.PartitionTxn;
import org.apache.directory.server.i18n.I18n;
import org.apache.directory.server.xdbm.IndexEntry;
import org.apache.directory.server.xdbm.ParentIdAndRdn;
import org.apache.directory.server.xdbm.Store;
import org.apache.directory.server.xdbm.search.Evaluator;

/**
 * Evaluates one level scope assertions on candidates using an entry database.
 *
 * @author Apache Directory Project
 */
public class OneLevelScopeEvaluator<E> implements Evaluator<ScopeNode>
{
    /** The ScopeNode containing initial search scope constraints */
    private final ScopeNode node;

    /** The entry identifier of the scope base */
    private final String baseId;

    /** True if the scope requires alias dereferencing while searching */
    private final boolean dereferencing;

    /** the entry db storing entries */
    private final Store db;

    /**
     * Creates a one level scope node Evaluator for search expressions.
     *
     * @param node the scope node
     * @param db the database used to evaluate scope node
     */
    public OneLevelScopeEvaluator( Store db, ScopeNode node )
    {
        this.node = node;

        if ( node.getScope() != SearchScope.ONELEVEL )
        {
            throw new IllegalStateException( I18n.err( I18n.ERR_720 ) );
        }

        this.db = db;
        baseId = node.getBaseId();
        dereferencing = node.getDerefAliases().isDerefInSearching() || node.getDerefAliases().isDerefAlways();
    }

    /**
     * Asserts whether or not a candidate has one level scope while taking
     * alias dereferencing into account.
     *
     * TODO - terribly inefficient - would benefit from exposing the id of an
     * entry within the Entry
     *
     * {@inheritDoc}
     */
    public boolean evaluate( Entry candidate ) throws LdapException
    {
        throw new UnsupportedOperationException( I18n.err( I18n.ERR_721 ) );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean evaluate( PartitionTxn partitionTxn, IndexEntry<?, String> indexEntry ) throws LdapException
    {
        ParentIdAndRdn parent = db.getRdnIndex().reverseLookup( partitionTxn, indexEntry.getId() );
        boolean isChild = parent.getParentId().equals( baseId );
        Entry entry = indexEntry.getEntry();

        // Fetch the entry
        if ( null == entry )
        {
            entry = db.fetch( partitionTxn, indexEntry.getId() );

            if ( null == entry )
            {
                // The entry is not anymore present : get out
                return false;
            }

            indexEntry.setEntry( entry );
        }

        /*
         * The candidate id could be any entry in the db.  If search
         * dereferencing is not enabled then we return the results of the child
         * test.
         */
        if ( !dereferencing )
        {
            return isChild;
        }

        /*
         * From here down alias dereferencing is enabled.  We determine if the
         * candidate id is an alias, if so we reject it since aliases should
         * not be returned.
         */
        if ( null != db.getAliasIndex().reverseLookup( partitionTxn, indexEntry.getId() ) )
        {
            return false;
        }

        /*
         * The candidate is NOT an alias at this point.  So if it is a child we
         * just return true since it is in normal one level scope.
         */
        if ( isChild )
        {
            return true;
        }

        /*
         * At this point the candidate is not a child and it is not an alias.
         * We need to check if the candidate is in extended one level scope by
         * performing a lookup on the one level alias index.  This index stores
         * a tuple mapping the baseId to the id of objects brought into the
         * one level scope of the base by an alias: ( baseId, aliasedObjId )
         * If the candidate id is an object brought into one level scope then
         * the lookup returns true accepting the candidate.  Otherwise the
         * candidate is rejected with a false return because it is not in scope.
         */
        return db.getOneAliasIndex().forward( partitionTxn, baseId, indexEntry.getId() );
    }

    public ScopeNode getExpression()
    {
        return node;
    }

    /**
     * Gets the id of the search base associated with the ScopeNode expression.
     *
     * @return identifier of the search base
     */
    public String getBaseId()
    {
        return baseId;
    }

    /**
     * Gets whether or not dereferencing is enabled for this evaluator.
     *
     * @return true if dereferencing is enabled, false otherwise
     */
    public boolean isDereferencing()
    {
        return dereferencing;
    }

    /**
     * @see Object#toString()
     */
    public String toString( String tabs )
    {
        StringBuilder sb = new StringBuilder();

        sb.append( tabs ).append( "OneLevelScopEvaluator : " ).append( node ).append( "\n" );

        return sb.toString();
    }

    /**
     * @see Object#toString()
     */
    public String toString()
    {
        return toString( "" );
    }
}


text:
namespace hect
{

///
/// A point in time represented as the number of seconds since January 1st, 1970.
typedef int64_t TimeStamp;

}


text:
namespace facebook {
namespace react {

#define REQUEST_MODULE_IDS 0
#define REQUEST_METHOD_IDS 1
#define REQUEST_PARAMSS 2
#define REQUEST_CALLID 3

std::vector<MethodCall> parseMethodCalls(folly::dynamic&& jsonData) throw(std::invalid_argument) {
  if (jsonData.isNull()) {
    return {};
  }

  if (!jsonData.isArray()) {
    throw std::invalid_argument(
      folly::to<std::string>("Did not get valid calls back from JS: ", jsonData.typeName()));
  }

  if (jsonData.size() < REQUEST_PARAMSS + 1) {
    throw std::invalid_argument(
      folly::to<std::string>("Did not get valid calls back from JS: size == ", jsonData.size()));
  }

  auto& moduleIds = jsonData[REQUEST_MODULE_IDS];
  auto& methodIds = jsonData[REQUEST_METHOD_IDS];
  auto& params = jsonData[REQUEST_PARAMSS];
  int  callId = -1;

  if (!moduleIds.isArray() || !methodIds.isArray() || !params.isArray()) {
    throw std::invalid_argument(
      folly::to<std::string>("Did not get valid calls back from JS: ", folly::toJson(jsonData)));
  }

  if (moduleIds.size() != methodIds.size() || moduleIds.size() != params.size()) {
    throw std::invalid_argument(
      folly::to<std::string>("Did not get valid calls back from JS: ", folly::toJson(jsonData)));
  }

  if (jsonData.size() > REQUEST_CALLID) {
    if (!jsonData[REQUEST_CALLID].isNumber()) {
      throw std::invalid_argument(
        folly::to<std::string>("Did not get valid calls back from JS: %s", folly::toJson(jsonData)));
    }
    callId = jsonData[REQUEST_CALLID].asInt();
  }

  std::vector<MethodCall> methodCalls;
  for (size_t i = 0; i < moduleIds.size(); i++) {
    if (!params[i].isArray()) {
      throw std::invalid_argument(
          folly::to<std::string>("Call argument isn't an array"));
    }

    methodCalls.emplace_back(
      moduleIds[i].asInt(),
      methodIds[i].asInt(),
      std::move(params[i]),
      callId);

    // only incremement callid if contains valid callid as callid is optional
    callId += (callId != -1) ? 1 : 0;
  }

  return methodCalls;
}

}}


text:
<?php

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2015
 * $Id$
 *
 */

/**
 * This class generates form components for Pledge
 *
 */
class CRM_Pledge_Form_PledgeView extends CRM_Core_Form {

  /**
   * Set variables up before form is built.
   *
   * @return void
   */
  public function preProcess() {

    $values = $ids = array();
    $params = array('id' => $this->get('id'));
    CRM_Pledge_BAO_Pledge::getValues($params,
      $values,
      $ids
    );

    $values['frequencyUnit'] = ts('%1(s)', array(1 => $values['frequency_unit']));

    if (isset($values["honor_contact_id"]) && $values["honor_contact_id"]) {
      $sql = "SELECT display_name FROM civicrm_contact WHERE id = " . $values["honor_contact_id"];
      $dao = new CRM_Core_DAO();
      $dao->query($sql);
      if ($dao->fetch()) {
        $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=$values[honor_contact_id]");
        $values["honor_display"] = "" . $dao->display_name . "";
      }
      $honor = CRM_Core_PseudoConstant::get('CRM_Pledge_DAO_Pledge', 'honor_type_id');
      $values['honor_type'] = $honor[$values['honor_type_id']];
    }

    //handle custom data.
    $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', $this, $params['id']);
    CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);

    if (!empty($values['contribution_page_id'])) {
      $values['contribution_page'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $values['contribution_page_id'], 'title');
    }

    $values['financial_type'] = CRM_Utils_Array::value($values['financial_type_id'], CRM_Contribute_PseudoConstant::financialType());

    if ($values['status_id']) {
      $values['pledge_status'] = CRM_Utils_Array::value($values['status_id'], CRM_Contribute_PseudoConstant::contributionStatus());
    }

    $url = CRM_Utils_System::url('civicrm/contact/view/pledge',
      "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
    );

    $recentOther = array();
    if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
      $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge',
        "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
      );
    }
    if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
      $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge',
        "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
      );
    }

    $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']);
    $this->assign('displayName', $displayName);

    $title = $displayName .
      ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($values['pledge_amount']) .
      ' - ' . $values['financial_type'] . ')';

    // add Pledge to Recent Items
    CRM_Utils_Recent::add($title,
      $url,
      $values['id'],
      'Pledge',
      $values['contact_id'],
      NULL,
      $recentOther
    );

    // Check if this is default domain contact CRM-10482
    if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) {
      $displayName .= ' (' . ts('default organization') . ')';
    }
    // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
    CRM_Utils_System::setTitle(ts('View Pledge by') . ' ' . $displayName);

    //do check for campaigns
    if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) {
      $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
      $values['campaign'] = $campaigns[$campaignId];
    }

    $this->assign($values);
  }

  /**
   * Build the form object.
   *
   * @return void
   */
  public function buildQuickForm() {
    $this->addButtons(array(
        array(
          'type' => 'next',
          'name' => ts('Done'),
          'spacing' => '         ',
          'isDefault' => TRUE,
        ),
      )
    );
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
XWPFRelation (POI API Documentation)
</TITLE>

<META NAME="date" CONTENT="2009-12-14">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.xwpf.usermodel

Class XWPFRelation

java.lang.Object
  org.apache.poi.POIXMLRelation
      org.apache.poi.xwpf.usermodel.XWPFRelation

public final class XWPFRelation
extends POIXMLRelation

Author:

Yegor Kozlov

Field Summary

protected static java.util.Map<java.lang.String,XWPFRelation>
_table

          A map to lookup POIXMLRelation by its relation type

static XWPFRelation
COMMENT

static XWPFRelation
DOCUMENT

static XWPFRelation
ENDNOTE

static XWPFRelation
FONT_TABLE

static XWPFRelation
FOOTER

static XWPFRelation
FOOTNOTE

static XWPFRelation
HEADER

static XWPFRelation
HYPERLINK

static XWPFRelation
MACRO_DOCUMENT

static XWPFRelation
MACRO_TEMPLATE_DOCUMENT

static XWPFRelation
SETTINGS

static XWPFRelation
STYLES

static XWPFRelation
TEMPLATE

static XWPFRelation
WEB_SETTINGS

Fields inherited from class org.apache.poi.POIXMLRelation

_defaultName, _relation, _type

Method Summary

static XWPFRelation
getInstance(java.lang.String rel)

          Get POIXMLRelation by relation type

Methods inherited from class org.apache.poi.POIXMLRelation

getContentType, getDefaultFileName, getFileName, getRelation, getRelationClass

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_table

protected static java.util.Map<java.lang.String,XWPFRelation> _table

A map to lookup POIXMLRelation by its relation type

DOCUMENT

public static final XWPFRelation DOCUMENT

TEMPLATE

public static final XWPFRelation TEMPLATE

MACRO_DOCUMENT

public static final XWPFRelation MACRO_DOCUMENT

MACRO_TEMPLATE_DOCUMENT

public static final XWPFRelation MACRO_TEMPLATE_DOCUMENT

FONT_TABLE

public static final XWPFRelation FONT_TABLE

SETTINGS

public static final XWPFRelation SETTINGS

STYLES

public static final XWPFRelation STYLES

WEB_SETTINGS

public static final XWPFRelation WEB_SETTINGS

HEADER

public static final XWPFRelation HEADER

FOOTER

public static final XWPFRelation FOOTER

HYPERLINK

public static final XWPFRelation HYPERLINK

COMMENT

public static final XWPFRelation COMMENT

FOOTNOTE

public static final XWPFRelation FOOTNOTE

ENDNOTE

public static final XWPFRelation ENDNOTE

Method Detail

getInstance

public static XWPFRelation getInstance(java.lang.String rel)

Get POIXMLRelation by relation type

Parameters:
rel - relation type, for example,
            http://schemas.openxmlformats.org/officeDocument/2006/relationships/image

Returns:
registered POIXMLRelation or null if not found

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright 2009 The Apache Software Foundation or
        its licensors, as applicable.


text:
<?php

require_once(dirname(__FILE__).'/sfDoctrineBaseTask.class.php');

/**
 * Generate migrations from database
 *
 * @package    symfony
 * @subpackage doctrine
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author     Jonathan H. Wage <jonwage@gmail.com>
 * @version    SVN: $Id: sfDoctrineGenerateMigrationsDbTask.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class sfDoctrineGenerateMigrationsDbTask extends sfDoctrineBaseTask
{
  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', true),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
    ));

    $this->aliases = array('doctrine-generate-migrations-db', 'doctrine-gen-migrations-from-db');
    $this->namespace = 'doctrine';
    $this->name = 'generate-migrations-db';
    $this->briefDescription = 'Generate migration classes from existing database connections';

    $this->detailedDescription = <<<EOF
The [doctrine:generate-migrations-db|INFO] task generates migration classes from
existing database connections:

  [./symfony doctrine:generate-migrations-db|INFO]
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);
    $config = $this->getCliConfig();

    $this->logSection('doctrine', 'generating migration classes from database');

    if (!is_dir($config['migrations_path']))
    {
      $this->getFilesystem()->mkdirs($config['migrations_path']);
    }

    $this->callDoctrineCli('generate-migrations-db', array(
      'yaml_schema_path' => $this->prepareSchemaFile($config['yaml_schema_path']),
    ));
  }
}


text:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  lessons.find({}, function(err, lesson){
    if (err) throw err;
    res.json(lesson);
  });
});

router.post('/lesson/:id/attend/:flag', function(req, res){
  var id = req.params.id;
  var flag = (req.params.flag == 1) ? true : false;
  lessons.update({lessonId: id},
    {attended : flag},
    function(err, cb){
      if (err) throw err;
      res.send(cb);
    }
  );
  //res.send("success");
});

var lessons = require("../models/lessons.js");

router.get('/lesson/:id', function(req, res){
  var id = req.params.id;
  lessons.findOne({lessonId:id}, function(err, lesson){
    if (err) throw err;
    res.json(lesson);
  });

});

//unit testing
router.get('/testGet', function(req, res){
  lessons.findOne({lessonId:50}, function(err, user){
    if (err) throw err;
    console.log(user);
    res.json(user);
  });
});

module.exports = router;


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
    <name>MainWindow</name>
    <message>
        <source>Login Manager Settings</source>
        <translation>Login Maniġer Issettjar</translation>
    </message>
    <message>
        <source>Auto login</source>
        <translation>Auto login</translation>
    </message>
    <message>
        <source>Enable auto login</source>
        <translation>Jippermettu login auto</translation>
    </message>
    <message>
        <source>Auto login user</source>
        <translation>Utent login Auto</translation>
    </message>
    <message>
        <source>Remote login</source>
        <translation>login remoti</translation>
    </message>
    <message>
        <source>Password Request</source>
        <translation>Talba password</translation>
    </message>
    <message>
        <source>Please enter the login password for this user</source>
        <translation>Jekk jogħġbok ikteb il-password login għal dan l-utent</translation>
    </message>
    <message>
        <source>Enable Remote Desktop (VNC)</source>
        <translation>Jippermettu Desktop Remote (VNC)</translation>
    </message>
    <message>
        <source>Misc</source>
        <translation>Misc</translation>
    </message>
    <message>
        <source>Enable "show password" button</source>
        <translation>Jippermettu "juru password" buttuna</translation>
    </message>
    <message>
        <source>Please enter the remote login password</source>
        <translation>Jekk jogħġbok ikteb il-password login remoti</translation>
    </message>
    <message>
        <source>Missing Config File</source>
        <translation>Nieqsa konfigurazzjoni File</translation>
    </message>
    <message>
        <source>The PCDM configuration file could not be found: %1</source>
        <translation>Il-fajl konfigurazzjoni PCDM ma setgħux jiġu misjuba: %1</translation>
    </message>
    <message>
        <source>This application will now close</source>
        <translation>Din l-applikazzjoni issa se tagħlaq</translation>
    </message>
    <message>
        <source>Time Delay</source>
        <translation>ħin Delay</translation>
    </message>
    <message>
        <source> Seconds</source>
        <translation>sekondi</translation>
    </message>
    <message>
        <source>Display available users</source>
        <translation>Utenti disponibbli Display</translation>
    </message>
    <message>
        <source>&Apply</source>
        <translation>&Applika</translation>
    </message>
    <message>
        <source>&Close</source>
        <translation>&Agħlaq</translation>
    </message>
    <message>
        <source>Allow Valid Users with UID under 1000</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Additional Excluded Users</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>...</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Allow Stealth Sessions</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>QObject</name>
    <message>
        <source>You should run this application as root</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
namespace Restore
{
    public class SynchronizationResult
    {
        public SynchronizationResult(bool success, string message = "", string messageKey = "")
        {
            MessageKey = messageKey;
            Message = message;
            Success = success;
        }

        public SynchronizationResult()
        {
            Success = true;
        }

        public static implicit operator bool(SynchronizationResult result)
        {
            return result.Success;
        }

        public virtual bool Success { get; }

        public string Message { get; }

        public string MessageKey { get; }
    }
}


text:
package robocode;

import net.sf.robocode.peer.IRobotStatics;
import net.sf.robocode.security.SafeComponent;
import net.sf.robocode.serialization.ISerializableHelper;
import net.sf.robocode.serialization.RbSerializer;
import robocode.robotinterfaces.IBasicRobot;
import robocode.robotinterfaces.IInteractiveEvents;
import robocode.robotinterfaces.IInteractiveRobot;

import java.awt.*;
import java.nio.ByteBuffer;

/**
 * A MouseEnteredEvent is sent to {@link Robot#onMouseEntered(java.awt.event.MouseEvent)
 * onMouseEntered()} when the mouse has entered the battle view.
 *
 * @see MouseClickedEvent
 * @see MousePressedEvent
 * @see MouseReleasedEvent
 * @see MouseExitedEvent
 * @see MouseMovedEvent
 * @see MouseDraggedEvent
 * @see MouseWheelMovedEvent
 *
 * @author Pavel Savara (original)
 * @author Flemming N. Larsen (contributor)
 *
 * @since 1.6.1
 */
public final class MouseEnteredEvent extends MouseEvent {
	private static final long serialVersionUID = 1L;
	private final static int DEFAULT_PRIORITY = 98;

	/**
	 * Called by the game to create a new MouseEnteredEvent.
	 *
	 * @param source the source mouse event originating from the AWT.
	 */
	public MouseEnteredEvent(java.awt.event.MouseEvent source) {
		super(source);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	final int getDefaultPriority() {
		return DEFAULT_PRIORITY;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	final void dispatch(IBasicRobot robot, IRobotStatics statics, Graphics2D graphics) {
		if (statics.isInteractiveRobot()) {
			IInteractiveEvents listener = ((IInteractiveRobot) robot).getInteractiveEventListener();

			if (listener != null) {
				listener.onMouseEntered(getSourceEvent());
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	byte getSerializationType() {
		return RbSerializer.MouseEnteredEvent_TYPE;
	}

	static ISerializableHelper createHiddenSerializer() {
		return new SerializableHelper();
	}

	private static class SerializableHelper implements ISerializableHelper {

		public int sizeOf(RbSerializer serializer, Object object) {
			return RbSerializer.SIZEOF_TYPEINFO + 6 * RbSerializer.SIZEOF_INT + RbSerializer.SIZEOF_LONG;
		}

		public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) {
			MouseEnteredEvent obj = (MouseEnteredEvent) object;
			java.awt.event.MouseEvent src = obj.getSourceEvent();

			serializer.serialize(buffer, src.getButton());
			serializer.serialize(buffer, src.getClickCount());
			serializer.serialize(buffer, src.getX());
			serializer.serialize(buffer, src.getY());
			serializer.serialize(buffer, src.getID());
			serializer.serialize(buffer, src.getModifiersEx());
			serializer.serialize(buffer, src.getWhen());
		}

		public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {
			int button = buffer.getInt();
			int clickCount = buffer.getInt();
			int x = buffer.getInt();
			int y = buffer.getInt();
			int id = buffer.getInt();
			int modifiersEx = buffer.getInt();
			long when = buffer.getLong();

			return new MouseEnteredEvent(
					new java.awt.event.MouseEvent(SafeComponent.getSafeEventComponent(), id, when, modifiersEx, x, y,
					clickCount, false, button));
		}
	}
}


text:
package com.github.yatrik.app.todopro.app;

import android.content.Context;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.github.yatrik.app.todopro.R;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by Yatrik Mehta on 8/8/2014.
 */
public class TodoAdapter extends ArrayAdapter<Todo> {

    //List for Adapter
    final private ArrayList<Todo> todos;

    //Cache for todos
    final private HashMap<Integer, Todo> todoMap;

    //database handler for persisting TodoItems
    final private DBHelper db;

    //Context
    final private Context context;

    //Sorting Order;
    private Constants.SORTING_ON sortingOn = Constants.SORTING_ON.PRIORITY;

    public TodoAdapter(Context context, ArrayList<Todo> todos) {
        super(context, R.layout.todos, todos);
        this.todos = todos;
        this.todoMap = new HashMap<Integer, Todo>();
        this.db = new DBHelper(context);
        this.context = context;
        refresh();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        final Todo todo = getItem(position);
        final ViewHolder viewHolder; // view lookup cache stored in tag

        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.todos, parent, false);
            viewHolder.todoText = (TextView) convertView.findViewById(R.id.todo_description);
            viewHolder.todoSel = (CheckBox) convertView.findViewById(R.id.todo_sel);
            viewHolder.todoRemindOn = (TextView) convertView.findViewById(R.id.todo_remind_on);
            viewHolder.todoSel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton checkbtn, boolean isChecked) {
                    Integer todoId = (Integer) checkbtn.getTag();
                    updateIsDone(todoId, isChecked);
                }
            });
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.todoText.setText(todo.getDescription());
        viewHolder.todoSel.setTag(todo.getId());
        viewHolder.todoSel.setChecked(todo.isCompleted());
        viewHolder.todoRemindOn.setText(todo.getRemindOn()==null?"":todo.getRemindOn());

        todoMap.put(todo.getId(), todo);
        if (todo.isCompleted()) {
            viewHolder.todoText.setPaintFlags(viewHolder.todoText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            viewHolder.todoText.setPaintFlags(viewHolder.todoText.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));

        }

        // set the remindOn
        if(todo.getRemindOn() != null && !todo.getRemindOn().equals("")){
            try {
                Date remindOnDate = Constants.TODO_REMINDER_FORMAT.parse(todo.getRemindOn());
                Calendar remindOnCal = Calendar.getInstance();
                remindOnCal.setTime(remindOnDate);
                int currentDayOfYear = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
                int remindOnDayOfYear = remindOnCal.get(Calendar.DAY_OF_YEAR);
                if (currentDayOfYear==remindOnDayOfYear){
                    viewHolder.todoRemindOn.setText(Constants.TODO_TODAYS_REMINDER_FORMAT.format(remindOnCal.getTime()));
                }else {
                    viewHolder.todoRemindOn.setText(Constants.TODO_REST_REMINDER_FORMAT.format(remindOnCal.getTime()));
                }
            }
            catch(ParseException exception){
                exception.printStackTrace();
            }
        }

        // set view color as per the priority
        if(todo.getPriority()==Constants.PRIORITY.HIGH.getPriority()) {
            convertView.setBackgroundColor(context.getResources().getColor(R.color.high_priority));
        }
        else if(todo.getPriority()==Constants.PRIORITY.NORMAL.getPriority()) {
            convertView.setBackgroundColor(context.getResources().getColor(R.color.normal_priority));
        }
        else if(todo.getPriority()==Constants.PRIORITY.LOW.getPriority()) {
            convertView.setBackgroundColor(context.getResources().getColor(R.color.low_priority));
        }

        // Return the completed view to render on screen
        return convertView;
    }

    // View lookup cache
    private static class ViewHolder {
        TextView todoText;
        CheckBox todoSel;
        TextView todoRemindOn;
    }

    private void populateTodoMap() {
        this.todoMap.clear();
        for (Todo item : todos) {
            todoMap.put(item.getId(), item);
        }
    }

    public void refresh() {
        this.todos.clear();
        this.todos.addAll(db.getAll());
        performSort();
        populateTodoMap();
    }

    public Todo getById(int todoId){
        return this.todoMap.get(todoId);
    }

    public void addTodo(Todo todo) {
        int id = db.add(todo);
        todo.setId(id);
        todo.setCreatedOn(Constants.TODO_REMINDER_FORMAT.format(Calendar.getInstance().getTime()));
        this.todos.add(todo);
        this.todoMap.put(id, todo);
        performSort();
    }

    public void update(Integer id, String description, String remindOn, Integer priority) {
        Todo todo = todoMap.get(id);

        if (todo != null) {
            todo.setDescription(description);
            todo.setRemindOn(remindOn);
            todo.setPriority(priority);
            db.update(todo);
            performSort();
        }
    }

    private void updateIsDone(Integer todoId, Boolean isCompleted) {
        Todo todoItem = todoMap.get(todoId);
        if (todoItem.isCompleted() != isCompleted) {
            todoItem.setCompleted(isCompleted);
            db.update(todoItem);
            this.notifyDataSetChanged();
        }
    }

    public void deleteSelected() {
        db.deleteAllDoneTodos();
        refresh();
    }

    public void sortByPriority(){
        sortingOn = Constants.SORTING_ON.PRIORITY;
        Collections.sort(todos, Todo.PriorityComparator);
        notifyDataSetChanged();
    }

    public void sortByRemindOnDate(){
        sortingOn = Constants.SORTING_ON.REMIND_ON_DATE;
        Collections.sort(todos, Todo.RemindOnComparator);
        notifyDataSetChanged();
    }

    public void performSort(){
        performSort(sortingOn);
    }

    public void performSort(Constants.SORTING_ON sortOn){
        if(sortOn.equals(Constants.SORTING_ON.PRIORITY)){
            sortByPriority();
        }
        else if(sortOn.equals(Constants.SORTING_ON.REMIND_ON_DATE)){
            sortByRemindOnDate();
        }
    }

}


text:
import * as React from 'react'
import {Component, ReactNode} from 'react'
import * as PropTypes from 'prop-types'
import {createStructuredSelector} from 'reselect'
import {connect} from 'react-redux'
import DumbContainer from './DumbContainer'
import CreateContainer from '../../model/actions/CreateContainer'
import {canUseDOM} from 'exenv'
import {Store} from '../../store'
import AddTitle from '../../model/actions/AddTitle'
import PathTitle from '../../model/PathTitle'
import SwitchToContainer from '../../model/actions/SwitchToContainer'
import {
  getDispatch, createCachingSelector,
  getContainerName, getContainerActiveUrl, getIsActiveInGroup, getMatchesCurrentUrl
} from '../selectors'

interface BaseContainerProps {
  children?: ReactNode
  initialUrl: string
  patterns: string[]
  animate?: boolean
  isDefault?: boolean
  resetOnLeave?: boolean
  className?: string
  style?: any
}

export type ContainerProps = BaseContainerProps & {
  name: string
}

type ContainerPropsWithStore = BaseContainerProps & {
  store: Store
  groupName: string
  containerName: string
  hideInactiveContainers: boolean
}

type ConnectedContainerProps = ContainerPropsWithStore & {
  activeUrl: string
  isActiveInGroup: boolean
  matchesCurrentUrl: boolean
  addTitle: (title:PathTitle) => any
  switchToContainer: () => void
}

class InnerSmartContainer extends Component<ConnectedContainerProps, undefined> {

  addTitleForPath(pathname:string) {
    const {addTitle} = this.props
    if (canUseDOM) {
      addTitle({
        pathname,
        title: document.title
      })
    }
  }

  componentDidUpdate() {
    const {activeUrl, matchesCurrentUrl} = this.props
    if (matchesCurrentUrl) {
      this.addTitleForPath(activeUrl)
    }
  }

  render() {
    const {animate=true} = this.props
    const props = {...this.props, animate}
    // @ts-ignore
    return <DumbContainer {...props} />
  }
}

const makeGetActions = () => createCachingSelector(
  getContainerName, getDispatch,
  (containerName, dispatch) => ({
    createContainer: (action:CreateContainer) => dispatch(action),
    addTitle: (title:PathTitle) => dispatch(new AddTitle(title)),
    switchToContainer: () => dispatch(new SwitchToContainer({name: containerName}))
  })
)

const mapStateToProps = createStructuredSelector({
  activeUrl: getContainerActiveUrl,
  isActiveInGroup: getIsActiveInGroup,
  matchesCurrentUrl: getMatchesCurrentUrl
})

const mergeProps = (stateProps, dispatchProps,
                    ownProps:ContainerPropsWithStore):ConnectedContainerProps => ({
  ...stateProps,
  ...dispatchProps,
  ...ownProps
})

const ConnectedSmartContainer = connect(
  mapStateToProps,
  makeGetActions,
  mergeProps
)(InnerSmartContainer as any) as any

export default class SmartContainer extends Component<ContainerProps, undefined> {
  static contextTypes = {
    rrnhStore: PropTypes.object.isRequired,
    groupName: PropTypes.string.isRequired,
    hideInactiveContainers: PropTypes.bool
  }

  render() {
    const {rrnhStore, ...context} = this.context
    const {name, ...props} = this.props
    return <ConnectedSmartContainer containerName={name}
                                    {...context}
                                    {...props}
                                    store={rrnhStore}

    />
  }
}


text:
    //
    // Note: This is sample code for demonstration purposes only and is provided as-is.
    //
[TestMethod]
public void AggregateLogs_PastThreeDays_ReturnsAllLinesFromPastThreeDaysAndToday()
{
    // Arrange
    var sut = new LogAggregator();

    // Act
    var result = sut.AggregateLogs(@"C:\SomeLogDir", daysInPast: 3);

    // Assert
    Assert.AreEqual(4, result.Length, "Number of aggregated lines incorrect.");
CollectionAssert.Contains(result, "ThreeDaysAgoFirstLine", "Expected line missing.");
CollectionAssert.Contains(result, "TodayLastLine", "Expected line missing.");
}


text:
#ifndef DATUNPACKER_ARGUMENTSCHECKER_H
#define DATUNPACKER_ARGUMENTSCHECKER_H

// C++ standard includes
#include <string>

// DatUnpacker includes
#include "Arguments.h"
#include "Format.h"

// Third party includes

namespace DatUnpacker
{
    class ArgumentsChecker
    {
        public:
            ArgumentsChecker() = default;
            bool check(const Arguments& arguments);
            bool checkFormat(const Format& format);
            bool checkSource(const std::string& source);
            bool checkDestination(const std::string& destination);
            std::string getErrorMessage() const;

        private:
            std::string _errorMessage;
    };
}

#endif //DATUNPACKER_ARGUMENTSCHECKER_H


text:
using System;
using Xwt.Backends;
using MonoMac.AppKit;

namespace Xwt.Mac
{
	public class ListBoxBackend: ListViewBackend, IListBoxBackend
	{
		ListViewColumn column = new ListViewColumn ();
		NSTableColumn columnHandle;

		public ListBoxBackend ()
		{
		}

		public new bool GridLinesVisible {
			get {
				return (base.GridLinesVisible == Xwt.GridLines.Horizontal || base.GridLinesVisible == Xwt.GridLines.Both);
			}
			set {
				base.GridLinesVisible = value ? Xwt.GridLines.Horizontal : Xwt.GridLines.None;
			}
		}

		public override void Initialize ()
		{
			base.Initialize ();
			HeadersVisible = false;
			columnHandle = AddColumn (column);
			VerticalScrollPolicy = ScrollPolicy.Automatic;
			HorizontalScrollPolicy = ScrollPolicy.Automatic;
		}

		public void SetViews (CellViewCollection views)
		{
			column.Views.Clear ();
			foreach (var v in views)
				column.Views.Add (v);
			UpdateColumn (column, columnHandle, ListViewColumnChange.Cells);
		}

		public override void SetSource (IListDataSource source, IBackend sourceBackend)
		{
			base.SetSource (source, sourceBackend);

			source.RowInserted += HandleColumnSizeChanged;
			source.RowDeleted += HandleColumnSizeChanged;
			source.RowChanged += HandleColumnSizeChanged;
			ResetColumnSize (source);
		}

		void HandleColumnSizeChanged (object sender, ListRowEventArgs e)
		{
			var source = (IListDataSource)sender;
			ResetColumnSize (source);
		}

		void ResetColumnSize (IListDataSource source)
		{
			// Calculate size of column
			// This is how Apple implements it; unfortunately, they don't expose this functionality in the API.
			// https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSTableViewDelegate_Protocol/index.html#//apple_ref/occ/intfm/NSTableViewDelegate/tableView:sizeToFitWidthOfColumn:
			float w = 0;
			for (var row = 0; row < source.RowCount; row++) {
				using (var cell = Table.GetCell (0, row)) {
					var size = cell.CellSize;
					w = Math.Max (w, size.Width);
				}
			}
			columnHandle.MinWidth = w;
			columnHandle.Width = w;
		}
	}
}


text:
Notification Alerts

Provide contextual feedback messages for typical user actions with the handful of available and flexible alert messages.

    <ngb-alert [dismissible]="false">
      Warning! Better check yourself, you're not looking too good.
    </ngb-alert>

Closeable Alert

      <ngb-alert [type]="alert.type" (close)="closeAlert(alert)">{{ alert.message }}</ngb-alert>

      <button type="button" class="btn btn-primary" (click)="reset()">Reset</button>

Self-Closing Alert

Static self-closing alert that disappears after 20 seconds (refresh the page if it has already disappeared)

    <ngb-alert *ngIf="!staticAlertClosed" (close)="staticAlertClosed = true">Check out our awesome new features!</ngb-alert>

Show a self-closing success message that disappears after 5 seconds.

    <ngb-alert *ngIf="successMessage" type="success" (close)="successMessage = null">{{ successMessage }}</ngb-alert>

      <button class="btn btn-primary" (click)="changeSuccessMessage()">Change message</button>

Closeable Alert

    <ngb-alert type="custom" [dismissible]="false">Whoa! This is a custom alert.</ngb-alert>


text:
from django.conf import settings
from django.test import TestCase
from django.utils.six.moves.urllib.parse import urlencode

class RenderingBaseTemplateRegressionTestCase(TestCase):

    def test_can_render_the_base_template(self):
        content = self.get_rendered_base_template_with_following_context()
        self.assertNotIn(settings.TEMPLATE_STRING_IF_INVALID, content)

    def get_rendered_base_template_with_following_context(self, **kwargs):
        url = self.get_url()
        response = self.client.get(url)
        content = response.content.decode('utf8')
        return content

    def get_url(self, **kwargs):
        template_name = '/rosetta/base.html'
        query = self.get_querystring(**kwargs)
        url = '?'.join([template_name, query])
        return url

    def get_querystring(self, **kwargs):
        query_dict = dict(
            version='1.2.3',
            ADMIN_MEDIA_PREFIX='',
        )
        query_dict.update(kwargs)
        return urlencode(query_dict)