text:
The `doc` directory contains the source files of the documentation of plotly.py.
It is composed of two parts:

- inside the [`python/` directory](python), tutorials corresponding to https://plot.ly/python/
- inside the [`apidoc/` directory](apidoc), configuration files for generating
  the API reference documentation (hosted on https://plot.ly/python-api-reference/)

Python packages required to build the doc are listed in
[`requirements.txt`](requirements.txt) in the `doc` directory.

## Tutorials (`python` directory)

Each tutorial is a markdown (`.md`) file, which can be opened in the Jupyter
notebook or in Jupyterlab by installing [jupytext](https://jupytext.readthedocs.io/en/latest/install.html).

For small edits (e.g., correcting typos) to an existing tutorial, you can simply click on the "edit this
page on Github" link at the top right of the page (e.g. clicking on this link
on https://plot.ly/python/bar-charts/ will take you to
https://github.com/plotly/plotly.py/edit/doc-prod/doc/python/bar-charts.md,
where you can edit the page on Github).

For more important edits where you need to run the notebook to check the output,
clone the repository and setup an environment as described in the [main
contributing notes](../contributing.md). If you're writing documentation at the
same time as you are developing a feature, make sure to install with editable
install (`pip install -e`, as described in [main
contributing notes](../contributing.md)), so that you only need to restart
the Jupyter kernel when you have changed the source code of the feature.

### Branches

Two different cases exist, whether you are documenting a feature already
released, or which has just been included but not yet released.

- Case of an already released feature: your changes can be deployed to the
  documentation website as soon as they have been merged, and you should start
  your branch off the `doc-prod` branch and open your pull request against this
  `doc-prod` branch.
- Case of a new (not released yet) feature: start your branch / pull request
  against the `master` branch. `master` and `doc-prod` will be synchronized at
  release time, so that the documentation of the feature is only deployed when
  it is available in a released version of `plotly.py`.

### Guidelines

We try to write short, standalone and (almost) self-explaining examples. Most
examples should focus on a single feature.

Checklist

- Each example should have a clear title (titles are used for the navigation
  bar and indexed by search engines)
- Package imports should be called in the same cell as the example, so that it
  is possible to copy-paste a single cell to reproduce the example.
- Variable names should be consistent with other examples, for example use
  `fig` for a `Figure` object, `df` for a pandas dataframe, etc.
- Examples should not be too long to execute (typically < 10s), since the doc is
  built as part of the continuous integration (CI) process. Examples taking
  longer to execute should be discussed in a new issue to decide whether they
  can be accepted.

### Build process

This build process requries a free personal public mapbox token to work.

First, create an account at https://account.mapbox.com/auth/signup Once that is done, navigate to https://account.mapbox.com/ and copy your "Default public token" to the file `doc/python/.mapbox_token`

Next, run `make` to build html pages for the tutorials. This uses `jupytext` to
execute the notebooks and `nbconvert` to convert notebook files to static html
pages. Note that the CI will build the doc, so you don't have to build it
yourself, it is enough to check that the markdown file runs correctly in
Jupyter.

The output of the `Makefile` is stored by CI in the `built` branch of the `plotly.py-docs` repo which is then used by the `documentation` repo to generate https://plot.ly/python.

## API reference documentation (`apidoc` directory)

We use [sphinx](http://www.sphinx-doc.org/en/master/) and its [`autodoc`
extension](http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html)
in order to generate the documentation of the API. Sphinx uses the [reST markup
language](https://www.sphinx-doc.org/en/2.0/usage/restructuredtext/basics.html).

Run `make html` inside `apidoc` to build the API doc in the `_build/html`
directory.

Lists of objects to be documented are found in files corresponding to
submodules, such as [`plotly.express.rst`](plotly.express.rst). When a new
object is added to the exposed API, it needs to be added to the corresponding
file to appear in the API doc.

Other files

- `css` files are found in `_static`
- Template files are found in `_templates`. `.rst` templates describe how the
  autodoc of the different objects should look like.


text:
		Dashboard reports & statistics

					<a target="_self" href="<?=$site_url?>/main/mainrac">Home

					Risk List

					<button type="button" class="btn btn-fit-height blue dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="true">
					Export
					</button>

							Export

					Risk To Verify

					Risk Register To Verify

					Treatment To Verify

					Action Plan To Verify

					KRI To Verify

					Change Request To Verify

		<input type = "hidden" id = "tabactive" name ="tabactive" value = "0">

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Risk List Export - choose field to export

				<form id = "get_check_risklist">

						Status <input type = "checkbox" checked="true"  name = "risk_status">
						Risk ID <input type = "checkbox" checked="true"  name = "risk_code" >
						Risk Event <input type = "checkbox" checked="true"  name = "risk_event" >
						Impact Level <input type = "checkbox" checked="true"  name = "risk_level_v" >
						Likelihood <input type = "checkbox" checked="true"  name = "impact_level_v" >
						Risk Level <input type = "checkbox" checked="true"  name = "likelihood_v" >
						Risk Owner <input type = "checkbox" checked="true"  name = "risk_owner_v" >

				</form>

				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button class = "btn btn-success" id = "risk_list_excel">Export to Excel</button>
				<button class = "btn btn-success" id = "risk_list_pdf" >Export to PDF</button>

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Risk Register List Export - choose field to export

				<form id = "get_check_riskregisterlist">

						Status <input type = "checkbox" checked="true"  name = "risk_status" >
						User <input type = "checkbox" checked="true"  name = "display_name"  >
						Divisi<input type = "checkbox" checked="true"  name = "division_name"  >
						Submited<input type = "checkbox" checked="true"  name = "tanggal_submit"  >

				</form>

				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button class = "btn btn-success" id = "risk_register_list_excel">Export to Excel</button>
				<button class = "btn btn-success" id = "risk_register_list_pdf" >Export to PDF</button>

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Treatment List Export - choose field to export

				<form id = "get_check_risktreatment">

						Status <input type = "checkbox" checked="true"  name = "risk_status" >
						Risk ID <input type = "checkbox" checked="true"  name = "risk_code"  >
						Risk Event<input type = "checkbox" checked="true"  name = "risk_event"  >
						Risk Owner<input type = "checkbox" checked="true"  name = "risk_owner_v"  >
						Risk Treatment<input type = "checkbox" checked="true"  name = "suggested_risk_treatment_v"  >

				</form>

				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button class = "btn btn-success" id = "treatment_list_excel">Export to Excel</button>
				<button class = "btn btn-success" id = "treatment_list_pdf" >Export to PDF</button>

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Action Plan List Export - choose field to export

				<form id = "get_check_actionplan">

						Status <input type = "checkbox" checked="true"  name = "action_plan_status" >
						AP ID <input type = "checkbox" checked="true"  name = "act_code"  >
						Action Plan<input type = "checkbox" checked="true"  name = "action_plan"  >
						Due Date<input type = "checkbox" checked="true"  name = "due_date_v"  >
						Action Plan Owner<input type = "checkbox" checked="true"  name = "division_name"  >
						Risk ID<input type = "checkbox" checked="true"  name = "risk_code"  >

				</form>

				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button class = "btn btn-success" id = "actionplan_list_excel">Export to Excel</button>
				<button class = "btn btn-success" id = "actionplan_list_pdf" >Export to PDF</button>

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Action Plan Execution List Export - choose field to export

				<form id = "get_check_execution">

						Status <input type = "checkbox" checked="true"  name = "action_plan_status" >
						AP ID <input type = "checkbox" checked="true"  name = "act_code"  >
						Action Plan<input type = "checkbox" checked="true"  name = "action_plan"  >
						Due Date<input type = "checkbox" checked="true"  name = "due_date_v"  >
						Action Plan Owner<input type = "checkbox" checked="true"  name = "division_name"  >
						Execution<input type = "checkbox" checked="true"  name = "execution_status"  >

				</form>

				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button class = "btn btn-success" id = "execution_list_excel">Export to Excel</button>
				<button class = "btn btn-success" id = "execution_list_pdf" >Export to PDF</button>

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

KRI List Export - choose field to export

				<form id = "get_check_kri">

						Status <input type = "checkbox" checked="true"  name = "kri_status" >
						KRI ID <input type = "checkbox" checked="true"  name = "kri_code"  >
						KRI<input type = "checkbox" checked="true"  name = "key_risk_indicator"  >
						KRI Owner<input type = "checkbox" checked="true"  name = "treshold"  >
						Timing Pelaporan<input type = "checkbox" checked="true"  name = "timing_pelaporan_v"  >
						Risk ID<input type = "checkbox" checked="true"  name = "risk_code"  >
						KRI Warning<input type = "checkbox" checked="true"  name = "kri_warning"  >

				</form>

				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button class = "btn btn-success" id = "kri_list_excel">Export to Excel</button>
				<button class = "btn btn-success" id = "kri_list_pdf" >Export to PDF</button>

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Change Request List Export - choose field to export

				<form id = "get_check_changereq">

						Status <input type = "checkbox" checked="true"  name = "GenRowNum" >
						ID CH<input type = "checkbox" checked="true"  name = "cr_code"  >
						Change In<input type = "checkbox" checked="true"  name = "cr_type"  >
						Requestor<input type = "checkbox" checked="true"  name = "created_by_v"  >
						Status Change Request<input type = "checkbox" checked="true"  name = "cr_status"  >

				</form>

				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button class = "btn btn-success" id = "changereq_list_excel">Export to Excel</button>
				<button class = "btn btn-success" id = "changereq_list_pdf" >Export to PDF</button>

					Risk List

					<?php
					if($cekrisklist > 0){
					echo "($cekrisklist)";
					}
					?>

					Risk Register List

					Treatment List

					<?php
					if($treatmentlist > 0){
					echo "($treatmentlist)";
					}
					?>

					Action Plan List

					<?php
					if($cekplan > 0){
					echo "($cekplan)";
					}
					?>

					Action Plan Execution

					<?php
					if($cekplanExec > 0){
					echo "($cekplanExec)";
					}
					?>

					KRI List

					<?php
					if($cekkrirac > 0){
					echo "($cekkrirac)";
					}
					?>

					Change Request List

					<?php
					if($cekChangeRequest > 0){
					echo "($cekChangeRequest)";
					}
					?>

					<form class="form-inline" role="form" style="margin-bottom: 10px;" id="form_tab_risk_list" >

							Filter By :
							<select class="form-control input-medium input-sm" id="tab_risk_list-filterBy">
								<option value="risk_event">Risk Event</option>
								<option value="risk_level">Risk Level</option>
								<option value="risk_impact_level">Impact Level</option>
								<option value="risk_likelihood_key">Likelihood</option>
								<option value="risk_owner">Risk Owner</option>
							</select>

							<input type="text" class="form-control input-sm" placeholder="Insert Filter Value" id="tab_risk_list-filterValue">

						<button type="submit" class="btn blue btn-sm" id="tab_risk_list-filterButton">Search</button>
					</form>

							Status
							Risk ID
							Risk Event
							Risk Level
							Impact Level
							Likelihood
							Risk Owner

Legend

								<img src="<?=$base_url?>assets/images/legend/draft.png"/>
								 Draft

								<img src="<?=$base_url?>assets/images/legend/submit.png"/>
								 submitted to rac

								<img src="<?=$base_url?>assets/images/legend/verified.png"/>
								 Verified By RAC

								<img src="<?=$base_url?>assets/images/legend/treatment.png"/>
								 on Risk Treatment Process

								<img src="<?=$base_url?>assets/images/legend/actplan.png"/>
								 on Action Plan Process

								<img src="<?=$base_url?>assets/images/legend/executed_2.png"/>
								 On Action Plan Execution Process

								<img src="<?=$base_url?>assets/images/legend/executed.png"/>
								 Action Plan Has Been Executed and Verified

					<form class="form-inline" role="form" style="margin-bottom: 10px;" id="form_tab_risk_register_list">

							Filter By :
							<select class="form-control input-medium input-sm" id="tab_risk_register_list-filterBy">
								<option value="display_name">User Name</option>
								<option value="division_name">Division</option>
							</select>

							<input type="text" class="form-control input-sm" placeholder="Insert Filter Value" id="tab_risk_register_list-filterValue">

						<button type="button" class="btn blue btn-sm" id="tab_risk_register_list-filterButton">Search</button>
					</form>

							Status
							User
							Divisi
							Submission Date
							Note

Legend

								<img src="<?=$base_url?>assets/images/legend/draft.png"/>
								 Draft

								<img src="<?=$base_url?>assets/images/legend/submit.png"/>
								 submitted to rac

								<img src="<?=$base_url?>assets/images/legend/verified.png"/>
								 Verified By RAC

					<form class="form-inline" role="form" style="margin-bottom: 10px;" id="form_tab_treatment_list">

							Filter By :
							<select class="form-control input-medium input-sm" id="tab_treatment_list-filterBy">
								<option value="risk_event">Risk Event</option>
								<option value="risk_owner">Risk Owner</option>
								<option value="suggested_risk_treatment">Risk Treatment</option>
							</select>

							<input type="text" class="form-control input-sm" placeholder="Insert Filter Value" id="tab_treatment_list-filterValue">

						<button type="button" class="btn blue btn-sm" id="tab_treatment_list-filterButton">Search</button>
					</form>

							Status
							Risk ID
							Risk Event
							Risk Owner
							Risk Treatment

Legend

								<img src="<?=$base_url?>assets/images/legend/draft.png"/>
								 Draft

								<img src="<?=$base_url?>assets/images/legend/submit.png"/>
								 submitted to rac

								<img src="<?=$base_url?>assets/images/legend/verified.png"/>
								 Verified By RAC

					<form class="form-inline" role="form" style="margin-bottom: 10px;" id="form_tab_action_plan_list">

							Filter By :
							<select class="form-control input-medium input-sm" id="tab_action_plan_list-filterBy">
								<option value="action_plan">Action Plan</option>
								<option value="due_date">Due Date</option>
								<option value="division_name">Action Plan Owner</option>
							</select>

							<input type="text" class="form-control input-sm" placeholder="Insert Filter Value" id="tab_action_plan_list-filterValue">

						<button type="button" class="btn blue btn-sm" id="tab_action_plan_list-filterButton">Search</button>
					</form>

							Status
							AP ID
							Action Plan
							Due Date
							Action Plan Owner
							Risk ID

Legend

								<img src="<?=$base_url?>assets/images/legend/draft.png"/>
								 Draft

								<img src="<?=$base_url?>assets/images/legend/submit.png"/>
								 submitted to rac

								<img src="<?=$base_url?>assets/images/legend/verified.png"/>
								 Verified By RAC

							Status
							KRI ID
							KRI
							KRI Owner
							Timing Pelaporan
							Risk ID
							KRI Warning

Legend

								<img src="<?=$base_url?>assets/images/legend/draft.png"/>
								 Draft

								<img src="<?=$base_url?>assets/images/legend/submit.png"/>
								 submitted to rac

								<img src="<?=$base_url?>assets/images/legend/verified.png"/>
								 Verified By RAC

							No
							ID CH
							Changes In
							Requestor
							Status Change Request
							Date
							Action

					<form class="form-inline" role="form" style="margin-bottom: 10px;" id="form_tab_action_plan_exec">

							Filter By :
							<select class="form-control input-medium input-sm" id="tab_action_plan_exec-filterBy">
								<option value="action_plan">Action Plan</option>
								<option value="due_date">Due Date</option>
								<option value="division_name">Action Plan Owner</option>
								<option value="execution_status">Execution</option>
							</select>

							<input type="text" class="form-control input-sm" placeholder="Insert Filter Value" id="tab_action_plan_exec-filterValue">

						<button type="button" class="btn blue btn-sm" id="tab_action_plan_exec-filterButton">Search</button>
					</form>

							Status
							AP ID
							Action Plan
							Due Date
							Action Plan Owner
							Execution
							Risk ID

Legend

								<img src="<?=$base_url?>assets/images/legend/draft.png"/>
								 Draft

								<img src="<?=$base_url?>assets/images/legend/submit.png"/>
								 submitted to rac

								<img src="<?=$base_url?>assets/images/legend/verified.png"/>
								 Verified By RAC

		<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Edit Note

		<form id="noteform" role="form" class="form-horizontal" action ="<?=base_url('index.php/main/mainrac/submit_note');?>" method="POST">
			<textarea name = "note" id = "modal_pic_note" class="form-control"></textarea>
			<input type = "hidden" id = "modal_pic_risk_input_by" name = "risk_input_by">
			<button type="button" class="btn blue btn-sm" onclick = "submit_note()">Save</button>
		</form>

		<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Action Plan Execution

		<form id="exec-form" role="form" class="form-horizontal">
		<input type="hidden" id="form-action-id" name="action_id" value="" />

					Status

					<select class="form-control input-sm" name="execution_status" id="exec-select-status">
						<option value="COMPLETE" selected>Complete</option>
						<option value="EXTEND">Extend</option>
						<option value="ONGOING">On Going</option>
					</select>

					Explanation*

					<textarea class="form-control" rows="3" name="execution_explain" placeholder=""></textarea>

					Evidence

					<textarea class="form-control" rows="3" name="execution_evidence" placeholder=""></textarea>

					Reason*

					<textarea class="form-control" rows="3" name="execution_reason" placeholder=""></textarea>

					Revised Date*

						<input type="text" class="form-control input-sm" name="revised_date" readonly value="<?=date('d-m-Y')?>">

						<button class="btn default btn-sm" type="button"></button>

				<button id="exec-button-save" type="button" class="btn blue"> Save </button>
				<button type="button" data-dismiss="modal" class="btn btn-default">Cancel</button>

		</form>

redpajama_set_name: RedPajamaGithub


text:
namespace chromeos {

FakeImageBurnerClient::FakeImageBurnerClient() = default;

FakeImageBurnerClient::~FakeImageBurnerClient() = default;

void FakeImageBurnerClient::Init(dbus::Bus* bus) {}

void FakeImageBurnerClient::ResetEventHandlers() {}

void FakeImageBurnerClient::BurnImage(const std::string& from_path,
                                      const std::string& to_path,
                                      ErrorCallback error_callback) {}

void FakeImageBurnerClient::SetEventHandlers(
    BurnFinishedHandler burn_finished_handler,
    const BurnProgressUpdateHandler& burn_progress_update_handler) {}

}  // namespace chromeos


text:
#include "Version.h"
#include <stdio.h>

SMuxVersion getVersion()
{
   SMuxVersion version;
   version.major = VER_MAJOR;
   version.minor = VER_MINOR;
   version.release = VER_PATCH;
   version.build = VER_BUILD;

   return version;
}

const char* getVersionString()
{
   static char version[64];
   SMuxVersion v = getVersion();
#ifdef _WIN32
   _snprintf_s(version, sizeof(version), "Serial Mux v%d.%d.%d (build %d)",
               v.major, v.minor, v.release, v.build);
#else
   snprintf(version, sizeof(version), "Serial Mux v%d.%d.%d (build %d)",
            v.major, v.minor, v.release, v.build);
#endif
   return version;
}


text:
package com.amb;

import com.amb.bus.BusAmenity;
import com.amb.bus.BusOrder;
import com.amb.bus.BusOrderItem;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.deser.ValueInstantiator;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.javamoney.moneta.Money;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.rest.webmvc.json.JsonSchema.JsonSchemaProperty;
import org.springframework.data.rest.webmvc.json.JsonSchemaPropertyCustomizer;
import org.springframework.data.util.TypeInformation;

import javax.money.MonetaryAmount;
import javax.money.format.MonetaryFormats;
import java.io.IOException;
import java.util.Collection;
import java.util.regex.Pattern;

/**
 * Configures custom serialization and deserialization of {@link Money} instances
 *
 * @author Oliver Gierke
 */
@Configuration
class JacksonCustomizations {

	public @Bean Module moneyModule() {
		return new MoneyModule();
	}

	public @Bean Module ambModule() {
		return new AmbModule();
	}

	@SuppressWarnings("serial")
	static class AmbModule extends SimpleModule {

		public AmbModule() {

			setMixInAnnotation(BusOrder.class, AmbModule.OrderMixin.class);
//			setMixInAnnotation(LineItem.class, LineItemMixin.class);
//			setMixInAnnotation(CreditCard.class, CreditCardMixin.class);
		}

		@JsonAutoDetect(isGetterVisibility = JsonAutoDetect.Visibility.NONE)
		static abstract class OrderMixin {

			@JsonCreator
			public OrderMixin(Collection<BusOrderItem> lineItems) {}
		}

//		@JsonAutoDetect(isGetterVisibility = JsonAutoDetect.Visibility.NONE)
//		static abstract class CreditCardMixin {
//
//			abstract @JsonUnwrapped CreditCardNumber getNumber();
//		}
//
//		@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
//		static abstract class CreditCardNumberMixin {}

	}

	@SuppressWarnings("serial")
	static class MoneyModule extends SimpleModule {

		public MoneyModule() {

			addSerializer(MonetaryAmount.class, new MonetaryAmountSerializer());
			addValueInstantiator(MonetaryAmount.class, new MoneyInstantiator());
		}

		/**
		 * A dedicated serializer to render {@link MonetaryAmount} instances as formatted {@link String}. Also implements
		 * {@link JsonSchemaPropertyCustomizer} to expose the different rendering to the schema exposed by Spring Data REST.
		 *
		 * @author Oliver Gierke
		 */
		static class MonetaryAmountSerializer extends StdSerializer<MonetaryAmount>
				implements JsonSchemaPropertyCustomizer {

			private static final Pattern MONEY_PATTERN;

			static {

				StringBuilder builder = new StringBuilder();

				builder.append("(?=.)^"); // Start
				builder.append("[A-Z]{3}?"); // 3-digit currency code
				builder.append("\\s"); // single whitespace character
				builder.append("(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?"); // digits with optional grouping by "," every 3)
				builder.append("(\\.[0-9]{1,2})?$"); // End with a dot and two digits

				MONEY_PATTERN = Pattern.compile(builder.toString());
			}

			public MonetaryAmountSerializer() {
				super(MonetaryAmount.class);
			}

			/*
			 * (non-Javadoc)
			 * @see com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
			 */
			@Override
			public void serialize(MonetaryAmount value, JsonGenerator jgen, SerializerProvider provider) throws IOException {

				if (value != null) {
					jgen.writeString(MonetaryFormats.getAmountFormat(LocaleContextHolder.getLocale()).format(value));
				} else {
					jgen.writeNull();
				}
			}

			/*
			 * (non-Javadoc)
			 * @see org.springframework.data.rest.webmvc.json.JsonSchemaPropertyCustomizer#customize(org.springframework.data.rest.webmvc.json.JsonSchema.JsonSchemaProperty, org.springframework.data.util.TypeInformation)
			 */
			@Override
			public JsonSchemaProperty customize(JsonSchemaProperty property, TypeInformation<?> type) {
				return property.withType(String.class).withPattern(MONEY_PATTERN);
			}
		}

		static class MoneyInstantiator extends ValueInstantiator {

			/*
			 * (non-Javadoc)
			 * @see com.fasterxml.jackson.databind.deser.ValueInstantiator#getValueTypeDesc()
			 */
			@Override
			public String getValueTypeDesc() {
				return MonetaryAmount.class.toString();
			}

			/*
			 * (non-Javadoc)
			 * @see com.fasterxml.jackson.databind.deser.ValueInstantiator#canCreateFromString()
			 */
			@Override
			public boolean canCreateFromString() {
				return true;
			}

			/*
			 * (non-Javadoc)
			 * @see com.fasterxml.jackson.databind.deser.ValueInstantiator#createFromString(com.fasterxml.jackson.databind.DeserializationContext, java.lang.String)
			 */
			@Override
			public Object createFromString(DeserializationContext context, String value) throws IOException {
				return Money.parse(value, MonetaryFormats.getAmountFormat(LocaleContextHolder.getLocale()));
			}
		}
	}
}


text:
<?php

include_once __DIR__ . '/../vendor/autoload.php';

if (!isset($addonId))
{
	$sitesDir    = __DIR__ . '/../vendor/s9e/text-formatter/src/Plugins/MediaEmbed/Configurator/sites';
	$classFile   = __DIR__ . '/../build/upload/library/s9e/MediaBBCodes.php';
	$addonFile   = __DIR__ . '/../build/addon-s9e.xml';
	$addonId     = 's9e';
	$namespace   = 's9e';
	$className   = 's9e_MediaBBCodes';
	$addonTitle  = 's9e Media Pack';
	$addonUrl    = 'https://xenforo.com/community/resources/s9e-media-bbcodes-pack.2476/';
	$linkText    = 'Media embeds by s9e';
	$tagsDescUrl = 'http://s9e.github.io/XenForoMediaBBCodes/tags.html';
	$githubUrl   = 'https://github.com/s9e/XenForoMediaBBCodes/blob/master/docs/';
}

// The version is simply the current UTC day, optionally followed by the first argument given to
// this script
$version   = gmdate('Ymd');
$versionId = $version * 10;
if (isset($_SERVER['argv'][1]))
{
	$version   .= $_SERVER['argv'][1];
	$versionId += ($_SERVER['argv'][1] === '-dev') ? -1 : (ord($_SERVER['argv'][1]) - 97);
}

// Set up the MediaEmbed plugin
$configurator = new s9e\TextFormatter\Configurator;
$configurator->rendering->engine = 'PHP';
$configurator->rendering->engine->enableQuickRenderer = false;
$configurator->rendering->engine->forceEmptyElements  = false;
$configurator->rendering->engine->useEmptyElements    = false;
$configurator->rendering->engine->serializer->branchTableThreshold = PHP_INT_MAX;
$configurator->MediaEmbed->sitesDir = $sitesDir;

// Load the PHP file and remove the renderers
$php = file_get_contents($classFile);
$php = preg_replace('((.*?)(?:\\s*public static function render.*)?\\}$)s', '$1', $php);

// Redefine the constants here
preg_match_all('(^\\s*const\\s+.*)m', $php, $m);
eval(implode('', $m[0]));

function setAttributes(DOMElement $element, array $attributes)
{
	foreach ($attributes as $attrName => $attrValue)
	{
		$element->setAttribute($attrName, $attrValue);
	}
}

function exportSites(array $sites)
{
	$php = 'array(';
	foreach ($sites as $siteId => $site)
	{
		$php .= "\n\t\t" . var_export($siteId, true) . '=>' . exportConfig($site) . ',';
	}
	$php = substr($php, 0, -1) . "\n\t)";

	return $php;
}

function exportConfig(array $config)
{
	ksort($config);

	// Remove null values at the end of the config
	while (end($config) === null)
	{
		array_pop($config);
	}

	$i = 0;
	$elements = [];
	foreach ($config as $k => $v)
	{
		$php = ($k === $i++) ? '' : var_export($k, true) . '=>';

		if (is_array($v))
		{
			$php .= exportConfig($v);
		}
		elseif (is_null($v))
		{
			// var_export() exports null values as "NULL" in uppercase and uppercase sucks
			$php .= 'null';
		}
		elseif (strpos($v, "\n") !== false)
		{
			$php .= '"' . addcslashes($v, "\\\"\n") . '"';
		}
		else
		{
			$php .= var_export($v, true);
		}

		$elements[] = $php;
	}

	return 'array(' . implode(',', $elements) . ')';
}

// Create the XML document
$dom = new DOMDocument('1.0', 'utf-8');
$addon = $dom->appendChild($dom->createElement('addon'));
$addon->appendChild($dom->createElement('bb_code_media_sites'));

// Set the add-on informations
setAttributes(
	$addon,
	[
		'addon_id'                  => $addonId,
		'title'                     => $addonTitle,
		'url'                       => $addonUrl,
		'version_id'                => $versionId,
		'version_string'            => $version,
		'install_callback_class'    => $className,
		'install_callback_method'   => 'install',
		'uninstall_callback_class'  => $className,
		'uninstall_callback_method' => 'uninstall'
	]
);

$sites       = [];
$sitenames   = [];
$optionNames = [];
$php         = [$php];

foreach (glob($sitesDir . '/*.xml') as $siteFile)
{
	$site   = simplexml_load_file($siteFile);
	$siteId = basename($siteFile, '.xml');

	$configurator->tags->clear();
	$template = (string) $configurator->MediaEmbed->add($siteId)->template;
	$template = preg_replace('( data-s9e-livepreview-[-\\w]+=".*?")', '', $template);

	$config = array(
		KEY_HTML  => null,
		KEY_TAGS  => array(),
		KEY_TITLE => (string) $site['name'],
		KEY_URL   => (string) $site['homepage']
	);

	if (isset($site->tags->tag))
	{
		foreach ($site->tags->tag as $tag)
		{
			$config[KEY_TAGS][(string) $tag] = 1;
		}
	}
	else
	{
		// Untagged sites go into the "misc" category
		$config[KEY_TAGS]['misc'] = 1;
	}

	// Default HTML replacement. Ensure that iframe and script have an end tag
	$html = preg_replace('#(<(iframe|script)[^>]+)/>#', '$1></$2>', $template);

	$useEmbedCallback = false;

	// Test whether the template needs to be rendered in PHP. Some sites don't like URL-encoding so
	// we force them to be rendered in PHP regardless of the template. XenForo encodes ":" to %3A
	// which Comedy Central's servers don't like
	if (strpos($html, '<xsl:') !== false
	 || preg_match('(="[^"]*(?<!\\{)\\{(?!\\{|@id\\}))', $html)
	 || strpos($html, 'media.mtvnservices.com') !== false
	 || $siteId === 'cnn'
	 || $siteId === 'gist'
	 || $siteId === 'imgur'
	 || $siteId === 'mailru'
	 || $siteId === 'telegram'
	 || $siteId === 'theguardian')
	{
		// Capture the PHP source for this template
		$regexp = '(switch\\(\\$node->nodeName\\)\\{[^:]+:(.*?)break;case\'br\')s';

		$configurator->rendering->getRenderer();
		$source = file_get_contents($configurator->rendering->engine->lastFilepath);
		if (!preg_match($regexp, $source, $m))
		{
			die('Could not match ' . $site['name'] . " renderer\n");
		}

		$src = "\$html='';" . $m[1];
		$src = str_replace("\$html='';\$this->out.=", '$html=', $src);
		$src = preg_replace("#\\\$node->hasAttribute\\(('[^']+')\\)#", 'isset($vars[$1])', $src);
		$src = preg_replace("#\\\$node->getAttribute\\(('[^']+')\\)#", '$vars[$1]', $src);
		$src = str_replace('$this->out', '$html', $src);

		// Replace the template params
		$src = preg_replace_callback(
			"#\\\$this->params\\['([^']+)'\\]#",
			function ($m) use ($addon, &$optionNames)
			{
				$paramName  = $m[1];
				$optionName = $addon->getAttribute('addon_id') . '_' . $m[1];

				$optionNames[$paramName] = $optionName;

				return "XenForo_Application::get('options')->" . $optionName;
			},
			$src
		);

		if (preg_match("((?<!XenForo_Application::get\\('options'\\))->)", $src))
		{
			echo "$src\n";
			echo 'Cannot convert ', $site['name'], " (->)\n";
			die(1);
		}

		// Collect the name of all vars in use to initialize them with a null value
		$vars = [];
		preg_match_all('(@(\\w+))', $template, $matches);
		foreach ($matches[1] as $varName)
		{
			$defaultValue = 'null';
			if (isset($site->attributes->$varName))
			{
				$attribute = $site->attributes->$varName;
				if (isset($attribute['defaultValue']))
				{
					$defaultValue = $attribute['defaultValue'];
				}
			}
			$vars[$varName] = var_export($varName, true) . ' => ' . $defaultValue;
		}
		ksort($vars);

		$php[] = '';
		$php[] = '	public static function render' . ucfirst($siteId) . '($vars)';
		$php[] = '	{';

		if (!empty($vars))
		{
			$php[] = '		$vars += array(' . implode(', ', $vars) . ');';
			$php[] = '';
		}

		$php[] = '		' . $src;
		$php[] = '';
		$php[] = '		return $html;';
		$php[] = '	}';
	}
	else
	{
		// Replace XSL attributes with XenForo's syntax and unescape brackets
		$config[KEY_HTML] = strtr($html, ['{@' => '{$', '{{' => '{', '}}' => '}']);
	}

	$regexps          = [];
	$extractRegexps   = [];
	$useMatchCallback = false;

	// Collect this site's hosts and build a regexp that matches all of them
	$hosts = [];
	foreach ($site->host as $host)
	{
		$hosts[] = (string) $host;
	}
	$hostsRegexp = s9e\TextFormatter\Configurator\Helpers\RegexpBuilder::fromList($hosts);

	foreach ($site->extract as $regexp)
	{
		$regexp = (string) $regexp;

		// Test whether it captures anything else than "id"
		if (preg_match("(\\(\\?['<](?!id))", $regexp))
		{
			$useMatchCallback = true;
		}

		$regexps[] = $regexp;
		$extractRegexps[$regexp] = $regexp;
	}

	foreach ($site->scrape as $scrape)
	{
		$entry = [];

		foreach ($scrape->match as $match)
		{
			$entry['match'][] = $regexps[] = (string) $match;
		}

		if (!isset($entry['match']))
		{
			$entry['match'] = ['//'];
		}

		foreach ($scrape->extract as $extract)
		{
			$entry['extract'][] = (string) $extract;
		}

		if (isset($scrape['url']))
		{
			$entry['url'] = (string) $scrape['url'];
		}

		$config[KEY_SCRAPES][] = $entry;
		$useMatchCallback = true;
	}

	if ($siteId === 'livestream')
	{
		$regexps = ['()'];
	}

	foreach ($regexps as $k => $regexp)
	{
		// Test whether this regexp contains the name of at least one host. If not, make it match
		// any of the host. (Spotify excluded)
		$matchHost = ($siteId != 'spotify');
		foreach ($hosts as $host)
		{
			if (strpos($regexp, preg_quote($host)) !== false)
			{
				$matchHost = false;
			}
		}

		if ($matchHost)
		{
			if (false === strpos($regexp, $hostsRegexp)
			 && false === strpos($regexp, str_replace('(?>', '(?:', $hostsRegexp)))
			{
				$regexps[$k] = $regexp[0] . '(?=.*?[./]' . $hostsRegexp . '[:/]).*?' . substr($regexp, 1);

				if (isset($extractRegexps[$regexp]))
				{
					$extractRegexps[$regexp] = $regexps[$k];
				}
			}
		}
	}

	if (isset($site->attributes))
	{
		$filters = array();
		foreach ($site->attributes->children() as $attribute)
		{
			if (isset($attribute['filterChain']))
			{
				$attrName = $attribute->getName();
				$callback = (string) $attribute['filterChain'];
				if ($callback[0] === '#')
				{
					$callback = $className . '::filter' . ucfirst(substr($callback, 1));
				}
				$filters[$attrName] = [$callback];
			}
		}

		if ($filters)
		{
			$config[KEY_FILTERS] = $filters;
			$useMatchCallback = true;
		}
	}

	if ($useMatchCallback)
	{
		$config[KEY_USE_MATCH_CALLBACK] = true;
	}

	// Test whether each regexp has a capture named "id". If not, add an empty capture named "id" to
	// satisfy XenForo's assumptions that every regexp contains one
	foreach ($regexps as &$regexp)
	{
		if (strpos($regexp, "(?'id'") === false)
		{
			$regexp = $regexp[0] . "(?'id')" . substr($regexp, 1);
		}
	}
	unset($regexp);

	$matchUrls = (empty($regexps)) ? "((?'id')" . $hostsRegexp . '/)' : implode("\n", $regexps);
	$config[KEY_MATCH_URLS] = $matchUrls;
	$config[KEY_EXTRACT_REGEXPS] = array_values($extractRegexps);

	// Record the name of the site
	$sitenames[] = (string) $site['name'];

	// Save the site's config
	$sites[$siteId] = $config;
}
$php[] = '}';

// Replace the sites config in the source
$php[0] = preg_replace_callback(
	'((?<=public static \\$sites = ).*?(?=;\\s*/\\*\\*))s',
	function () use ($sites)
	{
		$php = exportSites($sites);

		// Replace (?'id' with (?P<id>
		$php = preg_replace("(\\(\\?\\\\?'(\\w+)\\\\?')", '(?P<$1>', $php);

		return $php;
	},
	$php[0]
);

// Remove temp files
array_map('unlink', glob(sys_get_temp_dir() . '/Renderer_*'));

// Prepare the phrase group
$phrases = $addon->appendChild($dom->createElement('phrases'));

setAttributes(
	$phrases->appendChild($dom->createElement('phrase', $addonTitle)),
	[
		'title'          => 'option_group_' . $addonId,
		'version_id'     => '1',
		'version_string' => '1'
	]
);

// Add template modifications
$modifications = $addon->appendChild($dom->createElement('public_template_modifications'));
$modification  = $modifications->appendChild($dom->createElement('modification'));
setAttributes(
	$modification,
	[
		'action'           => 'preg_replace',
		'description'      => 'Fixes responsive embeds in XenForo Media Gallery',
		'enabled'          => 1,
		'execution_order'  => 10,
		'modification_key' => $addonId . '_xmg_fix',
		'template'         => 'xengallery_media_view.css'
	]
);
$modification->appendChild($dom->createElement('find', '(^)'));
$modification->appendChild($dom->createElement(
	'replace',
	".videoContainer>[data-s9e-mediaembed]\n{\n\tmax-width:100%!important;\n}\n\n"
));
$modification  = $modifications->appendChild($dom->createElement('modification'));
setAttributes(
	$modification,
	[
		'action'           => 'preg_replace',
		'description'      => "Fixes responsive embeds in XenForo Media Gallery's lightbox",
		'enabled'          => 1,
		'execution_order'  => 10,
		'modification_key' => $addonId . '_lightbox_fix',
		'template'         => 'xengallery_media_preview.css'
	]
);
$modification->appendChild($dom->createElement('find', '(^)'));
$modification->appendChild($dom->createElement(
	'replace',
	".mfp-iframe-scaler>span[data-s9e-mediaembed]>span>iframe\n{\n\tposition: fixed !important;\n}\n\n"
));
$modification  = $modifications->appendChild($dom->createElement('modification'));
setAttributes(
	$modification,
	[
		'action'           => 'preg_replace',
		'description'      => 'Fixes responsive embeds in sonnb XenGallery',
		'enabled'          => 1,
		'execution_order'  => 10,
		'modification_key' => $addonId . '_sonnb_fix',
		'template'         => 'sonnb_xengallery_photo_view.css'
	]
);
$modification->appendChild($dom->createElement('find', '(^.?)s'));
$modification->appendChild($dom->createElement(
	'replace',
	".video>[data-s9e-mediaembed],.videoHolder>[data-s9e-mediaembed]\n{\n\tmax-width:100%!important;\n}\n\n\$0"
));

$modification  = $modifications->appendChild($dom->createElement('modification'));
setAttributes(
	$modification,
	[
		'action'           => 'preg_replace',
		'description'      => 'Adds a scrollbar to the Add Media dialog',
		'enabled'          => 1,
		'execution_order'  => 10,
		'modification_key' => $addonId . '_add_media_dialog',
		'template'         => 'editor_ui.css'
	]
);
$modification->appendChild($dom->createElement('find', '(^.?)s'));
$modification->appendChild($dom->createElement(
	'replace',
	"#redactor_media_link+.listInline\n{\n\tmax-height:40vh;overflow-y:scroll;\n}\n\n\$0"
));

// Prepare the option group
$optiongroups = $addon->appendChild($dom->createElement('optiongroups'));

$group = $optiongroups->appendChild($dom->createElement('group'));
$group->setAttribute('group_id',      $addon->getAttribute('addon_id'));
$group->setAttribute('display_order', 0);
$group->setAttribute('debug_only',    0);
$displayOrder = 0;

// Add the attribution link
if (isset($linkText))
{
	$modification  = $modifications->appendChild($dom->createElement('modification'));
	setAttributes(
		$modification,
		[
			'action'           => 'str_replace',
			'description'      => 'Adds a link back to ' . $addonTitle,
			'enabled'          => 1,
			'execution_order'  => 10,
			'modification_key' => $addonId . '_footer',
			'template'         => 'footer'
		]
	);
	$modification->appendChild($dom->createElement(
		'find',
		'{xen:phrase extra_copyright}'
	));
	$modification->appendChild($dom->createElement(
		'replace',
		' | ' . $linkText . '$0'
	));

	$option = $optiongroups->appendChild($dom->createElement('option'));
	setAttributes(
		$option,
		[
			'option_id'         => $addonId . '_footer',
			'edit_format'       => 'radio',
			'data_type'         => 'string',
			'can_backup'        => 1,
			'validation_class'  => $className,
			'validation_method' => 'validateFooter'
		]
	);
	$option->appendChild($dom->createElement('default_value', 'show'));
	$option->appendChild($dom->createElement('edit_format_params', "show=I want to display a link to this add-on in the page footer\nhide=I do not want to display a link to this add-on"));
	setAttributes(
		$option->appendChild($dom->createElement('relation')),
		[
			'group_id'      => $addon->getAttribute('addon_id'),
			'display_order' => ++$displayOrder
		]
	);

	setAttributes(
		$phrases->appendChild($dom->createElement('phrase', 'Show your support')),
		[
			'title'          => 'option_' . $addonId . '_footer',
			'version_id'     => '1',
			'version_string' => '1'
		]
	);
	$html = 'You may also choose to support the author directly with a voluntary donation in USD or in EUR.
';
	setAttributes(
		$phrases->appendChild($dom->createElement('phrase', htmlspecialchars($html))),
		[
			'title'          => 'option_' . $addonId . '_footer_explain',
			'version_id'     => '1',
			'version_string' => '1'
		]
	);
}

// Tag checkboxes
setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Configure the s9e media sites')),
	[
		'title'          => 'option_group_' . $addonId . '_description',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Categories of media sites to install')),
	[
		'title'          => 'option_' . $addonId . '_media_tags',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

$html = '';
if (isset($tagsDescUrl))
{
	$html = 'List of optional sites enabled by each category';
}
setAttributes(
	$phrases->appendChild($dom->createElement('phrase', htmlspecialchars($html))),
	[
		'title'          => 'option_' . $addonId . '_media_tags_explain',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Custom callbacks')),
	[
		'title'          => 'option_' . $addonId . '_custom_callbacks',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

$text = '';
if (isset($githubUrl))
{
	$text = 'Help';
}
setAttributes(
	$phrases->appendChild($dom->createElement('phrase', $text)),
	[
		'title'          => 'option_' . $addonId . '_custom_callbacks_explain',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Custom dimensions')),
	[
		'title'          => 'option_' . $addonId . '_custom_dimensions',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Deprecated')),
	[
		'title'          => 'option_' . $addonId . '_custom_dimensions_explain',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Excluded sites')),
	[
		'title'          => 'option_' . $addonId . '_excluded_sites',
		'version_id'     => '1',
		'version_string' => '1'
	]
);
setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Comma-separated list of sites not to install')),
	[
		'title'          => 'option_' . $addonId . '_excluded_sites_explain',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

// Add the category checkboxes
$option = $optiongroups->appendChild($dom->createElement('option'));
setAttributes(
	$option,
	[
		'option_id'         => $addonId . '_media_tags',
		'edit_format'       => 'checkbox',
		'data_type'         => 'array',
		'can_backup'        => 1,
		'validation_class'  => $className,
		'validation_method' => 'updateTags'
	]
);

$tags = [];
foreach ($sites as $site)
{
	if (isset($site[KEY_TAGS]))
	{
		$tags += $site[KEY_TAGS];
	}
}
ksort($tags);

$lines = [];
foreach (array_keys($tags) as $tag)
{
	$lines[] = $tag . '=' . ucfirst($tag);
}

$option->appendChild($dom->createElement('default_value', serialize($tags)));
$option->appendChild($dom->createElement('edit_format_params', implode("\n", $lines)));
$option->appendChild($dom->createElement('sub_options', '*'));
setAttributes(
	$option->appendChild($dom->createElement('relation')),
	[
		'group_id'      => $addon->getAttribute('addon_id'),
		'display_order' => ++$displayOrder
	]
);

// Add the custom callbacks list
$option = $optiongroups->appendChild($dom->createElement('option'));
setAttributes(
	$option,
	[
		'option_id'         => $addonId . '_custom_callbacks',
		'edit_format'       => 'textbox',
		'data_type'         => 'string',
		'can_backup'        => 1,
		'validation_class'  => $className,
		'validation_method' => 'validateCustomCallbacks'
	]
);
$option->appendChild($dom->createElement('edit_format_params', 'rows=2'));
setAttributes(
	$option->appendChild($dom->createElement('relation')),
	[
		'group_id'      => $addon->getAttribute('addon_id'),
		'display_order' => ++$displayOrder
	]
);

// Add the custom dimensions list
$option = $optiongroups->appendChild($dom->createElement('option'));
setAttributes(
	$option,
	[
		'option_id'         => $addonId . '_custom_dimensions',
		'edit_format'       => 'textbox',
		'data_type'         => 'string',
		'can_backup'        => 1,
		'validation_class'  => $className,
		'validation_method' => 'validateCustomDimensions'
	]
);
$option->appendChild($dom->createElement('edit_format_params', 'rows=2'));
setAttributes(
	$option->appendChild($dom->createElement('relation')),
	[
		'group_id'      => $addon->getAttribute('addon_id'),
		'display_order' => ++$displayOrder
	]
);

// Add the blacklist param
$option = $optiongroups->appendChild($dom->createElement('option'));
setAttributes(
	$option,
	[
		'option_id'         => $addonId . '_excluded_sites',
		'edit_format'       => 'textbox',
		'data_type'         => 'string',
		'can_backup'        => 1,
		'validation_class'  => $className,
		'validation_method' => 'validateExcludedSites'
	]
);
setAttributes(
	$option->appendChild($dom->createElement('relation')),
	[
		'group_id'      => $addon->getAttribute('addon_id'),
		'display_order' => ++$displayOrder
	]
);

// Add the lazy loading modification and option
$modification  = $modifications->appendChild($dom->createElement('modification'));
setAttributes(
	$modification,
	[
		'action'           => 'preg_replace',
		'description'      => 'Defers the loading of embedded content',
		'enabled'          => 0,
		'execution_order'  => 10,
		'modification_key' => $addonId . '_lazy_loading',
		'template'         => 'ad_thread_view_below_messages'
	]
);
$modification->appendChild($dom->createElement('find', '(^)'));
$modification->appendChild($dom->createElement(
	'replace',
	htmlspecialchars('')
));

$option = $optiongroups->appendChild($dom->createElement('option'));
setAttributes(
	$option,
	[
		'option_id'         => $addonId . '_lazy_loading',
		'edit_format'       => 'radio',
		'data_type'         => 'string',
		'can_backup'        => 1,
		'validation_class'  => $className,
		'validation_method' => 'validateLazyLoading'
	]
);
$option->appendChild($dom->createElement('default_value', 'immediate'));
$option->appendChild($dom->createElement('edit_format_params', "immediate=Load embedded content immediately\nlazy=Defer loading embedded content until it's visible (experimental)"));
setAttributes(
	$option->appendChild($dom->createElement('relation')),
	[
		'group_id'      => $addon->getAttribute('addon_id'),
		'display_order' => ++$displayOrder
	]
);
setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Performance')),
	[
		'title'          => 'option_' . $addonId . '_lazy_loading',
		'version_id'     => '1',
		'version_string' => '1'
	]
);
setAttributes(
	$phrases->appendChild($dom->createElement('phrase', 'Deferring the loading of embedded content makes pages load faster and use less memory.')),
	[
		'title'          => 'option_' . $addonId . '_lazy_loading_explain',
		'version_id'     => '1',
		'version_string' => '1'
	]
);

// Make the CSS that applies to iframes in quotes apply to their wrapper too
$modification  = $modifications->appendChild($dom->createElement('modification'));
setAttributes(
	$modification,
	[
		'action'           => 'str_replace',
		'description'      => 'Makes the CSS that applies to iframes in quote also apply to the responsive embed wrapper',
		'enabled'          => 1,
		'execution_order'  => 10,
		'modification_key' => $addonId . '_quote_css',
		'template'         => 'bb_code.css'
	]
);
$modification->appendChild($dom->createElement('find', '.bbCodeQuote iframe,'));
$modification->appendChild($dom->createElement(
	'replace',
	'.bbCodeQuote iframe, .bbCodeQuote [data-s9e-mediaembed],'
));

// Expand embeds inside of expanded quote blocks
$modification  = $modifications->appendChild($dom->createElement('modification'));
setAttributes(
	$modification,
	[
		'action'           => 'preg_replace',
		'description'      => 'Expands embeds inside of expanded quote blocks',
		'enabled'          => 1,
		'execution_order'  => 1,
		'modification_key' => $addonId . '_quote_expanded_css',
		'template'         => 'bb_code.css'
	]
);
$modification->appendChild($dom->createElement('find', '(^)'));
$modification->appendChild($dom->createElement(
	'replace',
	'.quoteContainer.expanded iframe[data-s9e-mediaembed],
	.quoteContainer.expanded [data-s9e-mediaembed] iframe
	{
		max-height: none;
		max-width:  none;
	}

'
));

// Un-position iframes inside of collapsed quote blocks
$modification  = $modifications->appendChild($dom->createElement('modification'));
setAttributes(
	$modification,
	[
		'action'           => 'preg_replace',
		'description'      => 'Un-positions iframes inside of collapsed quote blocks',
		'enabled'          => 1,
		'execution_order'  => 1,
		'modification_key' => $addonId . '_quote_collapsed_css',
		'template'         => 'bb_code.css'
	]
);
$modification->appendChild($dom->createElement('find', '(^)'));
$modification->appendChild($dom->createElement(
	'replace',
	'.quoteContainer:not(.expanded) [data-s9e-mediaembed] iframe
	{
		position: unset !important;
	}

'
));

// Add the params as XenForo options
ksort($optionNames);

$displayOrder = 100;
foreach ($optionNames as $paramName => $optionName)
{
	$option = $optiongroups->appendChild($dom->createElement('option'));

	setAttributes(
		$option,
		[
			'option_id'   => $optionName,
			'edit_format' => 'textbox',
			'data_type'   => 'string',
			'can_backup'  => '1'
		]
	);

	setAttributes(
		$option->appendChild($dom->createElement('relation')),
		[
			'group_id'      => $addon->getAttribute('addon_id'),
			'display_order' => ++$displayOrder
		]
	);

	setAttributes(
		$phrases->appendChild($dom->createElement('phrase', $paramName)),
		[
			'title'          => 'option_' . $optionName,
			'version_id'     => '1',
			'version_string' => '1'
		]
	);

	setAttributes(
		$phrases->appendChild($dom->createElement('phrase')),
		[
			'title'          => 'option_' . $optionName . '_explain',
			'version_id'     => '1',
			'version_string' => '1'
		]
	);
}

// Save the helper class
$php = implode("\n", $php);
if (file_get_contents($classFile) !== $php)
{
	file_put_contents($classFile, $php);
}

// Save addon.xml
$dom->formatOutput = true;
$xml = $dom->saveXML($addon);
if (file_get_contents($addonFile) !== $xml)
{
	file_put_contents($addonFile, $xml);
}

if ($addonId !== 's9e')
{
	return;
}

if (!file_exists(__DIR__ . '/../releases') || !empty($_SERVER['TRAVIS']))
{
	return;
}

// @codeCoverageIgnoreStart
chdir(__DIR__ . '/../build');
copy('../LICENSE', 'LICENSE');
exec('kzip -r -y ../releases/XenForoMediaBBCodes-' . $version . '.zip addon-s9e.xml LICENSE upload/library/s9e/MediaBBCodes.php');
exec('advzip -z4 ../releases/XenForoMediaBBCodes-' . $version . '.zip');

$readme =
'[B]This add-on is for XenForo 1.x. For XenForo 2.x, install [URL=https://xenforo.com/community/resources/s9e-media-sites.5973/]the s9e/MediaSites add-on[/URL].[/B]

[center][url="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6P6985GT2DLGL"][img]https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif[/img][/url][url="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ABGFV5AGE98AG"][img]https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif[/img][/url][/center]

This pack contains the definitions for [b]' . count($sitenames) . ' media sites[/b]: ' . implode(', ', $sitenames) . '. The complete list with examples of supported URLs can be found on [url="http://s9etextformatter.readthedocs.io/Plugins/MediaEmbed/Sites/"]this page[/url].

The BBCodes definitions are based on [url="https://github.com/s9e/TextFormatter"]the s9e\TextFormatter library[/url], and more specifically its [url="https://github.com/s9e/TextFormatter/tree/master/src/Plugins/MediaEmbed"]MediaEmbed[/url] plugin. The BBCodes are designed for performance: the media site is only accessed once during posting, and only if absolutely necessary.

This add-on is released under [url="http://en.wikipedia.org/wiki/MIT_License"]The MIT License[/url]. Redistribution is allowed as per the license terms. [color=#fff]This add-on is free, open source and available on GitHub. If you paid for it, you\'ve been swindled.[/color]
[url="https://travis-ci.org/s9e/XenForoMediaBBCodes"][img]https://travis-ci.org/s9e/XenForoMediaBBCodes.png?branch=master&' . $version . '[/img][/url] [url="https://coveralls.io/r/s9e/XenForoMediaBBCodes"][img]https://coveralls.io/repos/s9e/XenForoMediaBBCodes/badge.png?' . $version . '[/img][/url]

[SIZE=6][FONT=Arial][B]How to remove the branding[/B][/FONT][/SIZE]

The add-on displays a small notice in the page footer, alongside XenForo\'s copyright. You can disable this notice from the Admin CP by going to Home > Options > s9e Media Pack. If you do, please consider making a voluntary donation using the PayPal buttons below.

[size=6][font=Arial][b]Installation / Upgrade[/b][/font][/size]

Unzip the archive and upload the content of the [font=monospace]upload[/font] folder to your XenForo installation. Then go to your forum\'s Admin CP and install/upgrade the add-on via the provided [font=monospace]addon-s9e.xml[/font] file.

[size=6][font=Arial][b]Configuration[/b][/font][/size]

You can configure which categories of media sites you want installed in the Admin CP by going to Home > Options > s9e Media Pack. By default, all the media sites are installed. You do not need to reinstall after changing the configuration.

[size=6][font=Arial][b]How to request a media site[/b][/font][/size]

If there is a media site that you would want to see in this pack, you can request it in this thread and it will be considered for inclusion. Selection may depend on the site\'s popularity, Alexa rank and activity on social sites. [b]Please post a few links as examples[/b] of the kind of links that should be supported. You do not need to post the embed code, only links to the content [i]you[/i] want to embed.

[size=6][font=Arial][b]How to support this add-on[/b][/font][/size]

You can donate any amount of your hard earned money in EUR or USD using either of the following links. Reviewing and rating the add-on helps improve its visibility too.

[center][url="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6P6985GT2DLGL"][img]https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif[/img][/url][url="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ABGFV5AGE98AG"][img]https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif[/img][/url][/center]';

file_put_contents(
	__DIR__ . '/../releases/XenForoMediaBBCodes-' . $version . '.txt',
	$readme
);
// @codeCoverageIgnoreEnd


text:
package org.axonframework.common;

import org.apache.commons.collections.set.ListOrderedSet;

import java.util.Arrays;
import java.util.Set;

/**
 *
 */
public class TestUtils {

    @SuppressWarnings({"unchecked"})
    public static <T> Set<T> setOf(T... items) {
        return ListOrderedSet.decorate(Arrays.asList(items));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Tooling;
using NSubstitute;

namespace Cake.FluentMigrator.UnitTests
{
    class ToolResolverFixture
    {
        public ICakeEnvironment Environment { get; set; }
        public IFileSystem FileSystem { get; set; }
        public IToolLocator ToolLocator { get; set; }

        public ToolResolverFixture(PlatformFamily family, bool is64Bit, Version frameworkVersion)
        {
            Environment = Substitute.For<ICakeEnvironment>();
            Environment.Platform.Returns(info =>
            {
                var platform = Substitute.For<ICakePlatform>();
                platform.Is64Bit.Returns(is64Bit);
                platform.Family.Returns(family);
                return platform;
            });
            Environment.Runtime.Returns(info =>
            {
                var runtime = Substitute.For<ICakeRuntime>();
                runtime.TargetFramework.Returns(callInfo => new FrameworkName(".Net 4.5.2", frameworkVersion));
                return runtime;
            });

            FileSystem = Substitute.For<IFileSystem>();
            ToolLocator = Substitute.For<IToolLocator>();
        }
    }
}


text:
/*************************************************************************/
/*  syntax_highlighter.cpp                                               */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "syntax_highlighter.h"

#include "core/object/script_language.h"
#include "scene/gui/text_edit.h"

Dictionary SyntaxHighlighter::get_line_syntax_highlighting(int p_line) {
	if (highlighting_cache.has(p_line)) {
		return highlighting_cache[p_line];
	}

	Dictionary color_map;
	if (text_edit == nullptr) {
		return color_map;
	}

	if (!GDVIRTUAL_CALL(_get_line_syntax_highlighting, p_line, color_map)) {
		color_map = _get_line_syntax_highlighting_impl(p_line);
	}

	highlighting_cache[p_line] = color_map;
	return color_map;
}

void SyntaxHighlighter::_lines_edited_from(int p_from_line, int p_to_line) {
	if (highlighting_cache.size() < 1) {
		return;
	}

	int cache_size = highlighting_cache.back()->key();
	for (int i = MIN(p_from_line, p_to_line) - 1; i <= cache_size; i++) {
		if (highlighting_cache.has(i)) {
			highlighting_cache.erase(i);
		}
	}
}

void SyntaxHighlighter::clear_highlighting_cache() {
	highlighting_cache.clear();

	if (GDVIRTUAL_CALL(_clear_highlighting_cache)) {
		return;
	}
	_clear_highlighting_cache();
}

void SyntaxHighlighter::update_cache() {
	clear_highlighting_cache();

	if (text_edit == nullptr) {
		return;
	}
	if (GDVIRTUAL_CALL(_update_cache)) {
		return;
	}
	_update_cache();
}

void SyntaxHighlighter::set_text_edit(TextEdit *p_text_edit) {
	if (text_edit && ObjectDB::get_instance(text_edit_instance_id)) {
		text_edit->disconnect("lines_edited_from", callable_mp(this, &SyntaxHighlighter::_lines_edited_from));
	}

	text_edit = p_text_edit;
	if (p_text_edit == nullptr) {
		return;
	}
	text_edit_instance_id = text_edit->get_instance_id();
	text_edit->connect("lines_edited_from", callable_mp(this, &SyntaxHighlighter::_lines_edited_from));
	update_cache();
}

TextEdit *SyntaxHighlighter::get_text_edit() {
	return text_edit;
}

void SyntaxHighlighter::_bind_methods() {
	ClassDB::bind_method(D_METHOD("get_line_syntax_highlighting", "line"), &SyntaxHighlighter::get_line_syntax_highlighting);
	ClassDB::bind_method(D_METHOD("update_cache"), &SyntaxHighlighter::update_cache);
	ClassDB::bind_method(D_METHOD("clear_highlighting_cache"), &SyntaxHighlighter::clear_highlighting_cache);
	ClassDB::bind_method(D_METHOD("get_text_edit"), &SyntaxHighlighter::get_text_edit);

	GDVIRTUAL_BIND(_get_line_syntax_highlighting, "line")
	GDVIRTUAL_BIND(_clear_highlighting_cache)
	GDVIRTUAL_BIND(_update_cache)
}

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

static bool _is_char(char32_t c) {
	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}

static bool _is_hex_symbol(char32_t c) {
	return ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
}

Dictionary CodeHighlighter::_get_line_syntax_highlighting_impl(int p_line) {
	Dictionary color_map;

	bool prev_is_char = false;
	bool prev_is_number = false;
	bool in_keyword = false;
	bool in_word = false;
	bool in_function_name = false;
	bool in_member_variable = false;
	bool is_hex_notation = false;
	Color keyword_color;
	Color color;

	color_region_cache[p_line] = -1;
	int in_region = -1;
	if (p_line != 0) {
		int prev_region_line = p_line - 1;
		while (prev_region_line > 0 && !color_region_cache.has(prev_region_line)) {
			prev_region_line--;
		}
		for (int i = prev_region_line; i < p_line - 1; i++) {
			get_line_syntax_highlighting(i);
		}
		if (!color_region_cache.has(p_line - 1)) {
			get_line_syntax_highlighting(p_line - 1);
		}
		in_region = color_region_cache[p_line - 1];
	}

	const String &str = text_edit->get_line(p_line);
	const int line_length = str.length();
	Color prev_color;

	if (in_region != -1 && str.length() == 0) {
		color_region_cache[p_line] = in_region;
	}
	for (int j = 0; j < line_length; j++) {
		Dictionary highlighter_info;

		color = font_color;
		bool is_char = !is_symbol(str[j]);
		bool is_a_symbol = is_symbol(str[j]);
		bool is_number = (str[j] >= '0' && str[j] <= '9');

		/* color regions */
		if (is_a_symbol || in_region != -1) {
			int from = j;
			for (; from < line_length; from++) {
				if (str[from] == '\\') {
					from++;
					continue;
				}
				break;
			}

			if (from != line_length) {
				/* check if we are in entering a region */
				if (in_region == -1) {
					for (int c = 0; c < color_regions.size(); c++) {
						/* check there is enough room */
						int chars_left = line_length - from;
						int start_key_length = color_regions[c].start_key.length();
						int end_key_length = color_regions[c].end_key.length();
						if (chars_left < start_key_length) {
							continue;
						}

						/* search the line */
						bool match = true;
						const char32_t *start_key = color_regions[c].start_key.get_data();
						for (int k = 0; k < start_key_length; k++) {
							if (start_key[k] != str[from + k]) {
								match = false;
								break;
							}
						}
						if (!match) {
							continue;
						}
						in_region = c;
						from += start_key_length;

						/* check if it's the whole line */
						if (end_key_length == 0 || color_regions[c].line_only || from + end_key_length > line_length) {
							prev_color = color_regions[in_region].color;
							highlighter_info["color"] = color_regions[c].color;
							color_map[j] = highlighter_info;

							j = line_length;
							if (!color_regions[c].line_only) {
								color_region_cache[p_line] = c;
							}
						}
						break;
					}

					if (j == line_length) {
						continue;
					}
				}

				/* if we are in one find the end key */
				if (in_region != -1) {
					/* search the line */
					int region_end_index = -1;
					int end_key_length = color_regions[in_region].end_key.length();
					const char32_t *end_key = color_regions[in_region].end_key.get_data();
					for (; from < line_length; from++) {
						if (line_length - from < end_key_length) {
							break;
						}

						if (!is_symbol(str[from])) {
							continue;
						}

						if (str[from] == '\\') {
							from++;
							continue;
						}

						region_end_index = from;
						for (int k = 0; k < end_key_length; k++) {
							if (end_key[k] != str[from + k]) {
								region_end_index = -1;
								break;
							}
						}

						if (region_end_index != -1) {
							break;
						}
					}

					prev_color = color_regions[in_region].color;
					highlighter_info["color"] = color_regions[in_region].color;
					color_map[j] = highlighter_info;

					j = from + (end_key_length - 1);
					if (region_end_index == -1) {
						color_region_cache[p_line] = in_region;
					}

					in_region = -1;
					prev_is_char = false;
					prev_is_number = false;
					continue;
				}
			}
		}

		// Allow ABCDEF in hex notation.
		if (is_hex_notation && (_is_hex_symbol(str[j]) || is_number)) {
			is_number = true;
		} else {
			is_hex_notation = false;
		}

		// Check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation.
		if ((str[j] == '.' || str[j] == 'x' || str[j] == '_' || str[j] == 'f' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {
			is_number = true;
			is_a_symbol = false;
			is_char = false;

			if (str[j] == 'x' && str[j - 1] == '0') {
				is_hex_notation = true;
			}
		}

		if (!in_word && _is_char(str[j]) && !is_number) {
			in_word = true;
		}

		if ((in_keyword || in_word) && !is_hex_notation) {
			is_number = false;
		}

		if (is_a_symbol && str[j] != '.' && in_word) {
			in_word = false;
		}

		if (!is_char) {
			in_keyword = false;
		}

		if (!in_keyword && is_char && !prev_is_char) {
			int to = j;
			while (to < line_length && !is_symbol(str[to])) {
				to++;
			}

			String word = str.substr(j, to - j);
			Color col = Color();
			if (keywords.has(word)) {
				col = keywords[word];
			} else if (member_keywords.has(word)) {
				col = member_keywords[word];
				for (int k = j - 1; k >= 0; k--) {
					if (str[k] == '.') {
						col = Color(); //member indexing not allowed
						break;
					} else if (str[k] > 32) {
						break;
					}
				}
			}

			if (col != Color()) {
				in_keyword = true;
				keyword_color = col;
			}
		}

		if (!in_function_name && in_word && !in_keyword) {
			int k = j;
			while (k < line_length && !is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
				k++;
			}

			// Check for space between name and bracket.
			while (k < line_length && (str[k] == '\t' || str[k] == ' ')) {
				k++;
			}

			if (str[k] == '(') {
				in_function_name = true;
			}
		}

		if (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) {
			int k = j;
			while (k > 0 && !is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
				k--;
			}

			if (str[k] == '.') {
				in_member_variable = true;
			}
		}

		if (is_a_symbol) {
			in_function_name = false;
			in_member_variable = false;
		}

		if (in_keyword) {
			color = keyword_color;
		} else if (in_member_variable) {
			color = member_color;
		} else if (in_function_name) {
			color = function_color;
		} else if (is_a_symbol) {
			color = symbol_color;
		} else if (is_number) {
			color = number_color;
		}

		prev_is_char = is_char;
		prev_is_number = is_number;

		if (color != prev_color) {
			prev_color = color;
			highlighter_info["color"] = color;
			color_map[j] = highlighter_info;
		}
	}

	return color_map;
}

void CodeHighlighter::_clear_highlighting_cache() {
	color_region_cache.clear();
}

void CodeHighlighter::_update_cache() {
	font_color = text_edit->get_theme_color(SNAME("font_color"));
}

void CodeHighlighter::add_keyword_color(const String &p_keyword, const Color &p_color) {
	keywords[p_keyword] = p_color;
	clear_highlighting_cache();
}

void CodeHighlighter::remove_keyword_color(const String &p_keyword) {
	keywords.erase(p_keyword);
	clear_highlighting_cache();
}

bool CodeHighlighter::has_keyword_color(const String &p_keyword) const {
	return keywords.has(p_keyword);
}

Color CodeHighlighter::get_keyword_color(const String &p_keyword) const {
	ERR_FAIL_COND_V(!keywords.has(p_keyword), Color());
	return keywords[p_keyword];
}

void CodeHighlighter::set_keyword_colors(const Dictionary p_keywords) {
	keywords.clear();
	keywords = p_keywords;
	clear_highlighting_cache();
}

void CodeHighlighter::clear_keyword_colors() {
	keywords.clear();
	clear_highlighting_cache();
}

Dictionary CodeHighlighter::get_keyword_colors() const {
	return keywords;
}

void CodeHighlighter::add_member_keyword_color(const String &p_member_keyword, const Color &p_color) {
	member_keywords[p_member_keyword] = p_color;
	clear_highlighting_cache();
}

void CodeHighlighter::remove_member_keyword_color(const String &p_member_keyword) {
	member_keywords.erase(p_member_keyword);
	clear_highlighting_cache();
}

bool CodeHighlighter::has_member_keyword_color(const String &p_member_keyword) const {
	return member_keywords.has(p_member_keyword);
}

Color CodeHighlighter::get_member_keyword_color(const String &p_member_keyword) const {
	ERR_FAIL_COND_V(!member_keywords.has(p_member_keyword), Color());
	return member_keywords[p_member_keyword];
}

void CodeHighlighter::set_member_keyword_colors(const Dictionary &p_member_keywords) {
	member_keywords.clear();
	member_keywords = p_member_keywords;
	clear_highlighting_cache();
}

void CodeHighlighter::clear_member_keyword_colors() {
	member_keywords.clear();
	clear_highlighting_cache();
}

Dictionary CodeHighlighter::get_member_keyword_colors() const {
	return member_keywords;
}

void CodeHighlighter::add_color_region(const String &p_start_key, const String &p_end_key, const Color &p_color, bool p_line_only) {
	for (int i = 0; i < p_start_key.length(); i++) {
		ERR_FAIL_COND_MSG(!is_symbol(p_start_key[i]), "color regions must start with a symbol");
	}

	if (p_end_key.length() > 0) {
		for (int i = 0; i < p_end_key.length(); i++) {
			ERR_FAIL_COND_MSG(!is_symbol(p_end_key[i]), "color regions must end with a symbol");
		}
	}

	int at = 0;
	for (int i = 0; i < color_regions.size(); i++) {
		ERR_FAIL_COND_MSG(color_regions[i].start_key == p_start_key, "color region with start key '" + p_start_key + "' already exists.");
		if (p_start_key.length() < color_regions[i].start_key.length()) {
			at++;
		}
	}

	ColorRegion color_region;
	color_region.color = p_color;
	color_region.start_key = p_start_key;
	color_region.end_key = p_end_key;
	color_region.line_only = p_line_only || p_end_key == "";
	color_regions.insert(at, color_region);
	clear_highlighting_cache();
}

void CodeHighlighter::remove_color_region(const String &p_start_key) {
	for (int i = 0; i < color_regions.size(); i++) {
		if (color_regions[i].start_key == p_start_key) {
			color_regions.remove(i);
			break;
		}
	}
	clear_highlighting_cache();
}

bool CodeHighlighter::has_color_region(const String &p_start_key) const {
	for (int i = 0; i < color_regions.size(); i++) {
		if (color_regions[i].start_key == p_start_key) {
			return true;
		}
	}
	return false;
}

void CodeHighlighter::set_color_regions(const Dictionary &p_color_regions) {
	color_regions.clear();

	List<Variant> keys;
	p_color_regions.get_key_list(&keys);

	for (const Variant &E : keys) {
		String key = E;

		String start_key = key.get_slice(" ", 0);
		String end_key = key.get_slice_count(" ") > 1 ? key.get_slice(" ", 1) : String();

		add_color_region(start_key, end_key, p_color_regions[key], end_key == "");
	}
	clear_highlighting_cache();
}

void CodeHighlighter::clear_color_regions() {
	color_regions.clear();
	clear_highlighting_cache();
}

Dictionary CodeHighlighter::get_color_regions() const {
	Dictionary r_color_regions;
	for (int i = 0; i < color_regions.size(); i++) {
		ColorRegion region = color_regions[i];
		r_color_regions[region.start_key + (region.end_key.is_empty() ? "" : " " + region.end_key)] = region.color;
	}
	return r_color_regions;
}

void CodeHighlighter::_bind_methods() {
	ClassDB::bind_method(D_METHOD("add_keyword_color", "keyword", "color"), &CodeHighlighter::add_keyword_color);
	ClassDB::bind_method(D_METHOD("remove_keyword_color", "keyword"), &CodeHighlighter::remove_keyword_color);
	ClassDB::bind_method(D_METHOD("has_keyword_color", "keyword"), &CodeHighlighter::has_keyword_color);
	ClassDB::bind_method(D_METHOD("get_keyword_color", "keyword"), &CodeHighlighter::get_keyword_color);

	ClassDB::bind_method(D_METHOD("set_keyword_colors", "keywords"), &CodeHighlighter::set_keyword_colors);
	ClassDB::bind_method(D_METHOD("clear_keyword_colors"), &CodeHighlighter::clear_keyword_colors);
	ClassDB::bind_method(D_METHOD("get_keyword_colors"), &CodeHighlighter::get_keyword_colors);

	ClassDB::bind_method(D_METHOD("add_member_keyword_color", "member_keyword", "color"), &CodeHighlighter::add_member_keyword_color);
	ClassDB::bind_method(D_METHOD("remove_member_keyword_color", "member_keyword"), &CodeHighlighter::remove_member_keyword_color);
	ClassDB::bind_method(D_METHOD("has_member_keyword_color", "member_keyword"), &CodeHighlighter::has_member_keyword_color);
	ClassDB::bind_method(D_METHOD("get_member_keyword_color", "member_keyword"), &CodeHighlighter::get_member_keyword_color);

	ClassDB::bind_method(D_METHOD("set_member_keyword_colors", "member_keyword"), &CodeHighlighter::set_member_keyword_colors);
	ClassDB::bind_method(D_METHOD("clear_member_keyword_colors"), &CodeHighlighter::clear_member_keyword_colors);
	ClassDB::bind_method(D_METHOD("get_member_keyword_colors"), &CodeHighlighter::get_member_keyword_colors);

	ClassDB::bind_method(D_METHOD("add_color_region", "start_key", "end_key", "color", "line_only"), &CodeHighlighter::add_color_region, DEFVAL(false));
	ClassDB::bind_method(D_METHOD("remove_color_region", "start_key"), &CodeHighlighter::remove_color_region);
	ClassDB::bind_method(D_METHOD("has_color_region", "start_key"), &CodeHighlighter::has_color_region);

	ClassDB::bind_method(D_METHOD("set_color_regions", "color_regions"), &CodeHighlighter::set_color_regions);
	ClassDB::bind_method(D_METHOD("clear_color_regions"), &CodeHighlighter::clear_color_regions);
	ClassDB::bind_method(D_METHOD("get_color_regions"), &CodeHighlighter::get_color_regions);

	ClassDB::bind_method(D_METHOD("set_function_color", "color"), &CodeHighlighter::set_function_color);
	ClassDB::bind_method(D_METHOD("get_function_color"), &CodeHighlighter::get_function_color);

	ClassDB::bind_method(D_METHOD("set_number_color", "color"), &CodeHighlighter::set_number_color);
	ClassDB::bind_method(D_METHOD("get_number_color"), &CodeHighlighter::get_number_color);

	ClassDB::bind_method(D_METHOD("set_symbol_color", "color"), &CodeHighlighter::set_symbol_color);
	ClassDB::bind_method(D_METHOD("get_symbol_color"), &CodeHighlighter::get_symbol_color);

	ClassDB::bind_method(D_METHOD("set_member_variable_color", "color"), &CodeHighlighter::set_member_variable_color);
	ClassDB::bind_method(D_METHOD("get_member_variable_color"), &CodeHighlighter::get_member_variable_color);

	ADD_PROPERTY(PropertyInfo(Variant::COLOR, "number_color"), "set_number_color", "get_number_color");
	ADD_PROPERTY(PropertyInfo(Variant::COLOR, "symbol_color"), "set_symbol_color", "get_symbol_color");
	ADD_PROPERTY(PropertyInfo(Variant::COLOR, "function_color"), "set_function_color", "get_function_color");
	ADD_PROPERTY(PropertyInfo(Variant::COLOR, "member_variable_color"), "set_member_variable_color", "get_member_variable_color");

	ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "keyword_colors"), "set_keyword_colors", "get_keyword_colors");
	ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "member_keyword_colors"), "set_member_keyword_colors", "get_member_keyword_colors");
	ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "color_regions"), "set_color_regions", "get_color_regions");
}

void CodeHighlighter::set_number_color(Color p_color) {
	number_color = p_color;
	clear_highlighting_cache();
}

Color CodeHighlighter::get_number_color() const {
	return number_color;
}

void CodeHighlighter::set_symbol_color(Color p_color) {
	symbol_color = p_color;
	clear_highlighting_cache();
}

Color CodeHighlighter::get_symbol_color() const {
	return symbol_color;
}

void CodeHighlighter::set_function_color(Color p_color) {
	function_color = p_color;
	clear_highlighting_cache();
}

Color CodeHighlighter::get_function_color() const {
	return function_color;
}

void CodeHighlighter::set_member_variable_color(Color p_color) {
	member_color = p_color;
	clear_highlighting_cache();
}

Color CodeHighlighter::get_member_variable_color() const {
	return member_color;
}


text:
from django.db.models.signals import pre_delete, post_save
from avocado.core.loader import AlreadyRegistered, NotRegistered
from .receivers import pre_delete_revision, post_save_revision
from . import utils

registry = {}

def register(model, fields=None, exclude=None):
    """Registers a model with the specified fields to be automatically
    versioned on save and delete operations.
    """
    if model in registry:
        raise AlreadyRegistered(u'The model {0} is already registered'.format(
            model.__name__))

    if not fields:
        fields = utils.get_model_fields(model)
    if not exclude:
        exclude = ()

    utils.validate_fields(model, fields, exclude)
    fields = tuple(set(fields) - set(exclude))

    if not fields:
        raise ValueError(u'No fields defined for versioning.')

    dispatch_uid = '{0}_revision'.format(model.__name__)

    pre_delete.connect(pre_delete_revision, weak=False, sender=model,
                       dispatch_uid=dispatch_uid)
    post_save.connect(post_save_revision, weak=False, sender=model,
                      dispatch_uid=dispatch_uid)

    registry[model] = {
        'fields': fields,
        'dispatch_uid': dispatch_uid,
    }

def unregister(model):
    "Unregisters a model from versioning."
    if model not in registry:
        raise NotRegistered(u'The model {0} is not registered'.format(
            model.__name__))
    cache = registry.pop(model)
    pre_delete.disconnect(sender=model, dispatch_uid=cache['dispatch_uid'])
    post_save.disconnect(sender=model, dispatch_uid=cache['dispatch_uid'])


text:
@interface MenuModel () {

    Callback _loadModelCallback;
}

@end

@implementation MenuModel

- (void)dealloc {

    [self.userManager removeServiceObserver:self];
}

#pragma mark - Public -

- (BOOL)isUserLoggedIn {

    return self.userManager.isUserLoggedIn;
}

- (void)logoutUser {

    [self.userManager logout];
}

#pragma mark - Protected -

- (void)commonInit {

    [super commonInit];

    // Add user state observing
    [self.userManager addServiceObserver:self];
}

- (void)willStartModelLoading:(Callback)callback {

    // Save for login/signup/logout callbacks later
    _loadModelCallback = callback;

    NSArray *itemList = nil;

    if (self.userManager.isUserLoggedIn) {

        itemList = [self menuItemsForLoggedInUserState];

    } else {

        itemList = [self menuItemsForNotLoggedInUserState];
    }

    // Done
    callback(YES, itemList, nil);
}

- (void)didFinishModelLoadingWithData:(id)data error:(NSError *)error {

    // Store menu items
    _menuItems = data;
}

#pragma mark - UserManagerObserver -

- (void)didLoginUser:(UserObject *)userObject {

    _menuItems = [self menuItemsForLoggedInUserState];

    // Notify view controler
    // Adding protection because was crashing upon opening app with 401
    if (_loadModelCallback) {

        _loadModelCallback(YES, _menuItems, nil);
    }
}

- (void)didSignUpUser:(UserObject *)userObject {

    _menuItems = [self menuItemsForLoggedInUserState];

    // Notify view controler
    // Adding protection because was crashing upon opening app with 401
    if (_loadModelCallback) {

        _loadModelCallback(YES, _menuItems, nil);
    }
}

- (void)didLogoutUser:(UserObject *)userObject {

    _menuItems = [self menuItemsForNotLoggedInUserState];

    // Notify view controler
    // Adding protection because was crashing upon opening app with 401
    if (_loadModelCallback) {

        _loadModelCallback(YES, _menuItems, nil);
    }
}

#pragma mark - Private -

// For mocking in unit tests
- (id<ViewControllerFactoryProtocol>)viewControllerFactory {

    ViewControllerFactory *factory = [REGISTRY getObject:[ViewControllerFactory class]];

    return factory;
}

- (NSMutableArray *)menuItemsForNotLoggedInUserState {

    // Create menu items
    NSMutableArray *itemList = [[NSMutableArray alloc] init];

    // Create menu items
    id<ViewControllerFactoryProtocol> viewControllerFactory = [self viewControllerFactory];

    // Home
    MenuItemObject *item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemMapKey);
    item.viewController = self.context;
    [itemList addObject:item];

    // Settings
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemSettingsKey);
    item.viewController = (BaseViewController *) [viewControllerFactory settingsViewControllerWithContext:nil];
    [itemList addObject:item];

    // User login
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemLoginKey);
    item.viewController = (BaseViewController *) [viewControllerFactory userContainerViewControllerWithContext:nil];
    item.isPresentedModally = YES;
    [itemList addObject:item];

    // TermsConditions
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemTermsConditionsKey);
    item.viewController = (BaseViewController *) [viewControllerFactory termsConditionsViewControllerWithContext:nil];
    [itemList addObject:item];

    // Privacy policy
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemPrivacyPolicyKey);
    item.viewController = (BaseViewController *) [viewControllerFactory privacyPolicyViewControllerWithContext:nil];
    [itemList addObject:item];

    // TableViewExample
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemTableViewExampleKey);
    item.viewController = (BaseViewController *) [viewControllerFactory tableViewExampleViewControllerWithContext:nil];
    [itemList addObject:item];

    // TableView with search
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemTableViewWithSearchKey);
    item.viewController = (BaseViewController *) [viewControllerFactory tableWithSearchViewControllerWithContext:nil];
    [itemList addObject:item];

    // Map
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemMapWithSearchKey);
    item.viewController = (BaseViewController *) [viewControllerFactory mapsViewControllerWithContext:nil];
    [itemList addObject:item];

    // Return
    return itemList;
}

- (NSMutableArray *)menuItemsForLoggedInUserState {

    // Create menu items
    NSMutableArray *itemList = [[NSMutableArray alloc] init];

    // Create menu items
    id<ViewControllerFactoryProtocol> viewControllerFactory = [self viewControllerFactory];

    // Home
    MenuItemObject *item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemMapKey);
    item.viewController = self.context;
    [itemList addObject:item];

    // Settings
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemSettingsKey);
    item.viewController = (BaseViewController *) [viewControllerFactory settingsViewControllerWithContext:nil];
    [itemList addObject:item];

    // TermsConditions
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemTermsConditionsKey);
    item.viewController = (BaseViewController *) [viewControllerFactory termsConditionsViewControllerWithContext:nil];
    [itemList addObject:item];

    // Privacy policy
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemPrivacyPolicyKey);
    item.viewController = (BaseViewController *) [viewControllerFactory privacyPolicyViewControllerWithContext:nil];
    [itemList addObject:item];

    // TableViewExample
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemTableViewExampleKey);
    item.viewController = (BaseViewController *) [viewControllerFactory tableViewExampleViewControllerWithContext:nil];
    [itemList addObject:item];

    // TableView with search
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemTableViewWithSearchKey);
    item.viewController = (BaseViewController *) [viewControllerFactory tableWithSearchViewControllerWithContext:nil];
    [itemList addObject:item];

    // Map
    item = [[MenuItemObject alloc] init];
    item.menuTitle = GMLocalizedString(kMenuModelMenuItemMapWithSearchKey);
    item.viewController = (BaseViewController *) [viewControllerFactory mapsViewControllerWithContext:nil];
    [itemList addObject:item];

    // Return
    return itemList;
}

