text:
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;

namespace ParentLoadRO.Business.ERCLevel
{

    ///
    /// B08_Region (read only object).

    /// This is a generated base class of <see cref="B08_Region"/> business object.
    ///
    /// <remarks>
    /// This class contains one child collection:

    /// - <see cref="B09_CityObjects"/> of type <see cref="B09_CityColl"/> (1:M relation to <see cref="B10_City"/>)

    /// This class is an item of <see cref="B07_RegionColl"/> collection.
    /// </remarks>
    [Serializable]
    public partial class B08_Region : ReadOnlyBase<B08_Region>
    {

        #region State Fields

        [NotUndoable]
        [NonSerialized]
        internal int parent_Country_ID = 0;

        #endregion

        #region Business Properties

        ///
        /// Maintains metadata about <see cref="Region_ID"/> property.
        ///
        public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Region ID", -1);
        ///
        /// Gets the Region ID.
        ///
        /// <value>The Region ID.</value>
        public int Region_ID
        {
            get { return GetProperty(Region_IDProperty); }
        }

        ///
        /// Maintains metadata about <see cref="Region_Name"/> property.
        ///
        public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Region Name");
        ///
        /// Gets the Region Name.
        ///
        /// <value>The Region Name.</value>
        public string Region_Name
        {
            get { return GetProperty(Region_NameProperty); }
        }

        ///
        /// Maintains metadata about child <see cref="B09_Region_SingleObject"/> property.
        ///
        public static readonly PropertyInfo<B09_Region_Child> B09_Region_SingleObjectProperty = RegisterProperty<B09_Region_Child>(p => p.B09_Region_SingleObject, "B09 Region Single Object");
        ///
        /// Gets the B09 Region Single Object ("parent load" child property).
        ///
        /// <value>The B09 Region Single Object.</value>
        public B09_Region_Child B09_Region_SingleObject
        {
            get { return GetProperty(B09_Region_SingleObjectProperty); }
            private set { LoadProperty(B09_Region_SingleObjectProperty, value); }
        }

        ///
        /// Maintains metadata about child <see cref="B09_Region_ASingleObject"/> property.
        ///
        public static readonly PropertyInfo<B09_Region_ReChild> B09_Region_ASingleObjectProperty = RegisterProperty<B09_Region_ReChild>(p => p.B09_Region_ASingleObject, "B09 Region ASingle Object");
        ///
        /// Gets the B09 Region ASingle Object ("parent load" child property).
        ///
        /// <value>The B09 Region ASingle Object.</value>
        public B09_Region_ReChild B09_Region_ASingleObject
        {
            get { return GetProperty(B09_Region_ASingleObjectProperty); }
            private set { LoadProperty(B09_Region_ASingleObjectProperty, value); }
        }

        ///
        /// Maintains metadata about child <see cref="B09_CityObjects"/> property.
        ///
        public static readonly PropertyInfo<B09_CityColl> B09_CityObjectsProperty = RegisterProperty<B09_CityColl>(p => p.B09_CityObjects, "B09 City Objects");
        ///
        /// Gets the B09 City Objects ("parent load" child property).
        ///
        /// <value>The B09 City Objects.</value>
        public B09_CityColl B09_CityObjects
        {
            get { return GetProperty(B09_CityObjectsProperty); }
            private set { LoadProperty(B09_CityObjectsProperty, value); }
        }

        #endregion

        #region Factory Methods

        ///
        /// Factory method. Loads a <see cref="B08_Region"/> object from the given SafeDataReader.
        ///
        /// <param name="dr">The SafeDataReader to use.</param>
        /// <returns>A reference to the fetched <see cref="B08_Region"/> object.</returns>
        internal static B08_Region GetB08_Region(SafeDataReader dr)
        {
            B08_Region obj = new B08_Region();
            obj.Fetch(dr);
            obj.LoadProperty(B09_CityObjectsProperty, new B09_CityColl());
            return obj;
        }

        #endregion

        #region Constructor

        ///
        /// Initializes a new instance of the <see cref="B08_Region"/> class.
        ///
        /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
        public B08_Region()
        {
            // Use factory methods and do not use direct creation.
        }

        #endregion

        #region Data Access

        ///
        /// Loads a <see cref="B08_Region"/> object from the given SafeDataReader.
        ///
        /// <param name="dr">The SafeDataReader to use.</param>
        private void Fetch(SafeDataReader dr)
        {
            // Value properties
            LoadProperty(Region_IDProperty, dr.GetInt32("Region_ID"));
            LoadProperty(Region_NameProperty, dr.GetString("Region_Name"));
            // parent properties
            parent_Country_ID = dr.GetInt32("Parent_Country_ID");
            var args = new DataPortalHookArgs(dr);
            OnFetchRead(args);
        }

        ///
        /// Loads child <see cref="B09_Region_Child"/> object.
        ///
        /// <param name="child">The child object to load.</param>
        internal void LoadChild(B09_Region_Child child)
        {
            LoadProperty(B09_Region_SingleObjectProperty, child);
        }

        ///
        /// Loads child <see cref="B09_Region_ReChild"/> object.
        ///
        /// <param name="child">The child object to load.</param>
        internal void LoadChild(B09_Region_ReChild child)
        {
            LoadProperty(B09_Region_ASingleObjectProperty, child);
        }

        #endregion

        #region DataPortal Hooks

        ///
        /// Occurs after the low level fetch operation, before the data reader is destroyed.
        ///
        partial void OnFetchRead(DataPortalHookArgs args);

        #endregion

    }
}


text:
package com.google.cloud.channel.v1.samples;

// [START channel_v1_generated_cloudchannelserviceclient_createentitlement_lro_async]
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.channel.v1.CloudChannelServiceClient;
import com.google.cloud.channel.v1.CreateEntitlementRequest;
import com.google.cloud.channel.v1.CustomerName;
import com.google.cloud.channel.v1.Entitlement;
import com.google.cloud.channel.v1.OperationMetadata;

public class AsyncCreateEntitlementLRO {

  public static void main(String[] args) throws Exception {
    asyncCreateEntitlementLRO();
  }

  public static void asyncCreateEntitlementLRO() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudChannelServiceClient cloudChannelServiceClient = CloudChannelServiceClient.create()) {
      CreateEntitlementRequest request =
          CreateEntitlementRequest.newBuilder()
              .setParent(CustomerName.of("[ACCOUNT]", "[CUSTOMER]").toString())
              .setEntitlement(Entitlement.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      OperationFuture<Entitlement, OperationMetadata> future =
          cloudChannelServiceClient.createEntitlementOperationCallable().futureCall(request);
      // Do something.
      Entitlement response = future.get();
    }
  }
}
// [END channel_v1_generated_cloudchannelserviceclient_createentitlement_lro_async]

redpajama_set_name: RedPajamaGithub


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

namespace Zenith.Core.Shared.EventAggregation
{
    public interface IEventAggregator : IDisposable
    {
		void Publish<T>(T data);
        void Publish<T>(T data, string routingKey);
        string Subsribe<T>(Action<T> action);
        string Subsribe<T>(Action<T> action, string routingKey);
        void Unsubscribe(string token);
        void Clear();
    }
}


text:
const DrawCard = require('../../drawcard.js');

class ThisMustBeAnsweredFiercely extends DrawCard {
    setupCardAbilities() {
        this.reaction({
            when: {
                onChallengeInitiated: event =>
                    event.challenge.initiatedAgainstPlayer === this.controller && event.challenge.attackers.length >= 3
            },
            handler: () => {
                this.game.promptForDeckSearch(this.controller, {
                    activePromptTitle: 'Select a card',
                    cardCondition: card => card.getType() === 'character' && card.isFaction('tyrell')
                        && this.controller.canPutIntoPlay(card),
                    onSelect: (player, card) => this.cardSelected(player, card),
                    onCancel: player => this.doneSelecting(player),
                    source: this
                });
            }
        });
    }

    cardSelected(player, card) {
        player.putIntoPlay(card);
        this.game.addMessage('{0} uses {1} to search their deck and put {2} into play',
            player, this, card);
    }

    doneSelecting(player) {
        this.game.addMessage('{0} uses {1} to search their deck, but does not put any card into play',
            player, this);
    }
}

ThisMustBeAnsweredFiercely.code = '08104';

module.exports = ThisMustBeAnsweredFiercely;


text:
require 'bundler/setup'
Bundler.require

require 'fakefs/spec_helpers'
require 'webmock/rspec'
require 'pathname'
require 'stringio'
require 'fileutils'

RSpec.configure do |config|
  def capture(stream)
    begin
      stream = stream.to_s
      eval "$#{stream} = StringIO.new"
      yield
      result = eval("$#{stream}").string
    ensure
      eval("$#{stream} = #{stream.upcase}")
    end

    result
  end

  def silence_stdout(&block)
    capture(:stdout, &block)
  end

  def tmp_dir
    @tmp_dir ||= begin
      Pathname('/fakefs/ec2ssh').tap do |path|
        FileUtils.mkdir_p path
      end
    end
  end

  alias :silence :capture
end

require 'vcr'
VCR.configure do |config|
  config.cassette_library_dir = "fixtures/vcr_cassettes"
  config.hook_into :webmock
end


text:
package design_pattern.command;

/**
 * Created by songheng on 9/12/16.
 */
public class ModifiedCommand extends Command {

    public ModifiedCommand(String name) {
        super(name);
    }

    @Override
    public void execute(String args) {
        this.args = args;
        configOperator.modify(args);
    }

    @Override
    public void execute() {
        configOperator.modify(args);
    }
}


text:
namespace AngleSharp.Html.Dom
{
    using AngleSharp.Dom;
    using AngleSharp.Media;
    using AngleSharp.Media.Dom;
    using System;

    /// <summary>
    /// Represents the HTML audio element.
    /// </summary>
    sealed class HtmlAudioElement : HtmlMediaElement<IAudioInfo>, IHtmlAudioElement
    {
        #region Fields

        private IAudioTrackList? _audios;

        #endregion

        #region ctor

        /// <summary>
        /// Creates a new HTML audio element.
        /// </summary>
        public HtmlAudioElement(Document owner, String? prefix = null)
            : base(owner, TagNames.Audio, prefix)
        {
            _audios = null;
        }

        #endregion

        #region Properties

        public override IAudioTrackList? AudioTracks => _audios;

        #endregion
    }
}


text:
Photo Guessing Game!

Guess which labels were detected for this photo by the Google Cloud Vision API.

Game Dashboard

    Guess: <input type="text" name="guess" id="guess">

    <button onclick="submitGuess(document.getElementById('guess').value)">Submit</button>


text: DROP TABLE sequel_test_table


text:
namespace {

} // namespace

AccountSettingsDialog::AccountSettingsDialog(const Account& account, QWidget *parent)
    : QDialog(parent),
      account_(account)
{
    setupUi(this);
    setWindowTitle(tr("Account Settings"));
    setWindowIcon(QIcon(":/images/seafile.png"));
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

    mServerAddr->setText(account_.serverUrl.toString());
    mUsername->setText(account_.username);
    mUsername->setEnabled(false);

    #if defined(Q_OS_MAC)
    layout()->setContentsMargins(9, 9, 9, 9);
    layout()->setSpacing(6);
    formLayout->setSpacing(6);
    formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
    formLayout->setLabelAlignment(Qt::AlignLeft);
    formLayout->setFormAlignment(Qt::AlignLeft);
    horizontalLayout->setSpacing(6);
    #endif

    connect(mOkBtn, SIGNAL(clicked()), this, SLOT(onSubmitBtnClicked()));

    // const QRect screen = QApplication::desktop()->screenGeometry();
    // move(screen.center() - this->rect().center());
}

