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

import com.facebook.presto.metadata.FunctionHandle;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.sql.analyzer.Session;
import com.facebook.presto.sql.analyzer.Type;
import com.facebook.presto.sql.planner.DependencyExtractor;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.SymbolAllocator;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.LimitNode;
import com.facebook.presto.sql.planner.plan.MaterializedViewWriterNode;
import com.facebook.presto.sql.planner.plan.OutputNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.PlanNodeRewriter;
import com.facebook.presto.sql.planner.plan.PlanRewriter;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.planner.plan.TableWriterNode;
import com.facebook.presto.sql.planner.plan.TopNNode;
import com.facebook.presto.sql.planner.plan.UnionNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FunctionCall;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.facebook.presto.sql.planner.plan.JoinNode.EquiJoinClause.leftGetter;
import static com.facebook.presto.sql.planner.plan.JoinNode.EquiJoinClause.rightGetter;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.in;
import static com.google.common.collect.Iterables.concat;

/**
 * Removes all computation that does is not referenced transitively from the root of the plan
 *

 * E.g.,
 *

 * {@code Output[$0] -> Project[$0 := $1 + $2, $3 = $4 / $5] -> ...}
 *

 * gets rewritten as
 *

 * {@code Output[$0] -> Project[$0 := $1 + $2] -> ...}
 */
public class PruneUnreferencedOutputs
        extends PlanOptimizer
{
    @Override
    public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator)
    {
        checkNotNull(plan, "plan is null");
        checkNotNull(session, "session is null");
        checkNotNull(types, "types is null");
        checkNotNull(symbolAllocator, "symbolAllocator is null");
        checkNotNull(idAllocator, "idAllocator is null");

        return PlanRewriter.rewriteWith(new Rewriter(types), plan, ImmutableSet.<Symbol>of());
    }

    private static class Rewriter
            extends PlanNodeRewriter<Set<Symbol>>
    {
        private final Map<Symbol, Type> types;

        public Rewriter(Map<Symbol, Type> types)
        {
            this.types = types;
        }

        @Override
        public PlanNode rewriteJoin(JoinNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            Set<Symbol> leftInputs = ImmutableSet.<Symbol>builder()
                    .addAll(expectedOutputs)
                    .addAll(Iterables.transform(node.getCriteria(), leftGetter()))
                    .build();

            Set<Symbol> rightInputs = ImmutableSet.<Symbol>builder()
                    .addAll(expectedOutputs)
                    .addAll(Iterables.transform(node.getCriteria(), rightGetter()))
                    .build();

            PlanNode left = planRewriter.rewrite(node.getLeft(), leftInputs);
            PlanNode right = planRewriter.rewrite(node.getRight(), rightInputs);

            return new JoinNode(node.getId(), node.getType(), left, right, node.getCriteria());
        }

        @Override
        public PlanNode rewriteSemiJoin(SemiJoinNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            Set<Symbol> sourceInputs = ImmutableSet.<Symbol>builder()
                    .addAll(expectedOutputs)
                    .add(node.getSourceJoinSymbol())
                    .build();

            Set<Symbol> filteringSourceInputs = ImmutableSet.<Symbol>builder()
                    .add(node.getFilteringSourceJoinSymbol())
                    .build();

            PlanNode source = planRewriter.rewrite(node.getSource(), sourceInputs);
            PlanNode filteringSource = planRewriter.rewrite(node.getFilteringSource(), filteringSourceInputs);

            return new SemiJoinNode(node.getId(), source, filteringSource, node.getSourceJoinSymbol(), node.getFilteringSourceJoinSymbol(), node.getSemiJoinOutput());
        }

        @Override
        public PlanNode rewriteAggregation(AggregationNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            ImmutableSet.Builder<Symbol> expectedInputs = ImmutableSet.<Symbol>builder()
                    .addAll(node.getGroupBy());

            ImmutableMap.Builder<Symbol, FunctionHandle> functions = ImmutableMap.builder();
            ImmutableMap.Builder<Symbol, FunctionCall> functionCalls = ImmutableMap.builder();
            for (Map.Entry<Symbol, FunctionCall> entry : node.getAggregations().entrySet()) {
                Symbol symbol = entry.getKey();

                if (expectedOutputs.contains(symbol)) {
                    FunctionCall call = entry.getValue();
                    expectedInputs.addAll(DependencyExtractor.extractUnique(call));

                    functionCalls.put(symbol, call);
                    functions.put(symbol, node.getFunctions().get(symbol));
                }
            }

            PlanNode source = planRewriter.rewrite(node.getSource(), expectedInputs.build());

            return new AggregationNode(node.getId(), source, node.getGroupBy(), functionCalls.build(), functions.build());
        }

        @Override
        public PlanNode rewriteWindow(WindowNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            ImmutableSet.Builder<Symbol> expectedInputs = ImmutableSet.<Symbol>builder()
                    .addAll(expectedOutputs)
                    .addAll(node.getPartitionBy())
                    .addAll(node.getOrderBy());

            ImmutableMap.Builder<Symbol, FunctionHandle> functions = ImmutableMap.builder();
            ImmutableMap.Builder<Symbol, FunctionCall> functionCalls = ImmutableMap.builder();
            for (Map.Entry<Symbol, FunctionCall> entry : node.getWindowFunctions().entrySet()) {
                Symbol symbol = entry.getKey();

                if (expectedOutputs.contains(symbol)) {
                    FunctionCall call = entry.getValue();
                    expectedInputs.addAll(DependencyExtractor.extractUnique(call));

                    functionCalls.put(symbol, call);
                    functions.put(symbol, node.getFunctionHandles().get(symbol));
                }
            }

            PlanNode source = planRewriter.rewrite(node.getSource(), expectedInputs.build());

            return new WindowNode(node.getId(), source, node.getPartitionBy(), node.getOrderBy(), node.getOrderings(), functionCalls.build(), functions.build());
        }

        @Override
        public PlanNode rewriteTableScan(TableScanNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            Set<Symbol> requiredTableScanOutputs = FluentIterable.from(expectedOutputs)
                    .filter(in(node.getOutputSymbols()))
                    .toSet();
            if (requiredTableScanOutputs.isEmpty()) {
                for (Symbol symbol : node.getOutputSymbols()) {
                    if (Type.isNumeric(types.get(symbol))) {
                        requiredTableScanOutputs = ImmutableSet.of(symbol);
                        break;
                    }
                }
                if (requiredTableScanOutputs.isEmpty()) {
                    requiredTableScanOutputs = ImmutableSet.of(node.getOutputSymbols().get(0));
                }
            }
            checkState(!requiredTableScanOutputs.isEmpty());

            List<Symbol> newOutputSymbols = FluentIterable.from(node.getOutputSymbols())
                    .filter(in(requiredTableScanOutputs))
                    .toList();

            Set<Symbol> requiredAssignmentSymbols = requiredTableScanOutputs;
            if (!node.getPartitionsDomainSummary().isNone()) {
                Set<Symbol> requiredPartitionDomainSymbols = Maps.filterValues(node.getAssignments(), Predicates.in(node.getPartitionsDomainSummary().getDomains().keySet())).keySet();
                requiredAssignmentSymbols = Sets.union(requiredTableScanOutputs, requiredPartitionDomainSymbols);
            }
            Map<Symbol, ColumnHandle> newAssignments = Maps.filterKeys(node.getAssignments(), in(requiredAssignmentSymbols));

            return new TableScanNode(node.getId(), node.getTable(), newOutputSymbols, newAssignments, node.getOriginalConstraint(), node.getGeneratedPartitions());
        }

        @Override
        public PlanNode rewriteFilter(FilterNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            Set<Symbol> expectedInputs = ImmutableSet.<Symbol>builder()
                    .addAll(DependencyExtractor.extractUnique(node.getPredicate()))
                    .addAll(expectedOutputs)
                    .build();

            PlanNode source = planRewriter.rewrite(node.getSource(), expectedInputs);

            return new FilterNode(node.getId(), source, node.getPredicate());
        }

        @Override
        public PlanNode rewriteProject(ProjectNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            ImmutableSet.Builder<Symbol> expectedInputs = ImmutableSet.builder();

            ImmutableMap.Builder<Symbol, Expression> builder = ImmutableMap.builder();
            for (int i = 0; i < node.getOutputSymbols().size(); i++) {
                Symbol output = node.getOutputSymbols().get(i);
                Expression expression = node.getExpressions().get(i);

                if (expectedOutputs.contains(output)) {
                    expectedInputs.addAll(DependencyExtractor.extractUnique(expression));
                    builder.put(output, expression);
                }
            }

            PlanNode source = planRewriter.rewrite(node.getSource(), expectedInputs.build());

            return new ProjectNode(node.getId(), source, builder.build());
        }

        @Override
        public PlanNode rewriteOutput(OutputNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            Set<Symbol> expectedInputs = ImmutableSet.copyOf(node.getOutputSymbols());
            PlanNode source = planRewriter.rewrite(node.getSource(), expectedInputs);
            return new OutputNode(node.getId(), source, node.getColumnNames(), node.getOutputSymbols());
        }

        @Override
        public PlanNode rewriteLimit(LimitNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            PlanNode source = planRewriter.rewrite(node.getSource(), expectedOutputs);
            return new LimitNode(node.getId(), source, node.getCount());
        }

        @Override
        public PlanNode rewriteTopN(TopNNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            Set<Symbol> expectedInputs = ImmutableSet.copyOf(concat(expectedOutputs, node.getOrderBy()));

            PlanNode source = planRewriter.rewrite(node.getSource(), expectedInputs);

            return new TopNNode(node.getId(), source, node.getCount(), node.getOrderBy(), node.getOrderings(), node.isPartial());
        }

        @Override
        public PlanNode rewriteSort(SortNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            Set<Symbol> expectedInputs = ImmutableSet.copyOf(concat(expectedOutputs, node.getOrderBy()));

            PlanNode source = planRewriter.rewrite(node.getSource(), expectedInputs);

            return new SortNode(node.getId(), source, node.getOrderBy(), node.getOrderings());
        }

        @Override
        public PlanNode rewriteTableWriter(TableWriterNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            PlanNode source = planRewriter.rewrite(node.getSource(), ImmutableSet.copyOf(node.getColumns()));

            return new TableWriterNode(node.getId(), source, node.getTarget(), node.getColumns(), node.getColumnNames(), node.getOutputSymbols());
        }

        @Override
        public PlanNode rewriteMaterializedViewWriter(MaterializedViewWriterNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            // Rewrite Query subtree in terms of the symbols expected by the writer.
            Set<Symbol> expectedInputs = ImmutableSet.copyOf(node.getColumns().keySet());
            PlanNode source = planRewriter.rewrite(node.getSource(), expectedInputs);
            return new MaterializedViewWriterNode(node.getId(),
                    source,
                    node.getTable(),
                    node.getColumns(),
                    node.getOutput());
        }

        @Override
        public PlanNode rewriteUnion(UnionNode node, Set<Symbol> expectedOutputs, PlanRewriter<Set<Symbol>> planRewriter)
        {
            // Find out which output symbols we need to keep
            ImmutableListMultimap.Builder<Symbol, Symbol> rewrittenSymbolMappingBuilder = ImmutableListMultimap.builder();
            for (Symbol symbol : node.getOutputSymbols()) {
                if (expectedOutputs.contains(symbol)) {
                    rewrittenSymbolMappingBuilder.putAll(symbol, node.getSymbolMapping().get(symbol));
                }
            }
            ListMultimap<Symbol, Symbol> rewrittenSymbolMapping = rewrittenSymbolMappingBuilder.build();

            // Find the corresponding input symbol to the remaining output symbols and prune the subplans
            ImmutableList.Builder<PlanNode> rewrittenSubPlans = ImmutableList.builder();
            for (int i = 0; i < node.getSources().size(); i++) {
                ImmutableSet.Builder<Symbol> expectedInputSymbols = ImmutableSet.builder();
                for (Collection<Symbol> symbols : rewrittenSymbolMapping.asMap().values()) {
                    expectedInputSymbols.add(Iterables.get(symbols, i));
                }
                rewrittenSubPlans.add(planRewriter.rewrite(node.getSources().get(i), expectedInputSymbols.build()));
            }

            return new UnionNode(node.getId(), rewrittenSubPlans.build(), rewrittenSymbolMapping);
        }
    }
}


