text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
    [Export(typeof(MiscellaneousFilesWorkspace))]
    internal sealed partial class MiscellaneousFilesWorkspace : Workspace, IVsRunningDocTableEvents2, IVisualStudioHostProjectContainer
    {
        private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
        private readonly IMetadataAsSourceFileService _fileTrackingMetadataAsSourceService;
        private readonly IVsRunningDocumentTable4 _runningDocumentTable;
        private readonly IVsTextManager _textManager;

        private readonly DocumentProvider _documentProvider;

        private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new Dictionary<Guid, LanguageInformation>();

        /// <summary>
        /// <see cref="WorkspaceRegistration"/> instances for all open buffers being tracked by by this object
        /// for possible inclusion into this workspace.
        /// </summary>
        private IBidirectionalMap<uint, WorkspaceRegistration> _docCookieToWorkspaceRegistration = BidirectionalMap<uint, WorkspaceRegistration>.Empty;

        private readonly Dictionary<ProjectId, HostProject> _hostProjects = new Dictionary<ProjectId, HostProject>();
        private readonly Dictionary<uint, HostProject> _docCookiesToHostProject = new Dictionary<uint, HostProject>();

        private readonly ImmutableArray<MetadataReference> _metadataReferences;
        private uint _runningDocumentTableEventsCookie;

        private readonly ForegroundThreadAffinitizedObject _foregroundThreadAffinitization;

        [ImportingConstructor]
        public MiscellaneousFilesWorkspace(
            IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
            IMetadataAsSourceFileService fileTrackingMetadataAsSourceService,
            SaveEventsService saveEventsService,
            VisualStudioWorkspace visualStudioWorkspace,
            SVsServiceProvider serviceProvider) :
            base(visualStudioWorkspace.Services.HostServices, WorkspaceKind.MiscellaneousFiles)
        {
            _foregroundThreadAffinitization = new ForegroundThreadAffinitizedObject(assertIsForeground: true);

            _editorAdaptersFactoryService = editorAdaptersFactoryService;
            _fileTrackingMetadataAsSourceService = fileTrackingMetadataAsSourceService;
            _runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
            _textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));

            ((IVsRunningDocumentTable)_runningDocumentTable).AdviseRunningDocTableEvents(this, out _runningDocumentTableEventsCookie);

            _metadataReferences = ImmutableArray.CreateRange(CreateMetadataReferences());
            _documentProvider = new DocumentProvider(this, serviceProvider, documentTrackingService: null);
            saveEventsService.StartSendingSaveEvents();
        }

        public void RegisterLanguage(Guid languageGuid, string languageName, string scriptExtension)
        {
            _languageInformationByLanguageGuid.Add(languageGuid, new LanguageInformation(languageName, scriptExtension));
        }

        internal void StartSolutionCrawler()
        {
            DiagnosticProvider.Enable(this, DiagnosticProvider.Options.Syntax);
        }

        internal void StopSolutionCrawler()
        {
            DiagnosticProvider.Disable(this);
        }

        private LanguageInformation TryGetLanguageInformation(string filename)
        {
            LanguageInformation languageInformation = null;

            if (ErrorHandler.Succeeded(_textManager.MapFilenameToLanguageSID(filename, out var fileLanguageGuid)))
            {
                _languageInformationByLanguageGuid.TryGetValue(fileLanguageGuid, out languageInformation);
            }

            return languageInformation;
        }

        private IEnumerable<MetadataReference> CreateMetadataReferences()
        {
            var manager = this.Services.GetService<VisualStudioMetadataReferenceManager>();
            var searchPaths = ReferencePathUtilities.GetReferencePaths();

            return from fileName in new[] { "mscorlib.dll", "System.dll", "System.Core.dll" }
                   let fullPath = FileUtilities.ResolveRelativePath(fileName, basePath: null, baseDirectory: null, searchPaths: searchPaths, fileExists: File.Exists)
                   where fullPath != null
                   select manager.CreateMetadataReferenceSnapshot(fullPath, MetadataReferenceProperties.Assembly);
        }

        public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
        {
            return VSConstants.S_OK;
        }

        public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
        {
            // Did we rename?
            if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_MkDocument) != 0)
            {
                // We want to consider this file to be added in one of two situations:
                //
                // 1) the old file already was a misc file, at which point we might just be doing a rename from
                //    one name to another with the same extension
                // 2) the old file was a different extension that we weren't tracking, which may have now changed
                if (TryUntrackClosingDocument(docCookie, pszMkDocumentOld) || TryGetLanguageInformation(pszMkDocumentOld) == null)
                {
                    // Add the new one, if appropriate.
                    TrackOpenedDocument(docCookie, pszMkDocumentNew);
                }
            }

            // When starting a diff, the RDT doesn't call OnBeforeDocumentWindowShow, but it does call
            // OnAfterAttributeChangeEx for the temporary buffer. The native IDE used this even to
            // add misc files, so we'll do the same.
            if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) != 0)
            {
                var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);

                if (moniker != null && TryGetLanguageInformation(moniker) != null && !_docCookiesToHostProject.ContainsKey(docCookie))
                {
                    TrackOpenedDocument(docCookie, moniker);
                }
            }

            if ((grfAttribs & (uint)__VSRDTATTRIB3.RDTA_DocumentInitialized) != 0)
            {
                // The document is now initialized, we should try tracking it
                TrackOpenedDocument(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
            }

            return VSConstants.S_OK;
        }

        public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
        {
            return VSConstants.E_NOTIMPL;
        }

        public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
        {
            return VSConstants.E_NOTIMPL;
        }

        public int OnAfterSave(uint docCookie)
        {
            return VSConstants.E_NOTIMPL;
        }

        public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
        {
            return VSConstants.E_NOTIMPL;
        }

        public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
        {
            _foregroundThreadAffinitization.AssertIsForeground();

            if (dwReadLocksRemaining + dwEditLocksRemaining == 0)
            {
                TryUntrackClosingDocument(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
            }

            return VSConstants.S_OK;
        }

        private void TrackOpenedDocument(uint docCookie, string moniker)
        {
            _foregroundThreadAffinitization.AssertIsForeground();

            var languageInformation = TryGetLanguageInformation(moniker);

            if (languageInformation == null)
            {
                // We can never put this document in a workspace, so just bail
                return;
            }

            // We don't want to realize the document here unless it's already initialized. Document initialization is watched in
            // OnAfterAttributeChangeEx and will retrigger this if it wasn't already done.
            if (_runningDocumentTable.IsDocumentInitialized(docCookie) && !_docCookieToWorkspaceRegistration.ContainsKey(docCookie))
            {
                var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
                var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);

                // As long as the buffer is initialized, then we should see if we should attach
                if (textBuffer != null)
                {
                    var registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer());

                    registration.WorkspaceChanged += Registration_WorkspaceChanged;
                    _docCookieToWorkspaceRegistration = _docCookieToWorkspaceRegistration.Add(docCookie, registration);

                    if (!IsClaimedByAnotherWorkspace(registration))
                    {
                        AttachToDocument(docCookie, moniker);
                    }
                }
            }
        }

        private void Registration_WorkspaceChanged(object sender, EventArgs e)
        {
            // We may or may not be getting this notification from the foreground thread if another workspace
            // is raising events on a background. Let's send it back to the UI thread since we can't talk
            // to the RDT in the background thread. Since this is all asynchronous a bit more asynchrony is fine.
            if (!_foregroundThreadAffinitization.IsForeground())
            {
                ScheduleTask(() => Registration_WorkspaceChanged(sender, e));
                return;
            }

            _foregroundThreadAffinitization.AssertIsForeground();

            var workspaceRegistration = (WorkspaceRegistration)sender;

            // Since WorkspaceChanged notifications may be asynchronous and happened on a different thread,
            // we might have already unsubscribed for this synchronously from the RDT while we were in the process of sending this
            // request back to the UI thread.
            if (!_docCookieToWorkspaceRegistration.TryGetKey(workspaceRegistration, out var docCookie))
            {
                return;
            }

            // It's also theoretically possible that we are getting notified about a workspace change to a document that has
            // been simultaneously removed from the RDT but we haven't gotten the notification. In that case, also bail.
            if (!_runningDocumentTable.IsCookieValid(docCookie))
            {
                return;
            }

            var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);

            if (workspaceRegistration.Workspace == null)
            {
                if (_docCookiesToHostProject.TryGetValue(docCookie, out var hostProject))
                {
                    // The workspace was taken from us and released and we have only asynchronously found out now.
                    var document = hostProject.Document;

                    if (document.IsOpen)
                    {
                        RegisterText(document.GetOpenTextContainer());
                    }
                }
                else
                {
                    // We should now try to claim this. The moniker we have here is the moniker after the rename if we're currently processing
                    // a rename. It's possible in that case that this is being closed by the other workspace due to that rename. If the rename
                    // is changing or removing the file extension, we wouldn't want to try attaching, which is why we have to re-check
                    // the moniker. Once we observe the rename later in OnAfterAttributeChangeEx we'll completely disconnect.
                    if (TryGetLanguageInformation(moniker) != null)
                    {
                        AttachToDocument(docCookie, moniker);
                    }
                }
            }
            else if (IsClaimedByAnotherWorkspace(workspaceRegistration))
            {
                // It's now claimed by another workspace, so we should unclaim it
                if (_docCookiesToHostProject.ContainsKey(docCookie))
                {
                    DetachFromDocument(docCookie, moniker);
                }
            }
        }

        /// <summary>
        /// Stops tracking a document in the RDT for whether we should attach to it.
        /// </summary>
        /// <returns>true if we were previously tracking it.</returns>
        private bool TryUntrackClosingDocument(uint docCookie, string moniker)
        {
            bool unregisteredRegistration = false;
            // Remove our registration changing handler before we call DetachFromDocument. Otherwise, calling DetachFromDocument
            // causes us to set the workspace to null, which we then respond to as an indication that we should
            // attach again.
            if (_docCookieToWorkspaceRegistration.TryGetValue(docCookie, out var registration))
            {
                registration.WorkspaceChanged -= Registration_WorkspaceChanged;
                _docCookieToWorkspaceRegistration = _docCookieToWorkspaceRegistration.RemoveKey(docCookie);
                unregisteredRegistration = true;
            }

            DetachFromDocument(docCookie, moniker);

            return unregisteredRegistration;
        }

        private bool IsClaimedByAnotherWorkspace(WorkspaceRegistration registration)
        {
            // Currently, we are also responsible for pushing documents to the metadata as source workspace,
            // so we count that here as well
            return registration.Workspace != null && registration.Workspace.Kind != WorkspaceKind.MetadataAsSource && registration.Workspace.Kind != WorkspaceKind.MiscellaneousFiles;
        }

        private void AttachToDocument(uint docCookie, string moniker)
        {
            _foregroundThreadAffinitization.AssertIsForeground();

            var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
            var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);

            if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
            {
                // We already added it, so we will keep it excluded from the misc files workspace
                return;
            }

            // This should always succeed since we only got here if we already confirmed the moniker is acceptable
            var languageInformation = TryGetLanguageInformation(moniker);
            Contract.ThrowIfNull(languageInformation);

            var languageServices = Services.GetLanguageServices(languageInformation.LanguageName);
            var compilationOptionsOpt = languageServices.GetService<ICompilationFactoryService>()?.GetDefaultCompilationOptions();
            var parseOptionsOpt = languageServices.GetService<ISyntaxTreeFactoryService>()?.GetDefaultParseOptions();

            if (parseOptionsOpt != null &&
                compilationOptionsOpt != null &&
                PathUtilities.GetExtension(moniker) == languageInformation.ScriptExtension)
            {
                parseOptionsOpt = parseOptionsOpt.WithKind(SourceCodeKind.Script);

                var metadataService = Services.GetService<IMetadataService>();
                var scriptEnvironmentService = Services.GetService<IScriptEnvironmentService>();

                // Misc files workspace always provides the service:
                Contract.ThrowIfNull(scriptEnvironmentService);

                var baseDirectory = PathUtilities.GetDirectoryName(moniker);

                // TODO (https://github.com/dotnet/roslyn/issues/5325, https://github.com/dotnet/roslyn/issues/13886):
                // - Need to have a way to specify these somewhere in VS options.
                // - Use RuntimeMetadataReferenceResolver like in InteractiveEvaluator.CreateMetadataReferenceResolver
                // - Add default namespace imports, default metadata references to match csi.rsp
                // - Add default script globals available in 'csi goo.csx' environment: CommandLineScriptGlobals

                var referenceResolver = new WorkspaceMetadataFileReferenceResolver(
                    metadataService,
                    new RelativePathResolver(scriptEnvironmentService.MetadataReferenceSearchPaths, baseDirectory));

                compilationOptionsOpt = compilationOptionsOpt.
                    WithMetadataReferenceResolver(referenceResolver).
                    WithSourceReferenceResolver(new SourceFileResolver(scriptEnvironmentService.SourceReferenceSearchPaths, baseDirectory));
            }

            // First, create the project
            var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptionsOpt, compilationOptionsOpt, _metadataReferences);

            // Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
            var document = _documentProvider.TryGetDocumentForFile(
                hostProject,
                moniker,
                parseOptionsOpt?.Kind ?? SourceCodeKind.Regular,
                getFolderNames: _ => SpecializedCollections.EmptyReadOnlyList<string>(),
                canUseTextBuffer: _ => true);

            // If the buffer has not yet been initialized, we won't get a document.
            if (document == null)
            {
                return;
            }

            // Since we have a document, we can do the rest of the project setup.
            _hostProjects.Add(hostProject.Id, hostProject);
            OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());

            OnDocumentAdded(document.GetInitialState());
            hostProject.Document = document;

            // Notify the document provider, so it knows the document is now open and a part of
            // the project
            _documentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document);

            Contract.ThrowIfFalse(document.IsOpen);

            var buffer = document.GetOpenTextBuffer();
            OnDocumentOpened(document.Id, document.GetOpenTextContainer());

            _docCookiesToHostProject.Add(docCookie, hostProject);
        }

        private void DetachFromDocument(uint docCookie, string moniker)
        {
            _foregroundThreadAffinitization.AssertIsForeground();
            if (_fileTrackingMetadataAsSourceService.TryRemoveDocumentFromWorkspace(moniker))
            {
                return;
            }

            if (_docCookiesToHostProject.TryGetValue(docCookie, out var hostProject))
            {
                var document = hostProject.Document;

                OnDocumentClosed(document.Id, document.Loader);
                OnDocumentRemoved(document.Id);
                OnProjectRemoved(hostProject.Id);

                _hostProjects.Remove(hostProject.Id);
                _docCookiesToHostProject.Remove(docCookie);

                document.Dispose();

                return;
            }
        }

        protected override void Dispose(bool finalize)
        {
            StopSolutionCrawler();

            var runningDocumentTableForEvents = (IVsRunningDocumentTable)_runningDocumentTable;
            runningDocumentTableForEvents.UnadviseRunningDocTableEvents(_runningDocumentTableEventsCookie);
            _runningDocumentTableEventsCookie = 0;
            base.Dispose(finalize);
        }

        public override bool CanApplyChange(ApplyChangesKind feature)
        {
            switch (feature)
            {
                case ApplyChangesKind.ChangeDocument:
                    return true;

                default:
                    return false;
            }
        }

        protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
        {
            var hostDocument = this.GetDocument(documentId);
            hostDocument.UpdateText(newText);
        }

        private HostProject GetHostProject(ProjectId id)
        {
            _hostProjects.TryGetValue(id, out var project);
            return project;
        }

        internal IVisualStudioHostDocument GetDocument(DocumentId id)
        {
            var project = GetHostProject(id.ProjectId);
            if (project != null && project.Document.Id == id)
            {
                return project.Document;
            }

            return null;
        }

        IReadOnlyList<IVisualStudioHostProject> IVisualStudioHostProjectContainer.GetProjects()
        {
            return _hostProjects.Values.ToImmutableReadOnlyListOrEmpty<IVisualStudioHostProject>();
        }

        void IVisualStudioHostProjectContainer.NotifyNonDocumentOpenedForProject(IVisualStudioHostProject project)
        {
            // Since the MiscellaneousFilesWorkspace doesn't do anything lazily, this is a no-op
        }

        private class LanguageInformation
        {
            public LanguageInformation(string languageName, string scriptExtension)
            {
                this.LanguageName = languageName;
                this.ScriptExtension = scriptExtension;
            }

            public string LanguageName { get; }
            public string ScriptExtension { get; }
        }
    }
}


