text:
split-path -parent $MyInvocation.MyCommand.Definition | Split-Path -Parent |
	New-variable PSParentPath -Force -scope global
New-variable PSScripts -value "$PSParentPath\Scripts" -Force -scope global
New-variable PSModules -value "$PSParentPath\Modules" -Force -scope global

#add folders to path
$env:Path += ";c:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\"
$env:Path += ";$PSScripts\"

#add modules folder to module path
$env:PSModulePath = $env:PSModulePath + ";$PSModules\"

#import modules
Import-Module posh-git
Import-Module PsReadLine
Import-Module psake
Import-Module pscx -arg "$PSScripts\Pscx.UserPreferences.ps1"

#import custom module
Import-Module TFSEnvironment.psm1
Use-TFSEnvironment

#run all profile files
dir "$PSParentPath\Profile\*" -Include *.ps1 -Exclude profile.ps1 |% { . $_.FullName }

#run all functions files
dir "$PSParentPath\functions\*" -Include *.ps1 |% {. $_.FullName}

#setup history
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward

redpajama_set_name: RedPajamaGithub


text:
import { IsIdenticalPipe } from './is-identical.pipe';

describe('IsIdenticalPipe', () => {
  let pipe: IsIdenticalPipe;

  beforeEach(() => {
    pipe = new IsIdenticalPipe();
  });

  it('Should return false', () => {
    expect(pipe.transform(3, 2)).toEqual(false);
  });

  it('Should return true', () => {
    expect(pipe.transform(1, 1)).toEqual(true);
  });

  it('Should return false #2', () => {
    expect(pipe.transform(1, '1')).toEqual(false);
  });
});


text:
<?php namespace Fungku\NetSuite\Classes;

class EmployeeSearch extends SearchRecord {
	public $basic;
	public $campaignResponseJoin;
	public $departmentJoin;
	public $fileJoin;
	public $locationJoin;
	public $messagesJoin;
	public $messagesFromJoin;
	public $messagesToJoin;
	public $resourceAllocationJoin;
	public $subsidiaryJoin;
	public $timeJoin;
	public $transactionJoin;
	public $userJoin;
	public $userNotesJoin;
	public $customSearchJoin;
	static $paramtypesmap = array(
		"basic" => "EmployeeSearchBasic",
		"campaignResponseJoin" => "CampaignSearchBasic",
		"departmentJoin" => "DepartmentSearchBasic",
		"fileJoin" => "FileSearchBasic",
		"locationJoin" => "LocationSearchBasic",
		"messagesJoin" => "MessageSearchBasic",
		"messagesFromJoin" => "MessageSearchBasic",
		"messagesToJoin" => "MessageSearchBasic",
		"resourceAllocationJoin" => "ResourceAllocationSearchBasic",
		"subsidiaryJoin" => "SubsidiarySearchBasic",
		"timeJoin" => "TimeBillSearchBasic",
		"transactionJoin" => "TransactionSearchBasic",
		"userJoin" => "EmployeeSearchBasic",
		"userNotesJoin" => "NoteSearchBasic",
		"customSearchJoin" => "CustomSearchJoin[]",
	);
}


text:
package main

const version = "v1"

// TODO: The release version (generated from the git tag) will be the raft
// protocol version for now. When things settle down we will fix it like the
// client API above.
const raftVersion = releaseVersion


text:
(function() {
  var fibrous, optimist;

  fibrous = require('use-global-fibrous');

  optimist = require('optimist');

  optimist.describe(['f', 'fibrous'], "Use fibrous (each input to the REPL will run in a Fiber)");

  if ((optimist.argv.f != null) || (optimist.argv.fibrous != null)) {
    exports.setup = function(context) {
      var nesh;
      nesh = context.nesh;
      process.versions.fibrous = fibrous.version;
      nesh.defaults.prompt = "fibrous-" + nesh.defaults.prompt;
      nesh.defaults.welcome = nesh.defaults.welcome.replace("\n", " with fibrous " + fibrous.version + "\n", 1);
      return nesh.log.debug("Using fibrous " + fibrous.version + " from " + (require.resolve('fibrous')));
    };
    exports.postStart = function(context) {
      var rawEval, repl;
      repl = context.repl;
      rawEval = repl["eval"];
      repl["eval"] = fibrous(function(input, context, filename) {
        return rawEval.sync(input, context, filename);
      });
      return repl.context.fibrous = fibrous;
    };
  }

}).call(this);


text:
package io.coala.aglobe;

import io.coala.log.LogUtil;

import org.apache.log4j.Logger;

import aglobe.container.AgentContainer;
import aglobe.container.DuplicateNameException;
import aglobe.container.ElementaryEntity;
import aglobe.container.agent.Agent;
import aglobe.container.agent.AgentManager;
import aglobe.ontology.AgentInfo;
import aglobe.ontology.Libraries;
import aglobe.platform.ContainerMonitor;

/**
 * {@link MyContainerMonitor} helper class
 *
 * @date $Date: 2014-04-18 17:39:26 +0200 (Fri, 18 Apr 2014) $
 * @version $Revision: 240 $
 * @author Rick
 *
 */
public class MyContainerMonitor implements ContainerMonitor
{

	/** */
	private static final Logger LOG = LogUtil
			.getLogger(MyContainerMonitor.class);

	/** */
	private final String containerName;

	/** */
	AgentContainer container = null;

	/** */
	private boolean removed = false;

	/** */
	public MyContainerMonitor(final String containerName)
	{
		this.containerName = containerName;
	}

	@Override
	public synchronized void containerStarted(final AgentContainer container)
	{
		if (!container.getContainerName().equals(this.containerName))
		{
			LOG.trace("Ignoring start of another container: "
					+ container.getContainerName());
			return;
		}

		this.container = container;
		notifyAll();
	}

	public static String entityStateToString(final int state)
	{
		// if ((state & ElementaryEntity.USE_IDLE_MASK) != 0)
		// return "idle";

		switch (state)
		{
		case ElementaryEntity.CLONING:
			return "cloning";
		case ElementaryEntity.DEAD:
			return "dead";
		case ElementaryEntity.DONE:
			return "done";
		case ElementaryEntity.EXCEPTION:
			return "exception";
		case ElementaryEntity.INIT:
			return "init";
		case ElementaryEntity.MIGRATING:
			return "migrating";
		case ElementaryEntity.RUNNING:
			return "running";
		}
		return "unknown";
	}

	/**
	 * @param simpleName
	 * @param aGENT_CLASS
	 * @throws Exception
	 * @throws DuplicateNameException
	 */
	public <T extends Agent> T createAgent(final String name,
			final Class<T> clazz) throws DuplicateNameException, Exception
	{
		waitUntilContainerStarted();

		final AgentManager mgr = this.container.getAgentManager();

		final AgentInfo ai = new AgentInfo();
		ai.setName(name);
		ai.setAutoRun(true);
		ai.setMainClass(clazz.getName());
		ai.setLibraries(new Libraries());

		LOG.trace("Creating agent " + name + "...");
		mgr.createAgent(ai);

		final T agent = clazz.cast(mgr.getAgentInstance(ai.getName()));

		boolean initiated = false;
		while (!initiated)
		{
			LOG.trace("Agent " + name + " state: "
					+ entityStateToString(agent.getState()));
			try
			{
				Thread.sleep(10);
			} catch (final InterruptedException ignore)
			{
				//
			}
			if (agent.getAddress().getName() != null
					&& agent.getState() == ElementaryEntity.RUNNING)
			{
				initiated = true;
			}

		}

		return agent;
	}

	@Override
	public synchronized void containerRemoved(final String containerName)
	{
		if (!containerName.equals(this.containerName))
		{
			LOG.trace("Ignoring removal of another container: " + containerName);
			return;
		}

		this.removed = true;
		notifyAll();
	}

	/** */
	public void waitUntilContainerStarted()
	{
		while (this.container == null)
		{
			LOG.trace("Waiting for container " + this.containerName + "...");
			try
			{
				synchronized (this)
				{
					wait();
				}
			} catch (final InterruptedException ignore)
			{
				//
			}
		}
	}

	/** */
	public void waitUntilRemoved()
	{
		while (!this.removed)
		{
			LOG.trace("Waiting for container to be removed");
			try
			{
				synchronized (this)
				{
					wait();
				}
			} catch (final InterruptedException ignore)
			{
				//
			}
		}
	}
}


text:
package com.intellij.ide.projectView.impl.nodes;

import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.ProjectViewNodeDecorator;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiPackage;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

public class PackageElementNode extends ProjectViewNode<PackageElement> {
  public PackageElementNode(@NotNull Project project,
                            final PackageElement value,
                            final ViewSettings viewSettings) {
    super(project, value, viewSettings);
  }

