text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

using XenAdmin.Controls;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAdmin.Properties;
using XenAPI;
using XenCenterLib;

namespace XenAdmin.Wizards.HAWizard_Pages
{
    public partial class AssignPriorities : XenTabPage
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private IXenConnection connection;

        private bool showStartOrderAndDelay;

        private readonly CollectionChangeEventHandler VM_CollectionChangedWithInvoke;
        private readonly QueuedBackgroundWorker m_worker;

        /// <summary>
        /// May not be set to null.
        /// </summary>
        public new IXenConnection Connection
        {
            set
            {
                if (value == null)
                    throw new ArgumentNullException();

                if (connection != null)
                    DeregisterEvents();

                this.connection = value;

                RegisterEvents();

                showStartOrderAndDelay = !Helpers.HaIgnoreStartupOptions(connection);
                if (!showStartOrderAndDelay)
                {
                    colStartOrder.Visible = false;
                    colDelay.Visible = false;

                    nudOrder.Visible = nudStartDelay.Visible = false;
                    labelStartOrder.Visible = labelStartDelay.Visible = labelStartDelayUnits.Visible = false;
                }

                UpdateMenuItems();
                PopulateVMs();

                haNtolIndicator.Connection = value;
                haNtolIndicator.Settings = getCurrentSettings();
            }
        }

        private void UpdateMenuItems()
        {
            List<VM.HA_Restart_Priority> restartPriorities = VM.GetAvailableRestartPriorities(connection);

            //When this line: m_dropDownButtonRestartPriority.ContextMenuStrip = this.contextMenuStrip
            //was called in the designer a "dummy" item was added to the contextMenuStrip by the m_dropDownButtonRestartPriority,
            //however here it is cleared so no need to remove it explicitly later when contextMenuStrip.Items is called
            contextMenuStrip.Items.Clear();

            foreach (var restartPriority in restartPriorities)
            {
                var menuItem = contextMenuStrip.Items.Add(Helpers.RestartPriorityI18n(restartPriority));
                menuItem.Tag = restartPriority;
                menuItem.Click += priority_Click;
            }
        }

        /// <summary>
        /// Called when the current IXenConnection's VM dictionary changes.
        /// </summary>
        private void VM_CollectionChanged(object sender, CollectionChangeEventArgs e)
        {
            Program.AssertOnEventThread();

            VM vm = (VM)e.Element;
            switch (e.Action)
            {
                case CollectionChangeAction.Add:
                    vm.PropertyChanged -= vm_PropertyChanged;
                    vm.PropertyChanged += vm_PropertyChanged;
                    AddVmRow(vm);
                    UpdateVMsAgility(new List<VM> {vm});
                    break;
                case CollectionChangeAction.Remove:
                    vm.PropertyChanged -= vm_PropertyChanged;
                    RemoveVmRow(vm);
                    break;
            }
        }

        /// <summary>
        /// The Ntol from the HaNtolIndicator control contained within.
        /// </summary>
        public long Ntol
        {
            get
            {
                return haNtolIndicator.Ntol;
            }
        }

        /// <summary>
        /// Whether the user has made any changes to VM restart priorities on the server.
        /// </summary>
        public bool ChangesMade { get; private set; }

        public AssignPriorities()
        {
            InitializeComponent();
            VM_CollectionChangedWithInvoke = Program.ProgramInvokeHandler(VM_CollectionChanged);

            haNtolIndicator.UpdateInProgressChanged += haNtolIndicator_UpdateInProgressChanged;

            nudStartDelay.Maximum = long.MaxValue;
            nudOrder.Maximum = long.MaxValue;

            m_worker = new QueuedBackgroundWorker();
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            DeregisterEvents();

            if (disposing && (components != null))
            {
                haNtolIndicator.UpdateInProgressChanged -= haNtolIndicator_UpdateInProgressChanged;
                components.Dispose();
            }

            StopNtolUpdate();

            base.Dispose(disposing);
        }

        private void RegisterEvents()
        {
            // Add listeners
            connection.Cache.RegisterCollectionChanged<VM>(VM_CollectionChangedWithInvoke);

            foreach (VM vm in connection.Cache.VMs)
            {
                vm.PropertyChanged -= vm_PropertyChanged;
                vm.PropertyChanged += vm_PropertyChanged;
            }
        }

        private void DeregisterEvents()
        {
            // Remove listeners
            connection.Cache.DeregisterCollectionChanged<VM>(VM_CollectionChangedWithInvoke);

            foreach (VM vm in connection.Cache.VMs)
                vm.PropertyChanged -= vm_PropertyChanged;
        }

        /// <summary>
        /// Sets all agile VMs to state 'Protected' and all non-agile VMs to 'Restart if possible'.
        /// Important: call before setting the Connection property.
        /// </summary>
        internal bool ProtectVmsByDefault { get; set; }

        internal void StartNtolUpdate()
        {
            haNtolIndicator.StartNtolUpdate();
        }

        internal void StopNtolUpdate()
        {
            haNtolIndicator.StopNtolUpdate();
        }

        /// <summary>
        /// Must be called on the event thread.
        /// </summary>
        private void PopulateVMs()
        {
            Program.AssertOnEventThread();

            try
            {
                dataGridViewVms.SuspendLayout();
                dataGridViewVms.Rows.Clear();

                var newRows = new List<DataGridViewRow>();
                var vms = connection.Cache.VMs.Where(v => v.HaCanProtect(Properties.Settings.Default.ShowHiddenVMs));

                // see if HA is being activated for the first time.
                bool firstTime = IsHaActivatedFirstTime(vms);

                foreach (VM vm in connection.Cache.VMs)
                {
                    if (!vm.HaCanProtect(Properties.Settings.Default.ShowHiddenVMs))
                        continue;

                    // Create a new row for this VM.
                    // The priority for this row is either initially null (which means 'fill in the restart priority with
                    // Protected/Restart if possible when we've determined if the VM is agile'), or its current restart priority.
                    // The first case is for the HA wizard when priorities are being configured for the first time,
                    // the second is for the edit dialog, when HA is already enabled.

                    VM.HA_Restart_Priority? priority = firstTime ? (VM.HA_Restart_Priority?)null : vm.HARestartPriority;
                    var row = new VmWithSettingsRow(vm, priority);
                    newRows.Add(row);
                }

                dataGridViewVms.Rows.AddRange(newRows.ToArray());
                var addedVms = from row in dataGridViewVms.Rows.Cast<VmWithSettingsRow>() select row.Vm;
                UpdateVMsAgility(addedVms);
            }
            finally
            {
                dataGridViewVms.ResumeLayout();
            }
        }

        /// <summary>
        /// Starts a new background thread that updates the displayed agility status for each VM.
        /// </summary>
        private void UpdateVMsAgility(IEnumerable<VM> vms)
        {
            Debug.Assert(connection != null, "Connection property must have been set to non-null before calling this function");

            //worker starts on UI (main) thread
            m_worker.RunWorkerAsync((sender, arg) => worker_DoWork(null, vms), worker_RunWorkerCompleted);
        }

        private object worker_DoWork(object sender, object arg)
        {
            var vms = arg as IEnumerable<VM>;
            Debug.Assert(vms != null);

            Session session = connection.DuplicateSession();
            var results = new Dictionary<VM, string>();

            foreach (VM vm in vms)
            {
                try
                {
                    VM.assert_agile(session, vm.opaque_ref);
                    results[vm] = null;
                }
                catch (Failure failure)//The VM wasn't agile
                {
                    results[vm] = failure.ErrorDescription[0];
                }
            }

            return results;
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                log.Error(e.Error);
                return;
            }

            var result = e.Result as Dictionary<VM, string>;
            Debug.Assert(result != null);

