text:
param([switch]$NoVersionWarn, [switch]$ForcePoshGitPrompt)

& $PSScriptRoot\CheckRequirements.ps1 > $null

. $PSScriptRoot\ConsoleMode.ps1
. $PSScriptRoot\Utils.ps1
. $PSScriptRoot\AnsiUtils.ps1
. $PSScriptRoot\PoshGitTypes.ps1
. $PSScriptRoot\GitUtils.ps1
. $PSScriptRoot\GitPrompt.ps1
. $PSScriptRoot\GitParamTabExpansion.ps1
. $PSScriptRoot\GitTabExpansion.ps1
. $PSScriptRoot\TortoiseGit.ps1
. $PSScriptRoot\SshUtils.ps1

if (!$Env:HOME) { $Env:HOME = "$Env:HOMEDRIVE$Env:HOMEPATH" }
if (!$Env:HOME) { $Env:HOME = "$Env:USERPROFILE" }

$IsAdmin = Test-Administrator

# Probe $Host.UI.RawUI.WindowTitle to see if it can be set without errors
$WindowTitleSupported = $false
try {
    $global:PreviousWindowTitle = $Host.UI.RawUI.WindowTitle
    $newTitle = "${global:PreviousWindowTitle} "
    $Host.UI.RawUI.WindowTitle = $newTitle
    $WindowTitleSupported = ($Host.UI.RawUI.WindowTitle -eq $newTitle)
    $Host.UI.RawUI.WindowTitle = $global:PreviousWindowTitle
}
catch {
    Write-Debug "Probing for WindowTitleSupported errored: $_"
}

# Get the default prompt definition.
$initialSessionState = [Runspace]::DefaultRunspace.InitialSessionState
if (!$initialSessionState.Commands -or !$initialSessionState.Commands['prompt']) {
    $defaultPromptDef = "`$(if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' }) + 'PS ' + `$(Get-Location) + `$(if (`$nestedpromptlevel -ge 1) { '>>' }) + '> '"
}
else {
    $defaultPromptDef = $initialSessionState.Commands['prompt'].Definition
}

# The built-in posh-git prompt function in ScriptBlock form.
$GitPromptScriptBlock = {
    $settings = $global:GitPromptSettings
    if (!$settings) {
        if ($WindowTitleSupported -and $global:PreviousWindowTitle) {
            $Host.UI.RawUI.WindowTitle = $global:PreviousWindowTitle
        }

        return "<`$GitPromptSettings not found> "
    }

    if ($settings.DefaultPromptEnableTiming) {
        $sw = [System.Diagnostics.Stopwatch]::StartNew()
    }

    $origLastExitCode = $global:LASTEXITCODE

    # Construct/write the prompt text
    $prompt = ''

    # Write default prompt prefix
    $prompt += Write-Prompt $settings.DefaultPromptPrefix.Expand()

    # Get the current path - formatted correctly
    $promptPath = $settings.DefaultPromptPath.Expand()

    # Write the path and Git status summary information
    if ($settings.DefaultPromptWriteStatusFirst) {
        $prompt += Write-VcsStatus
        $prompt += Write-Prompt $promptPath
    }
    else {
        $prompt += Write-Prompt $promptPath
        $prompt += Write-VcsStatus
    }

    # Write default prompt before suffix text
    $prompt += Write-Prompt $settings.DefaultPromptBeforeSuffix.Expand()

    # If stopped in the debugger, the prompt needs to indicate that by writing default propmt debug
    if ((Test-Path Variable:/PSDebugContext) -or [runspace]::DefaultRunspace.Debugger.InBreakpoint) {
        $prompt += Write-Prompt $settings.DefaultPromptDebug.Expand()
    }

    # Get the prompt suffix text
    $promptSuffix = $settings.DefaultPromptSuffix.Expand()

    # When using Write-Host, we return a single space from this function to prevent PowerShell from displaying "PS>"
    # So to avoid two spaces at the end of the suffix, remove one here if it exists
    if (!$settings.AnsiConsole -and $promptSuffix.Text.EndsWith(' ')) {
        $promptSuffix.Text = $promptSuffix.Text.Substring(0, $promptSuffix.Text.Length - 1)
    }

    # Update the host's WindowTitle is host supports it and user has not disabled $GitPromptSettings.WindowTitle
    # This has to be *after* the call to Write-VcsStatus, which populates $global:GitStatus
    if ($WindowTitleSupported) {
        $windowTitle = $settings.WindowTitle
        if (!$windowTitle) {
            if ($global:PreviousWindowTitle) {
                $Host.UI.RawUI.WindowTitle = $global:PreviousWindowTitle
            }
        }
        else {
            try {
                if ($windowTitle -is [scriptblock]) {
                    $windowTitleText = & $windowTitle $global:GitStatus $IsAdmin
                }
                else {
                    $windowTitleText = $ExecutionContext.SessionState.InvokeCommand.ExpandString("$windowTitle")
                }

                # Put $windowTitleText in a string to ensure results returned by scriptblock are flattened to a string
                $Host.UI.RawUI.WindowTitle = "$windowTitleText"
            }
            catch {
                if ($global:PreviousWindowTitle) {
                    $Host.UI.RawUI.WindowTitle = $global:PreviousWindowTitle
                }

                Write-Debug "Error occurred during evaluation of `$GitPromptSettings.WindowTitle: $_"
            }
        }
    }

    # If prompt timing enabled, write elapsed milliseconds
    if ($settings.DefaultPromptEnableTiming) {
        $timingInfo = [PoshGitTextSpan]::new($settings.DefaultPromptTimingFormat)
        $sw.Stop()
        $timingInfo.Text = $timingInfo.Text -f $sw.ElapsedMilliseconds
        $prompt += Write-Prompt $timingInfo
    }

    $prompt += Write-Prompt $promptSuffix

    # When using Write-Host, return at least a space to avoid "PS>" being unexpectedly displayed
    if (!$settings.AnsiConsole) {
        $prompt += " "
    }
    else {
        # If using ANSI, set this global to help debug ANSI issues
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssigments', '')]
        $global:PoshGitLastPrompt = EscapeAnsiString $prompt
    }

    $global:LASTEXITCODE = $origLastExitCode
    $prompt
}

$currentPromptDef = if ($funcInfo = Get-Command prompt -ErrorAction SilentlyContinue) { $funcInfo.Definition }

# If prompt matches pre-0.7 posh-git prompt, ignore it
$collapsedLegacyPrompt = '$realLASTEXITCODE = $LASTEXITCODE;Write-Host($pwd.ProviderPath) -nonewline;Write-VcsStatus;$global:LASTEXITCODE = $realLASTEXITCODE;return "> "'
if ($currentPromptDef -and (($currentPromptDef.Trim() -replace '[\r\n\t]+\s*',';') -eq $collapsedLegacyPrompt)) {
    Write-Warning 'Replacing old posh-git prompt. Did you copy profile.example.ps1 into $PROFILE?'
    $currentPromptDef = $null
}

if (!$currentPromptDef) {
    # HACK: If prompt is missing, create a global one we can overwrite with Set-Item
    function global:prompt { ' ' }
}

# If there is no prompt function or the prompt function is the default, replace the current prompt function definition
if ($ForcePoshGitPrompt -or !$currentPromptDef -or ($currentPromptDef -eq $defaultPromptDef)) {
    # Set the posh-git prompt as the default prompt
    Set-Item Function:\prompt -Value $GitPromptScriptBlock
}

# Install handler for removal/unload of the module
$ExecutionContext.SessionState.Module.OnRemove = {
    $global:VcsPromptStatuses = $global:VcsPromptStatuses | Where-Object { $_ -ne $PoshGitVcsPrompt }

    # Revert original WindowTitle
    if ($WindowTitleSupported -and $global:PreviousWindowTitle) {
        $Host.UI.RawUI.WindowTitle = $global:PreviousWindowTitle
    }

    # Check if the posh-git prompt function itself has been replaced. If so, do not restore the prompt function
    $promptDef = if ($funcInfo = Get-Command prompt -ErrorAction SilentlyContinue) { $funcInfo.Definition }
    if ($promptDef -eq $GitPromptScriptBlock) {
        Set-Item Function:\prompt -Value ([scriptblock]::Create($defaultPromptDef))
        return
    }

    Write-Warning 'If your prompt function uses any posh-git commands, it will cause posh-git to be re-imported every time your prompt function is invoked.'
}

$exportModuleMemberParams = @{
    Function = @(
        'Add-PoshGitToProfile',
        'Expand-GitCommand',
        'Format-GitBranchName',
        'Get-GitBranchStatusColor',
        'Get-GitDirectory',
        'Get-GitStatus',
        'Get-PromptPath',
        'Update-AllBranches',
        'Write-GitStatus',
        'Write-GitBranchName',
        'Write-GitBranchStatus',
        'Write-GitIndexStatus',
        'Write-GitStashCount',
        'Write-GitWorkingDirStatus',
        'Write-GitWorkingDirStatusSummary',
        'Write-Prompt',
        'Write-VcsStatus',
        'Get-SshAgent',
        'Start-SshAgent',
        'Stop-SshAgent',
        'Add-SshKey',
        'Get-SshPath',
        'TabExpansion',
        'tgit'
    )
    Variable = @(
        'GitPromptScriptBlock'
    )
}

Export-ModuleMember @exportModuleMemberParams


text:
import { DisplayProcessor } from "../display-processor";
import { CustomReporterResult } from "../spec-reporter";
import SuiteInfo = jasmine.SuiteInfo;
export declare type ProcessFunction = (displayProcessor: DisplayProcessor, object: ProcessObject, log: String) => String;
export declare type ProcessObject = SuiteInfo | CustomReporterResult;
export declare class Logger {
    private displayProcessors;
    private print;
    private indent;
    private currentIndent;
    private lastWasNewLine;
    constructor(displayProcessors: DisplayProcessor[], print: (line: String) => void);
    log(stuff: String): void;
    process(object: ProcessObject, processFunction: ProcessFunction): void;
    newLine(): void;
    resetIndent(): void;
    increaseIndent(): void;
    decreaseIndent(): void;
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hyracks.api.rewriter;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.tuple.Pair;

import org.apache.hyracks.api.dataflow.ActivityId;
import org.apache.hyracks.api.job.ActivityCluster;
import org.apache.hyracks.api.job.ActivityClusterGraph;
import org.apache.hyracks.api.job.ActivityClusterId;

/**
 * All the connectors in an OneToOneConnectedCluster are OneToOneConnectorDescriptors.
 *
 * @author yingyib
 */
public class OneToOneConnectedActivityCluster extends ActivityCluster {

    private static final long serialVersionUID = 1L;

    protected final Map<Integer, Pair<ActivityId, Integer>> clusterInputIndexMap = new HashMap<Integer, Pair<ActivityId, Integer>>();
    protected final Map<Integer, Pair<ActivityId, Integer>> clusterOutputIndexMap = new HashMap<Integer, Pair<ActivityId, Integer>>();
    protected final Map<Pair<ActivityId, Integer>, Integer> invertedClusterOutputIndexMap = new HashMap<Pair<ActivityId, Integer>, Integer>();
    protected final Map<Pair<ActivityId, Integer>, Integer> invertedClusterInputIndexMap = new HashMap<Pair<ActivityId, Integer>, Integer>();