  public PackageElementNode(@NotNull Project project,
                            final Object value,
                            final ViewSettings viewSettings) {
    this(project, (PackageElement)value, viewSettings);
  }

  @Override
  public boolean contains(@NotNull final VirtualFile file) {
    if (!isUnderContent(file) || getValue() == null) {
      return false;
    }

    final PsiDirectory[] directories = getValue().getPackage().getDirectories();
    for (PsiDirectory directory : directories) {
      if (VfsUtilCore.isAncestor(directory.getVirtualFile(), file, false)) return true;
    }
    return false;
  }

  private boolean isUnderContent(final VirtualFile file) {
    PackageElement element = getValue();
    final Module module = element == null ? null : element.getModule();
    if (module == null) {
      return ModuleUtilCore.projectContainsFile(getProject(), file, isLibraryElement());
    }
    else {
      return ModuleUtilCore.moduleContainsFile(module, file, isLibraryElement());
    }
  }

  private boolean isLibraryElement() {
    return getValue() != null && getValue().isLibraryElement();
  }

  @Override
  @NotNull
  public Collection<AbstractTreeNode> getChildren() {
    final PackageElement value = getValue();
    if (value == null) return Collections.emptyList();
    final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>();
    final Module module = value.getModule();
    final PsiPackage aPackage = value.getPackage();

    if (!getSettings().isFlattenPackages()) {

      final PsiPackage[] subpackages = PackageUtil.getSubpackages(aPackage, module, myProject, isLibraryElement());
      for (PsiPackage subpackage : subpackages) {
        PackageUtil.addPackageAsChild(children, subpackage, module, getSettings(), isLibraryElement());
      }
    }
    // process only files in package's directories
    final PsiDirectory[] dirs = PackageUtil.getDirectories(aPackage, myProject, module, isLibraryElement());
    for (final PsiDirectory dir : dirs) {
      children.addAll(ProjectViewDirectoryHelper.getInstance(myProject).getDirectoryChildren(dir, getSettings(), false));
    }
    return children;
  }

  @Override
  protected void update(final PresentationData presentation) {
    if (getValue() != null && getValue().getPackage().isValid()) {
      updateValidData(presentation);
    }
    else {
      setValue(null);
    }
  }

  private void updateValidData(final PresentationData presentation) {
    final PackageElement value = getValue();
    final PsiPackage aPackage = value.getPackage();

    if (!getSettings().isFlattenPackages()
        && getSettings().isHideEmptyMiddlePackages()
        && PackageUtil.isPackageEmpty(aPackage, value.getModule(), true, isLibraryElement())) {
      setValue(null);
      return;
    }

    PsiPackage parentPackage;
    Object parentValue = getParentValue();
    if (parentValue instanceof PackageElement) {
      parentPackage = ((PackageElement)parentValue).getPackage();
    }
    else {
      parentPackage = null;
    }
    String qName = aPackage.getQualifiedName();
    String name = PackageUtil.getNodeName(getSettings(), aPackage,parentPackage, qName, showFQName(aPackage));
    presentation.setPresentableText(name);

    presentation.setIcon(PlatformIcons.PACKAGE_ICON);

    for(ProjectViewNodeDecorator decorator: Extensions.getExtensions(ProjectViewNodeDecorator.EP_NAME, myProject)) {
      decorator.decorate(this, presentation);
    }
  }

  private boolean showFQName(final PsiPackage aPackage) {
    return getSettings().isFlattenPackages() && !aPackage.getQualifiedName().isEmpty();
  }

  @Override
  public String getTestPresentation() {
    final PresentationData presentation = new PresentationData();
    update(presentation);
    return "PsiPackage: " + presentation.getPresentableText();
  }

  @Override
  public boolean valueIsCut() {
    return getValue() != null && CopyPasteManager.getInstance().isCutElement(getValue().getPackage());
  }

  @NotNull
  public VirtualFile[] getVirtualFiles() {
    final PackageElement value = getValue();
    if (value == null) {
      return VirtualFile.EMPTY_ARRAY;
    }
    final PsiDirectory[] directories = PackageUtil.getDirectories(value.getPackage(), getProject(), value.getModule(), isLibraryElement());
    final VirtualFile[] result = new VirtualFile[directories.length];
    for (int i = 0; i < directories.length; i++) {
      PsiDirectory directory = directories[i];
      result[i] = directory.getVirtualFile();
    }
    return result;
  }

  @Override
  public boolean canRepresent(final Object element) {
    if (super.canRepresent(element)) return true;
    final PackageElement value = getValue();
    if (value == null) return true;
    if (element instanceof PackageElement) {
      final PackageElement packageElement = (PackageElement)element;
      final String otherPackage = packageElement.getPackage().getQualifiedName();
      final String aPackage = value.getPackage().getQualifiedName();
      if (otherPackage.equals(aPackage)) {
        return true;
      }
    }
    if (element instanceof PsiDirectory) {
      final PsiDirectory directory = (PsiDirectory)element;
      return Arrays.asList(value.getPackage().getDirectories()).contains(directory);
    }
    return false;
  }

  @Override
  public int getWeight() {
    return 0;
  }

  @Override
  public String getTitle() {
    final PackageElement packageElement = getValue();
    if (packageElement == null) {
      return super.getTitle();
    }
    return packageElement.getPackage().getQualifiedName();
  }

  @Override
  @Nullable
  public String getQualifiedNameSortKey() {
    final PackageElement packageElement = getValue();
    if (packageElement != null) {
      return packageElement.getPackage().getQualifiedName();
    }
    return null;
  }

  @Override
  public int getTypeSortWeight(final boolean sortByType) {
    return 4;
  }

  @Override
  public boolean isAlwaysShowPlus() {
    for (final VirtualFile dir : getVirtualFiles()) {
      if (dir.getChildren().length > 0) {
        return true;
      }
    }
    return false;

  }
}


text:
using System.Linq;
using ModuleInject.Injection;

namespace Test.ModuleInject.Modules.TestModules
{
    internal class Submodule : InjectionModule<Submodule>, ISubModule
    {
        public ISubComponent1 Component1 { get { return GetSingleInstance<SubComponent1>(); } }
        public ISubComponent2 Component2 { get { return GetSingleInstance<SubComponent2>(); } }

        public ISubComponent1 CreateComponent1()
        {
            return this.GetFactory<SubComponent1>();
        }
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title><%= htmlWebpackPlugin.options.title %></title>
	<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:300,400,700">

	<% for (var chunk in htmlWebpackPlugin.files.chunks) { %>
	<% } %>


text:
import { IteratorClass } from '../iterator'
import { IterableClass } from '../iterable'
import { $$iterator } from '../symbol'

export class ExpandIterator<T> extends IteratorClass<T> {
  protected i = 0
  protected iterators: Iterator<T>[] = []
  protected currentValue: T | undefined

  constructor(it: { [Symbol.iterator](): Iterator<T> }, protected project: (value: T, index?: number) => { [Symbol.iterator](): Iterator<T> }) {
    super()
    this.iterators = [it[$$iterator]()]
  }

  next() {
    const self = this

    function recurse(): IteratorResult<T> {
      if (self.currentValue) {
        const r = self.project(self.currentValue, self.i++)
        self.currentValue = undefined
        self.iterators.push(r[$$iterator]())
        return recurse()
      } else if (self.iterators.length === 0) {
        return self.settleReturn()
      } else {
        const iterator = self.iterators[self.iterators.length - 1]
        const next = iterator.next()
        if (next.done) {
          self.iterators.pop()
          return recurse()
        } else {
          self.currentValue = next.value
          return self.settleNext(next.value)
        }
      }
    }

    return recurse()
  }
}

export class ExpandIterable<T> extends IterableClass<T> {
  constructor(it: { [Symbol.iterator](): Iterator<T> }, private project: (value: T, index?: number) => { [Symbol.iterator](): Iterator<T> }) {
    super(new ExpandIterator(it, project))
  }
}

export function expand<T>(project: (value: T, index?: number) => { [Symbol.iterator](): Iterator<T> }) {
  return new ExpandIterable(this, project)
}


text:
package com.wallf.cloudcomic.domain;

/**
 * @author acton
 */
public class Chapter {
}


text:
package org.gluu.oxtrust.service.scim2.serialization;

import org.apache.logging.log4j.LogManager;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.gluu.oxtrust.model.scim2.BaseScimResource;
import org.gluu.oxtrust.model.scim2.ListResponse;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.List;

/**
 * Created by jgomer on 2017-10-01.
 */
public class ListResponseJsonSerializer extends JsonSerializer<ListResponse> {

