text:
redirect_from: /docs/1.0.23/classes/ng1.stateprovider.html
---
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>StateProvider | @uirouter/angularjs</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">
	<link rel="stylesheet" href="../assets/css/uirouter.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					@uirouter/angularjs

						Options

							<input type="checkbox" id="tsd-filter-externals" checked />
							Internal UI-Router API

					Menu

					@uirouter/angularjs

					ng1

					StateProvider

Class StateProvider

The Angular 1 StateProvider

The $stateProvider works similar to Angular's v1 router, but it focuses purely
					on state.

A state corresponds to a "place" in the application in terms of the overall UI and
						navigation. A state describes (via the controller / template / view properties) what
					the UI looks like and does at that place.

States often have things in common, and the primary way of factoring out these
						commonalities in this model is via the state hierarchy, i.e. parent/child states aka
					nested states.

The $stateProvider provides interfaces to declare these states for your app.

Hierarchy

						StateProvider

Index

Constructors

constructor

Properties

state<wbr>Registry

state<wbr>Service

Methods

decorator

on<wbr>Invalid

state

Constructors

new <wbr>State<wbr>Provider(stateRegistry: StateRegistry, stateService: StateService): StateProvider

Parameters

stateRegistry StateRegistry

stateService StateService

Returns StateProvider

Defined in ui-router-angularjs/src/stateProvider.ts:29

Properties

state<wbr>Registry: StateRegistry

Defined in ui-router-angularjs/src/stateProvider.ts:30

state<wbr>Service: StateService

Defined in ui-router-angularjs/src/stateProvider.ts:30

Methods

decorator(name: string, func: BuilderFunction): Function | this | function[]

 Decorates states when they are registered

Decorates states when they are registered

Allows you to extend (carefully) or override (at your own peril) the
									stateBuilder object used internally by StateRegistry.
									This can be used to add custom functionality to ui-router,
								for example inferring templateUrl based on the state name.

When passing only a name, it returns the current (original or decorated) builder
								function that matches name.

The builder functions that can be decorated are listed below. Though not all
								necessarily have a good use case for decoration, that is up to you to decide.

In addition, users can attach custom decorators, which will generate new
									properties within the state's internal definition. There is currently no clear
									use-case for this beyond accessing internal states (i.e. $state.$current),
									however, expect this to become increasingly relevant as we introduce additional
								meta-programming features.

Warning: Decorators should not be interdependent because the order of
									execution of the builder functions in non-deterministic. Builder functions
								should only be dependent on the state definition object and super function.

Existing builder functions and current return values:

parent {object} - returns the parent state object.

data {object} - returns state data, including any inherited data that is not
									overridden by own values (if any).

url {object} - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
									or null.

navigable {object} - returns closest ancestor state that has a URL (aka is
									navigable).

params {object} - returns an array of state params that are ensured to
									be a super-set of parent's params.

views {object} - returns a views object where each key is an absolute view
										name (i.e. "viewName@stateName") and each value is the config object
										(template, controller) for the view. Even when you don't use the views object
										explicitly on a state config, one is still created for you internally.
										So by decorating this builder function you have access to decorating template
									and controller properties.

ownParams {object} - returns an array of params that belong to the state,
									not including any params defined by ancestor states.

path {string} - returns the full path from the root down to this state.
									Needed for state activation.

includes {object} - returns an object that includes every state that
									would pass a $state.includes() test.

Example:

Override the internal 'views' builder with a function that takes the state
								definition, and a reference to the internal function being overridden:

$stateProvider.decorator('views', function (state, parent) {
  let result = {},
      views = parent(state);

  angular.forEach(views, function (config, name) {
    let autoName = (state.name + '.' + name).replace('.', '/');
    config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
    result[name] = config;
  });
  return result;
});

$stateProvider.state('home', {
  views: {
    'contact.list': { controller: 'ListController' },
    'contact.item': { controller: 'ItemController' }
  }
});

// Auto-populates list and item views with /partials/home/contact/list.html,
// and /partials/home/contact/item.html, respectively.
$state.go('home');

Parameters

name string

									:

The name of the builder function to decorate.

func BuilderFunction

									:

A function that is responsible for decorating the original
										builder function. The function receives two parameters:

{object} - state - The state config object.

{object} - super - The original builder function.

Returns Function
									 |
									this
									 |
									function[]

								:
$stateProvider - $stateProvider instance

Defined in ui-router-angularjs/src/stateProvider.ts:123

on<wbr>Invalid(callback: OnInvalidCallback): Function

 Registers an invalid state handler

Registers an invalid state handler

This is a passthrough to StateService.onInvalid for ng1.

Parameters

callback OnInvalidCallback

Returns Function

Defined in ui-router-angularjs/src/stateProvider.ts:277

state(name: string, definition: Ng1StateDeclaration): StateProvider

 Registers a state

state(definition: Ng1StateDeclaration): StateProvider

Registers a state

This is a passthrough to StateRegistry.register.

Registers a state configuration under a given state name.
								The stateConfig object has the following acceptable properties.

template - {string|function=} - html template as a string or a function that returns
											an html template as a string which should be used by the uiView directives. This property
										takes precedence over templateUrl.

If template is a function, it will be called with the following parameters:

{array.<object>} - state parameters extracted from the current $location.path() by
											applying the current state

templateUrl - {string|function=} - path or function that returns a path to an html
										template that should be used by uiView.

If templateUrl is a function, it will be called with the following parameters:

{array.<object>} - state parameters extracted from the current $location.path() by
											applying the current state

templateProvider - {function=} - Provider function that returns HTML content
									string.

controller - {string|function=} -  Controller fn that should be associated with newly
									related scope or the name of a registered controller if passed as a string.

controllerProvider - {function=} - Injectable provider function that returns
									the actual controller or string.

controllerAs – {string=} – A controller alias name. If present the controller will be
									published to scope under the controllerAs name.

resolve - {object.<string, function>=} - An optional map of dependencies which
											should be injected into the controller. If any of these dependencies are promises,
											the router will wait for them all to be resolved or one to be rejected before the
											controller is instantiated. If all the promises are resolved successfully, the values
											of the resolved promises are injected and $stateChangeSuccess event is fired. If any
										of the promises are rejected the $stateChangeError event is fired. The map object is:

key - {string}: name of dependency to be injected into controller

factory - {string|function}: If string then it is alias for service. Otherwise if function,
												it is injected and return value it treated as dependency. If result is a promise, it is
											resolved before its value is injected into controller.

url - {string=} - A url with optional parameters. When a state is navigated or
										transitioned to, the $stateParams service will be populated with any
									parameters that were passed.

params - {object=} - An array of parameter names or regular expressions. Only
										use this within a state if you are not using url. Otherwise you can specify your
										parameters within the url. When a state is navigated or transitioned to, the
									$stateParams service will be populated with any parameters that were passed.

views - {object=} - Use the views property to set up multiple views or to target views
									manually/explicitly.

abstract - {boolean=} - An abstract state will never be directly activated,
									but can provide inherited properties to its common children states.

onEnter - {object=} - Callback function for when a state is entered. Good way
										to trigger an action or dispatch an event, such as opening a dialog.
									If minifying your scripts, make sure to use the ['injection1', 'injection2', function(injection1, injection2){}] syntax.

onExit - {object=} - Callback function for when a state is exited. Good way to
										trigger an action or dispatch an event, such as opening a dialog.
									If minifying your scripts, make sure to use the ['injection1', 'injection2', function(injection1, injection2){}] syntax.

reloadOnSearch = true - {boolean=} - If false, will not retrigger the same state
										just because a search/query parameter has changed (via $location.search() or $location.hash()).
									Useful for when you'd like to modify $location.search() without triggering a reload.

data - {object=} - Arbitrary data object, useful for custom configuration.

Example:

Some state name examples

// stateName can be a single top-level name (must be unique).
$stateProvider.state("home", {});

// Or it can be a nested state name. This state is a child of the
// above "home" state.
$stateProvider.state("home.newest", {});

// Nest states as deeply as needed.
$stateProvider.state("home.newest.abc.xyz.inception", {});

// state() returns $stateProvider, so you can chain state declarations.
$stateProvider
  .state("home", {})
  .state("about", {})
  .state("contacts", {});

Parameters

name string

									:

A unique state name, e.g. "home", "about", "contacts".
										To create a parent/child state use a dot, e.g. "about.sales", "home.newest".

definition Ng1StateDeclaration

									:

State configuration object.

Returns StateProvider

Defined in ui-router-angularjs/src/stateProvider.ts:259

Parameters

definition Ng1StateDeclaration

Returns StateProvider

Defined in ui-router-angularjs/src/stateProvider.ts:260

						@uirouter/angularjs

						Public API

						common

						core

						directives

						injectables

						ng1

								"@uirouter/core/lib/router"

								"@uirouter/core/lib/state/state<wbr>Registry"

						ng1_<wbr>state_<wbr>events

						params

						resolve

						state

						transition

						url

						view

						Internal UI-<wbr><wbr>Router API

						"ui-<wbr>router-<wbr>core/src/common/trace"

						common_<wbr>hof

						common_<wbr>predicates

						common_<wbr>strings

						hooks

						path

						vanilla

						Ng1<wbr>Location<wbr>Services

						Ng1<wbr>View<wbr>Config

						State<wbr>Provider

								constructor

								state<wbr>Registry

								state<wbr>Service

								decorator

								on<wbr>Invalid

								state

						Ng1<wbr>Controller

						Ng1<wbr>State<wbr>Declaration

						Ng1<wbr>State<wbr>Transition<wbr>Hook

						Ng1<wbr>View<wbr>Declaration

						Template<wbr>Factory<wbr>Provider

						UIView<wbr>Scroll<wbr>Provider

						_<wbr>Ng1<wbr>State<wbr>Declaration

						mod_<wbr>cmpt

						mod_<wbr>init

						mod_<wbr>main

						mod_<wbr>rtr

						mod_<wbr>state

						mod_<wbr>util

						router

						$<wbr>Included<wbr>ByState<wbr>Filter

						$<wbr>IsState<wbr>Filter

						$ui<wbr>Router<wbr>Provider

						get<wbr>Ng1<wbr>View<wbr>Config<wbr>Factory

						get<wbr>Provider<wbr>For

						get<wbr>State<wbr>Hook<wbr>Builder

						get<wbr>State<wbr>Provider

						get<wbr>Url<wbr>Router<wbr>Provider

						has<wbr>Any<wbr>Key

						ng1<wbr>Views<wbr>Builder

						run<wbr>Block

						watch<wbr>Digests

						$resolve

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
class Importer
  attr_reader :errors, :slots

  def initialize(data)
    @data = data
    @run = false
    @errors = false
    @slots = []
  end

  def valid?
    build unless @run
    !errors
  end

  def save
    return unless valid?

    slots.each do |slot|
      slot.save
    end
  end

  private
  def build
    @data.each do |slot_data|
      slot = Slot.new(slot_hash(slot_data))
      @slots << slot
      @errors = true if !slot.valid?
    end
    @run = true
  end

  def slot_hash(data)
    {
      from: data[:from],
      to: data[:to],
      formation_type: data[:formation_type],
      formation_size: data[:formation_size],
      formation_quantity: data[:formation_quantity],
    }
  end
end

redpajama_set_name: RedPajamaGithub


text:
//
// Created by byter on 11/17/17.
//

#ifndef THREEPP_TYPES_H
#define THREEPP_TYPES_H

#include <string>
#include <vector>
#include <array>
#include <memory>
#include <unordered_map>
#include <type_traits>
#include <threepp/math/Vector2.h>
#include <threepp/math/Vector3.h>

namespace three {

using byte = unsigned char;

template <typename T>
class optional {
  T _t;
  bool _isSet;

public:
  optional() : _isSet(false) {}

  template <typename F>
  optional(F&& f) : _t(f), _isSet(true) {}

  template <typename F>
  optional &operator =(F&& f) {
    _t = f;
    _isSet = true;
    return *this;
  }

  const T &get() const {
    return _t;
  }

  operator const T &() const {
    return _t;
  }

  bool isSet() {return _isSet;}
};

struct Mipmap {
  std::vector<unsigned char> data;
  int width, height;
};

class TextureData
{
protected:
  std::vector<Mipmap> _mipmaps;

  size_t _width = 0;
  size_t _height = 0;

  TextureData(size_t width, size_t height) : _width(width), _height(height) {}
  TextureData() = default;

public:
  using Ptr = std::shared_ptr<TextureData>;

  size_t width() const {return _width;}
  size_t height() const {return _height;}

  const std::vector<Mipmap> &mipmaps() const {return _mipmaps;}
  const Mipmap &mipmap(unsigned index) const {return _mipmaps.at(index);}