text:
module Phantoms () where

type Param = (String, String)

type ContentType = String

data Part = Part
  { name :: String
  , fileName :: Maybe FilePath
  , contentType :: Maybe ContentType
  , body :: String
  } deriving (Show)

data Payload a = NoPayload
               | Raw ContentType String
               | Params [Param]
               | FormData [Part]
               deriving (Show)

-- Can you write a Monoid instance for `Payload`?
instance Monoid (Payload [Param]) where

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.ADF.CATIDs;
using System.Resources;
using ESRI.ArcGIS.Editor;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.CatalogUI;
using ESRI.ArcGIS.Catalog;

namespace ESRI.ArcGIS.OSM.Editor
{
    /// <summary>
    /// Generic property page implementation for ArcGIS Desktop
    /// </summary>
    [Guid("6c210462-106a-4ca9-8b3e-fd190468fe6b")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("OSMEditor.OSMEditorPropertyPage")]
    public partial class OSMEditorPropertyPage : UserControl, IComPropertyPage
    {
        #region COM Registration Function(s)
        [ComRegisterFunction()]
        [ComVisible(false)]
        static void RegisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryRegistration(registerType);
        }

        [ComUnregisterFunction()]
        [ComVisible(false)]
        static void UnregisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryUnregistration(registerType);
        }

        #region ArcGIS Component Category Registrar generated code
        /// <summary>
        /// Required method for ArcGIS Component Category registration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryRegistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            EditorPropertyPages.Register(regKey);

        }
        /// <summary>
        /// Required method for ArcGIS Component Category unregistration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryUnregistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            EditorPropertyPages.Unregister(regKey);

        }

        #endregion
        #endregion

        private string m_pageTitle;

        private bool m_dirtyFlag = false;
        private IComPropertyPageSite m_pageSite = null;
        private Dictionary<string, object> m_objectBag;
        private ResourceManager resourceManager = null;
        private IEditor m_editor = null;
        string m_osmbaseURL = String.Empty;

        public OSMEditorPropertyPage()
        {
            InitializeComponent();

            resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.Editor.OSMFeatureInspectorStrings", this.GetType().Assembly);

            //TODO: Modify property page title
            m_pageTitle = resourceManager.GetString("OSMEditor_OSMPropertyPage_tabtitle");
            lblBaseURL.Text = resourceManager.GetString("OSMEditor_OSMPropertyPage_labelBaseURL");
            lblFeatureDomains.Text = resourceManager.GetString("OSMEditor_OSMPropertyPage_labelOSMDomains");
            lblFeatureProperties.Text = resourceManager.GetString("OSMEditor_OSMPropertyPage_labelOSMFeatures");
        }

        /// <summary>
        /// Call this to set dirty flag whenever changes are made to the UI/page
        /// </summary>
        private void SetPageDirty(bool dirty)
        {
            if (m_dirtyFlag != dirty)
            {
                m_dirtyFlag = dirty;
                if (m_pageSite != null)
                    m_pageSite.PageChanged();
            }
        }

        #region IComPropertyPage Members

        string IComPropertyPage.Title
        {
            get
            {
                return m_pageTitle;
            }
            set
            {
                //Uncomment if title can be modified
                //m_pageTitle = value;
            }
        }

        int IComPropertyPage.Width
        {
            get { return this.Width; }
        }

        int IComPropertyPage.Height
        {
            get { return this.Height; }
        }

        int IComPropertyPage.Activate()
        {
            // get the OSM extension and retrieve the base url
            if (m_editor != null)
            {
                IExtensionManager extensionManager = m_editor as IExtensionManager;

                //for (int index = 0; index < extensionManager.ExtensionCount; index++)
                //{
                //    System.Diagnostics.Debug.WriteLine(extensionManager.Extension[index].Name);
                //}

                UID osmEditorExtensionCLSID = new UIDClass();
                osmEditorExtensionCLSID.Value = "{faa799f0-bdc7-4ca4-af0c-a8d591c22058}";
                OSMEditorExtension osmEditorExtension = m_editor.Parent.FindExtensionByCLSID(osmEditorExtensionCLSID) as OSMEditorExtension;

                if (osmEditorExtension != null)
                {
                    m_osmbaseURL = osmEditorExtension.OSMBaseURL;
                    txtOSMBaseURL.Text = m_osmbaseURL;
                    txtOSMDomainFileLocation.Text = osmEditorExtension.OSMDomainsXmlFilePath;
                    txtOSMFeaturePropertiesFileLocation.Text = osmEditorExtension.OSMFeaturePropertiesXmlFilePath;
                }
            }

            txtOSMBaseURL.Focus();
            m_dirtyFlag = false;

            return this.Handle.ToInt32();

        }

        void IComPropertyPage.Deactivate()
        {
            m_objectBag = null;
            this.Dispose(true);
        }

        /// <summary>
        /// Indicates if the page applies to the specified objects
        /// Do not hold on to the objects here.
        /// </summary>
        bool IComPropertyPage.Applies(ESRI.ArcGIS.esriSystem.ISet objects)
        {
            if (objects == null || objects.Count == 0)
                return false;

            bool isEditable = false;
            objects.Reset();
            object testObject;
            while ((testObject = objects.Next()) != null)
            {
                if (testObject != null)
                {
                    isEditable = true;
                }
            }

            return isEditable;
        }

        /// <summary>
        /// Supplies the page with the object(s) to be edited
        /// </summary>
        void IComPropertyPage.SetObjects(ESRI.ArcGIS.esriSystem.ISet objects)
        {
            if (objects == null || objects.Count == 0)
                return;

            //Prepare to hold on to editable objects
            if (m_objectBag == null)
                m_objectBag = new Dictionary<string, object>();
            else
                m_objectBag.Clear();

            objects.Reset();
            object testObject;
            while ((testObject = objects.Next()) != null)
            {
                if (testObject != null)
                {
                    m_editor = testObject as IEditor;
                    break;
                }
            }

            if (m_editor != null)
            {
                IExtensionManager extensionManager = m_editor as IExtensionManager;

                //for (int index = 0; index < extensionManager.ExtensionCount; index++)
                //{
                //    System.Diagnostics.Debug.WriteLine(extensionManager.Extension[index].Name);
                //}

                UID osmEditorExtensionCLSID = new UIDClass();
                osmEditorExtensionCLSID.Value = "{faa799f0-bdc7-4ca4-af0c-a8d591c22058}";
                OSMEditorExtension osmEditorExtension = m_editor.Parent.FindExtensionByCLSID(osmEditorExtensionCLSID) as OSMEditorExtension;

                if (osmEditorExtension != null)
                {
                    m_osmbaseURL = osmEditorExtension.OSMBaseURL;
                }
            }
        }

        IComPropertyPageSite IComPropertyPage.PageSite
        {
            set
            {
                m_pageSite = value;
            }
        }

        /// <summary>
        /// Indicates if the Apply button should be enabled
        /// </summary>
        bool IComPropertyPage.IsPageDirty
        {
            get { return m_dirtyFlag; }
        }

        void IComPropertyPage.Apply()
        {
            if (m_dirtyFlag)
            {
                if (m_editor != null)
                {
                    IExtensionManager extensionManager = m_editor as IExtensionManager;

                    //for (int index = 0; index < extensionManager.ExtensionCount; index++)
                    //{
                    //    System.Diagnostics.Debug.WriteLine(extensionManager.Extension[index].Name);
                    //}

                    UID osmEditorExtensionCLSID = new UIDClass();
                    osmEditorExtensionCLSID.Value = "{faa799f0-bdc7-4ca4-af0c-a8d591c22058}";
                    OSMEditorExtension osmEditorExtension = m_editor.Parent.FindExtensionByCLSID(osmEditorExtensionCLSID) as OSMEditorExtension;

                    if (osmEditorExtension != null)
                    {
                        osmEditorExtension.OSMBaseURL = m_osmbaseURL;
                        osmEditorExtension.OSMDomainsXmlFilePath = txtOSMDomainFileLocation.Text;
                        osmEditorExtension.OSMFeaturePropertiesXmlFilePath = txtOSMFeaturePropertiesFileLocation.Text;

                        // makes the changes persisting throughout
                        osmEditorExtension.PersistOSMSettings();
                    }
                }

                SetPageDirty(false);

            }
        }

        void IComPropertyPage.Cancel()
        {
            if (m_dirtyFlag)
            {
                SetPageDirty(false);
            }
        }

        void IComPropertyPage.Show()
        {
            if (String.IsNullOrEmpty(m_osmbaseURL) == false)
            {
                txtOSMBaseURL.Text = m_osmbaseURL;
                m_dirtyFlag = false;
            }
        }

        void IComPropertyPage.Hide()
        {
        }

        string IComPropertyPage.HelpFile
        {
            get { return string.Empty; }
        }

        int IComPropertyPage.get_HelpContextID(int controlID)
        {
            return 0;
        }

        int IComPropertyPage.Priority
        {
            get
            {
                return 0;
            }
            set
            {
            }
        }

        #endregion

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            m_osmbaseURL = txtOSMBaseURL.Text;
            SetPageDirty(true);
        }

        private void btnFeatureDomains_Click(object sender, EventArgs e)
        {
            try
            {
                bool isDomain = false;

                if (sender.Equals(btnFeatureDomains))
                {
                    isDomain = true;
                }

                IGxDialog xmlFileSelectDialog = new GxDialogClass();
                xmlFileSelectDialog.AllowMultiSelect = false;
                if (isDomain)
                {
                    xmlFileSelectDialog.Title = resourceManager.GetString("OSMEditor_OSMPropertyPage_fileselect_title_domain");
                }
                else
                {
                    xmlFileSelectDialog.Title = resourceManager.GetString("OSMEditor_OSMPropertyPage_fileselect_title_feature");

                }
                xmlFileSelectDialog.RememberLocation = true;
                xmlFileSelectDialog.ButtonCaption = resourceManager.GetString("OSMEditor_OSMPropertyPage_fileselect_buttoncaption");

                xmlFileSelectDialog.ObjectFilter = new GxFilterXmlFiles();

                IEnumGxObject selectedConfigurationFile = null;

                if (xmlFileSelectDialog.DoModalOpen(m_editor.Parent.hWnd, out selectedConfigurationFile))
                {
                    if (selectedConfigurationFile == null)
                        return;

                    selectedConfigurationFile.Reset();

                    IGxFile xmlFile = selectedConfigurationFile.Next() as IGxFile;

                    if (xmlFile == null)
                        return;

                    if (isDomain)
                    {
                        txtOSMDomainFileLocation.Text = xmlFile.Path;
                    }
                    else
                    {
                        txtOSMFeaturePropertiesFileLocation.Text = xmlFile.Path;
                    }

                    SetPageDirty(true);
                }
            }
            catch
            {
            }
        }

        private void FileLocation_TextChanged(object sender, EventArgs e)
        {
            SetPageDirty(true);
        }
    }

    [Guid("87883C5A-FC7B-49C7-8445-D8F63F3E7A97")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("OSMEditor.GxFilterXmlFiles")]
    public class GxFilterXmlFiles : IGxObjectFilter
    {
        private ResourceManager resourceManager = null;

        public GxFilterXmlFiles()
        {
            try
            {
                resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.Editor.OSMFeatureInspectorStrings", this.GetType().Assembly);
            }
            catch { }
        }

        #region IGxObjectFilter Members

        public bool CanChooseObject(IGxObject @object, ref esriDoubleClickResult result)
        {
            bool canChoose = false;

            if (@object == null)
            {
                return canChoose;
            }

            IGxFile gxFile = @object as IGxFile;

            if (gxFile == null)
                return false;

            if (gxFile.Path.EndsWith(".xml"))
                canChoose = true;

            return canChoose;
        }

        public bool CanDisplayObject(IGxObject @object)
        {
            bool canDisplay = false;

            if (@object == null)
            {
                return canDisplay;
            }

            IGxFile gxFile = @object as IGxFile;

            if (gxFile != null)
            {
                if (gxFile.Path.EndsWith(".xml"))
                {
                    canDisplay = true;
                }
            }

            IGxFolder gxFolder = @object as IGxFolder;

            if (gxFolder != null)
            {
                canDisplay = true;
            }

            return canDisplay;
        }

        public bool CanSaveObject(IGxObject Location, string newObjectName, ref bool objectAlreadyExists)
        {
            return false;
        }

        public string Description
        {
            get
            {
                return resourceManager.GetString("OSMEditor_GxFilterXmlFiles_description");
            }
        }

        public string Name
        {
            get
            {
                return "SimpleXMLFileSelectFilter";
            }
        }

        #endregion
    }
}


