text:
sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/ui/core/Fragment",
	"sap/ui/core/Item",
	"sap/m/MessageToast",
	"model/formatter",
	"sap/ui/core/Core"
], function (Controller, Fragment, Item, MessageToast, formatter, oCore) {
	"use strict";

	return Controller.extend("teamCalendar.controller.Main", {

		myformatter : formatter,
		imagePath : sap.ui.require.toUrl("sap/m/demokit/teamCalendar/webapp/").replace('/resources/', '/test-resources/'),

		// Initial setup
		onInit: function() {
			this._oModel = this.getView().getModel("calendar");
			this._oStartDate = this.myformatter.utcToLocalDateTime(this._oModel.getProperty("/startDate"));
			this._sSelectedView = this._oModel.getProperty("/viewKey");
			this._sSelectedMember = "Team";
			this._oCalendarContainer = this.byId("mainContent");
			this._mCalendars = {};
			this._sCalendarDisplayed = '';

			// load and display the Planning Calendar
			this._loadCalendar("PlanningCalendar");
		},

		// Does loading of the PC/SPC depending on selected item
		selectChangeHandler: function(oEvent) {
			this._sSelectedMember = oEvent.getParameter("selectedItem").getKey();
			this._loadCalendar(isNaN(this._sSelectedMember) ? "PlanningCalendar" : "SinglePlanningCalendar");
		},

		// Loads SPC for a person which row is clicked
		rowSelectionHandler: function(oEvent) {
			var oSelectedRow = oEvent.getParameter("rows")[0],
				sSelectedId = oSelectedRow.getId();
			this._sSelectedMember = sSelectedId.substr(sSelectedId.lastIndexOf('-') + 1);
			oSelectedRow.setSelected(false);
			this._loadCalendar("SinglePlanningCalendar");
		},

		// Saves currently selected date
		startDateChangeHandler: function(oEvent) {
			this._oStartDate = new Date(oEvent.getSource().getStartDate());
		},

		// Saves currently selected view
		viewChangeHandler: function(oEvent) {
			var oCalendar = oEvent.getSource();
			if (isNaN(this._sSelectedMember)) {
				this._sSelectedView = oCalendar.getViewKey();
			} else {
				this._sSelectedView = oCore.byId(oCalendar.getSelectedView()).getKey();
			}
			oCalendar.setStartDate(this._oStartDate);
		},

		// Handler of the "Create" button
		appointmentCreate: function(oEvent) {
			MessageToast.show("Creating new appointment...");
		},

		// Opend a legend
		openLegend: function(oEvent) {
			var oSource = oEvent.getSource(),
				oView = this.getView();
			if (!this._pLegendPopover) {
				this._pLegendPopover = Fragment.load({
					id: oView.getId(),
					name: "teamCalendar.view.Legend",
					controller: this
				}).then(function(oLegendPopover){
					oView.addDependent(oLegendPopover);
					return oLegendPopover;
				});
			}
			this._pLegendPopover.then(function(oLegendPopover){
				if (oLegendPopover.isOpen()) {
					oLegendPopover.close();
				} else {
					oLegendPopover.openBy(oSource);
				}
			});
		},

		// Loads and displays calendar (if not already loaded), otherwise just displays it
		_loadCalendar: function(sCalendarId) {
			var oView = this.getView();

			if (!this._mCalendars[sCalendarId]) {
				this._mCalendars[sCalendarId] =	Fragment.load({
					id: oView.getId(),
					name: "teamCalendar.view." + sCalendarId,
					controller: this
				}).then(function(oCalendarVBox){
					this._populateSelect(this.byId(sCalendarId + "TeamSelector"));
					return oCalendarVBox;
				}.bind(this));
			}

			this._mCalendars[sCalendarId].then(function(oCalendarVBox){
				this._displayCalendar(sCalendarId, oCalendarVBox);
			}.bind(this));
		},

		_hideCalendar: function(){
			if (this._sCalendarDisplayed === '') {
				return Promise.resolve();
			}
			return this._mCalendars[this._sCalendarDisplayed].then(function(oOldCalendarVBox){
				this._oCalendarContainer.removeContent(oOldCalendarVBox);
			}.bind(this));
		},

		// Displays already loaded calendar
		_displayCalendar: function(sCalendarId, oCalendarVBox) {
			this._hideCalendar().then(function(){
				this._oCalendarContainer.addContent(oCalendarVBox);
				this._sCalendarDisplayed = sCalendarId;
				var oCalendar = oCalendarVBox.getItems()[0];
				var oTeamSelect = this.byId(sCalendarId + "TeamSelector");
				oTeamSelect.setSelectedKey(this._sSelectedMember);
				oCalendar.setStartDate(this._oStartDate);
				if (isNaN(this._sSelectedMember)) {
					// Planning Calendar
					oCalendar.setViewKey(this._sSelectedView);
					oCalendar.bindElement({
						path: "/team",
						model: "calendar"
					});
				} else {
					// Single Planning Calendar
					oCalendar.setSelectedView(oCalendar.getViewByKey(this._sSelectedView));
					oCalendar.bindElement({
						path: "/team/" + this._sSelectedMember,
						model: "calendar"
					});
				}
			}.bind(this));
		},

		// Adds "Team" and all team members as select items
		_populateSelect: function(oSelect) {
			var iCount = this._oModel.getProperty("/team").length,
			iPerson;
			for (iPerson = 0; iPerson < iCount; iPerson++) {
				oSelect.addItem(new Item({
					key: iPerson,
					text: this._oModel.getProperty("/team")[iPerson].name
				}));
			}
		}

	});
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d | %5.5level [%10.10thread] %20.20logger{20} : %msg%n</pattern>
    </encoder>
  </appender>
  <root level="ALL">
    <appender-ref ref="CONSOLE"/>
  </root>
</configuration>

redpajama_set_name: RedPajamaGithub


text:
package com.crawljax.plugins.testplugin;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.crawljax.core.CrawljaxRunner;
import com.crawljax.core.configuration.CrawlRules.FormFillMode;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.core.configuration.InputSpecification;
import com.crawljax.core.plugin.HostInterfaceImpl;
import com.crawljax.core.plugin.descriptor.Parameter;
import com.crawljax.core.plugin.descriptor.PluginDescriptor;
import com.crawljax.core.state.Identification;
import com.crawljax.core.state.Identification.How;
import com.crawljax.forms.FormInput.InputType;

/**
 * Use the sample plugin in combination with Crawljax.
 *
 */
public class Runner {

	private static final String URL = "http://www.google.com";
	private static final int MAX_DEPTH = 1;
	private static final int MAX_NUMBER_STATES = 3;

	/**
	 * Entry point
	 */
	public static void main(String[] args) {
		CrawljaxConfiguration.CrawljaxConfigurationBuilder builder =
		        CrawljaxConfiguration.builderFor(URL);
		builder.crawlRules().setFormFillMode(FormFillMode.NORMAL);

		builder.crawlRules().click("a");
		builder.crawlRules().click("button");

		// except these
		builder.crawlRules().dontClick("a").underXPath("//DIV[@id='guser']");
		builder.crawlRules().dontClick("a").withText("Language Tools");

		// limit the crawling scope
		builder.setMaximumStates(MAX_NUMBER_STATES);
		builder.setMaximumDepth(MAX_DEPTH);

		PluginDescriptor descriptor = PluginDescriptor.forPlugin(TestPlugin.class);
		Map<String, String> parameters = new HashMap<>();
		for (Parameter parameter : descriptor.getParameters()) {
			parameters.put(parameter.getId(), "value");
		}
		builder.addPlugin(new TestPlugin(new HostInterfaceImpl(new File("out"), parameters)));

		builder.crawlRules().setInputSpec(getInputSpecification());

		CrawljaxRunner crawljax = new CrawljaxRunner(builder.build());
		crawljax.call();
	}

	private static InputSpecification getInputSpecification() {
		InputSpecification input = new InputSpecification();
		input.inputField(InputType.TEXT, new Identification(How.id, "lst-ib"))
		        .inputValues("Crawljax");

		return input;
	}

	private Runner() {
		// Utility class
	}
}


text:
pkg_name=jffi
pkg_origin=core
pkg_version="1.2.16"
pkg_maintainer="The Habitat Maintainers <humans@habitat.sh>"
pkg_license=('Apache-2.0')
pkg_source="https://github.com/jnr/jffi/archive/${pkg_name}-${pkg_version}.tar.gz"
pkg_dirname="${pkg_name}-${pkg_name}-${pkg_version}"
pkg_shasum="a116c53f26d13d738aaf6e21fe52231be5f0df6e1007673846fd18a4be875121"
pkg_upstream_url="https://github.com/jnr/jffi"
pkg_deps=(core/glibc lilian/libffi lilian/gcc-libs lilian/jre8)
pkg_build_deps=(
  lilian/jdk8
  lilian/ant
  lilian/pkg-config
  lilian/make
  lilian/gcc
  lilian/file
  lilian/diffutils
  lilian/maven
)

do_prepare() {
  build_line "replacing /usr/bin/file with $(pkg_path_for lilian/file)/bin/file"
  sed -i "s,/usr/bin/file,$(pkg_path_for lilian/file)/bin/file,g" "jni/libffi/configure"

  export USE_SYSTEM_LIBFFI=1
  export JAVA_HOME
  JAVA_HOME="$(pkg_path_for jdk8)"
}

do_build() {
  ant jar
  ant -Djava.library.path="${LD_RUN_PATH}" archive-platform-jar
  mvn -Djava.library.path="${LD_RUN_PATH}" package
}

do_install() {
  cp -r target "${pkg_prefix}"
}

# Strip was unable to recognise the format of the input file libjffi-1.2.so
do_strip() {
  return 0
}


text:
#import "WizAnalyticsPlugin.h"
#import "WizAnalytics.h"

@implementation WizAnalyticsPlugin

- (void)logEvent:(CDVInvokedUrlCommand *)command {
    NSString *eventName = [command.arguments objectAtIndex:0];
    NSDictionary *options = [command.arguments objectAtIndex:1];

    WizAnalytics* sharedSingleton = [WizAnalytics sharedInstance];
    [sharedSingleton analyticsEvent:eventName withExtraMetadata:options];
}

- (void)logScreen:(CDVInvokedUrlCommand *)command {
    NSString *eventName = [command.arguments objectAtIndex:0];
    NSDictionary *options = [command.arguments objectAtIndex:1];

    WizAnalytics* sharedSingleton = [WizAnalytics sharedInstance];
    [sharedSingleton analyticsScreenEvent:eventName withExtraMetadata:options];
}

- (void)handleOpenURL:(CDVInvokedUrlCommand *)command {
    NSString *urlString = [command.arguments objectAtIndex:0];
    NSURL *url = [NSURL URLWithString:urlString];

    WizAnalytics* sharedSingleton = [WizAnalytics sharedInstance];
    [sharedSingleton handleOpenURL:url];
}

@end


text:
This image is java runtime image, used for analysis your java coding style.
Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. It automates the process of checking Java code to spare humans of this boring (but important) task. This makes it ideal for projects that want to enforce a coding standard.

gradle checkstyleMain

gradle checkstyleTest

### Learn how to build it?

Use the `docker build` command build the image, and your project must build with gradle

```
docker build -t containerops/analysis/java_gradle_checkstyle ./
```
### Component Usage
```
docker run \
    --rm \
    --env CO_DATA=" \
    version=gradle3 \
    git-url=https://github.com/vanniuner/gradle-demo.git \
    out-put-type=json" \
    containerops/analysis/java_gradle_checkstyle \
```

### Parameters
- `version` gradle version available value: gradle3,gradle4
- `git-url` where your code is located
- `out-put-type`  available value: xml,yaml,json
- `report-path`   not required,if you defined reports path,
### Versions 1.0.0


text:
package cn.zhenghongen.android.common.util;

import android.util.Log;

import cn.zhenghongen.android.common.BuildConfig;

/**
 * Created by ZhengHongEn on 2015/12/22.
 */
public final class Logger {
    // TODO: 2015/12/22 在项目中使用Logger的时候,根据项目来判断DEBUG?
    private static final boolean DEBUG = BuildConfig.DEBUG;

    public static void v(String tag, String msg) {
        Log.v(tag, msg);
    }

    public static void v(String tag, String msg, Throwable tr) {
        Log.v(tag, msg, tr);
    }

    public static void d(String tag, String msg) {
        if (DEBUG) {
            Log.d(tag, msg);
        }
    }

    public static void d(String tag, String msg, Throwable tr) {
        if (DEBUG) {
            Log.d(tag, msg, tr);
        }
    }

    public static void i(String tag, String msg) {
        Log.i(tag, msg);
    }

    public static void i(String tag, String msg, Throwable tr) {
        Log.i(tag, msg, tr);
    }

    public static void w(String tag, String msg) {
        Log.w(tag, msg);
    }

    public static void w(String tag, String msg, Throwable tr) {
        Log.w(tag, msg, tr);
    }

    public static void w(String tag, Throwable tr) {
        Log.w(tag, tr);
    }

    public static void e(String tag, String msg) {
        Log.e(tag, msg);
    }

    public static void e(String tag, String msg, Throwable tr) {
        Log.e(tag, msg, tr);
    }

}


text:
#if !defined (__PRINTING__)
#define __PRINTING__

#include "DialogMgr.h"

#define bDraftLoop	0
#define bSpoolLoop	1

#define bDevCItoh	1
#define bDevLaser	3

#define iPFMaxPgs	128

#define iPrSavPFil	(-1)
#define controlErr	(-17)
#define iIOAbort	(-27)
#define MemFullErr	(-108)
#define iPrAbort	128

#define iPrDevCtl	7
#define lPrReset	0x10000
#define lPrLineFeed	0x30000
#define lPrLFSixth	0x3FFFF
#define lPrPageEnd	0x20000
#define iPrBitsCtl	4
#define lScreenBits	0
#define lPaintBits	1
#define iPrIOCtl	5

#define sPrDrvr		".Print"
#define iPrDrvrRef	(-3)

typedef struct PACKED {
  GrafPort gPort;
  QDProcs saveprocs;
  LONGINT spare[4];
  BOOLEAN fOurPtr;
  BOOLEAN fOurBits;
} TPrPort;
typedef TPrPort *TPPrPort;

typedef struct PACKED {
  INTEGER iDev;
  INTEGER iVRes;
  INTEGER iHRes;
  Rect rPage;
} TPrInfo;

typedef enum {feedCut, feedFanFold, feedMechCut, feedOther} TFeed;

typedef struct PACKED {
  INTEGER wDev;
  INTEGER iPageV;
  INTEGER iPageH;
  SignedByte bPort;
  char feed;
} TPrStl;

typedef enum { scanTB,  scanBL,  scanLR,  scanRL } TScan;
typedef struct PACKED {
  INTEGER iRowBytes;
  INTEGER iBandV;
  INTEGER iBandH;
  INTEGER iDevBytes;
  INTEGER iBands;
  SignedByte bPatScale;
  SignedByte bULThick;
  SignedByte bULOffset;
  SignedByte bULShadow;
  char scan;
  SignedByte bXInfoX;
} TPrXInfo;

typedef struct PACKED {
  INTEGER iFstPage;
  INTEGER iLstPage;
  INTEGER iCopies;
  SignedByte bJDocLoop;
  BOOLEAN fFromUsr;
  PACKED_MEMBER(ProcPtr, pIdleProc);
  PACKED_MEMBER(StringPtr, pFileName);
  INTEGER iFileVol;
  SignedByte bFileVers;
  SignedByte bJobX;
} TPrJob;

typedef struct PACKED {
  INTEGER iPrVersion;
  TPrInfo prInfo;
  Rect rPaper;
  TPrStl prStl;
  TPrInfo prInfoPT;
  TPrXInfo prXInfo;
  TPrJob prJob;
  INTEGER printX[19];
} TPrint;
typedef TPrint *TPPrint;
MAKE_HIDDEN(TPPrint);
typedef HIDDEN_TPPrint *THPrint;

typedef Rect *TPRect;

typedef struct PACKED {
  INTEGER iTotPages;
  INTEGER iCurPage;
  INTEGER iTotCopies;
  INTEGER iCurCopy;
  INTEGER iTotBands;
  INTEGER iCurBand;
  BOOLEAN fPgDirty;
  BOOLEAN fImaging;
  PACKED_MEMBER(THPrint, hPrint);
  PACKED_MEMBER(TPPrPort, pPRPort);
  PACKED_MEMBER(PicHandle, hPic);
} TPrStatus;

typedef struct PACKED {
/* From Technote 095 */
  DialogRecord dlg;
  PACKED_MEMBER(ProcPtr, pFltrProc);
  PACKED_MEMBER(ProcPtr, pItemProc);
  PACKED_MEMBER(THPrint, hPrintUsr);
  BOOLEAN fDoIt;
  BOOLEAN fDone;
  LONGINT lUser1;
  LONGINT lUser2;
  LONGINT lUser3;
  LONGINT lUser4;
  INTEGER iNumFst;
  INTEGER iNumLst;
    /* more stuff may be here */
} TPrDlg, *TPPrDlg;

#if !defined (PrintErr)
extern INTEGER 	PrintErr;
#endif

#if !defined (__STDC__)
extern INTEGER PrError();
extern void PrSetError();
extern void PrOpen();
extern void PrClose();
extern void PrDrvrOpen();
extern void PrDrvrClose();
extern void PrCtlCall();
extern Handle PrDrvrDCE();
extern INTEGER PrDrvrVers();
extern void C_ROMlib_myjobproc();
extern pascal BOOLEAN C_ROMlib_stlfilterproc();
extern pascal BOOLEAN C_ROMlib_numsonlyfilterproc();
extern void C_ROMlib_mystlproc();
extern TPPrDlg PrJobInit();
extern TPPrDlg PrStlInit();
extern BOOLEAN PrDlgMain();
extern void PrGeneral();
extern void donotPrArc();
extern void PrArc();
extern void donotPrBits();
extern void PrBits();
extern void donotPrLine();
extern void PrLine();
extern void donotPrOval();
extern void PrOval();
extern void textasPS();
extern void donotPrGetPic();
extern void PrGetPic();
extern void donotPrPutPic();
extern void PrPutPic();
extern void donotPrPoly();
extern void PrPoly();
extern void donotPrRRect();
extern void PrRRect();
extern void donotPrRect();
extern void PrRect();
extern void donotPrRgn();
extern void PrRgn();
extern INTEGER PrTxMeas();
extern void donotPrText();
extern void PrText();
extern void PrComment();
extern TPPrPort PrOpenDoc();
extern void PrOpenPage();
extern void PrClosePage();
extern void PrCloseDoc();
extern void PrPicFile();
extern void PrintDefault();
extern BOOLEAN PrValidate();
extern BOOLEAN PrStlDialog();
extern BOOLEAN PrJobDialog();
extern void PrJobMerge();
#else /* __STDC__ */
extern pascal trap INTEGER C_PrError( void  );
extern pascal trap void C_PrSetError( INTEGER iErr );
extern pascal trap void C_PrOpen( void  );
extern pascal trap void C_PrClose( void  );
extern pascal trap void C_PrDrvrOpen( void  );
extern pascal trap void C_PrDrvrClose( void  );
extern pascal trap void C_PrCtlCall( INTEGER iWhichCtl, LONGINT lParam1,
				    LONGINT lParam2, LONGINT lParam3 );
extern pascal trap Handle C_PrDrvrDCE( void  );
extern pascal trap INTEGER C_PrDrvrVers( void  );
extern pascal void C_ROMlib_myjobproc( DialogPtr dp, INTEGER itemno );
extern pascal BOOLEAN C_ROMlib_stlfilterproc( DialogPeek dp,
					     EventRecord *evt, INTEGER *ith );

extern pascal BOOLEAN C_ROMlib_numsonlyfilterproc( DialogPeek dp,
						  EventRecord *evt,
						  INTEGER *ith );

extern pascal void C_ROMlib_mystlproc( DialogPtr dp, INTEGER itemno );
extern pascal trap TPPrDlg C_PrJobInit( THPrint hPrint );
extern pascal trap TPPrDlg C_PrStlInit( THPrint hPrint );
extern pascal trap BOOLEAN C_PrDlgMain( THPrint hPrint, ProcPtr initfptr );
extern pascal trap void C_PrGeneral( Ptr pData );
extern pascal trap void C_donotPrArc( GrafVerb verb, Rect *r,
				     INTEGER starta, INTEGER arca );
extern pascal trap void C_PrArc( GrafVerb verb, Rect *r, INTEGER starta,
				INTEGER arca );
extern pascal trap void C_donotPrBits( BitMap *srcbmp, Rect *srcrp,
				      Rect *dstrp, INTEGER mode,
				      RgnHandle mask );
extern pascal trap void C_PrBits( BitMap *srcbmp, Rect *srcrp,
				 Rect *dstrp, INTEGER mode, RgnHandle mask );
extern pascal trap void C_donotPrLine( Point p );
extern pascal trap void C_PrLine( Point p );
extern pascal trap void C_donotPrOval( GrafVerb v, Rect *rp );
extern pascal trap void C_PrOval( GrafVerb v, Rect *rp );
extern pascal trap void C_textasPS( INTEGER n, Ptr textbufp,
				   Point num, Point den );
extern pascal trap void C_donotPrGetPic( Ptr dp, INTEGER bc );
extern pascal trap void C_PrGetPic( Ptr dp, INTEGER bc );
extern pascal trap void C_donotPrPutPic( Ptr sp, INTEGER bc );
extern pascal trap void C_PrPutPic( Ptr sp, INTEGER bc );
extern pascal trap void C_donotPrPoly( GrafVerb verb, PolyHandle ph );
extern pascal trap void C_PrPoly( GrafVerb verb, PolyHandle ph );
extern pascal trap void C_donotPrRRect( GrafVerb verb, Rect *r,
				       INTEGER width, INTEGER height );
extern pascal trap void C_PrRRect( GrafVerb verb, Rect *r, INTEGER width,
				  INTEGER height );

extern pascal trap void C_donotPrRect( GrafVerb v, Rect *rp );
extern pascal trap void C_PrRect( GrafVerb v, Rect *rp );
extern pascal trap void C_donotPrRgn( GrafVerb verb, RgnHandle rgn );
extern pascal trap void C_PrRgn( GrafVerb verb, RgnHandle rgn );
extern pascal trap INTEGER C_PrTxMeas( INTEGER n, Ptr p, Point *nump,
				      Point *denp, FontInfo *finfop );
extern pascal trap void C_donotPrText( INTEGER n, Ptr textbufp, Point num,
				      Point den );
extern pascal trap void C_PrText( INTEGER n, Ptr textbufp, Point num,
				 Point den );
extern pascal trap void C_PrComment( INTEGER kind, INTEGER size, Handle hand );
extern pascal trap TPPrPort C_PrOpenDoc( THPrint hPrint, TPPrPort port,
					Ptr pIOBuf );
extern pascal trap void C_PrOpenPage( TPPrPort port, TPRect pPageFrame );
extern pascal trap void C_PrClosePage( TPPrPort pPrPort );
extern pascal trap void C_PrCloseDoc( TPPrPort port );
extern pascal trap void C_PrPicFile( THPrint hPrint, TPPrPort pPrPort,
				    Ptr pIOBuf, Ptr pDevBuf,
				    TPrStatus *prStatus );
extern pascal trap void C_PrintDefault( THPrint hPrint );
extern pascal trap BOOLEAN C_PrValidate( THPrint hPrint );
extern pascal trap BOOLEAN C_PrStlDialog( THPrint hPrint );
extern pascal trap BOOLEAN C_PrJobDialog( THPrint hPrint );
extern pascal trap void C_PrJobMerge( THPrint hPrintSrc, THPrint hPrintDst );
#endif /* __STDC__ */
#endif /* __PRINTING__ */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using HIDLibrary;

namespace Multitouch.Driver.Logic
{
	class DriverCommunicator : IDisposable
	{
		private readonly Queue<HidContactInfo> currentContacts;
		private readonly Dictionary<int, HidContactInfo> lastContactInfo;

		private readonly Timer timer;
		private readonly HidDevice device;
		private readonly HidContactInfoEqualityComparer comparer;
		private readonly object lockCurrentContacts;

		public DriverCommunicator()
		{
			comparer = new HidContactInfoEqualityComparer();
			lockCurrentContacts = new object();

			device = HidDevices.Enumerate(0xdddd, 0x0001).FirstOrDefault();
			if (device == null)
				throw new InvalidOperationException("Universal Software HID driver was not found. Please ensure that it is installed.");

			device.Open(HidDevice.DeviceMode.Overlapped, HidDevice.DeviceMode.NonOverlapped);

			currentContacts = new Queue<HidContactInfo>();
			lastContactInfo = new Dictionary<int, HidContactInfo>();

			timer = new Timer();
			timer.AutoReset = false;
			timer.Interval = 1000 / 133d;
			timer.Elapsed += timer_Elapsed;
			timer.Start();
		}

		void timer_Elapsed(object sender, ElapsedEventArgs e)
		{
			SendContacts();
			timer.Start();
		}

		private void SendContacts()
		{
			List<HidContactInfo> contactsToSend = new List<HidContactInfo>();
			lock (lockCurrentContacts)
			{
				while (currentContacts.Count > 0)
				{
					HidContactInfo contactInfo = currentContacts.Dequeue();

					HidContactInfo lastContact;
					if (lastContactInfo.TryGetValue(contactInfo.Id, out lastContact))
					{
						if (contactInfo.State == HidContactState.Updated && lastContact.State == HidContactState.Removing)
							continue;
					}

					lastContactInfo[contactInfo.Id] = contactInfo;
					contactsToSend.Add(contactInfo);
				}
			}
			contactsToSend.AddRange(lastContactInfo.Values.Except(contactsToSend, comparer).Where(c => c.State == HidContactState.Updated).ToList());

			if (contactsToSend.Count > 0)
				SendContacts(contactsToSend);

			foreach (ushort id in lastContactInfo.Values.Where(c => c.State == HidContactState.Removed).Select(c => c.Id).ToList())
				lastContactInfo.Remove(id);
			foreach (HidContactInfo contactInfo in lastContactInfo.Values.Where(c => c.State == HidContactState.Removing).ToList())
				Enqueue(new HidContactInfo(HidContactState.Removed, contactInfo.Contact));
			foreach (HidContactInfo contactInfo in lastContactInfo.Values.Where(c => c.State == HidContactState.Adding).ToList())
				Enqueue(new HidContactInfo(HidContactState.Updated, contactInfo.Contact));
		}

		private void SendContacts(ICollection<HidContactInfo> contactsToSend)
		{
			MultiTouchReport report = new MultiTouchReport((byte) contactsToSend.Count, true);
			int index = 0;
			foreach (HidContactInfo contactInfo in contactsToSend)
			{
				contactInfo.Timestamp = DateTime.Now;
				report.Contacts.Add(contactInfo);
				index++;

				if (contactsToSend.Count - index == 0)
					SendReport(report);
				else if (index % MultiTouchReport.MaxContactsPerReport == 0)
				{
					SendReport(report);
					report = new MultiTouchReport((byte) contactsToSend.Count, false);
				}
			}
		}

		private void SendReport(MultiTouchReport report)
		{
			report.ToBytes();
			device.WriteReport(report);
		}

		public void Enqueue(HidContactInfo contactInfo)
		{
			lock (lockCurrentContacts)
			{
				currentContacts.Enqueue(contactInfo);
			}
		}

		public void Dispose()
		{
			device.Dispose();
			if (timer != null)
				timer.Dispose();
		}
	}
}


text:
package io.jsonwebtoken.impl.crypto;

import io.jsonwebtoken.SignatureException;

public interface Signer {

    byte[] sign(byte[] data) throws SignatureException;
}


text:
using namespace process;

using std::string;

using testing::_;
using testing::Assign;
using testing::DoAll;
using testing::Return;
using testing::ReturnArg;

// TODO(bmahler): Move tests into their own files as appropriate.

TEST(Process, event)
{
  Event* event = new TerminateEvent(UPID());
  EXPECT_FALSE(event->is<MessageEvent>());
  EXPECT_FALSE(event->is<ExitedEvent>());
  EXPECT_TRUE(event->is<TerminateEvent>());
  delete event;
}

TEST(Process, future)
{
  Promise<bool> promise;
  promise.set(true);
  ASSERT_TRUE(promise.future().isReady());
  EXPECT_TRUE(promise.future().get());
}

TEST(Process, associate)
{
  Promise<bool> promise1;
  Future<bool> future1(true);
  promise1.associate(future1);
  ASSERT_TRUE(promise1.future().isReady());
  EXPECT_TRUE(promise1.future().get());

  Promise<bool> promise2;
  Promise<bool> promise2_;
  Future<bool> future2 = promise2_.future();
  promise2.associate(future2);
  promise2_.discard();
  ASSERT_TRUE(promise2.future().isDiscarded());

  Promise<bool> promise3;
  Promise<bool> promise4;
  promise3.associate(promise4.future());
  promise4.fail("associate");
  ASSERT_TRUE(promise3.future().isFailed());
  EXPECT_EQ("associate", promise3.future().failure());

  // Test 'discard' versus 'discarded' after association.
  Promise<bool> promise5;
  Future<bool> future3;
  promise5.associate(future3);
  EXPECT_FALSE(future3.isDiscarded());
  promise5.future().discard();
  EXPECT_TRUE(future3.hasDiscard());

  Promise<bool> promise6;
  Promise<bool> promise7;
  promise6.associate(promise7.future());
  promise7.discard();
  EXPECT_TRUE(promise6.future().isDiscarded());
}

void onAny(const Future<bool>& future, bool* b)
{
  ASSERT_TRUE(future.isReady());
  *b = future.get();
}

TEST(Process, onAny)
{
  bool b = false;
  Future<bool>(true)
    .onAny(lambda::bind(&onAny, lambda::_1, &b));
  EXPECT_TRUE(b);
}

Future<string> itoa1(int* const& i)
{
  std::ostringstream out;
  out << *i;
  return out.str();
}

string itoa2(int* const& i)
{
  std::ostringstream out;
  out << *i;
  return out.str();
}

TEST(Process, then)
{
  Promise<int*> promise;

  int i = 42;

  promise.set(&i);

  Future<string> future = promise.future()
    .then(lambda::bind(&itoa1, lambda::_1));

  ASSERT_TRUE(future.isReady());
  EXPECT_EQ("42", future.get());

  future = promise.future()
    .then(lambda::bind(&itoa2, lambda::_1));

  ASSERT_TRUE(future.isReady());
  EXPECT_EQ("42", future.get());
}

Future<Nothing> after(volatile bool* executed, const Future<Nothing>& future)
{
  EXPECT_TRUE(future.hasDiscard());
  *executed = true;
  return Failure("Failure");
}

// Checks that the 'after' callback gets executed if the future is not
// completed.
TEST(Process, after1)
{
  Clock::pause();

  volatile bool executed = false;

  Future<Nothing> future = Future<Nothing>()
    .after(Hours(42), lambda::bind(&after, &executed, lambda::_1));

  // A pending future should stay pending until 'after' is executed.
  EXPECT_TRUE(future.isPending());

  // Only advanced halfway, future should remain pending.
  Clock::advance(Hours(21));

  EXPECT_TRUE(future.isPending());

  // Even doing a discard on the future should keep it pending.
  future.discard();

  EXPECT_TRUE(future.isPending());

  // After advancing all the way the future should now fail because
  // the 'after' callback gets executed.
  Clock::advance(Hours(21));

  AWAIT_FAILED(future);

  EXPECT_TRUE(executed);

  Clock::resume();
}

// Checks that completing a promise will keep the 'after' callback
// from executing.
TEST(Process, after2)
{
  Clock::pause();

  volatile bool executed = false;

  Promise<Nothing> promise;

  Future<Nothing> future = promise.future()
    .after(Hours(42), lambda::bind(&after, &executed, lambda::_1));

  EXPECT_TRUE(future.isPending());

  // Only advanced halfway, future should remain pending.
  Clock::advance(Hours(21));

  EXPECT_TRUE(future.isPending());

  // Even doing a discard on the future should keep it pending.
  future.discard();

  EXPECT_TRUE(future.isPending());

  // Now set the promise, the 'after' timer should be cancelled and
  // the pending future should be completed.
  promise.set(Nothing());

  AWAIT_READY(future);

  // Advancing time the rest of the way should not cause the 'after'
  // callback to execute.
  Clock::advance(Hours(21));

  EXPECT_FALSE(executed);

  Clock::resume();
}

Future<bool> readyFuture()
{
  return true;
}

Future<bool> failedFuture()
{
  return Failure("The value is not positive (or zero)");
}

Future<bool> pendingFuture(const Future<bool>& future)
{
  return future; // Keep it pending.
}

Future<string> second(const bool& b)
{
  return b ? string("true") : string("false");
}

Future<string> third(const string& s)
{
  return s;
}

TEST(Process, chain)
{
  Future<string> s = readyFuture()
    .then(lambda::bind(&second, lambda::_1))
    .then(lambda::bind(&third, lambda::_1));

  s.await();

  ASSERT_TRUE(s.isReady());
  EXPECT_EQ("true", s.get());

  s = failedFuture()
    .then(lambda::bind(&second, lambda::_1))
    .then(lambda::bind(&third, lambda::_1));

  s.await();

  ASSERT_TRUE(s.isFailed());

  Promise<bool> promise;

  s = pendingFuture(promise.future())
    .then(lambda::bind(&second, lambda::_1))
    .then(lambda::bind(&third, lambda::_1));

  ASSERT_TRUE(s.isPending());

  promise.discard();

  AWAIT_DISCARDED(s);
}

Future<bool> inner1(const Future<bool>& future)
{
  return future;
}

Future<int> inner2(volatile bool* executed, const Future<int>& future)
{
  *executed = true;
  return future;
}

// Tests that Future::discard does not complete the future unless
// Promise::discard is invoked.
TEST(Process, discard1)
{
  Promise<bool> promise1;
  Promise<int> promise2;

  volatile bool executed = false;

  Future<int> future = Future<string>("hello world")
    .then(lambda::bind(&inner1, promise1.future()))
    .then(lambda::bind(&inner2, &executed, promise2.future()));

  ASSERT_TRUE(future.isPending());

  future.discard();

  // The future should remain pending, even though we discarded it.
  ASSERT_TRUE(future.hasDiscard());
  ASSERT_TRUE(future.isPending());

  // The future associated with the lambda already executed in the
  // first 'then' should have the discard propagated to it.
  ASSERT_TRUE(promise1.future().hasDiscard());

  // But the future assocaited with the lambda that hasn't yet been
  // executed should not have the discard propagated to it.
  ASSERT_FALSE(promise2.future().hasDiscard());

  // Now discarding the promise should cause the outer future to be
  // discarded also.
  ASSERT_TRUE(promise1.discard());

  AWAIT_DISCARDED(future);

  // And the final lambda should never have executed.
  ASSERT_FALSE(executed);
  ASSERT_TRUE(promise2.future().isPending());
}

// Tests that Future::discard does not complete the future and
// Promise::set can still be invoked to complete the future.
TEST(Process, discard2)
{
  Promise<bool> promise1;
  Promise<int> promise2;

  volatile bool executed = false;

  Future<int> future = Future<string>("hello world")
    .then(lambda::bind(&inner1, promise1.future()))
    .then(lambda::bind(&inner2, &executed, promise2.future()));

  ASSERT_TRUE(future.isPending());

  future.discard();

  // The future should remain pending, even though we discarded it.
  ASSERT_TRUE(future.hasDiscard());
  ASSERT_TRUE(future.isPending());

  // The future associated with the lambda already executed in the
  // first 'then' should have the discard propagated to it.
  ASSERT_TRUE(promise1.future().hasDiscard());

  // But the future assocaited with the lambda that hasn't yet been
  // executed should not have the discard propagated to it.
  ASSERT_FALSE(promise2.future().hasDiscard());

  // Now setting the promise should cause the outer future to be
  // discarded rather than executing the last lambda because the
  // implementation of Future::then does not continue the chain once a
  // discard occurs.
  ASSERT_TRUE(promise1.set(true));

  AWAIT_DISCARDED(future);

  // And the final lambda should never have executed.
  ASSERT_FALSE(executed);
  ASSERT_TRUE(promise2.future().isPending());
}

// Tests that Future::discard does not complete the future and
// Promise::fail can still be invoked to complete the future.
TEST(Process, discard3)
{
  Promise<bool> promise1;
  Promise<int> promise2;

  volatile bool executed = false;

  Future<int> future = Future<string>("hello world")
    .then(lambda::bind(&inner1, promise1.future()))
    .then(lambda::bind(&inner2, &executed, promise2.future()));

  ASSERT_TRUE(future.isPending());

  future.discard();

  // The future should remain pending, even though we discarded it.
  ASSERT_TRUE(future.hasDiscard());
  ASSERT_TRUE(future.isPending());

  // The future associated with the lambda already executed in the
  // first 'then' should have the discard propagated to it.
  ASSERT_TRUE(promise1.future().hasDiscard());

  // But the future assocaited with the lambda that hasn't yet been
  // executed should not have the discard propagated to it.
  ASSERT_FALSE(promise2.future().hasDiscard());

  // Now failing the promise should cause the outer future to be
  // failed also.
  ASSERT_TRUE(promise1.fail("failure message"));

  AWAIT_FAILED(future);

  // And the final lambda should never have executed.
  ASSERT_FALSE(executed);
  ASSERT_TRUE(promise2.future().isPending());
}

class SpawnProcess : public Process<SpawnProcess>
{
public:
  MOCK_METHOD0(initialize, void(void));
  MOCK_METHOD0(finalize, void(void));
};

TEST(Process, spawn)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  SpawnProcess process;

  EXPECT_CALL(process, initialize())
    .Times(1);

  EXPECT_CALL(process, finalize())
    .Times(1);

  PID<SpawnProcess> pid = spawn(process);

  ASSERT_FALSE(!pid);

  ASSERT_FALSE(wait(pid, Seconds(0)));

  terminate(pid);
  wait(pid);
}