  virtual const byte *bytes() const = 0;
};

template <typename T>
class TextureDataT : public TextureData
{
  std::vector<T> _data;

  TextureDataT(const std::vector<T> &data, size_t width, size_t height)
     : TextureData(width, height), _data(data) {}

  TextureDataT(size_t width, size_t height, bool resize=false)
     : TextureData(width, height)
  {
    if(resize) _data.resize(width * height);
  }

  TextureDataT() = default;
public:
  static Ptr make(const std::vector<T> &data, size_t width, size_t height) {
    return Ptr(new TextureDataT(data, width, height));
  }

  static Ptr make(size_t width, size_t height) {
    return Ptr(new TextureDataT(width, height));
  }

  const byte *bytes() const override {
    return (byte *)_data.data();
  }
};

class Layers
{
  unsigned int mask = 1;

public:

  void set(unsigned int channel) {
    mask = (unsigned)1 << channel;
  }

  void enable(unsigned int channel) {
    mask |= 1 << channel;
  }

  void toggle(unsigned int channel) {
    mask ^= 1 << channel;
  }

  void disable(unsigned int channel) {
    mask &= ~(1 << channel);
  }

  bool test(const Layers &layers) const {
    return (mask & layers.mask) != 0;
  }
};

struct Group {
  size_t start;
  size_t count;
  size_t materialIndex;

  Group(size_t start, size_t count, size_t materialIndex)
     : start(start), count(count), materialIndex(materialIndex) {}

  Group() : start(0), count(0), materialIndex(0) {}
};

class UV : public math::Vector2
{
public:

  UV(float u = 0, float v = 0) : math::Vector2( u, v ) { }
  UV( const UV& uv ) : math::Vector2(uv) {}

  UV& lerpSelf( const UV& uv, float alpha )
  {
    _x += ( uv._x - _x ) * alpha;
    _y += ( uv._y - _y ) * alpha;

    return *this;
  }

  float &u() {return _x;}
  float &v() {return _y;}

  const float u() const {return _x;}
  const float v() const {return _y;}
};

using UV_Array = std::array<UV, 3>;

struct UpdateRange
{
  size_t start;
  size_t count;

  UpdateRange(size_t offset=0, size_t count=std::numeric_limits<size_t>::max())
    : start(offset), count(count) {}
};

template <class T>
inline void hash_combine(std::size_t & seed, const T & v)
{
  std::hash<T> hasher;
  seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}

/**
 * use this as hash functor for enum-key maps, or use the unordered_map further below
 */
struct EnumHash
{
  template <typename EnumT>
  typename std::underlying_type<EnumT>::type operator()(EnumT t) const
  {
    return static_cast<typename std::underlying_type<EnumT>::type>(t);
  }
};

/**
 * if your compiler doesn't accept enums as keys, you may try this..
 */
template <typename EnumT, typename ValueT>
using enum_map = std::unordered_map<EnumT, ValueT, EnumHash>;

struct no_delete
{
  template <typename T>
  void operator () (const T *o) const {}
};
extern no_delete DLX _no_delete;

} // namespace three

#endif //THREEPP_TYPES_H


text:
package jExif.metadata;

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

/** Recording format for pixel components */
public enum PlanarConfiguration {

    /** Chunky format */
    CHUNKY(1),

    /** Planar format */
    PLANAR(2);

    /** Mapping between field values and enumeration constants */
    private static final Map<Integer,PlanarConfiguration> valueMap = createValueMap();

    /**
     * Creates the mapping between field values and enumeration constants
     *
     * @return an unmodifiable map that resolves field values to enumeration constants
     */
    private static final Map<Integer,PlanarConfiguration> createValueMap() {
        PlanarConfiguration[] values = values();
        Map<Integer,PlanarConfiguration> map = new HashMap<>(values.length);

        for (PlanarConfiguration value : values) {
            map.put(value.fieldValue, value);
        }

        return Collections.unmodifiableMap(map);
    }

    /**
     * Retrieves the enumeration constant matching the specified field value
     *
     * @param fieldValue - the field value to use for look-up
     * @return the associated enumeration constant or null if the field value is unknown
     */
    public static PlanarConfiguration get(int fieldValue) {
        return valueMap.get(fieldValue);
    }

    /** The field value */
    private final int fieldValue;

    /**
     * Constructor
     *
     * @param fieldValue - the associated field value
     */
    private PlanarConfiguration(int fieldValue) {
        this.fieldValue = fieldValue;
    }

}


text:
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Test.QuickCheck.Regex.PCRE.Types.RegexCharacter (RegexCharacter (..)) where

