text:
#ifdef __cplusplus
extern "C" {
#endif

/* Registered charset names are at most 40 characters long. */

#define CHARSET_MAX 41

/* Figure out the charset to use from the ContentType.
   buf contains the body of the header field (the part after "Content-Type:").
   charset gets the charset to use.  It must be at least CHARSET_MAX chars
   long.  charset will be empty if the default charset should be used.
*/

void getXMLCharset(const char *buf, char *charset);

#ifdef __cplusplus
}
#endif


text:
package org.jboss.pnc.common.concurrent;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * A class for generating 64-bit unique IDs at high scale. The IDs generated by this service are roughly time sortable.
 *
 * The ID generation follows Twitter snowflake pattern and the IDs are made up of the following components:
 *
 * Epoch timestamp in millisecond precision - 41 bits (gives us 69 years with a custom epoch) Configured machine id - 10
 * bits (gives us up to 1024 machines) Sequence number - 12 bits (A local counter per machine that rolls over every
 * 4096)
 */
public class Sequence {

    private static final Map<Integer, Sequence> instance = new ConcurrentHashMap<>(1, 1.0f);
    private static final int INSTANCE_KEY = 0;

    /**
     * If nodeId is used, it can be set only once and have to be set before the first nextId() call. If nodeId is not
     * explicitly defined it's calculated based on machines mac address.
     *
     * @param nodeId an int value between (inclusive) 0 and 1023.
     */
    public static void setNodeId(int nodeId) {
        getInstance(nodeId);
    }

    public static Long nextId() {
        return getInstance(null).sequenceGenerator.nextId();
    }

    private static Sequence getInstance(Integer nodeId) {
        return instance.computeIfAbsent(INSTANCE_KEY, k -> new Sequence(nodeId));
    }

    private SequenceGenerator sequenceGenerator;