void AccountSettingsDialog::showWarning(const QString& msg)
{
    seafApplet->warningBox(msg, this);
}

bool AccountSettingsDialog::validateInputs()
{
    QString server_addr = mServerAddr->text().trimmed();
    QUrl url;

    if (server_addr.size() == 0) {
        showWarning(tr("Please enter the server address"));
        return false;
    } else {
        if (!server_addr.startsWith("http://") && !server_addr.startsWith("https://")) {
            showWarning(tr("%1 is not a valid server address").arg(server_addr));
            return false;
        }

        url = QUrl(server_addr, QUrl::StrictMode);
        if (!url.isValid()) {
            showWarning(tr("%1 is not a valid server address").arg(server_addr));
            return false;
        }
    }

    return true;
}

void AccountSettingsDialog::onSubmitBtnClicked()
{
    if (!validateInputs()) {
        return;
    }

    QString url = mServerAddr->text().trimmed();
    if (url != account_.serverUrl.toString()) {
        Account new_account(account_);
        new_account.serverUrl = url;
        if (seafApplet->accountManager()->replaceAccount(account_,
            new_account) < 0) {
            showWarning(tr("Failed to save account information"));
            return;
        }
        QString error;
        QUrl new_server_url = new_account.serverUrl;
        new_server_url.setPath("/");
        if (seafApplet->rpcClient()->updateReposServerHost(account_.serverUrl.host(),
            new_account.serverUrl.host(), new_server_url.toString(), &error) < 0) {
            showWarning(tr("Failed to save the changes: %1").arg(error));
            return;
        }
    }

    seafApplet->messageBox(tr("Successfully updated current account information"), this);
    accept();
}


text:
import { createMetric } from "../../builder/create";
import { getStatAsync } from "./getStatAsync";

const DefaultFormatter = (value: number) => "" + value;

/**
 * Creates a metric from CPU usage.
 *
 * @param {Process}     [currentProcess]    A current process.
 * @param {string}      [name]              A metric name.
 * @param {Function}    [formatter]         A formatter.
 * @return {string} The metric.
 */
export async function getCpuUsage(currentProcess = process, name = "node_process_cpu_usage", formatter = DefaultFormatter) {
    const stat = await getStatAsync(currentProcess.pid);
    const cpuUsage = formatter(stat.cpu);

    return createMetric(name, cpuUsage);
}


text:
package jef.database.jsqlparser.expression.operators.relational;

import jef.database.jsqlparser.expression.BinaryExpression;
import jef.database.jsqlparser.visitor.ExpressionType;
import jef.database.jsqlparser.visitor.ExpressionVisitor;

public class LikeExpression extends BinaryExpression {
    private String escape = null;

	@Override
	protected void acceptExp(ExpressionVisitor expressionVisitor) {
		expressionVisitor.visit(this);
	}

    public String getStringExpression() {
        return (isNot() ? "NOT " : "") + "LIKE";
    }

    @Override
	public void appendTo(StringBuilder sb) {
		super.appendTo(sb);
		if (escape != null) {
            sb.append(" ESCAPE ").append('\'').append(escape).append('\'');
//            retval +=  + "'" + escape + "'";
        }
	}

	public String getEscape() {
        return escape;
    }

    public void setEscape(String escape) {
        this.escape = escape;
    }

	public ExpressionType getType0() {
		return ExpressionType.like;
	}
}


text:
package com.thomasvitale.repository;

import java.util.Collection;

import com.thomasvitale.model.Quote;

public interface QuoteRepository {

	Collection<Quote> findAllQuotes();

}


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

namespace Problem14_CatLady
{
    public class StreetExtraordinaire : Cat
    {
        private int decibels;

        public StreetExtraordinaire(string name, int decibels)
        {
            this.Name = name;
            this.Decibels = decibels;
        }

        public int Decibels
        {
            get { return decibels; }
            set { decibels = value; }
        }

        public override string ToString()
        {
            return $"StreetExtraordinaire {this.Name} {this.Decibels}";
        }
    }
}


text:
package org.apache.lucene.analysis.uima;

import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.StoredDocument;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

/**
 * Testcase for {@link UIMABaseAnalyzer}
 */
public class UIMABaseAnalyzerTest extends BaseTokenStreamTestCase {

  private UIMABaseAnalyzer analyzer;

  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    analyzer = new UIMABaseAnalyzer("/uima/AggregateSentenceAE.xml", "org.apache.uima.TokenAnnotation", null);
  }

  @Override
  @After
  public void tearDown() throws Exception {
    analyzer.close();
    super.tearDown();
  }

  @Test
  public void baseUIMAAnalyzerStreamTest() throws Exception {
    TokenStream ts = analyzer.tokenStream("text", "the big brown fox jumped on the wood");
    assertTokenStreamContents(ts, new String[]{"the", "big", "brown", "fox", "jumped", "on", "the", "wood"});
  }

  @Test
  public void baseUIMAAnalyzerIntegrationTest() throws Exception {
    Directory dir = new RAMDirectory();
    IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
    // add the first doc
    Document doc = new Document();
    String dummyTitle = "this is a dummy title ";
    doc.add(new TextField("title", dummyTitle, Field.Store.YES));
    String dummyContent = "there is some content written here";
    doc.add(new TextField("contents", dummyContent, Field.Store.YES));
    writer.addDocument(doc, analyzer);
    writer.commit();

    // try the search over the first doc
    DirectoryReader directoryReader = DirectoryReader.open(dir);
    IndexSearcher indexSearcher = newSearcher(directoryReader);
    TopDocs result = indexSearcher.search(new MatchAllDocsQuery(), 1);
    assertTrue(result.totalHits > 0);
    StoredDocument d = indexSearcher.doc(result.scoreDocs[0].doc);
    assertNotNull(d);
    assertNotNull(d.getField("title"));
    assertEquals(dummyTitle, d.getField("title").stringValue());
    assertNotNull(d.getField("contents"));
    assertEquals(dummyContent, d.getField("contents").stringValue());

    // add a second doc
    doc = new Document();
    String dogmasTitle = "dogmas";
    doc.add(new TextField("title", dogmasTitle, Field.Store.YES));
    String dogmasContents = "white men can't jump";
    doc.add(new TextField("contents", dogmasContents, Field.Store.YES));
    writer.addDocument(doc, analyzer);
    writer.commit();

    directoryReader.close();
    directoryReader = DirectoryReader.open(dir);
    indexSearcher = newSearcher(directoryReader);
    result = indexSearcher.search(new MatchAllDocsQuery(), 2);
    StoredDocument d1 = indexSearcher.doc(result.scoreDocs[1].doc);
    assertNotNull(d1);
    assertNotNull(d1.getField("title"));
    assertEquals(dogmasTitle, d1.getField("title").stringValue());
    assertNotNull(d1.getField("contents"));
    assertEquals(dogmasContents, d1.getField("contents").stringValue());

    // do a matchalldocs query to retrieve both docs
    indexSearcher = newSearcher(directoryReader);
    result = indexSearcher.search(new MatchAllDocsQuery(), 2);
    assertEquals(2, result.totalHits);
    writer.close();
    indexSearcher.getIndexReader().close();
    dir.close();
  }

  @Test
  public void testRandomStrings() throws Exception {
    checkRandomData(random(), new UIMABaseAnalyzer("/uima/TestAggregateSentenceAE.xml", "org.apache.lucene.uima.ts.TokenAnnotation", null),
        100 * RANDOM_MULTIPLIER);
  }

  @Test
  public void testRandomStringsWithConfigurationParameters() throws Exception {
    Map<String, Object> cp = new HashMap<String, Object>();
    cp.put("line-end", "\r");
    checkRandomData(random(), new UIMABaseAnalyzer("/uima/TestWSTokenizerAE.xml", "org.apache.lucene.uima.ts.TokenAnnotation", cp),
        100 * RANDOM_MULTIPLIER);
  }

}


text:
using NUnit.Framework;
using SecurePrimitive;
using System;

namespace SecurePrimitive.Tests
{
    public class UInt16Tests
    {
        private Random random = new Random();

        [Test]
        public void TestEquatable()
        {
            var ushortVal = (ushort)random.Next();
            var snUInt16Val = new SPUInt16(ushortVal);

            Assert.AreEqual(ushortVal, snUInt16Val.Value);

            ushortVal = (ushort)random.Next();
            snUInt16Val = (SPUInt16)ushortVal;

            Assert.AreEqual(ushortVal, snUInt16Val.Value);

            ushortVal = 0;
            snUInt16Val = new SPUInt16();

            Assert.AreEqual(ushortVal, snUInt16Val.Value);
        }

        [Test]
        public void TestComparable()
        {
            var ushortVal1 = (ushort)random.Next();
            var ushortVal2 = (ushort)random.Next();

            var snUInt16Val1 = new SPUInt16(ushortVal1);
            var snUInt16Val2 = new SPUInt16(ushortVal2);

            Assert.AreEqual(ushortVal1.CompareTo(ushortVal2), snUInt16Val1.CompareTo(snUInt16Val2));
            Assert.AreEqual(snUInt16Val1.CompareTo(ushortVal2), snUInt16Val1.CompareTo(snUInt16Val2));
        }
    }
}


text:
namespace kj {

class EventLoop;
template <typename T>
class Promise;
class WaitScope;

template <typename T>
Promise<Array<T>> joinPromises(Array<Promise<T>>&& promises);

namespace _ {  // private

template <typename T> struct JoinPromises_ { typedef T Type; };
template <typename T> struct JoinPromises_<Promise<T>> { typedef T Type; };

template <typename T>
using JoinPromises = typename JoinPromises_<T>::Type;
// If T is Promise<U>, resolves to U, otherwise resolves to T.
//
// TODO(cleanup):  Rename to avoid confusion with joinPromises() call which is completely
//   unrelated.

class PropagateException {
  // A functor which accepts a kj::Exception as a parameter and returns a broken promise of
  // arbitrary type which simply propagates the exception.
public:
  class Bottom {
  public:
    Bottom(Exception&& exception): exception(kj::mv(exception)) {}

    Exception asException() { return kj::mv(exception); }

  private:
    Exception exception;
  };

  Bottom operator()(Exception&& e) {
    return Bottom(kj::mv(e));
  }
  Bottom operator()(const  Exception& e) {
    return Bottom(kj::cp(e));
  }
};

template <typename Func, typename T>
struct ReturnType_ { typedef decltype(instance<Func>()(instance<T>())) Type; };
template <typename Func>
struct ReturnType_<Func, void> { typedef decltype(instance<Func>()()) Type; };

template <typename Func, typename T>
using ReturnType = typename ReturnType_<Func, T>::Type;
// The return type of functor Func given a parameter of type T, with the special exception that if
// T is void, this is the return type of Func called with no arguments.

struct Void {};
// Application code should NOT refer to this!  See `kj::READY_NOW` instead.

template <typename T> struct FixVoid_ { typedef T Type; };
template <> struct FixVoid_<void> { typedef Void Type; };
template <typename T> using FixVoid = typename FixVoid_<T>::Type;
// FixVoid<T> is just T unless T is void in which case it is _::Void (an empty struct).

template <typename T> struct UnfixVoid_ { typedef T Type; };
template <> struct UnfixVoid_<Void> { typedef void Type; };
template <typename T> using UnfixVoid = typename UnfixVoid_<T>::Type;
// UnfixVoid is the opposite of FixVoid.

template <typename In, typename Out>
struct MaybeVoidCaller {
  // Calls the function converting a Void input to an empty parameter list and a void return
  // value to a Void output.