text:
package org.bpmscript;

import java.util.Map;

/**
 * A service that takes in a map of parameters and a template name and returns
 * a string with the template parameters merged into the template.
 */
public interface ITemplateService {

    /**
     * Merge the content template parameters into the named template and return
     * the result as a string.
     *
     * @param template the template name
     * @param content the parameters to merge into the template
     * @return the merged result
     * @throws BpmScriptException if the parameters couldn't be merged into the template.
     */
    public String merge(String template, Map<String, Object> content) throws BpmScriptException;
}

redpajama_set_name: RedPajamaGithub


text:
id: 587d781c367417b2b2512ac2
title: Set the font-size for Multiple Heading Elements
challengeType: 0
videoUrl: ''
localeTitle: Definir o tamanho da fonte para vários elementos de cabeçalho
---

## Description

 A propriedade font-size é usada para especificar o tamanho do texto em um determinado elemento. Essa regra pode ser usada para vários elementos para criar consistência visual de texto em uma página. Nesse desafio, você definirá os valores de todas as tags h1 a h6 para equilibrar os tamanhos dos títulos.

## Instructions

 Defina o font-size da font-size da tag h1 para 68 px.

 Defina o font-size da font-size da tag h2 para 52px.

 Defina o font-size da font-size da tag h3 para 40px.

 Defina o font-size da font-size da tag h4 para 32px.

 Defina o font-size da font-size da tag h5 para 21px.

 Defina o font-size da font-size da tag h6 para 14px.

## Tests

```yml
tests:
  - text: Seu código deve definir a propriedade de <code>font-size</code> da <code>font-size</code> da tag <code>h1</code> como 68 pixels.
    testString: 'assert($("h1").css("font-size") == "68px", "Your code should set the <code>font-size</code> property for the <code>h1</code> tag to 68 pixels.");'
  - text: Seu código deve definir a propriedade <code>font-size</code> da tag <code>h2</code> como 52 pixels.
    testString: 'assert($("h2").css("font-size") == "52px", "Your code should set the <code>font-size</code> property for the <code>h2</code> tag to 52 pixels.");'
  - text: Seu código deve definir a propriedade <code>font-size</code> para a tag <code>h3</code> em 40 pixels.
    testString: 'assert($("h3").css("font-size") == "40px", "Your code should set the <code>font-size</code> property for the <code>h3</code> tag to 40 pixels.");'
  - text: Seu código deve definir a propriedade <code>font-size</code> da tag <code>h4</code> como 32 pixels.
    testString: 'assert($("h4").css("font-size") == "32px", "Your code should set the <code>font-size</code> property for the <code>h4</code> tag to 32 pixels.");'
  - text: Seu código deve definir a propriedade de <code>font-size</code> da <code>font-size</code> para a tag <code>h5</code> como 21 pixels.
    testString: 'assert($("h5").css("font-size") == "21px", "Your code should set the <code>font-size</code> property for the <code>h5</code> tag to 21 pixels.");'
  - text: Seu código deve definir a propriedade <code>font-size</code> para a tag <code>h6</code> como 14 pixels.
    testString: 'assert($("h6").css("font-size") == "14px", "Your code should set the <code>font-size</code> property for the <code>h6</code> tag to 14 pixels.");'

```

## Challenge Seed

```html
<style>

</style>
<h1>This is h1 text</h1>
<h2>This is h2 text</h2>
<h3>This is h3 text</h3>
<h4>This is h4 text</h4>
<h5>This is h5 text</h5>
<h6>This is h6 text</h6>

```

## Solution

```js
// solution required
```


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Activity_BTLE_Services">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:textSize="@dimen/text_size_large"
            android:text="Name"
            android:id="@+id/tv_name"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:textSize="@dimen/text_size_medium"
            android:text="Address"
            android:id="@+id/tv_address"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="8"
            android:fillViewport="true"
            android:id="@+id/scrollView">

            <ExpandableListView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:groupIndicator="@null"
                android:id="@+id/lv_expandable"></ExpandableListView>

        </ScrollView>
    </LinearLayout>

</RelativeLayout>


text:
sfepy.terms.termsSurface module
===============================

.. automodule:: sfepy.terms.termsSurface
    :members:
    :undoc-members:


text:
package com.versionone.om;

import com.versionone.DB.DateTime;
import com.versionone.om.filters.BuildRunFilter;

import java.util.Collection;
import java.util.Map;

