text:
#include "config.h"
#include "ScrollableArea.h"

#include "GraphicsContext.h"
#include "GraphicsLayer.h"
#include "FloatPoint.h"
#include "PlatformWheelEvent.h"
#include "ScrollAnimator.h"
#include "ScrollbarTheme.h"
#include <wtf/PassOwnPtr.h>

namespace WebCore {

struct SameSizeAsScrollableArea {
    virtual ~SameSizeAsScrollableArea();
    void* pointer;
    unsigned bitfields : 16;
    IntPoint origin;
};

COMPILE_ASSERT(sizeof(ScrollableArea) == sizeof(SameSizeAsScrollableArea), ScrollableArea_should_stay_small);

ScrollableArea::ScrollableArea()
    : m_constrainsScrollingToContentEdge(true)
    , m_inLiveResize(false)
    , m_verticalScrollElasticity(ScrollElasticityNone)
    , m_horizontalScrollElasticity(ScrollElasticityNone)
    , m_scrollbarOverlayStyle(ScrollbarOverlayStyleDefault)
    , m_scrollOriginChanged(false)
{
}

ScrollableArea::~ScrollableArea()
{
}

ScrollAnimator* ScrollableArea::scrollAnimator() const
{
    if (!m_scrollAnimator)
        m_scrollAnimator = ScrollAnimator::create(const_cast<ScrollableArea*>(this));

    return m_scrollAnimator.get();
}

void ScrollableArea::setScrollOrigin(const IntPoint& origin)
{
    if (m_scrollOrigin != origin) {
        m_scrollOrigin = origin;
        m_scrollOriginChanged = true;
    }
}

bool ScrollableArea::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
{
    ScrollbarOrientation orientation;
    Scrollbar* scrollbar;
    if (direction == ScrollUp || direction == ScrollDown) {
        orientation = VerticalScrollbar;
        scrollbar = verticalScrollbar();
    } else {
        orientation = HorizontalScrollbar;
        scrollbar = horizontalScrollbar();
    }

    if (!scrollbar)
        return false;

    float step = 0;
    switch (granularity) {
    case ScrollByLine:
        step = scrollbar->lineStep();
        break;
    case ScrollByPage:
        step = scrollbar->pageStep();
        break;
    case ScrollByDocument:
        step = scrollbar->totalSize();
        break;
    case ScrollByPixel:
    case ScrollByPrecisePixel:
        step = scrollbar->pixelStep();
        break;
    }

    if (direction == ScrollUp || direction == ScrollLeft)
        multiplier = -multiplier;

    return scrollAnimator()->scroll(orientation, granularity, step, multiplier);
}

void ScrollableArea::scrollToOffsetWithoutAnimation(const FloatPoint& offset)
{
    scrollAnimator()->scrollToOffsetWithoutAnimation(offset);
}

void ScrollableArea::scrollToOffsetWithoutAnimation(ScrollbarOrientation orientation, float offset)
{
    if (orientation == HorizontalScrollbar)
        scrollToOffsetWithoutAnimation(FloatPoint(offset, scrollAnimator()->currentPosition().y()));
    else
        scrollToOffsetWithoutAnimation(FloatPoint(scrollAnimator()->currentPosition().x(), offset));
}

void ScrollableArea::notifyScrollPositionChanged(const IntPoint& position)
{
    scrollPositionChanged(position);
    scrollAnimator()->setCurrentPosition(position);
}

void ScrollableArea::scrollPositionChanged(const IntPoint& position)
{
    IntPoint oldPosition = scrollPosition();
    // Tell the derived class to scroll its contents.
    setScrollOffset(position);

    Scrollbar* verticalScrollbar = this->verticalScrollbar();

    // Tell the scrollbars to update their thumb postions.
    if (Scrollbar* horizontalScrollbar = this->horizontalScrollbar()) {
        horizontalScrollbar->offsetDidChange();
        if (horizontalScrollbar->isOverlayScrollbar() && !hasLayerForHorizontalScrollbar()) {
            if (!verticalScrollbar)
                horizontalScrollbar->invalidate();
            else {
                // If there is both a horizontalScrollbar and a verticalScrollbar,
                // then we must also invalidate the corner between them.
                IntRect boundsAndCorner = horizontalScrollbar->boundsRect();
                boundsAndCorner.setWidth(boundsAndCorner.width() + verticalScrollbar->width());
                horizontalScrollbar->invalidateRect(boundsAndCorner);
            }
        }
    }
    if (verticalScrollbar) {
        verticalScrollbar->offsetDidChange();
        if (verticalScrollbar->isOverlayScrollbar() && !hasLayerForVerticalScrollbar())
            verticalScrollbar->invalidate();
    }

    if (scrollPosition() != oldPosition)
        scrollAnimator()->notifyContentAreaScrolled(scrollPosition() - oldPosition);
}

bool ScrollableArea::handleWheelEvent(const PlatformWheelEvent& wheelEvent)
{
    return scrollAnimator()->handleWheelEvent(wheelEvent);
}

// NOTE: Only called from Internals for testing.
void ScrollableArea::setScrollOffsetFromInternals(const IntPoint& offset)
{
    setScrollOffsetFromAnimation(offset);
}

void ScrollableArea::setScrollOffsetFromAnimation(const IntPoint& offset)
{
    if (requestScrollPositionUpdate(offset))
        return;

    scrollPositionChanged(offset);
}

void ScrollableArea::willStartLiveResize()
{
    if (m_inLiveResize)
        return;
    m_inLiveResize = true;
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->willStartLiveResize();
}

void ScrollableArea::willEndLiveResize()
{
    if (!m_inLiveResize)
        return;
    m_inLiveResize = false;
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->willEndLiveResize();
}

void ScrollableArea::contentAreaWillPaint() const
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->contentAreaWillPaint();
}

void ScrollableArea::mouseEnteredContentArea() const
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->mouseEnteredContentArea();
}

void ScrollableArea::mouseExitedContentArea() const
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->mouseEnteredContentArea();
}

void ScrollableArea::mouseMovedInContentArea() const
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->mouseMovedInContentArea();
}

void ScrollableArea::mouseEnteredScrollbar(Scrollbar* scrollbar) const
{
    scrollAnimator()->mouseEnteredScrollbar(scrollbar);
}

void ScrollableArea::mouseExitedScrollbar(Scrollbar* scrollbar) const
{
    scrollAnimator()->mouseExitedScrollbar(scrollbar);
}

void ScrollableArea::contentAreaDidShow() const
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->contentAreaDidShow();
}

void ScrollableArea::contentAreaDidHide() const
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->contentAreaDidHide();
}

void ScrollableArea::finishCurrentScrollAnimations() const
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->finishCurrentScrollAnimations();
}

void ScrollableArea::didAddScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
{
    if (orientation == VerticalScrollbar)
        scrollAnimator()->didAddVerticalScrollbar(scrollbar);
    else
        scrollAnimator()->didAddHorizontalScrollbar(scrollbar);

    // <rdar://problem/9797253> AppKit resets the scrollbar's style when you attach a scrollbar
    setScrollbarOverlayStyle(scrollbarOverlayStyle());
}

void ScrollableArea::willRemoveScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
{
    if (orientation == VerticalScrollbar)
        scrollAnimator()->willRemoveVerticalScrollbar(scrollbar);
    else
        scrollAnimator()->willRemoveHorizontalScrollbar(scrollbar);
}

void ScrollableArea::contentsResized()
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->contentsResized();
}

bool ScrollableArea::hasOverlayScrollbars() const
{
    return (verticalScrollbar() && verticalScrollbar()->isOverlayScrollbar())
        || (horizontalScrollbar() && horizontalScrollbar()->isOverlayScrollbar());
}

void ScrollableArea::setScrollbarOverlayStyle(ScrollbarOverlayStyle overlayStyle)
{
    m_scrollbarOverlayStyle = overlayStyle;

    if (horizontalScrollbar()) {
        ScrollbarTheme::theme()->updateScrollbarOverlayStyle(horizontalScrollbar());
        horizontalScrollbar()->invalidate();
    }

    if (verticalScrollbar()) {
        ScrollbarTheme::theme()->updateScrollbarOverlayStyle(verticalScrollbar());
        verticalScrollbar()->invalidate();
    }
}

void ScrollableArea::invalidateScrollbar(Scrollbar* scrollbar, const IntRect& rect)
{
#if USE(ACCELERATED_COMPOSITING)
    if (scrollbar == horizontalScrollbar()) {
        if (GraphicsLayer* graphicsLayer = layerForHorizontalScrollbar()) {
            graphicsLayer->setNeedsDisplay();
            graphicsLayer->setContentsNeedsDisplay();
            return;
        }
    } else if (scrollbar == verticalScrollbar()) {
        if (GraphicsLayer* graphicsLayer = layerForVerticalScrollbar()) {
            graphicsLayer->setNeedsDisplay();
            graphicsLayer->setContentsNeedsDisplay();
            return;
        }
    }
#endif
    invalidateScrollbarRect(scrollbar, rect);
}

void ScrollableArea::invalidateScrollCorner(const IntRect& rect)
{
#if USE(ACCELERATED_COMPOSITING)
    if (GraphicsLayer* graphicsLayer = layerForScrollCorner()) {
        graphicsLayer->setNeedsDisplay();
        return;
    }
#endif
    invalidateScrollCornerRect(rect);
}

bool ScrollableArea::hasLayerForHorizontalScrollbar() const
{
#if USE(ACCELERATED_COMPOSITING)
    return layerForHorizontalScrollbar();
#else
    return false;
#endif
}

bool ScrollableArea::hasLayerForVerticalScrollbar() const
{
#if USE(ACCELERATED_COMPOSITING)
    return layerForVerticalScrollbar();
#else
    return false;
#endif
}

bool ScrollableArea::hasLayerForScrollCorner() const
{
#if USE(ACCELERATED_COMPOSITING)
    return layerForScrollCorner();
#else
    return false;
#endif
}

void ScrollableArea::serviceScrollAnimations()
{
    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
        scrollAnimator->serviceScrollAnimations();
}