  template <typename Func>
  static inline Out apply(Func& func, In&& in) {
    return func(kj::mv(in));
  }
};
template <typename In, typename Out>
struct MaybeVoidCaller<In&, Out> {
  template <typename Func>
  static inline Out apply(Func& func, In& in) {
    return func(in);
  }
};
template <typename Out>
struct MaybeVoidCaller<Void, Out> {
  template <typename Func>
  static inline Out apply(Func& func, Void&& in) {
    return func();
  }
};
template <typename In>
struct MaybeVoidCaller<In, Void> {
  template <typename Func>
  static inline Void apply(Func& func, In&& in) {
    func(kj::mv(in));
    return Void();
  }
};
template <typename In>
struct MaybeVoidCaller<In&, Void> {
  template <typename Func>
  static inline Void apply(Func& func, In& in) {
    func(in);
    return Void();
  }
};
template <>
struct MaybeVoidCaller<Void, Void> {
  template <typename Func>
  static inline Void apply(Func& func, Void&& in) {
    func();
    return Void();
  }
};

template <typename T>
inline T&& returnMaybeVoid(T&& t) {
  return kj::fwd<T>(t);
}
inline void returnMaybeVoid(Void&& v) {}

class ExceptionOrValue;
class PromiseNode;
class ChainPromiseNode;
template <typename T>
class ForkHub;

class TaskSetImpl;

class Event;

class PromiseBase {
public:
  kj::String trace();
  // Dump debug info about this promise.

private:
  Own<PromiseNode> node;

  PromiseBase() = default;
  PromiseBase(Own<PromiseNode>&& node): node(kj::mv(node)) {}

  friend class kj::EventLoop;
  friend class ChainPromiseNode;
  template <typename>
  friend class kj::Promise;
  friend class TaskSetImpl;
  template <typename U>
  friend Promise<Array<U>> kj::joinPromises(Array<Promise<U>>&& promises);
};

void detach(kj::Promise<void>&& promise);
void waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, WaitScope& waitScope);
Promise<void> yield();
Own<PromiseNode> neverDone();

class NeverDone {
public:
  template <typename T>
  operator Promise<T>() const {
    return Promise<T>(false, neverDone());
  }

  void wait(WaitScope& waitScope) const KJ_NORETURN;
};

}  // namespace _ (private)
}  // namespace kj

#endif  // KJ_ASYNC_PRELUDE_H_


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/enrollment/enrollment_screen.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/timer/elapsed_timer.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/chromeos/login/enrollment/enrollment_uma.h"
#include "chrome/browser/chromeos/login/screen_manager.h"
#include "chrome/browser/chromeos/login/screens/base_screen_delegate.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/enrollment_status_chromeos.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_method_call_status.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/pairing/controller_pairing_controller.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "google_apis/gaia/gaia_auth_util.h"

using namespace pairing_chromeos;
using policy::EnrollmentConfig;

// Do not change the UMA histogram parameters without renaming the histograms!
#define UMA_ENROLLMENT_TIME(histogram_name, elapsed_timer) \
  do {                                                     \
    UMA_HISTOGRAM_CUSTOM_TIMES(                            \
      (histogram_name),                                    \
      (elapsed_timer)->Elapsed(),                          \
      base::TimeDelta::FromMilliseconds(100) /* min */,    \
      base::TimeDelta::FromMinutes(15) /* max */,          \
      100 /* bucket_count */);                             \
  } while (0)

namespace {

const char * const kMetricEnrollmentTimeCancel =
    "Enterprise.EnrollmentTime.Cancel";
const char * const kMetricEnrollmentTimeFailure =
    "Enterprise.EnrollmentTime.Failure";
const char * const kMetricEnrollmentTimeSuccess =
    "Enterprise.EnrollmentTime.Success";

}  // namespace

namespace chromeos {

// static
EnrollmentScreen* EnrollmentScreen::Get(ScreenManager* manager) {
  return static_cast<EnrollmentScreen*>(
      manager->GetScreen(OobeScreen::SCREEN_OOBE_ENROLLMENT));
}

EnrollmentScreen::EnrollmentScreen(BaseScreenDelegate* base_screen_delegate,
                                   EnrollmentScreenActor* actor)
    : BaseScreen(base_screen_delegate, OobeScreen::SCREEN_OOBE_ENROLLMENT),
      actor_(actor),
      weak_ptr_factory_(this) {}

EnrollmentScreen::~EnrollmentScreen() {
  DCHECK(!enrollment_helper_ || g_browser_process->IsShuttingDown());
}

void EnrollmentScreen::SetParameters(
    const policy::EnrollmentConfig& enrollment_config,
    pairing_chromeos::ControllerPairingController* shark_controller) {
  enrollment_config_ = enrollment_config;
  switch (enrollment_config_.auth_mechanism) {
    case EnrollmentConfig::AUTH_MECHANISM_INTERACTIVE:
      current_auth_ = AUTH_OAUTH;
      last_auth_ = AUTH_OAUTH;
      break;
    case EnrollmentConfig::AUTH_MECHANISM_ATTESTATION:
      current_auth_ = AUTH_ATTESTATION;
      last_auth_ = AUTH_ATTESTATION;
      break;
    case EnrollmentConfig::AUTH_MECHANISM_BEST_AVAILABLE:
      current_auth_ = AUTH_ATTESTATION;
      last_auth_ = enrollment_config_.should_enroll_interactively()
                       ? AUTH_OAUTH
                       : AUTH_ATTESTATION;
      break;
    default:
      NOTREACHED();
      break;
  }
  shark_controller_ = shark_controller;
  SetConfig();
}

void EnrollmentScreen::SetConfig() {
  config_ = enrollment_config_;
  if (current_auth_ == AUTH_ATTESTATION) {
    config_.mode = enrollment_config_.is_attestation_forced()
                       ? policy::EnrollmentConfig::MODE_ATTESTATION_FORCED
                       : policy::EnrollmentConfig::MODE_ATTESTATION;
  }
  actor_->SetParameters(this, config_);
  enrollment_helper_ = nullptr;
}

bool EnrollmentScreen::AdvanceToNextAuth() {
  if (current_auth_ != last_auth_ && current_auth_ == AUTH_ATTESTATION) {
    current_auth_ = AUTH_OAUTH;
    SetConfig();
    return true;
  }
  return false;
}

void EnrollmentScreen::CreateEnrollmentHelper() {
  if (!enrollment_helper_) {
    enrollment_helper_ = EnterpriseEnrollmentHelper::Create(
        this, config_, enrolling_user_domain_);
  }
}

void EnrollmentScreen::ClearAuth(const base::Closure& callback) {
  if (!enrollment_helper_) {
    callback.Run();
    return;
  }
  enrollment_helper_->ClearAuth(base::Bind(&EnrollmentScreen::OnAuthCleared,
                                           weak_ptr_factory_.GetWeakPtr(),
                                           callback));
}

void EnrollmentScreen::OnAuthCleared(const base::Closure& callback) {
  enrollment_helper_ = nullptr;
  callback.Run();
}

void EnrollmentScreen::Show() {
  UMA(policy::kMetricEnrollmentTriggered);
  switch (current_auth_) {
    case AUTH_OAUTH:
      ShowInteractiveScreen();
      break;
    case AUTH_ATTESTATION:
      AuthenticateUsingAttestation();
      break;
    default:
      NOTREACHED();
      break;
  }
}

void EnrollmentScreen::ShowInteractiveScreen() {
  ClearAuth(base::Bind(&EnrollmentScreen::ShowSigninScreen,
                       weak_ptr_factory_.GetWeakPtr()));
}

void EnrollmentScreen::Hide() {
  actor_->Hide();
  weak_ptr_factory_.InvalidateWeakPtrs();
}

void EnrollmentScreen::AuthenticateUsingAttestation() {
  VLOG(1) << "Authenticating using attestation.";
  elapsed_timer_.reset(new base::ElapsedTimer());
  actor_->Show();
  CreateEnrollmentHelper();
  enrollment_helper_->EnrollUsingAttestation();
}

void EnrollmentScreen::OnLoginDone(const std::string& user,
                                   const std::string& auth_code) {
  LOG_IF(ERROR, auth_code.empty()) << "Auth code is empty.";
  elapsed_timer_.reset(new base::ElapsedTimer());
  enrolling_user_domain_ = gaia::ExtractDomainName(user);
  auth_code_ = auth_code;
  // TODO(rsorokin): Move ShowAdJoin after STEP_REGISTRATION
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          chromeos::switches::kEnableAd)) {
    actor_->ShowAdJoin();
  } else {
    OnAdJoined("");
  }
}

void EnrollmentScreen::OnRetry() {
  Show();
}

void EnrollmentScreen::OnCancel() {
  if (AdvanceToNextAuth()) {
    Show();
    return;
  }

  UMA(policy::kMetricEnrollmentCancelled);
  if (elapsed_timer_)
    UMA_ENROLLMENT_TIME(kMetricEnrollmentTimeCancel, elapsed_timer_);

  const BaseScreenDelegate::ExitCodes exit_code =
      config_.is_forced() ? BaseScreenDelegate::ENTERPRISE_ENROLLMENT_BACK
                          : BaseScreenDelegate::ENTERPRISE_ENROLLMENT_COMPLETED;
  ClearAuth(
      base::Bind(&EnrollmentScreen::Finish, base::Unretained(this), exit_code));
}

void EnrollmentScreen::OnConfirmationClosed() {
  ClearAuth(base::Bind(&EnrollmentScreen::Finish, base::Unretained(this),
                       BaseScreenDelegate::ENTERPRISE_ENROLLMENT_COMPLETED));
}

void EnrollmentScreen::OnAdJoined(const std::string& realm) {
  if (!realm.empty()) {
    config_.management_realm = realm;
  }
  UMA(enrollment_failed_once_ ? policy::kMetricEnrollmentRestarted
                              : policy::kMetricEnrollmentStarted);

  actor_->ShowEnrollmentSpinnerScreen();
  CreateEnrollmentHelper();
  enrollment_helper_->EnrollUsingAuthCode(
      auth_code_, shark_controller_ != NULL /* fetch_additional_token */);
}

void EnrollmentScreen::OnAuthError(const GoogleServiceAuthError& error) {
  RecordEnrollmentErrorMetrics();
  actor_->ShowAuthError(error);
}

void EnrollmentScreen::OnEnrollmentError(policy::EnrollmentStatus status) {
  // TODO(pbond): remove this LOG once http://crbug.com/586961 is fixed.
  LOG(WARNING) << "Enrollment error occured: status=" << status.status()
               << " http status=" << status.http_status()
               << " DM status=" << status.client_status();
  RecordEnrollmentErrorMetrics();
  // If the DM server does not have a device pre-provisioned for attestation-
  // based enrollment and we have a fallback authentication, show it.
  if (status.status() == policy::EnrollmentStatus::REGISTRATION_FAILED &&
      status.client_status() == policy::DM_STATUS_SERVICE_DEVICE_NOT_FOUND &&
      current_auth_ == AUTH_ATTESTATION && AdvanceToNextAuth())
    Show();
  else
    actor_->ShowEnrollmentStatus(status);
}

