text:
using DataAccess;
using FCSAmerica.DifferenceMaker;
using FCSAmerica.DifferenceMaker.Models;
using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.UI.WebControls;

#endregion

partial class Admin_Reporting : System.Web.UI.Page
{
    ILog _log = LogManager.GetLogger("Reporting");

    #region  Constants...

    private const int VW_REPORT_SELECTION = 0;

    #endregion

    #region  Private Attributes...

    private static string _currentPayPeriod = string.Empty;

    #endregion

    #region  Event Handlers...

    /// <summary>
    /// Initializes the web page.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
    override protected void OnInit(EventArgs e)
    {
        base.OnInit(e);
        lnkAwardsByEmployee.Click += this.lnkAwardsByEmployee_Click;
        lnkAybForTax.Click += this.lnkAybForTax_Click;
        ddlYearAyb.SelectedIndexChanged += this.ddlYearAyb_SelectedIndexChanged;
    }

    //ORIGINAL LINE: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles this.Load
    override protected void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (!(Page.IsPostBack))
        {
            if (UserUtil.IsCurrentUserAdmin())
            {
                //Set so person can view all awards, and do record deletions
                Session["currentUser_EmpID"] = -1;

                //Only Admins can execute the tax report
                lnkAybForTax.Visible = true;
            }
            else
            {
                //If the person isn't in "AYBAdmins", get their user ID, so the report will only be on their subemployees
                GetCurrentUser();

                //Hide the tax report link if the current user is not an Admin
                //lnkAybForTax.Visible = false;
                lnkAybForTax.Visible = false;
            }

            //Set the initial view
            this.mvAdmin.ActiveViewIndex = VW_REPORT_SELECTION;

            //Obtain the current pay period
            _currentPayPeriod = GetCurrentPayPeriod();

            //Populate the year drop-down list with a set of valid years (based on what's in the database)
            PopulateYearsLists();

            //Populate the pay period drop-down list based on the currently selected year
            PopulatePayPeriods(DateTime.Now.Year);
            Session["CurrentNodeValue"] = "0";
        }
    }

    /// <summary>
    /// Generates the "Awards for Tax Purposes" report.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
    protected void btnGenerateTaxReport_Click(object sender, System.EventArgs e)
    {
        this.treeEmployees.Visible = false;

        if (this.ddlAybReportType.SelectedIndex == 0)
        {
            Session["fileName"] = "AYB25DollarAwards";
        }
        else if (this.ddlAybReportType.SelectedIndex == 1)
        {
            Session["fileName"] = "AYBOtherDollarAwards";
        }
    }

    /// <summary>
    /// Displays the "Awards by Employee" report criteria form.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
    protected void lnkAwardsByEmployee_Click(object sender, System.EventArgs e)
    {
        GetActiveEmployees();

        if (this.treeEmployees.Nodes != null)
        {
            this.mvAdmin.ActiveViewIndex = 1;
        }
    }

    /// <summary>
    /// Displays the "Awards for Tax Purposes" report criteria form.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
    protected void lnkAybForTax_Click(object sender, System.EventArgs e)
    {
        this.mvAdmin.ActiveViewIndex = 2;
    }

    /// <summary>
    /// Reloads the pay period selection drop-down list when a different year is selected.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
    protected void ddlYearAyb_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        PopulatePayPeriods(int.Parse(ddlYearAyb.SelectedValue));
    }

    #endregion

    #region  Private Methods...

    /// <summary>
    /// Populates the years lists based on the minimum and maximum years found in the payroll schedules
    /// stored within the database.
    /// </summary>
    private void PopulateYearsLists()
    {
        ddlYearAyb.Items.Clear();

        for (int year = GetMinimumPayPeriodYear(); year <= DateTime.Now.Year; year++)
        {
            ddlYearAyb.Items.Add(new ListItem(year.ToString(), year.ToString()));

            if (year == DateTime.Now.Year)
            {
                ddlYearAyb.SelectedIndex = ddlYearAyb.Items.Count - 1;
            }
        }
    }

    /// <summary>
    /// Populates the list of active employees that report to the person currently logged in.
    /// </summary>
    private void GetActiveEmployees()
    {
        this.treeEmployees.Visible = true;
        //this.pnlGridButtons.Visible = false;

        DataSet dsEmployees = new DataSet();
        var tvEmployees = this.treeEmployees;
        //Get the leader information for the root node of the tree
        var currentUserEmpID = SessionHelper.GetValue<int>(Session["currentUser_EmpID"]);
        var dtLeaders = GetLeaders(currentUserEmpID);
        var dtEmployees = GetEmployees(currentUserEmpID);

        dsEmployees.Tables.Add(dtLeaders);
        dsEmployees.Tables.Add(dtEmployees);

        //add relations to dataset to allow for hierarchical logic
        dsEmployees.Relations.Add("relEmployees", dsEmployees.Tables["dtLeaders"].Columns["Employee_ID"], dsEmployees.Tables["dtEmployees"].Columns["LeaderEmployee_ID"], false);
        dsEmployees.Relations.Add("relEmptoLeader", dsEmployees.Tables["dtEmployees"].Columns["Employee_ID"], dsEmployees.Tables["dtEmployees"].Columns["LeaderEmployee_ID"], false);

        TreeNode nodeLeader;
        TreeNode nodeEmployee = null;
        TreeNode nodeEmployee_level2 = null;
        TreeNode nodeEmployee_level3 = null;
        TreeNode nodeEmployee_level4 = null;

        foreach (DataRow rowLeader in dsEmployees.Tables["dtLeaders"].Rows)
        {
            //Leader
            nodeLeader = new TreeNode();
            nodeLeader.Text = (string)rowLeader["Leader_Name"];
            nodeLeader.Value = rowLeader["Employee_ID"].ToString();
            tvEmployees.Nodes.Add(nodeLeader);

            foreach (DataRow rowemployee in rowLeader.GetChildRows("relEmployees"))
            {
                //Leader
                // -SubLeader
                nodeEmployee = new TreeNode();
                nodeEmployee.Text = (string)rowemployee["NameDisplay"];
                nodeEmployee.Value = rowemployee["Employee_ID"].ToString();
                nodeLeader.ChildNodes.Add(nodeEmployee);
                foreach (DataRow rowemployee_level2 in rowemployee.GetChildRows("relEmpToLeader"))
                {
                    //Leader
                    //   -SubLeader
                    //       -SubLeader
                    nodeEmployee_level2 = new TreeNode();
                    nodeEmployee_level2.Text = (string)rowemployee_level2["NameDisplay"];
                    nodeEmployee_level2.Value = rowemployee_level2["Employee_ID"].ToString();
                    nodeEmployee.ChildNodes.Add(nodeEmployee_level2);
                    foreach (DataRow rowEmployee_level3 in rowemployee_level2.GetChildRows("relEmpToLeader"))
                    {
                        //Leader
                        //   -SubLeader
                        //       -SubLeader
                        //           -Subleader
                        nodeEmployee_level3 = new TreeNode();
                        nodeEmployee_level3.Text = (string)rowEmployee_level3["NameDisplay"];
                        nodeEmployee_level3.Value = rowEmployee_level3["Employee_ID"].ToString();
                        nodeEmployee_level2.ChildNodes.Add(nodeEmployee_level3);
                        foreach (DataRow rowEmployee_level4 in rowEmployee_level3.GetChildRows("relEmpToLeader"))
                        {
                            //Leader
                            //   -SubLeader
                            //       -SubLeader
                            //           -SubLeader
                            //               -Lowest Level Employee
                            nodeEmployee_level4 = new TreeNode();
                            nodeEmployee_level4.Text = (string)rowEmployee_level4["NameDisplay"];
                            nodeEmployee_level4.Value = rowEmployee_level4["Employee_ID"].ToString();
                            nodeEmployee_level3.ChildNodes.Add(nodeEmployee_level4);
                        }
                    }
                }
            }
        }

        //select first node of the tree automatically
        if (this.treeEmployees.Nodes.Count > 0)
        {
            this.treeEmployees.Nodes[0].Selected = true;
        }
    }

    private DataTable GetLeaders(int currentUserEmpId)
    {
        var tableName = "dtLeaders";
        var result = GetEmptyTable<Leader_S_Result>(tableName);

        using (var client = new HttpClient())
        {
            var url = "employee/leader/" + currentUserEmpId;
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
            var apiResponse = client.GetAsync(url).Result;
            if (apiResponse.StatusCode == HttpStatusCode.NotFound)
            {
                return result;
            }
            var data = apiResponse.Content.ReadAsAsync<DataTable>().Result;
            if (data.Rows.Count == 0)
            {
                return result;
            }

            FillTable(result, data);
            return result;
        }
    }

    private DataTable GetEmployees(int currentUserEmpId)
    {
        var tableName = "dtEmployees";
        var result = GetEmptyTable<Employees_OfLeader_Result>(tableName);

        using (var client = new HttpClient())
        {
            var url = "employee/leaderEmployee/" + currentUserEmpId;
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
            var apiResponse = client.GetAsync(url).Result;
            if (apiResponse.StatusCode == HttpStatusCode.NotFound)
            {
                return result;
            }

            var data = apiResponse.Content.ReadAsAsync<DataTable>().Result;
            if (data.Rows.Count == 0)
            {
                return result;
            }

            FillTable(result, data);
            return result;
        }
    }

    private DataTable GetEmptyTable<T>(string tableName)
    {
        var empty = new DataTable();
        foreach (var prop in typeof(T).GetProperties())
        {
            var propertyType = prop.PropertyType;
            if (propertyType.IsGenericType &&
                propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                propertyType = propertyType.GetGenericArguments()[0];
            }
            empty.Columns.Add(prop.Name, propertyType);
        }
        empty.TableName = tableName;
        return empty;
    }

    private void FillTable(DataTable table, DataTable data)
    {
        table.BeginLoadData();
        for (int i = 0; i < data.Rows.Count; i++)
        {
            table.LoadDataRow(data.Rows[i].ItemArray,true);
        }
        table.EndLoadData();
    }

    /// <summary>
    /// Gets the currently logged in user's customer ID and stores it within a session variable.
    /// </summary>
    /// <remarks>The Employee ID for the currently logged in user is stored in a session variable
    /// called "currentUser_empID".</remarks>
    private void GetCurrentUser()
    {
        var loggedUserProvider = new LoggedUserProvider();
        var loggedUser = loggedUserProvider.GetLoggedUserFromNetworkId();
        var currentUserID = loggedUser.Employee_ID;
        Session["currentUser_empID"] = currentUserID;
    }

    /// <summary>
    /// Gets the current pay period.
    /// </summary>
    /// <returns>The current pay period in the format of "YYYY-NN" where:
    ///   YYYY = Year
    ///   NN   = Pay period number.
    /// If no pay period is available for the current date, then an empty string is returned.</returns>
    private string GetCurrentPayPeriod()
    {
        object payPeriod = null;
        return String.Empty;
    }

    /// <summary>
    /// Populates the pay period selection drop-down list.
    /// </summary>
    /// <param name="year">The year in which to populate pay periods for.</param>
    private void PopulatePayPeriods(int year)
    {
        ddlPayPeriodAyb.Items.Clear();

        var yearPaySchedules = new List<PaySchedule_OfYear_Result>();

        using (var client = new HttpClient())
        {
            var payScheduleUri = "report/payschedule/" + year;
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
            HttpResponseMessage responseMessage = client.GetAsync(payScheduleUri).Result;
            if (responseMessage.IsSuccessStatusCode)
            {
                yearPaySchedules = responseMessage.Content.ReadAsAsync<List<PaySchedule_OfYear_Result>>().Result;
            }
            foreach (var yearPaySchedule in yearPaySchedules)
            {
                var yearPay = yearPaySchedule.PayPeriodNumber_tx;

                if (yearPay != null)
                {
                    string payPeriodNumber = yearPay.Split('-')[1].Trim();
                    string formattedPayPeriodSchedule = yearPaySchedule.PayrollDeadlineDate_dt.ToShortDateString();
                    ddlPayPeriodAyb.Items.Add(new ListItem(string.Format("{0} - {1}", payPeriodNumber, formattedPayPeriodSchedule), payPeriodNumber));
                    if (yearPaySchedule.PayPeriodNumber_tx == _currentPayPeriod)
                    {
                        ddlPayPeriodAyb.SelectedIndex = ddlPayPeriodAyb.Items.Count - 1;
                    }
                }
            }
        }
    }

    /// <summary>
    /// Gets a list of payment period years from the database.
    /// </summary>
    /// <returns></returns>
    private int GetMinimumPayPeriodYear()
    {
        //Fills up the ddlAybYear with the min and max value of dropdown
        var minimumPayPeriodYears = new List<PaySchedule_MinMaxOfYear_Result>();
        var minYear = 0;
        using (var client = new HttpClient())
        {
            var requestUri = "report/minmaxpayschedule/";
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]);
            HttpResponseMessage responseMessage = client.GetAsync(requestUri).Result;
            if (responseMessage.IsSuccessStatusCode)
            {
                minimumPayPeriodYears = responseMessage.Content.ReadAsAsync<List<PaySchedule_MinMaxOfYear_Result>>().Result;
            }
            foreach (var payPeriodYear in minimumPayPeriodYears)
            {
                minYear = payPeriodYear.MinPayScheduleYear.HasValue ? payPeriodYear.MinPayScheduleYear.Value : DateTime.Now.Year;
            }
            return minYear;
        }
    }

    #endregion

    protected void treeEmployees_SelectedNodeChanged(object sender, EventArgs e)
    {
        Session["CurrentNodeValue"] = (sender as TreeView).SelectedNode.Value;
    }

}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="description" content="Materialize is a modern responsive CSS framework based on Material Design by Google. ">
    <title>About - Materialize</title>

    <link rel="apple-touch-icon-precomposed" href="images/favicon/apple-touch-icon-152x152.png">
    <meta name="msapplication-TileColor" content="#FFFFFF">
    <meta name="msapplication-TileImage" content="images/favicon/mstile-144x144.png">
    <link rel="icon" href="images/favicon/favicon-32x32.png" sizes="32x32">

    <meta name="theme-color" content="#EE6E73">

    <link href="css/prism.css" rel="stylesheet">
    <link href="css/ghpages-materialize.css" type="text/css" rel="stylesheet" media="screen,projection">
    <link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