    private Logger log = LogManager.getLogger(getClass());
    private ScimResourceSerializer resourceSerializer;
    private ObjectMapper mapper = new ObjectMapper();

    private String attributes;
    private String excludeAttributes;
    private boolean skipResults;

    private List<JsonNode> jsonResources;

    //why not to inject the resource serializer instead of passing it as parameter? weld simply does not like it!
    public ListResponseJsonSerializer(ScimResourceSerializer serializer){
        resourceSerializer=serializer;
    }

    public ListResponseJsonSerializer(ScimResourceSerializer serializer, String attributes, String excludeAttributes, boolean skipResults){
        resourceSerializer=serializer;
        this.attributes=attributes;
        this.excludeAttributes=excludeAttributes;
        this.skipResults=skipResults;
    }

    public void setJsonResources(List<JsonNode> resources){
        this.jsonResources=resources;
    }

    @Override
    public void serialize(ListResponse listResponse, JsonGenerator jGen, SerializerProvider provider) throws IOException {

        try {
            jGen.writeStartObject();

            jGen.writeArrayFieldStart("schemas");
            for (String schema : listResponse.getSchemas())
                jGen.writeString(schema);
            jGen.writeEndArray();

            jGen.writeNumberField("totalResults", listResponse.getTotalResults());

            if (!skipResults) {
                if (listResponse.getItemsPerPage()>0) {
                    //these two bits are "REQUIRED when partial results are returned due to pagination." (section 3.4.2 RFC 7644)
                    jGen.writeNumberField("startIndex", listResponse.getStartIndex());
                    jGen.writeNumberField("itemsPerPage", listResponse.getItemsPerPage());
                }

                //Section 3.4.2 RFC 7644: Resources [...] REQUIRED if "totalResults" is non-zero
                if (listResponse.getTotalResults()>0) {
                    jGen.writeArrayFieldStart("Resources");

                    if (listResponse.getResources().size()>0)
                        for (BaseScimResource resource : listResponse.getResources()) {
                            JsonNode jsonResource = mapper.readTree(resourceSerializer.serialize(resource, attributes, excludeAttributes));
                            jGen.writeTree(jsonResource);
                        }
                    else
                    if (jsonResources != null)
                        for (JsonNode node : jsonResources)
                            jGen.writeTree(node);

                    jGen.writeEndArray();
                }
            }

            jGen.writeEndObject();
        }
        catch (Exception e) {
            throw new IOException(e);
        }

    }

}


text:
{{<govuk_template}}

{{$head}}
  {{>includes/head}}
{{/head}}

{{$propositionHeader}}

{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}

{{>includes/phase_banner}}

	      Personal Independence Payment (PIP)

								Overview

								What you'll get

								Eligibility

								Make a claim

								Appeals

2. Eligibility

To qualify for PIP, you must:

be aged 16 to 64

have a long-term health condition or disability and difficulties with activities related to 'daily living' and or mobility

be in Great Britain when you claim - there are some exceptions, eg members and family members of the Armed Forces

have been in Great Britain for at least 2 of the last 3 years

be habitually resident in the UK, Ireland, Isle of Man or the Channel Islands

not be subject to immigration control (unless you're a sponsored immigrant)

There are some exceptions to these conditions if you're living or coming from another EEA country or Switzerland.

You can get PIP whether you're in work or not.

Your disability or health condition

You must have a long-term health condition or disability and have difficulties with activities related to 'daily living' and or mobility.

You must have had these difficulties for 3 months and expect them to last for at least 9 months. If you're terminally ill (ie not expected to live more than 6 months), you don't need to have had these difficulties for 3 months.

Daily living difficulties

You may get the daily living component of PIP if you need help with things like:

preparing or eating food

washing, bathing and using the toilet

dressing and undressing

reading and communicating

managing your medicines or treatments

making decisions about money

engaging with other people

Mobility difficulties

You may get the mobility component of PIP if you need help with going out or moving around.

Assessments

Your claim will be assessed by an independent health professional to help DWP work out the level of help you need. This may be a face-to-face consultation - you'll get a letter explaining why and where you must go.

DWP makes the decision about your claim based on the results of the assessment, your application and any supporting evidence you include.

Your rate will be regularly reassessed to make sure you're getting the right support. Tell DWP straight away if there's a change in how your condition affects you.

Carers and disability benefits

						Check how Personal Independence Payment (PIP) affects you

						Disability Living Allowance (DLA) for adults

						Disability Living Allowance (DLA) for children

						Financial help if you're disabled

						Morein Carers and disability benefits

Benefits

						How and when your benefits are paid

						More in Benefits

Elsewhere on GOV.UK

						Find a community support group or organisation

						Looking for work if you're disabled

Elsewhere on the web

						British Sign Language guide to PIP

			Return to top ↑

{{/content}}

{{$bodyEnd}}
  {{>includes/elements_scripts}}
{{/bodyEnd}}

{{/govuk_template}}


text:
import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    attrs: {
        version: 'version_id',
    },
});


text:
using namespace rfa::data;

TimeSeriesHandler::TimeSeriesHandler(rfa::sessionLayer::OMMConsumer* pOMMConsumer,
                                       rfa::common::EventQueue& eventQueue,
                                       rfa::common::Client& client,
                                       const std::string& serviceName,
                                       const RDMFieldDict* dict,
                                       rfa::logger::ComponentLogger& componentLogger,
                                       rfa::ts1::TS1DefDb& TS1DictDb):
_pOMMConsumer(pOMMConsumer),
_componentLogger(componentLogger),
_eventQueue(eventQueue),
_client(client),
_serviceName(serviceName),
_pDict(dict),
_debug(false),
_TS1DictDb(TS1DictDb),
_pTimeSeries(0),
_timeSeries(0),
_numberOfDictParsed(0),
_numberOfTimeSeriesRefreshParsed(0),
_isTimeSeriesParseComplete(true),
_log("")
{
}

TimeSeriesHandler::~TimeSeriesHandler(void){}

void TimeSeriesHandler::sendRequest(const std::string &itemName){
    rfa::message::ReqMsg reqMsg;
    rfa::message::AttribInfo attribInfo(true) ;

    //
    // request _itemName from _serviceName
    //
    attribInfo.setName(itemName.c_str());
    attribInfo.setNameType(rfa::rdm::INSTRUMENT_NAME_RIC);
    attribInfo.setServiceName(_serviceName.c_str());
    reqMsg.setAttribInfo(attribInfo);

    reqMsg.setMsgModelType(rfa::rdm::MMT_MARKET_PRICE);
    reqMsg.setInteractionType( rfa::message::ReqMsg::InitialImageFlag );

    rfa::sessionLayer::OMMItemIntSpec intSpec;
    intSpec.setMsg( &reqMsg );

    std::map<rfa::common::Handle*,std::string>::iterator it;
    std::pair<map<rfa::common::Handle*,std::string>::iterator,bool> ret;

    it = _watchList.find(getHandle(itemName));

    // If item already exists, re-issue the request
    if(it == _watchList.end()) {
        _pHandle = _pOMMConsumer->registerClient(&_eventQueue, &intSpec, _client);
        ret = _watchList.insert(  pair<rfa::common::Handle*,std::string>(_pHandle,itemName+"."+_serviceName) );
        if(ret.second) {
            if(_debug) {
                _log = "[TimeSeriesHandler::sendRequest] Add item subscription for: ";
                _log.append((itemName+"."+_serviceName).c_str());
            }
        } else {
            _log = "[TimeSeriesHandler::sendRequest] Watchlist insertion failed.";
            _componentLogger.log(LM_GENERIC_ONE,rfa::common::Error,_log.c_str());
            _isTimeSeriesParseComplete = true;
            return;
        }
        if(_debug) {
            _log += ". Watchlist size: ";
            _log.append((int)_watchList.size());
            _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str());
        }
    } else {
        if(_debug) {
            _log = "[TimeSeriesHandler::sendRequest] Item is already in the watchlist. Re-issuing for: ";
            _log.append((itemName+"."+_serviceName).c_str());
            _log += ". Watchlist size: ";
            _log.append((int)_watchList.size());
            _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str());
        }
        _pOMMConsumer->reissueClient(it->first, &intSpec);
    }
}

void TimeSeriesHandler::closeRequest(const std::string &itemName){
    std::map<rfa::common::Handle*,std::string>::iterator it;
    it = _watchList.find(getHandle(itemName));
    if(it != _watchList.end()) {
        if(_debug) {
            _log = "[TimeSeriesHandler::closeRequest] Close item subscription for: ";
            _log.append(it->second.c_str());
        }
        _pOMMConsumer->unregisterClient(it->first);
        _watchList.erase(it);
        if(_debug) {
            _log += ". Watchlist size: ";
            _log.append((int)_watchList.size());
            _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str());
        }
    }
    _isTimeSeriesParseComplete = true;
    _numberOfTimeSeriesRefreshParsed = 0;
}