class DispatchProcess : public Process<DispatchProcess>
{
public:
  MOCK_METHOD0(func0, void(void));
  MOCK_METHOD1(func1, bool(bool));
  MOCK_METHOD1(func2, Future<bool>(bool));
  MOCK_METHOD1(func3, int(int));
  MOCK_METHOD2(func4, Future<bool>(bool, int));
};

TEST(Process, dispatch)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  DispatchProcess process;

  EXPECT_CALL(process, func0())
    .Times(1);

  EXPECT_CALL(process, func1(_))
    .WillOnce(ReturnArg<0>());

  EXPECT_CALL(process, func2(_))
    .WillOnce(ReturnArg<0>());

  PID<DispatchProcess> pid = spawn(&process);

  ASSERT_FALSE(!pid);

  dispatch(pid, &DispatchProcess::func0);

  Future<bool> future;

  future = dispatch(pid, &DispatchProcess::func1, true);

  EXPECT_TRUE(future.get());

  future = dispatch(pid, &DispatchProcess::func2, true);

  EXPECT_TRUE(future.get());

  terminate(pid);
  wait(pid);
}

TEST(Process, defer1)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  DispatchProcess process;

  EXPECT_CALL(process, func0())
    .Times(1);

  EXPECT_CALL(process, func1(_))
    .WillOnce(ReturnArg<0>());

  EXPECT_CALL(process, func2(_))
    .WillOnce(ReturnArg<0>());

  EXPECT_CALL(process, func4(_, _))
    .WillRepeatedly(ReturnArg<0>());

  PID<DispatchProcess> pid = spawn(&process);

  ASSERT_FALSE(!pid);

  {
    Deferred<void(void)> func0 =
      defer(pid, &DispatchProcess::func0);
    func0();
  }

  Future<bool> future;

  {
    Deferred<Future<bool>(void)> func1 =
      defer(pid, &DispatchProcess::func1, true);
    future = func1();
    EXPECT_TRUE(future.get());
  }

  {
    Deferred<Future<bool>(void)> func2 =
      defer(pid, &DispatchProcess::func2, true);
    future = func2();
    EXPECT_TRUE(future.get());
  }

  {
    Deferred<Future<bool>(void)> func4 =
      defer(pid, &DispatchProcess::func4, true, 42);
    future = func4();
    EXPECT_TRUE(future.get());
  }

  {
    Deferred<Future<bool>(bool)> func4 =
      defer(pid, &DispatchProcess::func4, lambda::_1, 42);
    future = func4(false);
    EXPECT_FALSE(future.get());
  }

  {
    Deferred<Future<bool>(int)> func4 =
      defer(pid, &DispatchProcess::func4, true, lambda::_1);
    future = func4(42);
    EXPECT_TRUE(future.get());
  }

  // Only take const &!

  terminate(pid);
  wait(pid);
}