    public OneToOneConnectedActivityCluster(ActivityClusterGraph acg, ActivityClusterId id) {
        super(acg, id);
    }

    /**
     * Set up the mapping of the cluster's output channel to an internal activity and its output channel
     *
     * @param clusterOutputIndex
     *            the output channel index for the cluster
     * @param activityId
     *            the id of the internal activity which produces the corresponding output
     * @param activityOutputIndex
     *            the output channel index of the internal activity which corresponds to the output channel of the cluster of activities
     */
    public void setClusterOutputIndex(int clusterOutputIndex, ActivityId activityId, int activityOutputIndex) {
        clusterOutputIndexMap.put(clusterOutputIndex, Pair.of(activityId, activityOutputIndex));
        invertedClusterOutputIndexMap.put(Pair.of(activityId, activityOutputIndex), clusterOutputIndex);
    }

    /**
     * get the an internal activity and its output channel of a cluster output channel
     *
     * @param clusterOutputIndex
     *            the output channel index for the cluster
     * @return a pair containing the activity id of the corresponding internal activity and the output channel index
     */
    public Pair<ActivityId, Integer> getActivityIdOutputIndex(int clusterOutputIndex) {
        return clusterOutputIndexMap.get(clusterOutputIndex);
    }

    /**
     * Set up the mapping of the cluster's input channel to an internal activity and input output channel
     *
     * @param clusterInputIndex
     *            the input channel index for the cluster
     * @param activityId
     *            the id of the internal activity which consumes the corresponding input
     * @param activityInputIndex
     *            the output channel index of the internal activity which corresponds to the input channel of the cluster of activities
     */
    public void setClusterInputIndex(int clusterInputIndex, ActivityId activityId, int activityInputIndex) {
        clusterInputIndexMap.put(clusterInputIndex, Pair.of(activityId, activityInputIndex));
        invertedClusterInputIndexMap.put(Pair.of(activityId, activityInputIndex), clusterInputIndex);
    }

    /**
     * get the an internal activity and its input channel of a cluster input channel
     *
     * @param clusterOutputIndex
     *            the output channel index for the cluster
     * @return a pair containing the activity id of the corresponding internal activity and the output channel index
     */
    public Pair<ActivityId, Integer> getActivityIdInputIndex(int clusterInputIndex) {
        return clusterInputIndexMap.get(clusterInputIndex);
    }

    /**
     * Get the cluster input channel of an input-boundary activity and its input channel
     *
     * @param activityInputChannel
     *            the input-boundary activity and its input channel
     * @return the cluster input channel
     */
    public int getClusterInputIndex(Pair<ActivityId, Integer> activityInputChannel) {
        Integer channel = invertedClusterInputIndexMap.get(activityInputChannel);
        return channel == null ? -1 : channel;
    }

    /**
     * Get the cluster output channel of an input-boundary activity and its output channel
     *
     * @param activityOutputChannel
     *            the output-boundary activity and its output channel
     * @return the cluster output channel
     */
    public int getClusterOutputIndex(Pair<ActivityId, Integer> activityOutputChannel) {
        Integer channel = invertedClusterOutputIndexMap.get(activityOutputChannel);
        return channel == null ? -1 : channel;
    }

}


text:
class PupaError(Exception):
    """ Base class for exceptions from within Pupa """

class PupaInternalError(PupaError):
    """ Indication something went wrong inside of Pupa that never should happen """

class CommandError(PupaError):
    """ Errors from within pupa CLI """

# import-related errors

class DataImportError(PupaError):
    """ A generic error related to the import process. """

class InvalidVoteEventError(DataImportError):
    """ Attempt to create a vote event without an identifier or bill_id """

class NoMembershipsError(DataImportError):
    """ An attempt was made to import a person without any memberships. """

    def __init__(self, ids):
        super(NoMembershipsError, self).__init__('no memberships for {} people: \n{}'.format(
            len(ids), ', '.join(ids))
        )

class SameNameError(DataImportError):
    """ Attempt was made to import two people with the same name. """

    def __init__(self, name):
        super(SameNameError, self).__init__('multiple people with same name "{}" in Jurisdiction '
                                            '- must provide birth_date to disambiguate'
                                            .format(name))

class SameOrgNameError(DataImportError):
    """ Attempt was made to import two orgs with the same name. """

    def __init__(self, name):
        super(SameOrgNameError, self).__init__('multiple orgs with same name "{}" in Jurisdiction '
                                               .format(name))

class DuplicateItemError(DataImportError):
    """ Attempt was made to import items that resolve to the same database item. """

    def __init__(self, data, obj, data_sources=None):
        super(DuplicateItemError, self).__init__(
            'attempt to import data that would conflict with '
            'data already in the import: {} '
            '(already imported as {})\n'
            'obj1 sources: {}\nobj2 sources: {}'.format(
                data,
                obj,
                list(obj.sources.values_list('url', flat=True)
                     if hasattr(obj, 'sources') else []),
                [s['url'] for s in data_sources or []]
            ))

class UnresolvedIdError(DataImportError):
    """ Attempt was made to resolve an id that has no result. """

# scrape-related errors

class ScrapeError(PupaError):
    """ A generic error related to the scrape process. """

class ScrapeValueError(PupaError, ValueError):
    """ An invalid value was passed to a pupa scrape object. """


text:
using gaxgrpc = Google.Api.Gax.Grpc;
using gpr = Google.Protobuf.Reflection;
using scg = System.Collections.Generic;

namespace Google.Cloud.Container.V1
{
    /// Static class to provide common access to package-wide API metadata.
    internal static class PackageApiMetadata
    {
        /// The <see cref="gaxgrpc::ApiMetadata"/> for services in this package.
        internal static gaxgrpc::ApiMetadata ApiMetadata { get; } = new gaxgrpc::ApiMetadata("Google.Cloud.Container.V1", GetFileDescriptors);

        private static scg::IEnumerable<gpr::FileDescriptor> GetFileDescriptors()
        {
            yield return ClusterServiceReflection.Descriptor;
        }
    }
}


text:
import * as Promise from 'bluebird';
import GetPartitionsCodec = require('./codec/GetPartitionsCodec');
import ClientMessage = require('./ClientMessage');
import Address = require('./Address');
import HazelcastClient from './HazelcastClient';

class PartitionService {

    private client: HazelcastClient;
    private partitionMap: {[partitionId: number]: Address};
    private partitionCount: number;

    constructor(client: HazelcastClient) {
        this.client = client;
    }

    initialize(): Promise<PartitionService> {
        return this.refresh().then(() => {
            return this;
        });
    }

    /**
     * Refreshes the internal partition table.
     */
    refresh(): Promise<void> {
        var ownerConnection = this.client.getClusterService().getOwnerConnection();
        var clientMessage: ClientMessage = GetPartitionsCodec.encodeRequest();

        return this.client.getInvocationService()
            .invokeOnConnection(ownerConnection, clientMessage)
            .then((clientMessage: ClientMessage) => {
                this.partitionMap = GetPartitionsCodec.decodeResponse(clientMessage);
                this.partitionCount = Object.keys(this.partitionMap).length;
            });
    };

    /**
     * Returns the {@link Address} of the node which owns given partition id.
     * @param partitionId
     * @returns the address of the node.
     */
    getAddressForPartition(partitionId: number): Address {
        return this.partitionMap[partitionId];
    }