text:
package com.hazelcast.internal.networking.nio;

import com.hazelcast.nio.tcp.TcpIpConnection_BaseTest;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class SelectNow_TcpIpConnection_BasicTest extends TcpIpConnection_BaseTest {

    @Before
    public void setup() throws Exception {
        eventLoopGroupFactory = new SelectNow_NioEventLoopGroupFactory();
        super.setup();
    }
}


text:
@interface CIAPILogOffResponse : CIAPIObjectResponse {
  BOOL LoggedOut;
}

// LogOut status
@property (readonly) BOOL LoggedOut;

@end


text:
namespace v8 {
namespace internal {

namespace {

#if V8_USE_ADDRESS_SANITIZER

const size_t kASanRedzoneBytes = 24;  // Must be a multiple of 8.

#else

#define ASAN_POISON_MEMORY_REGION(start, size) \
  do {                                         \
    USE(start);                                \
    USE(size);                                 \
  } while (false)

#define ASAN_UNPOISON_MEMORY_REGION(start, size) \
  do {                                           \
    USE(start);                                  \
    USE(size);                                   \
  } while (false)

const size_t kASanRedzoneBytes = 0;

#endif  // V8_USE_ADDRESS_SANITIZER

}  // namespace

// Segments represent chunks of memory: They have starting address
// (encoded in the this pointer) and a size in bytes. Segments are
// chained together forming a LIFO structure with the newest segment
// available as segment_head_. Segments are allocated using malloc()
// and de-allocated using free().

class Segment {
 public:
  void Initialize(Segment* next, size_t size) {
    next_ = next;
    size_ = size;
  }