class DeferProcess : public Process<DeferProcess>
{
public:
  Future<string> func1(const Future<int>& f)
  {
    return f.then(defer(self(), &Self::_func1, lambda::_1));
  }

  Future<string> func2(const Future<int>& f)
  {
    return f.then(defer(self(), &Self::_func2));
  }

private:
  Future<string> _func1(int i)
  {
    return stringify(i);
  }

  Future<string> _func2()
  {
    return string("42");
  }
};

TEST(Process, defer2)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  DeferProcess process;

  PID<DeferProcess> pid = spawn(process);

  Future<string> f = dispatch(pid, &DeferProcess::func1, 41);

  f.await();

  ASSERT_TRUE(f.isReady());
  EXPECT_EQ("41", f.get());

  f = dispatch(pid, &DeferProcess::func2, 41);

  f.await();

  ASSERT_TRUE(f.isReady());
  EXPECT_EQ("42", f.get());

  terminate(pid);
  wait(pid);
}

template <typename T>
void set(T* t1, const T& t2)
{
  *t1 = t2;
}

TEST(Process, defer3)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  volatile bool bool1 = false;
  volatile bool bool2 = false;

  Deferred<void(bool)> set1 =
#if __cplusplus >= 201103L
    defer([&bool1] (bool b) { bool1 = b; });
