text:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using AutoUpdaterDotNET.Properties;

namespace AutoUpdaterDotNET
{
    /// <summary>
    ///     Enum representing the remind later time span.
    /// </summary>
    public enum RemindLaterFormat
    {
        /// <summary>
        ///     Represents the time span in minutes.
        /// </summary>
        Minutes,

        /// <summary>
        ///     Represents the time span in hours.
        /// </summary>
        Hours,

        /// <summary>
        ///     Represents the time span in days.
        /// </summary>
        Days
    }

    /// <summary>
    ///     Enum representing the effect of Mandatory flag.
    /// </summary>
    public enum Mode
    {
        /// <summary>
        /// In this mode, it ignores Remind Later and Skip values set previously and hide both buttons.
        /// </summary>
        [XmlEnum("0")] Normal,

        /// <summary>
        /// In this mode, it won't show close button in addition to Normal mode behaviour.
        /// </summary>
        [XmlEnum("1")] Forced,

        /// <summary>
        /// In this mode, it will start downloading and applying update without showing standard update dialog in addition to Forced mode behaviour.
        /// </summary>
        [XmlEnum("2")] ForcedDownload
    }

    /// <summary>
    ///     Main class that lets you auto update applications by setting some static fields and executing its Start method.
    /// </summary>
    public static class AutoUpdater
    {
        private static System.Timers.Timer _remindLaterTimer;

        private static bool _isWinFormsApplication;

        internal static Uri BaseUri;

        internal static bool Running;

        /// <summary>
        ///     You can set this field to your current version if you don't want to determine the version from the assembly.
        /// </summary>
        public static Version InstalledVersion;

        /// <summary>
        ///     Set it to folder path where you want to download the update file. If not provided then it defaults to Temp folder.
        /// </summary>
        public static string DownloadPath;

        /// <summary>
        ///     If you are using a zip file as an update file then you can set this value to path where your app is installed. This is only necessary when your installation directory differs from your executable path.
        /// </summary>
        public static string InstallationPath;

        /// <summary>
        ///     Set the Application Title shown in Update dialog. Although AutoUpdater.NET will get it automatically, you can set this property if you like to give custom Title.
        /// </summary>
        public static string AppTitle;

        /// <summary>
        ///     URL of the xml file that contains information about latest version of the application.
        /// </summary>
        public static string AppCastURL;

        /// <summary>
        /// Login/password/domain for FTP-request
        /// </summary>
        public static NetworkCredential FtpCredentials;

        /// <summary>
        ///     Opens the download URL in default browser if true. Very usefull if you have portable application.
        /// </summary>
        public static bool OpenDownloadPage;

        /// <summary>
        ///     Set Basic Authentication credentials required to download the file.
        /// </summary>
        public static IAuthentication BasicAuthDownload;

        /// <summary>
        ///     Set Basic Authentication credentials required to download the XML file.
        /// </summary>
        public static IAuthentication BasicAuthXML;

        /// <summary>
        ///     Set Basic Authentication credentials to navigate to the change log URL.
        /// </summary>
        public static IAuthentication BasicAuthChangeLog;

        /// <summary>
        ///     Set the User-Agent string to be used for HTTP web requests.
        /// </summary>
        public static string HttpUserAgent;

        /// <summary>
        ///     If this is true users can see the skip button.
        /// </summary>
        public static bool ShowSkipButton = true;

        /// <summary>
        ///     If this is true users can see the Remind Later button.
        /// </summary>
        public static bool ShowRemindLaterButton = true;

        /// <summary>
        ///     If this is true users see dialog where they can set remind later interval otherwise it will take the interval from
        ///     RemindLaterAt and RemindLaterTimeSpan fields.
        /// </summary>
        public static bool LetUserSelectRemindLater = true;

        /// <summary>
        ///     Remind Later interval after user should be reminded of update.
        /// </summary>
        public static int RemindLaterAt = 2;

        ///<summary>
        ///     AutoUpdater.NET will report errors if this is true.
        /// </summary>
        public static bool ReportErrors = false;

        /// <summary>
        ///     Set this to false if your application doesn't need administrator privileges to replace the old version.
        /// </summary>
        public static bool RunUpdateAsAdmin = true;

        /// <summary>
        ///     Set this to true if you want to run update check synchronously.
        /// </summary>
        public static bool Synchronous = false;

        /// <summary>
        ///     Set this to true if you want to clear application directory before extracting update.
        /// </summary>
        public static bool ClearAppDirectory = false;

        ///<summary>
        ///     Set this to true if you want to ignore previously assigned Remind Later and Skip settings. It will also hide Remind Later and Skip buttons.
        /// </summary>
        public static bool Mandatory;

        /// <summary>
        ///     Set this to any of the available modes to change behaviour of the Mandatory flag.
        /// </summary>
        public static Mode UpdateMode;

        /// <summary>
        ///     Set Proxy server to use for all the web requests in AutoUpdater.NET.
        /// </summary>
        public static IWebProxy Proxy;

        /// <summary>
        /// Set this to an instance implementing the IPersistenceProvider interface for using a data storage method different from the default Windows Registry based one.
        /// </summary>
        public static IPersistenceProvider PersistenceProvider;

        /// <summary>
        ///     Set if RemindLaterAt interval should be in Minutes, Hours or Days.
        /// </summary>
        public static RemindLaterFormat RemindLaterTimeSpan = RemindLaterFormat.Days;

        /// <summary>
        ///     A delegate type to handle how to exit the application after update is downloaded.
        /// </summary>
        public delegate void ApplicationExitEventHandler();

        /// <summary>
        ///     An event that developers can use to exit the application gracefully.
        /// </summary>
        public static event ApplicationExitEventHandler ApplicationExitEvent;

        /// <summary>
        ///     A delegate type for hooking up update notifications.
        /// </summary>
        /// <param name="args">An object containing all the parameters received from AppCast XML file. If there will be an error while looking for the XML file then this object will be null.</param>
        public delegate void CheckForUpdateEventHandler(UpdateInfoEventArgs args);

        /// <summary>
        ///     An event that clients can use to be notified whenever the update is checked.
        /// </summary>
        public static event CheckForUpdateEventHandler CheckForUpdateEvent;

        /// <summary>
        ///     A delegate type for hooking up parsing logic.
        /// </summary>
        /// <param name="args">An object containing the AppCast file received from server.</param>
        public delegate void ParseUpdateInfoHandler(ParseUpdateInfoEventArgs args);

        /// <summary>
        ///     An event that clients can use to be notified whenever the AppCast file needs parsing.
        /// </summary>
        public static event ParseUpdateInfoHandler ParseUpdateInfoEvent;

        /// <summary>
        ///     Set if you want the default update form to have a different size.
        /// </summary>
        public static Size? UpdateFormSize = null;

        /// <summary>
        ///     Start checking for new version of application and display a dialog to the user if update is available.
        /// </summary>
        /// <param name="myAssembly">Assembly to use for version checking.</param>
        public static void Start(Assembly myAssembly = null)
        {
            Start(AppCastURL, myAssembly);
        }

        /// <summary>
        ///     Start checking for new version of application via FTP and display a dialog to the user if update is available.
        /// </summary>
        /// <param name="appCast">FTP URL of the xml file that contains information about latest version of the application.</param>
        /// <param name="ftpCredentials">Credentials required to connect to FTP server.</param>
        /// <param name="myAssembly">Assembly to use for version checking.</param>
        public static void Start(string appCast, NetworkCredential ftpCredentials, Assembly myAssembly = null)
        {
            FtpCredentials = ftpCredentials;
            Start(appCast, myAssembly);
        }

        /// <summary>
        ///     Start checking for new version of application and display a dialog to the user if update is available.
        /// </summary>
        /// <param name="appCast">URL of the xml file that contains information about latest version of the application.</param>
        /// <param name="myAssembly">Assembly to use for version checking.</param>
        public static void Start(string appCast, Assembly myAssembly = null)
        {
            try
            {
                ServicePointManager.SecurityProtocol |= (SecurityProtocolType) 192 |
                                                        (SecurityProtocolType) 768 | (SecurityProtocolType) 3072;
            }
            catch (NotSupportedException)
            {
            }

            if (Mandatory && _remindLaterTimer != null)
            {
                _remindLaterTimer.Stop();
                _remindLaterTimer.Close();
                _remindLaterTimer = null;
            }

            if (!Running && _remindLaterTimer == null)
            {
                Running = true;

                AppCastURL = appCast;

                _isWinFormsApplication = Application.MessageLoop;

                if (!_isWinFormsApplication)
                {
                    Application.EnableVisualStyles();
                }

                Assembly assembly = myAssembly ?? Assembly.GetEntryAssembly();

                if (Synchronous)
                {
                    try
                    {
                        var result = CheckUpdate(assembly);

                        if (StartUpdate(result))
                        {
                            return;
                        }

                        Running = false;
                    }
                    catch (Exception exception)
                    {
                        ShowError(exception);
                    }
                }
                else
                {
                    using (var backgroundWorker = new BackgroundWorker())
                    {
                        backgroundWorker.DoWork += (_, args) =>
                        {
                            Assembly mainAssembly = args.Argument as Assembly;

                            args.Result = CheckUpdate(mainAssembly);
                        };

                        backgroundWorker.RunWorkerCompleted += (_, args) =>
                        {
                            if (args.Error != null)
                            {
                                ShowError(args.Error);
                            }
                            else
                            {
                                if (!args.Cancelled)
                                {
                                    if (StartUpdate(args.Result))
                                    {
                                        return;
                                    }
                                }

                                Running = false;
                            }
                        };

                        backgroundWorker.RunWorkerAsync(assembly);
                    }
                }
            }
        }

        private static object CheckUpdate(Assembly mainAssembly)
        {
            var companyAttribute =
                (AssemblyCompanyAttribute) GetAttribute(mainAssembly, typeof(AssemblyCompanyAttribute));
            string appCompany = companyAttribute != null ? companyAttribute.Company : "";

            if (string.IsNullOrEmpty(AppTitle))
            {
                var titleAttribute =
                    (AssemblyTitleAttribute) GetAttribute(mainAssembly, typeof(AssemblyTitleAttribute));
                AppTitle = titleAttribute != null ? titleAttribute.Title : mainAssembly.GetName().Name;
            }

            string registryLocation = !string.IsNullOrEmpty(appCompany)
                ? $@"Software\{appCompany}\{AppTitle}\AutoUpdater"
                : $@"Software\{AppTitle}\AutoUpdater";

