text:
/*
Weather App Javascript | MIT License
This weather app fetches the weather data of a city and continually updates it
*/

// Setup
var localData;
var BASE_URL = "YOUR WEBHOOK GOES HERE";
var syncano = new Syncano({
	apiKey: 'YOUR API KEY GOES HERE',
	instance: 'YOUR INSTANCE NAME GOES HERE'
});

//Map of conditions to weather icon class for matching
var condition = {
	mist: 'wi-day-sprinkle',
	fog: 'wi-day-fog',
	clear: 'wi-day-sunny',
	drizzle: 'wi-day-sprinkle',
	rain: 'wi-day-rain',
	thunderstorm: 'wi-day-thunderstorm',
	snow: 'wi-day-snow',
	cloud: 'wi-day-cloudy',
	haze: 'wi-day-haze'
};

//helper function to return correct weather icon
function getWeatherIcon(desc) {
	var keys = Object.keys(condition);

	for (var i = 0; i < keys.length; i++) {
		var r = new RegExp(keys[i], 'i');
		if (desc.match(r)) {
			return condition[keys[i]];
		}
	}

	return 'wi-day-cloudy';
};

//helper function to convert kelvin to ahrenheit
function kToF(k) {
	 return (Math.round(kToC(k) * 1.8000 + 32.00));
};

//helper function to convert kelvin to celcius
function kToC(k) {
	return (Math.round(k - 273.15));
};

//converts temp to proper scale depending on current setting of F or C
function convertTemp(k) {
	if (localData.scale === "F") {
		return kToF(k);
	} else {
		return kToC(k);
	}
}

//click handler for the F/C toggle in the UI
function toggleScale() {
	localData.scale = (localData.scale === 'F') ? 'C' : 'F';
	store('syncano-weather', localData);
	$('#scale span').text(localData.scale);
	var temps = $('*[data-temp]');

	for (var i = 0; i < temps.length; i++) {
		$t = $(temps[i]);
		//convert the temperature
		$t.get(0).childNodes[0].nodeValue = convertTemp($t.data("temp"));
		//change the scale text
		$t.find('span').text(localData.scale);
	}
}

// Handlebar helpers

//take a temp in kelvin, and displays the proper temperature
Handlebars.registerHelper('displayTemp', function(k) {
  var out = convertTemp(k) + '°' + localData.scale + '';
  return new Handlebars.SafeString(out);
});

//takes the short description from the data result, and returns the proper class for the weather icon
Handlebars.registerHelper('displayIcon', function(desc) {
	var out = '';
  return new Handlebars.SafeString(out);
});

//takes a string representation of utc time, and outouts the proper day, abbreviated to three letters
Handlebars.registerHelper('displayDay', function(t) {
	var day = new Date(t*1000);
  return new Handlebars.SafeString(day.toDateString().substring(0, 3));
});

//compile handlebar templates first
var wBoxTemplate = Handlebars.compile($('#wBox-template').html());

//localStorage
var store =  function (namespace, data) {
	if (arguments.length > 1) {
		return localStorage.setItem(namespace, JSON.stringify(data));
	} else {
		var store = localStorage.getItem(namespace);
		return (store && JSON.parse(store)) || {scale: 'F', city_ids: []};
	}
}
//This is where all of the real time action happens with Syncano.
function sync(id) {
	var realtime =  syncano.channel("weather_realtime").watch({room: id});

	realtime.on('update', function(res){
		console.log('updating');
		if(res) {
			var city = $('div[data-cityid="' + id + '"]');
			if (res.current_temp) {
				var cTemp = $(city.find('.curr_temp'));
				cTemp.attr('data-temp', res.current_temp);
				cTemp.get(0).childNodes[0].nodeValue = convertTemp(res.current_temp);
			}
			if (res.short_description) {
				var cIcon = $(city.find('.curr_cond'));
				cIcon.removeClass();
				cIcon.addClass('wi ' + getWeatherIcon(res.short_description));
			}
		}
		return;
	});
	return;
}