#else // __cplusplus >= 201103L
    defer(std::tr1::function<void(bool)>(
              std::tr1::bind(&set<volatile bool>,
                             &bool1,
                             std::tr1::placeholders::_1)));
#endif // __cplusplus >= 201103L

  set1(true);

  Deferred<void(bool)> set2 =
#if __cplusplus >= 201103L
    defer([&bool2] (bool b) { bool2 = b; });
#else // __cplusplus >= 201103L
    defer(std::tr1::function<void(bool)>(
              std::tr1::bind(&set<volatile bool>,
                             &bool2,
                             std::tr1::placeholders::_1)));
#endif // __cplusplus >= 201103L

  set2(true);

  while (!bool1);
  while (!bool2);
}

class HandlersProcess : public Process<HandlersProcess>
{
public:
  HandlersProcess()
  {
    install("func", &HandlersProcess::func);
  }

  MOCK_METHOD2(func, void(const UPID&, const string&));
};

TEST(Process, handlers)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  HandlersProcess process;

  EXPECT_CALL(process, func(_, _))
    .Times(1);

  PID<HandlersProcess> pid = spawn(&process);

  ASSERT_FALSE(!pid);

  post(pid, "func");

  terminate(pid, false);
  wait(pid);
}

// Tests EXPECT_MESSAGE and EXPECT_DISPATCH and in particular that an
// event can get dropped before being processed.
TEST(Process, expect)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  HandlersProcess process;

  EXPECT_CALL(process, func(_, _))
    .Times(0);

  PID<HandlersProcess> pid = spawn(&process);

  ASSERT_FALSE(!pid);

  Future<Message> message = DROP_MESSAGE("func", _, _);

  post(pid, "func");

  AWAIT_EXPECT_READY(message);

  Future<Nothing> func = DROP_DISPATCH(pid, &HandlersProcess::func);

  dispatch(pid, &HandlersProcess::func, pid, "");

  AWAIT_EXPECT_READY(func);

  terminate(pid, false);
  wait(pid);
}

// Tests the FutureArg<N> action.
TEST(Process, action)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  HandlersProcess process;

  PID<HandlersProcess> pid = spawn(&process);

  ASSERT_FALSE(!pid);

  Future<string> future1;
  Future<Nothing> future2;
  EXPECT_CALL(process, func(_, _))
    .WillOnce(FutureArg<1>(&future1))
    .WillOnce(FutureSatisfy(&future2));

  dispatch(pid, &HandlersProcess::func, pid, "hello world");

  AWAIT_EXPECT_EQ("hello world", future1);

  EXPECT_TRUE(future2.isPending());

  dispatch(pid, &HandlersProcess::func, pid, "hello world");

  AWAIT_EXPECT_READY(future2);

  terminate(pid, false);
  wait(pid);
}

class BaseProcess : public Process<BaseProcess>
{
public:
  virtual void func() = 0;
  MOCK_METHOD0(foo, void());
};

class DerivedProcess : public BaseProcess
{
public:
  DerivedProcess() {}
  MOCK_METHOD0(func, void());
};

TEST(Process, inheritance)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  DerivedProcess process;

  EXPECT_CALL(process, func())
    .Times(2);

  EXPECT_CALL(process, foo())
    .Times(1);

  PID<DerivedProcess> pid1 = spawn(&process);

  ASSERT_FALSE(!pid1);

  dispatch(pid1, &DerivedProcess::func);

  PID<BaseProcess> pid2(process);
  PID<BaseProcess> pid3 = pid1;

  ASSERT_EQ(pid2, pid3);

  dispatch(pid3, &BaseProcess::func);
  dispatch(pid3, &BaseProcess::foo);

  terminate(pid1, false);
  wait(pid1);
}

TEST(Process, thunk)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  struct Thunk
  {
    static int run(int i)
    {
      return i;
    }

    static int run(int i, int j)
    {
      return run(i + j);
    }
  };

  int result = run(&Thunk::run, 21, 21).get();

  EXPECT_EQ(42, result);
}

class DelegatorProcess : public Process<DelegatorProcess>
{
public:
  explicit DelegatorProcess(const UPID& delegatee)
  {
    delegate("func", delegatee);
  }
};

class DelegateeProcess : public Process<DelegateeProcess>
{
public:
  DelegateeProcess()
  {
    install("func", &DelegateeProcess::func);
  }

  MOCK_METHOD2(func, void(const UPID&, const string&));
};

TEST(Process, delegate)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  DelegateeProcess delegatee;
  DelegatorProcess delegator(delegatee.self());

  EXPECT_CALL(delegatee, func(_, _))
    .Times(1);

  spawn(&delegator);
  spawn(&delegatee);

  post(delegator.self(), "func");

  terminate(delegator, false);
  wait(delegator);

  terminate(delegatee, false);
  wait(delegatee);
}

class TimeoutProcess : public Process<TimeoutProcess>
{
public:
  MOCK_METHOD0(timeout, void());
};

TEST(Process, delay)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  Clock::pause();

  volatile bool timeoutCalled = false;

  TimeoutProcess process;

  EXPECT_CALL(process, timeout())
    .WillOnce(Assign(&timeoutCalled, true));

  spawn(process);

  delay(Seconds(5), process.self(), &TimeoutProcess::timeout);

  Clock::advance(Seconds(5));

  while (!timeoutCalled);

  terminate(process);
  wait(process);

  Clock::resume();
}