            PersistenceProvider ??= new RegistryPersistenceProvider(registryLocation);

            BaseUri = new Uri(AppCastURL);

            UpdateInfoEventArgs args;
            using (MyWebClient client = GetWebClient(BaseUri, BasicAuthXML))
            {
                string xml = client.DownloadString(BaseUri);

                if (ParseUpdateInfoEvent == null)
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(UpdateInfoEventArgs));
                    XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xml)) {XmlResolver = null};
                    args = (UpdateInfoEventArgs) xmlSerializer.Deserialize(xmlTextReader);
                }
                else
                {
                    ParseUpdateInfoEventArgs parseArgs = new ParseUpdateInfoEventArgs(xml);
                    ParseUpdateInfoEvent(parseArgs);
                    args = parseArgs.UpdateInfo;
                }
            }

            if (string.IsNullOrEmpty(args?.CurrentVersion) || string.IsNullOrEmpty(args.DownloadURL))
            {
                throw new MissingFieldException();
            }

            args.InstalledVersion = InstalledVersion ?? mainAssembly.GetName().Version;
            args.IsUpdateAvailable = new Version(args.CurrentVersion) > args.InstalledVersion;

            if (!Mandatory)
            {
                if (string.IsNullOrEmpty(args.Mandatory.MinimumVersion) ||
                    args.InstalledVersion < new Version(args.Mandatory.MinimumVersion))
                {
                    Mandatory = args.Mandatory.Value;
                    UpdateMode = args.Mandatory.UpdateMode;
                }
            }

            if (Mandatory)
            {
                ShowRemindLaterButton = false;
                ShowSkipButton = false;
            }
            else
            {
                // Read the persisted state from the persistence provider.
                // This method makes the persistence handling independent from the storage method.
                var skippedVersion = PersistenceProvider.GetSkippedVersion();
                if (skippedVersion != null)
                {
                    var currentVersion = new Version(args.CurrentVersion);
                    if (currentVersion <= skippedVersion)
                        return null;

                    if (currentVersion > skippedVersion)
                    {
                        // Update the persisted state. Its no longer makes sense to have this flag set as we are working on a newer application version.
                        PersistenceProvider.SetSkippedVersion(null);
                    }
                }

                var remindLaterAt = PersistenceProvider.GetRemindLater();
                if (remindLaterAt != null)
                {
                    int compareResult = DateTime.Compare(DateTime.Now, remindLaterAt.Value);

                    if (compareResult < 0)
                    {
                        return remindLaterAt.Value;
                    }
                }
            }

            return args;
        }

        private static bool StartUpdate(object result)
        {
            if (result is DateTime time)
            {
                SetTimer(time);
            }
            else
            {
                if (result is UpdateInfoEventArgs args)
                {
                    if (CheckForUpdateEvent != null)
                    {
                        CheckForUpdateEvent(args);
                    }
                    else
                    {
                        if (args.IsUpdateAvailable)
                        {
                            if (Mandatory && UpdateMode == Mode.ForcedDownload)
                            {
                                DownloadUpdate(args);
                                Exit();
                            }
                            else
                            {
                                if (Thread.CurrentThread.GetApartmentState().Equals(ApartmentState.STA))
                                {
                                    ShowUpdateForm(args);
                                }
                                else
                                {
                                    Thread thread = new Thread(new ThreadStart(delegate { ShowUpdateForm(args); }));
                                    thread.CurrentCulture =
                                        thread.CurrentUICulture = CultureInfo.CurrentCulture;
                                    thread.SetApartmentState(ApartmentState.STA);
                                    thread.Start();
                                    thread.Join();
                                }
                            }

                            return true;
                        }

                        if (ReportErrors)
                        {
                            MessageBox.Show(Resources.UpdateUnavailableMessage,
                                Resources.UpdateUnavailableCaption,
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }

            return false;
        }

        private static void ShowError(Exception exception)
        {
            if (CheckForUpdateEvent != null)
            {
                CheckForUpdateEvent(new UpdateInfoEventArgs {Error = exception});
            }
            else
            {
                if (ReportErrors)
                {
                    if (exception is WebException)
                    {
                        MessageBox.Show(
                            Resources.UpdateCheckFailedMessage,
                            Resources.UpdateCheckFailedCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show(exception.Message,
                            exception.GetType().ToString(), MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }
                }
            }

            Running = false;
        }

        /// <summary>
        ///     Detects and exits all instances of running assembly, including current.
        /// </summary>
        internal static void Exit()
        {
            var currentProcess = Process.GetCurrentProcess();
            foreach (var process in Process.GetProcessesByName(currentProcess.ProcessName))
            {
                string processPath;
                try
                {
                    processPath = process.MainModule?.FileName;
                }
                catch (Win32Exception)
                {
                    // Current process should be same as processes created by other instances of the application so it should be able to access modules of other instances.
                    // This means this is not the process we are looking for so we can safely skip this.
                    continue;
                }

                //get all instances of assembly except current
                if (process.Id != currentProcess.Id && currentProcess.MainModule?.FileName == processPath)
                {
                    if (process.CloseMainWindow())
                    {
                        process.WaitForExit((int) TimeSpan.FromSeconds(10)
                            .TotalMilliseconds); //give some time to process message
                    }

                    if (!process.HasExited)
                    {
                        process.Kill(); //TODO show UI message asking user to close program himself instead of silently killing it
                    }
                }
            }

            if (ApplicationExitEvent != null)
            {
                ApplicationExitEvent();
            }
            else
            {
                if (_isWinFormsApplication)
                {
                    MethodInvoker methodInvoker = Application.Exit;
                    methodInvoker.Invoke();
                }
                else if (System.Windows.Application.Current != null)
                {
                    System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        System.Windows.Application.Current.Shutdown()));
                }
                else
                {
                    Environment.Exit(0);
                }
            }
        }

        private static Attribute GetAttribute(Assembly assembly, Type attributeType)
        {
            object[] attributes = assembly.GetCustomAttributes(attributeType, false);
            if (attributes.Length == 0)
            {
                return null;
            }

            return (Attribute) attributes[0];
        }

        internal static string GetUserAgent()
        {
            return string.IsNullOrEmpty(HttpUserAgent) ? $"AutoUpdater.NET" : HttpUserAgent;
        }

        internal static void SetTimer(DateTime remindLater)
        {
            TimeSpan timeSpan = remindLater - DateTime.Now;

            var context = SynchronizationContext.Current;

            _remindLaterTimer = new System.Timers.Timer
            {
                Interval = Math.Max(1, timeSpan.TotalMilliseconds),
                AutoReset = false
            };

            _remindLaterTimer.Elapsed += delegate
            {
                _remindLaterTimer = null;
                if (context != null)
                {
                    try
                    {
                        context.Send(_ => Start(), null);
                    }
                    catch (InvalidAsynchronousStateException)
                    {
                        Start();
                    }
                }
                else
                {
                    Start();
                }
            };

            _remindLaterTimer.Start();
        }

        /// <summary>
        ///     Opens the Download window that download the update and execute the installer when download completes.
        /// </summary>
        public static bool DownloadUpdate(UpdateInfoEventArgs args)
        {
            using (var downloadDialog = new DownloadUpdateDialog(args))
            {
                try
                {
                    return downloadDialog.ShowDialog().Equals(DialogResult.OK);
                }
                catch (TargetInvocationException)
                {
                }
            }

            return false;
        }

        /// <summary>
        ///     Shows standard update dialog.
        /// </summary>
        public static void ShowUpdateForm(UpdateInfoEventArgs args)
        {
            using (var updateForm = new UpdateForm(args))
            {
                if (UpdateFormSize.HasValue)
                {
                    updateForm.Size = UpdateFormSize.Value;
                }

                if (updateForm.ShowDialog().Equals(DialogResult.OK))
                {
                    Exit();
                }
            }
        }

        internal static MyWebClient GetWebClient(Uri uri, IAuthentication basicAuthentication)
        {
            MyWebClient webClient = new MyWebClient
            {
                CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)
            };

            if (Proxy != null)
            {
                webClient.Proxy = Proxy;
            }

            if (uri.Scheme.Equals(Uri.UriSchemeFtp))
            {
                webClient.Credentials = FtpCredentials;
            }
            else
            {
                basicAuthentication?.Apply(ref webClient);

                webClient.Headers[HttpRequestHeader.UserAgent] = HttpUserAgent;
            }

            return webClient;
        }
    }
}


text:
  package   scalarules.test.scalafmt
    import         org.scalatest._
   class    FormatTest     extends      FlatSpec      {
  "FormatTest"       should    "be formatted"    in {
           assert     (        true   )
  }
}

redpajama_set_name: RedPajamaGithub


text:
import {AmpdocAnalyticsRoot} from '../analytics-root';
import {
  AnalyticsEvent,
  ClickEventTracker,
  CustomEventTracker,
  IniLoadTracker,
  SignalTracker,
  VisibilityTracker,
} from '../events';
import {Signals} from '../../../../src/utils/signals';
import * as sinon from 'sinon';

describes.realWin('Events', {amp: 1}, env => {
  let win;
  let ampdoc;
  let root;
  let handler;
  let analyticsElement;
  let target;
  let child;

  beforeEach(() => {
    win = env.win;
    ampdoc = env.ampdoc;
    root = new AmpdocAnalyticsRoot(ampdoc);
    handler = sandbox.spy();

    analyticsElement = win.document.createElement('amp-analytics');
    win.document.body.appendChild(analyticsElement);

    target = win.document.createElement('div');
    target.classList.add('target');
    win.document.body.appendChild(target);

    child = win.document.createElement('div');
    child.classList.add('child');
    target.appendChild(child);
  });

  describe('ClickEventTracker', () => {
    let iniEventCount;
    let tracker;

    beforeEach(() => {
      // ActionService and some other services may also add click listeners.
      iniEventCount = win.document.eventListeners.count('click');
      tracker = new ClickEventTracker(root);
    });

    it('should initalize, add listeners and dispose', () => {
      expect(tracker.root).to.equal(root);
      expect(tracker.clickObservable_.getHandlerCount()).to.equal(0);
      expect(win.document.eventListeners.count('click'))
          .to.equal(iniEventCount + 1);

      tracker.dispose();
      expect(win.document.eventListeners.count('click'))
          .to.equal(iniEventCount);
    });

    it('should require selector', () => {
      expect(() => {
        tracker.add(analyticsElement, 'click', {selector: ''});
      }).to.throw(/Missing required selector/);
    });

    it('should add listener', () => {
      const selUnlisten = function() {};
      const selListenerStub = sandbox.stub(root, 'createSelectiveListener',
          () => selUnlisten);
      tracker.add(analyticsElement, 'click',
          {selector: '*', selectionMethod: 'scope'}, handler);
      expect(tracker.clickObservable_.getHandlerCount()).to.equal(1);
      expect(tracker.clickObservable_.handlers_[0]).to.equal(selUnlisten);
      expect(selListenerStub).to.be.calledOnce;
      const args = selListenerStub.args[0];
      expect(args[0]).to.be.function;
      expect(args[1]).to.equal(win.document.body);  // Parent element of amp-analytics.
      expect(args[2]).to.equal('*');
      expect(args[3]).to.equal('scope');  // Default selection method.
    });

    it('should add listener with default selection method', () => {
      const selListenerStub = sandbox.stub(root, 'createSelectiveListener');
      tracker.add(analyticsElement, 'click', {selector: '*'}, handler);
      expect(selListenerStub.args[0][3]).to.be.null;  // Default selection method.
    });

    it('should handle click on target', () => {
      tracker.add(analyticsElement, 'click', {selector: '.target'}, handler);
      target.click();
      expect(handler).to.be.calledOnce;
      const event = handler.args[0][0];
      expect(event.target).to.equal(target);
      expect(event.type).to.equal('click');
      expect(event.vars).to.deep.equal({});
    });

    it('should handle click on child', () => {
      tracker.add(analyticsElement, 'click', {selector: '.target'}, handler);
      child.click();
      expect(handler).to.be.calledOnce;
      const event = handler.args[0][0];
      expect(event.target).to.equal(target);
      expect(event.type).to.equal('click');
      expect(event.vars).to.deep.equal({});
    });

    it('should call multiple handlers', () => {
      tracker.add(analyticsElement, 'click', {selector: '.target'}, handler);
      target.click();
      expect(handler).to.be.calledOnce;

      const handler2 = sandbox.spy();
      tracker.add(analyticsElement, 'click', {selector: '.target'}, handler2);
      child.click();
      expect(handler).to.be.calledTwice;
      expect(handler2).to.be.calledOnce;
    });

    it('should only stop on the first found target', () => {
      tracker.add(analyticsElement, 'click', {selector: '.target'}, handler);
      const handler2 = sandbox.spy();
      tracker.add(analyticsElement, 'click', {selector: '.child'}, handler2);
      target.click();
      child.click();
      expect(handler2).to.be.calledOnce;
      expect(handler).to.be.calledTwice;
    });

    it('should expand data params', () => {
      tracker.add(analyticsElement, 'click', {selector: '.target'}, handler);
      target.setAttribute('data-vars-foo', 'bar');
      target.click();
      const event = handler.args[0][0];
      expect(event.vars).to.deep.equal({'foo': 'bar'});
    });
  });

  describe('CustomEventTracker', () => {
    let tracker;
    let clock;
    const targetReadyPromise = Promise.resolve();
    let getElementSpy;

    beforeEach(() => {
      clock = sandbox.useFakeTimers();
      tracker = new CustomEventTracker(root);
      getElementSpy = sandbox.spy(root, 'getElement');
    });

    it('should initalize, add listeners and dispose', () => {
      expect(tracker.root).to.equal(root);
      expect(tracker.buffer_).to.exist;
      expect(tracker.sandboxBuffer_).to.exist;

      tracker.dispose();
      expect(tracker.buffer_).to.not.exist;
      expect(tracker.sandboxBuffer_).to.not.exist;
    });

    it('should listen on custom events', () => {
      const handler2 = sandbox.spy();
      tracker.add(analyticsElement, 'custom-event-1', {}, handler);
      tracker.add(analyticsElement, 'custom-event-2', {}, handler2);
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-1'));
      expect(getElementSpy).to.be.calledTwice;
      return getElementSpy.returnValues[1].then(() => {
        expect(handler).to.be.calledOnce;
        expect(handler2).to.have.not.been.called;
        tracker.trigger(new AnalyticsEvent(target, 'custom-event-2'));
        return targetReadyPromise.then(() => {
          expect(handler).to.be.calledOnce;
          expect(handler2).to.be.calledOnce;
          tracker.trigger(new AnalyticsEvent(target, 'custom-event-1'));
          return targetReadyPromise.then(() => {
            expect(handler).to.have.callCount(2);
            expect(handler2).to.be.calledOnce;
          });
        });
      });
    });

    it('should support selector', () => {
      let eventResolver1, eventResolver2;
      const eventPromise1 = new Promise(resolve => {
        eventResolver1 = resolve;
      });
      const eventPromise2 = new Promise(resolve => {
        eventResolver2 = resolve;
      });
      tracker.add(
          analyticsElement, 'custom-event', {'selector': '.child'}, handler);
      tracker.add(analyticsElement,
          'custom-event', {'selector': '.target'}, eventResolver1);
      tracker.add(
          analyticsElement, 'custom-event', {}, eventResolver2);
      tracker.trigger(new AnalyticsEvent(target, 'custom-event'));
      return eventPromise1.then(() => {
        return eventPromise2.then(() => {
          expect(handler).to.not.be.called;
        });
      });
    });

    it('should differ custom event with same name different selector', () => {
      const child2 = win.document.createElement('div');
      child2.classList.add('child2');
      target.appendChild(child2);
      const handler2 = sandbox.spy();
      tracker.add(
          analyticsElement, 'custom-event', {'selector': '.child'}, handler);
      tracker.add(
          analyticsElement, 'custom-event', {'selector': '.child2'}, handler2);
      tracker.trigger(new AnalyticsEvent(child, 'custom-event'));
      expect(getElementSpy).to.be.calledTwice;
      return getElementSpy.returnValues[1].then(() => {
        expect(handler).to.be.calledOnce;
        expect(handler2).to.not.be.called;
        handler.reset();
        tracker.trigger(new AnalyticsEvent(child2, 'custom-event'));
      }).then(() => {
        expect(handler).to.not.be.called;
        expect(handler2).to.be.calledOnce;
      });
    });

    it('should buffer custom events early on', function* () {
      // Events before listeners added.
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-1'));
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-2'));
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-2'));
      expect(tracker.buffer_['custom-event-1']).to.have.length(1);
      expect(tracker.buffer_['custom-event-2']).to.have.length(2);

      // Listeners added: immediate events fired.
      const handler2 = sandbox.spy();
      const handler3 = sandbox.spy();
      tracker.add(analyticsElement, 'custom-event-1', {}, handler);
      tracker.add(analyticsElement, 'custom-event-2', {}, handler2);
      tracker.add(analyticsElement, 'custom-event-3', {}, handler3);
      yield getElementSpy.returnValues[2];
      clock.tick(1);
      expect(handler).to.be.calledOnce;
      expect(handler2).to.have.callCount(2);
      expect(handler3).to.have.not.been.called;
      expect(tracker.buffer_['custom-event-1']).to.have.length(1);
      expect(tracker.buffer_['custom-event-2']).to.have.length(2);
      expect(tracker.buffer_['custom-event-3']).to.be.undefined;

      // Second round of events.
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-1'));
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-2'));
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-3'));
      expect(getElementSpy).to.have.callCount(3);

      yield getElementSpy.returnValues[2];

      expect(handler).to.have.callCount(2);
      expect(handler2).to.have.callCount(3);
      expect(handler3).to.be.calledOnce;
      expect(tracker.buffer_['custom-event-1']).to.have.length(2);
      expect(tracker.buffer_['custom-event-2']).to.have.length(3);
      expect(tracker.buffer_['custom-event-3']).to.have.length(1);

      // Buffering time expires.
      clock.tick(10001);
      expect(tracker.buffer_).to.be.undefined;

      // Post-buffering round of events.
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-1'));
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-2'));
      tracker.trigger(new AnalyticsEvent(target, 'custom-event-3'));
      return targetReadyPromise.then(() => {
        expect(handler).to.have.callCount(3);
        expect(handler2).to.have.callCount(4);
        expect(handler3).to.have.callCount(2);
        expect(tracker.buffer_).to.be.undefined;
      });
    });

    it('should not not fire twice from observerable and buffer', function* () {
      tracker.trigger(
          new AnalyticsEvent(target, 'custom-event-1', {'order': '1'}));
      tracker.add(analyticsElement, 'custom-event-1', {}, handler);
      yield targetReadyPromise;
      tracker.trigger(
          new AnalyticsEvent(target, 'custom-event-1', {'order': '2'}));
      yield targetReadyPromise;
      clock.tick(1);
      expect(handler).to.have.callCount(2);
      expect(handler.firstCall).to.be.calledWith(new AnalyticsEvent(
          target, 'custom-event-1', {'order': '2'}));
      expect(handler.secondCall).to.be.calledWith(new AnalyticsEvent(
          target, 'custom-event-1', {'order': '1'}));
    });

    it('should buffer sandbox events in different list', function* () {
      // Events before listeners added.
      tracker.trigger(new AnalyticsEvent(target, 'sandbox-1-event-1'));
      tracker.trigger(new AnalyticsEvent(target, 'event-1'));

      expect(tracker.buffer_['event-1']).to.have.length(1);
      expect(tracker.sandboxBuffer_['sandbox-1-event-1']).to.have.length(1);
      clock.tick(10001);
      expect(tracker.buffer_).to.be.undefined;
      expect(tracker.sandboxBuffer_['sandbox-1-event-1']).to.have.length(1);
      tracker.add(analyticsElement, 'sandbox-1-event-1', {}, handler);
      yield targetReadyPromise;
      clock.tick(1);
      expect(handler).to.be.calledOnce;
      expect(tracker.sandboxBuffer_['sandbox-1-event-1']).to.be.undefined;
    });

    it('should keep sandbox buffer before handler is added', function* () {
      tracker.trigger(new AnalyticsEvent(target, 'sandbox-1-event-1'));
      clock.tick(10001);
      tracker.trigger(new AnalyticsEvent(target, 'sandbox-1-event-1'));
      clock.tick(1000);
      tracker.add(analyticsElement, 'sandbox-1-event-1', {}, handler);
      yield targetReadyPromise;
      clock.tick(1);
      expect(handler).to.be.calledTwice;
    });

    it('should handle all events without duplicate trigger', function* () {
      tracker.trigger(
          new AnalyticsEvent(target, 'sandbox-1-event-1', {'order': '1'}));
      tracker.trigger(
          new AnalyticsEvent(target, 'sandbox-1-event-1', {'order': '2'}));
      tracker.add(analyticsElement, 'sandbox-1-event-1', {}, handler);
      yield targetReadyPromise;
      tracker.trigger(
          new AnalyticsEvent(target, 'sandbox-1-event-1', {'order': '3'}));
      yield targetReadyPromise;
      clock.tick(1);
      expect(tracker.sandboxBuffer_['sandbox-1-event-1']).to.be.undefined;
      tracker.trigger(
          new AnalyticsEvent(target, 'sandbox-1-event-1', {'order': '4'}));
      yield targetReadyPromise;
      expect(handler).to.have.callCount(4);
      expect(handler.firstCall).to.be.calledWith(new AnalyticsEvent(
          target, 'sandbox-1-event-1', {'order': '3'}));
      expect(handler.secondCall).to.be.calledWith(new AnalyticsEvent(
          target, 'sandbox-1-event-1', {'order': '1'}));
      expect(handler.thirdCall).to.be.calledWith(new AnalyticsEvent(
          target, 'sandbox-1-event-1', {'order': '2'}));
      expect(handler.lastCall).to.be.calledWith(new AnalyticsEvent(
          target, 'sandbox-1-event-1', {'order': '4'}));
    });
  });

  describe('SignalTracker', () => {
    let tracker;
    let targetSignals;

    beforeEach(() => {
      tracker = new SignalTracker(root);
      target.classList.add('i-amphtml-element');
      targetSignals = new Signals();
      target.signals = () => targetSignals;
    });

    it('should initalize, add listeners and dispose', () => {
      expect(tracker.root).to.equal(root);
    });

    it('should add doc listener', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      tracker.add(analyticsElement, 'sig1', {}, resolver);
      root.signals().signal('sig1');
      return promise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('sig1');
      });
    });

    it('should add root listener', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      tracker.add(analyticsElement, 'sig1', {selector: ':root'}, resolver);
      root.signals().signal('sig1');
      return promise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('sig1');
      });
    });

    it('should add host listener equal to root', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      tracker.add(analyticsElement, 'sig1', {selector: ':host'}, resolver);
      root.signals().signal('sig1');
      return promise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('sig1');
      });
    });

    it('should add target listener', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      tracker.add(analyticsElement, 'sig1', {selector: '.target'}, resolver);
      targetSignals.signal('sig1');
      return promise.then(event => {
        expect(event.target).to.equal(target);
        expect(event.type).to.equal('sig1');
      });
    });
  });

  describe('IniLoadTracker', () => {
    let tracker;
    let targetSignals;

    beforeEach(() => {
      tracker = new IniLoadTracker(root);
      target.classList.add('i-amphtml-element');
      targetSignals = new Signals();
      target.signals = () => targetSignals;
    });

    it('should initalize, add listeners and dispose', () => {
      expect(tracker.root).to.equal(root);
    });

    it('should add doc listener', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      const iniLoadStub = sandbox.stub(root, 'whenIniLoaded',
          () => Promise.resolve());
      tracker.add(analyticsElement, 'ini-load', {}, resolver);
      return promise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('ini-load');
        expect(iniLoadStub).to.be.calledOnce;
      });
    });

    it('should add root listener', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      const iniLoadStub = sandbox.stub(root, 'whenIniLoaded',
          () => Promise.resolve());
      tracker.add(analyticsElement, 'ini-load', {selector: ':root'}, resolver);
      return promise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('ini-load');
        expect(iniLoadStub).to.be.calledOnce;
      });
    });

    it('should add host listener equal to root', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      const iniLoadStub = sandbox.stub(root, 'whenIniLoaded',
          () => Promise.resolve());
      tracker.add(analyticsElement, 'sig1', {selector: ':host'}, resolver);
      return promise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('sig1');
        expect(iniLoadStub).to.be.calledOnce;
      });
    });

    it('should add target listener', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      const spy = sandbox.spy(targetSignals, 'whenSignal');
      tracker.add(analyticsElement, 'ini-load', {selector: '.target'},
          resolver);
      targetSignals.signal('ini-load');
      return promise.then(event => {
        expect(event.target).to.equal(target);
        expect(event.type).to.equal('ini-load');
        expect(spy).to.be.calledWith('ini-load');
      });
    });

    it('should trigger via load-end as well', () => {
      let resolver;
      const promise = new Promise(resolve => {
        resolver = resolve;
      });
      const spy = sandbox.spy(targetSignals, 'whenSignal');
      tracker.add(analyticsElement, 'ini-load', {selector: '.target'},
          resolver);
      targetSignals.signal('load-end');
      return promise.then(event => {
        expect(event.target).to.equal(target);
        expect(event.type).to.equal('ini-load');
        expect(spy).to.be.calledWith('load-end');
      });
    });
  });

  describe('VisibilityTracker', () => {
    let tracker;
    let visibilityManagerMock;
    let iniLoadTrackerMock;
    let targetSignals;
    let eventResolver, eventPromise;
    let saveCallback;
    let matchEmptySpec;
    let matchFunc;
    let getAmpElementSpy;

    beforeEach(() => {
      tracker = new VisibilityTracker(root);
      visibilityManagerMock = sandbox.mock(root.getVisibilityManager());
      getAmpElementSpy = sandbox.spy(root, 'getAmpElement');
      tracker.waitForTrackers_['ini-load'] = new IniLoadTracker(tracker.root);
      iniLoadTrackerMock = sandbox.mock(tracker.waitForTrackers_['ini-load']);

      target.classList.add('i-amphtml-element');
      targetSignals = new Signals();
      target.signals = () => targetSignals;

      eventPromise = new Promise(resolve => {
        eventResolver = resolve;
      });

      matchEmptySpec = sinon.match(arg => {
        return Object.keys(arg).length == 0;
      });
      matchFunc = sinon.match(arg => {
        if (typeof arg == 'function') {
          const promise = arg();
          if (typeof promise.then == 'function') {
            return true;
          }
        }
        return false;
      });
      saveCallback = sinon.match(arg => {
        if (typeof arg == 'function') {
          saveCallback.callback = arg;
          return true;
        }
        return false;
      });
    });

    afterEach(() => {
      visibilityManagerMock.verify();
    });

    it('should initalize, add listeners and dispose', () => {
      expect(tracker.root).to.equal(root);
    });

    it('should add doc listener', () => {
      const unlisten = function() {};
      iniLoadTrackerMock.expects('getRootSignal').never();
      iniLoadTrackerMock.expects('getElementSignal').never();
      visibilityManagerMock
          .expects('listenRoot')
          .withExactArgs(
          matchEmptySpec,
          /* readyPromise */ null,
          /* createReadyReportPromiseFunc */ null,
          saveCallback)
          .returns(unlisten)
          .once();
      const res = tracker.add(analyticsElement, 'visible', {}, eventResolver);
      expect(res).to.equal(unlisten);
      saveCallback.callback({totalVisibleTime: 10});
      return eventPromise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('visible');
        expect(event.vars.totalVisibleTime).to.equal(10);
      });
    });

    it('should add root listener', () => {
      const config = {selector: ':root'};
      const unlisten = function() {};
      iniLoadTrackerMock.expects('getElementSignal').never();
      const readyPromise = Promise.resolve();
      iniLoadTrackerMock
          .expects('getRootSignal')
          .returns(readyPromise)
          .once();
      visibilityManagerMock
          .expects('listenRoot')
          .withExactArgs(
          matchEmptySpec,
          readyPromise,
          null,
          saveCallback)
          .returns(unlisten)
          .once();
      const res = tracker.add(analyticsElement,
          'visible', config, eventResolver);
      expect(res).to.equal(unlisten);
      saveCallback.callback({totalVisibleTime: 10});
      return eventPromise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('visible');
        expect(event.vars.totalVisibleTime).to.equal(10);
      });
    });

    it('should add host listener and spec', () => {
      const config = {visibilitySpec: {selector: ':host'}};
      const unlisten = function() {};
      iniLoadTrackerMock.expects('getElementSignal').never();
      const readyPromise = Promise.resolve();
      iniLoadTrackerMock
          .expects('getRootSignal')
          .returns(readyPromise)
          .once();
      visibilityManagerMock
          .expects('listenRoot')
          .withExactArgs(
          config.visibilitySpec,
          readyPromise,
          /* createReadyReportPromiseFunc */ null,
          saveCallback)
          .returns(unlisten)
          .once();
      const res = tracker.add(analyticsElement,
          'visible', config, eventResolver);
      expect(res).to.equal(unlisten);
      saveCallback.callback({totalVisibleTime: 10});
      return eventPromise.then(event => {
        expect(event.target).to.equal(root.getRootElement());
        expect(event.type).to.equal('visible');
        expect(event.vars.totalVisibleTime).to.equal(10);
      });
    });

    it('should add target listener', () => {
      const config = {visibilitySpec: {selector: '.target'}};
      const unlisten = sandbox.spy();
      iniLoadTrackerMock.expects('getRootSignal').once();
      const readyPromise = Promise.resolve();
      iniLoadTrackerMock
          .expects('getElementSignal')
          .withExactArgs('ini-load', target)
          .returns(readyPromise)
          .once();
      visibilityManagerMock
          .expects('listenElement')
          .withExactArgs(
          target,
          config.visibilitySpec,
          readyPromise,
          /* createReadyReportPromiseFunc */ null,
          saveCallback)
          .returns(unlisten)
          .once();
      const res = tracker.add(analyticsElement,
          'visible', config, eventResolver);
      expect(res).to.be.function;
      const unlistenReady = getAmpElementSpy.returnValues[0];

      return unlistenReady.then(() => {
        saveCallback.callback({totalVisibleTime: 10});
        return eventPromise.then(event => {
          expect(event.target).to.equal(target);
          expect(event.type).to.equal('visible');
          expect(event.vars.totalVisibleTime).to.equal(10);

          // Test unlisten.
          expect(unlisten).to.not.be.called;
          res();
        }).then(() => {
          expect(unlisten).to.be.calledOnce;
        });
      });
    });

    it('should expand data params', () => {
      target.setAttribute('data-vars-foo', 'bar');

      const config = {selector: '.target'};
      const unlisten = sandbox.spy();
      iniLoadTrackerMock.expects('getRootSignal').never();
      const readyPromise = Promise.resolve();

      iniLoadTrackerMock
          .expects('getElementSignal')
          .withExactArgs('ini-load', target)
          .returns(readyPromise)
          .once();
      visibilityManagerMock
          .expects('listenElement')
          .withExactArgs(
          target,
          matchEmptySpec,
          readyPromise,
          /* createReadyReportPromiseFunc */ null,
          saveCallback)
          .returns(unlisten)
          .once();
      tracker.add(analyticsElement, 'visible', config, eventResolver);
      const unlistenReady = getAmpElementSpy.returnValues[0];
      return unlistenReady.then(() => {
        saveCallback.callback({totalVisibleTime: 10});
        return eventPromise.then(event => {
          expect(event.vars.totalVisibleTime).to.equal(10);
          expect(event.vars.foo).to.equal('bar');
        });
      });
    });

    it('should pass func to get reportReady with "hidden" trigger', () => {
      const config = {visibilitySpec: {selector: '.target', waitFor: 'none'}};
      visibilityManagerMock
          .expects('listenElement')
          .withExactArgs(
          target,
          config.visibilitySpec,
          /* readyPromise */ null,
          /* createReadyReportPromiseFunc */ matchFunc,
          saveCallback)
          .returns(null)
          .once();
      tracker.add(analyticsElement, 'hidden', config, eventResolver);
      const unlistenReady = getAmpElementSpy.returnValues[0];
      // NOTE: createReadyReportPromiseFunc is
      // fully tested in test-visibility-manager
      return unlistenReady.then(() => {
        saveCallback.callback({totalVisibleTime: 10});
        return eventPromise.then(event => {
          expect(event.vars.totalVisibleTime).to.equal(10);
          expect(event.type).to.equal('hidden');
        });
      });
    });

    describe('should wait on correct readyPromise', () => {
      const selector = '.target';

      it('with waitFor default value', () => {
        // Default case: selector is not specified
        expect(tracker.getReadyPromise(undefined, undefined)).to.be.null;
        // Default case: waitFor is not specified, no AMP element selected
        iniLoadTrackerMock
            .expects('getRootSignal')
            .returns(Promise.resolve())
            .once();
        const waitForTracker1 = tracker.getReadyPromise(undefined, ':root');
        return waitForTracker1.then(() => {
          iniLoadTrackerMock
              .expects('getElementSignal')
              .withExactArgs('ini-load', target)
              .returns(Promise.resolve())
              .once();
          // Default case: waitFor is not specified, AMP element selected
          const promise2 = tracker.getReadyPromise(undefined, selector, target);
          target.signals().signal('ini-load');
          return promise2;
        });
      });

      it('with waitFor NONE', () => {
        expect(tracker.getReadyPromise('none', undefined, undefined))
            .to.be.null;
        expect(tracker.getReadyPromise('none', ':root', undefined))
            .to.be.null;
        expect(tracker.getReadyPromise('none', selector, target))
            .to.be.null;
      });

      it('with waitFor INI_LOAD', () => {
        iniLoadTrackerMock
            .expects('getRootSignal')
            .returns(Promise.resolve())
            .twice();
        const promise =
            tracker.getReadyPromise('ini-load', undefined, undefined);
        return promise.then(() => {
          const promise1 =
            tracker.getReadyPromise('ini-load', ':root', undefined);
          return promise1.then(() => {
            iniLoadTrackerMock
                .expects('getElementSignal')
                .withExactArgs('ini-load', target)
                .returns(Promise.resolve())
                .once();
            const promise2 =
                tracker.getReadyPromise('ini-load', selector, target);
            return promise2;
          });
        });
      });

      it('with waitFor RENDER_START', () => {
        tracker.waitForTrackers_['render-start'] =
            new SignalTracker(tracker.root);
        const signalTrackerMock =
            sandbox.mock(tracker.waitForTrackers_['render-start']);
        signalTrackerMock
            .expects('getRootSignal')
            .withExactArgs('render-start')
            .returns(Promise.resolve())
            .twice();
        const promise =
            tracker.getReadyPromise('render-start', undefined, undefined);
        return promise.then(() => {
          const promise1 =
              tracker.getReadyPromise('render-start', ':root', undefined);
          return promise1.then(() => {
            signalTrackerMock
                .expects('getElementSignal')
                .withExactArgs('render-start', target)
                .returns(Promise.resolve())
                .once();
            const promise2 =
                tracker.getReadyPromise('render-start', selector, target);
            return promise2;
          });
        });
      });
    });

    describe('should create correct readyReportPromise', () => {
      it('with viewer hidden', () => {
        const stub = sandbox.stub(tracker.root, 'getViewer', () => {
          return {
            isVisible: () => {return false;},
          };
        });
        const promise = tracker.createReportReadyPromise_();
        return promise.then(() => {
          expect(stub).to.be.calledOnce;
        });
      });
    });
  });
});