    private Sequence(Integer nodeId) {
        if (sequenceGenerator != null && nodeId != null) {
            throw new IllegalStateException("NodeId have to be called only once and before first call to nextId().");
        }
        if (nodeId == null) {
            sequenceGenerator = new SequenceGenerator();
        } else {
            sequenceGenerator = new SequenceGenerator(nodeId);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Workshop::Project::Configuration do
  describe '#arduino_app_directory' do
    it 'defaults arduino app directory to standard OS X app location' do
      config = Workshop::Project::Configuration.new
      expect(config.arduino_app_directory).to eq('/Applications/Arduino.app')
    end
  end

  describe '#project_name' do
    it 'defaults project name to be the lowercased and underscored folder name' do
      Workshop::Project::Configuration.any_instance.stub(:app_directory).and_return('/a/Foo Bar')
      config = Workshop::Project::Configuration.new
      expect(config.project_name).to eq('foo_bar')
    end
  end

  describe '#app_directory' do
    it 'returns current working directory for app directory' do
      Dir.stub(:pwd).and_return('/foo/bar')
      config = Workshop::Project::Configuration.new
      expect(config.app_directory).to eq('/foo/bar')
    end
  end

  describe '#build' do
    it 'initialized with an instance of a build configuration' do
      expect(subject.build.class).to eq(Workshop::Project::Configuration::Build)
    end
  end

  describe '#upload' do
    it 'initialized with an instance of an upload configuration' do
      expect(subject.upload.class).to eq(Workshop::Project::Configuration::Upload)
    end
  end
end


text:
inline bool is_file_existing(const std::string& name) {
	if (FILE *file = fopen(name.c_str(), "r")) {
		fclose(file);
		return true;
	}
	else {
		return false;
	}
}

class clparser {
public:
	clparser(int, char**);
	~clparser() {};
	std::string in_FITS_filename = "";
	std::string in_params_filename = "";
	std::string in_config_filename = "";
	std::string out_FITS_filename = "";
	int nargs = 0;
private:
	int argc;
	char** argv;
	void check();
	void parse();
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
"http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
<chapter id="solr.misc">
	<title>Miscellaneous Solr Operation Support</title>
	<abstract>
		<para>
			This chapter covers additional support for Solr operations (such as
			faceting) that cannot be directly accessed via the repository
			interface.
			It is recommended to add those operations as custom
			implementation as
			described in
			<xref linkend="repositories.custom-implementations" />
			.
		</para>
	</abstract>

		<title>Partial Updates</title>
		<para>
			PartialUpdates can be done using
			<classname>PartialUpdate</classname>
			which implements
			<interfacename>Update</interfacename>
			.
			<note>
				Partial updates require Solr 4.x.
				With Solr 4.0.0 it is not possible
				to update mulitvalue fields.
			</note>
			<note>
				With Solr 4.1.0 you have to take
				care on parameter order when setting
				null values. Order parameters with nulls last.
			</note>
		</para>
		<example>
			<programlisting language="java">PartialUpdate update = new PartialUpdate("id", "123");
update.add("name", "updated-name");
solrTemplate.saveBean(update);</programlisting>
		</example>

		<title>Projection</title>
		<para>
			Projections can be applied via
			<interfacename>@Query</interfacename>
			using the fields value.
		</para>
		<example>
			<programlisting language="java">@Query(fields = { "name", "id" })
List<ProductBean> findByNameStartingWith(String name);</programlisting>
		</example>

		<title>Faceting</title>
		<para>
			Faceting cannot be directly applied using the
			<interfacename>SolrRepository</interfacename>
			but the
			<classname>SolrTemplate</classname>
			holds support for this feature.
		</para>
		<example>
			<programlisting language="java">FacetQuery query = new SimpleFacetQuery(new Criteria(Criteria.WILDCARD).expression(Criteria.WILDCARD))
  .setFacetOptions(new FacetOptions().addFacetOnField("name").setFacetLimit(5));
FacetPage<Product> page = solrTemplate.queryForFacetPage(query, Product.class);</programlisting>
		</example>
		<para>
			Facets on fields and/or queries can also be defined using
			<interfacename>@Facet</interfacename>
			. Please mind that the result will be a
			<classname>FacetPage</classname>
			.
			<note>
				Using
				<interfacename>@Facet</interfacename>
				allows you to define place holders which will use your input
				parameter as value.
			</note>
		</para>
		<example>
			<programlisting language="java">@Query(value = "*:*")
@Facet(fields = { "name" }, limit = 5)
FacetPage<Product> findAllFacetOnName(Pageable page);</programlisting>
		</example>
		<example>
			<programlisting language="java">@Query(value = "popularity:?0")
@Facet(fields = { "name" }, limit = 5, prefix="?1")
FacetPage<Product> findByPopularityFacetOnName(int popularity, String prefix, Pageable page);</programlisting>
		</example>
		<para>
			Solr allows definition of facet parameters on a per field basis. In order to add special facet options to defined fields use <classname>FieldWithFacetParameters</classname>.
		</para>
		<example>
			<programlisting language="java">// produces: f.name.facet.prefix=spring
FacetOptions options = new FacetOptions();
options.addFacetOnField(new FieldWithFacetParameters("name").setPrefix("spring"));
			</programlisting>
		</example>

		<title>Terms</title>
		<para>
		  Terms Vector cannot directly be used within <interfacename>SolrRepository</interfacename>
		  but can be applied via <classname>SolrTemplate</classname>.
		  Please mind, that the result will be a <interfacename>TermsPage</interfacename>.
		</para>
		<example>
			<programlisting language="java">TermsQuery query = SimpleTermsQuery.queryBuilder().fields("name").build();
TermsPage page = solrTemplate.queryForTermsPage(query);
			</programlisting>
		</example>

		<title>Filter Query</title>
		<para>
			Filter Queries improve query speed and do not influence document
			score. It is recommended to implement geospatial search as filter
			query.
			<note>
				Please note that in solr, unless otherwise specified, all units of
				distance are kilometers and points are in degrees of
				latitude,longitude.
			</note>
		</para>
		<example>
			<programlisting language="java">Query query = new SimpleQuery(new Criteria("category").is("supercalifragilisticexpialidocious"));
FilterQuery fq = new SimpleFilterQuery(new Criteria("store")
  .near(new GeoLocation(48.305478, 14.286699), new Distance(5)));
query.addFilterQuery(fq);</programlisting>
		</example>
		<para>
			Simple filter queries can also be defined using
			<interfacename>@Query</interfacename>
			.
			<note>
				Using
				<interfacename>@Query</interfacename>
				allows you to define place holders which will use your input
				parameter as value.
			</note>
		</para>
		<programlisting language="java">@Query(value = "*:*", filters = { "inStock:true", "popularity:[* TO 3]" })
List<Product> findAllFilterAvailableTrueAndPopularityLessThanEqual3();</programlisting>

        <title>Time allowed for a search</title>
        <para>
            It it possible to set the time allowed for a search to finish. This value only applies to the search and not to requests in general.
            Time is in milliseconds. Values less than or equal to zero implies no time restriction. Partial results may be returned, if there are any.
        </para>
        <example>
            <programlisting language="java">
                Query query = new SimpleQuery(new SimpleStringCriteria("field_1:value_1"));
                // Allowing maximum of 100ms for this search
                query.setTimeAllowed(100);
            </programlisting>
        </example>

        <title>Boost document Score</title>
        <para>
            Boost document score in case of matching criteria to influence result order. This can be done by either
            setting boost on <classname>Criteria</classname> or using <interfacename>@Boost</interfacename> for derived queries.
        </para>
        <example>
            <programlisting language="java">Page<Product> findByNameOrDescription(@Boost(2) String name, String description);
</programlisting>
        </example>

	        <title>Index Time Boosts</title>
	        <para>
	            Boosting documents score can be done on index time by using <interfacename>@SolrDocument</interfacename> annotation on
	            classes (for Solr documents) and/or <interfacename>@Indexed</interfacename> on fields (for Solr fields).
	        </para>
	        <example>
	            <programlisting language="java">import org.apache.solr.client.solrj.beans.Field;
import org.springframework.data.solr.repository.Boost;

@SolrDocument(boost = 0.8f)
public class MyEntity {

    @Id
    @Indexed
    private String id;

    @Indexed(boost = 1.0f)
    private String name;

    // setters and getters ...

}
	            </programlisting>
	        </example>

        <title>Select Request Handler</title>
        <para>
            Select the request handler via qt Parameter directly in
           <classname>Query</classname> or add <interfacename>@Query</interfacename> to your method signature.
        </para>
        <example>
            <programlisting language="java">@Query(requestHandler = "/instock")
Page<Product> findByNameOrDescription(String name, String description);
</programlisting>
        </example>

        <title>Using Join</title>
        <para>
           Join attributes within one solr core by defining <classname>Join</classname> attribute of <classname>Query</classname>.
           <note>
             Join is not available prior to solr 4.x.
           </note>
        </para>
        <example>
            <programlisting language="java">SimpleQuery query = new SimpleQuery(new SimpleStringCriteria("text:ipod"));
query.setJoin(Join.from("manu_id_s").to("id"));
</programlisting>
        </example>

        <title>Highlighting</title>
        <para>
           To highlight matches in search result add <classname>HighlightOptions</classname> to the <classname>SimpleHighlightQuery</classname>.
           Providing <classname>HighlightOptions</classname> without any further attributes will highlight apply highlighting on all fields within a <classname>SolrDocument</classname>.

           <note>
             Field specific highlight parameters can be set by adding <classname>FieldWithHighlightParameters</classname> to <classname>HighlightOptions</classname>.
           </note>
        </para>
        <example>
            <programlisting language="java">SimpleHighlightQuery query = new SimpleHighlightQuery(new SimpleStringCriteria("name:with"));
query.setHighlightOptions(new HighlightOptions());
HighlightPage<Product> page = solrTemplate.queryForHighlightPage(query, Product.class);
</programlisting>
        </example>
        <para>
        	Not all parameters are available via setters/getters but can be added directly.
        </para>
        <example>
            <programlisting language="java">SimpleHighlightQuery query = new SimpleHighlightQuery(new SimpleStringCriteria("name:with"));
query.setHighlightOptions(new HighlightOptions().addHighlightParameter("hl.bs.country", "at"));
</programlisting>
        </example>
        <para>
        	In order to apply Highlighting to derived queries use <interfacename>@Highlight</interfacename>. If no <methodname>fields</methodname> are defined highlighting will be aplied on all fields.
        </para>
        <example>
        	<programlisting language="java">@Highlight(prefix = "<b>", postfix = "</b>")
HighlightPage<Product> findByName(String name, Pageable page);
</programlisting>
        </example>

        <title>Using Functions</title>
        <para>
           Solr supports several functional expressions within queries. Followig functions are supported out of the box. Custom functions can be added by implementing <interfacename>Function</interfacename>

					<title>Functions</title>
					<tgroup cols="2">
						<colspec colwidth="1*" />
						<colspec colwidth="2*" />

							<row>
								<entry>Class</entry>
								<entry>Solr Function</entry>
							</row>

							<row>
								<entry>
									CurrencyFunction
								</entry>
								<entry>
									currency(field_name,[CODE])
								</entry>
							</row>
							<row>
								<entry>
									DefaultValueFunction
								</entry>
								<entry>
									def(field|function,defaultValue)
								</entry>
							</row>
							<row>
								<entry>
									DistanceFunction
								</entry>
								<entry>
									dist(power, pointA, pointB)
								</entry>
							</row>
							<row>
								<entry>
									DivideFunction
								</entry>
								<entry>
									div(x,y)
								</entry>
							</row>
							<row>
								<entry>
									ExistsFunction
								</entry>
								<entry>
									exists(field|function)
								</entry>
							</row>
							<row>
								<entry>
									GeoDistanceFunction
								</entry>
								<entry>
									geodist(sfield, latitude, longitude)
								</entry>
							</row>
							<row>
								<entry>
									GeoHashFunction
								</entry>
								<entry>
									geohash(latitude, longitude)
								</entry>
							</row>
							<row>
								<entry>
									IfFunction
								</entry>
								<entry>
									if(value|field|function,trueValue,falseValue)
								</entry>
							</row>
							<row>
								<entry>
									MaxFunction
								</entry>
								<entry>
									max(field|function,value)
								</entry>
							</row>
							<row>
								<entry>
									NotFunction
								</entry>
								<entry>
									not(field|function)
								</entry>
							</row>
							<row>
								<entry>
									ProductFunction
								</entry>
								<entry>
									product(x,y,...)
								</entry>
							</row>
							<row>
								<entry>
									QueryFunction
								</entry>
								<entry>
									query(x)
								</entry>
							</row>
							<row>
								<entry>
									TermFrequencyFunction
								</entry>
								<entry>
									termfreq(field,term)
								</entry>
							</row>

					</tgroup>

        </para>
        <example>
            <programlisting language="java">SimpleQuery query = new SimpleQuery(new SimpleStringCriteria("text:ipod"));
query.addFilterQuery(new FilterQuery(Criteria.where(QueryFunction.query("name:sol*"))));
</programlisting>
        </example>

</chapter>


text:
module FabricRequirements {

  export var requirementsContext = '/fabric/requirements';
  export var requirementsHash = '#' + requirementsContext;
  export var pluginName = "FabricRequirements";
  export var templatePath = 'app/fabric-requirements/html/';
  export var log:Logging.Logger = Logger.get(pluginName);
  export var _module = angular.module(pluginName, ['hawtioCore', 'fabric']);

  // little shortcut function we can easily prefix all of the controllers in this module
  export var controller = PluginHelpers.createControllerFunction(_module, pluginName);
  export var route = PluginHelpers.createRoutingFunction(templatePath);
  var fabricRoute = PluginHelpers.createRoutingFunction('app/fabric/html/');

  _module.config(['$routeProvider', ($routeProvider:ng.route.IRouteProvider) => {
    $routeProvider.when(UrlHelpers.join(requirementsContext, 'profile'), route('profileRequirements.html'))
                  .when(UrlHelpers.join(requirementsContext, 'sshConfig'), route('sshConfig.html'))
                  .when(UrlHelpers.join(requirementsContext, 'dockerConfig'), route('dockerConfig.html'))
                  .when(UrlHelpers.join(requirementsContext, 'status'), fabricRoute('activeProfiles.html'));
  }]);

  _module.run(['viewRegistry', 'layoutFull', 'workspace', 'ProfileViewActions', '$location', '$rootScope', (viewRegistry, layoutFull, workspace:Core.Workspace, ProfileViewActions:Fabric.ProfileViewActions, $location, $rootScope) => {
    viewRegistry['fabric/requirements'] = templatePath + 'layout.html';

    workspace.topLevelTabs.push({
      id: 'fabric.requirements',
      content: 'Scaling',
      isValid: (workspace:Core.Workspace) => Fabric.isFMCContainer(workspace),
      isActive: (workspace:Core.Workspace) => workspace.isLinkActive('fabric/requirements'),
      href: () => '#/fabric/requirements/profile'
    });

    ProfileViewActions['Add Requirements'] = <Fabric.ProfileViewAction>{
      index: 3,
      icon: 'icon-cog',
      buttonClass: 'btn-primary',
      title: 'Create requirements for the selected profiles',
      action: () => {
        $location.path('/fabric/requirements/profile');
        Core.$apply($rootScope);
      }
    };

  }]);

  hawtioPluginLoader.addModule(pluginName);
}


text:
title: Grove - Vibration Motor
category: Actuator
bzurl: https://seeedstudio.com/Grove-Vibration-Motor-p-839.html
oldwikiname: Grove_-_Vibration_Motor
prodimagename: Gvib.jpg
bzprodimageurl: http://statics3.seeedstudio.com/images/product/gvib.jpg
surveyurl: https://www.research.net/r/Grove-Vibration_Motor
sku: 105020003
tags: grove_digital, io_3v3, io_5v, plat_duino, plat_linkit, plat_pi, plat_bbg
---

![](https://raw.githubusercontent.com/SeeedDocument/Grove-Vibration_Motor/master/img/Gvib.jpg)

This is a mini vibration motor suitable as a non-audible indicator. When the input is HIGH, the motor will vibrate just like your cell phone on silent mode.

[![](https://raw.githubusercontent.com/SeeedDocument/common/master/Get_One_Now_Banner.png)](http://www.seeedstudio.com/Grove-Vibration-Motor-p-839.html)

Version Tracker
---------------

| Revision | Description                                                    | Release       |
|----------|----------------------------------------------------------------|---------------|
| v0.9b    | Initial public release                                         | May 10, 2011  |
| v1.0     | Directly uses an I/O port to drive Vibration Motor             | Nov 5, 2011   |
| v1.2     | Transistor added, uses bigger current to drive Vibration Motor | July 11, 2013 |

Features
--------

-   Grove compatible
-   Non-audible
-   Low power consumption
-   High reliability

Specifications
--------------

Item

Min

Typ

Max

Operating Voltage

3.0V

5.0V

5.5V

Control Mode

Logic Level
(When Logic HIGH, the motor is ON. When LOW, the motor is OFF.)

Rated speed

9000 rpm

Platforms Supported
-------------------

Usage
-----

### With [Arduino](/Arduino "Arduino")

To make it vibrate is just as easy as to turn on an LED. Here is an example showing how to turn on the vibration motor.

1. Plug it onto the Digital port 9 of Grove - Base Shield using a Grove cable.
2. Plug the Grove - Base Shield onto Arduino.
![](https://raw.githubusercontent.com/SeeedDocument/Grove-Vibration_Motor/master/img/IMG_0506.jpg)
3. Connect Arduino to PC by using a USB cable.
4. Copy and paste code below to a new Arduino sketch, and upload it to your Arduino. Please click [here](/Upload_Code) if you do not know how to upload.

Use the demo code shown below:

```
    int MoPin = 9;    // vibrator Grove connected to digital pin 9

    void setup()  {
      pinMode( MoPin, OUTPUT );
    }

    void loop()  {

        digitalWrite(MoPin, HIGH);
        delay(1000);

        digitalWrite(MoPin, LOW);
        delay(1000);
     }

    }
```

Now, feel the vibration of your motor!

### With [Raspberry Pi](/GrovePiPlus "GrovePi+")

1.You should have a Raspberry Pi and a grovepi or grovepi+.

2.You should have completed configuring the development enviroment, otherwise follow [here](/GrovePiPlus#Introducing_the_GrovePi.2B).

3.Connection

-   Plug the sensor to grovepi socket D8 by using a grove cable.

4.Navigate to the demos' directory:
```
    cd yourpath/GrovePi/Software/Python/
```
-   To see the code
```
    nano grove_vibration_motor.py   # "Ctrl+x" to exit #
```
```
    import time
    import grovepi

    # Connect the Grove Vibration Motor to digital port D8
    # SIG,NC,VCC,GND
    vibration_motor = 8

    grovepi.pinMode(vibration_motor,"OUTPUT")

    while True:
        try:
            # Start vibrating for 1 second
            grovepi.digitalWrite(vibration_motor,1)
            print 'start'
            time.sleep(1)

            # Stop vibrating for 1 second, then repeat
            grovepi.digitalWrite(vibration_motor,0)
            print 'stop'
            time.sleep(1)

        except KeyboardInterrupt:
            grovepi.digitalWrite(vibration_motor,0)
            break
        except IOError:
            print "Error"
```
5.Run the demo.
```
    sudo python grove_vibration_motor.py
```

Resources
---------

-   [Grove - Vibration Motor Eagle File](https://raw.githubusercontent.com/SeeedDocument/Grove-Vibration_Motor/master/res/Grove-Vibration_Motor_Eagle_Files.zip)
-   [S9013 Datasheet](https://raw.githubusercontent.com/SeeedDocument/Grove-Vibration_Motor/master/res/S9013.pdf)
-   [ANDA-B1020 Datasheet](https://raw.githubusercontent.com/SeeedDocument/Grove-Vibration_Motor/master/res/ANDA-B1020_datasheet.pdf)


text: Liu Peng' Blog


text:
<?php

/**
 * @package shop
 */
class AddProductForm extends Form
{
    /**
     * Populates quantity dropdown with this many values
     *
     * @var int
     */
    protected $maxquantity = 0;

    /**
     * Fields that can be saved to an order item.
     *
     * @var array
     */
    protected $saveablefields = array();

    public function __construct($controller, $name = "AddProductForm")
    {

        parent::__construct(
            $controller,
            $name,
            $this->getFormFields(),
            $this->getFormActions(),
            $this->getFormValidator()
        );

        $this->addExtraClass("addproductform");

        $this->extend('updateAddProductForm');
    }

    /**
     * Choose maximum value to populate quantity dropdown
     */
    public function setMaximumQuantity($qty)
    {
        $this->maxquantity = (int)$qty;

        return $this;
    }

    public function setSaveableFields($fields)
    {
        $this->saveablefields = $fields;
    }

    public function addtocart($data, $form)
    {
        if ($buyable = $this->getBuyable($data)) {
            $cart = ShoppingCart::singleton();
            $request = $this->getRequest();

            $order = $cart->current();
            if ($request && $request->isAjax() && $order) {
                ShopTools::install_locale($order->Locale);
            }

            $saveabledata = (!empty($this->saveablefields)) ? Convert::raw2sql(
                array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))
            ) : $data;
            $quantity = isset($data['Quantity']) ? (int)$data['Quantity'] : 1;
            $cart->add($buyable, $quantity, $saveabledata);
            if (!ShoppingCart_Controller::config()->direct_to_cart_page) {
                $form->SessionMessage($cart->getMessage(), $cart->getMessageType());
            }

            $this->extend('updateAddToCart', $form, $buyable);

            $this->extend('updateAddProductFormResponse', $request, $response, $buyable, $quantity, $form);

            return $response ? $response : ShoppingCart_Controller::direct($cart->getMessageType());
        }
    }

    public function getBuyable($data = null)
    {
        if ($this->controller->dataRecord instanceof Buyable) {
            return $this->controller->dataRecord;
        }
        return DataObject::get_by_id('Product', (int)$this->request->postVar("BuyableID")); //TODO: get buyable
    }

    /**
     * @return FieldList Fields for this form.
     */
    protected function getFormFields()
    {
        $fields = FieldList::create();

        if ($this->maxquantity) {
            $values = array();
            $count = 1;

            while ($count <= $this->maxquantity) {
                $values[$count] = $count;
                $count++;
            }

            $fields->push(DropdownField::create('Quantity', _t('AddProductForm.Quantity', 'Quantity'), $values, 1));
        } else {
            $fields->push(
                NumericField::create(_t('AddProductForm.Quantity', 'Quantity'), 'Quantity', 1)
                    ->setAttribute('type', 'number')
                    ->setAttribute('min', '0')
            );
        }

        return $fields;
    }

    /**
     * @return FieldList Actions for this form.
     */
    protected function getFormActions()
    {
        return FieldList::create(
            FormAction::create('addtocart', _t("AddProductForm.ADDTOCART", 'Add to Cart'))
        );
    }

    /**
     * @return Validator Validator for this form.
     */
    protected function getFormValidator()
    {
        return RequiredFields::create(
            array(
                'Quantity',
            )
        );
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="verify-v1" content="MDVa8XeTfpT5QHmJLKLK21bwYX/BsyLcyFfmQykCSx0=" />

<title>Map WebVTT track demo</title>

<link rel="stylesheet" href="css/mapTrack.css">

Map WebVTT track demo

This demo requires a browser such as Google Chrome Canary that supports the track element. In Chrome you must enable track element support on the chrome://flags page.

	<video id="gbikeVideo" autoplay controls>
		<source src="video/gbike.webm" type="video/webm" />
		<track label="GBike track" kind="metadata" srclang="en" src="tracks/gbike.vtt" default />
	</video>

Thanks to Jeff Faust for the original idea and data.

This demo shows how a HTML track element can be used to synchronise video playback with the position of a map marker, and to make synchronised changes to DOM elements.

(The functionality of this demo is the same as the Map XML track demo, but it uses a WebVTT file as the src of a track element, rather than parsing an XML file to dynamically create track cues.)

The position of the marker changes, corresponding to the current time of the video. Time of day is overlaid on the video. Click anywhere on the map to move the video to the closest point in the journey to the clicked location.

The HTML metadata track for the video on this page is built by parsing a Google Maps track in XML format:

<track name="track 0">
    <p t="1331363000" a="37.4219276" b="-122.0882180"/>
    <p t="1331363001" a="37.4219297" b="-122.0882154"/>
    ...
</track>

The text for each cue in the HTML track consists of JSON corresponding to a p element in the XML:

{"lat":37.4219276, "lng":-122.088218, "t":1331363000}
{"lat":37.4219297, "lng":-122.0882154, "t":1331363001}
...

The track cuechange event handler then parses the cue JSON to set the position of the map marker.

For more information about the track element, please see Getting started with the track element on HTML5 Rocks.


text:
<?php
$this->breadcrumbs=array(
	'Migracion Cursoses',
);

$this->menu=array(
	array('label'=>'Create MigracionCursos', 'url'=>array('create')),
	array('label'=>'Manage MigracionCursos', 'url'=>array('admin')),
);
?>

Migracion Cursoses

<?php $this->widget('zii.widgets.CListView', array(
	'dataProvider'=>$dataProvider,
	'itemView'=>'_view',
)); ?>


text:
def check_output_roughly_matches(output)
  output.split("[...]\n").each do |part|
    expect(@command).to have_output an_output_string_matching(part)
  end
end

def text_of_user_stories
  user_stories_path = Pathname(aruba.config.working_directory).join("user_stories.pdf")
  user_stories_txt_path = Pathname(aruba.config.working_directory).join("user_stories.txt")
  `pdftotext #{user_stories_path.to_s}` # ugly but necessary
  IO.read(user_stories_txt_path)
end

Then(/^I should see a help page like this:$/) do |output|
  check_output_roughly_matches(output)
end

When(/^I run `(.+)`$/) do |command|
  cmd = sanitize_text(command)
  @command = run(cmd, :fail_on_error => false, :exit_timeout => 1)
end

Given(/^a file named "(.*?)" with:$/) do |arg1, string|
  pending # express the regexp above with the code you wish you had
end

Then(/^the output should contain "(.*?)"$/) do |arg1|
  pending # express the regexp above with the code you wish you had
end

Then(/^the exit status should be (\d+)$/) do |arg1|
  pending # express the regexp above with the code you wish you had
end

Then(/^I should see my final configuration e\.g\. like this:$/) do |output|
  check_output_roughly_matches(output)
end

Given(/^I have a local 'github_scrumboard\.yml' with the following content:$/) do |content|
  write_file('github_scrumboard.yml', content)
end

Then(/^I my final configuration should merge default and local settings:$/) do |output|
  check_output_roughly_matches(output)
end

Then(/^a file called `github_scrumboard\.yml` is placed in the current directory$/) do
  @file_path = "github_scrumboard.yml"
  expect(@file_path).to be_an_existing_file
end

Then(/^the file has \(roughly\) the following content:$/) do |content|
  content.split("[...]\n").each do |part|
    expect(@file_path).to have_file_content file_content_including(part.chomp)
  end
end

Given(/^I have some open and closed issues in my github repository$/) do
  # assuming the vcr cassettes are used
	@expected_open_issues_text = "I want show the assignee on a printed user story"
	@expected_closed_issues_text = "I would like to see a watermark on a story"
end

Given(/^I use the default configuration$/) do
  # no implementation
end

Then(/^I should see only open issues in the output pdf$/) do
	expect(text_of_user_stories).to include(@expected_open_issues_text)
	expect(text_of_user_stories).not_to include(@expected_closed_issues_text)
end

Then(/^I should see only closed issues in the output pdf$/) do
	expect(text_of_user_stories).to include(@expected_closed_issues_text)
	expect(text_of_user_stories).not_to include(@expected_open_issues_text)
end

Then(/^I can see a big watermark saying "DONE" in the output pdf$/) do
  ["D\n", "O\n", "N\n", "E\n"].each do |letter|
    expect(text_of_user_stories).to include(letter)
  end
end

Then(/^I should see both open and closed issues in the output pdf$/) do
	expect(text_of_user_stories).to include(@expected_closed_issues_text)
	expect(text_of_user_stories).to include(@expected_open_issues_text)
end

Given(/^let's say, I won't be asked for my github credentials$/) do
  content = {'github' =>
             { 'login' => 'roschaefer',
               'project' => 'roschaefer/github_scrumboard',
               'password' => "not_for_you"
             } }.to_yaml
  content.slice!("---")
  append_to_file('github_scrumboard.yml', content)
end


text:
import PropTypes from 'prop-types'
import React from 'react'
import EventRow from '../../EventRow'
import Selection, { getBoundsForNode } from '../../Selection'
import { eventSegments } from '../../utils/eventLevels'
import { getSlotAtX, pointInBox } from '../../utils/selection'
import { dragAccessors, eventTimes } from './common'
import { DnDContext } from './DnDContext'

class WeekWrapper extends React.Component {
  static propTypes = {
    isAllDay: PropTypes.bool,
    slotMetrics: PropTypes.object.isRequired,
    accessors: PropTypes.object.isRequired,
    getters: PropTypes.object.isRequired,
    components: PropTypes.object.isRequired,
    resourceId: PropTypes.any,
    rtl: PropTypes.bool,
    localizer: PropTypes.any,
  }

  static contextType = DnDContext

  constructor(...args) {
    super(...args)
    this.state = {}
    this.ref = React.createRef()
  }

  componentDidMount() {
    this._selectable()
  }

  componentWillUnmount() {
    this._teardownSelectable()
  }

  reset() {
    if (this.state.segment) this.setState({ segment: null })
  }

  update(event, start, end) {
    const segment = eventSegments(
      { ...event, end, start, __isPreview: true },
      this.props.slotMetrics.range,
      dragAccessors,
      this.props.localizer
    )

    const { segment: lastSegment } = this.state
    if (
      lastSegment &&
      segment.span === lastSegment.span &&
      segment.left === lastSegment.left &&
      segment.right === lastSegment.right
    ) {
      return
    }
    this.setState({ segment })
  }

  handleMove = (point, bounds, draggedEvent) => {
    if (!pointInBox(bounds, point)) return this.reset()
    const event = this.context.draggable.dragAndDropAction.event || draggedEvent
    const { accessors, slotMetrics, rtl, localizer } = this.props

    const slot = getSlotAtX(bounds, point.x, rtl, slotMetrics.slots)

    const date = slotMetrics.getDateForSlot(slot)

    // Adjust the dates, but maintain the times when moving
    let { start, duration } = eventTimes(event, accessors, localizer)
    start = localizer.merge(date, start)
    const end = localizer.add(start, duration, 'milliseconds')
    // LATER: when dragging a multi-row event, only the first row is animating
    this.update(event, start, end)
  }

  handleDropFromOutside = (point, bounds) => {
    if (!this.context.draggable.onDropFromOutside) return
    const { slotMetrics, rtl, localizer } = this.props

    const slot = getSlotAtX(bounds, point.x, rtl, slotMetrics.slots)
    const start = slotMetrics.getDateForSlot(slot)

    this.context.draggable.onDropFromOutside({
      start,
      end: localizer.add(start, 1, 'day'),
      allDay: false,
    })
  }

  handleDragOverFromOutside = (point, node) => {
    if (!this.context.draggable.dragFromOutsideItem) return
    this.handleMove(point, node, this.context.draggable.dragFromOutsideItem())
  }

  handleResize(point, bounds) {
    const { event, direction } = this.context.draggable.dragAndDropAction
    const { accessors, slotMetrics, rtl, localizer } = this.props

    let { start, end } = eventTimes(event, accessors, localizer)

    const slot = getSlotAtX(bounds, point.x, rtl, slotMetrics.slots)
    const date = slotMetrics.getDateForSlot(slot)
    const cursorInRow = pointInBox(bounds, point)

    if (direction === 'RIGHT') {
      if (cursorInRow) {
        if (slotMetrics.last < start) return this.reset()
        if (localizer.eq(localizer.startOf(end, 'day'), end))
          end = localizer.add(date, 1, 'day')
        else end = date
      } else if (
        localizer.inRange(start, slotMetrics.first, slotMetrics.last) ||
        (bounds.bottom < point.y && +slotMetrics.first > +start)
      ) {
        end = localizer.add(slotMetrics.last, 1, 'milliseconds')
      } else {
        this.setState({ segment: null })
        return
      }
      const originalEnd = accessors.end(event)
      end = localizer.merge(end, originalEnd)
      if (localizer.lt(end, start)) {
        end = originalEnd
      }
    } else if (direction === 'LEFT') {
      if (cursorInRow) {
        if (slotMetrics.first > end) return this.reset()
        start = date
      } else if (
        localizer.inRange(end, slotMetrics.first, slotMetrics.last) ||
        (bounds.top > point.y && localizer.lt(slotMetrics.last, end))
      ) {
        start = localizer.add(slotMetrics.first, -1, 'milliseconds')
      } else {
        this.reset()
        return
      }
      const originalStart = accessors.start(event)
      start = localizer.merge(start, originalStart)
      if (localizer.gt(start, end)) {
        start = originalStart
      }
    }

    this.update(event, start, end)
  }

  _selectable = () => {
    let node = this.ref.current.closest('.rbc-month-row, .rbc-allday-cell')
    let container = node.closest('.rbc-month-view, .rbc-time-view')
    let isMonthRow = node.classList.contains('rbc-month-row')

    // Valid container check only necessary in TimeGrid views
    let selector = (this._selector = new Selection(() => container, {
      validContainers: [
        ...(!isMonthRow ? ['.rbc-day-slot', '.rbc-allday-cell'] : []),
      ],
    }))

    selector.on('beforeSelect', (point) => {
      const { isAllDay } = this.props
      const { action } = this.context.draggable.dragAndDropAction
      const bounds = getBoundsForNode(node)
      const isInBox = pointInBox(bounds, point)
      return (
        action === 'move' || (action === 'resize' && (!isAllDay || isInBox))
      )
    })

    selector.on('selecting', (box) => {
      const bounds = getBoundsForNode(node)
      const { dragAndDropAction } = this.context.draggable
      if (dragAndDropAction.action === 'move') this.handleMove(box, bounds)
      if (dragAndDropAction.action === 'resize') this.handleResize(box, bounds)
    })

    selector.on('selectStart', () => this.context.draggable.onStart())

    selector.on('select', (point) => {
      const bounds = getBoundsForNode(node)
      if (!this.state.segment) return
      if (!pointInBox(bounds, point)) {
        this.reset()
      } else {
        this.handleInteractionEnd()
      }
    })

    selector.on('dropFromOutside', (point) => {
      if (!this.context.draggable.onDropFromOutside) return
      const bounds = getBoundsForNode(node)
      if (!pointInBox(bounds, point)) return
      this.handleDropFromOutside(point, bounds)
    })

    selector.on('dragOverFromOutside', (point) => {
      if (!this.context.draggable.dragFromOutsideItem) return
      const bounds = getBoundsForNode(node)

      this.handleDragOverFromOutside(point, bounds)
    })

    selector.on('click', () => this.context.draggable.onEnd(null))

    selector.on('reset', () => {
      this.reset()
      this.context.draggable.onEnd(null)
    })
  }

  handleInteractionEnd = () => {
    const { resourceId, isAllDay } = this.props
    const { event } = this.state.segment

    this.reset()

    this.context.draggable.onEnd({
      start: event.start,
      end: event.end,
      resourceId,
      isAllDay,
    })
  }

  _teardownSelectable = () => {
    if (!this._selector) return
    this._selector.teardown()
    this._selector = null
  }

  render() {
    const { children, accessors } = this.props

    let { segment } = this.state

    return (
      <div ref={this.ref} className="rbc-addons-dnd-row-body">
        {children}

        {segment && (
          <EventRow
            {...this.props}
            selected={null}
            className="rbc-addons-dnd-drag-row"
            segments={[segment]}
            accessors={{
              ...accessors,
              ...dragAccessors,
            }}
          />
        )}
      </div>
    )
  }
}

export default WeekWrapper


text:
import unittest

from cupy import testing

@testing.gpu
class TestTrigonometric(unittest.TestCase):

    _multiprocess_can_split_ = True

    @testing.for_all_dtypes()
    @testing.numpy_cupy_allclose(atol=1e-5)
    def check_unary(self, name, xp, dtype):
        a = testing.shaped_arange((2, 3), xp, dtype)
        return getattr(xp, name)(a)

    @testing.for_all_dtypes()
    @testing.numpy_cupy_allclose(atol=1e-5)
    def check_binary(self, name, xp, dtype):
        a = testing.shaped_arange((2, 3), xp, dtype)
        b = testing.shaped_reverse_arange((2, 3), xp, dtype)
        return getattr(xp, name)(a, b)

    @testing.for_dtypes(['e', 'f', 'd'])
    @testing.numpy_cupy_allclose(atol=1e-5)
    def check_unary_unit(self, name, xp, dtype):
        a = xp.array([0.2, 0.4, 0.6, 0.8], dtype=dtype)
        return getattr(xp, name)(a)

    def test_sin(self):
        self.check_unary('sin')

    def test_cos(self):
        self.check_unary('cos')

    def test_tan(self):
        self.check_unary('tan')

    def test_arcsin(self):
        self.check_unary_unit('arcsin')

    def test_arccos(self):
        self.check_unary_unit('arccos')

    def test_arctan(self):
        self.check_unary('arctan')

    def test_arctan2(self):
        self.check_binary('arctan2')

    def test_hypot(self):
        self.check_binary('hypot')

    def test_deg2rad(self):
        self.check_unary('deg2rad')

    def test_rad2deg(self):
        self.check_unary('rad2deg')


text:
package com.evolveum.midpoint.web.component.util;

import com.evolveum.midpoint.web.util.WebMiscUtil;
import com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableRowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableType;
import org.apache.wicket.Application;
import org.apache.wicket.Session;
import org.apache.wicket.core.util.lang.PropertyResolver;
import org.apache.wicket.core.util.lang.PropertyResolverConverter;
import org.apache.wicket.model.AbstractPropertyModel;

/**
 *  @author shood
 * */
public class LookupPropertyModel<T> extends AbstractPropertyModel<T> {

    protected final String expression;
    private LookupTableType lookupTable;

    public LookupPropertyModel(Object modelObject, String expression, LookupTableType lookupTable){
        super(modelObject);
        this.expression = expression;
        this.lookupTable = lookupTable;
    }

    /**
     * @see org.apache.wicket.model.AbstractPropertyModel#propertyExpression()
     */
    @Override
    protected String propertyExpression(){
        return expression;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T getObject() {

        final Object target = getInnermostModelOrObject();

        if (target != null){
            String key = (String)PropertyResolver.getValue(expression, target);

            if(key == null){
                return null;
            }

            for(LookupTableRowType row: lookupTable.getRow()){
                if(key.equals(row.getKey())){
                    return (T)WebMiscUtil.getOrigStringFromPoly(row.getLabel());
                }
            }
        }

        return null;
    }

    @Override
    public void setObject(T object) {
        final String expression = propertyExpression();

        PropertyResolverConverter prc;
        prc = new PropertyResolverConverter(Application.get().getConverterLocator(),
                Session.get().getLocale());

        if(object instanceof String){
            String label = (String) object;
            String key;

            for(LookupTableRowType row: lookupTable.getRow()){
                if(label.equals(WebMiscUtil.getOrigStringFromPoly(row.getLabel()))){
                    key = row.getKey();

                    PropertyResolver.setValue(expression, getInnermostModelOrObject(), key, prc);
                }
            }
        }
    }

    @Override
    public void detach() {}
}


text:
(function () {
    'use strict';

    angular
        .module('ordillosInventoryApp')
        .controller('SaleReportCtrl', SaleReportCtrl)
        .factory('Sales', Sales)
        .filter('dateToISO', dateToISO);

    function SaleReportCtrl($scope, $timeout, Sales) {
        $scope.sales = [];
        $scope.getTotal = null;
        $scope.dateData = {};
        $scope.reportTitle = "Today's Sales Report";
        $scope.loadSales = function (data) {
            Sales.getSales(data).then(function (response) {
                console.log(response.data)
                $scope.sales = response.data;
                $scope.getTotalSales = function () {
                    var total = 0;
                    for (var i = 0; i < response.data.length; i++) {
                        var sale = response.data[i];
                        total += sale.sales_total;
                    }
                    return total;
                }
                if (data != null) {
                    $scope.reportTitle = "Sales Report From " + data.fromDate + " - " + data.toDate
                }
            }, function (error) {
                console.log(error);
            })
        }

        $scope.saleDate = function () {
            console.log($scope.dateData)
            var data = {
                'fromDate': $scope.dateData.fromDate,
                'toDate': $scope.dateData.toDate
            }
            $scope.loadSales(data);
        }
        $scope.printReturn = function (printableArea) {
            var mywindow = window.open('', 'PRINT', 'height=600,width=800');

            mywindow.document.write('<base href="/" /><title>' + document.title + '</title>');
            //mywindow.document.write('<link rel="stylesheet" href="assets/css/printstyles.css" type="text/css"/>');
            mywindow.document.write('')
            mywindow.document.write('');
            mywindow.document.write('
 Sales Report
');
            mywindow.document.write(document.getElementById(printableArea).innerHTML);
            mywindow.document.write('');

            // mywindow.document.close(); // necessary for IE >= 10
            //mywindow.focus(); // necessary for IE >= 10*/
            // CHROME
            $timeout(function () {
                jsPrintSetup.print();
                mywindow.close();
            }, 10);
            return true;

        }

        $scope.saleData = [];
        $scope.viewSaleDetails = function (or_number) {
            Sales.summary(or_number).then(function (response) {
                console.log(response.data)
                $scope.saleData = response.data;
                $scope.or_number = or_number;
                $scope.date = response.data[0].created_at;
                $scope.orTotal = function () {
                    var total = 0;
                    for (var i = 0; i < response.data.length; i++) {
                        var sale = response.data[i];
                        total += sale.total_price;
                    }
                    return total;
                }
                $('#viewSalesSummaryModal').openModal();
            }, function (error) {
                console.log(error);
            })
        }

    }

    function Sales($http) {
        return {
            getSales: function (data) {
                return $http({
                    url: '/api/reports/sales',
                    method: "GET",
                    params: data
                });
            },
            summary: function (or_number) {
                return $http.get('api/reports/sale_summary/' + or_number);
            }
        }
    }

    function dateToISO() {
        return function (input) {
            input = new Date(input).toISOString();
            return input;
        };
    }

})();


text:
#include <aws/sms/model/UpdateReplicationJobResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::SMS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

UpdateReplicationJobResult::UpdateReplicationJobResult()
{
}

UpdateReplicationJobResult::UpdateReplicationJobResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

UpdateReplicationJobResult& UpdateReplicationJobResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
var mongoose = require('mongoose');
var CarClassSchema = require('../schemas/carclass');
var CarClass = mongoose.model('CarClass', CarClassSchema);

module.exports = CarClass;


text:
import { Component, Inject, Input, EventEmitter, Output } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient, HttpEventType, HttpResponse } from '@angular/common/http';
import { AlertService } from '../../../shared/alert/services/alert.service';
import { DiplomsService } from '../../services/diploms.service';
import { SelectListItem } from '../../../shared/select-list-item';
declare var $: any;
@Component({
    selector: 'diploms-add-material',
    templateUrl: './add-material.component.html'
})
export class DiplomsAddMaterialComponent {
    form: FormGroup;
    @Input() public id: number = 0;
    @Output() public onMaterialCreated = new EventEmitter<any>();
    public uploadProgress: number = 0;

    materialsOptions: SelectListItem[] = [
        {
            text: "ПЗ в формате LaTeX",
            value: "3"
        },
        {
            text: "Преамбула",
            value: "4"
        },
        {
            text: "Введение",
            value: "5"
        },
        {
            text: "Раздел",
            value: "6"
        },
        {
            text: "Подраздел",
            value: "7"
        },
        {
            text: "Заключение",
            value: "8"
        }
    ]

    constructor(
        private formBuilder: FormBuilder,
        private service: DiplomsService,
        private alertSerivce: AlertService,
    ) {
        this.form = this.formBuilder.group({
            "type": [12, Validators.required],
        });
    }

    upload(files: any) {
        this.form.controls["type"].updateValueAndValidity();
        if (this.form.value.type>8) {
            console.log("formdata");
            if (files.length === 0)
                return;

            const formData = new FormData();

            for (let file of files)
                formData.append(file.name, file);

            this.service.uploadMaterial(this.id, formData).subscribe(event => {
                if (event.type === HttpEventType.UploadProgress)
                    this.uploadProgress = Math.round(100 * event.loaded / (event.total || 100));
                else if (event instanceof HttpResponse) {
                    // ($("#addMaterialDialog") as any).modal("hide");
                    this.onMaterialCreated.emit();
                }
            });
        }
        else {
            this.service.uploadMaterialByType(this.id, this.form.value.type)
                .subscribe(event => {
                    this.onMaterialCreated.emit();
                })
        }

    }
}


text:
<?php

Yii::import('system.db.CDbConnection');
Yii::import('system.db.ar.CActiveRecord');
require_once(dirname(__FILE__) . '/../data/models2.php');

class CActiveRecord2Test extends CTestCase
{

    /**
     * @var CDbConnection
     */
    private $db;

    public function setUp()
    {

        if (!extension_loaded('pdo') || !extension_loaded('pdo_pgsql')) {
            $this->markTestSkipped('PDO and PostgreSQL extensions are required.');
        }

        $this->db = new CDbConnection('pgsql:host=127.0.0.1;dbname=yii', 'test', 'test');
        try {
            $this->db->active = true;
        } catch (Exception $e) {
            $schemaFile = realpath(dirname(__FILE__) . '/../data/postgres.sql');
            $this->markTestSkipped(
                "Please read $schemaFile for details on setting up the test environment for PostgreSQL test case."
            );
        }

        try {
            $this->db->createCommand('DROP SCHEMA test CASCADE')->execute();
        } catch (Exception $e) {
        }
        try {
            $this->db->createCommand('DROP TABLE yii_types CASCADE')->execute();
        } catch (Exception $e) {
        }

        $sqls = file_get_contents(dirname(__FILE__) . '/../data/postgres.sql');
        foreach (explode(';', $sqls) as $sql) {
            if (trim($sql) !== '') {
                $this->db->createCommand($sql)->execute();
            }
        }
        $this->db->active = false;

        $config            = array(
            'basePath'   => dirname(__FILE__),
            'components' => array(
                'db' => array(
                    'class'            => 'system.db.CDbConnection',
                    'connectionString' => 'pgsql:host=127.0.0.1;dbname=yii',
                    'username'         => 'test',
                    'password'         => 'test',
                ),
            ),
        );
        $app               = new TestApplication($config);
        $app->db->active   = true;
        CActiveRecord::$db = $this->db = $app->db;
    }

    public function tearDown()
    {

        $this->db->active = false;
    }

    public function testModel()
    {

        $model = Post2::model();
        $this->assertTrue($model instanceof Post2);
        $this->assertTrue($model->dbConnection === $this->db);
        $this->assertTrue($model->dbConnection->active);
        $this->assertEquals('test.posts', $model->tableName());
        $this->assertEquals('id', $model->tableSchema->primaryKey);
        $this->assertEquals('test.posts_id_seq', $model->tableSchema->sequenceName);
        $this->assertEquals(array(), $model->attributeLabels());
        $this->assertEquals('Id', $model->getAttributeLabel('id'));
        $this->assertEquals('Author Id', $model->getAttributeLabel('author_id'));
        $this->assertTrue($model->getActiveRelation('author') instanceof CBelongsToRelation);
        $this->assertTrue($model->tableSchema instanceof CDbTableSchema);
        $this->assertTrue($model->commandBuilder instanceof CDbCommandBuilder);
        $this->assertTrue($model->hasAttribute('id'));
        $this->assertFalse($model->hasAttribute('comments'));
        $this->assertFalse($model->hasAttribute('foo'));
        $this->assertEquals(array(), $model->getAttributes(false));

        $post = new Post2;
        $this->assertNull($post->id);
        $this->assertNull($post->title);
        $post->setAttributes(array('id' => 3, 'title' => 'test title'));
        $this->assertNull($post->id);
        $this->assertEquals('test title', $post->title);
    }

    public function testFind()
    {

        // test find() with various parameters
        $post = Post2::model()->find();
        $this->assertTrue($post instanceof Post2);
        $this->assertEquals(1, $post->id);

        $post = Post2::model()->find('id=5');
        $this->assertTrue($post instanceof Post2);
        $this->assertEquals(5, $post->id);

        $post = Post2::model()->find('id=:id', array(':id' => 2));
        $this->assertTrue($post instanceof Post2);
        $this->assertEquals(2, $post->id);

        $post = Post2::model()->find(array('condition' => 'id=:id', 'params' => array(':id' => 3)));
        $this->assertTrue($post instanceof Post2);
        $this->assertEquals(3, $post->id);

        // test find() without result
        $post = Post2::model()->find('id=6');
        $this->assertNull($post);

        // test findAll() with various parameters
        $posts = Post2::model()->findAll();
        $this->assertEquals(5, count($posts));
        $this->assertTrue($posts[3] instanceof Post2);
        $this->assertEquals(4, $posts[3]->id);

        $posts = Post2::model()->findAll(new CDbCriteria(array('limit' => 3, 'offset' => 1)));
        $this->assertEquals(3, count($posts));
        $this->assertTrue($posts[2] instanceof Post2);
        $this->assertEquals(4, $posts[2]->id);

        // test findAll() without result
        $posts = Post2::model()->findAll('id=6');
        $this->assertTrue($posts === array());

        // test findByPk
        $post = Post2::model()->findByPk(2);
        $this->assertEquals(2, $post->id);

        $post = Post2::model()->findByPk(array(3, 2));
        $this->assertEquals(2, $post->id);

        $post = Post2::model()->findByPk(array());
        $this->assertNull($post);

        $post = Post2::model()->findByPk(6);
        $this->assertNull($post);

        // test findAllByPk
        $posts = Post2::model()->findAllByPk(2);
        $this->assertEquals(1, count($posts));
        $this->assertEquals(2, $posts[0]->id);

        $posts = Post2::model()->findAllByPk(array(4, 3, 2), 'id<4');
        $this->assertEquals(2, count($posts));
        $this->assertEquals(2, $posts[0]->id);
        $this->assertEquals(3, $posts[1]->id);

        $posts = Post2::model()->findAllByPk(array());
        $this->assertTrue($posts === array());

        // test findByAttributes
        $post = Post2::model()->findByAttributes(array('author_id' => 2), array('order' => 'id DESC'));
        $this->assertEquals(4, $post->id);

        // test findAllByAttributes
        $posts = Post2::model()->findAllByAttributes(array('author_id' => 2));
        $this->assertEquals(3, count($posts));

        // test findBySql
        $post = Post2::model()->findBySql('select * from test.posts where id=:id', array(':id' => 2));
        $this->assertEquals(2, $post->id);

        // test findAllBySql
        $posts = Post2::model()->findAllBySql('select * from test.posts where id>:id', array(':id' => 2));
        $this->assertEquals(3, count($posts));

        // test count
        $this->assertEquals(5, Post2::model()->count());
        $this->assertEquals(3, Post2::model()->count(array('condition' => 'id>2')));

        // test countBySql
        $this->assertEquals(1, Post2::model()->countBySql('select id from test.posts limit 1'));

        // test exists
        $this->assertTrue(Post2::model()->exists('id=:id', array(':id' => 1)));
        $this->assertFalse(Post2::model()->exists('id=:id', array(':id' => 6)));
    }

    public function testInsert()
    {

        $post = new Post2;
        $this->assertEquals(array(), $post->getAttributes(false));
        $post->title       = 'test post 1';
        $post->create_time = '2004-10-19 10:23:54';
        $post->author_id   = 1;
        $post->content     = 'test post content 1';
        $this->assertTrue($post->isNewRecord);
        $this->assertNull($post->id);
        $this->assertTrue($post->save());
        $this->assertEquals(
            array(
                'id'          => 6,
                'title'       => 'test post 1',
                'create_time' => $post->create_time,
                'author_id'   => 1,
                'content'     => 'test post content 1'
            ),
            $post->getAttributes()
        );
        $this->assertFalse($post->isNewRecord);
        $this->assertEquals($post->getAttributes(false), Post2::model()->findByPk($post->id)->getAttributes(false));
    }

    public function testUpdate()
    {

        // test save
        $post = Post2::model()->findByPk(1);
        $this->assertFalse($post->isNewRecord);
        $this->assertEquals('post 1', $post->title);
        $post->title = 'test post 1';
        $this->assertTrue($post->save());
        $this->assertFalse($post->isNewRecord);
        $this->assertEquals('test post 1', $post->title);
        $this->assertEquals('test post 1', Post2::model()->findByPk(1)->title);

        // test updateByPk
        $this->assertEquals(2, Post2::model()->updateByPk(array(4, 5), array('title' => 'test post')));
        $this->assertEquals('post 2', Post2::model()->findByPk(2)->title);
        $this->assertEquals('test post', Post2::model()->findByPk(4)->title);
        $this->assertEquals('test post', Post2::model()->findByPk(5)->title);

        // test updateAll
        $this->assertEquals(1, Post2::model()->updateAll(array('title' => 'test post'), 'id=1'));
        $this->assertEquals('test post', Post2::model()->findByPk(1)->title);

        // test updateCounters
        $this->assertEquals(2, Post2::model()->findByPk(2)->author_id);
        $this->assertEquals(2, Post2::model()->findByPk(3)->author_id);
        $this->assertEquals(2, Post2::model()->findByPk(4)->author_id);
        $this->assertEquals(3, Post2::model()->updateCounters(array('author_id' => -1), 'id>2'));
        $this->assertEquals(2, Post2::model()->findByPk(2)->author_id);
        $this->assertEquals(1, Post2::model()->findByPk(3)->author_id);
        $this->assertEquals(1, Post2::model()->findByPk(4)->author_id);
        $this->assertEquals(2, Post2::model()->findByPk(5)->author_id);
    }

    public function testDelete()
    {

        $post = Post2::model()->findByPk(1);
        $this->assertTrue($post->delete());
        $this->assertNull(Post2::model()->findByPk(1));

        $this->assertTrue(Post2::model()->findByPk(2) instanceof Post2);
        $this->assertTrue(Post2::model()->findByPk(3) instanceof Post2);
        $this->assertEquals(2, Post2::model()->deleteByPk(array(2, 3)));
        $this->assertNull(Post2::model()->findByPk(2));
        $this->assertNull(Post2::model()->findByPk(3));

        $this->assertTrue(Post2::model()->findByPk(5) instanceof Post2);
        $this->assertEquals(1, Post2::model()->deleteAll('id=5'));
        $this->assertNull(Post2::model()->findByPk(5));
    }

    public function testRefresh()
    {

        $post         = Post2::model()->findByPk(1);
        $post2        = Post2::model()->findByPk(1);
        $post2->title = 'new post';
        $post2->save();
        $this->assertEquals('post 1', $post->title);
        $this->assertTrue($post->refresh());
        $this->assertEquals('new post', $post->title);
    }

    public function testEquals()
    {

        $post  = Post2::model()->findByPk(1);
        $post2 = Post2::model()->findByPk(1);
        $post3 = Post2::model()->findByPk(3);
        $this->assertEquals(1, $post->primaryKey);
        $this->assertTrue($post->equals($post2));
        $this->assertTrue($post2->equals($post));
        $this->assertFalse($post->equals($post3));
        $this->assertFalse($post3->equals($post));
    }

    public function testValidation()
    {

        $user           = new User2;
        $user->password = 'passtest';
        $this->assertFalse($user->hasErrors());
        $this->assertEquals(array(), $user->errors);
        $this->assertEquals(array(), $user->getErrors('username'));
        $this->assertFalse($user->save());
        $this->assertNull($user->id);
        $this->assertTrue($user->isNewRecord);
        $this->assertTrue($user->hasErrors());
        $this->assertTrue($user->hasErrors('username'));
        $this->assertTrue($user->hasErrors('email'));
        $this->assertFalse($user->hasErrors('password'));
        $this->assertEquals(1, count($user->getErrors('username')));
        $this->assertEquals(1, count($user->getErrors('email')));
        $this->assertEquals(2, count($user->errors));

        $user->clearErrors();
        $this->assertFalse($user->hasErrors());
        $this->assertEquals(array(), $user->errors);
    }

    public function testCompositeKey()
    {

        $order = new Order2;
        $this->assertEquals(array('key1', 'key2'), $order->tableSchema->primaryKey);
        $order = Order2::model()->findByPk(array('key1' => 2, 'key2' => 1));
        $this->assertEquals('order 21', $order->name);
        $orders = Order2::model()->findAllByPk(array(array('key1' => 2, 'key2' => 1), array('key1' => 1, 'key2' => 3)));
        $this->assertEquals('order 13', $orders[0]->name);
        $this->assertEquals('order 21', $orders[1]->name);
    }

    public function testDefault()
    {

        $type = new ComplexType2;
        $this->assertEquals(1, $type->int_col2);
        $this->assertEquals('something', $type->char_col2);
        $this->assertEquals(1.23, $type->real_col);
        $this->assertNull($type->numeric_col);
        $this->assertNull($type->time);
        $this->assertNull($type->bool_col);
        $this->assertTrue($type->bool_col2);
    }

    public function testPublicAttribute()
    {

        $post = new PostExt2;
        $this->assertEquals(array('id' => null, 'title' => 'default title'), $post->getAttributes(false));
        $post = Post2::model()->findByPk(1);
        $this->assertEquals(
            array(
                'id'          => 1,
                'title'       => 'post 1',
                'create_time' => '2004-10-19 10:23:54',
                'author_id'   => 1,
                'content'     => 'content 1'
            ),
            $post->getAttributes(false)
        );

        $post              = new PostExt2;
        $post->title       = 'test post';
        $post->create_time = '2004-10-19 10:23:53';
        $post->author_id   = 1;
        $post->content     = 'test';
        $post->save();
        $this->assertEquals(
            array(
                'id'          => 6,
                'title'       => 'test post',
                'create_time' => '2004-10-19 10:23:53',
                'author_id'   => 1,
                'content'     => 'test'
            ),
            $post->getAttributes(false)
        );
    }

    public function testLazyRelation()
    {

        // test belongsTo
        $post = Post2::model()->findByPk(2);
        $this->assertTrue($post->author instanceof User2);
        $this->assertEquals(
            array(
                'id'       => 2,
                'username' => 'user2',
                'password' => 'pass2',
                'email'    => 'email2'
            ),
            $post->author->getAttributes(false)
        );

        // test hasOne
        $post = Post2::model()->findByPk(2);
        $this->assertTrue($post->firstComment instanceof Comment2);
        $this->assertEquals(
            array(
                'id'        => 4,
                'content'   => 'comment 4',
                'post_id'   => 2,
                'author_id' => 2
            ),
            $post->firstComment->getAttributes(false)
        );
        $post = Post2::model()->findByPk(4);
        $this->assertNull($post->firstComment);

        // test hasMany
        $post = Post2::model()->findByPk(2);
        $this->assertEquals(2, count($post->comments));
        $this->assertEquals(
            array(
                'id'        => 5,
                'content'   => 'comment 5',
                'post_id'   => 2,
                'author_id' => 2
            ),
            $post->comments[0]->getAttributes(false)
        );
        $this->assertEquals(
            array(
                'id'        => 4,
                'content'   => 'comment 4',
                'post_id'   => 2,
                'author_id' => 2
            ),
            $post->comments[1]->getAttributes(false)
        );
        $post = Post2::model()->findByPk(4);
        $this->assertEquals(array(), $post->comments);

        // test manyMany
        $post = Post2::model()->findByPk(2);
        $this->assertEquals(2, count($post->categories));

        // TODO: when joining, need to replace both placeholders for the two joinin tables
        $this->assertEquals(
            array(
                'id'        => 4,
                'name'      => 'cat 4',
                'parent_id' => 1
            ),
            $post->categories[0]->getAttributes(false)
        );
        $this->assertEquals(
            array(
                'id'        => 1,
                'name'      => 'cat 1',
                'parent_id' => null
            ),
            $post->categories[1]->getAttributes(false)
        );

        $post = Post2::model()->findByPk(4);
        $this->assertEquals(array(), $post->categories);

        // test self join
        $category = Category2::model()->findByPk(5);
        $this->assertEquals(array(), $category->posts);
        $this->assertEquals(2, count($category->children));
        $this->assertEquals(
            array(
                'id'        => 6,
                'name'      => 'cat 6',
                'parent_id' => 5
            ),
            $category->children[0]->getAttributes(false)
        );
        $this->assertEquals(
            array(
                'id'        => 7,
                'name'      => 'cat 7',
                'parent_id' => 5
            ),
            $category->children[1]->getAttributes(false)
        );
        $this->assertTrue($category->parent instanceof Category2);
        $this->assertEquals(
            array(
                'id'        => 1,
                'name'      => 'cat 1',
                'parent_id' => null
            ),
            $category->parent->getAttributes(false)
        );

        $category = Category2::model()->findByPk(2);
        $this->assertEquals(1, count($category->posts));
        $this->assertEquals(array(), $category->children);
        $this->assertNull($category->parent);

        // test composite key
        $order = Order2::model()->findByPk(array('key1' => 1, 'key2' => 2));
        $this->assertEquals(2, count($order->items));
        $order = Order2::model()->findByPk(array('key1' => 2, 'key2' => 1));
        $this->assertEquals(0, count($order->items));
        $item = Item2::model()->findByPk(4);
        $this->assertTrue($item->order instanceof Order2);
        $this->assertEquals(
            array(
                'key1' => 2,
                'key2' => 2,
                'name' => 'order 22'
            ),
            $item->order->getAttributes(false)
        );
    }

    public function testEagerRelation()
    {

        $post = Post2::model()->with('author', 'firstComment', 'comments', 'categories')->findByPk(2);
        $this->assertEquals(
            array(
                'id'       => 2,
                'username' => 'user2',
                'password' => 'pass2',
                'email'    => 'email2'
            ),
            $post->author->getAttributes(false)
        );
        $this->assertTrue($post->firstComment instanceof Comment2);
        $this->assertEquals(
            array(
                'id'        => 4,
                'content'   => 'comment 4',
                'post_id'   => 2,
                'author_id' => 2
            ),
            $post->firstComment->getAttributes(false)
        );
        $this->assertEquals(2, count($post->comments));
        $this->assertEquals(
            array(
                'id'        => 5,
                'content'   => 'comment 5',
                'post_id'   => 2,
                'author_id' => 2
            ),
            $post->comments[0]->getAttributes(false)
        );
        $this->assertEquals(
            array(
                'id'        => 4,
                'content'   => 'comment 4',
                'post_id'   => 2,
                'author_id' => 2
            ),
            $post->comments[1]->getAttributes(false)
        );
        $this->assertEquals(2, count($post->categories));

        $this->assertEquals(
            array(
                'id'        => 4,
                'name'      => 'cat 4',
                'parent_id' => 1
            ),
            $post->categories[0]->getAttributes(false)
        );
        $this->assertEquals(
            array(
                'id'        => 1,
                'name'      => 'cat 1',
                'parent_id' => null
            ),
            $post->categories[1]->getAttributes(false)
        );

        $post = Post2::model()->with('author', 'firstComment', 'comments', 'categories')->findByPk(4);
        $this->assertEquals(
            array(
                'id'       => 2,
                'username' => 'user2',
                'password' => 'pass2',
                'email'    => 'email2'
            ),
            $post->author->getAttributes(false)
        );
        $this->assertNull($post->firstComment);
        $this->assertEquals(array(), $post->comments);
        $this->assertEquals(array(), $post->categories);
    }

    public function testLazyRecursiveRelation()
    {

        $post = PostExt2::model()->findByPk(2);
        $this->assertEquals(2, count($post->comments));
        $this->assertTrue($post->comments[0]->post instanceof Post2);
        $this->assertTrue($post->comments[1]->post instanceof Post2);
        $this->assertTrue($post->comments[0]->author instanceof User2);
        $this->assertTrue($post->comments[1]->author instanceof User2);
        $this->assertEquals(3, count($post->comments[0]->author->posts));
        $this->assertEquals(3, count($post->comments[1]->author->posts));
        $this->assertTrue($post->comments[0]->author->posts[1]->author instanceof User2);

        // test self join
        $category = Category2::model()->findByPk(1);
        $this->assertEquals(2, count($category->nodes));
        $this->assertTrue($category->nodes[0]->parent instanceof Category2);
        $this->assertTrue($category->nodes[1]->parent instanceof Category2);
        $this->assertEquals(
            2,
            count($category->nodes[0]->children)
        ); // row in test.categories with id 5 (has 2 descendants)
        $this->assertEquals(
            0,
            count($category->nodes[1]->children)
        ); // row in test.categories with id 4 (has 0 descendants)
    }

    public function testEagerRecursiveRelation()
    {

        $post = Post2::model()->with(array('comments' => 'author', 'categories'))->findByPk(2);
        $this->assertEquals(2, count($post->comments));
        $this->assertEquals(2, count($post->categories));
    }

    public function testRelationWithCondition()
    {

        $posts = Post2::model()->with('comments')->findAllByPk(array(2, 3, 4), array('order' => 't.id'));
        $this->assertEquals(3, count($posts));
        $this->assertEquals(2, count($posts[0]->comments));
        $this->assertEquals(4, count($posts[1]->comments));
        $this->assertEquals(0, count($posts[2]->comments));

        $post = Post2::model()->with('comments')->findByAttributes(array('id' => 2));
        $this->assertTrue($post instanceof Post2);
        $this->assertEquals(2, count($post->comments));
        $posts = Post2::model()->with('comments')->findAllByAttributes(array('id' => 2));
        $this->assertEquals(1, count($posts));

        $post = Post2::model()->with('comments')->findBySql('select * from test.posts where id=:id', array(':id' => 2));
        $this->assertTrue($post instanceof Post2);
        $posts = Post2::model()->with('comments')->findAllBySql(
            'select * from test.posts where id=:id1 OR id=:id2',
            array(':id1' => 2, ':id2' => 3)
        );
        $this->assertEquals(2, count($posts));

        $post = Post2::model()->with('comments', 'author')->find('t.id=:id', array(':id' => 2));
        $this->assertTrue($post instanceof Post2);

        $posts = Post2::model()->with('comments', 'author')->findAll(
            array(
                'select'    => 'title',
                'condition' => 't.id=:id',
                'limit'     => 1,
                'offset'    => 0,
                'order'     => 't.title',
                'params'    => array(':id' => 2)
            )
        );
        $this->assertTrue($posts[0] instanceof Post2);

        $posts = Post2::model()->with('comments', 'author')->findAll(
            array(
                'select'    => 'title',
                'condition' => 't.id=:id',
                'limit'     => 1,
                'offset'    => 2,
                'order'     => 't.title',
                'params'    => array(':id' => 2)
            )
        );
        $this->assertTrue($posts === array());
    }

    public function testSelfManyMany()
    {

        $user = User2::model()->findByPk(1);
        $this->assertTrue($user instanceof User2);
        $friends = $user->friends;
        $this->assertEquals(count($friends), 2);
        $this->assertEquals($friends[0]->id, 2);
        $this->assertEquals($friends[1]->id, 3);

        $user = User2::model()->with('friends')->findByPk(1);
        $this->assertTrue($user instanceof User2);
        $friends = $user->friends;
        $this->assertEquals(count($friends), 2);
        $this->assertEquals($friends[0]->id, 2);
        $this->assertEquals($friends[1]->id, 3);
    }

    public function testRelationalCount()
    {

        $count = Post2::model()->with('author', 'firstComment', 'comments', 'categories')->count();
        $this->assertEquals(5, $count);

        $count = Post2::model()->with('author', 'firstComment', 'comments', 'categories')->count('t.id=4');
        $this->assertEquals(1, $count);

        $count = Post2::model()->with('author', 'firstComment', 'comments', 'categories')->count('t.id=14');
        $this->assertEquals(0, $count);
    }

    public function testEmptyFinding()
    {

        $post = Post2::model()->with('author', 'firstComment', 'comments', 'categories')->find('t.id=100');
        $this->assertNull($post);

        $posts = Post2::model()->with('author', 'firstComment', 'comments', 'categories')->findAll('t.id=100');
        $this->assertTrue($posts === array());

        $post = Post2::model()->with('author', 'firstComment', 'comments', 'categories')->findBySql(
            'SELECT * FROM test.posts WHERE id=100'
        );
        $this->assertNull($post);

        Post2::model()->with('author', 'firstComment', 'comments', 'categories')->findAllBySql(
            'SELECT * FROM test.posts WHERE id=100'
        );
        $this->assertTrue($posts === array());
    }

    /**
     * @see https://github.com/yiisoft/yii/issues/2122
     */
    public function testIssue2122()
    {

        $user = User2::model()->findByPk(2);
        $this->assertEquals(2, count($user->postsWithParam));
        $this->assertEquals('post 2', $user->postsWithParam[0]->title);
        $this->assertEquals('post 3', $user->postsWithParam[1]->title);
    }

    /**
     * https://github.com/yiisoft/yii/issues/2336
     */
    public function testEmptyModel()
    {

        $post = new NullablePost2();
        $post->insert();

        $post        = new NullablePost2();
        $post->title = 'dummy';
        $post->insert();

        $this->assertEquals(2, $this->db->createCommand('SELECT COUNT(*) FROM "test"."nullable_posts"')->queryScalar());
        $this->assertEquals(
            1,
            $this->db->createCommand(
                'SELECT COUNT(*) FROM "test"."nullable_posts" WHERE LENGTH("title") > 0'
            )->queryScalar()
        );
    }
}


text:
.form-group input[type="checkbox"] {
    display: none;
}

.form-group input[type="checkbox"] + .btn-group > label span {
    width: 20px;
}

.form-group input[type="checkbox"] + .btn-group > label span:first-child {
    display: none;
}
.form-group input[type="checkbox"] + .btn-group > label span:last-child {
    display: inline-block;
}

.form-group input[type="checkbox"]:checked + .btn-group > label span:first-child {
    display: inline-block;
}
.form-group input[type="checkbox"]:checked + .btn-group > label span:last-child {
    display: none;
}


text:
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;

namespace Umbraco.Web.PropertyEditors
{
    /// <summary>
    /// A custom value editor for any property editor that stores a pre-value int id so that we can ensure that the 'value' not the ID get's put into cache
    /// </summary>
    /// <remarks>
    /// This is required for legacy/backwards compatibility, otherwise we'd just store the string version and cache the string version without
    /// needing additional lookups.
    /// </remarks>
    internal class PublishValueValueEditor : PropertyValueEditorWrapper
    {
        private readonly IDataTypeService _dataTypeService;

        internal PublishValueValueEditor(IDataTypeService dataTypeService, PropertyValueEditor wrapped)
            : base(wrapped)
        {
            _dataTypeService = dataTypeService;
        }

        public PublishValueValueEditor(PropertyValueEditor wrapped)
            : this(ApplicationContext.Current.Services.DataTypeService, wrapped)
        {
        }

        /// <summary>
        /// Need to lookup the pre-values and put the string version in cache, not the ID (which is what is stored in the db)
        /// </summary>
        /// <param name="property"></param>
        /// <param name="propertyType"></param>
        /// <param name="dataTypeService"></param>
        /// <returns></returns>
        public override string ConvertDbToString(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
        {
            if (property.Value == null)
                return null;

            var idAttempt = property.Value.TryConvertTo<int>();
            if (idAttempt.Success)
            {
                var preValId = idAttempt.Result;
                var preVals = GetPreValues(property);
                if (preVals != null)
                {
                    if (preVals.Any(x => x.Value.Id == preValId))
                    {
                        return preVals.Single(x => x.Value.Id == preValId).Value.Value;
                    }

                    LogHelper.Warn<PublishValueValueEditor>("Could not find a pre value with ID " + preValId + " for property alias " + property.Alias);
                }
            }

            return base.ConvertDbToString(property, propertyType, dataTypeService);
        }

        protected IDictionary<string, PreValue> GetPreValues(Property property)
        {
            var preVals = _dataTypeService.GetPreValuesCollectionByDataTypeId(property.PropertyType.DataTypeDefinitionId);
            if (preVals != null)
            {
                var dictionary = preVals.FormatAsDictionary();
                return dictionary;
            }
            return null;
        }
    }
}


text:
using namespace std::tr1;
using std::string;
using std::allocator;
using std::pair;
using std::equal_to;

template class unordered_map<string, float>;
template class unordered_map<string, int,
			     hash<string>, equal_to<string>,
			     allocator<pair<const string, int> > >;
template class unordered_map<string, float,
			     hash<string>, equal_to<string>,
			     allocator<char> >;
template class __unordered_map<string, int,
			       hash<string>, equal_to<string>,
			       allocator<pair<const string, int> >, true>;