void TimeSeriesHandler::closeAllRequest(){
    _pOMMConsumer->unregisterClient();
    _watchList.clear();
    if(_debug) {
        _log = "[TimeSeriesHandler::closeAllRequest] Close all item subscription.";
        _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str());
    }
    _isTimeSeriesParseComplete = true;
    _numberOfTimeSeriesRefreshParsed = 0;
}

void TimeSeriesHandler::processResponse( const rfa::message::RespMsg& respMsg, rfa::common::Handle* handle, boost::python::tuple& out){
    dict d;
    std::string itemName = "";
    std::string itemServiceName = "";
    itemName = getItemName(handle);
    if (itemName.empty()) {
        itemName = respMsg.getAttribInfo().getName().c_str();
    }
    itemServiceName = getItemServiceName(handle);
    if (itemServiceName.empty()) {
        itemServiceName = _serviceName;
    }

    switch (respMsg.getRespType()){
        case rfa::message::RespMsg::RefreshEnum:
            if(_debug)
                cout << "[TimeSeriesHandler::processResponse] TimeSeries Refresh: " << itemName << "." << itemServiceName << endl;

            if (respMsg.getHintMask() & rfa::message::RespMsg::PayloadFlag) {
                if (_TS1DictDb.hasTS1DbRics(respMsg.getAttribInfo().getName().c_str())) {
                    decodeMarketPrice(respMsg.getPayload(), d);
                    _numberOfDictParsed++;

                } else {
                    decodeTimeSeries(respMsg, d);
                    _numberOfTimeSeriesRefreshParsed++;
                }
                out += boost::python::make_tuple(respMsg.getAttribInfo().getServiceName().c_str(), respMsg.getAttribInfo().getName().c_str(), boost::python::make_tuple(d));
            } else {
                if(_debug) {
                    _log = "[TimeSeriesHandler::processResponse] Empty Refresh.";
                    _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str());
                }
                _isTimeSeriesParseComplete = true;
            }
            break;

        case rfa::message::RespMsg::UpdateEnum:
            if(_debug)
                cout << "[TimeSeriesHandler::processResponse] TimeSeries Update: " << itemName << "." << itemServiceName << endl;

            if (respMsg.getHintMask() & rfa::message::RespMsg::PayloadFlag) {
                if (_TS1DictDb.hasTS1DbRics(respMsg.getAttribInfo().getName().c_str())) {
                    decodeMarketPrice(respMsg.getPayload(), d);
                } else {
                    decodeTimeSeries(respMsg, d);
                }
            } else {
                if(_debug) {
                    _log = "[TimeSeriesHandler::processResponse] Empty Update.";
                    _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str());
                }
                _isTimeSeriesParseComplete = true;
            }
            out += boost::python::make_tuple(respMsg.getAttribInfo().getServiceName().c_str(),respMsg.getAttribInfo().getName().c_str(), boost::python::make_tuple(d));
            break;

        case rfa::message::RespMsg::StatusEnum:
            if(_debug)
                cout << "[TimeSeriesHandler::processResponse] TimeSeries Status: "<< respMsg.getRespStatus().getStatusText().c_str() << endl;
            _log = "[TimeSeriesHandler::processResponse] TimeSeries Status: " + respMsg.getRespStatus().getStatusText();
            _componentLogger.log(LM_GENERIC_ONE,rfa::common::Warning,_log.c_str());
            break;
    }

    // display subscription status
    if (respMsg.getHintMask() & rfa::message::RespMsg::RespStatusFlag) {
        const rfa::common::RespStatus& status = respMsg.getRespStatus();

        // item status details
        _log = " \n\tStatus :";
        _log += " \n\tdataState=\"";
        _log.append(RDMUtils::dataStateToString(status.getDataState()).c_str());
        _log += "\"";
        _log += " \n\tstreamState=\"";
        _log.append(RDMUtils::streamStateToString(status.getStreamState()).c_str());
        _log += "\" \n\tstatusCode=\"";
        _log.append(RDMUtils::statusCodeToString(status.getStatusCode()).c_str());
        _log += "\" \n\tstatusText=\"";
        _log += status.getStatusText();
        _log += "\"";

        // close item if streamState is closed
        if(status.getStreamState() == rfa::common::RespStatus::ClosedEnum) {
            _componentLogger.log(LM_GENERIC_ONE,rfa::common::Error,_log.c_str());
            closeRequest(itemName);
        }

        // Unspecified dataState
        if(status.getDataState() == rfa::common::RespStatus::UnspecifiedEnum) {
            _componentLogger.log(LM_GENERIC_ONE,rfa::common::Error,_log.c_str());
        }
    }

    if(_debug && (out != boost::python::tuple()))
        prettyPrint(out);
}

void TimeSeriesHandler::prettyPrint(boost::python::tuple& inputTuple) {
    bool _isFirstElement = true;
    string out = "";
    out.append("(");
    for ( int i = 0 ; i < len(inputTuple) ; i++ ) {
        //cout << "out = " << out;
        if (_isFirstElement) {
            out.append("(");
            _isFirstElement = false;
        }
        extract<string>strElement(inputTuple[i]);

        if (!strElement.check()) {
            boost::python::tuple tupElement = extract<boost::python::tuple>(inputTuple[i]);
            out.append("(");

            for ( int ii = 0 ; ii < len(tupElement) ; ii++ ) {
                extract<string>nestedstrElement(tupElement[ii]);
                //check whether the converted data is python dictionary
                if (!nestedstrElement.check()) {
                    out.append("{");
                    dict dictElement = extract<dict>(tupElement[ii]);
                    boost::python::list keys = (boost::python::list)dictElement.keys();

                for (int j = 0; j < len(keys); j++) {
                    string key = extract<string>(keys[j]);
                    string value = "";

                    //string
                    extract<string>toString(dictElement[keys[j]]);
                    if(toString.check()) {
                        value = extract<string>(dictElement[keys[j]]);
                        value = "'" + value + "'";
                    }

                    //double
                    extract<double>toDouble(dictElement[keys[j]]);
                    if(toDouble.check()) {
                        double edouble = extract<double>(dictElement[keys[j]]);
                        value = boost::lexical_cast<string>(edouble);
                    }
                    //int
                    extract<int>toInt(dictElement[keys[j]]);
                    if(toInt.check()) {
                        int eint = extract<int>(dictElement[keys[j]]);
                        value = boost::lexical_cast<string>(eint);
                    }
                    //long
                    extract<long>toLong(dictElement[keys[j]]);
                    if(toLong.check()) {
                        value = extract<string>(str(dictElement[keys[j]]));
                    }

                    out.append("'"+key+"'"+":"+value);

                    if (j != len(keys) - 1) {
                        out.append(",");

                    }
                }
            out.append("}");
        } else {
            out.append("'");
            out.append(nestedstrElement);
            out.append("'");
        }
        if (ii != len(tupElement) - 1) {
            out.append(",");
        }
                }
            out.append("))");
            _isFirstElement = true;
        } else {
            out.append("'");
            out.append(strElement);
            out.append("'");
        }
        //check whether the converted data is python dictionary

        if (i != len(inputTuple) - 1) {
            out.append(",");
        }
    }
    out.append(")");
    cout << out << endl;;
}