/**
 * Represents a Build Project in the VersionOne System.
 */
@MetaDataAttribute("BuildProject")
public class BuildProject extends BaseAsset {
    /**
     * Constructor used to represent an BuildProject entity that DOES exist in
     * the VersionOne System.
     *
     * @param id Unique ID of this entity.
     * @param instance this entity belongs to.
     */
    BuildProject(AssetID id, V1Instance instance) {
        super(id, instance);
    }

    /**
     * Constructor used to represent an BuildProject entity that does NOT yet
     * exist in the VersionOne System.
     *
     * @param instance this entity belongs to.
     */
    BuildProject(V1Instance instance) {
        super(instance);
    }

    /**
     * @return Reference of this Build Project.
     */
    public String getReference() {
        return (String) get("Reference");
    }

    /**
     * @param value Reference of this Build Project.
     */
    public void setReference(String value) {
        set("Reference", value);
    }

    /**
     * @param filter limit the build runs returned; (If null, then all items
     *                returned).
     * @return A collection of Build Runs associated with this Build Project.
     */
    public Collection<BuildRun> getBuildRuns(BuildRunFilter filter) {
        filter = (filter == null) ? new BuildRunFilter() : filter;

        filter.buildProjects.clear();
        filter.buildProjects.add(this);
        return getInstance().get().buildRuns(filter);
    }

    /**
     * Create a Build Run with the given name and date in this Build Project.
     *
     * @param name of creating BuildRun.
     * @param date of creating BuildRun.
     * @return A new Build Run in this Build Project.
     */
    public BuildRun createBuildRun(String name, DateTime date) {
        return getInstance().create().buildRun(this, name, date);
    }

    /**
     * Create a Build Run with the given name and date in this Build Project.
     *
     * @param name of creating BuildRun.
     * @param date of creating BuildRun.
     * @param attributes additional attributes for the BuildRun.
     * @return A new Build Run in this Build Project.
     */
    public BuildRun createBuildRun(String name, DateTime date, Map<String, Object> attributes) {
        return getInstance().create().buildRun(this, name, date, attributes);
    }

    @Override
    void closeImpl() throws UnsupportedOperationException {
        getInstance().executeOperation(BuildProject.class, this, "Inactivate");
    }

    @Override
    void reactivateImpl() throws UnsupportedOperationException {
        getInstance().executeOperation(BuildProject.class, this, "Reactivate");
    }
}


text:
package dbg

// External imports.
import (
    "github.com/xaevman/goat/mod/net"
    "github.com/xaevman/goat/lib/buffer"
)

// Stdlin imports.
import (
    "errors"
    "fmt"
)

// Generated imports.
import (
    "github.com/xaevman/goat/proto"
)

// CmdMsgHandler is an empty function container.
type CmdMsgHandler struct {}

// Close is called when a message signature is unregistered from a protocol.
func (this *CmdMsgHandler) Close() {}

// Init is called when the message signature is first registered in a protocol.
func (this *CmdMsgHandler) Init(proto *net.Protocol) {}

// DeserializeMsg is called by the protocol after an incoming network message has been
// validated, decrypted, and uncompressed.
func (this *CmdMsgHandler) DeserializeMsg(msg *net.Msg, access byte) (interface{}, error) {
    var err error

    cursor := 0
    data   := msg.GetPayload()
    nMsg   := new(CmdMsg)

    nMsg.Cmd, err = buffer.ReadByte(data, &cursor)
    if err != nil { return nil, err }

    nMsg.Data, err = buffer.ReadString(data, &cursor)
    if err != nil { return nil, err }

    return nMsg, nil
}

// SerializeMsg is called by the protocol after a CmdMsg object has been validated,
// compressed, and encrypted, in order to prepare a network message for transmission.
func (this *CmdMsgHandler) SerializeMsg(data interface{}) (*net.Msg, error) {
    cursor      := 0
    nMsg, ok := data.(*CmdMsg)
    if !ok {
        return nil, errors.New(fmt.Sprintf("Cannot serialize type %T", data))
    }

    dataLen := 0

    dataLen += buffer.LenByte()
    dataLen += buffer.LenString(nMsg.Data)

    dataBuffer := make([]byte, dataLen)

    buffer.WriteByte(nMsg.Cmd, dataBuffer, &cursor)
    buffer.WriteString(nMsg.Data, dataBuffer, &cursor)

    msg := net.NewMsg()
    msg.SetMsgType(this.Signature())
    msg.SetPayload(dataBuffer)

    return msg, nil
}

// Signature returns CmdMsg's network signature (proto.DBG_MSG).
func (this *CmdMsgHandler) Signature() uint16 {
    return proto.DBG_MSG
}


text:
package lesson.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("My Swing Frame");
        frame.setSize(640,480);

        JButton button = new JButton("click me");

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "My message");
            }
        });

        button.setSize(400,50);
        frame.setLayout(null);
        frame.add(button);
        frame.setVisible(true);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="sonata_user_profile_list_noslash" path="/list/{currentpage}/{totalpageitems}/{extraParams}">
        <default key="_controller">SonataUserBundle:ProfileList:show</default>
        <default key="alias">profile/list</default>
        <default key="currentpage">0</default>
        <default key="totalpageitems">0</default>
        <default key="extraParams"></default>
        <requirement key="currentpage">\d+</requirement>
        <requirement key="totalpageitems">\d+</requirement>
    </route>

    <route id="sonata_user_profile_list_only_pagin" path="/list/{currentpage}/{totalpageitems}">
        <default key="_controller">SonataUserBundle:ProfileList:show</default>
        <default key="alias">profile/list</default>
        <default key="currentpage">0</default>
        <default key="totalpageitems">0</default>
        <default key="extraParams"></default>
        <requirement key="currentpage">\d+</requirement>
        <requirement key="totalpageitems">\d+</requirement>
    </route>

    <route id="sonata_user_profile_list_only_page" path="/list/{currentpage}">
        <default key="_controller">SonataUserBundle:ProfileList:show</default>
        <default key="alias">profile/list</default>
        <default key="currentpage">0</default>
        <default key="totalpageitems">0</default>
        <default key="extraParams"></default>
        <requirement key="currentpage">.*</requirement>
    </route>

    <route id="sonata_user_profile_list" path="/list">
        <default key="_controller">SonataUserBundle:ProfileList:show</default>
        <default key="alias">profile/list</default>
        <default key="currentpage">0</default>
        <default key="totalpageitems">0</default>
        <default key="extraParams"></default>
    </route>

    <route id="sonata_user_public_profile_show" path="/{userName}">
        <default key="_controller">SonataUserBundle:ProfileFOSUser1:show</default>
        <default key="alias">profile</default>
        <default key="userName">none</default>
        <requirement key="username">.*</requirement>
    </route>

    <route id="sonata_user_profile_show" path="/">
        <default key="_controller">SonataUserBundle:ProfileFOSUser1:show</default>
        <default key="alias">profile</default>
    </route>

    <route id="fos_user_profile_show" path="/" methods="GET">
        <default key="_controller">SonataUserBundle:ProfileFOSUser1:show</default>
        <default key="alias">profile</default>
    </route>

</routes>


text:
require 'yaml'

module QUnited

  # Contains results data from a QUnit JavaScript test. Useful for passing data
  # to formatters.
  class QUnitTestResult
    class AssertionResult
      attr_accessor :data

      def initialize(assertion_data)
        @data = assertion_data
      end

      def message
        data[:message] || 'Failed assertion, no message given.'
      end

      def result
        if data[:result]
          :passed
        else
          data[:message] =~ /^Died on test/ ? :error : :failed
        end
      end

      def passed?; result == :passed end
      def failed?; result == :failed end
      def error?;  result == :error end

      [:expected, :actual].each do |prop|
        define_method(prop) do
          data[prop]
        end
      end
    end

    def self.from_json(json)
      self.new clean_up_result(::YAML.load(json))
    end

    attr_accessor :data

    def initialize(test_data)
      @data = test_data
    end

    def passed?; result == :passed end
    def failed?; result == :failed end
    def error?;  result == :error end

    def result
      @result ||= if assertions.find { |a| a.error? }
        :error
      else
        assertions.find { |a| a.failed? } ? :failed : :passed
      end
    end

    def assertions
      @assertions ||= data[:assertion_data].map { |assertion_data| AssertionResult.new assertion_data }
    end

    [:name, :module_name, :duration, :file].each do |prop|
      define_method(prop) do
        data[prop]
      end
    end

    private

    # Turn String keys into Symbols and convert Strings representing dates
    # and numbers into their appropriate objects.
    def self.clean_up_result(test_result)
      test_result = symbolize_keys(test_result)
      test_result[:start] = DateTime.parse(test_result[:start])
      test_result
    end

    def self.symbolize_keys(obj)
      case obj
      when Hash
        obj.inject({}) do |new_hash, (key, value)|
          new_hash[key.to_sym] = symbolize_keys(value)
          new_hash
        end
      when Array
        obj.map { |x| symbolize_keys(x) }
      else
        obj
      end
    end
  end
end


text:
package io.dropwizard.db;

import com.codahale.metrics.MetricRegistry;
import io.dropwizard.configuration.ResourceConfigurationSourceProvider;
import io.dropwizard.configuration.YamlConfigurationFactory;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.util.Duration;
import io.dropwizard.validation.BaseValidator;
import org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
import org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;

public class DataSourceFactoryTest {
    private final MetricRegistry metricRegistry = new MetricRegistry();

    private DataSourceFactory factory;
    private ManagedDataSource dataSource;

    @Before
    public void setUp() {
        factory = new DataSourceFactory();
        factory.setUrl("jdbc:h2:mem:DbTest-" + System.currentTimeMillis() + ";user=sa");
        factory.setDriverClass("org.h2.Driver");
        factory.setValidationQuery("SELECT 1");
    }

    @After
    public void tearDown() throws Exception {
        if (null != dataSource) {
            dataSource.stop();
        }
    }

    private ManagedDataSource dataSource() throws Exception {
        dataSource = factory.build(metricRegistry, "test");
        dataSource.start();
        return dataSource;
    }

    @Test
    public void testInitialSizeIsZero() throws Exception {
        factory.setUrl("nonsense invalid url");
        factory.setInitialSize(0);
        ManagedDataSource dataSource = factory.build(metricRegistry, "test");
        dataSource.start();
    }

