text:
package com.terrabeata.wcm.siteRenderer;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.jcr.Node;
import javax.jcr.Session;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.mime.MimeTypeService;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.event.EventUtil;
import org.apache.sling.event.jobs.JobManager;
import org.apache.sling.event.jobs.JobUtil;
import org.apache.sling.event.jobs.Queue;
import org.apache.sling.event.jobs.QueueConfiguration;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.terrabeata.wcm.siteRenderer.api.Publisher;
import com.terrabeata.wcm.siteRenderer.api.PublisherPropertyConstants;
import com.terrabeata.wcm.siteRenderer.api.ResourceConfiguration;
import com.terrabeata.wcm.siteRenderer.api.SiteRenderManager;
import com.terrabeata.wcm.siteRenderer.api.exception.RenderingException;
import com.terrabeata.wcm.siteRenderer.api.job.RenderJobConstants;
import com.terrabeata.wcm.siteRenderer.internal.SiteRendererPersistence;
import com.terrabeata.wcm.siteRenderer.internal.site.SiteParser;

@Component(immediate=true)
@Service(value={SiteRenderManager.class,EventHandler.class})
@Property(name = EventConstants.EVENT_TOPIC,
          value=RenderJobConstants.PUBLISH_JOB_TOPIC)
public class SiteRenderManagerImpl implements
								    SiteRenderManager, EventHandler {

	public static final String DEFAULT_PUBLISHER_NAME =
			"terrabeata-renderer-publisher-default";

	public static final String DEFAULT_QUEUE_NAME =
			"terrabeata-renderer-job-queue";

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

	private static final String configurationFilterFormat =
			"(&(%s=%s) (service.pid=%s*))";

//	private static final String queueConfigurationFilter =
//			String.format(configurationFilterFormat,
//					      new Object[]{"publisher.name",
//		                                DEFAULT_QUEUE_NAME,
//					                    QueueConfiguration.class.getName()});

	private static final String publisherConfigurationFilter =
			String.format(configurationFilterFormat,
					  new Object[]{"publisher.name",
					                DEFAULT_PUBLISHER_NAME,
				                    PublisherImpl.class.getName()});

	@Reference
	private JobManager jobManager;

	@Reference
	private EventAdmin eventAdmin;

	@Reference
	private MimeTypeService mimeTypeService;

	@Reference
	private ConfigurationAdmin configAdmin;

	@Reference
	private ResourceResolverFactory resolverFactory;

	private ComponentContext context;

	private Hashtable<String, Publisher> publishers;

	private SiteParser siteParser;

	private SiteRendererPersistence persistence;

	public SiteRenderManagerImpl() {
		super();
		publishers = new Hashtable<String, Publisher>();
		siteParser = new SiteParser();
	}

	//--------------------------------------------------------------------------
	// OSGi methods
	//--------------------------------------------------------------------------

	@Activate
	@SuppressWarnings("rawtypes")
	private void activate(ComponentContext context) throws Exception {
		this.context = context;

		Dictionary properties = context.getProperties();
		Enumeration keys = properties.keys();

		while (keys.hasMoreElements()) {
			Object key = keys.nextElement();
			log.debug("activate:: {} = {}", key, properties.get(key));
		}

		persistence = new SiteRendererPersistence(resolverFactory);

		Map map = persistence.getData("/");
		if (null == map) {
			persistence.initialize();
			addDefaultPublisherConfig();
			addQueueConfig();
		}
	}

	@Deactivate
	private void deactivate() {

	}

	//--------------------------------------------------------------------------
	// EventHandler implementation
	//--------------------------------------------------------------------------

	public void handleEvent(Event event) {
		log.debug("handleEvent::");
		if (EventUtil.isLocal(event))
		{
			String publisherName = OsgiUtil.toString(
					event.getProperty(
						RenderJobConstants.PROPERTY_EVENT_PUBLISHER_NAME),
						DEFAULT_PUBLISHER_NAME);

			if (publishers.containsKey(publisherName))
			{
				log.info("handleEvent: use publisher, {}, to process " +
						  "publish job",publisherName);

				Publisher publisher = publishers.get(publisherName);
				confirmQueue();
				JobUtil.processJob(event, publisher);
			} else {
				log.warn("handleEvent:: Not able to find publisher, {}",
						 publisherName);
			}
		}
	}

	//--------------------------------------------------------------------------
	// PublishManager implementation
	//--------------------------------------------------------------------------

	public Enumeration<Publisher> getPublishers() {
		return publishers.elements();
	}

	public void registerPublisher(Publisher publisher) {
		log.debug("registerPublisher:: publisher={}", publisher.getName());
		publishers.put(publisher.getName(), publisher);
	}

	public void unregisterPublisher(Publisher publisher) {
		log.debug("unregisterPublisher:: publisher={}", publisher.getName());
		publishers.remove(publisher.getName());
	}

	public Queue getQueue() {
		Iterator<Queue> queues = jobManager.getQueues().iterator();
		while(queues.hasNext()) {
			Queue currentQueue = queues.next();
			String[] topics = currentQueue.getConfiguration().getTopics();
			for (int i = 0; i < topics.length; i++) {
				if (topics[i] == RenderJobConstants.PUBLISH_JOB_TOPIC)
					return currentQueue;
			}
		}
		log.warn("Unable to find queue for publishing site content.");
		return null;
	}

	public void publishTree(ResourceConfiguration resource)
			throws RenderingException {
		if (null == resource)
			throw new IllegalArgumentException(
					"publishTree(ResourceConfiguration): " +
					"resource may not be null");
		Iterator<ResourceConfiguration> configs =
				siteParser.getTreeResources(resource.getResource(),
			    resource.getWebsiteConfiguration());
		while(configs.hasNext()) {
			ResourceConfiguration config = configs.next();
			publishResource(config);
		}
	}

	@SuppressWarnings({"rawtypes","unchecked"})
	public void publishResource(ResourceConfiguration resource)
			throws RenderingException {
		if (null == resource)
			throw new IllegalArgumentException(
					"publishResource(ResourceConfiguration):" +
					" argument, resource, may not be null.");
		log.debug("publishResource:: {}", resource.toString());

		Map map = resource.adaptTo(Map.class);

		map.put(RenderJobConstants.PROPERTY_EVENT_ACTION,
				RenderJobConstants.ACTION_FILE_ADD);
		map.put(JobUtil.PROPERTY_JOB_TOPIC,
				RenderJobConstants.PUBLISH_JOB_TOPIC);
		map.put(JobUtil.PROPERTY_JOB_NAME, UUID.randomUUID().toString());

		Event job = new Event(JobUtil.TOPIC_JOB, map);

		log.debug("publishResource:: post event");
		eventAdmin.postEvent(job);
	}

	//--------------------------------------------------------------------------
	// Private discovery methods
	//--------------------------------------------------------------------------

	private void confirmQueue() {
		if (null != getQueue()) return;

		try {

			// get the bundle location for Sling event - will bind to that
			BundleContext bctx = context.getBundleContext();
			Bundle[] bundles = bctx.getBundles();
			String bundleLocation = null;

			for (int i = 0; i < bundles.length; i++) {
				Bundle bundle = bundles[i];
				if ("org.apache.sling.event".equals(bundle.getSymbolicName())) {
					bundleLocation = bundle.getLocation();
					break;
				}
			}

			Configuration config =
					configAdmin.createFactoryConfiguration(
							QueueConfiguration.class.getName(), bundleLocation);
			// create default queue
			Dictionary<String, Object> props = new Hashtable<String, Object>();
			props.put("queue.name", DEFAULT_QUEUE_NAME);
			props.put("queue.maxparallel", 15);
			props.put("queue.priority", "NORM");
			props.put("queue.retries", 10);
			props.put("queue.retrydelay", 2000);
			props.put("queue.runlocal", true);
			props.put("queue.topics",
					   new String[] {RenderJobConstants.PUBLISH_JOB_TOPIC});
			props.put("queue.type", "ORDERED");
			config.update(props);
			log.debug("confirmQueue:: Queue created");
		} catch (IOException e) {
			log.error("Unable find or create queue to handle publish jobs");
		}
	}

	private void confirmConfigurations() {
		log.debug("confirmConfigurations:: ");
		// Making it so this bundle can use queue configuration is
		// accessible to event bundle AND be detectable by this bundle is
		// problematic. Look for publish config - if exists, assume queue
		// config does too
		try {
			Configuration[] configurations =
				   configAdmin.listConfigurations(publisherConfigurationFilter);
			if (null != configurations && configurations.length > 0) {
				log.debug("confirmDefaultPublisher:: " +
						  "default publisher exists.");
				return;
			}
		} catch (Throwable e1) {
			log.warn("confirmDefaultPublisher:: Error while retrieving " +
					 "default publisher: {}\n {}",
					e1.toString(), getStackTrace(e1));
			e1.printStackTrace();
		}

		try {
			addQueueConfig();
		} catch (IOException e) {
			log.error("Error while creating queue configuration: {}",
					  getStackTrace(e));
			e.printStackTrace();
			// do not add publisher if error
			return;
		}

		try {
			addDefaultPublisherConfig();
		} catch (IOException e) {
			log.error("Error while creating default publisher: {}",
					  getStackTrace(e));
			e.printStackTrace();
		}
	}

	private void addDefaultPublisherConfig() throws IOException{
		Configuration config =
				configAdmin.createFactoryConfiguration(
						PublisherImpl.class.getName());
		// create default queue
		Dictionary<String, Object> props = new Hashtable<String, Object>();
		props.put(PublisherPropertyConstants.PROPERTY_NAME, DEFAULT_PUBLISHER_NAME);
		props.put(PublisherPropertyConstants.PROPERTY_PROTOCOL, "file");
		props.put(PublisherPropertyConstants.PROPERTY_DESTINATION_PATH,
				PublisherPropertyConstants.SLING_HOME_TAG + "/" +
				PublisherPropertyConstants.PUBLISHER_NAME_TAG + "/" +
				PublisherPropertyConstants.WEBSITE_NAME_TAG);
		config.update(props);
	}

	private void addQueueConfig() throws IOException {
		// get the bundle location for Sling event - will bind to that
		BundleContext bctx = context.getBundleContext();
		Bundle[] bundles = bctx.getBundles();
		String bundleLocation = null;

		for (int i = 0; i < bundles.length; i++) {
			Bundle bundle = bundles[i];
			if ("org.apache.sling.event".equals(bundle.getSymbolicName())) {
				bundleLocation = bundle.getLocation();
				break;
			}
		}

		Configuration config =
				configAdmin.createFactoryConfiguration(
						QueueConfiguration.class.getName(), bundleLocation);
		// create default queue
		Dictionary<String, Object> props = new Hashtable<String, Object>();
		props.put("queue.name", DEFAULT_QUEUE_NAME);
		props.put("queue.maxparallel", 15);
		props.put("queue.priority", "NORM");
		props.put("queue.retries", 10);
		props.put("queue.retrydelay", 2000);
		props.put("queue.runlocal", true);
		props.put("queue.topics",
				   new String[] {RenderJobConstants.PUBLISH_JOB_TOPIC});
		props.put("queue.type", "ORDERED");
		log.debug("addQueueConfig - config added");
		config.update(props);
	}

	private String getStackTrace(Throwable aThrowable) {
	    Writer result = new StringWriter();
	    PrintWriter printWriter = new PrintWriter(result);
	    aThrowable.printStackTrace(printWriter);
	    return result.toString();
	  }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. Z. Jl Bot. 27(2): 257 (1989)

#### Original name
Lophodermium irregulare P.R. Johnst., 1989

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
var React = require('react');
var PropTypes = require('prop-types');

var C = React.createClass({
  propTypes: {
    statistics: PropTypes.arrayOf(PropTypes.shape({
      label: PropTypes.string.isRequired,
      value: PropTypes.number,
    })).isRequired,
  }
});

// $ExpectError label is required, value not required
<C statistics={[
  {},
  {label:"",value:undefined},
]}/>;

// $ExpectError label is required, value not required
var props: Array<{label: string, value?: number}> = [
  {},
  {label:"",value:undefined},
];

PropTypes.checkPropTypes({ foo: PropTypes.string }, { foo: 'foo' }, 'value', 'TestComponent');

// $ExpectError missing arguments
PropTypes.checkPropTypes({ foo: PropTypes.string }, { foo: 'foo' });
// $ExpectError missing argument
PropTypes.checkPropTypes({ foo: PropTypes.string }, { foo: 'foo' }, 'value');

// $ExpectError property not found
PropTypes.checkPropTypes({ bar: PropTypes.string }, { foo: 'foo' }, 'value', 'TestComponent'); // error: property not found

// $ExpectError number -> string
PropTypes.checkPropTypes({ foo: PropTypes.string }, { foo: 'foo' }, 'value', 'TestComponent', () => 123);
PropTypes.checkPropTypes({ foo: PropTypes.string }, { foo: 'foo' }, 'value', 'TestComponent', () => null);
PropTypes.checkPropTypes({ foo: PropTypes.string }, { foo: 'foo' }, 'value', 'TestComponent', () => undefined);


text:
package com.amazonaws.services.mturk.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum NotificationTransport {

    Email("Email"),
    SQS("SQS"),
    SNS("SNS");

    private String value;

    private NotificationTransport(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return NotificationTransport corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static NotificationTransport fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (NotificationTransport enumEntry : NotificationTransport.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
import models from './models/models.index';
import socketIoService from './socket-io/socket-io.service';
import emitPromise from './socket-io/socket-io.emit-promise.service';
import validationUtilities from './validation-utilities/validation-utilities';
import notificationsService from './notifications/notifications.service';
import clipboardService from './clipboard/clipboard.service';
import modals from './modals/modals.index';

export default function (ngModule) {
    models(ngModule);
    socketIoService(ngModule);
    emitPromise(ngModule);
    validationUtilities(ngModule);
    notificationsService(ngModule);
    clipboardService(ngModule);
    modals(ngModule);
}


text:
    var i1 = document.getElementById('input1');

    function dispatchInputEvent(target) {
      var e = new Event('input', {
        bubbles: true
      });
      target.dispatchEvent(e);
    };

    suite('preventInvalidInput', function() {

      test('cannot enter invalid input', function() {
        i1.value = '123';
        dispatchInputEvent(i1);
        assert.ok(!i1.value);
      });

      test('preserves valid input after entering invalid input', function() {
        var value = 'abc';
        i1.value = value;
        dispatchInputEvent(i1);
        assert.strictEqual(value, i1.value);
        i1.value = value + '123';
        dispatchInputEvent(i1);
        assert.strictEqual(value, i1.value);
      });

    });


text:
namespace ParquetSharp.Column.Values.Plain
{
    using System.IO;
    using ParquetSharp.Bytes;
    using ParquetSharp.External;
    using ParquetSharp.IO;
    using ParquetSharp.IO.Api;

    public class BinaryPlainValuesReader : ValuesReader
    {
        private static readonly Log LOG = Log.getLog(typeof(BinaryPlainValuesReader));
        private ByteBuffer @in;
        private int _offset;

        public override Binary readBytes()
        {
            try
            {
                int length = BytesUtils.readIntLittleEndian(@in, _offset);
                int start = _offset + 4;
                _offset = start + length;
                return Binary.fromConstantByteBuffer(@in, start, length);
            }
            catch (IOException e)
            {
                throw new ParquetDecodingException("could not read bytes at offset " + _offset, e);
            }
            catch (RuntimeException e)
            {
                throw new ParquetDecodingException("could not read bytes at offset " + _offset, e);
            }
        }

        public override void skip()
        {
            try
            {
                int length = BytesUtils.readIntLittleEndian(@in, _offset);
                _offset += 4 + length;
            }
            catch (IOException e)
            {
                throw new ParquetDecodingException("could not skip bytes at offset " + _offset, e);
            }
            catch (RuntimeException e)
            {
                throw new ParquetDecodingException("could not skip bytes at offset " + _offset, e);
            }
        }

        public override void initFromPage(int valueCount, ByteBuffer @in, int offset)
        {
            if (Log.DEBUG) LOG.debug("init from page at offset " + offset + " for length " + (@in.limit() - offset));
            this.@in = @in;
            this._offset = offset;
        }
    }
}


text:
layout: post
title: Homemade Pulse Sensor
categories: robots
series: Custom PCBs
excerpt:
tags: [robots, SMD, PCB, Pulse Sensor]
color: "#152a55"
image:
  feature: IMG_9109.JPG
  teaser: IMG_9109.JPG
  thumb:
comments: true
---

Originally posted on [www.letsmakerobots.com](www.letsmakerobots.com)

I've been working on re-making the the [Open Hardware Pulse Sensor](http://pulsesensor.com/open-hardware/) so it'd be easy to send off to OSHPark and to make at home. I'm not sure, but I think I started this projects in March and I've just now finished it.

The bit of encouragement I needed was when hackaday.com put it up as their "[Fail of the Week.](http://hackaday.com/2013/09/19/fail-of-the-week-smoking-pulse-sensor-and-ble-dissappointment/)"  I thought I was going to be mature about it.  But those four red letters started eating at me, so I gave it another go.  Weirdly, I got it working.

I believe there were three problems:

1.  I had mixed up the op-amps _again_.  In my defense, I've got 5 different ICs flying about in the same package as the op-amp.
2.  The Arduino I'd been plugging into was sitting on a surface that provided enough conductivity to create noise between the 3.3v pin on the underside and A0, which I was using for the op-amp in.
3.  Every time I touched the sensor the exposed vias were shorted through my own conductivity.  Stupid mineral water.

[Video on Making](http://www.youtube.com/watch?v=llYuknlc3uk&feature=share&list=UUKodYd0Fj3TSHzXg7aOJYYQ)

I've already detailed how I [went about making it](http://letsmakerobots.com/node/37815); so, I'll try to stick to repeatability.

**1. Order the parts.**

*   Op-amp:  **.29**  ([**Digi-Key**](http://www.digikey.com/product-detail/en/MCP6001T-I%2FOT/MCP6001T-I%2FOTCT-ND/697158))
*   Light Photo Sensor: **1.23 ([Digi-Key](http://www.digikey.com/product-detail/en/APDS-9008-020/516-2662-1-ND/3909167))**
*   LED:  **.79   ([Digi-Key](http://www.digikey.com/product-detail/en/AM2520ZGC09/754-1423-1-ND/2163781))**
*   0603 Schottky Diode**: .50 ([Digi-Key](http://www.digikey.com/product-detail/en/CD0603-B0130L/CD0603-B0130LCT-ND/3438043?WT.mc_id=PLA_3438043))**
*   Passives:  ~**2.50** **- Resistors: 1 x 470k, 1 x 12k, 2 x 100k, 1 x 10k, 1 x 3.3Meg - Capacitors: 3 x 4.7uF, 2 x 2.2uF**
*   [OSHPark Boards](http://www.oshpark.com/shared_projectss/e3W0qHzw)**: **$**.67 **(minimum 3 boards, costing $2.00. 3/2.00 = ~.67)

 **Total (approximate): $ 5.98**

1. **Make sure you have theses tools.**

*  Clothes iron.
*  Solder at least .022"
*  Flux.
*  [A soldering iron with a "precision" tip](http://www.amazon.com/ZITRADE-5pcs-Soldering-tips-ZITRADES/dp/B009YSPGAS/ref=sr_1_2?s=hi&ie=UTF8&qid=1375550915&sr=1-2&keywords=soldering+tip+.5).
*  [Tacky-putty](http://www.amazon.com/Scotch-Adhesive-Putty-Removable-860/dp/B000AN7EW4).
*  [Precision tweezers.](http://www.fasttech.com/products/0/10002626/1195600-precision-tweezers-3-piece-set)

3. **Solder the light-sensor.**

The light sensor is the hardest bit, so take your time.  I put a little bit of solder on each pad with my soldering-iron, then, cover the soldered pads in flux.  Next, I attempt to align the light-sensor with the pads as close as possible.  After, I put the board with the backside on an over-turned clothes iron.  Let the iron heat up until the solder reflows and the sensor is attached.

![](/images/IMG_0673.jpg)

4. Flip the sensor and lock it to your surface with tacky-putty to solder the LED, passives, and op-amp.  I won't detail this, since my [video](http://www.youtube.com/watch?v=llYuknlc3uk&feature=share&list=UUKodYd0Fj3TSHzXg7aOJYYQ) shows the entire process.

![](/images/Overlays_on_HR.jpg)

5. **Wrap it with tape, cutting a small hole for the LED and light-sensor.**  (I'll come up with a better solution, and a way it to clip it to your body, on the next iteration).

6. **Wire it up to the Arduino **

Left ---- Middle ---- Right

A0 ------ 3.3v --------GND

7. **Run the [Arduino](https://pulse-sensor.googlecode.com/files/PulseSensorAmped_Arduino_1dot2.zip) and [Processing](http://pulse-sensor.googlecode.com/files/PulseSensorAmpd_Processing_1dot1.zip) sketches these [amazing guys](http://pulsesensor.myshopify.com/pages/about-us) provided.**

8. Yell at me if you have problems.


text:
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
list-style: decimal-leading-zero outside; invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

@base: #f938ab;

.box-shadow(@style, @c) when (iscolor(@c)) {
  -webkit-box-shadow: @style @c;
  box-shadow:         @style @c;
}
.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
  .box-shadow(@style, rgba(0, 0, 0, @alpha));
}
.box {
  color: saturate(@base, 5%);
  border-color: lighten(@base, 30%);
  div { .box-shadow(0 0 5px, 30%) }
}

#menu a {
  color: #111;
  .bordered;
}

.post a {
  color: red;
  .bordered;
}

.screen-color {
  @media screen {
    color: green;
    @media (min-width: 768px) {
      color: red;
    }
  }
  @media tv {
    color: black;
  }
}

@base: 5%;
@filler: @base * 2;
@other: @base + @filler;

color: #888 / 4;
background-color: @base-color + #111;
height: 100% / 2 + @filler;

.weird-element {
  content: ~"^//* some horrible but needed css hack";
}

@base: #f04615;
@width: 0.5;

.class {
  width: percentage(@width); // returns `50%`
  color: saturate(@base, 5%);
  background-color: spin(lighten(@base, 25%), 8);
}

/* HEADER
----------------------------------- */
header{
	a{
		font-size: 13px;
	}

	.navbar-collapse li:hover ul{
		display: block;
	}

	.navbar-beyond{
		height: 70px;
		.transition(500ms);

		.navbar-brand span{
			font-size: 11px;
		}
	}

	.navbar-beyond-light{
		height: 45px;
		border-bottom: solid 1px #e7e7e7;
		background-color: @color_bluegrey1 !important;

		.navbar-brand{
			color: #505050 !important;

			&:hover, &:hover span{
				color: #505050 !important;
			}

			span{
				display: none;
			}
		}
	}

	.navbar-beyond-dark{
		background-color: rgba(0,0,0,0.85);
		border-bottom: none;

		.navbar-brand{
			color: #f0f0f0 !important;

			&:hover, &:hover span{
				color: #f0f0f0 !important;
			}
		}

		.nav>li>a {
			color: #d0d0d0 !important;
		}

		.navbar-collapse{
			padding: 10px 0px 0px 0px;
		}
	}
}


text:
			Posted on

			by


text:
package insights

import original "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2018-03-01/insights"

type ActionGroupsClient = original.ActionGroupsClient
type ActivityLogAlertsClient = original.ActivityLogAlertsClient
type ActivityLogsClient = original.ActivityLogsClient
type AlertRuleIncidentsClient = original.AlertRuleIncidentsClient
type AlertRulesClient = original.AlertRulesClient
type AutoscaleSettingsClient = original.AutoscaleSettingsClient

const (
	DefaultBaseURI = original.DefaultBaseURI
)

type BaseClient = original.BaseClient
type DiagnosticSettingsClient = original.DiagnosticSettingsClient
type DiagnosticSettingsCategoryClient = original.DiagnosticSettingsCategoryClient
type EventCategoriesClient = original.EventCategoriesClient
type LogProfilesClient = original.LogProfilesClient
type MetricAlertsClient = original.MetricAlertsClient
type MetricAlertsStatusClient = original.MetricAlertsStatusClient
type MetricBaselineClient = original.MetricBaselineClient
type MetricDefinitionsClient = original.MetricDefinitionsClient
type MetricsClient = original.MetricsClient
type AggregationType = original.AggregationType

const (
	Average AggregationType = original.Average
	Count   AggregationType = original.Count
	Maximum AggregationType = original.Maximum
	Minimum AggregationType = original.Minimum
	None    AggregationType = original.None
	Total   AggregationType = original.Total
)

type AlertSeverity = original.AlertSeverity

const (
	Four  AlertSeverity = original.Four
	One   AlertSeverity = original.One
	Three AlertSeverity = original.Three
	Two   AlertSeverity = original.Two
	Zero  AlertSeverity = original.Zero
)

type CategoryType = original.CategoryType

const (
	Logs    CategoryType = original.Logs
	Metrics CategoryType = original.Metrics
)

type ComparisonOperationType = original.ComparisonOperationType

const (
	Equals             ComparisonOperationType = original.Equals
	GreaterThan        ComparisonOperationType = original.GreaterThan
	GreaterThanOrEqual ComparisonOperationType = original.GreaterThanOrEqual
	LessThan           ComparisonOperationType = original.LessThan
	LessThanOrEqual    ComparisonOperationType = original.LessThanOrEqual
	NotEquals          ComparisonOperationType = original.NotEquals
)

type ConditionalOperator = original.ConditionalOperator

const (
	ConditionalOperatorEqual       ConditionalOperator = original.ConditionalOperatorEqual
	ConditionalOperatorGreaterThan ConditionalOperator = original.ConditionalOperatorGreaterThan
	ConditionalOperatorLessThan    ConditionalOperator = original.ConditionalOperatorLessThan
)

type ConditionOperator = original.ConditionOperator

const (
	ConditionOperatorGreaterThan        ConditionOperator = original.ConditionOperatorGreaterThan
	ConditionOperatorGreaterThanOrEqual ConditionOperator = original.ConditionOperatorGreaterThanOrEqual
	ConditionOperatorLessThan           ConditionOperator = original.ConditionOperatorLessThan
	ConditionOperatorLessThanOrEqual    ConditionOperator = original.ConditionOperatorLessThanOrEqual
)

type Enabled = original.Enabled

const (
	False Enabled = original.False
	True  Enabled = original.True
)

type EventLevel = original.EventLevel

const (
	Critical      EventLevel = original.Critical
	Error         EventLevel = original.Error
	Informational EventLevel = original.Informational
	Verbose       EventLevel = original.Verbose
	Warning       EventLevel = original.Warning
)

type MetricStatisticType = original.MetricStatisticType

const (
	MetricStatisticTypeAverage MetricStatisticType = original.MetricStatisticTypeAverage
	MetricStatisticTypeMax     MetricStatisticType = original.MetricStatisticTypeMax
	MetricStatisticTypeMin     MetricStatisticType = original.MetricStatisticTypeMin
	MetricStatisticTypeSum     MetricStatisticType = original.MetricStatisticTypeSum
)

type MetricTriggerType = original.MetricTriggerType

const (
	MetricTriggerTypeConsecutive MetricTriggerType = original.MetricTriggerTypeConsecutive
	MetricTriggerTypeTotal       MetricTriggerType = original.MetricTriggerTypeTotal
)

type OdataType = original.OdataType

const (
	OdataTypeMicrosoftAzureManagementInsightsModelsRuleManagementEventDataSource OdataType = original.OdataTypeMicrosoftAzureManagementInsightsModelsRuleManagementEventDataSource
	OdataTypeMicrosoftAzureManagementInsightsModelsRuleMetricDataSource          OdataType = original.OdataTypeMicrosoftAzureManagementInsightsModelsRuleMetricDataSource
	OdataTypeRuleDataSource                                                      OdataType = original.OdataTypeRuleDataSource
)

type OdataTypeBasicAction = original.OdataTypeBasicAction

const (
	OdataTypeAction                                                                                OdataTypeBasicAction = original.OdataTypeAction
	OdataTypeMicrosoftWindowsAzureManagementMonitoringAlertsModelsMicrosoftAppInsightsNexusDataContractsResourcesScheduledQueryRulesAlertingAction OdataTypeBasicAction = original.OdataTypeMicrosoftWindowsAzureManagementMonitoringAlertsModelsMicrosoftAppInsightsNexusDataContractsResourcesScheduledQueryRulesAlertingAction
)

type OdataTypeBasicMetricAlertCriteria = original.OdataTypeBasicMetricAlertCriteria

const (
	OdataTypeMetricAlertCriteria                                       OdataTypeBasicMetricAlertCriteria = original.OdataTypeMetricAlertCriteria
	OdataTypeMicrosoftAzureMonitorSingleResourceMultipleMetricCriteria OdataTypeBasicMetricAlertCriteria = original.OdataTypeMicrosoftAzureMonitorSingleResourceMultipleMetricCriteria
)

type OdataTypeBasicRuleAction = original.OdataTypeBasicRuleAction

const (
	OdataTypeMicrosoftAzureManagementInsightsModelsRuleEmailAction   OdataTypeBasicRuleAction = original.OdataTypeMicrosoftAzureManagementInsightsModelsRuleEmailAction
	OdataTypeMicrosoftAzureManagementInsightsModelsRuleWebhookAction OdataTypeBasicRuleAction = original.OdataTypeMicrosoftAzureManagementInsightsModelsRuleWebhookAction
	OdataTypeRuleAction                                              OdataTypeBasicRuleAction = original.OdataTypeRuleAction
)

type OdataTypeBasicRuleCondition = original.OdataTypeBasicRuleCondition

const (
	OdataTypeMicrosoftAzureManagementInsightsModelsLocationThresholdRuleCondition OdataTypeBasicRuleCondition = original.OdataTypeMicrosoftAzureManagementInsightsModelsLocationThresholdRuleCondition
	OdataTypeMicrosoftAzureManagementInsightsModelsManagementEventRuleCondition   OdataTypeBasicRuleCondition = original.OdataTypeMicrosoftAzureManagementInsightsModelsManagementEventRuleCondition
	OdataTypeMicrosoftAzureManagementInsightsModelsThresholdRuleCondition         OdataTypeBasicRuleCondition = original.OdataTypeMicrosoftAzureManagementInsightsModelsThresholdRuleCondition
	OdataTypeRuleCondition                                                        OdataTypeBasicRuleCondition = original.OdataTypeRuleCondition
)

type ProvisioningState = original.ProvisioningState

const (
	Canceled  ProvisioningState = original.Canceled
	Deploying ProvisioningState = original.Deploying
	Failed    ProvisioningState = original.Failed
	Succeeded ProvisioningState = original.Succeeded
)

type QueryType = original.QueryType

const (
	ResultCount QueryType = original.ResultCount
)

type ReceiverStatus = original.ReceiverStatus

const (
	ReceiverStatusDisabled     ReceiverStatus = original.ReceiverStatusDisabled
	ReceiverStatusEnabled      ReceiverStatus = original.ReceiverStatusEnabled
	ReceiverStatusNotSpecified ReceiverStatus = original.ReceiverStatusNotSpecified
)

type ResultType = original.ResultType

const (
	Data     ResultType = original.Data
	Metadata ResultType = original.Metadata
)

type ScaleDirection = original.ScaleDirection

const (
	ScaleDirectionDecrease ScaleDirection = original.ScaleDirectionDecrease
	ScaleDirectionIncrease ScaleDirection = original.ScaleDirectionIncrease
	ScaleDirectionNone     ScaleDirection = original.ScaleDirectionNone
)

type ScaleType = original.ScaleType

const (
	ChangeCount        ScaleType = original.ChangeCount
	ExactCount         ScaleType = original.ExactCount
	PercentChangeCount ScaleType = original.PercentChangeCount
)

type Sensitivity = original.Sensitivity

const (
	High   Sensitivity = original.High
	Low    Sensitivity = original.Low
	Medium Sensitivity = original.Medium
)

type TimeAggregationOperator = original.TimeAggregationOperator

const (
	TimeAggregationOperatorAverage TimeAggregationOperator = original.TimeAggregationOperatorAverage
	TimeAggregationOperatorLast    TimeAggregationOperator = original.TimeAggregationOperatorLast
	TimeAggregationOperatorMaximum TimeAggregationOperator = original.TimeAggregationOperatorMaximum
	TimeAggregationOperatorMinimum TimeAggregationOperator = original.TimeAggregationOperatorMinimum
	TimeAggregationOperatorTotal   TimeAggregationOperator = original.TimeAggregationOperatorTotal
)

type TimeAggregationType = original.TimeAggregationType

const (
	TimeAggregationTypeAverage TimeAggregationType = original.TimeAggregationTypeAverage
	TimeAggregationTypeCount   TimeAggregationType = original.TimeAggregationTypeCount
	TimeAggregationTypeMaximum TimeAggregationType = original.TimeAggregationTypeMaximum
	TimeAggregationTypeMinimum TimeAggregationType = original.TimeAggregationTypeMinimum
	TimeAggregationTypeTotal   TimeAggregationType = original.TimeAggregationTypeTotal
)

type Unit = original.Unit

const (
	UnitBytes          Unit = original.UnitBytes
	UnitByteSeconds    Unit = original.UnitByteSeconds
	UnitBytesPerSecond Unit = original.UnitBytesPerSecond
	UnitCount          Unit = original.UnitCount
	UnitCountPerSecond Unit = original.UnitCountPerSecond
	UnitMilliSeconds   Unit = original.UnitMilliSeconds
	UnitPercent        Unit = original.UnitPercent
	UnitSeconds        Unit = original.UnitSeconds
	UnitUnspecified    Unit = original.UnitUnspecified
)

type BasicAction = original.BasicAction
type Action = original.Action
type ActionGroup = original.ActionGroup
type ActionGroupList = original.ActionGroupList
type ActionGroupPatch = original.ActionGroupPatch
type ActionGroupPatchBody = original.ActionGroupPatchBody
type ActionGroupResource = original.ActionGroupResource
type ActivityLogAlert = original.ActivityLogAlert
type ActivityLogAlertActionGroup = original.ActivityLogAlertActionGroup
type ActivityLogAlertActionList = original.ActivityLogAlertActionList
type ActivityLogAlertAllOfCondition = original.ActivityLogAlertAllOfCondition
type ActivityLogAlertLeafCondition = original.ActivityLogAlertLeafCondition
type ActivityLogAlertList = original.ActivityLogAlertList
type ActivityLogAlertPatch = original.ActivityLogAlertPatch
type ActivityLogAlertPatchBody = original.ActivityLogAlertPatchBody
type ActivityLogAlertResource = original.ActivityLogAlertResource
type AlertingAction = original.AlertingAction
type AlertRule = original.AlertRule
type AlertRuleResource = original.AlertRuleResource
type AlertRuleResourceCollection = original.AlertRuleResourceCollection
type AlertRuleResourcePatch = original.AlertRuleResourcePatch
type AutomationRunbookReceiver = original.AutomationRunbookReceiver
type AutoscaleNotification = original.AutoscaleNotification
type AutoscaleProfile = original.AutoscaleProfile
type AutoscaleSetting = original.AutoscaleSetting
type AutoscaleSettingResource = original.AutoscaleSettingResource
type AutoscaleSettingResourceCollection = original.AutoscaleSettingResourceCollection
type AutoscaleSettingResourceCollectionIterator = original.AutoscaleSettingResourceCollectionIterator
type AutoscaleSettingResourceCollectionPage = original.AutoscaleSettingResourceCollectionPage
type AutoscaleSettingResourcePatch = original.AutoscaleSettingResourcePatch
type AzNsActionGroup = original.AzNsActionGroup
type AzureAppPushReceiver = original.AzureAppPushReceiver
type AzureFunctionReceiver = original.AzureFunctionReceiver
type Baseline = original.Baseline
type BaselineMetadataValue = original.BaselineMetadataValue
type BaselineProperties = original.BaselineProperties
type BaselineResponse = original.BaselineResponse
type CalculateBaselineResponse = original.CalculateBaselineResponse
type DiagnosticSettings = original.DiagnosticSettings
type DiagnosticSettingsCategory = original.DiagnosticSettingsCategory
type DiagnosticSettingsCategoryResource = original.DiagnosticSettingsCategoryResource
type DiagnosticSettingsCategoryResourceCollection = original.DiagnosticSettingsCategoryResourceCollection
type DiagnosticSettingsResource = original.DiagnosticSettingsResource
type DiagnosticSettingsResourceCollection = original.DiagnosticSettingsResourceCollection
type EmailNotification = original.EmailNotification
type EmailReceiver = original.EmailReceiver
type EnableRequest = original.EnableRequest
type ErrorResponse = original.ErrorResponse
type EventCategoryCollection = original.EventCategoryCollection
type EventData = original.EventData
type EventDataCollection = original.EventDataCollection
type EventDataCollectionIterator = original.EventDataCollectionIterator
type EventDataCollectionPage = original.EventDataCollectionPage
type HTTPRequestInfo = original.HTTPRequestInfo
type Incident = original.Incident
type IncidentListResult = original.IncidentListResult
type ItsmReceiver = original.ItsmReceiver
type LocalizableString = original.LocalizableString
type LocationThresholdRuleCondition = original.LocationThresholdRuleCondition
type LogicAppReceiver = original.LogicAppReceiver
type LogMetricTrigger = original.LogMetricTrigger
type LogProfileCollection = original.LogProfileCollection
type LogProfileProperties = original.LogProfileProperties
type LogProfileResource = original.LogProfileResource
type LogProfileResourcePatch = original.LogProfileResourcePatch
type LogSearchRule = original.LogSearchRule
type LogSearchRulePatch = original.LogSearchRulePatch
type LogSearchRuleResource = original.LogSearchRuleResource
type LogSearchRuleResourceCollection = original.LogSearchRuleResourceCollection
type LogSearchRuleResourcePatch = original.LogSearchRuleResourcePatch
type LogSettings = original.LogSettings
type ManagementEventAggregationCondition = original.ManagementEventAggregationCondition
type ManagementEventRuleCondition = original.ManagementEventRuleCondition
type MetadataValue = original.MetadataValue
type Metric = original.Metric
type MetricAlertAction = original.MetricAlertAction
type BasicMetricAlertCriteria = original.BasicMetricAlertCriteria
type MetricAlertCriteria = original.MetricAlertCriteria
type MetricAlertProperties = original.MetricAlertProperties
type MetricAlertResource = original.MetricAlertResource
type MetricAlertResourceCollection = original.MetricAlertResourceCollection
type MetricAlertResourcePatch = original.MetricAlertResourcePatch
type MetricAlertSingleResourceMultipleMetricCriteria = original.MetricAlertSingleResourceMultipleMetricCriteria
type MetricAlertStatus = original.MetricAlertStatus
type MetricAlertStatusCollection = original.MetricAlertStatusCollection
type MetricAlertStatusProperties = original.MetricAlertStatusProperties
type MetricAvailability = original.MetricAvailability
type MetricCriteria = original.MetricCriteria
type MetricDefinition = original.MetricDefinition
type MetricDefinitionCollection = original.MetricDefinitionCollection
type MetricDimension = original.MetricDimension
type MetricSettings = original.MetricSettings
type MetricTrigger = original.MetricTrigger
type MetricValue = original.MetricValue
type Operation = original.Operation
type OperationDisplay = original.OperationDisplay
type OperationListResult = original.OperationListResult
type ProxyOnlyResource = original.ProxyOnlyResource
type Recurrence = original.Recurrence
type RecurrentSchedule = original.RecurrentSchedule
type Resource = original.Resource
type Response = original.Response
type RetentionPolicy = original.RetentionPolicy
type BasicRuleAction = original.BasicRuleAction
type RuleAction = original.RuleAction
type BasicRuleCondition = original.BasicRuleCondition
type RuleCondition = original.RuleCondition
type BasicRuleDataSource = original.BasicRuleDataSource
type RuleDataSource = original.RuleDataSource
type RuleEmailAction = original.RuleEmailAction
type RuleManagementEventClaimsDataSource = original.RuleManagementEventClaimsDataSource
type RuleManagementEventDataSource = original.RuleManagementEventDataSource
type RuleMetricDataSource = original.RuleMetricDataSource
type RuleWebhookAction = original.RuleWebhookAction
type ScaleAction = original.ScaleAction
type ScaleCapacity = original.ScaleCapacity
type ScaleRule = original.ScaleRule
type Schedule = original.Schedule
type SenderAuthorization = original.SenderAuthorization
type SmsReceiver = original.SmsReceiver
type Source = original.Source
type ThresholdRuleCondition = original.ThresholdRuleCondition
type TimeSeriesElement = original.TimeSeriesElement
type TimeSeriesInformation = original.TimeSeriesInformation
type TimeWindow = original.TimeWindow
type TriggerCondition = original.TriggerCondition
type VoiceReceiver = original.VoiceReceiver
type WebhookNotification = original.WebhookNotification
type WebhookReceiver = original.WebhookReceiver
type OperationsClient = original.OperationsClient
type ScheduledQueryRulesClient = original.ScheduledQueryRulesClient
type TenantActivityLogsClient = original.TenantActivityLogsClient

func NewActionGroupsClient(subscriptionID string) ActionGroupsClient {
	return original.NewActionGroupsClient(subscriptionID)
}
func NewActionGroupsClientWithBaseURI(baseURI string, subscriptionID string) ActionGroupsClient {
	return original.NewActionGroupsClientWithBaseURI(baseURI, subscriptionID)
}
func NewActivityLogAlertsClient(subscriptionID string) ActivityLogAlertsClient {
	return original.NewActivityLogAlertsClient(subscriptionID)
}
func NewActivityLogAlertsClientWithBaseURI(baseURI string, subscriptionID string) ActivityLogAlertsClient {
	return original.NewActivityLogAlertsClientWithBaseURI(baseURI, subscriptionID)
}
func NewActivityLogsClient(subscriptionID string) ActivityLogsClient {
	return original.NewActivityLogsClient(subscriptionID)
}
func NewActivityLogsClientWithBaseURI(baseURI string, subscriptionID string) ActivityLogsClient {
	return original.NewActivityLogsClientWithBaseURI(baseURI, subscriptionID)
}
func NewAlertRuleIncidentsClient(subscriptionID string) AlertRuleIncidentsClient {
	return original.NewAlertRuleIncidentsClient(subscriptionID)
}
func NewAlertRuleIncidentsClientWithBaseURI(baseURI string, subscriptionID string) AlertRuleIncidentsClient {
	return original.NewAlertRuleIncidentsClientWithBaseURI(baseURI, subscriptionID)
}
func NewAlertRulesClient(subscriptionID string) AlertRulesClient {
	return original.NewAlertRulesClient(subscriptionID)
}
func NewAlertRulesClientWithBaseURI(baseURI string, subscriptionID string) AlertRulesClient {
	return original.NewAlertRulesClientWithBaseURI(baseURI, subscriptionID)
}
func NewAutoscaleSettingsClient(subscriptionID string) AutoscaleSettingsClient {
	return original.NewAutoscaleSettingsClient(subscriptionID)
}
func NewAutoscaleSettingsClientWithBaseURI(baseURI string, subscriptionID string) AutoscaleSettingsClient {
	return original.NewAutoscaleSettingsClientWithBaseURI(baseURI, subscriptionID)
}
func New(subscriptionID string) BaseClient {
	return original.New(subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
	return original.NewWithBaseURI(baseURI, subscriptionID)
}
func NewDiagnosticSettingsClient(subscriptionID string) DiagnosticSettingsClient {
	return original.NewDiagnosticSettingsClient(subscriptionID)
}
func NewDiagnosticSettingsClientWithBaseURI(baseURI string, subscriptionID string) DiagnosticSettingsClient {
	return original.NewDiagnosticSettingsClientWithBaseURI(baseURI, subscriptionID)
}
func NewDiagnosticSettingsCategoryClient(subscriptionID string) DiagnosticSettingsCategoryClient {
	return original.NewDiagnosticSettingsCategoryClient(subscriptionID)
}
func NewDiagnosticSettingsCategoryClientWithBaseURI(baseURI string, subscriptionID string) DiagnosticSettingsCategoryClient {
	return original.NewDiagnosticSettingsCategoryClientWithBaseURI(baseURI, subscriptionID)
}
func NewEventCategoriesClient(subscriptionID string) EventCategoriesClient {
	return original.NewEventCategoriesClient(subscriptionID)
}
func NewEventCategoriesClientWithBaseURI(baseURI string, subscriptionID string) EventCategoriesClient {
	return original.NewEventCategoriesClientWithBaseURI(baseURI, subscriptionID)
}
func NewLogProfilesClient(subscriptionID string) LogProfilesClient {
	return original.NewLogProfilesClient(subscriptionID)
}
func NewLogProfilesClientWithBaseURI(baseURI string, subscriptionID string) LogProfilesClient {
	return original.NewLogProfilesClientWithBaseURI(baseURI, subscriptionID)
}
func NewMetricAlertsClient(subscriptionID string) MetricAlertsClient {
	return original.NewMetricAlertsClient(subscriptionID)
}
func NewMetricAlertsClientWithBaseURI(baseURI string, subscriptionID string) MetricAlertsClient {
	return original.NewMetricAlertsClientWithBaseURI(baseURI, subscriptionID)
}
func NewMetricAlertsStatusClient(subscriptionID string) MetricAlertsStatusClient {
	return original.NewMetricAlertsStatusClient(subscriptionID)
}
func NewMetricAlertsStatusClientWithBaseURI(baseURI string, subscriptionID string) MetricAlertsStatusClient {
	return original.NewMetricAlertsStatusClientWithBaseURI(baseURI, subscriptionID)
}
func NewMetricBaselineClient(subscriptionID string) MetricBaselineClient {
	return original.NewMetricBaselineClient(subscriptionID)
}
func NewMetricBaselineClientWithBaseURI(baseURI string, subscriptionID string) MetricBaselineClient {
	return original.NewMetricBaselineClientWithBaseURI(baseURI, subscriptionID)
}
func NewMetricDefinitionsClient(subscriptionID string) MetricDefinitionsClient {
	return original.NewMetricDefinitionsClient(subscriptionID)
}
func NewMetricDefinitionsClientWithBaseURI(baseURI string, subscriptionID string) MetricDefinitionsClient {
	return original.NewMetricDefinitionsClientWithBaseURI(baseURI, subscriptionID)
}
func NewMetricsClient(subscriptionID string) MetricsClient {
	return original.NewMetricsClient(subscriptionID)
}
func NewMetricsClientWithBaseURI(baseURI string, subscriptionID string) MetricsClient {
	return original.NewMetricsClientWithBaseURI(baseURI, subscriptionID)
}
func PossibleAggregationTypeValues() []AggregationType {
	return original.PossibleAggregationTypeValues()
}
func PossibleAlertSeverityValues() []AlertSeverity {
	return original.PossibleAlertSeverityValues()
}
func PossibleCategoryTypeValues() []CategoryType {
	return original.PossibleCategoryTypeValues()
}
func PossibleComparisonOperationTypeValues() []ComparisonOperationType {
	return original.PossibleComparisonOperationTypeValues()
}
func PossibleConditionalOperatorValues() []ConditionalOperator {
	return original.PossibleConditionalOperatorValues()
}
func PossibleConditionOperatorValues() []ConditionOperator {
	return original.PossibleConditionOperatorValues()
}
func PossibleEnabledValues() []Enabled {
	return original.PossibleEnabledValues()
}
func PossibleEventLevelValues() []EventLevel {
	return original.PossibleEventLevelValues()
}
func PossibleMetricStatisticTypeValues() []MetricStatisticType {
	return original.PossibleMetricStatisticTypeValues()
}
func PossibleMetricTriggerTypeValues() []MetricTriggerType {
	return original.PossibleMetricTriggerTypeValues()
}
func PossibleOdataTypeValues() []OdataType {
	return original.PossibleOdataTypeValues()
}
func PossibleOdataTypeBasicActionValues() []OdataTypeBasicAction {
	return original.PossibleOdataTypeBasicActionValues()
}
func PossibleOdataTypeBasicMetricAlertCriteriaValues() []OdataTypeBasicMetricAlertCriteria {
	return original.PossibleOdataTypeBasicMetricAlertCriteriaValues()
}
func PossibleOdataTypeBasicRuleActionValues() []OdataTypeBasicRuleAction {
	return original.PossibleOdataTypeBasicRuleActionValues()
}
func PossibleOdataTypeBasicRuleConditionValues() []OdataTypeBasicRuleCondition {
	return original.PossibleOdataTypeBasicRuleConditionValues()
}
func PossibleProvisioningStateValues() []ProvisioningState {
	return original.PossibleProvisioningStateValues()
}
func PossibleQueryTypeValues() []QueryType {
	return original.PossibleQueryTypeValues()
}
func PossibleReceiverStatusValues() []ReceiverStatus {
	return original.PossibleReceiverStatusValues()
}
func PossibleResultTypeValues() []ResultType {
	return original.PossibleResultTypeValues()
}
func PossibleScaleDirectionValues() []ScaleDirection {
	return original.PossibleScaleDirectionValues()
}
func PossibleScaleTypeValues() []ScaleType {
	return original.PossibleScaleTypeValues()
}
func PossibleSensitivityValues() []Sensitivity {
	return original.PossibleSensitivityValues()
}
func PossibleTimeAggregationOperatorValues() []TimeAggregationOperator {
	return original.PossibleTimeAggregationOperatorValues()
}
func PossibleTimeAggregationTypeValues() []TimeAggregationType {
	return original.PossibleTimeAggregationTypeValues()
}
func PossibleUnitValues() []Unit {
	return original.PossibleUnitValues()
}
func NewOperationsClient(subscriptionID string) OperationsClient {
	return original.NewOperationsClient(subscriptionID)
}
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
	return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func NewScheduledQueryRulesClient(subscriptionID string) ScheduledQueryRulesClient {
	return original.NewScheduledQueryRulesClient(subscriptionID)
}
func NewScheduledQueryRulesClientWithBaseURI(baseURI string, subscriptionID string) ScheduledQueryRulesClient {
	return original.NewScheduledQueryRulesClientWithBaseURI(baseURI, subscriptionID)
}
func NewTenantActivityLogsClient(subscriptionID string) TenantActivityLogsClient {
	return original.NewTenantActivityLogsClient(subscriptionID)
}
func NewTenantActivityLogsClientWithBaseURI(baseURI string, subscriptionID string) TenantActivityLogsClient {
	return original.NewTenantActivityLogsClientWithBaseURI(baseURI, subscriptionID)
}
func UserAgent() string {
	return original.UserAgent() + " profiles/preview"
}
func Version() string {
	return original.Version()
}


text:
package ui

import (
	"fmt"
	"net/http"

	"github.com/supergiant/supergiant/pkg/client"
	"github.com/supergiant/supergiant/pkg/model"
)

func NewVolume(sg *client.Client, w http.ResponseWriter, r *http.Request) error {
	return renderTemplate(sg, w, "new", map[string]interface{}{
		"title":      "Volumes",
		"formAction": "/ui/volumes",
		"model": map[string]interface{}{
			"kube_name": "",
			"name":      "",
			"type":      "gp2",
			"size":      10,
		},
	})
}

func CreateVolume(sg *client.Client, w http.ResponseWriter, r *http.Request) error {
	m := new(model.Volume)
	err := unmarshalFormInto(r, m)
	if err == nil {
		err = sg.Volumes.Create(m)
	}
	if err != nil {
		return renderTemplate(sg, w, "new", map[string]interface{}{
			"title":      "Volumes",
			"formAction": "/ui/volumes",
			"model":      m,
			"error":      err.Error(),
		})
	}

	http.Redirect(w, r, "/ui/volumes", http.StatusFound)
	return nil
}

func ListVolumes(sg *client.Client, w http.ResponseWriter, r *http.Request) error {
	fields := []map[string]interface{}{
		{
			"title": "Kube ID",
			"type":  "field_value",
			"field": "kube_name",
		},
		{
			"title": "Name",
			"type":  "field_value",
			"field": "name",
		},
		{
			"title": "Type",
			"type":  "field_value",
			"field": "type",
		},
		{
			"title": "Size",
			"type":  "field_value",
			"field": "size",
		},
	}
	return renderTemplate(sg, w, "index", map[string]interface{}{
		"title":         "Volumes",
		"uiBasePath":    "/ui/volumes",
		"apiBasePath":   "/api/v0/volumes",
		"fields":        fields,
		"showNewLink":   true,
		"showStatusCol": true,
		"actionPaths": map[string]string{
			"Edit": "/edit",
		},
		"batchActionPaths": map[string]map[string]string{
			"Delete": map[string]string{
				"method":       "DELETE",
				"relativePath": "",
			},
		},
	})
}

func GetVolume(sg *client.Client, w http.ResponseWriter, r *http.Request) error {
	id, err := parseID(r)
	if err != nil {
		return err
	}
	item := new(model.Volume)
	if err := sg.Volumes.Get(id, item); err != nil {
		return err
	}
	return renderTemplate(sg, w, "show", map[string]interface{}{
		"title": "Volumes",
		"model": item,
	})
}

func EditVolume(sg *client.Client, w http.ResponseWriter, r *http.Request) error {
	id, err := parseID(r)
	if err != nil {
		return err
	}
	item := new(model.Volume)
	if err := sg.Volumes.Get(id, item); err != nil {
		return err
	}
	return renderTemplate(sg, w, "new", map[string]interface{}{
		"title":      "Volumes",
		"formAction": fmt.Sprintf("/ui/volumes/%d", *id),
		"model": map[string]interface{}{
			"size": item.Size,
		},
	})
}

func UpdateVolume(sg *client.Client, w http.ResponseWriter, r *http.Request) error {
	id, err := parseID(r)
	if err != nil {
		return err
	}
	m := new(model.Volume)
	err = unmarshalFormInto(r, m)
	if err == nil {
		err = sg.Volumes.Update(id, m)
	}
	if err != nil {
		return renderTemplate(sg, w, "new", map[string]interface{}{
			"title":      "Volumes",
			"formAction": fmt.Sprintf("/ui/volumes/%d", *id),
			"model":      m,
			"error":      err.Error(),
		})
	}
	http.Redirect(w, r, "/ui/volumes", http.StatusFound)
	return nil
}


text:
<!doctype html>

<meta charset="utf-8">
<title>Real-Time Analytics With Storm - Lesson 2 – Pere Villega</title>
<meta name="description" content="">
<meta name="keywords" content="udacity, mooc, storm, datascience">

<meta name="twitter:title" content="Real-Time Analytics With Storm - Lesson 2 – Pere Villega">
<meta name="twitter:description" content="I just finished the second lesson of Real-Time Analytics with Apache Storm. At this stage I should be able to underst...">
<meta name="twitter:creator" content="@pvillega">

<meta name="twitter:card" content="summary">
<meta name="twitter:image:src" content="/images/default-thumb.png">
<meta property="og:type" content="article">
<meta property="og:image" content="/images/default-thumb.png">

<meta property="og:locale" content="en_US">
<meta property="og:title" content="Real-Time Analytics With Storm - Lesson 2 – Pere Villega">
<meta property="og:description" content="I just finished the second lesson of Real-Time Analytics with Apache Storm. At this stage I should be able to underst...">
<meta property="og:url" content="/real-time-analytics-with-storm-lesson-2">
<meta property="og:site_name" content="Pere Villega">

<meta name="google-site-verification" content="bkCiO-bEhrfzDurtD6X772P1JroB8Q_Hb_I_AVSXqIE">
<meta name="msvalidate.01" content="A144448522476B8417CB74945AA3E085">

<link rel="canonical" href="/real-time-analytics-with-storm-lesson-2">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Pere Villega Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link href='http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700|PT+Serif:400,700,400italic' rel='stylesheet' type='text/css'>

<link rel="stylesheet" href="/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/favicon.ico">

<link rel="shortcut icon" href="/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">

		Pere Villega

About

Articles

Projects

 Feed

Pere Villega

If at first you don't succeed; call it version 1.0

 Email

 Twitter

 LinkedIn

 Github

Real-Time Analytics With Storm - Lesson 2

I just finished the second lesson of Real-Time Analytics with Apache Storm. At this stage I should be able to understand how Sprouts and Bolts interact, and to parse data from Twitter in real time.

It was an interesting lesson. I like a lot the fact that you have videos explaining what to do, then a text document describing steps, followed by a video with the solution. It makes it easy to go through the course, and if you are tight on time you can skip the first video (and go back to it if you get stuck).

I found the use of Twitter data very interesting, seeing all that data coming to you in real time… wow. The only downside is that the server (run in your localhost) to visualise the results was dying under the pressure. The fans of my MacBook Pro were spinning like crazy, but the server couldn't handle the sheer amount of data. Oh, well, lesson learned!

To be honest I have the feeling my solutions for exercise 6 and 7 may not be correct, but due to the visualisation problem mentioned above I can't verify if that's the case. I'm not too worried, though, as the aim of this lesson is to understand the concepts behind connecting Sprouts and Bolts, which I did.

You can find my solutions to this lesson in Github.

Pere Villega

If at first you don't succeed; call it version 1.0

 Email

 Twitter

 LinkedIn

 Github

Real-Time Analytics With Storm - Lesson 2 was published on <time datetime="2015-02-15T21:05:12+00:00" itemprop="datePublished">February 15, 2015</time> by Pere Villega.

You might also enjoy (View all articles)

© 2020 Pere Villega. Powered by Jekyll using the Minimal Mistakes theme.


text:
package com.mesosphere.universe.bijection

import com.mesosphere.universe
import com.mesosphere.universe.bijection.UniverseConversions._
import com.mesosphere.universe.test.TestingPackages
import com.twitter.bijection.Bijection
import com.twitter.bijection.Conversion.asMethod
import com.twitter.bijection.Injection
import org.scalatest.FreeSpec
import org.scalatest.Matchers
import org.scalatest.prop.TableDrivenPropertyChecks
import scala.util.Failure
import scala.util.Success
import scala.util.Try

final class PackagingVersionConverterSpec extends FreeSpec with Matchers with TableDrivenPropertyChecks {

  "v2PackagingVersionToString should" - {

    "succeed in the forward direction" in {
      assertResult("2.0")(universe.v2.model.PackagingVersion("2.0").as[String])
    }

    "succeed in the reverse direction" in {
      assertResult(universe.v2.model.PackagingVersion("3.0")) {
        "3.0".as[universe.v2.model.PackagingVersion]
      }
    }

  }

  "v3V2PackagingVersionToString should" - {
    behave like v3V2PackagingVersionConversions[String]
  }

  "v3V2PackagingVersionToV2PackagingVersion should" - {
    behave like v3V2PackagingVersionConversions[universe.v2.model.PackagingVersion]
  }

  "v3V3PackagingVersionToString should" - {
    behave like v3V3PackagingVersionConversions[String]
  }

  "v3V3PackagingVersionToV2PackagingVersion should" - {
    behave like v3V3PackagingVersionConversions[universe.v2.model.PackagingVersion]
  }

  "v4V4PackagingVersionToString should" - {
    behave like v4V4PackagingVersionConversions[String]
  }

  "v4V4PackagingVersionToV2PackagingVersion should" - {
    behave like v4V4PackagingVersionConversions[universe.v2.model.PackagingVersion]
  }

  "v5V5PackagingVersionToV2PackagingVersion should" - {
    behave like v5V5PackagingVersionConversions[universe.v2.model.PackagingVersion]
  }

  "v5V5PackagingVersionToString should" - {
    behave like v5V5PackagingVersionConversions[String]
  }

  "v3PackagingVersionToString should" - {
    behave like v3PackagingVersionConversions[String]
  }

  "v3PackagingVersionToV2PackagingVersion should" - {
    behave like v3PackagingVersionConversions[universe.v2.model.PackagingVersion]
  }

  private[this] def v3V2PackagingVersionConversions[A](implicit
    v2ToA: Injection[universe.v3.model.V2PackagingVersion.type, A],
    aToString: Bijection[A, String]
  ): Unit = {

    "succeed in the forward direction" in {
      assertResult("2.0")(universe.v3.model.V2PackagingVersion.as[A].as[String])
    }

    """succeed in the reverse direction if the version is "2.0"""" in {
      assertResult(Success(universe.v3.model.V2PackagingVersion)) {
        "2.0".as[A].as[Try[universe.v3.model.V2PackagingVersion.type]]
      }
    }

    "fail in the reverse direction if the string is anything else" in {
      val Failure(iae) = "3.0".as[A].as[Try[universe.v3.model.V2PackagingVersion.type]]
      val message = "Expected value [2.0] for packaging version, but found [3.0]"
      assertResult(message)(iae.getMessage)
    }

  }

  private[this] def v3V3PackagingVersionConversions[A](implicit
    v3ToA: Injection[universe.v3.model.V3PackagingVersion.type, A],
    aToString: Bijection[A, String]
  ): Unit = {

    "succeed in the forward direction" in {
      assertResult("3.0")(universe.v3.model.V3PackagingVersion.as[A].as[String])
    }

    """succeed in the reverse direction if the string is "3.0"""" in {
      assertResult(Success(universe.v3.model.V3PackagingVersion)) {
        "3.0".as[A].as[Try[universe.v3.model.V3PackagingVersion.type]]
      }
    }

    "fail in the reverse direction if the string is anything else" in {
      val Failure(iae) = "2.0".as[A].as[Try[universe.v3.model.V3PackagingVersion.type]]
      val message = "Expected value [3.0] for packaging version, but found [2.0]"
      assertResult(message)(iae.getMessage)
    }

  }

  private[this] def v4V4PackagingVersionConversions[A](implicit
    packagingVersionConverter: Injection[universe.v4.model.V4PackagingVersion.type, A],
    aToString: Bijection[A, String]
  ): Unit = {

    "succeed in the forward direction" in {
      assertResult("4.0")(universe.v4.model.V4PackagingVersion.as[A].as[String])
    }

    """succeed in the reverse direction if the string is "4.0"""" in {
      assertResult(Success(universe.v4.model.V4PackagingVersion)) {
        "4.0".as[A].as[Try[universe.v4.model.V4PackagingVersion.type]]
      }
    }

    "fail in the reverse direction if the string is anything else" in {
      val Failure(iae) = "2.0".as[A].as[Try[universe.v4.model.V4PackagingVersion.type]]
      val message = "Expected value [4.0] for packaging version, but found [2.0]"
      assertResult(message)(iae.getMessage)
    }

  }

  private[this] def v5V5PackagingVersionConversions[A](implicit
   packagingVersionConverter: Injection[universe.v5.model.V5PackagingVersion.type, A],
   aToString: Bijection[A, String]
  ): Unit = {

    "succeed in the forward direction" in {
      assertResult("5.0")(universe.v5.model.V5PackagingVersion.as[A].as[String])
    }

    """succeed in the reverse direction if the string is "5.0"""" in {
      assertResult(Success(universe.v5.model.V5PackagingVersion)) {
        "5.0".as[A].as[Try[universe.v5.model.V5PackagingVersion.type]]
      }
    }

    "fail in the reverse direction if the string is anything else" in {
      val Failure(iae) = "2.0".as[A].as[Try[universe.v5.model.V5PackagingVersion.type]]
      val message = "Expected value [5.0] for packaging version, but found [2.0]"
      assertResult(message)(iae.getMessage)
    }

  }

  private[this] def v3PackagingVersionConversions[A](implicit
    versionToA: Injection[universe.v4.model.PackagingVersion, A],
    aToString: Bijection[A, String]
  ): Unit = {

    "succeed in the forward direction" in {
      forAll(TestingPackages.validPackagingVersions) { (version, string) =>
        version.as[A].as[String] should be (string)
      }
    }

    "succeed in the reverse direction" - {
      "when the version is valid" in {
        forAll(TestingPackages.validPackagingVersions) { (version, string) =>
          string.as[A].as[Try[universe.v4.model.PackagingVersion]] should be (Success(version))
        }
      }
    }

    "fail in the reverse direction if the version is not 2.0 or 3.0 or 4.0" in {
      val invalidVersion = "2.5"
      val Failure(iae) = invalidVersion.as[A].as[Try[universe.v4.model.PackagingVersion]]
      val message = TestingPackages.renderInvalidVersionMessage(invalidVersion)
      assertResult(message)(iae.getMessage)
    }

  }

}


text:
package org.apache.shardingsphere.encrypt.checker;

import org.apache.shardingsphere.encrypt.algorithm.config.AlgorithmProvidedEncryptRuleConfiguration;
import org.apache.shardingsphere.encrypt.constant.EncryptOrder;

/**
 * Algorithm provided encrypt rule configuration checker.
 */
public final class AlgorithmProvidedEncryptRuleConfigurationChecker extends AbstractEncryptRuleConfigurationChecker<AlgorithmProvidedEncryptRuleConfiguration> {

    @Override
    protected boolean isEmptyEncryptors(final AlgorithmProvidedEncryptRuleConfiguration config) {
        return config.getEncryptors().isEmpty();
    }

    @Override
    public int getOrder() {
        return EncryptOrder.ALGORITHM_PROVIDER_ORDER;
    }

    @Override
    public Class<AlgorithmProvidedEncryptRuleConfiguration> getTypeClass() {
        return AlgorithmProvidedEncryptRuleConfiguration.class;
    }
}


text:
- `list`
- `list-only`
- `table`
- `table-only`
- `elements`
- `tag-list`

#### Other representations:

#### Layout containers:

At this moment framework supports following layout containers:

- `hc`  - allows to layout children horizontally
- `lc`  - layouts children horizontally but aligns them to the left side of parent container
- `rc`  - layouts children horizontally but aligns them to the right side of parent container
- `vc`  - allows to layout children vertically
- `tf`  - allows to layout children in a tab folder
- `htf` - allows to layout children in a horizontal tab folder
- `accordition` - allows to layout children in an accordition panel


text:
package com.google.template.soy.parsepasses;

import com.google.common.base.Joiner;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.template.soy.base.IdGenerator;
import com.google.template.soy.base.SoySyntaxException;
import com.google.template.soy.exprtree.AbstractExprNodeVisitor;
import com.google.template.soy.exprtree.DataRefKeyNode;
import com.google.template.soy.exprtree.DataRefNode;
import com.google.template.soy.exprtree.ExprNode;
import com.google.template.soy.exprtree.ExprNode.OperatorNode;
import com.google.template.soy.exprtree.ExprNode.PrimitiveNode;
import com.google.template.soy.exprtree.ExprRootNode;
import com.google.template.soy.exprtree.FunctionNode;
import com.google.template.soy.exprtree.GlobalNode;
import com.google.template.soy.exprtree.OperatorNodes.ConditionalOpNode;
import com.google.template.soy.exprtree.OperatorNodes.PlusOpNode;
import com.google.template.soy.shared.SoyGeneralOptions.SafePrintTagsInferenceLevel;
import static com.google.template.soy.shared.SoyGeneralOptions.SafePrintTagsInferenceLevel.ADVANCED;
import static com.google.template.soy.shared.SoyGeneralOptions.SafePrintTagsInferenceLevel.NONE;
import static com.google.template.soy.shared.SoyGeneralOptions.SafePrintTagsInferenceLevel.SIMPLE;
import com.google.template.soy.soytree.AbstractSoyNodeVisitor;
import com.google.template.soy.soytree.CallNode;
import com.google.template.soy.soytree.CallParamNode;
import com.google.template.soy.soytree.CallParamValueNode;
import com.google.template.soy.soytree.ForNode;
import com.google.template.soy.soytree.ForeachNonemptyNode;
import com.google.template.soy.soytree.PrintDirectiveNode;
import com.google.template.soy.soytree.PrintNode;
import com.google.template.soy.soytree.SoyFileNode;
import com.google.template.soy.soytree.SoyFileSetNode;
import com.google.template.soy.soytree.SoyNode;
import com.google.template.soy.soytree.SoyNode.ParentSoyNode;
import com.google.template.soy.soytree.TemplateNode;
import com.google.template.soy.soytree.TemplateNode.SoyDocSafePath;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Visitor for inferring safe {@code PrintNode}s and optionally adding the {@code |noAutoescape}
 * directive to each {@code PrintNode} inferred to be safe.
 *
 * <p> Inference levels:
 * <pre>
 *     SIMPLE: Infers safe print tags based on '@safe' declarations in the current template's
 *         SoyDoc (same behavior for public and private templates).
 *     ADVANCED: Infers safe print tags based on '@safe' declarations in SoyDoc of public
 *         templates. For private templates, infers safe data from the data being passed in all
 *         the calls to the private template from the rest of the Soy code (in the same compiled
 *         bundle).
 * </pre>
 *
 * <p> Also checks calls between templates. Specifically, if the callee template's SoyDoc specifies
 * '@safe' declarations, then the data being passed in the call must be known to be safe for all of
 * those declared safe data paths. Otherwise, a data-safety-mismatch error is reported.
 *
 * <p> {@link #exec} should be called on a full parse tree. The result is the list of
 * {@code PrintNode}s inferred to be safe, ordered by appearance in the source Soy code.
 *
 * <p> Precondition: All the template names in {@code TemplateNode}s must be full names (i.e. you
 * must execute {@link PrependNamespacesVisitor} before executing this visitor).
 *
 * @author Kai Huang
 */
public class InferSafePrintNodesVisitor extends AbstractSoyNodeVisitor<List<PrintNode>> {

  /** The level of safe-print-tags inference. */
  private final SafePrintTagsInferenceLevel inferenceLevel;

  /** Whether to add '|noAutoescape' to each PrintNode inferred to be safe. */
  private final boolean shouldAddNoAutoescapeDirectives;

  /** The node id generator for the parse tree. Retrieved from the root SoyFileSetNode. */
  private IdGenerator nodeIdGen;

  /** The set of inferred safe PrintNodes (built during the pass). */
  private Set<PrintNode> inferredSafePrintNodesSet;

  /** The list of inferred safe PrintNodes (result of this visitor; ordered by appearance). */
  private List<PrintNode> inferredSafePrintNodes;

  /** Map from each template's name to its node. */
  private Map<String, TemplateNode> templateNameToNodeMap;

  /** [ADVANCED inference] Built by FindPrivateTemplateCallsVisitor and used during main pass. */
  private Map<String, Set<CallNode>> privateTemplateNameToCallsMap;

  /** [ADVANCED inference] Map from CallNode to SafetyInfo for the data (+params) being passed. */
  private Map<CallNode, SafetyInfo> callToDataSafetyInfoMap;

  /** The SafetyInfo corresponding to the current template's data (during pass). */
  private SafetyInfo dataSafetyInfo;

  /** Frames to hold SafetyInfo for current in-scope local vars (during pass). */
  private Deque<Map<String, SafetyInfo>> localVarFrames;

  /** The ComputeExprSafetyInfoVisitor instance to use for the current template (during pass). */
  private ComputeExprSafetyInfoVisitor computeExprSafetyInfoVisitor;

  /**
   * @param inferenceLevel The level of safe-print-tags inference.
   * @param shouldAddNoAutoescapeDirectives Whether to add the '|noAutoescape' directive to each
   */
  public InferSafePrintNodesVisitor(
      SafePrintTagsInferenceLevel inferenceLevel, boolean shouldAddNoAutoescapeDirectives) {
    checkArgument(inferenceLevel != NONE);
    this.inferenceLevel = inferenceLevel;
    this.shouldAddNoAutoescapeDirectives = shouldAddNoAutoescapeDirectives;
  }

  @Override protected void setup() {
    inferredSafePrintNodesSet = Sets.newLinkedHashSet();
  }

  @Override protected List<PrintNode> getResult() {
    return inferredSafePrintNodes;
  }

  // -----------------------------------------------------------------------------------------------
  // Implementations for concrete classes.

  @Override protected void visitInternal(SoyFileSetNode node) {

    if (shouldAddNoAutoescapeDirectives) {
      nodeIdGen = node.getNodeIdGen();
    }

    // Fill in the templateNameToTemplateMap.
    templateNameToNodeMap = Maps.newHashMap();
    for (SoyFileNode soyFile : node.getChildren()) {
      for (TemplateNode template : soyFile.getChildren()) {
        templateNameToNodeMap.put(template.getTemplateName(), template);
      }
    }

    if (inferenceLevel == SIMPLE) {
      visitSoyFileSetNodeForSimpleInference(node);
    } else {
      visitSoyFileSetNodeForAdvancedInference(node);
    }
  }

  private void visitSoyFileSetNodeForSimpleInference(SoyFileSetNode node) {

    for (SoyFileNode soyFile : node.getChildren()) {
      for (TemplateNode template : soyFile.getChildren()) {
        visit(template);
      }
    }

    inferredSafePrintNodes = ImmutableList.copyOf(inferredSafePrintNodesSet);
  }

  private void visitSoyFileSetNodeForAdvancedInference(SoyFileSetNode node) {

    callToDataSafetyInfoMap = Maps.newHashMap();

    // Initialize the set of unprocessed templates.
    Set<TemplateNode> unprocessedTemplates = Sets.newLinkedHashSet();
    for (SoyFileNode soyFile : node.getChildren()) {
      for (TemplateNode template : soyFile.getChildren()) {
        unprocessedTemplates.add(template);
      }
    }

    // Find all the calls of each private template.
    privateTemplateNameToCallsMap = (new FindPrivateTemplateCallsVisitor()).exec(node);

    // Loop repeatedly until there are no more templates that we can process.
    boolean didProcessTemplates;
    do {
      didProcessTemplates = false;

      for (TemplateNode template : ImmutableSet.copyOf(unprocessedTemplates)) {

        // First figure out whether we can process this template yet. We can process it if
        // (a) it's a public template, or
        // (b) it's a private template, but all calls of it have previously been processed.
        boolean canProcessTemplate;
        if (template.isPrivate()) {
          canProcessTemplate = true;
          Set<CallNode> calls = privateTemplateNameToCallsMap.get(template.getTemplateName());
          for (CallNode call : calls) {
            if (! callToDataSafetyInfoMap.containsKey(call)) {
              canProcessTemplate = false;
              break;
            }
          }
        } else {
          canProcessTemplate = true;
        }

        // Process the template (if we can).
        if (canProcessTemplate) {
          visit(template);
          unprocessedTemplates.remove(template);
          didProcessTemplates = true;
        }
      }

    } while (didProcessTemplates);

    // Note: There may be unprocessed templates left (e.g. if there are recursive private templates
    // or circular dependencies among private templates), but this shouldn't be an error since this
    // feature is best-effort only and there will be cases we can't handle.

    // Build the inferred safe print nodes list (ordered by appeareance of the nodes in the tree).
    inferredSafePrintNodes = Lists.newArrayListWithCapacity(inferredSafePrintNodesSet.size());
    for (PrintNode printNode : (new GetAllPrintNodesVisitor()).exec(node)) {
      if (inferredSafePrintNodesSet.contains(printNode)) {
        inferredSafePrintNodes.add(printNode);
      }
    }
  }

  @Override protected void visitInternal(TemplateNode node) {

    if (inferenceLevel == SIMPLE) {
      // SIMPLE inference: Safe data paths always come from SoyDoc.
      dataSafetyInfo = SafetyInfo.createFromSoyDocSafePaths(node.getSoyDocSafePaths());

    } else {
      // ADVANCED inference: For public templates, safe data paths come from SoyDoc; for private
      // templates, safe data paths are inferred by merging safe data paths from all calls.
      if (! node.isPrivate()) {
        dataSafetyInfo = SafetyInfo.createFromSoyDocSafePaths(node.getSoyDocSafePaths());
      } else {
        Set<CallNode> calls = privateTemplateNameToCallsMap.get(node.getTemplateName());
        List<SafetyInfo> callDataSafetyInfos = Lists.newArrayList();
        for (CallNode call : calls) {
          callDataSafetyInfos.add(callToDataSafetyInfoMap.get(call));
        }
        dataSafetyInfo = SafetyInfo.merge(callDataSafetyInfos);
      }
    }

    localVarFrames = new ArrayDeque<Map<String, SafetyInfo>>();

    computeExprSafetyInfoVisitor = new ComputeExprSafetyInfoVisitor(dataSafetyInfo, localVarFrames);

    visitChildren(node);
  }

  @Override protected void visitInternal(PrintNode node) {

    if (computeExprSafetyInfoVisitor.exec(node.getExpr()).isSafe()) {

      inferredSafePrintNodesSet.add(node);

      if (shouldAddNoAutoescapeDirectives) {
        boolean hasNoAutoescapeOrIdDirective = false;
        for (PrintDirectiveNode directive : node.getChildren()) {
          if (directive.getName().equals("|id") || directive.getName().equals("|noAutoescape")) {
            hasNoAutoescapeOrIdDirective = true;
            break;
          }
        }
        if (! hasNoAutoescapeOrIdDirective) {
          node.addChild(new PrintDirectiveNode(nodeIdGen.genStringId(), "|noAutoescape", ""));
        }
      }
    }
  }

  @Override protected void visitInternal(ForeachNonemptyNode node) {

    SafetyInfo foreachVarSafetyInfo = computeExprSafetyInfoVisitor.exec(node.getDataRef());

    Map<String, SafetyInfo> newLocalVarFrame = Maps.newHashMap();
    newLocalVarFrame.put(node.getLocalVarName(), foreachVarSafetyInfo);
    localVarFrames.push(newLocalVarFrame);
    visitChildren(node);
    localVarFrames.pop();
  }

  @Override protected void visitInternal(ForNode node) {

    SafetyInfo forVarSafetyInfo = SafetyInfo.SAFE_LEAF_INSTANCE;

    Map<String, SafetyInfo> newLocalVarFrame = Maps.newHashMap();
    newLocalVarFrame.put(node.getLocalVarName(), forVarSafetyInfo);
    localVarFrames.push(newLocalVarFrame);
    visitChildren(node);
    localVarFrames.pop();
  }

  @Override protected void visitInternal(CallNode node) {

    // Compute the SafetyInfo of the passed data from the 'data' attribute.
    SafetyInfo callDataSafetyInfo = (node.isPassingAllData()) ?
        dataSafetyInfo : computeExprSafetyInfoVisitor.exec(node.getDataRef());

    // Put SafetyInfo for 'param' tags (may replace some parts of the passed data's SafetyInfo).
    if (node.numChildren() > 0) {
      // If there are additional params, clone the original data so we don't modify it.
      callDataSafetyInfo = SafetyInfo.clone(callDataSafetyInfo);
    }
    for (CallParamNode param : node.getChildren()) {
      if (param instanceof CallParamValueNode) {
        SafetyInfo paramValueSafetyInfo =
            computeExprSafetyInfoVisitor.exec(((CallParamValueNode) param).getValueExpr());
        callDataSafetyInfo.putSubinfo(param.getKey(), paramValueSafetyInfo);
      } else {
        // For CallParamContentNode, the param value is assumed to be a safe string because it's the
        // result of template rendering.
        callDataSafetyInfo.putSubinfo(param.getKey(), SafetyInfo.SAFE_LEAF_INSTANCE);
      }
    }

    // Check that the call data's SafetyInfo contains the callee template's declared safe paths.
    TemplateNode callee = templateNameToNodeMap.get(node.getCalleeName());
    List<SoyDocSafePath> unmatchedSoyDocSafePaths =
        callDataSafetyInfo.findUnmatchedSoyDocSafePaths(callee.getSoyDocSafePaths());
    if (unmatchedSoyDocSafePaths.size() > 0) {
      StringBuilder unmatchedSoyDocSafePathsSb = new StringBuilder();
      for (SoyDocSafePath unmatchedSoyDocSafePath : unmatchedSoyDocSafePaths) {
        if (unmatchedSoyDocSafePathsSb.length() > 0) {
          unmatchedSoyDocSafePathsSb.append(", ");
        }
        unmatchedSoyDocSafePathsSb.append(Joiner.on('.').join(unmatchedSoyDocSafePath.path));
      }
      throw new SoySyntaxException(
          "Data safety mismatch for " + node.getTagString() + ": " +
          "the callee template " + callee.getTemplateName() + " expects safe data paths [" +
          unmatchedSoyDocSafePathsSb.toString() +
          "], but these paths are not known to be safe in the data being passed.");
    }

    if (inferenceLevel == ADVANCED) {
      // ADVANCED inference: Add the call data's SafetyInfo to the map. This info will be used later
      // when we process the callee template.
      callToDataSafetyInfoMap.put(node, callDataSafetyInfo);
    }
  }

  // -----------------------------------------------------------------------------------------------
  // Implementations for interfaces.

  @Override protected void visitInternal(SoyNode node) {
    // Nothing to do for non-parent nodes not handled above.
  }

  @Override protected void visitInternal(ParentSoyNode<? extends SoyNode> node) {
    localVarFrames.push(Maps.<String, SafetyInfo>newHashMap());
    visitChildren(node);
    localVarFrames.pop();
  }

  // -----------------------------------------------------------------------------------------------
  // Helper passes.

  /**
   * Private helper for InferSafePrintNodesVisitor to build a map from each private template's name
   * to its set of calls.
   */
  private static class FindPrivateTemplateCallsVisitor
      extends AbstractSoyNodeVisitor<Map<String, Set<CallNode>>> {

    private Map<String, Set<CallNode>> privateTemplateNameToCallsMap;

    @Override protected Map<String, Set<CallNode>> getResult() {
      return privateTemplateNameToCallsMap;
    }

    // ------ Implementations for concrete classes. ------

    @Override protected void visitInternal(SoyFileSetNode node) {

      // Find all the private templates and initialize the result map.
      privateTemplateNameToCallsMap = Maps.newLinkedHashMap();
      for (SoyFileNode soyFile : node.getChildren()) {
        for (TemplateNode template : soyFile.getChildren()) {
          if (template.isPrivate()) {
            privateTemplateNameToCallsMap.put(
                template.getTemplateName(), Sets.<CallNode>newLinkedHashSet());
          }
        }
      }

      visitChildren(node);
    }

    @Override protected void visitInternal(CallNode node) {

      // If this is a call of a private template, add it to the result map.
      Set<CallNode> calls = privateTemplateNameToCallsMap.get(node.getCalleeName());
      if (calls != null) {
        calls.add(node);
      }

      visitChildren(node);
    }

    // ------ Implementations for interfaces. ------

    @Override protected void visitInternal(SoyNode node) {
      // Nothing to do for non-parent nodes not handled above.
    }

    @Override protected void visitInternal(ParentSoyNode<? extends SoyNode> node) {
      visitChildren(node);
    }
  }

  /**
   * Private helper for InferSafePrintNodesVisitor to get a list of all the PrintNodes in the tree,
   * ordered by appearance in the source Soy code.
   */
  private static class GetAllPrintNodesVisitor extends AbstractSoyNodeVisitor<List<PrintNode>> {

    private List<PrintNode> allPrintNodes;

    @Override protected void setup() {
      allPrintNodes = Lists.newArrayList();
    }

    @Override protected List<PrintNode> getResult() {
      return allPrintNodes;
    }

    @Override protected void visitInternal(PrintNode node) {
      allPrintNodes.add(node);
    }

    @Override protected void visitInternal(SoyNode node) {
      // Nothing to do for non-parent nodes not handled above.
    }

    @Override protected void visitInternal(ParentSoyNode<? extends SoyNode> node) {
      visitChildren(node);
    }
  }

  /**
   * Private helper for InferSafePrintNodesVisitor to compute the SafetyInfo corresponding to the
   * result of a given expression.
   */
  private static class ComputeExprSafetyInfoVisitor extends AbstractExprNodeVisitor<SafetyInfo> {

    private static final Set<String> SAFE_FUNCTION_NAMES = ImmutableSet.of(
        "isFirst", "isLast", "index", "hasData", "length", "round", "floor", "ceiling", "min",
        "max", "randomInt");

    private final SafetyInfo dataSafetyInfo;

    private final Deque<Map<String, SafetyInfo>> localVarFrames;

    /** Stack of partial results of subtrees. */
    private Deque<SafetyInfo> resultStack;

    public ComputeExprSafetyInfoVisitor(
        SafetyInfo dataSafetyInfo, Deque<Map<String, SafetyInfo>> localVarFrames) {
      this.dataSafetyInfo = dataSafetyInfo;
      this.localVarFrames = localVarFrames;
    }

    @Override public SafetyInfo exec(ExprNode node) {
      return (node != null) ? super.exec(node) : SafetyInfo.EMPTY_INSTANCE;
    }

    @Override protected void setup() {
      resultStack = new ArrayDeque<SafetyInfo>();
    }

    @Override protected SafetyInfo getResult() {
      return resultStack.peek();
    }

    // ------ Implementations for concrete classes. ------

    @Override protected void visitInternal(ExprRootNode<? extends ExprNode> node) {
      visitChildren(node);
    }

    @Override protected void visitInternal(DataRefNode node) {

      String firstKey = ((DataRefKeyNode) node.getChild(0)).getKey();

      // First check local vars.
      for (Map<String, SafetyInfo> localVarFrame : localVarFrames) {
        SafetyInfo safetyInfo = localVarFrame.get(firstKey);
        if (safetyInfo != null) {
          resultStack.push(safetyInfo);
          return;
        }
      }

      // If got here, this is a data ref (not local var).
      resultStack.push(dataSafetyInfo.getSubinfo(node.getChildren()));
    }

    @Override protected void visitInternal(GlobalNode node) {
      // Assume unsafe.
      resultStack.push(SafetyInfo.EMPTY_INSTANCE);
    }

    @Override protected void visitInternal(PlusOpNode node) {

      for (ExprNode operand : node.getChildren()) {
        visit(operand);
        SafetyInfo operandSafetyInfo = resultStack.pop();
        if (! operandSafetyInfo.isSafe()) {
          resultStack.push(SafetyInfo.EMPTY_INSTANCE);
          return;
        }
      }

      resultStack.push(SafetyInfo.SAFE_LEAF_INSTANCE);
    }

    @Override protected void visitInternal(ConditionalOpNode node) {

      // Note: Only need to check the second and third operands.
      List<ExprNode> operands = node.getChildren();
      for (int i = 1; i <= 2; i++) {
        visit(operands.get(i));
        SafetyInfo operandSafetyInfo = resultStack.pop();
        if (! operandSafetyInfo.isSafe()) {
          resultStack.push(SafetyInfo.EMPTY_INSTANCE);
          return;
        }
      }

      resultStack.push(SafetyInfo.SAFE_LEAF_INSTANCE);
    }

    @Override protected void visitInternal(FunctionNode node) {

      // For now, we just check for a few basic function names, and assume the rest are unsafe.
      // TODO: Figure out how to better handle function return values.
      if (SAFE_FUNCTION_NAMES.contains(node.getFunctionName())) {
        resultStack.push(SafetyInfo.SAFE_LEAF_INSTANCE);
      } else {
        resultStack.push(SafetyInfo.EMPTY_INSTANCE);
      }
    }

    // ------ Implementations for interfaces. ------

    @Override protected void visitInternal(OperatorNode node) {
      // Safe for all mathematical and logical operators. The only exceptions are PlusOpNode and
      // ConditionalOpNode, which are specifically handled above.
      resultStack.push(SafetyInfo.SAFE_LEAF_INSTANCE);
    }

    @Override protected void visitInternal(PrimitiveNode node) {
      resultStack.push(SafetyInfo.SAFE_LEAF_INSTANCE);
    }
  }

}


text:
package org.exist.storage;

import org.apache.log4j.Logger;
import org.exist.EXistException;
import org.exist.backup.Backup;
import org.exist.util.Configuration;
import org.exist.xmldb.XmldbURI;
import org.xml.sax.SAXException;
import org.xmldb.api.base.XMLDBException;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;

/**
 * BackupSystemTask creates an XML backup of the current database into a directory
 * or zip file. Running the backup as a system task guarantees a consistent backup. No
 * other transactions will be allowed while the backup is in progress.
 *
 * The following properties can be used to configure the backup task if passed to the
 * {@link #configure(org.exist.util.Configuration, java.util.Properties)} method:
 *
 *

 *

 *          collection
 *          the collection to backup, specified as an absolute path into the db, e.g. /db/back-me-up
 *

 *

 *          user
 *          a valid user for writing the backup. Usually, this needs to be a user in the dba
 *          database admin group.
 *

 *

 *          password
 *          the password for the user
 *

 *

 *          dir
 *          the output directory where the backup will be written
 *

 *

 *          prefix
 *          a prefix for the generated file name. the final file name will consist of
 *          prefix + current-dateTime + suffix
 *

 *

 *          suffix
 *          a suffix for the generated file name. If it ends with .zip, BackupSystemTask will
 *          directly write the backup into a zip file. Otherwise, it will write into a plain directory.
 *

 *

 */
public class BackupSystemTask implements SystemTask {

    private static final Logger LOG = Logger.getLogger(BackupSystemTask.class);

    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HHmm");

    private String user;
    private String password;
    private File directory;
    private String suffix;
    private XmldbURI collection;
    private String prefix;
    // purge old zip backup files
    private int zipFilesMax = -1;

    public void configure(Configuration config, Properties properties) throws EXistException {
        user = properties.getProperty("user", "guest");
        password = properties.getProperty("password", "guest");
        String collName = properties.getProperty("collection", "xmldb:exist:///db");
        if (!collName.startsWith("xmldb:exist:"))
            collName = "xmldb:exist://" + collName;
        collection = XmldbURI.create(collName);
        LOG.debug("Collection to backup: " + collection.toString() + ". User: " + user);

        suffix = properties.getProperty("suffix", "");
        prefix = properties.getProperty("prefix", "");

        String dir = properties.getProperty("dir", "backup");
        directory = new File(dir);
        if (!directory.isAbsolute()) {
            dir = (String)config.getProperty(BrokerPool.PROPERTY_DATA_DIR) +
                File.separatorChar + dir;
            directory = new File(dir);
        }
        directory.mkdirs();

        // check for max zip files
        String filesMaxStr = properties.getProperty("zip-files-max");
        if (LOG.isDebugEnabled()) LOG.debug("zip-files-max: " + filesMaxStr);
        if (null != filesMaxStr)
            try
            {
                zipFilesMax = new Integer(filesMaxStr).intValue();
            }
            catch (NumberFormatException e) {LOG.debug("zip-files-max property error", e);}
    }

    public void execute(DBBroker broker) throws EXistException {
        String dateTime = df.format(new Date());
        String dest = directory.getAbsolutePath() + File.separatorChar + prefix + dateTime + suffix;

        Backup backup = new Backup(user, password, dest, collection);
        try {
            backup.backup(false, null);
        } catch (XMLDBException e) {
            LOG.debug(e.getMessage(), e);
            throw new EXistException(e.getMessage(), e);
        } catch (IOException e) {
            LOG.debug(e.getMessage(), e);
            throw new EXistException(e.getMessage(), e);
        } catch (SAXException e) {
            LOG.debug(e.getMessage(), e);
            throw new EXistException(e.getMessage(), e);
        }

        // see if old zip files need to be purged
        if (suffix.equals(".zip") && zipFilesMax > 0) purgeZipFiles();
    }

    public void purgeZipFiles()
    {
        if (LOG.isDebugEnabled()) LOG.debug("starting purgeZipFiles()");

        // get all files in target directory
        File[] files = directory.listFiles();

        if (files.length > 0)
        {
            Map sorted = new TreeMap();
            for (int i=0; i < files.length; i++)
            {
                //check for prefix and suffix match
                if (files[i].getName().startsWith(prefix) && files[i].getName().endsWith(suffix))
                {
                    sorted.put(Long.toString(files[i].lastModified()), files[i]);
                }
            }
            if (sorted.size() > zipFilesMax)
            {
               Set keys = sorted.keySet();
                Iterator ki = keys.iterator();
                int i = sorted.size() - zipFilesMax;
                while (ki.hasNext())
                {
                    File f = (File) sorted.get(ki.next());
                    if (i > 0)
                    {
                        if (LOG.isDebugEnabled()) LOG.debug("Purging backup : " + f.getName());
                        f.delete();
                    }
                    i--;
                }
            }
        }
    }

}


text:
"""
Copyright (c) 2013-2014 Heiko Strathmann, Dino Sejdinovic
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 *
1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 *
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the author.
"""

from matplotlib.pyplot import show, imshow
from numpy import shape, reshape
import numpy as np
from scipy.spatial.distance import squareform, pdist, cdist

from kameleon_mcmc.distribution.Banana import Banana
from kameleon_mcmc.kernel.Kernel import Kernel
from kameleon_mcmc.tools.GenericTests import GenericTests

class BrownianKernel(Kernel):
    def __init__(self, alpha=1.0):
        Kernel.__init__(self)
        GenericTests.check_type(alpha,'alpha',float)

        self.alpha = alpha

    def __str__(self):
        s=self.__class__.__name__+ "=["
        s += "alpha="+ str(self.alpha)
        s += ", " + Kernel.__str__(self)
        s += "]"
        return s

    def kernel(self, X, Y=None):

        GenericTests.check_type(X,'X',np.ndarray,2)
        # if X=Y, use more efficient pdist call which exploits symmetry
        normX=reshape(np.linalg.norm(X,axis=1),(len(X),1))
        if Y is None:
            dists = squareform(pdist(X, 'euclidean'))
            normY=normX.T
        else:
            GenericTests.check_type(Y,'Y',np.ndarray,2)
            assert(shape(X)[1]==shape(Y)[1])
            normY=reshape(np.linalg.norm(Y,axis=1),(1,len(Y)))
            dists = cdist(X, Y, 'euclidean')
        K=0.5*(normX**self.alpha+normY**self.alpha-dists**self.alpha)
        return K

    def gradient(self, x, Y):
        raise NotImplementedError()

if __name__ == '__main__':
    distribution = Banana()
    Z = distribution.sample(50).samples
    Z2 = distribution.sample(50).samples
    kernel = BrownianKernel()
    K = kernel.kernel(Z, Z2)
    imshow(K, interpolation="nearest")
    show()


text:
namespace firebase {
namespace testing {
namespace cppsdk {

class TickerObserver {
 public:
  TickerObserver() {}
  virtual ~TickerObserver();

  virtual void Elapse() = 0;
};

void RegisterTicker(TickerObserver* observer);

int64_t TickerNow();

}  // namespace cppsdk
}  // namespace testing
}  // namespace firebase

#endif  // FIREBASE_TESTING_CPPSDK_TICKER_DESKTOP_H_