text:
/* jshint strict: false, plusplus: true */
/*global define: false, require: false, module: false, exports: false */
(function(root, name, deps, factory) {
    "use strict";
    // Node
    if (typeof deps === 'function') {
        factory = deps;
        deps = [];
    }

    if (typeof exports === 'object') {
        module.exports = factory.apply(root, deps.map(require));
    } else if (typeof define === 'function' && 'amd' in define) {
        //require js, here we assume the file is named as the lower
        //case module name.
        define(name.toLowerCase(), deps, factory);
    } else {
        // Browser
        var d, i = 0,
            global = root,
            old = global[name],
            mod;
        while ((d = deps[i]) !== undefined) deps[i++] = root[d];
        global[name] = mod = factory.apply(global, deps);
        //Export no 'conflict module', aliases the module.
        mod.noConflict = function() {
            global[name] = old;
            return mod;
        };
    }
}(this, 'go2o', function() {

    /**
     * Extend method.
     * @param  {Object} target Source object
     * @return {Object}        Resulting object from
     *                         meging target to params.
     */
    var _extend = function extend(target) {
        if (!target) return {};

        var sources = [].slice.call(arguments, 1);
        sources.forEach(function(source) {
            for (var property in source) {
                if (source[property] && source[property].constructor &&
                    source[property].constructor === Object) {
                    target[property] = target[property] || {};
                    target[property] = extend(target[property], source[property]);
                } else target[property] = source[property];
            }
        });

        return target;
    };

    /**
     * Shim console, make sure that if no console
     * available calls do not generate errors.
     * @return {Object} Console shim.
     */
    var _shimConsole = function() {
        var empty = {},
            con = {},
            noop = function() {},
            properties = 'memory'.split(','),
            methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' +
                'groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,' +
                'table,time,timeEnd,timeStamp,trace,warn').split(','),
            prop,
            method;

        while (method = methods.pop()) con[method] = noop;
        while (prop = properties.pop()) con[prop] = empty;

        return con;
    };

    /**
     * Get keys in the `src` object not
     * present in the `tgt` object.
     * @param  {Object} src Source Object
     * @param  {Object} tgt Target Object
     * @return {Array}      Array with keys
     */
    var _diff = function(src, tgt) {
        if (!src) return Object.keys(tgt);
        if (!tgt) return [];
        var keys = Object.keys(tgt);
        return Object.keys(src).filter(function(i) {
            return keys.indexOf(i) < 0;
        });
    };

    /**
     * Unique elements in array.
     * @param  {Array} src Source array
     * @return {Array}     Filtered array, no dups
     */
    var _unique = function(src) {
        return src.filter(function(i, pos, self) {
            return self.indexOf(i) === pos;
        });
    };

    var _isFunction = function(src, key) {
        return src && key && src[key] && typeof src[key] === 'function';
    };

    ///////////////////////////////////////////////////
    /// HELPER JSON
    /// TODO: Implement as plugin?
    /// Go2o.use(Flattener);
    ///////////////////////////////////////////////////
    //{
    var Parser = {};
    /**
     * Flatten a deeply nested object into a map of a
     * single level where the keys match to original
     * string path of the property.
     *
     * @param  {Object} src    Object to be serialized
     * @return {Object}        Serialized object.
     */
    Parser.flatten = function flatten(src, /*private*/ prop, output) {
        prop || (prop = '');
        output || (output = {});

        if (Object(src) !== src) output[prop] = src;
        else if (Array.isArray(src)) {
            for (var i = 0, l = src.length; i < l; i++) {
                flatten(src[i], prop ? prop + '.' + i : '' + i, output);
            }
            if (l === 0) output[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in src) {
                isEmpty = false;
                flatten(src[p], prop ? prop + '.' + p : p, output);
            }
            if (isEmpty) output[prop] = {};
        }

        return (isEmpty === true) ? {} : output;
    };

    /**
     * Unflatten a map of string path keys
     * and values to a fully nested object.
     *
     * @param  {Object} src Map to be unmapped
     * @return {Object}
     */
    Parser.unflatten = function(src) {
        if (Object(src) !== src || Array.isArray(src)) return src;

        var result = {}, cur, prop, idx, last, temp;
        for (var p in src) {
            cur = result, prop = '__ROOT__', last = 0;

            do {
                idx = p.indexOf('.', last);
                temp = p.substring(last, idx !== -1 ? idx : undefined);
                cur = cur[prop] || (cur[prop] = (!isNaN(parseInt(temp)) ? [] : {}));
                prop = temp;
                last = idx + 1;
            } while (idx >= 0);

            cur[prop] = src[p];
        }

        return result['__ROOT__'] || {};
    };

    /**
     * Captures all object keys that match
     * a regexp pattern
     * @param  {Object} map     Source object
     * @param  {RegExp} pattern Matcher
     * @return {Object}         Object with the
     *                          subset of properties
     *                          matching `pattern`
     */
    Parser.glob = function(map, pattern) {
        map || (map = {});
        var out = {};
        Object.keys(map).forEach(function(key) {
            if (key.match(pattern)) out[key] = map[key];
        });
        return out;
    };
    //}
    ///////////////////////////////////////////////////
    // CONSTRUCTOR
    ///////////////////////////////////////////////////

    var OPTIONS = {
        /*
         * List of attributes that get initialized even
         * if not specified on the config object.
         */
        attributes: ['schema', 'transforms', 'flattened', 'matchers',
            'transformers', 'processors', 'preprocessors', 'postprocessors',
            'handledKeys'
        ],
        /*
         * Should we override output in case
         * of conflict, ie: object merge.
         */
        overrideOnConflict: true,
        /*
         * This pre-process should always
         * happen BEFORE than any other process
         */
        defaultPre: ['flattenPaths'],
        /*
         * This two processes should always happen,
         * unflattenPaths should always be the last
         * process to run.
         */
        defaultPost: ['mergeOrphans', 'unflattenPaths']
    };

    /**
     * Go2o constructor
     *
     * TODO: Life cycle.
     * - 1) Apply filters: ensure we don't have invalid data.
     * - 2) Flatten
     * @param  {object} config Configuration object.
     */
    var Go2o = function(config) {
        //TODO: We want to only merge in valid attributes!!
        //not the whole config object!
        config = config || {};
        config = _extend({}, this.constructor.DEFAULTS, config);

        this.init(config);
    };

    Go2o.VERSION = '0.3.0';

    /**
     * Make default options available so we
     * can override.
     */
    Go2o.DEFAULTS = OPTIONS;

    ///////////////////////////////////////////////////
    // PUBLIC METHODS
    ///////////////////////////////////////////////////

    Go2o.prototype.init = function(config) {
        if (this.initialized) return this.logger.warn('Already initialized');
        this.initialized = true;

        console.log('Go2o: Init!', config);

        _extend(this, config);

        /*
         * Create attributes.
         */
        OPTIONS.attributes.forEach(function(prop) {
            this.hasOwnProperty(prop) || (this[prop] = {});
        }, this);

        this.initializeProcessors();

        this.registerDefaultTransformations();
    };

    Go2o.prototype.initializeProcessors = function() {
        /*
         * We need to ensure that we kick start
         * pre/post collections.
         */
        this.pre || (this.pre = []);
        this.pre = _unique(this.defaultPre.concat(this.pre));

        this.post || (this.post = []);
        this.post = _unique(this.post.concat(this.defaultPost));
    };

    Go2o.prototype.registerDefaultTransformations = function() {
        /*****************************************
         * ADDING SAMPLE TRANSFORMATIONS. MOVE OUT
         *****************************************/
        this.addTransformer('rename', function rename(path, options) {
            if (typeof options === 'object' && options.glob === true) {
                Object.keys(this.flattened).forEach(function(key) {
                    if (!key.match(options.matcher)) return;
                    var name = key;
                    if (typeof options.execute === 'function') {
                        name = options.execute(key, path, options);
                    }

                    this.output[name] = this.flattened[key];
                    delete this.flattened[key];
                }, this);

                return true;
            } else if (!this.flattened.hasOwnProperty(path)) return false;

            console.log('=> rename %s to %s', path, options);
            this.output[options] = this.flattened[path];
            delete this.flattened[path];

            return true;
        });

        this.addTransformer('collapse', function collapse(path, name) {
            if (!this.flattened.hasOwnProperty(path)) return false;
            // console.log('=> collapse %s to %s', path, name);
            if (!this.output.hasOwnProperty(name)) this.output[name] = [];
            this.output[name].push(this.flattened[path]);
            return true;
        });

        this.addTransformer('remove', function remove(path, options) {
            if (typeof options === 'object' && options.glob === true) {
                Object.keys(this.flattened).forEach(function(key) {
                    if (!key.match(options.matcher)) return;
                    delete this.flattened[key];
                }, this);
            } else if (!this.flattened.hasOwnProperty(path)) return false;

            delete this.flattened[path];
            return true;
        });

        /*
         * Flatten source object into map. After this point we are
         * ready to apply our transformations.
         */
        this.addPreprocessor('flattenPaths', function flattenPaths() {
            console.warn('flattenPaths');
            this.flattened = Parser.flatten(this.source);
        });

        /*
         * Post processor that merges untransformed keys into the
         * output object.
         */
        this.addPostprocessor('mergeOrphans', function mergeOrphans() {
            /*
             * Collect all keys in the original map that were
             * not handled.
             */
            var orphans = _diff(this.flattened, this.handledKeys),
                fname = arguments.callee.name;

            orphans.forEach(function(key) {
                if (this.output.hasOwnProperty(key)) {
                    this.solveConflict(key);
                } else this.output[key] = this.flattened[key];
            }, this);
        });

        /*
         * We are done, rehydrate our object from the map.
         */
        this.addPostprocessor('unflattenPaths', function() {
            this.output = Parser.unflatten(this.output);
        });
    };

    /**
     * Simple method to solve conflict when
     * merging elements.
     * @param  {String} key Element ID
     * @return {void}
     */
    Go2o.prototype.solveConflict = function(key) {
        this.logger.warn('Conflict, solving for key', key);

        if (this.overrideOnConflict === true) {
            this.logger.warn('√ now %s, had value %s', this.flattened[key], this.output[key]);
            this.output[key] = this.flattened[key];
        } else {
            this.logger.warn('= now %s, ignore %s', this.output[key], this.flattened[key]);
        }
    };

    /**
     * Run processes and transformations.
     * @param  {Object} data Object to which
     *                       we want to modify.
     * @return {Object}      Transformed object.
     */
    Go2o.prototype.run = function(data) {
        console.log('parsing', data);

        this.original = data;
        this.source = _extend({}, data);

        //this is a reset
        this.output = {};
        this.handledKeys = {};

        this.runPre();

        //Iterate over the source properties in transforms:
        Object.keys(this.transforms).map(this.applyTransformTo, this);

        //after we run all trasforms, we should pic all properties of
        //original object and append those to the output.
        this.runPost();

        return this.output;
    };

    Go2o.prototype.applyTransformTo = function(path) {
        var rules = this.transforms[path],
            arg = null,
            handled = false;

        //for now we assume that all schema values are objs.
        Object.keys(rules).forEach(function(event) {
            arg = rules[event];

            if (!_isFunction(this.transformers, event)) return;

            handled = this.transformers[event].call(this, path, arg);
            if (handled === true) this.handledKeys[path] = true;
        }, this);
    };

    /**
     * Transformation method attached to `event`
     * key.
     * TODO: Transformer should be an object:
     * ```
     *     var transformer = {
     *         id: 'rename',
     *         check: function(path, name){
     *             return this.flattened.hasOwnProperty(path);
     *         },
     *         execute: function(path, name){
     *             this.output[name] = this.flattened[path];
     *         }
     *     };
     * ```
     * @param {String} event       Name to trigger
     *                             transformation.
     * @param {this}
     */
    Go2o.prototype.addTransformer = function(event, transformer) {
        //WE REALLY WANT TO DO THIS WITH EVENTS!!
        // this.on(transformer.key, transformer.execute);
        this.transformers[event] = transformer;
        return this;
    };

    Go2o.prototype.addPostprocessor = function(id, post) {
        this.postprocessors[id] = post;
        return this;
    };

    Go2o.prototype.addPreprocessor = function(id, pre) {
        this.preprocessors[id] = pre;
        return this;
    };

    Go2o.prototype.runPost = function() {
        var processId;
        Object.keys(this.post).forEach(function(id) {
            processId = this.post[id];
            if (!_isFunction(this.postprocessors, processId)) return;
            this.postprocessors[processId].call(this);
        }, this);

        return this;
    };

    Go2o.prototype.runPre = function() {
        var processId;
        Object.keys(this.pre).forEach(function(id) {
            processId = this.pre[id];

            if (!_isFunction(this.preprocessors, processId)) return;

            this.preprocessors[processId].call(this);
        }, this);
        return this;
    };

    /**
     * Logger method, meant to be implemented by
     * mixin. As a placeholder, we use console if available
     * or a shim if not present.
     */
    Go2o.prototype.logger = console || _shimConsole();

    /*****************************
     * EXPOSE HELPERS, FOR TESTING.
     ******************************/
    Go2o.helpers = {};
    Go2o.helpers.diff = _diff;
    Go2o.helpers.extend = _extend;
    Go2o.helpers.isFunction = _isFunction;
    Go2o.helpers.Parser = Parser;

    return Go2o;
}));