  Segment* next() const { return next_; }
  void clear_next() { next_ = nullptr; }

  size_t size() const { return size_; }
  size_t capacity() const { return size_ - sizeof(Segment); }

  Address start() const { return address(sizeof(Segment)); }
  Address end() const { return address(size_); }

 private:
  // Computes the address of the nth byte in this segment.
  Address address(size_t n) const { return Address(this) + n; }

  Segment* next_;
  size_t size_;
};

Zone::Zone(base::AccountingAllocator* allocator)
    : allocation_size_(0),
      segment_bytes_allocated_(0),
      position_(0),
      limit_(0),
      allocator_(allocator),
      segment_head_(nullptr) {}

Zone::~Zone() {
  DeleteAll();
  DeleteKeptSegment();

  DCHECK(segment_bytes_allocated_ == 0);
}

void* Zone::New(size_t size) {
  // Round up the requested size to fit the alignment.
  size = RoundUp(size, kAlignment);

  // If the allocation size is divisible by 8 then we return an 8-byte aligned
  // address.
  if (kPointerSize == 4 && kAlignment == 4) {
    position_ += ((~size) & 4) & (reinterpret_cast<intptr_t>(position_) & 4);
  } else {
    DCHECK(kAlignment >= kPointerSize);
  }

  // Check if the requested size is available without expanding.
  Address result = position_;

  const size_t size_with_redzone = size + kASanRedzoneBytes;
  const uintptr_t limit = reinterpret_cast<uintptr_t>(limit_);
  const uintptr_t position = reinterpret_cast<uintptr_t>(position_);
  // position_ > limit_ can be true after the alignment correction above.
  if (limit < position || size_with_redzone > limit - position) {
    result = NewExpand(size_with_redzone);
  } else {
    position_ += size_with_redzone;
  }

  Address redzone_position = result + size;
  DCHECK(redzone_position + kASanRedzoneBytes == position_);
  ASAN_POISON_MEMORY_REGION(redzone_position, kASanRedzoneBytes);

  // Check that the result has the proper alignment and return it.
  DCHECK(IsAddressAligned(result, kAlignment, 0));
  allocation_size_ += size;
  return reinterpret_cast<void*>(result);
}

void Zone::DeleteAll() {
#ifdef DEBUG
  // Constant byte value used for zapping dead memory in debug mode.
  static const unsigned char kZapDeadByte = 0xcd;
#endif

  // Find a segment with a suitable size to keep around.
  Segment* keep = nullptr;
  // Traverse the chained list of segments, zapping (in debug mode)
  // and freeing every segment except the one we wish to keep.
  for (Segment* current = segment_head_; current;) {
    Segment* next = current->next();
    if (!keep && current->size() <= kMaximumKeptSegmentSize) {
      // Unlink the segment we wish to keep from the list.
      keep = current;
      keep->clear_next();
    } else {
      size_t size = current->size();
#ifdef DEBUG
      // Un-poison first so the zapping doesn't trigger ASan complaints.
      ASAN_UNPOISON_MEMORY_REGION(current, size);
      // Zap the entire current segment (including the header).
      memset(current, kZapDeadByte, size);
#endif
      DeleteSegment(current, size);
    }
    current = next;
  }

  // If we have found a segment we want to keep, we must recompute the
  // variables 'position' and 'limit' to prepare for future allocate
  // attempts. Otherwise, we must clear the position and limit to
  // force a new segment to be allocated on demand.
  if (keep) {
    Address start = keep->start();
    position_ = RoundUp(start, kAlignment);
    limit_ = keep->end();
    // Un-poison so we can re-use the segment later.
    ASAN_UNPOISON_MEMORY_REGION(start, keep->capacity());
#ifdef DEBUG
    // Zap the contents of the kept segment (but not the header).
    memset(start, kZapDeadByte, keep->capacity());
#endif
  } else {
    position_ = limit_ = 0;
  }

  allocation_size_ = 0;
  // Update the head segment to be the kept segment (if any).
  segment_head_ = keep;
}

void Zone::DeleteKeptSegment() {
#ifdef DEBUG
  // Constant byte value used for zapping dead memory in debug mode.
  static const unsigned char kZapDeadByte = 0xcd;
#endif

  DCHECK(segment_head_ == nullptr || segment_head_->next() == nullptr);
  if (segment_head_ != nullptr) {
    size_t size = segment_head_->size();
#ifdef DEBUG
    // Un-poison first so the zapping doesn't trigger ASan complaints.
    ASAN_UNPOISON_MEMORY_REGION(segment_head_, size);
    // Zap the entire kept segment (including the header).
    memset(segment_head_, kZapDeadByte, size);
#endif
    DeleteSegment(segment_head_, size);
    segment_head_ = nullptr;
  }

  DCHECK(segment_bytes_allocated_ == 0);
}

// Creates a new segment, sets it size, and pushes it to the front
// of the segment chain. Returns the new segment.
Segment* Zone::NewSegment(size_t size) {
  Segment* result = reinterpret_cast<Segment*>(allocator_->Allocate(size));
  segment_bytes_allocated_ += size;
  if (result != nullptr) {
    result->Initialize(segment_head_, size);
    segment_head_ = result;
  }
  return result;
}

// Deletes the given segment. Does not touch the segment chain.
void Zone::DeleteSegment(Segment* segment, size_t size) {
  segment_bytes_allocated_ -= size;
  allocator_->Free(segment, size);
}

Address Zone::NewExpand(size_t size) {
  // Make sure the requested size is already properly aligned and that
  // there isn't enough room in the Zone to satisfy the request.
  DCHECK_EQ(size, RoundDown(size, kAlignment));
  DCHECK(limit_ < position_ ||
         reinterpret_cast<uintptr_t>(limit_) -
                 reinterpret_cast<uintptr_t>(position_) <
             size);

  // Compute the new segment size. We use a 'high water mark'
  // strategy, where we increase the segment size every time we expand
  // except that we employ a maximum segment size when we delete. This
  // is to avoid excessive malloc() and free() overhead.
  Segment* head = segment_head_;
  const size_t old_size = (head == nullptr) ? 0 : head->size();
  static const size_t kSegmentOverhead = sizeof(Segment) + kAlignment;
  const size_t new_size_no_overhead = size + (old_size << 1);
  size_t new_size = kSegmentOverhead + new_size_no_overhead;
  const size_t min_new_size = kSegmentOverhead + size;
  // Guard against integer overflow.
  if (new_size_no_overhead < size || new_size < kSegmentOverhead) {
    V8::FatalProcessOutOfMemory("Zone");
    return nullptr;
  }
  if (new_size < kMinimumSegmentSize) {
    new_size = kMinimumSegmentSize;
  } else if (new_size > kMaximumSegmentSize) {
    // Limit the size of new segments to avoid growing the segment size
    // exponentially, thus putting pressure on contiguous virtual address space.
    // All the while making sure to allocate a segment large enough to hold the
    // requested size.
    new_size = Max(min_new_size, kMaximumSegmentSize);
  }
  if (new_size > INT_MAX) {
    V8::FatalProcessOutOfMemory("Zone");
    return nullptr;
  }
  Segment* segment = NewSegment(new_size);
  if (segment == nullptr) {
    V8::FatalProcessOutOfMemory("Zone");
    return nullptr;
  }

  // Recompute 'top' and 'limit' based on the new segment.
  Address result = RoundUp(segment->start(), kAlignment);
  position_ = result + size;
  // Check for address overflow.
  // (Should not happen since the segment is guaranteed to accomodate
  // size bytes + header and alignment padding)
  DCHECK(reinterpret_cast<uintptr_t>(position_) >=
         reinterpret_cast<uintptr_t>(result));
  limit_ = segment->end();
  DCHECK(position_ <= limit_);
  return result;
}

}  // namespace internal
}  // namespace v8


