text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Outlining;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using UIAutomationClient;
using ThreadHelper = Microsoft.VisualStudio.Shell.ThreadHelper;

namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
    [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Used through .NET Remoting.")]
    internal partial class Editor_InProc : TextViewWindow_InProc
    {
        internal static readonly Guid IWpfTextViewId = new Guid("8C40265E-9FDB-4F54-A0FD-EBB72B7D0476");

        private readonly SendKeys_InProc _sendKeys;

        private Editor_InProc()
        {
            _sendKeys = new SendKeys_InProc(VisualStudio_InProc.Create());
        }

        public static Editor_InProc Create()
            => new Editor_InProc();

        protected override bool HasActiveTextView()
            => ErrorHandler.Succeeded(TryGetActiveTextViewHost().hr);

        protected override IWpfTextView GetActiveTextView()
            => GetActiveTextViewHost().TextView;

        private static IVsTextView GetActiveVsTextView()
        {
            var (textView, hr) = TryGetActiveVsTextView();
            Marshal.ThrowExceptionForHR(hr);
            return textView;
        }

        private static (IVsTextView textView, int hr) TryGetActiveVsTextView()
        {
            var vsTextManager = GetGlobalService<SVsTextManager, IVsTextManager>();
            var hresult = vsTextManager.GetActiveView(fMustHaveFocus: 1, pBuffer: null, ppView: out var vsTextView);
            return (vsTextView, hresult);
        }

        private static IWpfTextViewHost GetActiveTextViewHost()
        {
            var (textViewHost, hr) = TryGetActiveTextViewHost();
            Marshal.ThrowExceptionForHR(hr);
            return textViewHost;
        }

        private static (IWpfTextViewHost textViewHost, int hr) TryGetActiveTextViewHost()
        {
            // The active text view might not have finished composing yet, waiting for the application to 'idle'
            // means that it is done pumping messages (including WM_PAINT) and the window should return the correct text view
            WaitForApplicationIdle(Helper.HangMitigatingTimeout);

            var (activeVsTextView, hr) = TryGetActiveVsTextView();
            if (!ErrorHandler.Succeeded(hr))
            {
                return (null, hr);
            }

            var hresult = ((IVsUserData)activeVsTextView).GetData(IWpfTextViewId, out var wpfTextViewHost);
            return ((IWpfTextViewHost)wpfTextViewHost, hresult);
        }

        public bool IsUseSuggestionModeOn()
        {
            return ExecuteOnActiveView(textView =>
            {
                var featureServiceFactory = GetComponentModelService<IFeatureServiceFactory>();
                var subjectBuffer = GetBufferContainingCaret(textView);

                var options = textView.Options.GlobalOptions;
                EditorOptionKey<bool> optionKey;
                bool defaultOption;
                if (IsDebuggerTextView(textView))
                {
                    optionKey = new EditorOptionKey<bool>(PredefinedCompletionNames.SuggestionModeInDebuggerCompletionOptionName);
                    defaultOption = true;
                }
                else
                {
                    optionKey = new EditorOptionKey<bool>(PredefinedCompletionNames.SuggestionModeInCompletionOptionName);
                    defaultOption = false;
                }

                if (!options.IsOptionDefined(optionKey, localScopeOnly: false))
                {
                    return defaultOption;
                }

                return options.GetOptionValue(optionKey);
            });

            bool IsDebuggerTextView(IWpfTextView textView)
                => textView.Roles.Contains("DEBUGVIEW");
        }

        public void SetUseSuggestionMode(bool value)
        {
            if (IsUseSuggestionModeOn() != value)
            {
                ExecuteCommand(WellKnownCommandNames.Edit_ToggleCompletionMode);

                if (IsUseSuggestionModeOn() != value)
                {
                    throw new InvalidOperationException($"{WellKnownCommandNames.Edit_ToggleCompletionMode} did not leave the editor in the expected state.");
                }
            }
        }

        public void VerifyNotSaved()
        {
            Contract.ThrowIfTrue(GetDTE().ActiveDocument.ProjectItem.Saved);
        }

        public string VerifySaved()
        {
            var activeDocument = GetDTE().ActiveDocument;
            Contract.ThrowIfFalse(activeDocument.ProjectItem.Saved);
            return activeDocument.FullName;
        }

        public string GetActiveBufferName()
        {
            return GetDTE().ActiveDocument.Name;
        }

        public string GetActiveWindowName()
        {
            return GetDTE().ActiveWindow.Caption;
        }

        public void WaitForActiveView(string expectedView)
        {
            using var cts = new CancellationTokenSource(Helper.HangMitigatingTimeout);
            Retry(_ => GetActiveBufferName(), (actual, _) => actual == expectedView, TimeSpan.FromMilliseconds(100), cts.Token);
        }

        public void WaitForActiveWindow(string expectedWindow)
        {
            using var cts = new CancellationTokenSource(Helper.HangMitigatingTimeout);
            Retry(_ => GetActiveWindowName(), (actual, _) => actual == expectedWindow, TimeSpan.FromMilliseconds(100), cts.Token);
        }

        public void Activate()
            => GetDTE().ActiveDocument.Activate();

        public bool IsProjectItemDirty()
            => GetDTE().ActiveDocument.ProjectItem.IsDirty;

        public string GetText()
            => ExecuteOnActiveView(view => view.TextSnapshot.GetText());

        public void SetText(string text)
            => ExecuteOnActiveView(view =>
            {
                var textSnapshot = view.TextSnapshot;
                var replacementSpan = new SnapshotSpan(textSnapshot, 0, textSnapshot.Length);
                view.TextBuffer.Replace(replacementSpan, text);
            });

        public void SelectText(string text)
        {
            PlaceCaret(text, charsOffset: -1, occurrence: 0, extendSelection: false, selectBlock: false);
            PlaceCaret(text, charsOffset: 0, occurrence: 0, extendSelection: true, selectBlock: false);
        }

        public void ReplaceText(string oldText, string newText)
            => ExecuteOnActiveView(view =>
            {
                var textSnapshot = view.TextSnapshot;
                SelectText(oldText);
                var replacementSpan = new SnapshotSpan(textSnapshot, view.Selection.Start.Position, view.Selection.End.Position - view.Selection.Start.Position);
                view.TextBuffer.Replace(replacementSpan, newText);
            });

        public string GetCurrentLineText()
            => ExecuteOnActiveView(view =>
            {
                var subjectBuffer = view.GetBufferContainingCaret();
                var bufferPosition = view.Caret.Position.BufferPosition;
                var line = bufferPosition.GetContainingLine();

                return line.GetText();
            });

        public int GetLine()
            => ExecuteOnActiveView(view =>
            {
                view.Caret.Position.BufferPosition.GetLineAndCharacter(out var lineNumber, out var characterIndex);
                return lineNumber;
            });

        public int GetColumn()
            => ExecuteOnActiveView(view =>
            {
                view.Caret.Position.BufferPosition.GetLineAndCharacter(out var lineNumber, out var characterIndex);
                return characterIndex;
            });

        public string GetLineTextBeforeCaret()
            => ExecuteOnActiveView(view =>
            {
                var subjectBuffer = view.GetBufferContainingCaret();
                var bufferPosition = view.Caret.Position.BufferPosition;
                var line = bufferPosition.GetContainingLine();
                var text = line.GetText();

                return text.Substring(0, bufferPosition.Position - line.Start);
            });

        public string GetLineTextAfterCaret()
            => ExecuteOnActiveView(view =>
            {
                var subjectBuffer = view.GetBufferContainingCaret();
                var bufferPosition = view.Caret.Position.BufferPosition;
                var line = bufferPosition.GetContainingLine();
                var text = line.GetText();

                return text.Substring(bufferPosition.Position - line.Start);
            });

        public string GetSelectedText()
            => ExecuteOnActiveView(view =>
            {
                var subjectBuffer = view.GetBufferContainingCaret();
                var selectedSpan = view.Selection.SelectedSpans[0];
                return subjectBuffer.CurrentSnapshot.GetText(selectedSpan);
            });

        public void MoveCaret(int position)
            => ExecuteOnActiveView(view =>
            {
                var subjectBuffer = view.GetBufferContainingCaret();
                var point = new SnapshotPoint(subjectBuffer.CurrentSnapshot, position);

                view.Caret.MoveTo(point);
            });

        /// <remarks>
        /// This method does not wait for async operations before
        /// querying the editor
        /// </remarks>
        public bool IsSignatureHelpActive()
            => ExecuteOnActiveView(view =>
            {
                var broker = GetComponentModelService<ISignatureHelpBroker>();
                return broker.IsSignatureHelpActive(view);
            });

        public string[] GetErrorTags()
            => GetTags<IErrorTag>();

        public string[] GetHighlightTags()
           => GetTags<ITextMarkerTag>(tag => tag.Type == KeywordHighlightTag.TagId);

        private string PrintSpan(SnapshotSpan span)
                => $"'{span.GetText().Replace("\\", "\\\\").Replace("\r", "\\r").Replace("\n", "\\n")}'[{span.Start.Position}-{span.Start.Position + span.Length}]";

        private string[] GetTags<TTag>(Predicate<TTag> filter = null)
            where TTag : ITag
        {
            bool Filter(TTag tag)
                => true;

            if (filter == null)
            {
                filter = Filter;
            }

            return ExecuteOnActiveView(view =>
            {
                var viewTagAggregatorFactory = GetComponentModelService<IViewTagAggregatorFactoryService>();
                var aggregator = viewTagAggregatorFactory.CreateTagAggregator<TTag>(view);
                var tags = aggregator
                  .GetTags(new SnapshotSpan(view.TextSnapshot, 0, view.TextSnapshot.Length))
                  .Where(t => filter(t.Tag))
                  .Cast<IMappingTagSpan<ITag>>();
                return tags.Select(tag => $"{tag.Tag}:{PrintSpan(tag.Span.GetSpans(view.TextBuffer).Single())}").ToArray();
            });
        }

        /// <remarks>
        /// This method does not wait for async operations before
        /// querying the editor
        /// </remarks>
        public Signature[] GetSignatures()
            => ExecuteOnActiveView(view =>
            {
                var broker = GetComponentModelService<ISignatureHelpBroker>();

                var sessions = broker.GetSessions(view);
                if (sessions.Count != 1)
                {
                    throw new InvalidOperationException($"Expected exactly one session in the signature help, but found {sessions.Count}");
                }

                return sessions[0].Signatures.Select(s => new Signature(s)).ToArray();
            });

        /// <remarks>
        /// This method does not wait for async operations before
        /// querying the editor
        /// </remarks>
        public Signature GetCurrentSignature()
            => ExecuteOnActiveView(view =>
            {
                var broker = GetComponentModelService<ISignatureHelpBroker>();

                var sessions = broker.GetSessions(view);
                if (sessions.Count != 1)
                {
                    throw new InvalidOperationException($"Expected exactly one session in the signature help, but found {sessions.Count}");
                }

                return new Signature(sessions[0].SelectedSignature);
            });

        public bool IsCaretOnScreen()
            => ExecuteOnActiveView(view =>
            {
                var caret = view.Caret;

                return caret.Left >= view.ViewportLeft
                    && caret.Right <= view.ViewportRight
                    && caret.Top >= view.ViewportTop
                    && caret.Bottom <= view.ViewportBottom;
            });

        public ClassifiedToken[] GetLightbulbPreviewClassifications(string menuText)
        {
            return ThreadHelper.JoinableTaskFactory.Run(async () =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var view = GetActiveTextView();
                var broker = GetComponentModel().GetService<ILightBulbBroker>();
                var classifierAggregatorService = GetComponentModelService<IViewClassifierAggregatorService>();
                return await GetLightbulbPreviewClassificationsAsync(
                    menuText,
                    broker,
                    view,
                    classifierAggregatorService).ConfigureAwait(false);
            });
        }

        private async Task<ClassifiedToken[]> GetLightbulbPreviewClassificationsAsync(
            string menuText,
            ILightBulbBroker broker,
            IWpfTextView view,
            IViewClassifierAggregatorService viewClassifierAggregator)
        {
            await LightBulbHelper.WaitForLightBulbSessionAsync(broker, view).ConfigureAwait(true);

            var bufferType = view.TextBuffer.ContentType.DisplayName;
            if (!broker.IsLightBulbSessionActive(view))
            {
                throw new Exception(string.Format("No Active Smart Tags in View!  Buffer content type={0}", bufferType));
            }

            var activeSession = broker.GetSession(view);
            if (activeSession == null || !activeSession.IsExpanded)
            {
                throw new InvalidOperationException(string.Format("No expanded light bulb session found after View.ShowSmartTag.  Buffer content type={0}", bufferType));
            }

            if (!string.IsNullOrEmpty(menuText))
            {
                if (activeSession.TryGetSuggestedActionSets(out var actionSets) != QuerySuggestedActionCompletionStatus.Completed)
                {
                    actionSets = Array.Empty<SuggestedActionSet>();
                }

                var set = actionSets.SelectMany(s => s.Actions).FirstOrDefault(a => a.DisplayText == menuText);
                if (set == null)
                {
                    throw new InvalidOperationException(
                        string.Format("ISuggestionAction {0} not found.  Buffer content type={1}", menuText, bufferType));
                }

                IWpfTextView preview = null;
                var pane = await set.GetPreviewAsync(CancellationToken.None).ConfigureAwait(true);
                if (pane is System.Windows.Controls.UserControl)
                {
                    var container = ((System.Windows.Controls.UserControl)pane).FindName("PreviewDockPanel") as DockPanel;
                    var host = FindDescendants<UIElement>(container).OfType<IWpfTextViewHost>().LastOrDefault();
                    preview = (host == null) ? null : host.TextView;
                }

                if (preview == null)
                {
                    throw new InvalidOperationException(string.Format("Could not find light bulb preview.  Buffer content type={0}", bufferType));
                }

                activeSession.Collapse();
                var classifier = viewClassifierAggregator.GetClassifier(preview);
                var classifiedSpans = classifier.GetClassificationSpans(new SnapshotSpan(preview.TextBuffer.CurrentSnapshot, 0, preview.TextBuffer.CurrentSnapshot.Length));
                return classifiedSpans.Select(x => new ClassifiedToken(x.Span.GetText().ToString(), x.ClassificationType.Classification)).ToArray();
            }

            activeSession.Collapse();
            return Array.Empty<ClassifiedToken>();
        }

        private static IEnumerable<T> FindDescendants<T>(DependencyObject rootObject) where T : DependencyObject
        {
            if (rootObject != null)
            {
                for (var i = 0; i < VisualTreeHelper.GetChildrenCount(rootObject); i++)
                {
                    var child = VisualTreeHelper.GetChild(rootObject, i);

                    if (child != null && child is T)
                        yield return (T)child;

                    foreach (var descendant in FindDescendants<T>(child))
                        yield return descendant;
                }
            }
        }

        public void MessageBox(string message)
            => ExecuteOnActiveView(view => System.Windows.MessageBox.Show(message));

        public void VerifyDialog(string dialogAutomationId, bool isOpen)
        {
            var dialogAutomationElement = DialogHelpers.FindDialogByAutomationId((IntPtr)GetDTE().MainWindow.HWnd, dialogAutomationId, isOpen);

            if ((isOpen && dialogAutomationElement == null) ||
                (!isOpen && dialogAutomationElement != null))
            {
                throw new InvalidOperationException($"Expected the {dialogAutomationId} dialog to be {(isOpen ? "open" : "closed")}, but it is not.");
            }
        }

        public void DialogSendKeys(string dialogAutomationName, object[] keys)
        {
            var dialogAutomationElement = DialogHelpers.GetOpenDialogById((IntPtr)GetDTE().MainWindow.HWnd, dialogAutomationName);

            dialogAutomationElement.SetFocus();
            _sendKeys.Send(keys);
        }

        public void SendKeysToNavigateTo(object[] keys)
        {
            var dialogAutomationElement = FindNavigateTo();
            if (dialogAutomationElement == null)
            {
                throw new InvalidOperationException($"Expected the NavigateTo dialog to be open, but it is not.");
            }

            dialogAutomationElement.SetFocus();
            _sendKeys.Send(keys);
        }

        public void PressDialogButton(string dialogAutomationName, string buttonAutomationName)
        {
            DialogHelpers.PressButton((IntPtr)GetDTE().MainWindow.HWnd, dialogAutomationName, buttonAutomationName);
        }

        private static IUIAutomationElement FindNavigateTo()
        {
            var vsAutomationElement = Helper.Automation.ElementFromHandle((IntPtr)GetDTE().MainWindow.HWnd);
            return vsAutomationElement.FindDescendantByAutomationId("PART_SearchBox");
        }

        private T Retry<T>(Func<CancellationToken, T> action, Func<T, CancellationToken, bool> stoppingCondition, TimeSpan delay, CancellationToken cancellationToken)
        {
            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                T retval;
                try
                {
                    retval = action(cancellationToken);
                }
                catch (COMException)
                {
                    // Devenv can throw COMExceptions if it's busy when we make DTE calls.

                    Thread.Sleep(delay);
                    continue;
                }

                if (stoppingCondition(retval, cancellationToken))
                {
                    return retval;
                }
                else
                {
                    Thread.Sleep(delay);
                }
            }
            while (true);
        }

        public void AddWinFormButton(string buttonName)
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                var designerHost = (IDesignerHost)GetDTE().ActiveWindow.Object;
                var componentChangeService = (IComponentChangeService)designerHost;
                void ComponentAdded(object sender, ComponentEventArgs e)
                {
                    var control = (System.Windows.Forms.Control)e.Component;
                    if (control.Name == buttonName)
                    {
                        waitHandle.Set();
                    }
                }

                componentChangeService.ComponentAdded += ComponentAdded;

                try
                {
                    var mainForm = (Form)designerHost.RootComponent;
                    InvokeOnUIThread(cancellationToken =>
                    {
                        var newControl = (System.Windows.Forms.Button)designerHost.CreateComponent(typeof(System.Windows.Forms.Button), buttonName);
                        newControl.Parent = mainForm;
                    });
                    waitHandle.WaitOne();
                }
                finally
                {
                    componentChangeService.ComponentAdded -= ComponentAdded;
                }
            }
        }

        public void DeleteWinFormButton(string buttonName)
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                var designerHost = (IDesignerHost)GetDTE().ActiveWindow.Object;
                var componentChangeService = (IComponentChangeService)designerHost;
                void ComponentRemoved(object sender, ComponentEventArgs e)
                {
                    var control = (System.Windows.Forms.Control)e.Component;
                    if (control.Name == buttonName)
                    {
                        waitHandle.Set();
                    }
                }

                componentChangeService.ComponentRemoved += ComponentRemoved;

                try
                {
                    InvokeOnUIThread(cancellationToken =>
                    {
                        designerHost.DestroyComponent(designerHost.Container.Components[buttonName]);
                    });
                    waitHandle.WaitOne();
                }
                finally
                {
                    componentChangeService.ComponentRemoved -= ComponentRemoved;
                }
            }
        }

        public void EditWinFormButtonProperty(string buttonName, string propertyName, string propertyValue, string propertyTypeName = null)
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                var designerHost = (IDesignerHost)GetDTE().ActiveWindow.Object;
                var componentChangeService = (IComponentChangeService)designerHost;

                object GetEnumPropertyValue(string typeName, string value)
                {
                    var type = Type.GetType(typeName);
                    var converter = new EnumConverter(type);
                    return converter.ConvertFromInvariantString(value);
                }

                bool EqualToPropertyValue(object newValue)
                {
                    if (propertyTypeName == null)
                    {
                        return (newValue as string)?.Equals(propertyValue) == true;
                    }
                    else
                    {
                        var enumPropertyValue = GetEnumPropertyValue(propertyTypeName, propertyValue);
                        return newValue?.Equals(enumPropertyValue) == true;
                    }
                }

                void ComponentChanged(object sender, ComponentChangedEventArgs e)
                {
                    if (e.Member.Name == propertyName && EqualToPropertyValue(e.NewValue))
                    {
                        waitHandle.Set();
                    }
                }

                componentChangeService.ComponentChanged += ComponentChanged;

                try
                {
                    InvokeOnUIThread(cancellationToken =>
                    {
                        var button = designerHost.Container.Components[buttonName];
                        var properties = TypeDescriptor.GetProperties(button);
                        var property = properties[propertyName];
                        if (propertyTypeName == null)
                        {
                            property.SetValue(button, propertyValue);
                        }
                        else
                        {
                            var enumPropertyValue = GetEnumPropertyValue(propertyTypeName, propertyValue);
                            property.SetValue(button, enumPropertyValue);
                        }
                    });
                    waitHandle.WaitOne();
                }
                finally
                {
                    componentChangeService.ComponentChanged -= ComponentChanged;
                }
            }
        }

        public void EditWinFormButtonEvent(string buttonName, string eventName, string eventHandlerName)
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                var designerHost = (IDesignerHost)GetDTE().ActiveWindow.Object;
                var componentChangeService = (IComponentChangeService)designerHost;
                void ComponentChanged(object sender, ComponentChangedEventArgs e)
                {
                    if (e.Member.Name == eventName)
                    {
                        waitHandle.Set();
                    }
                }

                componentChangeService.ComponentChanged += ComponentChanged;

                try
                {
                    InvokeOnUIThread(cancellationToken =>
                    {
                        var button = designerHost.Container.Components[buttonName];
                        var eventBindingService = (IEventBindingService)button.Site.GetService(typeof(IEventBindingService));
                        var events = TypeDescriptor.GetEvents(button);
                        var eventProperty = eventBindingService.GetEventProperty(events.Find(eventName, ignoreCase: true));
                        eventProperty.SetValue(button, eventHandlerName);
                    });
                    waitHandle.WaitOne();
                }
                finally
                {
                    componentChangeService.ComponentChanged -= ComponentChanged;
                }
            }
        }

        public string GetWinFormButtonPropertyValue(string buttonName, string propertyName)
        {
            var designerHost = (IDesignerHost)GetDTE().ActiveWindow.Object;
            var button = designerHost.Container.Components[buttonName];
            var properties = TypeDescriptor.GetProperties(button);
            return properties[propertyName].GetValue(button) as string;
        }

        public void FormatDocumentViaCommand()
            => ExecuteCommand(WellKnownCommandNames.Edit_FormatDocument);

        public void Paste()
            => ExecuteCommand(WellKnownCommandNames.Edit_Paste);

        public void Undo()
            => ExecuteCommand(WellKnownCommandNames.Edit_Undo);

        public void Redo()
            => GetDTE().ExecuteCommand(WellKnownCommandNames.Edit_Redo);

        protected override ITextBuffer GetBufferContainingCaret(IWpfTextView view)
        {
            var caretBuffer = view.GetBufferContainingCaret();
            if (caretBuffer is null)
            {
                throw new InvalidOperationException($"Unable to find the buffer containing the caret. Ensure the Editor is activated berfore calling.");
            }

            return caretBuffer;
        }

        public string[] GetOutliningSpans()
        {
            return ExecuteOnActiveView(view =>
            {
                var manager = GetComponentModelService<IOutliningManagerService>().GetOutliningManager(view);
                var span = new SnapshotSpan(view.TextSnapshot, 0, view.TextSnapshot.Length);
                var regions = manager.GetAllRegions(span);
                return regions
                    .OrderBy(s => s.Extent.GetStartPoint(view.TextSnapshot))
                    .Select(r => PrintSpan(r.Extent.GetSpan(view.TextSnapshot)))
                    .ToArray();
            });
        }

        public List<string> GetF1Keywords()
        {
            return InvokeOnUIThread(cancellationToken =>
            {
                var results = new List<string>();
                GetActiveVsTextView().GetBuffer(out var textLines);
                Marshal.ThrowExceptionForHR(textLines.GetLanguageServiceID(out var languageServiceGuid));
                Marshal.ThrowExceptionForHR(Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.QueryService(languageServiceGuid, out var languageService));
                var languageContextProvider = languageService as IVsLanguageContextProvider;

                var monitorUserContext = GetGlobalService<SVsMonitorUserContext, IVsMonitorUserContext>();
                Marshal.ThrowExceptionForHR(monitorUserContext.CreateEmptyContext(out var emptyUserContext));
                Marshal.ThrowExceptionForHR(GetActiveVsTextView().GetCaretPos(out var line, out var column));
                var span = new TextManager.Interop.TextSpan()
                {
                    iStartLine = line,
                    iStartIndex = column,
                    iEndLine = line,
                    iEndIndex = column
                };

                Marshal.ThrowExceptionForHR(languageContextProvider.UpdateLanguageContext(0, textLines, new[] { span }, emptyUserContext));
                Marshal.ThrowExceptionForHR(emptyUserContext.CountAttributes("keyword", VSConstants.S_FALSE, out var count));
                for (var i = 0; i < count; i++)
                {
                    emptyUserContext.GetAttribute(i, "keyword", VSConstants.S_FALSE, out var key, out var value);
                    results.Add(value);
                }

                return results;
            });
        }

        public void GoToDefinition()
            => ExecuteCommand(WellKnownCommandNames.Edit_GoToDefinition);

        public void GoToImplementation()
            => ExecuteCommand(WellKnownCommandNames.Edit_GoToImplementation);

        /// <summary>
        /// Gets the spans where a particular tag appears in the active text view.
        /// </summary>
        /// <returns>
        /// Given a list of tag spans [s1, s2, ...], returns a decomposed array for serialization:
        ///     [s1.Start, s1.Length, s2.Start, s2.Length, ...]
        /// </returns>
        public int[] GetTagSpans(string tagId)
            => InvokeOnUIThread(cancellationToken =>
            {
                var view = GetActiveTextView();
                var tagAggregatorFactory = GetComponentModel().GetService<IViewTagAggregatorFactoryService>();
                var tagAggregator = tagAggregatorFactory.CreateTagAggregator<ITextMarkerTag>(view);
                var matchingTags = tagAggregator.GetTags(new SnapshotSpan(view.TextSnapshot, 0, view.TextSnapshot.Length)).Where(t => t.Tag.Type == tagId);

                return matchingTags.Select(t => t.Span.GetSpans(view.TextBuffer).Single().Span.ToTextSpan()).SelectMany(t => new List<int> { t.Start, t.Length }).ToArray();
            });

        public void SendExplicitFocus()
            => InvokeOnUIThread(cancellationToken =>
            {
                var view = GetActiveVsTextView();
                view.SendExplicitFocus();
            });
    }
}