import Data.Data
import GHC.Generics
import Test.QuickCheck
import Test.QuickCheck.Regex.Exemplify
import Test.QuickCheck.Regex.PCRE.RegexRenderer
import Test.QuickCheck.Regex.PCRE.Types.Metacharacters
import {-# SOURCE #-} Test.QuickCheck.Regex.PCRE.Types.Quantifiable

data RegexCharacter
  = Quant Quantifiable
  | Meta Metacharacter
  | Quoted String
  deriving (Data, Eq, Generic, Show)

instance Arbitrary RegexCharacter where
  arbitrary =
    oneof
      [ Quant <$> arbitrary,
        Meta <$> arbitrary
      ]
  shrink = genericShrink

instance Exemplify [RegexCharacter] where
  examples = fmap concat . traverse examples

instance Exemplify RegexCharacter where
  examples (Quant q) = examples q
  examples (Meta m) = examples m
  examples (Quoted s) = pure s

instance RegexRenderer RegexCharacter where
  render (Quant q) = render q
  render (Meta m) = render m
  render (Quoted s) = s

instance RegexRenderer [RegexCharacter] where
  render chars = concatMap render chars


text:
void LogDebug(LPCTSTR msg, LPCTSTR category)
{
   CString text;
   text.Format(_T("[%s] %s\n"), category, msg);

   OutputDebugString(text);
}

FILE* s_logfile = NULL;

void LogInfo(LPCTSTR msg, LPCTSTR category)
{
   LogDebug(msg, category);

   if (s_logfile == NULL)
      s_logfile = fopen("\\Recorder.txt", "w");

   fprintf(s_logfile, "[%ls] %ls\n", category, msg);
   fflush(s_logfile);
}


text:
 package com.indeed.iupload.core.authentification;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author akira
 */
public interface UserPermissionConfigLoader {
    public InputStream getConfigJsonStream() throws IOException;
}


text:
package org.ohdsi.jCdmBuilder.utilities;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.ohdsi.utilities.RandomUtilities;
import org.ohdsi.utilities.StringUtilities;
import org.ohdsi.utilities.collections.OneToManyList;
import org.ohdsi.utilities.files.ReadTextFile;
import org.ohdsi.utilities.files.Row;
import org.ohdsi.utilities.files.WriteTextFile;

/**
 * Checks a CSV file for formatting issues
 *
 * @author MSCHUEMI
 */
public class CSVFileChecker {

	private static char			delimiter				= ',';
	private static int			bufferSize				= 10000;
	private static int			sampleSize				= 1000;
	private static double		minFractionDateCorrect	= 0.95;
	private int					columnCount;
	private String				filename;
	private List<LineError>		errors;
	private List<ColumnInfo>	columnInfos;
	private JFrame				frame;
	private List<String>		header;

	public void checkFile(String filename) {
		checkFile(filename, null);
	}

	private void checkFile(String filename, List<ColumnInfo> columnInfos) {
		this.columnInfos = columnInfos;
		this.filename = filename;
		errors = new ArrayList<LineError>();
		int lineNr = 0;
		List<List<String>> rowBuffer = new ArrayList<List<String>>();
		for (String line : new ReadTextFile(filename)) {
			lineNr++;
			List<String> row = StringUtilities.safeSplit(line, delimiter);

			if (lineNr == 1) { // header
				columnCount = row.size();
				if (columnInfos == null)
					header = row;
				else
					for (ColumnInfo info : columnInfos) {
						int column = row.indexOf(info.header);
						if (column == -1)
							throw new RuntimeException("Could not find column " + info.header + " in table " + filename);
						else
							info.column = column;
					}
			} else {
				if (columnInfos == null) {
					if (rowBuffer.size() < bufferSize)
						rowBuffer.add(row);
					else {
						profile(rowBuffer);
						rowBuffer = null;
					}
				} else
					checkRow(lineNr, row);
			}
		}
		if (columnInfos == null && rowBuffer.size() > 1)
			profile(rowBuffer);

		if (errors.size() != 0)
			if (frame != null) {
				showDialog();
			} else
				reportToConsole();
	}

	private void checkRow(int lineNr, List<String> row) {
		if (row.size() != columnCount) {
			errors.add(new LineError(lineNr, "Incorrect number of columns (expected " + columnCount + ", found " + row.size() + ")"));
		} else {
			for (ColumnInfo info : columnInfos) {
				String value = row.get(info.column);
				if (value.trim().length() != 0) {
					if (info.isInteger && !StringUtilities.isInteger(value))
						errors.add(new LineError(lineNr, "Found non-integer value ('" + value + "') where integer value expected in column "
								+ (info.column + 1) + " (" + info.header + ")"));
					else if (info.isDateFormat1 && !isDateFormat1(value))
						errors.add(new LineError(lineNr, "Error in date ('" + value + "') in column " + (info.column + 1) + " (" + info.header + ")"));
					else if (info.isReal && !StringUtilities.isNumber(value))
						errors.add(new LineError(lineNr, "Error in real number ('" + value + "') in column " + (info.column + 1) + " (" + info.header + ")"));
				}
			}
		}
	}

	private void showDialog() {
		if (new ErrorDialog(frame, true, null).getAnswer()) {
			String backupName = createBackup();
			copyWithoutErrorLines(backupName, filename);
		}
	}

	private void copyWithoutErrorLines(String source, String target) {
		Set<Integer> errorLineNrs = new HashSet<Integer>();
		for (LineError error : errors)
			errorLineNrs.add(error.lineNr);

		WriteTextFile out = new WriteTextFile(target);
		int lineNr = 0;
		for (String line : new ReadTextFile(source)) {
			lineNr++;
			if (!errorLineNrs.contains(lineNr))
				out.writeln(line);
		}
		out.close();
		System.out.println("Removed " + errorLineNrs.size() + " lines from " + target);
	}

	private String createBackup() {
		String filenameWithoutExtention = filename.substring(0, filename.lastIndexOf('.'));

		String backupName = filenameWithoutExtention + ".backup";
		if (new File(backupName).exists()) {
			int i = 1;
			while (new File(filenameWithoutExtention + ".backup" + i).exists())
				i++;
			backupName = filenameWithoutExtention + ".backup" + i;
		}

		WriteTextFile out = new WriteTextFile(backupName);
		for (String line : new ReadTextFile(filename))
			out.writeln(line);
		out.close();
		System.out.println("Backed up " + filename + " to " + backupName);
		return backupName;
	}

	private class ErrorDialog extends JDialog implements ActionListener {
		private static final long	serialVersionUID	= 4440825466397612738L;
		private JButton				yesButton			= null;
		private JButton				noButton			= null;
		private boolean				answer				= false;

		public boolean getAnswer() {
			return answer;
		}

		public ErrorDialog(JFrame frame, boolean modal, String dummy) {
			super(frame, modal);
			String shortFilename = new File(filename).getName();
			setTitle("Errors found in " + shortFilename);
			JPanel panel = new JPanel();
			panel.setPreferredSize(new Dimension(800, 500));
			getContentPane().add(panel);
			panel.setLayout(new BorderLayout());

			JLabel message = new JLabel("Found " + errors.size() + " errors in " + shortFilename
					+ ". Do you want to automatically remove these lines (a backup will be created)?");
			panel.add(message, BorderLayout.NORTH);

			StringBuilder errorText = new StringBuilder();
			for (LineError error : errors)
				errorText.append(error + "\n");
			JTextArea errorArea = new JTextArea(errorText.toString());
			JScrollPane scrollPane = new JScrollPane(errorArea);
			panel.add(scrollPane, BorderLayout.CENTER);

			JPanel buttonPanel = new JPanel();
			yesButton = new JButton("Yes");
			yesButton.addActionListener(this);
			buttonPanel.add(yesButton);
			noButton = new JButton("No");
			noButton.addActionListener(this);
			buttonPanel.add(noButton);
			panel.add(buttonPanel, BorderLayout.SOUTH);

			pack();
			setLocationRelativeTo(frame);
			setVisible(true);
		}

		public void actionPerformed(ActionEvent e) {
			if (yesButton == e.getSource()) {
				answer = true;
				setVisible(false);
			} else if (noButton == e.getSource()) {
				answer = false;
				setVisible(false);
			}
		}

	}

	private void reportToConsole() {
		for (LineError error : errors)
			System.out.println(error);
	}

	private void profile(List<List<String>> rows) {
		columnInfos = new ArrayList<ColumnInfo>(columnCount);
		for (int i = 0; i < header.size(); i++)
			columnInfos.add(new ColumnInfo(i, header.get(i)));

		for (List<String> row : RandomUtilities.sampleWithoutReplacement(new ArrayList<List<String>>(rows), sampleSize)) {
			if (row.size() == columnCount) {
				for (ColumnInfo info : columnInfos) {
					String value = row.get(info.column);
					if (value.trim().length() != 0) {
						if (StringUtilities.isInteger(value))
							info.nNotDateFormat1++;
						else {
							info.isInteger = false;
							if (isDateFormat1(value)) {
								info.nDateFormat1++;
								info.isReal = false;
							} else {
								info.nNotDateFormat1++;
								if (!StringUtilities.isNumber(value))
									info.isReal = false;
							}
						}
					}
				}
			}
		}
		for (ColumnInfo columnInfo : columnInfos)
			if (columnInfo.nDateFormat1 > 0
					&& (columnInfo.nDateFormat1 / (double) (columnInfo.nDateFormat1 + columnInfo.nNotDateFormat1) > minFractionDateCorrect))
				columnInfo.isDateFormat1 = true;

		// for (int i = 0; i < columnInfos.size(); i++)
		// System.out.println("Column " + columnInfos.get(i).header + "(" + i + "): IsInteger=" + columnInfos.get(i).isInteger + ", IsDate="
		// + columnInfos.get(i).isDateFormat1);

		int lineNr = 1; // Skipping header, so start at 1
		for (List<String> row : rows) {
			lineNr++;
			checkRow(lineNr, row);
		}
	}

	public static boolean isDateFormat1(String string) {
		if (string.length() >= 10)
			if ((string.charAt(4) == '-' || string.charAt(4) == '/') || (string.charAt(4) == string.charAt(7)))
				try {
					int year = Integer.parseInt(string.substring(0, 4));
					if (year < 1700 || year > 3000)
						return false;
					int month = Integer.parseInt(string.substring(5, 7));
					if (month < 1 || month > 12)
						return false;
					int day = Integer.parseInt(string.substring(8, 10));
					if (day < 1 || day > 31)
						return false;
					return true;
				} catch (Exception e) {
					return false;
				}
		return false;
	}

	public JFrame getFrame() {
		return frame;
	}

	public void setFrame(JFrame frame) {
		this.frame = frame;
	}

	private class LineError {
		public int		lineNr;
		public String	error;

		public LineError(int lineNr, String error) {
			this.lineNr = lineNr;
			this.error = error;
		}

		public String toString() {
			return "Error in line " + lineNr + ": " + error;
		}
	}

	private class ColumnInfo {
		public ColumnInfo() {
		}

		public ColumnInfo(int column, String header) {
			this.header = header;
			this.column = column;
		}

		public int		column;
		public String	header;
		public int		nDateFormat1	= 0;
		public int		nNotDateFormat1	= 0;
		public boolean	isDateFormat1	= false;	// yyyy-mm-dd
		public boolean	isInteger		= true;
		public boolean	isReal			= true;
	}

	public void checkSpecifiedFields(String folder, Iterator<Row> iterator) {
		OneToManyList<String, Row> tableToFields = new OneToManyList<String, Row>();
		while (iterator.hasNext()) {
			Row row = iterator.next();
			if (row.get("Table").trim().length() != 0)
				tableToFields.put(row.get("Table"), row);
		}
		for (String table : tableToFields.keySet()) {
			System.out.println("Checking " + table);
			List<ColumnInfo> columnInfos = new ArrayList<ColumnInfo>();
			for (Row row : tableToFields.get(table))
				if (row.get("Check").equals("1")) {
					ColumnInfo info = new ColumnInfo();
					info.header = row.get("Field");
					if (row.get("Type").toLowerCase().equals("integer")) {
						info.isInteger = true;
						info.isDateFormat1 = false;
						info.isReal = false;
					} else if (row.get("Type").toLowerCase().equals("real")) {
						info.isInteger = false;
						info.isDateFormat1 = false;
						info.isReal = true;
					} else if (row.get("Type").toLowerCase().equals("date")) {
						info.isInteger = false;
						info.isDateFormat1 = true;
						info.isReal = false;
					} else {
						info.isInteger = false;
						info.isDateFormat1 = false;
						info.isReal = false;
					}
					columnInfos.add(info);
				}
			checkFile(folder + "/" + table, columnInfos);
		}
	}
}


text:
package com.example.doun.chapter21concurrency;

/**
 * Created by Doun on 2017/9/3.
 */

class RunAndYield implements Runnable{

    private static int taskCount = 0;
    private final int id = taskCount++;

    public RunAndYield() {
        System.out.println(id+" created");

    }

    @Override
    public void run() {
        System.out.println(id+" yield one");
        Thread.yield();
        System.out.println(id+" yield two");
        Thread.yield();
        System.out.println(id+" yield three");
        Thread.yield();

        System.out.println(id+" end");

    }
}
public class Exercise1 {
    public static void main(String[] args) {
        for (int i=0;i<10; i++){
            new Thread(new RunAndYield()).start();
        }
    }
}


text:
namespace Html2Markdown.Replacement
{
	internal interface IReplacer
	{
		string Replace(string html);
	}
}


text:
local mod	= DBM:NewMod(817, "DBM-ThroneofThunder", nil, 362)
local L		= mod:GetLocalizedStrings()
--BH ADD
local sndWOP	= mod:SoundMM("SoundWOP")

mod:SetRevision(("$Revision: 11365 $"):sub(12, -3))
mod:SetCreatureID(68078, 68079, 68080, 68081)--Ro'shak 68079, Quet'zal 68080, Dam'ren 68081, Iron Qon 68078
mod:SetEncounterID(1559)
mod:SetMainBossID(68078)
mod:SetZone()
mod:SetUsedIcons(8)

mod:RegisterCombat("combat")

mod:RegisterEventsInCombat(
	"SPELL_AURA_APPLIED",
	"SPELL_AURA_APPLIED_DOSE",
	"SPELL_AURA_REMOVED",
	"SPELL_CAST_SUCCESS",
	--BH ADD
	"UNIT_POWER",
	"SPELL_SUMMON",
	"SPELL_DAMAGE",
	"SPELL_MISSED",
	"UNIT_SPELLCAST_SUCCEEDED boss1 boss2 boss3 boss4",
	"UNIT_DIED"
)

local warnImpale						= mod:NewStackAnnounce(134691, 2, nil, mod:IsTank() or mod:IsHealer())
local warnThrowSpear					= mod:NewTargetAnnounce(134926, 3)--Target scanning does not work for this.
local warnPhase1						= mod:NewPhaseAnnounce(1)
local warnMoltenInferno					= mod:NewSpellAnnounce(134664, 2, nil, false)--highly variables cd, also can be spammy. disbled by default.
local warnUnleashedFlame				= mod:NewSpellAnnounce(134611, 3, nil, false)--Spammy and unnesssary. Every 6 seconds is too often for a non important warning. people can turn it on if they want.
local warnMoltenOverload				= mod:NewSpellAnnounce(137221, 4)
local warnWhirlingWinds					= mod:NewSpellAnnounce(139167, 3)--Heroic Phase 1
local warnPhase2						= mod:NewPhaseAnnounce(2)
local warnWindStorm						= mod:NewSpellAnnounce(136577, 4)
local warnWindStormEnd					= mod:NewEndAnnounce(136577, 4)
local warnLightningStorm				= mod:NewTargetAnnounce(136192, 3)
local warnFrostSpike					= mod:NewSpellAnnounce(139180, 3)--Heroic Phase 2
local warnPhase3						= mod:NewPhaseAnnounce(3)
local warnDeadZone						= mod:NewAnnounce("warnDeadZone", 3, 137229)
local warnFreeze						= mod:NewTargetAnnounce(135145, 3, nil, false)--Spammy, more of a duh type warning I think
local warnPhase4						= mod:NewPhaseAnnounce(4)
local warnRisingAnger					= mod:NewStackAnnounce(136323, 2, nil, false)
local warnFistSmash						= mod:NewCountAnnounce(136146, 3)

local specWarnImpale					= mod:NewSpecialWarningStack(134691, mod:IsTank(), 2)
local specWarnImpaleOther				= mod:NewSpecialWarningTarget(134691, mod:IsTank())
local specWarnThrowSpear				= mod:NewSpecialWarningSpell(134926, nil, nil, nil, 2)
local specWarnThrowSpearYou				= mod:NewSpecialWarningYou(134926)
local specWarnThrowSpearNear			= mod:NewSpecialWarningClose(134926)
local yellThrowSpear					= mod:NewYell(134926)
local specWarnScorched					= mod:NewSpecialWarningStack(134647, false, 3)--We do a 4 and 2 strat (4 melee 2 ranged). 3 is not an everyone strat.
local specWarnBurningCinders			= mod:NewSpecialWarningMove(137668)
local specWarnMoltenOverload			= mod:NewSpecialWarningSpell(137221, nil, nil, nil, 2)
local specWarnWindStorm					= mod:NewSpecialWarningSpell(136577, nil, nil, nil, 2)
local specWarnStormCloud				= mod:NewSpecialWarningMove(137669)
local specWarnLightningStorm			= mod:NewSpecialWarningYou(136192)
local yellLightningStorm				= mod:NewYell(136192)
local specWarnFrozenBlood				= mod:NewSpecialWarningMove(136520)
local specWarnFistSmash					= mod:NewSpecialWarningCount(136146, nil, nil, nil, 2)
--BH ADD
local specWarnJSA						= mod:NewSpecialWarning("SpecWarnJSA")

local timerImpale						= mod:NewTargetTimer(40, 134691, mod:IsTank() or mod:IsHealer())
local timerImpaleCD						= mod:NewCDTimer(20, 134691, mod:IsTank() or mod:IsHealer())
local timerThrowSpearCD					= mod:NewCDTimer(30, 134926)--30-42 second variation observed
local timerUnleashedFlameCD				= mod:NewCDTimer(6, 134611, nil, false)--CD for the periodic trigger, not when he'll actually be at 30 energy and use it.
local timerScorched						= mod:NewBuffFadesTimer(30, 134647)
local timerMoltenOverload				= mod:NewBuffActiveTimer(10, 137221)
local timerLightningStormCD				= mod:NewCDTimer(20, 136192)
local timerWindStorm					= mod:NewBuffActiveTimer(19.8, 136577)--19.8~21.7sec variables
local timerWindStormCD					= mod:NewNextTimer(70, 136577)
local timerFreezeCD						= mod:NewCDTimer(7, 135145, nil, false)
local timerDeadZoneCD					= mod:NewCDTimer(15, 137229)
local timerRisingAngerCD				= mod:NewNextTimer(15, 136323, nil, false)
local timerFistSmash					= mod:NewBuffActiveTimer(8, 136146)
local timerFistSmashCD					= mod:NewNextCountTimer(20, 136146)
local timerWhirlingWindsCD				= mod:NewCDTimer(30, 139167)--Heroic Phase 1
local timerFrostSpikeCD					= mod:NewCDTimer(11, 139180)--Heroic Phase 2

local berserkTimer						= mod:NewBerserkTimer(720)

mod:AddBoolOption("SetIconOnLightningStorm")

-- BH ADD
local Warned = false
local stormcount = 0
local lightmaker = {}
local FireMarkers={}

local morestack = 0

mod:AddBoolOption("ReapetAP", true, "sound")
mod:AddBoolOption("SoundARAT", mod:IsDps(), "sound")
mod:AddBoolOption("HudMAP", true, "sound")
mod:AddBoolOption("HudLight", false, "sound")

-- BH ADD END
mod:AddBoolOption("RangeFrame", true)--One tooltip says 8 yards, other says 10. Confirmed it's 10 during testing though. Ignore the 8 on spellid 134611
mod:AddBoolOption("InfoFrame")

local Roshak = select(2, EJ_GetCreatureInfo(2, 817))
local Quetzal = select(2, EJ_GetCreatureInfo(3, 817))
local Damren = select(2, EJ_GetCreatureInfo(4, 817))
local arcingName = GetSpellInfo(136193)
local phase = 1--Not sure this is useful yet, coding it in, in case spear cd is different in different phases
local fistSmashCount = 0
--Spear/arcing methods called VERY often, so cache these globals locally
local UnitDetailedThreatSituation = UnitDetailedThreatSituation
local UnitExists = UnitExists
local UnitClass = UnitClass
local UnitDebuff = UnitDebuff

local function updateHealthFrame()
	if DBM.BossHealth:IsShown() then
		DBM.BossHealth:Clear()
		if phase == 1 then
			DBM.BossHealth:AddBoss(68079, Roshak)
		elseif phase == 2 then
			DBM.BossHealth:AddBoss(68080, Quetzal)
		elseif phase == 3 then
			DBM.BossHealth:AddBoss(68081, Damren)
		elseif phase == 4 then
			DBM.BossHealth:AddBoss(68078, L.name)
			if mod:IsDifficulty("heroic10", "heroic25") then
				DBM.BossHealth:AddBoss(68081, Damren)
				DBM.BossHealth:AddBoss(68080, Quetzal)
				DBM.BossHealth:AddBoss(68079, Roshak)
			end
		end
	end
end

--Custom, don't use IsTanking prototype here
local function notEligable(unit)
	-- 1. check blizzard tanks first
	-- 2. check blizzard roles second
	-- 3. check boss' highest threat target
	-- 4. Check monks
	if GetPartyAssignment("MAINTANK", unit, 1) then
		return true
	end
	if UnitGroupRolesAssigned(unit) == "TANK" then
		return true
	end
	if UnitDetailedThreatSituation(unit, "boss1") then
		return true
	end
	if UnitExists("boss2target") and UnitDetailedThreatSituation(unit, "boss2") then
		return true
	end
	--He CAN spear monks that are not in melee (I seen our mistweaver get many spears at ranged).
	--However, if he targets a monk that IS in melee, he switches to a different target (again, i've seen him target our mistweaver in melee range, then instantly switched to ANOTHER target because the mistweaver was in melee).
	--We assume any monk within 15 yards of tank is in melee range, may be wrong once in a blue moon.
	--Should fairly accurately allow the mod to announce spears on monks outside melee range while ignoring monk targets in melee range
	if (select(2, UnitClass(unit)) == "MONK") and (DBM.RangeCheck:GetDistance(unit, "boss2target") <= 15) then
		return true
	end
	return false
end

--Spear target happens BEFORE cast, so we have to pre schedule scan it to grab target
--This will fail if the spear target actually IS his highest threat
--In that case the aoe failsafe warning will just be used, so 1/10 or 1/25 odds in phase 1.
local function checkSpear()
	if UnitExists("boss1target") and not notEligable("boss1target") then--Boss 1 is looking at someone that isn't his highest threat or a tank (have to filter tanks cause he looks at them to cast impale, have to filter his highest threat in case it's not a tank, ie a healer)
		mod:Unschedule(checkSpear)
		local targetname = DBM:GetUnitFullName("boss1target")
		warnThrowSpear:Show(targetname)
		if UnitIsUnit("boss1target", "player") then--you are spear target
			specWarnThrowSpearYou:Show()
			yellThrowSpear:Yell()
		else--Not spear target
			local inRange = DBM.RangeCheck:GetDistance("player", "boss1target")
			if inRange and inRange < 10 then
				specWarnThrowSpearNear:Show(targetname)--Near spear target
			elseif mod:AntiSpam(15, 6) then--Smart way to do a failsafe in case we never get a valid target
				specWarnThrowSpear:Show()--not spear target or near spear target, generic aoe warning (for the lines and stuff)
			end
		end
	else
		mod:Schedule(0.25, checkSpear)
	end
end

local function checkArcing()
	local arcingDebuffs = 0
	for uId in DBM:GetGroupMembers() do
		if UnitDebuff(uId, arcingName) then
			arcingDebuffs = arcingDebuffs + 1
		end
	end
	if arcingDebuffs == 0 then
		mod:Unschedule(checkArcing)
		if mod.Options.RangeFrame then
			DBM.RangeCheck:Hide()
		end
		if mod.Options.InfoFrame then
			DBM.InfoFrame:Hide()
		end
	else
		mod:Schedule(5, checkArcing)
	end
end
-- BH ADD
for i = 1, 7 do
	mod:AddBoolOption("dr"..i, false, "sound")
end

mod:AddBoolOption("dispsetLight", true, "sound")

local function MyJS()
	if (mod.Options.dr1 and fistSmashCount == 1) or (mod.Options.dr2 and fistSmashCount == 2) or (mod.Options.dr3 and fistSmashCount == 3) or (mod.Options.dr4 and fistSmashCount == 4) or (mod.Options.dr5 and fistSmashCount == 5) or (mod.Options.dr6 and fistSmashCount == 6) or (mod.Options.dr7 and fistSmashCount == 7) then
		return true
	end
	return false
end

local DBMHudMap = DBMHudMap
local free = DBMHudMap.free
local function register(e)
	DBMHudMap:RegisterEncounterMarker(e)
	return e
end
function mod:checkmydebuff()
    if UnitDebuff("player", GetSpellInfo(136192)) then
		SendChatMessage(L.Helpme, "SAY")
		self:ScheduleMethod(4, "checkmydebuff")
	end
end
local function fixdebuffremovebug(checkplayer)
    if UnitDebuff(checkplayer, GetSpellInfo(136192)) then
		mod:Schedule(2, function()
			fixdebuffremovebug(checkplayer)
		end)
	else
		if lightmaker[checkplayer] then
			lightmaker[checkplayer] = free(lightmaker[checkplayer])
		end
	end
end

local function fixdebuffremovebug2(checkplayer)
    if UnitDebuff(checkplayer, GetSpellInfo(136193)) then
		mod:Schedule(2, function()
			fixdebuffremovebug2(checkplayer)
		end)
	else
		if FireMarkers[checkplayer] then
			FireMarkers[checkplayer] = free(FireMarkers[checkplayer])
		end
	end
end
-- BH ADD END

function mod:OnCombatStart(delay)
	phase = 1
	fistSmashCount = 0
	morestack = 0
	updateHealthFrame()
	warnPhase1:Show()
	--BH ADD
	Warned = false
	stormcount = 0
	table.wipe(lightmaker)
	table.wipe(FireMarkers)
	sndWOP:Play("ex_tt_hyxt") --火焰形态
	--BH ADD END
	timerThrowSpearCD:Start(-delay)
	self:Schedule(25, checkSpear)
	if self.Options.RangeFrame then
		if self:IsDifficulty("normal10", "heroic10") then
			DBM.RangeCheck:Show(10, nil, nil, 2)
		else
			DBM.RangeCheck:Show(10, nil, nil, 4)
		end
	end
	if self:IsDifficulty("heroic10", "heroic25") then
		timerWhirlingWindsCD:Start(15-delay)
		timerLightningStormCD:Start(22-delay)
		if self.Options.InfoFrame then
			DBM.InfoFrame:SetHeader(GetSpellInfo(136193))
			DBM.InfoFrame:Show(5, "playerbaddebuff", 136193)
		end
	end
	berserkTimer:Start(-delay)
end

function mod:OnCombatEnd()
	if self.Options.RangeFrame then
		DBM.RangeCheck:Hide()
	end
	if self.Options.InfoFrame then
		DBM.InfoFrame:Hide()
	end
	--BH ADD
	if self.Options.HudMAP or self.Options.HudLight then
		DBMHudMap:FreeEncounterMarkers()
	end
	--BH ADD END
end

function mod:SPELL_AURA_APPLIED(args)
	if args.spellId == 134691 then
		local amount = args.amount or 1
		warnImpale:Show(args.destName, amount)
		timerImpaleCD:Start()
		if amount >= 2 then
			if args:IsPlayer() then
				specWarnImpale:Show(args.amount)
			else
				specWarnImpaleOther:Show(args.destName)
			end
		end
	elseif args.spellId == 134647 then
		if args:IsPlayer() then
			local amount = args.amount or 1
			timerScorched:Start()
			if amount > 2 then
				specWarnScorched:Show(amount)
			end
		end
		--[[
		if morestack < (args.amount or 1) then
			morestack = (args.amount or 1)
		end
		self:Schedule(0.2, function()
			if morestack == 1 then
				sndWOP:Play("countone")
			elseif morestack == 2 then
				sndWOP:Play("counttwo")
			elseif morestack == 3 then
				sndWOP:Play("countthree")
			elseif morestack == 4 then
				sndWOP:Play("countfour")
			elseif morestack == 5 then
				sndWOP:Play("countfive")
			elseif morestack == 6 then
				sndWOP:Play("countsix")
			end
			morestack = 0
		end)
		]]
	elseif args.spellId == 137221 then
		warnMoltenOverload:Show()
		specWarnMoltenOverload:Show()
		timerMoltenOverload:Start()
		sndWOP:Play("ex_tt_rycz") --熔岩超載
	elseif args.spellId == 136192 then
		warnLightningStorm:Show(args.destName)
		if phase == 2 then
			timerLightningStormCD:Start()
		else--Heroic phase 1 or 4
			timerLightningStormCD:Start(37.5)
		end
		if self.Options.SetIconOnLightningStorm and not self:IsDifficulty("lfr25") then
			self:SetIcon(args.destName, 8)
		end
		--BH ADD
		if args:IsPlayer() then
			specWarnLightningStorm:Show()
			yellLightningStorm:Yell()
			if self.Options.ReapetAP then
				self:ScheduleMethod(4, "checkmydebuff")
			end
		else
			if (mod.Options.dispsetLight1 == "") and (mod.Options.dispsetLight2 == "") then
				sndWOP:Play("helpme") --救我
				if self.Options.HudMAP then
					lightmaker[args.destName] = register(DBMHudMap:AddEdge(0, 0, 1, 1, nil, "player", args.destName))
					fixdebuffremovebug(args.destName)
				end
			else
				if (args.destName == mod.Options.dispsetLight1) or (args.destName == mod.Options.dispsetLight2) then
					sndWOP:Play("helpme") --救我
					if self.Options.HudMAP then
						lightmaker[args.destName] = register(DBMHudMap:AddEdge(0, 0, 1, 1, nil, "player", args.destName))
						fixdebuffremovebug(args.destName)
					end
				end
			end
		end
		--BH ADD END
	elseif args.spellId == 135145 then
		warnFreeze:Show(args.destName)
		if phase == 3 then
			timerFreezeCD:Start()
		else--Heroic phase 2 or 4
			timerFreezeCD:Start(36)
		end
	elseif args.spellId == 136323 then
		warnRisingAnger:Show(args.destName, args.amount or 1)
		timerRisingAngerCD:Start()
	elseif args.spellId == 136193 then
		if phase > 2 then
			if self.Options.HudLight and not FireMarkers[args.destName] then
				FireMarkers[args.destName] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("highlight", args.destName, 10, nil, 1, 1 ,1 ,0.8):Appear():RegisterForAlerts())
				fixdebuffremovebug2(args.destName)
			end
		end
	end