menu

            <object id="front-page-logo" type="image/svg+xml" data="res/materialize.svg">Your browser does not support SVG</object>

            <input id="search" placeholder="Search">search

About

Getting Started

CSS

Color

Grid

Helpers

Media

Pulse

Sass

Shadow

Table

Transitions

Typography

Components

Badges

Buttons

Breadcrumbs

Cards

Collections

Footer

Icons

Navbar

Pagination

Preloader

JavaScript

Carousel

Collapsible

Dropdown

FeatureDiscovery

Media

Modals

Parallax

Pushpin

Scrollspy

Sidenav

Tabs

Toasts

Tooltips

Waves

Forms

Autocomplete

Checkboxes

Chips

Pickers

Radio Buttons

Range

Select

Switches

Text Inputs

Mobile

Showcase

Themes

Become a Patron

About

Learn about Material Design and our Project Team.

Material Design

Created and designed by Google, Material Design is a design language that combines the classic principles of successful design
          along with innovation and technology. Google's goal is to develop a system of design that allows for a unified user experience
          across all their products on any platform.

Principles

Material is the metaphor

The metaphor of material defines the relationship between space and motion. The idea is that the technology is inspired by paper and ink and is utilized to facilitate creativity and innovation. Surfaces and edges provide familiar visual cues that allow users to quickly understand the technology beyond the physical world.

Bold, graphic, intentional

Elements and components such as grids, typography, color, and imagery are not only visually pleasing, but also create a sense of hierarchy, meaning, and focus. Emphasis on different actions and components create a visual guide for users.

Motion provides meaning

Motion allows the user to draw a parallel between what they see on the screen and in real life. By providing both feedback and familiarity, this allows the user to fully immerse him or herself into unfamiliar technology. Motion contains consistency and continuity in addition to giving users additional subconscious information about objects and transformations.

Meet the Team

We are a team of students from Carnegie Mellon University.

Alvin Wang

Alvin is an Information Systems and Human Computer Interaction Major. He worked as a Software Engineer at Fidelity Investments this past summer.

Alan Chang

Alan is an Information Systems major with a minor in computer science. He worked at as a Front End Developer at Shift Collaborative this past summer.

Alex Mark

Alex is an Information Systems major with a minor in Human Computer Interaction. He worked as a software developer for Intuit this past summer.

Kevin Louie

Kevin is an Information Systems major with a minor in Human Computer Interaction. This past summer, he worked as a technology analyst at PPG Industries.

Material Design

Meet the Team

Help Materialize Grow

We hope you have enjoyed using Materialize and if you feel like it has helped you out and want to support the team you can help us by donating or backing us on Patreon. Any amount would help support and continue development on this project and is greatly appreciated.

                Support Us

Join the Discussion

We have a Gitter chat room set up where you can talk directly with us. Come in and discuss new features, future goals, general problems or questions, or anything else you can think of.

                Chat

Connect

                Follow @MaterializeCSS

              © 2014-2017 Materialize, All rights reserved.
              MIT License

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for the AssemblyTaskFactory</summary>
//-----------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Framework;
using Microsoft.Build.Collections;
using Microsoft.Build.Shared;
using System.Reflection;
using Microsoft.Build.Utilities;
using Microsoft.Build.Construction;

using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService;
using LoggingService = Microsoft.Build.BackEnd.Logging.LoggingService;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Xunit;