void TimeSeriesHandler::decodeMarketPrice(const rfa::common::Data& data, dict &d){

    // iterate thru field entries
    const rfa::data::FieldList& fieldlist = static_cast<const rfa::data::FieldList&>(data);

    rfa::data::FieldListReadIterator flri;
    for (flri.start(fieldlist); !flri.off(); flri.forth())  {

        const rfa::data::FieldEntry& field = flri.value();
        const rfa::common::Int16 fieldID = field.getFieldID();
        const RDMFieldDef* fieldDef = _pDict->getFieldDef(fieldID);
        rfa::common::RFA_String fieldValue;

        // if no field definition then no dict then no dataType
        if(!fieldDef) {
            const rfa::common::UInt8 dataType = (rfa::common::UInt8)rfa::data::DataBuffer::UnknownDataBufferEnum;
            const rfa::common::Data& fieldData = field.getData(dataType);
            const rfa::data::DataBuffer& dataBuffer = static_cast<const rfa::data::DataBuffer&>(fieldData);
            fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str();
            d[fieldID] = fieldValue.trimWhitespace().c_str();
        } else {
            // convert to DataBuffer
            const rfa::common::UInt8 dataType = fieldDef->getDataType();
            const rfa::common::Data& fieldData = field.getData(dataType);
            const rfa::data::DataBuffer& dataBuffer = static_cast<const rfa::data::DataBuffer&>(fieldData);
            const rfa::common::UInt8 dataBufferType = dataBuffer.getDataBufferType();
            const RDMEnumDef* enumDef = 0;

            //Note: somehow RDNDISPLAY has dataType=2 but dataBufferType=4
            //check and decode according to data buffer type
            switch(dataBufferType) {
                case rfa::data::DataBuffer::EnumerationEnum:
                    enumDef = fieldDef->getEnumDef();
                    fieldValue = RDMUtils::dataBufferToString(dataBuffer,enumDef).c_str();
                    d[fieldDef->getName().c_str()] = fieldValue.c_str();
                    break;
                case rfa::data::DataBuffer::FloatEnum:
                case rfa::data::DataBuffer::DoubleEnum:
                case rfa::data::DataBuffer::Real32Enum:
                case rfa::data::DataBuffer::Real64Enum:
                    fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str();
                    if(fieldValue.empty()) {
                        //d[fieldDef->getName().c_str()] = boost::python::object();
                        d[fieldDef->getName().c_str()] = "";
                    } else {
                        d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToDouble(dataBuffer);
                    }
                    break;
                case rfa::data::DataBuffer::Int32Enum:
                case rfa::data::DataBuffer::UInt32Enum:
                    fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str();
                    if(fieldValue.empty()) {
                        d[fieldDef->getName().c_str()] = "";
                    } else {
                        d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToInt(dataBuffer);
                    }
                    break;
                case rfa::data::DataBuffer::Int64Enum:
                case rfa::data::DataBuffer::UInt64Enum:
                    fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str();
                    if(fieldValue.empty()) {
                        d[fieldDef->getName().c_str()] = "";
                    } else {
                        d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToLong(dataBuffer);
                    }
                    break;
                default:
                    fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str();
                    d[fieldDef->getName().c_str()] = fieldValue.trimWhitespace().c_str();
                    break;
            }
        }

            // The "_decoder" stores 14 pages of data, out of which 2 thru 10 indexes
            // correspond to ROW64_3 thru ROW64_11 each defining a TS1Def.
            // or get 'ROW64_12' that has next page code that needs to be requested:
            if( fieldID >= (_pDict->getFieldDef(RFA_String("ROW64_3", 0, false)))->getFieldId() &&  fieldID <= (_pDict->getFieldDef(RFA_String("ROW64_11", 0, false)))->getFieldId() ) {
                _TS1DictDb.add(fieldValue.c_str());
            } else if( fieldID == (_pDict->getFieldDef(RFA_String("ROW64_12", 0, false)))->getFieldId() ) {
                RFA_String nextStr = fieldValue;
                const char *next = nextStr.c_str();
                int len = nextStr.length();
                char nextRic[65];
                int j = len - 1;
                int n = 0; // Remove '+' and Spaces.
                for(; j >= 0; j--)
                {
                    if(next[j] != ' ' )
                        break;
                }
                n = 0;
                int i = 0;
                for(; i <= j; i++)
                {
                    if(next[i] != '+')
                    {
                        nextRic[n] = next[i];
                        n++;
                    }
                }
                nextRic[n] = '\0';

                // if addDbRics is successful (returns TRUE), meaning it wasn't in TS1DictDb
                // then send a subscription request on that db ric.
                if(_TS1DictDb.addDbRics(nextRic)) {
                    sendRequest(nextRic);
                }
            }
        }

}

void TimeSeriesHandler::decodeTimeSeries(const rfa::message::RespMsg& respMsg, dict &d) {
    rfa::common::RFA_String timeSeriesData("", 0, false);

    // iterate thru field entries
    const rfa::data::FieldList& fieldlist = static_cast<const rfa::data::FieldList&>(respMsg.getPayload());

    rfa::data::FieldListReadIterator flri;
    for (flri.start(fieldlist); !flri.off(); flri.forth())  {

        const rfa::data::FieldEntry& field = flri.value();
        const rfa::common::Int16 fieldID = field.getFieldID();

        const RDMFieldDef* fieldDef = _pDict->getFieldDef(fieldID);

        // if no field definition then no dict then no dataType
        if(!fieldDef) {
            const rfa::common::UInt8 dataType = (rfa::common::UInt8)rfa::data::DataBuffer::UnknownDataBufferEnum;
            const rfa::common::Data& fieldData = field.getData(dataType);
            const rfa::data::DataBuffer& dataBuffer = static_cast<const rfa::data::DataBuffer&>(fieldData);
            rfa::common::RFA_String fieldValue;
            fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str();
            d[fieldDef->getName().c_str()] = fieldValue.trimWhitespace().c_str();
        } else {
            // convert to DataBuffer
            const rfa::common::UInt8 dataType = fieldDef->getDataType();
            const rfa::common::Data& fieldData = field.getData(dataType);
            const rfa::data::DataBuffer& dataBuffer = static_cast<const rfa::data::DataBuffer&>(fieldData);

            rfa::common::RFA_String fieldValue;

            //check if enum
            if(fieldDef->getDataType() == rfa::data::DataBuffer::EnumerationEnum) {
                const RDMEnumDef* enumDef = fieldDef->getEnumDef();
                fieldValue = RDMUtils::dataBufferToString(dataBuffer,enumDef).c_str();
            } else {
                fieldValue = RDMUtils::dataBufferToStringNoCoversion(dataBuffer).c_str();
            }

            // Filter only the ROW64_1 to ROW64_14 fields
            if( fieldID >= (_pDict->getFieldDef(RFA_String("ROW64_1", 0, false)))->getFieldId() &&  fieldID <= (_pDict->getFieldDef(RFA_String("ROW64_14", 0, false)))->getFieldId() ) {
                timeSeriesData.append(fieldValue);
                d[fieldDef->getName().c_str()] = "<encoded timeseries data>";
            } else {
                d[fieldDef->getName().c_str()] = fieldValue.trimWhitespace().c_str();
            }
        }
    }

    if(!timeSeriesData.empty()) {
        if (_pTimeSeries->decode(respMsg.getAttribInfo().getName().c_str(),timeSeriesData.c_str()) == false) {
            _log = "[TimeSeriesHandler::decodeTimeSeries] Timeseries decoding failed for ";
            _log.append(respMsg.getAttribInfo().getName().c_str());
            _componentLogger.log(LM_GENERIC_ONE,rfa::common::Error,_log.c_str());
            _isTimeSeriesParseComplete = true;
            return;
        }

        // subscribe to secondary RICs e.g. dC.Nd1, dC.Nd2,...
        // 0 = primary
        // 1...N = secondary where N is from getRicCounts
        if(respMsg.getAttribInfo().getName() == _pTimeSeries->getPrimaryRic()) {
            for(int i=1; i < _pTimeSeries->getRicCounts(); ++i) {
                sendRequest(RFA_String(_pTimeSeries->getRicName(i), 0, false).c_str());
            }
        }
    }
}

bool TimeSeriesHandler::isTimeSeriesParseComplete() {
    // determine if all TS1 data is parsed completely
    if( _numberOfDictParsed == _TS1DictDb.getNumberDbRics() && _numberOfTimeSeriesRefreshParsed == _pTimeSeries->getRicCounts() && _numberOfTimeSeriesRefreshParsed > 0 ) {
        _isTimeSeriesParseComplete = true;
    }
    return _isTimeSeriesParseComplete;
}

void TimeSeriesHandler::setDebugMode(const bool &debug) {
    _debug = debug;
}

std::string TimeSeriesHandler::getItemName(rfa::common::Handle* handle) {
    std::map<rfa::common::Handle*,std::string>::iterator it;
    it = _watchList.find(handle);
    std::string itemName = "";
    if(it != _watchList.end()) {
        std::vector<std::string> strs;
        boost::split(strs, it->second, boost::is_any_of("."));
        if (strs.size() > 2) {
            std::vector<std::string>::iterator strsit = strs.begin();
            itemName = *strsit;
            strsit++;
            for (std::vector<std::string>::size_type i=1; i < strs.size()-1; i++) {
                itemName = itemName + "." + *strsit;
                strsit++;
            }
        } else {
            itemName = strs[0];
        }
    }
    return itemName;

}

std::string TimeSeriesHandler::getItemServiceName(rfa::common::Handle* handle) {
    std::map<rfa::common::Handle*,std::string>::iterator it;
    it = _watchList.find(handle);
    std::string itemServiceName = "";
    if(it != _watchList.end()) {
        std::vector<std::string> strs;
        boost::split(strs, it->second, boost::is_any_of("."));
        itemServiceName = strs.back();
    }
    return itemServiceName;
}

