text:
package io.sarl.lang.mwe2.externalspec.latex;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Set;

import com.google.common.base.Joiner;
import com.google.common.io.Files;
import com.google.inject.Injector;
import com.ibm.icu.text.SimpleDateFormat;
import org.eclipse.xtext.util.Strings;
import org.eclipse.xtext.xtext.generator.CodeConfig;

import io.sarl.lang.mwe2.externalspec.AbstractExternalHighlightingFragment2;
import io.sarl.lang.mwe2.externalspec.ExternalHighlightingConfig.Color;
import io.sarl.lang.mwe2.externalspec.ExternalHighlightingConfig.ColorConfig;
import io.sarl.lang.mwe2.externalspec.IStyleAppendable;

/**
 * A {@link IGeneratorFragment} that create the language specification for
 * the LaTeX listings.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
public class LaTeXListingsGenerator2 extends AbstractExternalHighlightingFragment2<IStyleAppendable> {

	/** The default basename pattern for {@link MessageFormat}.
	 */
	public static final String BASENAME_PATTERN = "{0}-listing.sty"; //$NON-NLS-1$

	/** Default definition for the basic style for floating algorithms (without colors).
	 */
	public static final String DEFAULT_FLOAT_BASIC_STYLE = "\\smaller\\smaller"; //$NON-NLS-1$

	/** Default definition for the basic style for floating algorithms (with colors).
	 */
	public static final String DEFAULT_COLORIZED_FLOAT_BASIC_STYLE = "\\normalcolor\\smaller\\smaller"; //$NON-NLS-1$

	/** Default definition for the basic style for inline code (without color).
	 */
	public static final String DEFAULT_INLINE_BASIC_STYLE = "{}"; //$NON-NLS-1$

	/** Default definition for the basic style for inline code (with colors).
	 */
	public static final String DEFAULT_COLORIZED_INLINE_BASIC_STYLE = "\\normalcolor"; //$NON-NLS-1$;

	/** Default definition for the identifier style (without color).
	 */
	public static final String DEFAULT_IDENTIFIER_STYLE = "\\ttfamily"; //$NON-NLS-1$

	/** Default definition for the identifier style (with color).
	 */
	public static final String DEFAULT_COLORIZED_IDENTIFIER_STYLE = "\\color{SARLidentifier}" //$NON-NLS-1$
			+ DEFAULT_IDENTIFIER_STYLE;

	/** Default definition for the comment style (without color).
	 */
	public static final String DEFAULT_COMMENT_STYLE = "\\smaller\\bfseries"; //$NON-NLS-1$

	/** Default definition for the identifier style (with color).
	 */
	public static final String DEFAULT_COLORIZED_COMMENT_STYLE = "\\color{SARLcomment}" //$NON-NLS-1$
			+ DEFAULT_COMMENT_STYLE;

	/** Default definition for the string style (without color).
	 */
	public static final String DEFAULT_STRING_STYLE = "\\ttfamily"; //$NON-NLS-1$

	/** Default definition for the string style (with color).
	 */
	public static final String DEFAULT_COLORIZED_STRING_STYLE = "\\color{SARLstring}" //$NON-NLS-1$
			+ DEFAULT_STRING_STYLE;

	/** Default definition for the keyword style (without color).
	 */
	public static final String DEFAULT_KEYWORD_STYLE = "\\bfseries"; //$NON-NLS-1$

	/** Default definition for the keyword style (with color).
	 */
	public static final String DEFAULT_COLORIZED_KEYWORD_STYLE = "\\color{SARLkeyword}" //$NON-NLS-1$
			+ DEFAULT_KEYWORD_STYLE;

	/** Default definition for the overridable TeX requirements.
	 */
	public static final String[] DEFAULT_REQUIREMENTS = new String[] {
		"relsize", //$NON-NLS-1$
	};

	private String floatBasicStyle;

	private String identifierStyle;

	private String commentStyle;

	private String stringStyle;

	private String keywordStyle;

	private String inlineBasicStyle;

	private boolean showLines = true;

	private int lineStep = 2;

	private int tabSize = 2;

	private boolean showSpecialCharacters;

	private Collection<String> requirements;

	@Override
	protected IStyleAppendable newStyleAppendable() {
		return new TeXAppendable(getCodeConfig(), getLanguageSimpleName(), getLanguageVersion());
	}

	@Override
	public String toString() {
		return "LaTeX listings"; //$NON-NLS-1$
	}

	@Override
	public void initialize(Injector injector) {
		super.initialize(injector);
		setBasenameTemplate(BASENAME_PATTERN);
	}

	/** Set the TeX style of the standard code in floats.
	 *
	 * @param style the TeX code that describes the style. If {@code null}
	 *     or empty, the default style is applied.
	 */
	public void setFloatBasicStyle(String style) {
		this.floatBasicStyle = style;
	}

	/** Set the TeX style of the inline standard code.
	 *
	 * @param style the TeX code that describes the style. If {@code null}
	 *     or empty, the default style is applied.
	 */
	public void setInlineBasicStyle(String style) {
		this.inlineBasicStyle = style;
	}

	/** Set the TeX style of the identifiers.
	 *
	 * @param style the TeX code that describes the style. If {@code null}
	 *     or empty, the default style is applied.
	 */
	public void setIdentifierStyle(String style) {
		this.identifierStyle = style;
	}

	/** Set the TeX style of the comments.
	 *
	 * @param style the TeX code that describes the style. If {@code null}
	 *     or empty, the default style is applied.
	 */
	public void setCommentStyle(String style) {
		this.commentStyle = style;
	}

	/** Set the TeX style of the strings of characters.
	 *
	 * @param style the TeX code that describes the style. If {@code null}
	 *     or empty, the default style is applied.
	 */
	public void setStringStyle(String style) {
		this.stringStyle = style;
	}

	/** Set the TeX style of the strings of keywords.
	 *
	 * @param style the TeX code that describes the style. If {@code null}
	 *     or empty, the default style is applied.
	 */
	public void setKeywordStyle(String style) {
		this.keywordStyle = style;
	}

	/** Set if the TeX style shows the line numbers.
	 *
	 * @param showLineNumbers true for showing the line numbers.
	 */
	public void setLineNumbers(boolean showLineNumbers) {
		this.showLines = showLineNumbers;
	}

	/** Set the step between two line numbers.
	 *
	 * @param step the step between two line numbers.
	 */
	public void setLineStep(int step) {
		this.lineStep = step;
	}

	/** Set the size of the tabs.
	 *
	 * @param size the size of one tab character.
	 */
	public void setTabSize(int size) {
		this.tabSize = size;
	}

	/** Set if the TeX style shows the special characters (including spaces).
	 *
	 * @param showSpecialChars true for showing the special characters.
	 */
	public void setShowSpecialChars(boolean showSpecialChars) {
		this.showSpecialCharacters = showSpecialChars;
	}

	/** Clear the list of the overridable requirements.
	 */
	public void clearRequirements() {
		if (this.requirements == null) {
			this.requirements = new ArrayList<>();
		} else {
			this.requirements.clear();
		}
	}

	/** Add a TeX requirement.
	 *
	 * @param requirement the name of the TeX package.
	 */
	public void addRequirement(String requirement) {
		if (!Strings.isEmpty(requirement)) {
			if (this.requirements == null) {
				this.requirements = new ArrayList<>();
			}
			this.requirements.add(requirement);
		}
	}

	@SuppressWarnings({"checkstyle:parameternumber", "checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"})
	@Override
	protected void generate(IStyleAppendable it, Set<String> literals, Set<String> expressionKeywords,
			Set<String> modifiers, Set<String> primitiveTypes, Set<String> punctuation, Set<String> ignored,
			Set<String> specialKeywords, Set<String> typeDeclarationKeywords) {
		final ColorConfig colors = getHighlightingConfig().getColors();

		final Set<String> texKeywords = sortedConcat(expressionKeywords, modifiers, primitiveTypes,
				specialKeywords, typeDeclarationKeywords, literals);

		it.appendHeader();

		final String basename = getBasename(
				MessageFormat.format(getBasenameTemplate(), getLanguageSimpleName().toLowerCase()));
		final String simpleBasename = Files.getNameWithoutExtension(basename);

		it.appendNl("\\NeedsTeXFormat{LaTeX2e}[1995/12/01]"); //$NON-NLS-1$
		final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); //$NON-NLS-1$
		it.appendNl("\\ProvidesPackage'{'{0}'}'[{1}]", simpleBasename, dateFormat.format(new Date())); //$NON-NLS-1$

		if (generateOptions(it)) {
			it.appendNl("\\ProcessOptions*"); //$NON-NLS-1$
		}

		it.appendNl("\\RequirePackage{algpseudocode}"); //$NON-NLS-1$
		it.appendNl("\\RequirePackage{listings}"); //$NON-NLS-1$
		it.appendNl("\\RequirePackage{xspace}"); //$NON-NLS-1$
		Collection<String> requirements = this.requirements;
		if (requirements == null) {
			requirements = Arrays.asList(DEFAULT_REQUIREMENTS);
		}
		for (final String requirement : requirements) {
			it.appendNl("\\RequirePackage'{'{0}'}'", requirement); //$NON-NLS-1$
		}
		if (getEnableColors()) {
			it.appendNl("\\RequirePackage{xcolor}"); //$NON-NLS-1$
		}

		if (getEnableColors()) {
			for (final Color color : colors.getColors().values()) {
				it.appendNl("\\definecolor'{'{0}'}{'RGB'}{'{1},{2},{3}'}'", //$NON-NLS-1$
						color.getName(), color.getRed(), color.getGreen(), color.getBlue());
			}
			it.appendNl("\\colorlet'{'SARLcomment'}{'{0}'}'", colors.getCommentColor()); //$NON-NLS-1$
			it.appendNl("\\colorlet'{'SARLstring'}{'{0}'}'", colors.getStringColor()); //$NON-NLS-1$
			it.appendNl("\\colorlet'{'SARLkeyword'}{'{0}'}'", colors.getKeywordColor()); //$NON-NLS-1$
			it.appendNl("\\colorlet'{'SARLidentifier'}{'{0}'}'", colors.getIdentifierColor()); //$NON-NLS-1$
			it.appendNl("\\colorlet'{'SARLlinenumber'}{'{0}'}'", colors.getLineNumberColor()); //$NON-NLS-1$
		}

		final String langName = getLanguageSimpleName().toUpperCase();
		it.appendNl("\\lstdefinelanguage'{'{0}'}{'%", langName); //$NON-NLS-1$
		it.appendNl("   morecomment=[l]{//},"); //$NON-NLS-1$
		it.appendNl("   morecomment=[s]{/*}{*/},"); //$NON-NLS-1$
		it.appendNl("   morestring=[b]\","); //$NON-NLS-1$
		it.appendNl("   morekeywords='{'{0}'}',", Joiner.on(",").join(texKeywords)); //$NON-NLS-1$ //$NON-NLS-2$
		it.appendNl("}"); //$NON-NLS-1$

		it.appendNl("\\lstset{%"); //$NON-NLS-1$

		String floatBasicStyle = this.floatBasicStyle;
		if (floatBasicStyle == null) {
			floatBasicStyle = getEnableColors() ? DEFAULT_COLORIZED_FLOAT_BASIC_STYLE : DEFAULT_FLOAT_BASIC_STYLE;
		}
		floatBasicStyle = Strings.emptyIfNull(floatBasicStyle);
		it.appendNl("   basicstyle={0}, % the size of the fonts that are used for the code", floatBasicStyle); //$NON-NLS-1$

		it.appendNl("   breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace"); //$NON-NLS-1$
		it.appendNl("   breaklines=true, % sets automatic line breaking"); //$NON-NLS-1$
		it.appendNl("   captionpos=b, % sets the caption-position to bottom"); //$NON-NLS-1$
		it.appendNl("   deletekeywords={filter}, % if you want to delete keywords from the given language"); //$NON-NLS-1$
		it.appendNl("   escapeinside={(*@}{@*)}, % if you want to add LaTeX within your code"); //$NON-NLS-1$
		it.append("   extendedchars=true, % lets you use non-ASCII characters; for 8-bits "); //$NON-NLS-1$
		it.appendNl("encodings only, does not work with UTF-8"); //$NON-NLS-1$
		it.appendNl("   frame=none, % no frame around the code"); //$NON-NLS-1$
		it.append("   keepspaces=true, % keeps spaces in text, useful for keeping "); //$NON-NLS-1$
		it.appendNl("indentation of code (possibly needs columns=flexible)"); //$NON-NLS-1$

		String identifierStyle = this.identifierStyle;
		if (identifierStyle == null) {
			identifierStyle = getEnableColors() ? DEFAULT_COLORIZED_IDENTIFIER_STYLE : DEFAULT_IDENTIFIER_STYLE;
		}
		identifierStyle = Strings.emptyIfNull(identifierStyle);
		it.appendNl("   identifierstyle={0},", identifierStyle); //$NON-NLS-1$

		String commentStyle = this.commentStyle;
		if (commentStyle == null) {
			commentStyle = getEnableColors() ? DEFAULT_COLORIZED_COMMENT_STYLE : DEFAULT_COMMENT_STYLE;
		}
		commentStyle = Strings.emptyIfNull(commentStyle);
		it.appendNl("   commentstyle={0},", commentStyle); //$NON-NLS-1$

		String stringStyle = this.stringStyle;
		if (stringStyle == null) {
			stringStyle = getEnableColors() ? DEFAULT_COLORIZED_STRING_STYLE : DEFAULT_STRING_STYLE;
		}
		stringStyle = Strings.emptyIfNull(stringStyle);
		it.appendNl("   stringstyle={0},", stringStyle); //$NON-NLS-1$

		String keywordStyle = this.keywordStyle;
		if (keywordStyle == null) {
			keywordStyle = getEnableColors() ? DEFAULT_COLORIZED_KEYWORD_STYLE : DEFAULT_KEYWORD_STYLE;
		}
		keywordStyle = Strings.emptyIfNull(keywordStyle);
		it.appendNl("   keywordstyle={0}, % keyword style", keywordStyle); //$NON-NLS-1$

		it.appendNl("   language={0}, % the default language of the code", langName); //$NON-NLS-1$

		it.append("   showspaces={0}, % show spaces everywhere adding particular ", this.showSpecialCharacters); //$NON-NLS-1$
		it.appendNl("underscores; it overrides 'showstringspaces'"); //$NON-NLS-1$
		it.appendNl("   showstringspaces={0}, % underline spaces within strings only", //$NON-NLS-1$
				this.showSpecialCharacters);
		it.appendNl("   showtabs={0}, % show tabs within strings adding particular underscores", //$NON-NLS-1$
				this.showSpecialCharacters);
		if (this.showLines) {
			it.appendNl("   numbers=left,% Numbers on left"); //$NON-NLS-1$
			it.appendNl("   firstnumber=1, % First line number"); //$NON-NLS-1$
			it.appendNl("   numberfirstline=false, %Start numbers at first line"); //$NON-NLS-1$
			it.append("   stepnumber={0}, % the step between two line-numbers. ", this.lineStep); //$NON-NLS-1$
			it.appendNl("If it's 1, each line will be numbered"); //$NON-NLS-1$
		}
		it.appendNl("   tabsize={0}, % sets default tabsize to 2 spaces", this.tabSize); //$NON-NLS-1$
		it.append("   title=\\lstname, % show the filename of files included with "); //$NON-NLS-1$
		it.appendNl("\\lstinputlisting; also try caption instead of title"); //$NON-NLS-1$
		it.appendNl("   frameround=fttt, % If framed, use this rounded corner style"); //$NON-NLS-1$
		it.appendNl("   xleftmargin=20pt,"); //$NON-NLS-1$
		it.append("   numberstyle="); //$NON-NLS-1$
		if (getEnableColors()) {
			it.append("\\color{SARLlinenumber}"); //$NON-NLS-1$
		}
		it.appendNl("\\tiny,"); //$NON-NLS-1$
		it.appendNl("}"); //$NON-NLS-1$

		String inlineBasicStyle = this.inlineBasicStyle;
		if (inlineBasicStyle == null) {
			inlineBasicStyle = getEnableColors() ? DEFAULT_COLORIZED_INLINE_BASIC_STYLE : DEFAULT_INLINE_BASIC_STYLE;
		}
		inlineBasicStyle = Strings.emptyIfNull(inlineBasicStyle);
		it.append("\\newcommand{\\code}[1]{"); //$NON-NLS-1$
		it.append("\\ifmmode\\text'{'\\lstinline[basicstyle={0}]'{'#1'}}'", inlineBasicStyle); //$NON-NLS-1$
		it.append("\\else\\lstinline[basicstyle={0}]'{'#1'}'", inlineBasicStyle); //$NON-NLS-1$
		it.appendNl("\\fi}"); //$NON-NLS-1$
		it.appendNl("\\newcommand{\\sarl}{\\mbox{SARL}\\xspace}"); //$NON-NLS-1$
		it.appendNl("\\newcommand'{'\\sarlversion'}{'{0}'}'", getLanguageVersion()); //$NON-NLS-1$

		generateExtension(it);

		it.appendNl("\\endinput"); //$NON-NLS-1$
	}

	/** Generate the package definition extensions.
	 *
	 * @param it the target.
	 * @since 0.6
	 */
	protected void generateExtension(IStyleAppendable it) {
		//
	}

	@Override
	protected Object getReadmeFileContent(String basename) {
		return null;
	}

	/** Generate the optional extensions.
	 *
	 * @param it the target.
	 * @return {@code true} if options are generated.
	 * @since 0.6
	 */
	protected boolean generateOptions(IStyleAppendable it) {
		if (getEnableColors()) {
			it.appendNl("\\newif\\ifusesarlcolors\\usesarlcolorstrue"); //$NON-NLS-1$
			it.appendNl("\\DeclareOption{sarlcolors}{\\global\\usesarlcolorstrue}"); //$NON-NLS-1$
			it.appendNl("\\DeclareOption{nosarlcolors}{\\global\\usesarlcolorsfalse}"); //$NON-NLS-1$
			return true;
		}
		return false;
	}

	/** Appendable for tex-based styles.
	 *
	 * @author $Author: sgalland$
	 * @version $FullVersion$
	 * @mavengroupid $GroupId$
	 * @mavenartifactid $ArtifactId$
	 * @since 0.6
	 */
	protected static class TeXAppendable extends AbstractAppendable {

		/** Constructor.
		 *
		 * @param codeConfig the code configuration.
		 * @param languageName the language name.
		 * @param languageVersion the language version.
		 */
		protected TeXAppendable(CodeConfig codeConfig, String languageName, String languageVersion) {
			super(codeConfig, languageName, languageVersion);
		}

		@Override
		public void appendComment(String text, Object... parameters) {
			final String comment = applyFormat(text, parameters);
			for (final String line : comment.split("[\n\r]")) { //$NON-NLS-1$
				appendNl("% " + line.trim()); //$NON-NLS-1$
			}
		}

		@Override
		public void appendHeader() {
			final String[] header = Strings.emptyIfNull(getCodeConfig().getFileHeader()).split("[\n\r]+"); //$NON-NLS-1$
			for (final String headerLine : header) {
				appendNl(headerLine.replaceFirst("^\\s*[/]?[*][/]?", "%")); //$NON-NLS-1$//$NON-NLS-2$
			}
		}

	}

}