            foreach (var pair in result)
            {
                VM vm = pair.Key;
                string nonAgileReason = pair.Value;
                bool isNowAgile = nonAgileReason == null;

                //worker started on main thread => this event handler will be on
                //main thread too, so no need to invoke

                VmWithSettingsRow row = findItemFromVM(vm);
                if (row == null)
                    return;

                // We previously had no restart priority assigned => protectVmsByDefault.
                // Now we know whether the VM is agile, so we can assign it the highest protection available.
                if (row.RestartPriority == null)
                {
                    Debug.Assert(ProtectVmsByDefault);

                    var priority = isNowAgile ? VM.HaHighestProtectionAvailable(connection) : VM.HA_Restart_Priority.BestEffort;

                    row.UpdateRestartPriority(priority);
                    haNtolIndicator.Settings = getCurrentSettings();
                }
                else if (!isNowAgile
                        && row.RestartPriority != VM.HA_Restart_Priority.BestEffort
                        && row.RestartPriority != VM.HA_Restart_Priority.DoNotRestart)
                {
                    row.UpdateRestartPriority(VM.HA_Restart_Priority.BestEffort);
                    haNtolIndicator.Settings = getCurrentSettings();
                }

                row.UpdateAgile(isNowAgile);
                row.FriendlyNonAgileReason = nonAgileReason;
            }
            updateButtons();
        }

        private bool IsHaActivatedFirstTime(IEnumerable<VM> vms)
        {
            return ProtectVmsByDefault && vms.All(v => string.IsNullOrEmpty(v.ha_restart_priority));
        }

        private void AddVmRow(VM vm)
        {
            Program.AssertOnEventThread();

            if (!vm.HaCanProtect(Properties.Settings.Default.ShowHiddenVMs))
                return;

            // see if HA is being activated for the first time
            var vms = connection.Cache.VMs.Where(v => v.HaCanProtect(Properties.Settings.Default.ShowHiddenVMs));
            bool firstTime = IsHaActivatedFirstTime(vms);

            VM.HA_Restart_Priority? priority = firstTime ? (VM.HA_Restart_Priority?)null : vm.HARestartPriority;
            var row = new VmWithSettingsRow(vm, priority);
            dataGridViewVms.Rows.Add(row);
        }

        private void RemoveVmRow(VM vm)
        {
            Program.AssertOnEventThread();

            var row = findItemFromVM(vm);
            if (row != null)
                dataGridViewVms.Rows.Remove(row);
        }

        /// <summary>
        /// Finds the ListViewItem for the given VM. Will return null if no corresponding item could be found.
        /// Must be called on the event thread.
        /// </summary>
        private VmWithSettingsRow findItemFromVM(VM vm)
        {
            Program.AssertOnEventThread();
            return dataGridViewVms.Rows.Cast<VmWithSettingsRow>().FirstOrDefault(r => r.Vm == vm);
        }

        private void vm_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            Program.Invoke(this, () =>
                {
                    VM vm = (VM)sender;
                    if (vm == null)
                        return;

                    // Find row for VM
                    var row = findItemFromVM(vm);

                    try
                    {
                        dataGridViewVms.SuspendLayout();

                        if (row == null)
                            AddVmRow(vm);
                        else
                        {
                            row.UpdateVm(vm);
                            row.SetAgileCalculating();
                        }

                        UpdateVMsAgility(new List<VM> {vm});
                    }
                    finally
                    {
                        dataGridViewVms.ResumeLayout();
                    }
                });
        }

        private void haNtolIndicator_UpdateInProgressChanged(object sender, EventArgs e)
        {
            // Signal to anyone who cares that this page is good to continue, or not.
            OnPageUpdated();

            if (!haNtolIndicator.UpdateInProgress)
            {
                if (haNtolIndicator.Ntol == -1)
                {
                    labelHaStatus.Text = Messages.HA_UNABLE_TO_CALCULATE_MESSAGE;
                    labelHaStatus.ForeColor = Color.Red;
                    pictureBoxStatus.Image = Resources._000_Alert2_h32bit_16;
                    return;
                }

                if (haNtolIndicator.Overcommitted || haNtolIndicator.Ntol == 0)
                {
                    labelHaStatus.Text = Messages.HA_OVERCOMMIT_MESSAGE;
                    labelHaStatus.ForeColor = Color.Red;
                    pictureBoxStatus.Image = Resources._000_Alert2_h32bit_16;
                    return;
                }

                labelHaStatus.Text = string.Format(Messages.HA_GUARANTEED_MESSAGE, haNtolIndicator.NtolMax);
                labelHaStatus.ForeColor = SystemColors.ControlText;
                pictureBoxStatus.Image = Resources._000_Tick_h32bit_16;
            }
        }

        private void dataGridViewVms_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
            {
                try
                {
                    dataGridViewVms.SuspendLayout();
                    dataGridViewVms.SelectAll();
                }
                finally
                {
                    dataGridViewVms.ResumeLayout();
                }
            }
        }

        /// <summary>
        /// Called when the user clicks one of the restart priorities in the context menu.
        /// </summary>
        private void priority_Click(object sender, EventArgs e)
        {
            var menuitem = (ToolStripMenuItem)sender;
            VM.HA_Restart_Priority pri = (VM.HA_Restart_Priority)menuitem.Tag;

            bool changesMade = false;
            foreach (var row in dataGridViewVms.SelectedRows.Cast<VmWithSettingsRow>())
            {
                if (row.RestartPriority != pri)
                {
                    changesMade = true;
                    row.UpdateRestartPriority(pri);
                }
            }

            if (changesMade)
            {
                ChangesMade = true;
                haNtolIndicator.Settings = getCurrentSettings();
                // Will trigger a ntol update under this revised plan
                updateButtons();
            }
        }

        /// <summary>
        /// Gets the current (uncommitted) VM restart priorities. Must be called on the GUI thread.
        /// </summary>
        public Dictionary<VM, VM.HA_Restart_Priority> getCurrentSettings()
        {
            Program.AssertOnEventThread();
            Dictionary<VM, VM.HA_Restart_Priority> result = new Dictionary<VM, VM.HA_Restart_Priority>();

            foreach (var row in dataGridViewVms.Rows.Cast<VmWithSettingsRow>())
            {
                // If the restart priority is null, it means we don't know if the VM is agile yet, and we have
                // protectVmsByDefault == true.
                result[row.Vm] = row.RestartPriority ?? VM.HA_Restart_Priority.BestEffort;
            }
            return result;
        }

        private void dataGridViewVms_SelectionChanged(object sender, EventArgs e)
        {
            updateButtons();
        }

        private void m_dropDownButtonRestartPriority_Click(object sender, EventArgs e)
        {
            var selectedRows = dataGridViewVms.SelectedRows.Cast<VmWithSettingsRow>();

            foreach (ToolStripMenuItem item in contextMenuStrip.Items)
            {
                var itemRestartPriority = ((VM.HA_Restart_Priority)item.Tag);
                item.Checked = selectedRows.Count() > 0 && selectedRows.All(s => s.RestartPriority == itemRestartPriority);
            }
        }

        private void updateButtons()
        {
            Program.AssertOnEventThread();

            var selectedRows = dataGridViewVms.SelectedRows.Cast<VmWithSettingsRow>();

            if (dataGridViewVms.SelectedRows.Count == 0)
            {
                m_dropDownButtonRestartPriority.Enabled = false;
                m_dropDownButtonRestartPriority.Text = "";
                if (showStartOrderAndDelay)
                {
                    nudOrder.Enabled = nudStartDelay.Enabled = false;
                    nudOrder.Text = nudStartDelay.Text = "";
                }
                return;
            }

            // if there is a VM with null priority in the selection disable all buttons. We are waiting on the background thread
            // to see if the VM is agile before giving it a starting value
            if (selectedRows.Any(r => r.RestartPriority == null))
            {
                m_dropDownButtonRestartPriority.Enabled = true;
                m_dropDownButtonRestartPriority.Text = "";
                if (showStartOrderAndDelay)
                {
                    nudOrder.Enabled = nudStartDelay.Enabled = true;
                    nudOrder.Text = nudStartDelay.Text = "";
                }
                return;
            }

            m_dropDownButtonRestartPriority.Enabled = true;

            //now set the drop down button text

            bool allSamePriority = false;

            foreach (ToolStripMenuItem item in contextMenuStrip.Items)
            {
                VM.HA_Restart_Priority itemRestartPriority = (VM.HA_Restart_Priority)item.Tag;

                if (selectedRows.All(r => r.RestartPriority == itemRestartPriority))
                {
                    allSamePriority = true;
                    m_dropDownButtonRestartPriority.Text = Helpers.RestartPriorityI18n(itemRestartPriority);
                    break;
                }
            }

            if (!allSamePriority && dataGridViewVms.SelectedRows.Count > 1)
            {
                m_dropDownButtonRestartPriority.Text = Messages.HA_ASSIGN_PRIORITIES_MIXED_PROTECTION_LEVELS;
            }

            // set the order and delay NUDs
            if (showStartOrderAndDelay)
            {
                nudOrder.Enabled = nudStartDelay.Enabled = true;

                var orderDistList = (from row in selectedRows select row.StartOrder).Distinct();
                nudOrder.Text = orderDistList.Count() == 1 ? orderDistList.ElementAt(0).ToString() : "";

                var delayDistList = (from row in selectedRows select row.StartDelay).Distinct();
                nudStartDelay.Text = delayDistList.Count() == 1 ? delayDistList.ElementAt(0).ToString() : "";
            }

            // check that all the VMs selected in the list are agile and make sure the protect button is disabled with the relevant reason
            VmWithSettingsRow nonAgileRow = selectedRows.FirstOrDefault(r => !r.IsAgile);

            // Now set the buttons and tooltips)
            foreach (ToolStripMenuItem menuItem in contextMenuStrip.Items)
            {
                var priority = (VM.HA_Restart_Priority)menuItem.Tag;

                if (VM.HaPriorityIsRestart(connection, priority))
                {
                    menuItem.Enabled = priority == VM.HA_Restart_Priority.AlwaysRestartHighPriority
                                           ? (nonAgileRow == null && Helpers.CowleyOrGreater(connection))
                                           : (nonAgileRow == null);

                    menuItem.ToolTipText = (nonAgileRow == null)
                                               ? ""
                                               : nonAgileRow.FriendlyNonAgileReason;
                }
                else
                {
                    menuItem.Enabled = true;
                }
            }
        }

        private void nudOrder_ValueChanged(object sender, EventArgs e)
        {
            long newValue = (long)nudOrder.Value;
            bool changesMade = false;

            foreach (var row in dataGridViewVms.SelectedRows.Cast<VmWithSettingsRow>())
            {
                if (row.StartOrder != newValue)
                {
                    changesMade = true;
                    row.UpdateStartOrder(newValue);
                }
            }

            if (changesMade)
            {
                ChangesMade = true;
                updateButtons();
            }
        }

        private void nudStartDelay_ValueChanged(object sender, EventArgs e)
        {
            long newValue = (long)nudStartDelay.Value;
            bool changesMade = false;

            foreach (var row in dataGridViewVms.SelectedRows.Cast<VmWithSettingsRow>())
            {
                if (row.StartDelay != newValue)
                {
                    changesMade = true;
                    row.UpdateStartDelay(newValue);
                }
            }

            if (changesMade)
            {
                ChangesMade = true;
                updateButtons();
            }
        }

        /// <summary>
        /// Gets the current (uncommitted) VM startup options. Must be called on the GUI thread.
        /// </summary>
        /// <returns></returns>
        public Dictionary<VM, VMStartupOptions> GetCurrentStartupOptions()
        {
            Program.AssertOnEventThread();
            Dictionary<VM, VMStartupOptions> result = new Dictionary<VM, VMStartupOptions>();

            foreach (var curRow in dataGridViewVms.Rows.Cast<VmWithSettingsRow>())
            {
                result[curRow.Vm] = new VMStartupOptions(curRow.StartOrder,
                                                         curRow.StartDelay,
                                                         curRow.RestartPriority ?? VM.HA_Restart_Priority.BestEffort);
            }
            return result;
        }

        private void linkLabelTellMeMore_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Help.HelpManager.Launch("HaNtolZero");
        }

        #region XentabPage overrides

        public override string Text
        {
            get { return Messages.HAWIZARD_ASSIGNRIORITIESPAGE_TEXT; }
        }

        public override string PageTitle
        {
            get
            {
                return showStartOrderAndDelay ? Messages.HAWIZARD_ASSIGNRIORITIESPAGE_TITLE : Messages.HAWIZARD_ASSIGNRIORITIESPAGE_TITLE_NOORDER;
            }
        }

        public override bool EnableNext()
        {
            return !haNtolIndicator.UpdateInProgress && Ntol >= 0 && !haNtolIndicator.Overcommitted;
        }

        public override void PageCancelled()
        {
            StopNtolUpdate();
        }

        public override void PageLoaded(PageLoadedDirection direction)
        {
            base.PageLoaded(direction);
            StartNtolUpdate();
        }

        public override void PageLeave(PageLoadedDirection direction, ref bool cancel)
        {
            StopNtolUpdate();
            base.PageLeave(direction, ref cancel);
        }

        #endregion

        #region Nested classes

        private class VmWithSettingsRow : DataGridViewRow
        {
            private readonly DataGridViewImageCell cellImage;
            private readonly DataGridViewTextBoxCell cellVm;
            private readonly DataGridViewTextBoxCell cellRestartPriority;
            private readonly DataGridViewTextBoxCell cellStartOrder;
            private readonly DataGridViewTextBoxCell cellDelay;
            private readonly DataGridViewTextBoxCell cellAgile;
            private string _nonAgileReason;

            public VM Vm { get; private set; }
            public long StartDelay { get; private set; }
            public long StartOrder { get; private set; }
            public VM.HA_Restart_Priority? RestartPriority { get; private set; }
            public bool IsAgile { get; private set; }

            /// <summary>
            /// Returns a short version of the agility violation for the error type stored in NonAgileReason.
            /// Returns empty string if there is no error.
            /// For a more detailed, technical description use the error translation in FriendlyErrorNames.resx
            /// </summary>
            public string FriendlyNonAgileReason
            {
                get
                {
                    switch (_nonAgileReason)
                    {
                        case null:
                            return "";
                        case "HA_CONSTRAINT_VIOLATION_SR_NOT_SHARED":
                            return Messages.NOT_AGILE_SR_NOT_SHARED;
                        case "HA_CONSTRAINT_VIOLATION_NETWORK_NOT_SHARED":
                            return Messages.NOT_AGILE_NETWORK_NOT_SHARED;
                        case "VM_HAS_VGPU":
                            return Messages.NOT_AGILE_VM_HAS_VGPU;
                        default:
                            // We shouldn't really be here unless we have not iterated all the return errors from vm.assert_agile
                            return Messages.NOT_AGILE_UNKOWN;
                    }
                }
                set
                {
                    _nonAgileReason = value;
                }
            }

            public VmWithSettingsRow(VM vm, VM.HA_Restart_Priority? priority)
            {
                cellImage = new DataGridViewImageCell {ValueType = typeof(Image)};
                cellVm = new DataGridViewTextBoxCell();
                cellRestartPriority = new DataGridViewTextBoxCell();
                cellStartOrder = new DataGridViewTextBoxCell();
                cellDelay = new DataGridViewTextBoxCell();
                cellAgile = new DataGridViewTextBoxCell();
                Cells.AddRange(cellImage, cellVm, cellRestartPriority, cellStartOrder, cellDelay, cellAgile);

                UpdateVm(vm);
                UpdateRestartPriority(priority);
                UpdateStartOrder(vm.order);
                UpdateStartDelay(vm.start_delay);
                SetAgileCalculating();
            }

            public void UpdateVm(VM vm)
            {
                Vm = vm;
                cellImage.Value = Images.GetImage16For(vm);
                cellVm.Value = vm.Name;
            }

            public void UpdateStartDelay(long startDelay)
            {
                StartDelay = startDelay;
                cellDelay.Value = string.Format(Messages.TIME_SECONDS, startDelay);
            }

            public void UpdateStartOrder(long startOrder)
            {
                StartOrder = startOrder;
                cellStartOrder.Value = startOrder.ToString();
            }

            public void UpdateRestartPriority(VM.HA_Restart_Priority? restartPriority)
            {
                RestartPriority = restartPriority;
                cellRestartPriority.Value = Helpers.RestartPriorityI18n(restartPriority);
            }

            public void UpdateAgile(bool isAgile)
            {
                IsAgile = isAgile;
                cellAgile.Value = isAgile.ToYesNoStringI18n();
            }

            public void SetAgileCalculating()
            {
                cellAgile.Value = Messages.HA_CALCULATING_AGILITY;
            }
        }

        #endregion
    }
}