rfa::common::Handle* TimeSeriesHandler::getHandle(const std::string &itemName) {
    std::map<rfa::common::Handle*,std::string>::iterator it;
    for(it = _watchList.begin(); it != _watchList.end(); it++) {
        if(it->second == itemName+"."+_serviceName) {
            return it->first;
        }
    }
    return NULL;
}

std::map<rfa::common::Handle*,std::string> &TimeSeriesHandler::getWatchList() {
    return _watchList;
}

const std::list<std::string>* TimeSeriesHandler::getTimeSeries(const int &maxRecords) {
    rfa::common::RFA_String timeSeriesRecord;
    rfa::ts1::TS1SampleIterator iterator;

    if(_debug) {
        _log = "[TimeSeriesHandler::getTimeSeries] Timeseries parsing statistics:\n";
        _log += "Number Of DB RICs = ";
        _log.append(_TS1DictDb.getNumberDbRics());
        _log += "\n";
        _log += "Number Of RICs parsed = ";
        _log.append(_pTimeSeries->getRicCounts());
        _log += "\n";
        _log += "Number Of FIDs = ";
        _log.append(_pTimeSeries->getFactCount());
        _log += "\n";
        _log += "Number Of Samples parsed = ";
        _log.append(_pTimeSeries->getNumberOfSamples());
        _log += "\n";
        _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str());
    }

    int count=0;
    struct tm * time_tm;
    char time_str[256];

    // Header record consists of FID definition
    if(_pTimeSeries->getNumberOfSamples() > 0) {
        timeSeriesRecord = "DATE";
        for (int i=0; i < _pTimeSeries->getFactCount(); i++) {
            timeSeriesRecord += ",";
            timeSeriesRecord.append( _TS1DictDb.getDefByFid(_pTimeSeries->getFact(i))->getLongName() );
        }
        _timeSeries.push_back(timeSeriesRecord.c_str());

        // Timeseries records
        for (iterator.start(_pTimeSeries); (!iterator.off() && (count++ < maxRecords)); iterator.forth()) {
            const rfa::ts1::TS1Sample* sample = iterator.getSample();

            time_t time = sample->getDate();
            time_tm = localtime(&time);
            sprintf(time_str,"%4ld/%02ld/%02ld",(long int)(1900+time_tm->tm_year),(long int)(time_tm->tm_mon+1),(long int)time_tm->tm_mday);
            timeSeriesRecord = time_str;

            if (!sample->isValid()) {
                timeSeriesRecord += ",";
                timeSeriesRecord.append(sample->text());
            } else {
                for (int i=0; i < sample->getNumberOfPoints(); i++) {
                    const rfa::ts1::TS1Point* point = (*sample)[i];
                    if (!point->isValid()) {
                        timeSeriesRecord += ",";
                        timeSeriesRecord.append(point->getText());
                    } else {
                        switch (point->getDataType()) {
                            case rfa::ts1::TS1Point::Double:
                                sprintf(time_str,"%g",point->toDouble());
                                timeSeriesRecord += ",";
                                timeSeriesRecord.append(time_str);
                                break;
                            case rfa::ts1::TS1Point::Integer:
                                sprintf(time_str,"%d",point->toInt());
                                timeSeriesRecord += ",";
                                timeSeriesRecord.append(time_str);
                                break;
                            case rfa::ts1::TS1Point::String:
                                sprintf(time_str,"%s",point->toString());
                                timeSeriesRecord += ",";
                                timeSeriesRecord.append(time_str);
                                break;
                            default:
                                timeSeriesRecord += ",";
                                timeSeriesRecord.append("datatype not supported");
                                break;
                        }
                    }
                }
            }
            _timeSeries.push_back(timeSeriesRecord.c_str());
        }
    }
    return &_timeSeries;
}

void TimeSeriesHandler::initTimeSeries(rfa::ts1::TS1Series* pTimeSeries) {
    _pTimeSeries = pTimeSeries;
    _isTimeSeriesParseComplete = false;
    _numberOfTimeSeriesRefreshParsed = 0;
    _timeSeries.clear();
}


text:
using Util.Ui.Builders;

namespace Util.Ui.Material.Forms.Builders {
    /// <summary>
    /// Mat复选框生成器
    /// </summary>
    class CheckBoxBuilder : TagBuilder {
        /// <summary>
        /// 初始化Mat复选框生成器
        /// </summary>
        public CheckBoxBuilder( ) : base( "mat-checkbox" ) {
        }
    }
}


text:
<?php
namespace CpPress\Application\Login\Provider;

use Symfony\Component\Ldap\LdapClient;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\Exception\LdapException;

class LdapProvider extends BaseProvider{

	/**
	 * @var LdapClient;
	 */
	private $ldap;

	private $dnUser;
	private $dnUserString;
	private $dnGroup;
	private $dnGroupString;

	private $filterUserGroup;

	private $displayGroup;

	private $adminGroups = array('Administrators', 'Website Admin');

	public function __construct(array $options){
		parent::__construct($options);
		$this->ldap = $this->connect();

		$this->dnUser = 'ou=Users,'.$this->get('basedn');
		if($this->has('userbasedn') && $this->get('userbasedn') !== ''){
			$this->dnUser = $this->get('userbasedn');
		}

		$this->dnUserString = 'uid={username}';
		if($this->has('login') && $this->get('login') !== ''){
			$this->dnUserString = $this->get('login');
		}
		$this->dnGroup = 'ou=Gourps,'.$this->get('basedn');
		if($this->has('groupbasedn') && $this->get('groupbasedn') !== ''){
			$this->dnGroup = $this->get('groupbasedn');
		}

		$this->dnGroupString = 'cn={group}';
		if($this->has('group') && $this->get('group') !== ''){
			$this->dnGroupString = $this->get('group');
		}

		$this->filterUserGroup = '(memberUid={username})';
		if($this->has('filterusergroup') && $this->get('filterusergroup') !== ''){
			$this->filterUserGroup = $this->get('filterusergroup');
		}

		$this->displayGroup = 'cn';
		if($this->has('displaygroup') && $this->get('displaygroup') !== ''){
			$this->displayGroup = $this->get('displaygroup');
		}
	}

	public function authenticate($username, $password){
		if('' === $password || '' === $username){
			$error = new \WP_Error();
			if('' === $username){
				$error->add('empty_username', __('ERROR:: The username field is empty.'));
			}
			if('' === $password){
				$error->add('empty_password', __('ERROR:: The password field is empty'));
			}

			return $error;
		}
		try{
			$username = $this->ldap->escape($username, '', LdapInterface::ESCAPE_DN);
			$dn = str_replace('{username}', $username, $this->dnUserString).','.$this->dnUser;

			$this->ldap->bind($dn, $password);
		}catch(ConnectionException $e){
			return false;
		}

		return true;
	}

	public function loadUserByUsername($username){
		try{
			$username = $this->ldap->escape($username, '', LdapInterface::ESCAPE_FILTER);
			$this->userHasGroup($username);
			$query = '('.str_replace('{username}', $username, $this->dnUserString).')';
			$search = $this->ldap->query($this->get('basedn'), $query);
		}catch(ConnectionException $e){
			return $this->error('username_not_found', sprintf(__('ERROR:: User "%s" not found', 'cppress'), $username));
		}

		$entries = $search->execute();
		$count = count($entries);

		if(!$count){
			return $this->error('username_not_found', sprintf(__('ERROR:: User "%s" not found', 'cppress'), $username));
		}

		if($count > 1){
			return $this->error('more_than_one_user_found', __('ERROR:: More than one user found'));
		}
		return $this->loadUser($username, $entries[0]);
	}

	private function connect(){
		$useSsl = false;
		$hostDc = $this->get('dc');
		$portDc = $this->get('dcport') !== null ? $this->get('dcport') : '389';
		$versionDc = $this->get('version') !== null ? $this->get('version') : '3';
		if(preg_match("/(ldap|ldaps):\/\/(\S*)/", $hostDc, $match)){
			if($match[1] === 'ldaps'){
				$useSsl = true;
			}
			$hostDc = $match[2];
		}

		$ldap = new LdapClient($hostDc, $portDc, $versionDc, $useSsl);
		$ldap->bind($this->get('searchdn'), $this->get('searchpassword'));
		return $ldap;
	}