// Creates a weather box whenever the 'Add' button is pressed.
function addWBox(city_id) {
	//also add by city id here as well
	var url;

	if (typeof(city_id) === 'number') {
		url = BASE_URL + '?city_id=' + city_id;
	} else {
		var name = $( '#city' ).val();
		var city = '?city=' + name.split(' ').join('%20');
		var state = '&stateOrCountry=' + $( '#state' ).val();
		url = BASE_URL + city + state;
	}

	$.get(url, function(data){
		var res = JSON.parse(data.result.stdout);

		if($("div[data-cityId*='"+ res.city_id + "']").length === 0) {
			res.forecast = JSON.parse(res.forecast);
			$newBox = $('
').html(wBoxTemplate(res));
			$newBox.appendTo( "#weatherBoxes" );
			//store city id in local storage for retrieval
			if (localData.city_ids.indexOf(res.city_id) === -1) {
				localData.city_ids.push(res.city_id);
				store('syncano-weather', localData);
			};

			$('input[type=text]').val('').blur();
			$( '#empty' ).hide();

			//watch the channel for updates to the weather
			return sync(res.city_id);
		} else {
			return;
		}

	});

};

// Set onClick handler for button and Enter Key for text boxes
$(document).ready(function(){

	//check local storage, and add boxes
	localData = store('syncano-weather');

	//set the initial scale
	$('#scale span').text(localData.scale);

	//load stored cities
	for(var i = 0; i < localData.city_ids.length; i++) {
		addWBox(localData.city_ids[i]);
	};

	$( "#addWeather" ).on('click', addWBox);
	$( "input" ).keypress(function(e) {
		if (e.keyCode == 13)
			addWBox();
    });

	$( "#scale" ).click(toggleScale);

	$( document ).on('click', '.exit', function() {
		$(this).parent().parent().parent().parent().fadeOut(function(){
			var id = $(this).data('cityid');
			var index = localData.city_ids.indexOf(id);
			if (index > -1) {
			    localData.city_ids.splice(index, 1);
			};
			store('syncano-weather', localData);
			$(this).remove();
		})
	});

});


text:
title: 	Meningkatkan kesadaran akan manipulasi sejarah yang direkayasa oleh Orde Baru dan masih diyakini oleh banyak orang hingga kini
date: 	2012-09-30
categories:
- laporan
- Bhinneka
layout: laporancmb
---

![200px-September_30_2012_Bhinneka_pembukaan_pelatihan.JPG](/uploads/200px-September_30_2012_Bhinneka_pembukaan_pelatihan.JPG){: .img-responsive .center-block }
![200px-September_30_2012_Bhinneka_pembukaan_pelatihan_1.JPG](/uploads/v){: .img-responsive .center-block }

**Tujuan** :	Meningkatkan kesadaran akan manipulasi sejarah yang direkayasa oleh Orde Baru dan masih diyakini oleh banyak orang hingga kini

**Lokasi** :	Surabaya

**Alamat** : 	Sekolah Mandala jl Putro Agung

**Jam** :	Jam 15.30 - 17.00

**Hadir** :
*	Soe Tjen Marching (Fasilitator)
*	Kristianto Batuadji (Fasilitator)
*	11 peserta yang hadir di seminar sebelumnya (tentang G30 SPKI)

**Ringkasan** :
*	Pembukaan pelatihan Multikulturalisme dalam kehidupan sehari-hari mahasiswa.
*	Mereka yang hadir di seminar diperkenalkan kepada pelatihan ini dan mengapa pelatihan ini dilaksanakan
*	TOR bisa disimak di: https://www.facebook.com/lembaga.bhinneka?sk=notes

redpajama_set_name: RedPajamaGithub


text:
4. Associations and Relational Mappings
#######################################

Usually data from different collections are related and may co-exist. As the
result, even though some database softwares do not allow associations, Passerine
allows the software-based relational mapping. This ORM supports all types of
relational mapping either unidirectionally or bidirectionally.

Passerine ORM utilizes two patterns to implement association.

* Decorators (AKA annotations) to define associations.
* Lazy loading to load data when it is requested.
* Proxy object as direct result of lazy loading.

In general, the decorator :meth:`passerine.db.mapper.link` is used to define
association by mapping decorated fields to another classes by primary key (or
object ID). The ID-to-object happens automatically during data mapping.

Types of Associations
=====================

For the sake of the simplicity of this chapter, all examples are assumed to
be in the module ``sampleapp.model``, and begin with::

    from passerine.db.entity import entity
    from passerine.db.mapper import link, AssociationType as t, CascadingType as c

One-to-one
----------

Suppose there are two entities: ``Owner`` and ``Restaurant``,
**one-to-one associations** imply the relationship between two entities as
described in the following UML::

     Owner (1) ----- (1) Restaurant

Unidirectional
~~~~~~~~~~~~~~

UML::

    Owner (1) <--x- (1) Restaurant

Suppose we have two classes: ``Owner`` and ``Restaurant``, where ``Restaurant``
has the one-to-one unidirectional relationship with ``Owner``.

.. code-block:: python

    @entity
    class Owner(object):
        def __init__(self, name):
            self.name  = name

    @link(
        target      = 'sampleapp.model.Owner',
        mapped_by   = 'owner',
        association = t.ONE_TO_ONE
    )
    @entity
    class Restaurant(object):
        def __init__(self, name, owner):
            self.name  = name
            self.owner = owner

where the sample of the stored documents will be:

.. code-block:: javascript

    // collection: owner
    {'_id': 'o-1', 'name': 'siamese'}

    // collection: restaurant
    {'_id': 'rest-1', 'name': 'green curry', 'owner': 'o-1'}

.. tip::

    To avoid the issue with the order of declaration, the full namespace in
    string is recommended to define the target class. However, the type
    reference can also be. For example, ``@link(target = Owner, ...)``.

Bidirectional
~~~~~~~~~~~~~

UML::

    Owner (1) <---> (1) Restaurant

Now, let's allow ``Owner`` to have a reference back to ``Restaurant`` where the
information about the reference is not kept with ``Owner``. So, the

.. code-block:: python

    @link(
        target      = 'sampleapp.model.Restaurant'
        inverted_by = 'owner',
        mapped_by   = 'restaurant',
        association = t.ONE_TO_ONE
    )
    @entity
    class Owner(object):
        def __init__(self, name, restaurant):
            self.name       = name
            self.restaurant = restaurant

where the the stored documents will be the same as the previous example.

``inverted_by`` means this class (``Owner``) maps ``Restaurant`` to the property
*restaurant* where the value of the property *owner* of the corresponding entity
of Restaurant must equal the *ID* of this class.

.. note::

    The option ``inverted_by`` only maps ``Owner.restaurant`` to ``Restaurant``
    virtually but the reference is stored in the **restaurant** collection.

Many-to-one
-----------

Suppose a ``Customer`` can have many ``Reward``'s as illustrated::

    Customer (1) ----- (0..n) Reward

Unidirectional
~~~~~~~~~~~~~~

UML::

    Customer (1) <--x- (0..n) Reward

.. code-block:: python

    @entity
    class Customer(object):
        def __init__(self, name):
            self.name    = name

    @link(
        target      = 'sampleapp.model.Customer',
        mapped_by   = 'customer',
        association = t.MANY_TO_ONE
    )
    @entity
    class Reward(object):
        def __init__(self, point, customer):
            self.point    = point
            self.customer = customer

where the data stored in the database can be like this:

.. code-block:: javascript

    // collection: customer
    {'_id': 'c-1', 'name': 'panda'}

    // collection: reward
    {'_id': 'rew-1', 'point': 2, 'customer': 'c-1'}
    {'_id': 'rew-2', 'point': 13, 'customer': 'c-1'}

.. _manual_orm_associations_m-1_bidirectional:

Bidirectional
~~~~~~~~~~~~~

UML::

    Customer (1) <---> (0..n) Reward

Just change ``Customer``.

.. code-block:: python

    @link(
        target      = 'sampleapp.model.Reward',
        inverted_by = 'customer',
        mapped_by   = 'rewards',
        association = t.ONE_TO_MANY
    )
    @entity
    class Customer(object):
        def __init__(self, name, rewards):
            self.name    = name
            self.rewards = rewards

where the property *rewards* refers to a list of rewards but the stored data
remains unchanged.

.. note:: This mapping is equivalent to a **bidirectional one-to-many mapping**.

One-to-many
-----------

Let's restart the example from the many-to-one section.

Unidirectional with Built-in List
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The one-to-many unidirectional mapping takes advantage of the built-in list.

UML::

    Customer (1) -x--> (0..n) Reward

.. code-block:: python

    @link(
        target      = 'sampleapp.model.Reward',
        mapped_by   = 'rewards',
        association = t.ONE_TO_MANY
    )
    @entity
    class Customer(object):
        def __init__(self, name, rewards):
            self.name    = name
            self.rewards = rewards

    @entity
    class Reward(object):
        def __init__(self, point):
            self.point = point

where the property ``rewards`` is a unsorted iterable list of ``Reward`` objects
and the data stored in the database can be like this:

.. code-block:: javascript

    // collection: customer
    {'_id': 'c-1', 'name': 'panda', 'reward': ['rew-1', 'rew-2']}

    // collection: reward
    {'_id': 'rew-1', 'point': 2}
    {'_id': 'rew-2', 'point': 13}

.. warning::

    As there is no way to enforce relationships with built-in functionality of
    MongoDB and there will be constant checks for every write operation, it is
    not recommended to use unless it is for **reverse mapping** via the option
    ``inverted_by`` (see below for more information).

    Without a proper checker, which is not provided for performance sake, this
    mapping can be used like the **many-to-many join-collection mapping**.

Bidirectional
~~~~~~~~~~~~~

See :ref:`Many-to-one Bidirectional Association <manual_orm_associations_m-1_bidirectional>`.

Many-to-many
------------

Suppose there are ``Teacher`` and ``Student`` where students can have many
teachers and vise versa::

    Teacher (*) ----- (*) Student

Similar other ORMs, the many-to-many mapping uses the corresponding join
collection.

Unidirectional with Join Collection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

UML::

    Teacher (*) <--x- (*) Student

.. code-block:: python

    @entity('teachers')
    class Teacher(object):
        def __init__(self, name):
            self.name = name

    @link(
        mapped_by   = 'teachers',
        target      = Teacher,
        association = AssociationType.MANY_TO_MANY,
        cascading   = [c.DELETE, c.PERSIST]
    )
    @entity('students')
    class Student(object):
        def __init__(self, name, teachers=[]):
            self.name     = name
            self.teachers = teachers

where the stored data can be like the following example:

.. code-block:: javascript

    // db.students.find()
    {'_id': 1, 'name': 'Shirou'}
    {'_id': 2, 'name': 'Shun'}
    {'_id': 3, 'name': 'Bob'}

    // db.teachers.find()
    {'_id': 1, 'name': 'John McCain'}
    {'_id': 2, 'name': 'Onizuka'}

    // db.students_teachers.find() // -> join collection
    {'_id': 1, 'origin': 1, 'destination': 1}
    {'_id': 2, 'origin': 1, 'destination': 2}
    {'_id': 3, 'origin': 2, 'destination': 2}
    {'_id': 4, 'origin': 3, 'destination': 1}

Bidirectional
~~~~~~~~~~~~~

.. code-block:: python

    @link(
        mapped_by   = 'students',
        inverted_by = 'teachers',
        target      = 'sampleapp.model',
        association = AssociationType.MANY_TO_MANY
    )
    @entity('teachers')
    class Teacher(object):
        def __init__(self, name, students=[]):
            self.name     = name
            self.students = students

    @link(
        mapped_by   = 'teachers',
        target      = Teacher,
        association = AssociationType.MANY_TO_MANY,
        cascading   = [c.DELETE, c.PERSIST]
    )
    @entity('students')
    class Student(object):
        def __init__(self, name, teachers=[]):
            self.name     = name
            self.teachers = teachers

Options for Associations
========================

The decorator :meth:`passerine.db.mapper.link` has the following options:

=========== ======================================================================================================
Option      Description
=========== ======================================================================================================
association the type of associations (See :class:`passerine.db.mapper.AssociationType`.)
cascading   the list of allowed cascading operations (See :doc:`06-cascading` :class:`passerine.db.mapper.CascadingType`.)
inverted_by the name of property used where **enable the reverse mapping if defined**
mapped_by   the name of property to be map
read_only   the flag to disable property setters (only usable with :class:`passerine.db.common.ProxyObject`.)
target      the full name of class or the actual class
=========== ======================================================================================================

How to make a join query
========================

From the customer-reward example, if we want to find all rewards of a particular
user, the query will be::

    query = reward_repository.new_criteria('r')
    query.join('r.customer', 'c')
    query.expect('c.name = "Bob"')

    rewards = reward_repository.find(query)

All features for querying is usable with joined entities.


text:
/*
*  This makes automatically fading alerts using pixy dust and magic
*/
$(document).ready(function(){
  $(".alert-success, .alert-error, .alert-info").alert();

  $(".alert-success").fadeOut(4000);

  $(".alert-success").mouseenter(function(){
    $(this).stop().fadeOut(0).fadeIn(0);
  });

  $(".alert-success").mouseleave(function(){
    $(this).fadeOut(2500);
  });
});


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

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateMembersResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The list of Amazon Web Services accounts that were not processed. For each account, the list includes the account
     * ID and the email address.
     *

     */
    private java.util.List<Result> unprocessedAccounts;

    /**
     *

     * The list of Amazon Web Services accounts that were not processed. For each account, the list includes the account
     * ID and the email address.
     *

     *
     * @return The list of Amazon Web Services accounts that were not processed. For each account, the list includes the
     *         account ID and the email address.
     */

    public java.util.List<Result> getUnprocessedAccounts() {
        return unprocessedAccounts;
    }

    /**
     *

     * The list of Amazon Web Services accounts that were not processed. For each account, the list includes the account
     * ID and the email address.
     *

     *
     * @param unprocessedAccounts
     *        The list of Amazon Web Services accounts that were not processed. For each account, the list includes the
     *        account ID and the email address.
     */

    public void setUnprocessedAccounts(java.util.Collection<Result> unprocessedAccounts) {
        if (unprocessedAccounts == null) {
            this.unprocessedAccounts = null;
            return;
        }

        this.unprocessedAccounts = new java.util.ArrayList<Result>(unprocessedAccounts);
    }

    /**
     *

     * The list of Amazon Web Services accounts that were not processed. For each account, the list includes the account
     * ID and the email address.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setUnprocessedAccounts(java.util.Collection)} or {@link #withUnprocessedAccounts(java.util.Collection)}
     * if you want to override the existing values.
     *

     *
     * @param unprocessedAccounts
     *        The list of Amazon Web Services accounts that were not processed. For each account, the list includes the
     *        account ID and the email address.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateMembersResult withUnprocessedAccounts(Result... unprocessedAccounts) {
        if (this.unprocessedAccounts == null) {
            setUnprocessedAccounts(new java.util.ArrayList<Result>(unprocessedAccounts.length));
        }
        for (Result ele : unprocessedAccounts) {
            this.unprocessedAccounts.add(ele);
        }
        return this;
    }

    /**
     *

     * The list of Amazon Web Services accounts that were not processed. For each account, the list includes the account
     * ID and the email address.
     *

     *
     * @param unprocessedAccounts
     *        The list of Amazon Web Services accounts that were not processed. For each account, the list includes the
     *        account ID and the email address.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateMembersResult withUnprocessedAccounts(java.util.Collection<Result> unprocessedAccounts) {
        setUnprocessedAccounts(unprocessedAccounts);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getUnprocessedAccounts() != null)
            sb.append("UnprocessedAccounts: ").append(getUnprocessedAccounts());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CreateMembersResult == false)
            return false;
        CreateMembersResult other = (CreateMembersResult) obj;
        if (other.getUnprocessedAccounts() == null ^ this.getUnprocessedAccounts() == null)
            return false;
        if (other.getUnprocessedAccounts() != null && other.getUnprocessedAccounts().equals(this.getUnprocessedAccounts()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getUnprocessedAccounts() == null) ? 0 : getUnprocessedAccounts().hashCode());
        return hashCode;
    }

    @Override
    public CreateMembersResult clone() {
        try {
            return (CreateMembersResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
from peewee import *
from sandstone.lib.db import sandstone_db

class BaseModel(Model):
    class Meta:
        database = sandstone_db


text:
namespace mojo {
namespace shell {

TestChildProcess::TestChildProcess() {
}

TestChildProcess::~TestChildProcess() {
}

void TestChildProcess::Main() {
  VLOG(2) << "TestChildProcess::Main()";

  CHECK(!base::MessageLoop::current());
}

}  // namespace shell
}  // namespace mojo


text:
<?php declare(strict_types = 1);

namespace Smalldb\StateMachine\Definition\AnnotationReader;

use Smalldb\StateMachine\Definition\Builder\StateMachineDefinitionBuilder;

interface ApplyToStateMachineBuilderInterface
{
	public function applyToBuilder(StateMachineDefinitionBuilder $builder): void;

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
TelParsedResult
</TITLE>

<META NAME="date" CONTENT="2012-02-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.zxing.client.result

Class TelParsedResult

java.lang.Object
  com.google.zxing.client.result.ParsedResult
      com.google.zxing.client.result.TelParsedResult

public final class TelParsedResult
extends ParsedResult

Author:

Sean Owen

Constructor Summary

TelParsedResult(java.lang.String number,
                java.lang.String telURI,
                java.lang.String title)

Method Summary

 java.lang.String
getDisplayResult()

 java.lang.String
getNumber()

 java.lang.String
getTelURI()

 java.lang.String
getTitle()

Methods inherited from class com.google.zxing.client.result.ParsedResult

getType, maybeAppend, maybeAppend, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

TelParsedResult

public TelParsedResult(java.lang.String number,
                       java.lang.String telURI,
                       java.lang.String title)

Method Detail

getNumber

public java.lang.String getNumber()

getTelURI

public java.lang.String getTelURI()

getTitle

public java.lang.String getTitle()

getDisplayResult

public java.lang.String getDisplayResult()

Specified by:
getDisplayResult in class ParsedResult

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<!--
    @license
    Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
    This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
    The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
    The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
    Code distributed by Google as part of the polymer project is also
    subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<x-meta id="paper-radio-group" label="Radio Group" isContainer group="Paper">
    <template>
        <paper-radio-group selected="Small" valueattr="label">
            <paper-radio-button label="Small"></paper-radio-button>
            <paper-radio-button label="Medium"></paper-radio-button>
            <paper-radio-button label="Large"></paper-radio-button>
        </paper-radio-group>
    </template>
    <template id="imports">
        <link rel="import" href="paper-radio-group.html">
        <link rel="import" href="../paper-radio-button/paper-radio-button.html">
    </template>
</x-meta>


text:
package leap.lang.meta;

import leap.lang.Named;
import leap.lang.Titled;

public interface MNamed extends MObject,Named,Titled {

}


text:
class LearnError < StandardError
  attr_accessor :filepath, :valid_yaml, :valid_license,
  :present_learn, :present_license, :present_readme, :yaml_error,
  :readme_error, :license_error, :valid_readme, :correct_yaml_content,
  :valid_contributing, :present_contributing, :contributing_error

  ESCAPES = { :green  => "\033[32m",
              :yellow => "\033[33m",
              :red    => "\033[31m",
              :reset  => "\033[0m" }

  def initialize
    @yaml_error = {present_dotlearn: false, valid_yaml: false, valid_whitespace: false, attributes: false}
    @readme_error = {present_readme: false, valid_readme: false}
    @license_error = {present_license: false, valid_license: false}
    @contributing_error = {present_contributing: false, valid_contributing: false}

    @correct_yaml_content = {message: ".learn file must have 'languages' key", color: :red}

    @valid_yaml = {message: "invalid yaml", color: :red}
    @valid_license = {message: "invalid or missing license content", color: :yellow}
    @valid_readme = {message: [], color: :red}
    @valid_contributing = {message: "invalid or missing contributing content", color: :yellow}

    @present_learn = {message: "missing .learn file", color: :red}
    @present_license = {message: "missing LICENSE.md", color: :red}
    @present_readme = {message: "missing README.md", color: :yellow}
    @present_contributing = {message: "missing CONTRIBUTING.md", color: :yellow}

  end

  def emit(opts={})
    color   = opts[:color]
    message = opts[:message]
    print ESCAPES[color]
    print message
    print ESCAPES[:reset]
    print "\n"
  end

  def total_errors
    {
      dot_learn: yaml_error,
      license: license_error,
      readme: readme_error,
      contributing: contributing_error
    }

  end

  def result_message
    [present_learn, valid_yaml, correct_yaml_content, present_license, valid_license, present_readme, valid_readme, valid_contributing, present_contributing]
  end

  def result_output
    result_message.each do |result|
      if result[:message].is_a?(Array)
        result[:message].each do |result_message|
          emit({message: result_message, color: result[:color]})
        end
      else
        emit(result)
      end
    end
  end

end


text:
/*
** DAV repository-independent lock functions
*/

#include "apr.h"
#include "apr_strings.h"

#include "mod_dav.h"
#include "http_log.h"
#include "http_config.h"
#include "http_protocol.h"
#include "http_core.h"

APLOG_USE_MODULE(dav);

/* ---------------------------------------------------------------
**
** Property-related lock functions
**
*/

/*
** dav_lock_get_activelock:  Returns a <lockdiscovery> containing
**    an activelock element for every item in the lock_discovery tree
*/
DAV_DECLARE(const char *) dav_lock_get_activelock(request_rec *r,
                                                  dav_lock *lock,
                                                  dav_buffer *pbuf)
{
    dav_lock *lock_scan;
    const dav_hooks_locks *hooks = DAV_GET_HOOKS_LOCKS(r);
    int count = 0;
    dav_buffer work_buf = { 0 };
    apr_pool_t *p = r->pool;

    /* If no locks or no lock provider, there are no locks */
    if (lock == NULL || hooks == NULL) {
        /*
        ** Since resourcediscovery is defined with (activelock)*,
        ** <D:activelock/> shouldn't be necessary for an empty lock.
        */
        return "";
    }

    /*
    ** Note: it could be interesting to sum the lengths of the owners
    **       and locktokens during this loop. However, the buffer
    **       mechanism provides some rough padding so that we don't
    **       really need to have an exact size. Further, constructing
    **       locktoken strings could be relatively expensive.
    */
    for (lock_scan = lock; lock_scan != NULL; lock_scan = lock_scan->next)
        count++;

    /* if a buffer was not provided, then use an internal buffer */
    if (pbuf == NULL)
        pbuf = &work_buf;

    /* reset the length before we start appending stuff */
    pbuf->cur_len = 0;

    /* prep the buffer with a "good" size */
    dav_check_bufsize(p, pbuf, count * 300);

    for (; lock != NULL; lock = lock->next) {
        char tmp[100];

#if DAV_DEBUG
        if (lock->rectype == DAV_LOCKREC_INDIRECT_PARTIAL) {
            /* ### crap. design error */
            dav_buffer_append(p, pbuf,
                              "DESIGN ERROR: attempted to product an "
                              "activelock element from a partial, indirect "
                              "lock record. Creating an XML parsing error "
                              "to ease detection of this situation: <");
        }
#endif

        dav_buffer_append(p, pbuf, "<D:activelock>" DEBUG_CR "<D:locktype>");
        switch (lock->type) {
        case DAV_LOCKTYPE_WRITE:
            dav_buffer_append(p, pbuf, "<D:write/>");
            break;
        default:
            /* ### internal error. log something? */
            break;
        }
        dav_buffer_append(p, pbuf, "</D:locktype>" DEBUG_CR "<D:lockscope>");
        switch (lock->scope) {
        case DAV_LOCKSCOPE_EXCLUSIVE:
            dav_buffer_append(p, pbuf, "<D:exclusive/>");
            break;
        case DAV_LOCKSCOPE_SHARED:
            dav_buffer_append(p, pbuf, "<D:shared/>");
            break;
        default:
            /* ### internal error. log something? */
            break;
        }
        dav_buffer_append(p, pbuf, "</D:lockscope>" DEBUG_CR);
        apr_snprintf(tmp, sizeof(tmp), "<D:depth>%s</D:depth>" DEBUG_CR,
                     lock->depth == DAV_INFINITY ? "infinity" : "0");
        dav_buffer_append(p, pbuf, tmp);

        if (lock->owner) {
            /*
            ** This contains a complete, self-contained <DAV:owner> element,
            ** with namespace declarations and xml:lang handling. Just drop
            ** it in.
            */
            dav_buffer_append(p, pbuf, lock->owner);
        }

        dav_buffer_append(p, pbuf, "<D:timeout>");
        if (lock->timeout == DAV_TIMEOUT_INFINITE) {
            dav_buffer_append(p, pbuf, "Infinite");
        }
        else {
            time_t now = time(NULL);

            /*
            ** Check if the timeout is not, for any reason, already elapsed.
            ** (e.g., because of a large collection, or disk under heavy load...)
             */
            if (now >= lock->timeout) {
                dav_buffer_append(p, pbuf, "Second-0");
            }
            else {
                apr_snprintf(tmp, sizeof(tmp), "Second-%lu", (long unsigned int)(lock->timeout - now));
                dav_buffer_append(p, pbuf, tmp);
            }
        }

        dav_buffer_append(p, pbuf,
                          "</D:timeout>" DEBUG_CR
                          "<D:locktoken>" DEBUG_CR
                          "<D:href>");
        dav_buffer_append(p, pbuf,
                          (*hooks->format_locktoken)(p, lock->locktoken));
        dav_buffer_append(p, pbuf,
                          "</D:href>" DEBUG_CR
                          "</D:locktoken>" DEBUG_CR
                          "</D:activelock>" DEBUG_CR);
    }

    return pbuf->buf;
}

/*
** dav_lock_parse_lockinfo:  Validates the given xml_doc to contain a
**    lockinfo XML element, then populates a dav_lock structure
**    with its contents.
*/
DAV_DECLARE(dav_error *) dav_lock_parse_lockinfo(request_rec *r,
                                                 const dav_resource *resource,
                                                 dav_lockdb *lockdb,
                                                 const apr_xml_doc *doc,
                                                 dav_lock **lock_request)
{
    apr_pool_t *p = r->pool;
    dav_error *err;
    apr_xml_elem *child;
    dav_lock *lock;

    if (!dav_validate_root(doc, "lockinfo")) {
        return dav_new_error(p, HTTP_BAD_REQUEST, 0, 0,
                             "The request body contains an unexpected "
                             "XML root element.");
    }

    if ((err = (*lockdb->hooks->create_lock)(lockdb, resource,
                                             &lock)) != NULL) {
        return dav_push_error(p, err->status, 0,
                              "Could not parse the lockinfo due to an "
                              "internal problem creating a lock structure.",
                              err);
    }

    lock->depth = dav_get_depth(r, DAV_INFINITY);
    if (lock->depth == -1) {
        return dav_new_error(p, HTTP_BAD_REQUEST, 0, 0,
                             "An invalid Depth header was specified.");
    }
    lock->timeout = dav_get_timeout(r);

    /* Parse elements in the XML body */
    for (child = doc->root->first_child; child; child = child->next) {
        if (strcmp(child->name, "locktype") == 0
            && child->first_child
            && lock->type == DAV_LOCKTYPE_UNKNOWN) {
            if (strcmp(child->first_child->name, "write") == 0) {
                lock->type = DAV_LOCKTYPE_WRITE;
                continue;
            }
        }
        if (strcmp(child->name, "lockscope") == 0
            && child->first_child
            && lock->scope == DAV_LOCKSCOPE_UNKNOWN) {
            if (strcmp(child->first_child->name, "exclusive") == 0)
                lock->scope = DAV_LOCKSCOPE_EXCLUSIVE;
            else if (strcmp(child->first_child->name, "shared") == 0)
                lock->scope = DAV_LOCKSCOPE_SHARED;
            if (lock->scope != DAV_LOCKSCOPE_UNKNOWN)
                continue;
        }

        if (strcmp(child->name, "owner") == 0 && lock->owner == NULL) {
            const char *text;

            /* quote all the values in the <DAV:owner> element */
            apr_xml_quote_elem(p, child);

            /*
            ** Store a full <DAV:owner> element with namespace definitions
            ** and an xml:lang definition, if applicable.
            */
            apr_xml_to_text(p, child, APR_XML_X2T_FULL_NS_LANG, doc->namespaces,
                            NULL, &text, NULL);
            lock->owner = text;

            continue;
        }

        return dav_new_error(p, HTTP_PRECONDITION_FAILED, 0, 0,
                             apr_psprintf(p,
                                         "The server cannot satisfy the "
                                         "LOCK request due to an unknown XML "
                                         "element (\"%s\") within the "
                                         "DAV:lockinfo element.",
                                         child->name));
    }

    *lock_request = lock;
    return NULL;
}

/* ---------------------------------------------------------------
**
** General lock functions
**
*/

/* dav_lock_walker:  Walker callback function to record indirect locks */
static dav_error * dav_lock_walker(dav_walk_resource *wres, int calltype)
{
    dav_walker_ctx *ctx = wres->walk_ctx;
    dav_error *err;

    /* We don't want to set indirects on the target */
    if ((*wres->resource->hooks->is_same_resource)(wres->resource,
                                                   ctx->w.root))
        return NULL;

    if ((err = (*ctx->w.lockdb->hooks->append_locks)(ctx->w.lockdb,
                                                     wres->resource, 1,
                                                     ctx->lock)) != NULL) {
        if (ap_is_HTTP_SERVER_ERROR(err->status)) {
            /* ### add a higher-level description? */
            return err;
        }

        /* add to the multistatus response */
        dav_add_response(wres, err->status, NULL);

        /*
        ** ### actually, this is probably wrong: we want to fail the whole
        ** ### LOCK process if something goes bad. maybe the caller should
        ** ### do a dav_unlock() (e.g. a rollback) if any errors occurred.
        */
    }

    return NULL;
}

/*
** dav_add_lock:  Add a direct lock for resource, and indirect locks for
**    all children, bounded by depth.
**    ### assume request only contains one lock
*/
DAV_DECLARE(dav_error *) dav_add_lock(request_rec *r,
                                      const dav_resource *resource,
                                      dav_lockdb *lockdb, dav_lock *lock,
                                      dav_response **response)
{
    dav_error *err;
    int depth = lock->depth;

    *response = NULL;

    /* Requested lock can be:
     *   Depth: 0   for null resource, existing resource, or existing collection
     *   Depth: Inf for existing collection
     */

    /*
    ** 2518 9.2 says to ignore depth if target is not a collection (it has
    **   no internal children); pretend the client gave the correct depth.
    */
    if (!resource->collection) {
        depth = 0;
    }

    /* In all cases, first add direct entry in lockdb */

    /*
    ** Append the new (direct) lock to the resource's existing locks.
    **
    ** Note: this also handles locknull resources
    */
    if ((err = (*lockdb->hooks->append_locks)(lockdb, resource, 0,
                                              lock)) != NULL) {
        /* ### maybe add a higher-level description */
        return err;
    }

    if (depth > 0) {
        /* Walk existing collection and set indirect locks */
        dav_walker_ctx ctx = { { 0 } };
        dav_response *multi_status;

        ctx.w.walk_type = DAV_WALKTYPE_NORMAL | DAV_WALKTYPE_AUTH;
        ctx.w.func = dav_lock_walker;
        ctx.w.walk_ctx = &ctx;
        ctx.w.pool = r->pool;
        ctx.w.root = resource;
        ctx.w.lockdb = lockdb;

        ctx.r = r;
        ctx.lock = lock;

        err = (*resource->hooks->walk)(&ctx.w, DAV_INFINITY, &multi_status);
        if (err != NULL) {
            /* implies a 5xx status code occurred. screw the multistatus */
            return err;
        }

        if (multi_status != NULL) {
            /* manufacture a 207 error for the multistatus response */
            *response = multi_status;
            return dav_new_error(r->pool, HTTP_MULTI_STATUS, 0, 0,
                                 "Error(s) occurred on resources during the "
                                 "addition of a depth lock.");
        }
    }

    return NULL;
}

/*
** dav_lock_query:  Opens the lock database. Returns a linked list of
**    dav_lock structures for all direct locks on path.
*/
DAV_DECLARE(dav_error*) dav_lock_query(dav_lockdb *lockdb,
                                       const dav_resource *resource,
                                       dav_lock **locks)
{
    /* If no lock database, return empty result */
    if (lockdb == NULL) {
        *locks = NULL;
        return NULL;
    }

    /* ### insert a higher-level description? */
    return (*lockdb->hooks->get_locks)(lockdb, resource,
                                       DAV_GETLOCKS_RESOLVED,
                                       locks);
}

/* dav_unlock_walker:  Walker callback function to remove indirect locks */
static dav_error * dav_unlock_walker(dav_walk_resource *wres, int calltype)
{
    dav_walker_ctx *ctx = wres->walk_ctx;
    dav_error *err;

    /* Before removing the lock, do any auto-checkin required */
    if (wres->resource->working) {
        /* ### get rid of this typecast */
        if ((err = dav_auto_checkin(ctx->r, (dav_resource *) wres->resource,
                                    0 /*undo*/, 1 /*unlock*/, NULL))
            != NULL) {
            return err;
        }
    }

    if ((err = (*ctx->w.lockdb->hooks->remove_lock)(ctx->w.lockdb,
                                                    wres->resource,
                                                    ctx->locktoken)) != NULL) {
        /* ### should we stop or return a multistatus? looks like STOP */
        /* ### add a higher-level description? */
        return err;
    }

    return NULL;
}

/*
** dav_get_direct_resource:
**
** Find a lock on the specified resource, then return the resource the
** lock was applied to (in other words, given a (possibly) indirect lock,
** return the direct lock's corresponding resource).
**
** If the lock is an indirect lock, this usually means traversing up the
** namespace [repository] hierarchy. Note that some lock providers may be
** able to return this information with a traversal.
*/
static dav_error * dav_get_direct_resource(apr_pool_t *p,
                                           dav_lockdb *lockdb,
                                           const dav_locktoken *locktoken,
                                           const dav_resource *resource,
                                           const dav_resource **direct_resource)
{
    if (lockdb->hooks->lookup_resource != NULL) {
        return (*lockdb->hooks->lookup_resource)(lockdb, locktoken,
                                                 resource, direct_resource);
    }

    *direct_resource = NULL;

    /* Find the top of this lock-
     * If r->filename's direct   locks include locktoken, use r->filename.
     * If r->filename's indirect locks include locktoken, retry r->filename/..
     * Else fail.
     */
    while (resource != NULL) {
        dav_error *err;
        dav_lock *lock;
        dav_resource *parent;

        /*
        ** Find the lock specified by <locktoken> on <resource>. If it is
        ** an indirect lock, then partial results are okay. We're just
        ** trying to find the thing and know whether it is a direct or
        ** an indirect lock.
        */
        if ((err = (*lockdb->hooks->find_lock)(lockdb, resource, locktoken,
                                               1, &lock)) != NULL) {
            /* ### add a higher-level desc? */
            return err;
        }

        /* not found! that's an error. */
        if (lock == NULL) {
            return dav_new_error(p, HTTP_BAD_REQUEST, 0, 0,
                                 "The specified locktoken does not correspond "
                                 "to an existing lock on this resource.");
        }

        if (lock->rectype == DAV_LOCKREC_DIRECT) {
            /* we found the direct lock. return this resource. */

            *direct_resource = resource;
            return NULL;
        }

        /* the lock was indirect. move up a level in the URL namespace */
        if ((err = (*resource->hooks->get_parent_resource)(resource,
                                                           &parent)) != NULL) {
            /* ### add a higher-level desc? */
            return err;
        }
        resource = parent;
    }

    return dav_new_error(p, HTTP_INTERNAL_SERVER_ERROR, 0, 0,
                         "The lock database is corrupt. A direct lock could "
                         "not be found for the corresponding indirect lock "
                         "on this resource.");
}

/*
** dav_unlock:  Removes all direct and indirect locks for r->filename,
**    with given locktoken.  If locktoken == null_locktoken, all locks
**    are removed.  If r->filename represents an indirect lock,
**    we must unlock the appropriate direct lock.
**    Returns OK or appropriate HTTP_* response and logs any errors.
**
** ### We've already crawled the tree to ensure everything was locked
**     by us; there should be no need to incorporate a rollback.
*/
DAV_DECLARE(int) dav_unlock(request_rec *r, const dav_resource *resource,
                            const dav_locktoken *locktoken)
{
    int result;
    dav_lockdb *lockdb;
    const dav_resource *lock_resource = resource;
    const dav_hooks_locks *hooks = DAV_GET_HOOKS_LOCKS(r);
    const dav_hooks_repository *repos_hooks = resource->hooks;
    dav_walker_ctx ctx = { { 0 } };
    dav_response *multi_status;
    dav_error *err;

    /* If no locks provider, then there is nothing to unlock. */
    if (hooks == NULL) {
        return OK;
    }

    /* 2518 requires the entire lock to be removed if resource/locktoken
     * point to an indirect lock.  We need resource of the _direct_
     * lock in order to walk down the tree and remove the locks.  So,
     * If locktoken != null_locktoken,
     *    Walk up the resource hierarchy until we see a direct lock.
     *    Or, we could get the direct lock's db/key, pick out the URL
     *    and do a subrequest.  I think walking up is faster and will work
     *    all the time.
     * Else
     *    Just start removing all locks at and below resource.
     */

    if ((err = (*hooks->open_lockdb)(r, 0, 1, &lockdb)) != NULL) {
        /* ### return err! maybe add a higher-level desc */
        /* ### map result to something nice; log an error */
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    if (locktoken != NULL
        && (err = dav_get_direct_resource(r->pool, lockdb,
                                          locktoken, resource,
                                          &lock_resource)) != NULL) {
        /* ### add a higher-level desc? */
        /* ### should return err! */
        return err->status;
    }

    /* At this point, lock_resource/locktoken refers to a direct lock (key), ie
     * the root of a depth > 0 lock, or locktoken is null.
     */
    ctx.w.walk_type = DAV_WALKTYPE_NORMAL | DAV_WALKTYPE_LOCKNULL;
    ctx.w.func = dav_unlock_walker;
    ctx.w.walk_ctx = &ctx;
    ctx.w.pool = r->pool;
    ctx.w.root = lock_resource;
    ctx.w.lockdb = lockdb;

    ctx.r = r;
    ctx.locktoken = locktoken;

    err = (*repos_hooks->walk)(&ctx.w, DAV_INFINITY, &multi_status);

    /* ### fix this! */
    /* ### do something with multi_status */
    result = err == NULL ? OK : err->status;

    (*hooks->close_lockdb)(lockdb);

    return result;
}

/* dav_inherit_walker:  Walker callback function to inherit locks */
static dav_error * dav_inherit_walker(dav_walk_resource *wres, int calltype)
{
    dav_walker_ctx *ctx = wres->walk_ctx;

    if (ctx->skip_root
        && (*wres->resource->hooks->is_same_resource)(wres->resource,
                                                      ctx->w.root)) {
        return NULL;
    }

    /* ### maybe add a higher-level desc */
    return (*ctx->w.lockdb->hooks->append_locks)(ctx->w.lockdb,
                                                 wres->resource, 1,
                                                 ctx->lock);
}

/*
** dav_inherit_locks:  When a resource or collection is added to a collection,
**    locks on the collection should be inherited to the resource/collection.
**    (MOVE, MKCOL, etc) Here we propagate any direct or indirect locks from
**    parent of resource to resource and below.
*/
static dav_error * dav_inherit_locks(request_rec *r, dav_lockdb *lockdb,
                                     const dav_resource *resource,
                                     int use_parent)
{
    dav_error *err;
    const dav_resource *which_resource;
    dav_lock *locks;
    dav_lock *scan;
    dav_lock *prev;
    dav_walker_ctx ctx = { { 0 } };
    const dav_hooks_repository *repos_hooks = resource->hooks;
    dav_response *multi_status;

    if (use_parent) {
        dav_resource *parent;
        if ((err = (*repos_hooks->get_parent_resource)(resource,
                                                       &parent)) != NULL) {
            /* ### add a higher-level desc? */
            return err;
        }
        if (parent == NULL) {
            /* ### map result to something nice; log an error */
            return dav_new_error(r->pool, HTTP_INTERNAL_SERVER_ERROR, 0, 0,
                                 "Could not fetch parent resource. Unable to "
                                 "inherit locks from the parent and apply "
                                 "them to this resource.");
        }
        which_resource = parent;
    }
    else {
        which_resource = resource;
    }

    if ((err = (*lockdb->hooks->get_locks)(lockdb, which_resource,
                                           DAV_GETLOCKS_PARTIAL,
                                           &locks)) != NULL) {
        /* ### maybe add a higher-level desc */
        return err;
    }

    if (locks == NULL) {
        /* No locks to propagate, just return */
        return NULL;
    }

    /*
    ** (1) Copy all indirect locks from our parent;
    ** (2) Create indirect locks for the depth infinity, direct locks
    **     in our parent.
    **
    ** The append_locks call in the walker callback will do the indirect
    ** conversion, but we need to remove any direct locks that are NOT
    ** depth "infinity".
    */
    for (scan = locks, prev = NULL;
         scan != NULL;
         prev = scan, scan = scan->next) {

        if (scan->rectype == DAV_LOCKREC_DIRECT
            && scan->depth != DAV_INFINITY) {

            if (prev == NULL)
                locks = scan->next;
            else
                prev->next = scan->next;
        }
    }

    /* <locks> has all our new locks.  Walk down and propagate them. */

    ctx.w.walk_type = DAV_WALKTYPE_NORMAL | DAV_WALKTYPE_LOCKNULL;
    ctx.w.func = dav_inherit_walker;
    ctx.w.walk_ctx = &ctx;
    ctx.w.pool = r->pool;
    ctx.w.root = resource;
    ctx.w.lockdb = lockdb;

    ctx.r = r;
    ctx.lock = locks;
    ctx.skip_root = !use_parent;

    /* ### do something with multi_status */
    return (*repos_hooks->walk)(&ctx.w, DAV_INFINITY, &multi_status);
}

/* ---------------------------------------------------------------
**
** Functions dealing with lock-null resources
**
*/

/*
** dav_get_resource_state:  Returns the state of the resource
**    r->filename:  DAV_RESOURCE_NULL, DAV_RESOURCE_LOCK_NULL,
**    or DAV_RESOURCE_EXIST.
**
**    Returns DAV_RESOURCE_ERROR if an error occurs.
*/
DAV_DECLARE(int) dav_get_resource_state(request_rec *r,
                                        const dav_resource *resource)
{
    const dav_hooks_locks *hooks = DAV_GET_HOOKS_LOCKS(r);

    if (resource->exists)
        return DAV_RESOURCE_EXISTS;

    if (hooks != NULL) {
        dav_error *err;
        dav_lockdb *lockdb;
        int locks_present;

        /*
        ** A locknull resource has the form:
        **
        **   known-dir "/" locknull-file
        **
        ** It would be nice to look into <resource> to verify this form,
        ** but it does not have enough information for us. Instead, we
        ** can look at the path_info. If the form does not match, then
        ** there is no way we could have a locknull resource -- it must
        ** be a plain, null resource.
        **
        ** Apache sets r->filename to known-dir/unknown-file and r->path_info
        ** to "" for the "proper" case. If anything is in path_info, then
        ** it can't be a locknull resource.
        **
        ** ### I bet this path_info hack doesn't work for repositories.
        ** ### Need input from repository implementors! What kind of
        ** ### restructure do we need? New provider APIs?
        */
        if (r->path_info != NULL && *r->path_info != '\0') {
            return DAV_RESOURCE_NULL;
        }

        if ((err = (*hooks->open_lockdb)(r, 1, 1, &lockdb)) == NULL) {
            /* note that we might see some expired locks... *shrug* */
            err = (*hooks->has_locks)(lockdb, resource, &locks_present);
            (*hooks->close_lockdb)(lockdb);
        }

        if (err != NULL) {
            /* ### don't log an error. return err. add higher-level desc. */

            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00623)
                          "Failed to query lock-null status for %s",
                          r->filename);

            return DAV_RESOURCE_ERROR;
        }

        if (locks_present)
            return DAV_RESOURCE_LOCK_NULL;
    }

    return DAV_RESOURCE_NULL;
}