    @Test
    public void buildsAConnectionPoolToTheDatabase() throws Exception {
        try (Connection connection = dataSource().getConnection()) {
            try (PreparedStatement statement = connection.prepareStatement("select 1")) {
                try (ResultSet set = statement.executeQuery()) {
                    while (set.next()) {
                        assertThat(set.getInt(1)).isEqualTo(1);
                    }
                }
            }
        }
    }

    @Test
    public void testNoValidationQueryTimeout() throws Exception {
        try (Connection connection = dataSource().getConnection()) {
            try (PreparedStatement statement = connection.prepareStatement("select 1")) {
                assertThat(statement.getQueryTimeout()).isEqualTo(0);
            }
        }
    }

    @Test
    public void testValidationQueryTimeoutIsSet() throws Exception {
        factory.setValidationQueryTimeout(Duration.seconds(3));

        try (Connection connection = dataSource().getConnection()) {
            try (PreparedStatement statement = connection.prepareStatement("select 1")) {
                assertThat(statement.getQueryTimeout()).isEqualTo(3);
            }
        }
    }

    @Test(expected = SQLException.class)
    public void invalidJDBCDriverClassThrowsSQLException() throws SQLException {
        final DataSourceFactory factory = new DataSourceFactory();
        factory.setDriverClass("org.example.no.driver.here");

        factory.build(metricRegistry, "test").getConnection();
    }

    @Test
    public void testCustomValidator() throws Exception {
        factory.setValidatorClassName(Optional.of(CustomConnectionValidator.class.getName()));
        try (Connection connection = dataSource().getConnection()) {
            try (PreparedStatement statement = connection.prepareStatement("select 1")) {
                try (ResultSet rs = statement.executeQuery()) {
                    assertThat(rs.next()).isTrue();
                    assertThat(rs.getInt(1)).isEqualTo(1);
                }
            }
        }
        assertThat(CustomConnectionValidator.loaded).isTrue();
    }

    @Test
    public void testJdbcInterceptors() throws Exception {
        factory.setJdbcInterceptors(Optional.of("StatementFinalizer;ConnectionState"));
        final ManagedPooledDataSource source = (ManagedPooledDataSource) dataSource();

        assertThat(source.getPoolProperties().getJdbcInterceptorsAsArray())
            .extracting("interceptorClass")
            .contains(StatementFinalizer.class, ConnectionState.class);
    }

    @Test
    public void createDefaultFactory() throws Exception {
        final DataSourceFactory factory = new YamlConfigurationFactory<>(DataSourceFactory.class,
            BaseValidator.newValidator(), Jackson.newObjectMapper(), "dw")
            .build(new ResourceConfigurationSourceProvider(), "yaml/minimal_db_pool.yml");

        assertThat(factory.getDriverClass()).isEqualTo("org.postgresql.Driver");
        assertThat(factory.getUser()).isEqualTo("pg-user");
        assertThat(factory.getPassword()).isEqualTo("iAMs00perSecrEET");
        assertThat(factory.getUrl()).isEqualTo("jdbc:postgresql://db.example.com/db-prod");
        assertThat(factory.getValidationQuery()).isEqualTo("/* Health Check */ SELECT 1");
        assertThat(factory.getValidationQueryTimeout()).isEqualTo(Optional.empty());
    }
}


text:
/**
 * Version: 2.0
 * Made By Jason Martin
 */

/**
 * If it hasn't been initialized before, initialized persistent status object
 * storage in the state object. The state object contains an Array of status
 * objects, and a one-up counter of the next available status id value. Status
 * objects have the following properties:
 *   id - Theoretically unique id for this object.
 *   name - A label for the status.
 *   duration - Integer duration of the status. -1 is permanent
 *   token_id - A graphics token associated with this object. "-1" if not
 *              associated with a token.
 *   link_id - If not "-1", the turn order status is associated with this token
 *             id. Used to have hidden statuses.
 *   marker - Marker tag value to be placed on targets of the status
 *   targets - List of target tokens for the effect
 *   show - The visibility status of the token.
 */
function createStatusTrackerObj() {
    var obj = new Object();
    obj.nextId = 1;
    obj.list = new Array();
    return obj;
}
state.status_tracker = state.status_tracker || createStatusTrackerObj();

/**
 * Constants
 */
var StatusTrackerConsts = StatusTrackerConsts || {};
StatusTrackerConsts.SCRIPT_NAME = "StatusTracker";
StatusTrackerConsts.CMD_PREFIX = '!statustracker';
StatusTrackerConsts.SUBCMD_ADD_STATUS = 'add_status';
StatusTrackerConsts.SUBCMD_ADD_TARGET = 'add_target';
StatusTrackerConsts.SUBCMD_CLEAR = 'clear';
StatusTrackerConsts.SUBCMD_HARD_RESET = 'hard_reset';
StatusTrackerConsts.SUBCMD_REMOVE_STATUS = 'remove_status';
StatusTrackerConsts.SUBCMD_REMOVE_TARGET = 'remove_target';
StatusTrackerConsts.SUBCMD_SHOWMENU = 'showmenu';
StatusTrackerConsts.SUBCMD_SHOW_STATUS = 'show_status';
StatusTrackerConsts.NO_TOKEN = "-1";

// List of token objects loaded into this campaign. This gets populated on ready
var tokenMarkers;

/******************************************************************************/

/**
 * Management of the status objects and markers.
 */