text:
package com.zakgof.db.velvet.link;

import com.zakgof.db.velvet.IVelvet;

public interface ILinkDef<HK, HV, CK, CV> extends IReadOnlyLinkDef<HK, HV, CK, CV> {

    public void connectKeys(IVelvet velvet, HK akey, CK bkey);

    // public void batchConnectKeys(IVelvet velvet, Map<HK, CK> connections);

    public void disconnectKeys(IVelvet velvet, HK akey, CK bkey);

    // public void batchDisconnectKeys(IVelvet velvet, Map<HK, CK> connections);

    public default void connect(IVelvet velvet, HV a, CV b) {
        connectKeys(velvet, getHostEntity().keyOf(a), getChildEntity().keyOf(b));
    }

    public default void disconnect(IVelvet velvet, HV a, CV b) {
        disconnectKeys(velvet, getHostEntity().keyOf(a), getChildEntity().keyOf(b));
    }
}


text:
<?php

namespace Ongoing;

class ProcessArticle
{

    /**
     * @var string $GoodsOwnerCode
     */
    protected $GoodsOwnerCode = null;

    /**
     * @var string $UserName
     */
    protected $UserName = null;

    /**
     * @var string $Password
     */
    protected $Password = null;

    /**
     * @var ArticleDefinition $art
     */
    protected $art = null;