end
mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED

function mod:SPELL_AURA_REMOVED(args)
	if args.spellId == 134647 and args:IsPlayer() then
		timerScorched:Cancel()
	--BH ADD
	elseif args.spellId == 136192 then
		if lightmaker[args.destName] then
			lightmaker[args.destName] = free(lightmaker[args.destName])
		end
		if (args.destName == mod.Options.dispsetLight1) or (args.destName == mod.Options.dispsetLight2) then
			sndWOP:Play("thanks")
		end
		if self.Options.SetIconOnLightningStorm and not self:IsDifficulty("lfr25") then
			self:SetIcon(args.destName, 0)
		end
	--BH ADD END
	elseif args.spellId == 136193 then
		if FireMarkers[args.destName] then
			FireMarkers[args.destName] = free(FireMarkers[args.destName])
		end
	end
end

function mod:SPELL_CAST_SUCCESS(args)
	if args.spellId == 134664 then
		warnMoltenInferno:Show()
	--Dead zone IDs, each dead zone has two shields and two openings. Each spellid identifies those openings.
	elseif args.spellId == 137226 then--Front, Right Shielded
		warnDeadZone:Show(args.spellName, DBM_CORE_FRONT, DBM_CORE_RIGHT)
		timerDeadZoneCD:Start()
		if self.Options.SoundARAT then
			sndWOP:Play("attmid")
		else
			sndWOP:Play("ex_tt_mq")
		end
		--Attack left or Behind (maybe add special warning that says where you can attack, for dps?)
	elseif args.spellId == 137227 then--Left, Right Shielded
		warnDeadZone:Show(args.spellName, DBM_CORE_LEFT, DBM_CORE_RIGHT)
		timerDeadZoneCD:Start()
		if self.Options.SoundARAT then
			sndWOP:Play("attmid")
		else
			sndWOP:Play("ex_tt_mq")
		end
		--Attack Front or Behind
	elseif args.spellId == 137228 then--Left, Front Shielded
		warnDeadZone:Show(args.spellName, DBM_CORE_LEFT, DBM_CORE_FRONT)
		timerDeadZoneCD:Start()
		if self.Options.SoundARAT then
			sndWOP:Play("attmid")
		else
			sndWOP:Play("ex_tt_mq")
		end
		--Attack Right or Behind
	elseif args.spellId == 137229 then--Back, Front Shielded
		warnDeadZone:Show(args.spellName, DBM_CORE_BACK, DBM_CORE_FRONT)
		timerDeadZoneCD:Start()
		if self.Options.SoundARAT then
			sndWOP:Play("attleft")
		else
			sndWOP:Play("ex_tt_mq")
		end
		--Attack left or Right
	elseif args.spellId == 137230 then--Back, Left Shielded
		warnDeadZone:Show(args.spellName, DBM_CORE_BACK, DBM_CORE_LEFT)
		timerDeadZoneCD:Start()
		if self.Options.SoundARAT then
			sndWOP:Play("attright")
		else
			sndWOP:Play("ex_tt_mq")
		end
		--Attack Front or Right
	elseif args.spellId == 137231 then--Back, Right Shielded
		warnDeadZone:Show(args.spellName, DBM_CORE_BACK, DBM_CORE_RIGHT)
		timerDeadZoneCD:Start()
		if self.Options.SoundARAT then
			sndWOP:Play("attleft")
		else
			sndWOP:Play("ex_tt_mq")
		end
		--Attack Front or Left
	end