class OrderProcess : public Process<OrderProcess>
{
public:
  void order(const PID<TimeoutProcess>& pid)
  {
    // TODO(benh): Add a test which uses 'send' instead of dispatch.
    dispatch(pid, &TimeoutProcess::timeout);
  }
};

TEST(Process, order)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  Clock::pause();

  TimeoutProcess process1;

  volatile bool timeoutCalled = false;

  EXPECT_CALL(process1, timeout())
    .WillOnce(Assign(&timeoutCalled, true));

  spawn(process1);

  Time now = Clock::now(&process1);

  Seconds seconds(1);

  Clock::advance(Seconds(1));

  EXPECT_EQ(now, Clock::now(&process1));

  OrderProcess process2;
  spawn(process2);

  dispatch(process2, &OrderProcess::order, process1.self());

  while (!timeoutCalled);

  EXPECT_EQ(now + seconds, Clock::now(&process1));

  terminate(process1);
  wait(process1);

  terminate(process2);
  wait(process2);

  Clock::resume();
}

class DonateProcess : public Process<DonateProcess>
{
public:
  void donate()
  {
    DonateProcess process;
    spawn(process);
    terminate(process);
    wait(process);
  }
};

TEST(Process, donate)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  DonateProcess process;
  spawn(process);

  dispatch(process, &DonateProcess::donate);

  terminate(process, false);
  wait(process);
}

class ExitedProcess : public Process<ExitedProcess>
{
public:
  explicit ExitedProcess(const UPID& pid) { link(pid); }

  MOCK_METHOD1(exited, void(const UPID&));
};

TEST(Process, exited)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  UPID pid = spawn(new ProcessBase(), true);

  ExitedProcess process(pid);

  volatile bool exitedCalled = false;

  EXPECT_CALL(process, exited(pid))
    .WillOnce(Assign(&exitedCalled, true));

  spawn(process);

  terminate(pid);

  while (!exitedCalled);

  terminate(process);
  wait(process);
}

TEST(Process, injectExited)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  UPID pid = spawn(new ProcessBase(), true);

  ExitedProcess process(pid);

  volatile bool exitedCalled = false;

  EXPECT_CALL(process, exited(pid))
    .WillOnce(Assign(&exitedCalled, true));

  spawn(process);

  inject::exited(pid, process.self());

  while (!exitedCalled);

  terminate(process);
  wait(process);
}

TEST(Process, select)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  Promise<int> promise1;
  Promise<int> promise2;
  Promise<int> promise3;
  Promise<int> promise4;

  std::set<Future<int> > futures;
  futures.insert(promise1.future());
  futures.insert(promise2.future());
  futures.insert(promise3.future());
  futures.insert(promise4.future());

  promise1.set(42);

  Future<Future<int> > future = select(futures);

  AWAIT_READY(future);
  AWAIT_READY(future.get());
  EXPECT_EQ(42, future.get().get());

  futures.erase(promise1.future());

  future = select(futures);
  EXPECT_TRUE(future.isPending());

  future.discard();
  AWAIT_DISCARDED(future);
}

TEST(Process, collect)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  // First ensure an empty list functions correctly.
  std::list<Future<int> > empty;
  Future<std::list<int> > future = collect(empty);
  AWAIT_ASSERT_READY(future);
  EXPECT_TRUE(future.get().empty());

  Promise<int> promise1;
  Promise<int> promise2;
  Promise<int> promise3;
  Promise<int> promise4;

  std::list<Future<int> > futures;
  futures.push_back(promise1.future());
  futures.push_back(promise2.future());
  futures.push_back(promise3.future());
  futures.push_back(promise4.future());

  // Set them out-of-order.
  promise4.set(4);
  promise2.set(2);
  promise1.set(1);
  promise3.set(3);

  future = collect(futures);

  AWAIT_ASSERT_READY(future);

  std::list<int> values;
  values.push_back(1);
  values.push_back(2);
  values.push_back(3);
  values.push_back(4);

  // We expect them to be returned in the same order as the
  // future list that was passed in.
  EXPECT_EQ(values, future.get());
}

TEST(Process, await1)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  // First ensure an empty list functions correctly.
  std::list<Future<int> > empty;
  Future<std::list<Future<int> > > future = await(empty);
  AWAIT_ASSERT_READY(future);
  EXPECT_TRUE(future.get().empty());

  Promise<int> promise1;
  Promise<int> promise2;
  Promise<int> promise3;
  Promise<int> promise4;

  std::list<Future<int> > futures;
  futures.push_back(promise1.future());
  futures.push_back(promise2.future());
  futures.push_back(promise3.future());
  futures.push_back(promise4.future());

  // Set them out-of-order.
  promise4.set(4);
  promise2.set(2);
  promise1.set(1);
  promise3.set(3);

  future = await(futures);

  AWAIT_ASSERT_READY(future);

  EXPECT_EQ(futures.size(), future.get().size());

  // We expect them to be returned in the same order as the
  // future list that was passed in.
  int i = 1;
  foreach (const Future<int>& result, future.get()) {
    ASSERT_TRUE(result.isReady());
    ASSERT_EQ(i++, result.get());
  }
}

TEST(Process, await2)
{
  Promise<int> promise1;
  Promise<bool> promise2;

  Future<tuples::tuple<Future<int>, Future<bool> > > future =
    await(promise1.future(), promise2.future());
  ASSERT_TRUE(future.isPending());

  promise1.set(42);

  ASSERT_TRUE(future.isPending());

  promise2.fail("failure message");

  AWAIT_READY(future);

  tuples::tuple<Future<int>, Future<bool> > futures = future.get();

  ASSERT_TRUE(tuples::get<0>(futures).isReady());
  ASSERT_EQ(42, tuples::get<0>(futures).get());

  ASSERT_TRUE(tuples::get<1>(futures).isFailed());
}

TEST(Process, await3)
{
  Promise<int> promise1;
  Promise<bool> promise2;

  Future<tuples::tuple<Future<int>, Future<bool> > > future =
    await(promise1.future(), promise2.future());
  ASSERT_TRUE(future.isPending());

  promise1.set(42);

  ASSERT_TRUE(future.isPending());

  promise2.discard();

  AWAIT_READY(future);

  tuples::tuple<Future<int>, Future<bool> > futures = future.get();

  ASSERT_TRUE(tuples::get<0>(futures).isReady());
  ASSERT_EQ(42, tuples::get<0>(futures).get());

  ASSERT_TRUE(tuples::get<1>(futures).isDiscarded());
}

class SettleProcess : public Process<SettleProcess>
{
public:
  SettleProcess() : calledDispatch(false) {}

  virtual void initialize()
  {
    os::sleep(Milliseconds(10));
    delay(Seconds(0), self(), &SettleProcess::afterDelay);
  }

  void afterDelay()
  {
    dispatch(self(), &SettleProcess::afterDispatch);
    os::sleep(Milliseconds(10));
    TimeoutProcess timeoutProcess;
    spawn(timeoutProcess);
    terminate(timeoutProcess);
    wait(timeoutProcess);
  }

  void afterDispatch()
  {
    os::sleep(Milliseconds(10));
    calledDispatch = true;
  }

  volatile bool calledDispatch;
};

TEST(Process, settle)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  Clock::pause();
  SettleProcess process;
  spawn(process);
  Clock::settle();
  ASSERT_TRUE(process.calledDispatch);
  terminate(process);
  wait(process);
  Clock::resume();
}

TEST(Process, pid)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  TimeoutProcess process;

  PID<TimeoutProcess> pid = process;
}

class Listener1 : public Process<Listener1>
{
public:
  virtual void event1() = 0;
};

class Listener2 : public Process<Listener2>
{
public:
  virtual void event2() = 0;
};

class MultipleListenerProcess
  : public Process<MultipleListenerProcess>,
    public Listener1,
    public Listener2
{
public:
  MOCK_METHOD0(event1, void());
  MOCK_METHOD0(event2, void());
};

TEST(Process, listener)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  MultipleListenerProcess process;

  EXPECT_CALL(process, event1())
    .Times(1);

  EXPECT_CALL(process, event2())
    .Times(1);

  spawn(process);

  dispatch(PID<Listener1>(process), &Listener1::event1);
  dispatch(PID<Listener2>(process), &Listener2::event2);

  terminate(process, false);
  wait(process);
}

class EventReceiver
{
public:
  MOCK_METHOD1(event1, void(int));
  MOCK_METHOD1(event2, void(const string&));
};

TEST(Process, executor)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  volatile bool event1Called = false;
  volatile bool event2Called = false;

  EventReceiver receiver;

  EXPECT_CALL(receiver, event1(42))
    .WillOnce(Assign(&event1Called, true));

  EXPECT_CALL(receiver, event2("event2"))
    .WillOnce(Assign(&event2Called, true));

  Executor executor;

  Deferred<void(int)> event1 =
    executor.defer(lambda::function<void(int)>(
                       lambda::bind(&EventReceiver::event1,
                                    &receiver,
                                    lambda::_1)));
  event1(42);

  Deferred<void(const string&)> event2 =
    executor.defer(lambda::function<void(const string&)>(
                       lambda::bind(&EventReceiver::event2,
                                    &receiver,
                                    lambda::_1)));

  event2("event2");

  while (!event1Called);
  while (!event2Called);
}

class RemoteProcess : public Process<RemoteProcess>
{
public:
  RemoteProcess()
  {
    install("handler", &RemoteProcess::handler);
  }

  MOCK_METHOD2(handler, void(const UPID&, const string&));
};

TEST(Process, remote)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  RemoteProcess process;
  spawn(process);

  Future<Nothing> handler;
  EXPECT_CALL(process, handler(_, _))
    .WillOnce(FutureSatisfy(&handler));

  int s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP);

  ASSERT_LE(0, s);

  sockaddr_in addr;
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = PF_INET;
  addr.sin_port = htons(process.self().port);
  addr.sin_addr.s_addr = process.self().ip;

  ASSERT_EQ(0, connect(s, (sockaddr*) &addr, sizeof(addr)));

  Message message;
  message.name = "handler";
  message.from = UPID();
  message.to = process.self();

  const string& data = MessageEncoder::encode(&message);

  ASSERT_EQ(data.size(), write(s, data.data(), data.size()));

  ASSERT_EQ(0, close(s));

  AWAIT_READY(handler);

  terminate(process);
  wait(process);
}

// Like the 'remote' test but uses http::post.
TEST(Process, http1)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  RemoteProcess process;
  spawn(process);

  Future<UPID> pid;
  Future<string> body;
  EXPECT_CALL(process, handler(_, _))
    .WillOnce(DoAll(FutureArg<0>(&pid),
                    FutureArg<1>(&body)));

  hashmap<string, string> headers;
  headers["User-Agent"] = "libprocess/";

  Future<http::Response> response =
    http::post(process.self(), "handler", headers, "hello world");

  AWAIT_READY(body);
  ASSERT_EQ("hello world", body.get());

  AWAIT_READY(pid);
  ASSERT_EQ(UPID(), pid.get());

  terminate(process);
  wait(process);
}