    /**
     * @param string $GoodsOwnerCode
     * @param string $UserName
     * @param string $Password
     * @param ArticleDefinition $art
     */
    public function __construct($GoodsOwnerCode, $UserName, $Password, $art)
    {
      $this->GoodsOwnerCode = $GoodsOwnerCode;
      $this->UserName = $UserName;
      $this->Password = $Password;
      $this->art = $art;
    }

    /**
     * @return string
     */
    public function getGoodsOwnerCode()
    {
      return $this->GoodsOwnerCode;
    }

    /**
     * @param string $GoodsOwnerCode
     * @return \Ongoing\ProcessArticle
     */
    public function setGoodsOwnerCode($GoodsOwnerCode)
    {
      $this->GoodsOwnerCode = $GoodsOwnerCode;
      return $this;
    }

    /**
     * @return string
     */
    public function getUserName()
    {
      return $this->UserName;
    }

    /**
     * @param string $UserName
     * @return \Ongoing\ProcessArticle
     */
    public function setUserName($UserName)
    {
      $this->UserName = $UserName;
      return $this;
    }

    /**
     * @return string
     */
    public function getPassword()
    {
      return $this->Password;
    }

    /**
     * @param string $Password
     * @return \Ongoing\ProcessArticle
     */
    public function setPassword($Password)
    {
      $this->Password = $Password;
      return $this;
    }