DAV_DECLARE(dav_error *) dav_notify_created(request_rec *r,
                                            dav_lockdb *lockdb,
                                            const dav_resource *resource,
                                            int resource_state,
                                            int depth)
{
    dav_error *err;

    if (resource_state == DAV_RESOURCE_LOCK_NULL) {

        /*
        ** The resource is no longer a locknull resource. This will remove
        ** the special marker.
        **
        ** Note that a locknull resource has already inherited all of the
        ** locks from the parent. We do not need to call dav_inherit_locks.
        **
        ** NOTE: some lock providers record locks for locknull resources using
        **       a different key than for regular resources. this will shift
        **       the lock information between the two key types.
        */
        (void)(*lockdb->hooks->remove_locknull_state)(lockdb, resource);

        /*
        ** There are resources under this one, which are new. We must
        ** propagate the locks down to the new resources.
        */
        if (depth > 0 &&
            (err = dav_inherit_locks(r, lockdb, resource, 0)) != NULL) {
            /* ### add a higher level desc? */
            return err;
        }
    }
    else if (resource_state == DAV_RESOURCE_NULL) {

        /* ### should pass depth to dav_inherit_locks so that it can
        ** ### optimize for the depth==0 case.
        */

        /* this resource should inherit locks from its parent */
        if ((err = dav_inherit_locks(r, lockdb, resource, 1)) != NULL) {

            err = dav_push_error(r->pool, err->status, 0,
                                 "The resource was created successfully, but "
                                 "there was a problem inheriting locks from "
                                 "the parent resource.",
                                 err);
            return err;
        }
    }
    /* else the resource already exists and its locks are correct. */

    return NULL;
}