// Like 'http1' but using a 'Libprocess-From' header.
TEST(Process, http2)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  RemoteProcess process;
  spawn(process);

  // Create a receiving socket so we can get messages back.
  int s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
  ASSERT_LE(0, s);

  // Set up socket.
  sockaddr_in addr;
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = PF_INET;
  addr.sin_addr.s_addr = INADDR_ANY;
  addr.sin_port = 0;

  ASSERT_EQ(0, ::bind(s, (sockaddr*) &addr, sizeof(addr)));

  // Create a UPID for 'Libprocess-From' based on the IP and port we
  // got assigned.
  socklen_t addrlen = sizeof(addr);
  ASSERT_EQ(0, getsockname(s, (sockaddr*) &addr, &addrlen));

  UPID from("", addr.sin_addr.s_addr, ntohs(addr.sin_port));

  ASSERT_EQ(0, listen(s, 1));

  Future<UPID> pid;
  Future<string> body;
  EXPECT_CALL(process, handler(_, _))
    .WillOnce(DoAll(FutureArg<0>(&pid),
                    FutureArg<1>(&body)));

  hashmap<string, string> headers;
  headers["Libprocess-From"] = stringify(from);

  Future<http::Response> response =
    http::post(process.self(), "handler", headers, "hello world");

  AWAIT_READY(response);
  ASSERT_EQ(http::statuses[202], response.get().status);

  AWAIT_READY(body);
  ASSERT_EQ("hello world", body.get());

  AWAIT_READY(pid);
  ASSERT_EQ(from, pid.get());

  // Now post a message as though it came from the process.
  const string name = "reply";
  post(process.self(), from, name);

  // Accept the incoming connection.
  memset(&addr, 0, sizeof(addr));
  addrlen = sizeof(addr);

  int c = ::accept(s, (sockaddr*) &addr, &addrlen);
  ASSERT_LT(0, c);

  const string data = "POST /" + name + " HTTP/1.0";
  EXPECT_SOME_EQ(data, os::read(c, data.size()));

  close(c);
  close(s);

  terminate(process);
  wait(process);
}

int foo()
{
  return 1;
}

int foo1(int a)
{
  return a;
}

int foo2(int a, int b)
{
  return a + b;
}

int foo3(int a, int b, int c)
{
  return a + b + c;
}

int foo4(int a, int b, int c, int d)
{
  return a + b + c + d;
}

void bar(int a)
{
  return;
}

TEST(Process, async)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  // Non-void functions with different no.of args.
  EXPECT_EQ(1, async(&foo).get());
  EXPECT_EQ(10, async(&foo1, 10).get());
  EXPECT_EQ(30, async(&foo2, 10, 20).get());
  EXPECT_EQ(60, async(&foo3, 10, 20, 30).get());
  EXPECT_EQ(100, async(&foo4, 10, 20, 30, 40).get());

  // Non-void function with a complex arg.
  int i = 42;
  EXPECT_EQ("42", async(&itoa2, &i).get());

  // Non-void function that returns a future.
  EXPECT_EQ("42", async(&itoa1, &i).get().get());
}

TEST(Process, limiter)
{
  ASSERT_TRUE(GTEST_IS_THREADSAFE);

  int permits = 2;
  Duration duration = Milliseconds(5);

  RateLimiter limiter(permits, duration);
  Milliseconds interval = duration / permits;

  Stopwatch stopwatch;
  stopwatch.start();

  Future<Nothing> acquire1 = limiter.acquire();
  Future<Nothing> acquire2 = limiter.acquire();
  Future<Nothing> acquire3 = limiter.acquire();

  AWAIT_READY(acquire1);

  AWAIT_READY(acquire2);
  ASSERT_LE(interval, stopwatch.elapsed());

  AWAIT_READY(acquire3);
  ASSERT_LE(interval * 2, stopwatch.elapsed());
}

class FileServer : public Process<FileServer>
{
public:
  explicit FileServer(const string& _path)
    : path(_path) {}

  virtual void initialize()
  {
    provide("", path);
  }

  const string path;
};

TEST(Process, provide)
{
  const Try<string>& mkdtemp = os::mkdtemp();
  ASSERT_SOME(mkdtemp);

  const string LOREM_IPSUM =
      "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do "
      "eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad "
      "minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip "
      "ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
      "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur "
      "sint occaecat cupidatat non proident, sunt in culpa qui officia "
      "deserunt mollit anim id est laborum.";

  const string path = path::join(mkdtemp.get(), "lorem.txt");
  ASSERT_SOME(os::write(path, LOREM_IPSUM));

  FileServer server(path);
  PID<FileServer> pid = spawn(server);

  Future<http::Response> response = http::get(pid);

  AWAIT_READY(response);

  ASSERT_EQ(LOREM_IPSUM, response.get().body);

  terminate(server);
  wait(server);

  ASSERT_SOME(os::rmdir(path));
}

#if __cplusplus >= 201103L
int baz(string s) { return 42; }

Future<int> bam(string s) { return 42; }

TEST(Process, defers)
{
  {
    std::function<Future<int>(string)> f =
      defer(std::bind(baz, std::placeholders::_1));

    Deferred<Future<int>(string)> d =
      defer(std::bind(baz, std::placeholders::_1));

    Future<int> future = Future<string>().then(
        defer(std::bind(baz, std::placeholders::_1)));

    Future<int> future3 = Future<string>().then(
        std::bind(baz, std::placeholders::_1));

    Future<string>().then(std::function<int(string)>());
    Future<string>().then(std::function<int(void)>());

    Future<int> future11 = Future<string>().then(
        defer(std::bind(bam, std::placeholders::_1)));

    Future<int> future12 = Future<string>().then(
        std::bind(bam, std::placeholders::_1));

    std::function<Future<int>(string)> f2 =
      defer([] (string s) { return baz(s); });

    Deferred<Future<int>(string)> d2 =
      defer([] (string s) { return baz(s); });

    Future<int> future2 = Future<string>().then(
        defer([] (string s) { return baz(s); }));

    Future<int> future4 = Future<string>().then(
        [] (string s) { return baz(s); });

    Future<int> future5 = Future<string>().then(
        defer([] (string s) -> Future<int> { return baz(s); }));

    Future<int> future6 = Future<string>().then(
        defer([] (string s) { return Future<int>(baz(s)); }));

    Future<int> future7 = Future<string>().then(
        defer([] (string s) { return bam(s); }));

    Future<int> future8 = Future<string>().then(
        [] (string s) { return Future<int>(baz(s)); });

    Future<int> future9 = Future<string>().then(
        [] (string s) -> Future<int> { return baz(s); });

    Future<int> future10 = Future<string>().then(
        [] (string s) { return bam(s); });
  }

//   {
//     // CAN NOT DO IN CLANG!
//     std::function<void(string)> f =
//       defer(std::bind(baz, std::placeholders::_1));

//     std::function<int(string)> blah;
//     std::function<void(string)> blam = blah;

//     std::function<void(string)> f2 =
//       defer([] (string s) { return baz(s); });
//   }

//   {
//     // CAN NOT DO WITH GCC OR CLANG!
//     std::function<int(int)> f =
//       defer(std::bind(baz, std::placeholders::_1));
//   }

  {
    std::function<Future<int>(void)> f =
      defer(std::bind(baz, "42"));

    std::function<Future<int>(void)> f2 =
      defer([] () { return baz("42"); });
  }

  {
    std::function<Future<int>(int)> f =
      defer(std::bind(baz, "42"));

    std::function<Future<int>(int)> f2 =
      defer([] (int i) { return baz("42"); });
  }

  // Don't care about value passed from Future::then.
  {
    Future<int> future = Future<string>().then(
        defer(std::bind(baz, "42")));

    Future<int> future3 = Future<string>().then(
        std::bind(baz, "42"));

    Future<int> future11 = Future<string>().then(
        defer(std::bind(bam, "42")));

    Future<int> future12 = Future<string>().then(
        std::bind(bam, "42"));

    Future<int> future2 = Future<string>().then(
        defer([] () { return baz("42"); }));

    Future<int> future4 = Future<string>().then(
        [] () { return baz("42"); });

    Future<int> future5 = Future<string>().then(
        defer([] () -> Future<int> { return baz("42"); }));

    Future<int> future6 = Future<string>().then(
        defer([] () { return Future<int>(baz("42")); }));

    Future<int> future7 = Future<string>().then(
        defer([] () { return bam("42"); }));

    Future<int> future8 = Future<string>().then(
        [] () { return Future<int>(baz("42")); });

    Future<int> future9 = Future<string>().then(
        [] () -> Future<int> { return baz("42"); });

    Future<int> future10 = Future<string>().then(
        [] () { return bam("42"); });
  }

  struct Functor
  {
    int operator () (string) const { return 42; }
    int operator () () const { return 42; }
  } functor;

  Future<int> future13 = Future<string>().then(
      defer(functor));
}
#endif // __cplusplus >= 201103L

TEST(Future, FromTry)
{
  Try<int> t = 1;
  Future<int> future = t;

  ASSERT_TRUE(future.isReady());
  EXPECT_EQ(1, future.get());

  t = Error("error");
  future = t;

  ASSERT_TRUE(future.isFailed());
}

class PercentEncodedIDProcess : public Process<PercentEncodedIDProcess>
{
public:
  PercentEncodedIDProcess()
    : ProcessBase("id(42)") {}

  virtual void initialize()
  {
    install("handler1", &Self::handler1);
    route("/handler2", None(), &Self::handler2);
  }

  MOCK_METHOD2(handler1, void(const UPID&, const string&));
  MOCK_METHOD1(handler2, Future<http::Response>(const http::Request&));
};

TEST(Process, PercentEncodedURLs)
{
  PercentEncodedIDProcess process;
  spawn(process);

  // Construct the PID using percent-encoding.
  UPID pid("id%2842%29", process.self().ip, process.self().port);

  // Mimic a libprocess message sent to an installed handler.
  Future<Nothing> handler1;
  EXPECT_CALL(process, handler1(_, _))
    .WillOnce(FutureSatisfy(&handler1));

  hashmap<string, string> headers;
  headers["User-Agent"] = "libprocess/";

  Future<http::Response> response = http::post(pid, "handler1", headers);

  AWAIT_READY(handler1);

  // Now an HTTP request.
  EXPECT_CALL(process, handler2(_))
    .WillOnce(Return(http::OK()));

  response = http::get(pid, "handler2");

  AWAIT_READY(response);
  EXPECT_EQ(http::statuses[200], response.get().status);

  terminate(process);
  wait(process);
}


text:
// @flow

import React from 'react';
import { toArray } from 'react-emoji-render';

import { translate } from '../../../base/i18n';
import { Linkify } from '../../../base/react';

import { MESSAGE_TYPE_LOCAL } from '../../constants';

import AbstractChatMessage, {
    type Props
} from '../AbstractChatMessage';
import PrivateMessageButton from '../PrivateMessageButton';

/**
 * Renders a single chat message.
 */
class ChatMessage extends AbstractChatMessage<Props> {
    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        const { message } = this.props;
        const processedMessage = [];

        // content is an array of text and emoji components
        const content = toArray(this._getMessageText(), { className: 'smiley' });

        content.forEach(i => {
            if (typeof i === 'string') {
                processedMessage.push(<Linkify key = { i }>{ i }</Linkify>);
            } else {
                processedMessage.push(i);
            }
        });

        return (

                <div className = { `chatmessage ${message.privateMessage ? 'privatemessage' : ''}` }>

                            { this.props.showDisplayName && this._renderDisplayName() }

                                { processedMessage }

                            { message.privateMessage && this._renderPrivateNotice() }

                        { message.privateMessage && message.messageType !== MESSAGE_TYPE_LOCAL
                            && (

                                    <PrivateMessageButton
                                        participantID = { message.id }
                                        reply = { true }
                                        showLabel = { false } />

                            ) }

                { this.props.showTimestamp && this._renderTimestamp() }

        );
    }

    _getFormattedTimestamp: () => string;

    _getMessageText: () => string;

    _getPrivateNoticeMessage: () => string;

    /**
     * Renders the display name of the sender.
     *
     * @returns {React$Element<*>}
     */
    _renderDisplayName() {
        return (

                { this.props.message.displayName }

        );
    }

    /**
     * Renders the message privacy notice.
     *
     * @returns {React$Element<*>}
     */
    _renderPrivateNotice() {
        return (

                { this._getPrivateNoticeMessage() }

        );
    }

    /**
     * Renders the time at which the message was sent.
     *
     * @returns {React$Element<*>}
     */
    _renderTimestamp() {
        return (

                { this._getFormattedTimestamp() }

        );
    }
}

export default translate(ChatMessage);


text:
using Nwazet.Commerce.Models;
using Nwazet.Commerce.Services;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.Data.Migration;
using Orchard.Environment.Extensions;
using System.Collections.Generic;
using System.Linq;