    /**
     * Computes the partition id for a given key.
     * @param key
     * @returns the partition id.
     */
    getPartitionId(key: any) {
        var partitionHash: number;
        if (typeof key === 'object' && 'getPartitionHash' in key) {
            partitionHash = key.getPartitionHash();
        } else {
            partitionHash = this.client.getSerializationService().toData(key).getPartitionHash();
        }
        return Math.abs(partitionHash) % this.partitionCount;
    }
}

export = PartitionService;


text:
#pragma once
//-------------------------------------------------------------------------------------------------
// <copyright file="thmutil.h" company="Outercurve Foundation">
//   Copyright (c) 2004, Outercurve Foundation.
//   This software is released under Microsoft Reciprocal License (MS-RL).
//   The license and further copyright text can be found in the file
//   LICENSE.TXT at the root directory of the distribution.
// </copyright>
//
// <summary>
//  Theme helper functions.
// </summary>
//-------------------------------------------------------------------------------------------------

#ifdef __cplusplus
extern "C" {
#endif

#define ReleaseTheme(p) if (p) { ThemeFree(p); p = NULL; }

typedef enum THEME_CONTROL_DATA
{
    THEME_CONTROL_DATA_HOVER = 1,
} THEME_CONTROL_DATA;

typedef enum THEME_CONTROL_TYPE
{
    THEME_CONTROL_TYPE_UNKNOWN,
    THEME_CONTROL_TYPE_BILLBOARD,
    THEME_CONTROL_TYPE_BUTTON,
    THEME_CONTROL_TYPE_CHECKBOX,
    THEME_CONTROL_TYPE_EDITBOX,
    THEME_CONTROL_TYPE_HYPERLINK,
    THEME_CONTROL_TYPE_HYPERTEXT,
    THEME_CONTROL_TYPE_IMAGE,
    THEME_CONTROL_TYPE_PROGRESSBAR,
    THEME_CONTROL_TYPE_RICHEDIT,
    THEME_CONTROL_TYPE_STATIC,
    THEME_CONTROL_TYPE_TEXT,
    THEME_CONTROL_TYPE_LISTVIEW,
    THEME_CONTROL_TYPE_TREEVIEW,
    THEME_CONTROL_TYPE_TAB,
} THEME_CONTROL_TYPE;

struct THEME_BILLBOARD
{
    HBITMAP hImage;
    LPWSTR sczUrl;
};

struct THEME_COLUMN
{
    LPWSTR pszName;
    UINT uStringId;
    int nWidth;
};

struct THEME_TAB
{
    LPWSTR pszName;
    UINT uStringId;
};

// THEME_ASSIGN_CONTROL_ID - Used to apply a specific id to a named control (usually
//                           to set the WM_COMMAND).
struct THEME_ASSIGN_CONTROL_ID
{
    WORD wId;       // id to apply to control
    LPCWSTR wzName; // name of control to match
};

const DWORD THEME_FIRST_ASSIGN_CONTROL_ID = 1024; // Recommended first control id to be assigned.

struct THEME_CONTROL
{
    THEME_CONTROL_TYPE type;

    WORD wId;
    WORD wPageId;

    LPWSTR sczName; // optional name for control, only used to apply control id.
    LPWSTR sczText;
    int nX;
    int nY;
    int nHeight;
    int nWidth;
    int nSourceX;
    int nSourceY;
    UINT uStringId;

    HBITMAP hImage;

    // Don't free these; it's just a handle to the central image lists stored in THEME. The handle is freed once, there.
    HIMAGELIST rghImageList[4];

    DWORD dwStyle;
    DWORD dwExtendedStyle;
    DWORD dwInternalStyle;

    DWORD dwFontId;
    DWORD dwFontHoverId;
    DWORD dwFontSelectedId;

    // Used by billboard controls
    THEME_BILLBOARD* ptbBillboards;
    DWORD cBillboards;
    WORD wBillboardInterval;
    WORD wBillboardUrls;
    BOOL fBillboardLoops;

    // Used by listview controls
    THEME_COLUMN *ptcColumns;
    DWORD cColumns;

    // Used by tab controls
    THEME_TAB *pttTabs;
    DWORD cTabs;

    // state variables that should be ignored
    HWND hWnd;
    DWORD dwData; // type specific data
};

struct THEME_IMAGELIST
{
    LPWSTR sczName;

    HIMAGELIST hImageList;
};

struct THEME_PAGE
{
    WORD wId;
    LPWSTR sczName;

    DWORD cControlIndices;
    DWORD* rgdwControlIndices;
};

struct THEME_FONT
{
    HFONT hFont;
    COLORREF crForeground;
    HBRUSH hForeground;
    COLORREF crBackground;
    HBRUSH hBackground;
};

struct THEME
{
    WORD wId;

    DWORD dwStyle;
    DWORD dwFontId;
    HANDLE hIcon;
    LPWSTR sczCaption;
    int nHeight;
    int nWidth;
    int nSourceX;
    int nSourceY;
    UINT uStringId;

    HBITMAP hImage;

    DWORD cFonts;
    THEME_FONT* rgFonts;

    DWORD cPages;
    THEME_PAGE* rgPages;

    DWORD cImageLists;
    THEME_IMAGELIST* rgImageLists;

    DWORD cControls;
    THEME_CONTROL* rgControls;

    // state variables that should be ignored
    HWND hwndParent; // parent for loaded controls
    HWND hwndHover; // current hwnd hovered over
};

/********************************************************************
 ThemeInitialize - initialized theme management.

*******************************************************************/
DAPI_(HRESULT) ThemeInitialize(
    __in_opt HMODULE hModule
    );

/********************************************************************
 ThemeUninitialize - unitialize theme management.

*******************************************************************/
DAPI_(void) ThemeUninitialize();

/********************************************************************
 ThemeLoadFromFile - loads a theme from a loose file.

 *******************************************************************/
DAPI_(HRESULT) ThemeLoadFromFile(
    __in_z LPCWSTR wzThemeFile,
    __out THEME** ppTheme
    );

/********************************************************************
 ThemeLoadFromResource - loads a theme from a module's data resource.

 NOTE: The resource data must be UTF-8 encoded.
*******************************************************************/
DAPI_(HRESULT) ThemeLoadFromResource(
    __in_opt HMODULE hModule,
    __in_z LPCSTR szResource,
    __out THEME** ppTheme
    );

/********************************************************************
 ThemeFree - frees any memory associated with a theme.

*******************************************************************/
DAPI_(void) ThemeFree(
    __in THEME* pTheme
    );

/********************************************************************
 ThemeLoadControls - creates the windows for all the theme controls.

*******************************************************************/
DAPI_(HRESULT) ThemeLoadControls(
    __in THEME* pTheme,
    __in HWND hwndParent,
    __in_ecount_opt(cAssignControlIds) const THEME_ASSIGN_CONTROL_ID* rgAssignControlIds,
    __in DWORD cAssignControlIds
    );

/********************************************************************
 ThemeUnloadControls - resets all the theme control windows so the theme
                       controls can be reloaded.

*******************************************************************/
DAPI_(void) ThemeUnloadControls(
    __in THEME* pTheme
    );

/********************************************************************
 ThemeLocalize - Localizes all of the strings in the them.

*******************************************************************/
DAPI_(HRESULT) ThemeLocalize(
    __in THEME *pTheme,
    __in const WIX_LOCALIZATION *pLocStringSet
    );

DAPI_(HRESULT) ThemeLoadStrings(
    __in THEME* pTheme,
    __in HMODULE hResModule
    );

/********************************************************************
 ThemeLoadRichEditFromFile - Attach a richedit control to a RTF file.

 *******************************************************************/
DAPI_(HRESULT) ThemeLoadRichEditFromFile(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in_z LPCWSTR wzFileName,
    __in HMODULE hModule
    );

/********************************************************************
 ThemeLoadRichEditFromResource - Attach a richedit control to resource data.

 *******************************************************************/
DAPI_(HRESULT) ThemeLoadRichEditFromResource(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in_z LPCSTR szResourceName,
    __in HMODULE hModule
    );

/********************************************************************
 ThemeLoadRichEditFromResourceToHWnd - Attach a richedit control (by
                                       HWND) to resource data.

 *******************************************************************/
DAPI_(HRESULT) ThemeLoadRichEditFromResourceToHWnd(
    __in HWND hWnd,
    __in_z LPCSTR szResourceName,
    __in HMODULE hModule
    );

/********************************************************************
 ThemeHandleKeyboardMessage - will translate the message using the active
                             accelerator table.

*******************************************************************/
DAPI_(BOOL) ThemeHandleKeyboardMessage(
    __in_opt THEME* pTheme,
    __in HWND hWnd,
    __in MSG* pMsg
    );

/********************************************************************
 ThemeDefWindowProc - replacement for DefWindowProc() when using theme.

*******************************************************************/
LRESULT CALLBACK ThemeDefWindowProc(
    __in_opt THEME* pTheme,
    __in HWND hWnd,
    __in UINT uMsg,
    __in WPARAM wParam,
    __in LPARAM lParam
    );

/********************************************************************
 ThemeGetPageIds - gets the page ids for the theme via page names.

*******************************************************************/
DAPI_(void) ThemeGetPageIds(
    __in const THEME* pTheme,
    __in_ecount(cGetPages) LPCWSTR* rgwzFindNames,
    __in_ecount(cGetPages) DWORD* rgdwPageIds,
    __in DWORD cGetPages
    );

/********************************************************************
 ThemeGetPage - gets a theme page by id.

 *******************************************************************/
DAPI_(THEME_PAGE*) ThemeGetPage(
    __in const THEME* pTheme,
    __in DWORD dwPage
    );

/********************************************************************
 ThemeShowPage - shows or hides all of the controls in the page at one time.

 *******************************************************************/
DAPI_(void) ThemeShowPage(
    __in THEME* pTheme,
    __in DWORD dwPage,
    __in int nCmdShow
    );

/********************************************************************
 ThemeControlExists - check if a control with the specified id exists.

 *******************************************************************/
DAPI_(BOOL) ThemeControlExists(
    __in THEME* pTheme,
    __in DWORD dwControl
    );

/********************************************************************
 ThemeControlEnable - enables/disables a control.

 *******************************************************************/
DAPI_(void) ThemeControlEnable(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in BOOL fEnable
    );

/********************************************************************
 ThemeControlEnabled - returns whether a control is enabled/disabled.

 *******************************************************************/
DAPI_(BOOL) ThemeControlEnabled(
    __in THEME* pTheme,
    __in DWORD dwControl
    );

/********************************************************************
 ThemeControlElevates - sets/removes the shield icon on a control.

 *******************************************************************/
DAPI_(void) ThemeControlElevates(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in BOOL fElevates
    );

/********************************************************************
 ThemeShowControl - shows/hides a control.

 *******************************************************************/
DAPI_(void) ThemeShowControl(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in int nCmdShow
    );

/********************************************************************
 ThemeControlVisible - returns whether a control is visible.

 *******************************************************************/
DAPI_(BOOL) ThemeControlVisible(
    __in THEME* pTheme,
    __in DWORD dwControl
    );

DAPI_(BOOL) ThemePostControlMessage(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in UINT Msg,
    __in WPARAM wParam,
    __in LPARAM lParam
    );

DAPI_(LRESULT) ThemeSendControlMessage(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in UINT Msg,
    __in WPARAM wParam,
    __in LPARAM lParam
    );

/********************************************************************
 ThemeDrawBackground - draws the theme background.

*******************************************************************/
DAPI_(HRESULT) ThemeDrawBackground(
    __in THEME* pTheme,
    __in PAINTSTRUCT* pps
    );

/********************************************************************
 ThemeDrawControl - draw an owner drawn control.

*******************************************************************/
DAPI_(HRESULT) ThemeDrawControl(
    __in THEME* pTheme,
    __in DRAWITEMSTRUCT* pdis
    );

/********************************************************************
 ThemeHoverControl - mark a control as hover.

*******************************************************************/
DAPI_(BOOL) ThemeHoverControl(
    __in THEME* pTheme,
    __in HWND hwndParent,
    __in HWND hwndControl
    );

/********************************************************************
 ThemeIsControlChecked - gets whether a control is checked. Only
                         really useful for checkbox controls.

*******************************************************************/
DAPI_(BOOL) ThemeIsControlChecked(
    __in THEME* pTheme,
    __in DWORD dwControl
    );

/********************************************************************
 ThemeSetControlColor - sets the color of text for a control.

*******************************************************************/
DAPI_(BOOL) ThemeSetControlColor(
    __in THEME* pTheme,
    __in HDC hdc,
    __in HWND hWnd,
    __out HBRUSH* phBackgroundBrush
    );

/********************************************************************
 ThemeStartBillboard - starts a billboard control changing images according
                       to their interval.

 NOTE: iImage specifies the image to start on. If iImage is
       greater than the number of images, the last image shown
       will be the start image.
*******************************************************************/
DAPI_(HRESULT) ThemeStartBillboard(
    __in const THEME* pTheme,
    __in DWORD dwControl,
    __in WORD iImage
    );

/********************************************************************
 ThemeStopBillboard - stops a billboard control from changing images.

*******************************************************************/
DAPI_(HRESULT) ThemeStopBillboard(
    __in const THEME* pTheme,
    __in DWORD dwControl
    );

/********************************************************************
 ThemeSetProgressControl - sets the current percentage complete in a
                           progress bar control.

*******************************************************************/
DAPI_(HRESULT) ThemeSetProgressControl(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in DWORD dwProgressPercentage
    );

/********************************************************************
 ThemeSetProgressControlColor - sets the current color of a
                                progress bar control.

*******************************************************************/
DAPI_(HRESULT) ThemeSetProgressControlColor(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in DWORD dwColorIndex
    );

/********************************************************************
 ThemeSetTextControl - sets the text of a control.

*******************************************************************/
DAPI_(HRESULT) ThemeSetTextControl(
    __in THEME* pTheme,
    __in DWORD dwControl,
    __in_z LPCWSTR wzText
    );

/********************************************************************
 ThemeGetTextControl - gets the text of a control.

*******************************************************************/
DAPI_(HRESULT) ThemeGetTextControl(
    __in const THEME* pTheme,
    __in DWORD dwControl,
    __out LPWSTR* psczText
    );

/********************************************************************
 ThemeUpdateCaption - updates the caption in the theme.

*******************************************************************/
DAPI_(HRESULT) ThemeUpdateCaption(
    __in THEME* pTheme,
    __in_z LPCWSTR wzCaption
    );

/********************************************************************
 ThemeSetFocus - set the focus to the control supplied or the next
                 enabled control if it is disabled.

*******************************************************************/
DAPI_(void) ThemeSetFocus(
    __in THEME* pTheme,
    __in DWORD dwControl
    );

#ifdef __cplusplus
}
#endif


text:
package ucesoft.cbm.vic20

import ucesoft.cbm.ChipID.ID
import ucesoft.cbm.cpu.{RAMComponent, ROM}
import ucesoft.cbm.expansion.vic20.VIC20ExpansionPort
import ucesoft.cbm.formats.Cartridge
import ucesoft.cbm.misc.TestCart
import ucesoft.cbm.peripheral.drive.VIA
import ucesoft.cbm.peripheral.vic.{VICType, VIC_I}
import ucesoft.cbm.{CBMComponentType, ChipID}

import java.io.{ObjectInputStream, ObjectOutputStream}

object VIC20MMU {
  val KERNAL_PAL_ROM = new ROM(null, "KernalPal", 0, 8192, ROM.VIC20_KERNAL_PAL_ROM_PROP)
  val KERNAL_NTSC_ROM = new ROM(null, "KernalNtsc", 0, 8192, ROM.VIC20_KERNAL_NTSC_ROM_PROP)
  val BASIC_ROM = new ROM(null, "Basic", 0, 8192, ROM.VIC20_BASIC_ROM_PROP)
  val CHAR_ROM = new ROM(null, "Char", 0, 4096, ROM.VIC20_CHAR_ROM_PROP)