void EnrollmentScreen::OnOtherError(
    EnterpriseEnrollmentHelper::OtherError error) {
  RecordEnrollmentErrorMetrics();
  actor_->ShowOtherError(error);
}

void EnrollmentScreen::OnDeviceEnrolled(const std::string& additional_token) {
  // TODO(pbond): remove this LOG once http://crbug.com/586961 is fixed.
  LOG(WARNING) << "Device is successfully enrolled.";
  if (!additional_token.empty())
    SendEnrollmentAuthToken(additional_token);

  enrollment_helper_->GetDeviceAttributeUpdatePermission();
}

void EnrollmentScreen::OnDeviceAttributeProvided(const std::string& asset_id,
                                                 const std::string& location) {
  enrollment_helper_->UpdateDeviceAttributes(asset_id, location);
}

void EnrollmentScreen::OnDeviceAttributeUpdatePermission(bool granted) {
  // If user is permitted to update device attributes
  // Show attribute prompt screen
  if (granted) {
    // TODO(pbond): remove this LOG once http://crbug.com/586961 is fixed.
    LOG(WARNING) << "Show device attribute prompt screen";
    StartupUtils::MarkDeviceRegistered(
        base::Bind(&EnrollmentScreen::ShowAttributePromptScreen,
                   weak_ptr_factory_.GetWeakPtr()));
  } else {
    // TODO(pbond): remove this LOG once http://crbug.com/586961 is fixed.
    LOG(WARNING) << "The device attribute update is not permitted";
    StartupUtils::MarkDeviceRegistered(
        base::Bind(&EnrollmentScreen::ShowEnrollmentStatusOnSuccess,
                   weak_ptr_factory_.GetWeakPtr()));
  }

}

void EnrollmentScreen::OnDeviceAttributeUploadCompleted(bool success) {
  if (success) {
    // If the device attributes have been successfully uploaded, fetch policy.
    policy::BrowserPolicyConnectorChromeOS* connector =
        g_browser_process->platform_part()->browser_policy_connector_chromeos();
    connector->GetDeviceCloudPolicyManager()->core()->RefreshSoon();
    actor_->ShowEnrollmentStatus(
        policy::EnrollmentStatus::ForStatus(policy::EnrollmentStatus::SUCCESS));
  } else {
    actor_->ShowEnrollmentStatus(policy::EnrollmentStatus::ForStatus(
        policy::EnrollmentStatus::ATTRIBUTE_UPDATE_FAILED));
  }
}

void EnrollmentScreen::ShowAttributePromptScreen() {
  policy::BrowserPolicyConnectorChromeOS* connector =
      g_browser_process->platform_part()->browser_policy_connector_chromeos();
  policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
      connector->GetDeviceCloudPolicyManager();

  policy::CloudPolicyStore* store = policy_manager->core()->store();

  const enterprise_management::PolicyData* policy = store->policy();

  std::string asset_id = policy ? policy->annotated_asset_id() : std::string();
  std::string location = policy ? policy->annotated_location() : std::string();
  actor_->ShowAttributePromptScreen(asset_id, location);
}

void EnrollmentScreen::SendEnrollmentAuthToken(const std::string& token) {
  DCHECK(shark_controller_);
  shark_controller_->OnAuthenticationDone(enrolling_user_domain_, token);
}

void EnrollmentScreen::ShowEnrollmentStatusOnSuccess() {
  if (elapsed_timer_)
    UMA_ENROLLMENT_TIME(kMetricEnrollmentTimeSuccess, elapsed_timer_);
  actor_->ShowEnrollmentStatus(
      policy::EnrollmentStatus::ForStatus(policy::EnrollmentStatus::SUCCESS));
}

void EnrollmentScreen::UMA(policy::MetricEnrollment sample) {
  EnrollmentUMA(sample, config_.mode);
}

void EnrollmentScreen::ShowSigninScreen() {
  actor_->Show();
  actor_->ShowSigninScreen();
}

void EnrollmentScreen::RecordEnrollmentErrorMetrics() {
  enrollment_failed_once_ = true;
  //  TODO(drcrash): Maybe create multiple metrics (http://crbug.com/640313)?
  if (elapsed_timer_)
    UMA_ENROLLMENT_TIME(kMetricEnrollmentTimeFailure, elapsed_timer_);
}

}  // namespace chromeos


text:
import { waitFor } from '@testing-library/dom';
import { fireEvent, render, RenderResult } from '@testing-library/react';
import React from 'react';
import {
  Commands,
  mockCore,
  mockNotifications,
  RendererActionSlot,
} from 'react-cosmos-shared2/ui';
import { loadPlugins, resetPlugins } from 'react-plugin';
import { mockFetch } from './testHelpers';

beforeEach(() => jest.isolateModules(() => require('.')));

afterEach(resetPlugins);

const fixtureId = { path: 'foo.js' };

async function loadTestPlugins() {
  loadPlugins();
  return render(
    <RendererActionSlot slotProps={{ fixtureId }} plugOrder={[]} />
  );
}

function clickButton({ getByTitle }: RenderResult) {
  const editBtn = getByTitle(/open fixture source/i);
  fireEvent.click(editBtn);
}

it(`doesn't render button when dev server is off`, async () => {
  mockCore({ isDevServerOn: () => false });
  mockNotifications();

  const { queryByTitle } = await loadTestPlugins();
  expect(queryByTitle(/open fixture source/i)).toBeNull();
});

it(`shows error notification when dev server is off`, async () => {
  let registeredCommands: Commands = {};
  mockCore({
    isDevServerOn: () => false,
    registerCommands: (context, commands) => {
      registeredCommands = commands;
      return () => {
        registeredCommands = {};
      };
    },
  });
  const { pushTimedNotification } = mockNotifications();

  await loadTestPlugins();
  registeredCommands.editFixture();

  await waitFor(() =>
    expect(pushTimedNotification).toBeCalledWith(expect.any(Object), {
      id: expect.any(String),
      type: 'error',
      title: 'Failed to open fixture',
      info: 'Static exports cannot access source files.',
    })
  );
});

it('renders button', async () => {
  mockCore({ isDevServerOn: () => true });
  mockNotifications();

  const { getByTitle } = await loadTestPlugins();
  getByTitle(/open fixture source/i);
});

it('calls server endpoint on button click', async () => {
  await mockFetch(200, async fetchMock => {
    mockCore({ isDevServerOn: () => true });
    mockNotifications();

    const renderer = await loadTestPlugins();
    clickButton(renderer);

    const openFileUrl = `/_open?filePath=${fixtureId.path}`;
    expect(fetchMock).toBeCalledWith(openFileUrl, expect.any(Object));
  });
});

it('shows 400 error notification', async () => {
  await mockFetch(400, async () => {
    mockCore({ isDevServerOn: () => true });
    const { pushTimedNotification } = mockNotifications();

    const renderer = await loadTestPlugins();
    clickButton(renderer);

    await waitFor(() =>
      expect(pushTimedNotification).toBeCalledWith(expect.any(Object), {
        id: expect.any(String),
        type: 'error',
        title: 'Failed to open fixture',
        info: 'This looks like a bug. Please let us know!',
      })
    );
  });
});

it('shows 404 error notification', async () => {
  await mockFetch(404, async () => {
    mockCore({ isDevServerOn: () => true });
    const { pushTimedNotification } = mockNotifications();

    const renderer = await loadTestPlugins();
    clickButton(renderer);

    await waitFor(() =>
      expect(pushTimedNotification).toBeCalledWith(expect.any(Object), {
        id: expect.any(String),
        type: 'error',
        title: 'Failed to open fixture',
        info: 'File is missing. Weird!',
      })
    );
  });
});

it('shows 500 error notification', async () => {
  await mockFetch(500, async () => {
    mockCore({ isDevServerOn: () => true });
    const { pushTimedNotification } = mockNotifications();

    const renderer = await loadTestPlugins();
    clickButton(renderer);

    await waitFor(() =>
      expect(pushTimedNotification).toBeCalledWith(expect.any(Object), {
        id: expect.any(String),
        type: 'error',
        title: 'Failed to open fixture',
        info: 'Does your OS know to open source files with your code editor?',
      })
    );
  });
});


text:
'use strict';

var scatterAttrs = require('../scatter/attributes');
var plotAttrs = require('../../plots/attributes');
var colorAttributes = require('../../components/colorscale/color_attributes');

var extendFlat = require('../../lib/extend').extendFlat;

var scatterMarkerAttrs = scatterAttrs.marker,
    scatterLineAttrs = scatterAttrs.line,
    scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = {
    a: {
        valType: 'data_array',
        description: [
            'Sets the quantity of component `a` in each data point.',
            'If `a`, `b`, and `c` are all provided, they need not be',
            'normalized, only the relative values matter. If only two',
            'arrays are provided they must be normalized to match',
            '`ternary<i>.sum`.'
        ].join(' ')
    },
    b: {
        valType: 'data_array',
        description: [
            'Sets the quantity of component `a` in each data point.',
            'If `a`, `b`, and `c` are all provided, they need not be',
            'normalized, only the relative values matter. If only two',
            'arrays are provided they must be normalized to match',
            '`ternary<i>.sum`.'
        ].join(' ')
    },
    c: {
        valType: 'data_array',
        description: [
            'Sets the quantity of component `a` in each data point.',
            'If `a`, `b`, and `c` are all provided, they need not be',
            'normalized, only the relative values matter. If only two',
            'arrays are provided they must be normalized to match',
            '`ternary<i>.sum`.'
        ].join(' ')
    },
    sum: {
        valType: 'number',
        role: 'info',
        dflt: 0,
        min: 0,
        description: [
            'The number each triplet should sum to,',
            'if only two of `a`, `b`, and `c` are provided.',
            'This overrides `ternary<i>.sum` to normalize this specific',
            'trace, but does not affect the values displayed on the axes.',
            '0 (or missing) means to use ternary<i>.sum'
        ].join(' ')
    },
    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),
    text: extendFlat({}, scatterAttrs.text, {
        description: [
            'Sets text elements associated with each (a,b,c) point.',
            'If a single string, the same string appears over',
            'all the data points.',
            'If an array of strings, the items are mapped in order to the',
            'the data points in (a,b,c).'
        ].join(' ')
    }),
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: scatterLineAttrs.dash,
        shape: extendFlat({}, scatterLineAttrs.shape,
            {values: ['linear', 'spline']}),
        smoothing: scatterLineAttrs.smoothing
    },
    connectgaps: scatterAttrs.connectgaps,
    fill: extendFlat({}, scatterAttrs.fill, {
        values: ['none', 'toself', 'tonext'],
        description: [
            'Sets the area to fill with a solid color.',
            'Use with `fillcolor` if not *none*.',
            'scatterternary has a subset of the options available to scatter.',
            '*toself* connects the endpoints of the trace (or each segment',
            'of the trace if it has gaps) into a closed shape.',
            '*tonext* fills the space between two traces if one completely',
            'encloses the other (eg consecutive contour lines), and behaves like',
            '*toself* if there is no trace before it. *tonext* should not be',
            'used if one trace does not enclose the other.'
        ].join(' ')
    }),
    fillcolor: scatterAttrs.fillcolor,
    marker: extendFlat({}, {
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        maxdisplayed: scatterMarkerAttrs.maxdisplayed,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        showscale: scatterMarkerAttrs.showscale,
        line: extendFlat({},
            {width: scatterMarkerLineAttrs.width},
            colorAttributes('marker'.line)
        )
    },
        colorAttributes('marker')
    ),
    textfont: scatterAttrs.textfont,
    textposition: scatterAttrs.textposition,
    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['a', 'b', 'c', 'text', 'name']
    }),
    hoveron: scatterAttrs.hoveron,
    _nestedModules: {
        'marker.colorbar': 'Colorbar'
    }
};