text:
package de.frvabe.bpm.camunda;

import java.io.InputStream;

import org.camunda.bpm.dmn.engine.DmnDecision;
import org.camunda.bpm.dmn.engine.DmnDecisionTableResult;
import org.camunda.bpm.dmn.engine.DmnEngine;
import org.camunda.bpm.dmn.engine.DmnEngineConfiguration;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;

/**
 * A listener that is registered to listen to all process activity events..
 */
public class GlobalExecutionListener implements ExecutionListener {

    private final DmnEngine dmnEngine;
    final DmnDecision eventLogDecision;

    /**
     * Default NoArgs constructor.
     */
    public GlobalExecutionListener() {
        dmnEngine = DmnEngineConfiguration.createDefaultDmnEngineConfiguration().buildEngine();
        InputStream inputStream =
                GlobalExecutionListener.class.getResourceAsStream("/dmn/event-log-config.dmn");
        eventLogDecision = dmnEngine.parseDecision("eventLog", inputStream);
    }

    @Override
    public void notify(final DelegateExecution execution) throws Exception {
        System.out.println("Entering activity (activitId=" + execution.getCurrentActivityId()
                + ", eventName=" + execution.getEventName() + ") ...");
        handleProcessLog(execution);
    }

    /**
     * Checks if the current execution matches the configuration. If {@code yes} performs desired
     * operation; here just prints a message that was specified in the DMN model.
     *
     * @param execution the current execution
     */
    private void handleProcessLog(final DelegateExecution execution) {
        if (execution.getCurrentActivityId() != null && execution.getEventName() != null) {
            VariableMap variables =
                    Variables.putValue("activityId", execution.getCurrentActivityId())
                            .putValue("eventName", execution.getEventName());
            DmnDecisionTableResult result =
                    dmnEngine.evaluateDecisionTable(eventLogDecision, variables);
            if (!result.isEmpty()) {
                // the configuration matched the event
                System.out.println(">>> " + result.getSingleEntry().toString());
            }
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.jreaper.plugins.reaper.task;

import com.jreaper.model.entity.seed.SeedChannel;

import java.util.List;

/**
 * Created by zarubin on 14.01.2015.
 */
public interface IReaperTaskExecutor {

    void execute(SeedChannel seedChannel);
}


text:
'use strict';

var resolve = require( 'path' ).resolve;
var readFile = require( '@stdlib/fs/read-file' );
var bifurcateByAsync = require( './../lib' );

var files = [
	resolve( __dirname, '..', 'package.json' ),
	resolve( __dirname, '..', 'README.md' ),
	resolve( __dirname, '..', 'beep.boop.md' )
];

function done( error, result ) {
	if ( error ) {
		throw error;
	}
	console.log( result );
}

function predicate( file, next ) {
	var opts = {
		'encoding': 'utf8'
	};
	readFile( file, opts, onFile );

	function onFile( error ) {
		if ( error ) {
			return next( null, false );
		}
		next( null, true );
	}
}

bifurcateByAsync( files, predicate, done );


text:
package parallelai.spyglass.hbase;

import java.io.IOException;

import cascading.tap.SinkMode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.Progressable;

/**
 * For writing Map/Reduce output into an HBase table
 */
public class HBaseOutputFormat extends
FileOutputFormat<ImmutableBytesWritable, Put> implements JobConfigurable {

  /** JobConf parameter that specifies the output table */
  public static final String OUTPUT_TABLE = "hbase.mapred.outputtable";
  private final Log LOG = LogFactory.getLog(HBaseOutputFormat.class);

  private SinkMode sinkMode = SinkMode.UPDATE;

  @Override
  public void configure(JobConf conf) {
      sinkMode = SinkMode.valueOf(
        conf.get(
            String.format(
                HBaseConstants.SINK_MODE, conf.get(HBaseOutputFormat.OUTPUT_TABLE)
            )
        )
      );
  }

  @Override
  @SuppressWarnings("unchecked")
  public RecordWriter getRecordWriter(FileSystem ignored,
      JobConf job, String name, Progressable progress) throws IOException {

    // expecting exactly one path

    String tableName = job.get(OUTPUT_TABLE);
    HTable table = null;
    try {
      table = new HTable(HBaseConfiguration.create(job), tableName);
    } catch(IOException e) {
      LOG.error(e);
      throw e;
    }
    table.setAutoFlush(job.getBoolean(String.format(HBaseConstants.AUTO_FLUSH, tableName),false));
    HBaseRecordWriter recordWriter = new HBaseRecordWriter(table);
    recordWriter.setSinkMode(sinkMode);
    return recordWriter;
  }

  @Override
  public void checkOutputSpecs(FileSystem ignored, JobConf job)
  throws IOException {

    String tableName = job.get(OUTPUT_TABLE);
    if(tableName == null) {
      throw new IOException("Must specify table name");
    }
  }
}


text:
package org.springframework.rules.reporting;

import java.util.Stack;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.rules.constraint.Constraint;
import org.springframework.core.style.ToStringCreator;
import org.springframework.rules.constraint.*;

/**
 * @author Keith Donald
 */
public abstract class ValidationResultsBuilder {
    protected static final Log logger = LogFactory
            .getLog(ValidationResultsBuilder.class);
    private Constraint top;
    private Stack levels = new Stack();

    public void pushAnd() {
        And and = new And();
        add(and);
    }

    public void pushOr() {
        Or or = new Or();
        add(or);
    }

    public void pushNot() {
        Not not = new Not();
        add(not);
    }

    private void add(Constraint predicate) {
        if (top != null) {
            if (top instanceof Not) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Negating predicate [" + predicate + "]");
                }
                ((Not)this.top).setConstraint(predicate);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Aggregating nested predicate [" + predicate
                            + "]");
                }
                ((CompoundConstraint)this.top).add(predicate);
            }
        }
        levels.push(predicate);
        this.top = predicate;
        if (logger.isDebugEnabled()) {
            logger.debug("Predicate [" + predicate + "] is at the top.");
        }
    }

    public void push(Constraint constraint) {
        if (this.top instanceof CompoundConstraint) {
            if (logger.isDebugEnabled()) {
                logger.debug("Adding constraint [" + constraint + "]");
            }
            ((CompoundConstraint)this.top).add(constraint);
        } else if (this.top instanceof Not) {
            if (logger.isDebugEnabled()) {
                logger.debug("Negating constraint [" + constraint + "]");
            }
            ((Not)this.top).setConstraint(constraint);
        } else if (this.top == null) {
            constraintViolated(constraint);
        } else {
            throw new IllegalArgumentException(constraint.toString());
        }
    }