namespace Nwazet.Commerce.Migrations {
    [OrchardFeature("Nwazet.Orders")]
    public class OrderMigrations : DataMigrationImpl {

        private readonly IContentManager _contentManager;
        private readonly ICurrencyProvider _currencyProvider;

        public OrderMigrations(
            IContentManager contentManager,
            ICurrencyProvider currencyProvider) {

            _contentManager = contentManager;
            _currencyProvider = currencyProvider;
        }

        public int Create() {
            SchemaBuilder.CreateTable("OrderPartRecord", table => table
                .ContentPartRecord()
                .Column<string>("Status")
                .Column<string>("Contents", column => column.Unlimited())
                .Column<string>("Customer", column => column.Unlimited())
                .Column<string>("Activity", column => column.Unlimited())
                .Column<string>("TrackingUrl")
                .Column<string>("Password")
                .Column<bool>("IsTestOrder"));

            ContentDefinitionManager.AlterTypeDefinition("Order", type => type
                .DisplayedAs("Order")
                .WithPart("Order")
                .WithPart("OrderPart")
                .WithPart("CommonPart", p => p.WithSetting("OwnerEditorSettings.ShowOwnerEditor", "false"))
                .WithPart("IdentityPart"));

            return 2;
        }

        public int UpdateFrom1() {
            ContentDefinitionManager.AlterTypeDefinition("Order", type => type
                .DisplayedAs("Order")
                .WithPart("Order")
                .WithPart("OrderPart")
                .WithPart("CommonPart", p => p.WithSetting("OwnerEditorSettings.ShowOwnerEditor", "false"))
                .WithPart("IdentityPart"));

            return 2;
        }

        public int UpdateFrom2() {
            SchemaBuilder.AlterTable("OrderPartRecord", table => table
                .AddColumn<int>("UserId", column => column.WithDefault(-1)));
            return 4;
        }

        public int UpdateFrom3() {

            //get all existing orders that do not have a CurrencyCode set, and set that to the currency
            //corresponding to the one set in the active ICurrencyProvider
            var query = _contentManager
                .Query<OrderPart, OrderPartRecord>(VersionOptions.AllVersions)
                .Where(opr => !opr.Contents.Contains("currencyCode"));
            string code = _currencyProvider.CurrencyCode;
            foreach (var item in query.List()) {
                item.CurrencyCode = code;
            }
            return 4;
        }
    }
}


text:
using ::testing::_;

namespace {
const char kRegularUrl1[] = "a.test";
const char kRegularUrl2[] = "b.test";
const char kAboutThisSiteUrl[] = "c.test";
}  // namespace

class AboutThisSiteSidePanelCoordinatorBrowserTest
    : public InProcessBrowserTest {
 protected:
  void SetUp() override {
    https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
    https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir());
    ASSERT_TRUE(https_server_.Start());
    SetUpFeatureList();
    InProcessBrowserTest::SetUp();
  }

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
  }

  GURL CreateUrl(const std::string& host) {
    return https_server_.GetURL(host, "/title1.html");
  }

  page_info::proto::SiteInfo CreateSiteInfo() {
    page_info::proto::SiteInfo info;
    info.mutable_more_about()->set_url(CreateUrl(kAboutThisSiteUrl).spec());
    return info;
  }

  content::WebContents* web_contents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

  SidePanelCoordinator* side_panel_coordinator() {
    return BrowserView::GetBrowserViewForBrowser(browser())
        ->side_panel_coordinator();
  }

 private:
  virtual void SetUpFeatureList() {
    feature_list_.InitWithFeatures(
        {features::kUnifiedSidePanel, page_info::kPageInfoAboutThisSiteMoreInfo,
         page_info::kPageInfoAboutThisSiteDescriptionPlaceholder},
        {});
  }

  base::test::ScopedFeatureList feature_list_;
  net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
};

IN_PROC_BROWSER_TEST_F(AboutThisSiteSidePanelCoordinatorBrowserTest,
                       ShowAndClose) {
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), CreateUrl(kRegularUrl1)));
  ASSERT_EQ(side_panel_coordinator()->GetCurrentEntryId(), absl::nullopt);

  // Test showing a sidepanel.
  ShowAboutThisSiteSidePanel(web_contents(), CreateUrl(kAboutThisSiteUrl));
  EXPECT_TRUE(side_panel_coordinator()->IsSidePanelShowing());
  EXPECT_EQ(side_panel_coordinator()->GetCurrentEntryId(),
            SidePanelEntry::Id::kAboutThisSite);

  // Check that it closes on navigation.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), CreateUrl(kRegularUrl2)));
  EXPECT_FALSE(side_panel_coordinator()->IsSidePanelShowing());
  EXPECT_EQ(side_panel_coordinator()->GetCurrentEntryId(), absl::nullopt);

  // Check that navigating to reloading that URL is works fine
  // (See https://crbug.com/1393000).
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), CreateUrl(kRegularUrl2)));
}

// TODO(crbug.com/1318000): Cover additional AboutThisSite side panel behavior.


text:
{{title}}

Milongas List for BaTango Guide.

    <select-guide type="countries" list="countries" label="Countries"></select-guide>


text:
package util

import (
	"strings"
)

// Takes a string of the form "name:port" or "name".
//  * If id is of the form "name" or "name:", then return (name, "", true)
//  * If id is of the form "name:port", then return (name, port, true)
//  * Otherwise, return ("", "", false)
// Additionally, name must be non-empty or valid will be returned false.
//
// Port is returned as a string, and it is not required to be numeric (could be
// used for a named port, for example).
func SplitPort(id string) (name, port string, valid bool) {
	parts := strings.Split(id, ":")
	if len(parts) > 2 {
		return "", "", false
	}
	if len(parts) == 2 {
		return parts[0], parts[1], len(parts[0]) > 0
	}
	return id, "", len(id) > 0
}


text:
namespace cast_streaming {

class FrameInjectingDemuxer;

// Handles initiating the streaming session between the browser-process sender
// and renderer-process receiver of the Cast Streaming Session. Specifically,
// this class manages the DemuxerConnector's lifetime in the renderer
// process. The lifetime of this object should match that of |render_frame| with
// which it is associated, and is guaranteed to outlive the
// FrameInjectingDemuxer that uses it, as the RenderFrame destruction will have
// triggered its destruction first.
class DemuxerConnector final : public mojom::DemuxerConnector {
 public:
  DemuxerConnector();
  ~DemuxerConnector() override;
  DemuxerConnector(const DemuxerConnector&) = delete;
  DemuxerConnector& operator=(const DemuxerConnector&) = delete;

  void BindReceiver(
      mojo::PendingAssociatedReceiver<mojom::DemuxerConnector> connector);

  void SetDemuxer(FrameInjectingDemuxer* demuxer);
  void OnDemuxerDestroyed();

  // Returns true if a Mojo connection is active.
  bool IsBound() const;

 private:
  void MaybeCallEnableReceiverCallback();

  void OnReceiverDisconnected();

  // mojom::DemuxerConnector implementation.
  void EnableReceiver(EnableReceiverCallback callback) override;
  void OnStreamsInitialized(
      mojom::AudioStreamInitializationInfoPtr audio_stream_info,
      mojom::VideoStreamInitializationInfoPtr video_stream_info) override;

  mojo::AssociatedReceiver<mojom::DemuxerConnector> demuxer_connector_receiver_{
      this};

  EnableReceiverCallback enable_receiver_callback_;
  FrameInjectingDemuxer* demuxer_ = nullptr;
  bool is_demuxer_initialized_ = false;

  SEQUENCE_CHECKER(sequence_checker_);
};

}  // namespace cast_streaming

#endif  // COMPONENTS_CAST_STREAMING_RENDERER_DEMUXER_CONNECTOR_H_


text:
require File.join File.dirname(__FILE__), "commenter", "active_record", "commentable", "class_methods.rb"
require File.join File.dirname(__FILE__), "commenter", "active_record", "comment", "class_methods.rb"
require File.join File.dirname(__FILE__), "commenter", "active_record", "comment", "instance_methods.rb"

# Rails Enhancements
if defined? Rails
  # Model
  if defined? ActiveRecord
    ActiveRecord::Base.send :include, Commenter::ActiveRecord::Commentable
    ActiveRecord::Base.send :include, Commenter::ActiveRecord::Comment
  end
end


text:
package main

import (
	"bytes"
	_ "embed"
	"flag"
	"fmt"
	"go/format"
	"html/template"
	"io/ioutil"
	"log"
	"os"
	"path"
	"strings"

	"github.com/gocql/gocql"
	"github.com/scylladb/gocqlx/v2"
	_ "github.com/scylladb/gocqlx/v2/table"
)

var (
	cmd          = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	flagCluster  = cmd.String("cluster", "127.0.0.1", "a comma-separated list of host:port tuples")
	flagKeyspace = cmd.String("keyspace", "", "keyspace to inspect")
	flagPkgname  = cmd.String("pkgname", "models", "the name you wish to assign to your generated package")
	flagOutput   = cmd.String("output", "models", "the name of the folder to output to")
	flagUser     = cmd.String("user", "", "user for password authentication")
	flagPassword = cmd.String("password", "", "password for password authentication")
)

var (
	//go:embed keyspace.tmpl
	keyspaceTmpl string
)

func main() {
	err := cmd.Parse(os.Args[1:])
	if err != nil {
		log.Fatalln("can't parse flags")
	}

	if *flagKeyspace == "" {
		log.Fatalln("missing required flag: keyspace")
	}

	if err := schemagen(); err != nil {
		log.Fatalf("failed to generate schema: %s", err)
	}
}

func schemagen() error {
	if err := os.MkdirAll(*flagOutput, os.ModePerm); err != nil {
		return fmt.Errorf("create output directory: %w", err)
	}

	session, err := createSession()
	if err != nil {
		return fmt.Errorf("open output file: %w", err)
	}
	metadata, err := session.KeyspaceMetadata(*flagKeyspace)
	if err != nil {
		return fmt.Errorf("fetch keyspace metadata: %w", err)
	}
	b, err := renderTemplate(metadata)
	if err != nil {
		return fmt.Errorf("render template: %w", err)
	}
	outputPath := path.Join(*flagOutput, *flagPkgname+".go")

	return ioutil.WriteFile(outputPath, b, os.ModePerm)
}

func renderTemplate(md *gocql.KeyspaceMetadata) ([]byte, error) {
	t, err := template.
		New("keyspace.tmpl").
		Funcs(template.FuncMap{"camelize": camelize}).
		Funcs(template.FuncMap{"mapScyllaToGoType": mapScyllaToGoType}).
		Funcs(template.FuncMap{"typeToString": typeToString}).
		Parse(keyspaceTmpl)

	if err != nil {
		log.Fatalln("unable to parse models template:", err)
	}

	imports := make([]string, 0)
	for _, t := range md.Tables {
		for _, c := range t.Columns {
			if (c.Validator == "timestamp" || c.Validator == "date" || c.Validator == "duration" || c.Validator == "time") && !existsInSlice(imports, "time") {
				imports = append(imports, "time")
			}
			if c.Validator == "decimal" && !existsInSlice(imports, "gopkg.in/inf.v0") {
				imports = append(imports, "gopkg.in/inf.v0")
			}
			if c.Validator == "duration" && !existsInSlice(imports, "github.com/gocql/gocql") {
				imports = append(imports, "github.com/gocql/gocql")
			}
		}
	}

	buf := &bytes.Buffer{}
	data := map[string]interface{}{
		"PackageName": *flagPkgname,
		"Tables":      md.Tables,
		"UserTypes":   md.UserTypes,
		"Imports":     imports,
	}

	if err = t.Execute(buf, data); err != nil {
		return nil, fmt.Errorf("template: %w", err)
	}
	return format.Source(buf.Bytes())
}

func createSession() (gocqlx.Session, error) {
	cluster := gocql.NewCluster(clusterHosts()...)
	if *flagUser != "" {
		cluster.Authenticator = gocql.PasswordAuthenticator{
			Username: *flagUser,
			Password: *flagPassword,
		}
	}
	return gocqlx.WrapSession(cluster.CreateSession())
}