var StatusTracker = StatusTracker || (function() {

    /**
     * @summary Create an off-board graphics object.
     * @param name - Name for the token.
     * @param show - String value specifying where the token is hidden or not.
     *               If this value is "hidden", the token will be placed in the
     *               gmlayer; otherwise, it will be placed in the objects layer.
     */
    function create_token(name, show) {
        var layer = (show == 'hidden' ? 'gmlayer' : 'objects');
        return createObj('graphic', {
           subtype: 'token',
           imgsrc: "",
           layer: layer,
           top: -100,
           left: -100,
           width: 70,
           height: 70,
           name: name,
           showname: true,
           pageid: Campaign().get("playerpageid"),
        });
    } // function create_token

    /**
     * @summary Get the next available status object id.
     * @returns integer value for the next status object id.
     */
    function get_next_id() {
        var found;
        var id;
        do {
            found = false;
            id = state.status_tracker.nextId++;
            for (let i = 0; i < state.status_tracker.list.length; i++) {
                if (state.status_tracker.list[i].id == id) {
                    found = true;
                    break;
                }
            }
        } while (found == true)
        return id;
    } // function get_next_id

    /**
     * @summary Insert a status object into the turnorder.
     * @param statusObj - A generated status object
     */
    function insert_status_into_turnorder(statusObj) {
        let turnorderStr = Campaign().get('turnorder')
        var turnorder = JSON.parse(turnorderStr);
        var position = 0; // By default, at the end of the turnorder
        if (statusObj.token_id != StatusTrackerConsts.NO_TOKEN) {
            for (let i = 0; i < turnorder.length; i++) {
                // Look for the turnorder object associated with the token_id
                if (turnorder[i].id == statusObj.token_id) {
                    position = i;
                    break;
                }
            }
        }

        // Create the turn order object
        turnObj = new Object();
        turnObj.id = statusObj.link_id;
        turnObj.pr = statusObj.duration;
        turnObj.custom = statusObj.name;
        turnObj.status_id = statusObj.id;
        turnObj.formula = (statusObj.duration == -1 ? 0 : -1);
        turnObj.token_id = statusObj.token_id;

        // Insert the token into the turn order and save
        turnorder.splice(position, 0, turnObj);
        Campaign().set('turnorder', JSON.stringify(turnorder));
        return;
    } // function insert_status_into_turnorder

    /**
     * @summary Removes a status from the turnorder
     * @param statusId - integer id of a status effect
     */
    function remove_status_from_turnorder(statusId) {
        let turnorderStr = Campaign().get('turnorder')
        var turnorder = JSON.parse(turnorderStr);
        for (let i = 0; i < turnorder.length; i++) {
            if (turnorder[i].status_id == statusId) {
                turnorder.splice(i,1);
                break;
            }
        }
        Campaign().set('turnorder', JSON.stringify(turnorder));
        return;
    } // function remove_status_from_turnorder

    /**
     * @summary Add a new status effect.
     * @param tokenId - Token id to associate the effect with. If not associated
     *                  with an on-board token, this should be "-1".
     * @param statusName - The label for the status effect
     * @param duration - How many turns the effect lasts. -1 for permanent
     * @param markerName - The name of the marker that will be added to targets
     *                     of the effect.
     * @param show - String for how to display the status effect in the turn
     *               tracker. "hidden" will make the effect visible to the GM;
     *               "no" will not have it visible at all (and effectively
     *               permanent). Default for visible in the turn tracker is "yes".
     */
    function add_status(tokenId, statusName, duration, markerName, show) {
        let durationNum = Number(duration);

        // Look up the marker tag, which may or may not be the same thing as
        // the marker name. The tag will get used to add/remove the marker from
        // a token.
        var markerTag = "";
        for (let i = 0; i < tokenMarkers.length; i++) {
            if (tokenMarkers[i].name == markerName) {
                markerTag = tokenMarkers[i].tag;
                break;
            }
        }

        // If we couldn't find the tag, use the name. The tag values of built-in
        // markers are the same as their names.
        if (markerTag == "") {
            markerTag = markerName;
        }

        // If the status is hidden, or not associated with a game token,
        // create a phantom token for it.
        var link_id = StatusTrackerConsts.NO_TOKEN;
        if ('hidden' == show) {
            var token = create_token(statusName, show)
            link_id = token.id
        }

        // Create a new status object and insert it into the status tracker
        newStatus = new Object();
        newStatus.id = get_next_id();
        newStatus.name = statusName;
        newStatus.duration = durationNum;
        newStatus.targets = new Array();
        newStatus.token_id = tokenId;
        newStatus.link_id = link_id;
        newStatus.marker = markerTag;
        newStatus.show = show;

        // Insert the new status into the status list
        state.status_tracker.list.push(newStatus);
        // Add it to the turn order.
        if (newStatus.show != 'no') {
            insert_status_into_turnorder(newStatus);
        }
        return;
    } // function add_status

    /**
     * @summary Adds a target for a status effect. If that status has a marker,
     *          the target token will have that marker placed on it.
     * @param statusId - Integer id for a status effect
     * @param targetId - String token id being targeted.
     */
    function add_status_target(statusId, targetId) {
        // Get the status object
        statusObj = get_status_obj(statusId);
        if (undefined == statusObj) {
            // Couldn't find it
            return;
        }

        // Check if the target token id is already a target.
        if (-1 != statusObj.targets.indexOf(targetId)) {
            // Already a target
            return;
        }

        // Add the status marker to the target, and record it as a target.
        add_marker(targetId, statusObj.marker);
        statusObj.targets.push(targetId);
        return;
    } // function add_status_target

    /**
     * @summary Gets the status object with the given status id.
     * @param statusId - Integer id for a status effect
     * @returns Status object for the given id. Return undefined if not found.
     */
    function get_status_obj(statusId) {
        for (let i = 0; i < state.status_tracker.list.length; i++) {
            statusObj = state.status_tracker.list[i];
            if (statusObj.id == statusId) {
                return statusObj;
            }
        }
        return undefined;
    } // function get_status_obj

    /**
     * @summary Adds a marker to a token
     * @param targetId - String token id.
     * @param markerTag - Marker tag value
     */
    function add_marker(targetId, markerTag) {
        // Get the graphic object for the given id.
        var token = getObj('graphic', targetId);
        if (undefined == token) {
            return;
        }

        // Add the marker tag to the list of markers for this token.
        var token_markers = token.get('statusmarkers').split(",");
        token_markers.push(markerTag);
        token.set('statusmarkers', token_markers.join(","));
        return;
    } // function add_marker

    /**
     * @summary Remove a marker from a token
     * @param tokenId - String token id
     * @param markerTag - Marker tag value
     */
    function remove_marker(tokenId, markerTag) {
        // Get the graphic object for the given id.
        var token = getObj('graphic', tokenId);
        if (undefined == token) {
            return;
        }

        // Bust out the marker tags for the token. Remove one instance of the
        // marker from the object.
        var token_markers = token.get("statusmarkers").split(",");
        for (let i = 0; i < token_markers.length; i++) {
            if (token_markers[i] == markerTag) {
                token_markers.splice(i, 1);
                token.set("statusmarkers", token_markers.join(","));
                break;
            }
        }
        return;
    } // function remove_marker

    /**
     * @summary Remove and clean up a status effect
     * @param statusId - Integer id for a status effect
     */
    function remove_status(statusId) {
        // Get the status object from the global store
        statusObj = get_status_obj(statusId);
        if (undefined == statusObj) {
            return;
        }

        // Remove the markers from each target of the status
        for (let i = 0; i < statusObj.targets.length; i++) {
            remove_marker(statusObj.targets[i], statusObj.marker);
        }

        // Remove the turnorder element
        remove_status_from_turnorder(statusObj.id);

        // Remove the status object from the global store.
        let index = state.status_tracker.list.indexOf(statusObj)
        if (-1 != index) {
            state.status_tracker.list.splice(index, 1);
        }

        // If there's a standalone token associated with this status, remove it.
        if (StatusTrackerConsts.NO_TOKEN != statusObj.link_id) {
            token = getObj('grapic', statusObj.link_id)
            if (undefined != token) {
                token.remove();
            }
        }
        return;
    } // function remove_status

    /**
     * @summary Removes all status effects associated with a token.
     * @param tokenId - String token id
     */
    function remove_token(tokenId) {
        // Walk backwards through the status list, looking for entries
        // associated with the given token. Remove any found.
        for (let i = state.status_tracker.list.length - 1; i >= 0; i--) {
            if (state.status_tracker.list[i].token_id == tokenId) {
                remove_status(state.status_tracker.list[i].id);
            }
        }
        return;
    } // function remove_token

    /**
     * @summary Process status effects associated with a turn order object.
     * @param turnObj - A turn order object
     */
    function next_turn(turnObj) {
        // If there's no status associated with this turn, kick out.
        if (undefined == turnObj || undefined == turnObj.status_id) {
            return;
        }

        // Get the status object for this turn object.
        statusObj = get_status_obj(turnObj.status_id)
        if (undefined == statusObj) {
            return;
        }

        // If the status has a duration, set the duration to the current turns
        // pr value.
        if (statusObj.duration > 0) {
            statusObj.duration = turnObj.pr;
        }

        // If the duration has timed out, remove it.
        if (0 == statusObj.duration) {
            // remove the status object
            remove_status_from_turnorder(statusObj.id);
            remove_status(statusObj.id);
        }
        return;
    } // function next_turn

    /**
     * @summary Remove all statuses associated with a token id.
     * @param tokenId - String token id. If the id is "all", remove all statuses.
     */
    function clear(tokenId) {
        // See if the input param is 'all'. If it is, we're clearing out
        // everything.
        let isAll = (tokenId.toLowerCase() == "all");

        // This _should_ work. Walk the status_tracker array back-to-front,
        // meaning we're deleting things from the back, meaning we _shouldn't_
        // be dorking with our array index. In theory.
        for (let i = state.status_tracker.list.length - 1; i >= 0; i--) {
            let statusObj = state.status_tracker.list[i];
            if (isAll == true || statusObj.token_id == tokenId) {
                remove_status(statusObj.id);
            }
        }
        return;
    } // function clear

    /**
     * @summary If tokens were removed from the the turn order, remove any
     *          statuses linked to those tokens.
     * @param currentTurn - JSON object defining the current turnorder
     * @param previousTurn - JSON object defining the previous turnorder
     */
    function validate_statuses(currentTurn, previousTurn) {
        for (let i = previousTurn.length - 1; i >= 0; i--) {
            let found = false;
            let turnId = previousTurn[i].id;
            for (let j = 0; j < currentTurn.length; j++) {
                if (currentTurn[j].id == turnId) {
                    found = true;
                }
            }
            if (false == found) {
                if (undefined != previousTurn[i].status_id) {
                    // If the turnorder entry has a status_id, it's something
                    // we created for a status effect. Remove that effect.
                    remove_status(previousTurn[i].status_id)
                } // end if (undefined != ...
                else if ("-1" != turnId) {
                    // A non-"-1" turn id is linked to a token. Clear out any
                    // status effects it might have.
                    clear(turnId);
                } // end else if ("-1" != ...
            } // end if (false == found)
        } // end for
        return;
    } // function validate_statuses

    /**
     * @summary Gets a list of status objects associated with a token.
     * @param tokenId - String token id. If the id is "all", get all statuses.
     * @returns Array containing status id objects
     */
    function get_token_statuses(tokenId) {
        var status_list = new Array();
        let isAll = (tokenId.toLowerCase() == 'all');
        for (let i = 0; i < state.status_tracker.list.length; i++) {
            statusObj = state.status_tracker.list[i];
            if (true == isAll || statusObj.token_id == tokenId) {
                status_list.push(statusObj);
            }
        }
        return status_list;
    } // function get_token_statuses

    /**
     * @summary Removes a token as a target of a status.
     * @param statusId - Integer id for a status effect
     * @param targetId - String token id
     */
    function remove_status_target(statusId, targetId)
    {
        var statusObj = get_status_obj(statusId);
        if (undefined == statusObj) {
            return;
        }
        remove_marker(targetId, statusObj.marker);
        let index = statusObj.targets.indexOf(targetId);
        if (-1 != index) {
            statusObj.targets.splice(index, 1);
        }
        return;
    } // function remove_status_target

    return {
        // List of functions and params to expose

        addStatus: add_status,
        addTarget: add_status_target,
        clear: clear,
        getTokenStatuses: get_token_statuses,
        nextTurn: next_turn,
        removeStatus: remove_status,
        removeTarget: remove_status_target,
        removeToken: remove_token,
        validateStatuses: validate_statuses,
    };
}()); // StatusTracker

/******************************************************************************/

/**
 * Menus and interfaces.
 */