    public void pop(boolean result) {
        Constraint p = (Constraint)levels.pop();
        if (logger.isDebugEnabled()) {
            logger.debug("Top [" + p + "] popped; result was " + result
                    + "; stack now has " + levels.size() + " elements");
        }
        if (levels.isEmpty()) {
            if (!result) {
                constraintViolated(top);
            } else {
                constraintSatisfied();
            }
            top = null;
        } else {
            this.top = (Constraint)levels.peek();
            if (result) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Removing compound predicate [" + p
                            + "]; tested true.");
                }
                ((CompoundConstraint)this.top).remove(p);
            }
        }
    }

    protected void clear() {
        levels.clear();
        top = null;
    }

    public boolean negated() {
        if (levels.size() == 0) {
            return false;
        }
        return peek() instanceof Not;
    }

    private Constraint peek() {
        return (Constraint)levels.peek();
    }

    protected abstract void constraintViolated(Constraint constraint);
    protected abstract void constraintSatisfied();

    public String toString() {
        return new ToStringCreator(this).append("topOfStack", top).append(
                "levelsStack", levels).toString();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.Reactive.Testing;

using Naru.Core;
using Naru.WPF.MVVM;
using Naru.WPF.Tests.Scheduler;
using Naru.WPF.ViewModel;

using NUnit.Framework;

namespace Naru.WPF.Tests.ViewModel
{
    [TestFixture]
    public class ReactiveMultiSelectCollectionTests
    {
        [Test]
        public void when_SelectedItem_is_set_then_the_SelectedItemChanged_pumps_the_value()
        {
            var testSchedulerProvider = new TestDispatcherSchedulerProvider();

            var result = new List<int>();

            var reactiveMultiSelectCollection = new ReactiveMultiSelectCollection<int>(new BindableCollection<int>(testSchedulerProvider),
                                                                                testSchedulerProvider);
            reactiveMultiSelectCollection.SelectedItemsChanged
                                          .Subscribe(x => result = x.ToList());

            var selectedItem = Enumerable.Range(0,1).ToList();

            reactiveMultiSelectCollection.SelectedItems = selectedItem;

            Assert.That(selectedItem.SequenceEqual(result));
        }

        [Test]
        public void when_SelectedItem_is_set_then_the_SelectedItems_INPC_is_fired()
        {
            var testSchedulerProvider = new TestDispatcherSchedulerProvider();

            var reactiveMultiSelectCollection = new ReactiveMultiSelectCollection<int>(new BindableCollection<int>(testSchedulerProvider),
                                                                                testSchedulerProvider);

            var result = false;

            reactiveMultiSelectCollection.PropertyChanged += (sender, args) =>
                                                             {
                                                                 var propertyName = PropertyExtensions.ExtractPropertyName(() => reactiveMultiSelectCollection.SelectedItems);
                                                                 if (args.PropertyName == propertyName)
                                                                 {
                                                                     result = true;
                                                                 }
                                                             };

            reactiveMultiSelectCollection.SelectedItems = Enumerable.Range(0, 1).ToList();
            ((TestScheduler)testSchedulerProvider.Dispatcher.RX).AdvanceBy(1);

            Assert.That(result, Is.True);
        }
    }
}


text:
package org.webrtc.kite.config.client;

/**
 * The Enum Orientation.
 */
public enum Orientation {
  /**
   * The portrait.
   */
  portrait,
  /**
   * The landscape.
   */
  landscape
}


text:
package com.dmonsters.models;

import com.dmonsters.entity.EntityWoman;

import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.MathHelper;

public class ModelWoman extends ModelBase
{
  //fields
    ModelRenderer head;
    ModelRenderer chest;
    ModelRenderer belly;
    ModelRenderer hips;
    ModelRenderer upperleftleg;
    ModelRenderer upperrightleg;
    ModelRenderer upperrightarm;
    ModelRenderer upperleftarm;
    ModelRenderer lowerrightleg;
    ModelRenderer lowerlefttleg;
    ModelRenderer lowerleftarm;
    ModelRenderer lowerrightarm;

  public ModelWoman()
  {
    textureWidth = 64;
    textureHeight = 64;

    head = new ModelRenderer(this, 0, 0);
    head.addBox(-3.466667F, 0F, -7F, 7, 7, 7);
    head.setRotationPoint(0F, 14F, -7F);
    head.setTextureSize(64, 32);
    head.mirror = true;
    setRotation(head, 0F, 0F, 0F);
    chest = new ModelRenderer(this, 0, 15);
    chest.addBox(0F, 0F, 0F, 8, 4, 7);
    chest.setRotationPoint(-4F, 13F, -7F);
    chest.setTextureSize(64, 32);
    chest.mirror = true;
    setRotation(chest, 0.1115358F, 0F, 0F);
    belly = new ModelRenderer(this, 0, 27);
    belly.addBox(0F, 0F, 0F, 6, 3, 4);
    belly.setRotationPoint(-3F, 13F, 0F);
    belly.setTextureSize(64, 32);
    belly.mirror = true;
    setRotation(belly, -0.1115358F, 0F, 0F);
    hips = new ModelRenderer(this, 0, 35);
    hips.addBox(0F, 0F, 0F, 8, 4, 5);
    hips.setRotationPoint(-4F, 13F, 4F);
    hips.setTextureSize(64, 32);
    hips.mirror = true;
    setRotation(hips, -0.2230717F, 0F, 0F);
    upperleftleg = new ModelRenderer(this, 39, 14);
    upperleftleg.addBox(-2F, -2F, 0F, 4, 4, 8);
    upperleftleg.setRotationPoint(3F, 16F, 8F);
    upperleftleg.setTextureSize(64, 32);
    upperleftleg.mirror = true;
    setRotation(upperleftleg, 0.3490659F, 0.7853982F, 0F);
    upperrightleg = new ModelRenderer(this, 39, 1);
    upperrightleg.addBox(-2F, -2F, 0F, 4, 4, 8);
    upperrightleg.setRotationPoint(-3F, 16F, 8F);
    upperrightleg.setTextureSize(64, 32);
    upperrightleg.mirror = true;
    setRotation(upperrightleg, 0.3490659F, -0.7853982F, 0F);
    upperrightarm = new ModelRenderer(this, 0, 45);
    upperrightarm.addBox(-3F, -2F, -7F, 3, 3, 7);
    upperrightarm.setRotationPoint(-3F, 15F, -6F);
    upperrightarm.setTextureSize(64, 32);
    upperrightarm.mirror = true;
    setRotation(upperrightarm, -0.3490659F, 0.7853982F, 0F);
    upperleftarm = new ModelRenderer(this, 21, 45);
    upperleftarm.addBox(0F, -2F, -7F, 3, 3, 7);
    upperleftarm.setRotationPoint(3F, 15F, -6F);
    upperleftarm.setTextureSize(64, 32);
    upperleftarm.mirror = true;
    setRotation(upperleftarm, -0.3490659F, -0.7853982F, 0F);
    lowerrightleg = new ModelRenderer(this, 51, 27);
    lowerrightleg.addBox(0F, 0F, 0F, 3, 8, 3);
    lowerrightleg.setRotationPoint(-1F, 0F, 7F);
    lowerrightleg.setTextureSize(64, 32);
    lowerrightleg.mirror = true;
    setRotation(lowerrightleg, 0F, 0F, 0F);
    upperrightleg.addChild(lowerrightleg);
    lowerlefttleg = new ModelRenderer(this, 38, 27);
    lowerlefttleg.addBox(0F, 0F, 0F, 3, 8, 3);
    lowerlefttleg.setRotationPoint(-2F, 0F, 7F);
    lowerlefttleg.setTextureSize(64, 32);
    lowerlefttleg.mirror = true;
    setRotation(lowerlefttleg, 0F, 0F, 0F);
    upperleftleg.addChild(lowerlefttleg);
    lowerleftarm = new ModelRenderer(this, 42, 45);
    lowerleftarm.addBox(0F, 0F, 0F, 2, 8, 2);
    lowerleftarm.setRotationPoint(0F, 0F, -8F);
    lowerleftarm.setTextureSize(64, 64);
    lowerleftarm.mirror = true;
    setRotation(lowerleftarm, 0F, 0F, 0F);
    upperleftarm.addChild(lowerleftarm);
    lowerrightarm = new ModelRenderer(this, 51, 45);
    lowerrightarm.addBox(0F, 0F, 0F, 2, 8, 2);
    lowerrightarm.setRotationPoint(-2F, 0F, -8F);
    lowerrightarm.setTextureSize(64, 64);
    lowerrightarm.mirror = true;
    setRotation(lowerrightarm, 0F, 0F, 0F);
    upperrightarm.addChild(lowerrightarm);
  }

  public void render(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale)
  {
	  super.render(entityIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale);
      this.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale, entityIn);

      if (this.isChild)
      {
          float f = 2.0F;
          GlStateManager.pushMatrix();
    	  lowerrightleg.render(scale);
          lowerleftarm.render(scale);
          lowerrightarm.render(scale);
          GlStateManager.popMatrix();
      }
      else
      {
    	  head.render(scale);
    	  chest.render(scale);
    	  belly.render(scale);
    	  hips.render(scale);
    	  upperrightarm.render(scale);
    	  upperleftarm.render(scale);
    	  upperleftleg.render(scale);
    	  upperrightleg.render(scale);
      }
  }

  private void setRotation(ModelRenderer model, float x, float y, float z)
  {
    model.rotateAngleX = x;
    model.rotateAngleY = y;
    model.rotateAngleZ = z;
  }

  public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn)
  {
    super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn);
    this.head.rotateAngleX = headPitch * 0.017453292F;
    this.head.rotateAngleY = netHeadYaw * 0.017453292F;
    this.upperleftarm.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount;
    this.upperrightarm.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount;
    this.upperleftleg.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount;
    this.upperrightleg.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount;
  }

}


text:
package com.wanasit.chrono.filter;

import java.util.ArrayList;
import java.util.List;

import com.wanasit.chrono.ChronoOption;
import com.wanasit.chrono.ParsedResult;
import com.wanasit.chrono.refiner.RefinerAbstract;

public abstract class Filter extends RefinerAbstract{

    public abstract boolean isValid(String text, ChronoOption options, ParsedResult result);

    @Override
    public List<ParsedResult> refine(List<ParsedResult> results, String text, ChronoOption options) {

        List<ParsedResult> filteredResults = new ArrayList<ParsedResult>();
        for (ParsedResult result : results) {
            if (isValid(text, options, result)) filteredResults.add(result);
        }

        return filteredResults;
    }

}


text:
class Derived : public Base {
  void foo();
};


text:
public class FirstSeenByMyClassLoader {
  public static void $inline$bar() {
  }

  public static void $noinline$bar() {
    try {
      System.out.println("In $noinline$bar");
    } catch (Throwable t) { /* Ignore */ }
  }
}


text:
/*  	class defs for a doubly linked list of pointers and
 *  	is basically copied out of Stroustup's C++ book Section 7.3.2
 *  	slists are used to implement lists of nodes and lists of edges,
 *  	in particular the successor and predecessor lists for nodes
 */

#ifndef slist_included
#define slist_included

typedef void* ent;

class slink {
    slink* next;
    slink* prev;
    ent e;
    slink(ent a, slink* n, slink* p) { e=a; next=n; prev=p; }
friend class slist;
friend class slist_iterator_forw;
friend class slist_iterator_back;
friend class slist_iterator;
friend class q_link;
friend class edge_queue;
friend class constr_queue;
};

class slist {
    slink* head;
    slink* tail;
    int del_link(slink* l);
public:
    int insert(ent a);
    int insertlist(slist* ll);
    int append(ent a);
    int append_unique(ent a);
    int appendlist(slist* ll);
    int find(ent a);
    int del(ent a);
    ent get();
    ent gethead();
    ent gettail();
    ent getbefore (ent a);
    int addbefore(ent a, ent b);
    ent first()         { return head ? head->e : 0; }
    ent second()        { return ((head)&&(head->next)) ? head->next->e : 0; }
    void clear();
    int length();
    void newlist()      { head=0; tail=0; }
    int operator==(slist& ll);
    int equal(slist& ll);
    int includes(slist& ll);
    void del_all();

    slist()             { head=0; tail=0; }
    slist(ent a)        { head=new slink(a, 0, 0); tail=head;}
    ~slist()            { clear(); }
friend class slist_iterator_forw;
friend class slist_iterator_back;
friend class slist_iterator;
friend class edge_queue;
friend class constr_queue;
};

class slist_iterator_forw {
    slink* ce;
    slist* cs;
public:
    slist_iterator_forw(slist& s)       { cs = &s; ce = 0; }

    ent operator()() { slink* ll;
        if (ce == 0) { ce = cs->head;  ll = ce; }
        else { ce = ce->next; ll = (ce==cs->head)?0:ce; }
        return ll ? ll->e : 0;
    }

    ent back() { slink* ll;
        if (ce == 0) { ce = cs->tail;  ll = ce; }
        else { ce = ce->prev; ll = (ce==cs->tail)?0:ce; }
        return ll ? ll->e : 0;
    }

};

class slist_iterator_back {
    slink* ce;
    slist* cs;
public:
    slist_iterator_back(slist& s)       { cs = &s; ce = 0; }

    ent operator()() { slink* ll;
        if (ce == 0) { ce = cs->tail;  ll = ce; }
        else { ce = ce->prev; ll = (ce==cs->tail)?0:ce; }
        return ll ? ll->e : 0;
    }
};

#endif

/*
   START-LOG-------------------------------------------

   $Log: slist.h  $
   Revision 1.2 2000/07/10 23:03:47EDT ktrans
   mainline merge from Visual C++ 6/ISO (extensionless) standard header files
 * Revision 1.2.1.5  1993/05/13  20:24:17  sergey
 * Initial Revision.
 *

   END-LOG---------------------------------------------

*/


text:
using namespace std;

enum SEARCH_TYPE
{
	NORMAL,
	BOOL,
	PHRASE_SEARCH
};

enum TOP_K_MODE
{
	TOP_K_OFF,
	TOP_K_HEAP,
	TOP_K_CHAMPION_LIST,
	TOP_K_STATIC_QUALITY_SCORE,
	TOP_K_CLUSTER_PRUNING
};

enum SYNONYM
{
	SYNONYM_OFF,
	SYNONYM_ON
};

class Interpreter
{
public:
	Interpreter(){_search_type = NORMAL; _top_k_mode = TOP_K_OFF; _synonym_mode = SYNONYM_OFF;};
	~Interpreter();
	int GetSearchType(){return _search_type;};
	int GetTopKMode(){return _top_k_mode;};
	int GetSynonymMode(){return _synonym_mode;};
	vector<pair<string,string> > ProcessQuery(InvertedIndex* II, const string query);
private:
	int _search_type;
	int _top_k_mode;
	int _synonym_mode;
};
#endif


text: export { Alarm20 as default } from "../../";


text: 2d side by side shooter game for ios


text:
namespace iroha {
namespace opt {

class OptimizerLogSection {
 public:
  OptimizerLogSection() : is_html_(false){};

  string dumpFileName(const string &base, const string &suffix) {
    string fn = base + "." + suffix;
    if (is_html_) {
      fn = fn + ".html";
    }
    return fn;
  }