text:
<q-grid caption="Select Row Single Only"
        [rows]="rows$ | async"
        class="q-grid-compact"
        selectionUnit="row"
        selectionMode="singleOnly">
    <q-grid-columns generation="deep">
    </q-grid-columns>
</q-grid>

redpajama_set_name: RedPajamaGithub


text:
<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

$app->before(function () use ($app) {
    if ($token = $app['security.token_storage']->getToken()) {
        $app['session']->start();
        if (!$app['session']->get('name')) {
            // get account's info > name, timezone etc (from an account repo)
            $app['session']->set('userId', $token->getUser()->getId());
            $app['session']->set('name', $token->getUser()->getName());
            $app['session']->set('username', $token->getUser()->getUsername());
        }
    }
});

$app->mount('/', new Days\Controller\IndexController);
$app->mount('/login', new Days\Controller\LoginController);
$app->mount('/user', new Days\Controller\UserController);
$app->mount('/counter', new Days\Controller\CounterController);
$app->mount('/series', new Days\Controller\SeriesController);
$app->mount('/leaderboard', new Days\Controller\LeaderboardController);
$app->mount('/feed', new Days\Controller\FeedController);

$app->match('/amsterdam/', function () use ($app) {
    return $app['twig']->render('amsterdam.html.twig', array());
})
->bind('amsterdam');

$app->error(function (\Exception $e, $code) use ($app) {
    if ($app['debug']) {
        return;
    }

    $templates = array(
        'Error/'.$code.'.html',
        'Error/'.substr($code, 0, 2).'x.html',
        'Error/'.substr($code, 0, 1).'xx.html',
        'Error/default.html',
    );

    return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
});


text:
package deployment

import (
	"errors"
	"fmt"

	gpb "github.com/grafeas/grafeas/proto/v1/grafeas_go_proto"
)

// ValidateNote validates that a deployable has all its required fields filled in.
func ValidateNote(d *gpb.DeploymentNote) []error {
	errs := []error{}

	if r := d.GetResourceUri(); r == nil {
		errs = append(errs, errors.New("resource_uri is required"))
	} else if len(r) == 0 {
		errs = append(errs, errors.New("resource_uri requires at least 1 element"))
	} else {
		for i, r := range r {
			if r == "" {
				errs = append(errs, fmt.Errorf("resource_uri[%d] cannot be empty", i))
			}
		}
	}

	return errs
}

// ValidateOccurrence validates that a details has all its required fields filled in.
func ValidateOccurrence(d *gpb.DeploymentOccurrence) []error {
	errs := []error{}

	if d.GetDeployTime() == nil {
		errs = append(errs, errors.New("deploy_time is required"))
	}

	return errs
}


text:
package com.tom_roush.pdfbox.pdmodel.interactive.annotation;

/**
 * Simple interface allowing the use of an annotation filter visitor.
 *
 * @author Maxime Veron
 *
 */
public interface AnnotationFilter
{
    boolean accept(PDAnnotation annotation);
}


text:
<?php

namespace Drupal\webform\Plugin\WebformElement;

use Drupal\webform\Plugin\WebformElementEntityReferenceInterface;

/**
 * Provides a 'webform_entity_select' element.
 *
 * @WebformElement(
 *   id = "webform_entity_select",
 *   label = @Translation("Entity select"),
 *   description = @Translation("Provides a form element to select a single or multiple entity references using a select menu."),
 *   category = @Translation("Entity reference elements"),
 * )
 */
class WebformEntitySelect extends Select implements WebformElementEntityReferenceInterface {

  use WebformEntityReferenceTrait;
  use WebformEntityOptionsTrait;

}


text:
package com.manchey.model.vo.wechat.message.response;

import com.manchey.model.vo.wechat.message.BaseMessage;
import com.manchey.utils.wechat.AdapterCDATA;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 * 回复文本消息
 * Created by Ray on 2016/5/27.
 */
@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class ResTextMessage extends BaseMessage {

    @XmlElement(name = "Content")
    @XmlJavaTypeAdapter(AdapterCDATA.class)
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}


text:
/*============================ INCLUDES ======================================*/

#include ".\compiler.h"
#include ".\delegate.h"

/*============================ MACROS ========================================*/

/*============================ MACROS ========================================*/
#define EVENT_RT_UNREGISTER         4

#ifndef this
#   define this             (*ptThis)
#endif

/*============================ MACROFIED FUNCTIONS ===========================*/
/*============================ TYPES =========================================*/

typedef fsm_rt_t delegate_handler_func_t(void *pArg, void *pParam);

/*============================ MACROFIED FUNCTIONS ===========================*/
/*============================ TYPES =========================================*/

//! \name general event handler
//! @{
def_class(delegate_handler_t,,
    delegate_handler_func_t    *fnHandler;         //!< event handler
    void                    *pArg;              //!< Argument
    class(delegate_handler_t)  *ptNext;            //!< next
)
end_def_class(delegate_handler_t)
//! @}

//! \name event
//! @{
def_class(delegate_t,,
    delegate_handler_t *ptEvent;
    delegate_handler_t *ptBlockedList;
    class(delegate_handler_t) **pptHandler;
)
end_def_class(delegate_t)
//! @}

/*============================ GLOBAL VARIABLES ==============================*/
/*============================ LOCAL VARIABLES ===============================*/
/*============================ PROTOTYPES ====================================*/
/*============================ IMPLEMENTATION ================================*/

/*! \brief initialize event
 *! \param ptEvent target event
 *! \return the address of event item
 */
delegate_t *delegate_init(delegate_t *ptEvent)
{
    class_internal(ptEvent, ptThis, delegate_t);

    do {
        if (NULL == ptThis) {
            break;
        }

        this.ptEvent = NULL;
        this.ptBlockedList = NULL;
        this.pptHandler = (class(delegate_handler_t) **)&(this.ptEvent);

    } while (0);

    return ptEvent;
}

/*! \brief initialize event handler item
 *! \param ptHandler the target event handler item
 *! \param fnRoutine event handler routine
 *! \param pArg handler extra arguments
 *! \return the address of event handler item
 */