  final val NO_EXP   = 0
  final val EXP_BLK0 = 1
  final val EXP_BLK1 = 2
  final val EXP_BLK2 = 4
  final val EXP_BLK3 = 8
  final val EXP_BLK5 = 16

  def parseConfig(config:String,updateMemoryConfig: Int => Unit): Unit = {
    if (!config.isEmpty) {
      val blocks = config.split(",").map(_.toUpperCase() match {
        case "400" => VIC20MMU.EXP_BLK0
        case "2000" => VIC20MMU.EXP_BLK1
        case "4000" => VIC20MMU.EXP_BLK2
        case "6000" => VIC20MMU.EXP_BLK3
        case "A000" => VIC20MMU.EXP_BLK5
        case _ => VIC20MMU.NO_EXP
      }).reduce(_ | _)

      updateMemoryConfig(blocks)
    }
  }

  def getStringConfig(config:Int,blocks:Boolean = false,sep:String = ","): String = {
    val labels = if (blocks) Array("B0","B1","B2","B3","B5") else Array("400","2000","4000","6000","A000")
    Array(EXP_BLK0,EXP_BLK1,EXP_BLK2,EXP_BLK3,EXP_BLK5).zip(labels).flatMap { e =>
      if ((config & e._1) > 0) Some(e._2) else None
    }.mkString(sep)
  }

  def getLabelConfig(config:Int): String = {
    if (config == NO_EXP) ""
    else if (config == EXP_BLK0) "3K"
    else if (config == EXP_BLK1) "8K"
    else if (config == (EXP_BLK1 | EXP_BLK2)) "16K"
    else if (config == (EXP_BLK1 | EXP_BLK2 | EXP_BLK3)) "24K"
    else getStringConfig(config,true,"|")
  }
}

class VIC20MMU extends RAMComponent {
  import VIC20MMU._

  override val isRom = false
  override val length: Int = 0x10000
  override val startAddress = 0
  override val name = "VIC20MMU"
  override def isActive = true
  override val componentID: String = "VIC20MMU"
  override val componentType = CBMComponentType.MEMORY

  private trait RW {
    def read(address:Int,chipID: ID): Int
    def write(address: Int, value: Int): Unit
  }

  private val memRW = Array.ofDim[RW](0x10000)
  private val ram = Array.ofDim[Int](0x10000)
  private var basicROM : Array[Int] = _
  private var kernelROM_PAL,kernelROM_NTSC,kernelROM : Array[Int] = _
  private var charROM : Array[Int] = _
  /*
    Index   Memory
    0       0400 - 0FFF
    1       2000 - 3FFF
    2       4000 - 5FFF
    3       6000 - 7FFF
    4       A000 - BFFF
   */
  private val expansionBlocks = Array(
    new EXPRAM_BLOCK_RW(0x400),
    new EXPRAM_BLOCK_RW(0x2000),
    new EXPRAM_BLOCK_RW(0x4000),
    new EXPRAM_BLOCK_RW(0x6000),
    new EXPRAM_BLOCK_RW(0xA000)
  )
  private val ioBlocks = Array(
    new IOBLOCK_RW(),
    new IOBLOCK_RW()
  )
  private val expansionBlockMAP = expansionBlocks map { e => (e.address,e) } toMap
  private var lastByteOnBUS = 0
  private var dontUpdateLastByteOnBUS = false

  private var via1,via2 : VIA = _
  private var vic : VIC_I = _

  private var carts : List[Cartridge] = Nil
  private var specialCart: VIC20ExpansionPort = _

  private var vicType: VICType.Value = VICType.PAL

  // Constructor
  setExpansion(NO_EXP)

  def setVICType(vicModel:VICType.Value): Unit = {
    this.vicType = vicModel
    kernelROM = vicType match {
      case VICType.PAL => kernelROM_PAL
      case VICType.NTSC => kernelROM_NTSC
    }
  }

  def setBasicROM(rom:Array[Int]): Unit = basicROM = rom
  def setKernelPALROM(rom:Array[Int]): Unit = kernelROM_PAL = rom
  def setKernelNTSCROM(rom: Array[Int]): Unit = kernelROM_NTSC = rom
  def setCharROM(rom:Array[Int]): Unit = charROM = rom

  def setIO2RAM(enabled:Boolean): Unit = ioBlocks(0).enabled = enabled
  def setIO3RAM(enabled:Boolean): Unit = ioBlocks(1).enabled = enabled
  def isIO2RAMEnabled(): Boolean = ioBlocks(0).enabled
  def isIO3RAMEnabled(): Boolean = ioBlocks(1).enabled

  def setExpansion(exp:Int): Unit = {
    var b = 0
    while (b < 5) {
      val enabled = (exp & (1 << b)) > 0
      expansionBlocks(b).enabled = enabled
      if (enabled && expansionBlocks(b).hasROM()) expansionBlocks(b).removeROM()
      b += 1
    }
  }

  def getExpansionSettings(): Int = {
    var e = 0
    var i = 0
    while (i < 5) {
      if (expansionBlocks(i).enabled) e |= 1 << i
      i += 1
    }
    e
  }

  def attachCart(crt:Cartridge): Boolean = {
    for (chip <- crt.chips) {
      expansionBlockMAP get chip.startingLoadAddress match {
        case Some(exp) =>
          if (exp.hasROM()) return false
          exp.setROM(chip.romData)
        case None =>
          return false
      }
    }
    carts ::= crt
    true
  }

  def attachSpecialCart(cart:VIC20ExpansionPort): Unit = {
    if (specialCart != null) specialCart.eject()
    specialCart = cart
  }
  def detachSpecialCart(): Unit = {
    if (specialCart != null) specialCart.eject()
    specialCart = null
  }

  def detachAllCarts(): Unit = {
    for(e <- expansionBlocks) e.removeROM()
    carts = Nil
  }

  def getAttachedCarts(): List[Cartridge] = carts
  def getAttachedSpecialCart(): Option[VIC20ExpansionPort] = Option(specialCart)

  def setIO(via1:VIA,via2:VIA,vic:VIC_I): Unit = {
    this.via1 = via1
    this.via2 = via2
    this.vic = vic
  }

  private object BASICROM_RW extends RW {
    override def read(address: Int, chipID: ID): Int = basicROM(address & 0x1FFF)
    override def write(address: Int, value: Int): Unit = {}
  }
  private object KERNELROM_RW extends RW {
    override def read(address: Int, chipID: ID): Int = kernelROM(address & 0x1FFF)
    override def write(address: Int, value: Int): Unit = {}
  }
  private object CHARROM_RW extends RW {
    override def read(address: Int, chipID: ID): Int = charROM(address & 0xFFF)
    override def write(address: Int, value: Int): Unit = {}
  }

  private object RAM_RW extends RW {
    override def read(address: Int, chipID: ID): Int = ram(address & 0xFFFF)
    override def write(address: Int, value: Int): Unit = ram(address & 0xFFFF) = value
  }
  private object COLOR_RW extends RW {
    override def read(address: Int, chipID: ID): Int = {
      val color = ram(address & 0xFFFF) & 0xF
      if (chipID == ChipID.VIC) {
        dontUpdateLastByteOnBUS = true
        color
      }
      else lastByteOnBUS & 0xF0 | color
    }
    override def write(address: Int, value: Int): Unit = ram(address & 0xFFFF) = value & 0xF
  }
  private class EXPRAM_BLOCK_RW(val address:Int) extends RW {
    private var rom : Array[Int] = _
    var enabled = false

    def setROM(rom:Array[Int]): Unit = this.rom = rom
    def removeROM(): Unit = rom = null
    def hasROM(): Boolean = rom != null

    override def read(address: Int, chipID: ID): Int = {
      if (chipID == ChipID.VIC)
        lastByteOnBUS
      else {
        if (rom == null) {
          if (enabled) ram(address)
          else lastByteOnBUS
        }
        else rom(address % rom.length)
      }
    }
    override def write(address: Int, value: Int): Unit = {
      if (rom == null) {
        if (enabled) ram(address & 0xFFFF) = value
      }
    }
  }
  private class IOBLOCK_RW extends RW {
    var enabled = false
    override def read(address: Int, chipID: ID): Int = {
      if (enabled) ram(address) else lastByteOnBUS
    }
    override def write(address: Int, value: Int): Unit = {
      if (enabled) ram(address) = value
    }
  }
  private object VIC_RW extends RW {
    override def read(address: Int, chipID: ID): Int = vic.read(address)
    override def write(address: Int, value: Int): Unit = vic.write(address,value)
  }
  private object VIA1_VIA2_RW extends RW {
    override def read(address: Int, chipID: ID): Int = {
      if ((address & 0x30) == 0) lastByteOnBUS
      else {
        var tmp = 0xFF
        if ((address & 0x10) > 0) tmp = via1.read(address)
        if ((address & 0x20) > 0) tmp = via2.read(address)
        tmp
      }
    }
    override def write(address: Int, value: Int): Unit = {
      if ((address & 0x10) > 0) via1.write(address,value)
      if ((address & 0x20) > 0) via2.write(address,value)
    }
  }

  override def init(): Unit = {
    for(r <- 0 until 0x10000) {
      memRW(r) =
        if (r < 0x400) RAM_RW
        else if (r < 0x1000) expansionBlocks(0)
        else if (r < 0x2000) RAM_RW
        else if (r < 0x4000) expansionBlocks(1)
        else if (r < 0x6000) expansionBlocks(2)
        else if (r < 0x8000) expansionBlocks(3)
        else if (r < 0x9000) CHARROM_RW
        else if (r < 0x90FF) VIC_RW
        else if (r < 0x93FF) VIA1_VIA2_RW
        else if (r < 0x9800) COLOR_RW
        else if (r < 0x9C00) ioBlocks(0)
        else if (r < 0xA000) ioBlocks(1)
        else if (r < 0xC000) expansionBlocks(4)
        else if (r < 0xE000) BASICROM_RW
        else KERNELROM_RW
    }
  }