    /**
     * @return ArticleDefinition
     */
    public function getArt()
    {
      return $this->art;
    }

    /**
     * @param ArticleDefinition $art
     * @return \Ongoing\ProcessArticle
     */
    public function setArt($art)
    {
      $this->art = $art;
      return $this;
    }

}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe ActionView::Helpers::FormHelper do
  before :each do
    @model = TestModel.new
    I18n.reload!
  end

  it "should produce a select_enum" do
    html = [
      %(<select id="model_category" name="model[category]"><option value="stuff">stuff</option>),
      %(<option value="things">things</option>),
      %(<option value="misc">misc</option></select>)
    ].join($/)
    form_for @model do |f|
      f.fields_for :model do |fields|
        fields.select_enum(:category).should eql(html)
      end
    end
  end

  it "should produce a radio_button_enum" do
    html = [
      %(<input id="model_status_pending" name="model[status]" type="radio" value="pending" />),
      %(pending),
      %(<input id="model_status_failed" name="model[status]" type="radio" value="failed" />),
      %(failed),
      %(<input id="model_status_done" name="model[status]" type="radio" value="done" />),
      %(done)
    ].join($/)

    fields_for(:model) do |fields|
      fields.radio_button_enum(:status).should eql(html)
    end
  end

  describe "I18n" do
    before :each do
      I18n.locale = :de
      I18n.backend.store_translations(:de, YAML::load(<<-YAML
      activerecord:
        attributes:
          model:
            category_enum:
              stuff:  'Zeug'
              things: 'Sachen'
              misc:   'Diverses'
            status_enum:
              pending: 'In Arbeit'
              failed:  'Fehlgeschlagen'
              done:    'Erledigt'
      YAML
      ))
    end

    it "should produce translated options for a select_enum" do
      html = fields_for(:model) do |fields|
        fields.select_enum(:category)
      end
      html.should include(%(<option value="stuff">Zeug</option>))
      html.should include(%(<option value="things">Sachen</option>))
      html.should include(%(<option value="misc">Diverses</option>))
    end

    it "should translated labels for produce a radio_button_enum" do
      html = fields_for(:model) do |fields|
        fields.radio_button_enum(:status)
      end
      html.should include(%(In Arbeit))
      html.should include(%(Fehlgeschlagen))
      html.should include(%(Erledigt))
    end
  end
end