delegate_handler_t *delegate_handler_init(
    delegate_handler_t *ptHandler, delegate_handler_func_t *fnRoutine, void *pArg)
{

    class_internal(ptHandler, ptThis, delegate_handler_t);

    if (NULL == ptHandler || NULL == fnRoutine) {
        return NULL;
    }
    this.fnHandler = fnRoutine;
    this.pArg = pArg;
    this.ptNext = NULL;

    return ptHandler;
}

static class(delegate_handler_t) **search_list(
    class(delegate_handler_t) **pptHandler, class(delegate_handler_t) *ptHND)
{
    //! search event handler chain
    while (NULL != (*pptHandler)) {
        if ((*pptHandler) == ptHND) {
            return pptHandler;
        }
        pptHandler = &((*pptHandler)->ptNext);      //!< get next item
    }
    return NULL;
}

/*! \brief register event handler to specified event
 *! \param ptEvent target event
 *! \param ptHandler target event handler
 *! \return access result
 */
gsf_err_t register_delegate_handler(delegate_t *ptEvent, delegate_handler_t *ptHandler)
{
    class_internal(ptEvent, ptThis, delegate_t);
    class_internal(ptHandler, ptHND, delegate_handler_t);

    if ((NULL == ptEvent) || (NULL == ptHandler) || (NULL == ptHND->fnHandler)) {
        return GSF_ERR_INVALID_PTR;
    } else if (NULL != ptHND->ptNext) {
        //! search ready list
        class(delegate_handler_t) **pptHandler = search_list(
            (class(delegate_handler_t) **)&(this.ptBlockedList), ptHND );

        if (NULL != pptHandler) {
            //! safe to remove
            (*pptHandler) = ptHND->ptNext;
            ptHND->ptNext = NULL;
        } else {
            return GSF_ERR_REQ_ALREADY_REGISTERED;
        }
    }

    //! add handler to the ready list
    ptHND->ptNext = (class(delegate_handler_t) *)(this.ptEvent);
    this.ptEvent = ptHandler;

    return GSF_ERR_NONE;
}

/*! \brief unregister a specified event handler
 *! \param ptEvent target event
 *! \param ptHandler target event handler
 *! \return access result
 */
gsf_err_t unregister_delegate_handler( delegate_t *ptEvent, delegate_handler_t *ptHandler)
{
    class_internal(ptEvent, ptThis, delegate_t);
    class_internal(ptHandler, ptHND, delegate_handler_t);

    class(delegate_handler_t) **pptHandler;
    if ((NULL == ptEvent) || (NULL == ptHandler)) {
        return GSF_ERR_INVALID_PTR;
    }

    do {
        //! search ready list
        pptHandler = search_list(   (class(delegate_handler_t) **)&(this.ptEvent),
                                    ptHND );
        if (NULL != pptHandler) {
            //! safe to remove
            (*pptHandler) = ptHND->ptNext;
            ptHND->ptNext = NULL;
            if (this.pptHandler == &(ptHND->ptNext)) {
                this.pptHandler = pptHandler;
            }
            break;
        }
        //! search ready list
        pptHandler = search_list(   (class(delegate_handler_t) **)&(this.ptBlockedList),
                                    ptHND );
        if (NULL != pptHandler) {
            //! safe to remove
            (*pptHandler) = ptHND->ptNext;
            ptHND->ptNext = NULL;
            if (this.pptHandler == &(ptHND->ptNext)) {
                this.pptHandler = pptHandler;
            }
            break;
        }
    } while(false);

    return GSF_ERR_NONE;
}

static fsm_rt_t __move_to_block_list(class(delegate_t) *ptThis, class(delegate_handler_t) *ptHandler)
{
    class(delegate_handler_t) *ptHND = ptHandler;
    //! remove handler from ready list
    (*this.pptHandler) = ptHND->ptNext;
    //! add handler to block list
    ptHND->ptNext = (class(delegate_handler_t) *)this.ptBlockedList;
    this.ptBlockedList = (delegate_handler_t *)ptHND;

    if (NULL == this.ptEvent) {
        return fsm_rt_cpl;
    }

    return fsm_rt_on_going;
}

#define RAISE_EVENT_START               0
#define RAISE_EVENT_CHECK_HANDLER       1
#define RAISE_EVENT_RUN_HANDLER         2
#define RAISE_EVENT_RESET_FSM()     do { this.chState = 0; } while (0)

/*! \brief raise target event
 *! \param ptEvent the target event
 *! \param pParam event parameter
 *! \return access result
 */
fsm_rt_t invoke_delegate( delegate_t *ptEvent, void *pParam)
{
    class_internal(ptEvent, ptThis, delegate_t);
    if (NULL == ptThis) {
        return (fsm_rt_t)GSF_ERR_INVALID_PTR;
    }

    if (NULL == this.ptEvent) {
        if (NULL == this.ptBlockedList) {
            //! nothing to do
            return fsm_rt_cpl;
        }

        //! initialize state
        this.ptEvent = this.ptBlockedList;
        this.ptBlockedList = NULL;
        this.pptHandler = (class(delegate_handler_t) **)&(this.ptEvent);
    }

    if (NULL == (*this.pptHandler)) {
        //! finish visiting the ready list
        this.pptHandler = (class(delegate_handler_t) **)&(this.ptEvent);
        if (NULL == (*this.pptHandler)) {
            //! complete
            return fsm_rt_cpl;
        }
    } else {
        class(delegate_handler_t) *ptHandler = (*this.pptHandler);

        if (NULL != ptHandler->fnHandler) {
            //! run the event handler
            fsm_rt_t tFSM = ptHandler->fnHandler(ptHandler->pArg,pParam);

            if (fsm_rt_on_going == tFSM) {
                this.pptHandler = &(ptHandler->ptNext);    //!< get next item
            } else if (EVENT_RT_UNREGISTER == tFSM) {
                //! return EVENT_RT_UNREGISTER means event handler could be removed
                class(delegate_handler_t) *ptHND = ptHandler;
                (*this.pptHandler) = ptHND->ptNext;
                ptHND->ptNext = NULL;
            } else {
                return __move_to_block_list(ptThis, ptHandler);
            }
        } else {
            return __move_to_block_list(ptThis, ptHandler);
        }
    }

    return fsm_rt_on_going;
}

/* EOF */


text:
namespace polly {

/// Addition
/// @{
inline isl::pw_aff operator+(isl::pw_aff Left, isl::pw_aff Right) {
  return Left.add(Right);
}

inline isl::pw_aff operator+(isl::val ValLeft, isl::pw_aff Right) {
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.add(Right);
}

inline isl::pw_aff operator+(isl::pw_aff Left, isl::val ValRight) {
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.add(Right);
}

inline isl::pw_aff operator+(long IntLeft, isl::pw_aff Right) {
  isl::ctx Ctx = Right.get_ctx();
  isl::val ValLeft(Ctx, IntLeft);
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.add(Right);
}

inline isl::pw_aff operator+(isl::pw_aff Left, long IntRight) {
  isl::ctx Ctx = Left.get_ctx();
  isl::val ValRight(Ctx, IntRight);
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.add(Right);
}
/// @}

/// Multiplication
/// @{
inline isl::pw_aff operator*(isl::pw_aff Left, isl::pw_aff Right) {
  return Left.mul(Right);
}

inline isl::pw_aff operator*(isl::val ValLeft, isl::pw_aff Right) {
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.mul(Right);
}

inline isl::pw_aff operator*(isl::pw_aff Left, isl::val ValRight) {
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.mul(Right);
}

inline isl::pw_aff operator*(long IntLeft, isl::pw_aff Right) {
  isl::ctx Ctx = Right.get_ctx();
  isl::val ValLeft(Ctx, IntLeft);
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.mul(Right);
}

inline isl::pw_aff operator*(isl::pw_aff Left, long IntRight) {
  isl::ctx Ctx = Left.get_ctx();
  isl::val ValRight(Ctx, IntRight);
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.mul(Right);
}
/// @}

/// Subtraction
/// @{
inline isl::pw_aff operator-(isl::pw_aff Left, isl::pw_aff Right) {
  return Left.sub(Right);
}

inline isl::pw_aff operator-(isl::val ValLeft, isl::pw_aff Right) {
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.sub(Right);
}

inline isl::pw_aff operator-(isl::pw_aff Left, isl::val ValRight) {
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.sub(Right);
}

inline isl::pw_aff operator-(long IntLeft, isl::pw_aff Right) {
  isl::ctx Ctx = Right.get_ctx();
  isl::val ValLeft(Ctx, IntLeft);
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.sub(Right);
}

inline isl::pw_aff operator-(isl::pw_aff Left, long IntRight) {
  isl::ctx Ctx = Left.get_ctx();
  isl::val ValRight(Ctx, IntRight);
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.sub(Right);
}
/// @}

/// Division
///
/// This division rounds towards zero. This follows the semantics of C/C++.
///
/// @{
inline isl::pw_aff operator/(isl::pw_aff Left, isl::pw_aff Right) {
  return Left.tdiv_q(Right);
}

inline isl::pw_aff operator/(isl::val ValLeft, isl::pw_aff Right) {
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.tdiv_q(Right);
}

inline isl::pw_aff operator/(isl::pw_aff Left, isl::val ValRight) {
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.tdiv_q(Right);
}

inline isl::pw_aff operator/(long IntLeft, isl::pw_aff Right) {
  isl::ctx Ctx = Right.get_ctx();
  isl::val ValLeft(Ctx, IntLeft);
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.tdiv_q(Right);
}

inline isl::pw_aff operator/(isl::pw_aff Left, long IntRight) {
  isl::ctx Ctx = Left.get_ctx();
  isl::val ValRight(Ctx, IntRight);
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.tdiv_q(Right);
}
/// @}

/// Remainder
///
/// This is the remainder of a division which rounds towards zero. This follows
/// the semantics of C/C++.
///
/// @{
inline isl::pw_aff operator%(isl::pw_aff Left, isl::pw_aff Right) {
  return Left.tdiv_r(Right);
}

inline isl::pw_aff operator%(isl::val ValLeft, isl::pw_aff Right) {
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.tdiv_r(Right);
}

inline isl::pw_aff operator%(isl::pw_aff Left, isl::val ValRight) {
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.tdiv_r(Right);
}

inline isl::pw_aff operator%(long IntLeft, isl::pw_aff Right) {
  isl::ctx Ctx = Right.get_ctx();
  isl::val ValLeft(Ctx, IntLeft);
  isl::pw_aff Left(Right.domain(), ValLeft);
  return Left.tdiv_r(Right);
}

inline isl::pw_aff operator%(isl::pw_aff Left, long IntRight) {
  isl::ctx Ctx = Left.get_ctx();
  isl::val ValRight(Ctx, IntRight);
  isl::pw_aff Right(Left.domain(), ValRight);
  return Left.tdiv_r(Right);
}
/// @}

} // namespace polly