  final def clock(cycles:Long): Unit = {
    if (specialCart != null) specialCart.clock(cycles)
  }

  override def reset(): Unit = {
    if (specialCart != null) specialCart.reset()
  }

  override def hardReset(): Unit = {
    java.util.Arrays.fill(ram,0)
    /*
    for(e <- expansionBlocks) {
      e.removeROM()
    }
     */
    if (specialCart != null) specialCart.hardReset()
  }

  final override def read(address: Int, chipID: ID): Int = {
    if (specialCart != null) {
      specialCart.read(address) match {
        case None =>
        case Some(v) =>
          if (!dontUpdateLastByteOnBUS) lastByteOnBUS = v
          return v
      }
    }

    val read = memRW(address).read(address, chipID)
    if (!dontUpdateLastByteOnBUS) lastByteOnBUS = read
    dontUpdateLastByteOnBUS = false
    read
  }
  final override def write(address: Int, value: Int, chipID: ID): Unit = {
    TestCart.write(address, value)
    lastByteOnBUS = value

    if (specialCart != null) {
      if (specialCart.write(address,value)) return
    }
    memRW(address).write(address, value)
  }

  override protected def saveState(out: ObjectOutputStream): Unit = {
    out.writeObject(ram)
    out.writeInt(getExpansionSettings())
  }
  override protected def loadState(in: ObjectInputStream): Unit = {
    loadMemory(ram,in)
    setExpansion(in.readInt())
  }
  override protected def allowsStateRestoring: Boolean = true
}


text:
import { VNode } from 'snabbdom/vnode';
import h from 'snabbdom/h';

import {
  Renderable,
  ConfiguredRenderable,
  AddChildArgs,
  RenderableConfig,
  isTransferable,
  RemoveChildArgs
} from '../dom';
import { Inject, Optional, PostConstruct } from '../di';
import {
  XYDirection,
  ConfigurationRef,
  RenderableConstructorArg,
  UNALLOCATED,
  DragStatus,
  DragEvent,
  ContextType
} from '../common';
import { XYItemContainer, XYItemContainerConfig } from './XYItemContainer';
import { Draggable } from '../Draggable';
import { Splitter, SPLITTER_SIZE } from './Splitter';
import { get, isNumber, clamp, round } from '../utils';
import { Stack, StackItemContainer, STACK_CLASS } from '../stack';
import { XY_ITEM_CONTAINER_CLASS, SPLITTER_CLASS } from './common';
import { RenderableStateChangeEvent } from '../events/RenderableStateChangeEvent';

export interface XYContainerConfig extends RenderableConfig {
  /**
   * The size in pixels of the splitter.
   * @type {number}
   */
  splitterSize?: number;
  /**
   * Determines whether the Row or Column should persist when only a single item remains.
   * The default behavior is to unwrap and destroy the row or column.
   * @type {boolean}
   */
  static?: boolean;
  children: Array<XYItemContainerConfig|RenderableConstructorArg<XYItemContainer>>;
}

export interface XYSizingOptions {
  render?: boolean;
  resize?: boolean;
}

export interface ContainerAddChildArgs extends AddChildArgs {
  distribute?: boolean;
}

export type AdjacentResults = { before: XYItemContainer|null, after: XYItemContainer|null };

export const MAX_RATIO_DISTRIBUTION_ITERATIONS = 5;

export class XYContainer extends Renderable {
  protected _height: number = 0;
  protected _width: number = 0;
  protected _direction: XYDirection;
  protected _className: string;
  protected _contentItems: XYItemContainer[] = [];
  protected _splitters: Splitter[] = [];
  protected _dragLimitMin: number = 0;
  protected _dragLimitMax: number = 0;
  protected _container: Renderable|null;

  @Inject(ConfigurationRef)
  @Optional()
  protected _config: XYContainerConfig|null;

  @Inject(STACK_CLASS) protected _Stack: typeof Stack;
  @Inject(XY_ITEM_CONTAINER_CLASS) protected _XYItemContainer: typeof XYItemContainer;
  @Inject(SPLITTER_CLASS) protected _Splitter: typeof Splitter;

  get height(): number {
    return this._height;
  }

  get width(): number {
    return this._width;
  }

  get direction(): XYDirection {
    return this._direction;
  }

  get isRow(): boolean {
    return this.direction === XYDirection.X;
  }

  get splitters(): Splitter[] {
    return this._splitters;
  }

  get splitterSize(): number {
    return get(this._config, 'splitterSize', SPLITTER_SIZE);
  }

  get isStatic(): boolean {
    return get(this._config, 'static', false);
  }

  protected get _totalSplitterSize(): number {
    return this._splitters.reduce((result, splitter) => result + splitter.size, 0);
  }

  protected get _totalContainerSize(): number {
    if (!this._container) {
      return 0;
    }

    return this.isRow
      ? this._container.width - this._totalSplitterSize
      : this._container.height - this._totalSplitterSize;
  }

  @PostConstruct()
  initialize(): void {
    super.initialize();

    const children = this._config && this._config.children ? this._config.children : [];

    children.forEach(config => {
      const item = ConfiguredRenderable.isRenderableConstructor<XYItemContainer>(config)
        ? this.createChild(config)
        : this.createChildItem(config as any);

      return this.addChild(item, { render: false, resize: false });
    });

    this.scope(RenderableStateChangeEvent).subscribe(() => this.resize());
  }

  createChildItem(config: XYItemContainerConfig, options: { index?: number } = {}): XYItemContainer {
    return this.createChild(new ConfiguredRenderable(this._XYItemContainer, config));
  }

  addChild(item: Renderable, options: ContainerAddChildArgs = {}): void {
    const { resize = true } = options;
    const childArgs = Object.assign({}, options, { render: false, resize: false });
    let container: XYItemContainer;
    let transferConfig: { [key: string]: any } = {};

    if (isTransferable(item)) {
      transferConfig = item.getTransferableConfig(this);
    }

    // If this is an item container just add it.
    if (!(item instanceof XYItemContainer)) {
      if (item instanceof StackItemContainer) {
        item = this._createStackWrapper(item);
      }

      container = this.createChildItem({ ...transferConfig, use: item }, childArgs);

      item.setContainer(container);
    } else {
      container = item;
    }

    if (resize) {
      let newItemRatio;

      if (container.initialSize != null) {
        newItemRatio = (container.initialSize / this._totalContainerSize) * 100;
      } else {
        newItemRatio = (1 / (this._contentItems.length + 1)) * 100;
      }

      container.ratio = newItemRatio;

      for (const item of this._contentItems) {
        item.ratio = <number>item.ratio * ((100 - newItemRatio) / 100);
      }
    }

    while (this._splitters.length < this._contentItems.length) {
      this._splitters.push(this._createSplitter());
    }

    super.addChild(container, options);
  }

  removeChild(item: XYItemContainer, options: RemoveChildArgs = {}): void {
    const index = this._contentItems.indexOf(item);
    const { context = ContextType.NONE } = options;

    if (index === -1) {
      return;
    }

    const splitterIndex = clamp(index, 0, this._splitters.length - 1);
    const splitter = this._splitters[splitterIndex];

    if (splitter) {
      this._splitters.splice(splitterIndex, 1);
      splitter.destroy({ type: context });
    }

    super.removeChild(item, { render: false, context });

    if (this._contentItems.length === 1 && this.container && get(this._config, 'static') !== true) {
      const container = this._contentItems[0];
      const item = container.item;

      this._contentItems = [];
      this.container.replaceChild(this, item, { destroy: true, render: false, context });

      container.setContainer(null);
      container.removeChild(item, { destroy: false, context });
    }

    this.resize();
    this._renderer.render();
  }

  render(): VNode {
    const children: VNode[] = [];
    let renderableIndex = 0;

    for (const child of this._contentItems) {
      // if (index > 0 && this._splitters[index - 1] && this._isSplitterRenderable(this._splitters[index - 1])) {
      //   children.push(this._splitters[index - 1].render());
      // }

      if (child.isRenderable()) {
        if (renderableIndex > 0 && this._splitters[renderableIndex - 1]) {
          children.push(this._splitters[renderableIndex - 1].render());
        }

        children.push(child.render());
        renderableIndex++;
      } else {
        // Render but don't attach to the dom.
        child.render();
      }
    }

    return h(`div.${this._className}`, {
      style: {
        height: `${this._height}px`,
        width: `${this._width}px`
      }
    }, children);
  }

  resize(): void {
    this._height = this._container ? this._container.height : 0 ;
    this._width = this._container ? this._container.width : 0;

    this._calculateRatios();
    this._setDimensions();

    super.resize();
  }

  setSizeOf(item: XYItemContainer, size: number, options: XYSizingOptions = {}): void {
    const { resize = true, render = true } = options;
    const { before, after } = this.getAdjacentItems(item);
    const prevRatio = item.ratio;

    item.ratio = (size / this._totalContainerSize) * 100;

    if (after && isNumber(after.ratio)) {
      after.ratio = Math.max(0, after.ratio + (<number>prevRatio - item.ratio));
    } else if (before && isNumber(before.ratio)) {
      before.ratio = Math.max(0, before.ratio + (<number>prevRatio - item.ratio));
    }

    if (resize) {
      this.resize();
    }

    if (render) {
      this._renderer.render();
    }
  }

  getChildren(): XYItemContainer[] {
    return super.getChildren() as XYItemContainer[];
  }

  getAdjacentItems(item: XYItemContainer): AdjacentResults {
    const index = this._contentItems.indexOf(item);

    return {
      before: index > 0 ? this._contentItems[index - 1] : null,
      after: index < this._contentItems.length - 1 ? this._contentItems[index + 1] : null
    };
  }

  getSplitterFromItem(item: XYItemContainer): Splitter|null {
    const index = this._contentItems.indexOf(item);

    if (index === -1) {
      return null;
    }

    if (index < this._contentItems.length - 1) {
      return this._splitters[index] || null;
    }

    return this._splitters[index - 1] || null;
  }

  getTotalSplitterSizes(start: number = 0, end: number = this._splitters.length - 1): number {
    return this._splitters.slice(start, end).reduce((res, splitter) => res + splitter.size, 0);
  }

  isRenderable(): boolean {
    return Boolean(this.getRenderableChildren().length);
  }

  private _getRenderableSplitters(): Splitter[] {
    return this._splitters.slice(0, this.getRenderableChildren().length - 1);
  }

  private _getRenderableSplitterSize(): number {
    return this._getRenderableSplitters().reduce((res, splitter) => res + splitter.size, 0);
  }

  private _getRenderableContainerSize(): number {
    return this.container
      ? this.isRow
        ? this.container.width - this._getRenderableSplitterSize()
        : this.container.height - this._getRenderableSplitterSize()
      : 0;
  }