text:
package com.beanframework.console.web;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.beanframework.common.AdminBaseController;
import com.beanframework.menu.init.MenuInit;
import com.beanframework.user.init.UserInit;

@Controller
@RequestMapping(ConsoleWebConstants.PATH_ROOT)
public class InitializeConsoleController extends AdminBaseController {

	@Autowired
	private MenuInit menuInit;

	@Autowired
	private UserInit userInit;

	@Value(ConsoleWebConstants.VAR_DIR)
	private String VAR_DIR;

	@RequestMapping(value = ConsoleWebConstants.PATH_INITIALIZE, method = { RequestMethod.GET, RequestMethod.POST })
	public String menu(Model model, @RequestParam Map<String, Object> allRequestParams, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (request.getMethod().equalsIgnoreCase("POST")) {

			StringBuilder sb = new StringBuilder();

			try {

				boolean menu = parseBoolean("menu", allRequestParams);
				if(menu){
					menuInit.init();
					sb.append("Menu was initialized successfully. \n");
				}

				boolean user = parseBoolean("user", allRequestParams);
				if(user){
					userInit.init();
					sb.append("User was initialized successfully. \n");
				}

				boolean log = parseBoolean("log", allRequestParams);
				if(log){
					File archiveFolder = new File(VAR_DIR+"/log/archive");
					if(archiveFolder.exists()){
						FileUtils.cleanDirectory(new File(VAR_DIR+"/log/archive"));
					}
					sb.append("Log was initialized successfully. \n");
				}

				model.addAttribute(PARAM_MESSAGE, sb.toString());
			} catch (Exception e) {
				model.addAttribute(PARAM_MESSAGE, sb.toString());
				model.addAttribute(PARAM_ERROR, e.getMessage());
			}
			return redirect(ConsoleWebConstants.PATH_ROOT + ConsoleWebConstants.PATH_INITIALIZE, model, redirectAttributes);
		}

		return page(ConsoleWebConstants.PAGE_INITIALIZE, model, allRequestParams);
	}

}