var StatusTrackerMenus = StatusTrackerMenus || (function() {

    var MENU_CSS = {
        'centeredBtn': {
          'text-align': 'center'
        },
        'menu': {
          'background': '#fff',
          'border': 'solid 1px #000',
          'border-radius': '5px',
          'font-weight': 'bold',
          'margin-bottom': '1em',
          'overflow': 'hidden'
        },
        'menuBody': {
          'padding': '5px',
          'text-align': 'center'
        },
        'menuHeader': {
          'background': '#000',
          'color': '#fff',
          'text-align': 'center'
        }
    };

    // Marker select is a prepopulated macro input line for selecting loaded
    // markers by name.
    // TODO : Would love to get the images involves in the drop down.
    var markerSelect = "?{Select Marker|";
    const base_markers = ['red', 'blue', 'green', 'brown', 'purple', 'pink', 'yellow', 'dead']

    /**
     * @summary Create the drop-down menu for the marker select input.
     */
    function create_marker_select() {
        // Add the default markers (colors and dead)
        _.each(base_markers, marker => {
            markerSelect = markerSelect + marker + "|";
        });
        // Add the loaded token markers.
        _.each(tokenMarkers, marker => {
            markerSelect = markerSelect + marker.name + "|";
        });

        // Trim off the trailing '|'
        markerSelect = markerSelect.substring(0, markerSelect.length - 1);
        markerSelect = markerSelect + "}";
    } // function create_marker_select

    /**
     * @summary Create a menu panel using HtmlBuilder
     * @param header - Label for the menu
     * @param content - Menu html content.
     * @returns HtmlBuilder object
     */
    function _build_menu_panel(header, content) {
        let menu = new HtmlBuilder('.menu');
        menu.append('.menuHeader', header);
        menu.append('.menuBody', content);
        return menu;
    } // function _build_menu_panel

    /**
     *  @summary Create the "Show Menu" macro.
     */
    function create_menu_macro() {
        let players = findObjs({_type: 'player'});
         _.each(players, player => {
            let playerId = player.get('id');
            if (!playerIsGM(playerId)) {
                return;
            };

            let macro = findObjs({
                _type: 'macro',
                _playerid: playerId,
                name: 'StatusTrackerMenu'
            })[0];

            if (macro) {
                macro.set('action', '!statustracker showmenu');
            }
            else {
                createObj('macro', {
                   _playerid: playerId,
                   name: 'StatusTrackerMenu',
                   action: '!statustracker showmenu'
                });
            }
        });
    } // function create_menu_macro

    /**
     * @summary Displays the base menu in the chat window.
     */
    function show_menu() {
        let content = new HtmlBuilder('div');
        content.append('.centeredBtn').append('a', "Add Status to Token", {
            href: '!statustracker add_status --token @{selected|token_id} --status ?{Effect Name} --duration ?{Duration in rounds (-1 for permanent)} --show ?{Show in turn tracker?|yes|no|hidden} --marker ' + markerSelect,
            title: 'Add New Token Status'
        });
        content.append('.centeredBtn').append('a', "Add Standalone Status", {
            href: '!statustracker add_status --token -1 --status ?{Effect Name} --duration ?{Duration in rounds (-1 for permanent)} --show ?{Show in turn tracker?|yes|no|hidden} --marker ' + markerSelect,
            title: 'Add New Standalone Status'
        });
        content.append('.centeredBtn').append('a', "Show Token Statuses", {
            href: '!statustracker show_status --token @{selected|token_id}',
            title: 'Show Token Statuses'
        });
        content.append('.centeredBtn').append('a', "Show All Statuses", {
            href: '!statustracker show_status --token all',
            title: 'Show All Statuses'
        });
        content.append('.centeredBtn').append('a', "Clear Token Statuses", {
            href: '!statustracker clear --token @{selected|token_id}',
            title: 'Clear All Token Statuses'
        });
        content.append('.centeredBtn').append('a', "Clear All Statuses", {
            href: '!statustracker clear --token all',
            title: 'Global Clear Statuses'
        });

        let menu = _build_menu_panel('StatusTracker Menu', content);
        sendChat(StatusTrackerConsts.SCRIPT_NAME, '/w gm ' + menu.toString(MENU_CSS));
    } // function show_menu

    /**
     * @summary Build the target/end menu for an individual status.
     * @param statusObj - Object for the status
     * @returns HtmlBuilder menu
     */
    function _build_status_menu(statusObj) {
        let content = new HtmlBuilder('div');
        content.append('.centeredBtn').append('a', "Add Target", {
            href: '!statustracker add_target --id ' + statusObj.id + ' --target @{selected|token_id}',
            title: 'Add Target For Effect'
        });
        content.append('.centeredBtn').append('a', "Remove Target", {
            href: '!statustracker remove_target --id ' + statusObj.id + ' --target @{selected|token_id}',
            title: 'Remove Target For Effect'
        });
        content.append('.centeredBtn').append('a', "End", {
            href: '!statustracker remove_status  --id ' + statusObj.id,
            title: 'End Effect'
        });

        let label = statusObj.name + " (" + statusObj.duration + ")";
        let tokenObj = getObj('graphic', statusObj.token_id);
        if (tokenObj != undefined) {
            label = label + " [" + tokenObj.get("name") + "]";
        }
        if (statusObj.targets.length > 0) {
            label = label + " [";
            for (let i = 0; i < statusObj.targets.length; i++) {
                label = label + " " + statusObj.targets[i] + ",";
            }
            // Trim off the last comma
            label = label.substring(0, label.length -1 ) + "]";
        }
        let menu = _build_menu_panel(label, content);
        return menu;
    } // function _build_status_menu

    /**
     * @summary Show the target menus for statuses associated with a given token
     * @param tokenId - Token id
     */
    function show_status_menu(tokenId) {
        let content = new HtmlBuilder('div');
        let statuses = StatusTracker.getTokenStatuses(tokenId);
        if (statuses.length == 0) {
            sendChat(StatusTrackerConsts.SCRIPT_NAME, '/w gm No active statuses');
            return;
        }
        _.each(statuses, function(obj) {
            let submenu = _build_status_menu(obj);
            content.append(submenu);
        });
        sendChat(StatusTrackerConsts.SCRIPT_NAME, '/w gm ' + content.toString(MENU_CSS));
        return
    } // function show_status_menu

    return {
        createMenuMacro: create_menu_macro,
        showMenu: show_menu,
        showStatusMenu: show_status_menu,
        createMarkerSelect: create_marker_select,
    };

}()); // StatusTrackerMenus

/******************************************************************************/

/**
 * Input handling
 */
var StatusTrackerCommandline = StatusTrackerCommandline || (function() {

    /**
     * Parses message content. The following presumptions are made:
     * 1. A command and any sub commands will be the first elements of the msg
     * 2. Parameters will be proceded by ' --<param name>'
     * 3. Each parameter name will be unique, and will be forced to lowercase.
     *
     * An object will be returned with the potential properties of 'command',
     * 'subcommand', and any parameter names.
     * @param msg - API commandline message content
     * @returns Object containing params from the command
     */
    function _argparse(msg) {
        var obj = {};
        // Split on  whitespace followed by "--".
        argv = msg.split(/\s+--/);
        // The first half of the split should be the command/subcommands.
        command = argv.shift().split(' ');
        if (command.length == 0) {
            return undefined;
        };

        // Populate the command and subcommand fields of the args object.
        obj['command'] = command.shift().toLowerCase();
        if (command.length >= 1) {
            obj['subcommand'] = command.join(' ').toLowerCase();
        }

        // Iterate through the remaining arguments. The first element of each
        // set should be the param name, followed by value. If no value, the
        // param will be set to true.
        _.each(argv, function(args) {
            let argSet = args.split(" ");
            if (argSet.length == 0) {
                return;
            } else if (argSet.length == 1) {
                // Treat parameters without as value as boolean
                obj[argSet[0].toLowerCase()] = true;
            } else {
                // Stitch a multi-spaced value back together.
                let key = argSet[0].toLowerCase();
                let value = argSet.slice(1).join(' ');
                obj[key] = value
            }
        });
        return obj;
    } // function _argparse

    /**
     * @summary Processes command string
     * @param msg - chat:message object
     */
    function do_command(msg) {
        args = _argparse(msg.content);
        if (args == undefined || args.command != StatusTrackerConsts.CMD_PREFIX) {
            return;
        }
        switch (args.subcommand) {
            case StatusTrackerConsts.SUBCMD_ADD_STATUS:
                StatusTracker.addStatus(args.token, args.status, args.duration, args.marker, args.show);
                StatusTrackerMenus.showStatusMenu(args.token);
                break;
            case StatusTrackerConsts.SUBCMD_ADD_TARGET:
                StatusTracker.addTarget(args.id, args.target);
                break;
            case StatusTrackerConsts.SUBCMD_CLEAR:
                StatusTracker.clear(args.token);
                break;
            case StatusTrackerConsts.SUBCMD_HARD_RESET:
                try {
                    StatusTracker.clear('all');
                }
                catch (err) {
                    log(err);
                }
                state.status_tracker = createStatusTrackerObj();
            case StatusTrackerConsts.SUBCMD_REMOVE_STATUS:
                StatusTracker.removeStatus(args.id);
                break;
            case StatusTrackerConsts.SUBCMD_REMOVE_TARGET:
                StatusTracker.removeTarget(args.id, args.target);
                break;
            case StatusTrackerConsts.SUBCMD_SHOWMENU:
                StatusTrackerMenus.showMenu();
                break;
            case StatusTrackerConsts.SUBCMD_SHOW_STATUS:
                StatusTrackerMenus.showStatusMenu(args.token)
                break;
            default:
                // print help?
                break;
        }

        return;
    } // function do_command

    return {
        doCommand: do_command,
    }
}()); // StatusTrackerCommandline

/******************************************************************************/

// Handler for the turn order changing
on('change:campaign:turnorder', function(current, prev) {
    currentTurnorder = JSON.parse(current.get('turnorder'));
    previousTurnorder = JSON.parse(prev.turnorder);
    StatusTracker.validateStatuses(currentTurnorder, previousTurnorder);
    currentTurn = currentTurnorder.shift()
    StatusTracker.nextTurn(currentTurn);
});

// Handler for chat messages
on('chat:message', function(msg) {
    if (msg.type != 'api') {
        return;
    }
    StatusTrackerCommandline.doCommand(msg);
});

// Handler for graphic destruction. Remove statuses of tokens deleted off the
// board.
on('destroy:graphic', function(obj) {
   StatusTracker.removeToken(obj.id);
});

// Handler for 'ready'. Do any initial do-once setup.
on('ready', () => {
    'use strict';
    // Create the list of available token markers
    tokenMarkers = JSON.parse(Campaign().get("token_markers"));
    StatusTrackerMenus.createMarkerSelect();
    // Create the show-menu macro
    StatusTrackerMenus.createMenuMacro();
    log("Loaded " + StatusTrackerConsts.SCRIPT_NAME);

});


text:
using System;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;

namespace Akka.Streams.Tests.Dsl
{
    public class HeadSinkSpec : ScriptedTest
    {
        private ActorMaterializer Materializer { get; }

        public HeadSinkSpec(ITestOutputHelper helper):base(helper)
        {
            var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 16);
            Materializer = ActorMaterializer.Create(Sys, settings);
        }

        [Fact]
        public void A_FLow_with_a_Sink_Head_must_yield_the_first_value()
        {
            this.AssertAllStagesStopped(() =>
            {
                var p = this.CreateManualPublisherProbe<int>();
                var task = Source.FromPublisher(p).Select(x=>x).RunWith(Sink.First<int>(), Materializer);
                var proc = p.ExpectSubscription();
                proc.ExpectRequest();
                proc.SendNext(42);
                task.Wait(100);
                task.Result.Should().Be(42);
                proc.ExpectCancellation();
            }, Materializer);
        }

        [Fact]
        public void A_FLow_with_a_Sink_Head_must_yield_the_first_value_when_actively_constructing()
        {
            var p = this.CreateManualPublisherProbe<int>();
            var f = Sink.First<int>();
            var s = Source.AsSubscriber<int>();
            var t = s.ToMaterialized(f, Keep.Both).Run(Materializer);
            var subscriber = t.Item1;
            var future = t.Item2;

            p.Subscribe(subscriber);
            var proc = p.ExpectSubscription();
            proc.ExpectRequest();
            proc.SendNext(42);
            future.Wait(100);
            future.Result.Should().Be(42);
            proc.ExpectCancellation();
        }

        [Fact]
        public void A_FLow_with_a_Sink_Head_must_yield_the_first_error()
        {
            this.AssertAllStagesStopped(() =>
            {
                Source.Failed<int>(new Exception("ex"))
                    .Invoking(s => s.RunWith(Sink.First<int>(), Materializer).Wait(TimeSpan.FromSeconds(1)))
                    .ShouldThrow<AggregateException>()
                    .WithInnerException<Exception>()
                    .WithInnerMessage("ex");
            }, Materializer);
        }

        [Fact]
        public void A_FLow_with_a_Sink_Head_must_yield_NoSuchElementException_for_empty_stream()
        {
            this.AssertAllStagesStopped(() =>
            {
                Source.Empty<int>()
                    .Invoking(s => s.RunWith(Sink.First<int>(), Materializer).Wait(TimeSpan.FromSeconds(1)))
                    .ShouldThrow<AggregateException>()
                    .WithInnerException<NoSuchElementException>()
                    .WithInnerMessage("First of empty stream");
            }, Materializer);
        }