  private _createSplitter(): Splitter {
    const splitterConfig = {
      size: this._config && this._config.splitterSize ? this._config.splitterSize : SPLITTER_SIZE,
      disabler: this._isSplitterDisabled.bind(this)
    };

    const splitter = this.createChild(new ConfiguredRenderable(this._Splitter, splitterConfig), [ Draggable ]);

    splitter.dragStatus.subscribe(this._dragStatusChanged.bind(this));

    return splitter;
  }

  private _isSplitterDisabled(splitter: Splitter): boolean {
    const { before, after } = this._getSplitterItems(splitter);

    return before.isMinimized
      || after.isMinimized
      || before.minSize === before.maxSize
      || after.minSize === after.maxSize;
  }

  private _dragStatusChanged(event: DragEvent<Splitter>): void {
    switch (event.status) {
      case DragStatus.START: return this._dragStart(event);
      case DragStatus.STOP: return this._dragEnd(event);
      case DragStatus.DRAGGING: return this._dragMove(event);
    }
  }

  private _getSplitterItems(splitter: Splitter): { before: XYItemContainer, after: XYItemContainer } {
    const index = this._splitters.indexOf(splitter);
    const children = this.getRenderableChildren() as XYItemContainer[];

    return {
      before: children[index],
      after: children[index + 1]
    };
  }

  private _dragStart(event: DragEvent<Splitter>): void {
    const { host } = event;
    const { before, after } = this._getSplitterItems(host);

    this._dragLimitMin = Math.max((-before.size + before.minSize), -(after.maxSize - after.size));
    this._dragLimitMax = Math.min(after.size - after.minSize, before.maxSize - before.size);
  }

  private _dragEnd(event: DragEvent<Splitter>): void {
    let { host, x, y } = event;

    host.dragTo(0, 0);

    x = clamp(x, this._dragLimitMin, this._dragLimitMax);
    y = clamp(y, this._dragLimitMin, this._dragLimitMax);

    this._updateSplitterItems(host, x, y);
    this._renderer.render();
  }

  private _updateSplitterItems(splitter: Splitter, x: number, y: number): void {
    const { before, after } = this._getSplitterItems(splitter);
    const totalContainerSize = this._totalContainerSize;

    if (this.isRow) {
      before.ratio = ((before.width + x) / totalContainerSize) * 100;
      after.ratio = ((after.width - x) / totalContainerSize) * 100;
    } else {
      before.ratio = ((before.height + y) / totalContainerSize) * 100;
      after.ratio = ((after.height - y) / totalContainerSize) * 100;
    }

    this.resize();
  }

  private _dragMove(event: DragEvent<Splitter>): void {
    if (this.isRow) {
      event.host.dragTo(clamp(event.x, this._dragLimitMin, this._dragLimitMax), event.host.y);
    } else {
      event.host.dragTo(event.host.x, clamp(event.y, this._dragLimitMin, this._dragLimitMax));
    }
  }

  private _setDimensions(): void {
    const totalSplitterSize = this._getRenderableSplitterSize();
    let total = 0;
    let totalWidth = this._width;
    let totalHeight = this._height;
    let sizes: number[] = [];
    const children = this.getRenderableChildren() as XYItemContainer[];

    if (this.isRow) {
      totalWidth -= totalSplitterSize;
    } else {
      totalHeight -= totalSplitterSize;
    }

    for (const child of children) {
      let size = (this.isRow ? totalWidth : totalHeight) * (<number>child.ratio / 100);

      total += size;
      sizes.push(size);
    }

    const extraPixels = Math.floor((this.isRow ? totalWidth : totalHeight) - total);

    for (const [ index, child ] of children.entries()) {
      if (extraPixels - index > 0) {
        sizes[index]++;
      }

      if (this.isRow) {
        child.setSize({ width: sizes[index], height: totalHeight });
      } else {
        child.setSize({ width: totalWidth, height: sizes[index] });
      }
    }
  }

  private _calculateRatios(): void {
    let total = 0;
    const unallocatedChildren: XYItemContainer[] = [];
    const minimizedItems: XYItemContainer[] = [];
    const children = this.getRenderableChildren() as XYItemContainer[];

    if (!children.length) {
      return;
    }

    for (const child of children) {
      if (child.ratio !== UNALLOCATED) {
        total += child.ratio as number;
      } else {
        unallocatedChildren.push(child);
      }

      if (child.isMinimized) {
        minimizedItems.push(child);
      }
    }

    if (Math.round(total) !== 100) {
      if (Math.round(total) < 100 && unallocatedChildren.length) {
        for (const child of unallocatedChildren) {
          child.ratio = (100 - total) / unallocatedChildren.length
        }
      } else {
        if (Math.round(total) > 100) {
          for (const child of unallocatedChildren) {
            child.ratio = 50;
            total += 50;
          }
        }

        for (const child of children) {
          child.ratio = (<number>child.ratio / total) * 100;
        }
      }
    }

    for (const child of minimizedItems) {
      this.setSizeOf(child, child.getMinimizedSize(), { render: false, resize: false });
    }

    this._distributeRatios();
  }

  private _distributeRatios(_iterationCount: number = 0): void {
    // Recursion alert. Check for infinite loop here.
    const growable: XYItemContainer[] = [];
    const shrinkable: XYItemContainer[] = [];
    const containerSize = this._totalContainerSize;
    const children = this.getRenderableChildren() as XYItemContainer[];
    let totalRatio = 0;

    for (const child of children) {
      const minRatio = !child.isMinimized ? (child.minSize / containerSize) * 100 : 0;
      const maxRatio = (child.maxSize / containerSize) * 100;

      child.ratio = clamp(child.ratio, minRatio, maxRatio);
      totalRatio += child.ratio;

      const size = containerSize * (<number>child.ratio / 100);

      if (size < child.maxSize) {
        growable.push(child);
      }

      if (size > child.minSize) {
        shrinkable.push(child);
      }
    }

    if (round(totalRatio, 2) > 100) {
      for (const child of shrinkable) {
        child.ratio = <number>child.ratio - ((totalRatio - 100) / shrinkable.length);
      }
    } else if (totalRatio < 100) {
      for (const child of growable) {
        child.ratio = <number>child.ratio + ((100 - totalRatio) / growable.length);
      }
    }

    totalRatio = children.reduce((r, i) => r + <number>i.ratio, 0);

    for (const child of children) {
      child.ratio = (<number>child.ratio / totalRatio) * 100;
    }
  }

  private _createStackWrapper(item: Renderable): Stack {
    const stack = this.createChild(new ConfiguredRenderable(this._Stack, null));

    stack.addChild(item, { render: false });

    return stack;
  }
}


text:
export default /* glsl */ `uniform vec4 layerScale;
uniform vec4 layerBias;

#define PROJECT_ORTHOGONAL

vec4 layerPosition(vec4 position, inout vec4 stpq) {
  return layerScale * position + layerBias;
}
`;


text:
bold() {
  echo ". $(tput bold)" "$*" "$(tput sgr0)";
}

err() {
  echo "$*" >&2;
}

source ./properties

if [ -z "$PROJECT_ID" ]; then
  err "Not running in a GCP project. Exiting."
  exit 1
fi

bold "Starting the setup process in project $PROJECT_ID..."

bold "Creating a service account $SERVICE_ACCOUNT_NAME..."

gcloud iam service-accounts create \
  $SERVICE_ACCOUNT_NAME \
  --display-name $SERVICE_ACCOUNT_NAME

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member serviceAccount:$SERVICE_ACCOUNT_EMAIL \
  --role roles/owner

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member serviceAccount:$SERVICE_ACCOUNT_EMAIL \
  --role roles/pubsub.subscriber

bold "Using bucket $BUCKET_URI..."

gsutil mb -p $PROJECT_ID $BUCKET_URI

bold "Configuring sample code & pipelines..."

gsutil cp gs://gke-spinnaker-codelab/services.tgz .
tar -xvzf services.tgz

gsutil cp gs://gke-spinnaker-codelab/front50.tgz .
tar -xvzf front50.tgz

replace() {
  find front50 -type f -name "*.json" -print0 | xargs -0 sed -i $1
  find services -type f -name "*" -print0 | xargs -0 sed -i $1
  sed -i $1 manifests.yml
}

replace 's|{%SPIN_GCS_ACCOUNT%}|'$SPIN_GCS_ACCOUNT'|g'
replace 's|{%SPIN_GCS_PUB_SUB%}|'$SPIN_GCS_PUB_SUB'|g'
replace 's|{%GCS_SUB%}|'$GCS_SUB'|g'
replace 's|{%GCR_SUB%}|'$GCR_SUB'|g'
replace 's|{%SPIN_GCR_PUB_SUB%}|'$SPIN_GCR_PUB_SUB'|g'
replace 's|{%PROJECT_ID%}|'$PROJECT_ID'|g'
replace 's|{%BUCKET_URI%}|'$BUCKET_URI'|g'
replace 's|{%BUCKET_NAME%}|'$BUCKET_NAME'|g'

bold "Configuring sample code & pipelines..."

gsutil cp -r services/manifests/frontend.yml $BUCKET_URI/manifests/frontend.yml
gsutil cp -r services/manifests/backend.yml $BUCKET_URI/manifests/backend.yml
gsutil cp -r front50 $BUCKET_URI

rm -rf front50/ # TODO remove front50.tgz as well

bold "Pushing sample images into gcr.io/$PROJECT_ID..."

gcloud auth configure-docker -q

docker pull us-docker.pkg.dev/spinnaker-community/codelabs/frontend
docker pull us-docker.pkg.dev/spinnaker-community/codelabs/backend

docker tag us-docker.pkg.dev/spinnaker-community/codelabs/frontend \
  gcr.io/$PROJECT_ID/frontend
docker tag us-docker.pkg.dev/spinnaker-community/codelabs/backend \
  gcr.io/$PROJECT_ID/backend

docker push gcr.io/$PROJECT_ID/frontend
docker push gcr.io/$PROJECT_ID/backend

bold "Configuring pub/sub from $GCS_TOPIC -> $GCS_SUB..."

gsutil notification create -t $GCS_TOPIC -f json $BUCKET_URI
gcloud pubsub subscriptions create $GCS_SUB --topic $GCS_TOPIC

bold "Configuring pub/sub for our docker builds..."

gcloud pubsub topics create projects/${PROJECT_ID}/topics/gcr
gcloud beta pubsub subscriptions create $GCR_SUB --topic $GCR_TOPIC

bold "Creating your cluster $GKE_CLUSTER..."

gcloud container clusters create $GKE_CLUSTER --zone $ZONE \
  --service-account $SERVICE_ACCOUNT_EMAIL \
  --username admin \
  --machine-type n1-standard-4 --image-type COS --disk-size 100 \
  --num-nodes 3 --enable-cloud-logging --enable-cloud-monitoring

gcloud container clusters get-credentials $GKE_CLUSTER --zone $ZONE

bold "Deploying spinnaker..."
kubectl apply -f manifests.yml

bold "Deploying sample service..."
kubectl apply -f services/manifests/seeding.yml
rm services/manifests/seeding.yml

bold "Waiting for spinnaker setup to complete (this might take some time)..."

job_ready() {
  kubectl get job $1 -n spinnaker -o jsonpath="{.status.succeeded}"
}

printf "Waiting on deployment to finish"
while [[ "$(job_ready hal-deploy-apply)" != "1" ]]; do
  printf "."
  sleep 5
done
echo ""

deploy_ready() {
  kubectl get deploy $1 -n spinnaker -o jsonpath="{.status.readyReplicas}"
}

printf "Waiting on API server to come online"
while [[ "$(deploy_ready spin-gate)" != "1" ]]; do
  printf "."
  sleep 5
done
echo ""

printf "Waiting on storage server to come online"
while [[ "$(deploy_ready spin-front50)" != "1" ]]; do
  printf "."
  sleep 5
done
echo ""

printf "Waiting on orchestration engine to come online"
while [[ "$(deploy_ready spin-orca)" != "1" ]]; do
  printf "."
  sleep 5
done
echo ""

bold "Ready! Run ./connect.sh to continue..."


text:
package org.spongepowered.common.data.manipulator.mutable.item;

import com.google.common.collect.Sets;
import com.google.common.primitives.Booleans;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.item.ImmutableBreakableData;
import org.spongepowered.api.data.manipulator.mutable.item.BreakableData;
import org.spongepowered.api.data.value.mutable.SetValue;
import org.spongepowered.common.data.manipulator.immutable.item.ImmutableSpongeBreakableData;
import org.spongepowered.common.data.manipulator.mutable.common.AbstractSingleSetData;

import java.util.Set;
import java.util.stream.Collectors;

public class SpongeBreakableData extends AbstractSingleSetData<BlockType, BreakableData, ImmutableBreakableData> implements BreakableData {