text:
<?php
/**
 * @author h.woltersdorf
 */

namespace Fortuneglobe\IceHawk\Tests\Unit\Builders;

use Fortuneglobe\IceHawk\Builders\DomainRequestHandlerBuilder;
use Fortuneglobe\IceHawk\Constants\Http;
use Fortuneglobe\IceHawk\Interfaces\ServesUriComponents;
use Fortuneglobe\IceHawk\RequestInfo;
use Fortuneglobe\IceHawk\Requests\GetRequest;
use Fortuneglobe\IceHawk\Requests\PostRequest;
use Fortuneglobe\IceHawk\Tests\Unit\Fixtures\Domain\Read\ValidReadTestRequestHandler;
use Fortuneglobe\IceHawk\Tests\Unit\Fixtures\Domain\Write\ValidWriteTestRequestHandler;

class DomainRequestHandlerBuilderTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * @expectedException \Fortuneglobe\IceHawk\Exceptions\BuildingDomainRequestHandlerFailed
	 */
	public function testBuildingThrowsExceptionIfHandlerDoesNotExist()
	{
		$uriComponents               = $this->getUriComponentsMock( 'not', 'existing', [ ] );
		$domainRequestHandlerBuilder = new DomainRequestHandlerBuilder(
			'Fortuneglobe\\IceHawk\\Tests\\Unit\\Fixtures',
			Http::METHOD_GET,
			$uriComponents
		);

		$request = new GetRequest( RequestInfo::fromEnv(), [ ] );

		$domainRequestHandlerBuilder->buildDomainRequestHandler( $request );
	}

	/**
	 * @param string $domain
	 * @param string $demand
	 * @param array  $params
	 *
	 * @return \PHPUnit_Framework_MockObject_MockObject|ServesUriComponents
	 */
	private function getUriComponentsMock( $domain, $demand, array $params )
	{
		$mock = $this->getMockBuilder( ServesUriComponents::class )->setMethods(
			[ 'getDomain', 'getDemand', 'getParams' ]
		)->getMock();

		$mock->expects( $this->once() )->method( 'getDomain' )->willReturn( $domain );
		$mock->expects( $this->once() )->method( 'getDemand' )->willReturn( $demand );
		$mock->expects( $this->never() )->method( 'getParams' )->willReturn( $params );

		return $mock;
	}

	/**
	 * @expectedException \Fortuneglobe\IceHawk\Exceptions\MissingInterfaceImplementationForHandlingDomainRequests
	 */
	public function testBuildingThrowsExceptionIfHandlerExistsButInterfaceImplementationIsMissing()
	{
		$uriComponents               = $this->getUriComponentsMock( 'domain', 'invalid-test', [ ] );
		$domainRequestHandlerBuilder = new DomainRequestHandlerBuilder(
			'Fortuneglobe\\IceHawk\\Tests\\Unit\\Fixtures',
			Http::METHOD_GET,
			$uriComponents
		);

		$request = new GetRequest( RequestInfo::fromEnv(), [ ] );

		$domainRequestHandlerBuilder->buildDomainRequestHandler( $request );
	}

	public function testBuildingSucceedsIfReadSideHandlerExistsAndImplementsInterface()
	{
		$uriComponents               = $this->getUriComponentsMock( 'domain', 'valid-read-test', [ ] );
		$domainRequestHandlerBuilder = new DomainRequestHandlerBuilder(
			'Fortuneglobe\\IceHawk\\Tests\\Unit\\Fixtures',
			Http::METHOD_GET,
			$uriComponents
		);

		$request = new GetRequest( RequestInfo::fromEnv(), [ ] );

		$handler = $domainRequestHandlerBuilder->buildDomainRequestHandler( $request );

		$this->assertInstanceOf( ValidReadTestRequestHandler::class, $handler );
	}

	public function testBuildingSucceedsIfWriteSideHandlerExistsAndImplementsInterface()
	{
		$uriComponents               = $this->getUriComponentsMock( 'domain', 'valid-write-test', [ ] );
		$domainRequestHandlerBuilder = new DomainRequestHandlerBuilder(
			'Fortuneglobe\\IceHawk\\Tests\\Unit\\Fixtures',
			Http::METHOD_POST,
			$uriComponents
		);

		$request = new PostRequest( RequestInfo::fromEnv(), [ ], [ ] );

		$handler = $domainRequestHandlerBuilder->buildDomainRequestHandler( $request );

		$this->assertInstanceOf( ValidWriteTestRequestHandler::class, $handler );
	}
}