end

function mod:SPELL_SUMMON(args)
	if args.spellId == 134926 and phase < 4 then
		if self:AntiSpam(15, 6) then--Basically, if the target scanning failed, we do an aoe warning on the actual summon.
			specWarnThrowSpear:Show()
		end
		timerThrowSpearCD:Start()
		self:Unschedule(checkSpear)
		self:Schedule(25, checkSpear)--Timing adjust to reduce cpu usage when we know for sure the best time to check target. spear cd is variable, minimum though is 30, 25 is probably too early to start scanning but a good place to start.
		sndWOP:Play("spear") --投擲長矛
	end
end

--[[
--One of these is standing in fire and you need to move,other is dot you can't do anything about cause you stood in it too long. I'm not sure which is which so mod may be backwards, if it is, swap the damage events
"<54.8 20:15:39> [CLEU] SPELL_PERIODIC_DAMAGE#true##nil#1297#2#0x0100000000001E03#Omegal#1297#2#137668#Burning Cinders#4#15972#-1#4#nil#nil#nil#nil#nil#nil#nil", -- [3846]
"<55.4 20:15:39> [CLEU] SPELL_DAMAGE#true##nil#1298#8#0x01000000000036C3#Ixila#1298#8#137668#Burning Cinders#4#8896#-1#4#nil#nil#17562#nil#nil#nil#nil", -- [3905]
--]]
function mod:SPELL_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
	if spellId == 137668 and destGUID == UnitGUID("player") and self:AntiSpam(3, 2) then
		specWarnBurningCinders:Show()
		sndWOP:Play("runaway") --快躲開
	elseif spellId == 137669 and destGUID == UnitGUID("player") and self:AntiSpam(3, 3) then
		specWarnStormCloud:Show()
		sndWOP:Play("runaway")
	elseif spellId == 137664 and destGUID == UnitGUID("player") and self:AntiSpam(2, 4) then
		specWarnFrozenBlood:Show()
		sndWOP:Play("runaway")
	end
end
mod.SPELL_MISSED = mod.SPELL_DAMAGE

function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId)
	if spellId == 134611 then--Unleashed Flame internal CD. He cannot use more often than every 6 seconds. 137991 is ability activation on pull, before 137991 is cast, he can't use ability at all
		warnUnleashedFlame:Show()
		timerUnleashedFlameCD:Start()
		--NOTE, on heroic phase 3-4, trigger still fires every 6 seconds but energy gain is slower so it won't actually go off often like it does in phase 1.
		--None the less, this timer is accurate on heroic as 6 seconds as it indicates when the next POSSIBLE cast is. in other words, if he reaches enough energy during this cd, he won't cast it until 6 second cd ends
		--This cast is the periodic trigger that checks whether or not boss has 30 energy, nothing more.
	elseif spellId == 50630 then--Eject All Passengers (heroic phase change trigger)
		local cid = self:GetCIDFromGUID(UnitGUID(uId))
		self:Unschedule(checkSpear)
		timerThrowSpearCD:Start()
		if cid == 68079 then--Ro'shak
			if self.Options.RangeFrame then
				DBM.RangeCheck:Show(10, nil, nil, 1)--Switch range frame back to 1. Range is assumed 10, no spell info
			end
			--Only one log, but i looks like spear cd from phase 1 remains intact
			phase = 2
			stormcount = 0
			updateHealthFrame()
			if self:IsDifficulty("heroic10", "heroic25") then
				sndWOP:Play("ex_tt_sdxt") --閃電形态
			end
			timerUnleashedFlameCD:Cancel()
			timerMoltenOverload:Cancel()
			timerWhirlingWindsCD:Cancel()
			warnPhase2:Show()
			self:Schedule(25, checkSpear)
			if self:IsDifficulty("heroic10", "heroic25") then
				timerFreezeCD:Start(13)
				timerFrostSpikeCD:Start(15)
			end
			timerLightningStormCD:Start()
			warnWindStorm:Schedule(52)
			specWarnWindStorm:Schedule(52)
			timerWindStorm:Schedule(52)
			timerWindStormCD:Start(52)
			sndWOP:Schedule(47, "wwsoon")
			sndWOP:Schedule(48, "countfive")
			sndWOP:Schedule(49, "countfour")
			sndWOP:Schedule(50, "countthree")
			sndWOP:Schedule(51, "counttwo")
			sndWOP:Schedule(52, "countone")
		elseif cid == 68080 then--Quet'zal
			phase = 3
			if self.Options.HudLight then
				for i = 1, DBM:GetNumGroupMembers() do
					if UnitDebuff("raid"..i, GetSpellInfo(136193)) then
						if UnitName("raid"..i) ~= UnitName("player") then
							FireMarkers[UnitName("raid"..i)] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("highlight", UnitName("raid"..i), 10, nil, 1, 1 ,1 ,0.8):Appear():RegisterForAlerts())
						else
							FireMarkers[UnitName("raid"..i)] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("highlight", UnitName("raid"..i), 10, nil, 1, 1 ,1 ,0.4):Appear():RegisterForAlerts())
						end
						fixdebuffremovebug2(UnitName("raid"..i))
					end
				end
			end
			updateHealthFrame()
			if self:IsDifficulty("heroic10", "heroic25") then
				sndWOP:Play("ex_tt_bsxt") --冰霜形態
			end
			timerLightningStormCD:Cancel()
			timerWindStorm:Cancel()
			timerWindStormCD:Cancel()
			warnWindStorm:Cancel()
			specWarnWindStorm:Cancel()
			sndWOP:Cancel("wwsoon")
			sndWOP:Cancel("countfive")
			sndWOP:Cancel("countfour")
			sndWOP:Cancel("countthree")
			sndWOP:Cancel("counttwo")
			sndWOP:Cancel("countone")
			timerFrostSpikeCD:Cancel()
			warnPhase3:Show()
			self:Schedule(25, checkSpear)
			timerDeadZoneCD:Start(8.5)
			checkArcing()
		elseif cid == 68081 then--Dam'ren
			--confirmed, dam'ren's abilities do NOT reset in phase 4, cds from phase 3 carry over.
			phase = 4
			updateHealthFrame()
			warnPhase4:Show()
			timerRisingAngerCD:Start(15)
			timerFistSmashCD:Start(62, 1)
			self:Unschedule(checkArcing)--Phase 4, new arcings start going out again so no need to do waste time on this check until  quet'zal dies
			if self.Options.RangeFrame then
				DBM.RangeCheck:Show(10, nil, nil, 1)--Switch range frame back to 1. Range is assumed 10, no spell info
			end
			if self.Options.InfoFrame then
				DBM.InfoFrame:SetHeader(arcingName)
				DBM.InfoFrame:Show(5, "playerbaddebuff", 136193)
			end
			if self:IsDifficulty("heroic10", "heroic25") then
				sndWOP:Play("ptwo") --2階段
			end
		end
	elseif spellId == 139172 then--Whirling Winds (Phase 1 Heroic).
		warnWhirlingWinds:Show()
		timerWhirlingWindsCD:Start()
	elseif spellId == 139181 then--Frost Spike (Phase 2 Heroic)
		warnFrostSpike:Show()
		timerFrostSpikeCD:Start()
	elseif spellId == 137656 and self:AntiSpam(2, 1) then--Rushing Winds (Wind Storm end trigger)
		warnWindStorm:Cancel()
		specWarnWindStorm:Cancel()
		warnWindStormEnd:Show()
		sndWOP:Cancel("wwsoon")
		sndWOP:Cancel("countfive")
		sndWOP:Cancel("countfour")
		sndWOP:Cancel("countthree")
		sndWOP:Cancel("counttwo")
		sndWOP:Cancel("countone")
		if phase == 2 then
			warnWindStorm:Schedule(70)
			specWarnWindStorm:Schedule(70)
			timerWindStorm:Schedule(70)
			sndWOP:Schedule(65, "wwsoon")
			sndWOP:Schedule(66, "countfive")
			sndWOP:Schedule(67, "countfour")
			sndWOP:Schedule(68, "countthree")
			sndWOP:Schedule(69, "counttwo")
			sndWOP:Schedule(70, "countone")
		end
		timerWindStormCD:Start()
	elseif spellId == 136146 and self:AntiSpam(2, 5) then
		fistSmashCount = fistSmashCount + 1
		warnFistSmash:Show(fistSmashCount)
--		specWarnFistSmash:Show()
		timerFistSmash:Start()
		if self:IsDifficulty("heroic10", "heroic25") then
			timerFistSmashCD:Start(30, fistSmashCount+1) -- heroic cd longer.
		else
			timerFistSmashCD:Start(nil, fistSmashCount+1)
		end
		if MyJS() then
			specWarnJSA:Show()
			sndWOP:Play("defensive") --注意減傷
		else
			specWarnFistSmash:Show(fistSmashCount)
			sndWOP:Play("aesoon")
		end
	end
end

function mod:UNIT_DIED(args)
	local cid = self:GetCIDFromGUID(args.destGUID)
	if cid == 68079 then--Ro'shak
		timerUnleashedFlameCD:Cancel()
		timerMoltenOverload:Cancel()
		if self:IsDifficulty("heroic10", "heroic25") then--In heroic, all mounts die in phase 4.
			DBM.BossHealth:RemoveBoss(cid)
		else
			if self.Options.RangeFrame then
				DBM.RangeCheck:Show(10, nil, nil, 1)--Switch range frame back to 1. Range is assumed 10, no spell info
			end
			if self.Options.InfoFrame and not self:IsDifficulty("lfr25") then
				DBM.InfoFrame:SetHeader(arcingName)
				DBM.InfoFrame:Show(5, "playerbaddebuff", 136193)
			end
			phase = 2
			stormcount = 0
			updateHealthFrame()
			timerLightningStormCD:Start(17)
			self:Unschedule(checkSpear)
			self:Schedule(25, checkSpear)
			timerThrowSpearCD:Start()
			warnPhase2:Show()
			warnWindStorm:Schedule(49.5)
			specWarnWindStorm:Schedule(49.5)
			timerWindStorm:Schedule(49.5)
			sndWOP:Schedule(44.5, "wwsoon")
			sndWOP:Schedule(45.5, "countfive")
			sndWOP:Schedule(46.5, "countfour")
			sndWOP:Schedule(47.5, "countthree")
			sndWOP:Schedule(48.5, "counttwo")
			sndWOP:Schedule(49.5, "countone")
			timerWindStormCD:Start(49.5)
			sndWOP:Play("ex_tt_sdxt") --閃電形态
		end
	elseif cid == 68080 then--Quet'zal
		timerLightningStormCD:Cancel()
		timerWindStormCD:Cancel()
		warnWindStorm:Cancel()
		specWarnWindStorm:Cancel()
		sndWOP:Cancel("wwsoon")
		sndWOP:Cancel("countfive")
		sndWOP:Cancel("countfour")
		sndWOP:Cancel("countthree")
		sndWOP:Cancel("counttwo")
		sndWOP:Cancel("countone")
		timerWindStorm:Cancel()
		if not self:IsDifficulty("lfr25") then--LFR has no concept of clearing arcing, they certainly don't use info/range frames
			checkArcing()
		else--So just hide range frame when quet'zal dies
			if self.Options.RangeFrame then
				DBM.RangeCheck:Hide()
			end
		end
		if self:IsDifficulty("heroic10", "heroic25") then--In heroic, all mounts die in phase 4.
			DBM.BossHealth:RemoveBoss(cid)
		else
			phase = 3
			if self.Options.HudLight then
				for i = 1, DBM:GetNumGroupMembers() do
					if UnitDebuff("raid"..i, GetSpellInfo(136193)) then
						if UnitName("raid"..i) ~= UnitName("player") then
							FireMarkers[UnitName("raid"..i)] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("highlight", UnitName("raid"..i), 10, nil, 1, 1 ,1 ,0.8):Appear():RegisterForAlerts())
						else
							FireMarkers[UnitName("raid"..i)] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("highlight", UnitName("raid"..i), 10, nil, 1, 1 ,1 ,0.4):Appear():RegisterForAlerts())
						end
						fixdebuffremovebug2(UnitName("raid"..i))
					end
				end
			end
			updateHealthFrame()
			warnPhase3:Show()
			timerDeadZoneCD:Start(6)
			self:Unschedule(checkSpear)
			self:Schedule(25, checkSpear)
			timerThrowSpearCD:Start()
			sndWOP:Play("ex_tt_bsxt") --冰霜形態
		end
	elseif cid == 68081 then--Dam'ren
		timerDeadZoneCD:Cancel()
		timerFreezeCD:Cancel()
		if self:IsDifficulty("heroic10", "heroic25") then--In heroic, all mounts die in phase 4.
			DBM.BossHealth:RemoveBoss(cid)
		else
			phase = 4
			updateHealthFrame()
			self:Unschedule(checkSpear)
			timerThrowSpearCD:Cancel()
			self:UnregisterShortTermEvents()
			warnPhase4:Show()
			timerRisingAngerCD:Start()
			timerFistSmashCD:Start(22.5, 1)--fist smash cd is random. (22.5 or 31.5)
			sndWOP:Play("ptwo") --2階段
		end
	end