text:
[![Build Status](https://api.travis-ci.org/fbalicchia/graylog-plugin-backup-configuration.svg?branch=master)](https://travis-ci.org/fbalicchia/graylog-plugin-backup-configuration.git)
[![Github Downloads](https://img.shields.io/github/downloads/fbalicchia/graylog-plugin-backup-configuration/total.svg)](https://github.com/fbalicchia/graylog-plugin-backup-configuration/releases)

This plugin provides the possibility of saving and restore graylog environment configurations like registered user, dashboard, input etc.etc. To do this task the plugin uses directly **mongorestore** and **mongodump** command.
At the moment is supported only unix-like os and dump can be stored only on filesystem and not on other Storage Service like s3 etc.etc

Any feedback are wellcome !

**Required Graylog version:** 2.1 and later

Installation
------------

[Download the plugin](https://github.com/fbalicchia/graylog-plugin-backup-configuration/releases)
and place the `.jar` file in your Graylog plugin directory. The plugin directory
is the `plugins/` folder relative from your `graylog-server` directory by default
and can be configured in your `graylog.conf` file.
Restart `graylog-server` and you are done.

"Official" release is cut around the last Graylog build of plugins release in this case 2.1.2, nothing prevents to compile it independently using
for example rc or beta version. In the same way binary package install jar under folder '/usr/share/graylog-server/plugin'

To adapt it to yours environment just change 'graylog.version' and 'graylog.plugin-dir' properties in pom file
the is created using a third library and not '-gzip' flag introduced with 3.2 Mongo's version

Usage
-----

You can configure backup plugin Under System -> Configurations.

[![](https://github.com/fbalicchia/graylog-plugin-backup-configuration/blob/master/images/backupconf_overview.png)]

Using  `update configuration button` is possible adapt configuration to your environment. If not specified back data is saved under graylog data directory.

[![](https://github.com/fbalicchia/graylog-plugin-backup-configuration/blob/master/images/backupconf_popup.png)]

Backup file follow the this naming convention **graylogyyyyMMddHHmm.zip**

For restore data is necessary to put backup file under restore folder.
At the moment there is a limitation that under restore folder there is only zip without any directory.

* Under System-configuration press `Restore data button`. If something fails the system show the corresponding error

[![](https://github.com/fbalicchia/graylog-plugin-backup-configuration/blob/master/images/backup_conf_restore_fail.png)]

Otherwise if process ends successfully

[![](https://github.com/fbalicchia/graylog-plugin-backup-configuration/blob/master/images/backconfig_restore.png)]

`Simple configuration example`
* threshold PT1M (every minute)
* Enable backup Process
* Select directory where you want to save data for example /tmp/data/bck and /tmp/data/restore
* find where MongoDump is installed. On ubuntu, for example, by default is under */usr/bin*

To restore your data please put the zip in this restore folder in this case /tmp/data/restore then from GUI click restore data


text:
package net.tatans.rhea.network.event;

import android.widget.ExpandableListView;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by Yuriy on 16-04-30.
 * ·µ»ØÀàÐÍ void
 * ´«ÈëµÄ²ÎÊý int groupPosition
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@EventBase(
        listenerType = ExpandableListView.OnGroupExpandListener.class,
        listenerSetter = "setOnGroupExpandListener",
        methodName = "onGroupExpand")
public @interface OnGroupExpand {
    int[] value();

    int[] parentId() default 0;
}


text:
.class final synthetic Lcom/android/systemui/statusbar/notification/-$Lambda$mrZnuGpGaPmmUw8hQkArZeLgDzo;
.super Ljava/lang/Object;

# interfaces
.implements Landroid/animation/ValueAnimator$AnimatorUpdateListener;

# instance fields
.field private final synthetic -$f0:Ljava/lang/Object;

# direct methods
.method private final synthetic $m$0(Landroid/animation/ValueAnimator;)V
    .locals 1

    iget-object v0, p0, Lcom/android/systemui/statusbar/notification/-$Lambda$mrZnuGpGaPmmUw8hQkArZeLgDzo;->-$f0:Ljava/lang/Object;

    check-cast v0, Ljava/util/function/Consumer;

    invoke-static {v0, p1}, Lcom/android/systemui/statusbar/notification/NotificationDozeHelper;->lambda$-com_android_systemui_statusbar_notification_NotificationDozeHelper_3101(Ljava/util/function/Consumer;Landroid/animation/ValueAnimator;)V

    return-void
.end method

.method public synthetic constructor <init>(Ljava/lang/Object;)V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p1, p0, Lcom/android/systemui/statusbar/notification/-$Lambda$mrZnuGpGaPmmUw8hQkArZeLgDzo;->-$f0:Ljava/lang/Object;

    return-void
.end method

# virtual methods
.method public final onAnimationUpdate(Landroid/animation/ValueAnimator;)V
    .locals 0

    invoke-direct {p0, p1}, Lcom/android/systemui/statusbar/notification/-$Lambda$mrZnuGpGaPmmUw8hQkArZeLgDzo;->$m$0(Landroid/animation/ValueAnimator;)V

    return-void
.end method


text:
package com.changeme.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;

import java.sql.Date;

@RepositoryRestResource(collectionResourceRel = "persons", path = "persons")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {

    Page<Person> findByDepartment(@Param("department") Department department, Pageable pageable);

    @Query("SELECT p from Person p " +
            "WHERE " +
            "(:lastName IS NULL or p.lastName like CONCAT('%',:lastName, '%')) AND " +
            "(:firstName IS NULL or p.firstName like  CONCAT('%',:firstName, '%')) AND " +
            "(:birthDate IS NULL or p.birthDate >= :birthDate) AND " +
            "(:department IS NULL or p.department = :department)")
    @RestResource(path="findPerson", rel="findPerson")
    Page<Person> findPerson(
            @Param("lastName")String lastName,
            @Param("firstName")String firstName,
            @Param("birthDate")Date birthDate,
            @Param("department")Department department,
            Pageable pageable);

}


text:
package org.springframework.social.connect.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;

/**
 * {@link UsersConnectionRepository} that uses the JDBC API to persist connection data to a relational database.
 * The supporting schema is defined in JdbcUsersConnectionRepository.sql.
 * @author Keith Donald
 */
public class JdbcUsersConnectionRepository implements UsersConnectionRepository {

	private final JdbcTemplate jdbcTemplate;

	private final ConnectionFactoryLocator connectionFactoryLocator;

	private final TextEncryptor textEncryptor;

	private ConnectionSignUp connectionSignUp;

	private String tablePrefix = "";

	public JdbcUsersConnectionRepository(DataSource dataSource, ConnectionFactoryLocator connectionFactoryLocator, TextEncryptor textEncryptor) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
		this.connectionFactoryLocator = connectionFactoryLocator;
		this.textEncryptor = textEncryptor;
	}

	@Override
	public void setConnectionSignUp(ConnectionSignUp connectionSignUp) {
		this.connectionSignUp = connectionSignUp;
	}

	/**
	 * Sets a table name prefix. This will be prefixed to all the table names before queries are executed. Defaults to "".
	 * This is can be used to qualify the table name with a schema or to distinguish Spring Social tables from other application tables.
	 * @param tablePrefix the tablePrefix to set
	 */
	public void setTablePrefix(String tablePrefix) {
		this.tablePrefix = tablePrefix;
	}

	public List<String> findUserIdsWithConnection(Connection<?> connection) {
		ConnectionKey key = connection.getKey();
		List<String> localUserIds = jdbcTemplate.queryForList("select userId from " + tablePrefix + "UserConnection where providerId = ? and providerUserId = ?", String.class, key.getProviderId(), key.getProviderUserId());
		if (localUserIds.size() == 0 && connectionSignUp != null) {
			String newUserId = connectionSignUp.execute(connection);
			if (newUserId != null)
			{
				createConnectionRepository(newUserId).addConnection(connection);
				return Arrays.asList(newUserId);
			}
		}
		return localUserIds;
	}

	public Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds) {
		MapSqlParameterSource parameters = new MapSqlParameterSource();
		parameters.addValue("providerId", providerId);
		parameters.addValue("providerUserIds", providerUserIds);
		final Set<String> localUserIds = new HashSet<String>();
		return new NamedParameterJdbcTemplate(jdbcTemplate).query("select userId from " + tablePrefix + "UserConnection where providerId = :providerId and providerUserId in (:providerUserIds)", parameters,
			new ResultSetExtractor<Set<String>>() {
				public Set<String> extractData(ResultSet rs) throws SQLException, DataAccessException {
					while (rs.next()) {
						localUserIds.add(rs.getString("userId"));
					}
					return localUserIds;
				}
			});
	}

	public ConnectionRepository createConnectionRepository(String userId) {
		if (userId == null) {
			throw new IllegalArgumentException("userId cannot be null");
		}
		return new JdbcConnectionRepository(userId, jdbcTemplate, connectionFactoryLocator, textEncryptor, tablePrefix);
	}

}


text:
package jp.co.tis.gsp.tools.dba.util;

import jp.co.tis.gsp.tools.dba.dialect.Dialect;

/**
 * @author kawasima
 */
public class DialectUtil {
    static ThreadLocal<Dialect> threadDialect= new ThreadLocal<Dialect>();

    public static Dialect getDialect() {
        return threadDialect.get();
    }

    public static void setDialect(Dialect dialect) {
        threadDialect.set(dialect);
    }
}


text:
<?php
/*
 *  Made by Samerton
 *  https://github.com/NamelessMC/Nameless/
 *  NamelessMC version 2.0.0-pr8
 *
 *  License: MIT
 *
 *  Home page
 */

// Always define page name
const PAGE = 'index';
$page_title = $language->get('general', 'home');
require_once(ROOT_PATH . '/core/templates/frontend_init.php');

$template->assets()->include([
    DARK_MODE
        ? AssetTree::PRISM_DARK
        : AssetTree::PRISM_LIGHT,
    AssetTree::TINYMCE_SPOILER,
]);

if (Session::exists('home')) {
    $smarty->assign('HOME_SESSION_FLASH', Session::flash('home'));
    $smarty->assign('SUCCESS_TITLE', $language->get('general', 'success'));
}

if (Session::exists('home_error')) {
    $smarty->assign('HOME_SESSION_ERROR_FLASH', Session::flash('home_error'));
    $smarty->assign('ERROR_TITLE', $language->get('general', 'error'));
}

$home_type = Util::getSetting('home_type');

$smarty->assign('HOME_TYPE', $home_type);

if ($home_type === 'news') {
    foreach ($front_page_modules as $module) {
        require(ROOT_PATH . '/' . $module);
    }
} else if ($home_type === 'custom') {
    $smarty->assign('CUSTOM_HOME_CONTENT', Util::getSetting('home_custom_content'));
}

// Assign to Smarty variables
$smarty->assign('SOCIAL', $language->get('general', 'social'));

// Load modules + template
Module::loadPage($user, $pages, $cache, $smarty, [$navigation, $cc_nav, $staffcp_nav], $widgets, $template);

$template->onPageLoad();

$smarty->assign('WIDGETS_LEFT', $widgets->getWidgets('left'));
$smarty->assign('WIDGETS_RIGHT', $widgets->getWidgets('right'));

require(ROOT_PATH . '/core/templates/navbar.php');
require(ROOT_PATH . '/core/templates/footer.php');

// Display template
$template->displayTemplate('index.tpl', $smarty);


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

namespace EA4S
{
    public static class RandomHelper
    {

        private static readonly Random _random = new Random(DateTime.Now.Millisecond);
        public static T GetRandom<T>(this IList<T> list)
        {
            if (list.Count == 0) {
                throw new System.Exception("Cannot get a random element from the list as count is zero.");
            }
            return list[_random.Next(0, list.Count)];
        }

        public static T GetRandomParams<T>(params T[] ids)
        {
            return ids[_random.Next(0, ids.Length)];
        }

        public static T GetRandomEnum<T>()
        {
            var A = Enum.GetValues(typeof(T));
            var V = (T)A.GetValue(UnityEngine.Random.Range(0, A.Length));
            return V;
        }

        /// <summary>
        /// Extension to Shuffle a list and return a new one
        /// </summary>
        public static List<T> Shuffle<T>(this List<T> fromList)
        {
            return new List<T>(fromList.OrderBy(a => UnityEngine.Random.value));
        }

        public static List<T> RouletteSelectNonRepeating<T>(List<T> fromList, int numberToSelect)
        {
            if (numberToSelect > fromList.Count) {
                throw new System.Exception("Cannot select more than available with a non-repeating selection");
            }

            var chosenList = new List<T>();

            if (numberToSelect == fromList.Count) {
                chosenList.AddRange(fromList);
                return chosenList;
            }

            for (var choice_index = 0; choice_index < numberToSelect; choice_index++) {
                var element_index = UnityEngine.Random.Range(0, fromList.Count);
                var chosenItem = fromList[element_index];
                fromList.RemoveAt(element_index);
                chosenList.Add(chosenItem);
            }

            return chosenList;
        }

        public static List<T> RouletteSelectNonRepeating<T>(List<T> fromList, List<float> weightsList, int numberToSelect)
        {
            if (numberToSelect > fromList.Count) {
                throw new System.Exception("Cannot select more than available with a non-repeating selection");
            }

            var chosenList = new List<T>();

            if (numberToSelect == fromList.Count) {
                chosenList.AddRange(fromList);
                chosenList = chosenList.Shuffle();
                return chosenList;
            }

            for (var choice_index = 0; choice_index < numberToSelect; choice_index++) {
                var totalWeight = weightsList.Sum();
                var choiceValue = UnityEngine.Random.value * totalWeight;
                float cumulativeWeight = 0;
                for (var element_index = 0; element_index < fromList.Count; element_index++) {
                    cumulativeWeight += weightsList[element_index];
                    if (choiceValue <= cumulativeWeight) {
                        var chosenItem = fromList[element_index];
                        fromList.RemoveAt(element_index);
                        weightsList.RemoveAt(element_index);
                        chosenList.Add(chosenItem);
                        break;
                    }
                }
            }

            return chosenList;
        }

        public static List<T> RandomSelect<T>(this List<T> all_list, int maxNumberToSelect, bool forceMaxNumber = false)
        {
            if (maxNumberToSelect == 0) {
                return new List<T>();
            }

            if (all_list.Count == 0) {
                throw new System.Exception("The list has zero elements to select from.");
            }

            if (!forceMaxNumber && all_list.Count < maxNumberToSelect) {
                maxNumberToSelect = all_list.Count;

            }

            return RouletteSelectNonRepeating<T>(all_list, maxNumberToSelect);
        }

        public static T RandomSelectOne<T>(this List<T> all_list)
        {
            if (all_list.Count == 0) {
                throw new System.Exception("The list has zero elements to select from.");
            }

            return RouletteSelectNonRepeating<T>(all_list, 1)[0];
        }
    }
}


text:
!(function(window) {
    'use strict';

    // define main constants
    var ROOT       = 'LSP.';
    var STORE      = window.localStorage;
    var EXPIRE_KEY = '--exp';

    /**
     * Util functions
     * @private
     * @type {Object}
     */
    var util = {
        remove: function(key) {
            STORE.removeItem(key.replace(EXPIRE_KEY, ''));
            STORE.removeItem(key);
        },
        flush: function(index) {
            Object.keys(STORE).map(function(key) {
                if (key.indexOf(index) === 0) {
                    util.remove(key);
                }
            });
        },
        flushExpired: function(index) {
            if (Object.keys(STORE).length > 0) {
                Object.keys(STORE).map(function(key) {
                    if (key.indexOf(index) === 0 && key.indexOf(EXPIRE_KEY) !== -1) {
                        if (STORE.getItem(key) < Date.now()) {
                            util.remove(key);
                        }
                    }
                });
            }
        }
    }

    /**
     * Define a new store
     * @class
     * @param  {string} name            The name of the store
     * @param  {boolean} [flushExpired] should the flush expired not run
     * @return {Store}                  The store instance
     */
    var Store = function(name, autoFlushExpired) {
        var storeName;

        function __construct(name) {
            try {
                storeName = validateStoreName(name);

                if (autoFlushExpired === undefined || autoFlushExpired !== false) {
                    flushExpired();
                }
            } catch(error) {
                console.error(error);
            }
        }

        /**
         * Set a defined key with the given value
         * @param  {string} key          The name of the value
         * @param  {mixed}  data         The data to store, can be any datatype
         * @param  {int}    [expiresAt]  When should this value expire
         * @return {void}
         */
        function set(key, data, expiresAt) {
            try {
                if (expiresAt !== undefined && typeof expiresAt === 'number') {
                    STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString());
                }

                STORE.setItem(storeName + key, decodeObjectString(data));

                return true;
            } catch(error) {
                console.error(error);
                return false;
            }
        }

        /**
         * Get the value stored under the given key, or the whole store
         * @param  {string} [key] Index defined in @set
         * @return {mixed}        Stored value
         */
        function get(key) {
            try {
                if (key !== undefined) {
                    var result = encodeObjectString(STORE.getItem(storeName + key));
                    return result !== null ? result : false;
                } else {
                    var resultAll = {};

                    Object.keys(STORE).map(function(key) {
                        if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) {
                            var varKey = key.replace(storeName, '');
                            resultAll[varKey] = get(varKey);
                        }
                    });

                    return resultAll;
                }
            } catch(error) {
                console.error(error)
                return false;
            }
        }

        /**
         * Check if the given key exists in the store
         * @param  {string}  key  index of the value to test
         * @return {boolean}      Key defined or not
         */
        function isset(key) {
            return STORE.getItem(storeName + key) !== null ? true : false;
        }

        /**
         * Flush all values, that are stored in the store instance
         * @return {void}
         */
        function flush() {
            util.flush(storeName);
        }

        /**
         * Remove an item, by the given key and its expire if set
         * @param  {string} key  Index of the value
         * @return {void}
         */
        function remove(key) {
            util.remove(storeName + key);
        }

        /**
         * flush expired values defined in this store
         * @return {void}
         */
        function flushExpired() {
            util.flushExpired(storeName);
        }

        /**
         * generate a store name
         * @param  {string} storeName  The name of the store instance
         * @return {string}            The generated name
         * @throws {TypeError}
         */
        function validateStoreName(storeName) {
            if (storeName === undefined) {
                throw new TypeError('Please provide a storename');
            }

            if (typeof(storeName) !== 'string') {
                throw new TypeError('The storename has to be a string');
            }

            var chargedStoreName = storeName = ROOT + storeName + '-';
            return chargedStoreName;
        }

        /**
         * decode a value if its type is a object
         * @private
         * @param  {mixed}  data  Value to decode
         * @return {mixed}        The decoded value
         */
        function decodeObjectString(data) {
            if (typeof data === 'object') {
                return JSON.stringify(data);
            }

            return data;
        }

        /**
         * encode a value if the value is a object
         * @param  {mixed} data  The value to encode
         * @return {mixed}       The encoded value
         */
        function encodeObjectString(data) {
            if (typeof data === 'string') {
                try {
                    return JSON.parse(data);
                } catch(e) {
                    return data;
                }
            }
        }

        __construct(name);

        // define public interface
        return {
            set    : set,
            get    : get,
            flush  : flush,
            remove : remove,
            isset  : isset
        }
    }

    // static store methods

    /**
     * remove all items from the whole store
     * @return {void}
     */
    Store.flush = function() {
        util.flush(ROOT);
    }

    /**
     * remove all expired items from the whole store
     * @return {void}
     */
    Store.flushExpired = function() {
        util.flushExpired(ROOT);
    }

    // remove the expired values
    Store.flushExpired();

    // export the module
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = Store;
    }

    if (typeof window !== 'undefined' && window) {
        window.Store = Store;
    }
})(window);


text:
/****************************************************************************
 Module
     ES_CheckEvents.h
 Description
     header file for use with the data structures to define the event checking
     functions and the function to loop through the array calling the checkers
 Notes

 History
 When           Who     What/Why
 -------------- ---     --------
 02/08/12 15:27 jec      added #define for the case of no user event checkers
 01/15/12 12:00 jec      new header for local types
 10/16/11 17:17 jec      started coding
*****************************************************************************/

#ifndef ES_CheckEvents_H
#define ES_CheckEvents_H

#include "ES_Types.h"

typedef boolean CheckFunc( void );

typedef CheckFunc (*pCheckFunc);

boolean ES_CheckUserEvents( void );

#define NO_EVENT_CHECKERS ((pCheckFunc)0)

#endif  // ES_CheckEvents_H


text:
whiptail --title "TerminalGAME" --menu --separate-output "Choose:" 20 78 15 \
"Pacman4Console" "Pacman!!"  \
"Sudoku" "The classic game of Sudoku"  \
"Arithmetic" "Gives your brain a workout"  \
"Crawl" "role-playing text based game"  \
"Dopewars" "Clean up New York for drugs"  \
"Empire" "War simulation"  \
"Greed" "Eat as much as possible"  \
"Mancala" "Mancala in the Terminal"  \
"Moon-Buggy" "Jump around in your mooncar"  \
"NetHack" "Dungeon exploration game"  \
"Ninvaders" "Space Invaders in the Terminal"  \
"Nsnake" "Snake in the Terminal"  \
"Slash-em" "Variant of NetHack"  \
"Tint" "This Is Not Tetris"  2>games

CHOICE=$(cat games)
case $CHOICE in
      Pacman4Console) pacman4console
      ;;
      Sudoku) sudoku
      ;;
      Arithmetic) arithmetic
      ;;
      Crawl) crawl
      ;;
      Dopewars) dopewars
      ;;
      Empire) empire
      ;;
      Greed) greed
      ;;
      Mancala) mancala
      ;;
      Moon-Buggy) moon-buggy
      ;;
      NetHack) nethack-console
      ;;
      Ninvaders) ninvaders
      ;;
      Nsnake) nsnake
      ;;
      Slash-em) slashem
      ;;
      Tint) tint
      ;;
    esac