	private function loadUser($username, Entry $entry){
		$user = get_user_by('login', $username);
		if(false === $user || strtolower($user->user_login) !== strtolower($username)){
			if(!$this->true('usercreations')){
				return $this->error('invalid_username', __('Simple LDAP Login Error: LDAP credentials are correct, but there is no matching WordPress user and user creation is not enabled.'));
			}

			$this->userData->set('user_login', $username);
			$this->userData->set('user_nicename',
				$this->getUserData($entry, $this->get('userfirstnameattribute')).' - '.
				$this->getUserData($entry, $this->get('userlastnameattribute')));
			$this->userData->set('user_email', $this->getUserData($entry, $this->get('useremailattribute')));
			$this->userData->set('display_name',
					$this->getUserData($entry, $this->get('userfirstnameattribute')) .' '.
					$this->getUserData($entry, $this->get('userlastnameattribute')));
			$this->userData->set('first_name', $this->getUserData($entry, $this->get('userfirstnameattribute')));
			$this->userData->set('last_name', $this->getUserData($entry, $this->get('userlastnameattribute')));
			$this->userData->set('user_url', $this->getUserData($entry, $this->get('userurlattribute')));

			$newUser = wp_insert_user($this->userData);

			if($newUser instanceof \WP_Error){
				return $this->error('login_error', 'ERROR: '.$newUser->get_error_message());
			}

			foreach($this->getUserMetaData($entry) as $metaKey => $metaValue){
				add_user_meta($newUser, $metaKey, $metaValue);
			}

			return new \WP_User($newUser);

		}else{
			return new \WP_User($user->ID);
		}
	}

	private function userHasGroup($username){
		$groups = $this->has('groups') ? (array) $this->get('groups') : array();
		$groups = array_filter($groups);

		if(count($groups) === 0){
			return;
		}

		$query = str_replace('{username}', $username, $this->filterUserGroup);
		$search = $this->ldap->query($this->get('basedn'), $query);
		$entries = $search->execute();
		$count = count($entries);

		if($count > 0){
			$userGroups = array();
			foreach($entries as $entry){
				$groupName = $entry->getAttribute($this->displayGroup);
				$userGroups[] = is_array($groupName) ? $groupName[0] : $groupName;
			}

			$validGroups = array_intersect($userGroups, $groups);
			foreach($this->adminGroups as $adminGroup){
				if(in_array($adminGroup, $validGroups)){
					$this->userData->set('role', 'administrator');
					break;
				}
			}

			if(count($validGroups) > 0){
				return;
			}
		}

		throw new ConnectionException('No groups found');
	}

	private function getUserData(Entry $entry, $attribute){
		$value = $entry->getAttribute(strtolower($attribute));
		return is_array($value) ? $value[0] : $value;
	}

	private function getUserMetaData(Entry $entry){
		$settingsUserMetaData = $this->has('usermetadata') ? (array) $this->get('usermetadata') : array();
		$userMetaData = array();

		foreach($settingsUserMetaData as $attribute){
			$userMetaData[$attribute[1]] = $this->getUserData($entry, $attribute[0]);
		}

		return $userMetaData;
	}
}


text:
#import <AppKit/AppKit.h>

@interface NSMenuView : NSView {
    unsigned _selectedItemIndex;
    NSMutableArray *_visibleArray;
}

- (unsigned)itemIndexAtPoint:(NSPoint)point;
- (unsigned)selectedItemIndex;
- (void)setSelectedItemIndex:(unsigned)itemIndex;

- (NSArray *)visibleItemArray;
- (NSMenuItem *)itemAtSelectedIndex;

- (NSMenuView *)viewAtSelectedIndexPositionOnScreen:(NSScreen *)screen;

- (NSMenuItem *)trackForEvent:(NSEvent *)event;

@end


text:
using SDL.ECommerce.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SDL.ECommerce.OData
{
    public partial class ProductRef : IProductRef
    {
    }
}


text:
#include "postgres_fe.h"

#include <pwd.h>
#include <signal.h>
#include <unistd.h>

#include "common.h"
#include "libpq/pqsignal.h"

static void SetCancelConn(PGconn *conn);
static void ResetCancelConn(void);

#ifndef HAVE_INT_OPTRESET
int			optreset;
#endif

static PGcancel *volatile cancelConn = NULL;

#ifdef WIN32
static CRITICAL_SECTION cancelConnLock;
#endif

/*
 * Returns the current user name.
 */
const char *
get_user_name(const char *progname)
{
#ifndef WIN32
	struct passwd *pw;

	pw = getpwuid(geteuid());
	if (!pw)
	{
		fprintf(stderr, _("%s: could not obtain information about current user: %s\n"),
				progname, strerror(errno));
		exit(1);
	}
	return pw->pw_name;
#else
	static char username[128];	/* remains after function exit */
	DWORD		len = sizeof(username) - 1;

	if (!GetUserName(username, &len))
	{
		fprintf(stderr, _("%s: could not get current user name: %s\n"),
				progname, strerror(errno));
		exit(1);
	}
	return username;
#endif
}

/*
 * Provide strictly harmonized handling of --help and --version
 * options.
 */
void
handle_help_version_opts(int argc, char *argv[],
						 const char *fixed_progname, help_handler hlp)
{
	if (argc > 1)
	{
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
		{
			hlp(get_progname(argv[0]));
			exit(0);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			printf("%s (Greenplum Database) " PG_VERSION "\n", fixed_progname);
			exit(0);
		}
	}
}

/*
 * Make a database connection with the given parameters.  An
 * interactive password prompt is automatically issued if required.
 */
PGconn *
connectDatabase(const char *dbname, const char *pghost, const char *pgport,
				const char *pguser, enum trivalue prompt_password,
				const char *progname)
{
	PGconn	   *conn;
	char	   *password = NULL;
	bool		new_pass;

	if (prompt_password == TRI_YES)
		password = simple_prompt("Password: ", 100, false);

	/*
	 * Start the connection.  Loop until we have a password if requested by
	 * backend.
	 */
	do
	{
#define PARAMS_ARRAY_SIZE	7
		const char **keywords = malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
		const char **values = malloc(PARAMS_ARRAY_SIZE * sizeof(*values));

		if (!keywords || !values)
		{
			fprintf(stderr, _("%s: out of memory\n"), progname);
			exit(1);
		}

		keywords[0] = "host";
		values[0] = pghost;
		keywords[1] = "port";
		values[1] = pgport;
		keywords[2] = "user";
		values[2] = pguser;
		keywords[3] = "password";
		values[3] = password;
		keywords[4] = "dbname";
		values[4] = dbname;
		keywords[5] = "fallback_application_name";
		values[5] = progname;
		keywords[6] = NULL;
		values[6] = NULL;

		new_pass = false;
		conn = PQconnectdbParams(keywords, values, true);

		free(keywords);
		free(values);

		if (!conn)
		{
			fprintf(stderr, _("%s: could not connect to database %s\n"),
					progname, dbname);
			exit(1);
		}

		if (PQstatus(conn) == CONNECTION_BAD &&
			PQconnectionNeedsPassword(conn) &&
			password == NULL &&
			prompt_password != TRI_NO)
		{
			PQfinish(conn);
			password = simple_prompt("Password: ", 100, false);
			new_pass = true;
		}
	} while (new_pass);

	if (password)
		free(password);

	/* check to see that the backend connection was successfully made */
	if (PQstatus(conn) == CONNECTION_BAD)
	{
		fprintf(stderr, _("%s: could not connect to database %s: %s"),
				progname, dbname, PQerrorMessage(conn));
		exit(1);
	}

	return conn;
}

/*
 * Run a query, return the results, exit program on failure.
 */
PGresult *
executeQuery(PGconn *conn, const char *query, const char *progname, bool echo)
{
	PGresult   *res;

	if (echo)
		printf("%s\n", query);

	res = PQexec(conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, _("%s: query failed: %s"),
				progname, PQerrorMessage(conn));
		fprintf(stderr, _("%s: query was: %s\n"),
				progname, query);
		PQfinish(conn);
		exit(1);
	}

	return res;
}

/*
 * As above for a SQL command (which returns nothing).
 */
void
executeCommand(PGconn *conn, const char *query,
			   const char *progname, bool echo)
{
	PGresult   *res;

	if (echo)
		printf("%s\n", query);

	res = PQexec(conn, query);
	if (!res ||
		PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, _("%s: query failed: %s"),
				progname, PQerrorMessage(conn));
		fprintf(stderr, _("%s: query was: %s\n"),
				progname, query);
		PQfinish(conn);
		exit(1);
	}

	PQclear(res);
}

/*
 * As above for a SQL maintenance command (returns command success).
 * Command is executed with a cancel handler set, so Ctrl-C can
 * interrupt it.
 */
bool
executeMaintenanceCommand(PGconn *conn, const char *query, bool echo)
{
	PGresult   *res;
	bool		r;

	if (echo)
		printf("%s\n", query);

	SetCancelConn(conn);
	res = PQexec(conn, query);
	ResetCancelConn();

	r = (res && PQresultStatus(res) == PGRES_COMMAND_OK);

	if (res)
		PQclear(res);

	return r;
}