text:
package newrelic

import (
	"runtime"
	"strconv"
	"testing"

	"github.com/newrelic/go-agent/internal"
)

type myError struct{}

func (e myError) Error() string { return "my msg" }

func TestNoticeErrorBackground(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(myError{})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.myError",
		Caller:  "go-agent.TestNoticeErrorBackground",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNoticeErrorWeb(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	err := txn.NoticeError(myError{})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "WebTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.myError",
		Caller:  "go-agent.TestNoticeErrorWeb",
		URL:     "/hello",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, webErrorMetrics)
}

func TestNoticeErrorTxnEnded(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	txn.End()
	err := txn.NoticeError(myError{})
	if err != errAlreadyEnded {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundMetrics)
}

func TestNoticeErrorHighSecurity(t *testing.T) {
	cfgFn := func(cfg *Config) { cfg.HighSecurity = true }
	app := testApp(nil, cfgFn, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(myError{})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     highSecurityErrorMsg,
		Klass:   "newrelic.myError",
		Caller:  "go-agent.TestNoticeErrorHighSecurity",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   highSecurityErrorMsg,
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNoticeErrorMessageSecurityPolicy(t *testing.T) {
	replyfn := func(reply *internal.ConnectReply) { reply.SecurityPolicies.AllowRawExceptionMessages.SetEnabled(false) }
	app := testApp(replyfn, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(myError{})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     securityPolicyErrorMsg,
		Klass:   "newrelic.myError",
		Caller:  "go-agent.TestNoticeErrorMessageSecurityPolicy",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   securityPolicyErrorMsg,
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNoticeErrorLocallyDisabled(t *testing.T) {
	cfgFn := func(cfg *Config) { cfg.ErrorCollector.Enabled = false }
	app := testApp(nil, cfgFn, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(myError{})
	if errorsLocallyDisabled != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundMetrics)
}

func TestNoticeErrorRemotelyDisabled(t *testing.T) {
	replyfn := func(reply *internal.ConnectReply) { reply.CollectErrors = false }
	app := testApp(replyfn, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(myError{})
	if errorsRemotelyDisabled != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundMetrics)
}

func TestNoticeErrorNil(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(nil)
	if errNilError != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundMetrics)
}

func TestNoticeErrorEventsLocallyDisabled(t *testing.T) {
	cfgFn := func(cfg *Config) { cfg.ErrorCollector.CaptureEvents = false }
	app := testApp(nil, cfgFn, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(myError{})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.myError",
		Caller:  "go-agent.TestNoticeErrorEventsLocallyDisabled",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNoticeErrorEventsRemotelyDisabled(t *testing.T) {
	replyfn := func(reply *internal.ConnectReply) { reply.CollectErrorEvents = false }
	app := testApp(replyfn, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(myError{})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.myError",
		Caller:  "go-agent.TestNoticeErrorEventsRemotelyDisabled",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

type errorWithClass struct{ class string }

func (e errorWithClass) Error() string      { return "my msg" }
func (e errorWithClass) ErrorClass() string { return e.class }

func TestErrorWithClasser(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(errorWithClass{class: "zap"})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "zap",
		Caller:  "go-agent.TestErrorWithClasser",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "zap",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestErrorWithClasserReturnsEmpty(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(errorWithClass{class: ""})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.errorWithClass",
		Caller:  "go-agent.TestErrorWithClasserReturnsEmpty",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.errorWithClass",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

type withStackTrace struct{ trace []uintptr }

func makeErrorWithStackTrace() error {
	callers := make([]uintptr, 20)
	written := runtime.Callers(1, callers)
	return withStackTrace{
		trace: callers[0:written],
	}
}

func (e withStackTrace) Error() string         { return "my msg" }
func (e withStackTrace) StackTrace() []uintptr { return e.trace }

func TestErrorWithStackTrace(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	e := makeErrorWithStackTrace()
	err := txn.NoticeError(e)
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.withStackTrace",
		Caller:  "go-agent.makeErrorWithStackTrace",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.withStackTrace",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestErrorWithStackTraceReturnsNil(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	e := withStackTrace{trace: nil}
	err := txn.NoticeError(e)
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.withStackTrace",
		Caller:  "go-agent.TestErrorWithStackTraceReturnsNil",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.withStackTrace",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNewrelicErrorNoAttributes(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(Error{
		Message: "my msg",
		Class:   "my class",
	})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "my class",
		Caller:  "go-agent.TestNewrelicErrorNoAttributes",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "my class",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNewrelicErrorValidAttributes(t *testing.T) {
	extraAttributes := map[string]interface{}{
		"zip": "zap",
	}
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(Error{
		Message:    "my msg",
		Class:      "my class",
		Attributes: extraAttributes,
	})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName:        "OtherTransaction/Go/hello",
		Msg:            "my msg",
		Klass:          "my class",
		Caller:         "go-agent.TestNewrelicErrorValidAttributes",
		URL:            "",
		UserAttributes: extraAttributes,
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "my class",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
		UserAttributes: extraAttributes,
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNewrelicErrorAttributesHighSecurity(t *testing.T) {
	extraAttributes := map[string]interface{}{
		"zip": "zap",
	}
	cfgFn := func(cfg *Config) { cfg.HighSecurity = true }
	app := testApp(nil, cfgFn, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(Error{
		Message:    "my msg",
		Class:      "my class",
		Attributes: extraAttributes,
	})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName:        "OtherTransaction/Go/hello",
		Msg:            "message removed by high security setting",
		Klass:          "my class",
		Caller:         "go-agent.TestNewrelicErrorAttributesHighSecurity",
		URL:            "",
		UserAttributes: map[string]interface{}{},
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "my class",
			"error.message":   "message removed by high security setting",
			"transactionName": "OtherTransaction/Go/hello",
		},
		UserAttributes: map[string]interface{}{},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNewrelicErrorAttributesSecurityPolicy(t *testing.T) {
	extraAttributes := map[string]interface{}{
		"zip": "zap",
	}
	replyfn := func(reply *internal.ConnectReply) { reply.SecurityPolicies.CustomParameters.SetEnabled(false) }
	app := testApp(replyfn, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(Error{
		Message:    "my msg",
		Class:      "my class",
		Attributes: extraAttributes,
	})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName:        "OtherTransaction/Go/hello",
		Msg:            "my msg",
		Klass:          "my class",
		Caller:         "go-agent.TestNewrelicErrorAttributesSecurityPolicy",
		URL:            "",
		UserAttributes: map[string]interface{}{},
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "my class",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
		UserAttributes: map[string]interface{}{},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNewrelicErrorAttributeOverridesNormalAttribute(t *testing.T) {
	extraAttributes := map[string]interface{}{
		"zip": "zap",
	}
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	if err := txn.AddAttribute("zip", 123); nil != err {
		t.Error(err)
	}
	err := txn.NoticeError(Error{
		Message:    "my msg",
		Class:      "my class",
		Attributes: extraAttributes,
	})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName:        "OtherTransaction/Go/hello",
		Msg:            "my msg",
		Klass:          "my class",
		Caller:         "go-agent.TestNewrelicErrorAttributeOverridesNormalAttribute",
		URL:            "",
		UserAttributes: extraAttributes,
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "my class",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
		UserAttributes: extraAttributes,
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestNewrelicErrorInvalidAttributes(t *testing.T) {
	extraAttributes := map[string]interface{}{
		"zip":     "zap",
		"INVALID": struct{}{},
	}
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(Error{
		Message:    "my msg",
		Class:      "my class",
		Attributes: extraAttributes,
	})
	if _, ok := err.(internal.ErrInvalidAttributeType); !ok {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundMetrics)
}

func TestExtraErrorAttributeRemovedThroughConfiguration(t *testing.T) {
	cfgfn := func(cfg *Config) {
		cfg.ErrorCollector.Attributes.Exclude = []string{"IGNORE_ME"}
	}
	app := testApp(nil, cfgfn, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(Error{
		Message: "my msg",
		Class:   "my class",
		Attributes: map[string]interface{}{
			"zip":       "zap",
			"IGNORE_ME": 123,
		},
	})
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{{
		TxnName:        "OtherTransaction/Go/hello",
		Msg:            "my msg",
		Klass:          "my class",
		Caller:         "go-agent.TestExtraErrorAttributeRemovedThroughConfiguration",
		URL:            "",
		UserAttributes: map[string]interface{}{"zip": "zap"},
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "my class",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
		UserAttributes: map[string]interface{}{"zip": "zap"},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)

}

func TestTooManyExtraErrorAttributes(t *testing.T) {
	attrs := make(map[string]interface{})
	for i := 0; i <= internal.AttributeErrorLimit; i++ {
		attrs[strconv.Itoa(i)] = i
	}
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.NoticeError(Error{
		Message:    "my msg",
		Class:      "my class",
		Attributes: attrs,
	})
	if errTooManyErrorAttributes != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundMetrics)
}

redpajama_set_name: RedPajamaGithub


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
//
//     Produced by Entity Framework Visual Editor v3.0.4.7
//     Source:                    https://github.com/msawczyn/EFDesigner
//     Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner
//     Documentation:             https://msawczyn.github.io/EFDesigner/
//     License (MIT):             https://github.com/msawczyn/EFDesigner/blob/master/LICENSE
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.CompilerServices;

namespace Testing
{
   public partial class BChild
   {
      partial void Init();

      /// <summary>
      /// Default constructor. Protected due to required properties, but present because EF needs it.
      /// </summary>
      protected BChild()
      {
         // NOTE: This class has one-to-one associations with BChild.
         // One-to-one associations are not validated in constructors since this causes a scenario where each one must be constructed before the other.

         BParentCollection = new System.Collections.Generic.HashSet<global::Testing.BParentCollection>();
         BParentCollection_1 = new System.Collections.Generic.HashSet<global::Testing.BParentCollection>();
         BParentCollection_2 = new System.Collections.Generic.HashSet<global::Testing.BParentCollection>();

         Init();
      }

      /// <summary>
      /// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving.
      /// </summary>
      public static BChild CreateBChildUnsafe()
      {
         return new BChild();
      }

      /// <summary>
      /// Public constructor with required data
      /// </summary>
      /// <param name="bparentrequired"></param>
      /// <param name="bparentrequired_2"></param>
      public BChild(global::Testing.BParentRequired bparentrequired, global::Testing.BParentRequired bparentrequired_2)
      {
         // NOTE: This class has one-to-one associations with BChild.
         // One-to-one associations are not validated in constructors since this causes a scenario where each one must be constructed before the other.

         if (bparentrequired == null) throw new ArgumentNullException(nameof(bparentrequired));
         this.BParentRequired = bparentrequired;
         bparentrequired.BChildOptional = this;

         if (bparentrequired_2 == null) throw new ArgumentNullException(nameof(bparentrequired_2));
         this.BParentRequired_2 = bparentrequired_2;
         bparentrequired_2.BChildCollection.Add(this);

         this.BParentCollection = new System.Collections.Generic.HashSet<global::Testing.BParentCollection>();
         this.BParentCollection_1 = new System.Collections.Generic.HashSet<global::Testing.BParentCollection>();
         this.BParentCollection_2 = new System.Collections.Generic.HashSet<global::Testing.BParentCollection>();
         Init();
      }

      /// <summary>
      /// Static create function (for use in LINQ queries, etc.)
      /// </summary>
      /// <param name="bparentrequired"></param>
      /// <param name="bparentrequired_2"></param>
      public static BChild Create(global::Testing.BParentRequired bparentrequired, global::Testing.BParentRequired bparentrequired_2)
      {
         return new BChild(bparentrequired, bparentrequired_2);
      }

      /*************************************************************************
       * Properties
       *************************************************************************/

      /// <summary>
      /// Backing field for Id
      /// </summary>
      internal int _id;
      /// <summary>
      /// When provided in a partial class, allows value of Id to be changed before setting.
      /// </summary>
      partial void SetId(int oldValue, ref int newValue);
      /// <summary>
      /// When provided in a partial class, allows value of Id to be changed before returning.
      /// </summary>
      partial void GetId(ref int result);

      /// <summary>
      /// Identity, Indexed, Required
      /// </summary>
      [Key]
      [Required]
      public int Id
      {
         get
         {
            int value = _id;
            GetId(ref value);
            return (_id = value);
         }
         set
         {
            int oldValue = _id;
            SetId(oldValue, ref value);
            if (oldValue != value)
            {
               _id = value;
            }
         }
      }

      /*************************************************************************
       * Navigation properties
       *************************************************************************/

      /// <summary>
      /// Required
      /// </summary>
      public virtual global::Testing.BParentRequired BParentRequired { get; set; }

      /// <summary>
      /// Required
      /// </summary>
      public virtual global::Testing.BParentRequired BParentRequired_1 { get; set; }

      /// <summary>
      /// Required
      /// </summary>
      public virtual global::Testing.BParentRequired BParentRequired_2 { get; set; }

      public virtual ICollection<global::Testing.BParentCollection> BParentCollection { get; private set; }

      public virtual ICollection<global::Testing.BParentCollection> BParentCollection_1 { get; private set; }

      public virtual ICollection<global::Testing.BParentCollection> BParentCollection_2 { get; private set; }

      public virtual global::Testing.BParentOptional BParentOptional { get; set; }

      public virtual global::Testing.BParentOptional BParentOptional_1 { get; set; }

      public virtual global::Testing.BParentOptional BParentOptional_2 { get; set; }

   }
}


text:
static const QString kFeedURL = "http://www.facebook.com/connect/prompt_feed.php";

///////////////////////////////////////////////////////////////////////////////////////////////////

FBFeedDialog::FBFeedDialog(FBSession* aSession) : FBDialog(aSession)
{}

void FBFeedDialog::load ()
{
    Dictionary getParams, postParams;
    getParams["display"] = "touch";

    postParams["api_key"] = iSession->apiKey();
    postParams["session_key"] = iSession->sessionKey();
    postParams["preview"] = "1";
    postParams["callback"] = "fbconnect:success";
    postParams["cancel"] = "fbconnect:cancel";
    postParams["feed_info"] = generateFeedInfo();
    postParams["feed_target_type"] = "self_feed";
    postParams["user_message_prompt"] = iUserMessagePrompt;

    loadURL(kFeedURL, QNetworkAccessManager::PostOperation, getParams, postParams );

}

QString FBFeedDialog::generateFeedInfo() const
{
    QStringList pairs;

    if (iTemplateBundleId) {
        pairs.append("\"template_id\":" + QString::number( iTemplateBundleId, 10 ));
    }
    if (iTemplateData.length()) {
        pairs.append("\"template_data\":" + iTemplateData);
    }
    if (iBodyGeneral.length()) {
        pairs.append("\"body_general\":" + iBodyGeneral);
    }

    return "{" + pairs.join(",") + "}";
}


text:
import datetime
import distutils.spawn
import functools
import subprocess
import weechat

# https://gist.github.com/ChrisTM/5834503
class throttle(object):
    """
    Decorator that prevents a function from being called more than once every
    time period.

    To create a function that cannot be called more than once a minute:

        @throttle(minutes=1)
        def my_fun():
            pass
    """
    def __init__(self, seconds=0, minutes=0, hours=0):
        self.throttle_period = datetime.timedelta(
            seconds=seconds, minutes=minutes, hours=hours
        )
        self.time_of_last_call = datetime.datetime.min

    def __call__(self, fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            now = datetime.datetime.now()
            time_since_last_call = now - self.time_of_last_call
            if time_since_last_call > self.throttle_period:
                self.time_of_last_call = now
                return fn(*args, **kwargs)
        return wrapper

@throttle(seconds=1)
def notify(data, signal, signal_data):
    separated = signal_data.split("\t")
    try:
        title = separated[0]
    except IndexError:
        title = "WeeChat"

    message = "\t".join(separated[1:])
    notification = f'display notification "{message}" with title "{title}""'
    process = subprocess.Popen("osascript -".split(), stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    process.communicate(notification.encode())
    exit_code = process.wait()
    if exit_code == 0:
        return weechat.WEECHAT_RC_OK
    else:
        return weechat.WEECHAT_RC_ERROR

def main():
    if not weechat.register("terminal_notifier", "Keith Smiley", "1.1.0", "MIT",
                            "Get OS X notifications for messages", "", ""):
        return weechat.WEECHAT_RC_ERROR

    if distutils.spawn.find_executable("osascript") is None:
        return weechat.WEECHAT_RC_OK

    weechat.hook_signal("weechat_pv", "notify", "")
    weechat.hook_signal("weechat_highlight", "notify", "")

    return weechat.WEECHAT_RC_OK

if __name__ == "__main__":
    main()


text:
<?php include("header.php") ?>

    Previous

    Next

New release

     <form action="https://www.paypal.com/cgi-bin/webscr" method="post">

TOM CLANCY'S GHOST

Price: 1790 Baths

              <input type="hidden" name="cmd" value="_cart" />
              <input type="hidden" name="add" value="1" />
              <input type="hidden" name="business" value="payment@nextlevel.com" />
              <input type="hidden" name="item_name" value="TOM CLANCY'S GHOST RECON WILDLANDS" />
              <input type="hidden" name="quantity" value="1" />
              <input type="hidden" name="amount" value="1790.00" />
              <input type="hidden" name="currency_code" value="THB" />
              <input type="hidden" name="no_note" value="1">
              <input type="hidden" name="shipping" value="50">
              <input type="submit" name="submit" value="Add to cart" class="btn btn-primary" />

         </form>
  <form action="https://www.paypal.com/cgi-bin/webscr" method="post">

Sniper Elite4

Price: 1890 Baths

        <input type="hidden" name="cmd" value="_cart" />
          <input type="hidden" name="add" value="1" />
          <input type="hidden" name="business" value="payment@nextlevel.com" />
          <input type="hidden" name="item_name" value="Sniper Elite4" />
          <input type="hidden" name="quantity" value="1" />
          <input type="hidden" name="amount" value="1890.00" />
          <input type="hidden" name="currency_code" value="THB" />
          <input type="hidden" name="no_note" value="1">
          <input type="hidden" name="shipping" value="50">
          <input type="submit" name="submit" value="Add to cart" class="btn btn-primary" />

  </form>
  <form action="https://www.paypal.com/cgi-bin/webscr" method="post">

Resident Evil7

Price: 1890 Baths

        <input type="hidden" name="cmd" value="_cart" />
          <input type="hidden" name="add" value="1" />
          <input type="hidden" name="business" value="payment@nextlevel.com" />
          <input type="hidden" name="item_name" value="Resident Evil7" />
          <input type="hidden" name="quantity" value="1" />
          <input type="hidden" name="amount" value="1890.00" />
          <input type="hidden" name="currency_code" value="THB" />
          <input type="hidden" name="no_note" value="1">
          <input type="hidden" name="shipping" value="50">
          <input type="submit" name="submit" value="Add to cart" class="btn btn-primary" />

          </form>

<?php include("footer.php") ?>


text: google-site-verification: google81d8591a7281f655.html


text:
package   com.lite.android.launcher3;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

import   com.lite.android.launcher3.compat.UserHandleCompat;
import   com.lite.android.launcher3.compat.UserManagerCompat;

import java.util.Arrays;

/**
 * Represents an item in the launcher.
 */
public class ItemInfo {

    /**
     * Intent extra to store the profile. Format: UserHandle
     */
    static final String EXTRA_PROFILE = "profile";

    public static final int NO_ID = -1;

    /**
     * The id in the settings database for this item
     */
    public long id = NO_ID;

    /**
     * One of {@link LauncherSettings.Favorites#ITEM_TYPE_APPLICATION},
     * {@link LauncherSettings.Favorites#ITEM_TYPE_SHORTCUT},
     * {@link LauncherSettings.Favorites#ITEM_TYPE_FOLDER}, or
     * {@link LauncherSettings.Favorites#ITEM_TYPE_APPWIDGET}.
     */
    public int itemType;

    /**
     * The id of the container that holds this item. For the desktop, this will be
     * {@link LauncherSettings.Favorites#CONTAINER_DESKTOP}. For the all applications folder it
     * will be {@link #NO_ID} (since it is not stored in the settings DB). For user folders
     * it will be the id of the folder.
     */
    public long container = NO_ID;

    /**
     * Iindicates the screen in which the shortcut appears.
     */
    public long screenId = -1;

    /**
     * Indicates the X position of the associated cell.
     */
    public int cellX = -1;

    /**
     * Indicates the Y position of the associated cell.
     */
    public int cellY = -1;

    /**
     * Indicates the X cell span.
     */
    public int spanX = 1;

    /**
     * Indicates the Y cell span.
     */
    public int spanY = 1;

    /**
     * Indicates the minimum X cell span.
     */
    public int minSpanX = 1;

    /**
     * Indicates the minimum Y cell span.
     */
    public int minSpanY = 1;

    /**
     * Indicates the position in an ordered list.
     */
    public int rank = 0;

    /**
     * Indicates that this item needs to be updated in the db
     */
    public boolean requiresDbUpdate = false;

    /**
     * Title of the item
     */
    public CharSequence title;

    /**
     * Content description of the item.
     */
    public CharSequence contentDescription;

    /**
     * Indicates that this item has had it's position changed
     * because the grid size was made smaller and it could no longer fit.
     */
    public boolean wasMovedDueToReducedSpace = false;

    /**
     * The position of the item in a drag-and-drop operation.
     */
    public int[] dropPos = null;

    public UserHandleCompat user;

    /**
     * A custom drawable to use for the icon. Not persisted to the database because
     * it is not guaranteed to be a bitmap (could be a vector).
     */
    Drawable customDrawable;

    public ItemInfo() {
        user = UserHandleCompat.myUserHandle();
    }

    ItemInfo(ItemInfo info) {
        copyFrom(info);
        // tempdebug:
        LauncherModel.checkItemInfo(this);
    }

    public void copyFrom(ItemInfo info) {
        id = info.id;
        cellX = info.cellX;
        cellY = info.cellY;
        spanX = info.spanX;
        spanY = info.spanY;
        rank = info.rank;
        screenId = info.screenId;
        itemType = info.itemType;
        container = info.container;
        user = info.user;
        contentDescription = info.contentDescription;
    }

    public Intent getIntent() {
        throw new RuntimeException("Unexpected Intent");
    }

    /**
     * Write the fields of this item to the DB
     *
     * @param context A context object to use for getting UserManagerCompat
     * @param values
     */

    void onAddToDatabase(Context context, ContentValues values) {
        values.put(LauncherSettings.BaseLauncherColumns.ITEM_TYPE, itemType);
        values.put(LauncherSettings.Favorites.CONTAINER, container);
        values.put(LauncherSettings.Favorites.SCREEN, screenId);
        values.put(LauncherSettings.Favorites.CELLX, cellX);
        values.put(LauncherSettings.Favorites.CELLY, cellY);
        values.put(LauncherSettings.Favorites.SPANX, spanX);
        values.put(LauncherSettings.Favorites.SPANY, spanY);
        values.put(LauncherSettings.Favorites.RANK, rank);
        long serialNumber = UserManagerCompat.getInstance(context).getSerialNumberForUser(user);
        values.put(LauncherSettings.Favorites.PROFILE_ID, serialNumber);

        if (screenId == Workspace.EXTRA_EMPTY_SCREEN_ID) {
            // We should never persist an item on the extra empty screen.
            throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
        }
    }

    static void writeBitmap(ContentValues values, Bitmap bitmap) {
        if (bitmap != null) {
            byte[] data = Utilities.flattenBitmap(bitmap);
            values.put(LauncherSettings.Favorites.ICON, data);
        }
    }

    /**
     * It is very important that sub-classes implement this if they contain any references
     * to the activity (anything in the view hierarchy etc.). If not, leaks can result since
     * ItemInfo objects persist across rotation and can hence leak by holding stale references
     * to the old view hierarchy / activity.
     */
    void unbind() {
    }

    @Override
    public String toString() {
        return "Item(id=" + this.id + " type=" + this.itemType + " container=" + this.container
            + " screen=" + screenId + " cellX=" + cellX + " cellY=" + cellY + " spanX=" + spanX
            + " spanY=" + spanY + " dropPos=" + Arrays.toString(dropPos)
            + " user=" + user + ")";
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>JENO Nigeria</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

    <link href="css/agency.min.css" rel="stylesheet">

            <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
                Menu
            </button>
            Jeno

                        Services

                        Portfolio

                        About

                        Contact

JENO INNOVATIONS

Intelligent solutions

                Find Out More

Services

Our team is able and ready.

Consultancy

First class consultancy for all things information technology.

Software Development

Reliable, responsive and secure platform bulding, fine-tuned to your taste.

Branding and Design

Modern and professional branding for your project(s).

Works

Take a look at our archives.

Codemate

Educational software

HouseOnCamp

Web solution

Lifeline

Security software.

ChowNow

Food Ordering App

Schedula

software

About

Know us more.

 2014

JENO is Formed

Jeno is created in order to staisfy the growing hunger for technological growth in Nigeria and subsequently, the world.

2015

Transition to Full Service

Jeno moved from little beginnings to full time service,providing intelligent solutions for clients.

 2016

Phase Two Expansion

 Jeno begins to deliver top notch projects,focusing on achieving the best user interface and experience combined,while also delivering on analysis and consultancy,you should build your next project with us!

Get The

Quality Service

You Deserve

JENO INNOVATIONS

Enugu-Onitsha Expressway

Awka, Anambra state

 +2348166763009

 INFO@JENO.COM.NG  jenoinnovations@gmail.com

Copyright JENO 2017

Codemate

Educational software for beginners and intermediate alike.

Codemate is an educational desktop-based software that teaches programming to those who wish to learn about programming or improve on their skills.
                                    It comes with a well-structured tutorial for different aspects of programming, it's own in-built text-editor, browser and game. Codemate makes learning programming fun.

Date: February 2015

Client: Owned

Category: Software

Status: Development Stage

                                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

HouseOnCamp

freelance housing web solution.

HouseOnCamp is a web-based project which solves the problem of accomodation,its a freelance web platform for finding available rooms and roommates whenever you need them.

Date: October 2016

Client: Owned

Category: Web

Status: Development Stage

                                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

Lifeline

Security for me and you.

Lifeline does its bit to reduce the rate of insecurity, lifeline helps users report major and minor incidences to security authorities before and after they happen.

Date: January 2016

Client: Owned

Category: Software

Status: Development Stage

                                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

ChowNow

Food ordering app.

ChowNow allows users to order food directly from available fastfoods nearby, delivery of packages goes directly to your doorstep.

Date: April 2017

Client: Owned

Category: Software

Status: Development Stage

                                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

Schedula.

message dispatcher.

Schedula sends messages on your behalf at the time you set it to do so, it is simply your handy message tool made to work on your smartphone.

Date: december 2016

Client: undisclosed

Category: mobile application.

Status: Development Stage

                                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

simple branding.

Logo finished for a client of ours.

Date: January 2017

Client:

Category: Branding and design.

                                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>


text:
package permafrost.tundra.server.invoke;

import com.wm.app.b2b.server.BaseService;
import com.wm.app.b2b.server.ISRuntimeException;
import com.wm.app.b2b.server.invoke.ServiceStatus;
import com.wm.data.IData;
import com.wm.util.ServerException;
import permafrost.tundra.lang.RecoverableException;
import permafrost.tundra.lang.UnrecoverableException;
import java.util.Iterator;

/**
 * Converts any exceptions thrown by a trigger service to be instances of ISRuntimeException to support being retried.
 */
public class TriggerRetryProcessor extends AbstractInvokeChainProcessor {
    /**
     * Initialization on demand holder idiom.
     */
    private static class Holder {
        /**
         * The singleton instance of the class.
         */
        private static final TriggerRetryProcessor INSTANCE = new TriggerRetryProcessor();
    }

    /**
     * Disallow instantiation of this class.
     */
    private TriggerRetryProcessor() {}

    /**
     * Returns the singleton instance of this class.
     *
     * @return The singleton instance of this class.
     */
    public static TriggerRetryProcessor getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * Processes a service invocation: if invoked by a trigger, converts all exceptions thrown to be instances of
     * ISRuntimeException so that the service can be retried.
     *
     * @param iterator          Invocation chain.
     * @param baseService       The invoked service.
     * @param pipeline          The input pipeline for the service.
     * @param serviceStatus     The status of the service invocation.
     * @throws ServerException  If the service invocation fails.
     */
    @Override
    public void process(Iterator iterator, BaseService baseService, IData pipeline, ServiceStatus serviceStatus) throws ServerException {
        boolean isTrigger = Thread.currentThread().getName().startsWith("TriggerTask");
        if (isTrigger) {
            try {
                super.process(iterator, baseService, pipeline, serviceStatus);
            } catch(Throwable ex) {
                if (ex instanceof UnrecoverableException) {
                    // do not retry unrecoverable exceptions
                    throw (UnrecoverableException) ex;
                } else if (ex instanceof ISRuntimeException) {
                    // rethrow if exception is already recoverable
                    throw (ISRuntimeException)ex;
                } else {
                    // convert all other exceptions to be instances of ISRuntimeException
                    throw new RecoverableException(ex);
                }
            }
        } else {
            super.process(iterator, baseService, pipeline, serviceStatus);
        }
    }
}


text:
package msgraph

// AirPrintDestination undocumented
type AirPrintDestination struct {
	// Object is the base model of AirPrintDestination
	Object
	// IPAddress The IP Address of the AirPrint destination.
	IPAddress *string `json:"ipAddress,omitempty"`
	// ResourcePath undocumented
	ResourcePath *string `json:"resourcePath,omitempty"`
	// Port The listening port of the AirPrint destination. If this key is not specified AirPrint will use the default port. Available in iOS 11.0 and later.
	Port *int `json:"port,omitempty"`
	// ForceTLS If true AirPrint connections are secured by Transport Layer Security (TLS). Default is false. Available in iOS 11.0 and later.
	ForceTLS *bool `json:"forceTls,omitempty"`
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=utf8">
<TITLE>
Uses of Package org.jgentleframework.services.eventservices.context
</TITLE>

<META NAME="date" CONTENT="2009-08-05">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.jgentleframework.services.eventservices.context

Packages that use org.jgentleframework.services.eventservices.context

org.jgentleframework.services.eventservices

org.jgentleframework.services.eventservices.context

Classes in org.jgentleframework.services.eventservices.context used by org.jgentleframework.services.eventservices

EventServiceContext

          Chịu trách nhiệm quản lý, thực thi các bean có chức năng
 fire và receive event trong "Event Service".

Classes in org.jgentleframework.services.eventservices.context used by org.jgentleframework.services.eventservices.context

EventServiceContext

          Chịu trách nhiệm quản lý, thực thi các bean có chức năng
 fire và receive event trong "Event Service".

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
Test.

I would also like to read this. :)

Hello world!


text:
package io.atomix.protocols.raft.protocol;

/**
 * Cluster metadata request.
 */
public class MetadataRequest extends SessionRequest {

  /**
   * Returns a new metadata request builder.
   *
   * @return A new metadata request builder.
   */
  public static Builder builder() {
    return new Builder();
  }

  public MetadataRequest(long session) {
    super(session);
  }

  /**
   * Metadata request builder.
   */
  public static class Builder extends SessionRequest.Builder<Builder, MetadataRequest> {
    @Override
    public MetadataRequest build() {
      return new MetadataRequest(session);
    }
  }
}


text:
// http://dev.w3.org/html5/postmsg/#event-definitions

/**
 MessageEvent

 @name  MessageEvent
 @class MessageEvent
 */
function MessageEvent(target_, data_, origin_) {
    return {
        target: target_,
        data: data_,
        origin: origin_,
        bubbles: true,
        cancelable: true,
        type: "message",
        lastEventId: ""
    }
}

/**
 Contents of the message.

 @field
 @readonly
 @name       data
 @type       Object
 @memberOf   MessageEvent#
 */

/**
 Origin that produced the message.
 See RFC6455 The Web Origin
 Concept.

 @field
 @readonly
 @name       origin
 @type       String
 @memberOf   MessageEvent#
 */


text:
namespace flutter {
TEST(IncomingMessageDispatcher, SetHandle) {
  FlutterDesktopMessengerRef messenger =
      reinterpret_cast<FlutterDesktopMessengerRef>(0xfeedface);
  const uint8_t* message_data = reinterpret_cast<const uint8_t*>(0xcafebabe);
  auto dispatcher = std::make_unique<IncomingMessageDispatcher>(messenger);
  bool did_call = false;
  dispatcher->SetMessageCallback(
      "hello",
      [](FlutterDesktopMessengerRef messenger,
         const FlutterDesktopMessage* message, void* user_data) {
        EXPECT_EQ(messenger,
                  reinterpret_cast<FlutterDesktopMessengerRef>(0xfeedface));
        EXPECT_EQ(message->message,
                  reinterpret_cast<const uint8_t*>(0xcafebabe));
        EXPECT_EQ(message->message_size, 123u);
        *reinterpret_cast<bool*>(user_data) = true;
      },
      &did_call);
  FlutterDesktopMessage message = {
      .struct_size = sizeof(FlutterDesktopMessage),
      .channel = "hello",
      .message = message_data,
      .message_size = 123,
      .response_handle = nullptr,
  };
  dispatcher->HandleMessage(message);
  EXPECT_TRUE(did_call);
}

TEST(IncomingMessageDispatcher, BlockInputFalse) {
  FlutterDesktopMessengerRef messenger = nullptr;
  auto dispatcher = std::make_unique<IncomingMessageDispatcher>(messenger);
  bool did_call[3] = {false, false, false};
  dispatcher->SetMessageCallback(
      "hello",
      [](FlutterDesktopMessengerRef messenger,
         const FlutterDesktopMessage* message,
         void* user_data) { reinterpret_cast<bool*>(user_data)[0] = true; },
      &did_call);
  FlutterDesktopMessage message = {
      .struct_size = sizeof(FlutterDesktopMessage),
      .channel = "hello",
      .message = nullptr,
      .message_size = 0,
      .response_handle = nullptr,
  };
  dispatcher->HandleMessage(
      message, [&did_call] { did_call[1] = true; },
      [&did_call] { did_call[2] = true; });
  EXPECT_TRUE(did_call[0]);
  EXPECT_FALSE(did_call[1]);
  EXPECT_FALSE(did_call[2]);
}

TEST(IncomingMessageDispatcher, BlockInputTrue) {
  FlutterDesktopMessengerRef messenger = nullptr;
  auto dispatcher = std::make_unique<IncomingMessageDispatcher>(messenger);
  static int counter = 0;
  int did_call[3] = {-1, -1, -1};
  dispatcher->EnableInputBlockingForChannel("hello");
  dispatcher->SetMessageCallback(
      "hello",
      [](FlutterDesktopMessengerRef messenger,
         const FlutterDesktopMessage* message,
         void* user_data) { reinterpret_cast<int*>(user_data)[counter++] = 1; },
      &did_call);
  FlutterDesktopMessage message = {
      .struct_size = sizeof(FlutterDesktopMessage),
      .channel = "hello",
      .message = nullptr,
      .message_size = 0,
      .response_handle = nullptr,
  };
  dispatcher->HandleMessage(
      message, [&did_call] { did_call[counter++] = 0; },
      [&did_call] { did_call[counter++] = 2; });
  EXPECT_EQ(did_call[0], 0);
  EXPECT_EQ(did_call[1], 1);
  EXPECT_EQ(did_call[2], 2);
}

}  // namespace flutter


text:
import time
import threading
import uuid

from nose.tools import eq_
from nose.tools import raises

from kazoo.exceptions import KazooException
from kazoo.protocol.states import EventType
from kazoo.testing import KazooTestCase

class KazooDataWatcherTests(KazooTestCase):
    def setUp(self):
        super(KazooDataWatcherTests, self).setUp()
        self.path = "/" + uuid.uuid4().hex
        self.client.ensure_path(self.path)

    def test_data_watcher(self):
        update = threading.Event()
        data = [True]

        # Make it a non-existent path
        self.path += 'f'

        @self.client.DataWatch(self.path)
        def changed(d, stat):
            data.pop()
            data.append(d)
            update.set()

        update.wait(10)
        eq_(data, [None])
        update.clear()

        self.client.create(self.path, b'fred')
        update.wait(10)
        eq_(data[0], b'fred')
        update.clear()

    def test_data_watcher_once(self):
        update = threading.Event()
        data = [True]

        # Make it a non-existent path
        self.path += 'f'

        dwatcher = self.client.DataWatch(self.path)

        @dwatcher
        def changed(d, stat):
            data.pop()
            data.append(d)
            update.set()

        update.wait(10)
        eq_(data, [None])
        update.clear()

        @raises(KazooException)
        def test_it():
            @dwatcher
            def func(d, stat):
                data.pop()
        test_it()

    def test_data_watcher_with_event(self):
        # Test that the data watcher gets passed the event, if it
        # accepts three arguments
        update = threading.Event()
        data = [True]

        # Make it a non-existent path
        self.path += 'f'

        @self.client.DataWatch(self.path)
        def changed(d, stat, event):
            data.pop()
            data.append(event)
            update.set()

        update.wait(10)
        eq_(data, [None])
        update.clear()

        self.client.create(self.path, b'fred')
        update.wait(10)
        eq_(data[0].type, EventType.CREATED)
        update.clear()

    def test_func_style_data_watch(self):
        update = threading.Event()
        data = [True]

        # Make it a non-existent path
        path = self.path + 'f'

        def changed(d, stat):
            data.pop()
            data.append(d)
            update.set()
        self.client.DataWatch(path, changed)

        update.wait(10)
        eq_(data, [None])
        update.clear()

        self.client.create(path, b'fred')
        update.wait(10)
        eq_(data[0], b'fred')
        update.clear()

    def test_datawatch_across_session_expire(self):
        update = threading.Event()
        data = [True]

        @self.client.DataWatch(self.path)
        def changed(d, stat):
            data.pop()
            data.append(d)
            update.set()

        update.wait(10)
        eq_(data, [b""])
        update.clear()

        self.expire_session()
        self.client.retry(self.client.set, self.path, b'fred')
        update.wait(25)
        eq_(data[0], b'fred')

    def test_func_stops(self):
        update = threading.Event()
        data = [True]

        self.path += "f"

        fail_through = []

        @self.client.DataWatch(self.path)
        def changed(d, stat):
            data.pop()
            data.append(d)
            update.set()
            if fail_through:
                return False

        update.wait(10)
        eq_(data, [None])
        update.clear()

        fail_through.append(True)
        self.client.create(self.path, b'fred')
        update.wait(10)
        eq_(data[0], b'fred')
        update.clear()

        self.client.set(self.path, b'asdfasdf')
        update.wait(0.2)
        eq_(data[0], b'fred')

        d, stat = self.client.get(self.path)
        eq_(d, b'asdfasdf')

    def test_no_such_node(self):
        args = []

        @self.client.DataWatch("/some/path")
        def changed(d, stat):
            args.extend([d, stat])

        eq_(args, [None, None])

    def test_bad_watch_func2(self):
        counter = 0

        @self.client.DataWatch(self.path)
        def changed(d, stat):
            if counter > 0:
                raise Exception("oops")

        raises(Exception)(changed)

        counter += 1
        self.client.set(self.path, b'asdfasdf')

    def test_watcher_evaluating_to_false(self):
        class WeirdWatcher(list):
            def __call__(self, *args):
                self.called = True
        watcher = WeirdWatcher()
        self.client.DataWatch(self.path, watcher)
        self.client.set(self.path, b'mwahaha')
        self.assertTrue(watcher.called)

    def test_watcher_repeat_delete(self):
        a = []
        ev = threading.Event()

        self.client.delete(self.path)

        @self.client.DataWatch(self.path)
        def changed(val, stat):
            a.append(val)
            ev.set()

        eq_(a, [None])
        ev.wait(10)
        ev.clear()
        self.client.create(self.path, b'blah')
        ev.wait(10)
        eq_(ev.is_set(), True)
        ev.clear()
        eq_(a, [None, b'blah'])
        self.client.delete(self.path)
        ev.wait(10)
        eq_(ev.is_set(), True)
        ev.clear()
        eq_(a, [None, b'blah', None])
        self.client.create(self.path, b'blah')
        ev.wait(10)
        eq_(ev.is_set(), True)
        ev.clear()
        eq_(a, [None, b'blah', None, b'blah'])

    def test_watcher_with_closing(self):
        a = []
        ev = threading.Event()

        self.client.delete(self.path)

        @self.client.DataWatch(self.path)
        def changed(val, stat):
            a.append(val)
            ev.set()
        eq_(a, [None])

        b = False
        try:
            self.client.stop()
        except:
            b = True
        eq_(b, False)

class KazooChildrenWatcherTests(KazooTestCase):
    def setUp(self):
        super(KazooChildrenWatcherTests, self).setUp()
        self.path = "/" + uuid.uuid4().hex
        self.client.ensure_path(self.path)

    def test_child_watcher(self):
        update = threading.Event()
        all_children = ['fred']

        @self.client.ChildrenWatch(self.path)
        def changed(children):
            while all_children:
                all_children.pop()
            all_children.extend(children)
            update.set()

        update.wait(10)
        eq_(all_children, [])
        update.clear()

        self.client.create(self.path + '/' + 'smith')
        update.wait(10)
        eq_(all_children, ['smith'])
        update.clear()

        self.client.create(self.path + '/' + 'george')
        update.wait(10)
        eq_(sorted(all_children), ['george', 'smith'])

    def test_child_watcher_once(self):
        update = threading.Event()
        all_children = ['fred']

        cwatch = self.client.ChildrenWatch(self.path)

        @cwatch
        def changed(children):
            while all_children:
                all_children.pop()
            all_children.extend(children)
            update.set()

        update.wait(10)
        eq_(all_children, [])
        update.clear()

        @raises(KazooException)
        def test_it():
            @cwatch
            def changed_again(children):
                update.set()
        test_it()

    def test_child_watcher_with_event(self):
        update = threading.Event()
        events = [True]

        @self.client.ChildrenWatch(self.path, send_event=True)
        def changed(children, event):
            events.pop()
            events.append(event)
            update.set()

        update.wait(10)
        eq_(events, [None])
        update.clear()

        self.client.create(self.path + '/' + 'smith')
        update.wait(10)
        eq_(events[0].type, EventType.CHILD)
        update.clear()

    def test_func_style_child_watcher(self):
        update = threading.Event()
        all_children = ['fred']

        def changed(children):
            while all_children:
                all_children.pop()
            all_children.extend(children)
            update.set()

        self.client.ChildrenWatch(self.path, changed)

        update.wait(10)
        eq_(all_children, [])
        update.clear()

        self.client.create(self.path + '/' + 'smith')
        update.wait(10)
        eq_(all_children, ['smith'])
        update.clear()

        self.client.create(self.path + '/' + 'george')
        update.wait(10)
        eq_(sorted(all_children), ['george', 'smith'])

    def test_func_stops(self):
        update = threading.Event()
        all_children = ['fred']

        fail_through = []

        @self.client.ChildrenWatch(self.path)
        def changed(children):
            while all_children:
                all_children.pop()
            all_children.extend(children)
            update.set()
            if fail_through:
                return False

        update.wait(10)
        eq_(all_children, [])
        update.clear()

        fail_through.append(True)
        self.client.create(self.path + '/' + 'smith')
        update.wait(10)
        eq_(all_children, ['smith'])
        update.clear()

        self.client.create(self.path + '/' + 'george')
        update.wait(0.5)
        eq_(all_children, ['smith'])

    def test_child_watch_session_loss(self):
        update = threading.Event()
        all_children = ['fred']

        @self.client.ChildrenWatch(self.path)
        def changed(children):
            while all_children:
                all_children.pop()
            all_children.extend(children)
            update.set()

        update.wait(10)
        eq_(all_children, [])
        update.clear()

        self.client.create(self.path + '/' + 'smith')
        update.wait(10)
        eq_(all_children, ['smith'])
        update.clear()
        self.expire_session()

        self.client.retry(self.client.create,
                          self.path + '/' + 'george')
        update.wait(20)
        eq_(sorted(all_children), ['george', 'smith'])

    def test_child_stop_on_session_loss(self):
        update = threading.Event()
        all_children = ['fred']

        @self.client.ChildrenWatch(self.path, allow_session_lost=False)
        def changed(children):
            while all_children:
                all_children.pop()
            all_children.extend(children)
            update.set()

        update.wait(10)
        eq_(all_children, [])
        update.clear()

        self.client.create(self.path + '/' + 'smith')
        update.wait(10)
        eq_(all_children, ['smith'])
        update.clear()
        self.expire_session()

        self.client.retry(self.client.create,
                          self.path + '/' + 'george')
        update.wait(4)
        eq_(update.is_set(), False)
        eq_(all_children, ['smith'])

        children = self.client.get_children(self.path)
        eq_(sorted(children), ['george', 'smith'])

    def test_bad_children_watch_func(self):
        counter = 0

        @self.client.ChildrenWatch(self.path)
        def changed(children):
            if counter > 0:
                raise Exception("oops")

        raises(Exception)(changed)
        counter += 1
        self.client.create(self.path + '/' + 'smith')

class KazooPatientChildrenWatcherTests(KazooTestCase):
    def setUp(self):
        super(KazooPatientChildrenWatcherTests, self).setUp()
        self.path = "/" + uuid.uuid4().hex

    def _makeOne(self, *args, **kwargs):
        from kazoo.recipe.watchers import PatientChildrenWatch
        return PatientChildrenWatch(*args, **kwargs)

    def test_watch(self):
        self.client.ensure_path(self.path)
        watcher = self._makeOne(self.client, self.path, 0.1)
        result = watcher.start()
        children, asy = result.get()
        eq_(len(children), 0)
        eq_(asy.ready(), False)

        self.client.create(self.path + '/' + 'fred')
        asy.get(timeout=1)
        eq_(asy.ready(), True)

    def test_exception(self):
        from kazoo.exceptions import NoNodeError
        watcher = self._makeOne(self.client, self.path, 0.1)
        result = watcher.start()

        @raises(NoNodeError)
        def testit():
            result.get()
        testit()

    def test_watch_iterations(self):
        self.client.ensure_path(self.path)
        watcher = self._makeOne(self.client, self.path, 0.5)
        result = watcher.start()
        eq_(result.ready(), False)

        time.sleep(0.08)
        self.client.create(self.path + '/' + uuid.uuid4().hex)
        eq_(result.ready(), False)
        time.sleep(0.08)
        eq_(result.ready(), False)
        self.client.create(self.path + '/' + uuid.uuid4().hex)
        time.sleep(0.08)
        eq_(result.ready(), False)

        children, asy = result.get()
        eq_(len(children), 2)


text:
if Rails.env == 'development'
  # require 'rack-mini-profiler'
  #
  # # initialization is skipped so trigger it
  # Rack::MiniProfilerRails.initialize!(Rails.application)
  Rack::MiniProfiler.config.storage = Rack::MiniProfiler::MemoryStore
  # Have Mini Profiler show up on the right
  Rack::MiniProfiler.config.position = 'right'
  # Have Mini Profiler start in hidden mode - display with short cut (defaulted to 'Alt+P')
  Rack::MiniProfiler.config.start_hidden = true
  # Don't collect backtraces on SQL queries that take less than 5 ms to execute
  # (necessary on Rubies earlier than 2.0)
  Rack::MiniProfiler.config.backtrace_threshold_ms = 5
  Rack::MiniProfiler.config.toggle_shortcut = 'alt+d'
end


text:
<?php

namespace Symfony\Component\Lock\Store;

use Symfony\Component\Lock\Exception\InvalidArgumentException;
use Symfony\Component\Lock\Exception\InvalidTtlException;
use Symfony\Component\Lock\Exception\LockConflictedException;
use Symfony\Component\Lock\Key;
use Symfony\Component\Lock\PersistingStoreInterface;

/**
 * PdoStore is a PersistingStoreInterface implementation using a PDO connection.
 *
 * Lock metadata are stored in a table. You can use createTable() to initialize
 * a correctly defined table.

 * CAUTION: This store relies on all client and server nodes to have
 * synchronized clocks for lock expiry to occur at the correct time.
 * To ensure locks don't expire prematurely; the TTLs should be set with enough
 * extra time to account for any clock drift between nodes.
 *
 * @author Jérémy Derussé <jeremy@derusse.com>
 */
class PdoStore implements PersistingStoreInterface
{
    use DatabaseTableTrait;
    use ExpiringStoreTrait;

    private \PDO $conn;
    private string $dsn;
    private string $driver;
    private string $username = '';
    private string $password = '';
    private array $connectionOptions = [];

    /**
     * You can either pass an existing database connection as PDO instance
     * or a DSN string that will be used to lazy-connect to the database
     * when the lock is actually used.
     *
     * List of available options:
     *  * db_table: The name of the table [default: lock_keys]
     *  * db_id_col: The column where to store the lock key [default: key_id]
     *  * db_token_col: The column where to store the lock token [default: key_token]
     *  * db_expiration_col: The column where to store the expiration [default: key_expiration]
     *  * db_username: The username when lazy-connect [default: '']
     *  * db_password: The password when lazy-connect [default: '']
     *  * db_connection_options: An array of driver-specific connection options [default: []]
     *
     * @param array $options       An associative array of options
     * @param float $gcProbability Probability expressed as floating number between 0 and 1 to clean old locks
     * @param int   $initialTtl    The expiration delay of locks in seconds
     *
     * @throws InvalidArgumentException When first argument is not PDO nor Connection nor string
     * @throws InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
     * @throws InvalidArgumentException When the initial ttl is not valid
     */
    public function __construct(\PDO|string $connOrDsn, array $options = [], float $gcProbability = 0.01, int $initialTtl = 300)
    {
        $this->init($options, $gcProbability, $initialTtl);

        if ($connOrDsn instanceof \PDO) {
            if (\PDO::ERRMODE_EXCEPTION !== $connOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
                throw new InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)).', __METHOD__));
            }

            $this->conn = $connOrDsn;
        } else {
            $this->dsn = $connOrDsn;
        }

        $this->username = $options['db_username'] ?? $this->username;
        $this->password = $options['db_password'] ?? $this->password;
        $this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions;
    }

    /**
     * {@inheritdoc}
     */
    public function save(Key $key)
    {
        $key->reduceLifetime($this->initialTtl);

        $sql = "INSERT INTO $this->table ($this->idCol, $this->tokenCol, $this->expirationCol) VALUES (:id, :token, {$this->getCurrentTimestampStatement()} + $this->initialTtl)";
        $conn = $this->getConnection();
        try {
            $stmt = $conn->prepare($sql);
        } catch (\PDOException) {
            if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
                $this->createTable();
            }
            $stmt = $conn->prepare($sql);
        }

        $stmt->bindValue(':id', $this->getHashedKey($key));
        $stmt->bindValue(':token', $this->getUniqueToken($key));

        try {
            $stmt->execute();
        } catch (\PDOException) {
            // the lock is already acquired. It could be us. Let's try to put off.
            $this->putOffExpiration($key, $this->initialTtl);
        }

        $this->randomlyPrune();
        $this->checkNotExpired($key);
    }

    /**
     * {@inheritdoc}
     */
    public function putOffExpiration(Key $key, float $ttl)
    {
        if ($ttl < 1) {
            throw new InvalidTtlException(sprintf('"%s()" expects a TTL greater or equals to 1 second. Got "%s".', __METHOD__, $ttl));
        }

        $key->reduceLifetime($ttl);

        $sql = "UPDATE $this->table SET $this->expirationCol = {$this->getCurrentTimestampStatement()} + $ttl, $this->tokenCol = :token1 WHERE $this->idCol = :id AND ($this->tokenCol = :token2 OR $this->expirationCol <= {$this->getCurrentTimestampStatement()})";
        $stmt = $this->getConnection()->prepare($sql);

        $uniqueToken = $this->getUniqueToken($key);
        $stmt->bindValue(':id', $this->getHashedKey($key));
        $stmt->bindValue(':token1', $uniqueToken);
        $stmt->bindValue(':token2', $uniqueToken);
        $result = $stmt->execute();

        // If this method is called twice in the same second, the row wouldn't be updated. We have to call exists to know if we are the owner
        if (!(\is_object($result) ? $result : $stmt)->rowCount() && !$this->exists($key)) {
            throw new LockConflictedException();
        }

        $this->checkNotExpired($key);
    }

    /**
     * {@inheritdoc}
     */
    public function delete(Key $key)
    {
        $sql = "DELETE FROM $this->table WHERE $this->idCol = :id AND $this->tokenCol = :token";
        $stmt = $this->getConnection()->prepare($sql);

        $stmt->bindValue(':id', $this->getHashedKey($key));
        $stmt->bindValue(':token', $this->getUniqueToken($key));
        $stmt->execute();
    }

    /**
     * {@inheritdoc}
     */
    public function exists(Key $key): bool
    {
        $sql = "SELECT 1 FROM $this->table WHERE $this->idCol = :id AND $this->tokenCol = :token AND $this->expirationCol > {$this->getCurrentTimestampStatement()}";
        $stmt = $this->getConnection()->prepare($sql);

        $stmt->bindValue(':id', $this->getHashedKey($key));
        $stmt->bindValue(':token', $this->getUniqueToken($key));
        $result = $stmt->execute();

        return (bool) (\is_object($result) ? $result->fetchOne() : $stmt->fetchColumn());
    }

    private function getConnection(): \PDO
    {
        if (!isset($this->conn)) {
            $this->conn = new \PDO($this->dsn, $this->username, $this->password, $this->connectionOptions);
            $this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        }

        return $this->conn;
    }

    /**
     * Creates the table to store lock keys which can be called once for setup.
     *
     * @throws \PDOException    When the table already exists
     * @throws \DomainException When an unsupported PDO driver is used
     */
    public function createTable(): void
    {
        // connect if we are not yet
        $conn = $this->getConnection();
        $driver = $this->getDriver();

        $sql = match ($driver) {
            'mysql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(44) NOT NULL, $this->expirationCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB",
            'sqlite' => "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->tokenCol TEXT NOT NULL, $this->expirationCol INTEGER)",
            'pgsql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(64) NOT NULL, $this->expirationCol INTEGER)",
            'oci' => "CREATE TABLE $this->table ($this->idCol VARCHAR2(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR2(64) NOT NULL, $this->expirationCol INTEGER)",
            'sqlsrv' => "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(64) NOT NULL, $this->expirationCol INTEGER)",
            default => throw new \DomainException(sprintf('Creating the lock table is currently not implemented for platform "%s".', $driver)),
        };

        $conn->exec($sql);
    }

    /**
     * Cleans up the table by removing all expired locks.
     */
    private function prune(): void
    {
        $sql = "DELETE FROM $this->table WHERE $this->expirationCol <= {$this->getCurrentTimestampStatement()}";

        $this->getConnection()->exec($sql);
    }

    private function getDriver(): string
    {
        if (isset($this->driver)) {
            return $this->driver;
        }

        $conn = $this->getConnection();
        $this->driver = $conn->getAttribute(\PDO::ATTR_DRIVER_NAME);

        return $this->driver;
    }

    /**
     * Provides an SQL function to get the current timestamp regarding the current connection's driver.
     */
    private function getCurrentTimestampStatement(): string
    {
        return match ($this->getDriver()) {
            'mysql' => 'UNIX_TIMESTAMP()',
            'sqlite' => 'strftime(\'%s\',\'now\')',
            'pgsql' => 'CAST(EXTRACT(epoch FROM NOW()) AS INT)',
            'oci' => '(SYSDATE - TO_DATE(\'19700101\',\'yyyymmdd\'))*86400 - TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone), 1, 3))*3600',
            'sqlsrv' => 'DATEDIFF(s, \'1970-01-01\', GETUTCDATE())',
            default => (string) time(),
        };
    }
}