    public SpongeBreakableData() {
        this(Sets.<BlockType>newHashSet());
    }

    public SpongeBreakableData(Set<BlockType> breakable) {
        super(BreakableData.class, Sets.newHashSet(breakable), Keys.BREAKABLE_BLOCK_TYPES, ImmutableSpongeBreakableData.class);
    }

    @Override
    public int compareTo(BreakableData o) {
        return Booleans.compare(o.breakable().containsAll(getValue()),
                getValue().containsAll(o.breakable().get()));
    }

    @Override
    public DataContainer toContainer() {
        return super.toContainer()
            .set(Keys.BREAKABLE_BLOCK_TYPES.getQuery(), getValue().stream()
                .map(BlockType::getId)
                .collect(Collectors.toList()));
    }

    @SuppressWarnings("unchecked")
    @Override
    public SetValue<BlockType> breakable() {
        return (SetValue<BlockType>) getValueGetter();
    }
}


text:
      AST

      AdminSet

        Toggle navigation

管理站点

      {% include 'navbar-custom-menu.html' %}


text:
class AddPageCountToTexts < ActiveRecord::Migration
  def change
    add_column :texts, :pages, :integer
  end
end


text:
package ua.com.fielden.platform.expression.lexer;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import org.junit.Test;

import ua.com.fielden.platform.expression.automata.NoTransitionAvailable;
import ua.com.fielden.platform.expression.automata.SequenceRecognitionFailed;
import ua.com.fielden.platform.expression.lexer.mult.MultTokenAutomata;

public class MultTokenAutomataTest {
    private MultTokenAutomata automata = new MultTokenAutomata();

    @Test
    public void test_full_recognition_of_correct_sequences() throws NoTransitionAvailable, SequenceRecognitionFailed {
        assertEquals("Incorrect recognition result", "*", automata.recognisePartiallyFromStart("*", 0));
        assertEquals("Incorrect recognition result", "*", automata.recognisePartiallyFromStart("    *", 0));
        assertEquals("Incorrect recognition result", "*", automata.recognisePartiallyFromStart("\t\n*\t(", 0));
    }

    @Test
    public void test_recognition_of_partially_correct_sequences() throws NoTransitionAvailable, SequenceRecognitionFailed {
        assertEquals("Incorrect recognition result", "*", automata.recognisePartiallyFromStart(" * property )", 0));
        assertEquals("Incorrect recognition result", "*", automata.recognisePartiallyFromStart("\t*\t +\"", 0));
    }

    @Test
    public void test_recognition_of_incorrect_sequences() {
        try {
            automata.recognisePartiallyFromStart("", 0);
            fail("Should have failed");
        } catch (final SequenceRecognitionFailed e) {
        }
        try {
            automata.recognisePartiallyFromStart("(*", 0);
            fail("Should have failed");
        } catch (final SequenceRecognitionFailed e) {
        }
        try {
            automata.recognisePartiallyFromStart("_*", 0);
            fail("Should have failed");
        } catch (final SequenceRecognitionFailed e) {
        }
        try {
            automata.recognisePartiallyFromStart("S U*", 0);
            fail("Should have failed");
        } catch (final SequenceRecognitionFailed e) {
        }
    }

}


text:
'use strict';

angular.module('core').controller('HomeController', ['$scope', '$state', 'Authentication',
    function($scope, $state, Authentication) {
        // This provides Authentication context.
        $scope.authentication = Authentication;

        if ($scope.authentication.user) $state.go('main');
    }
]);


text:
At present, September 2, 2015 there is no hardware implementing Redfish for sale or available to RedHelix for testing. If you have Redfish capable
hardware contact us. The current Java software
is tested with the DMTF Redfish mockup files. This prevents any development of Redfish operations that change the state of the server, for example
to reboot it.  The software is undergoing massive changes. It's pre-alpa and not ready to use but you can see the direction it is going.

### September 13, 2013
The old maven project redhx-app-server-db has been removed. The Java main method for running Redhelix was in RedHxServerDb and it has moved
to the maven project redhx-server-util as RedHelixClientReport.java. There is more error checking.
In preparation for the web interface two new java projects have been introduced.

1. redhx-server-db The main RESTfull threads that read Redfish JSON messages and use AngularJS to communicate with web browsers.
2. redhx-server-lib This is where all the JSON readers of the Redfish live.

As a result of these changes a new git up brach for version 0.2 has been made.

### September 12, 2013
HP has added HTTPS with Basic Authorization. See scripts  winBuild.cmd  and winRun.cmd. Thanks Dan.
Added processing for Computer System JSON messages. SimpleStorage, Ethernets, Memory status is not yet added.

### September 2, 2013
HTTP reading of the Chassis messages and saving them in Java classes.


text:
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using Kooboo.CMS.Common.Persistence.Non_Relational;
using Kooboo.CMS.Content.Models;
using Kooboo.CMS.Content.Persistence;
using Kooboo.CMS.Sites.DataRule;
using Kooboo.CMS.Sites.Models;
using Kooboo.CMS.Sites.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kooboo.CMS.Sites.Services
{
    [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(Kooboo.CMS.Content.Services.TextFolderManager), Order = 2)]
    public class SiteTextFolderManager : Kooboo.CMS.Content.Services.TextFolderManager
    {
        #region .ctor
        ViewManager _viewManager;
        PageManager _pageManager;
        public SiteTextFolderManager(ITextFolderProvider provider, ViewManager viewManager, PageManager pageManager)
            : base(provider)
        {
            this._viewManager = viewManager;
            this._pageManager = pageManager;
        }
        #endregion

        #region Relation
        public override IEnumerable<RelationModel> Relations(TextFolder textFolder)
        {
            var relations = base.Relations(textFolder);
            var site = Site.Current;
            if (site != null)
            {
                var viewDataRules = _viewManager.All(site, null).Select(it => it.AsActual()).Where(it => it.DataRules != null)
                .SelectMany(it => FindDataRuleRelations("View:" + it.Name, it.DataRules, textFolder));

                var pageDataRules = _pageManager.AllPagesFlattened(site).Select(it => it.AsActual()).Where(it => it.DataRules != null)
                .SelectMany(it => FindDataRuleRelations("Page:" + it.FullName, it.DataRules, textFolder));

                relations = relations.Concat(viewDataRules).Concat(pageDataRules);
            }
            return relations;
        }
        private IEnumerable<RelationModel> FindDataRuleRelations(string relationType, IEnumerable<DataRuleSetting> dataRules, TextFolder textFolder)
        {
            List<RelationModel> relations = new List<RelationModel>();
            foreach (var item in dataRules)
            {
                if (item.DataRule is FolderDataRule)
                {
                    var folderDataRule = (FolderDataRule)item.DataRule;
                    if (folderDataRule.FolderName.EqualsOrNullEmpty(textFolder.FullName, StringComparison.OrdinalIgnoreCase))
                    {
                        relations.Add(new RelationModel()
                        {
                            DisplayName = textFolder.FriendlyText,
                            ObjectUUID = textFolder.FullName,
                            RelationObject = textFolder,
                            RelationType = relationType + "." + item.DataName
                        });
                    }
                }

            }
            return relations;
        }
        #endregion
    }
}


text:
package main

import (
  "github.com/go-gl/gl/v4.1-core/gl"
)

// ShaderData  Maps shader data
type ShaderData struct {
  VertexAttributes    uint32
  NormalAttributes    uint32
  VertexTextureCoords uint32
}

// InstanceShader  Stores shader data
var InstanceShader ShaderData

// ShaderVertex  Defines code for vertex shader
var ShaderVertex = `
#version 330

uniform mat4 projectionUniform;
uniform mat4 cameraUniform;
uniform mat4 modelUniform;
uniform mat3 normalUniform;

uniform vec3 pointLightingLocationUniform;
uniform vec3 pointLightingColorUniform;

uniform int isLightEmitterUniform;

in vec3 vertexAttributes;
in vec3 vertexNormalAttributes;
in vec2 vertexTextureCoords;

out vec3 N;
out vec2 shaderTextureCoords;
out vec3 vertexLighting;

void main() {
  vec4 modelViewPosition = modelUniform * vec4(vertexAttributes, 1);
  gl_Position = projectionUniform * cameraUniform * modelViewPosition;
  shaderTextureCoords = vertexTextureCoords;

  // Process lighting
  if (isLightEmitterUniform == 1) {
    // Light emitter
    vec3 lightDirection = normalize(pointLightingLocationUniform - modelViewPosition.xyz);

    vec3 transformedNormal = normalUniform * vertexNormalAttributes;
    float directionalLighting = max(dot(transformedNormal, lightDirection), 0.0);
    vertexLighting = pointLightingColorUniform * directionalLighting;
  } else {
    // Light receiver
    vertexLighting = vec3(1.0, 1.0, 1.0);
  }
}
` + "\x00"

// ShaderFragment  Defines code for fragment shader
var ShaderFragment = `
#version 330

uniform sampler2D textureUniform;

uniform int isLightReceiverUniform;

in vec2 shaderTextureCoords;
in vec3 vertexLighting;

out vec4 objectColor;

void main() {
  vec4 objectColorTexture = texture(textureUniform, shaderTextureCoords);

  // Apply lighting to pixel
  if (isLightReceiverUniform == 1) {
    objectColor = vec4(objectColorTexture.rgb * vertexLighting, objectColorTexture.a);
  } else {
    objectColor = objectColorTexture;
  }
}
` + "\x00"

func getShader() (*ShaderData) {
  return &InstanceShader
}