        [Fact]
        public void A_FLow_with_a_Sink_HeadOption_must_yield_the_first_value()
        {
            this.AssertAllStagesStopped(() =>
            {
                var p = this.CreateManualPublisherProbe<int>();
                var task = Source.FromPublisher(p).Select(x => x).RunWith(Sink.FirstOrDefault<int>(), Materializer);
                var proc = p.ExpectSubscription();
                proc.ExpectRequest();
                proc.SendNext(42);
                task.Wait(100);
                task.Result.Should().Be(42);
                proc.ExpectCancellation();
            }, Materializer);
        }

        [Fact]
        public void A_FLow_with_a_Sink_HeadOption_must_yield_the_first_error()
        {
            this.AssertAllStagesStopped(() =>
            {
                Source.Failed<int>(new Exception("ex"))
                    .Invoking(s => s.RunWith(Sink.FirstOrDefault<int>(), Materializer).Wait(TimeSpan.FromSeconds(1)))
                    .ShouldThrow<AggregateException>()
                    .WithInnerException<Exception>()
                    .WithInnerMessage("ex");
            }, Materializer);
        }

        [Fact]
        public void A_FLow_with_a_Sink_HeadOption_must_yield_default_for_empty_stream()
        {
            this.AssertAllStagesStopped(() =>
            {
                var task = Source.Empty<int>().RunWith(Sink.FirstOrDefault<int>(), Materializer);
                task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue();
                task.Result.Should().Be(0);
            }, Materializer);
        }
    }
}


text:
<?php
namespace TwbBundleTest;
class ModuleTest extends \PHPUnit_Framework_TestCase{

	/**
	 * @var \TwbBundle\Module
	 */
	protected $module;

	public function setUp(){
		$this->module = new \TwbBundle\Module();
	}

	public function testGetAutoloaderConfig(){
		$this->assertEquals(
			array('Zend\Loader\ClassMapAutoloader' => array(realpath(getcwd().'/../autoload_classmap.php'))),
			$this->module->getAutoloaderConfig()
		);
	}

	public function testGetConfig(){
		$this->assertTrue(is_array($this->module->getConfig()));
	}
}


text:
<?php echo convert_body($album->body, array('is_truncate' => false)); ?>

<?php if (Config::get('album.display_setting.detail.display_slide_image')): ?>
<?php 	if ($list): ?>

<?php $i = 0; ?>
<?php 		foreach ($list as $album_image): ?>
		<div class="item<?php if (!$i): ?> active<?php endif; ?>">
			<?php echo img($album_image->get_image(), img_size('ai', 'L'), 'album/image/'.$album_image->id); ?>
<?php if (!empty($album_image->name)): ?>

<?php echo $album_image->name; ?>

<?php endif; ?>

<?php $i++; ?>
<?php 		endforeach; ?>

<?php 	endif; ?>
<?php endif; ?>

<?php if (!empty($val)): ?>

<?php echo term('album_image', 'form.upload'); ?>

<?php echo render('_parts/form/upload_form', array('form_attrs' => array('action' => 'album/upload_image/'.$id), 'with_public_flag' => true, 'val' => $val)); ?>

<?php endif; ?>

<?php if ($list): ?>
<?php echo btn(sprintf('%sを見る', term('site.picture')), 'album/slide/'.$album->id, 'mr', true, null, null, null, 'picture', null, null, false); ?>
<?php endif; ?>
<?php if (Auth::check() && $album->member_id == $u->id): ?>
<?php if (!$disabled_to_update): ?>
<?php echo btn(sprintf('%sを%s', term('site.picture'), term('form.add')), 'album/upload/'.$album->id, 'mr', true, null, null, null, 'upload', null, null, false); ?>
<?php endif; ?>
<?php echo btn(term('site.picture', 'site.management'), 'album/edit_images/'.$album->id, null, true, null, null, null, 'th-list', null, null, false); ?>
<?php endif; ?>

<?php echo render('image/_parts/list', array(
	'id' => $id,
	'album' => $album,
	'list' => $list,
	'page' => $page,
	'next_page' => $next_page,
	'is_member_page' => $is_member_page,
	'liked_album_image_ids' => isset($liked_album_image_ids) ? $liked_album_image_ids : array(),
)); ?>


text:
import pymysql.cursors
import argparse
import prettytable
import logging
from errors import *

class BaseManager(object):
    def __init__(self, settings):
        self.settings = settings
        self.dbconn = pymysql.connect(host=self.settings.TRACKING_DB['host'],
                             port=self.settings.TRACKING_DB['port'],
                             user=self.settings.TRACKING_DB['user'],
                             password=self.settings.TRACKING_DB['pass'],
                             db=self.settings.TRACKING_DB['dbname'])
        self.db = self.dbconn.cursor()
        self.logger = self.get_logger()
        self.boto_conns = {}
        self.__subinit__()
        self._az_region_map = {}

    def __subinit__(self):
        ''' Called  by the constructor to allow subclasses to have their own unique constructors '''
        pass

    def build_argument_parser(self, parser):
        if not isinstance(parser, argparse.ArgumentParser):
            raise TypeError("Expecting an ArgumentParser")
        self.argument_parser_builder(parser)

    # this must be implemented to build out the argument parser sub section for a particular module
    def argument_parser_builder(self, parser):
        raise NotImplementedError("argument_parser_builder not implemented")

    def output_formatted(self, table_title, column_headers, data, summary_text=None, insert_breaks=0):
        def tstr(x):
            if x is not None:
                return str(x)
            else:
                # gives some value for output so that command line tools like cut and awk work more easily
                return "---"

        if self.settings.HUMAN_OUTPUT:
            print "\n\n{0}:".format(table_title)
            table = prettytable.PrettyTable(column_headers)
            table.align = 'l'
            for row in data:
                table.add_row(map(tstr, row))
                for x in range(insert_breaks):
                    table.add_row([' '] * len(row))
            print table
            if summary_text:
                print "{0}\n".format(summary_text)
            else:
                print "{0} total records\n".format(len(data))
            print "\n\n"
        else:
            for row in data:
                print "\t".join(map(tstr, row))

    def get_logger(self):
        if not hasattr(self.settings, 'logger'):
            self.settings.logger = logging.getLogger('ams')
            amsloglevel = getattr(logging, self.settings.AMS_LOGLEVEL.upper(), 'WARNING')
            globalloglevel = getattr(logging, self.settings.GLOBAL_LOGLEVEL.upper(), 'CRITICAL')
            logging.basicConfig(level=globalloglevel)
            self.settings.logger.setLevel(level=amsloglevel)
        return self.settings.logger

    def parse_region_from_availability_zone(self, availability_zone):
        if availability_zone not in self._az_region_map:
            self.db.execute("select region from availability_zones where availability_zone = %s", (availability_zone, ))
            row = self.db.fetchone()
            if not row:
                raise InvalidValue("Availability zone not found, to load availability zone data try running: ams host discovery")
            self._az_region_map[availability_zone] = row[0]
        return self._az_region_map[availability_zone]

    def argparse_stub(self):
        raise NotImplemented('argparse_stub() must be implemented for dynamic modules')

    def argparse_help_text(self):
        return ''


text:
package jadx.core.dex.instructions;

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

import jadx.api.plugins.input.insns.custom.IArrayPayload;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.utils.exceptions.JadxRuntimeException;

public final class FillArrayData extends InsnNode {

	private static final ArgType ONE_BYTE_TYPE = ArgType.unknown(PrimitiveType.BYTE, PrimitiveType.BOOLEAN);
	private static final ArgType TWO_BYTES_TYPE = ArgType.unknown(PrimitiveType.SHORT, PrimitiveType.CHAR);
	private static final ArgType FOUR_BYTES_TYPE = ArgType.unknown(PrimitiveType.INT, PrimitiveType.FLOAT);
	private static final ArgType EIGHT_BYTES_TYPE = ArgType.unknown(PrimitiveType.LONG, PrimitiveType.DOUBLE);

	private final Object data;
	private final int size;
	private final int elemSize;
	private ArgType elemType;

	public FillArrayData(IArrayPayload payload) {
		this(payload.getData(), payload.getSize(), payload.getElementSize());
	}

	private FillArrayData(Object data, int size, int elemSize) {
		super(InsnType.FILL_ARRAY_DATA, 0);
		this.data = data;
		this.size = size;
		this.elemSize = elemSize;
		this.elemType = getElementType(elemSize);
	}

	private static ArgType getElementType(int elementWidthUnit) {
		switch (elementWidthUnit) {
			case 1:
			case 0:
				return ONE_BYTE_TYPE;
			case 2:
				return TWO_BYTES_TYPE;
			case 4:
				return FOUR_BYTES_TYPE;
			case 8:
				return EIGHT_BYTES_TYPE;
			default:
				throw new JadxRuntimeException("Unknown array element width: " + elementWidthUnit);
		}
	}

	public Object getData() {
		return data;
	}

	public int getSize() {
		return size;
	}

	public ArgType getElementType() {
		return elemType;
	}

	public List<LiteralArg> getLiteralArgs(ArgType type) {
		List<LiteralArg> list = new ArrayList<>(size);
		Object array = data;
		switch (elemSize) {
			case 1:
				for (byte b : (byte[]) array) {
					list.add(InsnArg.lit(b, type));
				}
				break;
			case 2:
				for (short b : (short[]) array) {
					list.add(InsnArg.lit(b, type));
				}
				break;
			case 4:
				for (int b : (int[]) array) {
					list.add(InsnArg.lit(b, type));
				}
				break;
			case 8:
				for (long b : (long[]) array) {
					list.add(InsnArg.lit(b, type));
				}
				break;
			default:
				throw new JadxRuntimeException("Unknown type: " + data.getClass() + ", expected: " + type);
		}
		return list;
	}

	@Override
	public boolean isSame(InsnNode obj) {
		if (this == obj) {
			return true;
		}
		if (!(obj instanceof FillArrayData) || !super.isSame(obj)) {
			return false;
		}
		FillArrayData other = (FillArrayData) obj;
		return elemType.equals(other.elemType) && data == other.data;
	}

	@Override
	public InsnNode copy() {
		FillArrayData copy = new FillArrayData(data, size, elemSize);
		copy.elemType = this.elemType;
		return copyCommonParams(copy);
	}

	public String dataToString() {
		switch (elemSize) {
			case 1:
				return Arrays.toString((byte[]) data);
			case 2:
				return Arrays.toString((short[]) data);
			case 4:
				return Arrays.toString((int[]) data);
			case 8:
				return Arrays.toString((long[]) data);
			default:
				return "?";
		}
	}