namespace Microsoft.Build.UnitTests.BackEnd
{
    /// <summary>
    /// Tests for the assembly task factory
    /// </summary>
    public class AssemblyTaskFactory_Tests
    {
        /// <summary>
        ///  A well instantiated task factory
        /// </summary>
        private AssemblyTaskFactory _taskFactory;

        /// <summary>
        /// The load info about a task to wrap in the assembly task factory
        /// </summary>
        private AssemblyLoadInfo _loadInfo;

        /// <summary>
        /// The loaded type from the initialized task factory.
        /// </summary>
        private LoadedType _loadedType;

        /// <summary>
        /// Initialize a task factory
        /// </summary>
        public AssemblyTaskFactory_Tests()
        {
            SetupTaskFactory(null, false);
        }

        #region AssemblyTaskFactory
        #region ExpectExceptions
        /// <summary>
        /// Make sure we get an invalid project file exception when a null load info is passed to the factory
        /// </summary>
        [Fact]
        public void NullLoadInfo()
        {
            Assert.Throws<ArgumentNullException>(() =>
            {
                AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
                taskFactory.InitializeFactory(null, "TaskToTestFactories", new Dictionary<string, TaskPropertyInfo>(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty);
            }
           );
        }
        /// <summary>
        /// Make sure we get an invalid project file exception when a null task name is passed to the factory
        /// </summary>
        [Fact]
        public void NullTaskName()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
                taskFactory.InitializeFactory(_loadInfo, null, new Dictionary<string, TaskPropertyInfo>(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty);
            }
           );
        }
        /// <summary>
        /// Make sure we get an invalid project file exception when an empty task name is passed to the factory
        /// </summary>
        [Fact]
        public void EmptyTaskName()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
                taskFactory.InitializeFactory(_loadInfo, String.Empty, new Dictionary<string, TaskPropertyInfo>(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty);
            }
           );
        }
        /// <summary>
        /// Make sure we get an invalid project file exception when the task is not in the info
        /// </summary>
        [Fact]
        public void GoodTaskNameButNotInInfo()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
                taskFactory.InitializeFactory(_loadInfo, "RandomTask", new Dictionary<string, TaskPropertyInfo>(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty);
            }
           );
        }
        /// <summary>
        /// Make sure we get an internal error when we call the initialize factory on the public method.
        /// This is done because we cannot properly initialize the task factory using the public interface and keep
        /// backwards compatibility with orcas and whidbey.
        /// </summary>
        [Fact]
        public void CallPublicInitializeFactory()
        {
            Assert.Throws<InternalErrorException>(() =>
            {
                AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
                taskFactory.Initialize(String.Empty, new Dictionary<string, TaskPropertyInfo>(), String.Empty, null);
            }
           );
        }
        /// <summary>
        /// Make sure we get an internal error when we call the ITaskFactory2 version of initialize factory.
        /// This is done because we cannot properly initialize the task factory using the public interface and keep
        /// backwards compatibility with orcas and whidbey.
        /// </summary>
        [Fact]
        public void CallPublicInitializeFactory2()
        {
            Assert.Throws<InternalErrorException>(() =>
            {
                AssemblyTaskFactory taskFactory = new AssemblyTaskFactory();
                taskFactory.Initialize(String.Empty, null, new Dictionary<string, TaskPropertyInfo>(), String.Empty, null);
            }
           );
        }
        #endregion

        /// <summary>
        /// Verify that we can ask the factory if a given task is in the factory and get the correct result back
        /// </summary>
        [Fact]
        public void CreatableByTaskFactoryGoodName()
        {
            Assert.True(_taskFactory.TaskNameCreatableByFactory("TaskToTestFactories", null, String.Empty, null, ElementLocation.Create(".", 1, 1)));
        }

        /// <summary>
        /// Expect a false answer when we ask for a task which is not in the factory.
        /// </summary>
        [Fact]
        public void CreatableByTaskFactoryNotInAssembly()
        {
            Assert.False(_taskFactory.TaskNameCreatableByFactory("NotInAssembly", null, String.Empty, null, ElementLocation.Create(".", 1, 1)));
        }

        /// <summary>
        /// Expect a false answer when we ask for a task which is not in the factory.
        /// </summary>
        [Fact]
        public void CreatableByTaskFactoryNotInAssemblyEmptyTaskName()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                Assert.False(_taskFactory.TaskNameCreatableByFactory(String.Empty, null, String.Empty, null, ElementLocation.Create(".", 1, 1)));
            }
           );
        }
        /// <summary>
        /// Expect a false answer when we ask for a task which is not in the factory.
        /// </summary>
        [Fact]
        public void CreatableByTaskFactoryNullTaskName()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                Assert.False(_taskFactory.TaskNameCreatableByFactory(null, null, String.Empty, null, ElementLocation.Create(".", 1, 1)));
            }
           );
        }
        /// <summary>
        /// Make sure that when an explicitly matching identity is specified (e.g. the identity is non-empty),
        /// it still counts as correct.
        /// </summary>
        [Fact]
        public void CreatableByTaskFactoryMatchingIdentity()
        {
            IDictionary<string, string> factoryIdentityParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            factoryIdentityParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.currentRuntime);
            factoryIdentityParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);

            SetupTaskFactory(factoryIdentityParameters, false /* don't want task host */);

            IDictionary<string, string> taskIdentityParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            taskIdentityParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4);
            taskIdentityParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

            Assert.True(_taskFactory.TaskNameCreatableByFactory("TaskToTestFactories", taskIdentityParameters, String.Empty, null, ElementLocation.Create(".", 1, 1)));
        }

        /// <summary>
        /// Verify that if the task identity parameters don't match the factory identity, TaskNameCreatableByFactory
        /// returns false.
        /// </summary>
        [Fact]
        public void CreatableByTaskFactoryMismatchedIdentity()
        {
            IDictionary<string, string> factoryIdentityParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            factoryIdentityParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
            factoryIdentityParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);

            SetupTaskFactory(factoryIdentityParameters, false /* don't want task host */);

            IDictionary<string, string> taskIdentityParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            taskIdentityParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4);
            taskIdentityParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);

            Assert.False(_taskFactory.TaskNameCreatableByFactory("TaskToTestFactories", taskIdentityParameters, String.Empty, null, ElementLocation.Create(".", 1, 1)));
        }

        /// <summary>
        /// Make sure the number of properties retrieved from the task factory are the same number retrieved from the type directly.
        /// </summary>
        [Fact]
        public void VerifyGetTaskParameters()
        {
            TaskPropertyInfo[] propertyInfos = _taskFactory.GetTaskParameters();
            LoadedType comparisonType = new LoadedType(typeof(TaskToTestFactories), _loadInfo);
            PropertyInfo[] comparisonInfo = comparisonType.Type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            Assert.Equal(comparisonInfo.Length, propertyInfos.Length);

            bool foundExpectedParameter = false;
            bool foundNotExpectedParameter = false;

            for (int i = 0; i < propertyInfos.Length; i++)
            {
                if (propertyInfos[i].Name.Equals("ExpectedParameter", StringComparison.OrdinalIgnoreCase))
                {
                    foundExpectedParameter = true;
                }

                if (propertyInfos[i].Name.Equals("NotExpectedParameter", StringComparison.OrdinalIgnoreCase))
                {
                    foundNotExpectedParameter = true;
                }
            }

            Assert.True(foundExpectedParameter);
            Assert.False(foundNotExpectedParameter);
        }

        /// <summary>
        /// Verify a good task can be created.
        /// </summary>
        [Fact(Skip = "Ignored in MSTest")]
        // Ignore: Test requires installed toolset.
        public void VerifyGoodTaskInstantiation()
        {
            ITask createdTask = null;
            try
            {
                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.False(createdTask is TaskHostTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that does not use the task host can be created when passed "don't care"
        /// for the task invocation task host parameters.
        /// </summary>
        [Fact(Skip = "Ignored in MSTest")]
        // Ignore: Test requires installed toolset.
        public void VerifyMatchingTaskParametersDontLaunchTaskHost1()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.False(createdTask is TaskHostTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that does not use the task host can be created when passed task host
        /// parameters that explicitly match the current process.
        /// </summary>
        [Fact(Skip = "Ignored in MSTest")]
        // Ignore: Test requires installed toolset.
        public void VerifyMatchingTaskParametersDontLaunchTaskHost2()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.GetCurrentMSBuildArchitecture());

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.False(createdTask is TaskHostTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that does not use the task host can be created when passed "don't care"
        /// for the task invocation task host parameters.
        /// </summary>
        [Fact(Skip = "Ignored in MSTest")]
        // Ignore: Test requires installed toolset.
        public void VerifyMatchingUsingTaskParametersDontLaunchTaskHost1()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

                SetupTaskFactory(taskParameters, false /* don't want task host */);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.False(createdTask is TaskHostTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that does not use the task host can be created when passed task host
        /// parameters that explicitly match the current process.
        /// </summary>
        [Fact(Skip = "Ignored in MSTest")]
        // Ignore: Test requires installed toolset.
        public void VerifyMatchingUsingTaskParametersDontLaunchTaskHost2()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.GetCurrentMSBuildArchitecture());

                SetupTaskFactory(taskParameters, false /* don't want task host */);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.False(createdTask is TaskHostTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that uses the task host can be created when passed task host
        /// parameters that explicitly do not match the current process.
        /// </summary>
        [Fact(Skip = "Ignored in MSTest")]
        // Ignore: Test requires installed toolset.
        public void VerifyMatchingParametersDontLaunchTaskHost()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> factoryParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                factoryParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4);

                SetupTaskFactory(factoryParameters, false /* don't want task host */);

                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.False(createdTask is TaskHostTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that uses the task host can be created when passed task host
        /// parameters that explicitly do not match the current process.
        /// </summary>
        [Fact]
        public void VerifyNonmatchingUsingTaskParametersLaunchTaskHost()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

                SetupTaskFactory(taskParameters, false /* don't want task host */);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.IsAssignableFrom(typeof(TaskHostTask), createdTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that uses the task host can be created when passed task host
        /// parameters that explicitly do not match the current process.
        /// </summary>
        [Fact]
        public void VerifyNonmatchingTaskParametersLaunchTaskHost()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.IsAssignableFrom(typeof(TaskHostTask), createdTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that uses the task host can be created when passed task host
        /// parameters that explicitly do not match the current process.
        /// </summary>
        [Fact]
        public void VerifyNonmatchingParametersLaunchTaskHost()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> factoryParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                factoryParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);

                SetupTaskFactory(factoryParameters, false /* don't want task host */);

                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.IsAssignableFrom(typeof(TaskHostTask), createdTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that uses the task host can be created when the task factory is
        /// explicitly instructed to launch the task host.
        /// </summary>
        [Fact]
        public void VerifyExplicitlyLaunchTaskHost()
        {
            ITask createdTask = null;
            try
            {
                SetupTaskFactory(null, true /* want task host */);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.IsAssignableFrom(typeof(TaskHostTask), createdTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that uses the task host can be created when the task factory is
        /// explicitly instructed to launch the task host.
        /// </summary>
        [Fact]
        public void VerifyExplicitlyLaunchTaskHostEvenIfParametersMatch1()
        {
            ITask createdTask = null;
            try
            {
                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

                SetupTaskFactory(taskParameters, true /* want task host */);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.IsAssignableFrom(typeof(TaskHostTask), createdTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that uses the task host can be created when the task factory is
        /// explicitly instructed to launch the task host.
        /// </summary>
        [Fact]
        public void VerifyExplicitlyLaunchTaskHostEvenIfParametersMatch2()
        {
            ITask createdTask = null;
            try
            {
                SetupTaskFactory(null, true /* want task host */);

                IDictionary<string, string> taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.IsAssignableFrom(typeof(TaskHostTask), createdTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Verify a good task that uses the task host can be created when the task factory is
        /// explicitly instructed to launch the task host.
        /// </summary>
        [Fact(Skip = "Ignored in MSTest")]
        // Ignore: Test requires installed toolset.
        public void VerifySameFactoryCanGenerateDifferentTaskInstances()
        {
            ITask createdTask = null;
            IDictionary<string, string> factoryParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            factoryParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.any);
            factoryParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.any);

            SetupTaskFactory(factoryParameters, explicitlyLaunchTaskHost: false);

            try
            {
                // #1: don't launch task host
                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), null, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.False(createdTask is TaskHostTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }

            try
            {
                // #2: launch task host
                var taskParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr2);
                taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.currentArchitecture);

                createdTask = _taskFactory.CreateTaskInstance(ElementLocation.Create("MSBUILD"), null, new MockHost(), taskParameters, new AppDomainSetup(), false);
                Assert.NotNull(createdTask);
                Assert.IsAssignableFrom(typeof(TaskHostTask), createdTask);
            }
            finally
            {
                if (createdTask != null)
                {
                    _taskFactory.CleanupTask(createdTask);
                }
            }
        }

        /// <summary>
        /// Abstract out the creation of the new AssemblyTaskFactory with default task, and
        /// with some basic validation.
        /// </summary>
        private void SetupTaskFactory(IDictionary<string, string> factoryParameters, bool explicitlyLaunchTaskHost)
        {
            _taskFactory = new AssemblyTaskFactory();
            _loadInfo = AssemblyLoadInfo.Create(null, Assembly.GetAssembly(typeof(TaskToTestFactories)).Location);
            _loadedType = _taskFactory.InitializeFactory(_loadInfo, "TaskToTestFactories", new Dictionary<string, TaskPropertyInfo>(), string.Empty, factoryParameters, explicitlyLaunchTaskHost, null, ElementLocation.Create("NONE"), String.Empty);
            Assert.True(_loadedType.Assembly.Equals(_loadInfo)); // "Expected the AssemblyLoadInfo to be equal"
        }

        #endregion

        #region InternalClasses
        /// <summary>
        ///  Create a task which can be used to test the factories
        /// </summary>
        public class TaskToTestFactories : AppDomainIsolatedTask
        {
            /// <summary>
            /// Give a parameter which can be considered expected
            /// </summary>
            public string ExpectedParameter
            {
                get;
                set;
            }

            /// <summary>
            /// Expect not to find this parameter as it is internal
            /// </summary>
            internal string NotExpected
            {
                get;
                set;
            }

            /// <summary>
            /// Execute the test
            /// </summary>
            public override bool Execute()
            {
                return true;
            }
        }
        #endregion
    }
}


text:
package org.gradle.api.internal.artifacts.ivyservice.ivyresolve.memcache;

import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.BuildableArtifactResolveResult;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.*;
import org.gradle.api.internal.artifacts.metadata.ComponentArtifactMetaData;
import org.gradle.api.internal.artifacts.metadata.DependencyMetaData;

// TODO:DAZ Should share local and remote caches, and use make in-memory caching a decorator over filesystem caching
class InMemoryCachedModuleComponentRepository extends BaseModuleComponentRepository {
    final InMemoryCacheStats stats;
    private final ModuleComponentRepositoryAccess localAccess;
    private final ModuleComponentRepositoryAccess remoteAccess;

    public InMemoryCachedModuleComponentRepository(InMemoryModuleComponentRepositoryCaches cache, ModuleComponentRepository delegate) {
        super(delegate);
        this.stats = cache.stats;
        this.localAccess = new CachedAccess(delegate.getLocalAccess(), cache.localArtifactsCache, cache.localMetaDataCache);
        this.remoteAccess = new CachedAccess(delegate.getRemoteAccess(), cache.remoteArtifactsCache, cache.remoteMetaDataCache);
    }

    @Override
    public ModuleComponentRepositoryAccess getLocalAccess() {
        return localAccess;
    }

    @Override
    public ModuleComponentRepositoryAccess getRemoteAccess() {
        return remoteAccess;
    }

    private class CachedAccess extends BaseModuleComponentRepositoryAccess {
        private final InMemoryMetaDataCache metaDataCache;
        private final InMemoryArtifactsCache artifactsCache;

        public CachedAccess(ModuleComponentRepositoryAccess access, InMemoryArtifactsCache artifactsCache, InMemoryMetaDataCache metaDataCache) {
            super(access);
            this.artifactsCache = artifactsCache;
            this.metaDataCache = metaDataCache;
        }

        public void listModuleVersions(DependencyMetaData dependency, BuildableModuleVersionSelectionResolveResult result) {
            if(!metaDataCache.supplyModuleVersions(dependency.getRequested(), result)) {
                super.listModuleVersions(dependency, result);
                metaDataCache.newModuleVersions(dependency.getRequested(), result);
            }
        }

        public void resolveComponentMetaData(DependencyMetaData dependency, ModuleComponentIdentifier moduleComponentIdentifier, BuildableModuleVersionMetaDataResolveResult result) {
            if(!metaDataCache.supplyMetaData(moduleComponentIdentifier, result)) {
                super.resolveComponentMetaData(dependency, moduleComponentIdentifier, result);
                metaDataCache.newDependencyResult(moduleComponentIdentifier, result);
            }
        }

        public void resolveArtifact(ComponentArtifactMetaData artifact, ModuleSource moduleSource, BuildableArtifactResolveResult result) {
            if (!artifactsCache.supplyArtifact(artifact.getId(), result)) {
                super.resolveArtifact(artifact, moduleSource, result);
                artifactsCache.newArtifact(artifact.getId(), result);
            }
        }
    }
}


text:
package com.intellij.openapi.ui.ex;

import com.intellij.openapi.ui.MultiLineLabelUI;
import org.jetbrains.annotations.Nls;

import javax.swing.*;
import java.awt.*;

public class MultiLineLabel extends JLabel {
  public MultiLineLabel() { }

  public MultiLineLabel(@Nls String text) {
    super(text);
  }

  @Override
  public void updateUI() {
    setUI(new MultiLineLabelUI());
  }

  @Override
  public Dimension getMinimumSize() {
    return getPreferredSize();
  }
}


text:
LOCALWIKI="C:\Users\rafas\Documents\wiki"
LIVEWIKI="C:\Users\rafas\Documents\FreeCodeCamp.wiki"
REMOTE="upstream"
BRANCH="master"

echo "FreeCodeCamp Wiki updater v1"
echo
echo "Move to Local Wiki directory at " + $LOCALWIKI
cd $LOCALWIKI
echo
echo "Updating local repository..."
git pull
git status
echo
echo "Done!"
echo "Going to the live Wiki ..."
cd $LIVEWIKI
echo
echo "Update live wiki..."
git fetch --all --prune
git pull $REMOTE $BRANCH
git push
echo "Done!"
echo
# Keep the windows Open until I press a key
echo "Press any key to close this windows..."
read -n 1 -s


text:
class Widgets::Text < Widget
  settings_attr_accessor({style: [:color, :size_x, :size_y, :row, :col]})
  settings_attr_accessor({custom: [:title, :text, :moreinfo]})

  def dashing_data_hash
    {
      id: self.secret_token,
      view: self.dashing_type,
      title: self.title,
      text: self.text,
      moreinfo: self.moreinfo
    }.merge(self.last_values)
  end
end


text:
game.RobotUp = me.Entity.extend({
  init: function(x, y, settings) {
    // define this here instead of tiled
     //var skin = Math.floor((Math.random()*6)+1);
      settings.name = "enemy";
   this.hp = 1200;
      settings.image = "robot";
        this.now = new Date().getTime();
      this.lastShot = this.now;
     this.touchSound = false;
      this.prevMove = 0;
    // save the area size defined in Tiled
    var width = settings.width;
    var height = settings.height;
    this.type = "EnemyEntity";
    // adjust the size setting information to match the sprite size
    // so that the entity object is created with the right size
    settings.spritewidth = settings.width = 32;
    settings.spriteheight = settings.height = 32;

    // call the parent constructor
    this._super(me.Entity, 'init', [x, y , settings]);

	 this.body.gravity = 0;

    // set start/end position based on the initial area size
    y = this.pos.y;
    this.startY = y;
    this.endY   = y + height - settings.spriteheight;
    this.pos.y  = y + height - settings.spriteheight;

    // manually update the entity bounds as we manually change the position
    this.updateBounds();

	this.body.collisionType = me.collision.types.ENEMY_OBJECT;

 this.renderable.flipX(this.walkLeft);
    // to remember which side we were walking
    this.walkLeft = false;

 this.renderable.addAnimation("run_down", [0,1,2] );
      this.renderable.addAnimation("run_up", [9,10,11] );
    // walking & jumping speed
    this.body.setVelocity(2, 3);

  },

  // manage the enemy movement
  update: function(dt) {
 this.now = new Date().getTime();
    if (this.alive) {
        if(this.hp <= 0) me.game.world.removeChild(this);
      if (this.walkLeft && this.pos.y <= this.startY) {
      this.walkLeft = false;
           this.touchSound = false; // here is where I change it to false
          this.body.setVelocity( Math.floor((Math.random()*5)+1), Math.floor((Math.random()*5)+1));
    } else if (!this.walkLeft && this.pos.y >= this.endY) {
      this.walkLeft = true;
         this.touchSound = false; // here is where I change it to false
        this.body.setVelocity( Math.floor((Math.random()*5)+1), Math.floor((Math.random()*5)+1));
    }
    // make it walk
   // this.renderable.flipX(this.walkLeft);
         var buffer = this.walkLeft ? -32:32;
        if((Math.round(this.now/1000)%2 === 0) && ((this.now - this.lastShot) >= 500)){
                this.lastShot = this.now;
                var bullet = me.pool.pull("EnemyBullet", this.pos.x, this.pos.y+buffer, {
				image: 'bullet',
				spritewidth: 24,
				spriteheight: 24,
				width: 24,
				height: 24
			}, [this.prevMove, downOn, leftOn, rightOn]);
			me.game.world.addChild(bullet, this.z);
        }

     if(this.walkLeft){
         this.prevMove = 0;
            this.body.vel.y +=-this.body.accel.y * me.timer.tick;
            if(!this.renderable.isCurrentAnimation("run_down")){
        this.renderable.setCurrentAnimation("run_down");
            }
        }else if(!this.walkLeft){
            this.prevMove = 2;
                    this.body.vel.y +=this.body.accel.y * me.timer.tick;
            if(!this.renderable.isCurrentAnimation("run_up")){
              this.renderable.setCurrentAnimation("run_up");
            }

    } else {
      this.body.vel.x = 0;
    }

    } else {
      this.body.vel.y = 0;
    }

    // update the body movement
    this.body.update(dt);

    // handle collisions against other shapes
    me.collision.check(this);

    // return true if we moved or if the renderable was updated
    return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
  },

  /**
   * colision handler
   * (called when colliding with other objects)
   */
  onCollision : function (response, other) {
  if (response.b.body.collisionType !== me.collision.types.WORLD_SHAPE) {
      // res.y >0 means touched by something on the bottom
      // which mean at top position for this one
  if(response.b.body.collisionType === me.collision.types.PROJECTILE_OBJECT) {
      this.hp -= 10;
        this.renderable.flicker(750);
  }

      if (this.alive && ((response.overlapV.y >= 0)  || (response.overlapV.x >= -5)) && response.b.body.collisionType === me.collision.types.PLAYER_OBJECT ) {

          //here i removed flickering and added audio stuff
         var choose = Math.floor((Math.random()*3)+1);
         if(this.touchSound == false){
          switch(choose){
                case 1: me.audio.play("criminalscum", .5);
                        this.touchSound = true;
                        break;
                case 2: me.audio.play("stoprest", .5); this.touchSound = true;break;

                case 3: me.audio.play("freezescumbag", .5);this.touchSound = true; break;

                default: me.audio.play("stoprest");this.touchSound = true; break;
          }
         }

      }
         if ((response.overlapV.x >= -5)&& response.b.body.collisionType !== me.collision.types.PLAYER_OBJECT){
                //this.moveV = false;
            this.walkLeft = this.walkLeft ? false: true;
             this.body.setVelocity( Math.floor((Math.random()*5)+1), Math.floor((Math.random()*5)+1));
         }

      return false;
    }
       if ((response.overlapV.x >= -5)&& response.b.body.collisionType !== me.collision.types.PLAYER_OBJECT){
                this.walkLeft = this.walkLeft ? false: true;
           this.body.setVelocity( Math.floor((Math.random()*5)+1), Math.floor((Math.random()*5)+1));
         }
      //this.touchSound = false;
    // Make all other objects solid
    return true;
}
});


text:
require 'rest-client'
require 'private_address_check'
require 'private_address_check/tcpsocket_ext'

module Seek
  module DownloadHandling
    class HTTPHandler
      include Seek::UploadHandling::ContentInspection

      attr_reader :url

      def initialize(url, fallback_to_get: true)
        @url = url
        @fallback_to_get = fallback_to_get
      end

      def info
        content_type = nil
        content_length = nil
        file_name = nil
        code = nil
        p = proc do
          begin
            response = RestClient.head(url, accept: '*/*')
            content_type = if is_slideshare_url?
                             'text/html'
                           else
                             response.headers[:content_type]
                           end
            content_length = response.headers[:content_length]
            file_name = determine_filename_from_disposition(response.headers[:content_disposition])
            code = response.code
          rescue RestClient::MethodNotAllowed => e # Try a GET if HEAD isn't allowed, but don't download anything
            if @fallback_to_get
              begin
                uri = URI.parse(url)
                Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
                  http.request(Net::HTTP::Get.new(uri)) do |res|
                    content_type = res['content-type']
                    content_length = res['content-length']
                    file_name = determine_filename_from_disposition(res['content-disposition'])
                    code = res.code.try(:to_i)
                  end
                end
              rescue Seek::DownloadHandling::BadResponseCodeException => e2
                code = e2.code
              end
            else
              code = e.http_code
            end
          rescue RestClient::Exception => e
            code = e.http_code
          rescue SocketError, Errno::ECONNREFUSED, Errno::EHOSTUNREACH
            code = 404
          end
        end

        begin
          if Seek::Config.allow_private_address_access
            p.call
          else
            PrivateAddressCheck.only_public_connections { p.call }
          end
        rescue PrivateAddressCheck::PrivateConnectionAttemptedError
          code = 490 # A made up error code to be handled internally by SEEK
        end

        file_name ||= determine_filename_from_url(@url)
        content_type ||= content_type_from_filename(file_name)

        {
          code: code,
          file_size: content_length.present? ? content_length.try(:to_i) : nil,
          content_type: content_type,
          file_name: file_name
        }
      end

      def fetch
        file = Tempfile.new('remote-content')
        file.binmode # Strange encoding issues occur if this is not set

        Seek::DownloadHandling::HTTPStreamer.new(url, size_limit: Seek::Config.hard_max_cachable_size).stream do |chunk|
          file << chunk
        end

        file
      end

      private

      # if it is a slideshare url, which starts with www.slideshare.net, and is made up of 2 parts (params ignored)
      # i.e http://www.slideshare.new/<org>/<slidetitle>
      #
      # this is a quick fix to get around slideshare not always giving a content type of text/html, and instead sometimes giving application/xml
      def is_slideshare_url?
        renderer = Seek::Renderers::SlideshareRenderer.new(nil)
        renderer.is_slideshare_url?(url)
      end
    end
  end
end


text:
package urlshortener.common.repository.fixture;

import urlshortener.common.domain.Click;
import urlshortener.common.domain.ShortURL;

public class ClickFixture {

	public static Click click(ShortURL su) {
		return new Click(null, su.getHash(), null, null, null, null, null, null, 0, 0);
	}
}


text: export { default } from 'ember-fhir/models/meta';


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.expm1Docs = void 0;
var expm1Docs = {
  name: 'expm1',
  category: 'Arithmetic',
  syntax: ['expm1(x)'],
  description: 'Calculate the value of subtracting 1 from the exponential value.',
  examples: ['expm1(2)', 'pow(e, 2) - 1', 'log(expm1(2) + 1)'],
  seealso: ['exp', 'pow', 'log']
};
exports.expm1Docs = expm1Docs;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.laranevans.warehouse</groupId>
        <artifactId>warehouse-parent</artifactId>
        <version>0.0.1</version>
    </parent>

    <groupId>com.laranevans</groupId>
    <artifactId>warehouse-application-starter</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>

    <name>Warehouse - Application starter</name>
    <description>This is a starter project from which Warehouse applications can be built.</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <warehouse.version>0.0.1</warehouse.version>
        <!-- Java 8 is a requirement because of support for Java 8 LocalDate/LocalDateTime -->
        <java.version>1.8</java.version>
        <jackson.version>2.6.0</jackson.version>
        <jackson.xml.version>2.5.3</jackson.xml.version>
        <velocity.version>1.7</velocity.version>
        <hikari.version>2.4.1</hikari.version>
        <woodstox.version>4.4.1</woodstox.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.3.0.BUILD-SNAPSHOT</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!--
         Database driver. Warehouse uses an in-memory h2 database just to make it easy to get up and running.
         You will want to add to or replace the h2 driver with the correct driver for your database of choice.
         -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.189</version>
        </dependency>
        <!-- Here we bring in the core Warehouse code as a dependency. -->
        <dependency>
            <groupId>com.laranevans</groupId>
            <artifactId>warehouse</artifactId>
            <version>${warehouse.version}</version>
        </dependency>
        <!--
          Hikari is a high-performance connection pool. It's compatible with whatever database driver you choose.
          So you should not need to change this.
          -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>${hikari.version}</version>
        </dependency>
        <!--
          log4jdbc is a nice library that helps for debugging database activity. It's not used by default. But it's
          easily enabled with a quick change to application.properties and another quick change to logback.xml.
          -->
        <dependency>
            <groupId>org.bgee.log4jdbc-log4j2</groupId>
            <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
            <version>1.16</version>
        </dependency>
        <!-- Jackson core provides JSON serialization/deserialization of request/response objects -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <!-- Jackson XML and woodstox provide support for XML requests/responses -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>${jackson.xml.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.woodstox</groupId>
            <artifactId>woodstox-core-asl</artifactId>
            <version>${woodstox.version}</version>
        </dependency>
        <!-- JSR-310 is needed for valid rendering of Java 8 LocalDate/LocalDateTime -->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.4.0</version>
        </dependency>
        <!-- Velocity is used for rendering various templates via the TemplateService. -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>${velocity.version}</version>
        </dependency>
        <!--
            Logback is a more configurable and faster logging engine than other options (e.g. log4j, java logging).
            See: http://logback.qos.ch/reasonsToSwitch.html
            -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.13</version>
        </dependency>
        <!-- Flyway for programmatic database migrations in Java. -->
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
            <version>3.2.1</version>
        </dependency>
        <!-- Spring dependencies below -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.2.5.RELEASE</version>
                <configuration>
                    <!-- Uncomment this section below in order to run Warehouse in debug mode -->
                    <jvmArguments>
                        -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
                    </jvmArguments>
                    <!--
                    -->
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.flywaydb</groupId>
                <artifactId>flyway-maven-plugin</artifactId>
                <version>3.2.1</version>
                <!--
                    Configuration is all done through src/main/resources/flyway.properties.
                -->
            </plugin>
        </plugins>
    </build>
    <!-- We need the Spring repositories right now because we're using a pre-release version of Spring. -->
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>
</project>


text:
package org.jfxvnc.net.rfb.codec.decoder.rect;

import java.util.List;
import org.jfxvnc.net.rfb.codec.PixelFormat;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class UnknownRectDecoder implements FrameRectDecoder {

  protected final int bpp;
  protected int capacity;

  public UnknownRectDecoder(PixelFormat pixelFormat) {
    this.bpp = pixelFormat.getBytePerPixel();
  }

  @Override
  public boolean decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable(capacity)) {
      return false;
    }
    in.skipBytes(capacity);
    return true;
  }

  @Override
  public void setRect(FrameRect rect) {
    this.capacity = rect.getWidth() * rect.getHeight() * bpp;
  }
}


text:
package org.ovirt.engine.api.restapi.resource;

import javax.ws.rs.core.Response;

import org.ovirt.engine.api.common.util.QueryHelper;
import org.ovirt.engine.api.model.Disk;
import org.ovirt.engine.api.model.StorageDomain;
import org.ovirt.engine.core.common.action.RemoveDiskParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.queries.GetUnregisteredDiskQueryParameters;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;

public class BackendStorageDomainDiskResource extends BackendDiskResource {

    private final String storageDomainId;
    private final BackendStorageDomainDisksResource parent;

    public static final String UNREGISTERED_CONSTRAINT_PARAMETER = "unregistered";

    protected BackendStorageDomainDiskResource(String id, BackendStorageDomainDisksResource parent) {
        super(id);
        this.storageDomainId = parent.getStorageDomainId().toString();
        this.parent = parent;
    }

    @Override
    protected Disk performGet(VdcQueryType query, VdcQueryParametersBase params) {
        Disk disk;
        if (QueryHelper.hasMatrixParam(getUriInfo(), UNREGISTERED_CONSTRAINT_PARAMETER)) {
            VdcQueryReturnValue result = runQuery(VdcQueryType.GetDiskByDiskId, new IdQueryParameters(guid));
            if (!result.getSucceeded() || result.getReturnValue() == null) {
                Guid storageDomainGuid = asGuid(storageDomainId);
                disk = super.performGet(VdcQueryType.GetUnregisteredDisk, new GetUnregisteredDiskQueryParameters(guid, storageDomainGuid, parent.getStoragePoolIdForDomain(storageDomainGuid)));
            } else {
                // The disk was found in the first get which means it is already registered. We must return nothing since the unregistered
                // parameter was passed.
                return notFound();
            }
        } else {
            disk = super.performGet(VdcQueryType.GetDiskByDiskId, new IdQueryParameters(guid));
        }
        if (disk.isSetStorageDomains() && !disk.getStorageDomains().getStorageDomains().isEmpty()) {
            for (StorageDomain sd : disk.getStorageDomains().getStorageDomains()) {
                if (sd.isSetId() && sd.getId().equals(this.storageDomainId)) {
                    return disk;
                }
            }
        }
        return notFound();
    }

    @Override
    protected Disk deprecatedPopulate(Disk model, org.ovirt.engine.core.common.businessentities.storage.Disk entity) {
        Disk populatedDisk = super.doPopulate(model, entity);

        // this code generates back-link to the corresponding SD
        populatedDisk.setStorageDomain(new StorageDomain());
        populatedDisk.getStorageDomain().setId(this.storageDomainId);

        return model;
    }

    public String getStorageDomainId() {
        return storageDomainId;
    }

    @Override
    public Response remove() {
        get();
        return performAction(VdcActionType.RemoveDisk, new RemoveDiskParameters(guid, asGuid(storageDomainId)));
    }
}


text:
ActiveRecord::Schema.define(version: 20170222132154) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"
  enable_extension "unaccent"

  create_table "agreement_revisions", force: :cascade do |t|
    t.integer  "agreement_id",                  null: false
    t.integer  "user_id",                       null: false
    t.integer  "state",             default: 0, null: false
    t.text     "purpose"
    t.text     "legal_base"
    t.string   "log"
    t.string   "file"
    t.text     "objection_message"
    t.integer  "revision_number",               null: false
    t.datetime "created_at",                    null: false
    t.datetime "updated_at",                    null: false
    t.index ["agreement_id"], name: "index_agreement_revisions_on_agreement_id", using: :btree
    t.index ["user_id"], name: "index_agreement_revisions_on_user_id", using: :btree
  end

  create_table "agreements", force: :cascade do |t|
    t.integer  "service_provider_organization_id", null: false
    t.integer  "service_consumer_organization_id", null: false
    t.datetime "created_at",                       null: false
    t.datetime "updated_at",                       null: false
    t.string   "client_secret"
    t.index ["service_consumer_organization_id"], name: "index_agreements_on_service_consumer_organization_id", using: :btree
    t.index ["service_provider_organization_id"], name: "index_agreements_on_service_provider_organization_id", using: :btree
  end

  create_table "agreements_services", force: :cascade do |t|
    t.integer "agreement_id", null: false
    t.integer "service_id",   null: false
    t.index ["agreement_id"], name: "index_agreements_services_on_agreement_id", using: :btree
    t.index ["service_id"], name: "index_agreements_services_on_service_id", using: :btree
  end

  create_table "notifications", force: :cascade do |t|
    t.integer  "user_id",                      null: false
    t.string   "subject_type",                 null: false
    t.integer  "subject_id",                   null: false
    t.string   "message",                      null: false
    t.boolean  "read",         default: false
    t.boolean  "seen",         default: false
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.string   "email"
    t.index ["subject_type", "subject_id"], name: "index_notifications_on_subject_type_and_subject_id", using: :btree
    t.index ["user_id"], name: "index_notifications_on_user_id", using: :btree
  end

  create_table "organizations", force: :cascade do |t|
    t.string "name", null: false
  end

  create_table "roles", id: false, force: :cascade do |t|
    t.integer "user_id",         null: false
    t.integer "organization_id", null: false
    t.string  "name",            null: false
    t.index ["organization_id"], name: "index_roles_on_organization_id", using: :btree
    t.index ["user_id"], name: "index_roles_on_user_id", using: :btree
  end

  create_table "schema_categories", force: :cascade do |t|
    t.string   "name",        null: false
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.string   "description"
  end

  create_table "schema_categories_schemas", force: :cascade do |t|
    t.integer "schema_id"
    t.integer "schema_category_id"
  end

  create_table "schema_versions", force: :cascade do |t|
    t.integer  "schema_id",               null: false
    t.integer  "version_number",          null: false
    t.jsonb    "spec",                    null: false
    t.datetime "created_at",              null: false
    t.datetime "updated_at",              null: false
    t.jsonb    "spec_with_resolved_refs"
    t.integer  "user_id",                 null: false
  end

  create_table "schemas", force: :cascade do |t|
    t.string   "name",           null: false
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
    t.tsvector "lexemes"
    t.string   "humanized_name"
    t.index ["lexemes"], name: "schemas_lexemes_idx", using: :gin
    t.index ["name"], name: "index_schemas_on_name", using: :btree
  end

  create_table "service_versions", force: :cascade do |t|
    t.integer  "service_id",                              null: false
    t.integer  "version_number",                          null: false
    t.jsonb    "spec",                                    null: false
    t.datetime "created_at",                              null: false
    t.datetime "updated_at",                              null: false
    t.integer  "status",                  default: 0
    t.integer  "user_id",                                 null: false
    t.boolean  "backwards_compatible",    default: false, null: false
    t.jsonb    "spec_with_resolved_refs"
    t.text     "reject_message"
  end

  create_table "services", force: :cascade do |t|
    t.string   "name",                            null: false
    t.integer  "organization_id",                 null: false
    t.datetime "created_at",                      null: false
    t.datetime "updated_at",                      null: false
    t.boolean  "public",          default: false
    t.tsvector "lexemes"
    t.string   "humanized_name"
    t.boolean  "featured",        default: false
    t.string   "provider_id"
    t.string   "provider_secret"
    t.index ["lexemes"], name: "services_lexemes_idx", using: :gin
  end

  create_table "users", force: :cascade do |t|
    t.string   "login_id",                           null: false
    t.string   "login_provider",                     null: false
    t.string   "id_token",                           null: false
    t.string   "name"
    t.integer  "sign_in_count",      default: 0,     null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
    t.datetime "created_at",                         null: false
    t.datetime "updated_at",                         null: false
    t.boolean  "can_create_schemas", default: false, null: false
    t.index ["login_id"], name: "index_users_on_login_id", unique: true, using: :btree
  end

  add_foreign_key "schema_categories_schemas", "schema_categories"
  add_foreign_key "schema_categories_schemas", "schemas"
  add_foreign_key "schema_versions", "schemas"
  add_foreign_key "schema_versions", "users"
  add_foreign_key "service_versions", "services"
  add_foreign_key "service_versions", "users"
  add_foreign_key "services", "organizations"
end


text:
int get_time_ms();

#endif // #ifndef MISC_INCLUDED


text:
// This file is automatically generated.

package adila.db;

/*
 * Spectralink PIVOT 8741/8753
 *
 * DEVICE: thor_6dq
 * MODEL: 8753
 */
final class thor5f6dq_8753 {
    public static final String DATA = "Spectralink|PIVOT 8741/8753|";
}


text:
/* vim: set syntax=c et sw=4 ts=4: */

#ifndef MMDEV_H
#define MMDEV_H

#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
#include "pautina-driver.h"

#ifdef __cplusplus
extern "C" {
#endif

extern int mmdev_open (const char * pathname, int flags);
extern int mmdev_close (int fd);
extern int mmdev_ioctl (int fd, unsigned long request, pautina_driver_ioctl_arg_t arg);
extern void * mmdev_mmap (void * addr, size_t length, int prot, int flags, int fd, off_t offset);
extern int mmdev_munmap (void * addr, size_t length);

extern void * mmdev_memcpy (void * dst, const void * src, size_t n);
extern void mmdev_put64 (volatile void * ptr, uint64_t value);
extern uint64_t mmdev_get64 (volatile void * ptr);
extern void mmdev_fence();

#ifdef __cplusplus
}
#endif

#endif /* MMDEV_H */


text:
require 'spec_helper'

RSpec.describe Gitlab::GithubImport::Importer::PullRequestImporter, :clean_gitlab_redis_cache do
  let(:project) { create(:project, :repository) }
  let(:client) { double(:client) }
  let(:user) { create(:user) }
  let(:created_at) { Time.new(2017, 1, 1, 12, 00) }
  let(:updated_at) { Time.new(2017, 1, 1, 12, 15) }
  let(:merged_at) { Time.new(2017, 1, 1, 12, 17) }

  let(:source_commit) { project.repository.commit('feature') }
  let(:target_commit) { project.repository.commit('master') }
  let(:milestone) { create(:milestone, project: project) }
  let(:state) { :closed }

  let(:pull_request) do
    alice = Gitlab::GithubImport::Representation::User.new(id: 4, login: 'alice')

    Gitlab::GithubImport::Representation::PullRequest.new(
      iid: 42,
      title: 'My Pull Request',
      description: 'This is my pull request',
      source_branch: 'feature',
      source_branch_sha: source_commit.id,
      target_branch: 'master',
      target_branch_sha: target_commit.id,
      source_repository_id: 400,
      target_repository_id: 200,
      source_repository_owner: 'alice',
      state: state,
      milestone_number: milestone.iid,
      author: alice,
      assignee: alice,
      created_at: created_at,
      updated_at: updated_at,
      merged_at: state == :closed && merged_at
    )
  end

  let(:importer) { described_class.new(pull_request, project, client) }

  describe '#execute' do
    it 'imports the pull request' do
      mr = double(:merge_request, id: 10)

      expect(importer)
        .to receive(:create_merge_request)
        .and_return([mr, false])

      expect(importer)
        .to receive(:set_merge_request_assignees)
        .with(mr)

      expect(importer)
        .to receive(:insert_git_data)
        .with(mr, false)

      expect_any_instance_of(Gitlab::GithubImport::IssuableFinder)
        .to receive(:cache_database_id)
        .with(mr.id)

      importer.execute
    end
  end

  describe '#create_merge_request' do
    before do
      allow(importer.milestone_finder)
        .to receive(:id_for)
        .with(pull_request)
        .and_return(milestone.id)
    end

    context 'when the author could be found' do
      before do
        allow(importer.user_finder)
          .to receive(:author_id_for)
          .with(pull_request)
          .and_return([user.id, true])
      end

      it 'imports the pull request with the pull request author as the merge request author' do
        expect(importer)
          .to receive(:insert_and_return_id)
          .with(
            {
              iid: 42,
              title: 'My Pull Request',
              description: 'This is my pull request',
              source_project_id: project.id,
              target_project_id: project.id,
              source_branch: 'github/fork/alice/feature',
              target_branch: 'master',
              state_id: 3,
              milestone_id: milestone.id,
              author_id: user.id,
              created_at: created_at,
              updated_at: updated_at
            },
            project.merge_requests
          )
          .and_call_original

        importer.create_merge_request
      end

      it 'returns the created merge request' do
        mr, exists = importer.create_merge_request

        expect(mr).to be_instance_of(MergeRequest)
        expect(exists).to eq(false)
      end

      context 'when the source and target branch are identical' do
        before do
          allow(pull_request).to receive_messages(
            source_repository_id: pull_request.target_repository_id,
            source_branch: 'master'
          )
        end

        it 'uses a generated source branch name for the merge request' do
          expect(importer)
            .to receive(:insert_and_return_id)
            .with(
              {
                iid: 42,
                title: 'My Pull Request',
                description: 'This is my pull request',
                source_project_id: project.id,
                target_project_id: project.id,
                source_branch: 'master-42',
                target_branch: 'master',
                state_id: 3,
                milestone_id: milestone.id,
                author_id: user.id,
                created_at: created_at,
                updated_at: updated_at
              },
              project.merge_requests
            )
            .and_call_original

          importer.create_merge_request
        end
      end

      context 'when the import fails due to a foreign key error' do
        it 'does not raise any errors' do
          expect(importer)
            .to receive(:insert_and_return_id)
            .and_raise(ActiveRecord::InvalidForeignKey, 'invalid foreign key')

          expect { importer.create_merge_request }.not_to raise_error
        end
      end

      context 'when the merge request already exists' do
        it 'returns the existing merge request' do
          mr1, exists1 = importer.create_merge_request
          mr2, exists2 = importer.create_merge_request

          expect(mr2).to eq(mr1)
          expect(exists1).to eq(false)
          expect(exists2).to eq(true)
        end
      end
    end

    context 'when the author could not be found' do
      before do
        allow(importer.user_finder)
          .to receive(:author_id_for)
          .with(pull_request)
          .and_return([project.creator_id, false])
      end

      it 'imports the pull request with the project creator as the merge request author' do
        expect(importer)
          .to receive(:insert_and_return_id)
          .with(
            {
              iid: 42,
              title: 'My Pull Request',
              description: "*Created by: alice*\n\nThis is my pull request",
              source_project_id: project.id,
              target_project_id: project.id,
              source_branch: 'github/fork/alice/feature',
              target_branch: 'master',
              state_id: 3,
              milestone_id: milestone.id,
              author_id: project.creator_id,
              created_at: created_at,
              updated_at: updated_at
            },
            project.merge_requests
          )
          .and_call_original

        importer.create_merge_request
      end
    end
  end

  describe '#set_merge_request_assignees' do
    let_it_be(:merge_request) { create(:merge_request) }

    before do
      allow(importer.user_finder)
        .to receive(:assignee_id_for)
        .with(pull_request)
        .and_return(user_id)

      importer.set_merge_request_assignees(merge_request)
    end

    context 'when pull request has an assignee' do
      let(:user_id) { user.id }

      it 'sets merge request assignees' do
        expect(merge_request.assignee_ids).to eq [user.id]
      end
    end

    context 'when pull request does not have any assignees' do
      let(:user_id) { nil }

      it 'does not set merge request assignees' do
        expect(merge_request.assignee_ids).to eq []
      end
    end
  end

  describe '#insert_git_data' do
    before do
      allow(importer.milestone_finder)
        .to receive(:id_for)
        .with(pull_request)
        .and_return(milestone.id)

      allow(importer.user_finder)
        .to receive(:author_id_for)
        .with(pull_request)
        .and_return([user.id, true])
    end

    it 'does not create the source branch if merge request is merged' do
      mr = insert_git_data

      expect(project.repository.branch_exists?(mr.source_branch)).to be_falsey
      expect(project.repository.branch_exists?(mr.target_branch)).to be_truthy
    end

    context 'when merge request is open' do
      let(:state) { :opened }

      it 'creates the source branch' do
        # Ensure the project creator is creating the branches because the
        # merge request author may not have access to push to this
        # repository. The project owner may also be a group.
        allow(project.repository).to receive(:add_branch).with(project.creator, anything, anything).and_call_original

        mr = insert_git_data

        expect(project.repository.branch_exists?(mr.source_branch)).to be_truthy
        expect(project.repository.branch_exists?(mr.target_branch)).to be_truthy
      end

      it 'is able to retry on pre-receive errors' do
        expect(importer).to receive(:insert_or_replace_git_data).twice.and_call_original
        expect(project.repository).to receive(:add_branch).and_raise('exception')

        expect { insert_git_data }.to raise_error('exception')

        expect(project.repository).to receive(:add_branch).with(project.creator, anything, anything).and_call_original

        mr = insert_git_data

        expect(project.repository.branch_exists?(mr.source_branch)).to be_truthy
        expect(project.repository.branch_exists?(mr.target_branch)).to be_truthy
        expect(mr.merge_request_diffs).to be_one
      end

      it 'ignores Git command errors when creating a branch' do
        expect(project.repository).to receive(:add_branch).and_raise(Gitlab::Git::CommandError)
        expect(Gitlab::ErrorTracking).to receive(:track_exception).and_call_original

        mr = insert_git_data

        expect(project.repository.branch_exists?(mr.source_branch)).to be_falsey
        expect(project.repository.branch_exists?(mr.target_branch)).to be_truthy
      end
    end

    it 'creates a merge request diff and sets it as the latest' do
      mr = insert_git_data

      expect(mr.merge_request_diffs.exists?).to eq(true)
      expect(mr.reload.latest_merge_request_diff_id).to eq(mr.merge_request_diffs.first.id)
    end

    it 'creates the merge request diff commits' do
      mr = insert_git_data

      diff = mr.merge_request_diffs.reload.first

      expect(diff.merge_request_diff_commits.exists?).to eq(true)
    end

    context 'when the merge request exists' do
      it 'creates the merge request diffs if they do not yet exist' do
        mr, _ = importer.create_merge_request

        mr.merge_request_diffs.delete_all

        importer.insert_git_data(mr, true)

        expect(mr.merge_request_diffs.exists?).to eq(true)
      end
    end

    def insert_git_data
      mr, exists = importer.create_merge_request
      importer.insert_git_data(mr, exists)
      mr
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<ram-component manifest-version="2.0"
               name="SIDefinitions" version="3" release="3" clevel="0" metamodel="9023">
    <description>
        <![CDATA[Model Library for Quantity Kinds and Units (SysML 1.2)]]>
    </description>
    <dependencies>
    </dependencies>
    <contributors>
      <contributor name="SysMLArchitect" version="3.2.00.9022"></contributor>
    </contributors>
    <roots>
      <root metaclass="Project" name="SIDefinitions" uuid="54204ce5-9615-460e-bee7-5507cc8560ea"></root>
    </roots>
</ram-component>


text:
layout: page
title: Basic Global Trade Fair
date: 2016-05-24
author: Paul Hunter
tags: weekly links, java
status: published
summary: Suspendisse tempus augue blandit nisl sagittis molestie.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 11/05/2016
  endDate: 11/06/2016
  ctyhocn: HOUKYHX
  groupCode: BGTF
published: true
---
Donec ligula mauris, condimentum eu dui in, posuere fermentum velit. Aenean vel felis erat. Nam in augue convallis, iaculis nibh at, eleifend leo. Nulla sit amet metus sed mi egestas aliquam. Quisque non tellus elit. Vivamus volutpat justo nisl, non vulputate leo tincidunt et. Nulla vel commodo tortor. In rhoncus metus non ante scelerisque mattis. Etiam non nibh pulvinar, maximus eros sit amet, sodales leo. Phasellus et enim eget ipsum interdum tempus.
Sed posuere iaculis nisi vel malesuada. Vivamus felis nibh, tincidunt eget lectus eu, accumsan fringilla dui. Nullam tempus metus a volutpat placerat. Proin malesuada orci ut eros tincidunt, quis auctor augue commodo. Suspendisse vitae condimentum augue, eget rhoncus tellus. Sed aliquet id neque vitae posuere. Integer ut molestie est. Mauris posuere lacus lectus, vitae luctus lorem volutpat a.

* Integer ut dui eget lacus gravida tempus
* Sed tincidunt erat ut condimentum iaculis.

Cras venenatis ultricies tincidunt. Aliquam eros ligula, elementum quis feugiat vitae, pulvinar id nunc. Morbi imperdiet arcu vitae lacus sagittis congue. In nisi est, cursus eget rhoncus in, egestas eget libero. Nunc sed ipsum hendrerit risus pulvinar viverra quis vitae ipsum. Suspendisse quis consectetur dui. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc maximus, nulla vel aliquet aliquet, ex ipsum maximus dolor, in eleifend augue nunc ut elit. Morbi commodo nulla ut auctor congue. Nullam vel neque lobortis, laoreet nisi a, scelerisque elit. Etiam euismod ex felis. Donec consequat posuere mi eu semper. Cras sodales sed orci sed lacinia. Pellentesque vitae felis lacinia, rutrum enim eu, condimentum lorem.