text:
/**
 * @Author: philip
 * @Date:   2017-05-27T22:58:51+00:00
 * @Filename: ArticleList.js
 * @Last modified by:   philip
 * @Last modified time: 2017-05-31T10:05:13+00:00
 */

import React from 'react';
import { Meteor } from 'meteor/meteor';
import { composeWithTracker } from 'react-komposer';
// import NewsRooms from '/lib/collections/newsRooms';
import Loading from '../components/Loading.js';
import ArticleList from '../components/ArticleList';

const composer = ({ url, renderDetailComponent }, onData) => {
  Meteor.call('getRssArticles', [url], (err, articles) => {
    if (!err) {
      onData(null, { articles, renderDetailComponent, url });
      return;
    }
    console.log(err);
    onData(null, { renderDetailComponent, url });
  });

};

export default composeWithTracker(composer, Loading)(ArticleList);


text:
package fleetdb;

public class FleetDBException extends Exception {
  public FleetDBException(String msg) { super(msg); }
  public FleetDBException()           { super();    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Reflection;
using System.Runtime.InteropServices;
using System.Diagnostics;

using System.Xml.Linq;

namespace Class2XML
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            UpdateObjectViewer();
        }

        void UpdateObjectViewer()
        {
            treeView1.Nodes.Clear();

            treeView1.Nodes.AddRange(Namespaces.Select(x =>
            {
                var node = new TreeNode(x.Name) { Tag = x };
                node.Nodes.Add(new TreeNode());
                return node;
            }).ToArray());
        }