text:
from __future__ import division
import abc

from serializablecallable import SerializableCallable

from menpofast.image import Image
from menpofast.utils import build_parts_image

from alabortcvpr2015.clm.classifier import MultipleMCF

# Abstract Interface for Unified Objects --------------------------------------

class Unified(object):

    __metaclass__ = abc.ABCMeta

    def __getstate__(self):
        import menpofast.feature as menpofast_feature
        d = self.__dict__.copy()

        features = d.pop('features')
        d['features'] = SerializableCallable(features, [menpofast_feature])

        return d

    def __setstate__(self, state):
        state['features'] = state['features'].callable
        self.__dict__.update(state)

    @property
    def n_levels(self):
        """
        The number of scale levels of the AAM.

        :type: `int`
        """
        return len(self.scales)

    def parts_filters(self):

        if isinstance(self.classifiers[0], MultipleMCF):
            return [[Image(f) for f in clf.invert_filters()]
                    for clf in self.classifiers]
        else:
            raise ValueError('Only suported MultipleMCF are supported')

    def parts_response(self, image, group=None, label=None):

        centers = image.landmarks[group][label].landmarks.lms

        parts_image = build_parts_image(
            image, centers, parts_shape=self.parts_shape,
            normalize_parts=self.normalize_parts)

        return [clf(parts_image)for clf in self.classifiers]