text:
namespace OrchardCore.Cors.Settings
{
    public class CorsPolicySetting
    {
        public string Name { get; set; }

        public bool AllowAnyOrigin { get; set; }

        public string[] AllowedOrigins { get; set; }

        public bool AllowAnyHeader { get; set; }

        public string[] AllowedHeaders { get; set; }

        public bool AllowAnyMethod { get; set; }

        public string[] AllowedMethods { get; set; }

        public bool AllowCredentials { get; set; }

        public bool IsDefaultPolicy { get; set; }
    }
}


text:
package com.arm4j.weixin.request.tags;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.arm4j.core.DefaultEntityParam;
import com.arm4j.core.DefaultURLParam;
import com.arm4j.weixin.WeiXinCoreManagement;
import com.arm4j.weixin.WeiXinToken;
import com.arm4j.weixin.exception.WeiXinRequestException;
import org.apache.commons.lang3.StringUtils;

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

@SuppressWarnings("unchecked")
public class WeiXinTagsMembersBatchTaggingRequest {

    public static void request(String accessToken, int tagid, List<String> openidList) throws WeiXinRequestException {
        Map<String, Object> tagMap = new HashMap<>();
        tagMap.put("tagid", tagid);
        tagMap.put("openid_list", openidList);

        // 发送请求
        String result = WeiXinCoreManagement.getInstance().get(WeiXinToken.TAGS_MEMBERS_BATCHTAGGING)
                .createConn()
                .connect(
                        new DefaultURLParam.Builder()
                                .add("access_token", accessToken)
                                .build(),
                        new DefaultEntityParam(JSON.toJSONString(tagMap))
                ).doPost();

        // 处理返回结果
        if (!StringUtils.isEmpty(result)) {
            JSONObject resultJSON = JSON.parseObject(result);
            int errCode = resultJSON.getInteger("errcode");
            if (0 != errCode) {
                throw new WeiXinRequestException(result);
            }
        } else {
            throw new WeiXinRequestException("请求失败,原因[未知]");
        }
    }

}


text:
package org.elasticsearch.xpack.core.ml.inference.preprocessing;

import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.core.ml.utils.MapHelper;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * PreProcessor for frequency encoding a set of categorical values for a given field.
 */
public class FrequencyEncoding implements LenientlyParsedPreProcessor, StrictlyParsedPreProcessor {

    private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(FrequencyEncoding.class);

    public static final ParseField NAME = new ParseField("frequency_encoding");
    public static final ParseField FIELD = new ParseField("field");
    public static final ParseField FEATURE_NAME = new ParseField("feature_name");
    public static final ParseField FREQUENCY_MAP = new ParseField("frequency_map");

    public static final ConstructingObjectParser<FrequencyEncoding, Void> STRICT_PARSER = createParser(false);
    public static final ConstructingObjectParser<FrequencyEncoding, Void> LENIENT_PARSER = createParser(true);

    @SuppressWarnings("unchecked")
    private static ConstructingObjectParser<FrequencyEncoding, Void> createParser(boolean lenient) {
        ConstructingObjectParser<FrequencyEncoding, Void> parser = new ConstructingObjectParser<>(
            NAME.getPreferredName(),
            lenient,
            a -> new FrequencyEncoding((String)a[0], (String)a[1], (Map<String, Double>)a[2]));
        parser.declareString(ConstructingObjectParser.constructorArg(), FIELD);
        parser.declareString(ConstructingObjectParser.constructorArg(), FEATURE_NAME);
        parser.declareObject(ConstructingObjectParser.constructorArg(),
            (p, c) -> p.map(HashMap::new, XContentParser::doubleValue),
            FREQUENCY_MAP);
        return parser;
    }

    public static FrequencyEncoding fromXContentStrict(XContentParser parser) {
        return STRICT_PARSER.apply(parser, null);
    }

    public static FrequencyEncoding fromXContentLenient(XContentParser parser) {
        return LENIENT_PARSER.apply(parser, null);
    }

    private final String field;
    private final String featureName;
    private final Map<String, Double> frequencyMap;

    public FrequencyEncoding(String field, String featureName, Map<String, Double> frequencyMap) {
        this.field = ExceptionsHelper.requireNonNull(field, FIELD);
        this.featureName = ExceptionsHelper.requireNonNull(featureName, FEATURE_NAME);
        this.frequencyMap = Collections.unmodifiableMap(ExceptionsHelper.requireNonNull(frequencyMap, FREQUENCY_MAP));
    }

    public FrequencyEncoding(StreamInput in) throws IOException {
        this.field = in.readString();
        this.featureName = in.readString();
        this.frequencyMap = Collections.unmodifiableMap(in.readMap(StreamInput::readString, StreamInput::readDouble));
    }

    /**
     * @return Field name on which to frequency encode
     */
    public String getField() {
        return field;
    }

    /**
     * @return Map of Value: frequency for the frequency encoding
     */
    public Map<String, Double> getFrequencyMap() {
        return frequencyMap;
    }

    /**
     * @return The encoded feature name
     */
    public String getFeatureName() {
        return featureName;
    }

    @Override
    public Map<String, String> reverseLookup() {
        return Collections.singletonMap(featureName, field);
    }

    @Override
    public String getName() {
        return NAME.getPreferredName();
    }

    @Override
    public void process(Map<String, Object> fields) {
        Object value = MapHelper.dig(field, fields);
        if (value == null) {
            return;
        }
        fields.put(featureName, frequencyMap.getOrDefault(value.toString(), 0.0));
    }

    @Override
    public String getWriteableName() {
        return NAME.getPreferredName();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeString(field);
        out.writeString(featureName);
        out.writeMap(frequencyMap, StreamOutput::writeString, StreamOutput::writeDouble);
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.field(FIELD.getPreferredName(), field);
        builder.field(FEATURE_NAME.getPreferredName(), featureName);
        builder.field(FREQUENCY_MAP.getPreferredName(), frequencyMap);
        builder.endObject();
        return builder;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        FrequencyEncoding that = (FrequencyEncoding) o;
        return Objects.equals(field, that.field)
            && Objects.equals(featureName, that.featureName)
            && Objects.equals(frequencyMap, that.frequencyMap);
    }

    @Override
    public int hashCode() {
        return Objects.hash(field, featureName, frequencyMap);
    }

    @Override
    public long ramBytesUsed() {
        long size = SHALLOW_SIZE;
        size += RamUsageEstimator.sizeOf(field);
        size += RamUsageEstimator.sizeOf(featureName);
        // defSize:0 indicates that there is not a defined size. Finding the shallowSize of Double gives the best estimate
        size += RamUsageEstimator.sizeOfMap(frequencyMap, 0);
        return size;
    }

    @Override
    public String toString() {
        return Strings.toString(this);
    }
}


text:
package com.intellij.jsonpath.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface JsonPathFilterExpression extends PsiElement {

  @Nullable
  JsonPathExpression getExpression();

}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using System;

namespace JsonRpc.Tests
{
	[TestClass]
	public class JsonRpcProcessorProviderTests
	{
		private const string Method1Name = "method1";
		private const string Method2Name = "method2";
		private const string Method3Name = "method3";

		[TestMethod]
		[ExpectedException(typeof(InvalidOperationException))]
		public void CheckRegisterExistingJsonRpcService()
		{
			var provider = CreateProvider();

			provider.Register<TestJsonRpcService>(o =>
			{
			});
		}

		[TestMethod]
		[ExpectedException(typeof(InvalidOperationException))]
		public void CheckRegisterExistingJsonRpcMethod()
		{
			var provider = new JsonRpcProcessorProvider().Register<TestJsonRpcService>(o =>
			{
				o.RegisterJsonRpcMethod(Method1Name, s => s.Method1());
				o.RegisterJsonRpcMethod(Method2Name, s => s.Method2(0, 0));
				o.RegisterJsonRpcMethod(Method3Name, s => s.Method3(null));
				o.RegisterJsonRpcMethod(Method3Name, s => s.Method3(null));
			});

			provider.Get<TestJsonRpcService>();
		}

		[TestMethod]
		public void CheckCreatedProcessorType()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			Assert.IsInstanceOfType(processor, typeof(IJsonRpcProcessor));
		}

		[TestMethod]
		public void CheckReturnedResponseType()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var result = processor.Process($"{{'method' : '{Method1Name}', 'id': '1'}}");

			Assert.IsInstanceOfType(result, typeof(JsonRpcResponse));
		}

		[TestMethod]
		public void CheckReturnedResponseValue()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var result = processor.Process($"{{'method' : '{Method1Name}', 'id': '1'}}");

			Assert.AreEqual("Ok", result.Result);
		}

		[TestMethod]
		public void CheckReturnedResponseSumValueWithArrayParams()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			int x = 1, y = 2;

			var result = processor.Process($"{{'method' : '{Method2Name}', 'params': [{x},{y}], 'id': '1'}}");

			Assert.AreEqual(x + y, result.Result);
		}

		[TestMethod]
		public void CheckReturnedResponseSumValueWithRequestModelParams()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var testRequestModel = new TestRequestModel
			{
				X = 1,
				Y = 2
			};

			var parameters = JsonConvert.SerializeObject(testRequestModel);

			var result = processor.Process($"{{'method' : '{Method2Name}', 'params': {parameters}, 'id': '1'}}");

			Assert.AreEqual(testRequestModel.X + testRequestModel.Y, result.Result);
		}

		[TestMethod]
		public void CheckReturnedResponseSumValueWithInvalidRequestModelParams()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var testRequestModel = new
			{
				X = 1,
				Z = 2
			};

			var parameters = JsonConvert.SerializeObject(testRequestModel);

			var result = processor.Process($"{{'method' : '{Method2Name}', 'params': {parameters}, 'id': '1'}}") as JsonRpcErrorResponse;

			Assert.IsTrue(result.Error != null && !String.IsNullOrWhiteSpace(result.Error.Message) && result.Error.Code == JsonRpcErrorCodes.InvalidParams);
		}

		[TestMethod]
		public void CheckReturnedErrorResponseType()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var result = processor.Process($"error");

			Assert.IsInstanceOfType(result, typeof(JsonRpcErrorResponse));
		}

		[TestMethod]
		public void CheckReturnedErrorResponseValue()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var result = processor.Process($"error") as JsonRpcErrorResponse;

			Assert.IsTrue(result.Error != null && !String.IsNullOrWhiteSpace(result.Error.Message) && result.Error.Code == JsonRpcErrorCodes.ParseError);
		}

		[TestMethod]
		public void CheckReturnedErrorResponseMethodNotFound()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var result = processor.Process($"{{'method':'invalidMethodName', 'id': '1'}}") as JsonRpcErrorResponse;

			Assert.IsTrue(result.Error != null && !String.IsNullOrWhiteSpace(result.Error.Message) && result.Error.Code == JsonRpcErrorCodes.MethodNotFound);
		}

		[TestMethod]
		public void CheckReturnedResponseId()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var id = Guid.NewGuid();

			var result = processor.Process($"{{'method':'{Method1Name}', 'id': '{id}'}}");

			Assert.AreEqual(id, Guid.Parse(result.Id));
		}

		[TestMethod]
		public void CheckReturnedResponseWithoutId()
		{
			var provider = CreateProvider();

			var processor = provider.Get<TestJsonRpcService>();

			var result = processor.Process($"{{'method':'{Method1Name}' }}");

			Assert.AreEqual(result, null);
		}

		private IJsonRpcProcessorProvider CreateProvider()
		{
			return new JsonRpcProcessorProvider().Register<TestJsonRpcService>(o =>
			{
				o.RegisterJsonRpcMethod(Method1Name, s => s.Method1());
				o.RegisterJsonRpcMethod(Method2Name, s => s.Method2(0, 0));
				o.RegisterJsonRpcMethod(Method3Name, s => s.Method3(null));
			});
		}
	}
}