IntPoint ScrollableArea::scrollPosition() const
{
    int x = horizontalScrollbar() ? horizontalScrollbar()->value() : 0;
    int y = verticalScrollbar() ? verticalScrollbar()->value() : 0;
    return IntPoint(x, y);
}

IntPoint ScrollableArea::minimumScrollPosition() const
{
    return IntPoint();
}

IntPoint ScrollableArea::maximumScrollPosition() const
{
    return IntPoint(totalContentsSize().width() - visibleWidth(), totalContentsSize().height() - visibleHeight());
}

IntSize ScrollableArea::totalContentsSize() const
{
    IntSize totalContentsSize = contentsSize();
    totalContentsSize.setHeight(totalContentsSize.height() + headerHeight() + footerHeight());
    return totalContentsSize;
}

IntRect ScrollableArea::visibleContentRect(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
{
    int verticalScrollbarWidth = 0;
    int horizontalScrollbarHeight = 0;

    if (scrollbarInclusion == IncludeScrollbars) {
        if (Scrollbar* verticalBar = verticalScrollbar())
            verticalScrollbarWidth = !verticalBar->isOverlayScrollbar() ? verticalBar->width() : 0;
        if (Scrollbar* horizontalBar = horizontalScrollbar())
            horizontalScrollbarHeight = !horizontalBar->isOverlayScrollbar() ? horizontalBar->height() : 0;
    }

    return IntRect(scrollPosition().x(),
                   scrollPosition().y(),
                   std::max(0, visibleWidth() + verticalScrollbarWidth),
                   std::max(0, visibleHeight() + horizontalScrollbarHeight));
}

IntPoint ScrollableArea::constrainScrollPositionForOverhang(const IntRect& visibleContentRect, const IntSize& totalContentsSize, const IntPoint& scrollPosition, const IntPoint& scrollOrigin, int headerHeight, int footerHeight)
{
    // The viewport rect that we're scrolling shouldn't be larger than our document.
    IntSize idealScrollRectSize(std::min(visibleContentRect.width(), totalContentsSize.width()), std::min(visibleContentRect.height(), totalContentsSize.height()));

    IntRect scrollRect(scrollPosition + scrollOrigin - IntSize(0, headerHeight), idealScrollRectSize);
    IntRect documentRect(IntPoint(), IntSize(totalContentsSize.width(), totalContentsSize.height() - headerHeight - footerHeight));

    // Use intersection to constrain our ideal scroll rect by the document rect.
    scrollRect.intersect(documentRect);

    if (scrollRect.size() != idealScrollRectSize) {
        // If the rect was clipped, restore its size, effectively pushing it "down" from the top left.
        scrollRect.setSize(idealScrollRectSize);

        // If we still clip, push our rect "up" from the bottom right.
        scrollRect.intersect(documentRect);
        if (scrollRect.width() < idealScrollRectSize.width())
            scrollRect.move(-(idealScrollRectSize.width() - scrollRect.width()), 0);
        if (scrollRect.height() < idealScrollRectSize.height())
            scrollRect.move(0, -(idealScrollRectSize.height() - scrollRect.height()));
    }

    return scrollRect.location() - toIntSize(scrollOrigin);
}

IntPoint ScrollableArea::constrainScrollPositionForOverhang(const IntPoint& scrollPosition)
{
    return constrainScrollPositionForOverhang(visibleContentRect(), totalContentsSize(), scrollPosition, scrollOrigin(), headerHeight(), footerHeight());
}

} // namespace WebCore


text:
package com.dynatrace.diagnostics.plugins.extendedmailreport.exception;