#endif // POLLY_ISLOPERATORS_H


text:
<!DOCTYPE html>

    <link href="css/awsdocs.css" rel="stylesheet" type="text/css">

    <meta charset="utf-8">

AWS::CodeBuild::Project

The AWS::CodeBuild::Project resource configures how AWS CodeBuild builds your source
                        code. For example, it tells AWS CodeBuild where to get the source code and which build
                        environment to
                        use.

Syntax

To declare this entity in your AWS CloudFormation template, use the following syntax:

JSON

{
  "Type" : "AWS::CodeBuild::Project",
  "Properties" : {
    "Artifacts" : Artifacts,
    "BadgeEnabled" : Boolean,
    "Cache" : ProjectCache,
    "Description" : String,
    "EncryptionKey" : String,
    "Environment" : Environment,
    "LogsConfig" : LogsConfig,
    "Name" : String,
    "QueuedTimeoutInMinutes" : Integer,
    "SecondaryArtifacts" : [ Artifacts, ... ],
    "SecondarySources" : [ Source, ... ],
    "ServiceRole" : String,
    "Source" : Source,
    "Tags" : [ Resource Tag, ... ],
    "TimeoutInMinutes" : Integer,
    "Triggers" : Triggers,
    "VpcConfig" : VpcConfig
  }
}

YAML

Type: AWS::CodeBuild::Project
Properties:
  Artifacts: Artifacts
  BadgeEnabled: Boolean
  Cache: ProjectCache
  Description: String
  EncryptionKey: String
  Environment: Environment
  LogsConfig: LogsConfig
  Name: String
  QueuedTimeoutInMinutes: Integer
  SecondaryArtifacts:
    - Artifacts
  SecondarySources:
    - Source
  ServiceRole: String
  Source: Source
  Tags:
    - Resource Tag
  TimeoutInMinutes: Integer
  Triggers: Triggers
  VpcConfig: VpcConfig

Properties

Artifacts

The output settings for artifacts that the project generates during a build.

Required: Yes

Type: AWS CodeBuild Project Artifacts

Update requires: No interruption

BadgeEnabled

Indicates whether AWS CodeBuild generates a publicly accessible URL for your project's
                                 build
                                 badge. For more information, see Build Badges
                                    Sample in the AWS CodeBuild User Guide.

Note

Including build badges with your project is currently not supported if the
                                    source type is CodePipeline. If you specify CODEPIPELINE for the
                                    Source property, don't specify the BadgeEnabled property.

                                 Required: No

                                 Type: Boolean

                                 Update requires:
                                 No interruption

Cache

Settings that AWS CodeBuild uses to store and reuse build dependencies.

                                 Required: No

                                 Type: ProjectCache

                                 Update requires:
                                 No interruption

Description

A description of the project. Use the description to identify the purpose of the
                                 project.

Required: No

Type: String

Update requires: No interruption

EncryptionKey

The alias or Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
                                 customer master key
                                 (CMK) that AWS CodeBuild uses to encrypt the build output. If you don't specify a
                                 value, AWS CodeBuild
                                 uses the AWS-managed CMK for Amazon Simple Storage Service.

Required: No

Type: String

Update requires: No interruption

Environment

The build environment settings for the project, such as the environment type or the
                                 environment variables to use for the build environment.

Required: Yes

Type: AWS CodeBuild Project Environment

Update requires: No interruption

LogsConfig

Information about logs for this build project.

Required: No

Type: AWS CodeBuild Project LogsConfig

Update requires: No interruption

Name

A name for the project. The name must be unique across all of the projects in your
                                 AWS account.

Required: No

Type: String

Update requires: Replacement

QueuedTimeoutInMinutes

The number of minutes a build is allowed to be queued before it times out.

                                 Required: No

                                 Type: Integer

                                 Update requires: No interruption

SecondaryArtifacts

An array of artifacts objects. Each artifacts object specifies output settings that
                                 the project generates during a build.

Required: No

Type: List of AWS CodeBuild Project Artifacts

Update requires: No interruption

SecondarySources

An array of source objects. Each source object contains source code settings for the
                                 project.

Required: No

Type: List of AWS CodeBuild Project Source

Update requires: No interruption

ServiceRole

The ARN of the service role that AWS CodeBuild uses to interact with services on your
                                 behalf.

Required: Yes

Type: String

Update requires: No interruption

Source

The source code settings for the project, such as the source code's repository type
                                 and location.

Required: Yes

Type: AWS CodeBuild Project Source

Update requires: No interruption

Tags

An arbitrary set of tags (key-value pairs) for the AWS CodeBuild project.

Required: No

Type: Resource Tag

Update requires: No interruption

TimeoutInMinutes

The number of minutes after which AWS CodeBuild stops the build if it's not complete.
                                 For
                                 valid values, see the timeoutInMinutes field in the
                                 AWS CodeBuild User Guide.

Required: No

Type: Integer

Update requires: No interruption

Triggers

For an existing AWS CodeBuild build project that has its source code stored in a GitHub
                                 repository, enables AWS CodeBuild to begin automatically rebuilding the source code
                                 every time a
                                 code change is pushed to the repository.

Required: No

                                 Type: AWS CodeBuild Project ProjectTriggers

Update requires: No interruption

VpcConfig

Settings that enable AWS CodeBuild to access resources in an Amazon VPC.
                                 For more information, see Use AWS CodeBuild with Amazon Virtual Private Cloud
                                 in the AWS CodeBuild User Guide.

                                 Required: No

                                 Type: VpcConfig

                                 Update requires:
                                 No interruption

Return Values

Ref

When the logical ID of this resource is provided to the Ref
                        intrinsic function, Ref returns the name of the AWS CodeBuild project, such as
                        myProjectName.

For more information about using the Ref function, see Ref.

Fn::GetAtt

Fn::GetAtt returns a value for a specified attribute of this type.
                        This section lists the available attribute and a sample return value.

Arn

The ARN of the AWS CodeBuild project, such as
                                 arn:aws:codebuild:us-west-2:123456789012:project/myProjectName.

For more information about using Fn::GetAtt, see Fn::GetAtt.

Examples

The following example creates an AWS CodeBuild project.

JSON

{
  "Project": {
    "Type": "AWS::CodeBuild::Project",
    "Properties": {
      "Name": "myProjectName",
      "Description": "A description about my project",
      "ServiceRole": { "Fn::GetAtt": [ "ServiceRole", "Arn" ] },
      "Artifacts": {
        "Type": "no_artifacts"
      },
      "Environment": {
        "Type": "LINUX_CONTAINER",
        "ComputeType": "BUILD_GENERAL1_SMALL",
        "Image": "aws/codebuild/java:openjdk-8",
        "EnvironmentVariables": [
          {
            "Name": "varName",
            "Value": "varValue"
          }
        ]
      },
      "Source": {
        "Location": "codebuild-demo-test/0123ab9a371ebf0187b0fe5614fbb72c",
        "Type": "S3"
      },
      "TimeoutInMinutes": 10,
      "Tags": [
        {
          "Key": "Key1",
          "Value": "Value1"
        },
        {
          "Key": "Key2",
          "Value": "Value2"
        }
      ]
    }
  }
}

YAML

Project:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: myProjectName
    Description: A description about my project
    ServiceRole: !GetAtt ServiceRole.Arn
    Artifacts:
      Type: no_artifacts
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/java:openjdk-8
      EnvironmentVariables:
      - Name: varName
        Value: varValue
    Source:
      Location: codebuild-demo-test/0123ab9a371ebf0187b0fe5614fbb72c
      Type: S3
    TimeoutInMinutes: 10
    Tags:
      - Key: Key1
        Value: Value1
      - Key: Key2
        Value: Value2

The following example creates a project that caches build dependencies in Amazon S3
                        and uses resources in an Amazon VPC.

JSON