/*
 * "Safe" wrapper around strdup().	Pulled from psql/common.c
 */
char *
pg_strdup(const char *string)
{
	char	   *tmp;

	if (!string)
	{
		fprintf(stderr, _("pg_strdup: cannot duplicate null pointer (internal error)\n"));
		exit(EXIT_FAILURE);
	}
	tmp = strdup(string);
	if (!tmp)
	{
		fprintf(stderr, _("out of memory\n"));
		exit(EXIT_FAILURE);
	}
	return tmp;
}

/*
 * Check yes/no answer in a localized way.	1=yes, 0=no, -1=neither.
 */

/* translator: abbreviation for "yes" */
#define PG_YESLETTER gettext_noop("y")
/* translator: abbreviation for "no" */
#define PG_NOLETTER gettext_noop("n")

bool
yesno_prompt(const char *question)
{
	char		prompt[256];

	/*
	 * translator: This is a question followed by the translated options for
	 * "yes" and "no".
	 */
	snprintf(prompt, sizeof(prompt), _("%s (%s/%s) "),
			 _(question), _(PG_YESLETTER), _(PG_NOLETTER));

	for (;;)
	{
		char	   *resp;

		resp = simple_prompt(prompt, 1, true);

		if (strcmp(resp, _(PG_YESLETTER)) == 0)
		{
			free(resp);
			return true;
		}
		else if (strcmp(resp, _(PG_NOLETTER)) == 0)
		{
			free(resp);
			return false;
		}

		free(resp);
		printf(_("Please answer \"%s\" or \"%s\".\n"),
			   _(PG_YESLETTER), _(PG_NOLETTER));
	}
}

/*
 * SetCancelConn
 *
 * Set cancelConn to point to the current database connection.
 */
static void
SetCancelConn(PGconn *conn)
{
	PGcancel   *oldCancelConn;

#ifdef WIN32
	EnterCriticalSection(&cancelConnLock);
#endif

	/* Free the old one if we have one */
	oldCancelConn = cancelConn;

	/* be sure handle_sigint doesn't use pointer while freeing */
	cancelConn = NULL;

	if (oldCancelConn != NULL)
		PQfreeCancel(oldCancelConn);

	cancelConn = PQgetCancel(conn);

#ifdef WIN32
	LeaveCriticalSection(&cancelConnLock);
#endif
}

/*
 * ResetCancelConn
 *
 * Free the current cancel connection, if any, and set to NULL.
 */
static void
ResetCancelConn(void)
{
	PGcancel   *oldCancelConn;

#ifdef WIN32
	EnterCriticalSection(&cancelConnLock);
#endif

	oldCancelConn = cancelConn;

	/* be sure handle_sigint doesn't use pointer while freeing */
	cancelConn = NULL;

	if (oldCancelConn != NULL)
		PQfreeCancel(oldCancelConn);

#ifdef WIN32
	LeaveCriticalSection(&cancelConnLock);
#endif
}

#ifndef WIN32
/*
 * Handle interrupt signals by cancelling the current command,
 * if it's being executed through executeMaintenanceCommand(),
 * and thus has a cancelConn set.
 */
static void
handle_sigint(SIGNAL_ARGS)
{
	int			save_errno = errno;
	char		errbuf[256];

	/* Send QueryCancel if we are processing a database query */
	if (cancelConn != NULL)
	{
		if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
			fprintf(stderr, _("Cancel request sent\n"));
		else
			fprintf(stderr, _("Could not send cancel request: %s"), errbuf);
	}

	errno = save_errno;			/* just in case the write changed it */
}

void
setup_cancel_handler(void)
{
	pqsignal(SIGINT, handle_sigint);
}
#else							/* WIN32 */

/*
 * Console control handler for Win32. Note that the control handler will
 * execute on a *different thread* than the main one, so we need to do
 * proper locking around those structures.
 */
static BOOL WINAPI
consoleHandler(DWORD dwCtrlType)
{
	char		errbuf[256];

	if (dwCtrlType == CTRL_C_EVENT ||
		dwCtrlType == CTRL_BREAK_EVENT)
	{
		/* Send QueryCancel if we are processing a database query */
		EnterCriticalSection(&cancelConnLock);
		if (cancelConn != NULL)
		{
			if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
				fprintf(stderr, _("Cancel request sent\n"));
			else
				fprintf(stderr, _("Could not send cancel request: %s"), errbuf);
		}
		LeaveCriticalSection(&cancelConnLock);

		return TRUE;
	}
	else
		/* Return FALSE for any signals not being handled */
		return FALSE;
}

void
setup_cancel_handler(void)
{
	InitializeCriticalSection(&cancelConnLock);

	SetConsoleCtrlHandler(consoleHandler, TRUE);
}

#endif   /* WIN32 */


text:
module Byebug
  module Helpers
    #
    # Utilities to assist frame navigation
    #
    module FrameHelper
      def switch_to_frame(frame)
        new_frame = index_from_start(frame)
        return frame_err('c_frame') if Frame.new(context, new_frame).c_frame?

        adjust_frame(new_frame)
      end

      def jump_frames(steps)
        adjust_frame(navigate_to_frame(steps))
      end

      private

      def adjust_frame(new_frame)
        return frame_err('too_low') if new_frame >= context.stack_size
        return frame_err('too_high') if new_frame < 0

        context.frame = new_frame
        processor.prev_line = nil
      end

      def navigate_to_frame(jump_no)
        current_jumps = 0
        current_pos = context.frame.pos

        loop do
          current_pos += direction(jump_no)
          break if out_of_bounds?(current_pos)

          next if Frame.new(context, current_pos).c_frame?

          current_jumps += 1
          break if current_jumps == jump_no.abs
        end

        current_pos
      end

      def out_of_bounds?(pos)
        !(0...context.stack_size).include?(pos)
      end

      def frame_err(msg)
        errmsg(pr("frame.errors.#{msg}"))
      end

      #
      # @param [Integer] A positive or negative integer
      #
      # @return [Integer] +1 if step is positive / -1 if negative
      #
      def direction(step)
        step / step.abs
      end

      #
      # Convert a possibly negative index to a positive index from the start
      # of the callstack. -1 is the last position in the stack and so on.
      #
      # @param [Integer] Integer to be converted in a proper positive index.
      #
      def index_from_start(i)
        i >= 0 ? i : context.stack_size + i
      end
    end
  end
end


text:
require "chandler/refinements/color"

module Chandler
  # Similar to Ruby's standard Logger, but automatically removes ANSI color
  # from the logged messages if stdout and stderr do not support it.
  #
  class Logger
    using Chandler::Refinements::Color
    attr_accessor :stderr, :stdout

    def initialize(stderr: $stderr, stdout: $stdout)
      @stderr = stderr
      @stdout = stdout
      @color_enabled = nil
    end

    # Logs a message to stderr. Unless otherwise specified, the message will
    # be printed in red.
    def error(message)
      message = message.red unless message.color?
      puts(stderr, message)
    end

    # Logs a message to stdout.
    def info(message)
      puts(stdout, message)
    end

    # Logs a message to stdout, runs the given block, and then prints the time
    # it took to run the block.
    def benchmark(message)
      start = Time.now
      print(stdout, "#{message} ")
      result = yield
      duration = Time.now - start
      info("✔".green + format(" %0.3fs", duration).gray)
      result
    rescue
      info("✘".red)
      raise
    end

    private

    def print(io, message)
      message = message.strip_color unless color_enabled?
      io.print(message)
    end

    def puts(io, message)
      message = message.strip_color unless color_enabled?
      io.puts(message)
    end

    def color_enabled?
      @color_enabled = determine_color_support if @color_enabled.nil?
      @color_enabled
    end

    def determine_color_support
      if ENV["CLICOLOR_FORCE"] == "1"
        true
      elsif ENV["TERM"] == "dumb"
        false
      else
        tty?(stdout) && tty?(stderr)
      end
    end

    def tty?(io)
      io.respond_to?(:tty?) && io.tty?
    end
  end
end


text:
package model.domain

import org.scalatest.{FlatSpec, Matchers}

class ProductTests extends FlatSpec with Matchers {

}


text:
import pickle
from complex import ComplexThing

# Create the instance
awesome_thing = ComplexThing("awesomeness", 15)
print("Before Pickling:")
print(awesome_thing)

# Pickle the instance
pickle.dump(awesome_thing, open("complex.sav", "wb"))

# Load the instance from save
loaded = pickle.load(open("complex.sav", "rb"))

# Print the loaded instance to verify intact data
print("\nAfter Loading from Pickle: ")
print(loaded)