func clusterHosts() []string {
	return strings.Split(*flagCluster, ",")
}

func existsInSlice(s []string, v string) bool {
	for _, i := range s {
		if v == i {
			return true
		}
	}

	return false
}


text:
package cz.metacentrum.perun.registrar.modules;

import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.PerunException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.blImpl.ModulesUtilsBlImpl;
import cz.metacentrum.perun.core.impl.Utils;
import cz.metacentrum.perun.registrar.model.Application;
import cz.metacentrum.perun.registrar.model.ApplicationForm;
import cz.metacentrum.perun.registrar.model.ApplicationFormItem;
import cz.metacentrum.perun.registrar.model.ApplicationFormItemWithPrefilledValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * Registration module used in "Elixir" VO on Elixir Perun instance.
 * It is used to pre-generate available user login on application form for new users.
 *
 * @author Pavel Zlámal <zlamal@cesnet.cz/>
 */
public class Elixir extends DefaultRegistrarModule {

	final static Logger log = LoggerFactory.getLogger(Elixir.class);

	private static String URN_USER_DISPLAY_NAME = AttributesManager.NS_USER_ATTR_CORE + ":" + "displayName";
	private static String URN_USER_PREFERRED_MAIL = AttributesManager.NS_USER_ATTR_DEF + ":" + "preferredMail";

	@Override
	public void processFormItemsWithData(PerunSession session, Application.AppType appType, ApplicationForm form, List<ApplicationFormItemWithPrefilledValue> formItems) throws PerunException {

		// generate login only on initial application
		if (!Application.AppType.INITIAL.equals(appType)) return;

		for (ApplicationFormItemWithPrefilledValue item : formItems) {
			if (Objects.equals(ApplicationFormItem.Type.USERNAME, item.getFormItem().getType())) {

				// skip if user already has login pre-filled from perun or federation
				if (!StringUtils.isEmpty(item.getPrefilledValue())) continue;

				// do not generate login if destination attribute is not set (won't be stored)
				if (StringUtils.isEmpty(item.getFormItem().getPerunDestinationAttribute())) continue;

				// set new generated value
				item.setPrefilledValue(generateLogin(session, item, formItems));
				// mark value as generated so the GUI allows editing and on submit server process new login
				item.setGenerated(true);

			}
		}

	}

	/**
	 * Generates new login for input data
	 *
	 *
	 * @param session PerunSession
	 * @param formItems Whole form data
	 * @return
	 */
	private String generateLogin(PerunSession session, ApplicationFormItemWithPrefilledValue loginItem, List<ApplicationFormItemWithPrefilledValue> formItems) {

		String displayName = fetchFormValue(formItems, URN_USER_DISPLAY_NAME);
		PerunBl perun = (PerunBl)session.getPerun();

		User user = null;
		try {
			user = Utils.parseUserFromCommonName(displayName, false);
		} catch (Exception ex) {

			log.warn("We couldn't parse commonName/displayName into User object");

			String mail = fetchFormValue(formItems, URN_USER_PREFERRED_MAIL);
			if (mail != null) {
				mail = mail.split("@")[0];
				user = new User(0, null, mail, null, null, null);
			}

		}

		if (user != null) {

			ModulesUtilsBlImpl.LoginGenerator generator = new ModulesUtilsBlImpl.LoginGenerator();

			String login = generator.generateLogin(user, new ModulesUtilsBlImpl.LoginGenerator.LoginGeneratorFunction() {
				@Override
				public String generateLogin(String firstName, String lastName) {

					String wholeLogin = "";
					if (firstName != null && !firstName.isEmpty()) {
						wholeLogin = firstName;
					}
					if (lastName != null && !lastName.isEmpty()) {
						wholeLogin = wholeLogin + lastName;
					}
					return wholeLogin;

				}
			});

			if (StringUtils.isEmpty(login)) return null;

			String checkedLogin = login;

			// fill value (with incremental number on conflict)
			int iterator = 0;
			while (iterator >= 0) {

				if (iterator > 0) {
					int iteratorLength = String.valueOf(iterator).length();
					if (login.length() + iteratorLength > 20) {
						// if login+iterator > 20 => crop login & reset iterator
						checkedLogin = login.substring(0, login.length()-1);
						iterator = 0;
					} else {
						checkedLogin = login + iterator;
					}
				} else {
					// checked login is used
				}

				try {

					AttributeDefinition def = perun.getAttributesManagerBl().getAttributeDefinition(session, loginItem.getFormItem().getPerunDestinationAttribute());
					Attribute checkAttribute = new Attribute(def, checkedLogin);
					perun.getAttributesManagerBl().checkAttributeSemantics(session, user, checkAttribute);
					return checkedLogin;

				} catch (WrongReferenceAttributeValueException ex) {
					// continue in a WHILE cycle - generated login was used
					iterator++;
				} catch (AttributeNotExistsException ex) {
					// we couldn't pre-fill login, its mapped to non-existing attribute
					log.warn("We couldn't generate new login, since its mapped to non-exisitng attribute {}., {}", loginItem.getFormItem().getPerunDestinationAttribute(), ex);
					return null;
				} catch (WrongAttributeAssignmentException | InternalErrorException e) {
					log.warn("We couldn't generate new login, because of exception.", e);
					return null;
				}
			}

		} else {
			log.error("We couldn't create arbitrary User object with name from form items in order to generate login.");
		}

		return null;

	}

	/**
	 * Retrieves specific attribute value from form items (first occurrence)
	 *
	 * @param formItems form items to search in
	 * @param perunDestinationAttribute destination attribute
	 * @return value of first found form item mapped to perunDestinationAttribute
	 */
	private String fetchFormValue(List<ApplicationFormItemWithPrefilledValue> formItems, String perunDestinationAttribute) {

		for (ApplicationFormItemWithPrefilledValue item : formItems) {
			if (perunDestinationAttribute.equals(item.getFormItem().getPerunDestinationAttribute())) {
				return item.getPrefilledValue();
			}
		}
		return null;

	}

}


text:
from __future__ import absolute_import

import pytest
import logging
import mock

from sentry.logging.handlers import StructLogHandler

@pytest.fixture
def handler():
    return StructLogHandler()

@pytest.fixture
def logger():
    return mock.MagicMock()

def make_logrecord(**extra):
    kwargs = dict(
        name='name',
        level=logging.INFO,
        pathname='pathname',
        lineno=10,
        msg='msg',
        args=None,
        exc_info=None,
    )
    kwargs.update(extra or {})
    return logging.LogRecord(**kwargs)

@pytest.mark.parametrize(
    'record,out', (
        ({}, {}), ({
            'msg': '%s',
            'args': (1, )
        }, {
            'event': '%s',
            'positional_args': (1, )
        }), ({
            'args': ({
                'a': 1
            }, )
        }, {
            'positional_args': ({
                'a': 1
            }, )
        }), ({
            'exc_info': True
        }, {
            'exc_info': True
        }),
    )
)
def test_emit(record, out, handler, logger):
    record = make_logrecord(**record)
    handler.emit(record, logger=logger)
    expected = dict(level=logging.INFO, event='msg', name='name')
    expected.update(out)
    logger.log.assert_called_once_with(**expected)


text:
namespace mojo {

std::vector<std::string>
StructTraits<network::mojom::ProxyBypassRulesDataView,
             net::ProxyBypassRules>::rules(const net::ProxyBypassRules& r) {
  std::vector<std::string> out;
  for (const auto& rule : r.rules()) {
    out.push_back(rule->ToString());
  }
  return out;
}

bool StructTraits<network::mojom::ProxyBypassRulesDataView,
                  net::ProxyBypassRules>::
    Read(network::mojom::ProxyBypassRulesDataView data,
         net::ProxyBypassRules* out_proxy_bypass_rules) {
  std::vector<std::string> rules;
  if (!data.ReadRules(&rules))
    return false;
  for (const auto& rule : rules) {
    if (!out_proxy_bypass_rules->AddRuleFromString(rule))
      return false;
  }
  return true;
}

std::vector<std::string>
StructTraits<network::mojom::ProxyListDataView, net::ProxyList>::proxies(
    const net::ProxyList& r) {
  std::vector<std::string> out;
  for (const auto& proxy : r.GetAll()) {
    out.push_back(net::ProxyServerToPacResultElement(proxy));
  }
  return out;
}

bool StructTraits<network::mojom::ProxyListDataView, net::ProxyList>::Read(
    network::mojom::ProxyListDataView data,
    net::ProxyList* out_proxy_list) {
  std::vector<std::string> proxies;
  if (!data.ReadProxies(&proxies))
    return false;
  for (const auto& proxy : proxies) {
    net::ProxyServer proxy_server = net::PacResultElementToProxyServer(proxy);
    if (!proxy_server.is_valid())
      return false;
    out_proxy_list->AddProxyServer(proxy_server);
  }
  return true;
}

network::mojom::ProxyRulesType
EnumTraits<network::mojom::ProxyRulesType, net::ProxyConfig::ProxyRules::Type>::
    ToMojom(net::ProxyConfig::ProxyRules::Type net_proxy_rules_type) {
  switch (net_proxy_rules_type) {
    case net::ProxyConfig::ProxyRules::Type::EMPTY:
      return network::mojom::ProxyRulesType::EMPTY;
    case net::ProxyConfig::ProxyRules::Type::PROXY_LIST:
      return network::mojom::ProxyRulesType::PROXY_LIST;
    case net::ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME:
      return network::mojom::ProxyRulesType::PROXY_LIST_PER_SCHEME;
  }
  return network::mojom::ProxyRulesType::EMPTY;
}

bool EnumTraits<network::mojom::ProxyRulesType,
                net::ProxyConfig::ProxyRules::Type>::
    FromMojom(network::mojom::ProxyRulesType mojo_proxy_rules_type,
              net::ProxyConfig::ProxyRules::Type* out) {
  switch (mojo_proxy_rules_type) {
    case network::mojom::ProxyRulesType::EMPTY:
      *out = net::ProxyConfig::ProxyRules::Type::EMPTY;
      return true;
    case network::mojom::ProxyRulesType::PROXY_LIST:
      *out = net::ProxyConfig::ProxyRules::Type::PROXY_LIST;
      return true;
    case network::mojom::ProxyRulesType::PROXY_LIST_PER_SCHEME:
      *out = net::ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME;
      return true;
  }
  return false;
}

bool StructTraits<network::mojom::ProxyRulesDataView,
                  net::ProxyConfig::ProxyRules>::
    Read(network::mojom::ProxyRulesDataView data,
         net::ProxyConfig::ProxyRules* out_proxy_rules) {
  out_proxy_rules->reverse_bypass = data.reverse_bypass();
  return data.ReadBypassRules(&out_proxy_rules->bypass_rules) &&
         data.ReadType(&out_proxy_rules->type) &&
         data.ReadSingleProxies(&out_proxy_rules->single_proxies) &&
         data.ReadProxiesForHttp(&out_proxy_rules->proxies_for_http) &&
         data.ReadProxiesForHttps(&out_proxy_rules->proxies_for_https) &&
         data.ReadProxiesForFtp(&out_proxy_rules->proxies_for_ftp) &&
         data.ReadFallbackProxies(&out_proxy_rules->fallback_proxies);
}

bool StructTraits<network::mojom::ProxyConfigDataView, net::ProxyConfig>::Read(
    network::mojom::ProxyConfigDataView data,
    net::ProxyConfig* out_proxy_config) {
  std::string pac_url;
  if (!data.ReadPacUrl(&pac_url) ||
      !data.ReadProxyRules(&out_proxy_config->proxy_rules())) {
    return false;
  }
  out_proxy_config->set_pac_url(GURL(pac_url));

  out_proxy_config->set_auto_detect(data.auto_detect());
  out_proxy_config->set_pac_mandatory(data.pac_mandatory());
  out_proxy_config->set_from_system(data.from_system());
  return true;
}

}  // namespace mojo