  ostringstream dump_;
  bool is_html_;
};

OptimizerLog::OptimizerLog() : enabled_(false), current_pass_index_(0) {}

OptimizerLog::~OptimizerLog() { STLDeleteSecondElements(&sections_); }

void OptimizerLog::Enable() { enabled_ = true; }

bool OptimizerLog::IsEnabled() { return enabled_; }

void OptimizerLog::WriteToFiles(const string &baseFn) {
  for (auto &p : sections_) {
    OptimizerLogSection *ls = p.second;
    string fn = ls->dumpFileName(baseFn, p.first);
    ofstream os(fn);
    if (ls->is_html_) {
      writer::Writer::WriteDumpHeader(os);
    }
    os << ls->dump_.str();
    if (ls->is_html_) {
      writer::Writer::WriteDumpFooter(os);
    }
  }
  // Index of generated dump files.
  ofstream os(baseFn + ".html");
  writer::Writer::WriteDumpHeader(os);
  for (auto &p : sections_) {
    OptimizerLogSection *ls = p.second;
    string linkFn = ls->dumpFileName(baseFn, p.first);
    linkFn = File::BaseName(linkFn);
    os << "<a href=\"" << linkFn << "\">" << linkFn << "\n";
  }
  writer::Writer::WriteDumpFooter(os);
}

void OptimizerLog::DumpTable(const ITable *tab) {
  writer::Writer::DumpTable(tab, GetSection(current_file_name_)->dump_);
}

ostream &OptimizerLog::GetDumpStream() {
  return GetSection(current_file_name_)->dump_;
}

ostream &OptimizerLog::Table(const ITable *tab) { return table_[tab]; }

ostream &OptimizerLog::State(const IState *st) { return state_[st]; }

ostream &OptimizerLog::Insn(const IInsn *insn) { return insn_[insn]; }

ostream &OptimizerLog::Reg(const IRegister *reg) { return reg_[reg]; }

string OptimizerLog::GetTableAnnotation(const ITable *tab) const {
  auto it = table_.find(tab);
  if (it == table_.end()) {
    return string();
  }
  return it->second.str();
}

void OptimizerLog::SetStateColorIndex(const IState *st, int idx) {
  state_color_[st] = idx;
}

string OptimizerLog::GetStateAnnotation(const IState *st) const {
  auto it = state_.find(st);
  if (it == state_.end()) {
    return string();
  }
  return it->second.str();
}

string OptimizerLog::GetInsnAnnotation(const IInsn *insn) const {
  auto it = insn_.find(insn);
  if (it == insn_.end()) {
    return "";
  }
  return it->second.str();
}

string OptimizerLog::GetRegAnnotation(const IRegister *reg) const {
  auto it = reg_.find(reg);
  if (it == reg_.end()) {
    return "";
  }
  return it->second.str();
}

int OptimizerLog::GetStateColorIndex(const IState *st) const {
  auto p = state_color_.find(st);
  if (p == state_color_.end()) {
    return 0;
  }
  return p->second;
}

void OptimizerLog::StartPass(const string &name) {
  string s = Util::Itoa(current_pass_index_);
  while (s.length() < 3) {
    s = "0" + s;
  }
  current_pass_name_ = s + name;
  current_pass_index_++;
  current_section_name_ = "";
  UpdateFileName(true);
  table_.clear();
  state_.clear();
}

void OptimizerLog::StartSubSection(const string &section, bool isHtml) {
  current_section_name_ = section;
  UpdateFileName(isHtml);
}

void OptimizerLog::ClearSubSection() {
  current_section_name_.clear();
  UpdateFileName(false);
}

void OptimizerLog::UpdateFileName(bool isHtml) {
  current_file_name_ = current_pass_name_;
  if (!current_section_name_.empty()) {
    current_file_name_ += "." + current_section_name_;
  }
  OptimizerLogSection *ls = GetSection(current_file_name_);
  ls->is_html_ = isHtml;
}

OptimizerLogSection *OptimizerLog::GetSection(const string &name) {
  auto it = sections_.find(name);
  if (it == sections_.end()) {
    OptimizerLogSection *s = new OptimizerLogSection();
    sections_[name] = s;
    return s;
  }
  return it->second;
}

}  // namespace opt
}  // namespace iroha


text:
Allows to set different screen resolutions in VMware.

Copyright 2009-2011 Zenith432. All rights reserved.

Portions Copyright 2009 VMware, Inc.  All rights reserved.


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Route extends Kohana_Route {}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Stereocaulon paschale f. gracilentum

### Remarks
null