text:
layout: post
title:  "Temperature Control"
date:   2014-06-01
categories: [brewery]
---

I've been brewing on the brewstand for a while now.
I've worked out a system for getting mash temperatures right -- even with a HERMS system, it's not as easy as it might seem!

To review, a HERMS (heat exchanger recirculating mash system) maintains mash temperature by pumping the wort through a heat exchanger (a copper coil in my case) in the hot liquor tank.
The hot liquor tank is temperature controlled.
Other options are RIMS (recirculating infusion mash system), which circulates wort through a tube with a heating element; and directly heating the mash tun.
Both of these options have the disadvantage of directly heating the wort, which may send it over 170°F (the temperature range where the diastatic enzymes denature) a little bit at a time.

Mashing In
==========

The obvious choice for mashing in with a HERMS is to heat the hot liquor tank to the desired mash temp (say, 152°F), draw off the strike water into the mash tun, and dough in.
There are two problems with this.
First, those 15lbs or so of grain and the heat mass of the mash tun will pull the overall mash temperature down 10-20°F.
Second, there is a temperature differential of about 4°F between the hot liquor tank and the mash tun.
So, for that 152°F mash, the HLT should be at 156°F, but once the water hits the mash tun, it's at something closer to 135°F -- way too low.
With a 1500W element, it takes almost an hour to get that mass back up to 152°F, meaning a slow ramp through the β-Amylase range ultimately a very thin-bodied beer.

The solution to this quandry is to strike at an appropriate temperature for the mash, just like an infusion mash, then start the recirculation once hte HLT is near the target temperature.
To accelerate the brewday, I heat all of the brewing liquor in the boil kettle, where the 5500W element can get it to temperature in under a half-hour.
I then transfer the strike water directly to the mash tun, then pump the rest into the hot liquor tank.

There's one more temperature differential to think about in this case: for reasons I can't identify, the system loses about 25°F between the boil kettle and the mash tun.
I suspect that this is due to loss heating the tubing, fittings, and pump bodies, but at any rate it's consistent.

So the process is this:
First, I calculate the strike temperature given the desired mash temperature, grain weight, and mash-tun mass (BeerSmith does this for me, but online calculators do too), and add 25°F.
I heat the total water volume, plus enough to cover the HERMS coil, to this temperature.
The strike volume goes into the mash tun, with the remainder going into the hot liquor tank, and the grain goes into hte mash tun.

I set the hot liquor tank for 4°F over the mash temperature, but don't start recirculating until the water cools to about that temperature, or until the mash temperature falls a few degrees below the mash temp.

Mashing Out
===========

The mash out is, fortunately, a little simpler: I change the HLT temperature controller to 168°F and wait.
The system can heat that at about 0.3°F/min, so about a half-hour later, the mash is at 168°F.
At that point, the hot liquor tank is full of 168°F water ready to sparge.

Only as Good as Your Tools
==========================

A few weeks ago, I co-brewed a with Rian Colbert, following the plan above.
I measured the temperature in the boil kettle with my "traceable" Fisher thermometer, and bragged about how fast it came up to temperature (190°F).
I measured the water in the mash tun at about 165°F, as expected.
We doughed in, and then Rian measured the mash temperature - 132°F!
The dial on the mash tun, and the probe from the HLT temperature controller agreed - way too low.

After some testing, I discovered that the thermometer will sometimes read about 25°F hot.
It does so consistently, but will "reset" to the correct temperature after a power cycle.

We managed to get the mash to temperature eventually, by re-heating some of the wort in the boil kettle -- but in the process de-natured the enzymes in that wort.
The beer is still in the fermenter, so no word yet on how it turned out, but surely less well than it could have!

I've purchased a pair of digital probe thermometers now - a [ThermoWorks RT600C](http://www.thermoworks.com/products/low_cost/rt600c.html) and a [CDN DTQ450X](http://www.amazon.com/gp/product/B0021AEAG2/ref=oh_details_o02_s00_i00?ie=UTF8&psc=1) - and will be using both and comparing the results.
In today's brewday, both new thermometers agreed with one another and with the temperature controller, so I have high confidence in the mash temps for this brew.


text:
'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Payment = mongoose.model('Payment'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create a payment
 */
exports.create = function(req, res) {
  Payment.create(req.body, function(err, payments) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(payments);
    }
  });

};

/**
 * Show the current payment
 */
exports.read = function(req, res) {
  res.json(req.payment);
};

/**
 * List of Consumptions
 */
exports.list = function(req, res) {
  Payment.find(req.query).exec(function(err, payments) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(payments);
    }
  });
};

/**
 * Consumption middleware
 */
exports.paymentByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Consumption is invalid'
    });
  }

  Payment.findById(id).exec(function(err, payment) {
    if (err) {
      return next(err);
    } else if (!payment) {
      return res.status(404).send({
        message: 'No payment with that identifier has been found'
      });
    }
    req.payment = payment;
    next();
  });
};


text:
<?php
/**
 * The template for displaying all single posts.
 *
 * @package Rocked
 */

get_header(); ?>

	<?php if (get_theme_mod('fullwidth_single')) { //Check if the post needs to be full width
		$fullwidth = 'fullwidth';
	} else {
		$fullwidth = '';
	} ?>

	<div id="primary" class="content-area col-md-9 <?php echo $fullwidth; ?>">
		<main id="main" class="content-wrap" role="main">

		<?php while ( have_posts() ) : the_post(); ?>

			<?php get_template_part( 'template-parts/content', 'single' ); ?>

			<?php the_post_navigation(); ?>

			<?php
				// If comments are open or we have at least one comment, load up the comment template
				if ( comments_open() || get_comments_number() ) :
					comments_template();
				endif;
			?>

		<?php endwhile; // end of the loop. ?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php if ( get_theme_mod('fullwidth_single', 0) != 1 ) : ?>
	<?php get_sidebar(); ?>
<?php endif; ?>
<?php get_footer(); ?>


text:
package model.exception;

public class XMLGenerationException extends AppException {
    public XMLGenerationException() {}

    public XMLGenerationException(Exception e) {
        super(e);
    }
}


text:
package com.toastertim.spikemod.potion;

import java.awt.Color;

import net.minecraft.client.Minecraft;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;

public class BleedingPotion extends Potion{

	public BleedingPotion() {
		super(true, Color.RED.getRGB());
		setRegistryName("bleeding");
		setPotionName("effect.spikemod.bleeding");
	}

	private static ItemStack sword = new ItemStack(Items.DIAMOND_SWORD);

	@Override
    public void renderInventoryEffect(int x, int y, PotionEffect effect, Minecraft mc) {
		mc.getRenderItem().renderItemIntoGUI(sword, x + 6, y + 7);
	}

	@Override
    public void renderHUDEffect(int x, int y, PotionEffect effect, Minecraft mc, float alpha) {
		renderInventoryEffect(x - 2, y - 3, effect, mc);
	}

	@Override //This runs whenever isReady returns true in a given tick.  (I think)
	public void performEffect(EntityLivingBase entity, int amplifier) {
		entity.attackEntityFrom(DamageSource.CACTUS, 5 * amplifier);//Probably want a custom DamageSource for a custom death message.
	}//But yeah, do damage in here.  It does stuff.

	@Override //When, based on duration, the potion actually does anything, I'm not sure what unit duration is in, ticks or seconds. (TICKS. YEP. TICKS.)
	public boolean isReady(int duration, int amplifier) {
		return duration % 100 == 0;
	}//Make this faster to make more calls to performEffect.

}


text:
package org.dynmap.utils;

import org.dynmap.Log;
import org.dynmap.renderer.DynmapBlockState;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Utility class used for parsing block name and block state identity from lines in model and texture files
public class BlockStateParser {
	private HashMap<DynmapBlockState, BitSet> basestates;
	private ArrayList<String> badtokens;
	private String modid;
	private int linenum;
	private boolean filtered;

	public BlockStateParser() {
	}

	/**
	 * Process new line into list of matching states Produce list of block states
	 * matching the fields in the provided line (specifically the portion after the
	 * '<type>:" prefix) at the stsrt of the line. Processes id=<block ID> or
	 * id=<nlock Name> or id=<modid>:<blockName> as block identifier data=<N> or
	 * data=<N>-<N2> as selecting matching states of identified blocks by ordered
	 * index of their block states (analog to metadata>
	 * state=<id:val>/<id2:val2>/... as selecting matching states (based on all
	 * states where given id=val values match)
	 *
	 * @return success or no
	 */
	public boolean processLine(String modid, String line, int linenum, Map<String, Integer> varMap) {
		boolean success = true;
		String tokens[] = line.split(","); // Split on the commas
		this.basestates = new HashMap<DynmapBlockState, BitSet>();
		this.badtokens = new ArrayList<String>();
		this.modid = modid;
		this.linenum = linenum;
		this.filtered = false;
		// Loop through and process id= tokens
		for (String token : tokens) {
			int idx = token.indexOf("="); // Find equals
			if (idx < 0)
				continue; // Skip token without equals
			String fieldid = token.substring(0, idx); // Split off left of equals
			String args = token.substring(idx + 1); // And rest of token after equals
			// Just do IDs first (need block names to get to states
			if (fieldid.equals("id")) {
				if (!handleBlockName(args)) {
					badtokens.add(token);
					success = false;
				}
			}
		}
		// Loop through and process data= and state= tokens
		for (String token : tokens) {
			int idx = token.indexOf("="); // Find equals
			if (idx < 0)
				continue; // Skip token without equals
			String fieldid = token.substring(0, idx); // Split off left of equals
			String args = token.substring(idx + 1); // And rest of token after equals
			// Check for data=
			if (fieldid.equals("data")) {
				if (!handleBlockData(args, varMap)) {
					badtokens.add(token);
					success = false;
				}
			}
			// If state=
			else if (fieldid.equals("state")) {
				if (!handleBlockState(args)) {
					badtokens.add(token);
					success = false;
				}
			}
		}
		// If unfiltered, add all states for all blocks
		if (!filtered) {
			// Now loop through base states and add matching indexes
			for (DynmapBlockState bs : basestates.keySet()) {
				int cnt = bs.getStateCount();
				BitSet bits = basestates.get(bs);
				for (int idx = 0; idx < cnt; idx++) {
					bits.set(bs.getState(idx).stateIndex);
				}
			}
		}
		// Log.info(String.format("processLine(%s)=%b, basestates=%s", line, success,
		// basestates));
		return success;
	}