end

--BH ADD
function mod:UNIT_POWER(uId)
	if self:IsDifficulty("lfr25") then return end
	if (self:GetUnitCreatureId(uId) == 68079) and UnitPower(uId) > 50 and not Warned then
		Warned = true
		sndWOP:Play("energyhigh") --能量過高
	elseif (self:GetUnitCreatureId(uId) == 68079) and UnitPower(uId) < 20 and Warned then
		Warned = false
	end
end

--BH ADD END


text:
var gulp = require('gulp');
var mocha = require('gulp-mocha');

gulp.task('default', function() {
  console.log('Hello!');
});

gulp.task('mocha', function(){
    return gulp.src(['test/test-*.js'], { read: false })
        .pipe(mocha({
            reporter: 'spec',
            globals: {}
        }))
        .once('end', function() {
          process.exit();
        });
});


text:
<?php
namespace APM\VenteBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Created by PhpStorm.
 * User: Yannick
 * Date: 04/02/2017
 * Time: 07:58
 */
class TransactionPromptType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('motif', TextType::class, ['required' => true])
            ->add('montant', MoneyType::class, ['required' => true, 'currency' => 'XAF'])
            ->add('utilisateurNonAVM', TextType::class, ['required' => false])
            ->add('quantite', NumberType::class, ['required' => false]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'transaction_prompt';
    }

}


text:
package org.apache.flink.streaming.runtime.streamrecord;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeutils.CompositeTypeSerializerSnapshot;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.watermarkstatus.WatermarkStatus;

import java.io.IOException;

import static java.util.Objects.requireNonNull;

/**
 * Serializer for {@link StreamRecord}, {@link Watermark}, {@link LatencyMarker}, and {@link
 * WatermarkStatus}.
 *
 * <p>This does not behave like a normal {@link TypeSerializer}, instead, this is only used at the
 * stream task/operator level for transmitting StreamRecords and Watermarks.
 *
 * @param <T> The type of value in the StreamRecord
 */
@Internal
public final class StreamElementSerializer<T> extends TypeSerializer<StreamElement> {

    private static final long serialVersionUID = 1L;

    private static final int TAG_REC_WITH_TIMESTAMP = 0;
    private static final int TAG_REC_WITHOUT_TIMESTAMP = 1;
    private static final int TAG_WATERMARK = 2;
    private static final int TAG_LATENCY_MARKER = 3;
    private static final int TAG_STREAM_STATUS = 4;

    private final TypeSerializer<T> typeSerializer;

    public StreamElementSerializer(TypeSerializer<T> serializer) {
        if (serializer instanceof StreamElementSerializer) {
            throw new RuntimeException(
                    "StreamRecordSerializer given to StreamRecordSerializer as value TypeSerializer: "
                            + serializer);
        }
        this.typeSerializer = requireNonNull(serializer);
    }

    public TypeSerializer<T> getContainedTypeSerializer() {
        return this.typeSerializer;
    }

    // ------------------------------------------------------------------------
    //  Utilities
    // ------------------------------------------------------------------------

    @Override
    public boolean isImmutableType() {
        return false;
    }

    @Override
    public StreamElementSerializer<T> duplicate() {
        TypeSerializer<T> copy = typeSerializer.duplicate();
        return (copy == typeSerializer) ? this : new StreamElementSerializer<T>(copy);
    }

    // ------------------------------------------------------------------------
    //  Utilities
    // ------------------------------------------------------------------------

    @Override
    public StreamRecord<T> createInstance() {
        return new StreamRecord<T>(typeSerializer.createInstance());
    }

    @Override
    public int getLength() {
        return -1;
    }

    @Override
    public StreamElement copy(StreamElement from) {
        // we can reuse the timestamp since Instant is immutable
        if (from.isRecord()) {
            StreamRecord<T> fromRecord = from.asRecord();
            return fromRecord.copy(typeSerializer.copy(fromRecord.getValue()));
        } else if (from.isWatermark() || from.isWatermarkStatus() || from.isLatencyMarker()) {
            // is immutable
            return from;
        } else {
            throw new RuntimeException();
        }
    }

    @Override
    public StreamElement copy(StreamElement from, StreamElement reuse) {
        if (from.isRecord() && reuse.isRecord()) {
            StreamRecord<T> fromRecord = from.asRecord();
            StreamRecord<T> reuseRecord = reuse.asRecord();

            T valueCopy = typeSerializer.copy(fromRecord.getValue(), reuseRecord.getValue());
            fromRecord.copyTo(valueCopy, reuseRecord);
            return reuse;
        } else if (from.isWatermark() || from.isWatermarkStatus() || from.isLatencyMarker()) {
            // is immutable
            return from;
        } else {
            throw new RuntimeException("Cannot copy " + from + " -> " + reuse);
        }
    }

    @Override
    public void copy(DataInputView source, DataOutputView target) throws IOException {
        int tag = source.readByte();
        target.write(tag);

        if (tag == TAG_REC_WITH_TIMESTAMP) {
            // move timestamp
            target.writeLong(source.readLong());
            typeSerializer.copy(source, target);
        } else if (tag == TAG_REC_WITHOUT_TIMESTAMP) {
            typeSerializer.copy(source, target);
        } else if (tag == TAG_WATERMARK) {
            target.writeLong(source.readLong());
        } else if (tag == TAG_STREAM_STATUS) {
            target.writeInt(source.readInt());
        } else if (tag == TAG_LATENCY_MARKER) {
            target.writeLong(source.readLong());
            target.writeLong(source.readLong());
            target.writeLong(source.readLong());
            target.writeInt(source.readInt());
        } else {
            throw new IOException("Corrupt stream, found tag: " + tag);
        }
    }

    @Override
    public void serialize(StreamElement value, DataOutputView target) throws IOException {
        if (value.isRecord()) {
            StreamRecord<T> record = value.asRecord();

            if (record.hasTimestamp()) {
                target.write(TAG_REC_WITH_TIMESTAMP);
                target.writeLong(record.getTimestamp());
            } else {
                target.write(TAG_REC_WITHOUT_TIMESTAMP);
            }
            typeSerializer.serialize(record.getValue(), target);
        } else if (value.isWatermark()) {
            target.write(TAG_WATERMARK);
            target.writeLong(value.asWatermark().getTimestamp());
        } else if (value.isWatermarkStatus()) {
            target.write(TAG_STREAM_STATUS);
            target.writeInt(value.asWatermarkStatus().getStatus());
        } else if (value.isLatencyMarker()) {
            target.write(TAG_LATENCY_MARKER);
            target.writeLong(value.asLatencyMarker().getMarkedTime());
            target.writeLong(value.asLatencyMarker().getOperatorId().getLowerPart());
            target.writeLong(value.asLatencyMarker().getOperatorId().getUpperPart());
            target.writeInt(value.asLatencyMarker().getSubtaskIndex());
        } else {
            throw new RuntimeException();
        }
    }

    @Override
    public StreamElement deserialize(DataInputView source) throws IOException {
        int tag = source.readByte();
        if (tag == TAG_REC_WITH_TIMESTAMP) {
            long timestamp = source.readLong();
            return new StreamRecord<T>(typeSerializer.deserialize(source), timestamp);
        } else if (tag == TAG_REC_WITHOUT_TIMESTAMP) {
            return new StreamRecord<T>(typeSerializer.deserialize(source));
        } else if (tag == TAG_WATERMARK) {
            return new Watermark(source.readLong());
        } else if (tag == TAG_STREAM_STATUS) {
            return new WatermarkStatus(source.readInt());
        } else if (tag == TAG_LATENCY_MARKER) {
            return new LatencyMarker(
                    source.readLong(),
                    new OperatorID(source.readLong(), source.readLong()),
                    source.readInt());
        } else {
            throw new IOException("Corrupt stream, found tag: " + tag);
        }
    }

    @Override
    public StreamElement deserialize(StreamElement reuse, DataInputView source) throws IOException {
        int tag = source.readByte();
        if (tag == TAG_REC_WITH_TIMESTAMP) {
            long timestamp = source.readLong();
            T value = typeSerializer.deserialize(source);
            StreamRecord<T> reuseRecord = reuse.asRecord();
            reuseRecord.replace(value, timestamp);
            return reuseRecord;
        } else if (tag == TAG_REC_WITHOUT_TIMESTAMP) {
            T value = typeSerializer.deserialize(source);
            StreamRecord<T> reuseRecord = reuse.asRecord();
            reuseRecord.replace(value);
            return reuseRecord;
        } else if (tag == TAG_WATERMARK) {
            return new Watermark(source.readLong());
        } else if (tag == TAG_LATENCY_MARKER) {
            return new LatencyMarker(
                    source.readLong(),
                    new OperatorID(source.readLong(), source.readLong()),
                    source.readInt());
        } else {
            throw new IOException("Corrupt stream, found tag: " + tag);
        }
    }

    // ------------------------------------------------------------------------
    //  Utilities
    // ------------------------------------------------------------------------

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof StreamElementSerializer) {
            StreamElementSerializer<?> other = (StreamElementSerializer<?>) obj;

            return typeSerializer.equals(other.typeSerializer);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return typeSerializer.hashCode();
    }

    // --------------------------------------------------------------------------------------------
    // Serializer configuration snapshotting & compatibility
    //
    // This serializer may be used by Flink internal operators that need to checkpoint
    // buffered records. Therefore, it may be part of managed state and need to implement
    // the configuration snapshot and compatibility methods.
    // --------------------------------------------------------------------------------------------

    @Override
    public StreamElementSerializerSnapshot<T> snapshotConfiguration() {
        return new StreamElementSerializerSnapshot<>(this);
    }

    /** Configuration snapshot specific to the {@link StreamElementSerializer}. */
    public static final class StreamElementSerializerSnapshot<T>
            extends CompositeTypeSerializerSnapshot<StreamElement, StreamElementSerializer<T>> {

        private static final int VERSION = 2;

        @SuppressWarnings("WeakerAccess")
        public StreamElementSerializerSnapshot() {
            super(StreamElementSerializer.class);
        }

        StreamElementSerializerSnapshot(StreamElementSerializer<T> serializerInstance) {
            super(serializerInstance);
        }

        @Override
        protected int getCurrentOuterSnapshotVersion() {
            return VERSION;
        }

        @Override
        protected TypeSerializer<?>[] getNestedSerializers(
                StreamElementSerializer<T> outerSerializer) {
            return new TypeSerializer[] {outerSerializer.getContainedTypeSerializer()};
        }

        @Override
        protected StreamElementSerializer<T> createOuterSerializerWithNestedSerializers(
                TypeSerializer<?>[] nestedSerializers) {
            @SuppressWarnings("unchecked")
            TypeSerializer<T> casted = (TypeSerializer<T>) nestedSerializers[0];

            return new StreamElementSerializer<>(casted);
        }
    }
}


text:
/*global QUnit: false, CrocMSRP: false*/

QUnit.module("ChunkReceiver");