{
  "Resources": {
    "CodeBuildProject": {
      "Type": "AWS::CodeBuild::Project",
      "Properties": {
        "ServiceRole": {
          "Ref": "CodeBuildRole"
        },
        "Artifacts": {
          "Type": "CODEPIPELINE"
        },
        "Environment": {
          "Type": "LINUX_CONTAINER",
          "ComputeType": "BUILD_GENERAL1_SMALL",
          "Image": "aws/codebuild/ubuntu-base:14.04",
          "EnvironmentVariables": [
            {
              "Name": "varName1",
              "Value": "varValue1"
            },
            {
              "Name": "varName2",
              "Value": "varValue2",
              "Type": "PLAINTEXT"
            },
            {
              "Name": "varName3",
              "Value": "/CodeBuild/testParameter",
              "Type": "PARAMETER_STORE"
            }
          ]
        },
        "Source": {
          "Type": "CODEPIPELINE"
        },
        "TimeoutInMinutes": 10,
        "VpcConfig": {
          "VpcId": {
            "Ref": "CodeBuildVPC"
          },
          "Subnets": [
            {
              "Ref": "CodeBuildSubnet"
            }
          ],
          "SecurityGroupIds": [
            {
              "Ref": "CodeBuildSecurityGroup"
            }
          ]
        },
        "Cache": {
          "Type": "S3",
          "Location": "mybucket/prefix"
        }
      }
    },
    "CodeBuildRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Statement": [
            {
              "Action": [
                "sts:AssumeRole"
              ],
              "Effect": "Allow",
              "Principal": {
                "Service": [
                  "codebuild.amazonaws.com"
                ]
              }
            }
          ],
          "Version": "2012-10-17"
        },
        "Path": "/",
        "Policies": [
          {
            "PolicyName": "CodeBuildAccess",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Action": [
                    "logs:*",
                    "ec2:CreateNetworkInterface",
                    "ec2:DescribeNetworkInterfaces",
                    "ec2:DeleteNetworkInterface",
                    "ec2:DescribeSubnets",
                    "ec2:DescribeSecurityGroups",
                    "ec2:DescribeDhcpOptions",
                    "ec2:DescribeVpcs",
                    "ec2:CreateNetworkInterfacePermission"
                  ],
                  "Effect": "Allow",
                  "Resource": "*"
                }
              ]
            }
          }
        ]
      }
    },
    "CodeBuildVPC": {
      "Type": "AWS::EC2::VPC",
      "Properties": {
        "CidrBlock": "10.0.0.0/16",
        "EnableDnsSupport": "true",
        "EnableDnsHostnames": "true",
        "Tags": [
          {
            "Key": "name",
            "Value": "codebuild"
          }
        ]
      }
    },
    "CodeBuildSubnet": {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "VpcId": {
          "Ref": "CodeBuildVPC"
        },
        "CidrBlock": "10.0.1.0/24"
      }
    },
    "CodeBuildSecurityGroup": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupName": "Codebuild Internet Group",
        "GroupDescription": "CodeBuild SecurityGroup",
        "VpcId": {
          "Ref": "CodeBuildVPC"
        }
      }
    }
  }
}

YAML

Resources:
  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      ServiceRole: !Ref CodeBuildRole
      Artifacts:
        Type: CODEPIPELINE
      Environment:
        Type: LINUX_CONTAINER
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/ubuntu-base:14.04
        EnvironmentVariables:
          - Name: varName1
            Value: varValue1
          - Name: varName2
            Value: varValue2
            Type: PLAINTEXT
          - Name: varName3
            Value: /CodeBuild/testParameter
            Type: PARAMETER_STORE
      Source:
        Type: CODEPIPELINE
      TimeoutInMinutes: 10
      VpcConfig:
        VpcId: !Ref CodeBuildVPC
        Subnets: [!Ref CodeBuildSubnet]
        SecurityGroupIds: [!Ref CodeBuildSecurityGroup]
      Cache:
        Type: S3
        Location: mybucket/prefix
  CodeBuildRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Action: ['sts:AssumeRole']
          Effect: Allow
          Principal:
            Service: [codebuild.amazonaws.com]
        Version: '2012-10-17'
      Path: /
      Policies:
        - PolicyName: CodeBuildAccess
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Action:
                - 'logs:*'
                - 'ec2:CreateNetworkInterface'
                - 'ec2:DescribeNetworkInterfaces'
                - 'ec2:DeleteNetworkInterface'
                - 'ec2:DescribeSubnets'
                - 'ec2:DescribeSecurityGroups'
                - 'ec2:DescribeDhcpOptions'
                - 'ec2:DescribeVpcs'
                - 'ec2:CreateNetworkInterfacePermission'
                Effect: Allow
                Resource: '*'
  CodeBuildVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      Tags:
        - Key: name
          Value: codebuild
  CodeBuildSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId:
        Ref: CodeBuildVPC
      CidrBlock: 10.0.1.0/24
  CodeBuildSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: Codebuild Internet Group
      GroupDescription: 'CodeBuild SecurityGroup'
      VpcId: !Ref CodeBuildVPC

See Also

                                    CreateProject in the AWS CodeBuild API Reference


text:
import json
import os
import unittest

import codacy.reporter

HERE = os.path.abspath(os.path.dirname(__file__))

def _file_location(*args):
    return os.path.join(HERE, *args)

class ReporterTests(unittest.TestCase):
    def compare_parse_result(self, generated, expected_filename):
        def file_get_contents(filename):
            with open(filename) as f:
                return f.read()

        def to_utf8(d):
            if type(d) is dict:
                result = {}
                for key, value in d.items():
                    result[to_utf8(key)] = to_utf8(value)
            elif type(d) is unicode:
                return d.encode('utf8')
            else:
                return d

        json_content = file_get_contents(expected_filename)
        expected = json.loads(json_content)

        self.assertEqual(to_utf8(generated), to_utf8(expected))

    def test_parser_coverage3(self):
        self.maxDiff = None

        parsed = codacy.reporter.parse_report_file(
            _file_location('coverage3', 'cobertura.xml'), '')

        rounded = codacy.reporter.merge_and_round_reports([parsed])

        self.compare_parse_result(rounded,
                                  _file_location('coverage3', 'coverage.json'))

    def test_parser_coverage4(self):
        self.maxDiff = None

        parsed = codacy.reporter.parse_report_file(
            _file_location('coverage4', 'cobertura.xml'), '')

        rounded = codacy.reporter.merge_and_round_reports([parsed])

        self.compare_parse_result(rounded,
                                  _file_location('coverage4', 'coverage.json'))

    def test_parser_git_filepath(self):
        self.maxDiff = None

        parsed = codacy.reporter.parse_report_file(
            _file_location('filepath', 'cobertura.xml.tpl'), '')

        rounded = codacy.reporter.merge_and_round_reports([parsed])

        self.compare_parse_result(rounded,
                                  _file_location('filepath', 'coverage.json'))

    def test_merge(self):
        self.maxDiff = None

        generated3 = codacy.reporter.parse_report_file(
            _file_location('coverage-merge', 'cobertura.3.xml'), '')
        generated4 = codacy.reporter.parse_report_file(
            _file_location('coverage-merge', 'cobertura.4.xml'), '')

        result = codacy.reporter.merge_and_round_reports([generated3, generated4])

        self.compare_parse_result(result, _file_location('coverage-merge', 'coverage-merge.json'))

if __name__ == '__main__':
    unittest.main()


text:
title: <init> -
---
//[kotlin-util](../../index.md)/[it.czerwinski.kotlin.util](../index.md)/[LeftProjection](index.md)/[<init>](-init-.md)