# Concrete Implementations of Unified Objects ---------------------------------

class GlobalUnified(Unified):

    def __init__(self, shape_models, appearance_models, classifiers,
                 reference_shape, transform, parts_shape, features,
                 normalize_parts, covariance, sigma, scales, scale_shapes,
                 scale_features):
        self.shape_models = shape_models
        self.appearance_models = appearance_models
        self.classifiers = classifiers
        self.reference_shape = reference_shape
        self.transform = transform
        self.parts_shape = parts_shape
        self.features = features
        self.normalize_parts = normalize_parts
        self.covariance = covariance
        self.sigma = sigma
        self.scales = scales
        self.scale_shapes = scale_shapes
        self.scale_features = scale_features

class PartsUnified(Unified):

    def __init__(self, shape_models, appearance_models, classifiers,
                 reference_shape, parts_shape, features, normalize_parts,
                 covariance, sigma, scales, scale_shapes, scale_features):
        self.shape_models = shape_models
        self.appearance_models = appearance_models
        self.classifiers = classifiers
        self.reference_shape = reference_shape
        self.parts_shape = parts_shape
        self.features = features
        self.normalize_parts = normalize_parts
        self.covariance = covariance
        self.sigma = sigma
        self.scales = scales
        self.scale_shapes = scale_shapes
        self.scale_features = scale_features