text:
#pragma once

#include "Vector2.h"
#include "Vector3.h"
#include "Vector4.h"

//Various data type used by the rasterizer

typedef Vector3 PixelRGB;				//type define Vector3 as PixelRGB type
typedef Vector4 PixelRGBA;				//type define Vector4 as PixelRGBA type
typedef Vector4 Colour4;				//type define Vector4 as Colour4 type

//struct for a 2D vertex
typedef struct _Vertex2d
{
	Colour4 colour;					//Colour property of the vertex
	Vector2 position;				//Coordinate (position) of the vertex
} Vertex2d;

//struct for a 2D circle
typedef struct _Circle2D
{
	Colour4 colour;					//colour of the circle
	Vector2 centre;					//location of the centre of the circle
	float radius;					//radius of the circle
} Circle2D;


text:
import os
import sys

import sponsors

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

version = sponsors.__version__

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    print("You probably want to also tag the version now:")
    print("  git tag -a %s -m 'version %s'" % (version, version))
    print("  git push --tags")
    sys.exit()

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

setup(
    name='django-sponsors',
    version=version,
    description="""Django App to easily manage project sponsors""",
    long_description=readme + '\n\n' + history,
    author='Miguel Fiandor',
    author_email='miguel.fiandor.gutierrez@gmail.com',
    url='https://github.com/miguelfg/django-sponsors',
    packages=[
        'sponsors',
    ],
    include_package_data=True,
    install_requires=['python-dateutil', 'django-stdimage'],
    license="MIT",
    zip_safe=False,
    keywords=['django', 'sponsors', 'sponsor', 'logos', 'logo'],
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Framework :: Django',
        'Framework :: Django :: 1.6',
        'Framework :: Django :: 1.7',
        'Framework :: Django :: 1.8',
    ],
)


text:
package org.jasig.openregistry.test.domain;

import org.openregistry.core.domain.*;
import org.openregistry.core.domain.sor.SorDisclosureSettings;
import org.openregistry.core.domain.sor.SorName;
import org.openregistry.core.domain.sor.SorRole;
import org.openregistry.core.service.DisclosureRecalculationStrategy;

import java.util.*;

/**
 * @version $Revision$ $Date$
 * @since 0.1
 */
public class MockPerson implements Person {

    private ActivationKey activationKey = new MockActivationKey(UUID.randomUUID().toString(), new Date(), new Date());

	private Set<Role> roles = new HashSet<Role>();

    private long id = 1L;

    private Set<MockName> names = new HashSet<MockName>();

    private MockEmailAddress mockEmailAddress = new MockEmailAddress();

    private MockPhoneNumber mockPhoneNumber = new MockPhoneNumber();

    private MockDisclosureSettings mockDisclosureSettings;

    private final Set<Identifier> identifiers = new HashSet<Identifier>();
    private final Set<IdCard> idcards = new HashSet<IdCard>();

    private Map<String, String> attributes = new HashMap<String, String>();

    private String gender;

    private Date dob;

    /**
     * Generates a new active, non-expired person with Identifier of type NETID
     */
    public MockPerson() {
        this("testId", false, false);
    }

    /**
     * Generates a person with Identifier of type NETID with supplied value
     */
    public MockPerson(final String identifierValue, final boolean notActive, final boolean expired) {

        if (notActive && expired) {
            throw new IllegalArgumentException("You're crazy!");
        }

        final Date startDate;
        final Date endDate;

        if (notActive) {
            startDate = new Date(System.currentTimeMillis() + 50000);
            endDate = new Date(System.currentTimeMillis() + 50000000);
        } else if (expired) {
            startDate = new Date(System.currentTimeMillis() - 500000);
            endDate = new Date(System.currentTimeMillis() - 50000);
        } else {
            startDate = new Date();
            endDate = new Date(System.currentTimeMillis() + 50000000);
        }

        this.activationKey = new MockActivationKey("key", startDate, endDate);
        this.addIdentifier(new MockIdentifierType("NETID", false), identifierValue);
    }