public class ReportCreationException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = -6869543200215509789L;

	public ReportCreationException() {}

	public ReportCreationException(String msg) {
		super(msg);
	}

	public ReportCreationException(Throwable cause) {
		super(cause);
	}

	public ReportCreationException(String msg, Throwable cause) {
		super(msg, cause);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require_once(dirname(__FILE__) . '/../config.php');
require_once($CFG->dirroot . '/message/lib.php');

$userid = optional_param('id', $USER->id, PARAM_INT);    // user id
$disableall = optional_param('disableall', 0, PARAM_BOOL); //disable all of this user's notifications

$url = new moodle_url('/message/edit.php');
$url->param('id', $userid);

$PAGE->set_url($url);
$PAGE->set_popup_notification_allowed(false); // We are within the messaging system so don't show message popups

require_login();

if (isguestuser()) {
    print_error('guestnoeditmessage', 'message');
}

if (!$user = $DB->get_record('user', array('id' => $userid))) {
    print_error('invaliduserid');
}

$systemcontext   = context_system::instance();
$personalcontext = context_user::instance($user->id);

$PAGE->set_context($personalcontext);
$PAGE->set_pagelayout('course');
$PAGE->requires->js_init_call('M.core_message.init_editsettings');

// check access control
if ($user->id == $USER->id) {
    //editing own message profile
    require_capability('moodle/user:editownmessageprofile', $systemcontext);
} else {
    // teachers, parents, etc.
    require_capability('moodle/user:editmessageprofile', $personalcontext);
    // no editing of guest user account
    if (isguestuser($user->id)) {
        print_error('guestnoeditmessageother', 'message');
    }
    // no editing of admins by non admins!
    if (is_siteadmin($user) and !is_siteadmin($USER)) {
        print_error('useradmineditadmin');
    }
    $PAGE->navigation->extend_for_user($user);
}

// Fetch message providers
$providers = message_get_providers_for_user($user->id);

/// Save new preferences if data was submitted

if (($form = data_submitted()) && confirm_sesskey()) {
    $preferences = array();

    //only update the user's "emailstop" if its actually changed
    if ( $user->emailstop != $disableall ) {
        $user->emailstop = $disableall;
        $DB->set_field('user', 'emailstop', $user->emailstop, array("id"=>$user->id));
    }

    // Turning on emailstop disables the preference checkboxes in the browser.
    // Disabled checkboxes may not be submitted with the form making them look (incorrectly) like they've been unchecked.
    // Only alter the messaging preferences if emailstop is turned off
    if (!$user->emailstop) {
        foreach ($providers as $provider) {
            $componentproviderbase = $provider->component.'_'.$provider->name;
            foreach (array('loggedin', 'loggedoff') as $state) {
                $linepref = '';
                $componentproviderstate = $componentproviderbase.'_'.$state;
                if (array_key_exists($componentproviderstate, $form)) {
                    foreach (array_keys($form->{$componentproviderstate}) as $process) {
                        if ($linepref == ''){
                            $linepref = $process;
                        } else {
                            $linepref .= ','.$process;
                        }
                    }
                }
                if (empty($linepref)) {
                    $linepref = 'none';
                }
                $preferences['message_provider_'.$provider->component.'_'.$provider->name.'_'.$state] = $linepref;
            }
        }
    }

/// Set all the processor options as well
    $processors = get_message_processors(true);
    foreach ($processors as $processor) {
        $processor->object->process_form($form, $preferences);
    }

    //process general messaging preferences
    $preferences['message_blocknoncontacts'] = !empty($form->blocknoncontacts)?1:0;
    //$preferences['message_beepnewmessage']    = !empty($form->beepnewmessage)?1:0;

    // Save all the new preferences to the database
    if (!set_user_preferences($preferences, $user->id)) {
        print_error('cannotupdateusermsgpref');
    }

    redirect("$CFG->wwwroot/message/edit.php?id=$user->id");
}

/// Load preferences
$preferences = new stdClass();
$preferences->userdefaultemail = $user->email;//may be displayed by the email processor

/// Get providers preferences
foreach ($providers as $provider) {
    foreach (array('loggedin', 'loggedoff') as $state) {
        $linepref = get_user_preferences('message_provider_'.$provider->component.'_'.$provider->name.'_'.$state, '', $user->id);
        if ($linepref == ''){
            continue;
        }
        $lineprefarray = explode(',', $linepref);
        $preferences->{$provider->component.'_'.$provider->name.'_'.$state} = array();
        foreach ($lineprefarray as $pref) {
            $preferences->{$provider->component.'_'.$provider->name.'_'.$state}[$pref] = 1;
        }
    }
}

// Load all processors
$processors = get_message_processors();
/// For every processors put its options on the form (need to get function from processor's lib.php)
foreach ($processors as $processor) {
    $processor->object->load_data($preferences, $user->id);
}

//load general messaging preferences
$preferences->blocknoncontacts  =  get_user_preferences( 'message_blocknoncontacts', '', $user->id);
//$preferences->beepnewmessage    =  get_user_preferences( 'message_beepnewmessage', '', $user->id);

/// Display page header
$strmessaging = get_string('messaging', 'message');
$PAGE->set_title($strmessaging);
$PAGE->set_heading($strmessaging);

// Grab the renderer
$renderer = $PAGE->get_renderer('core', 'message');
// Fetch default (site) preferences
$defaultpreferences = get_message_output_default_preferences();

$messagingoptions = $renderer->manage_messagingoptions($processors, $providers, $preferences, $defaultpreferences, $user->emailstop);

echo $OUTPUT->header();
echo $messagingoptions;
echo $OUTPUT->footer();


text:
package log

// Loggable describes objects that can be marshalled into Metadata for logging
type Loggable interface {
	Loggable() map[string]interface{}
}

// LoggableMap is just a generic map keyed by string. It
// implements the Loggable interface.
type LoggableMap map[string]interface{}

// Loggable implements the Loggable interface for LoggableMap
func (l LoggableMap) Loggable() map[string]interface{} {
	return l
}

// LoggableF converts a func into a Loggable
type LoggableF func() map[string]interface{}

// Loggable implements the Loggable interface by running
// the LoggableF function.
func (l LoggableF) Loggable() map[string]interface{} {
	return l()
}

// Deferred returns a LoggableF where the execution of the
// provided function is deferred.
func Deferred(key string, f func() string) Loggable {
	function := func() map[string]interface{} {
		return map[string]interface{}{
			key: f(),
		}
	}
	return LoggableF(function)
}

// Pair returns a Loggable where key is paired to Loggable.
func Pair(key string, l Loggable) Loggable {
	return LoggableMap{
		key: l,
	}
}


text:
/*global URLify*/
(function($) {
    'use strict';
    $.fn.prepopulate = function(dependencies, maxLength, allowUnicode) {
        /*
            Depends on urlify.js
            Populates a selected field with the values of the dependent fields,
            URLifies and shortens the string.
            dependencies - array of dependent fields ids
            maxLength - maximum length of the URLify'd string
            allowUnicode - Unicode support of the URLify'd string
        */
        return this.each(function() {
            var prepopulatedField = $(this);

            var populate = function() {
                // Bail if the field's value has been changed by the user
                if (prepopulatedField.data('_changed')) {
                    return;
                }

                var values = [];
                $.each(dependencies, function(i, field) {
                    field = $(field);
                    if (field.val().length > 0) {
                        values.push(field.val());
                    }
                });
                prepopulatedField.val(URLify(values.join(' '), maxLength, allowUnicode));
            };

            prepopulatedField.data('_changed', false);
            prepopulatedField.on('change', function() {
                prepopulatedField.data('_changed', true);
            });

            if (!prepopulatedField.val()) {
                $(dependencies.join(',')).on('keyup change focus', populate);
            }
        });
    };
})(grp.jQuery);


text:
<?php

namespace Lebed\GuestbookBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Lebed\GuestbookBundle\Entity\Post;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;

class LoadPostData extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {
        date_default_timezone_set('Europe/Kiev');

        $post = new Post();
        $post->setTitle('Doctrine Fixtures Bundle');
        $post->setAuthor('Natasha');
        $post->setViewsNumber(0);
        $post->setCategory($this->getReference('configuration-and-basic-usage'));
        $post->addTag($this->getReference('symfony-tag'));
        $post->addTag($this->getReference('doctrine-tag'));
        $post->setText('Fixtures are used to load a controlled set of data into a database. This data can be used for testing or could be the initial data required for the application to run smoothly. Symfony2 has no built in way to manage fixtures but Doctrine2 has a library to help you write fixtures for the Doctrine ORM or ODM. Writing a basic fixture is simple. But what if you have multiple fixture classes and want to be able to refer to the data loaded in other fixture classes? For example, what if you load a User object in one fixture, and then want to refer to reference it in a different fixture in order to assign that user to a particular group?');
        $manager->persist($post);

        $post1 = new Post();
        $post1->setTitle('Loggable');
        $post1->setAuthor('Makar');
        $post1->setViewsNumber(0);
        $post1->setCategory($this->getReference('doctrine-extensions'));
        $post1->addTag($this->getReference('symfony-tag'));
        $post1->addTag($this->getReference('doctrine-tag'));
        $post1->addTag($this->getReference('extension-tag'));
        $post1->setText("Loggable behavior tracks your record changes and is able to manage versions. Features:Automatic storage of log entries in database ORM and ODM support using same listener Can be nested with other behaviors Objects can be reverted to previous versions Annotation, Yaml and Xml mapping support for extensions");
        $manager->persist($post1);

        $post2 = new Post();
        $post2->setTitle('Creating and using Templates');
        $post2->setAuthor('Veronika');
        $post2->setViewsNumber(0);
        $post2->setCategory($this->getReference('templates'));
        $post2->addTag($this->getReference('template-tag'));
        $post2->setText('As you know, the controller is responsible for handling each request that comes into a Symfony2 application. In reality, the controller delegates most of the heavy work to other places so that code can be tested and reused. When a controller needs to generate HTML, CSS or any other content, it hands the work off to the templating engine. In this chapter, youll learn how to write powerful templates that can be used to return content to the user, populate email bodies, and more. Youll learn shortcuts, clever ways to extend templates and how to reuse template code.');
        $manager->persist($post2);

        $post3 = new Post();
        $post3->setTitle('Introduction');
        $post3->setAuthor('Tymofiy');
        $post3->setViewsNumber(0);
        $post3->setCategory($this->getReference('twig'));
        $post3->addTag($this->getReference('symfony-tag'));
        $post3->addTag($this->getReference('twig-tag'));
        $post3->setText('This is the documentation for Twig, the flexible, fast, and secure template engine for PHP. If you have any exposure to other text-based template languages, such as Smarty, Django, or Jinja, you should feel right at home with Twig. Its both designer and developer friendly by sticking to PHPs principles and adding functionality useful for templating environments. The key-features are...');
        $manager->persist($post3);

        $post4 = new Post();
        $post4->setTitle('The Text Extension');
        $post4->setAuthor('Natasha');
        $post4->setViewsNumber(0);
        $post4->setCategory($this->getReference('twig-extension'));
        $post4->addTag($this->getReference('symfony-tag'));
        $post4->addTag($this->getReference('extension-tag'));
        $post4->addTag($this->getReference('twig-tag'));
        $post4->setText('The Text extension provides the following filters: truncate wordwrap nl2br');
        $manager->persist($post4);

        $manager->flush();
    }

    public function getOrder()
    {
        return 3; // the order in which fixtures will be loaded
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>src/screen.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.8.0/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for:

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Chip8

Chip8.CPU

Chip8.Keyboard

Chip8.Screen

Chip8.Screen.CanvasScreen

Chip8.Speaker

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: src/screen.js

(function() {
  /**
   * The CPU of the emulator, responsible for processing memory opcodes.
   *
   * @class Chip8.Screen
   * @constructor
   *
   * @property {Array} bitMap the display map
   */
  var Screen = function Screen() {
    this.rows = 32;
    this.columns = 64;
    this.resolution = this.rows * this.columns;
    this.bitMap = new Array(this.resolution);

    /**
     * Clear the bitMap.
     * @method clear
     */
    this.clear = function() {
      this.bitMap = new Array(this.resolution);
    }

    /**
     * @method setPixel
     * @param {Integer} x the starting x coordinate of the pixel
     * @param {Integer} y the starting y coordinate of the pixel
     */
    this.setPixel = function(x, y) {
      // Wrap around pixels that overflow the screen
      if (x > this.columns) {
        x -= this.columns;
      } else if (x < 0) {
        x += this.columns;
      }

      if (y > this.rows) {
        y -= this.rows;
      } else if (y < 0) {
        y += this.rows;
      }

      var location = x + (y * this.columns);
      this.bitMap[location] = this.bitMap[location] ^ 1;

      return !this.bitMap[location];
    }

    this.render = function(output) {}
  }

  /**
   * The CPU of the emulator, responsible for processing memory opcodes.
   *
   * @class Chip8.Screen.CanvasScreen
   * @extends Chip8.Screen
   * @constructor
   * @param {CanvasRenderingContext2D} ctx context 2D of a canvas element
   * @param {Integer} scale the scale of the rendering, defaults to 10.
   */
  Screen.CanvasScreen = function CanvasScreen(ctx, scale) {
    Screen.apply(this, arguments);

    this.scale = scale || 10;

    var width = ctx.canvas.width = this.columns * this.scale;
    var height = ctx.canvas.height = this.rows * this.scale;

    /**
     * Renders the bitMap array into the canvas context.
     * @method render
     */
    this.render = function() {
      var i, x, y;

      ctx.clearRect(0, 0, width, height);

      for (i = 0; i < this.resolution; i++) {
        x = (i % this.columns) * this.scale;
        y = Math.floor(i / this.columns) * this.scale;

        if (this.bitMap[i]) {
          ctx.fillStyle = "#000";
          ctx.fillRect(x, y, this.scale, this.scale);
        }
      }
    }
  }

  if (typeof module != "undefined") {
    module.exports = Screen;
  } else {
    window.Chip8.Screen = Screen;
  }
})();


text:
[log4j](https://logging.apache.org/log4j/1.2/) support for Raven.
It provides an [`Appender`](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Appender.html)
for log4j to send the logged events to Sentry.

## Installation

### Maven
```xml
<dependency>
    <groupId>net.kencochrane.raven</groupId>
    <artifactId>raven-log4j</artifactId>
    <version>4.1.2</version>
</dependency>
```

### Other dependency managers
Details in the [central Maven repository](https://search.maven.org/#artifactdetails%7Cnet.kencochrane.raven%7Craven-log4j%7C4.1.2%7Cjar).

### Manual dependency management
Relies on:

 - [raven dependencies](../raven)
 - [log4j-1.2.17.jar](https://search.maven.org/#artifactdetails%7Clog4j%7Clog4j%7C1.2.17%7Cjar)
 - [slf4j-log4j12-1.7.5.jar](https://search.maven.org/#artifactdetails%7Corg.slf4j%7Cslf4j-log4j12%7C1.7.5%7Cjar)
 is recommended as the implementation of slf4j (instead of slf4j-jdk14).

## Usage
### Configuration
In the `log4j.properties` file set:

```properties
log4j.rootLogger=WARN, SentryAppender
log4j.appender.SentryAppender=net.kencochrane.raven.log4j.SentryAppender
log4j.appender.SentryAppender.dsn=https://publicKey:secretKey@host:port/1?options
log4j.appender.SentryAppender.tags=tag1:value1,tag2:value2
# Optional, allows to select the ravenFactory
#log4j.appender.SentryAppender.ravenFactory=net.kencochrane.raven.DefaultRavenFactory
```

### Additional data and information
It's possible to add extra details to events captured by the Log4j module
thanks to both [the MDC](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html)
and [the NDC](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html) systems provided by Log4j are
usable, allowing to attach extras information to the event.

### In practice
```java
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.log4j.NDC;

public class MyClass {
    private static final Logger logger = Logger.getLogger(MyClass.class);

    void logSimpleMessage() {
        // This adds a simple message to the logs
        logger.info("This is a test");
    }

    void logWithExtras() {
        // MDC extras
        MDC.put("extra_key", "extra_value");
        // NDC extras are sent under 'log4J-NDC'
        NDC.push("Extra_details");
        // This adds a message with extras to the logs
        logger.info("This is a test");
    }

    void logException() {
        try {
            unsafeMethod();
        } catch (Exception e) {
            // This adds an exception to the logs
            logger.error("Exception caught", e);
        }
    }

    void unsafeMethod() {
        throw new UnsupportedOperationException("You shouldn't call that");
    }
}
```

## Asynchronous logging
It is not recommended to attempt to set up `SentryAppender` within an
[AsyncAppender](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html).
While this is a common solution to avoid blocking the current thread until the
event is sent to Sentry, it is recommended to rely instead on the asynchronous
connection provided by Raven.


text:
class SimpleAlertInfoBarDelegate : public ConfirmInfoBarDelegate {
 public:
  // Creates a simple alert delegate and adds it to |infobar_service|.
  static void Create(InfoBarService* infobar_service,
                     gfx::Image* icon,  // May be NULL.
                     const string16& message,
                     bool auto_expire);

 private:
  SimpleAlertInfoBarDelegate(InfoBarService* infobar_service,
                             gfx::Image* icon,
                             const string16& message,
                             bool auto_expire);
  virtual ~SimpleAlertInfoBarDelegate();

  // ConfirmInfoBarDelegate:
  virtual gfx::Image* GetIcon() const OVERRIDE;
  virtual string16 GetMessageText() const OVERRIDE;
  virtual int GetButtons() const OVERRIDE;
  virtual bool ShouldExpireInternal(
      const content::LoadCommittedDetails& details) const OVERRIDE;

  gfx::Image* icon_;
  string16 message_;
  bool auto_expire_;  // Should it expire automatically on navigation?

  DISALLOW_COPY_AND_ASSIGN(SimpleAlertInfoBarDelegate);
};

#endif  // CHROME_BROWSER_INFOBARS_SIMPLE_ALERT_INFOBAR_DELEGATE_H_


text:
package org.apache.isis.viewer.restfulobjects.rendering.util;

import java.io.IOException;
import org.apache.isis.core.runtime.system.DeploymentType;
import org.apache.isis.core.runtime.system.context.IsisContext;
import org.apache.isis.viewer.restfulobjects.applib.util.JsonMapper;

public final class JsonWriterUtil {

    private JsonWriterUtil(){}

    public static String jsonFor(final Object object) {
        final JsonMapper.PrettyPrinting prettyPrinting = inferPrettyPrinting(IsisContext.getDeploymentType());
        try {
            return JsonMapper.instance(prettyPrinting).write(object);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static JsonMapper.PrettyPrinting inferPrettyPrinting(final DeploymentType deploymentType) {
        return deploymentType.isProduction() ? JsonMapper.PrettyPrinting.DISABLE : JsonMapper.PrettyPrinting.ENABLE;
    }
}


text:
'use strict';

module.exports = {
    port: process.env.PORT || 3000,
    secret: 'patatopdeveloper',
    expirationTime: '24h',
    database: 'mongodb://localhost:27017/forum',
    loggerMode: 'dev',
    publicPath: 'client'
};


text:
import os
import copy
from random import seed, choice

from docopt import docopt

from .utils.ui import main_menu
from .__metadata__ import __versionstr__ as version
from .utils.logger import get_logger
from .utils.data_loaders import load_maps, load_mobs, load_items, load_tiles

def initialize_game(initial_seed=None, debug=False):
    """Generates a basic game state"""
    seed(initial_seed)
    if isinstance(initial_seed, str) and initial_seed.isdigit():
        initial_seed = int(initial_seed)
    game_state = {
        'screen-width': 80,
        'screen-height': 43,
        'map-width': 72,
        'map-height': 42,
        'panel-height': 7,
        'panel-width': 43,
        'limit-fps': 20,
        'fov-algorithm': 0,
        'fov-light-walls': True,
        'torch-radius': 8,
        'current-round': 0,

        'debug': debug,
        'seed': initial_seed,
        'package-path': os.path.dirname(__file__),
        'player-inventory': [
            'punch-card', 'default-pocket-protector'
        ],
    }
    load_tiles(game_state)
    load_items(game_state)
    load_mobs(game_state)
    load_maps(game_state)
    for index, item_name in enumerate(game_state.get('player-inventory', [])):
        item = copy.deepcopy(game_state['items'][item_name])
        item['equipped'] = True
        game_state['player-inventory'][index] = item

    map_name = 'level0'
    level_map = game_state['maps'][map_name]
    game_state['current-level'] = level_map

    floors = [position for position, tile in level_map.items() if tile['name'] == 'floor']
    character_position = choice(floors)
    game_state['character-position'] = character_position
    return game_state

def runner(docstring=None, cli_arguments=None):
    """Runs the game

    Args:
        docstring(str): Basic docstring for running the game
        cli_arguments(str): Basic command-line string
    """
    version_string = f"LOSE {version} Land of Software Engineering [7drl 2017]"
    options = docopt(docstring, version=version_string, argv=cli_arguments)
    if options.get('--verbose') > 1:
        logger = get_logger('lose', 'TRACE')
    elif options.get('--verbose') > 0:
        logger = get_logger('lose', 'DEBUG')
    else:
        logger = get_logger('lose', 'INFO')

    opt_seed = options.get('--seed')
    debug = options.get('--debug')
    initial_seed = None
    if opt_seed:
        initial_seed = opt_seed
    elif debug:
        initial_seed = 10
    game_state = initialize_game(initial_seed=initial_seed, debug=debug)
    logger.trace('Starting game')
    # logger.trace({'game_state': game_state})
    main_menu(game_state)


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>ConfigurationChangedEventArgs Properties</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

ConfigurationChangedEventArgs Properties

The properties of the ConfigurationChangedEventArgs class are listed below. For a complete list of ConfigurationChangedEventArgs class members, see the ConfigurationChangedEventArgs Members topic.

Public Instance Properties

ConfigurationMessages

See Also

        ConfigurationChangedEventArgs Class | log4net.Repository Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="ConfigurationChangedEventArgs class, properties">
        </param>
      </object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


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

<!--
  ~ Copyright 2014 Google Inc. All rights reserved.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_gravity="bottom"
        android:background="#80000000"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/movie_info_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/movie_info_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:textSize="14sp" />
    </LinearLayout>

    <ImageButton
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:id="@+id/movie_play"
        android:layout_gravity="bottom|right"
        android:layout_marginBottom="170dp"
        android:layout_marginRight="40dp"
        android:background="@drawable/fab"
        android:src="@drawable/ic_av_play_arrow"
        style="@style/WatchDetailsPlayButton"/>
</FrameLayout>


text:
package org.aludratest.service.gui.integrationtest;

import java.io.ByteArrayInputStream;

import org.aludratest.service.gui.component.FileField;
import org.aludratest.service.gui.web.AludraWebGUI;
import org.aludratest.testcase.TestStatus;
import org.databene.commons.Encodings;
import org.junit.Test;

/** Tests the {@link FileField}-related features of {@link AludraWebGUI} services.
 * @author Volker Bergmann */
@SuppressWarnings("javadoc")
public abstract class AbstractFileFieldTest extends GUITest {

    @Test
    public void setResourceNameAndContent() throws Exception {
        guiTestUIMap.fileField().assertTextEquals("");
        ByteArrayInputStream content = new ByteArrayInputStream("myTestFileContent".getBytes(Encodings.UTF_8));
        guiTestUIMap.fileField().setResourceNameAndContent("myTestFile.txt", content);
        checkLastStepStatus(TestStatus.PASSED);
        guiTestUIMap.fileSubmitButton().click();
        checkLastStepStatus(TestStatus.PASSED);
        guiTestUIMap.fileNameLabel().assertTextEquals("myTestFile.txt");
        checkLastStepStatus(TestStatus.PASSED);
        guiTestUIMap.fileContentLabel().assertTextEquals("myTestFileContent");
        checkLastStepStatus(TestStatus.PASSED);
    }

}


text:
package org.apache.syncope.client.cli.commands.task;

import javax.xml.ws.WebServiceException;
import org.apache.syncope.client.cli.Input;
import org.apache.syncope.common.lib.SyncopeClientException;
import org.apache.syncope.common.lib.to.AbstractTaskTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TaskDeleteAllProp extends AbstractTaskCommand {

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

    private static final String DELETE_HELP_MESSAGE = "task --delete-all-prop";

    private final Input input;

    public TaskDeleteAllProp(final Input input) {
        this.input = input;
    }

    public void delete() {

        if (input.parameterNumber() == 0) {
            for (final AbstractTaskTO taskTO : taskSyncopeOperations.listPropagationTask()) {
                final String taskId = String.valueOf(taskTO.getKey());
                try {
                    taskSyncopeOperations.delete(taskId);
                    taskResultManager.deletedMessage("Task", taskId);
                } catch (final WebServiceException | SyncopeClientException ex) {
                    LOG.error("Error deleting task", ex);
                    if (ex.getMessage().startsWith("NotFound")) {
                        taskResultManager.notFoundError("Task", taskId);
                    } else if (ex.getMessage().startsWith("DataIntegrityViolation")) {
                        taskResultManager.genericError("You cannot delete task " + taskId);
                    } else {
                        taskResultManager.genericError(ex.getMessage());
                    }
                } catch (final NumberFormatException ex) {
                    LOG.error("Error deleting task", ex);
                    taskResultManager.notBooleanDeletedError("task", taskId);
                }
            }
        } else {
            taskResultManager.commandOptionError(DELETE_HELP_MESSAGE);
        }
    }
}


text:
Ada - Iup
=========

This is an Ada binding for the
[Iup library](http://www.tecgraf.puc-rio.br/iup/). Iup itself is a
multi-platform toolkit for building graphical user interfaces. You cat
use Iup on Unix (the backend is GTK) and in Windows (the backend uses
the Windows API).

This is a thin binding that you can use with the Gnat Ada compiler.

Examples
--------

You can find an example program in the file `provaiup.adb` and
`provadue_iup.adb`.

Licence
-------

The MIT License (MIT)

Copyright (c) 2014, Leonardo Cecchi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
RSpec.describe Hyrax::CustomQueries::FindManyByAlternateIds do
  subject(:query_handler) { described_class.new(query_service: query_service) }
  let(:adapter)           { Valkyrie::MetadataAdapter.find(:test_adapter) }
  let(:persister)         { adapter.persister }
  let(:query_service)     { adapter.query_service }

  let(:ids) { resources.map { |r| r.alternate_ids.first } }

  let(:resources) do
    [persister.save(resource: Hyrax::Resource.new(alternate_ids: ['1'])),
     persister.save(resource: Hyrax::Resource.new(alternate_ids: ['2'])),
     persister.save(resource: Hyrax::Resource.new(alternate_ids: ['3']))]
  end

  before { persister.wipe! }

  describe '#find_many_by_alternate_ids' do
    it 'returns empty with no ids' do
      expect(query_handler.find_many_by_alternate_ids(alternate_ids: []).count)
        .to eq 0
    end

    context 'with Valkyrie::ID input' do
      it 'returns matching resources' do
        expect(query_handler.find_many_by_alternate_ids(alternate_ids: ids))
          .to contain_exactly(*resources)
      end
    end

    context 'when list includes an invalid id' do
      let(:ids) { resources.map { |r| r.alternate_ids.first } + ['fake_id'] }

      it 'raises ObjectNotFoundError' do
        expect { query_handler.find_many_by_alternate_ids(alternate_ids: ids).to_a }
          .to raise_error Valkyrie::Persistence::ObjectNotFoundError
      end
    end
  end
end


text:
require "google/cloud/spanner/errors"
require "google/cloud/spanner/results"
require "google/cloud/spanner/commit"

module Google
  module Cloud
    module Spanner
      ##
      # # Transaction
      #
      # A transaction in Cloud Spanner is a set of reads and writes that execute
      # atomically at a single logical point in time across columns, rows, and
      # tables in a database.
      #
      # All changes are accumulated in memory until the block passed to
      # {Client#transaction} completes. Transactions will be automatically
      # retried when possible. See {Client#transaction}.
      #
      # @example
      #   require "google/cloud/spanner"
      #
      #   spanner = Google::Cloud::Spanner.new
      #   db = spanner.client "my-instance", "my-database"
      #
      #   db.transaction do |tx|
      #     results = tx.execute "SELECT * FROM users"
      #
      #     results.rows.each do |row|
      #       puts "User #{row[:id]} is #{row[:name]}"
      #     end
      #   end
      #
      class Transaction
        # @private The Session object.
        attr_accessor :session

        def initialize
          @commit = Commit.new
        end

        ##
        # Identifier of the transaction results were run in.
        # @return [String] The transaction id.
        def transaction_id
          return nil if @grpc.nil?
          @grpc.id
        end

        ##
        # Executes a SQL query.
        #
        # Arguments can be passed using `params`, Ruby types are mapped to
        # Spanner types as follows:
        #
        # | Spanner     | Ruby           | Notes  |
        # |-------------|----------------|---|
        # | `BOOL`      | `true`/`false` | |
        # | `INT64`     | `Integer`      | |
        # | `FLOAT64`   | `Float`        | |
        # | `STRING`    | `String`       | |
        # | `DATE`      | `Date`         | |
        # | `TIMESTAMP` | `Time`, `DateTime` | |
        # | `BYTES`     | `File`, `IO`, `StringIO`, or similar | |
        # | `ARRAY`     | `Array` | Nested arrays are not supported. |
        #
        # See [Data
        # types](https://cloud.google.com/spanner/docs/data-definition-language#data_types).
        #
        # @param [String] sql The SQL query string. See [Query
        #   syntax](https://cloud.google.com/spanner/docs/query-syntax).
        #
        #   The SQL query string can contain parameter placeholders. A parameter
        #   placeholder consists of "@" followed by the parameter name.
        #   Parameter names consist of any combination of letters, numbers, and
        #   underscores.
        # @param [Hash] params SQL parameters for the query string. The
        #   parameter placeholders, minus the "@", are the the hash keys, and
        #   the literal values are the hash values. If the query string contains
        #   something like "WHERE id > @msg_id", then the params must contain
        #   something like `:msg_id => 1`.
        # @param [Hash] types Types of the SQL parameters in `params`. It is not
        #   always possible for Cloud Spanner to infer the right SQL type from a
        #   value in `params`. In these cases, the `types` hash can be used to
        #   specify the exact SQL type for some or all of the SQL query
        #   parameters.
        #
        #   The keys of the hash should be query string parameter placeholders,
        #   minus the "@". The values of the hash should be Cloud Spanner type
        #   codes from the following list:
        #
        #   * `:BOOL`
        #   * `:BYTES`
        #   * `:DATE`
        #   * `:FLOAT64`
        #   * `:INT64`
        #   * `:STRING`
        #   * `:TIMESTAMP`
        #
        #   Arrays are specified by providing the type code in an array. For
        #   example, an array of integers are specified as `[:INT64]`.
        #
        #   Structs are not yet supported in query parameters.
        #
        #   Types are optional.
        # @return [Google::Cloud::Spanner::Results] The results of the query
        #   execution.
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     results = tx.execute "SELECT * FROM users"
        #
        #     results.rows.each do |row|
        #       puts "User #{row[:id]} is #{row[:name]}"
        #     end
        #   end
        #
        # @example Query using query parameters:
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     results = tx.execute "SELECT * FROM users WHERE active = @active",
        #                          params: { active: true }
        #
        #     results.rows.each do |row|
        #       puts "User #{row[:id]} is #{row[:name]}"
        #     end
        #   end
        #
        def execute sql, params: nil, types: nil
          ensure_session!
          session.execute sql, params: params, types: types,
                               transaction: tx_selector
        end
        alias_method :query, :execute

        ##
        # Read rows from a database table, as a simple alternative to
        # {#execute}.
        #
        # @param [String] table The name of the table in the database to be
        #   read.
        # @param [Array<String, Symbol>] columns The columns of table to be
        #   returned for each row matching this request.
        # @param [Object, Array<Object>] keys A single, or list of keys or key
        #   ranges to match returned data to. Values should have exactly as many
        #   elements as there are columns in the primary key.
        # @param [String] index The name of an index to use instead of the
        #   table's primary key when interpreting `id` and sorting result rows.
        #   Optional.
        # @param [Integer] limit If greater than zero, no more than this number
        #   of rows will be returned. The default is no limit.
        #
        # @return [Google::Cloud::Spanner::Results] The results of the read
        #   operation.
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     results = tx.read "users", [:id, :name]
        #
        #     results.rows.each do |row|
        #       puts "User #{row[:id]} is #{row[:name]}"
        #     end
        #   end
        #
        def read table, columns, keys: nil, index: nil, limit: nil
          ensure_session!
          session.read table, columns, keys: keys, index: index, limit: limit,
                                       transaction: tx_selector
        end

        ##
        # Inserts or updates rows in a table. If any of the rows already exist,
        # then its column values are overwritten with the ones provided. Any
        # column values not explicitly written are preserved.
        #
        # All changes are accumulated in memory until the block passed to
        # {Client#transaction} completes.
        #
        # @param [String] table The name of the table in the database to be
        #   modified.
        # @param [Array<Hash>] rows One or more hash objects with the hash keys
        #   matching the table's columns, and the hash values matching the
        #   table's values.
        #
        #   Ruby types are mapped to Spanner types as follows:
        #
        #   | Spanner     | Ruby           | Notes  |
        #   |-------------|----------------|---|
        #   | `BOOL`      | `true`/`false` | |
        #   | `INT64`     | `Integer`      | |
        #   | `FLOAT64`   | `Float`        | |
        #   | `STRING`    | `String`       | |
        #   | `DATE`      | `Date`         | |
        #   | `TIMESTAMP` | `Time`, `DateTime` | |
        #   | `BYTES`     | `File`, `IO`, `StringIO`, or similar | |
        #   | `ARRAY`     | `Array` | Nested arrays are not supported. |
        #
        #   See [Data
        #   types](https://cloud.google.com/spanner/docs/data-definition-language#data_types).
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     tx.upsert "users", [{ id: 1, name: "Charlie", active: false },
        #                         { id: 2, name: "Harvey",  active: true }]
        #   end
        #
        def upsert table, *rows
          ensure_session!
          @commit.upsert table, rows
        end
        alias_method :save, :upsert

        ##
        # Inserts new rows in a table. If any of the rows already exist, the
        # write or request fails with error {Google::Cloud::AlreadyExistsError}.
        #
        # All changes are accumulated in memory until the block passed to
        # {Client#transaction} completes.
        #
        # @param [String] table The name of the table in the database to be
        #   modified.
        # @param [Array<Hash>] rows One or more hash objects with the hash keys
        #   matching the table's columns, and the hash values matching the
        #   table's values.
        #
        #   Ruby types are mapped to Spanner types as follows:
        #
        #   | Spanner     | Ruby           | Notes  |
        #   |-------------|----------------|---|
        #   | `BOOL`      | `true`/`false` | |
        #   | `INT64`     | `Integer`      | |
        #   | `FLOAT64`   | `Float`        | |
        #   | `STRING`    | `String`       | |
        #   | `DATE`      | `Date`         | |
        #   | `TIMESTAMP` | `Time`, `DateTime` | |
        #   | `BYTES`     | `File`, `IO`, `StringIO`, or similar | |
        #   | `ARRAY`     | `Array` | Nested arrays are not supported. |
        #
        #   See [Data
        #   types](https://cloud.google.com/spanner/docs/data-definition-language#data_types).
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     tx.insert "users", [{ id: 1, name: "Charlie", active: false },
        #                         { id: 2, name: "Harvey",  active: true }]
        #   end
        #
        def insert table, *rows
          ensure_session!
          @commit.insert table, rows
        end

        ##
        # Updates existing rows in a table. If any of the rows does not already
        # exist, the request fails with error {Google::Cloud::NotFoundError}.
        #
        # All changes are accumulated in memory until the block passed to
        # {Client#transaction} completes.
        #
        # @param [String] table The name of the table in the database to be
        #   modified.
        # @param [Array<Hash>] rows One or more hash objects with the hash keys
        #   matching the table's columns, and the hash values matching the
        #   table's values.
        #
        #   Ruby types are mapped to Spanner types as follows:
        #
        #   | Spanner     | Ruby           | Notes  |
        #   |-------------|----------------|---|
        #   | `BOOL`      | `true`/`false` | |
        #   | `INT64`     | `Integer`      | |
        #   | `FLOAT64`   | `Float`        | |
        #   | `STRING`    | `String`       | |
        #   | `DATE`      | `Date`         | |
        #   | `TIMESTAMP` | `Time`, `DateTime` | |
        #   | `BYTES`     | `File`, `IO`, `StringIO`, or similar | |
        #   | `ARRAY`     | `Array` | Nested arrays are not supported. |
        #
        #   See [Data
        #   types](https://cloud.google.com/spanner/docs/data-definition-language#data_types).
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     tx.update "users", [{ id: 1, name: "Charlie", active: false },
        #                         { id: 2, name: "Harvey",  active: true }]
        #   end
        #
        def update table, *rows
          ensure_session!
          @commit.update table, rows
        end

        ##
        # Inserts or replaces rows in a table. If any of the rows already exist,
        # it is deleted, and the column values provided are inserted instead.
        # Unlike #upsert, this means any values not explicitly written become
        # `NULL`.
        #
        # All changes are accumulated in memory until the block passed to
        # {Client#transaction} completes.
        #
        # @param [String] table The name of the table in the database to be
        #   modified.
        # @param [Array<Hash>] rows One or more hash objects with the hash keys
        #   matching the table's columns, and the hash values matching the
        #   table's values.
        #
        #   Ruby types are mapped to Spanner types as follows:
        #
        #   | Spanner     | Ruby           | Notes  |
        #   |-------------|----------------|---|
        #   | `BOOL`      | `true`/`false` | |
        #   | `INT64`     | `Integer`      | |
        #   | `FLOAT64`   | `Float`        | |
        #   | `STRING`    | `String`       | |
        #   | `DATE`      | `Date`         | |
        #   | `TIMESTAMP` | `Time`, `DateTime` | |
        #   | `BYTES`     | `File`, `IO`, `StringIO`, or similar | |
        #   | `ARRAY`     | `Array` | Nested arrays are not supported. |
        #
        #   See [Data
        #   types](https://cloud.google.com/spanner/docs/data-definition-language#data_types).
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     tx.replace "users", [{ id: 1, name: "Charlie", active: false },
        #                          { id: 2, name: "Harvey",  active: true }]
        #   end
        #
        def replace table, *rows
          ensure_session!
          @commit.replace table, rows
        end

        ##
        # Deletes rows from a table. Succeeds whether or not the specified rows
        # were present.
        #
        # All changes are accumulated in memory until the block passed to
        # {Client#transaction} completes.
        #
        # @param [String] table The name of the table in the database to be
        #   modified.
        # @param [Object, Array<Object>] keys A single, or list of keys or key
        #   ranges to match returned data to. Values should have exactly as many
        #   elements as there are columns in the primary key.
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction { |tx| tx.delete "users", [1, 2, 3] }
        #
        def delete table, keys = []
          ensure_session!
          @commit.delete table, keys
        end

        ##
        # @private
        # Returns the field names and types for a table.
        #
        # @param [String] table The name of the table in the database to
        #   retrieve types for
        #
        # @return [Hash, Array] The types of the returned data. The default is a
        #   Hash. Is a nested Array of Arrays when `pairs` is specified.
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     users_types = rx.fields_for "users"
        #     tx.insert "users", [{ id: 1, name: "Charlie", active: false },
        #                         { id: 2, name: "Harvey",  active: true }],
        #               types: users_types
        #   end
        #
        def fields_for table
          execute("SELECT * FROM #{table} WHERE 1 = 0").fields
        end

        ##
        # Creates a Cloud Spanner Range. This can be used in place of a Ruby
        # Range when needing to exclude the beginning value.
        #
        # @param [Object] beginning The object that defines the beginning of the
        #   range.
        # @param [Object] ending The object that defines the end of the range.
        # @param [Boolean] exclude_begin Determines if the range excludes its
        #   beginning value. Default is `false`.
        # @param [Boolean] exclude_end Determines if the range excludes its
        #   ending value. Default is `false`.
        #
        # @return [Google::Cloud::Spanner::Range] The new Range instance.
        #
        # @example
        #   require "google/cloud/spanner"
        #
        #   spanner = Google::Cloud::Spanner.new
        #   db = spanner.client "my-instance", "my-database"
        #
        #   db.transaction do |tx|
        #     key_range = tx.range 1, 100
        #     results = tx.read "users", [:id, :name], keys: key_range
        #
        #     results.rows.each do |row|
        #       puts "User #{row[:id]} is #{row[:name]}"
        #     end
        #   end
        #
        def range beginning, ending, exclude_begin: false, exclude_end: false
          Range.new beginning, ending,
                    exclude_begin: exclude_begin,
                    exclude_end: exclude_end
        end

        ##
        # @private
        # Keeps the transaction current by creating a new transaction.
        def keepalive!
          ensure_session!
          @grpc = session.create_transaction.instance_variable_get :@grpc
        end

        ##
        # @private
        # Permanently deletes the transaction and session.
        def release!
          ensure_session!
          session.release!
        end

        ##
        # @private
        # Determines if the transaction has been idle longer than the given
        # duration.
        def idle_since? duration
          session.idle_since? duration
        end

        ##
        # @private
        # All of the mutations created in the transaction block.
        def mutations
          @commit.mutations
        end

        ##
        # @private Creates a new Transaction instance from a
        # Google::Spanner::V1::Transaction.
        def self.from_grpc grpc, session
          new.tap do |s|
            s.instance_variable_set :@grpc,    grpc
            s.instance_variable_set :@session, session
          end
        end

        protected

        # The TransactionSelector to be used for queries
        def tx_selector
          return nil if transaction_id.nil?
          Google::Spanner::V1::TransactionSelector.new id: transaction_id
        end

        ##
        # @private Raise an error unless an active connection to the service is
        # available.
        def ensure_session!
          fail "Must have active connection to service" unless session
        end

        def service
          session.service
        end
      end
    end
  end
end


text:
master_path = File.expand_path(File.join(__FILE__, '..', '..', '..', '..', '..', 'dsc','lib'))
$:.push(master_path) if File.directory?(master_path)
require 'puppet/type/base_dsc'

Puppet::Type.newtype(:dsc_xmysqluser) do

  provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
    defaultfor :operatingsystem => :windows
  end

  @doc = %q{
    The DSC xMySqlUser resource type.
    Originally generated from the following schema.mof file:
      import/dsc_resources/dsc-resource-kit/xMySql/DscResources/MSFT_xMySqlUser/MSFT_xMySqlUser.schema.mof
  }

  validate do
      fail('dsc_name is a required attribute') if self[:dsc_name].nil?
    end

  newparam(:dscmeta_resource_friendly_name) do
    defaultto "xMySqlUser"
  end

  newparam(:dscmeta_resource_name) do
    defaultto "MSFT_xMySqlUser"
  end

  newparam(:dscmeta_import_resource) do
    newvalues(true, false)

    munge do |value|
      provider.munge_boolean(value.to_s)
    end

    defaultto true
  end

  newparam(:dscmeta_module_name) do
    defaultto "xMySql"
  end

  newparam(:dscmeta_module_version) do
    defaultto "1.0.0.0"
  end

  newparam(:name, :namevar => true ) do
  end

  ensurable do
    newvalue(:exists?) { provider.exists? }
    newvalue(:present) { provider.create }
    newvalue(:absent)  { provider.destroy }
    defaultto :present
  end

  # Name:         Name
  # Type:         string
  # IsMandatory:  True
  # Values:       None
  newparam(:dsc_name) do
    desc "Name of MySQL user to create or remove."
    isrequired
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Credential
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_credential) do
    desc "Credential for MySql user."
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         ConnectionCredential
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_connectioncredential) do
    desc "MySql connection credential used to create a user."
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Ensure
  # Type:         string
  # IsMandatory:  False
  # Values:       ["Present", "Absent"]
  newparam(:dsc_ensure) do
    desc "Ensure mysql user is present or absent."
    validate do |value|
      resource[:ensure] = value.downcase
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
      unless ['Present', 'present', 'Absent', 'absent'].include?(value)
        fail("Invalid value '#{value}'. Valid values are Present, Absent")
      end
    end
  end

end


text:
//
//  KSAudioPlayer.h
//  KSAudioPlayer
//
//  Created by Sergii Kryvoblotskyi on 5/20/14.
//  Copyright (c) 2014 home. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol KSAudioPlayerDelegate;
@interface KSAudioPlayer : NSObject

@property (nonatomic, weak) id <KSAudioPlayerDelegate> delegate;

/*
Play. Existing channel will be released
 */
- (BOOL)playItemWithURL:(NSURL *)url;

/*
 Player interactions
 */
- (void)pause;
- (void)resume;
- (void)stop;
- (BOOL)isPlaying;

/*
 Player values
 */
- (NSTimeInterval)duration;
- (NSTimeInterval)position;

@property (nonatomic, assign) CGFloat volume;

@end

@protocol KSAudioPlayerDelegate <NSObject>
@optional

/*
 Will be called when track is over
 */

- (void)playerDidFinishPlaying:(KSAudioPlayer *)player;

/*
 Will be called when interruption occured.
 For ex. phone call.
 Basically you should call - (void)pause in this case.
 */

- (void)playerBeginInterruption:(KSAudioPlayer *)player;

/*
 Will be called when interruption ended.
 For ex. phone call ended.
 It's up to you to decide to call - (void)resume or not.
 */

- (void)playerEndInterruption:(KSAudioPlayer *)player shouldResume:(BOOL)should;

@end


text:
from flask import Flask, render_template

# Importar SQLAlchemy
from flask_sqlalchemy import SQLAlchemy

# Importar FireBase
from firebase import firebase

# Definir la aplicacion del objeto WSGI
app = Flask(__name__)

# Configuraciones
app.config.from_object('config')

# Definir el objeto de base de datos que se importa por modulos y controladores
db = SQLAlchemy(app)

# Definir la coneccion a los nodos de FireBase
firebase = firebase.FirebaseApplication('https://ecclesiapp-fe5b2.firebaseio.com', None)

# Ejemplo de manejo de error HTTP
@app.errorhandler(404)
def not_found(error):
    return render_template('404.html'), 404

# Importar a modulo / componente usando la variable de manejo blueprint (mod_auth)
from app.mod_auth.controllers import mod_auth as auth_module

# Registrar blueprint(s)
app.register_blueprint(auth_module)
# app.register_blueprint(xyz_module)
# ..

# Construir la base de datos
# Esto debera crear un archivo usando SQLAlchemy
#db.create_all()


text:
import unittest
from Registry import *
import radio
from lifecycle import *

radio.DEBUG=True

REGISTRY_KVS = "registry.kvs"

#----- FILE HELPERS -----------------------------------------------------------
#
#TODO: This is repeated in KVS_test.py

def remove_file(filename):
    import os
    try:
        os.unlink(filename)
    except OSError:
        pass # ok if it does not already exist

def show_file(filename):
    """Show the contents of a file on screen"""
    with open(filename) as f:
            for l in f.readlines():
                l = l.strip() # remove nl
                print(l)

def create_file(filename):
    with open(filename, "w"):
        pass

#----- TEST REGISTRY ----------------------------------------------------------

class TestRegistry(unittest.TestCase):

    @test_1
    def test_create(self):
        """Make a registry file by calling methods, and see that the file is the correct format"""
        remove_file(REGISTRY_KVS)
        create_file(REGISTRY_KVS)
        registry = DeviceRegistry(REGISTRY_KVS)

        # add some devices to the registry, it should auto update the file
        tv = Devices.MIHO005(device_id=0x68b)
        fan = Devices.ENER002(device_id=(0xC8C8C, 1))
        registry.add(tv, "tv")
        registry.add(fan, "fan")

        # see what the file looks like
        show_file(registry.DEFAULT_FILENAME)

    @test_1
    def test_load(self):
        """Load back a persisted registry and create objects from them, in the registry"""

        # create a registry file
        remove_file(REGISTRY_KVS)
        create_file(REGISTRY_KVS)
        registry = DeviceRegistry(REGISTRY_KVS)
        registry.add(Devices.MIHO005(device_id=0x68b), "tv")
        registry.add(Devices.ENER002(device_id=(0xC8C8C, 1)), "fan")
        registry.list()

        # clear the in memory registry
        registry = None

        # create and load from file
        registry = DeviceRegistry()
        fsk_router = Router("fsk")
        registry.set_fsk_router(fsk_router)
        registry.load_from(REGISTRY_KVS)

        # dump the registry state
        registry.list()

        # get device intances, this will cause receive routes to be knitted up
        tv = registry.get("tv")
        fan = registry.get("fan")
        registry.fsk_router.list()

    @test_1
    def test_load_into(self):

        # create an in memory registry
        registry = DeviceRegistry()
        registry.add(Devices.MIHO005(device_id=0x68b), "tv")
        registry.add(Devices.ENER002(device_id=(0xC8C8C, 1)), "fan")

        class MyContext():pass
        context = MyContext()

        registry.load_into(context)
        print(context.tv)
        print(context.fan)

#----- TEST ROUTER ------------------------------------------------------------

class TestRouter(unittest.TestCase):
    def setUp(self):
        # seed the registry
        registry = DeviceRegistry()
        registry.add(Devices.MIHO005(device_id=0x68b), "tv")
        registry.add(Devices.ENER002(device_id=(0xC8C8C, 1)), "fan")

        # test the auto create mechanism
        registry.load_into(self)

    @test_1
    def test_capabilities(self):
        print("tv switch:%s"  % self.tv.has_switch())
        print("tv send:%s"    % self.tv.can_send())
        print("tv receive:%s" % self.tv.can_receive())

        print("fan switch:%s"  % self.fan.has_switch())
        print("fan send:%s"    % self.fan.can_send())
        print("fan receive:%s" % self.fan.can_receive())

    @test_1
    def test_ook_tx(self):
        """Test the transmit pipeline"""

        self.fan.turn_on()
        self.fan.turn_off()

    @test_1
    def test_fsk_tx(self):
        """Test the transmit pipeline for MiHome FSK devices"""

        self.tv.turn_on()
        self.tv.turn_off()

    @test_1
    def test_fsk_rx(self):
        """Test the receive pipeline for FSK MiHome adaptor"""

        #synthesise receiving a report message
        #push it down the receive pipeline
        #radio.receive()
        # ->OpenThingsAirInterface.incoming
        # ->OpenThings.decrypt
        # ->OpenThings.decode
        # ->OpenThingsAirInterface->route
        # ->MIHO005.incoming_message()
        #
        #it should update voltage, power etc
        # poor mans incoming synthetic message

        report = OpenThings.Message(Devices.MIHO005_REPORT)
        report.set(recs_VOLTAGE_value=240,
                   recs_CURRENT_value=2,
                   recs_FREQUENCY_value=50,
                   recs_REAL_POWER_value=100,
                   recs_REACTIVE_POWER_value=0,
                   recs_APPARENT_POWER_value=100)
        self.tv.incoming_message(report)

        # get readings from device
        voltage   = self.tv.get_voltage()
        frequency = self.tv.get_frequency()
        power     = self.tv.get_real_power()
        switch    = self.tv.is_on()

        print("voltage %f"    % voltage)
        print("frequency %f"  % frequency)
        print("real power %f" % power)
        print("switch %s"     % switch)

#----- TEST DISCOVERY ---------------------------------------------------------

UNKNOWN_SENSOR_ID = 0x111

class TestDiscovery(unittest.TestCase):
    def setUp(self):
        # build a synthetic message
        self.msg = OpenThings.Message(Devices.MIHO005_REPORT)
        self.msg[OpenThings.PARAM_VOLTAGE]["value"] = 240

        self.fsk_router = Router("fsk")

        #OOK receive not yet written
        #It will be used to be able to learn codes from Energenie legacy hand remotes
        ##ook_router = Registry.Router("ook")

        self.registry = DeviceRegistry()
        self.registry.set_fsk_router(self.fsk_router)

    @test_1
    def test_discovery_none(self):
        self.fsk_router.when_unknown(None) # Discovery NONE

        # Poke synthetic unknown into the router and let it route to unknown handler
        self.msg.set(header_sensorid=UNKNOWN_SENSOR_ID)
        self.fsk_router.incoming_message(
            (Devices.MFRID_ENERGENIE, Devices.PRODUCTID_MIHO005, UNKNOWN_SENSOR_ID), self.msg)

        # expect unknown handler to fire

    @test_1
    def test_discovery_auto(self):
        d = AutoDiscovery(self.registry, self.fsk_router) # Discovery AUTO

        # Poke synthetic unknown into the router and let it route to unknown handler
        self.msg.set(header_sensorid=UNKNOWN_SENSOR_ID)
        self.fsk_router.incoming_message(
            (Devices.MFRID_ENERGENIE, Devices.PRODUCTID_MIHO005, UNKNOWN_SENSOR_ID), self.msg)

        # expect auto accept logic to fire
        self.registry.list()
        self.fsk_router.list()

    @test_1
    def test_discovery_ask(self):
        def yes(a,b): return True
        def no(a,b):  return False

        d = ConfirmedDiscovery(self.registry, self.fsk_router, no) # Discovery ASK(NO)

        # Poke synthetic unknown into the router and let it route to unknown handler
        self.msg.set(header_sensorid=UNKNOWN_SENSOR_ID)
        self.fsk_router.incoming_message(
            (Devices.MFRID_ENERGENIE, Devices.PRODUCTID_MIHO005, UNKNOWN_SENSOR_ID), self.msg)

        # expect a reject

        d = ConfirmedDiscovery(self.registry, self.fsk_router, yes) # Discovery ASK(YES)

        # Poke synthetic unknown into the router and let it route to unknown handler
        self.msg.set(header_sensorid=UNKNOWN_SENSOR_ID)
        self.fsk_router.incoming_message(
            (Devices.MFRID_ENERGENIE, Devices.PRODUCTID_MIHO005, UNKNOWN_SENSOR_ID), self.msg)

        # expect a accept
        self.registry.list()
        self.fsk_router.list()

    @test_1
    def test_discovery_autojoin(self):
        d = JoinAutoDiscovery(self.registry, self.fsk_router) # Discovery AUTO JOIN

        # Poke synthetic unknown JOIN into the router and let it route to unknown handler
        msg = Devices.MIHO005.get_join_req(UNKNOWN_SENSOR_ID)

        self.fsk_router.incoming_message(
            (Devices.MFRID_ENERGENIE, Devices.PRODUCTID_MIHO005, UNKNOWN_SENSOR_ID), msg)

        # expect auto accept and join_ack logic to fire
        self.registry.list()
        self.fsk_router.list()

    @test_1
    def test_discovery_askjoin(self):
        def no(a,b): return False
        def yes(a,b): return True

        d = JoinConfirmedDiscovery(self.registry, self.fsk_router, no) # Discovery ASK JOIN(NO)

        # Poke synthetic unknown JOIN into the router and let it route to unknown handler
        msg = Devices.MIHO005.get_join_req(UNKNOWN_SENSOR_ID)
        self.fsk_router.incoming_message(
            (Devices.MFRID_ENERGENIE, Devices.PRODUCTID_MIHO005, UNKNOWN_SENSOR_ID), msg)

        # expect reject
        self.registry.list()
        self.fsk_router.list()

        d = JoinConfirmedDiscovery(self.registry, self.fsk_router, yes) # Discovery ASK JOIN(YES)

        self.fsk_router.incoming_message(
            (Devices.MFRID_ENERGENIE, Devices.PRODUCTID_MIHO005, UNKNOWN_SENSOR_ID), msg)

        # expect auto accept and join_ack logic to fire
        self.registry.list()
        self.fsk_router.list()

if __name__ == "__main__":
    import OpenThings
    OpenThings.init(Devices.CRYPT_PID)

    unittest.main()

# END


text:
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLX import _types as _cs
# End users want this...
from OpenGL.raw.GLX._types import *
from OpenGL.raw.GLX import _errors
from OpenGL.constant import Constant as _C

import ctypes
_EXTENSION_NAME = 'GLX_SGIX_video_source'
def _f( function ):
    return _p.createFunction( function,_p.PLATFORM.GLX,'GLX_SGIX_video_source',error_checker=_errors._error_checker)

@_f
@_p.types(_cs.GLXVideoSourceSGIX,ctypes.POINTER(_cs.Display),_cs.c_int,_cs.VLServer,_cs.VLPath,_cs.c_int,_cs.VLNode)
def glXCreateGLXVideoSourceSGIX(display,screen,server,path,nodeClass,drainNode):pass
@_f
@_p.types(None,ctypes.POINTER(_cs.Display),_cs.GLXVideoSourceSGIX)
def glXDestroyGLXVideoSourceSGIX(dpy,glxvideosource):pass


text:
package notificationhubs

import (
	"context"

	original "github.com/Azure/azure-sdk-for-go/services/notificationhubs/mgmt/2017-04-01/notificationhubs"
)

const (
	DefaultBaseURI = original.DefaultBaseURI
)

type AccessRights = original.AccessRights

const (
	Listen AccessRights = original.Listen
	Manage AccessRights = original.Manage
	Send   AccessRights = original.Send
)

type NamespaceType = original.NamespaceType

const (
	Messaging       NamespaceType = original.Messaging
	NotificationHub NamespaceType = original.NotificationHub
)

type SkuName = original.SkuName

const (
	Basic    SkuName = original.Basic
	Free     SkuName = original.Free
	Standard SkuName = original.Standard
)

type AdmCredential = original.AdmCredential
type AdmCredentialProperties = original.AdmCredentialProperties
type ApnsCredential = original.ApnsCredential
type ApnsCredentialProperties = original.ApnsCredentialProperties
type BaiduCredential = original.BaiduCredential
type BaiduCredentialProperties = original.BaiduCredentialProperties
type BaseClient = original.BaseClient
type CheckAvailabilityParameters = original.CheckAvailabilityParameters
type CheckAvailabilityResult = original.CheckAvailabilityResult
type Client = original.Client
type CreateOrUpdateParameters = original.CreateOrUpdateParameters
type DebugSendResponse = original.DebugSendResponse
type DebugSendResult = original.DebugSendResult
type ErrorResponse = original.ErrorResponse
type GcmCredential = original.GcmCredential
type GcmCredentialProperties = original.GcmCredentialProperties
type ListResult = original.ListResult
type ListResultIterator = original.ListResultIterator
type ListResultPage = original.ListResultPage
type MpnsCredential = original.MpnsCredential
type MpnsCredentialProperties = original.MpnsCredentialProperties
type NamespaceCreateOrUpdateParameters = original.NamespaceCreateOrUpdateParameters
type NamespaceListResult = original.NamespaceListResult
type NamespaceListResultIterator = original.NamespaceListResultIterator
type NamespaceListResultPage = original.NamespaceListResultPage
type NamespacePatchParameters = original.NamespacePatchParameters
type NamespaceProperties = original.NamespaceProperties
type NamespaceResource = original.NamespaceResource
type NamespacesClient = original.NamespacesClient
type NamespacesDeleteFuture = original.NamespacesDeleteFuture
type Operation = original.Operation
type OperationDisplay = original.OperationDisplay
type OperationListResult = original.OperationListResult
type OperationListResultIterator = original.OperationListResultIterator
type OperationListResultPage = original.OperationListResultPage
type OperationsClient = original.OperationsClient
type PatchParameters = original.PatchParameters
type PnsCredentialsProperties = original.PnsCredentialsProperties
type PnsCredentialsResource = original.PnsCredentialsResource
type PolicykeyResource = original.PolicykeyResource
type Properties = original.Properties
type Resource = original.Resource
type ResourceListKeys = original.ResourceListKeys
type ResourceType = original.ResourceType
type SharedAccessAuthorizationRuleCreateOrUpdateParameters = original.SharedAccessAuthorizationRuleCreateOrUpdateParameters
type SharedAccessAuthorizationRuleListResult = original.SharedAccessAuthorizationRuleListResult
type SharedAccessAuthorizationRuleListResultIterator = original.SharedAccessAuthorizationRuleListResultIterator
type SharedAccessAuthorizationRuleListResultPage = original.SharedAccessAuthorizationRuleListResultPage
type SharedAccessAuthorizationRuleProperties = original.SharedAccessAuthorizationRuleProperties
type SharedAccessAuthorizationRuleResource = original.SharedAccessAuthorizationRuleResource
type Sku = original.Sku
type SubResource = original.SubResource
type WnsCredential = original.WnsCredential
type WnsCredentialProperties = original.WnsCredentialProperties

func New(subscriptionID string) BaseClient {
	return original.New(subscriptionID)
}
func NewClient(subscriptionID string) Client {
	return original.NewClient(subscriptionID)
}
func NewClientWithBaseURI(baseURI string, subscriptionID string) Client {
	return original.NewClientWithBaseURI(baseURI, subscriptionID)
}
func NewListResultIterator(page ListResultPage) ListResultIterator {
	return original.NewListResultIterator(page)
}
func NewListResultPage(getNextPage func(context.Context, ListResult) (ListResult, error)) ListResultPage {
	return original.NewListResultPage(getNextPage)
}
func NewNamespaceListResultIterator(page NamespaceListResultPage) NamespaceListResultIterator {
	return original.NewNamespaceListResultIterator(page)
}
func NewNamespaceListResultPage(getNextPage func(context.Context, NamespaceListResult) (NamespaceListResult, error)) NamespaceListResultPage {
	return original.NewNamespaceListResultPage(getNextPage)
}
func NewNamespacesClient(subscriptionID string) NamespacesClient {
	return original.NewNamespacesClient(subscriptionID)
}
func NewNamespacesClientWithBaseURI(baseURI string, subscriptionID string) NamespacesClient {
	return original.NewNamespacesClientWithBaseURI(baseURI, subscriptionID)
}
func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator {
	return original.NewOperationListResultIterator(page)
}
func NewOperationListResultPage(getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage {
	return original.NewOperationListResultPage(getNextPage)
}
func NewOperationsClient(subscriptionID string) OperationsClient {
	return original.NewOperationsClient(subscriptionID)
}
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
	return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func NewSharedAccessAuthorizationRuleListResultIterator(page SharedAccessAuthorizationRuleListResultPage) SharedAccessAuthorizationRuleListResultIterator {
	return original.NewSharedAccessAuthorizationRuleListResultIterator(page)
}
func NewSharedAccessAuthorizationRuleListResultPage(getNextPage func(context.Context, SharedAccessAuthorizationRuleListResult) (SharedAccessAuthorizationRuleListResult, error)) SharedAccessAuthorizationRuleListResultPage {
	return original.NewSharedAccessAuthorizationRuleListResultPage(getNextPage)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
	return original.NewWithBaseURI(baseURI, subscriptionID)
}
func PossibleAccessRightsValues() []AccessRights {
	return original.PossibleAccessRightsValues()
}
func PossibleNamespaceTypeValues() []NamespaceType {
	return original.PossibleNamespaceTypeValues()
}
func PossibleSkuNameValues() []SkuName {
	return original.PossibleSkuNameValues()
}
func UserAgent() string {
	return original.UserAgent() + " profiles/preview"
}
func Version() string {
	return original.Version()
}


text:
  {{- partial "_components/time.html" (dict "context" . "show_time" true ) -}}

      {{- markdownify .Title -}}

  {{- partial "_components/item-summary.html" . -}}
  {{/*  {{- partial "_components/event-venue.html" . -}}  */}}


text:
[![Build Status](https://travis-ci.org/mwmahlberg/pkv.svg?branch=master)](https://travis-ci.org/mwmahlberg/pkv)
[![Coverage Status](https://coveralls.io/repos/mwmahlberg/pkv/badge.svg?branch=master&service=github)](https://coveralls.io/github/mwmahlberg/pkv?branch=master)
# PKV – Partial Key Verification

PKV is an implementation of the Partial Key Verification pattern for product keys as described by [Brandon Stagg in "Implementing a Partial Serial Number Verification System in Delphi"][pkv] for the Go programming language.

Contrary to Brandon's example, it offers variable matrixes. Those matrices  are generated using secure cryprographic random number generators.

PKV comes as a command line tool which generates go code to include in your application offering functions to verify the chosen portion and the checksum of the key.

## State of project

The project is in a *very* early stage. Almost all of the documentation is lacking, as are most unit tests. The API most likely will change.

For that reason, make sure that you only use a versioned import, as described below

However, it works as intended.

## How it works

Basically, each product key generated with  `pkv` consists of a public seed, four key parts and a checksum. The idea behing PKV is that only one of those four key parts is checked wether it is valid to make it easier for the developer to mitigate a successful crack. A cracker can only create a key generator for the checked key part. For the next release, simply change the key part checked and the according generators and/or patches will not work any more, but all keys issued by you will still be valid. This will not eliminate problems or losses, but reduce them.

## Installation

`go get -u "gopkg.in/mwmahlberg/pkv.v1"`

This installs the package (which is not so interesting) and the command line tool, which is the primary tool you will work with.

## Usage

> Please ***NEVER*** include the package `"gopkg.in/mwmahlberg/pkv.v1"` into your software unless you write a key **generator**.

Use the `pkv.v1` command line tool inside your package directory.

 1. Call `pkv.v1 init`. This creates a file named `pkv.key` with key parameters used to generate the actual product keys. ***Never, ever make this file publicly available!***
 2. Call `pkv.v1 gencode -k [1-4]`. The flag denotes the key part to be checked. `pkv.v1` will generate the necessary code in a subdirectory:

        $GOPATH/example.com/you/cool
        └── internal
    	    ├── pkvcheck.go
    	    └── pkvtools.go

 3. Import the package inside your code with an *absolute* import and check the product key:

        package main

        import (
            "fmt"
            "example.com/cool/internal"
        )

        func main() {
		var key       string = getKeyFromSomewhere()
		var blacklist []uint64 = loadBlacklistFromServer()

		if err := internal.KeyChecksum(key); err != nil {
		    fmt.Println("Key checksum verification failed.")
		    fmt.Println("Possibly an error during entering the product key")
			panic(err)
		}

		if err := internal.Key(key, blacklist); err != nil {
			fmt.Println("Key verification failed.")
		    fmt.Println("Possibly a tampered or backlisted key.")
			panic(err)
		}

        }

 4. To generate a key, simply call `pkv.v1 genkey -s 123456`. The value for `-s` is called seed and identifies the generated key uniquely. Furthermore, this is the value you need to blacklist a product key. So make sure you keep track of the seed you used for generating a product key for a user! The combination of `pkv.key` and the seed can be used to regenerate a key.

[pkv]: http://www.brandonstaggs.com/2007/07/26/implementing-a-partial-serial-number-verification-system-in-delphi/