redpajama_set_name: RedPajamaGithub


text:
package no.nordicsemi.android.nrfblejoiner.ble;

import android.app.Activity;
import android.app.Dialog;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;

import no.nordicsemi.android.nrfblejoiner.R;

public class ConfigureBleFragment extends DialogFragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private static final String TAG = "BLE";
    private TextView tvOpcode, tvNextMode;
    private CheckBox chkAdvanced;
    private EditText etActionDelay, etIdentificationDuration, etDeviceLabel;
    private TextInputLayout tiActionDelay, tiIdentificationDuration, tiDeviceLabel;
    private Spinner spOpCode, spNextMode;
    private BleConfigFragmentInteractionListener mListener;
    private BleNodeSettingsAdapter opCodesAdapter, nextModeAdapter;
    private String opCode, nextMode;
    private Button cancel, configure, identify;

    private String mDeviceName;
    private String mDeviceAddress;
    private boolean mConnected = false;
    private boolean advancedIdentifyMode = false;

    public ConfigureBleFragment() {
        // Required empty public constructor
    }

    public static ConfigureBleFragment newInstance(String mDeviceName, String mDeviceAddress) {
        ConfigureBleFragment fragment = new ConfigureBleFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, mDeviceName);
        args.putString(ARG_PARAM2, mDeviceAddress);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mDeviceName = getArguments().getString(ARG_PARAM1);
            mDeviceAddress = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        final View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_configure_ble, null);

        final TextView tvTitle = (TextView) dialogView.findViewById(R.id.tv_ble_frag_title);
        tvTitle.setText("Configure " + mDeviceName);
        tvOpcode = (TextView) dialogView.findViewById(R.id.tv_opcode_message);
        tvNextMode = (TextView) dialogView.findViewById(R.id.tv_next_mode_message);
        spOpCode = (Spinner) dialogView.findViewById(R.id.sp_op_code);
        spNextMode = (Spinner) dialogView.findViewById(R.id.sp_next_mode);
        etActionDelay = (EditText) dialogView.findViewById(R.id.et_action_delay);
        etIdentificationDuration = (EditText) dialogView.findViewById(R.id.et_identity_mode_duration);
        etDeviceLabel = (EditText) dialogView.findViewById(R.id.et_ble_label);
        tiActionDelay = (TextInputLayout) dialogView.findViewById(R.id.ti_action_delay);
        tiIdentificationDuration = (TextInputLayout) dialogView.findViewById(R.id.ti_identity_mode_duration);
        tiDeviceLabel = (TextInputLayout) dialogView.findViewById(R.id.ti_device_label);
        chkAdvanced = (CheckBox) dialogView.findViewById(R.id.chk_edit);
        opCodesAdapter = new BleNodeSettingsAdapter(getActivity(), R.layout.custom_spinner, populateBleOpCodes());
        spOpCode.setAdapter(opCodesAdapter);

        nextModeAdapter = new BleNodeSettingsAdapter(getActivity(), R.layout.custom_spinner, populateBleNextMode());
        spNextMode.setAdapter(nextModeAdapter);

        alertDialogBuilder.setView(dialogView).setNeutralButton(getString(R.string.identify), null).setNegativeButton(getString(R.string.cancel), null).setPositiveButton(getString(R.string.configure), null);
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
        alertDialog.setCanceledOnTouchOutside(false);
        setCancelable(false);

        configure = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        cancel = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        identify = alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL);

        configure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (validateInput()) {
                    if (chkAdvanced.isChecked()) {
                        mListener.configureBleNode(opCode, etActionDelay.getText().toString(), etIdentificationDuration.getText().toString(), nextMode, etDeviceLabel.getText().toString());
                    } else {
                        Resources resources = getActivity().getResources();
                        mListener.configureBleNode(resources.getString(R.string.ble_connection_mode_value), resources.getString(R.string.action_delay_default), resources.getString(R.string.connection_duration_default), resources.getString(R.string.configuration_mode_value), "");
                    }
                }
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.disconnectFromDevice();
            }
        });

        identify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (advancedIdentifyMode) {
                    mListener.advancedIdentifyMode(opCode, etActionDelay.getText().toString(), etIdentificationDuration.getText().toString(), nextMode, etDeviceLabel.getText().toString());
                } else {
                    mListener.identifyMode();
                }
            }
        });

        etActionDelay.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tiActionDelay.setError(null);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etIdentificationDuration.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tiIdentificationDuration.setError(null);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etDeviceLabel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tiDeviceLabel.setError(null);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        spOpCode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                opCode = parent.getSelectedItem().toString();
                advancedIdentifyMode = false;
                if (opCode.equalsIgnoreCase(getActivity().getString(R.string.ble_connection_mode)))
                    opCode = getActivity().getString(R.string.ble_connection_mode_value);
                else if (opCode.equalsIgnoreCase(getActivity().getString(R.string.ble_configuration_mode)))
                    opCode = getActivity().getString(R.string.ble_configuration_mode_value);
                else if (opCode.equalsIgnoreCase(getActivity().getString(R.string.ble_identification_mode)))
                    opCode = getActivity().getString(R.string.ble_identification_mode_value);
                updateUiOnIdentificationMode();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spNextMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                advancedIdentifyMode = false;
                nextMode = parent.getSelectedItem().toString();

                if (nextMode.equalsIgnoreCase(getActivity().getString(R.string.no_state_change)))
                    nextMode = getActivity().getString(R.string.no_state_change_value);
                else if (nextMode.equalsIgnoreCase(getActivity().getString(R.string.power_off)))
                    nextMode = getActivity().getString(R.string.power_off_value);
                else
                    nextMode = getActivity().getString(R.string.configuration_mode_value);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        chkAdvanced.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                showAdvancedSettings(isChecked);
            }
        });

        return alertDialog;
    }

    private boolean validateInput() {

        if (spOpCode.getVisibility() == View.VISIBLE && opCode == null) {
            Toast.makeText(getActivity(), getString(R.string.op_code_error), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (spNextMode.getVisibility() == View.VISIBLE && nextMode == null) {
            Toast.makeText(getActivity(), getString(R.string.backup_mode_error), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (etActionDelay.getVisibility() == View.VISIBLE && etActionDelay.getText().toString().equalsIgnoreCase("")) {
            tiActionDelay.setError(getString(R.string.action_delay_error));
            return false;
        }
        if (etIdentificationDuration.getVisibility() == View.VISIBLE && etIdentificationDuration.getText().toString().equalsIgnoreCase("")) {
            tiIdentificationDuration.setError(getString(R.string.identification_duration_error));
            return false;
        }

        if (etDeviceLabel.getVisibility() == View.VISIBLE && etDeviceLabel.getText().toString().equalsIgnoreCase("")) {
            tiDeviceLabel.setError(getString(R.string.device_label_error));
            return false;
        }

        return true;
    }

    private ArrayList<String> populateBleOpCodes() {
        ArrayList<String> configurationList = new ArrayList<>();
        String[] bleSettings = getActivity().getResources().getStringArray(R.array.op_codes);

        Collections.addAll(configurationList, bleSettings);

        return configurationList;
    }

    private ArrayList<String> populateBleNextMode() {
        final ArrayList<String> configurationList = new ArrayList<>();
        final String[] bleSettings = getActivity().getResources().getStringArray(R.array.next_mode);

        Collections.addAll(configurationList, bleSettings);

        return configurationList;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (BleConfigFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement BleConfigFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v("BLE", "Dismiss called");
    }

    private void updateUiOnIdentificationMode() {
        if (opCode.equalsIgnoreCase(getActivity().getString(R.string.ble_identification_mode_value))) {
            etDeviceLabel.setVisibility(View.VISIBLE);
            configure.setEnabled(false);
            advancedIdentifyMode = true;
        } else {
            configure.setEnabled(true);
            etDeviceLabel.setVisibility(View.GONE);
        }
    }

    private void showAdvancedSettings(boolean flag) {
        if (flag) {
            tvOpcode.setVisibility(View.VISIBLE);
            tvNextMode.setVisibility(View.VISIBLE);
            etActionDelay.setVisibility(View.VISIBLE);
            etIdentificationDuration.setVisibility(View.VISIBLE);
            spNextMode.setVisibility(View.VISIBLE);
            spOpCode.setVisibility(View.VISIBLE);
            etDeviceLabel.setVisibility(View.GONE);
            spOpCode.setSelection(0, false);
            spNextMode.setSelection(2, false);
        } else {
            tvOpcode.setVisibility(View.GONE);
            tvNextMode.setVisibility(View.GONE);
            etActionDelay.setVisibility(View.GONE);
            etIdentificationDuration.setVisibility(View.GONE);
            spNextMode.setVisibility(View.GONE);
            spOpCode.setVisibility(View.GONE);
            etDeviceLabel.setVisibility(View.GONE);
            configure.setEnabled(true);
            advancedIdentifyMode = false;
        }
    }

    public interface BleConfigFragmentInteractionListener {

        void configureBleNode(String characteristic, String actionDelay, String identityModeDuration, String nextMode, String label);

        void identifyMode();

        void advancedIdentifyMode(String characteristic, String actionDelay, String identityModeDuration, String nextMode, String label);

        void disconnectFromDevice();
    }
}


text:
/**
 * @fileoverview  Provide the DiggerBlue class.
 * @author scott@scottlininger.com (Scott Lininger)
 */

/**
 * Constructor for the DiggerBlue class, baddie who walks around and hurls rocks.
 * @constructor
 * @extends {ace.BaseClass}
 */
ace.DiggerBlue = function(game, room) {
  ace.base(this, game, room);
  this.name = 'DiggerBlue';
  this.spriteVariant = 'blue';
  this.hitPoints = 4;
};
ace.inherits(ace.DiggerBlue, ace.Digger);


text:
# onesLike

> Create an array filled with ones and having the same length and data type as a provided array.

## Usage

```javascript
var onesLike = require( '@stdlib/array/ones-like' );
```

#### onesLike( x\[, dtype] )

Creates an array filled with ones and having the same length and data type as a provided array `x`.

```javascript
var x = [ 1, 2, 3, 4, 5 ];

var arr = onesLike( x );
// returns [ 1, 1, 1, 1, 1 ]
```

The function supports the following data types:

-   `float64`: double-precision floating-point numbers (IEEE 754)
-   `float32`: single-precision floating-point numbers (IEEE 754)
-   `complex128`: double-precision complex floating-point numbers
-   `complex64`: single-precision complex floating-point numbers
-   `int32`: 32-bit two's complement signed integers
-   `uint32`: 32-bit unsigned integers
-   `int16`: 16-bit two's complement signed integers
-   `uint16`: 16-bit unsigned integers
-   `int8`: 8-bit two's complement signed integers
-   `uint8`: 8-bit unsigned integers
-   `uint8c`: 8-bit unsigned integers clamped to `0-255`
-   `generic`: generic JavaScript values

By default, the output array data type is inferred from the provided array `x`. To return an array having a different data type, provide a `dtype` argument.

```javascript
var x = [ 0, 0 ];

var arr = onesLike( x, 'int32' );
// returns <Int32Array>[ 1, 1 ]
```

## Notes

-   If the output array has a complex number data type, each element of the returned array has a real component equal to `1` and an imaginary component equal to `0`.

## Examples

```javascript
var dtypes = require( '@stdlib/array/dtypes' );
var zeros = require( '@stdlib/array/zeros' );
var onesLike = require( '@stdlib/array/ones-like' );

// Create a zero-filled array:
var x = zeros( 4, 'complex128' );

// Get a list of array data types:
var dt = dtypes();

// Generate filled arrays...
var y;
var i;
for ( i = 0; i < dt.length; i++ ) {
    y = onesLike( x, dt[ i ] );
    console.log( y );
}
```


text:
import slick from 'slick-carousel';
import magnificPopup from 'magnific-popup';
import wowJs from 'wow.js';
import {filterByType, carousel, slickCarouselSettins} from '../../components/clients/clients';
import {reviewsMagnificPopup, reviewsCarousel} from '../../components/reviews/reviews';
import {ourTeamCarousel} from '../../components/content/about-us/main';
import {map} from '../../components/map/map';
import {stickyNav, mobileNav} from '../../components/header/header';
import {showForm} from '../../components/request-form/request-form';
import {modalVacancies} from '../../components/vacancies/vacancies';
import {modalOnlineServices} from '../../components/online-services/online-services';
import {sweetAlertJs} from '../../components/contact-form/ajaxFormSend';
import * as iziModal from '../../components/iziModal/iziModal';

$(() => {
    sweetAlertJs();
    modalOnlineServices();
    modalVacancies();
    stickyNav();
    mobileNav();
    slickCarouselSettins();
    reviewsMagnificPopup();
    reviewsCarousel();
    ourTeamCarousel();
    showForm();
    $('.office-life__list').slick({
        dots: false,
        centerMode: true,
        centerPadding: '200px',
        slidesToShow: 1,
        slidesToScroll: 1,
        responsive: [
          {
            breakpoint: 420,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1,
                dots: false,
                arrows: true,
                centerMode: false
            }
          }
        ]
    });
    filterByType();
    map();
    // validation();
    let wow = new wowJs(
        {
            boxClass: 'wow',      // animated element css class (default is wow)
            animateClass: 'animated', // animation css class (default is animated)
            offset: 300,          // distance to the element when triggering the animation (default is 0)
            mobile: true,       // trigger animations on mobile devices (default is true)
            live: true,       // act on asynchronously loaded content (default is true)
            scrollContainer: null // optional scroll container selector, otherwise use window
        }
);
    wow.init();
    $('#modal').iziModal({
      width: '1100px'
    });
});


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef AudioParam_h_
#define AudioParam_h_

#include "AudioParamTimeline.h"
#include "nsWrapperCache.h"
#include "nsCycleCollectionParticipant.h"
#include "nsAutoPtr.h"
#include "AudioNode.h"
#include "mozilla/dom/TypedArray.h"
#include "WebAudioUtils.h"
#include "js/TypeDecls.h"

namespace mozilla {

namespace dom {

class AudioParam final : public nsWrapperCache,
                         public AudioParamTimeline
{
  virtual ~AudioParam();

public:
  typedef void (*CallbackType)(AudioNode*);

  AudioParam(AudioNode* aNode,
             CallbackType aCallback,
             float aDefaultValue,
             const char* aName);

  NS_IMETHOD_(MozExternalRefCountType) AddRef(void);
  NS_IMETHOD_(MozExternalRefCountType) Release(void);
  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(AudioParam)

  AudioContext* GetParentObject() const
  {
    return mNode->Context();
  }

  double DOMTimeToStreamTime(double aTime) const
  {
    return mNode->Context()->DOMTimeToStreamTime(aTime);
  }

  virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;

  // We override SetValueCurveAtTime to convert the Float32Array to the wrapper
  // object.
  void SetValueCurveAtTime(const Float32Array& aValues, double aStartTime, double aDuration, ErrorResult& aRv)
  {
    if (!WebAudioUtils::IsTimeValid(aStartTime)) {
      aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
      return;
    }
    aValues.ComputeLengthAndData();
    AudioParamTimeline::SetValueCurveAtTime(aValues.Data(), aValues.Length(),
                                            DOMTimeToStreamTime(aStartTime), aDuration, aRv);
    mCallback(mNode);
  }

  // We override the rest of the mutating AudioParamTimeline methods in order to make
  // sure that the callback is called every time that this object gets mutated.
  void SetValue(float aValue)
  {
    // Optimize away setting the same value on an AudioParam
    if (HasSimpleValue() &&
        WebAudioUtils::FuzzyEqual(GetValue(), aValue)) {
      return;
    }
    AudioParamTimeline::SetValue(aValue);
    mCallback(mNode);
  }
  void SetValueAtTime(float aValue, double aStartTime, ErrorResult& aRv)
  {
    if (!WebAudioUtils::IsTimeValid(aStartTime)) {
      aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
      return;
    }
    AudioParamTimeline::SetValueAtTime(aValue, DOMTimeToStreamTime(aStartTime), aRv);
    mCallback(mNode);
  }
  void LinearRampToValueAtTime(float aValue, double aEndTime, ErrorResult& aRv)
  {
    if (!WebAudioUtils::IsTimeValid(aEndTime)) {
      aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
      return;
    }
    AudioParamTimeline::LinearRampToValueAtTime(aValue, DOMTimeToStreamTime(aEndTime), aRv);
    mCallback(mNode);
  }
  void ExponentialRampToValueAtTime(float aValue, double aEndTime, ErrorResult& aRv)
  {
    if (!WebAudioUtils::IsTimeValid(aEndTime)) {
      aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
      return;
    }
    AudioParamTimeline::ExponentialRampToValueAtTime(aValue, DOMTimeToStreamTime(aEndTime), aRv);
    mCallback(mNode);
  }
  void SetTargetAtTime(float aTarget, double aStartTime, double aTimeConstant, ErrorResult& aRv)
  {
    if (!WebAudioUtils::IsTimeValid(aStartTime) ||
        !WebAudioUtils::IsTimeValid(aTimeConstant)) {
      aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
      return;
    }
    AudioParamTimeline::SetTargetAtTime(aTarget, DOMTimeToStreamTime(aStartTime), aTimeConstant, aRv);
    mCallback(mNode);
  }
  void CancelScheduledValues(double aStartTime, ErrorResult& aRv)
  {
    if (!WebAudioUtils::IsTimeValid(aStartTime)) {
      aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
      return;
    }
    AudioParamTimeline::CancelScheduledValues(DOMTimeToStreamTime(aStartTime));
    mCallback(mNode);
  }

  uint32_t ParentNodeId()
  {
    return mNode->Id();
  }

  void GetName(nsAString& aName)
  {
    aName.AssignASCII(mName);
  }

  float DefaultValue() const
  {
    return mDefaultValue;
  }

  AudioNode* Node() const
  {
    return mNode;
  }

  const nsTArray<AudioNode::InputNode>& InputNodes() const
  {
    return mInputNodes;
  }

  void RemoveInputNode(uint32_t aIndex)
  {
    mInputNodes.RemoveElementAt(aIndex);
  }

  AudioNode::InputNode* AppendInputNode()
  {
    return mInputNodes.AppendElement();
  }

  void DisconnectFromGraphAndDestroyStream();

  // May create the stream if it doesn't exist
  MediaStream* Stream();

  virtual size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const override
  {
    size_t amount = AudioParamTimeline::SizeOfExcludingThis(aMallocSizeOf);
    // Not owned:
    // - mNode

    // Just count the array, actual nodes are counted in mNode.
    amount += mInputNodes.SizeOfExcludingThis(aMallocSizeOf);

    if (mNodeStreamPort) {
      amount += mNodeStreamPort->SizeOfIncludingThis(aMallocSizeOf);
    }

    return amount;
  }

  virtual size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const override
  {
    return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
  }

protected:
  nsCycleCollectingAutoRefCnt mRefCnt;
  NS_DECL_OWNINGTHREAD

private:
  nsRefPtr<AudioNode> mNode;
  // For every InputNode, there is a corresponding entry in mOutputParams of the
  // InputNode's mInputNode.
  nsTArray<AudioNode::InputNode> mInputNodes;
  CallbackType mCallback;
  const float mDefaultValue;
  const char* mName;
  // The input port used to connect the AudioParam's stream to its node's stream
  nsRefPtr<MediaInputPort> mNodeStreamPort;
};

}
}

#endif


text:
<?php

namespace BeholderWebClient\Eyes\Nfs;

use Exception;
use BeholderWebClient\Eyes\Nfs\NfsStatus as Status;

Class Eye extends AbstractNfs {

  public function checkRequirement(){

    $result = exec('type -P stat');

    if(!$result)
      throw new Exception(Status::REQUERIMENT_FAIL, Status::INTERNAL_SERVER_ERROR_NUMBER);

  }

  protected function checkIfPathIsMounted() {

   $cmd = 'stat -fc%t:%T ';

   $pathFather = realpath($this->path . '/../');

   $p = shell_exec($cmd . $this->path);
   $f = shell_exec($cmd . $pathFather);

   if( $p === $f )
     throw new Exception(Status::NOT_MOUNTED, Status::NOT_MOUNTED_NUMBER);

  }

  protected function tryWriteFile(){

    try {

      $this->date = date('Y-m-d H:i:s');

      $link = fopen($this->fullFileName,'a+');
      fwrite($link, $this->date . PHP_EOL);
      fclose($link);

    } catch(Exception $ex){

      throw new Exception(Status::COULD_NOT_WRITE_FILE . ' - ' . $ex->getMessage(), Status::COULD_NOT_WRITE_FILE_NUMBER, $ex);

    }

  }

  protected function tryReadFile(){

    try {

      $link = fopen($this->fullFileName,'r');
      fclose($link);

    } catch(Exception $ex){

      throw new Exception(Status::COULD_NOT_READ_FILE . ' - ' . $ex->getMessage(), Status::COULD_NOT_READ_FILE_NUMBER, $ex);

    }

  }

  protected function tryDeleteFile(){

    try {

      unlink($this->fullFileName);

    } catch(Exception $ex){

      throw new Exception(Status::COULD_NOT_DELETE_FILE . ' - ' . $ex->getMessage(), Status::COULD_NOT_DELETE_FILE_NUMBER, $ex);

    }

  }

}


text:
<?php

class SimpleMDEEditor extends TextareaField
{
    /**
     * Returns the field holder used by templates
     * @return {string} HTML to be used
     */
    public function FieldHolder($properties=array())
    {
        Requirements::css('vendor/etdsolutions/simplemde-markdown-editor/simplemde.min.css');
        Requirements::javascript('vendor/etdsolutions/simplemde-markdown-editor/simplemde.min.js');
        Requirements::css(MARKDOWN_MODULE_BASE.'/css/editor.css');
        Requirements::javascript(MARKDOWN_MODULE_BASE.'/javascript/editor.js');
        return parent::FieldHolder($properties);
    }
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved.                        */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package edu.wpi.first.wpilibj;

/**
 * Manages a PWM object.
 */
public class SafePWM extends PWM implements MotorSafety {

  private final MotorSafetyHelper m_safetyHelper;

  /**
   * Constructor for a SafePWM object taking a channel number.
   *
   * @param channel The channel number to be used for the underlying PWM object. 0-9 are on-board,
   *                10-19 are on the MXP port.
   */
  public SafePWM(final int channel) {
    super(channel);

    m_safetyHelper = new MotorSafetyHelper(this);
    m_safetyHelper.setExpiration(0.0);
    m_safetyHelper.setSafetyEnabled(false);
  }

  /**
   * Set the expiration time for the PWM object.
   *
   * @param timeout The timeout (in seconds) for this motor object
   */
  public void setExpiration(double timeout) {
    m_safetyHelper.setExpiration(timeout);
  }

  /**
   * Return the expiration time for the PWM object.
   *
   * @return The expiration time value.
   */
  public double getExpiration() {
    return m_safetyHelper.getExpiration();
  }

  /**
   * Check if the PWM object is currently alive or stopped due to a timeout.
   *
   * @return a bool value that is true if the motor has NOT timed out and should still be running.
   */
  public boolean isAlive() {
    return m_safetyHelper.isAlive();
  }

  /**
   * Stop the motor associated with this PWM object. This is called by the MotorSafetyHelper object
   * when it has a timeout for this PWM and needs to stop it from running.
   */
  public void stopMotor() {
    disable();
  }

  /**
   * Check if motor safety is enabled for this object.
   *
   * @return True if motor safety is enforced for this object
   */
  public boolean isSafetyEnabled() {
    return m_safetyHelper.isSafetyEnabled();
  }

  /**
   * Feed the MotorSafety timer. This method is called by the subclass motor whenever it updates its
   * speed, thereby reseting the timeout value.
   */
  @SuppressWarnings("MethodName")
  public void Feed() {
    m_safetyHelper.feed();
  }

  public void setSafetyEnabled(boolean enabled) {
    m_safetyHelper.setSafetyEnabled(enabled);
  }

  public String getDescription() {
    return "PWM " + getChannel();
  }

  public void disable() {
    setDisabled();
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/Florian.S/AndroidStudioProjects/NavigationDrawer/Application/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.2/res/values-ur-rPK/values.xml -->
    <eat-comment/>
    <string msgid="4600421777120114993" name="abc_action_bar_home_description">"ہوم پر نیویگیٹ کریں"</string>
    <string msgid="1397052879051804371" name="abc_action_bar_home_description_format">"%1$s, %2$s"</string>
    <string msgid="6623331958280229229" name="abc_action_bar_home_subtitle_description_format">"%1$s, %2$s, %3$s"</string>
    <string msgid="1594238315039666878" name="abc_action_bar_up_description">"اوپر نیویگیٹ کریں"</string>
    <string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"مزید اختیارات"</string>
    <string msgid="4076576682505996667" name="abc_action_mode_done">"ہو گیا"</string>
    <string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"سبھی دیکھیں"</string>
    <string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"ایک ایپ منتخب کریں"</string>
    <string msgid="3691816814315814921" name="abc_searchview_description_clear">"استفسار صاف کریں"</string>
    <string msgid="2550479030709304392" name="abc_searchview_description_query">"استفسار تلاش کریں"</string>
    <string msgid="8264924765203268293" name="abc_searchview_description_search">"تلاش کریں"</string>
    <string msgid="8928215447528550784" name="abc_searchview_description_submit">"استفسار جمع کرائیں"</string>
    <string msgid="893419373245838918" name="abc_searchview_description_voice">"صوتی تلاش"</string>
    <string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"اشتراک کریں مع"</string>
    <string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"%s کے ساتھ اشتراک کریں"</string>
</resources>


text:
A very simple Java take on Redux.

Consider this library experimental.  Originally ripped from https://github.com/brianegan/bansa.

Thread safe use of this library requires immutable** state objects and also requires pure*** reducers.  The order of action
dispatch can only be guaranteed if called from the same thread.  Do not dispatch actions that update the
same part of the state structure from different threads as the order in which the actions are applied cannot be guaranteed.
If you do call dispatch from different threads ensure that these actions (and any listener actions they may trigger) do
not update the same part of the state.  You're almost certainly better off just having a one thread call dispatch.

Redux basics: http://redux.js.org/docs/basics/

The Java Immutables library https://immutables.github.io/ is recommended.

Utils.combineReducers is used to combine multiple reducers into a single reducer that can be passed to constructor.

We did consider using https://github.com/MutabilityDetector/MutabilityDetector to runtime check the immutability
of the state object, but decided against the overhead.  We do however recommend annotating immutable classes and
using the associated findbugs plugin.  See https://stackoverflow.com/questions/37087809/how-to-find-out-if-a-class-is-immutable

** by using immutable objects we avoid the need to deep copy (clone) state objects

*** a pure function will always give the same result given the same arguments and should cause no observable side effects (see https://en.wikipedia.org/wiki/Pure_function)


text:
class AzWarningPeriod < AzUsingPeriod
  belongs_to :az_company
end


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef _CONF_ETH_H_
#define _CONF_ETH_H_

/*! Number of receive buffers. Max ethernet frame size is 1526. A Rx buffer is
128 Bytes long. So 12 Rx buffers are necessary to store one max sized frame.
Multiply that by 2 for performance. */
#define ETHERNET_CONF_NB_RX_BUFFERS        24

/*! USE_RMII_INTERFACE must be defined as 1 to use an RMII interface, or 0
to use an MII interface. */
#define ETHERNET_CONF_USE_RMII_INTERFACE   1

/*! Number of Transmit buffers */
#define ETHERNET_CONF_NB_TX_BUFFERS        10

/*! Size of each Transmit buffer. */
#define ETHERNET_CONF_TX_BUFFER_SIZE       512

/*! Use Auto negotiation to get speed and duplex */
#define ETHERNET_CONF_AN_ENABLE                      1

/*! Use auto cross capability. Used by default. */
#define ETHERNET_CONF_AUTO_CROSS_ENABLE              1
/*! Use direct cable. Ignored when ETHERNET_CONF_AN_ENABLE and
    ETHERNET_CONF_AUTO_CROSS_ENABLE are enabled. */
#define ETHERNET_CONF_CROSSED_LINK                   0

/* ethernet default parameters */
/*! MAC address definition.  The MAC address must be unique on the network. */
#define ETHERNET_CONF_ETHADDR0                        0x00
#define ETHERNET_CONF_ETHADDR1                        0x04
#define ETHERNET_CONF_ETHADDR2                        0x25
#define ETHERNET_CONF_ETHADDR3                        0x1C
#define ETHERNET_CONF_ETHADDR4                        0xA0
#define ETHERNET_CONF_ETHADDR5                        0x02

/*! The IP address being used. */
#define ETHERNET_CONF_IPADDR0                         192
#define ETHERNET_CONF_IPADDR1                         168
#define ETHERNET_CONF_IPADDR2                         0
#define ETHERNET_CONF_IPADDR3                         2

/*! The gateway address being used. */
#define ETHERNET_CONF_GATEWAY_ADDR0                   192
#define ETHERNET_CONF_GATEWAY_ADDR1                   168
#define ETHERNET_CONF_GATEWAY_ADDR2                   0
#define ETHERNET_CONF_GATEWAY_ADDR3                   1

/*! The network mask being used. */
#define ETHERNET_CONF_NET_MASK0                       255
#define ETHERNET_CONF_NET_MASK1                       255
#define ETHERNET_CONF_NET_MASK2                       255
#define ETHERNET_CONF_NET_MASK3                       0

#endif


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Narrowspark\TestingHelper\Middleware;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RuntimeException;
use Throwable;
use UnexpectedValueException;

final class CallableMiddleware implements MiddlewareInterface
{
    /** @var callable */
    private $handler;

    /**
     * A response factory class name.
     *
     * @var null|\Psr\Http\Message\ResponseFactoryInterface
     */
    private $responseFactory;

    /**
     * Create a new CallableMiddleware instance.
     *
     * @param callable                                   $handler
     * @param \Psr\Http\Message\ResponseFactoryInterface $responseFactory
     *
     * @throws \RuntimeException
     */
    public function __construct(callable $handler, ResponseFactoryInterface $responseFactory = null)
    {
        $this->handler = $handler;
        $this->responseFactory = $responseFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        return $this->execute($this->handler, [$request, $handler]);
    }

    /**
     * Execute the callable.
     *
     * @param callable|\Closure $callable
     * @param mixed[]           $arguments
     *
     * @throws \Throwable
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    private function execute(callable $callable, array $arguments = []): ResponseInterface
    {
        \ob_start();
        $level = \ob_get_level();

        try {
            $return = \call_user_func_array($callable, $arguments);

            if ($return instanceof ResponseInterface) {
                $response = $return;
                $return = '';
            } elseif (
                $return === null
                || \is_scalar($return)
                || (\is_object($return) && \method_exists($return, '__toString'))
            ) {
                $instance = $this->responseFactory;

                if ($instance === null) {
                    throw new RuntimeException('No ResponseFactory class found.');
                }

                $response = $instance->createResponse();
            } else {
                throw new UnexpectedValueException('The value returned must be "scalar" or an object with "__toString" method.');
            }

            while (\ob_get_level() >= $level) {
                $return = \ob_get_clean() . $return;
            }

            $body = $response->getBody();

            if ($return !== '' && $body->isWritable()) {
                $body->write((string) $return);
            }

            return $response;
        } catch (Throwable $exception) {
            while (\ob_get_level() >= $level) {
                \ob_end_clean();
            }

            throw $exception;
        }
    }
}


text:
export const FOO = 'FOO';
export const BAR = 'BAR';
export const BAZ = 'BAZ';


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

//   This file has been modified.
//   Original copyright notice :

using System;

namespace Summer.Batch.Core.Launch.Support
{
    /// <summary>
    /// Implementation of the <see cref="ISystemExiter"/> interface that calls the standards
    /// Environment.Exit method. It should be noted that there will be no unit tests for
    /// this class, since there is only one line of actual code, that would only be
    /// testable by mocking System or Runtime.
    /// </summary>
    public class VmSystemExiter : ISystemExiter
    {
        /// <summary>
        /// Terminates the current running Virtual Machine.
        /// Delegates to Environment.Exit .
        /// </summary>
        /// <param name="status">exit status</param>
        public void Exit(int status)
        {
            Environment.Exit(status);
        }
    }
}