    public MockPerson(long id) {
        this.id = id;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    @Override
    public ContactEmailAddress getPreferredContactEmailAddress() {
        return this.mockEmailAddress;
    }

    @Override
    public ContactPhone getPreferredContactPhoneNumber() {
        return this.mockPhoneNumber;
    }

    @Override
    public Map<String, String> getAttributes() {
        return this.attributes;
    }

    public void addRole(final Role role) {
        this.roles.add(role);
    }

    public Set<? extends Name> getNames() {
        return this.names;
    }

    public Name addName() {
        final MockName name = new MockName();
        this.names.add(name);
        return name;
    }

    public Name addName(Type type) {
        final MockName name = new MockName(type);
        this.names.add(name);
        return name;
    }

    @Override
    public void addName(final SorName sorName) {
        final MockName name = new MockName();
        name.setType(sorName.getType());
        name.setGiven(sorName.getGiven());
        name.setFamily(sorName.getFamily());
        name.setMiddle(sorName.getMiddle());
        name.setPrefix(sorName.getPrefix());
        name.setSuffix(sorName.getSuffix());
        name.setSourceNameId(sorName.getId());
        this.names.add(name);

        //To change body of implemented methods use File | Settings | File Templates.
    }

    public Set<Role> getRoles() {
        return this.roles;
    }

    public Role addRole(final SorRole sorRole) {
        final MockRole mockRole = new MockRole(sorRole);
        this.roles.add(mockRole);
        return mockRole;
    }

    public Set<Identifier> getIdentifiers() {
       return identifiers;
    }

    @Override
    public Set<IdCard> getIdCards() {
        return idcards;
    }

    public Name getPreferredName() {
        return null;
    }

    public Name getOfficialName() {
        Set<? extends Name> names = this.getNames();
    	for(Name name: names) {
    		if (name.isOfficialName()) {
    			return name;
    		}
    	}
    	return null;
    }

    public String getGender() {
        return this.gender;
    }

    public Date getDateOfBirth() {
        return this.dob;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dob = dateOfBirth;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void calculateDisclosureSettings(SorDisclosureSettings ds) {
    	if (ds != null) {
    		this.mockDisclosureSettings =
    			new MockDisclosureSettings(ds.getDisclosureCode(), ds.getLastUpdateDate(), ds.isWithinGracePeriod());
    	} else {
    		this.mockDisclosureSettings = null;
    	}
    }
	public DisclosureSettings getDisclosureSettings() {
		return this.mockDisclosureSettings;
	}

	public void setDisclosureSettingInfo(String disclosureCode,
			boolean isWithinGracePeriod, Date lastUpdatedDate) {
		this.mockDisclosureSettings = new MockDisclosureSettings
			(disclosureCode, lastUpdatedDate, isWithinGracePeriod);
	}

    public Identifier addIdentifier(IdentifierType identifierType, String value) {
    	MockIdentifier mid = new MockIdentifier(this, identifierType, value);
    	this.identifiers.add(mid);
    	return mid;
    }
    public IdCard addIDCard( String cardNumber,String cardSecurityValue, String barCode){
        MockIdCard card =new MockIdCard(this,cardNumber,cardSecurityValue,barCode);
        this.idcards.add(card);
        return card;
    }

    @Override
    public IdCard addIDCard(IdCard idCard) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
	public void setIdentifierNotified(IdentifierType identifierType, Date date) {
		if (!identifierType.isNotifiable()) {
			throw new IllegalArgumentException("Only notifiable identifiers can have a notification date set");
		}
		if (identifierType == null) {
			throw new IllegalArgumentException("Identifier type must be supplied");
		}

		Identifier identiferToUpdate = this.getPrimaryIdentifiersByType().get(identifierType.getName());
		if (identiferToUpdate != null && identiferToUpdate.getNotificationDate() == null) {
			identiferToUpdate.setNotificationDate(date);
		} else {
			throw new IllegalStateException("Identifier to be updated was not found");
		}
	}

    public Name addOfficialName() {
        MockName name = new MockName();
        name.setOfficialName(true);
        return name;
    }

    public Name addPreferredName() {
        MockName name = new MockName();
        name.setPreferredName(true);
        return name;
    }

    public void setPreferredName(Name name) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public Role pickOutRole(Type affiliationType) {
        for(final Role r : this.roles) {
            if(r.getAffiliationType().getDescription().equals(affiliationType.getDescription())) {
                return r;
            }
        }
        return null;
    }

    public Role pickOutRole(String affiliation) {
        for(final Role r : this.roles) {
            if(r.getAffiliationType().getDescription().equals(affiliation)) {
                return r;
            }
        }
        return null;
    }

    @Override
    public Map<String, Identifier> getPrimaryIdentifiersByType() {
        final Map<String,Identifier> primaryIdentifiers = new HashMap<String,Identifier>();

        for (final Identifier identifier : getIdentifiers()) {
            if (identifier.isPrimary()) {
                primaryIdentifiers.put(identifier.getType().getName(), identifier);
            }
        }

        return primaryIdentifiers;
    }

    @Override
    public Map<String, Deque<Identifier>> getIdentifiersByType() {
        final Map<String, Deque<Identifier>> identifiersByType = new HashMap<String, Deque<Identifier>>();

        for (final Identifier identifier : this.identifiers) {
            final String identifierType = identifier.getType().getName();
            Deque<Identifier> listIdentifiers = identifiersByType.get(identifierType);

            if (listIdentifiers == null) {
                listIdentifiers = new ArrayDeque<Identifier>();
                identifiersByType.put(identifierType, listIdentifiers);
            }

            if (identifier.isPrimary()) {
                listIdentifiers.addFirst(identifier);
            } else {
                listIdentifiers.addLast(identifier);
            }
        }

        return identifiersByType;
    }

    public ActivationKey generateNewActivationKey(Date start, Date end) {
        this.activationKey = new MockActivationKey(UUID.randomUUID().toString(), start, end);
        return this.activationKey;
    }

    public ActivationKey generateNewActivationKey(Date end) {
        this.activationKey = new MockActivationKey(UUID.randomUUID().toString(), new Date(), end);
        return this.activationKey;
    }

    public ActivationKey getCurrentActivationKey() {
        return this.activationKey;
    }

    public void removeCurrentActivationKey() {
        this.activationKey = null;
    }

    public Role findRoleBySoRRoleId(final Long sorRoleId) {
        for (final Role role : this.roles) {
            if (sorRoleId.equals(role.getSorRoleId())) {
                return role;
            }
        }
        return null;
    }

    @Override
    public Identifier findIdentifierByValue(String identifierType, String identifierValue) {
        final Map<String, Deque<Identifier>> identifiersByType = getIdentifiersByType();
        Deque<Identifier> ids = identifiersByType.get(identifierType);
        if(ids == null) {
             return null;
        }
        Iterator<Identifier> iter = ids.iterator();
        Identifier id = null;
        while(iter.hasNext()) {
            id = iter.next();
            if(id.getValue().equals(identifierValue)) {
                return id;
            }
        }
        return null;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final MockPerson that = (MockPerson) o;

        return id == that.id;
    }

    @Override
    public int hashCode() {
        return 31 * (int) (id ^ (id >>> 32));
    }

    @Override
    public String toString() {
        return "MockPerson{" +
                "activationKey=" + activationKey +
                ", roles=" + roles +
                ", id=" + id +
                ", names=" + names +
                ", mockEmailAddress=" + mockEmailAddress +
                ", mockPhoneNumber=" + mockPhoneNumber +
                ", mockDisclosureSettings=" + mockDisclosureSettings +
                ", identifiers=" + identifiers +
                ", gender='" + gender + '\'' +
                ", dob=" + dob +
                '}';
    }

    @Override
    public IdCard getPrimaryIdCard() {
        if(this.idcards.size()==0) return null;

        for(IdCard card:idcards){
            if (card.isPrimary())
                return card;
        }

        return null;
    }
    public void setAttributes(Map<String, String> attributes){
        this.attributes=attributes;
    }
}


text:
package shared

type Device map[string]string
type Devices map[string]Device

func (list Devices) ContainsName(k string) bool {
	if list[k] != nil {
		return true
	}
	return false
}

func (d Device) get(key string) string {
	return d[key]
}

func (list Devices) Contains(k string, d Device) bool {
	// If it didn't exist, it's different
	if list[k] == nil {
		return false
	}

	old := list[k]

	return deviceEquals(old, d)
}

func deviceEquals(old Device, d Device) bool {
	// Check for any difference and addition/removal of properties
	for k, _ := range d {
		if d[k] != old[k] {
			return false
		}
	}

	for k, _ := range old {
		if d[k] != old[k] {
			return false
		}
	}

	return true
}

func (old Devices) Update(newlist Devices) (map[string]Device, map[string]Device, map[string]Device) {
	rmlist := map[string]Device{}
	addlist := map[string]Device{}
	updatelist := map[string]Device{}

	for key, d := range old {
		if !newlist.Contains(key, d) {
			rmlist[key] = d
		}
	}

	for key, d := range newlist {
		if !old.Contains(key, d) {
			addlist[key] = d
		}
	}

	for key, d := range addlist {
		srcOldDevice := rmlist[key]
		var oldDevice Device
		err := DeepCopy(&srcOldDevice, &oldDevice)
		if err != nil {
			continue
		}

		srcNewDevice := newlist[key]
		var newDevice Device
		err = DeepCopy(&srcNewDevice, &newDevice)
		if err != nil {
			continue
		}

		for _, k := range []string{"limits.max", "limits.read", "limits.write", "limits.egress", "limits.ingress"} {
			delete(oldDevice, k)
			delete(newDevice, k)
		}

		if deviceEquals(oldDevice, newDevice) {
			delete(rmlist, key)
			delete(addlist, key)
			updatelist[key] = d
		}
	}

	return rmlist, addlist, updatelist
}

func (newBaseDevices Devices) ExtendFromProfile(currentFullDevices Devices, newDevicesFromProfile Devices) error {
	// For any entry which exists in a profile and doesn't in the container config, add it

	for name, newDev := range newDevicesFromProfile {
		if curDev, ok := currentFullDevices[name]; ok {
			newBaseDevices[name] = curDev
		} else {
			newBaseDevices[name] = newDev
		}
	}

	return nil
}


text:
package org.intellij.plugins.relaxNG.compact.psi.impl;

import com.intellij.icons.AllIcons;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.meta.PsiMetaOwner;
import com.intellij.psi.meta.PsiPresentableMetaData;
import com.intellij.util.IncorrectOperationException;
import org.intellij.plugins.relaxNG.compact.RncTokenTypes;
import org.intellij.plugins.relaxNG.compact.psi.*;
import org.intellij.plugins.relaxNG.compact.psi.util.EscapeUtil;
import org.intellij.plugins.relaxNG.compact.psi.util.RenameUtil;
import org.intellij.plugins.relaxNG.model.Define;
import org.intellij.plugins.relaxNG.model.resolve.DefinitionResolver;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Map;
import java.util.Set;

public class RncDefineImpl extends RncElementImpl implements RncDefine, PsiMetaOwner {
  public RncDefineImpl(ASTNode node) {
    super(node);
  }

  @Override
  public void accept(@NotNull RncElementVisitor visitor) {
    visitor.visitDefine(this);
  }

  @Override
  public void accept(Visitor visitor) {
    visitor.visitDefine(this);
  }

  @Override
  public String getName() {
    final ASTNode node = getNameNode();
    return EscapeUtil.unescapeText(node);
  }

  @Override
  public PsiElement getNameElement() {
    return getNameNode().getPsi();
  }

  @NotNull
  public ASTNode getNameNode() {
    final ASTNode node = getNode().findChildByType(RncTokenTypes.IDENTIFIERS);
    assert node != null;
    return node;
  }

  @Override
  public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException {
    final ASTNode node = getNameNode();
    node.getTreeParent().replaceChild(node, RenameUtil.createIdentifierNode(getManager(), name));
    return this;
  }

  @Override
  @Nullable
  public RncPattern getPattern() {
    return findChildByClass(RncPattern.class);
  }

  @Override
  public PsiReference getReference() {
    if (getParent() instanceof RncInclude) {
      final TextRange range = TextRange.from(0, getNameNode().getTextLength());
      return new PsiReferenceBase<RncDefine>(this, range, true) {
        @Override
        public PsiElement resolve() {
          return RncDefineImpl.this;
        }

        @Override
        @NotNull
        public Object[] getVariants() {
          final RncInclude parent = (RncInclude)getParent();
          final RncFile referencedFile = parent.getReferencedFile();
          if (referencedFile == null) {
            return EMPTY_ARRAY;
          }
          final RncGrammar grammar = referencedFile.getGrammar();
          if (grammar == null) {
            return EMPTY_ARRAY;
          }

          final Map<String, Set<Define>> map = DefinitionResolver.getAllVariants(grammar);
          if (map != null) {
            return map.keySet().toArray();
          }
          return EMPTY_ARRAY;
        }
      };
    }
    return super.getReference();
  }

  @Override
  @Nullable
  public Icon getIcon(int flags) {
    return AllIcons.Nodes.Property;
  }

  public boolean isMetaEnough() {
    return true;
  }

  @Override
  @Nullable
  public PsiMetaData getMetaData() {
    return new MyMetaData();
  }

  private class MyMetaData implements PsiMetaData, PsiPresentableMetaData {
    /*public boolean processDeclarations(PsiElement context, PsiScopeProcessor processor, PsiSubstitutor substitutor, PsiElement lastElement, PsiElement place) {
      return false;
    }*/

    @Override
    @Nullable
    public Icon getIcon() {
      return RncDefineImpl.this.getIcon(0);
    }

    @Override
    public String getTypeName() {
      return "Pattern Definition";
    }

    @Override
    public PsiElement getDeclaration() {
      return RncDefineImpl.this;
    }

    @Override
    @NonNls
    public String getName(PsiElement context) {
      return RncDefineImpl.this.getName();
    }

    @Override
    @NonNls
    public String getName() {
      return RncDefineImpl.this.getName();
    }

    @Override
    public void init(PsiElement element) {
    }
  }
}


text:
layout: base
title:  'POS tags'
generated: 'true'
permalink: rm/pos/index.html
---

# POS tags

{% include rm-pos-table.html %}

----------

Alphabetical listing

{% assign sorted = site.rm-pos | sort: 'title' %}{% for p in sorted %}
* [{{ p.title }}](): {{ p.shortdef }}{% endfor %}


text:
<?php
namespace components\documents\controllers;

use core\AbstractController;

class DocumentsController extends AbstractController
{
    /**
     * keep this out of the parent controller since we want
     * to have custom arguements to pass in.
     *
     * @param int $id
     * @param int $name
     */
    public function get($id, $name){
        $this->model->setView($this->view);
        $this->model->get($id, $name);
    }
}


text:
package org.apache.drill.exec.physical.impl.join;

import java.util.List;

import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.exec.ops.ExecutorFragmentContext;
import org.apache.drill.exec.physical.config.MergeJoinPOP;
import org.apache.drill.exec.physical.impl.BatchCreator;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.calcite.rel.core.JoinRelType;

import com.google.common.base.Preconditions;

public class MergeJoinCreator implements BatchCreator<MergeJoinPOP> {
  @Override
  public MergeJoinBatch getBatch(ExecutorFragmentContext context, MergeJoinPOP config, List<RecordBatch> children)
      throws ExecutionSetupException {
    Preconditions.checkArgument(children.size() == 2);
    if(config.getJoinType() == JoinRelType.RIGHT){
      return new MergeJoinBatch(config.flipIfRight(), context, children.get(1), children.get(0));
    }else{
      return new MergeJoinBatch(config, context, children.get(0), children.get(1));
    }
  }
}