# <init>
[Kotlin utilities]
Content
fun <[L](index.md) : [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?, [R](index.md) : [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?> [<init>](-init-.md)(either: [Either](../-either/index.md)<[L](index.md), [R](index.md)>)


text:
ActionController::Base.session = {
  :key         => '_eisq_session',
  :secret      => 'f71b916ade6b24acbf2931753298ec38ee37a2dd303d3049333b5b4647b31ffc2094c5330924e67b3d53ee28b1537ea27225257accc43a6e97762dcc2aeef84b'
}

# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store


text:
/**
 * CFS Performance Monitor Source Code Search Criteria Dialog
 */
package CFSPerformanceMonitor;

import static CFSPerformanceMonitor.CPMConstants.BUTTON_FONT;
import static CFSPerformanceMonitor.CPMConstants.CANCEL_ICON;
import static CFSPerformanceMonitor.CPMConstants.CANCEL_OPTION;
import static CFSPerformanceMonitor.CPMConstants.DEFAULT_FILE_EXTENSION;
import static CFSPerformanceMonitor.CPMConstants.DEFAULT_PERF_ID_SUFFIX;
import static CFSPerformanceMonitor.CPMConstants.DEFAULT_SUBFOLDERS;
import static CFSPerformanceMonitor.CPMConstants.LABEL_FONT_BOLD;
import static CFSPerformanceMonitor.CPMConstants.LABEL_FONT_PLAIN;
import static CFSPerformanceMonitor.CPMConstants.LABEL_HORIZONTAL_SPACING;
import static CFSPerformanceMonitor.CPMConstants.LABEL_VERTICAL_SPACING;
import static CFSPerformanceMonitor.CPMConstants.OK_ICON;
import static CFSPerformanceMonitor.CPMConstants.OK_OPTION;
import static CFSPerformanceMonitor.CPMConstants.RESET_ICON;
import static CFSPerformanceMonitor.CPMConstants.SEARCH_FILE_EXTENSION;
import static CFSPerformanceMonitor.CPMConstants.SEARCH_PERF_ID_SUFFIX;
import static CFSPerformanceMonitor.CPMConstants.SEARCH_SUBFOLDERS;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;

/******************************************************************************
 * CFS Performance Monitor source code search criteria dialog class
 *****************************************************************************/
@SuppressWarnings("serial")
public class CPMSourceSearchDialog extends CPMDialogHandler
{
    private final CPMMain perfMain;

    // Components that need to be accessed globally
    private List<JCheckBox> subfolderCheckBox;
    private JTextField extensionField;
    private JTextField suffixField;

    // Folder containing the subfolders to search in for IDs
    private final File folder;

    // Button selected by the user
    private int buttonSelected;

    /**************************************************************************
     * Search criteria dialog class constructor
     *
     * @param perfMain
     *            main class
     *************************************************************************/
    protected CPMSourceSearchDialog(CPMMain perfMain,
                                    File folder)
    {
        this.perfMain = perfMain;
        this.folder = folder;

        // Create the search criteria dialog
        initialize();
    }

    /**************************************************************************
     * Return the button selected
     *
     * @return Selected button (OK_OPTION or CANCEL_OPTION)
     *************************************************************************/
    protected int getButtonSelected()
    {
        return buttonSelected;
    }

    /**************************************************************************
     * Create the search criteria dialog
     *************************************************************************/
    private void initialize()
    {
        // Create a border for the text fields
        Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED,
                                                        Color.LIGHT_GRAY,
                                                        Color.GRAY);

        // Set the initial layout manager characteristics
        GridBagConstraints gbc = new GridBagConstraints(0,
                                                        0,
                                                        GridBagConstraints.RELATIVE,
                                                        1,
                                                        0.0,
                                                        0.0,
                                                        GridBagConstraints.LINE_START,
                                                        GridBagConstraints.NONE,
                                                        new Insets(0,
                                                                   LABEL_HORIZONTAL_SPACING,
                                                                   LABEL_VERTICAL_SPACING * 2,
                                                                   LABEL_HORIZONTAL_SPACING),
                                                        0,
                                                        0);

        // Create the search criteria components ------------------------------
        JPanel searchPanel = new JPanel(new GridBagLayout());

        // Set up the subfolders label
        JLabel subfoldersLabel = new JLabel("Search subfolders");
        subfoldersLabel.setFont(LABEL_FONT_BOLD);
        searchPanel.add(subfoldersLabel, gbc);

        // Create a list of check boxes showing the target folder's subfolders.
        // Get the list of files and folders in the target folder and sort them
        // alphabetically
        File[] folderItems = folder.listFiles();
        Arrays.sort(folderItems);

        // Create a panel to contain the check boxes
        JPanel subPanel = new JPanel(new GridLayout(1, 0));

        // Create the check box array list
        subfolderCheckBox = new ArrayList<JCheckBox>();

        // Step through the list of files & folders in the target folder
        for (File item : folderItems)
        {
            // Check if this if a folder and not a file
            if (item.isDirectory())
            {
                // Create a check box with the subfolder name as the label and
                // add the check box to the panel
                subfolderCheckBox.add(new JCheckBox(item.getName()));
                subPanel.add(subfolderCheckBox.get(subfolderCheckBox.size() - 1));
            }
        }

        // Check if no subfolders exist in the target folder
        if (subfolderCheckBox.size() == 0)
        {
            // Indicate that the files within the target folder will be checked
            // for IDs
            JLabel allLabel = new JLabel("<html><i>all files in selected folder");
            allLabel.setFont(LABEL_FONT_PLAIN);
            subPanel.add(allLabel);
        }
        // At least one subfolder exists
        else
        {
            // Set the number of rows in which to group the subfolder check
            // boxes. This puts them into a more or less square grid
            ((GridLayout) subPanel.getLayout()).setColumns((int) Math.sqrt(subfolderCheckBox.size()));
            ((GridLayout) subPanel.getLayout()).setRows(0);
        }

        // Set the selection statuses of the check boxes based on the
        // preferences information
        setSubfolderSelected();

        // Place the subfolder search panel into the dialog
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridx++;
        searchPanel.add(subPanel, gbc);

        // Set up the file extension label
        JLabel extensionLabel = new JLabel("File extension");
        extensionLabel.setFont(LABEL_FONT_BOLD);
        gbc.fill = GridBagConstraints.NONE;
        gbc.gridwidth = GridBagConstraints.RELATIVE;
        gbc.gridx = 0;
        gbc.gridy++;
        searchPanel.add(extensionLabel, gbc);

        // Create the file extension text field
        extensionField = new JTextField(" "
                                        + perfMain.getPreferences().get(SEARCH_FILE_EXTENSION,
                                                                        DEFAULT_FILE_EXTENSION),
                                        10);
        extensionField.setFont(LABEL_FONT_PLAIN);
        extensionField.setBorder(border);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridx++;
        searchPanel.add(extensionField, gbc);

        // Create the performance ID suffix label
        JLabel suffixLabel = new JLabel("Performance ID suffix");
        suffixLabel.setFont(LABEL_FONT_BOLD);
        gbc.fill = GridBagConstraints.NONE;
        gbc.gridwidth = GridBagConstraints.RELATIVE;
        gbc.gridx = 0;
        gbc.gridy++;
        searchPanel.add(suffixLabel, gbc);

        // Create the suffix text field
        suffixField = new JTextField(" "
                                     + perfMain.getPreferences().get(SEARCH_PERF_ID_SUFFIX,
                                                                     DEFAULT_PERF_ID_SUFFIX));
        suffixField.setFont(LABEL_FONT_PLAIN);
        suffixField.setBorder(border);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridx++;
        searchPanel.add(suffixField, gbc);

        // Add a separator
        gbc.gridx = 0;
        gbc.gridy++;
        gbc.insets.set(0,
                       LABEL_HORIZONTAL_SPACING,
                       0,
                       LABEL_HORIZONTAL_SPACING);
        searchPanel.add(new JSeparator(JSeparator.HORIZONTAL), gbc);

        // Create a panel to hold the dialog Okay, Default, and Cancel buttons
        JPanel buttonPanel = new JPanel();

        // Create the Okay button
        JButton btnOkay = new JButton("Okay",
                                      new ImageIcon(getClass().getResource(OK_ICON)));
        btnOkay.setFont(BUTTON_FONT);
        btnOkay.setMnemonic('O');
        buttonPanel.add(btnOkay);

        // Add a listener for the Okay button
        btnOkay.addActionListener(new ActionListener()
        {
            /******************************************************************
             * Apply the search criteria changes
             *****************************************************************/
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                // Set the button selected to Okay
                setButtonSelected(OK_OPTION);

                // Check that the search criteria are valid
                if (verifySelection())
                {
                    // Build the list of subfolders to search from the selected
                    // check boxes
                    String subfolderNames = "";

                    // Check if no subfolders exist in the target folder
                    if (subfolderCheckBox.size() == 0)
                    {
                        // Set the target folder an the subfolder to check;
                        // i.e., search through the files within the target
                        // folder
                        subfolderNames = "../" + folder.getName();
                    }
                    // At least one subfolder exists
                    else
                    {
                        // Step through the subfolder check boxes
                        for (JCheckBox box : subfolderCheckBox)
                        {
                            // Check if the subfolder is selected
                            if (box.isSelected())
                            {
                                // Add the subfolder to the search list
                                subfolderNames += box.getText() + ",";
                            }
                        }

                        // Remove the trailing comma
                        subfolderNames = subfolderNames.substring(0,
                                                                  subfolderNames.length() - 1);
                    }

                    // Store the search criteria in the program preferences
                    // backing store
                    perfMain.getPreferences().put(SEARCH_SUBFOLDERS,
                                                  subfolderNames);
                    perfMain.getPreferences().put(SEARCH_FILE_EXTENSION,
                                                  extensionField.getText().trim());
                    perfMain.getPreferences().put(SEARCH_PERF_ID_SUFFIX,
                                                  suffixField.getText().trim());

                    // Close the dialog
                    closeDialog();
                }
            }
        });

        // Create the Default button
        JButton btnDefault = new JButton("Default",
                                         new ImageIcon(getClass().getResource(RESET_ICON)));
        btnDefault.setFont(BUTTON_FONT);
        btnDefault.setMnemonic('D');
        buttonPanel.add(btnDefault);

        // Add a listener for the Default button
        btnDefault.addActionListener(new ActionListener()
        {
            /******************************************************************
             * Set the search criteria to the default values
             *****************************************************************/
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                // Update the check boxes and text fields to show the default
                // values
                setSubfolderSelected();
                extensionField.setText(" " + DEFAULT_FILE_EXTENSION);
                suffixField.setText(" " + DEFAULT_PERF_ID_SUFFIX);
            }
        });

        // Create the Cancel button
        JButton btnCancel = new JButton("Cancel",
                                        new ImageIcon(getClass().getResource(CANCEL_ICON)));
        btnCancel.setFont(BUTTON_FONT);
        btnCancel.setMnemonic('C');
        buttonPanel.add(btnCancel);

        // Add a listener for the Cancel button
        btnCancel.addActionListener(new ActionListener()
        {
            /******************************************************************
             * Cancel changing the search criteria
             *****************************************************************/
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                // Set the button selected to Cancel
                setButtonSelected(CANCEL_OPTION);
                closeDialog();
            }
        });

        // Display the search criteria dialog and wait for the user to select
        // the Okay or Cancel button
        buttonSelected = showOptionsDialog(perfMain.getMainFrame(),
                                           searchPanel,
                                           buttonPanel,
                                           "Search Criteria",
                                           false);
    }

    /**************************************************************************
     * Set the state of the subfolder check boxes based on the stored
     * preference information
     *************************************************************************/
    private void setSubfolderSelected()
    {
        // Get the subfolder preference information and split it into separate
        // subfolder names
        String[] subfolderPrefs = perfMain.getPreferences().get(SEARCH_SUBFOLDERS,
                                                                DEFAULT_SUBFOLDERS).split(",");

        // Step through each subfolder check box
        for (JCheckBox box : subfolderCheckBox)
        {
            // Assume the box is not selected
            boolean selected = false;

            // Step through the preference subfolder names
            for (String subfolderName : subfolderPrefs)
            {
                // Check if the preference name matches the check box name
                if (subfolderName.toLowerCase().equals(box.getText().toLowerCase()))
                {
                    // Select the check box and exit the loop
                    selected = true;
                    break;
                }
            }

            // Set the state of this check box
            box.setSelected(selected);
        }
    }

    /**************************************************************************
     * Verify that the search criteria are valid
     *
     * @return true if the search criteria are valid
     *************************************************************************/
    @Override
    protected boolean verifySelection()
    {
        // Assume the inputs contain an error
        boolean validInputs = false;

        // Get the criteria from the input fields, and remove leading and
        // trailing white space
        String extension = extensionField.getText().trim();
        String suffix = suffixField.getText().trim();

        // Assume none of the check boxes are selected
        boolean noSubfolderSelected = true;

        // Step through the subfolder check boxes
        for (JCheckBox box : subfolderCheckBox)
        {
            // Check if the box is selected
            if (box.isSelected())
            {
                // Clear the "none selected" flag and exit the loop
                noSubfolderSelected = false;
                break;
            }
        }

        // Check if the target folder contains one or more subfolders and none
        // is selected
        if (noSubfolderSelected && subfolderCheckBox.size() != 0)
        {
            // Let the user know that a subfolder must be selected
            new CPMDialogHandler().showMessageDialog(this,
                                                     "<html><b>At least one subfolder must be selected",
                                                     "Invalid Criteria",
                                                     JOptionPane.ERROR_MESSAGE,
                                                     OK_OPTION);
        }
        // Check if the extension or suffix field is empty
        else if (extension.equals("")
                 || suffix.equals(""))
        {
            // Let the user know that the fields can't be empty
            new CPMDialogHandler().showMessageDialog(this,
                                                     "<html><b>Search criteria fields cannot be blank",
                                                     "Invalid Criteria",
                                                     JOptionPane.ERROR_MESSAGE,
                                                     OK_OPTION);
        }
        // Check if the file extension or ID suffix fields have spaces or
        // commas
        else if (extension.contains(" ")
                 || extension.contains(",")
                 || suffix.contains(" ")
                 || suffix.contains(","))
        {
            // Let the user know that the extension and suffix fields can't
            // contain spaces or commas
            new CPMDialogHandler().showMessageDialog(this,
                                                     "<html><b>File extension and ID suffix<br>cannot contain spaces or commas",
                                                     "Invalid Criteria",
                                                     JOptionPane.ERROR_MESSAGE,
                                                     OK_OPTION);
        }
        // Inputs are valid
        else
        {
            // set the valid inputs flag
            validInputs = true;
        }

        return validInputs;
    }
}