text:
#include <aws/kinesisanalyticsv2/model/ApplicationConfigurationUpdate.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace KinesisAnalyticsV2
{
namespace Model
{

ApplicationConfigurationUpdate::ApplicationConfigurationUpdate() :
    m_sqlApplicationConfigurationUpdateHasBeenSet(false),
    m_applicationCodeConfigurationUpdateHasBeenSet(false),
    m_flinkApplicationConfigurationUpdateHasBeenSet(false),
    m_environmentPropertyUpdatesHasBeenSet(false),
    m_applicationSnapshotConfigurationUpdateHasBeenSet(false),
    m_vpcConfigurationUpdatesHasBeenSet(false),
    m_zeppelinApplicationConfigurationUpdateHasBeenSet(false)
{
}

ApplicationConfigurationUpdate::ApplicationConfigurationUpdate(JsonView jsonValue) :
    m_sqlApplicationConfigurationUpdateHasBeenSet(false),
    m_applicationCodeConfigurationUpdateHasBeenSet(false),
    m_flinkApplicationConfigurationUpdateHasBeenSet(false),
    m_environmentPropertyUpdatesHasBeenSet(false),
    m_applicationSnapshotConfigurationUpdateHasBeenSet(false),
    m_vpcConfigurationUpdatesHasBeenSet(false),
    m_zeppelinApplicationConfigurationUpdateHasBeenSet(false)
{
  *this = jsonValue;
}

ApplicationConfigurationUpdate& ApplicationConfigurationUpdate::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("SqlApplicationConfigurationUpdate"))
  {
    m_sqlApplicationConfigurationUpdate = jsonValue.GetObject("SqlApplicationConfigurationUpdate");

    m_sqlApplicationConfigurationUpdateHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApplicationCodeConfigurationUpdate"))
  {
    m_applicationCodeConfigurationUpdate = jsonValue.GetObject("ApplicationCodeConfigurationUpdate");

    m_applicationCodeConfigurationUpdateHasBeenSet = true;
  }

  if(jsonValue.ValueExists("FlinkApplicationConfigurationUpdate"))
  {
    m_flinkApplicationConfigurationUpdate = jsonValue.GetObject("FlinkApplicationConfigurationUpdate");

    m_flinkApplicationConfigurationUpdateHasBeenSet = true;
  }

  if(jsonValue.ValueExists("EnvironmentPropertyUpdates"))
  {
    m_environmentPropertyUpdates = jsonValue.GetObject("EnvironmentPropertyUpdates");

    m_environmentPropertyUpdatesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApplicationSnapshotConfigurationUpdate"))
  {
    m_applicationSnapshotConfigurationUpdate = jsonValue.GetObject("ApplicationSnapshotConfigurationUpdate");

    m_applicationSnapshotConfigurationUpdateHasBeenSet = true;
  }

  if(jsonValue.ValueExists("VpcConfigurationUpdates"))
  {
    Aws::Utils::Array<JsonView> vpcConfigurationUpdatesJsonList = jsonValue.GetArray("VpcConfigurationUpdates");
    for(unsigned vpcConfigurationUpdatesIndex = 0; vpcConfigurationUpdatesIndex < vpcConfigurationUpdatesJsonList.GetLength(); ++vpcConfigurationUpdatesIndex)
    {
      m_vpcConfigurationUpdates.push_back(vpcConfigurationUpdatesJsonList[vpcConfigurationUpdatesIndex].AsObject());
    }
    m_vpcConfigurationUpdatesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ZeppelinApplicationConfigurationUpdate"))
  {
    m_zeppelinApplicationConfigurationUpdate = jsonValue.GetObject("ZeppelinApplicationConfigurationUpdate");

    m_zeppelinApplicationConfigurationUpdateHasBeenSet = true;
  }

  return *this;
}

JsonValue ApplicationConfigurationUpdate::Jsonize() const
{
  JsonValue payload;

  if(m_sqlApplicationConfigurationUpdateHasBeenSet)
  {
   payload.WithObject("SqlApplicationConfigurationUpdate", m_sqlApplicationConfigurationUpdate.Jsonize());

  }

  if(m_applicationCodeConfigurationUpdateHasBeenSet)
  {
   payload.WithObject("ApplicationCodeConfigurationUpdate", m_applicationCodeConfigurationUpdate.Jsonize());

  }

  if(m_flinkApplicationConfigurationUpdateHasBeenSet)
  {
   payload.WithObject("FlinkApplicationConfigurationUpdate", m_flinkApplicationConfigurationUpdate.Jsonize());

  }

  if(m_environmentPropertyUpdatesHasBeenSet)
  {
   payload.WithObject("EnvironmentPropertyUpdates", m_environmentPropertyUpdates.Jsonize());

  }

  if(m_applicationSnapshotConfigurationUpdateHasBeenSet)
  {
   payload.WithObject("ApplicationSnapshotConfigurationUpdate", m_applicationSnapshotConfigurationUpdate.Jsonize());

  }

  if(m_vpcConfigurationUpdatesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> vpcConfigurationUpdatesJsonList(m_vpcConfigurationUpdates.size());
   for(unsigned vpcConfigurationUpdatesIndex = 0; vpcConfigurationUpdatesIndex < vpcConfigurationUpdatesJsonList.GetLength(); ++vpcConfigurationUpdatesIndex)
   {
     vpcConfigurationUpdatesJsonList[vpcConfigurationUpdatesIndex].AsObject(m_vpcConfigurationUpdates[vpcConfigurationUpdatesIndex].Jsonize());
   }
   payload.WithArray("VpcConfigurationUpdates", std::move(vpcConfigurationUpdatesJsonList));

  }

  if(m_zeppelinApplicationConfigurationUpdateHasBeenSet)
  {
   payload.WithObject("ZeppelinApplicationConfigurationUpdate", m_zeppelinApplicationConfigurationUpdate.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace KinesisAnalyticsV2
} // namespace Aws


text:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Text;
using System.Collections.Generic;
using DSL.POS.Facade;
using DSL.POS.DTO.DTO;
using DSL.POS.BusinessLogicLayer.Interface;
using DSL.POS.Common.Utility;

public partial class Admin_Setup_Booth_BoothRegistration : System.Web.UI.Page
{
    ClsErrorHandle cls = new ClsErrorHandle();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole(ConfigurationManager.AppSettings["adminrolename"]))
        {
            Response.Redirect("~/CustomErrorPages/NotAuthorized.aspx");
        }
        if (!IsPostBack)
        {
            try
            {
                this.chkPermanent.Focus();
                this.chkPermanent.Attributes.Add("onkeypress", "FocusControl_byEnter()");
                this.chkDemo.Attributes.Add("onkeypress", "FocusControl_byEnter()");
                this.txtBoothExpiresDate.Attributes.Add("onkeypress", "FocusControl_byEnter()");
                this.txtBoothExpiresDate.Attributes.Add("onkeypress", "doNumeric()");
                this.ddlBoothNo.Attributes.Add("onkeypress", "FocusControl_byEnter()");

                // Retrieving data in cookies

                if (Request.Cookies["DPOS"] != null)
                {

                    //Banding data in Dropdown List

                    Response.Redirect("~/Admin/Setup/Default.aspx");
                    //string ApplName = "";

                    //if (Request.Cookies["DPOS"]["BoothNo"] != null)
                    //{
                    //    ApplName = Request.Cookies["DPOS"]["BoothNo"];

                    //    if (ApplName.ToString() == "3e3771ea-d7c9-4551-bb68-2ce8eb941ab1")
                    //    {
                    //        //Response.Redirect("http://localhost:3116/Web/Client/Sales/Default.aspx");
                    //        //return;
                    //    }
                    //    Response.Redirect("http://localhost:3116/Web/Client/Sales/Default.aspx");
                    //    return;
                    //}
                }
                else
                    if (User.Identity.Name.ToLower() == "admin")
                    {
                        Facade facade = Facade.GetInstance();

                        DropDownListBoothNo(facade);

                    }
                    else
                    {
                        Response.Redirect("~/Admin/Setup/Booth/BoothErrorPage.aspx");
                        return;

                    }

            }
            catch (Exception Exp)
            {
                lblErrorMessage.Text = cls.ErrorString(Exp);
            }
        }
        else
        {
            //Response.Write("not not");
        }

    }

    private void DropDownListBoothNo(Facade facade)
    {

        IBoothInfoBL BoothList = facade.createBoothInfoBL();
        List<BoothInfoDTO> oBoothInfoList = BoothList.showDataBoothInfo();

        int i = 0;
        ddlBoothNo.Items.Clear();
        ddlBoothNo.Items.Add("(Select booth No.)");
        this.ddlBoothNo.Items[i].Value = "";
        foreach (BoothInfoDTO newDto in oBoothInfoList)
        {
            i++;
            this.ddlBoothNo.Items.Add(newDto.BoothNo.ToString());
            this.ddlBoothNo.Items[i].Value = newDto.PrimaryKey.ToString();
        }
    }

    protected void btnBoothReg_Click(object sender, EventArgs e)
    {
        int permanentDay = 0;
        int demoDay = 0;
        int ExpiresDate = 0;

        if ((chkPermanent.Checked == false ) && (chkDemo.Checked == false))
        {
            this.lblErrorMessage.Text = "You must be select Registration Type!";
            return;
        }
        if ((chkPermanent.Checked == true ) && (chkDemo.Checked == true ))
        {
            this.lblErrorMessage.Text = "You must be select one registration Type!";
            return;
        }
        if ((chkPermanent.Checked == true) && (chkDemo.Checked == false) )
        {
             permanentDay = 356;
        }
        if ((chkPermanent.Checked == false ) && (chkDemo.Checked == true))
        {
            if (this.txtBoothExpiresDate.Text == "")
            {
                return;
            }
            demoDay =int.Parse(this.txtBoothExpiresDate.Text);
        }
        if (this.lblErrorMessage.Text.Length != 0)
        {
            this.lblErrorMessage.Text = "";
        }

        BoothInfoDTO dto = populate();

        Facade facade = Facade.GetInstance();
        IBoothInfoBL oBoothInfoBL = facade.createBoothInfoBL();
        oBoothInfoBL.addNewBoothRecord(dto);

        // Get values in text field
        string boothNo = this.ddlBoothNo.SelectedValue;

        if( permanentDay != 0 )
        {
            ExpiresDate = permanentDay;
        }
        else
            ExpiresDate = demoDay;

        DateTime dt = DateTime.Now;
        TimeSpan ts = new TimeSpan(0, ExpiresDate, 0, 0);

        //Create a custome coookies
        HttpCookie myCookie = new HttpCookie("DPOS");

        //Keep data in cookies
        //myCookie["BoothNo"] = "ONE";
        myCookie["BoothNo"] = boothNo;
        myCookie.Expires = dt.Add(ts);
        Response.Cookies.Add(myCookie);

        this.lblErrorMessage.Text = "Booth Registration Successfully.";
        this.ddlBoothNo.SelectedValue = "";
        //this.pnlDay.Visible = false;
        this.txtHideFieldPK.Value = "";
        this.chkPermanent.Checked = false;
        this.chkDemo.Checked = false;

    }

    private BoothInfoDTO populate()
    {

        try
        {
            short  intBoothNo = 0;
            BoothInfoDTO dto = new BoothInfoDTO();
            // populate dto

            Facade facade = Facade.GetInstance();

            // PK keep in local variable
            intBoothNo =Convert.ToInt16 ( ddlBoothNo.SelectedItem.Text);

            //  Get the Booth Information Corresponding Booth No. and keep Booth Info Domain Object
            dto = facade.getBoothInfoByCodeDTO(intBoothNo);

            // set up the member primary code in local declared Hidden field
            this.txtHideFieldPK.Value = dto.PrimaryKey.ToString();

            dto.EntryBy = "Admin";
            dto.EntryDate = DateTime.Now.Date;
            return dto;
        }
        catch (Exception Exp)
        {
            throw Exp;
        }
    }

}


text:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class ObservingPatternsDemo {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        BufferedReader reader = openSampleFile();

        String result = "";
        String line = "";
        while (null != (line = reader.readLine())) {
            result += line;
        }

        System.out.println(result);
        System.out.println("Finished!");
    }

    protected static BufferedReader openSampleFile() throws FileNotFoundException {
        return new BufferedReader(new InputStreamReader(new FileInputStream("sample.json")));
    }
}


text:
package com.wrbug.gravitybox.nougat.quicksettings;

import de.robv.android.xposed.XSharedPreferences;

public class MtkMobileDataTile extends AospTile {
    public static final String AOSP_KEY = "dataconnection";

    protected MtkMobileDataTile(Object host, Object tile, XSharedPreferences prefs,
            QsTileEventDistributor eventDistributor) throws Throwable {
        super(host, "mtk_tile_mobile_data", tile, prefs, eventDistributor);
    }

    @Override
    public String getAospKey() {
        return AOSP_KEY;
    }
}


text:
#ifndef art_Framework_Services_Optional_MemoryTrackerDarwin_h
#define art_Framework_Services_Optional_MemoryTrackerDarwin_h

// ======================================================================
//
// MemoryTrackerDarwin
//
// ======================================================================

#include "art/Framework/Services/Registry/ServiceTable.h"
#include "messagefacility/MessageLogger/MessageLogger.h"

namespace fhicl { class ParameterSet; }

namespace art {

  class ActivityRegistry;

  class MemoryTracker {
  public:

    MemoryTracker(fhicl::ParameterSet const&, ActivityRegistry&) {
      mf::LogAbsolute("MemoryTracker") << "\n"
                                       << "The MemoryTracker service is not supported for this operating system.\n"
                                       << "If desired, please log an issue with:\n\n"
                                       << "https://cdcvs.fnal.gov/redmine/projects/cet-is/issues/new\n\n";
    }

  };

}  // art

#endif /* art_Framework_Services_Optional_MemoryTrackerDarwin_h */

// Local variables:
// mode: c++
// End:


text:
package fr.opensagres.maven.plugins.noannotations;

import java.io.File;

import junit.framework.Assert;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import fr.opensagres.maven.plugins.noannotations.RemoveAnnotationsMojo;

public class RemoveAnnotationsTest {

	RemoveAnnotationsMojo sut = new RemoveAnnotationsMojo();
	String givenAClassWithAnnotations;
	@Test
	public void testName() throws Exception {
		givenJavaFileWithAnnotations();

		final String newSource = sut.cleanupAnnotations(givenAClassWithAnnotations);

		annotationsAreRemoved(newSource);

	}

	private String givenJavaFileWithAnnotations() {
		//@formatter:off
		givenAClassWithAnnotations ="package fr.opensagres.maven.noannotations;\n"+
					 "import java.io.Serializable;\n"+
					 "import one.MemberAnnotation;\n"+
					 "import two.PropertyAnnotation;\n"+
					 "import three.MethodAnnotation;\n"+
					 "\n"+
					 "@MemberAnnotation\n"+
					 "public class Demo implements Serializable {\n"+
					 "\n"+
					 "	@PropertyAnnotation\n"+
					 "	int deprecatedAtttibute;\n"+
					 "\n"+
					 "\n"+
					 "	@MethodAnnotation\n"+
					 "	public String toString() {\n"+
					 "		return super.toString();\n"+
					 "	}\n"+
					 "}";
		//@formatter:on
		return givenAClassWithAnnotations;
	}

	private void annotationsAreRemoved(final String newSource) {
		//@formatter:off
		String expectedContent ="package fr.opensagres.maven.noannotations;\n"+
				"import java.io.Serializable;\n"+
				"\n"+
				"public class Demo implements Serializable {\n"+
				"\n"+
				"	int deprecatedAtttibute;\n"+
				"\n"+
				"\n"+
				"	public String toString() {\n"+
				"		return super.toString();\n"+
				"	}\n"+
				"}";
		//@formatter:on
		Assert.assertEquals(expectedContent, newSource);
	}

	@Test
	public void fromUser_java() throws Exception {
		String content = FileUtils.readFileToString(new File(ClassLoader.getSystemResource("User.java").getFile()));
		String cleanedUp = sut.cleanupAnnotations(content);

		String expected ="package demo;\n"+
		"\n"+
		"import java.util.Date;\n"+
		"\n"+
		"\n"+
		"public class User {\n"+
		"\n"+
		"    private String userName;\n"+
		"\n"+
		"    private String firstName;\n"+
		"\n"+
		"    private String surname;\n"+
		"\n"+
		"    private String email;\n"+
		"\n"+
		"    private byte[] avatar;\n"+
		"\n"+
		"    private Date lastUpdated;\n"+
		"\n"+
		"    public String getUserName() {\n"+
		"        return userName;\n"+
		"    }\n"+
		"\n"+
		"    public void setUserName(String userName) {\n"+
		"        this.userName = userName;\n"+
		"    }\n"+
		"\n"+
		"    public String getFirstName() {\n"+
		"        return firstName;\n"+
		"    }\n"+
		"\n"+
		"    public void setFirstName(String firstName) {\n"+
		"        this.firstName = firstName;\n"+
		"    }\n"+
		"\n"+
		"    public String getSurname() {\n"+
		"        return surname;\n"+
		"    }\n"+
		"\n"+
		"    public void setSurname(String surname) {\n"+
		"        this.surname = surname;\n"+
		"    }\n"+
		"\n"+
		"    public String getEmail() {\n"+
		"        return email;\n"+
		"    }\n"+
		"\n"+
		"    public void setEmail(String email) {\n"+
		"        this.email = email;\n"+
		"    }\n"+
		"\n"+
		"    public byte[] getAvatar() {\n"+
		"        return avatar;\n"+
		"    }\n"+
		"\n"+
		"    public void setAvatar(byte[] avatar) {\n"+
		"        this.avatar = avatar;\n"+
		"    }\n"+
		"\n"+
		"    public Date getLastUpdated() {\n"+
		"        return lastUpdated;\n"+
		"    }\n"+
		"\n"+
		"    public void setLastUpdated(Date lastUpdated) {\n"+
		"        this.lastUpdated = lastUpdated;\n"+
		"    }\n"+
		"}";
		Assert.assertEquals(expected, cleanedUp);
		//System.out.println(sut.cleanupAnnotations(content));

	}
}


text:
irfc_bot
========
A web scraper and irc bot to relay the BBC football live text commentary written in node.js

This small project is actually a result of another one ([bbc-lc](https://github.com/cramsay/bbc-lc)).
The goal was to create a ncurses interface to the BBC commentary.
However, I suck at UI design... I realised I was just trying to replicate the configuration I had for irssi
(my irc client of choice). IRC bots are _cool_ and I could use some better OOP skills with javascript for my work.
So I turned it in to an IRC bot written in Node.js :)
If you want to see it in action (and there is football happening) connect to "cramsay.co.uk" and join the "#fitba" channel.

## Usage
Any IRC user can type "!games" to have the bot return details of all of the games today.
Any live games will be detected automatically and the commentary will be posted by the bot in a unique-ish colour.
To run the bot, just change the ircbot.config object to point to your preferred IRC server and channel.

## Details
I made use of 3 node.js packages...
* **Request** : for grabbing bbc pages
* **Cheerio** : for parsing the DOM of pages
* **IRC** : for interaction with the IRC server

This is my step in to node.js so it *is* not a golden example of good style...
For anyone in the position I was, here are a few helpful sites :)
  1. [Node.js web scraping guide](http://blog.miguelgrinberg.com/post/easy-web-scraping-with-nodejs)
  2. [Node.js IRC tutorial](http://davidwalsh.name/nodejs-irc)

Just now it only searches for world cup games, however this is easily adapted to more competitions.
The real challange would be allowing users to pick which games to follow and which to ignore without much scope for griefing.


text:
503 Service Unavailable

        No server is available to handle this request.


text:
CREATE TABLE inode(
    id integer not null primary key autoincrement
);

CREATE TABLE file(
    id integer not null references inode(id) ON DELETE CASCADE,
    real_location char(512) unique,
    name char(512) unique,
    owner references filesystem_user(id),
    primary key(id)
);

CREATE TABLE collection(
    id integer not null references inode(id) ON DELETE CASCADE,
    name char(512) unique,
    owner references filesystem_user(id),
    primary key(id)
);

CREATE TABLE collection2(
    id integer not null references inode(id) ON DELETE CASCADE,
    name char(512) unique,
    owner references filesystem_user(id),
    primary key(id)
);

CREATE TABLE collection_file(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    collection_ref INTEGER REFERENCES collection(id) ON DELETE CASCADE,
    file_ref INTEGER REFERENCES file(id) ON DELETE CASCADE,
    owner references filesystem_user(id)
);

CREATE TABLE collection2_collection(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    collection2_ref INTEGER REFERENCES collection2(id) ON DELETE CASCADE,
    collection_ref INTEGER REFERENCES collection(id) ON DELETE CASCADE,
    owner references filesystem_user(id)
);

CREATE TABLE abstract_user(
    id integer not null primary key AUTOINCREMENT
);

CREATE TABLE filesystem_user(
    id integer not null references abstract_user(id) ON DELETE CASCADE,
    name char(512) unique,
    primary key(id)
);

CREATE TABLE filesystem_group(
    id integer not null references abstract_user(id) ON DELETE CASCADE,
    name char(512) unique,
    owner references filesystem_user(id),
    primary key(id)
);

CREATE TABLE filesystem_group_filesystem_user(
    id integer primary key autoincrement,
    filesystem_user_ref integer references filesystem_user(id) on delete cascade,
    filesystem_group_ref integer references filesystem_group(id) on delete cascade,
    owner references filesystem_user(id)
);

CREATE TABLE permission(
    id integer not null primary key AUTOINCREMENT,
    inode_ref INTEGER REFERENCES inode(id) ON DELETE CASCADE,
    user_ref INTEGER REFERENCES abstract_user(id) ON DELETE CASCADE,
    owner references filesystem_user(id)
);


text:
/**
* # resetPassword.js
*
* This is a client side implementation that supports the reset
 * password user case.  When the user presses the "reset" button a
 * AJAX call is sent to the server.
 *
*/

var internals = {};

/**
* ## executeAjax
*
* Post the data to the url
*
*/
internals.executeAJAX = function (url, data, callback) {

  internals.clearErrors();

  var request = new XMLHttpRequest();

  request.open('POST', url);

  request.timedOut = false;

  var requestTimer = setTimeout(function () {

    // Request timed out, Retry or inform user.
    request.timedOut = true;
    request.abort();
  }, 3000);

  request.onreadystatechange = function () {
    if (request.readyState === 4 && callback) {
      return callback(request);
    }
  };

  request.setRequestHeader('Content-Type', 'application/json');

  request.send(JSON.stringify(data));

  return true;
};

/**
* ## errorMessage
*
* display any error message
*
*/
internals.errorMessage = function (message) {

  //  handle error message

  var newP = document.createElement('p');
  newP.innerHTML = message;

  var att = document.createAttribute('class');
  att.value = 'errorMessage';
  newP.setAttributeNode(att);

  var form = document.getElementsByTagName('form')[0];

  var parentDiv = form.parentNode;

  parentDiv.insertBefore(newP, form);

  return false;
};
/**
* ## clearErrors
*
* Remove any errors
*
*/
internals.clearErrors = function () {

  var errorMessages = document.getElementsByTagName('p');

  if (errorMessages.length > 0) {
    console.log('Has Errors');
    errorMessages[0].parentNode.removeChild(errorMessages[0]);
  }
};
/**
* ## successMessage
*
* Display the success message from the server
*
*/
internals.successMessage = function (request) {

  // Success clear and display authenticated users links.

  var form = document.getElementsByTagName('form')[0];
  var parent1 = form.parentNode;

  parent1.innerHTML = 'Your password has been reset';

  return;
};

/**
* ## onreadystatechange
*
* List for click event on button, send data to server to reset password
*
*/
document.onreadystatechange = function () {

  if (document.readyState === 'complete') {

    // Add click event handler
    document.getElementById('btnReset').addEventListener('click', function (event) {
      event.preventDefault();

      // Get submitted form data
      var password = document.getElementsByName('password')[0].value;
      var token = document.getElementsByName('token')[0].value;

      var requestData = { password: password, token: token };

      internals.executeAJAX('/account/resetPassword', requestData, function (request) {

        if (request.status === 200) {

          internals.successMessage(request);

        } else if (request.status !== 0) {

          // Boom error message received from server.
          var responseJson = JSON.parse(request.response);
          internals.errorMessage(responseJson.message);

        } else {

          // Oh no! request aborted
          if (request.timedOut === true) {
            internals.errorMessage('Your request timed out.  Most likely you have a slow internet connection.');
          } else {
            internals.errorMessage('[Error] Failed to load resource: Could not connect to the server.');
          }
        }
      });
    });
  }
};


text:
package com.belatrixsf.connect.networking.retrofit.responses;

/**
 * Created by PedroCarrillo on 4/27/16.
 */
public class StarResponse {

    Integer pk;

}


text:
#ifndef clipper_hpp
#define clipper_hpp

#include <vector>
#include <stdexcept>
#include <cstring>
#include <cstdlib>

enum ClipType { ctIntersection=0x1, ctUnion=0x2, ctDifference=0x3, ctXor=0x4 };
enum PolyType { ptSubject=0x1, ptClip=0x2 };
enum PolyFillType { pftEvenOdd=0x1, pftNonZero=0x2 };

typedef signed long long long64;
typedef unsigned long long ulong64;

struct IntPoint {
  long64 X;
  long64 Y;
  IntPoint(long64 x = 0, long64 y = 0): X(x), Y(y) {};
};

typedef std::vector< IntPoint > Polygon;
typedef std::vector< Polygon > Polygons;

struct ExPolygon {
  Polygon  outer;
  Polygons holes;
};
typedef std::vector< ExPolygon > ExPolygons;

bool IsClockwise(const Polygon &poly, bool UseFullInt64Range = true);
double Area(const Polygon &poly, bool UseFullInt64Range = true);
bool OffsetPolygons(const Polygons &in_pgs, Polygons &out_pgs, const float &delta);

extern "C" {

  typedef void * polygon;
  typedef void * polygons;
  typedef void * expolygon;
  typedef void * expolygons;
  typedef void * clipper;

  polygon polygon_new(int numPoints);
  void polygon_clear(polygon poly);
  int polygon_size(polygon poly);
  void polygon_addPoint(polygon poly, long64 x, long64 y);
  long64 polygon_getPointX(polygon poly, int i);
  long64 polygon_getPointY(polygon poly, int i);
  void polygon_free(polygon poly);

  int polygon_isClockwise(polygon poly, int useFullInt64Range);
  double polygon_getArea(polygon poly, int useFullInt64Range);

  polygons polygons_new(int numPolys);
  void polygons_clear(polygons poly);
  int polygons_size(polygons poly);
  polygon polygons_getPoly(polygons polys, int i);
  void polygons_addPoly(polygons polys, polygon poly);
  void polygons_free(polygons poly);

  clipper clipper_new();
  void clipper_addPolygon(clipper c, polygon poly, PolyType ptype);
  void clipper_addPolygons(clipper c, polygons poly, PolyType ptype);
  void clipper_executePoly(clipper c, ClipType ctype, polygons soln);
  void clipper_free(clipper c);
}

//used internally ...
enum EdgeSide { esLeft, esRight };
enum IntersectProtects { ipNone = 0, ipLeft = 1, ipRight = 2, ipBoth = 3 };

struct TEdge {
  long64 xbot;
  long64 ybot;
  long64 xcurr;
  long64 ycurr;
  long64 xtop;
  long64 ytop;
  double dx;
  long64 tmpX;
  PolyType polyType;
  EdgeSide side;
  int windDelta; //1 or -1 depending on winding direction
  int windCnt;
  int windCnt2; //winding count of the opposite polytype
  int outIdx;
  TEdge *next;
  TEdge *prev;
  TEdge *nextInLML;
  TEdge *nextInAEL;
  TEdge *prevInAEL;
  TEdge *nextInSEL;
  TEdge *prevInSEL;
};

struct IntersectNode {
  TEdge          *edge1;
  TEdge          *edge2;
  IntPoint        pt;
  IntersectNode  *next;
};

struct LocalMinima {
  long64        Y;
  TEdge        *leftBound;
  TEdge        *rightBound;
  LocalMinima  *next;
};

struct Scanbeam {
  long64    Y;
  Scanbeam *next;
};

struct OutPt; //forward declaration

struct OutRec {
  int     idx;
  bool    isHole;
  OutRec *FirstLeft;
  OutRec *AppendLink;
  OutPt  *pts;
  OutPt  *bottomPt;
};

struct OutPt {
  int     idx;
  IntPoint pt;
  OutPt   *next;
  OutPt   *prev;
};

struct JoinRec {
  IntPoint  pt1a;
  IntPoint  pt1b;
  int       poly1Idx;
  IntPoint  pt2a;
  IntPoint  pt2b;
  int       poly2Idx;
};

struct HorzJoinRec {
  TEdge    *edge;
  int       savedIdx;
};

struct IntRect { long64 left; long64 top; long64 right; long64 bottom; };

typedef std::vector < OutRec* > PolyOutList;
typedef std::vector < TEdge* > EdgeList;
typedef std::vector < JoinRec* > JoinList;
typedef std::vector < HorzJoinRec* > HorzJoinList;

//ClipperBase is the ancestor to the Clipper class. It should not be
//instantiated directly. This class simply abstracts the conversion of sets of
//polygon coordinates into edge objects that are stored in a LocalMinima list.
class ClipperBase
{
public:
  ClipperBase();
  virtual ~ClipperBase();
  bool AddPolygon(const Polygon &pg, PolyType polyType);
  bool AddPolygons( const Polygons &ppg, PolyType polyType);
  virtual void Clear();
  IntRect GetBounds();
  bool UseFullCoordinateRange() {return m_UseFullRange;};
  void UseFullCoordinateRange(bool newVal);
protected:
  void DisposeLocalMinimaList();
  TEdge* AddBoundsToLML(TEdge *e);
  void PopLocalMinima();
  virtual void Reset();
  void InsertLocalMinima(LocalMinima *newLm);
  LocalMinima      *m_CurrentLM;
  LocalMinima      *m_MinimaList;
  bool              m_UseFullRange;
  EdgeList          m_edges;
};

class Clipper : public virtual ClipperBase
{
public:
  Clipper();
  ~Clipper();
  bool Execute(ClipType clipType,
    Polygons &solution,
    PolyFillType subjFillType = pftEvenOdd,
    PolyFillType clipFillType = pftEvenOdd);
  bool Execute(ClipType clipType,
    ExPolygons &solution,
    PolyFillType subjFillType = pftEvenOdd,
    PolyFillType clipFillType = pftEvenOdd);
  void Clear();
protected:
  void Reset();
  virtual bool ExecuteInternal(bool fixHoleLinkages);
private:
  PolyOutList       m_PolyOuts;
  JoinList          m_Joins;
  HorzJoinList      m_HorizJoins;
  ClipType          m_ClipType;
  Scanbeam         *m_Scanbeam;
  TEdge           *m_ActiveEdges;
  TEdge           *m_SortedEdges;
  IntersectNode    *m_IntersectNodes;
  bool              m_ExecuteLocked;
  PolyFillType      m_ClipFillType;
  PolyFillType      m_SubjFillType;
  void DisposeScanbeamList();
  void SetWindingCount(TEdge& edge);
  bool IsNonZeroFillType(const TEdge& edge) const;
  bool IsNonZeroAltFillType(const TEdge& edge) const;
  void InsertScanbeam(const long64 Y);
  long64 PopScanbeam();
  void InsertLocalMinimaIntoAEL(const long64 botY);
  void InsertEdgeIntoAEL(TEdge *edge);
  void AddEdgeToSEL(TEdge *edge);
  void CopyAELToSEL();
  void DeleteFromSEL(TEdge *e);
  void DeleteFromAEL(TEdge *e);
  void UpdateEdgeIntoAEL(TEdge *&e);
  void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
  bool IsContributing(const TEdge& edge) const;
  bool IsTopHorz(const long64 XPos);
  void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
  void DoMaxima(TEdge *e, long64 topY);
  void ProcessHorizontals();
  void ProcessHorizontal(TEdge *horzEdge);
  void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
  void AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
  void AppendPolygon(TEdge *e1, TEdge *e2);
  void DoEdge1(TEdge *edge1, TEdge *edge2, const IntPoint &pt);
  void DoEdge2(TEdge *edge1, TEdge *edge2, const IntPoint &pt);
  void DoBothEdges(TEdge *edge1, TEdge *edge2, const IntPoint &pt);
  void IntersectEdges(TEdge *e1, TEdge *e2,
    const IntPoint &pt, IntersectProtects protects);
  void AddOutPt(TEdge *e, const IntPoint &pt);
  void DisposeAllPolyPts();
  void DisposeOutRec(int index, bool ignorePts = false);
  bool ProcessIntersections( const long64 topY);
  void AddIntersectNode(TEdge *e1, TEdge *e2, const IntPoint &pt);
  void BuildIntersectList(const long64 topY);
  void ProcessIntersectList();
  void ProcessEdgesAtTopOfScanbeam(const long64 topY);
  void BuildResult(Polygons& polys);
  void BuildResultEx(ExPolygons& polys);
  void SetHoleState(TEdge *e, OutRec *OutRec);
  void DisposeIntersectNodes();
  bool FixupIntersections();
  void FixupOutPolygon(OutRec &outRec);
  bool IsHole(TEdge *e);
  void FixHoleLinkage(OutRec *outRec);
  void AddJoin(TEdge *e1, TEdge *e2, int e1OutIdx = -1, int e2OutIdx = -1);
  void ClearJoins();
  void AddHorzJoin(TEdge *e, int idx);
  void ClearHorzJoins();
  void JoinCommonEdges();
};

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

class clipperException : public std::exception
{
  public:
    clipperException(const char* description)
      throw(): std::exception(), m_description (description) {}
    virtual ~clipperException() throw() {}
    virtual const char* what() const throw() {return m_description.c_str();}
  private:
    std::string m_description;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

#endif //clipper_hpp


text:
@interface LKCAuthRequestManager()

-(void)denyFromAuthFailure:(AuthResponseReason)reason withCompletion:(denyAuthCompletion)completion;
-(void)postAuthenticationForAuthenticated:(BOOL)authenticated type:(AuthResponseType)type reason:(AuthResponseReason)reason denialReason:(NSString *)denialReason withCompletion:(void (^)(NSError *error))completion;

// Support for Legacy AuthRequestManager
-(void)checkForPendingAuthRequestWithCompletion:(authRequestCompletion)completion withBlockToCallSegueForUILibrary:(void (^)(void))doUISeque;
-(NSString *)getAuthRequestTitle;
-(NSString *)getAuthRequestContext;
-(int)getCreatedAtInMilliseconds;
-(int)getExpiresAtInMilliseconds;
-(LKCAuthRequestDetails*)getAuthRequestDetailsForCurrentRequest;
-(int)getNumberRequiredAuthMethodsForCurrentRequest;
-(NSArray*)getRequiredAuthMethodArrayForCurrentRequest;
-(BOOL)isCurrentRequestQuickfail;
-(NSString*)getCurrentRequestQuickFailReason;

@end


text:
#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dcrledrg.h"

#include "dcmtk/dcmdata/dccodec.h"  /* for DcmCodecStruct */
#include "dcmtk/dcmdata/dcrleccd.h" /* for class DcmRLECodecDecoder */
#include "dcmtk/dcmdata/dcrlecp.h"  /* for class DcmRLECodecParameter */

// initialization of static members
OFBool DcmRLEDecoderRegistration::registered                  = OFFalse;
DcmRLECodecParameter *DcmRLEDecoderRegistration::cp           = NULL;
DcmRLECodecDecoder *DcmRLEDecoderRegistration::codec          = NULL;

void DcmRLEDecoderRegistration::registerCodecs(
    OFBool pCreateSOPInstanceUID,
    OFBool pReverseDecompressionByteOrder)
{
  if (! registered)
  {
    cp = new DcmRLECodecParameter(
      pCreateSOPInstanceUID,
      0, OFTrue, OFFalse,
      pReverseDecompressionByteOrder);

    if (cp)
    {
      codec = new DcmRLECodecDecoder();
      if (codec) DcmCodecList::registerCodec(codec, NULL, cp);
      registered = OFTrue;
    }
  }
}

void DcmRLEDecoderRegistration::cleanup()
{
  if (registered)
  {
    DcmCodecList::deregisterCodec(codec);
    delete codec;
    delete cp;
    registered = OFFalse;
#ifdef DEBUG
    // not needed but useful for debugging purposes
    codec  = NULL;
    cp     = NULL;
#endif
  }
}

/*
 * CVS/RCS Log
 * $Log: dcrledrg.cc,v $
 * Revision 1.5  2010-10-14 13:14:09  joergr
 * Updated copyright header. Added reference to COPYRIGHT file.
 *
 * Revision 1.4  2009-11-04 09:58:10  uli
 * Switched to logging mechanism provided by the "new" oflog module
 *
 * Revision 1.3  2005-12-08 15:41:33  meichel
 * Changed include path schema for all DCMTK header files
 *
 * Revision 1.2  2005/07/26 17:08:35  meichel
 * Added option to RLE decoder that allows to correctly decode images with
 *   incorrect byte order of byte segments (LSB instead of MSB).
 *
 * Revision 1.1  2002/06/06 14:52:42  meichel
 * Initial release of the new RLE codec classes
 *   and the dcmcrle/dcmdrle tools in module dcmdata
 *
 *
 */


text:
package com.genie.enums;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import javax.faces.model.SelectItem;

import com.genie.utils.ResourceUtil;

public enum AchievementType {
	GRADE(1),
	ATTENDANCE_OVERALL(10),
	ATTENDANCE_CONSECUTIVE(20),
	SUBMISSION_OVERALL(30),
	SUBMISSION_EARLY(40);

	private int index;

	private static final List<AchievementType> valueList = Arrays.asList(values());
	private static final int size = valueList.size();

	private AchievementType(int index) {
		this.index = index;
	}

	public int getIndex() {
		return index;
	}

	public static List<SelectItem> getAsSelectItems() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (AchievementType at : AchievementType.values()) {
    		items.add(new SelectItem(at.getIndex(), ResourceUtil.getLabel("achievementType.enum." + at.toString())));
        }
        return items;
    }

	public String getLabel() {
    	return getLabel(this.index);
    }

    public static String getLabel(int at) {
        return ResourceUtil.getLabel("achievementType.enum." + getAchievementType(at).toString());
    }

    public static AchievementType getAchievementType(int index) {
    	for (AchievementType at : values()) {
    		if (at.index == index) {
    			return at;
    		}
    	}
    	return null;
    }

	public static AchievementType getRandomType() {
		return valueList.get(new Random().nextInt(size));
	}
}


text:
<?php

class Denkmal_Scraper_Source_HinterhofTest extends CMTest_TestCase {

    public function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testProcessPageDate() {
        $html = Denkmal_Scraper_Source_Abstract::loadFile(DIR_TEST_DATA . 'scraper/hinterhof.html');
        $scraper = new Denkmal_Scraper_Source_Hinterhof();

        $eventDataList = $scraper->processPage($html, new DateTime('2014-04-01'));

        $this->assertCount(24, $eventDataList);

        $this->assertEquals(new Denkmal_Scraper_EventData(
            $scraper->getRegion(),
            'Hinterhof',
            new Denkmal_Scraper_Description('Hinterhof Slam', null, new Denkmal_Scraper_Genres('slam poetry, whiskey grooves')),
            new DateTime('2014-04-17 20:00:00')
        ), $eventDataList[0]);

        $this->assertEquals(new Denkmal_Scraper_EventData(
            $scraper->getRegion(),
            'Hinterhof',
            new Denkmal_Scraper_Description('The Correspondents | Live', 'Bandura & Hinterhof "Bitten zum" Tanz', new Denkmal_Scraper_Genres('funk beats, swing hop, world grooves')),
            new DateTime('2014-04-17 20:00:00')
        ), $eventDataList[1]);

        $this->assertEquals(new Denkmal_Scraper_EventData(
            $scraper->getRegion(),
            'Hinterhof Dachterrasse',
            new Denkmal_Scraper_Description('Dachterasse geöffnet'),
            new DateTime('2014-05-07 20:00:00')
        ), $eventDataList[13]);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/fragment_group_main_swipe_refresh"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/fragment_group_main_coordinator"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/fragment_group_main_empty_textview"
            style="@style/TextAppearance.AppCompat.Title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|top"
            android:layout_marginTop="@dimen/common_rect_large"
            android:drawablePadding="@dimen/common_margin_xxtiny"
            android:gravity="center"
            android:visibility="gone"/>

        <com.shareyourproxy.app.adapter.BaseRecyclerView
            android:id="@+id/fragment_group_main_recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="com.shareyourproxy.widget.behavior.SnackbarMarginBehavior"/>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fragment_group_main_fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_marginBottom="@dimen/common_margin_tiny"
            android:layout_marginEnd="@dimen/common_margin_tiny"
            android:scaleType="center"
            app:backgroundTint="@color/common_blue"
            app:borderWidth="0dp"
            app:fabSize="normal"
            app:layout_anchorGravity="bottom|right|end"
            app:rippleColor="@color/common_blue_light"/>

    </android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.SwipeRefreshLayout>


text:
GLuint loadBMP_custom(const char * imagepath);

//// Since GLFW 3, glfwLoadTexture2D() has been removed. You have to use another texture loading library,
//// or do it yourself (just like loadBMP_custom and loadDDS)
//// Load a .TGA file using GLFW's own loader
//GLuint loadTGA_glfw(const char * imagepath);

// Load a .DDS file using GLFW's own loader
GLuint loadDDS(const char * imagepath);

#endif


text:
import React from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
import Header from './Header.js';
import { hashHistory } from 'react-router';
import Loader from '../components/Loader';

const mapStateToProps = (state) => ({
  routing: state.routing,
  user: state.user,
  property: state.property,
});

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.redirectIfNotLogin = this.redirectIfNotLogin.bind(this);
  }

  redirectIfNotLogin() {
    const { user, routing, setLastRoute } = this.props;
    const route = '/login';

    if (user.logged == 0 && routing.locationBeforeTransitions.pathname !== route) {
      setLastRoute(routing.locationBeforeTransitions.pathname);
      hashHistory.push(route);
    }
  }

  componentWillMount() {
    this.redirectIfNotLogin();

    const { property, fetchPropertyById, params } = this.props;
    if (params.propertyId) {
      if (property.propertyDetail) {
        if (property.propertyDetail.id == params.propertyId) {
          return;
        }
      }

      fetchPropertyById(params.propertyId);
    }
  }

  componentDidUpdate(prevProps, prevState) {
    this.redirectIfNotLogin();
  }

  render() {
    const { user } = this.props;
    if (user.logged == -1) {
      return <Loader />;
    }

    const headerValues = {
      title: 'CoffeeT',
      titleIcon: 'fa fa-home',
      githubLink: 'https://github.com/jepz20/coffee_tracker',
      menuItems: [
        {
          label: 'News',
          icon: 'fa fa-newspaper-o',
          index: 0,
          route: '/news',
        }, {
          label: 'Properties',
          icon: 'fa fa-home',
          index: 1,
          route: '/properties',
        },
      ],
    };
    return (
      <div>
        <Header headerValues={ headerValues }/>
        <main>
          { this.props.children }
        </main>
      </div>
    );
  }
}

Main = connect(mapStateToProps, actions)(Main);

export default Main;