text:
using NLog.Internal.Pooling;
using NLog.Internal.Pooling.Pools;

namespace NLog.Targets
{
    using System;
    using System.Collections.Generic;

    using NLog.Common;
    using NLog.Config;
    using NLog.Internal;
    using NLog.Layouts;

    /// <summary>
    /// Represents logging target.
    /// </summary>
    [NLogConfigurationItem]
    public abstract class Target : ISupportsInitialize, IDisposable
    {
        private object lockObject = new object();
        private List<Layout> allLayouts;
        private bool scannedForLayouts;
        private Exception initializeException;

        /// <summary>
        /// Gets or sets the name of the target.
        /// </summary>
        /// <docgen category='General Options' order='10' />
        public string Name { get; set; }

        /// <summary>
        /// Gets the object which can be used to synchronize asynchronous operations that must rely on the .
        /// </summary>
        protected object SyncRoot
        {
            get { return this.lockObject; }
        }

        /// <summary>
        /// Gets the logging configuration this target is part of.
        /// </summary>
        protected LoggingConfiguration LoggingConfiguration { get; private set; }

        /// <summary>
        /// Gets a value indicating whether the target has been initialized.
        /// </summary>
        protected bool IsInitialized { get; private set; }

        /// <summary>
        /// Get all used layouts in this target.
        /// </summary>
        /// <returns></returns>
        internal List<Layout> GetAllLayouts()
        {

            if (!scannedForLayouts)
            {
                FindAllLayouts();
            }
            return allLayouts;
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
        {
            this.Initialize(configuration);
        }

        /// <summary>
        /// Closes this instance.
        /// </summary>
        void ISupportsInitialize.Close()
        {
            this.Close();
        }

        /// <summary>
        /// Closes the target.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Flush any pending log messages (in case of asynchronous targets).
        /// </summary>
        /// <param name="asyncContinuation">The asynchronous continuation.</param>
        public void Flush(AsyncContinuation asyncContinuation)
        {
            if (asyncContinuation == null)
            {
                throw new ArgumentNullException("asyncContinuation");
            }

            lock (this.SyncRoot)
            {
                if (!this.IsInitialized)
                {
                    asyncContinuation(null);
                    return;
                }

                asyncContinuation = AsyncHelpers.PreventMultipleCalls(this.LoggingConfiguration, asyncContinuation);

                try
                {
                    this.FlushAsync(asyncContinuation);
                }
                catch (Exception exception)
                {
                    if (exception.MustBeRethrown())
                    {
                        throw;
                    }

                    asyncContinuation(exception);
                }
            }
        }

        /// <summary>
        /// Calls the <see cref="Layout.Precalculate"/> on each volatile layout
        /// used by this target.
        /// </summary>
        /// <param name="logEvent">
        /// The log event.
        /// </param>
        public void PrecalculateVolatileLayouts(LogEventInfo logEvent)
        {
            lock (this.SyncRoot)
            {
                if (this.IsInitialized)
                {
                    if (this.allLayouts != null)
                    {
                        for (int x = 0; x < this.allLayouts.Count; x++)
                        {
                            Layout l = this.allLayouts[x];
                            l.Precalculate(logEvent);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            var targetAttribute = (TargetAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(TargetAttribute));
            if (targetAttribute != null)
            {
                return targetAttribute.Name + " Target[" + (this.Name ?? "(unnamed)") + "]";
            }

            return this.GetType().Name;
        }

        /// <summary>
        /// Writes the log to the target.
        /// </summary>
        /// <param name="logEvent">Log event to write.</param>
        public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
        {
            lock (this.SyncRoot)
            {
                if (!this.IsInitialized)
                {
                    logEvent.Continuation(null);
                    return;
                }

                if (this.initializeException != null)
                {
                    logEvent.Continuation(this.CreateInitException());
                    return;
                }

                AsyncContinuation wrappedContinuation = AsyncHelpers.PreventMultipleCalls(this.LoggingConfiguration, logEvent.Continuation); ;

                // Create async continuation to put log item back into the pool
                if (this.LoggingConfiguration.PoolingEnabled())
                {
                    var pool = this.LoggingConfiguration.PoolFactory.Get<CombinedAsyncContinuationPool, CombinedAsyncContinuation>();

                    wrappedContinuation = pool.Get(wrappedContinuation, logEvent.LogEvent.PutBackDelegate).Delegate;
                }

                try
                {
                    this.Write(logEvent.LogEvent.WithContinuation(wrappedContinuation));
                }
                catch (Exception exception)
                {
                    if (exception.MustBeRethrown())
                    {
                        throw;
                    }

                    wrappedContinuation(exception);
                }
            }
        }

        /// <summary>
        /// Writes the array of log events.
        /// </summary>
        /// <param name="logEvents">The log events.</param>
        public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents)
        {
            if (logEvents == null || logEvents.Length == 0)
            {
                return;
            }

            this.WriteAsyncLogEvents(new ArraySegment<AsyncLogEventInfo>(logEvents));
        }

        internal void WriteAsyncLogEvents(ArraySegment<AsyncLogEventInfo> logEvents)
        {
            if (logEvents.Count == 0)
            {
                return;
            }

            lock (this.SyncRoot)
            {
                if (!this.IsInitialized)
                {
                    for(int x=0;x<logEvents.Count;x++)
                    {
                        var ev = logEvents.Array[x];

                        ev.Continuation(null);
                    }

                    return;
                }

                if (this.initializeException != null)
                {
                    for (int x = 0; x < logEvents.Count; x++)
                    {
                        var ev = logEvents.Array[x];
                        ev.Continuation(this.CreateInitException());
                    }

                    return;
                }
                AsyncLogEventInfo[] wrappedEvents;
                if (this.LoggingConfiguration.PoolingEnabled())
                {
                    wrappedEvents = this.LoggingConfiguration.PoolFactory.Get<AsyncLogEventInfoArrayPool, AsyncLogEventInfo[]>().Get(logEvents.Count);
                }
                else
                {
                    wrappedEvents = new AsyncLogEventInfo[logEvents.Count];
                }
                for (int i = 0; i < logEvents.Count; ++i)
                {
                    wrappedEvents[i] = logEvents.Array[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(this.LoggingConfiguration, logEvents.Array[i].Continuation));
                }

                try
                {
                    this.Write(new ArraySegment<AsyncLogEventInfo>(wrappedEvents,0,logEvents.Count));
                }
                catch (Exception exception)
                {
                    if (exception.MustBeRethrown())
                    {
                        throw;
                    }

                    // in case of synchronous failure, assume that nothing is running asynchronously
                    foreach (var ev in wrappedEvents)
                    {
                        ev.Continuation(exception);
                    }
                }
                finally
                {
                    this.LoggingConfiguration.PutBack(wrappedEvents);
                }
            }

        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        internal void Initialize(LoggingConfiguration configuration)
        {
            lock (this.SyncRoot)
            {
                this.LoggingConfiguration = configuration;

                if (!this.IsInitialized)
                {
                    PropertyHelper.CheckRequiredParameters(this);
                    this.IsInitialized = true;
                    try
                    {
                        this.InitializeTarget();
                        this.initializeException = null;
                        if (!scannedForLayouts)
                        {
                            InternalLogger.Debug("InitializeTarget is done but not scanned For Layouts");
                            //this is critical, as we need the layouts. So if base.InitializeTarget() isn't called, we fix the layouts here.
                            FindAllLayouts();
                        }
                    }
                    catch (Exception exception)
                    {
                        InternalLogger.Error(exception, "Error initializing target '{0}'.", this);

                        this.initializeException = exception;

                        if (exception.MustBeRethrown())
                        {
                            throw;
                        }

                    }
                }
            }
        }

        /// <summary>
        /// Closes this instance.
        /// </summary>
        internal void Close()
        {
            lock (this.SyncRoot)
            {
                this.LoggingConfiguration = null;

                if (this.IsInitialized)
                {
                    this.IsInitialized = false;

                    try
                    {
                        if (this.initializeException == null)
                        {
                            // if Init succeeded, call Close()
                            this.CloseTarget();
                        }
                    }
                    catch (Exception exception)
                    {
                        InternalLogger.Error(exception, "Error closing target '{0}'.", this);

                        if (exception.MustBeRethrown())
                        {
                            throw;
                        }
                    }
                }
            }
        }

        internal void WriteAsyncLogEvents(AsyncLogEventInfo[] logEventInfos, AsyncContinuation continuation)
        {
            this.WriteAsyncLogEvents(new ArraySegment<AsyncLogEventInfo>(logEventInfos), continuation);
        }

        internal void WriteAsyncLogEvents(ArraySegment<AsyncLogEventInfo> logEventInfos, AsyncContinuation continuation)
        {
            if (logEventInfos.Count == 0)
            {
                continuation(null);
            }
            else
            {
                AsyncLogEventInfo[] wrappedLogEventInfos = null;
                try
                {
                    Counter counter;

                    GenericPool<ContinueWhenAll> continuePool = null;
                    int remaining = logEventInfos.Count;

                    if (this.LoggingConfiguration.PoolingEnabled())
                    {
                        counter = this.LoggingConfiguration.PoolFactory.Get<Counter>();
                        continuePool = this.LoggingConfiguration.PoolFactory.Get<GenericPool<ContinueWhenAll>, ContinueWhenAll>();
                        wrappedLogEventInfos = this.LoggingConfiguration.PoolFactory.Get<AsyncLogEventInfoArrayPool, AsyncLogEventInfo[]>().Get(logEventInfos.Count);
                    }
                    else
                    {
                        wrappedLogEventInfos = new AsyncLogEventInfo[logEventInfos.Count];
                        counter = new Counter();
                    }

                    counter.Reset(remaining);

                    for (int i = 0; i < logEventInfos.Count; ++i)
                    {
                        AsyncContinuation originalContinuation = logEventInfos.Array[i].Continuation;

                        ContinueWhenAll cont;
                        if (continuePool != null)
                        {
                            cont = continuePool.Get();
                            cont.Reset(counter, originalContinuation, continuation);
                            wrappedLogEventInfos[i] = logEventInfos.Array[i].LogEvent.WithContinuation(cont.Delegate);
                        }
                        else
                        {
                            cont = new ContinueWhenAll();

                        }
                        cont.Reset(counter, originalContinuation, continuation);
                        wrappedLogEventInfos[i] = logEventInfos.Array[i].LogEvent.WithContinuation(cont.Delegate);

                    }

                    this.WriteAsyncLogEvents(new ArraySegment<AsyncLogEventInfo>(wrappedLogEventInfos,0, logEventInfos.Count));
                }
                finally
                {
                    this.LoggingConfiguration.PutBack(wrappedLogEventInfos);
                }
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.CloseTarget();
            }
        }

        /// <summary>
        /// Initializes the target. Can be used by inheriting classes
        /// to initialize logging.
        /// </summary>
        protected virtual void InitializeTarget()
        {
            //rescan as amount layouts can be changed.
            FindAllLayouts();
        }

        private void FindAllLayouts()
        {
            this.allLayouts = new List<Layout>(ObjectGraphScanner.FindReachableObjects<Layout>(this));
            InternalLogger.Trace("{0} has {1} layouts", this, this.allLayouts.Count.AsString());
            this.scannedForLayouts = true;
        }

        /// <summary>
        /// Closes the target and releases any unmanaged resources.
        /// </summary>
        protected virtual void CloseTarget()
        {
        }

        /// <summary>
        /// Flush any pending log messages asynchronously (in case of asynchronous targets).
        /// </summary>
        /// <param name="asyncContinuation">The asynchronous continuation.</param>
        protected virtual void FlushAsync(AsyncContinuation asyncContinuation)
        {
            asyncContinuation(null);
        }

        /// <summary>
        /// Writes logging event to the log target.
        /// classes.
        /// </summary>
        /// <param name="logEvent">
        /// Logging event to be written out.
        /// </param>
        protected virtual void Write(LogEventInfo logEvent)
        {
            // do nothing
        }

        /// <summary>
        /// Writes log event to the log target. Must be overridden in inheriting
        /// classes.
        /// </summary>
        /// <param name="logEvent">Log event to be written out.</param>
        protected virtual void Write(AsyncLogEventInfo logEvent)
        {
            try
            {
                this.MergeEventProperties(logEvent.LogEvent);

                this.Write(logEvent.LogEvent);
                logEvent.Continuation(null);
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                logEvent.Continuation(exception);
            }
        }

        /// <summary>
        /// Writes an array of logging events to the log target. By default it iterates on all
        /// events and passes them to "Write" method. Inheriting classes can use this method to
        /// optimize batch writes.
        /// </summary>
        /// <param name="logEvents">Logging events to be written out.</param>
        protected virtual void Write(AsyncLogEventInfo[] logEvents)
        {
            this.Write(new ArraySegment<AsyncLogEventInfo>(logEvents));
        }

        /// <summary>
        /// Writes an array of logging events to the log target. By default it iterates on all
        /// events and passes them to "Write" method. Inheriting classes can use this method to
        /// optimize batch writes.
        /// </summary>
        /// <param name="logEvents">Logging events to be written out.</param>
        protected virtual void Write(ArraySegment<AsyncLogEventInfo> logEvents)
        {
            for (int i = 0; i < logEvents.Count; ++i)
            {
                this.Write(logEvents.Array[i]);
            }
        }

        private Exception CreateInitException()
        {
            return new NLogRuntimeException("Target " + this + " failed to initialize.", this.initializeException);
        }

        /// <summary>
        /// Merges (copies) the event context properties from any event info object stored in
        /// parameters of the given event info object.
        /// </summary>
        /// <param name="logEvent">The event info object to perform the merge to.</param>
        protected void MergeEventProperties(LogEventInfo logEvent)
        {
            if (logEvent.Parameters == null)
            {
                return;
            }

            foreach (var item in logEvent.Parameters)
            {
                var logEventParameter = item as LogEventInfo;
                if (logEventParameter != null)
                {
                    foreach (var key in logEventParameter.Properties.Keys)
                    {
                        logEvent.Properties.Add(key, logEventParameter.Properties[key]);
                    }
                    logEventParameter.Properties.Clear();
                }
            }
        }
    }
}


text:
require 'spec_helper'

describe Spree::FavoriteProductsController do

  let(:proxy_object) { Object.new }

  shared_examples_for "request which requires user authentication" do
    it "authenticates user" do
      expect(controller).to receive(:authenticate_spree_user!)
      send_request
    end
  end

  shared_examples_for "request which finds favorite product" do
    it "finds favorite product" do
      expect(@favorites).to receive(:where).with(favoritable_id: 'id', favoritable_type: 'Spree::Product')
      send_request
    end

    it "assigns @favorite" do
      send_request
      expect(assigns(:favorite)).to eq(@favorite)
    end
  end

  describe 'POST create' do
    def send_request
      post :create, params: { id: 1, type: 'Spree::Product' }, as: :js
    end

    before(:each) do
      @favorite = mock_model(Spree::Favorite, save: true)
      allow(controller).to receive(:authenticate_spree_user!).and_return(true)
      allow(Spree::Favorite).to receive(:new).and_return(@favorite)
      @user = mock_model(Spree::User, favorites: Spree::Favorite, generate_spree_api_key!: false, last_incomplete_spree_order: nil)
      allow(controller).to receive(:spree_current_user).and_return(@user)
    end

    it_behaves_like "request which requires user authentication"

    it "creates favorite" do
      expect(Spree::Favorite).to receive(:new).with(favoritable_id: 1, favoritable_type: 'Spree::Product')
      send_request
    end

    it "saves favorite" do
      expect(@favorite).to receive(:save)
      send_request
    end

    context "when favorite saved successfully" do
      it "renders create" do
        send_request
        expect(response).to render_template(:create)
      end

      it "should assign success message" do
        send_request
        expect(assigns(:message)).to eq("Product has been successfully marked as favorite")
      end
    end

    context "when favorite not saved sucessfully" do
      before(:each) do
        allow(@favorite).to receive(:save).and_return(false)
        allow(@favorite).to receive(:errors).and_return(proxy_object)
        allow(proxy_object).to receive(:full_messages).and_return(["Product already marked as favorite"])
      end

      it "renders create template" do
        send_request
        expect(response).to render_template(:create)
      end

      it "should assign error message" do
        send_request
        expect(assigns(:message)).to eq("Product already marked as favorite")
      end
    end
  end

  describe 'GET index' do
    def send_request
      get :index
    end

    before(:each) do
      @favorite_products = double('favorite_products')
      @favorite_variants = double('favorite_variants')
      @user = mock_model(Spree::User, favorite_products: @favorite_products, favorite_variants: @favorite_variants, generate_spree_api_key!: false, last_incomplete_spree_order: nil)
      allow(controller).to receive(:authenticate_spree_user!).and_return(true)
      allow(controller).to receive(:spree_current_user).and_return(@user)
    end

    it "authenticates user" do
      expect(controller).to receive(:authenticate_spree_user!)
      send_request
    end

    it "finds favorite products of current user" do
      expect(@user).to receive(:favorite_products)
      send_request
    end

    it "assigns @favorite_products" do
      send_request
      expect(assigns(:favorite_products)).to eq(@favorite_products)
    end

    it "assigns @favorite_variants" do
      send_request
      expect(assigns(:favorite_variants)).to eq(@favorite_variants)
    end
  end

  describe 'destroy' do
    def send_request(params = {})
      post :destroy, params: params.merge({method: :delete, id: 'id', type: 'Spree::Product'}), as: :js
    end

    before do
      @favorite = mock_model(Spree::Favorite)
      @favorites = double('spree_favorites', favoritable_id: 'id', favoritable_type: 'Spree::Product')
      allow(@favorites).to receive(:where).and_return([@favorite])
      @user = mock_model(Spree::User, favorites: @favorites, generate_spree_api_key!: false, last_incomplete_spree_order: nil)
      allow(controller).to receive(:authenticate_spree_user!).and_return(true)
      allow(controller).to receive(:spree_current_user).and_return(@user)
    end

    it_behaves_like "request which requires user authentication"
    it_behaves_like "request which finds favorite product"

    it { is_expected.to use_before_action(:find_favorite_product) }

    context 'when @favorite  exist' do
      before(:each) do
        controller.instance_variable_set(:@favorite, @favorite)
      end

      it 'destroys' do
        expect(@favorite).to receive(:destroy)
        send_request
      end

      context 'when destroyed successfully' do
        before(:each) do
          allow(@favorite).to receive(:destroy).and_return(true)
        end

        it "sets @success to true" do
          send_request
          expect(assigns(:success)).to eq(true)
        end
      end

      context 'when not destroyed' do
        before(:each) do
          allow(@favorite).to receive(:destroy).and_return(false)
        end

        it 'sets @success to false' do
          send_request
          expect(assigns(:success)).to eq(false)
        end
      end
    end

    context 'when @favorite does not exist' do
      before(:each) do
        allow(@favorite).to receive(:present?).and_return(false)
        send_request
      end

      it { is_expected.to respond_with(422) }
      it 'is expected to return js' do
        expect(response.headers["Content-Type"]).to eq "text/javascript; charset=utf-8"
      end
    end

  end

  describe 'get_favoritable_value' do
    def send_request(params = {})
      get :get_favoritable_value, params: params.merge({ id: 'id', type: 'Spree::Variant' }), xhr: true
    end

    before do
      @favorite = mock_model(Spree::Favorite)
      @favorites = double('spree_favorites', favoritable_id: 'id', favoritable_type: 'Spree::Variant')
      @user = mock_model(Spree::User, favorites: @favorites, generate_spree_api_key!: false, last_incomplete_spree_order: nil)
      allow(@favorites).to receive(:where).and_return([@favorite])
      allow(controller).to receive(:authenticate_spree_user!).and_return(true)
      allow(controller).to receive(:spree_current_user).and_return(@user)
    end

    context 'when favorite exists' do
      it 'is expected to assign @favorite to product' do
        send_request
        expect(assigns(:favorite)).to eq(@favorite)
      end
    end

    context 'when favorite does not exists' do
      before do
        allow(@favorites).to receive(:where).and_return(Spree::Favorite.none)
      end

      it 'is expected to assign @favorite to nil' do
        send_request
        expect(assigns(:favorite)).to eq(nil)
      end
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <ProgressBar
        android:id="@+id/footer_progressbar"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:indeterminateTint="@color/colorAccent"
        android:indeterminateTintMode="src_atop"
        android:layout_gravity="center_horizontal"
        />

</LinearLayout>


text:
<!DOCTYPE html>

		<title>Homepage logged in</title>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<link rel="stylesheet" href="../../css/style.css?1452369477" media="all" />

		<meta http-equiv="cache-control" content="max-age=0" />
		<meta http-equiv="cache-control" content="no-cache" />
		<meta http-equiv="expires" content="0" />
		<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
		<meta http-equiv="pragma" content="no-cache" />

		<link rel="stylesheet" href="../../styleguide/css/styleguide.css?1452369477" media="all">
		<link rel="stylesheet" href="../../styleguide/css/styleguide-specific.css?1452369477" media="all" />

	Skip to content

			<button id="nav-toggle" class="nav-toggle">Open menu</button>

Find a Job

Post a Job

Pricing

Your Account

Manage job alerts

Manage bookmarks

Manage jobs

Your account

Your cart

Logout
			<button class="logout-symbol">Logout</button>

				<video autoplay muted loop poster="../../video/typing-numbers.jpg">
					<source src="../../video/typing-numbers.mp4" type="video/mp4">
					<source src="../../video/typing-numbers.webm" type="video/webm">
					<source src="../../video/typing-numbers.ogv" type="video/ogg">
				</video>

The go-to for careers in International Education

Find a Job

Post a Job

Start your search now

					        Search
					        <input id="search" type="search" placeholder="Enter Search Term">

					        Search
					        <input id="search" type="search" placeholder="Enter Search Term">

						    <fieldset>
						        Select
						        <select id="select">
						            <optgroup label="Option Group">
						                <option>Option One</option>
						                <option>Option Two</option>
						                <option>Option Three</option>
						            </optgroup>
						        </select>
						    </fieldset>

										Search Jobs

							New

International Sales Manager

Tellus Group

New York, USA

							Full Time

							<time>Posted 6 days ago</time>

							New

International Sales Manager

Tellus Group

New York, USA

							Full Time

							<time>Posted 6 days ago</time>

							New

International Sales Manager

Tellus Group

New York, USA

							Full Time

							<time>Posted 6 days ago</time>

							New

International Sales Manager

Tellus Group

New York, USA

							Full Time

							<time>Posted 6 days ago</time>

Find your perfect job from employers like these

Browse all jobs

			" If you are looking for a career in international education or student recruitment, The PIE is the place.  I applied for three jobs and was invited for interviews for two of them, which led me to my current job. All happened within a few weeks. I highly recommend The PIE to other industry professionals. "

		Mickey Kromann-Jensen, INTO Queen's University Belfast

Employers, find your perfect candidate

With years of experience connecting International Education and recruitment employers with the right candidates, we know what you need to get your position filled.

With a streamlined job posting process and access to hundreds of candidates, The PIE Jobs is the go-to site for your recruitment needs.

Post your Job

£99

for 2 weeks

Get your job seen by potential employees for two weeks straight

64

active employers

Get access to jobs from the leading names in International Education

234

active candidates

The PIE Jobs is the go-to place for active job seekers in International Education

BUMP

your ad anytime

In a rush? Need to be seen? Bump up your listing to the top of the pile for only £75

			Create your account now

Employers and job seekers alike, create your account to manage job alerts, post jobs and much more

	  <button data-remodal-action="close" class="remodal-close"></button>

Login

The PIE Jobs is the leading international education career site

			<form method="post" action="#" class="comment-form">
				<fieldset>

						Your Email *
						<input id="comment-email" type="email" placeholder="Your email address" required>

				        Your Password *
				        <input id="password" type="password" placeholder="Type your Password" required>

				</fieldset>

<button class="btn" data-remodal-action="confirm" class="remodal-confirm" type="submit">Login</button>

			</form>

Don't have an account? Create one now

	  <button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>

Search Jobs

About us

Contact us

Pricing

Report a problem

PIE Blog

<form action="#" method="post" class="inline-form newsletter-form">
    <fieldset>
	    Sign up for our newsletter

	   		<input type="newsletter" placeholder="E-mail address" id="newsletter-field" class="newsletter-field" />
	    	<button class="btn newsletter-submit">Subscribe</button>

    </fieldset>
</form>

© 2015 The PIE Partnership

Terms & Conditions / Privacy Policy


text:
package water;

/**
 * A UDP Heartbeat packet.
 *
 * @author
 * @version 1.0
 */
class UDPHeartbeat extends UDP {
  @Override AutoBuffer call(AutoBuffer ab) {
    if( ab._h2o != H2O.SELF ) { // Do not update self-heartbeat object
      // The self-heartbeat is the sole holder of racey cloud-concensus hashes
      // and if we update it here we risk dropping an update.
      ab._h2o._heartbeat = new HeartBeat().read(ab);
      Paxos.doHeartbeat(ab._h2o);
    }
    return ab;
  }

  static void build_and_multicast( H2O cloud, HeartBeat hb ) {
    // Paxos.print_debug("send: heartbeat ",cloud._memset);
    assert hb._cloud_hash != 0 || hb._client; // Set before send, please
    H2O.SELF._heartbeat = hb;
    hb.write(new AutoBuffer(H2O.SELF).putUdp(UDP.udp.heartbeat)).close();
  }
}


text:
module RackApp
  def app
    ActiveRecordRoutes::API
  end

  def request(method, body={}, headers={})
    @response = send(method, body, headers)
  end

  def response
    @response
  end

  def json
    JSON.parse(response.body)
  end
end


text:
cask 'microblog' do
  version '1.8.2'
  sha256 '92a3683160f3f1f19e5c35ef7d2071421c8bc54fcd9f695c2f1e542e51f4648b'

  # s3.amazonaws.com/micro.blog was verified as official when first introduced to the cask
  url "https://s3.amazonaws.com/micro.blog/mac/Micro.blog_#{version}.zip"
  appcast 'https://s3.amazonaws.com/micro.blog/mac/appcast.xml'
  name 'Micro.blog'
  homepage 'https://help.micro.blog/2017/mac-version/'

  auto_updates true
  depends_on macos: '>= :sierra'

  app 'Micro.blog.app'

  zap trash: [
               '~/Library/Application Support/blog.micro.mac',
               '~/Library/Caches/blog.micro.mac',
               '~/Library/Caches/com.crashlytics.data/blog.micro.mac',
               '~/Library/Caches/io.fabric.sdk.mac.data/blog.micro.mac',
               '~/Library/Cookies/blog.micro.mac.binarycookies',
               '~/Library/Preferences/blog.micro.mac.plist',
               '~/Library/Saved Application State/blog.micro.mac.savedState',
             ]
end


text:
module AlchemyContentable
  class Engine < ::Rails::Engine
    isolate_namespace AlchemyContentable
  end
end


text:
using EloBuddy;
using EloBuddy.SDK;
using System.Collections.Generic;
using System.Linq;
using static SmartCast.Damages;
using static SmartCast.Program;
using static SmartCast.Settings;
using static SmartCast.Spells;
using static SmartCast.Logic.SummonerSpells;

namespace SmartCast.Logic
{
    internal class Abilities
    {
        #region Basic

        internal static void BasicAttack(Unit unit)
        {
            if (unit == Unit.Enemy)
                BasicAttackEnemy();
            else if (unit == Unit.Minion)
                BasicAttackMinion();
            else if (unit == Unit.Monster)
                BasicAttackMonster();
        }

        private static void BasicAttackEnemy()
        {
            AIHeroClient target = EntityManager.Heroes.Enemies.OrderBy(Enemy => Enemy.Health).Where(Enemy => Enemy.IsValidTarget(FULL_RANGE) && !Enemy.HasUndyingBuff()).FirstOrDefault();

            if (target != null)
                Orbwalker.ForcedTarget = target;
        }

        private static void BasicAttackMinion()
        {
            Obj_AI_Minion target = EntityManager.MinionsAndMonsters.EnemyMinions.OrderBy(Minion => Minion.Health).Where(Minion => Minion.IsValidTarget(HALF_RANGE)).FirstOrDefault();

            if (target != null)
                Orbwalker.ForcedTarget = target;
        }

        private static void BasicAttackMonster()
        {
            Obj_AI_Minion target = EntityManager.MinionsAndMonsters.Monsters.OrderByDescending(Monster => Monster.MaxHealth).Where(Monster => Monster.IsValidTarget(HALF_RANGE)).FirstOrDefault();

            if (target != null)
                Orbwalker.ForcedTarget = target;
        }

        #endregion

        #region Attack

        internal static void Attack(Mode mode, bool quickCast = false)
        {
            if (!Q.IsReady() && !R.IsReady())
                return;
            else if (mode == Mode.Combo || mode == Mode.Harass)
                ComboHarassAttack(quickCast);
            else if (mode == Mode.LastHit)
                LastHitAttack(quickCast);
            else if (mode == Mode.JungleClear)
                JungleAttack(quickCast);
            else if (mode == Mode.LaneClear)
                LaneAttack(quickCast);

        }

        private static void ComboHarassAttack(bool quickCast = false)
        {
            AIHeroClient target = EntityManager.Heroes.Enemies.OrderBy(Enemy => Enemy.Health).Where(Enemy => Enemy.IsValidTarget(FULL_RANGE) && !Enemy.HasUndyingBuff()).FirstOrDefault();

            if (target == null)
                return;

            Stance stance = GetStance(target, quickCast);

            switch (stance)
            {
                case Stance.Tiger:
                    CastQ(quickCast, target);
                    break;
                case Stance.Phoenix:
                    CastR(quickCast, target);
                    break;
                case Stance.Hybrid:
                    CastQ(quickCast, target);
                    CastR(true, target);
                    break;
            }

            Orbwalker.ForcedTarget = target;
        }

        private static void LastHitAttack(bool quickCast = false)
        {
            Obj_AI_Minion target = EntityManager.MinionsAndMonsters.EnemyMinions.OrderBy(Minion => Minion.Health).Where(Minion => Minion.IsValidTarget(HALF_RANGE)).FirstOrDefault();

            if (target == null)
                return;
            else if (!InQStance)
                CastQ(quickCast);
        }

        private static void JungleAttack(bool quickCast = false)
        {
            List<Obj_AI_Minion> targets = EntityManager.MinionsAndMonsters.Monsters.OrderByDescending(Monster => Monster.MaxHealth).Where(Monster => Monster.IsValidTarget(HALF_RANGE)).ToList();

            if (targets == null || targets.Count == 0)
                return;

            Obj_AI_Minion target = targets.FirstOrDefault();

            if (targets.Count == 1)
            {
                Stance stance = GetStance(target, quickCast);

                switch (stance)
                {
                    case Stance.Tiger:
                        CastQ(quickCast);
                        break;
                    case Stance.Phoenix:
                        CastR(quickCast);
                        break;
                    case Stance.Hybrid:
                        CastQ(quickCast);
                        CastR(true);
                        break;
                }
            }
            else if (targets.Count > 1)
            {
                CastR(quickCast);
                CastQ(quickCast);
            }

            Orbwalker.ForcedTarget = target;
        }

        private static void LaneAttack(bool quickCast = false)
        {
            Obj_AI_Minion target = EntityManager.MinionsAndMonsters.EnemyMinions.OrderBy(Minion => Minion.Health).Where(Minion => Minion.IsValidTarget(HALF_RANGE)).FirstOrDefault();

            if (target == null)
                return;

            CastR(quickCast);
            CastQ(quickCast);
            Orbwalker.ForcedTarget = target;
        }

        private static void CastQ(bool quickCast = false, AIHeroClient target = null)
        {
            if (!Q.IsReady())
                return;
            else if (NextBasicIsConeFlame)
                return;
            else if (target != null && HasEActive && Stunable(target))
                return;
            else if (!quickCast && HasRActive)
                return;

            Q.Cast();
        }

        private static void CastR(bool quickCast = false, AIHeroClient target = null)
        {
            if (!R.IsReady())
                return;
            else if (NextBasicIsPunchBleed)
                return;
            else if (target != null && HasEActive && Stunable(target))
                return;
            else if (!quickCast && HasQActive)
                return;

            R.Cast();
        }

        #endregion

        #region Shield

        internal static void Shield(Mode mode)
        {
            if (!W.IsReady())
                return;
            else if (mode == Mode.Combo)
                ComboShield();
            else if (mode == Mode.Harass)
                HarassShield();
            else if (mode == Mode.JungleClear)
                JungleShield();
            else if (mode == Mode.LaneClear)
                LaneShield();
            else if (mode == Mode.Flee)
                FleeShield();
        }

        internal static void CriticalShield()
        {
            if (!W.IsReady())
                return;

            if (Udyr.HealthPercent > CRITICAL_CHAMPIONS_HEALTH && Udyr.Health > CRITICAL_MINIONS_AND_MONSTERS_HEALTH)
                return;

            int enemies = EntityManager.Heroes.Enemies.Where(Enemy => Enemy.IsInRange(Udyr, FULL_RANGE)).Count();
            int minions = EntityManager.MinionsAndMonsters.EnemyMinions.Where(Minion => Minion.IsInRange(Udyr, HALF_RANGE)).Count();
            int monsters = EntityManager.MinionsAndMonsters.Monsters.Where(Monster => Monster.IsInRange(Udyr, HALF_RANGE)).Count();

            if (enemies > 0 || minions > 0 || monsters > 0)
            {
                if (enemies > 0 && Udyr.HealthPercent <= CRITICAL_CHAMPIONS_HEALTH)
                    W.Cast();
                else if ((minions > 0 || monsters > 0) && Udyr.Health <= CRITICAL_MINIONS_AND_MONSTERS_HEALTH)
                    W.Cast();
            }
        }

        private static void ComboShield()
        {
            if (NextBasicIsPunchBleed || NextBasicIsConeFlame)
                return;
            else if ((HasQActive || HasRActive) && Udyr.HealthPercent >= CHAMPIONS_HEALTH)
                return;

            AIHeroClient target = EntityManager.Heroes.Enemies.OrderBy(Enemy => Enemy.Health).Where(Enemy => Enemy.IsValidTarget(FULL_RANGE) && !Enemy.HasUndyingBuff()).FirstOrDefault();

            if (target == null)
                return;

            bool quickCast = Udyr.HealthPercent < CHAMPIONS_HEALTH;
            Stance stance = GetStance(target, quickCast);

            bool castQ = stance == Stance.Tiger && Q.IsReady();
            bool castR = stance == Stance.Phoenix && R.IsReady();
            bool castQR = stance == Stance.Hybrid && (Q.IsReady() || R.IsReady()) && Udyr.HealthPercent >= CHAMPIONS_HEALTH;

            if (castQ || castR || castQR)
                return;

            W.Cast();
        }

        private static void HarassShield()
        {
            if (NextBasicIsPunchBleed || NextBasicIsConeFlame)
                return;

            AIHeroClient target = EntityManager.Heroes.Enemies.OrderBy(Enemy => Enemy.Health).Where(Enemy => Enemy.IsValidTarget(FULL_RANGE) && !Enemy.HasUndyingBuff()).FirstOrDefault();

            if (target == null)
                return;

            Stance stance = GetStance(target, true);

            bool castQ = stance == Stance.Tiger && Q.IsReady();
            bool castR = stance == Stance.Phoenix && R.IsReady();
            bool castQR = stance == Stance.Hybrid && (Q.IsReady() || R.IsReady()) && Udyr.HealthPercent >= CHAMPIONS_HEALTH;

            if (castQ || castR || castQR)
                return;

            W.Cast();
        }

        private static void JungleShield()
        {
            if (NextBasicIsPunchBleed || NextBasicIsConeFlame)
                return;

            List<Obj_AI_Minion> targets = EntityManager.MinionsAndMonsters.Monsters.OrderByDescending(Monster => Monster.MaxHealth).Where(Monster => Monster.IsValidTarget(HALF_RANGE)).ToList();

            if (targets == null || targets.Count == 0)
                return;

            string monster = targets.FirstOrDefault().BaseSkinName;

            if (monster == Monster["Baron Nashor"])
                W.Cast();
            else if ((monster == Monster["Rift Herard"] || monster == Monster["Mountain Drake"]) && Udyr.Health <= BIG_MINIONS_AND_MONSTERS_HEALTH)
                W.Cast();
            else if (Udyr.Health <= SMALL_MINIONS_AND_MONSTERS_HEALTH)
                W.Cast();
        }

        private static void LaneShield()
        {
            if (NextBasicIsPunchBleed || NextBasicIsConeFlame)
                return;

            if (Udyr.Health <= LANE_MINIONS_AND_MONSTERS_HEALTH)
                W.Cast();
        }

        private static void FleeShield()
        {
            if (HasEActive)
                return;

            W.Cast();
        }

        #endregion

        #region Stun

        internal static void Stun(Mode mode)
        {
            if (!E.IsReady() && !InEStance)
                return;

            switch(mode)
            {
                case Mode.Combo:
                    ComboStun();
                    break;
                case Mode.Harass:
                    HarassStun();
                    break;
                case Mode.Flee:
                    FleeStun();
                    break;
            }
        }

        internal static void Escape()
        {
            if (E.IsReady())
                E.Cast();
        }

        private static void ComboStun()
        {
            AIHeroClient target = EntityManager.Heroes.Enemies.OrderBy(Enemy => Enemy.Distance(Udyr)).Where(Enemy => Enemy.IsValidTarget(FULL_RANGE) && !Enemy.HasBuffOfType(BuffType.Stun) && Stunable(Enemy)).FirstOrDefault();

            if (target == null)
                return;
            else if (E.IsReady())
                E.Cast();

            Orbwalker.ForcedTarget = target;
        }

        private static void HarassStun()
        {
            if (NextBasicIsStunCycle)
                return;

            AIHeroClient target = EntityManager.Heroes.Enemies.OrderBy(Enemy => Enemy.Distance(Udyr)).Where(Enemy => Enemy.IsValidTarget(FULL_RANGE) && !Enemy.HasBuffOfType(BuffType.Stun) && Stunable(Enemy)).FirstOrDefault();

            if (target == null)
                return;
            else if (E.IsReady())
                E.Cast();

            Orbwalker.ForcedTarget = target;
        }

        private static void FleeStun()
        {
            AIHeroClient target = EntityManager.Heroes.Enemies.OrderBy(Enemy => Enemy.Distance(Udyr)).Where(Enemy => Enemy.IsValidTarget(Udyr.AttackRange) && !Enemy.HasBuffOfType(BuffType.Stun) && Stunable(Enemy)).FirstOrDefault();

            if (target == null)
                return;
            else if (E.IsReady())
                E.Cast();

            Orbwalker.ForcedTarget = target;
        }

        private static bool Stunable(AIHeroClient target)
        {
            return !target.IsEStunned() && StunTimer[target.Hero] + 6 < Game.Time;
        }

        #endregion
    }
}


text:
"""
Estimates time of DMC frames using GPS & fire data, when they exist.
work in progress

We use UT1 Unix epoch time instead of datetime, since we are working with HDF5 and also need to do fast comparisons

Outputs:
--------
    UT1_unix:   double-precision float (64-bit) estimate of frame exposure START

Michael Hirsch
"""
from datetime import datetime
from dateutil.parser import parse
import numpy as np

def frame2ut1(tstart, kineticsec, rawind):
    """ if you don't have GPS & fire data, you use this function for a software-only
    estimate of time. This estimate may be off by more than a minute, so think of it
    as a relative indication only. You can try verifying your absolute time with satellite
    passes in the FOV using a plate-scaled calibration and ephemeris data.
    Contact Michael Hirsch, he does have Github code for this.
    """
    # total_seconds is required for Python 2 compatibility
    # this variable is in units of seconds since Jan 1, 1970, midnight
    # rawind-1 because camera is one-based indexing
    try:
        return datetime2unix(tstart)[0] + (rawind - 1) * kineticsec
    except TypeError:
        return

def ut12frame(treq, ind, ut1_unix) -> np.ndarray:
    """
    Given treq, output index(ces) to extract via rawDMCreader
    treq: scalar or vector of ut1_unix time (seconds since Jan 1, 1970)
    ind: zero-based frame index corresponding to ut1_unix, corresponding to input data file.
    """
    if treq is None:  # have to do this since interp1 will return last index otherwise
        return

    treq = np.atleast_1d(treq)
    # %% handle human specified string scalar case
    if treq.size == 1:
        treq = datetime2unix(treq[0])
    # %% handle time range case
    elif treq.size == 2:
        tstartreq = datetime2unix(treq[0])
        tendreq = datetime2unix(treq[1])
        treq = ut1_unix[(ut1_unix > tstartreq) & (ut1_unix < tendreq)]
    else:  # otherwise, it's a vector of requested values
        treq = datetime2unix(treq)
    # %% get indices
    """
    We use nearest neighbor interpolation to pick a frame index for each requested time.
    """
    framereq = np.rint(np.interp(treq, ut1_unix, ind)).astype(np.int64)
    framereq = framereq[framereq >= 0]  # discard outside time limits

    return framereq

def datetime2unix(T):
    """
    converts datetime to UT1 unix epoch time
    """
    T = np.atleast_1d(T)

    ut1_unix = np.empty(T.shape, dtype=float)
    for i, t in enumerate(T):
        if isinstance(t, (datetime, np.datetime64)):
            pass
        elif isinstance(t, str):
            try:
                ut1_unix[i] = float(t)  # it was ut1_unix in a string
                continue
            except ValueError:
                t = parse(t)  # datetime in a string
        elif isinstance(t, (float, int)):  # assuming ALL are ut1_unix already
            return T
        else:
            raise TypeError("I only accept datetime or parseable date string")

        # ut1 seconds since unix epoch, need [] for error case
        ut1_unix[i] = t.timestamp()

    return ut1_unix

def firetime(tstart, Tfire):
    """ Highly accurate sub-millisecond absolute timing based on GPSDO 1PPS and camera fire feedback.
    Right now we have some piecemeal methods to do this, and it's time to make it industrial strength
    code.

    """
    raise NotImplementedError("Yes this is a priority, would you like to volunteer?")


text:
module Aws
  # @api private
  class TypeBuilder

    def initialize(svc_module)
      @types_module = svc_module.const_set(:Types, Module.new)
    end

    def build_type(shape, shapes)
      @types_module.const_set(shape.name, Structure.new(*shape.member_names))
    end

  end
end


text: """Certbot nginx plugin."""


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

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, defaultImpl = StatusTaskBegin.class)
public class StatusTaskBegin extends AbstractJobMessage {

    @JsonCreator
    private StatusTaskBegin() {
        super();
    }

    public StatusTaskBegin(String host, String job, int node) {
        super(host, job, node);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Rossman, Samuels, Rogerson & Lowen, Stud. Mycol. 42: 137 (1999)

#### Original name
Neoskofitzia termitum Höhn., 1908

### Remarks
null


text:
#pragma once

#include "get_avatar/v1_3.hpp"

namespace mf {
namespace api {
/** API action path "user" */
namespace user {
/** API action "user/get_avatar" */
namespace get_avatar {

// Default version
using namespace v1_3;  // NOLINT

}  // namespace get_avatar
}  // namespace user
}  // namespace api
}  // namespace mf


text:
//=====================================================================
//
//File:      $RCSfile: UITestingUtilities.java,v $
//Version:   $Revision: 1.35 $
//Modified:  $Date: 2013/05/10 13:29:06 $
//
//(c) Copyright 2004-2014 by Mentor Graphics Corp. All rights reserved.
//
//========================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the
// License for the specific language governing permissions and limitations under
// the License.
//========================================================================

package com.mentor.nucleus.bp.test.common;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import junit.framework.Assert;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.gef.tools.AbstractTool;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.views.properties.PropertySheet;

import com.mentor.nucleus.bp.core.Ooaofooa;
import com.mentor.nucleus.bp.core.common.ClassQueryInterface_c;
import com.mentor.nucleus.bp.core.common.ModelRoot;
import com.mentor.nucleus.bp.core.common.NonRootModelElement;
import com.mentor.nucleus.bp.core.common.PersistenceManager;
import com.mentor.nucleus.bp.core.ui.Selection;
import com.mentor.nucleus.bp.core.util.UIUtil;
import com.mentor.nucleus.bp.ui.canvas.Cl_c;
import com.mentor.nucleus.bp.ui.canvas.Connector_c;
import com.mentor.nucleus.bp.ui.canvas.ElementInSuppression_c;
import com.mentor.nucleus.bp.ui.canvas.GraphicalElement_c;
import com.mentor.nucleus.bp.ui.canvas.ModelTool_c;
import com.mentor.nucleus.bp.ui.canvas.Model_c;
import com.mentor.nucleus.bp.ui.canvas.Ooaofgraphics;
import com.mentor.nucleus.bp.ui.canvas.Shape_c;
import com.mentor.nucleus.bp.ui.explorer.ExplorerView;
import com.mentor.nucleus.bp.ui.explorer.ui.actions.ExplorerCopyAction;
import com.mentor.nucleus.bp.ui.explorer.ui.actions.ExplorerCutAction;
import com.mentor.nucleus.bp.ui.explorer.ui.actions.ExplorerPasteAction;
import com.mentor.nucleus.bp.ui.graphics.actions.CanvasCopyAction;
import com.mentor.nucleus.bp.ui.graphics.actions.CanvasCutAction;
import com.mentor.nucleus.bp.ui.graphics.actions.CanvasPasteAction;
import com.mentor.nucleus.bp.ui.graphics.editor.GraphicalEditor;
import com.mentor.nucleus.bp.ui.graphics.editor.ModelEditor;
import com.mentor.nucleus.bp.ui.graphics.parts.DiagramEditPart;
import com.mentor.nucleus.bp.ui.graphics.parts.GraphicalZoomManager;
import com.mentor.nucleus.bp.utilities.ui.CanvasUtilities;

public class UITestingUtilities {
	private static Point fDownLocation;

	public static void printControl(Composite parent, String intend) throws Exception {
		System.out.print(intend);
		printOject("Parent", parent); //$NON-NLS-1$

		intend = intend + "  "; //$NON-NLS-1$

		printItems(parent, intend);

		Control[] children = parent.getChildren();
		for (int i = 0; i < children.length; i++) {
			if (children[i] instanceof Composite) {
				printControl((Composite) children[i], intend);
			} else {
				System.out.print(intend);
				printOject("Child", children[i]); //$NON-NLS-1$
			}
		}
	}

	public static void printItems(Widget parent, String intend) throws Exception {
		Item[] items = (Item[]) invokeMethod(parent, "getItems", new Object[0]); //$NON-NLS-1$
		if (items != null) {
			for (int i = 0; i < items.length; i++) {
				System.out.print(intend + "Item"); //$NON-NLS-1$
				printProperties(items[i]);
				System.out.println();
				printItems(items[i], intend + "  "); //$NON-NLS-1$
			}
		}
	}

	protected static void printOject(String label, Object target) throws Exception{
		System.out.print(label);
		printProperties(target);
		System.out.println();
	}

	public static void printProperties(Object target) throws InvocationTargetException, IllegalAccessException {
		System.out.print("["); //$NON-NLS-1$
		try {
			PropertyDescriptor[] propertyInfos = Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors();
			for (int i = 0; i < propertyInfos.length; i++) {
				Class propertyType = propertyInfos[i].getPropertyType();
				if (propertyType != null && !propertyType.isArray()) {
					Method readMethod = propertyInfos[i].getReadMethod();

					if(readMethod != null){
						Object propertyValue = readMethod.invoke(target, new Object[0]);
						if (i > 0) {
							System.out.print("; "); //$NON-NLS-1$
						}
						System.out.print(propertyInfos[i].getName() + ":" + propertyValue); //$NON-NLS-1$
					}
				}
			}
		} catch (IntrospectionException e) {
		}
		System.out.print("]"); //$NON-NLS-1$
	}

	public static Object getProperty(Object target, String propertyName)
		throws InvocationTargetException, IllegalAccessException {
		return invokeMethod(target, "get" + propertyName, new Object[0]); //$NON-NLS-1$
	}

	public static Object invokeMethod(Object target, String methodName, Object[] arguments)
		throws InvocationTargetException, IllegalAccessException {
		Class targetClass = target.getClass();
		Class[] argumentTypes = new Class[arguments.length];
		for (int i = 0; i < argumentTypes.length; i++) {
			argumentTypes[i] = arguments[i].getClass();
		}

		try {
			Method method = targetClass.getMethod(methodName, argumentTypes);
			return method.invoke(target, arguments);
		} catch (SecurityException e) {
		} catch (NoSuchMethodException e) {
		}

		return null;
	}

	public static MenuItem[] getMenuItems(final Menu menu, String childMenu) {

		Event event = new Event();
		event.x = 5;
		event.y = 5;
		menu.notifyListeners(SWT.Show, event);

		MenuItem[] items;

		// get child items if item in question
		// is contained in a child menu
		if (!childMenu.equals("")) {
			items = getChildMenuItems(menu, childMenu);
		} else {
			items = menu.getItems();
		}

		event.doit = true;
		menu.notifyListeners(SWT.Hide, event);

		return items;

	}

	private static MenuItem[] getChildMenuItems(Menu menu, String childMenu) {
		MenuItem[] parentItems = menu.getItems();
		for (int i = 0; i < parentItems.length; i++) {
			if (removeAccelerator(parentItems[i].getText()).equals(childMenu)) {
				MenuManager manager = (MenuManager) parentItems[i].getData();
				Menu child = manager.getMenu();
				Event event = new Event();
				event.x = 5;
				event.y = 5;
				child.notifyListeners(SWT.Show, event);
				return child.getItems();
			}
		}
		return null;
	}
	private static String removeAccelerator(String withAccelerator){
		return withAccelerator.replaceFirst("&", "");
	}

	public static boolean checkItemStatusInContextMenu(Menu menu, String text, String childMenu, boolean readonly) {

    	MenuItem[] items = getMenuItems(menu, childMenu);

    	// find the item in question
    	for(int i = 0; items != null && i < items.length; i++) {
    		if(removeAccelerator(items[i].getText()).indexOf(text) != -1) {
    			// verify the item
    			// if item is enabled
    			if(items[i].isEnabled()) {
    				// and is read only
    				if(readonly) {
    					// item should be disabled
    					return false;
    				} else {
    					// item is fine
    					return true;
    				}
    			} else {
    				// if item is disabled
    				// switch the returns
    				if(readonly) {
    					return true;
    				} else {
    					return false;
    				}
    			}
    		}
    	}
    	// action was not found
    	return false;
    }

	public static boolean menuItemExists(Menu menu, String childMenu, String item) {
		MenuItem[] menuItems = getMenuItems(menu, childMenu);
		for(int i = 0; menuItems != null && i < menuItems.length; i++) {
			if(removeAccelerator(menuItems[i].getText()).equals(item)) {
				return true;
			}
		}
		return false;
	}

	public static IEditorPart getActiveEditor() {
		IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
		if(activeEditor instanceof ModelEditor) {
			return ((ModelEditor) activeEditor).getActivePart();
		} else
			return activeEditor;
	}

	public static void copyElement(NonRootModelElement element, GraphicalEditor ce) {
		clearGraphicalSelection(); addElementToGraphicalSelection(element);
		CanvasCopyAction canvascopyaction = new CanvasCopyAction(ce);
		canvascopyaction.run();
		BaseTest.waitForTransaction();
	}
	public static void copyElements(List elements, GraphicalEditor ce) {
		clearGraphicalSelection();
		Iterator iterator = elements.iterator();
		while(iterator.hasNext()) {
			addElementToGraphicalSelection(iterator.next());
		}
		CanvasCopyAction canvascopyaction = new CanvasCopyAction(ce);
		canvascopyaction.run();
		BaseTest.waitForTransaction();
	}
	public static void pasteClipboardContents(Point location, GraphicalEditor ce) {
		CanvasPasteAction canvaspasteaction = new CanvasPasteAction(ce);
		CanvasTestUtils.doMouseMove(location.x, location.y);
		CanvasTestUtils.doMouseContextPress(location.x, location.y);
		canvaspasteaction.run();
		BaseTest.dispatchEvents(0);
	}

	public static GraphicalEditor getGraphicalEditorFor(final NonRootModelElement columnInstance, boolean isRootOf) {
		return getGraphicalEditorFor(columnInstance, isRootOf, true);
	}

	public static GraphicalEditor getGraphicalEditorFor(final NonRootModelElement columnInstance, boolean isRootOf, boolean validateOpen) {
		if(columnInstance == null) return null;
		if(isRootOf) {
			IEditorReference[] editorReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
					.getActivePage().getEditorReferences();
			int count = editorReferences.length;
			CanvasTestUtils.openCanvasEditor(columnInstance);
			editorReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getActivePage().getEditorReferences();
			int count_after = editorReferences.length;
			if(validateOpen) {
				if(count < count_after) {
					return (GraphicalEditor) getActiveEditor();
				} else {
					// no editor was opened
					return null;
				}
			} else {
				return (GraphicalEditor) getActiveEditor();
			}
		}
		Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(columnInstance.getModelRoot().getId());
		GraphicalElement_c[] elements = GraphicalElement_c.GraphicalElementInstances(graphicsRoot);
		GraphicalEditor editor = getGraphicalEditorFrom(columnInstance, elements);
		if(editor == null) {
			// try system level elements
			elements = GraphicalElement_c.GraphicalElementInstances(Ooaofgraphics.getDefaultInstance());
			editor = getGraphicalEditorFrom(columnInstance, elements);
		}
		return editor;
	}

	private static GraphicalEditor getGraphicalEditorFrom(final NonRootModelElement columnInstance, GraphicalElement_c[] elements) {
		for(int i = 0; i < elements.length; i++) {
			if(elements[i].getRepresents() == null) {
				elements[i].setRepresents(Cl_c.Getinstancefromooa_id((Ooaofooa)
						columnInstance.getModelRoot(), elements[i].getOoa_id(),
						elements[i].getOoa_type()));
			}
			if(elements[i].getRepresents() == columnInstance) {
				Model_c model = Model_c.getOneGD_MDOnR1(elements[i]);
				CanvasTestUtils.openCanvasEditor(model.getRepresents());
				return (GraphicalEditor) getActiveEditor();
			}
		}
		return null;
	}

	public static GraphicalElement_c getGraphicalElementFor(NonRootModelElement element, boolean excludeSuppressedGraphics) {
		Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(element.getModelRoot().getId());
		if (PersistenceManager.findComponent(element.getModelRoot().getId())
				.getRootModelElement() == element) {
			graphicsRoot = Ooaofgraphics.getDefaultInstance();
		}
		GraphicalElement_c[] elements = GraphicalElement_c.GraphicalElementInstances(graphicsRoot);
		for(int i = 0; i < elements.length; i++) {
			ElementInSuppression_c eis = ElementInSuppression_c.getOneGD_EISOnR32(elements[i]);
			if(excludeSuppressedGraphics && eis != null)
				continue;
			if(elements[i].getRepresents() == null) {
				elements[i].setRepresents(Cl_c.Getinstancefromooa_id((Ooaofooa)
						element.getModelRoot(), elements[i].getOoa_id(),
						elements[i].getOoa_type()));
			}
			if(elements[i].getRepresents() == element) {
				return elements[i];
			}
		}
		return null;
	}

	public static MenuItem getMenuItem(Menu menu, String childMenu, String name) {
		MenuItem[] items = getMenuItems(menu, childMenu);
		for(int i = 0; items != null && i < items.length; i++) {
			if(items[i].getText().equals(name)) {
				return items[i];
			}
		}
		return null;
	}

	public static MenuItem getMenuItem(Menu menu, String name) {
		MenuItem[] items = getMenuItems(menu, "");
		for(int i = 0; items != null && i < items.length; i++) {
			if(items[i].getText().equals(name)) {
				return items[i];
			}
		}
		return null;
	}

	public static void activateMenuItem(MenuItem item) {
		item.notifyListeners(SWT.Selection, null);
	}

	public static void activateMenuItem(Menu menu, String childMenu, String name) {
		MenuItem item = getMenuItem(menu, childMenu, name);
		activateMenuItem(item);
	}

	public static void activateMenuItem(Menu menu, String name) {
		// if the given name is a menu path, split it and execute
		// the final menu item
		String[] menuPath = name.split("::");
		if(menuPath.length > 1) {
			MenuItem item = null;
			for(int i = 0; i < menuPath.length; i++) {
				MenuItem[] children = getMenuItems(menu, "");
				for(int j = 0; j < children.length; j++) {
					if(removeAccelerator(children[j].getText()).equals(menuPath[i])) {
						item = children[j];
						if(item.getData() instanceof MenuManager) {
							MenuManager manager = (MenuManager) item.getData();
							menu = manager.getMenu();
						}
						break;
					}
				}
				if(item != null && !(item.getData() instanceof MenuManager)) {
					break;
				}
			}
			activateMenuItem(item);
		} else {
		MenuItem item = getMenuItem(menu, name);
		activateMenuItem(item);
	}
		UIUtil.dispatchAll();
	}

	public class Tool_by_id_c implements ClassQueryInterface_c {
		public boolean evaluate(Object candidate) {
			ModelTool_c selected = (ModelTool_c) candidate;
			return (selected.getTool_id().equals(m_id));
		}
		public Tool_by_id_c(UUID id) {
			m_id = id;
		}
		private UUID m_id;
	}

	public static void activateTool(AbstractTool tool) {
		CanvasUtilities.activateTool(tool);
	}

	public static void deactivateTool(AbstractTool tool) {
		CanvasUtilities.deactivateTool(tool);
	}

	public static boolean ctrlDown = false;
	public static void createMouseEvent(int x, int y, String eventType) {
		GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor())
				.getGraphicalEditor();
		Event me = new Event();
		if(ctrlDown) {
			me.stateMask = SWT.CTRL;
		}

		if (eventType.equals("MouseMove")) {
			me.x = x;
			me.y = y;
			if(fDownLocation != null) {
				me.stateMask |= SWT.BUTTON1;
				// GEF has a drag event, which we need
				// to imitate.
				// we will move the mouse 10 times, to reach
				// the final destination
				int xDownLocation = fDownLocation.x;
				int yDownLocation = fDownLocation.y;
				int xDelta = x - xDownLocation;
				int yDelta = y - yDownLocation;
				int xIncrement = xDelta / 10;
				int yIncrement = yDelta / 10;
				boolean crossedThreshold = false;
				int xIncrementRealValue = xIncrement;
				if(xIncrementRealValue < 0)
					xIncrementRealValue = xIncrementRealValue * -1;
				int yIncrementRealValue = yIncrement;
				if(yIncrementRealValue < 0)
					yIncrementRealValue = yIncrementRealValue * -1;
				boolean reverse = x < xDownLocation;
				if(yIncrementRealValue >= xIncrementRealValue)
					reverse = y < yDownLocation;
				while(!crossedThreshold) {
					xDownLocation = xDownLocation + xIncrement;
					yDownLocation = yDownLocation + yIncrement;
					me.x = xDownLocation;
					me.y = yDownLocation;
					if(xIncrementRealValue > yIncrementRealValue) {
						if(reverse) {
							// check that the current x < expected x
							if(xDownLocation < x)
								crossedThreshold = true;
						} else {
							if(xDownLocation > x)
								crossedThreshold = true;
						}
					} else {
						if(reverse) {
							// check that the current x < expected x
							if(yDownLocation < y)
								crossedThreshold = true;
						} else {
							if(yDownLocation > y)
								crossedThreshold = true;
						}
					}
					if(crossedThreshold) {
						// If we crossed the expected location, do not
						// send this location. Instead send the expected
						// location
						me.x = x;
						me.y = y;
					}
					ce.getCanvas().notifyListeners(SWT.MouseMove, me);
				}
			} else
				ce.getCanvas().notifyListeners(SWT.MouseMove, me);
		} else if (eventType.equals("MouseDown")) {
			// with GEF we must create a mouse move first,
			// this will set the proper source edit part
			// for any creation request
			createMouseEvent(x, y, "MouseMove"); // $NON-NLS-1$
			me.x = x;
			me.y = y;
			me.button = 1;
			fDownLocation = new Point(x, y);
			ce.getCanvas().notifyListeners(SWT.MouseDown, me);
		} else if (eventType.equals("MouseDownRetainSelection")) {
			me.x = x;
			me.y = y;
			me.button = 1;
			me.stateMask |= SWT.CTRL;
			ce.getCanvas().notifyListeners(SWT.MouseDown, me);
		} else if (eventType.equals("MouseContextDown")) {
			me.x = x;
			me.y = y;
			me.button = 3;
			ce.getCanvas().notifyListeners(SWT.MouseDown, me);
		} else if (eventType.equals("MouseUp")) {
			me.x = x;
			me.y = y;
			me.button = 1;
			fDownLocation = null;
			ce.getCanvas().notifyListeners(SWT.MouseUp, me);
			// allow any transaction to complete if started
			// this will allow graphical symbols to be fully
			// configured before a test proceeds
			BaseTest.waitForTransaction();
		} else if (eventType.equals("MouseDoubleClick")) {
			// with GEF we must create a mouse move first,
			// this will set the proper source edit part
			// for any creation request
			createMouseEvent(x, y, "MouseMove"); // $NON-NLS-1$
			createMouseEvent(x, y, "MouseDown"); // $NON-NLS-1$
			fDownLocation = null;
			me.x = x;
			me.y = y;
			me.button = 1;
			ce.getCanvas().notifyListeners(SWT.MouseDoubleClick, me);
		}
		while(PlatformUI.getWorkbench().getDisplay().readAndDispatch())
			;
	}

    /**
     * A convenience method.  See method wrapped.
     */
    public static void doMousePress(int x, int y)
    {
		createMouseEvent(x, y, "MouseDown");
    }

    /**
     * A convenience method.  See method wrapped.
     */
    public static void doMouseRelease(int x, int y)
    {
		createMouseEvent(x, y, "MouseUp");
    }

    /**
     * A convenience method.  See method wrapped.
     */
    public static void doMouseMove(int x, int y)
    {
		createMouseEvent(x, y, "MouseMove");
    }

    /**
     * A convenience method.  See method wrapped.
     */
    public static void doMouseContextPress(int x, int y)
    {
		createMouseEvent(x, y, "MouseContextDown");
    }

    /**
     * A convenience method.  See method wrapped.
     */
    public static void doMousePressRetainSelection(int x, int y)
    {
		createMouseEvent(x, y, "MouseDownRetainSelection");
    }

    /**
     * A convenience method.  See method wrapped.
     */
    public static void doMouseDoubleClick(int x, int y)
    {
        createMouseEvent(x, y, "MouseDoubleClick");
    }

    private static void createElementInDiagram(GraphicalEditor ce, String toolSet , String toolName, int x1, int y1, int x2, int y2) {
		AbstractTool tool = null;
		if (toolSet != null) {
			tool = ce.getTool(toolSet, toolName);
		} else {
			tool = ce.getTool(toolName);
		}
		if(tool != null) {
			activateTool(tool);
			doMouseMove(x1, y1);
			doMousePress(x1, y1);
			doMouseMove(x2,y2);
			doMouseRelease(x2,y2);
			deactivateTool(tool);
		} else {
			Assert.fail("Unable to locate tool for given diagram.");
		}
    }

	public static void createShapeInDiagram(GraphicalEditor ce, Rectangle rectangle, String toolName) {
		createShapeInDiagram(ce, rectangle, null, toolName);
	}
	public static void createShapeInDiagram(GraphicalEditor ce, Rectangle rectangle, String toolSet , String toolName) {
		createElementInDiagram(ce, toolSet, toolName, rectangle.x, rectangle.y, rectangle.x + rectangle.width, rectangle.y + rectangle.height);
	}

	public static void createConnectorInDiagram(GraphicalEditor ce, Point start,
			Point end, String toolSet, String toolName)
	{
		createElementInDiagram(ce, toolSet, toolName, start.x, start.y, end.x, end.y);
	}

	public static void createConnectorInDiagram(GraphicalEditor ce, Point start,
			Point end, String toolName)
	{
		createConnectorInDiagram(ce, start, end, null, toolName );
	}

	public static void cutElement(NonRootModelElement element, GraphicalEditor ce) {
		clearGraphicalSelection(); addElementToGraphicalSelection(element);
		CanvasCutAction canvascutaction = new CanvasCutAction(ce);
		canvascutaction.run();
		BaseTest.waitForTransaction();
	}

	public static void cutElementInExplorer(NonRootModelElement element, ExplorerView explorer) {
		Selection.getInstance().clear(); Selection.getInstance().addToSelection(element);
		ExplorerCutAction cut = new ExplorerCutAction(explorer.getTreeViewer());
		cut.run();
		BaseTest.dispatchEvents(0);
	}

	public static AbstractTool getTool(String toolName) {
		return CanvasUtilities.getTool(toolName);
	}
	public static AbstractTool getTool(String toolSet, String toolName) {
		return CanvasUtilities.getTool(toolSet, toolName);

	}

	/**
	 * This method will select the appropriate editor part in
	 * the current editor, if the current editor is not the appropriate
	 * one it tries to locate it.  If a different editor was opened
	 * the method will return it
	 *
	 * @param obj
	 */
	public static GraphicalEditor addElementToGraphicalSelection(Object obj) {
		GraphicalEditor editor = (GraphicalEditor) getActiveEditor();
		GraphicalEditor originalEditor = editor;
		GraphicalViewer viewer = (GraphicalViewer) editor.getAdapter(GraphicalViewer.class);
		if(obj instanceof GraphicalEditPart) {
			viewer.appendSelection((EditPart) obj);
			while(PlatformUI.getWorkbench().getDisplay().readAndDispatch());
			return editor;
		}
		Model_c model = (Model_c) viewer.getContents().getModel();
		GraphicalElement_c[] elements = GraphicalElement_c.getManyGD_GEsOnR1(model);
		GraphicalElement_c element = null;
		for(int i = 0; i < elements.length; i++) {
			if(elements[i].getRepresents() == obj) {
				element = elements[i];
				break;
			}
		}
		if(element == null) {
			editor = getGraphicalEditorFor((NonRootModelElement) obj, false);
			if(editor == null)
				return null;
			viewer = (GraphicalViewer) editor.getAdapter(GraphicalViewer.class);
			model = (Model_c) viewer.getContents().getModel();
			elements = GraphicalElement_c.getManyGD_GEsOnR1(model);
			for(int i = 0; i < elements.length; i++) {
				if(elements[i].getRepresents() == obj) {
					element = elements[i];
					break;
				}
			}
		}
		if(element == null) {
			return originalEditor;
		}
		Object gObject = Shape_c.getOneGD_SHPOnR2(element);
		if(gObject == null)
			gObject = Connector_c.getOneGD_CONOnR2(element);
		GraphicalEditPart part = (GraphicalEditPart) viewer.getEditPartRegistry().get(gObject);
		viewer.appendSelection(part);
		while(PlatformUI.getWorkbench().getDisplay().readAndDispatch());
		return editor;
	}

	public static void clearGraphicalSelection() {
		GraphicalEditor editor = (GraphicalEditor) getActiveEditor();
		GraphicalViewer viewer = (GraphicalViewer) editor.getAdapter(GraphicalViewer.class);
		viewer.deselectAll();
		while(PlatformUI.getWorkbench().getDisplay().readAndDispatch());
	}

	public static void revealElementInGraphicalEditor(Shape_c shape) {
		GraphicalEditor editor = (GraphicalEditor) getActiveEditor();
		GraphicalViewer viewer = (GraphicalViewer) editor.getAdapter(GraphicalViewer.class);
		viewer.reveal(getEditorPartFor(shape));
		while(PlatformUI.getWorkbench().getDisplay().readAndDispatch());
	}

	public static EditPart getEditorPartFor(Object element) {
		final Object initialElement = element;
		if(element instanceof NonRootModelElement) {
			ModelRoot root = ((NonRootModelElement) element).getModelRoot();
			if(root instanceof Ooaofooa) {
				// locate the shape or connector that represents the
				// given element
				Ooaofgraphics graphicRoot = Ooaofgraphics.getInstance(root.getId());
				GraphicalElement_c ge = GraphicalElement_c.GraphicalElementInstance(graphicRoot, new ClassQueryInterface_c() {

					@Override
					public boolean evaluate(Object candidate) {
						return ((GraphicalElement_c) candidate).getRepresents() == initialElement;
					}
				});
				Shape_c shape = Shape_c.getOneGD_SHPOnR2(ge);
				if(shape != null) {
					element = shape;
				}
				Connector_c con = Connector_c.getOneGD_CONOnR2(ge);
				if(con != null) {
					element = con;
				}
			}
		}
		GraphicalEditor editor = (GraphicalEditor) getActiveEditor();
		GraphicalViewer viewer = (GraphicalViewer) editor.getAdapter(GraphicalViewer.class);
		return (GraphicalEditPart) viewer.getEditPartRegistry().get(element);
	}

	public static void removeElementFromGraphicalSelection(EditPart part) {
		GraphicalEditor editor = (GraphicalEditor) getActiveEditor();
		GraphicalViewer viewer = (GraphicalViewer) editor.getAdapter(GraphicalViewer.class);
		viewer.deselect(part);
		while(PlatformUI.getWorkbench().getDisplay().readAndDispatch());
	}

	public static void pasteClipboardContentsInExplorer(Object destination) {
		Selection.getInstance().clear();
		Selection.getInstance().addToSelection(destination);
		ExplorerPasteAction paste = new ExplorerPasteAction();
		paste.run();
		BaseTest.dispatchEvents(0);
	}

	public static void pasteClipboardContentsInExplorer() {
		ExplorerPasteAction paste = new ExplorerPasteAction();
		paste.run();
		BaseTest.dispatchEvents(0);
	}

	public static void copyElementInExplorer(ExplorerView explorer) {
		ExplorerCopyAction copy = new ExplorerCopyAction(explorer.getTreeViewer());
		copy.run();
		BaseTest.dispatchEvents(0);
	}

	/**
	 * This function closes (hides) the property view if it is visible.
	 */
	public static void hidePropertyView() {
		PropertySheet propSheet = UITestingUtilities.getPropertySheet();
		if (propSheet != null) {
			propSheet.getSite().getPage().hideView(propSheet);
		}
	}

	/**
	 * This function finds the property view and returns it.
	 *
	 * @return The property sheet view or null if the property sheet view is
	 *         not visible
	 */
	public static PropertySheet getPropertySheet() {
		PropertySheet propSheet = null;
		IWorkbenchWindow[] windows = PlatformUI.getWorkbench()
				.getWorkbenchWindows();
		for (int i = 0; propSheet==null && i < windows.length; ++i) {
			IWorkbenchPage[] pages = windows[i].getPages();
			for (int j = 0; propSheet==null && j < pages.length; ++j) {
				IViewReference[] views = pages[j].getViewReferences();
				for (int k = 0; propSheet==null && k < views.length; ++k) {
					if (views[k].getPart(false) instanceof PropertySheet) {
						propSheet = (PropertySheet)views[k].getPart(false);
					}
				}
			}
		}
		return propSheet;
	}

    public static Point getClearPoint(GraphicalEditor rowEditor) {
    	Point point = new Point(100, 100);
		List<GraphicalEditPart> allSymbols = GraphicalEditor.getAllSymbols(
				rowEditor.getGraphicalViewer(), rowEditor.getModel()
						.Hascontainersymbol());
		org.eclipse.draw2d.geometry.Rectangle extentRectangle = GraphicalZoomManager.getExtentRectangle(allSymbols);
		if(extentRectangle == null) {
			// no need to change position
			return point;
		}
		((DiagramEditPart) rowEditor.getGraphicalViewer().getContents())
				.getFigure().translateToAbsolute(extentRectangle);
		point.x = extentRectangle.getRight().x + 100;
		return point;
	}

	public static void cutElementsInExplorer(Object[] cuttableElements,
			ExplorerView explorer) {
		Selection.getInstance().clear();
		for(Object element : cuttableElements) {
			Selection.getInstance().addToSelection(element);
		}
		ExplorerCutAction cut = new ExplorerCutAction(explorer.getTreeViewer());
		cut.run();
		BaseTest.dispatchEvents(0);
	}

	public static String findInputDialogErrorText(InputDialog dialog) {
		List<Text> texts = findTextInControl(dialog.getShell());
		return texts.get(1).getText();
	}

	private static List<Text> findTextInControl(Composite composite) {
		List<Text> texts = new ArrayList<Text>();
		Control[] children = composite.getChildren();
		for(Control control : children) {
			if(control instanceof Text) {
				texts.add((Text) control);
			} else if(control instanceof Composite) {
				texts.addAll(findTextInControl((Composite) control));
			}
		}
		return texts;
	}

	public static Text findInputDialogTextField(InputDialog dialog) {
		List<Text> texts = findTextInControl(dialog.getShell());
		return texts.get(0);
	}

	/**
	 * This method returns a tree item in the given tree that contains
	 * the given text.  It does not do an exact match.
	 */
	public static TreeItem findItemInTree(Tree tree, String name) {
		TreeItem[] items = tree.getItems();
		for(TreeItem item : items) {
			TreeItem foundItem = findItemInTree(item, name);
			if(foundItem != null) {
				return foundItem;
			}
		}
		return null;
	}

	/**
	 * This method returns a tree item as a child of the given item
	 * that contains the given text.  It does not do an exact match.
	 */
	public static TreeItem findItemInTree(TreeItem item, String name) {
		if(item.getText().contains(name)) {
			return item;
		} else {
			TreeItem[] children = item.getItems();
			for(TreeItem child : children) {
				TreeItem foundItem = findItemInTree(child, name);
				if(foundItem != null) {
					return foundItem;
				}
			}
		}
		return null;
	}

    public static Tree findTree(Composite parent) {
        Control [] child_set = parent.getChildren();
        for ( int i = 0; i < child_set.length; ++i )
        {
            if ( child_set[i] instanceof Tree )
            {
            	return (Tree) child_set[i];
            }
            else if ( child_set[i] instanceof Composite )
            {
                Tree result = findTree((Composite)child_set[i]);
                if ( result != null )
                {
                   return result;
                }
            }
        }
        return null;
    }

	public static void resizeMainWindow(int x, int y) {
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()
				.setSize(x, y);
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()
				.redraw();
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()
				.update();
		while (PlatformUI.getWorkbench().getDisplay().readAndDispatch());
	}

}


text:
layout: post
title: 642 - Design Search Autocomplete System
date: 2019-12-27
tags:
- Leetcode
categories:
- Data Structure
author: Jason
---
**Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). For each character they type except '#', you need to return the top 3 historical hot sentences that have prefix the same as the part of sentence already typed. Here are the specific rules:**

1. The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.
2. The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same degree of hot, you need to use ASCII-code order (smaller one appears first).
3. If less than 3 hot sentences exist, then just return as many as you can.
4. When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.

```python
from collections import defaultdict
class TrieNode:
    def __init__(self):
        self.children = {}
        self.words = defaultdict(int)

class AutocompleteSystem:
    def __init__(self, sentences: List[str], times: List[int]):
        self.root = self.curr = TrieNode()
        self.sentence = ""
        for sentence, time in zip(sentences, times):
            self.insert(sentence, time)

    def insert(self, sentence, time):
        curr = self.root
        for c in sentence:
            if c not in curr.children:
                curr.children[c] = TrieNode()
            curr = curr.children[c]
            curr.words[sentence] += time

    def input(self, c: str) -> List[str]:
        if c == "#":
            self.curr = self.root
            self.insert(self.sentence, 1)
            self.sentence = ""
            return []
        self.sentence += c
        if c not in self.curr.children:
            #create a dummy node for following input
            self.curr = TrieNode()
            return []
        else:
            self.curr = self.curr.children[c]
            candidates = sorted(self.curr.words.items(), key=lambda item: (-item[1], item[0]))
            return [v[0] for v in candidates[:3]]
```


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/swag"
)

// SingleBeadSimulation single bead simulation
// swagger:model SingleBeadSimulation
type SingleBeadSimulation struct {
	Simulation

	SingleBeadSimulationParameters
}

// UnmarshalJSON unmarshals this object from a JSON structure
func (m *SingleBeadSimulation) UnmarshalJSON(raw []byte) error {

	var aO0 Simulation
	if err := swag.ReadJSON(raw, &aO0); err != nil {
		return err
	}
	m.Simulation = aO0

	var aO1 SingleBeadSimulationParameters
	if err := swag.ReadJSON(raw, &aO1); err != nil {
		return err
	}
	m.SingleBeadSimulationParameters = aO1

	return nil
}

// MarshalJSON marshals this object to a JSON structure
func (m SingleBeadSimulation) MarshalJSON() ([]byte, error) {
	var _parts [][]byte

	aO0, err := swag.WriteJSON(m.Simulation)
	if err != nil {
		return nil, err
	}
	_parts = append(_parts, aO0)

	aO1, err := swag.WriteJSON(m.SingleBeadSimulationParameters)
	if err != nil {
		return nil, err
	}
	_parts = append(_parts, aO1)

	return swag.ConcatJSON(_parts...), nil
}

// Validate validates this single bead simulation
func (m *SingleBeadSimulation) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.Simulation.Validate(formats); err != nil {
		res = append(res, err)
	}

	if err := m.SingleBeadSimulationParameters.Validate(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

// MarshalBinary interface implementation
func (m *SingleBeadSimulation) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *SingleBeadSimulation) UnmarshalBinary(b []byte) error {
	var res SingleBeadSimulation
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Nova Hedwigia 96: 160 (1989)

#### Original name
Tyromyces amyloideus Corner

### Remarks
null