@end


text:
package org.apache.beam.sdk.microbenchmarks.coders;

import java.io.IOException;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.util.CoderUtils;

/**
 * Utilities for writing coder benchmarks.
 */
class CoderBenchmarking {

  /**
   * Encodes and decodes the given value using the specified Coder.
   *
   * @throws IOException if there are errors during encoding or decoding
   */
  public static <T> T testCoder(
      Coder<T> coder, boolean isWholeStream, T value) throws IOException {
    Coder.Context context =
        isWholeStream ? Coder.Context.OUTER : Coder.Context.NESTED;
    byte[] encoded = CoderUtils.encodeToByteArray(coder, value, context);
    return CoderUtils.decodeFromByteArray(coder, encoded, context);
  }
}


text:
<!DOCTYPE html>

    <title>Add Diagnosis</title>
    <link href="../../../resources/css/datepicker3.css" th:href="@{/resources/css/datepicker3.css}" rel="stylesheet"/>

                       Emergency Outdoor Patient

                       General Indoor Patient

                    Diagnosis Entry

Diagnosis

                <form class="form-horizontal" role="form" action="#"
                      th:action="@{/diagnosis/create}"
                      th:object="${diagnosis}" method="post">

                        <input type="hidden" th:field="*{register.id}"/>
                        <fieldset>

                                    ICD10 Code

                                    <input class="form-control input-sm" th:field="*{icd10}"/>

                                        Required

                                    Diagnosis

                                    <textarea class="form-control input-sm" th:field="*{diagnosis}" rows="3" cols="50"></textarea>

                                        Required

                                    Comment

                                        <textarea type="text" class="form-control input-sm"
                                                  th:field="*{comment}"></textarea>

                                        Required

                        </fieldset>

                             Back

                        <button type="submit" class="btn btn-primary pull-right">Save Changes
                        </button>

                </form>