func initializeShaders(program uint32) {
  shader := getShader()

  // Bind buffer to shaders attributes
  shader.VertexAttributes = uint32(gl.GetAttribLocation(program, gl.Str("vertexAttributes\x00")))
  gl.EnableVertexAttribArray(shader.VertexAttributes)

  shader.NormalAttributes = uint32(gl.GetAttribLocation(program, gl.Str("vertexNormalAttributes\x00")))
  gl.EnableVertexAttribArray(shader.NormalAttributes)

  shader.VertexTextureCoords = uint32(gl.GetAttribLocation(program, gl.Str("vertexTextureCoords\x00")))
  gl.EnableVertexAttribArray(shader.VertexTextureCoords)

  // Bind misc. shaders uniforms
  setLightUniforms(program)
  setMatrixUniforms(program)
}


text:
#!/usr/bin/env node

var crypto = require('crypto');
var request = require('request');
var _ = require('lodash');

if (!module.parent) {

    var argv = require('yargs')
        .usage("$0 profile.json NSURL api-secret [--preview]")
        .option('preview', {
            alias: 'p'
            , describe: "Give a preview of the outcome without uploading"
            , default: false
        })
        .strict(true)
        .help('help');

    function usage() {
        argv.showHelp();
    }

    var params = argv.argv;
    var errors = [];
    var warnings = [];

    var profile_input = params._[0];

    if ([null, '--help', '-h', 'help'].indexOf(profile_input) > 0) {
        usage();
        process.exit(0);
    }

    var nsurl = params._[1];
    var apisecret = params._[2];
    var headers = {
      'content-type': 'application/json'
    };

    if (!profile_input || !nsurl || !apisecret) {
        usage();
        process.exit(1);
    }

    if (apisecret.indexOf('token=') !== 0 && apisecret.length !== 40) {
        var shasum = crypto.createHash('sha1');
        shasum.update(String(apisecret));
        apisecret = shasum.digest('hex');
        geturl = nsurl + '/api/v1/profile/current';
        headers['api-secret'] = apisecret;
    } else {
        geturl = nsurl + '/api/v1/profile/current?' + apisecret;
    }

    try {
        var cwd = process.cwd();
        var profiledata = require(cwd + '/' + profile_input);

        // Rudimentary check that the profile is valid

        if (!profiledata.dia
          || profiledata.basalprofile.length < 1
          || profiledata.bg_targets.length < 1
          || profiledata.isfProfile.length < 1 )
          { throw "Profile JSON missing data"; }

    } catch (e) {
        return console.error('Could not parse input data: ', e);
    }

    var options = {
        uri: geturl
        , json: true
        , headers
    };

    request(options, function(error, res, data) {
        if (error || res.statusCode !== 200) {
            console.log('Loading current profile from Nightscout failed: ' + res.statusCode);
            process.exit(1);
        }

        var original_profile = data;
        var new_profile = _.cloneDeep(data);

        if (!data.defaultProfile) {
            console.error('Nightscout profile missing data');
            process.exit(1);
        }

        var profile_id = data.defaultProfile;
        var profile_store = new_profile.store[profile_id];

        profile_store.dia = profiledata.dia;

        // Basals

        var new_basal = [];

        _.forEach(profiledata.basalprofile, function(basalentry) {

            var newEntry = {
                time: '' + basalentry.start.substring(0, 5)
                , value: '' + +(Math.round(basalentry.rate + 'e+3') + 'e-3')
                , timeAsSeconds: '' + basalentry.minutes * 60
            };

            new_basal.push(newEntry);

        });

        profile_store.basal = new_basal;

        // BG Targets

        var new_target_low = [];
        var new_target_high = [];

        _.forEach(profiledata.bg_targets.targets, function(target_entry) {

            var time = target_entry.start.substring(0, 5);
            var seconds = parseInt(time.substring(0, 2)) * 60 * 60 + parseInt(time.substring(3, 5)) * 60;
            var low_value = Math.round(target_entry.low);
            var high_value = Math.round(target_entry.high);

            if (new_profile.units === 'mmol' && profiledata.bg_targets.units === 'mg/dL') {
                low_value = +(Math.round(target_entry.low / 18 + 'e+1') + 'e-1');
                high_value = +(Math.round(target_entry.high / 18 + 'e+1') + 'e-1');
            }

            var new_low_entry = {
                time: '' + time
                , value: '' + low_value
                , timeAsSeconds: '' + seconds
            };

            var new_high_entry = {
                time: '' + time
                , value: '' + high_value
                , timeAsSeconds: '' + seconds

            };

            new_target_low.push(new_low_entry);
            new_target_high.push(new_high_entry);
        });

        profile_store.target_low = new_target_low;
        profile_store.target_high = new_target_high;

        // ISF

        var new_sens = [];

        _.forEach(profiledata.isfProfile.sensitivities, function(isf_entry) {

            var value = Math.round(isf_entry.sensitivity);

            if (new_profile.units === 'mmol' && profiledata.isfProfile.units === 'mg/dL') {
                value = +(Math.round(isf_entry.sensitivity / 18 + 'e+1') + 'e-1');
            }

            var new_isf_entry = {
                time: isf_entry.start.substring(0, 5)
                , value: '' + value
                , timeAsSeconds: '' + isf_entry.offset * 60
            };

            new_sens.push(new_isf_entry);
        });

        profile_store.sens = new_sens;

        // Carb ratios

        var new_carb_ratios = [];

        _.forEach(profiledata.carb_ratios.schedule, function(carb_entry) {

            var new_entry = {
                time: carb_entry.start.substring(0, 5)
                , value: '' + carb_entry.ratio
                , timeAsSeconds: '' + carb_entry.offset * 60
            };

            new_carb_ratios.push(new_entry);
        });

        profile_store.carbratio = new_carb_ratios;

        // change dates & remove Mongo ID from new profile to create a new object
        // Inserts the new profile with name "OpenAPS Autosync" to not overwrite
        // human-entered data

        var upload_profile;

        if (profile_id !== 'OpenAPS Autosync') {
            upload_profile = _.cloneDeep(data);
        } else {
            upload_profile = new_profile;
        }

        var do_upload = !_.isEqual(original_profile, new_profile);

        if (do_upload) {

            var d = new Date();
            profile_store.startDate = d.toISOString();

            if (profile_id !== 'OpenAPS Autosync') {
                upload_profile.defaultProfile = 'OpenAPS Autosync';
                upload_profile.store['OpenAPS Autosync'] = profile_store;
            }

            delete upload_profile._id;

            upload_profile.startDate = profile_store.startDate;
            upload_profile.created_at = profile_store.startDate;
            upload_profile.mills = d.getTime();
        }

        // render preview

        if (params.preview) {

            if (_.isEqual(original_profile, new_profile)) {
                console.log('Profile in Nightscout and OpenAPS are identical');
            } else {
                console.log('Profile in Nightscout and OpenAPS differ');
                console.log('-------------- Nightscout Profile ----------------');
                console.log(JSON.stringify(original_profile, null, 2));
                console.log('-------------- New profile from OpenAPS data ----------------');
                console.log(JSON.stringify(upload_profile, null, 2));
            }

            process.exit(0);
        }

        if (do_upload) {
            var nsheaders = {
                'Content-Type': 'application/json'
            };

            console.log('Profile changed, uploading to Nightscout');

            nsurl += '/api/v1/profile';

            if (apisecret.indexOf('token=') === 0) {
                nsurl = nsurl + '?' + apisecret;
            } else {
                nsheaders['API-SECRET'] = apisecret;
            }

            options = {
                uri: nsurl
                , json: true
                , method: 'POST'
                , headers: nsheaders
                , body: upload_profile
            };

            request(options, function(error, res, data) {
                if (error || res.statusCode !== 200) {
                    console.log(error);
                    console.log(res.body);
                } else {
                    console.log('Profile uploaded to Nightscout');
                }
            });
        } else {
            console.log('Profiles match, no upload needed');
        }
    });
}


text:
namespace android {
namespace base {

// Tests whether 's' starts with 'prefix'.
bool StartsWith(std::string_view s, std::string_view prefix);
bool StartsWith(std::string_view s, char prefix);

// Tests whether 's' ends with 'suffix'.
bool EndsWith(std::string_view s, std::string_view suffix);
bool EndsWith(std::string_view s, char suffix);

}  // namespace base
}  // namespace android


text:
package adapter;

import java.util.List;

import com.example.mp3player.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import model.Mp3Info;
import utils.ImageUtils;
import utils.MediaUtils;

public class MusicListAdapter extends BaseAdapter{

	private Context context;		//ÉÏÏÂÎĶÔÏóÒýÓÃ
	private List<Mp3Info> mp3Infos;	//´æ·ÅMp3InfoÒýÓõļ¯ºÏ
	private Mp3Info mp3Info;		//Mp3Info¶ÔÏóÒýÓÃ
	private int pos = -1;			//ÁбíλÖÃ

	public MusicListAdapter(Context context,List<Mp3Info> mp3Infos){
		this.context = context;
		this.mp3Infos = mp3Infos;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mp3Infos.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		ViewHolder viewHolder = null;

		if(convertView == null){
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.music_list_item_layout, null);
			viewHolder.albumImage = (ImageView) convertView.findViewById(R.id.albumImage);
			viewHolder.musicArtist = (TextView) convertView.findViewById(R.id.music_artist);
			viewHolder.musicTitle = (TextView)convertView.findViewById(R.id.music_title1);
			viewHolder.musicDuration = (TextView)convertView.findViewById(R.id.music_duration);
			convertView.setTag(viewHolder);
		}
		else{
			viewHolder = (ViewHolder) convertView.getTag();
		}

		//´ËÏî±ØÐëÌí¼Ó£¬·ñÔò±¨´í£¬ÎÞ·¨»ñÈ¡ÐÅÏ¢
		mp3Info = mp3Infos.get(position);

		viewHolder.musicTitle.setText(mp3Info.getTitle());//ÏÔʾ±êÌâ
		viewHolder.musicArtist.setText(mp3Info.getArtist());//ÏÔʾÒÕÊõ¼Ò
		viewHolder.musicDuration.setText(MediaUtils.formatTime(mp3Info.getDuration()));//ÏÔʾʱ¼ä

		Bitmap bitmap = MediaUtils.getArtwork(context, mp3Info.getId(),mp3Info.getAlbumId(), true, true);
		viewHolder.albumImage.setImageBitmap(bitmap);

		return convertView;
	}

	public class ViewHolder {
		//ËùÓпؼþ¶ÔÏóÒýÓÃ
		public ImageView albumImage;	//ר¼Í¼Æ¬
		public TextView musicTitle;		//ÒôÀÖ±êÌâ
		public TextView musicDuration;	//ÒôÀÖʱ³¤
		public TextView musicArtist;	//ÒôÀÖÒÕÊõ¼Ò
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/content_padding_double"
    android:paddingTop="@dimen/content_padding"
    android:paddingRight="@dimen/content_padding_double"
    android:paddingBottom="@dimen/content_padding"
    android:textAppearance="?android:attr/textAppearanceMedium"
    tools:text="Badges here" />