(function () {
	var lineEnd = '\r\n';
	var rawMsg = 'MSRP xol1lmt9 SEND' + lineEnd;
	rawMsg += 'To-Path: msrp://1ckpb61p.invalid:2855/30y1eetsdu;ws' + lineEnd;
	rawMsg += 'From-Path: msrp://f1z7aduu.invalid:2855/f4enevqwx1;ws' + lineEnd;
	rawMsg += 'Message-ID: 3560751376.r8igluab' + lineEnd;
	rawMsg += 'Byte-Range: $RANGE' + lineEnd;
	rawMsg += 'Content-Disposition: attachment; filename=test.txt' + lineEnd;
	rawMsg += 'Content-Type: text/plain' + lineEnd;
	rawMsg += lineEnd;
	rawMsg += '$BODY' + lineEnd;
	rawMsg += '-------xol1lmt9$FLAG' + lineEnd;

	function msg(start, end, total, body, flag, disp) {
		var m = rawMsg;
		m = m.replace('$RANGE', start + '-' + end + '/' + total);
		m = m.replace('$FLAG', flag);
		if (disp) {
			m = m.replace(/attachment.*/, disp);
		}
		m = m.replace('$BODY', body);
		return CrocMSRP.parseMessage(m);
	}

	QUnit.test("Four one-byte chunks in order", function(assert) {
		var recv = new CrocMSRP.ChunkReceiver(msg(1, 1, 4, '1', '+'), 0);
		assert.strictEqual(recv.isComplete(), false, 'Not completed');
		assert.strictEqual(recv.receivedBytes, 1, 'Received 1');
		assert.strictEqual(recv.blob.size, 1, 'Blob size 1');
		assert.strictEqual(recv.totalBytes, 4, 'Total');

		recv.processChunk(msg(2, 2, 4, '2', '+'));
		assert.strictEqual(recv.isComplete(), false, 'Not completed');
		assert.strictEqual(recv.receivedBytes, 2, 'Received 2');
		assert.strictEqual(recv.blob.size, 2, 'Blob size 2');

		recv.processChunk(msg(3, 3, 4, '3', '+'));
		assert.strictEqual(recv.isComplete(), false, 'Not completed');
		assert.strictEqual(recv.receivedBytes, 3, 'Received 3');
		assert.strictEqual(recv.blob.size, 3, 'Blob size 3');

		recv.processChunk(msg(4, 4, 4, '4', '$'));
		assert.strictEqual(recv.isComplete(), true, 'Completed');
		assert.strictEqual(recv.receivedBytes, 4, 'Received 4');
		assert.strictEqual(recv.blob.size, 4, 'Blob size 4');
		assert.strictEqual(recv.aborted, false, 'Not aborted');
		assert.strictEqual(CrocMSRP.util.isEmpty(recv.incontiguousChunks), true, 'No incontiguous chunks');
		assert.strictEqual(recv.bufferedChunks.length, 0, 'No buffered chunks');
	});

	QUnit.test("Four one-byte chunks out of order", function(assert) {
		var recv = new CrocMSRP.ChunkReceiver(msg(1, 1, 4, '1', '+'), 0);
		assert.strictEqual(recv.isComplete(), false, 'Not completed');
		assert.strictEqual(recv.receivedBytes, 1, 'Received 1');
		assert.strictEqual(recv.blob.size, 1, 'Blob size 1');
		assert.strictEqual(recv.totalBytes, 4, 'Total');
		assert.strictEqual(CrocMSRP.util.isEmpty(recv.incontiguousChunks), true, 'No incontiguous chunks');

		recv.processChunk(msg(3, 3, 4, '3', '+'));
		assert.strictEqual(recv.isComplete(), false, 'Not completed');
		assert.strictEqual(recv.receivedBytes, 2, 'Received 2');
		assert.strictEqual(recv.blob.size, 1, 'Blob size 1');
		assert.strictEqual(CrocMSRP.util.isEmpty(recv.incontiguousChunks), false, 'Incontiguous chunk');

		recv.processChunk(msg(2, 2, 4, '2', '+'));
		assert.strictEqual(recv.isComplete(), false, 'Not completed');
		assert.strictEqual(recv.receivedBytes, 3, 'Received 3');
		assert.strictEqual(recv.blob.size, 3, 'Blob size 3');
		assert.strictEqual(CrocMSRP.util.isEmpty(recv.incontiguousChunks), true, 'No incontiguous chunks');

		recv.processChunk(msg(4, 4, 4, '4', '$'));
		assert.strictEqual(recv.isComplete(), true, 'Completed');
		assert.strictEqual(recv.receivedBytes, 4, 'Received 4');
		assert.strictEqual(recv.blob.size, 4, 'Blob size 4');
		assert.strictEqual(recv.aborted, false, 'Not aborted');
		assert.strictEqual(CrocMSRP.util.isEmpty(recv.incontiguousChunks), true, 'No incontiguous chunks');
	});

	QUnit.test("Big message with buffering", function(assert) {
		var chunksize = 2048, totalsize = 10*1024*1024;
		var start = 1, body = '12345678';
		while (body.length < chunksize) {
			body = body + body;
		}

		var recv = new CrocMSRP.ChunkReceiver(msg(start, start - 1 + chunksize, totalsize, body, '+'), 1024*1024);
		assert.strictEqual(recv.isComplete(), false, 'Not completed');
		assert.strictEqual(recv.receivedBytes, chunksize, 'Received chunk');
		assert.strictEqual(recv.totalBytes, totalsize, 'Total correct');
		assert.strictEqual(CrocMSRP.util.isEmpty(recv.incontiguousChunks), true, 'No incontiguous chunks');
		assert.strictEqual(recv.bufferedChunks.length, 1, 'Buffered chunk');
		start += chunksize;

		while (start - 1 + chunksize < totalsize) {
			recv.processChunk(msg(start, start - 1 + chunksize, totalsize, body, '+'));
			start += chunksize;
		}
		assert.strictEqual(recv.isComplete(), false, 'Not completed');
		assert.strictEqual(recv.receivedBytes, start - 1, 'Received most');
		assert.strictEqual(CrocMSRP.util.isEmpty(recv.incontiguousChunks), true, 'No incontiguous chunks');

		recv.processChunk(msg(start, totalsize, totalsize, body.slice(0, totalsize - start + 1), '$'));
		assert.strictEqual(recv.isComplete(), true, 'Completed');
		assert.strictEqual(recv.receivedBytes, totalsize, 'Received all');
		assert.strictEqual(recv.blob.size, totalsize, 'Blob size correct');
		assert.strictEqual(recv.aborted, false, 'Not aborted');
		assert.strictEqual(CrocMSRP.util.isEmpty(recv.incontiguousChunks), true, 'No incontiguous chunks');
		assert.strictEqual(recv.bufferedChunks.length, 0, 'No buffered chunks');
	});

}());


text:
using UnityEngine;
using Mutsuki;

public class MObject : MonoBehaviour {
	[HideInInspector]
	public Category category;
	[HideInInspector]
	public int id;

	[HideInInspector]
	public Vector3 pos;

	[HideInInspector]
	public int hp;
	private float cooltime;

	[HideInInspector]
	public enum Status {
		Stop,
		Move,
		Attack,
	}

	[HideInInspector]
	public Status status;

	[HideInInspector]
	public Animator animator;

	public void SetUp(NewObjectPacket packet) {
		category = packet.category;
		id = packet.movableId;
		pos = new Vector3 (packet.x, 0.0f, packet.y);

		if (category == Category.Player) {
			animator = GetComponent<Animator> ();
		}

		status = Status.Stop;

		if (category == Category.Player) {
			hp = Constants.PLAYER_HP;
		} else {
			hp = Constants.ENEMY_HP;
		}
		cooltime = 0.0f;

		if (category == Category.Player) {
			transform.localPosition = (pos + new Vector3 (0.5f, 0.0f, 0.5f));
		} else {
			transform.localPosition = (pos + new Vector3 (0.5f, 0.5f, 0.5f));
		}
	}

	void Update() {
		if (category == Category.Player) {
			Debug.Log(status + " " + Time.time);
			switch(status) {
			case Status.Move:
				animator.SetBool("move", true);
				status = Status.Stop;
				break;
			case Status.Attack:
				animator.SetBool("attack", true);
				status = Status.Stop;
				break;
			case Status.Stop:
				animator.SetBool("move", false);
				animator.SetBool("attack", false);
				break;
			}
		}

		if (cooltime > 0.0f) {
			var deltaTime = Time.deltaTime;
			if (cooltime < deltaTime) {
				deltaTime = cooltime;
			}
			var diff = new Vector3 (0.0f, 0.0f, deltaTime);
			if (category == Category.Player) {
				diff /= Constants.PLAYER_COOLTIME_MOVE;
			} else {
				diff /= Constants.ENEMY_COOLTIME_MOVE;
			}
			transform.Translate (diff);
			cooltime -= deltaTime;

			if (cooltime > 0.0f) {
				status = Status.Move;
			}
		}
	}

	private Vector3 nameplatePos;
	private string nameplateStr;

	void OnGUI() {
		nameplatePos = Camera.main.WorldToScreenPoint(gameObject.transform.position);
		nameplateStr = "object_" + id + "\n" + hp + "/";
		switch (category) {
		case Category.Player:
			nameplateStr += Constants.PLAYER_HP;
			break;
		case Category.Enemy:
			nameplateStr += Constants.ENEMY_HP;
			break;
		}
		GUI.Label(new Rect(nameplatePos.x + 10, (Screen.height - nameplatePos.y - 36), 100, 50), nameplateStr);
	}

	void OnMouseDown() {
		if (category == Category.Enemy) {
			var packet = PacketFactory.requestAttack(id);
			Main.request (packet);
		}
	}

	private static Vector3 axis = new Vector3(0.0f, 1.0f, 0.0f);

	public bool updateTarget(Vector3 targetPos) {
		if (cooltime > 0.0f) {
			return false;
		}
		else {
			var diff = this.pos - targetPos;
			float rotation = transform.localRotation.eulerAngles.y;
			if(diff.x > 0.99f) {
				rotation = 270.0f - rotation;
				this.pos += new Vector3(-1.0f, 0.0f, 0.0f);
			}
			else if(diff.x < -0.99f) {
				rotation = 90.0f - rotation;
				this.pos += new Vector3(1.0f, 0.0f, 0.0f);
			}
			else if(diff.z > 0.99f) {
				rotation = 180.0f - rotation;
				this.pos += new Vector3(0.0f, 0.0f, -1.0f);
			}
			else if(diff.z < -0.99f) {
				rotation = 0.0f - rotation;
				this.pos += new Vector3(0.0f, 0.0f, 1.0f);
			}
			transform.Rotate(axis, rotation);

			if(category == Category.Player) {
				cooltime = Constants.PLAYER_COOLTIME_MOVE;
			}
			else {
				cooltime = Constants.ENEMY_COOLTIME_MOVE;
			}
			return true;
		}
	}
}


text:
#ifndef RADOLAN
#define RADOLAN

#include <radolan/conversion_exeption.h>
#include <radolan/coordinate_system.h>
#include <radolan/endianess.h>
#include <radolan/netcdf_converter.h>
#include <radolan/radolan_utils.h>
#include <radolan/read.h>
#include <radolan/shapefile_converter.h>
#include <radolan/types.h>
#include <radolan/version.h>

#endif /* Header Guard */


text:
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="my_images_debug"
        path="Android/data/pl.temomuko.autostoprace.debug/files/Pictures"/>
</paths>


text:
package com.sbiger.entity.log;

import javax.persistence.*;

/**
 * Created by saber on 2017/2/18.
 */
@Entity
@Table(name = "log_login")
public class LogLogin {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;            //主键标识
}


text:
<?php

namespace Backend\Modules\{{ moduleNameSafe }}\Actions;

{% if action in ['add', 'edit', 'delete'] %}
use Backend\Core\Engine\Form as BackendForm;
use Backend\Core\Engine\Meta as BackendMeta;
{% endif %}
{% if action in ['index', 'add', 'edit', 'delete'] %}
use Backend\Core\Engine\Base\Action{{ actionSafe }} as BackendBaseAction{{ actionSafe }};
{% else %}
use Backend\Core\Engine\Base\Action as BackendBaseAction;
use Backend\Core\Engine\Form as BackendForm;
{% endif %}
{% if action in ['index'] %}
use Backend\Core\Engine\DataGridArray as BackendDataGridArray;
use Backend\Core\Engine\DataGridFunctions as BackendDataGridFunctions;
{% endif %}
use Backend\Core\Engine\Language as BL;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\{{ moduleNameSafe }}\Engine\Model;