text:
/*
 * File:   common.h
 * Author: Jared
 *
 * Created on 10 June 2014, 8:57 PM
 */

#ifndef COMMON_H
#define	COMMON_H

#include <stdint.h>

typedef unsigned char byte;
typedef unsigned int uint;

#ifndef	__cplusplus
typedef unsigned char bool;
#endif

#define true 1
#define false 0

#define _XKEYCHECK // TODO: Don't know why I had to define this, but it makes the program compile.
#include <GenericTypeDefs.h>

#endif	/* COMMON_H */


text:
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;

namespace vm.Aspects.Facilities.LogWriters.Etw
{
    /// <summary>
    /// ETW event source that takes Event Library's logging application block's log event entries.
    /// </summary>
    /// <seealso cref="EtwLogEntryBaseEventSource" />
    [EventSource(Name = "vm-Aspects-LogEntryEventSource")]
    public sealed partial class EtwLogEntryEventSource : EtwLogEntryBaseEventSource
    {
        /// <summary>
        /// The log singleton instance.
        /// </summary>
        public static EtwLogEntryEventSource Log { get; }

        static readonly IReadOnlyDictionary<TraceEventType, Action<int, int, string, string, string, string, string>> _writeLogEntry;
        static readonly IReadOnlyDictionary<TraceEventType, Action<string>> _writeMessage;
        static readonly IReadOnlyDictionary<TraceEventType, Action<string>> _dumpObject;
        static readonly IReadOnlyDictionary<TraceEventType, Action<int, string, string>> _trace;