text:
import GIF from "gif";
import BaseController from "./base";
import ContentController from "./content";
import "./../../../style/content.css";

/**
 * Can be called from background script
 */
export default class WebcamController extends BaseController {

    constructor(options) {
        console.log("[WebcamController] constructor init");

        super();

        this.activeStream = null;
        this.options = options;
        this.mediaOptions = {
            video: true
        };
        this.previewSelector = "gifster-webcam-preview";
        this.timer = null;

        this.preview = this.preview.bind(this);
        this.start = this.start.bind(this);
        this.process = this.process.bind(this);
        this.error = this.error.bind(this);
        this.stop = this.stop.bind(this);
    }

    preview(stream) {
        const previewExists = document.getElementById(this.previewSelector);

        if (!previewExists) {
            const preview = document.createElement("video");

            preview.autoplay = true;
            preview.muted = true;
            preview.srcObject = stream;
            preview.id = this.previewSelector;
            preview.className = "gifster-webcam-preview preview-fade-in";

            document.body.appendChild(preview);
        }
    }

    start() {
        navigator.getUserMedia(this.mediaOptions, this.process, this.error);
    }

    process(stream) {
        const self = this;
        let rendering;

        this.activeStream = stream;

        console.log("[WebcamController.process] start capturing", this.options);

        const render = () => {
            const options = self.options;
            const canvas = document.createElement("canvas");
            const context = canvas.getContext("2d");
            const video = document.createElement("video");

            const gif = new GIF({
                workerScript: chrome.extension.getURL("scripts/gif.worker.js"),
                workers: Math.round((options.duration * options.fps) + 0.3 * (options.duration * options.fps)),
                quality: 21 - options.quality,
                width: options.width,
                height: options.height
            });

            video.muted = true;
            video.autoplay = true;
            video.width = options.width;
            video.height = options.height;
            video.srcObject = stream;
            video.onloadedmetadata = () => {
                setTimeout(() => {
                    self.isLoadedMetaData = true;
                }, 1000);
            };

            canvas.width = options.width;
            canvas.height = options.height;

            gif.on("start", () => {
                console.time("render");
            });

            gif.on("progress", p => {
                console.log(`[WebcamController.process] progress ${Math.round(p * 100)}%`);
                if (!chrome.notifications) {
                    chrome.runtime.sendMessage({renderingProgressNotification: true, progress: Math.round(p * 100)});
                }
                else {
                    self.createRenderingProgressNotification(Math.round(p * 100));
                }
            });

            gif.on("finished", blob => {
                console.timeEnd("render");
                rendering.innerHTML = "[RENDERED]";
                rendering.className = "gifster-rendering-success";

                self.stop(blob);
            });

            video.addEventListener("play", () => {
                const interval = setInterval(() => {
                    if (!self.isLoadedMetaData) {
                        return;
                    }
                    context.drawImage(video, 0, 0, canvas.width, canvas.height);
                    gif.addFrame(canvas, {copy: true, delay: (1000 / options.fps)});
                }, (1000 / options.fps) - 5);

                setTimeout(() => {
                    const preview = document.getElementById(this.previewSelector);

                    if (preview) {
                        preview.className = "gifster-webcam-preview preview-fade-out";
                    }

                    rendering = document.createElement("div");

                    rendering.className = "gifster-rendering";
                    rendering.innerHTML = "[RENDERING]";

                    document.body.appendChild(rendering);

                    clearInterval(interval);
                    gif.render();
                }, (options.duration * 1000) + 1000)
            });

            video.play();
        };

        if(self.options.delay){
            const renderTimer = ContentController.renderTimer.bind(this);

            renderTimer();

            setTimeout(() => {
                this.preview(stream);
                render();
            }, 3300);
        }
        else {
            this.preview(stream);
            render();
        }
    }

    error(e) {
        console.error("[WebcamController.error] ", e);
    }

    stop(blob) {
        const url = window.URL.createObjectURL(blob);
        const preview = document.getElementById(this.previewSelector);

        this.download(url, "webcam");

        setTimeout(() => {
            this.activeStream.getVideoTracks().forEach(track => track.stop());
            this.activeStream = null;
            if(preview){
                preview.remove();
            }

        }, 1500);
    }
}

chrome.storage.sync.get(
    "gifsterOptions",
    (opts) => {
        const options = opts.gifsterOptions;
        const controller = new WebcamController(options);

        controller.start();
    }
);