/**
 * Backend {{ moduleName }} {{ action }} action
 */
{% if action in ['index', 'add', 'edit', 'delete'] %}
class {{ actionSafe }} extends BackendBaseAction{{ actionSafe }}
{% else %}
class {{ actionSafe }} extends BackendBaseAction
{% endif %}
{
    /**
     * Execute the action
     */
    public function execute()
    {
        parent::execute();
{% if action in ['edit', 'delete'] %}

        $this->id = $this->getParameter('id', 'int');
{% endif %}
{% if action == 'delete' %}
        $item = Model::get($this->id);
        if (empty($item)) {
            $this->redirect(BackendModel::createURLForAction('Index') . '&report=non-existing');
        }

        Model::delete($this->id);
{% endif %}

{% if action == 'index' %}
        $this->loadDataGrids();
{% elseif action in ['add', 'edit'] %}
{% if action == 'edit' %}
        $this->getData();
{% endif %}
        $this->handleForm();
{% endif %}
{% if action != 'delete' %}

        $this->parse();
        $this->display();
{% else %}
        // Redirect
        $this->redirect(BackendModel::createURLForAction('Index') . '&report={{ action }}{% if action == 'delete' %}d{% endif %}');
{% endif %}
    }
{% if action == 'index' %}

    /**
     * Loads the datagrids
     */
    protected function loadDataGrids()
    {
        // Create datagrid
        $this->dataGrid = new BackendDataGridArray(Model::getAll());

        // Add buttons
        $editURL = BackendModel::createURLForAction('Edit') . '&id=[id]';
        $this->dataGrid->addColumn(
            'edit',
            null,
            BL::lbl('Edit'),
            $editURL,
            BL::lbl('Edit')
        );
{% if meta %}
        $this->dataGrid->setColumnURL('title', $editURL);
{% endif %}

        // Hide unnecessary columns
        $hiddenColumns = array({% if meta %}'meta_id'{% endif %});
        $this->dataGrid->setColumnsHidden($hiddenColumns);
    }
{% elseif action in ['add', 'edit'] %}
{% if action == 'edit' %}

    /**
     * Get data
     */
    protected function getData()
    {
        $this->record = Model::get($this->id);

        // Validate
        if (empty($this->record)) {
            $this->redirect(BackendModel::createURLForAction('Index') . '&error=non-existing');
        }
    }
{% endif %}

    /**
     * Handle form
     */
    protected function handleForm()
    {
        // Create the form
        $form = new BackendForm('{{ action }}');

        // Add fields
{% if meta %}
        $fieldTitle = $form->addText('title', {% if action == 'edit' %}$this->record['title']{% else %}null{% endif %}, 255, 'inputText title', 'inputTextError title');
{% endif %}
{% if tags and action in ['add', 'edit'] %}
        $fieldTags = $form->addText('tags', {% if action == 'edit' %}$this->record['tags']{% else %}null{% endif %}, null, 'inputText tagBox', 'inputTextError tagBox');
{% endif %}
{% if meta %}

        // Meta
{% if action == 'add' %}
        $meta = new BackendMeta($form, null, 'title', true);
{% elseif action == 'edit' %}
        $meta = new BackendMeta($form, $this->record['meta_id'], 'title', true);

        // Set callback for generating a unique URL
        $meta->setUrlCallback('Backend\Modules\{{ moduleNameSafe }}\Engine\Model', 'getURL', array($this->record['id']));
{% endif %}
{% endif %}

        // Submitted?
        if ($form->isSubmitted()) {
            // Check fields
{% if meta %}
            $meta->validate();
            $fieldTitle->isFilled(BL::err('FieldIsRequired'));
{% endif %}

            // Correct?
            if ($form->isCorrect()) {
                // Build item
                $item = array();
{% if action == 'edit' %}
                $item['id'] = $this->id;
{% endif %}
{% if meta %}
                $item['title'] = $fieldTitle->getValue();
                $item['meta_id'] = $meta->save();
{% endif %}
{% if tags %}

                $tags = $fieldTags->getValue();
{% endif %}

                // Save
{% if action in ['add', 'edit'] %}
                {% if action == 'add' %}$id = {% endif %}Model::{% if action == 'add' %}create{% endif %}{% if action == 'edit' %}update{% endif %}($item{% if tags %}, $tags{% endif %});
{% endif %}

                // Redirect
                $redirectURL = BackendModel::createURLForAction('Index');
{% if action in ['add', 'edit'] %}
                $redirectURL .= '&highlight=row-' . {% if action == 'add' %}$id{% elseif action == 'edit' %}$this->record['id']{% endif %};
{% endif %}
                $redirectURL .= '&report={{ action }}ed';
                $this->redirect($redirectURL);
            }
        }

        $form->parse($this->tpl);
    }
{% endif %}
{% if action != 'delete' %}

    /**
     * Parse method
     */
    protected function parse()
    {
        parent::parse();
{% if action == 'index' %}
        $this->tpl->assign('dataGrid', (string) $this->dataGrid->getContent());
{% elseif action in ['add', 'edit'] and meta %}
        // Get url
        $url = BackendModel::getURLForBlock($this->URL->getModule(), 'Detail');
        $url404 = BackendModel::getURL(404);

        // Parse additional variables
        if ($url404 != $url) {
            $this->tpl->assign('detailURL', SITE_URL . $url);
        }
{% if action == 'edit' %}

        $this->tpl->assign('item', $this->record);
{% endif %}
{% endif %}
    }
{% endif %}
}


text:
package com.canyinghao.canphotos;

import android.graphics.*;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RectShape;
import android.graphics.drawable.shapes.RoundRectShape;

public class TextDrawable extends ShapeDrawable {

    private final Paint textPaint;
    private final Paint borderPaint;
    private static final float SHADE_FACTOR = 0.9f;
    private final String text;
    private final int color;
    private final RectShape shape;
    private final int height;
    private final int width;
    private final int fontSize;
    private final float radius;
    private final int borderThickness;

    private TextDrawable(Builder builder) {
        super(builder.shape);

        // shape properties
        shape = builder.shape;
        height = builder.height;
        width = builder.width;
        radius = builder.radius;

        // text and color
        text = builder.toUpperCase ? builder.text.toUpperCase() : builder.text;
        color = builder.color;

        // text paint settings
        fontSize = builder.fontSize;
        textPaint = new Paint();
        textPaint.setColor(builder.textColor);
        textPaint.setAntiAlias(true);
        textPaint.setFakeBoldText(builder.isBold);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTypeface(builder.font);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setStrokeWidth(builder.borderThickness);

        // border paint settings
        borderThickness = builder.borderThickness;
        borderPaint = new Paint();
        borderPaint.setColor(getDarkerShade(color));
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setStrokeWidth(borderThickness);

        // drawable paint color
        Paint paint = getPaint();
        paint.setColor(color);

    }

    private int getDarkerShade(int color) {
        return Color.rgb((int)(SHADE_FACTOR * Color.red(color)),
                (int)(SHADE_FACTOR * Color.green(color)),
                (int)(SHADE_FACTOR * Color.blue(color)));
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        Rect r = getBounds();

        // draw border
        if (borderThickness > 0) {
            drawBorder(canvas);
        }

        int count = canvas.save();
        canvas.translate(r.left, r.top);

        // draw text
        int width = this.width < 0 ? r.width() : this.width;
        int height = this.height < 0 ? r.height() : this.height;
        int fontSize = this.fontSize < 0 ? (Math.min(width, height) / 2) : this.fontSize;
        textPaint.setTextSize(fontSize);
        canvas.drawText(text, width / 2, height / 2 - ((textPaint.descent() + textPaint.ascent()) / 2), textPaint);

        canvas.restoreToCount(count);

    }

    private void drawBorder(Canvas canvas) {
        RectF rect = new RectF(getBounds());
        rect.inset(borderThickness/2, borderThickness/2);

        if (shape instanceof OvalShape) {
            canvas.drawOval(rect, borderPaint);
        }
        else if (shape instanceof RoundRectShape) {
            canvas.drawRoundRect(rect, radius, radius, borderPaint);
        }
        else {
            canvas.drawRect(rect, borderPaint);
        }
    }

    @Override
    public void setAlpha(int alpha) {
        textPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        textPaint.setColorFilter(cf);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    @Override
    public int getIntrinsicWidth() {
        return width;
    }

    @Override
    public int getIntrinsicHeight() {
        return height;
    }

    public static IShapeBuilder builder() {
        return new Builder();
    }

    public static class Builder implements IConfigBuilder, IShapeBuilder, IBuilder {

        private String text;

        private int color;

        private int borderThickness;

        private int width;

        private int height;

        private Typeface font;

        private RectShape shape;

        public int textColor;

        private int fontSize;

        private boolean isBold;

        private boolean toUpperCase;

        public float radius;

        private Builder() {
            text = "";
            color = Color.GRAY;
            textColor = Color.WHITE;
            borderThickness = 0;
            width = -1;
            height = -1;
            shape = new RectShape();
            font = Typeface.create("sans-serif-light", Typeface.NORMAL);
            fontSize = -1;
            isBold = false;
            toUpperCase = false;
        }

        public IConfigBuilder width(int width) {
            this.width = width;
            return this;
        }

        public IConfigBuilder height(int height) {
            this.height = height;
            return this;
        }

        public IConfigBuilder textColor(int color) {
            this.textColor = color;
            return this;
        }

        public IConfigBuilder withBorder(int thickness) {
            this.borderThickness = thickness;
            return this;
        }

        public IConfigBuilder useFont(Typeface font) {
            this.font = font;
            return this;
        }

        public IConfigBuilder fontSize(int size) {
            this.fontSize = size;
            return this;
        }

        public IConfigBuilder bold() {
            this.isBold = true;
            return this;
        }

        public IConfigBuilder toUpperCase() {
            this.toUpperCase = true;
            return this;
        }

        @Override
        public IConfigBuilder beginConfig() {
            return this;
        }

        @Override
        public IShapeBuilder endConfig() {
            return this;
        }

        @Override
        public IBuilder rect() {
            this.shape = new RectShape();
            return this;
        }

        @Override
        public IBuilder round() {
            this.shape = new OvalShape();
            return this;
        }

        @Override
        public IBuilder roundRect(int radius) {
            this.radius = radius;
            float[] radii = {radius, radius, radius, radius, radius, radius, radius, radius};
            this.shape = new RoundRectShape(radii, null, null);
            return this;
        }

        @Override
        public TextDrawable buildRect(String text, int color) {
            rect();
            return build(text, color);
        }

        @Override
        public TextDrawable buildRoundRect(String text, int color, int radius) {
            roundRect(radius);
            return build(text, color);
        }

        @Override
        public TextDrawable buildRound(String text, int color) {
            round();
            return build(text, color);
        }

        @Override
        public TextDrawable build(String text, int color) {
            this.color = color;
            this.text = text;
            return new TextDrawable(this);
        }
    }

    public interface IConfigBuilder {
        public IConfigBuilder width(int width);

        public IConfigBuilder height(int height);

        public IConfigBuilder textColor(int color);

        public IConfigBuilder withBorder(int thickness);

        public IConfigBuilder useFont(Typeface font);

        public IConfigBuilder fontSize(int size);

        public IConfigBuilder bold();

        public IConfigBuilder toUpperCase();

        public IShapeBuilder endConfig();
    }

    public static interface IBuilder {

        public TextDrawable build(String text, int color);
    }

    public static interface IShapeBuilder {

        public IConfigBuilder beginConfig();

        public IBuilder rect();

        public IBuilder round();

        public IBuilder roundRect(int radius);

        public TextDrawable buildRect(String text, int color);

        public TextDrawable buildRoundRect(String text, int color, int radius);

        public TextDrawable buildRound(String text, int color);
    }

    public TextDrawable getRoundWithCustomFont() {
        String text = "Bold";
        return TextDrawable.builder()
                .beginConfig()
                    .useFont(Typeface.DEFAULT)
                    .fontSize(14)
                    .textColor(0xfff58559)
                    .bold()
                .endConfig()
                .buildRect(text, Color.DKGRAY );
    }

}


text:
package com.ivan.jsp;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DefaultController {

    @RequestMapping("/")
    public String index(ModelAndView modelAndView)
    {
        return "index";
    }

    @RequestMapping("/test")
    public String test(ModelAndView modelAndView)
    {
        return "some-template";
    }
}


text:
require 'rails_helper'

RSpec.describe "notifications/index", type: :view do
  before(:each) do
    assign(:notifications, [
      Notification.create!(
        :title => "Title",
        :description => "MyText",
        :user => nil
      ),
      Notification.create!(
        :title => "Title",
        :description => "MyText",
        :user => nil
      )
    ])
  end

  it "renders a list of notifications" do
    render
    assert_select "tr>td", :text => "Title".to_s, :count => 2
    assert_select "tr>td", :text => "MyText".to_s, :count => 2
    assert_select "tr>td", :text => nil.to_s, :count => 2
  end
end