        XMLDocCommentList DocComments
        {
            get
            {
                var docs = new XMLDocCommentList();
                docs.AddRange(listBox1.Items.Cast<XMLDocComment>());
                return docs;
            }
        }

        IEnumerable<NamespaceInfo> Namespaces
        {
            get
            {
                return NamespaceInfo.Create(checkedListBox1.Items.Cast<Assembly>().Where((x, i) => checkedListBox1.GetItemChecked(i)), DocComments);
            }
        }

        enum FileOpeningResult
        {
            Succeed, Fail, Skipped
        }

        FileOpeningResult OpenAssembly(string path)
        {
            try
            {
                if (checkedListBox1.Items.Cast<Assembly>().Any(x => x.Location == path))
                {
                    checkedListBox1.SetItemCheckState(checkedListBox1.Items.Cast<Assembly>()
                        .Select((x, i) => Tuple.Create(x, i))
                        .First(x => x.Item1.Location == path).Item2, CheckState.Checked);
                    return FileOpeningResult.Skipped;
                }

                checkedListBox1.Items.Add(Assembly.LoadFrom(path));
                checkedListBox1.SetItemCheckState(checkedListBox1.Items.Count - 1, CheckState.Checked);

                return FileOpeningResult.Succeed;
            }
            catch (Exception)
            {
                return FileOpeningResult.Fail;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (libOpenDialog.ShowDialog() != DialogResult.OK) return;

            int succeed = 0, fail = 0, skipped = 0;
            foreach (var f in libOpenDialog.FileNames)
            {
                var result = OpenAssembly(f);
                if (result == FileOpeningResult.Succeed) succeed++;
                if (result == FileOpeningResult.Fail) fail++;
                if (result == FileOpeningResult.Skipped) skipped++;
            }

            var statuses = new List<string>();
            if (succeed > 0) statuses.Add(string.Format("{0} 読み込み完了", succeed));
            if (skipped > 0) statuses.Add(string.Format("{0} スキップ", skipped));
            if (fail > 0) statuses.Add(string.Format("{0} 失敗", fail));

            statusLabel.Text = string.Join(" / ", statuses);

            UpdateObjectViewer();
        }

        FileOpeningResult OpenXMLDoc(string path)
        {
            try
            {
                if (listBox1.Items.Cast<XMLDocComment>().Any(x => x.FileName == path))
                    return FileOpeningResult.Skipped;

                listBox1.Items.Add(XMLDocComment.Load(path));

                return FileOpeningResult.Succeed;
            }
            catch (Exception)
            {
                return FileOpeningResult.Fail;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (xmldocOpenDialog.ShowDialog() != DialogResult.OK) return;

            int succeed = 0, fail = 0, skipped = 0;
            foreach (var f in xmldocOpenDialog.FileNames)
            {
                var result = OpenXMLDoc(f);
                if (result == FileOpeningResult.Succeed) succeed++;
                if (result == FileOpeningResult.Fail) fail++;
                if (result == FileOpeningResult.Skipped) skipped++;
            }

            var statuses = new List<string>();
            if (succeed > 0) statuses.Add(string.Format("{0} 読み込み完了", succeed));
            if (skipped > 0) statuses.Add(string.Format("{0} スキップ", skipped));
            if (fail > 0) statuses.Add(string.Format("{0} 失敗", fail));

            statusLabel.Text = string.Join(" / ", statuses);

            UpdateObjectViewer();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            checkedListBox1.DisplayMember = "FullName";
            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (o, ex) =>
            {
                try
                {
                    return Assembly.ReflectionOnlyLoad(ex.Name);
                }
                catch (Exception exx)
                {
                    try
                    {
                        return Assembly.ReflectionOnlyLoadFrom(
                            System.IO.Path.Combine(
                                System.IO.Path.GetDirectoryName(ex.RequestingAssembly.Location), ex.Name.Split(',')[0] + ".dll"));
                    }
                    catch
                    {
                        throw exx;
                    }
                }
            };

            AppDomain.CurrentDomain.AssemblyResolve += (o, ex) =>
            {
                try
                {
                    return Assembly.Load(ex.Name);
                }
                catch (Exception exx)
                {
                    try
                    {
                        return Assembly.LoadFrom(
                            System.IO.Path.Combine(
                                System.IO.Path.GetDirectoryName(ex.RequestingAssembly.Location), ex.Name.Split(',')[0] + ".dll"));
                    }
                    catch
                    {
                        throw exx;
                    }
                }
            };
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (checkedListBox1.SelectedIndex >= 0)
                checkedListBox1.Items.RemoveAt(checkedListBox1.SelectedIndex);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            while (listBox1.SelectedIndices.Count > 0)
                listBox1.Items.RemoveAt(listBox1.SelectedIndices[0]);
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
                propertyGrid1.SelectedObject = treeView1.SelectedNode.Tag;
            else
                propertyGrid1.SelectedObject = null;
        }

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            e.Node.Nodes.Clear();
            if (((MemberItem)e.Node.Tag).Children != null)
                e.Node.Nodes.AddRange(((MemberItem)e.Node.Tag).Children.Select(x =>
                {
                    var node = new TreeNode(x.Name) { Tag = x };
                    if(x.Children != null && x.Children.Length > 0)
                        node.Nodes.Add(new TreeNode(x.Name));
                        return node;
                }).ToArray());
        }

        private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            if (((MemberItem)e.Node.Tag).Children != null && ((MemberItem)e.Node.Tag).Children.Length > 0)
                e.Node.Nodes.Add(new TreeNode());

        }

        private void button7_Click(object sender, EventArgs e)
        {
            exportDialog.FileName = textBox1.Text;
            if (exportDialog.ShowDialog() != DialogResult.OK) return;
            textBox1.Text = exportDialog.FileName;
        }

        private async void button6_Click(object sender, EventArgs e)
        {
            var fileName = textBox1.Text;
            button6.Enabled = false;
            try
            {
                if (System.IO.File.Exists(fileName))
                    MessageBox.Show(string.Format("ファイル {0} は既に存在します。上書きしますか?", fileName), "確認", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);

                var doc = new XDocument();
                doc.Add(new XElement("namespaces"));

                NamespaceInfo[] nss = new NamespaceInfo[0] ;
                if (checkBox1.Checked)
                    nss = NamespaceInfo.Create(checkedListBox1.Items.Cast<Assembly>().Where((x, i) => checkedListBox1.GetItemChecked(i)).SelectMany(x => x.GetTypes().Where(y => TypeInfo.CheckVisibleType(y) && !y.IsImport)), DocComments);
                else
                    nss = Namespaces.ToArray();

                progressBar1.Maximum = nss.Length;
                progressBar1.Value = 0;
                progressBar1.Step = 1;

                foreach (var ns in nss)
                {
                    doc.Root.Add(ns.CreateXML());

                    progressBar1.PerformStep();
                }

                using (var stream = System.IO.File.Create(fileName))
                    await Task.Run(() => doc.Save(stream));
            }
            finally
            {
                button6.Enabled = true;
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            if(e.Data.GetDataPresent(DataFormats.FileDrop)) {
                var files = (string[])e.Data.GetData(DataFormats.FileDrop);

                int succeed = 0, fail = 0, skipped = 0;
                foreach (var f in files)
                {
                    var resultX = OpenXMLDoc(f);
                    var resultA = OpenAssembly(f);
                    if (resultA == FileOpeningResult.Succeed || resultX == FileOpeningResult.Succeed)
                        succeed++;
                    else if (resultA == FileOpeningResult.Skipped || resultX == FileOpeningResult.Skipped)
                        skipped++;
                    else
                        fail++;
                }

                var statuses = new List<string>();
                if (succeed > 0) statuses.Add(string.Format("{0} 読み込み完了", succeed));
                if (skipped > 0) statuses.Add(string.Format("{0} スキップ", skipped));
                if (fail > 0) statuses.Add(string.Format("{0} 失敗", fail));

                statusLabel.Text = string.Join(" / ", statuses);

                UpdateObjectViewer();
            }
        }
    }
}