text:
using System;
using System.Collections.Generic;
using Chloe.Server.Data.Contracts;
using Chloe.Server.Dtos;
using Chloe.Server.Services.Contracts;
using System.Data.Entity;
using System.Linq;
using Chloe.Server.Models;

namespace Chloe.Server.Services
{
    public class ScoringFunctionInterpolationService : IScoringFunctionInterpolationService
    {
        public ScoringFunctionInterpolationService(IChloeUow uow, ICacheProvider cacheProvider)
        {
            this.uow = uow;
            this.repository = uow.ScoringFunctionInterpolations;
            this.cache = cacheProvider.GetCache();
        }

        public ScoringFunctionInterpolationAddOrUpdateResponseDto AddOrUpdate(ScoringFunctionInterpolationAddOrUpdateRequestDto request)
        {
            var entity = repository.GetAll()
                .FirstOrDefault(x => x.Id == request.Id && x.IsDeleted == false);
            if (entity == null) repository.Add(entity = new ScoringFunctionInterpolation());
            entity.Name = request.Name;
            uow.SaveChanges();
            return new ScoringFunctionInterpolationAddOrUpdateResponseDto(entity);
        }

        public dynamic Remove(int id)
        {
            var entity = repository.GetById(id);
            entity.IsDeleted = true;
            uow.SaveChanges();
            return id;
        }

        public ICollection<ScoringFunctionInterpolationDto> Get()
        {
            ICollection<ScoringFunctionInterpolationDto> response = new HashSet<ScoringFunctionInterpolationDto>();
            var entities = repository.GetAll().Where(x => x.IsDeleted == false).ToList();
            foreach(var entity in entities) { response.Add(new ScoringFunctionInterpolationDto(entity)); }
            return response;
        }

        public ScoringFunctionInterpolationDto GetById(int id)
        {
            return new ScoringFunctionInterpolationDto(repository.GetAll().Where(x => x.Id == id && x.IsDeleted == false).FirstOrDefault());
        }

        protected readonly IChloeUow uow;
        protected readonly IRepository<ScoringFunctionInterpolation> repository;
        protected readonly ICache cache;
    }
}


text:
#include "GlobalShortcut.h"
#include "ConfigDialog.h"
#include "Global.h"

#include <QX11Info>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/extensions/XInput.h>
#include <X11/Xutil.h>
#ifdef Q_OS_LINUX
#include <linux/input.h>
#include <fcntl.h>
#endif

#define NUM_BUTTONS 0x2ff

class GlobalShortcutX : public GlobalShortcutEngine {
	private:
		Q_OBJECT
		Q_DISABLE_COPY(GlobalShortcutX)
	public:
		Display *display;
		volatile bool bRunning;
		bool bXInput;
		QSet<QString> qsKeyboards;
		QMap<QString, QFile *> qmInputDevices;
		QMap<XID, XDevice *> qmXDevices;

		GlobalShortcutX();
		~GlobalShortcutX();
		void run();
		QString buttonName(const QVariant &);

		int iKeyPress, iKeyRelease, iButtonPress, iButtonRelease;

		void initXInput();
	public slots:
		void displayReadyRead(int);
		void inputReadyRead(int);
		void directoryChanged(const QString &);
};


text:
package org.apache.felix.ipojo.test.scenarios.component;

public class ParentClass2 extends SuperParentClass {

    public ParentClass2(String n) {
        super(n);
    }

}


text:
struct IMemorySection
{
	virtual ~IMemorySection () {};
	virtual size_t address () const = 0;
	virtual size_t size () const = 0;
	virtual bool indexInRange (size_t i) const = 0;
	virtual uint8_t operator[] (size_t i) const = 0;
	virtual void relocateTo (size_t targetAddress) = 0;
};

#endif // __IMEMORYSECTION_H


text:
ACCEPTED

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

#### Published in
Lyon Médical 141: 369-378 (1928)

#### Original name
Microsporum gypseum var. gypseum (E. Bodin) Guiart & Grigoraki, 1928

### Remarks
null


text:
struct TreeNode;
struct Tree;

Tree *createTree();
bool addTreeNode(Tree *tree, int x);
TreeNode **search(Tree *tree, int x);
bool removeTreeNode(Tree *tree, int x);
void clearTree(Tree *tree);
void printTree(Tree *tree);
void printInfix(Tree *tree);
void printLargestToSmallest(Tree *tree);


text:
"""
If you have two expressions containing unification variables, these expressions
can be "unified" if there exists an assignment to all unification variables
such that the two expressions are equal.

For instance, [5, A, B] and [A, C, 9] can be unified if A=C=5 and B=9,
yielding [5, 5, 9].
[5, [A, B]] and [A, [1, 2]] cannot be unified because there is no value for A
that satisfies the constraints. That's useful for pattern matching.

"""
from __future__ import absolute_import, print_function, division
from copy import copy

from functools import partial
from theano.gof.utils import ANY_TYPE, comm_guard, FALL_THROUGH, iteritems

################################

class Variable:
    """
    Serves as a base class of variables for the purpose of unification.
    "Unification" here basically means matching two patterns, see the
    module-level docstring.

    Behavior for unifying various types of variables should be added as
    overloadings of the 'unify' function.

    Notes
    -----
    There are two Variable classes in theano and this is the more rarely used
    one.
    This class is used internally by the PatternSub optimization,
    and possibly other subroutines that have to perform graph queries.
    If that doesn't sound like what you're doing, the Variable class you
    want is probably theano.gof.graph.Variable.

    """
    def __init__(self, name="?"):
        self.name = name

    def __str__(self):
        return (self.__class__.__name__ + "(" +
                ", ".join("%s=%s" % (key, value)
                          for key, value in iteritems(self.__dict__)) + ")")

    def __repr__(self):
        return str(self)

class FreeVariable(Variable):
    """
    This Variable can take any value.

    """

    pass

class BoundVariable(Variable):
    """
    This Variable is bound to a value accessible via the value field.

    """

    def __init__(self, name, value):
        self.name = name
        self.value = value

class OrVariable(Variable):
    """
    This Variable could be any value from a finite list of values,
    accessible via the options field.

    """

    def __init__(self, name, options):
        self.name = name
        self.options = options

class NotVariable(Variable):
    """
    This Variable can take any value but a finite amount of forbidden
    values, accessible via the not_options field.

    """

    def __init__(self, name, not_options):
        self.name = name
        self.not_options = not_options

class VariableInList:  # not a subclass of Variable
    """
    This special kind of variable is matched against a list and unifies
    an inner Variable to an OrVariable of the values in the list.
    For example, if we unify VariableInList(FreeVariable('x')) to [1,2,3],
    the 'x' variable is unified to an OrVariable('?', [1,2,3]).

    """

    def __init__(self, variable):
        self.variable = variable

################################

_all = {}

def var_lookup(vartype, name, *args, **kwargs):
    sig = (vartype, name)
    if sig in _all:
        return _all[sig]
    else:
        v = vartype(name, *args)
        _all[sig] = v
        return v

Var = partial(var_lookup, FreeVariable)
V = Var
OrV = partial(var_lookup, OrVariable)
NV = partial(var_lookup, NotVariable)

################################

