text:
package io.druid.query.aggregation.post;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import io.druid.data.input.MapBasedRow;
import io.druid.jackson.AggregatorsModule;
import io.druid.java.util.common.granularity.Granularities;
import io.druid.java.util.common.guava.Sequence;
import io.druid.java.util.common.guava.Sequences;
import io.druid.query.aggregation.AggregationTestHelper;
import io.druid.query.aggregation.Aggregator;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.CountAggregator;
import io.druid.query.aggregation.PostAggregator;
import io.druid.query.groupby.GroupByQueryRunnerTest;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class FinalizingFieldAccessPostAggregatorTest
{
  @Rule
  public final TemporaryFolder tempFoler = new TemporaryFolder();

  @Test(expected = UnsupportedOperationException.class)
  public void testComputeWithoutFinalizing()
  {
    String aggName = "rows";
    Aggregator agg = new CountAggregator();
    agg.aggregate();
    agg.aggregate();
    agg.aggregate();

    Map<String, Object> metricValues = Maps.newHashMap();
    metricValues.put(aggName, agg.get());

    FinalizingFieldAccessPostAggregator postAgg = new FinalizingFieldAccessPostAggregator("final_rows", aggName);
    Assert.assertEquals(new Long(3L), postAgg.compute(metricValues));
  }

  @Test
  public void testComputedWithFinalizing()
  {
    String aggName = "biily";
    AggregatorFactory aggFactory = EasyMock.createMock(AggregatorFactory.class);
    EasyMock.expect(aggFactory.finalizeComputation("test"))
            .andReturn(new Long(3L))
            .times(1);
    EasyMock.replay(aggFactory);

    FinalizingFieldAccessPostAggregator postAgg = FinalizingFieldAccessPostAggregator.buildDecorated(
        "final_billy", aggName, ImmutableMap.of(aggName, aggFactory)
    );

    Map<String, Object> metricValues = Maps.newHashMap();
    metricValues.put(aggName, "test");

    Assert.assertEquals(new Long(3L), postAgg.compute(metricValues));
    EasyMock.verify(aggFactory);
  }

  @Test
  public void testComputedInArithmeticPostAggregator()
  {
    String aggName = "billy";
    AggregatorFactory aggFactory = EasyMock.createMock(AggregatorFactory.class);
    EasyMock.expect(aggFactory.finalizeComputation("test"))
            .andReturn(new Long(3L))
            .times(1);
    EasyMock.replay(aggFactory);

    FinalizingFieldAccessPostAggregator postAgg = FinalizingFieldAccessPostAggregator.buildDecorated(
        "final_billy", aggName, ImmutableMap.of(aggName, aggFactory)
    );

    Map<String, Object> metricValues = Maps.newHashMap();
    metricValues.put(aggName, "test");

    List<PostAggregator> postAggsList = Lists.newArrayList(
        new ConstantPostAggregator("roku", 6), postAgg);

    ArithmeticPostAggregator arithmeticPostAggregator = new ArithmeticPostAggregator("add", "+", postAggsList);

    Assert.assertEquals(new Double(9.0f), arithmeticPostAggregator.compute(metricValues));
    EasyMock.verify();
  }

  @Test
  public void testComparatorsWithFinalizing() throws Exception
  {
    String aggName = "billy";
    AggregatorFactory aggFactory = EasyMock.createMock(AggregatorFactory.class);
    EasyMock.expect(aggFactory.finalizeComputation("test_val1"))
            .andReturn(new Long(10L))
            .times(1);
    EasyMock.expect(aggFactory.finalizeComputation("test_val2"))
            .andReturn(new Long(21))
            .times(1);
    EasyMock.expect(aggFactory.finalizeComputation("test_val3"))
            .andReturn(new Long(3))
            .times(1);
    EasyMock.expect(aggFactory.finalizeComputation("test_val4"))
            .andReturn(null)
            .times(1);
    EasyMock.expect(aggFactory.getComparator())
        .andReturn(Ordering.natural().<Long>nullsLast())
        .times(1);
    EasyMock.replay(aggFactory);

    FinalizingFieldAccessPostAggregator postAgg = FinalizingFieldAccessPostAggregator.buildDecorated(
        "final_billy", aggName, ImmutableMap.of(aggName, aggFactory)
    );

    List<Object> computedValues = Lists.newArrayList();
    computedValues.add(postAgg.compute(ImmutableMap.of(aggName, "test_val1")));
    computedValues.add(postAgg.compute(ImmutableMap.of(aggName, "test_val2")));
    computedValues.add(postAgg.compute(ImmutableMap.of(aggName, "test_val3")));
    computedValues.add(postAgg.compute(ImmutableMap.of(aggName, "test_val4")));

    Collections.sort(computedValues, postAgg.getComparator());
    Assert.assertArrayEquals(new Object[]{3L, 10L, 21L, null}, computedValues.toArray(new Object[]{}));
    EasyMock.verify();
  }

  @Test
  public void testComparatorsWithFinalizingAndComparatorNull() throws Exception
  {
    String aggName = "billy";
    AggregatorFactory aggFactory = EasyMock.createMock(AggregatorFactory.class);
    EasyMock.expect(aggFactory.getComparator())
            .andReturn(null)
            .times(1);
    EasyMock.replay(aggFactory);

    FinalizingFieldAccessPostAggregator postAgg = FinalizingFieldAccessPostAggregator.buildDecorated(
        "final_billy", "joe", ImmutableMap.of(aggName, aggFactory));

    List<Object> computedValues = Lists.newArrayList();
    Map<String, Object> forNull = Maps.newHashMap();
    forNull.put("joe", null); // guava does not allow the value to be null.
    computedValues.add(postAgg.compute(ImmutableMap.of("joe", "test_val1")));
    computedValues.add(postAgg.compute(ImmutableMap.of("joe", "test_val2")));
    computedValues.add(postAgg.compute(forNull));
    computedValues.add(postAgg.compute(ImmutableMap.of("joe", "test_val4")));
    Collections.sort(computedValues, postAgg.getComparator());

    Assert.assertArrayEquals(new Object[]{null, "test_val1", "test_val2", "test_val4"}, computedValues.toArray(new Object[]{}));

    EasyMock.verify();
  }

  @Test
  public void testIngestAndQueryWithArithmeticPostAggregator() throws Exception
  {
    AggregationTestHelper helper = AggregationTestHelper.createGroupByQueryAggregationTestHelper(
        Lists.newArrayList(new AggregatorsModule()),
        GroupByQueryRunnerTest.testConfigs().get(0),
        tempFoler
    );

    String metricSpec = "[{\"type\": \"hyperUnique\", \"name\": \"hll_market\", \"fieldName\": \"market\"},"
                        + "{\"type\": \"hyperUnique\", \"name\": \"hll_quality\", \"fieldName\": \"quality\"}]";

    String parseSpec = "{"
                       + "\"type\" : \"string\","
                       + "\"parseSpec\" : {"
                       + "    \"format\" : \"tsv\","
                       + "    \"timestampSpec\" : {"
                       + "        \"column\" : \"timestamp\","
                       + "        \"format\" : \"auto\""
                       + "},"
                       + "    \"dimensionsSpec\" : {"
                       + "        \"dimensions\": [],"
                       + "        \"dimensionExclusions\" : [],"
                       + "        \"spatialDimensions\" : []"
                       + "    },"
                       + "    \"columns\": [\"timestamp\", \"market\", \"quality\", \"placement\", \"placementish\", \"index\"]"
                       + "  }"
                       + "}";

    String query = "{"
                   + "\"queryType\": \"groupBy\","
                   + "\"dataSource\": \"test_datasource\","
                   + "\"granularity\": \"ALL\","
                   + "\"dimensions\": [],"
                   + "\"aggregations\": ["
                   + "  { \"type\": \"hyperUnique\", \"name\": \"hll_market\", \"fieldName\": \"hll_market\" },"
                   + "  { \"type\": \"hyperUnique\", \"name\": \"hll_quality\", \"fieldName\": \"hll_quality\" }"
                   + "],"
                   + "\"postAggregations\": ["
                   + "  { \"type\": \"arithmetic\", \"name\": \"uniq_add\", \"fn\": \"+\", \"fields\":["
                   + "    { \"type\": \"finalizingFieldAccess\", \"name\": \"uniq_market\", \"fieldName\": \"hll_market\" },"
                   + "    { \"type\": \"finalizingFieldAccess\", \"name\": \"uniq_quality\", \"fieldName\": \"hll_quality\" }]"
                   + "  }"
                   + "],"
                   + "\"intervals\": [ \"1970/2050\" ]"
                   + "}";

    Sequence seq = helper.createIndexAndRunQueryOnSegment(
        new File(this.getClass().getClassLoader().getResource("druid.sample.tsv").getFile()),
        parseSpec,
        metricSpec,
        0,
        Granularities.NONE,
        50000,
        query
    );

    MapBasedRow row = (MapBasedRow) Sequences.toList(seq, Lists.newArrayList()).get(0);
    Assert.assertEquals(3.0, row.getMetric("hll_market").floatValue(), 0.1);
    Assert.assertEquals(9.0, row.getMetric("hll_quality").floatValue(), 0.1);
    Assert.assertEquals(12.0, row.getMetric("uniq_add").floatValue(), 0.1);
  }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<settings>
<authentication>
	<api>
		<key>client_key</key>
		<secret>client_secret</secret>
		<callback>http://example.com:8080</callback>
	</api>
</authentication>
<proxy>
	<http>
		<port>8080</port>
		<active>true</active>
		<user>username</user>
		<password>password</password>
		<host>host</host>
	</http>
	<https>
		<port>8080</port>
		<active>true</active>
		<user>username</user>
		<password>password</password>
		<host>host</host>
	</https>
</proxy>
</settings>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Service Sample</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_service_log">Service Log</string>
    <string name="hello_world">Hello world!</string>

</resources>


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Talk generated by Markdown to Reveal</title>

		<meta name="description" content="Generate a Reveal.js talk from a Markdown file.">
		<meta name="author" content="Kyle Tolle">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/black.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

An Intro to Implementing Webhooks in Ruby

With Real Examples, Too!

Who am I?

Kyle Tolle

kyletolle.com |
@kyletolle

Software Engineer at Spatial Networks

Implemented webhooks in Fulcrum, our mobile data
collection service

Ours have been in operation for about a year and a half. I wanted to share
what I've learned. Maybe you'll find it useful or interesting. And I would
love to get your feedback as well.

First off

Ask questions at any time!

If I don't know the answer, I can always ignore you!

Slides for this talk

Presentation:

https://kyletolle.github.io/ruby_webhooks_intro

Code:

https://github.com/kyletolle/ruby_webhooks_intro

Overview

How clients use APIs

Why webhooks are a thing

Barebones webhooks demo

Webhooks integration demo

Other things we can do

Recapping and wrapping up

Our fictional client

Government Agency for Bear Attacks

This fictional organization will help make things a little more concrete.
Explain how they'll use Fulcrum.

Vicious

Relentless

Unexpected

So I'm here

to talk about webhooks

But first

we need some background

Let's start with

what we know

APIs

Why do we have APIs?

Can you shout out some reasons for why we have APIs?
Those are all great ideas.
And I want to focus on one in particular.

APIs allow

people to get their data

How do APIs work?

The client calls us

When our clients want their data, they make a request to our servers.
The people in the office will use our API to get our their data on bear
attacks.

Why are they really trying to get their data?

To do things with it!

Their data is important. Taking action on it is valuable. Acting quickly gives
them an advantage.
They can share it with the public. Analyze it. Try to prevent more bear
attacks.

How do they use the API?

Call our API

Frequently

In a script/application

They write a script to hit our API every few days, or hours, or seconds
and do something with the data they get back.

This is

polling

Polling is straight-forward

And there are some upsides to it, which we won't get into here

But there are some

Downsides

#1

Your client writes the code

How long until

someone murders your servers?

They're likely to push the limits. Maybe they'll write an infinite loop which
hits your API as fast as it can.

Or, they'll have some "mission critical" need for ONE MILLION calls per month.
That's not a made up number. We had someone whose script really did this.

It's bad enough if one person does this, but imagine a few more people doing
the same thing. These legitimate requests can end up swamping your servers.

#2

To react faster, they have to poll more

More polling means

more resources

development time

support time

processors

memory

bandwidth

For you, and for them. These costs add up, especially when you have more
customers.

#3

It's mostly useless

This isn't an existential crisis, I promise.
So what do I mean?

Most polls won't return new data

The rate of their polling is constant.
They do it once every few seconds.
But the rate of their data changing is variable.
Maybe it only changes every couple days, or only during business hours.

Meaning, a majority of their polls won't return anything to act on.

They're hitting up yuor server all the time, and usually it's for nothing.
Talk about disappointing.

#4

And it's still not Real-Time™

Additionally, to approach acting in real-time, they have to poll more and
more frequently. Except that, even when polling faster, they won't have truly
Real-Time™ data.

Okay

we see the disadvantages

But so what?

We already have an API

It exists

It works

Let's come back to what's important

Fast response time

is what's valuable

&

Polling helps them react quickly

But it's only one approach

How else can we help them react quickly?

Because, if we can do this…

It'll make our service more valuable

And that means happier customers

Maybe even some extra revenue

We know that polling is

Client –> Us

Client sends a request to us.

But what about the other way around?

Us –> Client

What about us making a request to the client?
We can invert the relationship.
Flip the equation around.

Hmm, this is interesting

Instead of

them calling us

to see if data changes

We let them know

when data has changed

We do this over the web

since it's common infrastructure

No need to reinvent the wheel here.

Client gives us a URL

&

We have events we watch for

When an event happens, we make an HTTP POST request to our client's URL

Boom, Webhooks!

The Benefits

What are the benefits to this?
They're pretty much the opposite of the disadvantages of polling.

#1

We write the code

Our clients have better things to do than write the code for polling.
So we'll be the ones to write the code to send them their data.

We have control over how the sending works. So we can tailor the loads to
something we define as feasible.

#2

Fewer resources required

Because we're not making as many requests as we would be with polling.
Since we only send them data when something's happened, since we know when
something has happened.
We never make a request that has no data.

#3

We send the data just as it changes

This is Real-Time™

Exciting for integration!

It's like Push Notifications for the web

We've got our background!

How about implementing it?

Let's see a small example

Show us making a single request

Start small & build momentum

Random Number Generator

require_relative '../lib/webhooks'

class RandomNumberGenerator
  include Webhooks

  def initialize
    self.webhooks = %w{http://localhost:9000}
  end

  def generate
    random_number = SecureRandom.random_number(1000)

    send_webhooks(:random_number, :generate, random_number)

    return random_number
  end
end

The Idea

Generate a random number

Send a webhook to our client with that number

We'll have a client server running, Polis.rb

A small web server which logs POST data

In IRB

require ./examples/random_number_generator.rb'
> puts RandomNumberGenerator.new.generate
=> 863

From the client

We see the webhook request

$ PORT=9000 bf
...
Logging POST request:
...
Body:
{"event":"random_number:generate","data":863}
...

I've omitted some of the output, to maintain focus on what' important: the
random number it received.

Webhooks module

require 'net/http'
require 'securerandom'
require 'json'

module Webhooks
  attr_accessor :webhooks

  def send_webhooks(resource, action, data)
    event_type = "#{resource}:#{action}"
    payload    = JSON.generate({
      event: event_type,
      data:  data })

    webhooks.each do |webhook|
      url = URI.parse(webhook)

      Net::HTTP.start(url.host, url.port) do |http|
        headers       = { 'Content-Type' => 'application/json' }
        response      = http.post('/', payload, headers)
      end
    end
  end
end

Client code

...
class Polis < Sinatra::Base
  ...
  post '/' do
    # Note: Thanks to this SO page: http://stackoverflow.com/a/6318491/249218
    http_headers = env.select{|h| h =~ /HTTP_/}
    body_string  = request.body.read

    ...

    logger.info <<-LOG
      Logging POST request:
      Headers:
      #{http_headers}
      Body:
      #{body_string}

    LOG

    status 200
    return body_string
  end

  ...
end

We sent our first webhook!

There's no official spec

It's a general practice to

Send data to a URL

when something happens

The data we send is a JSON encoded string.
Lots of flesibility.
But that also means, there are things you'll have to try out on your own. Or issues you might have to re-solve in a way.

How about another demo?

push a button on a site

generate a random number

send a text message

Random Number Button

Before we push the button

After we push the button

And the text sent

Client code

...
class RandomNumberTexter < Sinatra::Base
  ...

  post '/' do
    request.body.rewind
    post_body = request.body.read

    if request.content_type == 'application/json'
      payload = JSON.parse post_body

      is_random_number_generate = payload['event'] == 'random_number:generate'
      return unless is_random_number_generate

      has_payload_data = payload['data']
      return unless has_payload_data

      random_number = payload['data']

      send_text(random_number)
      status 201

    else
      status 202
    end

    post_body
  end

  ...
end

It still feels like magic

What Can I Do With Them?

Workflows are suddenly much easier

Post support emails, chat requests, and help forum posts in support
chatroom

Kick off continuous integration build after pushing commits to GitHub

Post to engineering chatroom when CI build/tests fails

Text employee when they've been assigned work

Reorder products, when inventory drops below threshold

Once the webhooks scaffolding is in place, you can tie many things together.

After you see examples

the floodgates of possibility open

Who Uses Them?

Loads of companies!

Github

Slack

Dropbox

Twilio

Notes:
Companies large and small use webhooks to do more with their service.
Even if you don't implement them in your software, it can be nice to
understand how other people use them.

Zapier

Connects many services together, using webhooks

Clients can integrate with many services

Webhooks Recap

Communicate events between your server and a client's using HTTP

Webhooks accompany an API to enable powerful integrations

Only real requirement is a web server

You can do lots of cool stuff with them

Other things to think about

Use background jobs

Send requests sequentially

Persisting requests

Handle failures

Performance

But these are for another talk!

Webhooks Docs for Fulcrum

http://fulcrumapp.com/guides/webhooks/webhooks-for-push-notifications/

http://fulcrumapp.com/developers/overview/webhooks/

http://fulcrumapp.com/guides/webhooks/webhooks-getting-started/

What's Next?

Create gem(s) to help others add webhooks to their code

Would you find this useful?

Create/extend tools for using, testing, debugging

Make webhooks easier to debug

Add scoping to webhooks

I'd like to hear from you if you think a gem would be helpful in adding
webhooks to your project.

Links to Code

Webhooks module, random number generator, random number button site

https://github.com/kyletolle/webhooks.rb

Simple webhooks endpoint

https://github.com/kyletolle/polis.rb

Random number texter

https://github.com/kyletolle/random_number_texter

Script to create this presentation

https://github.com/kyletolle/markdown_to_reveal

Thanks!


text:
/**
 * @file lv_line.h
 *
 */

#ifndef LV_LINE_H
#define LV_LINE_H

#ifdef __cplusplus
extern "C" {
#endif

/*********************
 *      INCLUDES
 *********************/
#ifdef LV_CONF_INCLUDE_SIMPLE
#include "lv_conf.h"
#else
#include "../../../lv_conf.h"
#endif

#if LV_USE_LINE != 0

#include "../lv_core/lv_obj.h"

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/*Data of line*/
typedef struct
{
    /*Inherited from 'base_obj' so no inherited ext.*/ /*Ext. of ancestor*/
    const lv_point_t * point_array;                    /*Pointer to an array with the points of the line*/
    uint16_t point_num;                                /*Number of points in 'point_array' */
    uint8_t auto_size : 1;                             /*1: set obj. width to x max and obj. height to y max */
    uint8_t y_inv : 1;                                 /*1: y == 0 will be on the bottom*/
} lv_line_ext_t;

/*Styles*/
enum {
    LV_LINE_STYLE_MAIN,
};
typedef uint8_t lv_line_style_t;

/**********************
 * GLOBAL PROTOTYPES
 **********************/

/**
 * Create a line objects
 * @param par pointer to an object, it will be the parent of the new line
 * @return pointer to the created line
 */
lv_obj_t * lv_line_create(lv_obj_t * par, const lv_obj_t * copy);

/*=====================
 * Setter functions
 *====================*/

/**
 * Set an array of points. The line object will connect these points.
 * @param line pointer to a line object
 * @param point_a an array of points. Only the address is saved,
 * so the array can NOT be a local variable which will be destroyed
 * @param point_num number of points in 'point_a'
 */
void lv_line_set_points(lv_obj_t * line, const lv_point_t point_a[], uint16_t point_num);

/**
 * Enable (or disable) the auto-size option. The size of the object will fit to its points.
 * (set width to x max and height to y max)
 * @param line pointer to a line object
 * @param en true: auto size is enabled, false: auto size is disabled
 */
void lv_line_set_auto_size(lv_obj_t * line, bool en);

/**
 * Enable (or disable) the y coordinate inversion.
 * If enabled then y will be subtracted from the height of the object,
 * therefore the y=0 coordinate will be on the bottom.
 * @param line pointer to a line object
 * @param en true: enable the y inversion, false:disable the y inversion
 */
void lv_line_set_y_invert(lv_obj_t * line, bool en);

#define lv_line_set_y_inv                                                                                \
    lv_line_set_y_invert /*The name was inconsistent. In v.6.0 only `lv_line_set_y_invert`will                         \
                            work */

/**
 * Set the style of a line
 * @param line pointer to a line object
 * @param type which style should be set (can be only `LV_LINE_STYLE_MAIN`)
 * @param style pointer to a style
 */
static inline void lv_line_set_style(lv_obj_t * line, lv_line_style_t type, const lv_style_t * style)
{
    (void)type; /*Unused*/
    lv_obj_set_style(line, style);
}

/*=====================
 * Getter functions
 *====================*/

/**
 * Get the auto size attribute
 * @param line pointer to a line object
 * @return true: auto size is enabled, false: disabled
 */
bool lv_line_get_auto_size(const lv_obj_t * line);

/**
 * Get the y inversion attribute
 * @param line pointer to a line object
 * @return true: y inversion is enabled, false: disabled
 */
bool lv_line_get_y_invert(const lv_obj_t * line);

/**
 * Get the style of an line object
 * @param line pointer to an line object
 * @param type which style should be get (can be only `LV_LINE_STYLE_MAIN`)
 * @return pointer to the line's style
 */
static inline const lv_style_t * lv_line_get_style(const lv_obj_t * line, lv_line_style_t type)
{
    (void)type; /*Unused*/
    return lv_obj_get_style(line);
}

/**********************
 *      MACROS
 **********************/

#endif /*LV_USE_LINE*/

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif /*LV_LINE_H*/


text:
For example, core could be

    node_modules/corvid-core

containing

    node_modules/
        corvid-core-referent/
        corvid-core-relation/
        corvid-core-transform/
        corvid-core-group/


text:
[![Build Status](https://travis-ci.org/devgateway/oc-explorer.svg?branch=develop)](https://travis-ci.org/devgateway/oc-explorer)

## Presentation

OCE is a project that allows importing the public procurement data, available in the common MS Excel format, into a native [Open Contracting Data Standard (OCDS)](http://standard.open-contracting.org/) NoSQL storage, and then run visual data analytics (display a *live* dashboard with charts, maps and data tables as well as custom comparison charts). Since the data is natively stored in the OCDS format, it can be readily exported in this format without any transformation required, and with great throughput.

## Visual Identity
SVG and raster version of the logo and favicon can be found in the [`docs/images`](./docs/images/) directory.

### Logo:
![DT Toolkit logo](./docs/images/raster/toolkit-logo-0256.png)

### Favicon:
![DT Toolkit favicon](./docs/images/raster/toolkit-favicon-0032.png)

# Modules

The project uses open source technologies exclusively, with the following list of key components:

- [Spring Framework](https://projects.spring.io/spring-framework/) - for security, service oriented architecture and REST API.
- [JPA persistence](http://hibernate.org/orm/) for temporarily storing and organizing the MS Excel Files containing the raw data.
- [Apache POI](https://poi.apache.org/) for reading the native MS Excel input dataset.
- [MongoDB](https://www.mongodb.org/) - as the native OCDS NoSQL datastore. We have implemented the whole OCDS 1.0 standard schema and all data used in analytics/maps as well as raw OCDS export is stored directly into this format in MongoDB.
- [Apache Wicket](http://wicket.apache.org/) - for the admin interface that runs the upload/import process of raw data
- [React](https://facebook.github.io/react/) - for integrating the dashboard/map/filter technologies
- [Plot.ly](https://plot.ly/) - as the chart library
- [Leaflet](http://leafletjs.com/) - as the map library

The project's source code is licensed under the open source [MIT](https://opensource.org/licenses/MIT) license.

## Architecture

This is a mavenized multi-module project. It is built on the open source [dg-toolkit](https://github.com/devgateway/dg-toolkit) architecture. Each module can be started independently of the rest. All modules are based on [Spring Boot](http://projects.spring.io/spring-boot/) templates.

<img src="ocvn.mmd.png" width="400">

The project uses [the gitflow workflow](https://github.com/devgateway/oc-explorer/blob/develop/gitflow.md) to drive the software release process.

### Modules

- [persistence](https://github.com/devgateway/oc-explorer/tree/master/persistence) - this is a module responsible with [JPA 2.0](https://en.wikipedia.org/wiki/Java_Persistence_API) data persistence. It is also provides [HATEOAS](https://en.wikipedia.org/wiki/HATEOAS) services on top of the existing entities.

- [persistence-mongodb](https://github.com/devgateway/oc-explorer/tree/master/persistence-mongodb) - this is a module responsible with Spring Data MongoDB access. It stores the MongoDB DAO and MongoDB Template configuration files.

- [web](https://github.com/devgateway/oc-explorer/tree/master/web) - this module provides REST endpoints for the services needed, as well as basic security. It depends on the **persistence** module.

- [forms](https://github.com/devgateway/oc-explorer/tree/master/forms) - this module provides a basic toolkit for quickly building forms over the entities defined in the persistence module. It uses [Apache Wicket](http://wicket.apache.org/) as the backend.

- [ui](https://github.com/devgateway/oc-explorer/tree/master/ui) - this module is a template for building front-end functionality. It is supposed to work in conjunction with the **web** module as the back-end. It is based on [React](https://facebook.github.io/react/) and [NuclearJS](https://optimizely.github.io/nuclear-js/). The Maven build integration is assured by [frontend-maven-plugin](https://github.com/eirslett/frontend-maven-plugin) which invokes [npm](https://www.npmjs.com/) and [webpack](https://webpack.github.io/). The UI module can be used by both UI developers, with no need of knowledge or Java/Maven local setup and by the back-end developers, with no need to have [node](https://nodejs.org/) installed on their system.

### Building

As prerequisites, we need Java 8 and Maven 3.3.x.
In order to build the project, invoke:

```
mvn install
```

isnide the root project folder.

### Debugging

You can import dg-toolkit as a Maven project inside your favorite IDE, it should work in IDEA/STS/Eclipse but you will need Maven 3.3.x.

## Debugging in STS

Since all the modules are Spring Boot, debugging in STS is really easy. In Spring Boot 1.3 and later there is something called [spring-boot-devtools](https://spring.io/blog/2015/06/17/devtools-in-spring-boot-1-3).
This dependency is already included in the pom.xml of the modules, uncomment it if you plan to use it. If you do, then in STS you can do Debug As->Spring DevTools Client.

If you have JRebel license, then don't use spring-boot-devtools. Best is to start the modules by invoking Debug As->Spring Boot App

### Debugging fat jars

[Fat jars](http://docs.spring.io/spring-boot/docs/current/reference/html/howto-build.html) are the way to go when it comes to java micro-services these days. While the pre-built maven project can be easily debugged as described above, a already packaged jar requires remote debugging. You can start the fat jar with remote debugging parameters by invoking:

```java -Xverify:none -noverify -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 -jar fat.jar```

... And then for example in STS you can add a new Debug Configuration->Remote Java Application and specify localhost and port 5005.
## Running dg-toolkit

DG-toolkit is a package of several modules, among which forms and web are runnable. See the [forms](https://github.com/devgateway/dg-toolkit/tree/master/forms) and/or the [web](https://github.com/devgateway/dg-toolkit/tree/master/web) modules documentation for starting the project.

## Installing dg-toolkit as system service on the production server

We are closely following the spring boot executable/fat jar documentation which provides an extremely nice way to run a jar as a linux system service. This works for both the old System V and the new systemd. You can find [the full Spring documentation here] (http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#deployment-service).

## Start a new project with DG-Toolkit as the base

DG-Toolkit should be used as a template project, so as starting point for other projects. This should be done by forking the repository. Unfortunately Github denies forking of repositories inside the same organization, so @devgateway can own only one DG-Toolkit fork (the current one). A chat with Github support has not solved the problem, they used to have this functionality but have opted to disable it. Therefore one cannot use the FORK button on Github, but since Git is the back-end of Github, this does not mean you cannot fork it using git on your machine.

To fork DG-Toolkit you can simply create a new independent github repository, and after creation add a new remote on your machine. So you will have /origin/ that points to the new repo, and say dg-toolkit remote that points to the DG-Toolkit repo url. After this you should be able to merge from dg-toolkit remote to the origin remote, that is, you can take DG-Toolkit code and merge it over your existing empty project, thus you will get the DG-Toolkit tree inside your local project. This is much better than just copy-pasting the contents of DG-Toolkit. If you use remotes, you can later merge new fixes and features from DG-Toolkit back into your project, thus you keep your project up to date with fixes coming from DG-Toolkit.

## Contributing code back to DG-Toolkit

There are several ways in which this can be achieved:

### Forking DG-Tookit for a feature/fix development

The best and easiest is to fork DG-Toolkit for the sole purpose of developing a new module/feature/fix. You can very well use your own private github user space to do this and thus you can use the FORK button on the Ghihub page. After the fork you can commit all your new stuff to your copy of DG-Tooolkit then ask for a Pull Request of your code back into DG-Toolkit.

### Develop the contributions in an already forked project

Yes, it would be cool if we could develop the new contribution as part of your current project, which was forked some time ago from DG-Toolkit. It is possible but it is a bit trickier. You will not be able to merge your project back to DG-Toolkit, because this will bring all your project's custom code into DG-Toolkit, so basically the customized implementation the client has asked for, like all the dashboards and forms that it asked. That is undesirable.

One simple solution to this is to commit the changes you are willing to merge back to DG-Toolkit as atomic changes. That means that when you commit your files, you commit only those files that are related to that new feature and nothing else. For example let's suppose you want to develop a new search module that will use Lucene for indexing and you will like to merge this new module to DG-Toolkit. You should commit all the code that has to do with the search module in separate commits that do not contain other code, for example if the search module is also used in a dashboard page in your project, you will commit that linking in a separate commit , so keep the commits that target the module functionality separate.

Then, you can cherry-pick your project's branch over the dg-tookit remote branch. By doing so, you can pick what commits to apply and what to leave out and you will choose only the commits that implement the generic new module functionality and you will leave out the client-specific customizations that are not meant to be posted to DG-Toolkit


text:
package net

import (
	"encoding/json"
	"io/ioutil"
	"reflect"
	"testing"
)

func saveToTemp(v interface{}) (string, error) {
	f, err := ioutil.TempFile("", "net")
	if err != nil {
		return "", err
	}
	defer f.Close()

	return f.Name(), json.NewEncoder(f).Encode(v)
}

func TestNet(t *testing.T) {
	expected := Net{
		Name: "mynet",
		Type: "veth",
	}
	expected.IPAlloc.Type = "static"
	expected.IPAlloc.Subnet = "10.1.2.0/24"

	fn, err := saveToTemp(expected)
	if err != nil {
		t.Fatal(err)
	}
	expected.Filename = fn

	actual := Net{}
	if err = LoadNet(fn, &actual); err != nil {
		t.Fatal(err)
	}

	if expected.Filename != actual.Filename {
		t.Errorf("Filename mismatch: expected=%q; actual=%q", expected.Filename, actual.Filename)
	}

	if !reflect.DeepEqual(expected, actual) {
		t.Errorf("Mismatch: expected=%#v; actual=%#v", expected, actual)
	}
}

type MyNet struct {
	Net
}

func TestNetEmbedded(t *testing.T) {
	expected := MyNet{
		Net: Net{
			Name: "mynet",
			Type: "veth",
		},
	}
	expected.IPAlloc.Type = "static"
	expected.IPAlloc.Subnet = "10.1.2.0/24"

	fn, err := saveToTemp(expected)
	if err != nil {
		t.Fatal(err)
	}
	expected.Filename = fn

	actual := MyNet{}
	if err = LoadNet(fn, &actual); err != nil {
		t.Fatal(err)
	}

	if expected.Filename != actual.Filename {
		t.Errorf("Filename mismatch: expected=%q; actual=%q", expected.Filename, actual.Filename)
	}

	if !reflect.DeepEqual(expected, actual) {
		t.Errorf("Mismatch: expected=%#v; actual=%#v", expected, actual)
	}
}


text:
#ifndef _ONYX_NET_ICMPV6_H
#define _ONYX_NET_ICMPV6_H

#include <stddef.h>
#include <stdint.h>

#include <onyx/net/inet_route.h>
#include <onyx/net/inet_socket.h>
#include <onyx/public/icmp.h>
#include <onyx/scoped_lock.h>
#include <onyx/spinlock.h>

#define ICMPV6_DEST_UNREACHABLE  1
#define ICMPV6_PACKET_TOO_BIG    2
#define ICMPV6_TIME_EXCEEDED     3
#define ICMPV6_PARAMETER_PROBLEM 4
#define ICMPV6_ECHO_REQUEST      128
#define ICMPV6_ECHO_REPLY        129
#define ICMPV6_ROUTER_SOLICIT    133
#define ICMPV6_ROUTER_ADVERT     134
#define ICMPV6_NEIGHBOUR_SOLICIT 135
#define ICMPV6_NEIGHBOUR_ADVERT  136
#define ICMPV6_MLDV2_REPORT_MSG  143

struct icmpv6_header
{
    uint8_t type;
    uint8_t code;
    uint16_t checksum;
    uint32_t data;
} __attribute__((packed));

namespace icmpv6
{

struct send_data
{
    uint8_t type;
    uint8_t code;
    const inet_route &route;
    uint32_t data;

    send_data(uint8_t t, uint8_t c, const inet_route &r, uint32_t data)
        : type{t}, code{c}, route{r}, data{data}
    {
    }
};

class icmp6_socket : public inet_socket
{
private:
    static constexpr unsigned int icmp_max_filters = 5;
    spinlock filters_lock{};
    cul::vector<icmp_filter> filters;

    int add_filter(icmp_filter &&f);

    packetbuf *get_rx_head()
    {
        if (list_is_empty(&rx_packet_list))
            return nullptr;

        return list_head_cpp<packetbuf>::self_from_list_head(list_first_element(&rx_packet_list));
    }

    bool has_data_available()
    {
        return !list_is_empty(&rx_packet_list);
    }

    expected<packetbuf *, int> get_datagram(int flags);

    int wait_for_dgrams()
    {
        return wait_for_event_socklocked_interruptible(&rx_wq, !list_is_empty(&rx_packet_list));
    }

public:
    icmp6_socket()
    {
        spinlock_init(&filters_lock);
    }

    ~icmp6_socket() override = default;

    int bind(struct sockaddr *addr, socklen_t addrlen) override;
    int connect(struct sockaddr *addr, socklen_t addrlen, int flags) override;
    ssize_t sendmsg(const struct msghdr *msg, int flags) override;
    int getsockopt(int level, int optname, void *val, socklen_t *len) override;
    int setsockopt(int level, int optname, const void *val, socklen_t len) override;
    short poll(void *poll_file, short events) override;
    ssize_t recvmsg(msghdr *msg, int flags) override;

    bool match_filter(const icmpv6_header *header)
    {
        scoped_lock g{filters_lock};

        for (const auto &f : filters)
        {
            if (header->type != f.type && f.type != ICMP_FILTER_TYPE_UNSPEC)
                continue;
            if (header->code != f.code && f.code != ICMP_FILTER_CODE_UNSPEC)
                continue;

            return true;
        }

        return false;
    }

    void rx_dgram(packetbuf *buf);

    /**
     * @brief Handle ICMP socket backlog
     *
     */
    void handle_backlog() override;
};

icmp6_socket *create_socket(int type);

static constexpr unsigned int min_icmp6_size()
{
    return sizeof(icmpv6_header);
}

int handle_packet(netif *nif, packetbuf *buf);

int send_packet(const send_data &data, cul::slice<unsigned char> packet_data);

} // namespace icmpv6

#endif


text:
{- |
Typed AST for Stan programs

-}

{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, FunctionalDependencies, OverloadedStrings, UndecidableInstances #-}

module Math.Stan.TAST where

import Control.Monad.State.Strict
import Math.Stan.AST
import Data.String
import Data.List

------------------------------------------------
----  Typed Expressions
-----------------------------------------------

data Expr a = Expr { exprTy:: T,
                     unExpr :: E }
  deriving (Show)

data Prob a = Prob T E
  deriving (Show)

newtype Pat a = Pat P
  deriving (Show)

newtype TyT a = TyT T --typed type
  deriving (Show)

instance IsString (Pat a) where
  fromString nm = Pat (nm,[])

{-instance IsString (Expr a) where
  fromString nm = Expr $ EVar nm -}

instance Num a => Num (Expr a) where
   (Expr t e1) + (Expr _ e2) = Expr t $ EBin "+" e1 e2
   (Expr t e1) - (Expr _ e2) = Expr t $ EBin "-" e1 e2
   (Expr t e1) * (Expr _ e2) = Expr t $ EBin "*" e1 e2
   abs (Expr t e) = Expr t$ EApp "abs" [e]
   fromInteger  = Expr (fromBase TInt) . EInt . fromInteger

instance Fractional a => Fractional (Expr a) where
   (Expr t e1) / (Expr _ e2) = Expr t $ EBin "/" e1 e2
   fromRational = Expr (fromBase TReal) . EReal . fromRational

infixl 7 !

class Indexable a b | a -> b, b -> a where
  (!) :: a -> Expr Int -> b

instance Indexable (Pat [a]) (Pat a) where
   (Pat (nm, ixs)) ! moreIx = Pat (nm,ixs++[unExpr moreIx])

instance Indexable (Expr [a]) (Expr a) where
   (Expr t e) ! ix = Expr (reduceDims t) $ EIx e [unExpr ix]

instance Indexable (TyT a) (TyT [a]) where
   (TyT (T base bnds dims)) ! (Expr _ dime) = TyT $ T base bnds $ dims++[dime]

int :: TyT Int
int = TyT $ T TInt (Nothing, Nothing) []

real :: TyT Double
real = TyT $ T TReal (Nothing, Nothing) []

vec :: Expr Int -> TyT [Double]
vec (Expr t n) = TyT $ T (TVector n) (Nothing, Nothing) []

infixl 1 .:

(.:) :: Id -> TyT a -> (Id,T)
ident .: (TyT t)  = (ident,t)

pToExpr :: P -> T -> Expr a
pToExpr (nm,[]) t = Expr t $ EVar nm
pToExpr (nm,ixs) t = Expr t $ EIx (EVar nm) ixs

class LoopWrap a b | a -> b  where
  loopwrap :: Expr Int -> a -> b

instance LoopWrap (Expr a) (Expr [a]) where
  loopwrap (Expr _ n) (Expr t e) = Expr (addDim n t) e

instance (LoopWrap a b, LoopWrap c d) => LoopWrap (a,c) (b,d) where
  loopwrap e (x,y) = (loopwrap e x, loopwrap e y)


text:
/*! \file
  \brief This files contains methods relevant to the creation and execution of
            commands.

    The shell provides the following built-in commands.
    - exit
      + closes the shell
    - pid
      + prints the shell's process id
    - ppid
      + prints the shell's parent process id
    - cd \<dir>
      + changes the working directory to \<dir>
    - pwd
      + prints the current working directory
    - set \<var> \<value>
      + sets the environment variable \<var> to \<value>
    - get \<var>
      + prints the value of environment variable \<var>

 */
#ifndef CMD_H
#define CMD_H

#include <stdlib.h>

static const char* EXIT = "exit";
static const char* PID = "pid";
static const char* PPID = "ppid";
static const char* CD = "cd";
static const char* PWD = "pwd";
static const char* SET = "set";
static const char* GET = "get";

/*!
  \brief holds the arguments for a command.

  args is a char** containing all the arguments for the command. By convention,
  the first element in args is the command itself. args is terminated by a
  NULL element.
 */
typedef struct {
  /*!
    char** containing all the arguments for the command. By convention,
    the first element in args is the command itself. args is terminated by a
    NULL element.
  */
  char** args;
  /*!
    Total size of args.
   */
  size_t size;
} cmd_args_t;

/*!
  \brief Represents a command to be executed by the shell.

  command_t should be created using make_command(). A command_t created using
  this method must be free'd using free_command().
 */
typedef struct {
  /*!
    bin is the first part of the text that was entered into the console, the
    shell will attempt to search the path to find an executable and if none is
    found, the bin will be interpreted as a literal path to a file.
   */
  char* bin;

  /*!
    args is the arguments for the command, it contains size information in
    addition to command arguments.
   */
  cmd_args_t args;
} command_t;

/*!
  \brief Creates a command_t.

  creates a command_t from a string typed into the shell. The command_t
  returned by this method must be free'd by free_command.

  ##Example

  ---
  ~~~{.c}
  const char* input_line = "ls --color=auto";
  command_t cmd = make_command(input_line);
  ~~~
 */
command_t make_command(char* input);

/*!
  \brief Frees a command_t from memory.

  Removes the cmd from the heap. This function should only be called if
  make_command() was used to create it.

  ##Example

  ---
  ~~~{.c}
  const char* input_line = "ls --color=auto";
  command_t cmd = make_command(input_line);

  free_command(&cmd)

  // This will cause a compile error because cmd has been free'd from memory.
  cmd.bin;
  ~~~
 */
void free_command(command_t* cmd);

void run_command(command_t* cmd);

void sh_exit();
void sh_pid();
void sh_ppid();
void sh_cd(cmd_args_t args);
void sh_pwd();
void sh_set(cmd_args_t args);
void sh_get(cmd_args_t args);

#endif


text:
module Chief
  class Tame < Sequel::Model(Sequel::Model.db[:chief_tame].order(Sequel.asc(:audit_tsmp), Sequel.asc(:fe_tsmp)))

    set_primary_key [:msrgp_code,
                     :msr_type,
                     :tty_code,
                     :tar_msr_no,
                     :fe_tsmp,
                     :le_tsmp,
                     :audit_tsmp,
                     :amend_indicator]

    one_to_one :measure_type, key: {}, primary_key: {},
      dataset: -> { Chief::MeasureTypeAdco.where(chief_measure_type_adco__measure_group_code: msrgp_code,
                                                 chief_measure_type_adco__measure_type: msr_type,
                                                 chief_measure_type_adco__tax_type_code: tty_code) },
                                                 class_name: 'Chief::MeasureTypeAdco'

    one_to_one :duty_expression, key: [:adval1_rate, :adval2_rate, :spfc1_rate, :spfc2_rate],
                                 primary_key: [:adval1_rate, :adval2_rate, :spfc1_rate, :spfc2_rate]

    one_to_many :tamfs, key:{}, primary_key: {}, dataset: -> {
      Chief::Tamf.filter({:fe_tsmp => fe_tsmp})
                 .filter({:msrgp_code => msrgp_code})
                 .filter({:msr_type => msr_type})
                 .filter({:tty_code => tty_code})
                 .filter({:tar_msr_no => tar_msr_no})
                 .filter({:amend_indicator => amend_indicator})
    }, class_name: 'Chief::Tamf'

    one_to_many :mfcms, key: {}, primary_key: {}, dataset: -> {
      Chief::Mfcm.filter({:msrgp_code => msrgp_code})
                 .filter({:msr_type => msr_type})
                 .filter({:tty_code => tty_code})
                 .filter({:tar_msr_no => tar_msr_no})
                 .order(Sequel.asc(:audit_tsmp))
    }

    one_to_one :chief_update, key: :filename,
                              primary_key: :origin,
                              class_name: TariffSynchronizer::ChiefUpdate

    delegate :issue_date, to: :chief_update, allow_nil: true

    dataset_module do
      def unprocessed
        filter(processed: false)
      end
    end

    def adval1_rate; true; end
    def adval2_rate; false; end
    def spfc1_rate; false; end
    def spfc2_rate; false; end

    def mark_as_processed!
      self.this.unlimited.update(processed: true)

      tamfs.each(&:mark_as_processed!)
    end

    def has_tamfs?
      tamfs.any?
    end

    def audit_tsmp
      self[:audit_tsmp].presence || Time.now
    end

    def operation_date
      issue_date
    end
  end
end


text:
class AddHoursUsers < ActiveRecord::Migration
  def change
    add_column :users , :weekly_hours , :integer , :default => 0
  end
end


text:
#ifndef GVT_MANAGER_IMPLEMENTATION_BASE_H
#define GVT_MANAGER_IMPLEMENTATION_BASE_H

#include <string>                       // for string

#include "GVTManager.h"                 // for GVTManager
#include "warped.h"

using std::string;

class ObjectID;
class SimulationConfiguration;
class TimeWarpSimulationManager;
class VTime;

/** The GVTManagerImplementationBase base class.

    This is the implementation base class for the various GVT
    Estimation Algorithm implementations in the Simulation
    kernel. Data/Methods common to all gvt managers are defined here.

*/
class GVTManagerImplementationBase : public GVTManager {
public:

    /**@name Public Class Methods of GVTManagerImplementationBase. */
    //@{

    /// Default constructor
    GVTManagerImplementationBase(TimeWarpSimulationManager* simMgr,
                                 unsigned int period);

    /// Destructor
    virtual ~GVTManagerImplementationBase();

    /// Set the LTSE while circulating the red token
    virtual void calculateGVTInfo(const VTime& receiveTime);

    /// get any gvt manager specific info
    virtual const string getGVTInfo(unsigned int srcSimMgr,
                                    unsigned int destSimMgr,
                                    const VTime& sendTime);

    /// update this simulation manager's record of events it sent out
    virtual void updateEventRecord(const char* infoStream,
                                   unsigned int srcSimMgr);

    /// is it time to start a GVT estimation cycle
    virtual bool checkGVTPeriod();

    /// return the GVT value to the caller
    const VTime& getGVT();

    /** Calculate the actual value of GVT.

    This function should only be called in the function that is
    responsible for the calculation of the "real" gVT.  It is
    assumed that simulation manager 0 is responsible for gVT
    calculation.

    */
    virtual void calculateGVT();

    /// update everybody in the simulation with the new GVT value
    virtual void sendGVTUpdate();

    void configure(SimulationConfiguration& configuration);

    /**
       Set a new GVT value.
    */
    void setGVT(const VTime& newGVT);

    virtual bool getGVTTokenStatus();

    //@} // End of Public Class Methods of GVTManager.

protected:
    /// number of cycles to wait before gvt estimation is attempted
    unsigned int gVTPeriodCounter;

    /// number of cycles to wait - user specifies this value
    unsigned int gVTPeriod;

    /// handle to the simulation manager that owns this gvt manager
    TimeWarpSimulationManager* mySimulationManager;

private:
    /**@name Protected Class Attributes of GVTManagerImplementationBase. */
    //@{

    /// the global virtual time of the simulation
    const VTime* gVT;

    //@} // End of Protected Class Methods of GVTManagerImplementationBase.
};
#endif


text:
<?php

namespace Eticsol\EticsolBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Localidad
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Localidad
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="descripcion", type="string", length=255)
     */
    private $descripcion;

    /**
     * @var string
     *
     * @ORM\Column(name="codigoPostal", type="string", length=255)
     */
    private $codigoPostal;

    /**
     * @var integer
     *
     *
     * @ORM\ManyToOne(targetEntity="Provincia")
     * @ORM\JoinColumn(name="provincia_id", referencedColumnName="id")
     */
    private $provincia;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     * @return Localidad
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * Set codigoPostal
     *
     * @param string $codigoPostal
     * @return Localidad
     */
    public function setCodigoPostal($codigoPostal)
    {
        $this->codigoPostal = $codigoPostal;

        return $this;
    }

    /**
     * Get codigoPostal
     *
     * @return string
     */
    public function getCodigoPostal()
    {
        return $this->codigoPostal;
    }

    /**
     * Set provincia
     *
     * @param \Eticsol\EticsolBundle\Entity\Provincia $provincia
     * @return Localidad
     */
    public function setProvincia(\Eticsol\EticsolBundle\Entity\Provincia $provincia = null)
    {
        $this->provincia = $provincia;

        return $this;
    }

    /**
     * Get provincia
     *
     * @return \Eticsol\EticsolBundle\Entity\Provincia
     */
    public function getProvincia()
    {
        return $this->provincia;
    }

    public function __toString() {
        return $this->getDescripcion();
    }
}


text:
@class IRTextFieldDescriptor;
@class IRTextField;
@class IRView;
@class IRBaseDescriptor;
@class IRScreenDescriptor;
@class IRViewDescriptor;
@class IRViewController;

@interface IRTextFieldBuilder : IRBaseBuilder

+ (IRView *) buildComponentFromDescriptor:(IRBaseDescriptor *)descriptor
                           viewController:(IRViewController *)viewController
                                    extra:(id)extra;

+ (void) setUpComponent:(IRView *)irTextField
    componentDescriptor:(IRBaseDescriptor *)descriptor
         viewController:(IRViewController *)viewController
                  extra:(id)extra;

@end


text:
@extends('connexion::templates.frontend')

@section('title','Sign up for an event: ' . $event->groupname)

@section('css')
  <meta id="token" name="token" value="{{ csrf_token() }}" />
  <link href="{{ asset('/vendor/bishopm/css/selectize.css') }}" rel="stylesheet" type="text/css" />
@stop

@section('content')

{{$event->groupname}} {{date("d M Y H:i",$event->eventdatetime)}}

        @if ($leader->user)
          Co-ordinator: slug}}">{{$leader->firstname}} {{$leader->surname}}.
        @else
          Co-ordinator: {{$leader->firstname}} {{$leader->surname}}.
        @endif

{!!$event->description!!}

            @if (Auth::check())
              Which members of your household would like to sign up?
              {!! Form::open(['route' => array('admin.events.signup',$event->id), 'method' => 'post']) !!}
              <select class="selectize" name="individual_id[]" multiple>
                @foreach (Auth::user()->individual->household->individuals as $indiv)
                  @if (in_array($indiv->id, $people))
                    <option selected value="{{$indiv->id}}">{{$indiv->firstname}} {{$indiv->surname}}</option>
                  @else
                    <option value="{{$indiv->id}}">{{$indiv->firstname}} {{$indiv->surname}}</option>
                  @endif
                @endforeach
              </select>
              <button type="submit" class="btn btn-primary btn-flat">OK</button> slug)}}"> Cancel
              {!! Form::close() !!}
            @else

Register or <button class="btn btn-primary btn-flat" data-toggle="modal" data-target="#modal-login" data-action-target="{{ route('login') }}">Login</button> to sign up automatically, or send us an {{ HTML::mailto($setting['church_email'],'email') }}.

            @endif

@stop

@section('js')

@stop


text:
Automatic DJ
================================

![AutomaticDJ](https://dl.dropboxusercontent.com/u/101688/website/img/automaticdj-large.png)

Automatic music selection system for people who love great music (even if they don't know it yet). Uses [facial recognition](http://developers.face.com/) and the [Hunch API](http://hunch.com/developers) to build a custom playlist based on the tastes of the people at the party.

Take a picture of one of your friends at a party. The Face.com API maps the face to a Facebook ID. Given this ID, the Hunch API provides music (or movie, or picture, or food) recommendations (and it's scary accurate). Tailor your entire party to the taste of your guests. Play their theme song when they enter the room. Or discover new music recommendations that they would like. Note that you don't need to have music likes on your Facebook page, the Hunch API can infer taste based solely on the social graph.

The current version uses Spotify to play the songs (controlled via AppleScript), but once the playlist is generated you can use any music player to play the track. There is also minimal support in the code for playing songs through the GrooveShark API.

Other libraries used include:

* [isightcapture](http://www.intergalactic.de/pages/iSight.html) for taking pictures via the command line
* [python-face-client](https://github.com/Kami/python-face-client) edited to work with the current Face.com API
* [EchoNest](http://code.google.com/p/pyechonest/)
* [Spotify Metadata API](http://developer.spotify.com/en/metadata-api/overview/)

Getting started
---------------

1. In `visage.py`
   * Edit the section titled "edit me!" with youe Face.com API key and secret, Facebook session key, Facebook ID, and Hunch auth token

2. Train your friends' faces
   * `import visage`
   * `visage.train("http://www.facebook.com/gleitz")`

4. Take a photo, get the Facebook id of the user, get music recommendations from Hunch, and play the song using Spotify
   * `visage.musicify()`

Notes and gotchas
-----------------

* If you just want to test the photo -> FB id functionality, try calling `visage.recognize()`

* Getting a FB session is a bit of a pain. Here's what I did:
  1. Create a Facebook App (make sure the Canvas Type is `IFrame` and Application Type is `HTML5`
  2. Set your site URL to `http://gleitzman.com/faces/` (or a link of your choosing, I am just using this as a dummy)
  3. Go to this link, inserting your client_id where I have 'XXX' `https://graph.facebook.com/oauth/authorize?client_id=XXX&redirect_uri=http%3A//gleitzman.com/faces/&scope=offline_access,email,user_birthday,user_about_me,user_education_history,user_interests,user_likes,user_location,user_religion_politics,user_website,user_work_history,user_checkins,friends_about_me,friends_likes,friends_birthday,friends_education_history,friends_checkins,user_photo_video_tags,user_photos,friends_photo_video_tags,friends_photos,friends_birthday,friends_location,friends_work_history,friends_education_history,friends_activities,friends_hometown,friends_interests,friends_location,friends_likes`
  4. Note the code that is returned in the URL
  5. Exchange the code, your Facebook client id, and Facebook client secret for an infinite session `https://graph.facebook.com/oauth/access_token?client_id=XXX&client_secret=XXX&code=XXX&redirect_uri=http%3A//gleitzman.com/faces/`


text:
package org.takes.facets.auth.social;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import javax.json.Json;
import org.apache.commons.lang.RandomStringUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.auth.Identity;
import org.takes.facets.fork.FkRegex;
import org.takes.facets.fork.TkFork;
import org.takes.http.FtRemote;
import org.takes.misc.Href;
import org.takes.rq.RqFake;
import org.takes.rq.RqHref;
import org.takes.rq.RqPrint;
import org.takes.rs.RsJSON;

/**
 * Test case for {@link PsLinkedin}.
 * @author Dmitry Zaytsev (dmitry.zaytsev@gmail.com)
 * @version $Id$
 * @since 0.16
 * @checkstyle MagicNumberCheck (500 lines)
 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
 * @checkstyle MultipleStringLiteralsCheck (500 lines)
 */
public final class PsLinkedinTest {

    /**
     * PsLinkedin can login.
     * @throws IOException If some problem inside
     */
    @Test
    public void logins() throws IOException {
        final String code = RandomStringUtils.randomAlphanumeric(10);
        final String lapp = RandomStringUtils.randomAlphanumeric(10);
        final String lkey = RandomStringUtils.randomAlphanumeric(10);
        final String identifier = RandomStringUtils.randomAlphanumeric(10);
        final Take take = new TkFork(
            new FkRegex(
                "/uas/oauth2/accessToken",
                // @checkstyle AnonInnerLengthCheck (100 lines)
                new Take() {
                    @Override
                    public Response act(final Request req) throws IOException {
                        MatcherAssert.assertThat(
                            new RqPrint(req).printBody(),
                            Matchers.stringContainsInOrder(
                                Arrays.asList(
                                    "grant_type=authorization_code",
                                    String.format("client_id=%s", lapp),
                                    "redirect_uri=",
                                    String.format(
                                        "client_secret=%s",
                                        lkey
                                    ),
                                    String.format("code=%s", code)
                                )
                            )
                        );
                        MatcherAssert.assertThat(
                            new RqHref.Base(req).href().toString(),
                            Matchers.endsWith("/uas/oauth2/accessToken")
                        );
                        return new RsJSON(
                            Json.createObjectBuilder()
                                .add(
                                    "access_token",
                                    RandomStringUtils.randomAlphanumeric(10)
                                ).build()
                        );
                    }
                }
            ),
            new FkRegex(
                "/v1/people",
                new Take() {
                    @Override
                    public Response act(final Request req) throws IOException {
                        return new RsJSON(
                            Json.createObjectBuilder()
                                .add("id", identifier)
                                .add("firstName", "Frodo")
                                .add("lastName", "Baggins")
                                .build()
                        );
                    }
                }
            )
        );
        new FtRemote(take).exec(
            // @checkstyle AnonInnerLengthCheck (100 lines)
            new FtRemote.Script() {
                @Override
                public void exec(final URI home) throws IOException {
                    final Identity identity = new PsLinkedin(
                        new Href(
                            String.format(
                                "%s/uas/oauth2/accessToken",
                                home
                            )
                        ),
                        new Href(String.format("%s/v1/people/", home)),
                        lapp,
                        lkey
                    ).enter(
                        new RqFake("GET", String.format("?code=%s", code))
                    ).next();
                    MatcherAssert.assertThat(
                        identity.urn(),
                        CoreMatchers.equalTo(
                            String.format("urn:linkedin:%s", identifier)
                        )
                    );
                    MatcherAssert.assertThat(
                        identity.properties(),
                        Matchers.allOf(
                            Matchers.hasEntry("firstName", "Frodo"),
                            Matchers.hasEntry("lastName", "Baggins")
                        )
                    );
                }
            }
        );
    }
}


text:
layout: post
status: publish
published: true
title: 'Review: Spiderman 3'
author: Jeff
author_login: admin
author_email: jeff@allthingsdork.com
author_url: http://www.allthingsdork.com
wordpress_id: 102
wordpress_url: http://www.allthingsdork.com/?p=102
date: '2007-05-07 07:46:29 -0500'
date_gmt: '2007-05-07 11:46:29 -0500'
categories:
- Random
tags: []
comments:
- id: 750
  author: Aaron
  author_email: siamus1@aol.com
  author_url: http://
  date: '2007-05-07 13:35:19 -0500'
  date_gmt: '2007-05-07 17:35:19 -0500'
  content: "You know I'm an old comics fan from waaay back. So you know that I automatically
    have some problems with this film because they're switching some major Spidey
    historical facts around. I didn't see the film yet, but all I can say is that
    I hope Gwen Stacy dies, because if she doesn't, that is some bullshit. \r\n\r\nI'm
    still going to see it though..because it's Spiderman. I just fear that it'll turn
    out like that last X-Men movie. They did my man Xavier wrong."
- id: 1907
  author: Mark Alvarez
  author_email: aalvarez828@bellsouth.net
  author_url: ''
  date: '2007-08-23 10:43:17 -0500'
  date_gmt: '2007-08-23 14:43:17 -0500'
  content: "spiderman 3 sucks balls! its the worst movie i've ever seen!!\r\nit has
    the worst storyline i've ever seen, do i need to go on.\r\n\r\noh! and the guy
    who plays venom sucks balls to!\r\nhe has the gayest voice when he's VENOM!"
- id: 105937
  author: social networking software
  author_email: ''
  author_url: http://www.social-networking-software.org/
  date: '2010-08-31 16:07:35 -0500'
  date_gmt: '2010-08-31 22:07:35 -0500'
  content: |-
    social networking software...

    Great post! I really liked the content and disposition in your topic!...
---

If Spiderman 3 has taught us anything about movies, its that opening weekend box office numbers have no bearing on how could the film actually is. Now before everyone starts throwing egg at my face, I did think the movie was entertaining. But I believe director Sam Raimi has become a victim of his own success, as has the franchise itself.

Because Spiderman 3 is such a blockbuster event, I won't go into too many details here right now. Because its a blockbuster it doesn't matter what combination of words or letters I string together on this page, you're going to go see it. And I can't blame you for that because I'd be the same way. The truth of the matter is however, Mr. Raimi and his boys tried to squeeze WAAAY to much story into a single film. This piece could of easily been two separate films, which would have given the plot points the proper exposure they needed instead of the fledgling bits of info we received in this version. Oh well, I think all the fan boys knew that was going to be an issue. Not only were they not properly handled, but sometimes they just downright sucked. Sandman's origin story sucks, period. I hate it when an ongoing series tries to inject characters into an already established past. (Think Palo and Nikki from Lost. **VOMIT**) Same time of BS happens in this flick.

Like I said, I know you have to go see it, because it is Spiderman 3. But remember this post as you sit in that crammed theatre between two big sweaty dorks. You'll be spending the next 2 hours and 30 some odd minutes in anticipation for something that probably ain't gonna show. Namely the quality that you would expect from a record setting blockbuster.

Oh well, see you in 2 years for Spiderman 4. (Cause you know I'm still going to see that shit)


text:
- Fix autorun env on iPhone
- Added re-run test (experimental!)
- Test log viewer (iPhone)
- Showing time in tests vs time running

# Release 0.4.18
- Fixing test stats on parallel running
- Adding reraiseException options (MacOSX)
- Adding env var support for reraise and autorun (see README)
- Smaller font size for test view (iPhone)
- Show filename/line number in trace on failure
- Show link to exception filename on failure (MacOSX)
- Fix bug where test trace/log doesn't update if selected before running

# Release 0.4.17
- Fixing disabled on new test bug
- Fixing bugs with All/Failed/Edit views not showing tests properly (MacOSX)

# Release 0.4.16
- Fixing hidden tests bug

# Release 0.4.15
- Text filter (MacOSX)
- Text filter now searches test case and test names (prefix)
- Failed filter (MacOSX/iPhone)
- Copy text in text view (MacOSX)
- Remember test state

# Release 0.4.14
- Fix window resizing when showing details
- Adding test for 0 found test cases

# Release 0.4.13
- Fixing framework build: Header error and 32/64 bit universal (MacOSX)
- Fixing SenTest macros not failing correctly
- Fixing persist of test enabled/disabled state
- Fixing SenTest macros

# Release 0.4.12
- Fixing compile warning in main (iPhone)

# Release 0.4.11
- Added value formatter (from http://github.com/JohannesRudolph); For better Assert error messages.
- Fixed deprecation warning (iPhone)
- Added default exception handler to give stack trace if triggered outside of GHUnit run

# Release 0.4.10
- Added Search Bar
- Added GHTestSuite#suiteWithPrefix:options

# Release 0.4.9
- Fix compile warning

# Release 0.4.8
- Fix bug with turning Parallel off not working
- Building 32/64 bit universal

# Release 0.4.7
- Removing redirect, was a bad idea; Test output goes to stderr, you can redirect stdout yourself

# Release 0.4.6
- Redirecting test output to file
- Test output does OK/FAIL
- Disabled tests appear gray (MacOSX)
- UI fixes

# Release 0.4.5 (2008-07-21)
- Including GHUnitIPhoneAppDelegate so you can subclass and interact with UIApplication delegate in tests

# Release 0.4.4 (2008-07-20)
- Ignore disable/cancelled tests in scroll (iPhone)
- Only start group test (notify) if we have tests to run

# Release 0.4.3 (2008-07-20)
- When running test on main thread should wait until finished
- Auto scrolls to middle instead of bottom (iPhone)

# Release 0.4.2 (2008-07-19)
- Fixing run warning

# Release 0.4.1 (2008-07-18)
- Option to use NSOperationQueue to manage tests runs
- Updated how test groups run
- Handling failure in setUpClass/tearDownClass
- Updated how shouldRunOnMainThread works
- Added Edit UI for Mac OSX tests
- Bug fixes and other refactoring

# Release 0.3.19 (2008-06-15)
- Fixed bug in Edit->Save crash (iPhone)
- Tweaking test text color (iPhone)
- Re-run crash
- Added reset to GHTest protocol
- Added testDidUpdate: to GHTestDelegate protocol
- On Edit->Save, triggers reset
- Added cancel to GHTest protocol
- Added cancelling, cancelled enums to test status
- Changed testDidFinish to testDidEnd (since test may be cancelled)

# Release 0.3.18 (2008-06-15)
- Adding Run button; By default tests do not automatically run on start
- Added AutoRun setting

# Release 0.3.17 (2008-06-09)
- Updating RunTests.sh

# Release 0.3.16 (2008-06-09)
- Rebuilding from 3.0 GM
- Setting debug variables in main directly instead of from setenv (which doesn't seem to work)

# Release 0.3.14 (2008-06-08)
- Creating separate iPhone 3.0 builds

# Release 0.3.12 (2008-05-25)
- Creating iPhone static library with device and simulator platforms

# Release 0.3.11 (2008-05-20)
- Fixing version number
- Creating separate version with CoreLocation linked

# Release 0.3.10 (2008-05-20)
- Fix namespace issue

# Release 0.3.9 (2008-05-19)

## 2008-05-19
- 3.0 compatibility fixes
- Added GHUITestCase
- Added shouldRunOnMainThread to test case, and if present and YES will run the tests on the main thread

## 2008-05-05
- (iPhone) Added select/deselect to iPhone test UI
- (iPhone) Fixed auto-scroll if you manually scroll (will stop auto-scrolling)

# Release 0.3.8 (2008-04-28)

## 2008-04-28
- Removed button enabled cell from Mac OS X view; Makes NSOutlineView really slow; Need to figure out how to do it right

# Release 0.3.7 (2008-04-26)

## 2008-04-20
- CLLocationManager mock
- Fixed afterDelay not using delay value
- Select/unselect (ignore) tests in Mac OSX view
- Added initWithTestSuite to GHTestApp for custom suites from test main

## 2008-04-16
- Adding ability to set run loops in async test case
- Adding more methods to NSURLConnection mock

# Release 0.3.6 (2008-04-13)

## 2008-04-13
- Adding swizzle methods for mocking
- Adding NSLocale mock
- Adding NSURLConnection, NSHTTPURLResponse mocks
- Fix bug with setUpClass/tearDownClass not working for single command line tests
- Setting Installation Directory to @rpath (Thanks chapados), so you can embed the framework with your app
- Sorting tests by class name (as well as method name)

# Release 0.3.4 (2009-04-11)

## 2008-04-11
- Added Doxygen support

## 2008-04-08
- Added GHAsyncTestCase for asynchronous tests (seems really complex :/, might have gone mental on it)
- Supporting streaming logging with GHTestLog(...)
- GHUNIT_VERSION from xcconfig in Info plists and shown in test GUI
- Mocks for NSURLConnection and NSHTTPURLResponse
- Added setUpClass/tearDownClass for GHTestCase
- Added currentSelector property for GHTestCase

# Release 0.3.3 (2009-04-08)

## 2009-04-08
- Removed GTMLogger and GHLogger; Not used in Release and potentially can
  conflict with project logging with iPhone static library

# Release 0.3.2 (2009-04-05)

## 2009-04-05
- Building as static library for iPhone
- Adding in support for running single test case or test

# Release 0.3.1

## 2009-03-22
- Renamed TEST_CLI to GHUNIT_CLI
- Removing main from target; Projects should specify their own test target main.
- Added test for special registered test case classes

## 2009-03-21
- Renamed Examples/MyTestable to MyTestable-IPhone

## 2009-03-19
- Commented a bunch of the code
- Renamed GHTestUtils to GHTesting


text:
package middleware

import (
	"encoding/base64"
	"net/http"

	"github.com/insionng/vodka"
)

type (
	BasicValidateFunc func(string, string) bool
)

const (
	Basic = "Basic"
)

// BasicAuth returns an HTTP basic authentication middleware.
//
// For valid credentials it calls the next handler.
// For invalid credentials, it sends "401 - Unauthorized" response.
func BasicAuth(fn BasicValidateFunc) vodka.HandlerFunc {
	return func(c *vodka.Context) error {
		// Skip WebSocket
		if (c.Request().Header.Get(vodka.Upgrade)) == vodka.WebSocket {
			return nil
		}

		auth := c.Request().Header.Get(vodka.Authorization)
		l := len(Basic)

		if len(auth) > l+1 && auth[:l] == Basic {
			b, err := base64.StdEncoding.DecodeString(auth[l+1:])
			if err == nil {
				cred := string(b)
				for i := 0; i < len(cred); i++ {
					if cred[i] == ':' {
						// Verify credentials
						if fn(cred[:i], cred[i+1:]) {
							return nil
						}
					}
				}
			}
		}
		c.Response().Header().Set(vodka.WWWAuthenticate, Basic+" realm=Restricted")
		return vodka.NewHTTPError(http.StatusUnauthorized)
	}
}


text:
=============================
django-publica-positions
=============================

.. image:: https://badge.fury.io/py/django-publica-positions.png
    :target: https://badge.fury.io/py/django-publica-positions

.. image:: https://travis-ci.org/DarylAntony/django-publica-positions.png?branch=master
    :target: https://travis-ci.org/DarylAntony/django-publica-positions

.. image:: https://coveralls.io/repos/DarylAntony/django-publica-positions/badge.png?branch=master
    :target: https://coveralls.io/r/DarylAntony/django-publica-positions?branch=master

"Template positions to show content"

Documentation
-------------

The full documentation is at https://django-publica-positions.readthedocs.org.

Quickstart
----------

Install django-publica-positions::

    pip install django-publica-positions

Then use it in a project::

    import django-publica-positions

Features
--------

* TODO


text:
<?php if($btn){?>

        <?=$btn;?>

<?php }?>

      <form method="post" id="simple_search_form">

          <?php echo form_dropdown('search_type', $simple_search_fields, $search_conditions['search_type'], 'class="form-control"');?>

            <input type="text" class="form-control" name="search_text" value="<?php echo $search_conditions['search_text'];?>" placeholder="Search some stuff.">

            <button class="btn blue" type="button"  id="simple_search_button" data-placement="top" data-toggle="tooltip" data-original-title="search"></button>

            Clear Filter

      </form>

          Show entries:

            <?php echo form_dropdown('per_page_options', $per_page_options, $per_page, 'class="form-control input-sm"');?>


text:
package org.terasology.logic.behavior.tree;

import org.terasology.engine.ComponentFieldUri;
import org.terasology.module.sandbox.API;
import org.terasology.rendering.assets.animation.MeshAnimation;
import org.terasology.rendering.logic.SkeletalMeshComponent;
import org.terasology.rendering.nui.properties.OneOf;

import java.util.List;
import java.util.Random;

/**
 * Plays a animation from a animation set and sets the animation pool to pick animation to play from.
 *
 * The node stays forever in status RUNNING.
 *
 */
@API
public class SetAnimationNode extends Node {
    @OneOf.Provider(name = "animations")
    private ComponentFieldUri play;

    @OneOf.Provider(name = "animations")
    private ComponentFieldUri loop;

    public SetAnimationNode() {
    }

    @Override
    public SetAnimationTask createTask() {
        return new SetAnimationTask(this);
    }

    public static class SetAnimationTask extends Task {
        private Random random;

        public SetAnimationTask(SetAnimationNode node) {
            super(node);
            random = new Random();
        }

        @Override
        public void onInitialize() {
            SkeletalMeshComponent skeletalMesh = actor().skeletalMesh();
            if (getNode().play != null) {
                List<?> animationListToPlay = (List<?>) actor().getComponentField(getNode().play);
                if (animationListToPlay != null) {
                    skeletalMesh.animation = (MeshAnimation) animationListToPlay.get(
                            random.nextInt(animationListToPlay.size()));
                } else {
                    // ignore error, effect is visible
                    skeletalMesh.animation = null;
                }
            }
            if (getNode().loop != null) {
                skeletalMesh.animationPool.clear();
                List<?> animationListToLoop = (List<?>) actor().getComponentField(getNode().loop);
                if (animationListToLoop != null) {
                    for (Object object : animationListToLoop) {
                        skeletalMesh.animationPool.add((MeshAnimation) object);
                    }
                }
            }
            skeletalMesh.loop = true;
            actor().save(skeletalMesh);
        }

        @Override
        public void handle(Status result) {

        }

        @Override
        public Status update(float dt) {
            return  Status.SUCCESS;
        }

        @Override
        public SetAnimationNode getNode() {
            return (SetAnimationNode) super.getNode();
        }

    }
}


text:
/**
 * openHAB, the open Home Automation Bus.
 * Copyright (C) 2010-2012, openHAB.org <admin@openhab.org>
 *
 * See the contributors.txt file in the distribution for a
 * full listing of individual contributors.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 *
 * Additional permission under GNU GPL version 3 section 7
 *
 * If you modify this Program, or any covered work, by linking or
 * combining it with Eclipse (or a modified version of that library),
 * containing parts covered by the terms of the Eclipse Public License
 * (EPL), the licensors of this Program grant you additional permission
 * to convey the resulting work.
 */
package org.ow2.chameleon.fuchsia.importer.zwave.internal.commandclass;

import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.SerialMessage;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.SerialMessage.SerialMessageClass;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.SerialMessage.SerialMessagePriority;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.SerialMessage.SerialMessageType;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.ZWaveController;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.ZWaveEndpoint;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.ZWaveEvent;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.ZWaveEvent.ZWaveEventType;
import org.ow2.chameleon.fuchsia.importer.zwave.internal.protocol.ZWaveNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Handles the Binary Switch command class. Binary switches can be turned on or off and report
 * their status as on (0xFF) or off (0x00).
 *
 * The commands include the possibility to set a given level, get a given level and report a level.
 *
 * @author Jan-Willem Spuij
 * @since 1.3.0
 */
public class ZWaveBinarySwitchCommandClass extends ZWaveCommandClass implements ZWaveBasicCommands {

	private static final Logger logger = LoggerFactory.getLogger(ZWaveBinarySwitchCommandClass.class);

	private static final int SWITCH_BINARY_SET = 0x01;
	private static final int SWITCH_BINARY_GET = 0x02;
	private static final int SWITCH_BINARY_REPORT = 0x03;

	/**
	 * Creates a new instance of the ZWaveBinarySwitchCommandClass class.
	 * @param node the node this command class belongs to
	 * @param controller the controller to use
	 * @param endpoint the endpoint this Command class belongs to
	 */
	public ZWaveBinarySwitchCommandClass(ZWaveNode node,
			ZWaveController controller, ZWaveEndpoint endpoint) {
		super(node, controller, endpoint);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public CommandClass getCommandClass() {
		return CommandClass.SWITCH_BINARY;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void handleApplicationCommandRequest(SerialMessage serialMessage,
			int offset, int endpoint) {
		logger.trace("Handle Message Switch Binary Request");
		logger.debug(String.format("Received Switch Binary Request for Node ID = %d", this.getNode().getNodeId()));
		int command = serialMessage.getMessagePayloadByte(offset);
		switch (command) {
			case SWITCH_BINARY_SET:
			case SWITCH_BINARY_GET:
				logger.warn(String.format("Command 0x%02X not implemented.", command));
				return;
			case SWITCH_BINARY_REPORT:
				logger.trace("Process Switch Binary Report");

				int value = serialMessage.getMessagePayloadByte(offset + 1);
				logger.debug(String.format("Switch Binary report from nodeId = %d, value = 0x%02X", this.getNode().getNodeId(), value));
				Object eventValue;
				if (value == 0) {
					eventValue = "OFF";
				} else {
					eventValue = "ON";
				}
				ZWaveEvent zEvent = new ZWaveEvent(ZWaveEventType.SWITCH_EVENT, this.getNode().getNodeId(), endpoint, eventValue);
				this.getController().notifyEventListeners(zEvent);
				break;
			default:
			logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).",
					command,
					this.getCommandClass().getLabel(),
					this.getCommandClass().getKey()));
		}
	}

	/**
	 * Gets a SerialMessage with the SWITCH_BINARY_GET command
	 * @return the serial message
	 */
	public SerialMessage getValueMessage() {
		logger.debug("Creating new message for application command SWITCH_BINARY_GET for node {}", this.getNode().getNodeId());
		SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);
    	byte[] newPayload = { 	(byte) this.getNode().getNodeId(),
    							2,
								(byte) getCommandClass().getKey(),
								(byte) SWITCH_BINARY_GET };
    	result.setMessagePayload(newPayload);
    	return result;
	}

	/**
	 * Gets a SerialMessage with the SWITCH_BINARY_SET command
	 * @param the level to set. 0 is mapped to off, > 0 is mapped to on.
	 * @return the serial message
	 */
	public SerialMessage setValueMessage(int level) {
		logger.debug("Creating new message for application command SWITCH_BINARY_SET for node {}", this.getNode().getNodeId());
		SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);
    	byte[] newPayload = { 	(byte) this.getNode().getNodeId(),
    							3,
								(byte) getCommandClass().getKey(),
								(byte) SWITCH_BINARY_SET,
								(byte) (level > 0 ? 0xFF : 0x00)
								};
    	result.setMessagePayload(newPayload);
    	return result;
	}

}


text:
namespace  {

namespace instrumentation = bart::instrumentation;
namespace test_helpers = bart::test_helpers;

using ::testing::Return, ::testing::ReturnRef, ::testing::DoDefault;

class InstrumentationBuilderInstrumentBuilderTest : public ::testing::Test {
 public:
  using Builder = instrumentation::builder::InstrumentBuilder;
  using DealiiVector = dealii::Vector<double>;
  using InstrumentName = instrumentation::builder::InstrumentName;
  using IntDoublePair = std::pair<int, double>;
  using ConvergenceStatus = bart::convergence::Status;
  using StringColorPair = std::pair<std::string, bart::utility::Color>;
  using SphericalHarmonics = bart::system::moments::SphericalHarmonicI;
};

TEST_F(InstrumentationBuilderInstrumentBuilderTest,
       ColorStringToConditionalOstream) {
  using InstrumentType = instrumentation::Instrument<StringColorPair, std::string>;
  using ConverterType = instrumentation::converter::convert_to_string::StringColorPairToString;
  using OutstreamType = instrumentation::outstream::ToConditionalOstream;
  auto instrument_ptr = Builder::BuildInstrument<StringColorPair>(
      instrumentation::builder::InstrumentName::kColorStatusToConditionalOstream);
  ASSERT_NE(instrument_ptr, nullptr);
  auto dynamic_ptr = dynamic_cast<InstrumentType*>(instrument_ptr.get());
  ASSERT_NE(dynamic_ptr, nullptr);
  ASSERT_NE(dynamic_cast<ConverterType*>(dynamic_ptr->converter_ptr()), nullptr);
  ASSERT_NE(dynamic_cast<OutstreamType*>(dynamic_ptr->outstream_ptr()), nullptr);
}

TEST_F(InstrumentationBuilderInstrumentBuilderTest, AllGroupsFourierInstrument) {
  using InstrumentType = instrumentation::Instrument<SphericalHarmonics, std::string>;
  using SphericalHarmonicMock = bart::system::moments::SphericalHarmonicMock;
  std::unique_ptr<SphericalHarmonics> mock_spherical_harmonics =
      std::make_unique<SphericalHarmonicMock>();
  SphericalHarmonicMock* mock_spherical_harmonic_obs_ptr =
      dynamic_cast<SphericalHarmonicMock*>(mock_spherical_harmonics.get());
  const int total_groups{ test_helpers::RandomInt(5, 10) };
  const int flux_size { test_helpers::RandomInt(10, 20) };
  const std::string filename_base { "filename_base" };
  std::vector<dealii::Vector<double>> group_scalar_fluxes(total_groups);

  for (int i = 0; i < total_groups; ++i) {
    dealii::Vector<double> group_flux(flux_size);
    for (dealii::Vector<double>::size_type i = 0; i < group_flux.size(); ++i) {
      group_flux[i] = test_helpers::RandomDouble(-100, 100);
    }
    group_scalar_fluxes.emplace_back(group_flux);
  }

  EXPECT_CALL(*mock_spherical_harmonic_obs_ptr, total_groups())
      .WillOnce(Return(total_groups));
  for (int i = 0; i < total_groups; ++i) {
    EXPECT_CALL(*mock_spherical_harmonic_obs_ptr,
                GetMoment(std::array{i, 0, 0}))
        .WillOnce(ReturnRef(group_scalar_fluxes.at(i)));
  }

  auto instrument_ptr = Builder::BuildInstrument<SphericalHarmonics>(
      InstrumentName::kFourierTransformOfAllGroupScalarFluxErrorToFile,
      mock_spherical_harmonics.get(),
      filename_base);

  using InstrumentArrayType = instrumentation::InstrumentArray<SphericalHarmonics>;
  using InstrumentType = instrumentation::Instrument<SphericalHarmonics, std::string>;
  using OutStreamType = instrumentation::outstream::ToOstream;

  auto array_dynamic_ptr = dynamic_cast<InstrumentArrayType*>(instrument_ptr.get());
  ASSERT_NE(array_dynamic_ptr, nullptr);
  EXPECT_EQ(array_dynamic_ptr->size(), total_groups);
  for (const auto& instrument : *array_dynamic_ptr) {
    auto dynamic_ptr = dynamic_cast<InstrumentType*>(instrument.get());
    ASSERT_NE(dynamic_ptr, nullptr);
    ASSERT_NE(dynamic_cast<OutStreamType*>(dynamic_ptr->outstream_ptr()), nullptr);
  }

  for (int i = 0; i < total_groups; ++i) {
    std::string filename = filename_base + '_' + std::to_string(i) + ".csv";
    EXPECT_EQ(remove(filename.c_str()), 0);
  }

}

TEST_F(InstrumentationBuilderInstrumentBuilderTest, FourierInstrument) {
  using InstrumentType = instrumentation::Instrument<SphericalHarmonics, std::string>;
  using OutStreamType = instrumentation::outstream::ToOstream;
  const std::string filename{ "filename.csv" };
  const int group{ test_helpers::RandomInt(0, 10) };

  dealii::Vector<double> error_vector(test_helpers::RandomInt(5, 10));
  for (auto& entry : error_vector)
    entry = test_helpers::RandomDouble(0, 1000);

  auto instrument_ptr = Builder::BuildInstrument<SphericalHarmonics>(
      InstrumentName::kFourierTransformOfSingleGroupScalarFluxErrorToFile, group, error_vector, filename);
  ASSERT_NE(instrument_ptr, nullptr);
  auto dynamic_ptr = dynamic_cast<InstrumentType*>(instrument_ptr.get());
  ASSERT_NE(dynamic_ptr, nullptr);

  // This is a nested instrument with many levels; we'll check each converter
  using ComplexVector = std::vector<std::complex<double>>;
  using IntComplexVectorPair = std::pair<int, ComplexVector>;
  using MultiConverterOne = instrumentation::converter::MultiConverter<SphericalHarmonics, IntComplexVectorPair, std::string>;
  // First multi-converter
  auto multi_converter_one_ptr =
      dynamic_cast<MultiConverterOne*>(dynamic_ptr->converter_ptr());
  ASSERT_NE(multi_converter_one_ptr, nullptr);
  ASSERT_NE(
      dynamic_cast<instrumentation::converter::convert_to_string::IntVectorComplexPairToString*>(
          multi_converter_one_ptr->second_stage_converter_ptr()), nullptr);
  // Next multi-converter
  using MultiConverterTwo = instrumentation::converter::MultiConverter<SphericalHarmonics, ComplexVector, IntComplexVectorPair>;
  auto multi_converter_two_ptr = dynamic_cast<MultiConverterTwo*>(
      multi_converter_one_ptr->first_stage_converter_ptr());
  ASSERT_NE(multi_converter_two_ptr, nullptr);
  ASSERT_NE(
      dynamic_cast<instrumentation::converter::PairIncrementer<ComplexVector>*>(
          multi_converter_two_ptr->second_stage_converter_ptr()), nullptr);
  // Next multi-converter
  using MultiConverterThree = instrumentation::converter::MultiConverter<SphericalHarmonics, ComplexVector, ComplexVector>;
  auto multi_converter_three_ptr = dynamic_cast<MultiConverterThree*>(
      multi_converter_two_ptr->first_stage_converter_ptr());
  ASSERT_NE(multi_converter_three_ptr, nullptr);
  ASSERT_NE(
      dynamic_cast<instrumentation::converter::fourier::FourierTransform*>(
          multi_converter_three_ptr->second_stage_converter_ptr()), nullptr);
  // Next multi-converter
  using MultiConverterFour = instrumentation::converter::MultiConverter<SphericalHarmonics , DealiiVector , ComplexVector >;
  auto multi_converter_four_ptr = dynamic_cast<MultiConverterFour*>(
      multi_converter_three_ptr->first_stage_converter_ptr());
  ASSERT_NE(multi_converter_four_ptr, nullptr);
  ASSERT_NE(dynamic_cast<instrumentation::converter::DealiiToComplexVector*>(
      multi_converter_four_ptr->second_stage_converter_ptr()), nullptr);
  ASSERT_NE(dynamic_cast<OutStreamType*>(dynamic_ptr->outstream_ptr()), nullptr);
  EXPECT_EQ(remove(filename.c_str()), 0);

  // Next multi-converter
  using MultiConverterFive = instrumentation::converter::MultiConverter<SphericalHarmonics , DealiiVector , DealiiVector >;
  auto multi_converter_five_ptr = dynamic_cast<MultiConverterFive*>(
      multi_converter_four_ptr->first_stage_converter_ptr());
  ASSERT_NE(multi_converter_five_ptr, nullptr);

  auto group_scalar_flux_extractor_ptr =
      dynamic_cast<instrumentation::converter::system::GroupScalarFluxExtractor*>(
          multi_converter_five_ptr->first_stage_converter_ptr());
  ASSERT_NE(group_scalar_flux_extractor_ptr, nullptr);
  EXPECT_EQ(group_scalar_flux_extractor_ptr->group_to_extract(), group);

  auto vector_subtractor_ptr = dynamic_cast<instrumentation::converter::calculator::VectorSubtractor*>(
      multi_converter_five_ptr->second_stage_converter_ptr());
  ASSERT_NE(vector_subtractor_ptr, nullptr);
  EXPECT_EQ(vector_subtractor_ptr->minuend(), error_vector);

}

TEST_F(InstrumentationBuilderInstrumentBuilderTest,
       ConvergenceStatusToConditionalOstream) {
  using InstrumentType = instrumentation::Instrument<ConvergenceStatus, std::string>;
  using ConverterType = instrumentation::converter::convert_to_string::ConvergenceToString;
  using OutstreamType = instrumentation::outstream::ToConditionalOstream;
  auto instrument_ptr = Builder::BuildInstrument<ConvergenceStatus>(
      InstrumentName::kConvergenceStatusToConditionalOstream);
  ASSERT_NE(instrument_ptr, nullptr);
  auto dynamic_ptr = dynamic_cast<InstrumentType*>(instrument_ptr.get());
  ASSERT_NE(dynamic_ptr, nullptr);
  ASSERT_NE(dynamic_cast<ConverterType*>(dynamic_ptr->converter_ptr()), nullptr);
  ASSERT_NE(dynamic_cast<OutstreamType*>(dynamic_ptr->outstream_ptr()), nullptr);
}

TEST_F(InstrumentationBuilderInstrumentBuilderTest,
       IntDoublePairToFile) {
  const std::string filename{ "filename.csv" };
  using InstrumentType = instrumentation::Instrument<IntDoublePair, std::string>;
  using ConverterType = instrumentation::converter::convert_to_string::IntDoublePairToString;
  using OutstreamType = instrumentation::outstream::ToOstream;
  auto instrument_ptr = Builder::BuildInstrument<IntDoublePair>(
      InstrumentName::kIntDoublePairToFile,
      filename);
  ASSERT_NE(instrument_ptr, nullptr);
  auto dynamic_ptr = dynamic_cast<InstrumentType*>(instrument_ptr.get());
  ASSERT_NE(dynamic_ptr, nullptr);
  ASSERT_NE(dynamic_cast<ConverterType*>(dynamic_ptr->converter_ptr()), nullptr);
  ASSERT_NE(dynamic_cast<OutstreamType*>(dynamic_ptr->outstream_ptr()), nullptr);
  EXPECT_EQ(remove(filename.c_str()), 0);
}

TEST_F(InstrumentationBuilderInstrumentBuilderTest, DoubleToFile) {
  const std::string filename{ "filename.csv" };
  using InstrumentType = instrumentation::Instrument<double, std::string>;
  using ConverterType = instrumentation::converter::convert_to_string::DoubleToString;
  using OutstreamType = instrumentation::outstream::ToOstream;
  auto instrument_ptr = Builder::BuildInstrument<double>(InstrumentName::kDoubleToFile, filename);
  ASSERT_NE(instrument_ptr, nullptr);
  auto dynamic_ptr = dynamic_cast<InstrumentType*>(instrument_ptr.get());
  ASSERT_NE(dynamic_ptr, nullptr);
  ASSERT_NE(dynamic_cast<ConverterType*>(dynamic_ptr->converter_ptr()), nullptr);
  ASSERT_NE(dynamic_cast<OutstreamType*>(dynamic_ptr->outstream_ptr()), nullptr);
  EXPECT_EQ(remove(filename.c_str()), 0);
}

TEST_F(InstrumentationBuilderInstrumentBuilderTest,
       StringToConditionalOstream) {
  using InstrumentType = instrumentation::BasicInstrument<std::string>;
  using OutstreamType = instrumentation::outstream::ToConditionalOstream;
  auto instrument_ptr = Builder::BuildInstrument<std::string>(
      instrumentation::builder::InstrumentName::kStringToConditionalOstream);
  ASSERT_NE(instrument_ptr, nullptr);
  auto dynamic_ptr = dynamic_cast<InstrumentType*>(instrument_ptr.get());
  ASSERT_NE(dynamic_ptr, nullptr);
  ASSERT_NE(dynamic_cast<OutstreamType*>(dynamic_ptr->outstream_ptr()), nullptr);
}

TEST_F(InstrumentationBuilderInstrumentBuilderTest,
       BadInstrumentNamesPerType) {
  EXPECT_ANY_THROW(Builder::BuildInstrument<std::string>(
      instrumentation::builder::InstrumentName::kColorStatusToConditionalOstream));
  EXPECT_ANY_THROW(Builder::BuildInstrument<StringColorPair>(
      instrumentation::builder::InstrumentName::kStringToConditionalOstream));

  for (auto bad_name : {InstrumentName::kColorStatusToConditionalOstream,
                        InstrumentName::kStringToConditionalOstream}) {
    EXPECT_ANY_THROW(Builder::BuildInstrument<ConvergenceStatus>(bad_name));
  }

  for (auto bad_name : {InstrumentName::kColorStatusToConditionalOstream,
                        InstrumentName::kStringToConditionalOstream,
                        InstrumentName::kConvergenceStatusToConditionalOstream}) {
    EXPECT_ANY_THROW(Builder::BuildInstrument<IntDoublePair>(bad_name, std::string{}));
  }

  for (auto bad_name : {InstrumentName::kColorStatusToConditionalOstream,
                        InstrumentName::kStringToConditionalOstream,
                        InstrumentName::kConvergenceStatusToConditionalOstream}) {
    EXPECT_ANY_THROW(Builder::BuildInstrument<double>(bad_name, std::string{}));
  }

  for (auto bad_name : {InstrumentName::kColorStatusToConditionalOstream,
                        InstrumentName::kStringToConditionalOstream,
                        InstrumentName::kConvergenceStatusToConditionalOstream,
                        InstrumentName::kIntDoublePairToFile,
                        InstrumentName::kFourierTransformOfAllGroupScalarFluxErrorToFile}) {
    EXPECT_ANY_THROW(Builder::BuildInstrument<SphericalHarmonics>(bad_name,
                                                            int{},
                                                            DealiiVector{},
                                                            std::string{}));
  }
  for (auto bad_name : {InstrumentName::kColorStatusToConditionalOstream,
                        InstrumentName::kStringToConditionalOstream,
                        InstrumentName::kConvergenceStatusToConditionalOstream,
                        InstrumentName::kIntDoublePairToFile,
                        InstrumentName::kFourierTransformOfSingleGroupScalarFluxErrorToFile}) {
    std::unique_ptr<SphericalHarmonics> spherical_harmonics
        = std::make_unique<bart::system::moments::SphericalHarmonicMock>();
    EXPECT_ANY_THROW(Builder::BuildInstrument<SphericalHarmonics>(
        bad_name,
        spherical_harmonics.get(),
        std::string{}));
  }
}

} // namespace