	@Override
	public String toString() {
		return super.toString() + ", data: " + dataToString();
	}
}


text:
> This package has moved into the [Static2000 monorepo](https://github.com/judas-christ/static2000).

Nunjucks adapter for [Static2000](https://github.com/judas-christ/static2000).

## Installation

Via npm:

```bash
npm install static2000-nunjucks
```

## Usage

Install, create templates and content as `.html` files and run [static2000](https://github.com/judas-christ/static2000) with `templateAdapter` specified:

```bash
static2000 --templateAdapter static2000-nunjucks
```

or

```js
var static2000 = require('static2000');

static2000({ templateAdapter: 'static2000-nunjucks' });
```

## Globals

### Global include

This adapter includes `[templates folder]/includes/globals.html` in all files, templates and content, so macros defined there are available both in the body of content and in templates:

```html+django
{{ globals.myMacro() }}
```

### Global functions

The global functions are available without namespace in the templates:

```html+django
{% set visiblePages = query({ visible: true }) %}
```


text:
<?php

/**
 * Cache class that stores cached content in Redis server.
 *
 * @package    sfRedisPlugin
 * @subpackage cache
 * @author     Benjamin Viellard <bicou@bicou.com>
 * @version    SVN: $Id: sfRedisCache.class.php 28828 2010-03-27 16:01:49Z bicou $
 */
class sfRedisCache extends sfCache
{
  /**
   * Predis client instance
   *
   * @var Predis_Client
   * @access protected
   */
  protected $redis = null;

  /**
   * Available options :
   *
   * * connection:   Configuration key to connection parameters
   *
   * @see sfCache
   */
  public function initialize($options = array())
  {
    parent::initialize($options);

    $this->redis = sfRedis::getClient($this->getOption('connection', 'default'));
  }

  /**
   * @see sfCache
   */
  public function getBackend()
  {
    return $this->redis;
  }

 /**
  * @see sfCache
  */
  public function get($key, $default = null)
  {
    $value = $this->redis->get($this->getKey($key));

    return null === $value ? $default : $value;
  }

  /**
   * @see sfCache
   */
  public function has($key)
  {
    return $this->redis->exists($this->getKey($key));
  }

  /**
   * @see sfCache
   */
  public function set($key, $data, $lifetime = null)
  {
    $lifetime = $this->getLifetime($lifetime);

    if ($lifetime < 1)
    {
      $ret = $this->remove($key);
    }
    else
    {
      $pkey = $this->getKey($key);
      $mkey = $this->getKey($key, '_lastmodified');
      $pipe = $this->redis->pipeline();

      $pipe->mset(array($pkey => $data, $mkey => time()));
      $pipe->expire($pkey, $lifetime);
      $pipe->expire($mkey, $lifetime);

      $reply = $pipe->execute();

      $ret = $reply[0] and $reply[1] and $reply[2];
    }

    return $ret;
  }

  /**
   * @see sfCache
   */
  public function remove($key)
  {
    return $this->redis->delete($this->getKey($key), $this->getKey($key, '_lastmodified'));
  }

  /**
   * We manually remove keys as the redis glob style * == sfCache ** style
   *
   * @see sfCache
   */
  public function removePattern($pattern)
  {
    $pattern = $this->getKey($pattern);
    $regexp  = self::patternToRegexp($pattern);
    foreach ($this->redis->keys($pattern) as $key)
    {
      if (preg_match($regexp, $key))
      {
        $this->remove(substr($key, strlen($this->getOption('prefix'))));
      }
    }
  }

  /**
   * @see sfCache
   */
  public function clean($mode = sfCache::ALL)
  {
    if (sfCache::ALL === $mode)
    {
      $this->removePattern('*');
    }
  }

  /**
   * @see sfCache
   */
  public function getTimeout($key)
  {
    $ttl = $this->redis->ttl($this->getKey($key));
    return $ttl > -1 ? time() + $ttl : 0;
  }

  /**
   * @see sfCache
   */
  public function getLastModified($key)
  {
    return $this->redis->get($this->getKey($key, '_lastmodified'));
  }

  /**
   * Optimized getMany with Redis mget method
   *
   * @param array $keys
   * @access public
   * @return array
   */
  public function getMany($keys)
  {
    $cache_keys = array_map(array($this, 'getKey'), $keys);

    return array_combine($keys, $this->redis->getMultiple($cache_keys));
  }

  /**
   * Checks if a key is expired or not
   *
   * @param string $key
   * @access public
   * @return void
   */
  public function isExpired($key)
  {
    return !$this->getTimeout($key);
  }

  /**
   * Apply prefix and suffix to a value
   *
   * Usefull to be mapped on an array. Faster than foreach
   *
   * @param string $name
   * @param string $suffix
   * @access protected
   * @return string
   */
  protected function getKey($name, $suffix = null)
  {
    $key = $this->getOption('prefix').$name;

    if ($suffix !== null)
    {
      $key .= self::SEPARATOR.$suffix;
    }

    return $key;
  }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\Conveniencies;

/* @var $this yii\web\View */
/* @var $models app\modules\institutions\models\CourseLevels */
/* @var $model app\modules\institutions\models\CourseLevels */
/* @var $form yii\widgets\ActiveForm */
?>

<fieldset class="courses-levels-form">
    <legend>Study Levels</legend>

            <?php foreach ($models as $lvl => $model): ?>

                    <?= $form->field($model, "[$lvl]active")->checkbox(['checked' => '1', 'value' => ''], true) ?>

            <?php endforeach; ?>

</fieldset>


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

namespace Disclose.DiscordClient.DiscordNetAdapters
{
    internal class ServerUser : User, IServerUser
    {
        public ServerUser(IGuildUser user) : base(user)
        {
            RoleIds = user.RoleIds;
        }

        public IEnumerable<ulong> RoleIds { get; }
    }
}


text:
class Regulation < ApplicationRecord
  validates :name, :content, presence: true
  validates :regulation_type, inclusion: [1]
  validates :regulation_type, uniqueness: {scope: :name, message: '同一名字的类型不能重复'}
end


text:
<?php

namespace Acme\DemoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Acme\DemoBundle\Entity\TplTemplatetypes
 *
 * @ORM\Table(name="tpl__templatetypes")
 * @ORM\Entity
 */
class TplTemplatetypes
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer $customerid
     *
     * @ORM\Column(name="CustomerID", type="integer", nullable=false)
     */
    private $customerid;

    /**
     * @var boolean $templateclass
     *
     * @ORM\Column(name="TemplateClass", type="boolean", nullable=false)
     */
    private $templateclass;

    /**
     * @var integer $groupid
     *
     * @ORM\Column(name="GroupID", type="integer", nullable=false)
     */
    private $groupid;

    /**
     * @var string $name
     *
     * @ORM\Column(name="Name", type="string", length=50, nullable=false)
     */
    private $name;

    /**
     * @var string $referencename
     *
     * @ORM\Column(name="ReferenceName", type="string", length=50, nullable=false)
     */
    private $referencename;

    /**
     * @var string $referenceentity
     *
     * @ORM\Column(name="ReferenceEntity", type="string", length=10, nullable=false)
     */
    private $referenceentity;

    /**
     * @var string $description
     *
     * @ORM\Column(name="Description", type="string", length=255, nullable=true)
     */
    private $description;

    /**
     * @var boolean $deleted
     *
     * @ORM\Column(name="Deleted", type="boolean", nullable=false)
     */
    private $deleted;

    /**
     * @var \DateTime $datlastchange
     *
     * @ORM\Column(name="datLastChange", type="datetime", nullable=false)
     */
    private $datlastchange;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set customerid
     *
     * @param integer $customerid
     * @return TplTemplatetypes
     */
    public function setCustomerid($customerid)
    {
        $this->customerid = $customerid;

        return $this;
    }

    /**
     * Get customerid
     *
     * @return integer
     */
    public function getCustomerid()
    {
        return $this->customerid;
    }

    /**
     * Set templateclass
     *
     * @param boolean $templateclass
     * @return TplTemplatetypes
     */
    public function setTemplateclass($templateclass)
    {
        $this->templateclass = $templateclass;

        return $this;
    }

    /**
     * Get templateclass
     *
     * @return boolean
     */
    public function getTemplateclass()
    {
        return $this->templateclass;
    }

    /**
     * Set groupid
     *
     * @param integer $groupid
     * @return TplTemplatetypes
     */
    public function setGroupid($groupid)
    {
        $this->groupid = $groupid;

        return $this;
    }

    /**
     * Get groupid
     *
     * @return integer
     */
    public function getGroupid()
    {
        return $this->groupid;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return TplTemplatetypes
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set referencename
     *
     * @param string $referencename
     * @return TplTemplatetypes
     */
    public function setReferencename($referencename)
    {
        $this->referencename = $referencename;

        return $this;
    }

    /**
     * Get referencename
     *
     * @return string
     */
    public function getReferencename()
    {
        return $this->referencename;
    }

    /**
     * Set referenceentity
     *
     * @param string $referenceentity
     * @return TplTemplatetypes
     */
    public function setReferenceentity($referenceentity)
    {
        $this->referenceentity = $referenceentity;

        return $this;
    }

    /**
     * Get referenceentity
     *
     * @return string
     */
    public function getReferenceentity()
    {
        return $this->referenceentity;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return TplTemplatetypes
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set deleted
     *
     * @param boolean $deleted
     * @return TplTemplatetypes
     */
    public function setDeleted($deleted)
    {
        $this->deleted = $deleted;

        return $this;
    }

    /**
     * Get deleted
     *
     * @return boolean
     */
    public function getDeleted()
    {
        return $this->deleted;
    }

    /**
     * Set datlastchange
     *
     * @param \DateTime $datlastchange
     * @return TplTemplatetypes
     */
    public function setDatlastchange($datlastchange)
    {
        $this->datlastchange = $datlastchange;

        return $this;
    }

    /**
     * Get datlastchange
     *
     * @return \DateTime
     */
    public function getDatlastchange()
    {
        return $this->datlastchange;
    }
}


text:
<action>
    <field name="string">General Ledger Details</field>
    <field name="view_cls">report</field>
    <field name="model">report.gl.details</field>
    <field name="report_template">report_gl_details</field>
    <field name="report_template_xls">account_gl_detail</field>
    <field name="fast_render">1</field>
    <field name="menu">account_menu</field>
</action>