class Unification:
    """
    This class represents a possible unification of a group of variables
    with each other or with tangible values.
    Parameters
    ----------
    inplace : bool
        If inplace is False, the merge method will return a new Unification
        that is independent from the previous one (which allows backtracking).

    """

    def __init__(self, inplace=False):
        self.unif = {}
        self.inplace = inplace

    def merge(self, new_best, *vars):
        """
        Links all the specified vars to a Variable that represents their
        unification.

        """
        if self.inplace:
            U = self
        else:
            # Copy all the unification data.
            U = Unification(self.inplace)
            for var, (best, pool) in iteritems(self.unif):
                # The pool of a variable is the set of all the variables that
                # are unified to it (all the variables that must have the same
                # value). The best is the Variable that represents a set of
                # values common to all the variables in the pool.
                U.unif[var] = (best, pool)
        # We create a new pool for our new set of unified variables, initially
        # containing vars and new_best
        new_pool = set(vars)
        new_pool.add(new_best)
        for var in copy(new_pool):
            best, pool = U.unif.get(var, (var, set()))
            # We now extend the new pool to contain the pools of all the variables.
            new_pool.update(pool)
        # All variables get the new pool.
        for var in new_pool:
            U.unif[var] = (new_best, new_pool)
        return U

    def __getitem__(self, v):
        """
        For a variable v, returns a Variable that represents the tightest
        set of possible values it can take.

        """
        return self.unif.get(v, (v, None))[0]

################################

def unify_walk(a, b, U):
    """
    unify_walk(a, b, U) returns an Unification where a and b are unified,
    given the unification that already exists in the Unification U. If the
    unification fails, it returns False.

    There are two ways to expand the functionality of unify_walk. The first way
    is:
    @comm_guard(type_of_a, type_of_b)
    def unify_walk(a, b, U):
        ...
    A function defined as such will be executed whenever the types of a and b
    match the declaration. Note that comm_guard automatically guarantees that
    your function is commutative: it will try to match the types of a, b or
    b, a.
    It is recommended to define unify_walk in that fashion for new types of
    Variable because different types of Variable interact a lot with each other,
    e.g. when unifying an OrVariable with a NotVariable, etc. You can return
    the special marker FALL_THROUGH to indicate that you want to relay execution
    to the next match of the type signature. The definitions of unify_walk are
    tried in the reverse order of their declaration.

    Another way is to override __unify_walk__ in an user-defined class.

    Limitations: cannot embed a Variable in another (the functionality could
    be added if required)

    Here is a list of unification rules with their associated behavior:

    """
    if a.__class__ != b.__class__:
        return False
    elif a == b:
        return U
    else:
        return False

@comm_guard(FreeVariable, ANY_TYPE)  # noqa
def unify_walk(fv, o, U):
    """
    FreeV is unified to BoundVariable(other_object).

    """
    v = BoundVariable("?", o)
    return U.merge(v, fv)

@comm_guard(BoundVariable, ANY_TYPE)  # noqa
def unify_walk(bv, o, U):
    """
    The unification succeed iff BV.value == other_object.

    """
    if bv.value == o:
        return U
    else:
        return False

@comm_guard(OrVariable, ANY_TYPE)  # noqa
def unify_walk(ov, o, U):
    """
    The unification succeeds iff other_object in OrV.options.

    """
    if o in ov.options:
        v = BoundVariable("?", o)
        return U.merge(v, ov)
    else:
        return False

@comm_guard(NotVariable, ANY_TYPE)  # noqa
def unify_walk(nv, o, U):
    """
    The unification succeeds iff other_object not in NV.not_options.

    """
    if o in nv.not_options:
        return False
    else:
        v = BoundVariable("?", o)
        return U.merge(v, nv)

@comm_guard(FreeVariable, Variable)  # noqa
def unify_walk(fv, v, U):
    """
    Both variables are unified.

    """
    v = U[v]
    return U.merge(v, fv)

@comm_guard(BoundVariable, Variable)  # noqa
def unify_walk(bv, v, U):
    """
    V is unified to BV.value.

    """
    return unify_walk(v, bv.value, U)

@comm_guard(OrVariable, OrVariable)  # noqa
def unify_walk(a, b, U):
    """
    OrV(list1) == OrV(list2) == OrV(intersection(list1, list2))

    """
    opt = a.options.intersection(b.options)
    if not opt:
        return False
    elif len(opt) == 1:
        v = BoundVariable("?", opt[0])
    else:
        v = OrVariable("?", opt)
    return U.merge(v, a, b)

@comm_guard(NotVariable, NotVariable)  # noqa
def unify_walk(a, b, U):
    """
    NV(list1) == NV(list2) == NV(union(list1, list2))

    """
    opt = a.not_options.union(b.not_options)
    v = NotVariable("?", opt)
    return U.merge(v, a, b)

@comm_guard(OrVariable, NotVariable)  # noqa
def unify_walk(o, n, U):
    """
    OrV(list1) == NV(list2) == OrV(list1 \ list2)

    """
    opt = [x for x in o.options if x not in n.not_options]
    if not opt:
        return False
    elif len(opt) == 1:
        v = BoundVariable("?", opt[0])
    else:
        v = OrVariable("?", opt)
    return U.merge(v, o, n)

@comm_guard(VariableInList, (list, tuple))  # noqa
def unify_walk(vil, l, U):
    """
    Unifies VIL's inner Variable to OrV(list).

    """
    v = vil.variable
    ov = OrVariable("?", l)
    return unify_walk(v, ov, U)

@comm_guard((list, tuple), (list, tuple))  # noqa
def unify_walk(l1, l2, U):
    """
    Tries to unify each corresponding pair of elements from l1 and l2.

    """
    if len(l1) != len(l2):
        return False
    for x1, x2 in zip(l1, l2):
        U = unify_walk(x1, x2, U)
        if U is False:
            return False
    return U

@comm_guard(dict, dict)  # noqa
def unify_walk(d1, d2, U):
    """
    Tries to unify values of corresponding keys.

    """
    for (k1, v1) in iteritems(d1):
        if k1 in d2:
            U = unify_walk(v1, d2[k1], U)
            if U is False:
                return False
    return U

@comm_guard(ANY_TYPE, ANY_TYPE)  # noqa
def unify_walk(a, b, U):
    """
    Checks for the existence of the __unify_walk__ method for one of
    the objects.

    """
    if (not isinstance(a, Variable) and
            not isinstance(b, Variable) and
            hasattr(a, "__unify_walk__")):
        return a.__unify_walk__(b, U)
    else:
        return FALL_THROUGH

@comm_guard(Variable, ANY_TYPE)  # noqa
def unify_walk(v, o, U):
    """
    This simply checks if the Var has an unification in U and uses it
    instead of the Var. If the Var is already its tighest unification,
    falls through.

    """
    best_v = U[v]
    if v is not best_v:
        return unify_walk(o, best_v, U)  # reverse argument order so if o is a Variable this block of code is run again
    else:
        return FALL_THROUGH  # call the next version of unify_walk that matches the type signature

################################

class FVar:

    def __init__(self, fn, *args):
        self.fn = fn
        self.args = args

    def __call__(self, u):
        return self.fn(*[unify_build(arg, u) for arg in self.args])

################################

def unify_merge(a, b, U):
    return a

@comm_guard(Variable, ANY_TYPE)  # noqa
def unify_merge(v, o, U):
    return v

@comm_guard(BoundVariable, ANY_TYPE)  # noqa
def unify_merge(bv, o, U):
    return bv.value

@comm_guard(VariableInList, (list, tuple))  # noqa
def unify_merge(vil, l, U):
    return [unify_merge(x, x, U) for x in l]

@comm_guard((list, tuple), (list, tuple))  # noqa
def unify_merge(l1, l2, U):
    return [unify_merge(x1, x2, U) for x1, x2 in zip(l1, l2)]

@comm_guard(dict, dict)  # noqa
def unify_merge(d1, d2, U):
    d = d1.__class__()
    for k1, v1 in iteritems(d1):
        if k1 in d2:
            d[k1] = unify_merge(v1, d2[k1], U)
        else:
            d[k1] = unify_merge(v1, v1, U)
    for k2, v2 in iteritems(d2):
        if k2 not in d1:
            d[k2] = unify_merge(v2, v2, U)
    return d

@comm_guard(FVar, ANY_TYPE)  # noqa
def unify_merge(vs, o, U):
    return vs(U)

@comm_guard(ANY_TYPE, ANY_TYPE)  # noqa
def unify_merge(a, b, U):
    if (not isinstance(a, Variable) and
            not isinstance(b, Variable) and
            hasattr(a, "__unify_merge__")):
        return a.__unify_merge__(b, U)
    else:
        return FALL_THROUGH

@comm_guard(Variable, ANY_TYPE)  # noqa
def unify_merge(v, o, U):
    """
    This simply checks if the Var has an unification in U and uses it
    instead of the Var. If the Var is already its tighest unification,
    falls through.

    """
    best_v = U[v]
    if v is not best_v:
        return unify_merge(o, best_v, U)  # reverse argument order so if o is a Variable this block of code is run again
    else:
        return FALL_THROUGH  # call the next version of unify_walk that matches the type signature

################################

def unify_build(x, U):
    return unify_merge(x, x, U)

################################

def unify(a, b):
    U = unify_walk(a, b, Unification())
    if not U:
        return None, False
    else:
        return unify_merge(a, b, U), U

################################

if __name__ == "__main__":

    vx = NotVariable("x", ["big", "bones"])
    vy = OrVariable("y", ["hello", "big"])
    vz = V("z")
    va = V("a")
    vl = VariableInList(vz)

    pattern1 = dict(hey=vx, ulala=va, a=1)
    pattern2 = dict(hey=vy, ulala=10, b=2)

#    pattern1 = ["hello", "big", "bones"]
#    pattern2 = vl

#    pattern1 = [vx]#, "big", "bones"]
#    pattern2 = [vy]#, vy, vz]

    U = unify_walk(pattern1, pattern2, Unification())

    if U:
        print(U[va])
        print(U[vx])
        print(U[vy])
        print(U[vz])
        print(unify_merge(pattern1, pattern2, U))
    else:
        print("no match")

    U = unify_walk((1, 2), (va, va), Unification())
    print(U[va])