	// Return matching results from last processLine call
	public Map<DynmapBlockState, BitSet> getMatchingStates() {
		return basestates;
	}

	// Return bad tokens from last processLine call
	public List<String> getBadTokens() {
		return badtokens;
	}

	private boolean handleBlockName(String blockname) {
		char c = blockname.charAt(0);
		if (Character.isLetter(c) || (c == '%') || (c == '&')) {
			String orig = blockname;
			if ((c == '%') || (c == '&')) {
				blockname = blockname.substring(1);
			}
			if (blockname.indexOf(':') < 0) {
				blockname = modid + ":" + blockname;
			}
			// Now find the base block state
			DynmapBlockState bs = DynmapBlockState.getBaseStateByName(blockname);
			// Bad if we failed
			if (bs == null) {
				Log.warning(String.format("id=%s on line %d does not match valid blockName", orig, linenum));
				return false;
			}
			basestates.put(bs, new BitSet());
			return true;
		} else { // Numbers not support anymore
			Log.warning(String.format("id=%s on line %d invalid format (numbers not supported anymore)", blockname,
					linenum));
			return false;
		}
	}

	private boolean handleBlockData(String data, Map<String, Integer> varMap) {
		try {
			if (data.equals("*")) {
				filtered = false;
			} else {
				int split = data.indexOf('-'); // See if range of data
				int m0, m1;
				if (split > 0) {
					String start = data.substring(0, split);
					String end = data.substring(split + 1);
					m0 = getIntValue(varMap, start);
					m1 = getIntValue(varMap, end);
				} else {
					m0 = m1 = getIntValue(varMap, data);
				}
				filtered = true;
				// Now loop through base states and add matching indexes
				for (DynmapBlockState bs : basestates.keySet()) {
					int cnt = bs.getStateCount();
					BitSet bits = basestates.get(bs);
					for (int idx = m0; (idx <= m1) && (idx < cnt); idx++) {
						bits.set(bs.getState(idx).stateIndex);
					}
					if ((m1 >= cnt) || (m0 >= cnt)) {
						Log.warning(String.format("data=%s on line %d exceeds state count for %s", data, linenum,
								bs.blockName));
					}
				}
			}
			return true;
		} catch (NumberFormatException x) {
			return false;
		}
	}

	private boolean handleBlockState(String data) {
		boolean success = true;
		if (data.equals("*")) {
			filtered = false;
		} else {
			String[] split = data.split("/"); // Split on pairs
			String[] attribs = new String[split.length];
			String[] vals = new String[split.length];
			for (int i = 0; i < split.length; i++) {
				String[] av = split[i].split(":");
				if (av.length == 2) {
					attribs[i] = av[0];
					vals[i] = av[1];
				} else {
					success = false;
				}
			}
			filtered = true;
			// Now loop through base states and add matching indexes
			if (success) {
				for (DynmapBlockState bs : basestates.keySet()) {
					int cnt = bs.getStateCount();
					BitSet bits = basestates.get(bs);
					for (int idx = 0; idx < cnt; idx++) {
						DynmapBlockState s = bs.getState(idx);
						boolean match = true;
						for (int i = 0; match && (i < attribs.length); i++) {
							if (!s.isStateMatch(attribs[i], vals[i])) {
								match = false;
							}
						}
						if (match) {
							bits.set(idx); // Set matching state
						}
					}
				}
			}
		}
		if (!success) {
			Log.warning(String.format("Bad block state %s for line %s", data, linenum));
		}
		return success;
	}

	private static Integer getIntValue(Map<String, Integer> vars, String val) throws NumberFormatException {
		char c = val.charAt(0);
		if (Character.isLetter(c) || (c == '%') || (c == '&')) {
			int off = val.indexOf('+');
			int offset = 0;
			if (off > 0) {
				offset = Integer.valueOf(val.substring(off + 1));
				val = val.substring(0, off);
			}
			Integer v = vars.get(val);
			if (v == null) {
				if ((c == '%') || (c == '&')) { // block/item unique IDs
					vars.put(val, 0);
					v = 0;
				} else {
					throw new NumberFormatException("invalid ID - " + val);
				}
			}
			if ((offset != 0) && (v.intValue() > 0))
				v = v.intValue() + offset;
			return v;
		} else {
			return Integer.valueOf(val);
		}
	}
}


text:
<?php

namespace Symfony\Component\ErrorHandler\Error;

class UndefinedMethodError extends \Error
{
    public function __construct(string $message, \Throwable $previous)
    {
        parent::__construct($message, $previous->getCode(), $previous->getPrevious());

        foreach ([
            'file' => $previous->getFile(),
            'line' => $previous->getLine(),
            'trace' => $previous->getTrace(),
        ] as $property => $value) {
            $refl = new \ReflectionProperty(\Error::class, $property);
            $refl->setValue($this, $value);
        }
    }
}


text:
<?php

final class PhabricatorPhurlURLEditController
  extends PhabricatorPhurlController {

  public function handleRequest(AphrontRequest $request) {
    return id(new PhabricatorPhurlURLEditEngine())
      ->setController($this)
      ->buildResponse();
  }
}


text:
#pragma once
#include "Hero.h"
class Magician : public Hero
{
public:
    Magician(Player* owner, const b2Vec2& pos, float scale);
    virtual ~Magician();
};


text:
#pragma once

#include <QtCore/qglobal.h>

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	#include <QtGui/QWidget>
	#include <QtGui/QVBoxLayout>
	#include <QtGui/QRadioButton>
	#include <QtGui/QButtonGroup>
#else
	#include <QtWidgets/QWidget>
	#include <QtWidgets/QVBoxLayout>
	#include <QtWidgets/QRadioButton>
	#include <QtWidgets/QButtonGroup>
#endif

#include "trikGuiDialog.h"

namespace trikGui {

/// Widget that shows some system settings.
class SystemSettingsWidget : public TrikGuiDialog
{
	Q_OBJECT

public:
	/// Constructor.
	/// @param parent - parent of this widget in terms of Qt widget parent/child system.
	/// @param fileManagerRoot - current FilesManagerRoot
	explicit SystemSettingsWidget(MainWidget::FileManagerRootType fileManagerRoot, QWidget *parent = 0);

	/// Destructor.
	~SystemSettingsWidget();

	/// String that shall appear in menu for this widget.
	static QString menuEntry();

public slots:
	void renewFocus() override;

signals:
	/// Emitted when we want to save current FilesManegerRoot
	void currentFilesDirPath(MainWidget::FileManagerRootType const& path);

protected:
	void keyPressEvent(QKeyEvent *event) override;

private:
	void changeDefaultButton();
	void emitCheckedDirPath();
	void setCurrentFilesRootButton(MainWidget::FileManagerRootType fileManagerRoot);

	/// Main layout of this widget.
	QButtonGroup mButtonGroup;
	QVBoxLayout mLayout;
	QRadioButton* mAllFSButton = nullptr;  // Has ownership.
	QRadioButton* mOnlyScriptsButton = nullptr;  // Has ownership.
};

}


text:
package aes.gui.widgets;

import net.minecraft.util.ChatAllowedCharacters;
import aes.gui.widgets.base.TextField;

/**
 *
 * Vanilla GuiTextField in Widget form.
 *
 */
public class TextFieldVanilla extends TextField {

	public static class NumberFilter implements CharacterFilter {
		@Override
		public String filter(String s) {
			final StringBuilder sb = new StringBuilder();
			for (final char c : s.toCharArray())
				if (isAllowedCharacter(c)) {
					sb.append(c);
				}
			return sb.toString();
		}

		@Override
		public boolean isAllowedCharacter(char c) {
			return Character.isDigit(c);
		}

	}

	public static class VanillaFilter implements CharacterFilter {
		@Override
		public String filter(String s) {
			return ChatAllowedCharacters.filerAllowedCharacters(s);
		}

		@Override
		public boolean isAllowedCharacter(char c) {
			return ChatAllowedCharacters.isAllowedCharacter(c);
		}

	}

	private int outerColor, innerColor;

	public TextFieldVanilla(CharacterFilter filter) {
		this(200, 20, filter);
	}

	public TextFieldVanilla(int width, int height, CharacterFilter filter) {
		super(width, height, filter);

		this.outerColor = -6250336;
		this.innerColor = -16777216;
	}

	public TextFieldVanilla(int width, int height, int innerColor, int outerColor, CharacterFilter filter) {
		super(width, height, filter);

		this.outerColor = outerColor;
		this.innerColor = innerColor;
	}

	@Override
	protected void drawBackground() {
		drawRect(this.x - 1, this.y - 1, this.x + this.width + 1, this.y + this.height + 1, this.outerColor);
		drawRect(this.x, this.y, this.x + this.width, this.y + this.height, this.innerColor);
	}

	@Override
	protected int getDrawX() {
		return (int) this.x + 4;
	}

	@Override
	protected int getDrawY() {
		return (int) (this.y + (this.height - 8) / 2);
	}

	@Override
	public int getInternalWidth() {
		return (int) this.width - 8;
	}

	public void setInnerColor(int c) {
		this.innerColor = c;
	}