        static readonly IReadOnlyDictionary<TraceEventType, EventLevel> _traceEventType2eventLevel =
            new ReadOnlyDictionary<TraceEventType, EventLevel>(
                new SortedDictionary<TraceEventType, EventLevel>
                {
                    [TraceEventType.Verbose]     = EventLevel.Verbose,
                    [TraceEventType.Warning]     = EventLevel.Warning,
                    [TraceEventType.Error]       = EventLevel.Error,
                    [TraceEventType.Critical]    = EventLevel.Critical,
                    [TraceEventType.Information] = EventLevel.Informational,
                    [TraceEventType.Start]       = EventLevel.Informational,
                    [TraceEventType.Suspend]     = EventLevel.Informational,
                    [TraceEventType.Resume]      = EventLevel.Informational,
                    [TraceEventType.Stop]        = EventLevel.Informational,
                    [TraceEventType.Transfer]    = EventLevel.Informational,
                });

        [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Log must be initialized before the other initializations take place.")]
        static EtwLogEntryEventSource()
        {
            // make sure Log is created before _writeXyz
            Log = new EtwLogEntryEventSource();

            _writeMessage = new ReadOnlyDictionary<TraceEventType, Action<string>>(
                new Dictionary<TraceEventType, Action<string>>
                {
                    [TraceEventType.Verbose]     = Log.VerboseMessage,
                    [TraceEventType.Warning]     = Log.WarningMessage,
                    [TraceEventType.Error]       = Log.ErrorMessage,
                    [TraceEventType.Critical]    = Log.CriticalMessage,
                    [TraceEventType.Information] = Log.InformationalMessage,
                    [TraceEventType.Start]       = Log.InformationalMessage,
                    [TraceEventType.Suspend]     = Log.InformationalMessage,
                    [TraceEventType.Resume]      = Log.InformationalMessage,
                    [TraceEventType.Stop]        = Log.InformationalMessage,
                    [TraceEventType.Transfer]    = Log.InformationalMessage,
                });

            _dumpObject = new ReadOnlyDictionary<TraceEventType, Action<string>>(
                new Dictionary<TraceEventType, Action<string>>
                {
                    [TraceEventType.Verbose]     = Log.VerboseDumpObject,
                    [TraceEventType.Warning]     = Log.WarningDumpObject,
                    [TraceEventType.Error]       = Log.ErrorDumpObject,
                    [TraceEventType.Critical]    = Log.CriticalDumpObject,
                    [TraceEventType.Information] = Log.InformationalDumpObject,
                    [TraceEventType.Start]       = Log.InformationalDumpObject,
                    [TraceEventType.Suspend]     = Log.InformationalDumpObject,
                    [TraceEventType.Resume]      = Log.InformationalDumpObject,
                    [TraceEventType.Stop]        = Log.InformationalDumpObject,
                    [TraceEventType.Transfer]    = Log.InformationalDumpObject,
                });

            _trace = new ReadOnlyDictionary<TraceEventType, Action<int, string, string>>(
                new Dictionary<TraceEventType, Action<int, string, string>>
                {
                    [TraceEventType.Verbose]     = Log.VerboseTrace,
                    [TraceEventType.Warning]     = Log.WarningTrace,
                    [TraceEventType.Error]       = Log.ErrorTrace,
                    [TraceEventType.Critical]    = Log.CriticalTrace,
                    [TraceEventType.Information] = Log.InformationalTrace,
                    [TraceEventType.Start]       = Log.InformationalTrace,
                    [TraceEventType.Suspend]     = Log.InformationalTrace,
                    [TraceEventType.Resume]      = Log.InformationalTrace,
                    [TraceEventType.Stop]        = Log.InformationalTrace,
                    [TraceEventType.Transfer]    = Log.InformationalTrace,
                });

            _writeLogEntry = new ReadOnlyDictionary<TraceEventType, Action<int, int, string, string, string, string, string>>(
                new Dictionary<TraceEventType, Action<int, int, string, string, string, string, string>>
                {
                    [TraceEventType.Verbose]     = Log.VerboseLogEntry,
                    [TraceEventType.Warning]     = Log.WarningLogEntry,
                    [TraceEventType.Error]       = Log.ErrorLogEntry,
                    [TraceEventType.Critical]    = Log.CriticalLogEntry,
                    [TraceEventType.Information] = Log.InformationalLogEntry,
                    [TraceEventType.Start]       = Log.InformationalLogEntry,
                    [TraceEventType.Suspend]     = Log.InformationalLogEntry,
                    [TraceEventType.Resume]      = Log.InformationalLogEntry,
                    [TraceEventType.Stop]        = Log.InformationalLogEntry,
                    [TraceEventType.Transfer]    = Log.InformationalLogEntry,
                });
        }

        bool IsEnabled(
            TraceEventType eventType,
            EventKeywords keyWords)
            => IsEnabled(_traceEventType2eventLevel[eventType], keyWords);

        /// <summary>
        /// Dispatches the message to the appropriate message event writer.
        /// </summary>
        /// <param name="eventType">Type of the event.</param>
        /// <param name="message">The message.</param>
        [NonEvent]
        public void WriteMessage(
            string message,
            TraceEventType eventType = TraceEventType.Information)
        {
            if (!IsEnabled(eventType, Keywords.ELLab | Keywords.Message))
                return;

            if (!_writeMessage.TryGetValue(eventType, out var writeMessage))
                writeMessage = Log.InformationalMessage;

            writeMessage(message);
        }

        /// <summary>
        /// Dispatches a dump of the object to the appropriate dumped object event writer.
        /// </summary>
        /// <param name="eventType">Type of the event.</param>
        /// <param name="data">The object.</param>
        [NonEvent]
        public void DumpObject(
            object data,
            TraceEventType eventType = TraceEventType.Verbose)
        {
            if (!IsEnabled(eventType, Keywords.ELLab | Keywords.Dump))
                return;

            var dataDump = data.DumpString();

            if (!_dumpObject.TryGetValue(eventType, out var dumpObject))
                dumpObject = Log.InformationalDumpObject;

            dumpObject(dataDump);
        }

        /// <summary>
        /// Dispatches the trace text to the appropriate trace event writer.
        /// </summary>
        /// <param name="id">The EL LAB identifier.</param>
        /// <param name="eventType">Type of the event.</param>
        /// <param name="source">The source.</param>
        /// <param name="text">The text.</param>
        [NonEvent]
        public void Trace(
            int id,
            string text,
            string source = null,
            TraceEventType eventType = TraceEventType.Verbose)
        {
            if (!IsEnabled(eventType, Keywords.ELLab | Keywords.Trace))
                return;

            if (!_trace.TryGetValue(eventType, out var trace))
                trace = Log.InformationalTrace;

            trace(id, source, text);
        }

        /// <summary>
        /// Dispatches the log entry to the appropriate log entry event writer.
        /// </summary>
        /// <param name="logEntry">The log entry.</param>
        [NonEvent]
        public void WriteLogEntry(
            LogEntry logEntry)
        {
            if (logEntry == null)
                throw new ArgumentNullException(nameof(logEntry));

            if (!IsEnabled(logEntry.Severity, Keywords.ELLab | Keywords.LogEntry))
                return;

            var severity = logEntry.Severity.ToString();
            var message = logEntry.Message;
            var messages = logEntry.ErrorMessages;
            var categories = DumpCategories(logEntry.Categories);
            var extendedProperties = DumpExtendedProperties(logEntry.ExtendedProperties);

            if (!_writeLogEntry.TryGetValue(logEntry.Severity, out var writeLogEntry))
                writeLogEntry = Log.InformationalLogEntry;

            writeLogEntry(
                    logEntry.EventId,
                    logEntry.Priority,
                    severity,
                    message,
                    messages,
                    categories,
                    extendedProperties);
        }

        static string DumpCategories(
            ICollection<string> categories)
        {
            if (categories == null  ||  !categories.Any())
                return string.Empty;

            return string.Join(", ", categories);
        }

        static string DumpExtendedProperties(
            IDictionary<string, object> extendedProperties)
        {
            if (extendedProperties == null  ||  !extendedProperties.Any())
                return null;

            using (var writer = new StringWriter())
            {
                foreach (var kv in extendedProperties)
                    writer.WriteLine("{0,-24} = {1}", kv.Key, kv.Value.DumpString(1));

                return writer.GetStringBuilder().ToString();
            }
        }

        // ======================================================
        // Events:
        // ======================================================

        #region Write LogEntry events to ETW
        /// <summary>
        /// Writes a verbose log entry event.
        /// </summary>
        /// <param name="EventId">The EL-LAB event identifier.</param>
        /// <param name="Priority">The EL-LAB event priority.</param>
        /// <param name="Severity">The EL-LAB event severity.</param>
        /// <param name="Message">The EL-LAB event message.</param>
        /// <param name="ErrorMessages">The EL-LAB event error messages.</param>
        /// <param name="Categories">The EL-LAB event categories.</param>
        /// <param name="Extended">The EL-LAB event extended properties.</param>
        [Event(VerboseLogEntryId, Level = EventLevel.Verbose, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.LogEntry, Message = "{5} {2}: {3}")]
        void VerboseLogEntry(
            int EventId,
            int Priority,
            string Severity,
            string Message,
            string ErrorMessages,
            string Categories,
            string Extended)
        {
            if (IsEnabled())
                WriteEvent(
                    VerboseLogEntryId,
                    EventId,
                    Priority,
                    Severity,
                    Message,
                    ErrorMessages,
                    Categories,
                    Extended);
        }

        /// <summary>
        /// Writes an informational log entry event.
        /// </summary>
        /// <param name="EventId">The EL-LAB event identifier.</param>
        /// <param name="Priority">The EL-LAB event priority.</param>
        /// <param name="Severity">The EL-LAB event severity.</param>
        /// <param name="Message">The EL-LAB event message.</param>
        /// <param name="ErrorMessages">The EL-LAB event error messages.</param>
        /// <param name="Categories">The EL-LAB event categories.</param>
        /// <param name="Extended">The EL-LAB event extended properties.</param>
        [Event(InformationalLogEntryId, Level = EventLevel.Informational, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.LogEntry, Message = "{5} {2}: {3}")]
        void InformationalLogEntry(
            int EventId,
            int Priority,
            string Severity,
            string Message,
            string ErrorMessages,
            string Categories,
            string Extended)
        {
            if (IsEnabled())
                WriteEvent(
                    InformationalLogEntryId,
                    EventId,
                    Priority,
                    Severity,
                    Message,
                    ErrorMessages,
                    Categories,
                    Extended);
        }

        /// <summary>
        /// Writes a warning log entry event.
        /// </summary>
        /// <param name="EventId">The EL-LAB event identifier.</param>
        /// <param name="Priority">The EL-LAB event priority.</param>
        /// <param name="Severity">The EL-LAB event severity.</param>
        /// <param name="Message">The EL-LAB event message.</param>
        /// <param name="ErrorMessages">The EL-LAB event error messages.</param>
        /// <param name="Categories">The EL-LAB event categories.</param>
        /// <param name="Extended">The EL-LAB event extended properties.</param>
        [Event(WarningLogEntryId, Level = EventLevel.Warning, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.LogEntry, Message = "{5} {2}: {3}")]
        void WarningLogEntry(
            int EventId,
            int Priority,
            string Severity,
            string Message,
            string ErrorMessages,
            string Categories,
            string Extended)
        {
            if (IsEnabled())
                WriteEvent(
                    WarningLogEntryId,
                    EventId,
                    Priority,
                    Severity,
                    Message,
                    ErrorMessages,
                    Categories,
                    Extended);
        }

        /// <summary>
        /// Writes an error log entry event.
        /// </summary>
        /// <param name="EventId">The EL-LAB event identifier.</param>
        /// <param name="Priority">The EL-LAB event priority.</param>
        /// <param name="Severity">The EL-LAB event severity.</param>
        /// <param name="Message">The EL-LAB event message.</param>
        /// <param name="ErrorMessages">The EL-LAB event error messages.</param>
        /// <param name="Categories">The EL-LAB event categories.</param>
        /// <param name="Extended">The EL-LAB event extended properties.</param>
        [Event(ErrorLogEntryId, Level = EventLevel.Error, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.LogEntry, Message = "{5} {2}: {3}")]
        void ErrorLogEntry(
            int EventId,
            int Priority,
            string Severity,
            string Message,
            string ErrorMessages,
            string Categories,
            string Extended)
        {
            if (IsEnabled())
                WriteEvent(
                    ErrorLogEntryId,
                    EventId,
                    Priority,
                    Severity,
                    Message,
                    ErrorMessages,
                    Categories,
                    Extended);
        }

        /// <summary>
        /// Writes a critical log entry event.
        /// </summary>
        /// <param name="EventId">The EL-LAB event identifier.</param>
        /// <param name="Priority">The EL-LAB event priority.</param>
        /// <param name="Severity">The EL-LAB event severity.</param>
        /// <param name="Message">The EL-LAB event message.</param>
        /// <param name="ErrorMessages">The EL-LAB event error messages.</param>
        /// <param name="Categories">The EL-LAB event categories.</param>
        /// <param name="Extended">The EL-LAB event extended properties.</param>
        [Event(CriticalLogEntryId, Level = EventLevel.Critical, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.LogEntry, Message = "{5} {2}: {3}")]
        void CriticalLogEntry(
            int EventId,
            int Priority,
            string Severity,
            string Message,
            string ErrorMessages,
            string Categories,
            string Extended)
        {
            if (IsEnabled())
                WriteEvent(
                    CriticalLogEntryId,
                    EventId,
                    Priority,
                    Severity,
                    Message,
                    ErrorMessages,
                    Categories,
                    Extended);
        }
        #endregion

        #region Write text message to ETW
        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="Text">An arbitrary object that will be dumped and logged.</param>
        [Event(VerboseMessageId, Level = EventLevel.Verbose, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Message, Message = "{0}")]
        void VerboseMessage(
            string Text)
        {
            if (IsEnabled())
                WriteEvent(VerboseMessageId, Text);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="Text">An arbitrary object that will be dumped and logged.</param>
        [Event(InformationalMessageId, Level = EventLevel.Informational, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Message, Message = "{0}")]
        void InformationalMessage(
            string Text)
        {
            if (IsEnabled())
                WriteEvent(InformationalMessageId, Text);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="Text">An arbitrary object that will be dumped and logged.</param>
        [Event(WarningMessageId, Level = EventLevel.Warning, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Message, Message = "{0}")]
        void WarningMessage(
            string Text)
        {
            if (IsEnabled())
                WriteEvent(WarningMessageId, Text);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="Text">An arbitrary object that will be dumped and logged.</param>
        [Event(ErrorMessageId, Level = EventLevel.Error, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Message, Message = "{0}")]
        void ErrorMessage(
            string Text)
        {
            if (IsEnabled())
                WriteEvent(ErrorMessageId, Text);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="Text">An arbitrary object that will be dumped and logged.</param>
        [Event(CriticalMessageId, Level = EventLevel.Critical, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Message, Message = "{0}")]
        void CriticalMessage(
            string Text)
        {
            if (IsEnabled())
                WriteEvent(CriticalMessageId, Text);
        }
        #endregion

        #region Dump an arbitrary object to ETW
        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="DataDump">An arbitrary object that will be dumped and logged.</param>
        [Event(VerboseDumpObjectId, Level = EventLevel.Verbose, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Dump)]
        void VerboseDumpObject(
            string DataDump)
        {
            if (IsEnabled())
                WriteEvent(VerboseDumpObjectId, DataDump);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="DataDump">An arbitrary object that will be dumped and logged.</param>
        [Event(InformationalDumpObjectId, Level = EventLevel.Informational, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Dump)]
        void InformationalDumpObject(
            string DataDump)
        {
            if (IsEnabled())
                WriteEvent(InformationalDumpObjectId, DataDump);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="DataDump">An arbitrary object that will be dumped and logged.</param>
        [Event(WarningDumpObjectId, Level = EventLevel.Warning, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Dump)]
        void WarningDumpObject(
            string DataDump)
        {
            if (IsEnabled())
                WriteEvent(WarningDumpObjectId, DataDump);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="DataDump">An arbitrary object that will be dumped and logged.</param>
        [Event(ErrorDumpObjectId, Level = EventLevel.Error, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Dump)]
        void ErrorDumpObject(
            string DataDump)
        {
            if (IsEnabled())
                WriteEvent(ErrorDumpObjectId, DataDump);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="DataDump">An arbitrary object that will be dumped and logged.</param>
        [Event(CriticalDumpObjectId, Level = EventLevel.Critical, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Dump)]
        void CriticalDumpObject(
            string DataDump)
        {
            if (IsEnabled())
                WriteEvent(CriticalDumpObjectId, DataDump);
        }
        #endregion

        #region Trace stuff to ETW
        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="ID">The EL LAB identifier.</param>
        /// <param name="Source">The source.</param>
        /// <param name="Text">An arbitrary trace text.</param>
        [Event(VerboseTraceId, Level = EventLevel.Verbose, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Trace, Message = "{2}: {1}")]
        void VerboseTrace(
            int ID,
            string Text,
            string Source = null)
        {
            if (IsEnabled())
                WriteEvent(VerboseTraceId, ID, Text, Source);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="ID">The EL LAB identifier.</param>
        /// <param name="Source">The source.</param>
        /// <param name="Text">An arbitrary trace text.</param>
        [Event(InformationalTraceId, Level = EventLevel.Informational, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Trace, Message = "{2}: {1}")]
        void InformationalTrace(
            int ID,
            string Text,
            string Source = null)
        {
            if (IsEnabled())
                WriteEvent(InformationalTraceId, ID, Text, Source);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="ID">The EL LAB identifier.</param>
        /// <param name="Source">The source.</param>
        /// <param name="Text">An arbitrary trace text.</param>
        [Event(WarningTraceId, Level = EventLevel.Warning, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Trace, Message = "{2}: {1}")]
        void WarningTrace(
            int ID,
            string Text,
            string Source = null)
        {
            if (IsEnabled())
                WriteEvent(WarningTraceId, ID, Text, Source);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="ID">The EL LAB identifier.</param>
        /// <param name="Source">The source.</param>
        /// <param name="Text">An arbitrary trace text.</param>
        [Event(ErrorTraceId, Level = EventLevel.Error, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Trace, Message = "{2}: {1}")]
        void ErrorTrace(
            int ID,
            string Text,
            string Source = null)
        {
            if (IsEnabled())
                WriteEvent(ErrorTraceId, ID, Text, Source);
        }

        /// <summary>
        /// Writes the log entry event.
        /// </summary>
        /// <param name="ID">The EL LAB identifier.</param>
        /// <param name="Source">The source.</param>
        /// <param name="Text">An arbitrary trace text.</param>
        [Event(CriticalTraceId, Level = EventLevel.Critical, Keywords = Keywords.vmAspects | Keywords.ELLab | Keywords.Trace, Message = "{2}: {1}")]
        void CriticalTrace(
            int ID,
            string Text,
            string Source = null)
        {
            if (IsEnabled())
                WriteEvent(CriticalTraceId, ID, Text, Source);
        }
        #endregion
    }
}


text:
layout: default
title: "Politics Of Sport"

---

{% include interests/politics-of-sport.md %}

### Who is interested in Politics Of Sport?

* [Ms Angela Eagle]({{ site.baseurl }}/members/ms-angela-eagle.html)


text:
package org.apache.carbondata.core.keygenerator.directdictionary.timestamp;

/**
 * Constant related to timestamp conversion
 */
public interface TimeStampGranularityConstants {

  /**
   * The property to set the date to be considered as start date for calculating the timestamp
   * java counts the number of milliseconds from  start of "January 1, 1970", this property is
   * customized the start of position. for example "January 1, 2000"
   */
  String CARBON_CUTOFF_TIMESTAMP = "carbon.cutOffTimestamp";
  /**
   * The property to set the timestamp (ie millisecond) conversion to the SECOND, MINUTE, HOUR
   * or DAY level
   */
  String CARBON_TIME_GRANULARITY = "carbon.timegranularity";

  /**
   * Second level key
   */
  String TIME_GRAN_SEC = "SECOND";
  /**
   * minute level key
   */
  String TIME_GRAN_MIN = "MINUTE";
  /**
   * hour level key
   */
  String TIME_GRAN_HOUR = "HOUR";
  /**
   * day level key
   */
  String TIME_GRAN_DAY = "DAY";
}


text:
import roslib; roslib.load_manifest('articulation_structure')
import rospy
import sys
from visualization_msgs.msg import Marker, MarkerArray
from geometry_msgs.msg import Vector3, Point, Pose, PoseArray
from std_msgs.msg import ColorRGBA
from sensor_msgs.msg import ChannelFloat32,CameraInfo,CompressedImage
from articulation_msgs.msg import *
from articulation_msgs.srv import *
from articulation_models.track_utils import *
import logging
import getopt
import colorsys
import numpy
import copy
import rosbag

def main():
  rospy.init_node('articulation_eval')

  info_pub = rospy.Publisher('/camera/camera_info',CameraInfo)
  image_pub = rospy.Publisher('/camera/image_raw/compressed',CompressedImage)
  posearray_pub = rospy.Publisher('/camera/pose_array',PoseArray)
  model_pub = rospy.Publisher('/model', ModelMsg)
  track_pub = rospy.Publisher('/track', TrackMsg)

  fit_models = rospy.ServiceProxy('fit_models', ArticulatedObjectSrv)
  get_spanning_tree = rospy.ServiceProxy('get_spanning_tree', ArticulatedObjectSrv)
  get_fast_graph = rospy.ServiceProxy('get_fast_graph', ArticulatedObjectSrv)
  get_graph = rospy.ServiceProxy('get_graph', ArticulatedObjectSrv)
  visualize_graph = rospy.ServiceProxy('visualize_graph', ArticulatedObjectSrv)

  #read data
  for (topic,object,t) in rosbag.Bag("eval.bag").read_messages():
    print t

  #object.parts = [object.parts[1],object.parts[2]]
  for p in object.parts:
    print "publishing part %d"%p.id
    track_pub.publish(p)

  #sys.exit()

  parts = len(object.parts)
  request = ArticulatedObjectSrvRequest()
  request.object = object
  #print object

  response = fit_models(request)
  print '\n'.join(
     ['(%s:%d,%d) bic=%f pos_err=%f rot_err=%f \n%s'%(
          model.name[0:2],
          model.id/parts,
          model.id%parts,
          get_param(model,'bic'),
          get_param(model,'avg_error_position'),
          get_param(model,'avg_error_orientation'),
          "\n".join(["  %s = %f"%(p.name,p.value) for p in model.params if p.name[0:3]=="rot"])
      ) for model in response.object.models])

  for m in response.object.models:
    if m.name=="rotational":
      model_pub.publish(m)

  request.object = copy.deepcopy(response.object)
  response = visualize_graph(request)

  sys.exit()

  if mode=="fastgraph":
    response = get_fast_graph(request)
  elif mode=="graph":
    response = get_graph(request)
  elif mode=="spanningtree":
    response = get_spanning_tree(request)

  request.object = copy.deepcopy(response.object)
  response = visualize_graph(request)

  rospy.loginfo('received articulation model: '+(' '.join(
     ['(%s:%d,%d)'%(model.name[0:2],model.id/parts,model.id%parts) for model in response.object.models])))

  print '\n'.join(
     ['(%s:%d,%d) bic=%f pos_err=%f rot_err=%f'%(
          model.name[0:2],
          model.id/parts,
          model.id%parts,
          get_param(model,'bic'),
          get_param(model,'avg_error_position'),
          get_param(model,'avg_error_orientation')
      ) for model in response.object.models])
  print "dofs=%d, nominal dofs=%d, bic=%f pos_err=%f rot_err=%f"%(
          get_param(response.object,'dof'),
          get_param(response.object,'dof.nominal'),
          get_param(response.object,'bic'),
          get_param(response.object,'avg_error_position'),
          get_param(response.object,'avg_error_orientation')
          )

  #print response.object.models

  # send image and info for last pose
  last_timestamp = timestamps[ downsampled[-1] ]
  info_pub.publish( bag[last_timestamp]['/camera/camera_info'] )
  image_pub.publish( bag[last_timestamp]['/camera/image_raw/compressed'] )
  posearray_pub.publish( bag[last_timestamp]['/camera/pose_array'] )

#  model_pub.publish(response.object.models[1])
#  track_pub.publish(request.object.parts[0])
#  track_pub.publish(request.object.parts[1])
#  rospy.sleep(5)
  #model_pub.publish(response.object.models[0])
  rospy.sleep(5)

if __name__ == '__main__':
  main()


text:
require 'test_helper'

class CartTest < ActiveSupport::TestCase
  setup do
    @cart = carts(:one)
  end

  test "cart must belong to a user" do
    cart = Cart.new()
    assert_not cart.save()
    cart.user = users(:admin_one)
    assert cart.save()
  end

  test "cart cannot belong to user with cart" do
    cart = Cart.new(user_uuid: users(:one).uuid)
    assert_not cart.save()
  end

  test "cart calculates subtotal" do
    exp_subtotal = @cart.items.inject(0) { |t, i| t + i.subtotal }
    assert_equal exp_subtotal, @cart.subtotal
  end

  test "cart can delete an item" do
    @cart.items.destroy(@cart.items.last)
    assert @cart.save
    assert_equal 1, @cart.items.length
  end

  test "cart should not include duplicate products" do
    @cart.items << Item.new({
      product: products(:one),
      cart: @cart,
      quantity: 3
    })
    assert_not @cart.save()
  end

  test "cart calculates shipping for one item with a quantity > 1" do
    @cart.items.destroy(@cart.items.first)
    @cart.save()
    item = @cart.items.first
    exp_shipping = item.product.add_on_shipping * item.quantity
    assert_equal exp_shipping, @cart.shipping
  end

  test "cart calculates shipping for one item with a quantity = 1" do
    @cart.items.destroy(@cart.items.last)
    @cart.save()
    exp_shipping = @cart.items.first.product.base_shipping * 1
    assert_equal exp_shipping, @cart.shipping
  end

  test "cart calculates shipping for multiple items" do
    exp_shipping = @cart.items.inject(0) { |t, i|
      t + i.product.add_on_shipping * i.quantity
    }
    assert_equal exp_shipping, @cart.shipping
  end

end


text:
FactoryGirl.define do
  factory :adjustment do
    user
    time_type
    date "2013-05-27"
    duration 1
    label "test"

    factory :invalid_adjustment do
      date "invalid-date"
    end
  end
end


text:
module XenAPI
  module HypervisorConnection
    class << self
      def hypervisor_session(host)
        sessions[host.ip] ||= hypervisor_session!(host)
      end

      def hypervisor_session!(host)
        Rails.logger.info "Connecting to hypervisor on #{host.ip} with user #{host.username}"
        session = SessionFactory.create(host.ip, host.username, host.password) do |error, &called_method|
          Rails.logger.error(error)
          session = HypervisorErrorHandler.new(host.pool, error).handle_error

          if called_method
            called_method.call(session)
          else
            session
          end
        end
      end

      def close_hypervisor_session!
        sessions.each do |host, session|
          begin
            session.close unless session.nil?
          rescue Exception => error
            Rails.logger.error("Error while trying to close connection to #{host}")
            Rails.logger.error(error)
          end
        end
        @sessions = {}
      end

     private
      def sessions
        @sessions ||= {}
      end
    end

    def hypervisor_session
      raise "Pool not found for #{self.inspect}" unless self.pool
      HypervisorConnection.hypervisor_session(self.pool.master)
    end
  end
end


text:
using Microsoft.Xna.Framework;
using Nez.Textures;

namespace Nez.Tiled
{
	public class TiledTile
	{
		/// <summary>
		/// returns the Subtexture that maps to this particular tile
		/// </summary>
		/// <value>The texture region.</value>
		public Subtexture textureRegion { get { return tileset.getTileTextureRegion( id ); } }

		/// <summary>
		/// gets the TiledtilesetTile for this TiledTile if it exists. TiledtilesetTile only exist for animated tiles and tiles with attached
		/// properties.
		/// </summary>
		/// <value>The tileset tile.</value>
		public TiledTilesetTile tilesetTile
		{
			get
			{
				if( !_tilesetTileIndex.HasValue )
				{
					_tilesetTileIndex = -1;
					for( var i = 0; i < tileset.tiles.Count; i++ )
					{
						// id is a gid so we need to subtract the tileset.firstId to get a local id
						if( tileset.tiles[i].id == id - tileset.firstId )
							_tilesetTileIndex = i;
					}
				}

				if( _tilesetTileIndex.Value < 0 )
					return null;
				return tileset.tiles[_tilesetTileIndex.Value];
			}
		}

		public int id;
		public int x;
		public int y;
		public bool flippedHorizonally;
		public bool flippedVertically;
		public bool flippedDiagonally;
		public TiledTileset tileset;

		/// <summary>
		/// we use this for 3 states: HasValue is false means we havent yet checked for the TiledTilesetTile, less than 0 means there is no
		/// TiledTilesetTile for this, and 0+ means we have a TiledTilesetTile.
		/// </summary>
		int? _tilesetTileIndex;

		public TiledTile( int id )
		{
			this.id = id;
		}

		/// <summary>
		/// sets a new Tile id for this tile and invalidates the previous tilesetTileIndex
		/// </summary>
		/// <returns>The tile identifier.</returns>
		/// <param name="id">Identifier.</param>
		public void setTileId( int id )
		{
			this.id = id;
			_tilesetTileIndex = null;
		}

		/// <summary>
		/// Rectangle that encompases this tile with origin on the top left
		/// </summary>
		/// <returns>The tile rectangle.</returns>
		/// <param name="tilemap">Tilemap.</param>
		public Rectangle getTileRectangle( TiledMap tilemap )
		{
			return new Rectangle( x * tilemap.tileWidth, y * tilemap.tileHeight, tilemap.tileWidth, tilemap.tileHeight );
		}

		/// <summary>
		/// note that the origin is the top left so this position will represent that
		/// </summary>
		/// <returns>The world position.</returns>
		/// <param name="tilemap">Tilemap.</param>
		public Vector2 getWorldPosition( TiledMap tilemap )
		{
			return new Vector2( x * tilemap.tileWidth, y * tilemap.tileHeight );
		}

		public override string ToString()
		{
			return string.Format( "[TiledTile] id: {0}, x: {1}, y: {2}", id, x, y );
		}

	}
}


text:
<?php

namespace Cjm\Behat\Psr7Extension;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

/**
 * Testable PSR-7 app
 */
interface Psr7App
{
    public function handle(Request $request) : Response;
}