	public void setOuterColor(int c) {
		this.outerColor = c;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="debug">
	<appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</Console>
	</appenders>

	<loggers>
		<root level="warn">
			<appender-ref ref="Console"/>
		</root>
		<Logger name="org.silverbullit.auditlog" level="debug">
			<AppenderRef ref="Console" />
		</Logger>
	</loggers>
</configuration>


text:
define("dijit/form/MappedTextBox", [
	"dojo/_base/declare", // declare
	"dojo/dom-construct", // domConstruct.place
	"./ValidationTextBox"
], function(declare, domConstruct, ValidationTextBox){

	// module:
	//		dijit/form/MappedTextBox

	return declare("dijit.form.MappedTextBox", ValidationTextBox, {
		// summary:
		//		A dijit/form/ValidationTextBox subclass which provides a base class for widgets that have
		//		a visible formatted display value, and a serializable
		//		value in a hidden input field which is actually sent to the server.
		// description:
		//		The visible display may
		//		be locale-dependent and interactive.  The value sent to the server is stored in a hidden
		//		input field which uses the `name` attribute declared by the original widget.  That value sent
		//		to the server is defined by the dijit/form/MappedTextBox.serialize() method and is typically
		//		locale-neutral.
		// tags:
		//		protected

		postMixInProperties: function(){
			this.inherited(arguments);

			// we want the name attribute to go to the hidden <input>, not the displayed <input>,
			// so override _FormWidget.postMixInProperties() setting of nameAttrSetting
			this.nameAttrSetting = "";
		},

		// Override default behavior to assign name to focusNode
		_setNameAttr: null,

		serialize: function(val /*=====, options =====*/){
			// summary:
			//		Overridable function used to convert the get('value') result to a canonical
			//		(non-localized) string.  For example, will print dates in ISO format, and
			//		numbers the same way as they are represented in javascript.
			// val: anything
			// options: Object?
			// tags:
			//		protected extension
			return val.toString ? val.toString() : ""; // String
		},

		toString: function(){
			// summary:
			//		Returns widget as a printable string using the widget's value
			// tags:
			//		protected
			var val = this.filter(this.get('value')); // call filter in case value is nonstring and filter has been customized
			return val != null ? (typeof val == "string" ? val : this.serialize(val, this.constraints)) : ""; // String
		},

		validate: function(){
			// Overrides `dijit/form/TextBox.validate`
			this.valueNode.value = this.toString();
			return this.inherited(arguments);
		},

		buildRendering: function(){
			// Overrides `dijit/_TemplatedMixin/buildRendering`

			this.inherited(arguments);

			// Create a hidden <input> node with the serialized value used for submit
			// (as opposed to the displayed value).
			// Passing in name as markup rather than calling domConstruct.create() with an attrs argument
			// to make query(input[name=...]) work on IE. (see #8660)
			this.valueNode = domConstruct.place("<input type='hidden'" + (this.name ? ' name="' + this.name.replace(/"/g, """) + '"' : "") + "/>", this.textbox, "after");
		},

		reset: function(){
			// Overrides `dijit/form/ValidationTextBox.reset` to
			// reset the hidden textbox value to ''
			this.valueNode.value = '';
			this.inherited(arguments);
		}
	});
});


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

using JetBrains.Annotations;

using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Impl;

using PPWCode.Vernacular.NHibernate.III.MappingByCode;

namespace PPWCode.Vernacular.NHibernate.III
{
    ///
    ///     This is a wrapper around the mapping by code class <see cref="HbmMapping" /> from nHibernate.
    ///
    public interface IPpwHbmMapping
    {
        ///
        ///     Get a <see cref="HbmMapping" /> instance or null, this can be used by hbmMapping by code.
        ///
        /// <returns>
        ///     A <see cref="HbmMapping" /> instance or null.
        /// </returns>
        [NotNull]
        HbmMapping HbmMapping { get; }

        ///
        ///     Get a <see cref="ModelMapper" /> instance.
        ///
        /// <returns>
        ///     A <see cref="ModelMapper" /> instance.
        /// </returns>
        [NotNull]
        ModelMapper ModelMapper { get; }

        ///
        ///     Get an instance that implements <see cref="ICandidatePersistentMembersProvider" /> instance.
        ///
        /// <returns>
        ///     A <see cref="ICandidatePersistentMembersProvider" /> instance.
        /// </returns>
        [NotNull]
        ICandidatePersistentMembersProvider MembersProvider { get; }

        ///
        ///
If an identifier is a reserved word for a dialect, it needs to quoted.

        ///

        ///         You can use this member for this purpose. The value of
        ///         <see cref="SimpleModelMapper.QuoteIdentifiers" />
        ///         is returned here.
        ///

        ///
        /// <returns>
        ///     Returns <see cref="SimpleModelMapper.QuoteIdentifiers" />
        /// </returns>
        bool QuoteIdentifiers { get; }

        IdentifierFormat IdentifierFormat { get; }

        [ContractAnnotation("null => null; notnull => notnull")]
        string GetIdentifier(string identifier);

        [ContractAnnotation("identifier:null => null; identifier:notnull => notnull")]
        string ConditionalQuoteIdentifier(string identifier, bool? quoteIdentifier);
    }
}


text:
from setuptools import setup

setup(
    name='beets-mpdadd',
    version='0.2',
    description='beets plugin that adds query results to the current MPD playlist',
    author='Daniel Greve',
    author_email='danielgreve@users.noreply.github.com',
    license='MIT',
    platforms='ALL',
    packages=['beetsplug'],
    install_requires=['beets', 'python-mpd2'],
)


text:
<?php

namespace AsseticBundle\CacheBuster;

use Assetic\Asset\AssetInterface,
    Assetic\Factory\Worker\WorkerInterface,
    Assetic\Factory\AssetFactory;

class LastModifiedStrategy implements WorkerInterface
{
    public function process(AssetInterface $asset)
    {
        $path = $asset->getTargetPath();
        $ext  = pathinfo($path, PATHINFO_EXTENSION);

        $lastModified = $asset->getLastModified();
        if (null !== $lastModified) {
            $path = substr_replace(
                $path,
                "$lastModified.$ext",
                -1 * strlen($ext)
            );
            $asset->setTargetPath($path);
        }
    }
}


text:
using namespace std;

Item::Item(const char* title, const char* description, Entity* parent,vector<ItemType> item_type,bool locked, Entity* key) :
	Entity(title, description, parent),locked(locked),key(key),item_type(item_type)
{
	type = ITEM;
}

Item::~Item()
{}

void Item::Look() const
{
	Cout("\n" + name + "\n");
	Cout(description + "\n");

	if (Contains(ItemType::CONTAINER) || Contains(ItemType::LIQUID_CONTAINER)) {
		if (locked) {
			Cout(keyDescription + "\n");
		}
		else
		{
			Cout("It contains: \n");
			for (vector<Entity*>::const_iterator it = container.cbegin(); it != container.cend(); ++it) {
				Cout((*it)->name + "\n");
			}
		}
	}
}

void Item::ChangeItemType(ItemType old,ItemType remplace) {
	for (vector<ItemType>::iterator it= item_type.begin(); it != item_type.end();++it)
	{
		if (*it == old) {
			*it = remplace;
		}
	}
}

bool Item::Contains(ItemType type)const {
	for (vector<ItemType>::const_iterator it = item_type.cbegin(); it != item_type.cend(); ++it)
	{
		if (*it == type) {
			return true;
		}
	}
	return false;
}

void Item::DropItems() {
	while (container.size() != 0) {
		container[0]->ChangeParentTo(parent);
	}
}


text:
/// <reference path="../../../typings/index.d.ts" />

/// <reference path="Resource.ts" />
/// <reference path="DependencyId.ts" />

describe("Resource", function () {
  it('should match when the id and name match', function () {
    var template = new ArmViz.ArmTemplate(null);

    var r = new ArmViz.Resource(null);
    r.type = 'type';
    r.name = 'name'

    var dep = new ArmViz.DependencyId();
    dep.type = 'type';
    dep.name = 'name';

    var result = template.resourceMatchesDependency(r, dep);

    expect(result).toBe(true);
  });
	/*
	it('should get the correct ID when the name is an expression', function() {
		var r = new ArmViz.Resource(null);
		r.type = 'type';
		r.name = "[concat(parameters('nicNamePrefix'), copyindex())]";

		var id = ArmViz.Resource.getResourceId(r);

		expect(id).toEqual("type/parameters('nicNamePrefix')copyindex()");
	});

	it('should get valid resource id when the name is an expression', function() {
		var id = ArmViz.Resource.getResourceId(testResource1);

		expect(id).toEqual("Microsoft.Web/sites/concat(parameters('endpointName'),'gateway')");
	});*/
});

var testResource1 = {
  "type": "Microsoft.Web/sites",
  "apiVersion": "2015-04-01",
  "name": "[concat(parameters('endpointName'),'gateway')]"
}


text:
/* @flow */

import test from 'tape';
import formatQuickfix from '../src/formatQuickfix';
import F1 from './fixture/1.json';
import F2 from './fixture/2.json';

test('formatQuickfix', (t) => {
  t.test('with fixture/1.json', (q) => {
    const lines = formatQuickfix(F1)

    q.equals(lines.length, 7, 'there should be the appropriate number of lines');

    q.equals(lines[0], 'redux-saga_0.9.5.js:25:5,28: [LIB] | $npm$ReduxSaga$PutEffect | Application of polymorphic type needs <list of 1 argument>. (Can use `*` for inferrable ones)', 'line 1 should have the right format');
    q.equals(lines[1], 'redux-saga_0.9.5.js:26:5,29: [LIB] | $npm$ReduxSaga$CallEffect | Application of polymorphic type needs <list of 1 argument>. (Can use `*` for inferrable ones)', 'line 2 should have the right format');
    // q.equals(lines[2], 'test_redux-saga_0.9.5.js:5:55,61: redux | Required module not found', 'line 3 should have the right format');
    // q.equals(lines[3], 'test_redux-saga_0.9.5.js:6:34,45: redux-saga | Required module not found', 'line 4 should have the right format');
    // q.equals(lines[4], 'test_redux-saga_0.9.5.js:7:39,58: redux-saga/effects | Required module not found', 'line 5 should have the right format');
    // q.equals(lines[5], 'test_redux-saga_0.9.5.js:13:15,35: identifier `$npm$ReduxSaga$Effect` | Could not resolve name', 'line 6 should have the right format');
    // q.equals(lines[6], 'test_redux-saga_0.9.5.js:26:15,18: property `type` | Property not found in `Array` | const { type } = action;', 'line 7 should have the right format');

    q.end();
  });

  t.test('with fixture/2.json', (q) => {
    const lines = formatQuickfix(F2)

    q.equals(lines.length, 3, 'there should be the appropriate number of lines');

    // q.equals(lines[0], '/Projects/test/interface/redux-saga_0.9.5.js:25:5,28: [LIB] | $npm$ReduxSaga$PutEffect | Application of polymorphic type needs <list of 1 argument>. (Can use `*` for inferrable ones)', 'line 1 should have the right format');
    // q.equals(lines[1], '/Projects/test/interface/redux-saga_0.9.5.js:26:5,29: [LIB] | $npm$ReduxSaga$CallEffect | Application of polymorphic type needs <list of 1 argument>. (Can use `*` for inferrable ones)', 'line 2 should have the right format');
    // q.equals(lines[2], '/Projects/test/test_redux-saga_0.9.5.js:26:15,18: property `type` | Property not found in `Array` | const { type } = action;', 'line 3 should have the right format');

    q.end();
  });

  t.end();
});


text:
namespace {

class Service : public KeyedService {
 public:
  explicit Service(Profile* profile) {
#if defined(OS_ANDROID)
    context_ = new GeolocationPermissionContextAndroid(profile);
#else
    context_ = new GeolocationPermissionContext(profile);
#endif
  }

  GeolocationPermissionContext* context() {
    return context_.get();
  }

  virtual void Shutdown() OVERRIDE {
    context()->ShutdownOnUIThread();
  }

 private:
  scoped_refptr<GeolocationPermissionContext> context_;

  DISALLOW_COPY_AND_ASSIGN(Service);
};

}  // namespace

// static
GeolocationPermissionContext*
GeolocationPermissionContextFactory::GetForProfile(Profile* profile) {
  return static_cast<Service*>(
      GetInstance()->GetServiceForBrowserContext(profile, true))->context();
}

// static
GeolocationPermissionContextFactory*
GeolocationPermissionContextFactory::GetInstance() {
  return Singleton<GeolocationPermissionContextFactory>::get();
}

GeolocationPermissionContextFactory::GeolocationPermissionContextFactory()
    : BrowserContextKeyedServiceFactory(
          "GeolocationPermissionContext",
          BrowserContextDependencyManager::GetInstance()) {
}

GeolocationPermissionContextFactory::~GeolocationPermissionContextFactory() {
}

KeyedService*
GeolocationPermissionContextFactory::BuildServiceInstanceFor(
    content::BrowserContext* profile) const {
  return new Service(static_cast<Profile*>(profile));
}

void GeolocationPermissionContextFactory::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
#if defined(OS_ANDROID)
  registry->RegisterBooleanPref(
      prefs::kGeolocationEnabled,
      true,
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
#endif
}

content::BrowserContext*
GeolocationPermissionContextFactory::GetBrowserContextToUse(
    content::BrowserContext* context) const {
  return chrome::GetBrowserContextOwnInstanceInIncognito(context);
}