text:
/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

namespace Altavant.Fusion.UI.Aero
{
	using Fusion.UI.Blocks;

	public abstract class PanelFrame : IPanelFrame
	{
		protected Layer _owner;
		protected IPanel _panel;
		protected bool _attached;
		protected bool _constructed;
		protected bool _active;

		protected PanelFrame()
		{

		}

		public Layer Owner
		{
			get
			{
				return _owner;
			}
			set
			{
				_owner = value;
			}
		}

		public bool Attached
		{
			get
			{
				return _attached;
			}
		}

		public bool Constructed
		{
			get
			{
				return _constructed;
			}
		}

		public bool Active
		{
			get
			{
				return _active;
			}
		}

		public void Attach(IPanel panel)
		{
			if (_attached)
				return;

			_panel = panel;

			AttachImpl();

			_attached = true;
		}

		protected virtual void AttachImpl()
		{

		}

		public void Detach()
		{
			if (!_attached)
				return;

			DetachImpl();

			_panel.Behavior = null;

			_panel = null;

			_attached = false;
		}

		protected virtual void DetachImpl()
		{

		}

		public void Construct()
		{
			if (_constructed)
				return;

			ConstructImpl();

			_constructed = true;
		}

		protected virtual void ConstructImpl()
		{

		}

		public void Destroy()
		{
			if (!_constructed)
				return;

			DestroyImpl();

			_constructed = false;
		}

		protected virtual void DestroyImpl()
		{

		}

		public virtual void Layout()
		{

		}

		public virtual void TransitionInStart()
		{

		}

		public virtual void TransitionInEnd()
		{

		}

		public virtual void TransitionInCancel()
		{

		}

		public virtual void TransitionOutStart()
		{

		}

		public virtual void TransitionOutEnd()
		{

		}

		public virtual void TransitionOutCancel()
		{

		}

		public virtual void TransitionProgress(float value)
		{

		}

		public virtual BackButtonState GetBackButtonState()
		{
			return BackButtonState.Allowed;
		}
	}
}


text:
electricimp
===========

some electricimp examples

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Assets.InputMapper.Maths
{
    /// <summary>
    ///     Easing that uses a power function.
    /// </summary>
    public sealed class PowerEasing : Easing
    {
        public PowerEasing()
        {
            Power = 2.0d;
        }

        public double Power { get; set; }

        public override double GetValueCore(double t)
        {
            var d = Math.Pow(t, Math.Max(0.0d, Power));
            return d;
        }
    }
}


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var core_1 = require('angular2/core');
var ion_1 = require('../ion');
var app_1 = require('../app/app');
var config_1 = require('../../config/config');
var dom_1 = require('../../util/dom');
var view_controller_1 = require('../nav/view-controller');
var scroll_to_1 = require('../../animations/scroll-to');
/**
 * @name Content
 * @description
 * The Content component provides an easy to use content area with some useful
 * methods to control the scrollable area.
 *
 * The content area can also implement pull-to-refresh with the
 * [Refresher](../../scroll/Refresher) component.
 *
 * @usage
 * ```html
 * <ion-content>
 *   Add your content here!
 * </ion-content>
 * ```
 *
 */
var Content = (function (_super) {
    __extends(Content, _super);
    function Content(_elementRef, _config, _app, _zone, viewCtrl) {
        _super.call(this, _elementRef);
        this._elementRef = _elementRef;
        this._config = _config;
        this._app = _app;
        this._zone = _zone;
        this._padding = 0;
        if (viewCtrl) {
            viewCtrl.setContent(this);
            viewCtrl.setContentRef(_elementRef);
        }
    }
    /**
     * @private
     */
    Content.prototype.ngOnInit = function () {
        var self = this;
        self.scrollElement = self._elementRef.nativeElement.children[0];
        if (self._config.get('tapPolyfill') === true) {
            self._zone.runOutsideAngular(function () {
                self._scLsn = self.addScrollListener(function () {
                    self._app.setScrolling();
                });
            });
        }
    };
    /**
     * @private
     */
    Content.prototype.ngOnDestroy = function () {
        this._scLsn && this._scLsn();
        this.scrollElement = this._scLsn = null;
    };
    /**
     * @private
     * Adds the specified scroll handler to the content' scroll element.
     *
     * ```ts
     * @Page({
     *   template: `<ion-content id="my-content"></ion-content>`
     * )}
     * export class MyPage{
     *    constructor(app: IonicApp){
     *        this.app = app;
     *    }
     *   // Need to wait until the component has been initialized
     *   ngAfterViewInit() {
     *     // Here 'my-content' is the ID of my ion-content
     *     this.content = this.app.getComponent('my-content');
     *     this.content.addScrollListener(this.myScroll);
     *   }
     *     myScroll() {
     *      console.info('They see me scrolling...');
     *    }
     * }
     * ```
     * @param {Function} handler  The method you want perform when scrolling
     * @returns {Function} A function that removes the scroll handler.
     */
    Content.prototype.addScrollListener = function (handler) {
        return this._addListener('scroll', handler);
    };
    /**
     * @private
     */
    Content.prototype.addTouchStartListener = function (handler) {
        return this._addListener('touchstart', handler);
    };
    /**
     * @private
     */
    Content.prototype.addTouchMoveListener = function (handler) {
        return this._addListener('touchmove', handler);
    };
    /**
     * @private
     */
    Content.prototype.addTouchEndListener = function (handler) {
        return this._addListener('touchend', handler);
    };
    /**
     * @private
     */
    Content.prototype.addMouseDownListener = function (handler) {
        return this._addListener('mousedown', handler);
    };
    /**
     * @private
     */
    Content.prototype.addMouseUpListener = function (handler) {
        return this._addListener('mouseup', handler);
    };
    /**
     * @private
     */
    Content.prototype.addMouseMoveListener = function (handler) {
        return this._addListener('mousemove', handler);
    };
    Content.prototype._addListener = function (type, handler) {
        var _this = this;
        if (!this.scrollElement) {
            return;
        }
        // ensure we're not creating duplicates
        this.scrollElement.removeEventListener(type, handler);
        this.scrollElement.addEventListener(type, handler);
        return function () {
            if (!this.scrollElement) { return; }
            _this.scrollElement.removeEventListener(type, handler);
        };
    };
    /**
     * @private
     * Call a method when scrolling has stopped
     * @param {Function} callback The method you want perform when scrolling has ended
     */
    Content.prototype.onScrollEnd = function (callback) {
        var lastScrollTop = null;
        var framesUnchanged = 0;
        var _scrollEle = this.scrollElement;
        function next() {
            var currentScrollTop = _scrollEle.scrollTop;
            if (lastScrollTop !== null) {
                if (Math.round(lastScrollTop) === Math.round(currentScrollTop)) {
                    framesUnchanged++;
                }
                else {
                    framesUnchanged = 0;
                }
                if (framesUnchanged > 9) {
                    return callback();
                }
            }
            lastScrollTop = currentScrollTop;
            dom_1.raf(function () {
                dom_1.raf(next);
            });
        }
        setTimeout(next, 100);
    };
    Content.prototype.onScrollElementTransitionEnd = function (callback) {
        dom_1.transitionEnd(this.scrollElement, callback);
    };
    /**
     * Scroll to the specified position.
     *
     * ```ts
     * @Page({
     *   template: `<ion-content id="my-content">
     *      <button (click)="scrollTo()"> Down 500px</button>
     *   </ion-content>`
     * )}
     * export class MyPage{
     *    constructor(app: IonicApp){
     *        this.app = app;
     *    }
     *   // Need to wait until the component has been initialized
     *   ngAfterViewInit() {
     *     // Here 'my-content' is the ID of my ion-content
     *     this.content = this.app.getComponent('my-content');
     *   }
     *    scrollTo() {
     *      this.content.scrollTo(0, 500, 200);
     *    }
     * }
     * ```
     * @param {number} x  The x-value to scroll to.
     * @param {number} y  The y-value to scroll to.
     * @param {number} duration  Duration of the scroll animation in ms.
     * @param {TODO} tolerance  TODO
     * @returns {Promise} Returns a promise when done
     */
    Content.prototype.scrollTo = function (x, y, duration, tolerance) {
        if (this._scrollTo) {
            this._scrollTo.dispose();
        }
        this._scrollTo = new scroll_to_1.ScrollTo(this.scrollElement);
        return this._scrollTo.start(x, y, duration, tolerance);
    };
    /**
     * Scroll to the specified position.
     *
     * ```ts
     * @Page({
     *   template: `<ion-content id="my-content">
     *      <button (click)="scrollTop()"> Down 500px</button>
     *   </ion-content>`
     * )}
     * export class MyPage{
     *    constructor(app: IonicApp){
     *        this.app = app;
     *    }
     *   // Need to wait until the component has been initialized
     *   ngAfterViewInit() {
     *     // Here 'my-content' is the ID of my ion-content
     *     this.content = this.app.getComponent('my-content');
     *   }
     *    scrollTop() {
     *      this.content.scrollTop();
     *    }
     * }
     * ```
     * @returns {Promise} Returns a promise when done
     */
    Content.prototype.scrollToTop = function () {
        if (this._scrollTo) {
            this._scrollTo.dispose();
        }
        this._scrollTo = new scroll_to_1.ScrollTo(this.scrollElement);
        return this._scrollTo.start(0, 0, 300, 0);
    };
    /**
     * @private
     */
    Content.prototype.getScrollTop = function () {
        return this.getNativeElement().scrollTop;
    };
    /**
     * @private
     */
    Content.prototype.addCssClass = function (className) {
        this.getNativeElement().classList.add(className);
    };
    /**
     * @private
     */
    Content.prototype.removeCssClass = function (className) {
        this.getNativeElement().classList.remove(className);
    };
    /**
     * @private
     */
    Content.prototype.setScrollElementStyle = function (prop, val) {
        this.scrollElement.style[prop] = val;
    };
    /**
     * Returns the content and scroll elements' dimensions.
     * @returns {object} dimensions  The content and scroll elements' dimensions
     * {number} dimensions.contentHeight  content offsetHeight
     * {number} dimensions.contentTop  content offsetTop
     * {number} dimensions.contentBottom  content offsetTop+offsetHeight
     * {number} dimensions.contentWidth  content offsetWidth
     * {number} dimensions.contentLeft  content offsetLeft
     * {number} dimensions.contentRight  content offsetLeft + offsetWidth
     * {number} dimensions.scrollHeight  scroll scrollHeight
     * {number} dimensions.scrollTop  scroll scrollTop
     * {number} dimensions.scrollBottom  scroll scrollTop + scrollHeight
     * {number} dimensions.scrollWidth  scroll scrollWidth
     * {number} dimensions.scrollLeft  scroll scrollLeft
     * {number} dimensions.scrollRight  scroll scrollLeft + scrollWidth
     */
    Content.prototype.getContentDimensions = function () {
        var _scrollEle = this.scrollElement;
        var parentElement = _scrollEle.parentElement;
        return {
            contentHeight: parentElement.offsetHeight,
            contentTop: parentElement.offsetTop,
            contentBottom: parentElement.offsetTop + parentElement.offsetHeight,
            contentWidth: parentElement.offsetWidth,
            contentLeft: parentElement.offsetLeft,
            contentRight: parentElement.offsetLeft + parentElement.offsetWidth,
            scrollHeight: _scrollEle.scrollHeight,
            scrollTop: _scrollEle.scrollTop,
            scrollBottom: _scrollEle.scrollTop + _scrollEle.scrollHeight,
            scrollWidth: _scrollEle.scrollWidth,
            scrollLeft: _scrollEle.scrollLeft,
            scrollRight: _scrollEle.scrollLeft + _scrollEle.scrollWidth,
        };
    };
    /**
     * @private
     * Adds padding to the bottom of the scroll element when the keyboard is open
     * so content below the keyboard can be scrolled into view.
     */
    Content.prototype.addScrollPadding = function (newPadding) {
        if (newPadding > this._padding) {
            void 0;
            this._padding = newPadding;
            this.scrollElement.style.paddingBottom = newPadding + 'px';
        }
    };
    Content = __decorate([
        core_1.Component({
            selector: 'ion-content',
            template: '<scroll-content>' +
                '<ng-content></ng-content>' +
                '</scroll-content>' +
                '<ng-content select="ion-refresher"></ng-content>'
        }),
        __param(4, core_1.Optional()),
        __metadata('design:paramtypes', [core_1.ElementRef, config_1.Config, app_1.IonicApp, core_1.NgZone, view_controller_1.ViewController])
    ], Content);
    return Content;
})(ion_1.Ion);
exports.Content = Content;


text:
import datetime
import xmlrpclib
from twisted.application import service
from twisted.web import xmlrpc
from peloton.coreio import PelotonRequestInterface

def dump_xmlrpc_date(self, value, write):
    # according to spec at http://www.xmlrpc.com/spec XML-RPC date
    # is ISO 8601 format e.g. 19980717T14:08:55
    date = datetime.datetime.strftime(value, "%Y%m%dT%H:%M:%S")
    write("<value><dateTime.iso8601>%s</dateTime.iso8601></value>" % date)

def dump_xmlrpc_time(self, value, write):
    """ Serialize a datetime.time instance iso8601 format"""
    write("<value><dateTime.iso8601>%s</dateTime.iso8601></value>" % value.strftime("%Y%m%dT%H:%M:%S"))

def dump_xmlrpc_none(self, value, write):
    """ Handle None types by sending a string? """
    write("<value><nil/></value>")

class PelotonXMLRPCHandler(service.Service):
    """ XMLRPC protocol interface"""

    def __init__(self, kernel):
        self.kernel = kernel
        self.logger = kernel.logger
        self.requestInterface = PelotonRequestInterface(kernel)

        # Need to add a marshaler for datetime instances as xmlrpclib
        # will only marshall it's own style of datetime.
        xmlrpclib.Marshaller.dispatch[type(datetime.datetime.now())] = dump_xmlrpc_date
        xmlrpclib.Marshaller.dispatch[type(datetime.date(2007,1,1))] = dump_xmlrpc_date
        xmlrpclib.Marshaller.dispatch[type(datetime.time(0,0))] = dump_xmlrpc_time
        xmlrpclib.Marshaller.dispatch[type(None)] = dump_xmlrpc_none

        self.setResource()

    def xmlrpc_request(self, sessionId, *args, **kargs):
        """ Make a service request. Takes the following arguments:
    - service (string)
    - method (string)
    - <parameters>
"""
        service = args[0]
        method = args[1]
        params = args[2:]
        return self.requestInterface.public_call(sessionId, "raw", service, method, params, {})

    def setResource(self):
        """ Create the XMLRPC resource and attach all xmlrpc_* methods
to it. """
        x = xmlrpc.XMLRPC()
        publishedMethods = [i for i in dir(self) if i.startswith('xmlrpc_')]
        for mthd in publishedMethods:
            # equiv to x.<mthd> = self.<mthd>
            setattr(x, mthd, getattr(self, mthd))
        self._resource = x


text:
'use strict';

jest.autoMockOff();
jest.mock('jquery');

// Fixes https://github.com/facebook/jest/issues/78
jest.dontMock('react');
jest.dontMock('underscore');

describe("Server rendering", function () {
    var React;
    var App;
    var document;
    var home_url = "http://localhost/";
    var home = {
        "@id": "/",
        "@type": ["portal"],
        "portal_title": "ClinGen",
        "title": "Home"
    };

    beforeEach(function () {
        require('../../libs/react-patches');
        React = require('react');
        App = require('..');
        var server_app = <App context={home} href={home_url} />;
        var markup = '<!DOCTYPE html>\n' + React.renderToString(server_app);
        var parser = new DOMParser();
        document = parser.parseFromString(markup, 'text/html');
    });

    it("renders the application to html", function () {
        expect(document.title).toBe(home.portal_title);
    });

    it("react render http-equiv correctly", function () {
        var meta_http_equiv = document.querySelectorAll('meta[http-equiv]');
        expect(meta_http_equiv.length).not.toBe(0);
    });

    it("mounts the application over the rendered html", function () {
        var props = App.getRenderedProps(document);
        var app = React.render(<App {...props} />, document);
        expect(app.getDOMNode()).toBe(document.documentElement);
    });
});


text:
package com.example.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import org.testng.annotations.Test;

import com.example.fw.Folders;

public class TestFolderDeletion extends TestBase{

	@Test
	public void testFolderDeletion(){
		Folders oldFolders = app.getFolderHelper().getFolders();

		int index = generateRandomIndex(oldFolders.size());
		String folderDeleted = app.getFolderHelper().deleteFolder(index);

		Folders newFolders = app.getFolderHelper().getFolders();
		assertThat(newFolders, equalTo(oldFolders.without(folderDeleted)));
	}

}


text:
FROM ubuntu:16.04

RUN apt-get update && apt-get install -y apache2
CMD /usr/sbin/apachectl -D FOREGROUND


text:
package io.microgenie.service;

import io.dropwizard.Application;
import io.dropwizard.lifecycle.Managed;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.microgenie.application.ApplicationFactory;
import io.microgenie.service.bundle.AwsInitBundle;
import io.microgenie.service.bundle.PublishJsonSchemaBundle;
import io.microgenie.service.healthchecks.HealthCheckResource;

import java.text.SimpleDateFormat;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;

/***
 * Abstract Service Application class. The purpose is to handle initialization, service bootstrapping
 * and other common service tasks while just letting the services themselves define application factory,
 * register resources, health checks, queue consumers and event subscribers.
 *
 *

 * The service parent project handles the ordering by which this happens and delegates to the actual
 * service implementation for specifics via the template method pattern
 *
 * @author shawn
 *
 */
public abstract class MicroService<T extends AppConfiguration> extends Application<T>{

	protected abstract ApplicationFactory createApplicationFactory(final T configuration, final Environment environment);

	/**
 	* Register any application health checks
	*
 	* @param appFactory - {@link ApplicationFactory} - The application factory
	* @param configuration {@link AppConfiguration} - The application configuration
	* @param healthCheckRegistry - {@link HealthCheckRegistry} - The health check registry used to register HealthChecks for this service
	*/
	protected abstract void registerHealthChecks(final ApplicationFactory appFactory, final T configuration, final HealthCheckRegistry healthCheckRegistry);

	/***
	 * Register any custom application metrics
	 * @param appFactory
	 * @param configuration
	 * @param metricRegistry
	 */
	protected abstract void registerMetrics(final ApplicationFactory appFactory, final T configuration, final MetricRegistry metricRegistry);

	/***
	 * Register any Jersey resources
	 *
	 * @param appFactory
	 * @param configuration
	 * @param environment
	 */
	protected abstract void registerResources(final ApplicationFactory appFactory, final T configuration, final Environment environment);

	/**
	 * Initialize documentation and add bootstrap commands and bundles
	 * @param bootstrap - {@link Bootstrap}
	 */
	@Override
	public synchronized void initialize(Bootstrap<T> bootstrap) {
		bootstrap.addBundle(new AwsInitBundle());
		bootstrap.addBundle(new PublishJsonSchemaBundle());
	    this.bootstrap(bootstrap);
	}

	/**
	 * Bootstrap the service by adding commands and bundles
	 * @param bootstrap - {@link Bootstrap}
	 */
	protected abstract void bootstrap(Bootstrap<T> bootstrap);

	/***
	 * Run the application
	 * @param configuration - {@link AppConfiguration} - application configuration
	 * @param environment - {@link Environment} - dropwizard Environment
	 */
	@Override
	public void run(T configuration, final Environment environment) throws Exception {

		final SimpleDateFormat globalDateFormat = new SimpleDateFormat(configuration.getDateFormat());

		/** set object mapper data format pattern **/
		environment.getObjectMapper().setDateFormat(globalDateFormat);

		/** Initialize the application factory **/
		final ApplicationFactory appFactory = this.createApplicationFactory(configuration, environment);
		this.manageApplicationFactory(appFactory, environment);

		/** register metrics, health checks and jersey resources **/
		this.registerMetrics(appFactory, configuration, environment.metrics());
		this.registerHealthChecks(appFactory, configuration, environment.healthChecks());
		this.registerResources(appFactory, configuration, environment);

        /** register the Health Check API endpoint **/
        environment.jersey().register(new HealthCheckResource(environment.healthChecks()));
	}

	/***
	 * Manage the {@link ApplicationFactory} in terms of starting up and shutting down resources.
	 *

	 * @param appFactory - The application factory to manage
	 * @param environment - The environment
	 */
	protected void manageApplicationFactory(final ApplicationFactory appFactory, final Environment environment){
		final Managed managedAppFactory = new Managed() {
			@Override
			public void start() throws Exception {

			}
			@Override
			public void stop() throws Exception {
				appFactory.close();
			}
		};
		environment.lifecycle().manage(managedAppFactory);
	}
}


text:
import { BotsController } from './bots.controller';

export const BotsState = {
    url: '',
    template: require('./bots.module.html'),
    controller: BotsController,
    controllerAs: 'vm'
};


text:
package metric

import (
	"strings"
)

//ReportConfidence is metric type for Temporal Metrics
type ReportConfidence int

//Constant of ReportConfidence result
const (
	ReportConfidenceNotDefined ReportConfidence = iota
	ReportConfidenceUnknown
	ReportConfidenceReasonable
	ReportConfidenceConfirmed
)

var reportConfidenceMap = map[ReportConfidence]string{
	ReportConfidenceNotDefined: "X",
	ReportConfidenceUnknown:    "U",
	ReportConfidenceReasonable: "R",
	ReportConfidenceConfirmed:  "C",
}

var reportConfidenceValueMap = map[ReportConfidence]float64{
	ReportConfidenceNotDefined: 1,
	ReportConfidenceUnknown:    0.92,
	ReportConfidenceReasonable: 0.96,
	ReportConfidenceConfirmed:  1,
}

//GetReportConfidence returns result of ReportConfidence metric
func GetReportConfidence(s string) ReportConfidence {
	s = strings.ToUpper(s)
	for k, v := range reportConfidenceMap {
		if s == v {
			return k
		}
	}
	return ReportConfidenceNotDefined
}

func (rc ReportConfidence) String() string {
	if s, ok := reportConfidenceMap[rc]; ok {
		return s
	}
	return ""
}

//Value returns value of ReportConfidence metric
func (rc ReportConfidence) Value() float64 {
	if v, ok := reportConfidenceValueMap[rc]; ok {
		return v
	}
	return 1
}

//IsDefined returns false if undefined result value of metric
func (rc ReportConfidence) IsDefined() bool {
	_, ok := reportConfidenceValueMap[rc]
	return ok
}

/* Contributed by Spiegel, 2020 */


text:
package com.sdl.ecommerce.odata.model;

import com.sdl.ecommerce.api.model.ProductRef;
import com.sdl.odata.api.edm.annotations.EdmComplex;
import com.sdl.odata.api.edm.annotations.EdmProperty;

/**
 * ODataProductRef
 *
 * @author nic
 */
@EdmComplex(name = "ProductRef", namespace = "SDL.ECommerce")
public class ODataProductRef {

    @EdmProperty
    private String id;

    @EdmProperty
    private String name;

    public ODataProductRef() {}
    public ODataProductRef(ProductRef productRef) {
        this.id = productRef.getId();
        this.name = productRef.getName();
    }

    public ProductRef getReference() {
        return new ProductRef(this.id, this.name);
    }
}


text:
package org.alien4cloud.tosca.model.workflow.conditions;

import java.util.List;

import lombok.Getter;
import lombok.Setter;

/**
 * Abstract class for condition clauses.
 */
@Getter
@Setter
public class AbstractConditionClause {
    /** Defines an and clause where every defined clauses has to be considered truly so the clause is considered truly. */
    @Getter
    @Setter
    public static class AndConditionClause extends AbstractConditionClause {
        private List<AbstractConditionClause> clauses;
    }

    /** Defines an or clause where one of the defined clauses has to be considered truly so the clause is considered truly. */
    @Getter
    @Setter
    public static class OrConditionClause extends AbstractConditionClause {
        private List<AbstractConditionClause> clauses;
    }

    /**
     * Defines a clause with assertions against a node or relationship attributes. As in an and clause all assertions have to be truly so the assert clause is
     * considered truly.
     */
    @Getter
    @Setter
    public static class AssertConditionClause extends AbstractConditionClause {
        /** */
        private List<AssertionDefinition> assertions;
    }
}


text:
window.twttr = (function (d,s,id) {
  var t, js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
  js.src="//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
  return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
}(document, "script", "twitter-wjs"));

// Configure Messenger
Messenger.options = {
	extraClasses: 'messenger-fixed messenger-on-top',
	theme: 'block',
  messageDefaults: {
    showCloseButton: true,
    retry: { allow: false }
  }
};

// Public: JS implementation of Rails #to_sentence.
//
// Example -
//  [1, 2, 3].to_sentence();
//  # => "1, 2 and 3"
Array.prototype.to_sentence = function() {
  return this.join(", ").replace(/,\s([^,]+)$/, ' and $1');
};

// Public: Javascript implementation of Rails #capitalize.
String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

// Public: Show the first help modal.
window.showHelp = function(e) {
  $("#helpModals .modal:first").modal("show");
  Analytics.trackEvent("Help", "Shown", (e ? "Clicked" : "Programatically initiated"));
  if (e) { e.preventDefault(); }
};

// Bind the help modal to the help link.
$(function() {
  $("a#help").click(window.showHelp);

  // Initialize help modal buttons.
  $("#helpModals .modal .next").on("click", function(e) {
    var currentModal = $(this).parents(".modal");
    currentModal.modal("hide");
    currentModal.next().modal("show");
    Analytics.trackEvent("Help", "Next", currentModal.index()+1);
    e.preventDefault();
  });

  // Mobile navigation JS
  $("#toggle-mobile-nav").tappable(function(e) {
    $(".mobile-nav li:nth-child(n+2)").toggleClass("visible");
    e.preventDefault();
  });
});


text:
<configuration>

    <!-- The underlying appender will be the standard console one. -->
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                %d [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
        <appender-ref ref="stdout"/>
        <discardingThreshold>0</discardingThreshold>
    </appender>
    <!-- Direct all logging through the AsyncAppender. -->
    <root level="info">
        <appender-ref ref="async"/>
    </root>

</configuration>


text:
namespace cc {

TEST(TilePriorityTest, IsHigherPriorityThan) {
  TilePriority now(HIGH_RESOLUTION, TilePriority::NOW, 0);
  TilePriority close_soon(HIGH_RESOLUTION, TilePriority::SOON, 1);
  TilePriority far_soon(HIGH_RESOLUTION, TilePriority::SOON, 500);
  TilePriority close_eventually(HIGH_RESOLUTION, TilePriority::EVENTUALLY, 2);
  TilePriority far_eventually(HIGH_RESOLUTION, TilePriority::EVENTUALLY, 1000);
  TilePriority non_ideal_now(NON_IDEAL_RESOLUTION, TilePriority::NOW, 0);

  EXPECT_FALSE(now.IsHigherPriorityThan(now));
  EXPECT_FALSE(now.IsHigherPriorityThan(non_ideal_now));

  EXPECT_TRUE(now.IsHigherPriorityThan(close_soon));
  EXPECT_TRUE(now.IsHigherPriorityThan(far_soon));
  EXPECT_TRUE(now.IsHigherPriorityThan(close_eventually));
  EXPECT_TRUE(now.IsHigherPriorityThan(far_eventually));
  EXPECT_TRUE(close_soon.IsHigherPriorityThan(far_soon));
  EXPECT_TRUE(close_soon.IsHigherPriorityThan(close_eventually));
  EXPECT_TRUE(close_soon.IsHigherPriorityThan(far_eventually));
  EXPECT_TRUE(far_soon.IsHigherPriorityThan(close_eventually));
  EXPECT_TRUE(far_soon.IsHigherPriorityThan(far_eventually));
  EXPECT_TRUE(close_eventually.IsHigherPriorityThan(far_eventually));

  EXPECT_FALSE(far_eventually.IsHigherPriorityThan(close_eventually));
  EXPECT_FALSE(far_eventually.IsHigherPriorityThan(far_soon));
  EXPECT_FALSE(far_eventually.IsHigherPriorityThan(close_soon));
  EXPECT_FALSE(far_eventually.IsHigherPriorityThan(now));
  EXPECT_FALSE(far_eventually.IsHigherPriorityThan(non_ideal_now));
  EXPECT_FALSE(close_eventually.IsHigherPriorityThan(far_soon));
  EXPECT_FALSE(close_eventually.IsHigherPriorityThan(close_soon));
  EXPECT_FALSE(close_eventually.IsHigherPriorityThan(now));
  EXPECT_FALSE(far_soon.IsHigherPriorityThan(close_soon));
  EXPECT_FALSE(far_soon.IsHigherPriorityThan(now));
  EXPECT_FALSE(close_soon.IsHigherPriorityThan(now));
}

}  // namespace cc


text:
from datetime import date
import os
import tempfile
from io import StringIO
from django.contrib.gis.gdal import DataSource
from django.utils.text import slugify
from django.test import TestCase
from organisations.models import (
    DivisionGeography,
    Organisation,
    OrganisationDivision,
    OrganisationDivisionSet,
)
from organisations.management.commands.import_lgbce import Command

class ImportLgbceTests(TestCase):
    def setUp(self):
        self.test_data_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "test_data",
            "test_shapefile",
            "test_shapefile.shp",
        )

        # an org with no division set
        self.org1 = Organisation.objects.create(
            official_identifier="TEST1",
            organisation_type="local-authority",
            official_name="Test Council 1",
            slug="test1",
            territory_code="ENG",
            election_name="Test Council 1 Local Elections",
            start_date=date(2016, 10, 1),
        )

        # valid org/div
        self.valid_org_code = "TEST2"
        valid_org = Organisation.objects.create(
            official_identifier=self.valid_org_code,
            organisation_type="local-authority",
            official_name="Test Council 2",
            slug="test2",
            territory_code="ENG",
            election_name="Test Council 2 Local Elections",
            start_date=date(2016, 10, 1),
        )
        self.valid_divset = OrganisationDivisionSet.objects.create(
            organisation=valid_org,
            start_date="2016-10-01",
            end_date=None,
            legislation_url="",
            consultation_url="",
            short_title="",
            notes="",
        )
        division_names = [
            "Furley",
            "Bybrook",
            "Conningbrook & Little Burton Farm",
            "Bockhanger",
            "Kennington",
        ]
        for division_name in division_names:
            OrganisationDivision.objects.create(
                official_identifier=division_name,
                divisionset=self.valid_divset,
                name=division_name,
                slug=slugify(division_name),
                division_type="DIW",
                seats_total=1,
            )

    def run_import_with_test_data(self, org, name_map):
        cmd = Command()
        cmd.get_data = lambda x: (tempfile.mkdtemp(), DataSource(self.test_data_path))
        cmd.get_name_map = lambda x: name_map
        args = {
            "org": org,
            "s3": "foo.bar/baz",
            "name_column": "Ward_name",
            "srid": "27700",
        }
        cmd.stderr = StringIO()
        cmd.handle(**args)
        cmd.stderr.seek(0)
        error_output = cmd.stderr.read()
        return error_output

    def test_org_not_found(self):
        with self.assertRaises(Organisation.DoesNotExist):
            self.run_import_with_test_data("NOT-AN-ORG", {})

    def test_divset_not_found(self):
        with self.assertRaises(OrganisationDivisionSet.DoesNotExist):
            self.run_import_with_test_data("TEST1", {})

    def test_divset_has_no_divisions(self):
        # add an empty division set to org1
        OrganisationDivisionSet.objects.create(
            organisation=self.org1,
            start_date="2016-10-01",
            end_date=None,
            legislation_url="",
            consultation_url="",
            short_title="",
            notes="",
        )

        with self.assertRaises(Exception):
            self.run_import_with_test_data("TEST1", {})

    def test_divset_has_end_date(self):
        # divset has divisions and no related geographies but has end date

        # normally this setup would import fine, but we're going to
        # set an end date on the division set so it should fail
        self.valid_divset.end_date = "2018-05-02"
        self.valid_divset.save()

        with self.assertRaises(Exception):
            self.run_import_with_test_data(self.valid_org_code, {})

    def test_names_dont_match(self):
        # there's some names in the test file that don't match the ones in the database
        # but we'll pass an empty name_map - this should cause a failure
        name_map = {}
        error_output = self.run_import_with_test_data(self.valid_org_code, name_map)
        self.assertEqual(
            "Failed: legislation_names != boundary_names", error_output[:43]
        )

    def test_valid(self):
        # all data is valid - should import cleanly

        # this time we'll pass a name_map so all the areas can import
        name_map = {
            "Conningbrook and Little Burton Farm": "Conningbrook & Little Burton Farm"
        }
        self.run_import_with_test_data(self.valid_org_code, name_map)

        # ensure all of our divisions now have a geography attached to them
        count = 0
        for d in self.valid_divset.divisions.all():
            try:
                d.geography
                count = count + 1
            except DivisionGeography.DoesNotExist:
                pass
        self.assertEqual(5, count)

    def test_divisionset_has_related_geographies(self):
        name_map = {
            "Conningbrook and Little Burton Farm": "Conningbrook & Little Burton Farm"
        }
        self.run_import_with_test_data(self.valid_org_code, name_map)

        # now that we've imported geographies for this divisionset once,
        # if we try to do it again then it should fail
        # because the divisionset has related geographies now
        with self.assertRaises(Exception):
            self.run_import_with_test_data(self.valid_org_code, name_map)


text:
ACCEPTED

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

#### Published in
L. Diels, Bot. Jahrb. Syst. 29:396. 1900

#### Original name
null

### Remarks
null


text:
<TITLE>Review for Sleepy Hollow (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Sleepy Hollow (1999)

reviewed by
David N. Butterworth

SLEEPY HOLLOW
A film review by David N. Butterworth
Copyright 1999 David N. Butterworth

** (out of ****)

        "Heads will roll" is the campy tagline for the latest film based on
Washington Irving's classic fable about a horseman with a penchant for
rendering his victims headless, but the ratings board figured there were
too many decapitations in Tim Burton's latest extravaganza and slapped
"Sleepy Hollow" with an "R."  That's a bit of a blow to a film which, in
hindsight, might have done better with a Halloween--rather than a
Thanksgiving--release.

        Burton's film is a strange fish regardless.  Although typically
ghoulish and macabre for the director of "Batman" and "Beetlejuice," it's
too bleak for kids, who'll have to drag a seventeen-year-old along with
them to see it.  And it's too relentless for adults, who are likely to grow
tired of its unsparing focus on severed heads bouncing through the
undergrowth.  Still, they might find some comfort in Rick Heinrichs'
Burton-esque production design or Johnny Depp's no-nonsense performance as
New York constable Ichabod Crane.

        Depp, in his third film with the director (following "Edward
Scissorhands" and "Ed Wood"), is deliciously affected as Crane, a dandy of
a policeman circa 1799 who's sent to the town of Sleepy Hollow in the
Hudson Islands to investigate the mysterious slayings of three of its
locals.  "Their heads were...gone?" gulps Depp when the town's
representatives fill him in on the gory goings-on.  Depp has a great way of
speaking in the film: mannered, polite, and with just a hint of the King's
English.

        Sleepy Hollow's spokespersons are an interesting mix of talent
decked out in fascinating period wardrobes that make them look like
characters in a Lewis Carroll novel, among them Michael Gambon, Miranda
Richardson, Jeffrey Jones, Michael Gough, and Richard Griffiths.  Christina
Ricci, who plays Katrina Van Tassel, provides the pulchritudinous love
interest but isn't given much to do and certainly doesn't connect in any
way with Depp's character.  Also on board, albeit briefly, is horror
veteran Christopher Lee, whose Hammer horror films of the '60s "Sleepy
Hollow" most closely resembles.

        The "R" rating is unfortunate because "Sleepy Hollow," like
Hammer's slew of Dracula pictures, is clearly a gothic fantasy and its
bloodlettings more ludicrously camp than graphic (although Burton never
spares us the post-decapitation shot and seems to revel in squirting blood
in Depp's face at every opportunity).  Since Irving's novel is the stuff of
American folklore, however, it's a pity Burton couldn't have done more with
it.  He's dressed it up some, and then painted it depressingly black.  And
he's milked a great performance from Depp but asked him, for the most part,
only to react to lifeless corpses.

        "Sleepy Hollow" never quite finds its footing despite some strong
performances and a great look (including a creepy-looking windmill in the
closing scenes that recalls Burton's debut short, "Frankenweenie").  As for
that tagline, heads are more likely to be scratched, and it's the eyes that
will be doing the rolling during "Sleepy Hollow."

--
David N. Butterworth
dnb@dca.net

Got beef?  Visit "La Movie Boeuf"
online at http://members.dca.net/dnb

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?php

namespace PM\Main\Filesystem;

/**
 * This script defines class for manage file in filesystem.
 *
 * @author     Martin Kovar
 * @category   Performance
 * @package    Main
 */
class File {

    /**
     * File pointer from fopen function.
     *
     * @var resource
     */
    private $_filePointer = null;

    /**
     * Dirname of file.
     *
     * @var string
     */
    private $_path = null;

    /**
     * Filename of file.
     *
     * @var string
     */
    private $_name = null;

    /**
     * Offset of read method.
     *
     * @var int
     */
    private $_readOffset = 0;

    /**
     * Offset of write method.
     *
     * @var int
     */
    private $_writeOffset = 0;

    /**
     * Flag for synchronization offsets.
     *
     * @var boolean
     */
    private $_syncOffsets = false;

    /**
     * Construct method.
     *
     * @param string  $path        Dirname of file
     * @param string  $name        Filename of file
     * @param boolean $open        Flag for automatic open file
     * @param boolean $autoCreate  Flag for automatic creation of file when it doesn't exist
     * @param booelan $syncOffsets Flag for synchronization offsets
     *
     * @return void
     */
    public function __construct($path, $name, $open = true, $autoCreate = false, $syncOffsets = false) {
        $this->_path        = $path;
        $this->_name        = $name;
        $this->_syncOffsets = $syncOffsets;

        if ($open === true) {
            $this->open($autoCreate);
        } elseif ($autoCreate === true) {
            $this->_createFile();
        }
    }

    /**
     * It provides copy this file to new path and create new instance of the copy.
     *
     * @param string $path Dirname of new file
     *
     * @return \PM\Main\Filesystem\File
     */
    public function copy($path) {
        copy($this->_getFilepath(), $path.'/'.$this->getName());
        $copy = new self($path, $this->_name, false, false, $this->_syncOffsets);

        return $copy;
    }

    /**
     * Returns filename of file.
     *
     * @return string
     */
    public function getName() {
        return $this->_name;
    }

    /**
     * Returns dirname of file.
     *
     * @return string
     */
    public function getPath() {
        return $this->_path;;
    }

    /**
     * Returns size of file in bytes.
     *
     * @return int
     */
    public function getFilesize() {
        return filesize($this->_getFilepath());
    }

    /**
     * Returns last modification date.
     *
     * @return int
     */
    public function getModificationDate() {
        return filemtime($this->_getFilepath());
    }

    /**
     * Returns flag that file is open.
     *
     * @return boolean
     */
    public function isOpen() {
        return $this->_filePointer !== null;
    }

    /**
     * Open file and sets pointer to default values.
     *
     * @param boolean $autoCreate Flag for automatic create file when doesn't exist
     *
     * @return \PM\Main\Filesystem\File
     */
    public function open($autoCreate = false) {
        if ($autoCreate === false) {
            $this->_checkFileExist();
        }

        if ($this->isOpen()) {
            $this->close();
        }

        $this->_createFile();
        $this->_filePointer = fopen($this->_getFilepath(), 'a+');
        $this->_readOffset  = 0;
        $this->_writeOffset = ftell($this->_filePointer);
        $this->_synchronizeOffsets($this->_writeOffset);

        return $this;
    }

    /**
     * Close file pointer.
     *
     * @return \PM\Main\Filesystem\File
     */
    public function close() {
        $this->_checkOpen();

        fclose($this->_filePointer);
        $this->_filePointer = null;

        return $this;
    }

    /**
     * Write data to file. It is alias for write method.
     *
     * @param string $data Data to save
     *
     * @return \PM\Main\Filesystem\File
     */
    public function fputs($data) {
        $this->write($data);

        return $this;
    }

    /**
     * Write data to file.
     *
     * @param string $data Data to save
     *
     * @return \PM\Main\Filesystem\File
     */
    public function write($data) {
        $this->_checkOpen();

        fseek($this->_filePointer, $this->_writeOffset);
        fwrite($this->_filePointer, $data);
        $this->_writeOffset = ftell($this->_filePointer);
        $this->_synchronizeOffsets($this->_writeOffset);

        return $this;
    }

    /**
     * Returns data from actual pointer to end line
     *
     * @return string
     */
    public function fgets() {
        $this->_checkOpen();

        fseek($this->_filePointer, $this->_readOffset);
        $data = fgets($this->_filePointer);
        $this->_readOffset = ftell($this->_filePointer);
        $this->_synchronizeOffsets($this->_readOffset);

        return $data;
    }

    /**
     * Reads entire file into an array
     *
     * @return array the file in an array.
     */
    public function file() {
        $this->_checkFileExist();
        $data = array();

        while(($line = fgets($this->_filePointer))) {
            $data[] = $line;
        }

        return $data;
    }

    /**
     * It provides touch method for file.
     *
     * @param boolean $autoCreate Flag for automatic create file when doesn't exist
     *
     * @return \PM\Main\Filesystem\File
     */
    public function touch($autoCreate = true) {
        if ($autoCreate === false) {
            $this->_checkFileExist();
        }

        touch($this->_getFilepath());

        return $this;
    }

    /**
     * It provides delete method for file. It close pointer and unlink file from filesystem.
     *
     * @return \PM\Main\Filesystem\File
     */
    public function delete() {
        if ($this->isOpen() === true) {
            $this->close();
        }

        umask(0000);
        unlink($this->_getFilepath());
        $this->setReadOffset(0);
        $this->setWriteOffset(0);

        return $this;
    }

    /**
     * Gets read offset.
     *
     * @return int
     */
    public function getReadOffset() {
        return $this->_readOffset;
    }

    /**
     * Sets read offset.
     *
     * @param int $offset Offset of read pointer
     *
     * @return \PM\Main\Filesystem\File
     */
    public function setReadOffset($offset) {
        $this->_readOffset = $offset;
        $this->_synchronizeOffsets($offset);

        return $this;
    }

    /**
     * Gets write offset.
     *
     * @return int
     */
    public function getWriteOffset() {
        return $this->_writeOffset;
    }

    /**
     * Sets write offset.
     *
     * @param int $offset Offset of write pointer
     *
     * @return \PM\Main\Filesystem\File
     */
    public function setWriteOffset($offset) {
        $this->_writeOffset = $offset;
        $this->_synchronizeOffsets($offset);

        return $this;
    }

    /**
     * Returns that file exists in filesystem.
     *
     * @return boolean
     */
    public function fileExist() {
        return $this->_isFileExist();
    }

    /**
     * Destruct method. It close file pointer.
     *
     * @return void
     */
    public function __destruct() {
        if ($this->_filePointer !== null && $this->isOpen() === true) {
            $this->close();
        }
    }

    /**
     * It creates file when doesn't exist.
     *
     * @return \PM\Main\Filesystem\File
     */
    private function _createFile() {
        if ($this->_isFileExist() === false) {
            touch($this->_getFilepath());
            $this->_checkFileExist();
        }

        return $this;
    }

    /**
     * Returns whole path of file include dirname and filename.
     *
     * @return string
     *
     * @throws \PM\Main\Filesystem\Exception Throws when path or name is not set.
     */
    private function _getFilepath() {
        if ($this->_path === null || $this->_name === null) {
            throw new Exception('Path or name is not set.');
        }

        return $this->_path.'/'.$this->_name;
    }

    /**
     * Method for synchronize offsets when synchronization is enabled.
     *
     * @param int $pointer New pointer value for synchronize
     *
     * @return \PM\Main\Filesystem\File
     */
    private function _synchronizeOffsets($pointer) {
        if ($this->_syncOffsets === true) {
            $this->_readOffset  = $pointer;
            $this->_writeOffset = $pointer;
        }

        return $this;
    }

    /**
     * Checks that file exists.
     *
     * @return \PM\Main\Filesystem\File
     *
     * @throws \PM\Main\Filesystem\Exception Throws when file doesn't exist.
     */
    private function _checkFileExist() {
        if ($this->_isFileExist() === false) {
            throw new Exception('File doesn\'t exist.');
        }

        return $this;
    }

    /**
     * Returns flag that file exists.
     *
     * @return boolean
     */
    private function _isFileExist() {
        $filepath = $this->_getFilepath();
        return file_exists($filepath);
    }

    /**
     * Checks that file is open.
     *
     * @return \PM\Main\Filesystem\File
     *
     * @throws \PM\Main\Filesystem\Exception Throws when file is not open.
     */
    private function _checkOpen() {
        if ($this->isOpen() === false) {
            throw new Exception('File is not open.');
        }

        return $this;
    }
}


text:
helper_path = Rails.application.helpers_paths.reject {|p| p == File.dirname(__FILE__)}.first
load(File.expand_path('tasks_helper.rb', helper_path))

# override
module TasksHelper

  def task_assignee(task)
    task.assigned_to || task.user.id
  end

  def hide_task_and_possibly_bucket(task, bucket)
    text = "jQuery('##{dom_id(task)}').remove();\n"
    text << "jQuery('#user_#{task_assignee(task)} #list_#{h bucket.to_s}').fadeOut({ duration:500 });\n" if Task.bucket_empty?(bucket, User.find_by_id(task_assignee(task)), @view)
    text.html_safe
  end

  def replace_content(task, bucket = nil)
    partial = (task.assigned_to && task.assigned_to != current_user.id) ? "assigned" : "pending"
    html = render(:partial => "tasks/#{partial}", :collection => [ task ], :locals => { :bucket => bucket })
    text = "jQuery('##{dom_id(task)}').html('#{ j html }');\n".html_safe
  end

  #----------------------------------------------------------------------------
  def insert_content(task, bucket, view)
    text = "jQuery('#user_#{task_assignee(task)} #list_#{bucket}').show();\n".html_safe
    html = render(:partial => view, :collection => [ task ], :locals => { :bucket => bucket })
    text << "jQuery('#user_#{task_assignee(task)} ##{h bucket.to_s}').prepend('#{ j html }');\n".html_safe
    text << "jQuery('##{dom_id(task)}').effect('highlight', { duration:1500 });\n".html_safe
    text
  end

  def reassign(task)
    text = "".html_safe
    if @view == "pending" && task_assignee(task)  !=  task_assignee(@task_before_update)
      text << hide_task_and_possibly_bucket(task, @task_before_update.bucket)
      text << tasks_flash( t(:task_assigned, (h @task.assignee.try(:full_name))) + " (#{link_to(t(:view_assigned_tasks), url_for(:controller => :tasks, :view => :assigned))})" )
      text << insert_content(task, task.bucket, @view)
    elsif @view == "assigned" && @task.assigned_to.blank?
      text << hide_task_and_possibly_bucket(task, @task_before_update.bucket)
      text << tasks_flash( t(:task_pending) + " (#{link_to(t(:view_pending_tasks), tasks_url)}.")
      text << insert_content(task, task.bucket, @view)   if @task.assigned_to
    else
      text << replace_content(@task, @task.bucket)
    end
    text << refresh_sidebar(:index, :filters)
    text
  end

  def show_bucket(task, bucket)
    text = "".html_safe
    text << "jQuery('#list_#{h bucket.to_s}').fadeOut({ duration:500 });\n" if Task.bucket_empty?(bucket, current_user, @view)
    text.html_safe
  end

end


text:
package org.waveprotocol.wave.model.id;

/**
 * Checked exception indicating that a serialised wave or wavelet id is
 * invalid.
 *
 * @author anorth@google.com (Alex North)
 */
public class InvalidIdException extends Exception {
  private final String id;
  public InvalidIdException(String id, String message) {
    super(message);
    this.id = id;
  }

  public String getId() {
    return id;
  }

  @Override
  public String getMessage() {
    return "Invalid id '" + id + "': " + super.getMessage();
  }
}


text:
using System.Windows;
using System.Windows.Media;
using OpenTK.Platform.Egl;
using WpfGles.Interop;

namespace WpfGles
{
    public interface IReadOnlyDpi
    {
        double ScaleX { get; }
        double ScaleY { get; }
        double DpiX { get; }
        double DpiY { get; }
    }

    public interface IDpi : IReadOnlyDpi
    {
        void SetVisual(Visual v);
    }

    public class Dpi : IDpi
    {
        private double _dpi_x = 96.0;
        private double _dpi_y = 96.0;
        private double _scale_x = 1.0;
        private double _scale_y = 1.0;

        public void SetVisual(Visual v)
        {
            var source = PresentationSource.FromVisual(v);

            if (source == null || source.CompositionTarget == null)
            {
                throw new AngleInteropException("Cannot determine dpi.");
            }

            var m = source.CompositionTarget.TransformToDevice;

            _scale_x = m.M11;
            _scale_y = m.M22;
            _dpi_x = 96.0 * _scale_x;
            _dpi_y = 96.0 * _scale_y;
        }

        public double ScaleX
        {
            get { return _scale_x; }
        }
        public double ScaleY
        {
            get { return _scale_y; }
        }
        public double DpiX
        {
            get { return _dpi_x; }
        }
        public double DpiY
        {
            get { return _dpi_y; }
        }
    }
}


text:
class CreatePatrons < ActiveRecord::Migration
  def up
	  create_table :patrons do |t|
		  t.string :firstname
		  t.string :lastname
		  t.string :department
		  t.string :notes
		  t.timestamps
  end
  Patron.create(firstname: "Bob", lastname: "Smith", department: "Libraries", notes: "Bob Smith is a Librarian")
  end
  def down
	  drop_table :patrons
  end
end


text:
"""
Twitter Streaming API.

@see: U{http://dev.twitter.com/pages/streaming_api}.
"""

import simplejson as json

from twisted.internet import defer
from twisted.protocols.basic import LineReceiver
from twisted.protocols.policies import TimeoutMixin
from twisted.python import log
from twisted.web.client import ResponseDone
from twisted.web.http import PotentialDataLoss

class LengthDelimitedStream(LineReceiver):
    """
    Length-delimited datagram decoder protocol.

    Datagrams are prefixed by a line with a decimal length in ASCII. Lines are
    delimited by C{\r\n} and maybe empty, for keep-alive purposes.
    """

    def __init__(self):
        self._buffer = None
        self._bufferLength = None
        self._expectedLength = None

    def lineReceived(self, line):
        """
        Called when a line is received.

        We expect a length in bytes or an empty line for keep-alive. If
        we got a length, switch to raw mode to receive that amount of bytes.
        """
        if line and line.isdigit():
            self._expectedLength = int(line)
            self._buffer = []
            self._bufferLength = 0
            self.setRawMode()
        else:
            self.keepAliveReceived()

    def rawDataReceived(self, data):
        """
        Called when raw data is received.

        Fill the raw buffer C{_rawBuffer} until we have received at least
        C{_lenghtExpected} bytes. Call objectReceived with the received byte
        string of the expected size. Then switch back to line mode with the
        remainder of the buffer.
        """
        self._buffer.append(data)
        self._bufferLength += len(data)

        if self._bufferLength >= self._expectedLength:
            receivedData = ''.join(self._buffer)
            expectedData = receivedData[:self._expectedLength]
            extraData = receivedData[self._expectedLength:]

            self._buffer = None
            self._bufferLength = None
            self._expectedLength = None

            self.datagramReceived(expectedData)
            self.setLineMode(extraData)

    def datagramReceived(self, data):
        """
        Called when a datagram is received.
        """
        raise NotImplementedError()

    def keepAliveReceived(self):
        """
        Called when a empty line as keep-alive is received.

        This can be overridden for logging purposes.
        """

class TwitterObject(object):
    """
    A Twitter object.
    """
    raw = None

    @classmethod
    def fromDict(cls, data):
        """
        Fill this objects attributes from a dict for known properties.
        """
        obj = cls()
        obj.raw = data
        for name, value in data.iteritems():
            if name in cls.SIMPLE_PROPS:
                setattr(obj, name, value)
            elif name in cls.COMPLEX_PROPS:
                value = cls.COMPLEX_PROPS[name].fromDict(value)
                setattr(obj, name, value)

        return obj

class Status(TwitterObject):
    """
    Twitter Status.
    """
    SIMPLE_PROPS = set(['created_at', 'id', 'text', 'source', 'truncated',
        'in_reply_to_status_id', 'in_reply_to_screen_name',
        'in_reply_to_user_id', 'favorited', 'user_id', 'geo'])
    COMPLEX_PROPS = {}

# circular reference:
Status.COMPLEX_PROPS['retweeted_status'] = Status

class User(TwitterObject):
    """
    Twitter User.
    """
    SIMPLE_PROPS = set(['id', 'name', 'screen_name', 'location', 'description',
        'profile_image_url', 'url', 'protected', 'followers_count',
        'profile_background_color', 'profile_text_color', 'profile_link_color',
        'profile_sidebar_fill_color', 'profile_sidebar_border_color',
        'friends_count', 'created_at', 'favourites_count', 'utc_offset',
        'time_zone', 'following', 'notifications', 'statuses_count',
        'profile_background_image_url', 'profile_background_tile', 'verified',
        'geo_enabled'])
    COMPLEX_PROPS = {'status': Status}

# circular reference:
Status.COMPLEX_PROPS['user'] = User

class TwitterStream(LengthDelimitedStream, TimeoutMixin):
    """
    Twitter Stream.

    This protocol decodes an JSON encoded stream of Twitter statuses and
    associated datastructures, where each datagram is length-delimited.

    L{TimeoutMixin} is used to disconnect the stream in case Twitter stops
    sending data, including the keep-alives that usually result in traffic
    at least every 30 seconds. If not passed using C{timeoutPeriod}, the
    timeout period is set to 60 seconds.
    """

    def __init__(self, callback, timeoutPeriod=60):
        LengthDelimitedStream.__init__(self)
        self.setTimeout(timeoutPeriod)
        self.callback = callback
        self.deferred = defer.Deferred()

    def dataReceived(self, data):
        """
        Called when data is received.

        This overrides the default implementation from LineReceiver to
        reset the connection timeout.
        """
        self.resetTimeout()
        LengthDelimitedStream.dataReceived(self, data)

    def datagramReceived(self, data):
        """
        Decode the JSON-encoded datagram and call the callback.
        """
        try:
            obj = json.loads(data)
        except ValueError, e:
            log.err(e, 'Invalid JSON in stream: %r' % data)
            return

        if u'text' in obj:
            obj = Status.fromDict(obj)
        else:
            log.msg('Unsupported object %r' % obj)
            return

        self.callback(obj)

    def connectionLost(self, reason):
        """
        Called when the body is complete or the connection was lost.

        @note: As the body length is usually not known at the beginning of the
        response we expect a L{PotentialDataLoss} when Twitter closes the
        stream, instead of L{ResponseDone}. Other exceptions are treated
        as error conditions.
        """
        self.setTimeout(None)
        if reason.check(ResponseDone, PotentialDataLoss):
            self.deferred.callback(None)
        else:
            self.deferred.errback(reason)

    def timeoutConnection(self):
        """
        Called when the connection times out.

        This protocol is used to process the HTTP response body. Its transport
        is really a proxy, that does not provide C{loseConnection}. Instead it
        has C{stopProducing}, which will result in the real transport being
        closed when called.
        """
        self.transport.stopProducing()


text:
using AsyncMqttClientInternals::UnsubAckPacket;

UnsubAckPacket::UnsubAckPacket(ParsingInformation* parsingInformation, OnUnsubAckInternalCallback callback)
: _parsingInformation(parsingInformation)
, _callback(callback)
, _bytePosition(0)
, _packetIdMsb(0)
, _packetId(0) {
}

UnsubAckPacket::~UnsubAckPacket() {
}

void UnsubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
  char currentByte = data[(*currentBytePosition)++];
  if (_bytePosition++ == 0) {
    _packetIdMsb = currentByte;
  } else {
    _packetId = currentByte | _packetIdMsb << 8;
    _parsingInformation->bufferState = BufferState::NONE;
    _callback(_packetId);
  }
}

void UnsubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
  (void)data;
  (void)currentBytePosition;
}


text:
set -e

hash pacstrap &>/dev/null || {
    echo "Could not find pacstrap. Run pacman -S arch-install-scripts"
    exit 1
}

hash expect &>/dev/null || {
    echo "Could not find expect. Run pacman -S expect"
    exit 1
}

ROOTFS=$(mktemp -d /tmp/rootfs-archlinux-XXXXXXXXXX)
chmod 755 $ROOTFS

# packages to ignore for space savings
PKGIGNORE=linux,jfsutils,lvm2,cryptsetup,groff,man-db,man-pages,mdadm,pciutils,pcmciautils,reiserfsprogs,s-nail,xfsprogs

expect <<EOF
  set timeout 60
  set send_slow {1 1}
  spawn pacstrap -C ./mkimage-arch-pacman.conf -c -d -G -i $ROOTFS base haveged --ignore $PKGIGNORE
  expect {
    "Install anyway?" { send n\r; exp_continue }
    "(default=all)" { send \r; exp_continue }
    "Proceed with installation?" { send "\r"; exp_continue }
    "skip the above package" {send "y\r"; exp_continue }
    "checking" { exp_continue }
    "loading" { exp_continue }
    "installing" { exp_continue }
  }
EOF

arch-chroot $ROOTFS /bin/sh -c "haveged -w 1024; pacman-key --init; pkill haveged; pacman -Rs --noconfirm haveged; pacman-key --populate archlinux"
arch-chroot $ROOTFS /bin/sh -c "ln -s /usr/share/zoneinfo/UTC /etc/localtime"
echo 'en_US.UTF-8 UTF-8' > $ROOTFS/etc/locale.gen
arch-chroot $ROOTFS locale-gen
arch-chroot $ROOTFS /bin/sh -c 'echo "Server = http://mirrors.kernel.org/archlinux/\$repo/os/\$arch" > /etc/pacman.d/mirrorlist'

# udev doesn't work in containers, rebuild /dev
DEV=$ROOTFS/dev
rm -rf $DEV
mkdir -p $DEV
mknod -m 666 $DEV/null c 1 3
mknod -m 666 $DEV/zero c 1 5
mknod -m 666 $DEV/random c 1 8
mknod -m 666 $DEV/urandom c 1 9
mkdir -m 755 $DEV/pts
mkdir -m 1777 $DEV/shm
mknod -m 666 $DEV/tty c 5 0
mknod -m 600 $DEV/console c 5 1
mknod -m 666 $DEV/tty0 c 4 0
mknod -m 666 $DEV/full c 1 7
mknod -m 600 $DEV/initctl p
mknod -m 666 $DEV/ptmx c 5 2

tar --numeric-owner -C $ROOTFS -c . | docker import - archlinux
docker run -i -t archlinux echo Success.
rm -rf $ROOTFS


text:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Voter extends Model {

	//

}


text:
<!DOCTYPE HTML>

  <meta charset="UTF-8">

    <title>My new Post2 | Henry's Home</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">

    <meta name="author" content="Henry">

    <meta name="description" content="first levelthis is the first paragraph~
second level12int a = 1;a += 1;
first levelhaha  another test sentence.">
<meta property="og:type" content="article">
<meta property="og:title" content="My new Post2">
<meta property="og:url" content="http://yoursite.com/2016/03/16/old-post/index.html">
<meta property="og:site_name" content="Henry's Home">
<meta property="og:description" content="first levelthis is the first paragraph~
second level12int a = 1;a += 1;
first levelhaha  another test sentence.">
<meta property="og:updated_time" content="2016-03-17T02:07:07.291Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="My new Post2">
<meta name="twitter:description" content="first levelthis is the first paragraph~
second level12int a = 1;a += 1;
first levelhaha  another test sentence.">

    <link rel="alternative" href="/atom.xml" title="Henry's Home" type="application/atom+xml">

    <link rel="icon" href="/img/cheese.ico">

    <link rel="apple-touch-icon" href="/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/jacman.jpg">

    <link rel="stylesheet" href="/css/style.css">

Henry's Home

Move With The Cheese And Enjoy It!

Home

Archives

About

						<form class="search" action="http://cheesezhe.github.io/" target="_blank">
							Search
						<input name="s" type="hidden" value= null ><input type="text" name="q" size="30" placeholder="Search">

						</form>

      My new Post2

By

		Henry

    <time datetime="2016-03-16T07:28:02.000Z" itemprop="datePublished"> Published 2016-03-16</time>

			Contents

1. first level

1.1. second level

2. first level

first level

this is the first paragraph~

second level

1
2

int a = 1;
a += 1;

first level

haha  another test sentence.

  编程语言

   Python

  上一篇:

  My new Post

 下一篇:

 Hello World

  Contents

1. first level

1.1. second level

2. first level

Categories

测试1

编程语言1

Tags

C++1

Python1

Links

            	ZH奶酪

Archives

March 20163

 Hello ,我是Henry.

			人生犹如"迷宫",每个人都在其中寻找各自的"奶酪"——稳定的工作、身心的健康、和谐的人际关系、甜蜜美满的爱情,或是令人充满想象的财富……

		Powered by hexo and Theme by Jacman © 2016

		Henry

<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">


text:
package org.heaven7.scrap.core.delegate;

import android.content.Intent;
import android.os.Bundle;
import android.widget.FrameLayout;

import org.heaven7.scrap.R;
import org.heaven7.scrap.core.event.ActivityEventCallbackGroup;
import org.heaven7.scrap.core.lifecycle.ActivityLifeCycleDispatcher;
import org.heaven7.scrap.core.oneac.ActivityController;

public class SingleActivityUiDelegate extends AbstractUiDelegate {

    private static final String KEY_DATA = "__saud:data";

    private FrameLayout mFl_content;

    @Override
    public int getLayoutId() {
        return R.layout.lib_style_ac_container;
    }

    @Override
    public ActivityEventCallbackGroup getEventGroup() {
        return ActivityController.get().getEventListenerGroup();
    }
    @Override
    public ActivityLifeCycleDispatcher getLifeCycleDispatcher() {
        return ActivityController.get().getLifeCycleDispatcher();
    }

    @Override
    public void onInitialize(Intent intent, Bundle savedInstanceState) {
        super.onInitialize(intent, savedInstanceState);
        init(savedInstanceState);
    }

    @Override
    public void onFinish() {
        super.onFinish();
        ActivityController.get().attach(null, null,null);
    }

    private void init(Bundle savedInstanceState) {
        mFl_content = (FrameLayout) findViewById(R.id.lib_style_content);
        /* this must called after the container(top,middle,and bottom) is found ! */
        ActivityController.get().attach(getActivity(), mFl_content, savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Bundle b = new Bundle();
        ActivityController.get().getViewController().onSaveInstanceState(b);
        outState.putBundle(KEY_DATA, b);
    }
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if(savedInstanceState != null){
            Bundle b = savedInstanceState.getBundle(KEY_DATA);
            ActivityController.get().getViewController().onRestoreInstanceState(b);
        }
    }
}


text:
# Price calculator library

Library for easier price calculation using VAT and discount.

## Installation

```bash
composer require sunfoxcz/price-calculator
```

## Usage

```php
<?php declare(strict_types=1);

use Sunfox\PriceCalculator\Discount\PercentDiscount;
use Sunfox\PriceCalculator\PriceCalculator;

/* @var Sunfox\PriceCalculator\PriceCalculatorResult $calc */
$calc = (new PriceCalculator)
	->setBasePrice(1983.48)
	->setDiscount(new PercentDiscount(10.0))
	->setVatRate(21.0)
	->calculate();

$calc->getBasePrice(); // price without VAT and discount
$calc->getDiscount();  // discount in percent without VAT
$calc->getPrice();     // price after discount without VAT
$calc->getVatRate();   // VAT rate in percent
$calc->getVat();       // VAT value
$calc->getPriceVat();  // price after discount with VAT
$calc->toArray();      // Ger results as array

$calc->getCalculator(); // Sunfox\PriceCalculator\PriceCalculator
```


text:
define({
  "_widgetLabel": "Ağ İzleme",
  "configError": "Araç uygun şekilde yapılandırılmamış.",
  "clearButtonValue": "Temizle",
  "GPExecutionFailed": "İzleme tamamlanamadı Yeniden deneyin.",
  "backButtonValue": "Geri",
  "exportToCSVSuccess": "CSV'ye aktarma başarıyla tamamlandı.",
  "lblInputLocTab": "Girdi Konumları",
  "lblBlockLocTab": "Konumları Engelle",
  "lblInputLocation": "Detay Girdisi",
  "lblBlockLocation": "Detayı Engelle",
  "lblInputLocHeader": "Girdi Konumları (0)",
  "lblBlockLocHeader": "Konumları Engelle (0)",
  "inputTabTitle": "Girdi",
  "outputTabTitle": "Çıktı",
  "exportSelectAllCheckBoxLabel": "Tümünü Seç",
  "lblSkipLocHeader": "Konumları Atla (0)",
  "lblSkipLocation": "Konum",
  "lblSkipLocTab": "Konumları Atla",
  "skipAllLocationButtonLabel": "Tüm Konumları Atla",
  "allLocationSkippedMessage": "Tüm konumlar atlandı",
  "locationAlreadySkippedMessage": "Konum önceden atlandı",
  "locationSkippedMessage": "Konum atlandı",
  "removeAllSkipLocationLabel": "Hepsini Kaldır",
  "newProjectOptionText": "Yeni Proje",
  "selectProject": "Proje Seç",
  "saveButtonLabel": "Kaydet",
  "exportToCSVText": "CSV'ye Aktar",
  "editProjectAttributesToolTip": "Proje Özniteliklerini Düzenle",
  "projectNameLabel": "Proje Adı",
  "saveProjectPopupTitle": "Kaydet",
  "saveAsLabel": "Farklı Kaydet",
  "saveChangesMsg": "Değişikliklerinizi <b>${loadProjectDropdownlabel}</b> projesine mi, yoksa yeni bir proje olarak mı kaydetmek istiyorsunuz?",
  "creatingNewProjectErrorMessage": "Yeni proje oluşturulurken hata oluştu. Yeniden deneyin.",
  "projectNameFetchingErr": "Mevcut proje adları alınırken hata oluştu. Yeniden deneyin.",
  "projectAttributeLoadingErr": "Proje öznitelikleri yüklenirken hata oluştu. Yeniden deneyin.",
  "attributeUpdatedMsg": "Öznitelikler başarılı bir şekilde güncellendi.",
  "projectAttributeUpdatingErr": "Proje öznitelikleri güncellenirken hata oluştu.",
  "loadingProjectDetailsErrorMessage": "Bayraklar, engeller ve atlanacak konumlar alınırken hata oluştu. Yeniden deneyin.",
  "savingProjectDetailsErr": "Proje ayrıntıları kaydedilirken hata oluştu. Lütfen projeyi yeniden kaydetmeyi deneyin.",
  "updatingOutagePolygonErr": "Kesinti çokgeni güncellenirken hata oluştu. Lütfen projeyi yeniden kaydetmeyi deneyin.",
  "deletingExistingPolygonErr": "Mevcut kesinti çokgeni silinirken hata oluştu. Lütfen projeyi yeniden kaydetmeyi deneyin.",
  "loadingProjectFeaturesErr": "Proje detayları yüklenirken hata oluştu. Lütfen projeyi yeniden yüklemeyi deneyin.",
  "addingProjectFeaturesErr": "Proje detayları eklenirken hata oluştu. Lütfen projeyi yeniden kaydetmeyi deneyin.",
  "deletingExistingProjectFeaturesErr": "Mevcut proje detayları silinirken hata oluştu. Lütfen projeyi yeniden kaydetmeyi deneyin.",
  "projectNotFoundErr": "Proje bulunamadı",
  "projectLayersNotFound": "Yapılandırılan Proje ayarı katmanları haritada kullanılabilir değil. Araç, 'Çizim modu'nda yüklenecek.",
  "fetchingOutagePolygonMessage": "Kesinti çokgeni alınırken hata oluştu. Lütfen projeyi yeniden yüklemeyi deneyin.",
  "projectNameExistsMessage": "Proje adı zaten var. Lütfen benzersiz proje adı girin.",
  "fetchingProjectNamesErrorMessage": "Mevcut proje adları alınırken hata oluştu. Lütfen projeyi yeniden kaydetmeyi deneyin.",
  "enterProjectNameMessage": "Lütfen proje adı girin.",
  "projectLengthErrorMessage": "Proje adı bundan büyük olamaz:",
  "gpServiceNotAccessible": "Hesabınızın, bu izlemeyi gerçekleştirmek için gerekli hizmete erişimi yok.",
  "loadingClonedLayerErrorMessage": "Klonlanan detay katmanı yüklenirken hata oluştu. Yeniden deneyin.",
  "addingFeatureInClonedLayerError": "Klonlanan detay katmanına grafik eklenirken hata oluştu. Yeniden deneyin.",
  "selectingFeatureInClonedLayerError": "Klonlanan detay katmanında grafik seçilirken hata oluştu. Yeniden deneyin.",
  "filteredProjectError": "Filtrelenen proje detaylarının alınması kontrol edilirken hata oluştu. Yeniden deneyin.",
  "filteredProjectMessage": "Seçilen proje öznitelikleri, web haritası veya başka bir araçtan uygulanan filtreler nedeniyle kullanılabilir değil. Filtreleri temizleyin ve yeniden deneyin.",
  "filteredProjectLoadMessage": "Projeniz artık kullanılamıyor. Lütfen aktif bir proje seçin.",
  "defaultValueForRunButton": "Çalıştır",
  "closeButtonLabel": "Kaldır"
});


text:
package com.emc.pie.esa.test.spring;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.apache.commons.io.FileUtils;

@org.testng.annotations.Test
public class Test {

	public void readFileFromClassPath() throws IOException {

		URL resource = Test.class.getResource("/application-beans.properties");

		System.out.println(resource.toString());

		List<String> lines = FileUtils.readLines(FileUtils.toFile(resource), "utf-8");

		System.out.println(lines.size());
	}
}


text:
require 'fog/openstack/models/model'

module Fog
  module Network
    class OpenStack
      class SubnetPool < Fog::OpenStack::Model
        identity :id

        attribute :name
        attribute :prefixes
        attribute :description
        attribute :address_scope_id
        attribute :shared
        attribute :ip_version
        attribute :min_prefixlen
        attribute :max_prefixlen
        attribute :default_prefixlen
        attribute :is_default
        attribute :default_quota
        attribute :created_at
        attribute :updated_at
        attribute :tenant_id

        def create
          requires :name, :prefixes
          merge_attributes(service.create_subnet_pool(name,
                                                      prefixes,
                                                      attributes).body['subnetpool'])
          self
        end

        def update
          requires :id
          merge_attributes(service.update_subnet_pool(id,
                                                      attributes).body['subnetpool'])
          self
        end

        def destroy
          requires :id
          service.delete_subnet_pool(id)
          true
        end
      end
    end
  end
end


text:
We present a proof of concept template string tag for generating template string tags. See below for why this is only a proof of concept. There are many good serious parser generator frameworks out there, all of which are easily superior to the toy parser generator at the heart of this tag. The point of this project is not to provide an alternative to any of these, but rather to demonstrate how any of these technologies could be adapted to provide a template string tag for generating template string tags that could and should replace this project.

Nevertheless, until it is replaced, the template string tag for generating template string tags presented here is adequate for creating lots of useful little DSLs.

# A Template String Tag Generator

The input to our parser generator is expressed as a bnf template string, and the result is a template string tag for parsing template strings expressed in the grammar described by that bnf. The name of a template string tag usually names the language in which the template is written, which in our case is ```bnf.``` An example extracted from test/testbnf.es6:

```javascript
var bnf = require('../src/bootbnf.es6');

var arith = bnf`
    start ::= expr EOF  ${(v,_) => v};
    expr ::=
      term "+" expr     ${(a,_,b) => (...subs) => a(...subs) + b(...subs)}
    | term;
    term ::=
      NUMBER            ${n => (..._) => JSON.parse(n)}
    | HOLE              ${h => (...subs) => subs[h]}
    | "(" expr ")"      ${(_,v,_2) => v};
   `;
}

arith`1 + (2 + ${3*11} + ${55-11}) + 4`;
// 84

```

By expressing the bnf grammar itself as a template string, we avoid an awkwardness nearly universal among parser generator input languages: the mixing of the language-independent bnf notation and the target-language-specific action rules. By contrast, our ```bnf``` template string tag only needs to parse bnf in the literal part of its template. The actions associated with each rule are provided using  ```${...}```substitution holes in the host language, as functions to be invoked during parsing of the template.

Each action rule takes as input the value associated with each of its input productions, and returns the value to be associated with its own production. The first bnf production is the start rule, and its value must be an n-ary function of the substitution values as arguments. The value returned by that function is the value of the template string expression as a whole.

The generated template string tag caches that n-ary start function on the template (the unchanging part of the template string expression), to be reused on each evaluation by applying it to the new substitution values. Thus, the parsing step only happens on first evaluation.

In the above ```arith``` grammar, each action returns such an n-ary function. The start production simply returns the n-ary function associated with ```expr```. The ```NUMBER``` and ```HOLE``` productions are built in token types of our proof of concept bnf grammar. ```NUMBER``` returns the string recognized by the JSON production for "number". The action rule ```n => (..._) => JSON.parse(n)``` turns this into an n-ary function of substition values, which are ignored, returning the resulting number itself.

The ```HOLE``` production recognizes a substitution hole as a token type, and its value is the substitution hole number. The action rule ```h => (...subs) => subs[h]``` turns this into an n-ary function that returns the substition value provided for that hole.

The grammar for our bnf language, extracted from src/bootbnf.es6, expressed in itself, is

```javascript
  bnf`bnf ::= rule+ EOF              ${metaCompile};
      rule ::= IDENT "::=" body ";"  ${(name,_,body,_2) => ['def', name, body]};
      body ::= choice ** "|"         ${list => simple('or', list)};
      choice ::=
        seq HOLE                     ${(list,hole) => ['act', list, hole]}
      | seq                          ${list => simple('seq', list)};
      seq ::= term*;
      term ::=
        prim ("**" | "++") prim      ${(patt,q,sep) => [q, patt, sep]}
      | prim ("?" | "*" | "+")       ${(patt,q) => [q, patt]}
      | prim;
      prim ::=
        STRING | IDENT
      | "NUMBER" | "STRING" | "IDENT" | "HOLE" | "EOF"
      | "(" body ")"                 ${(_,b,_2) => b};
    `
```

where the action rules themselves only make sense within the context of src/bootbnf.es6.

The ```**``` operator is an infix generalization of the usual postfix ```*```, with the right operand recognized as the separator. For example, ```x ** ","``` recognizes ```x```'s separated by commas. The value is the list of values associated with the left (```x```) operand.

```NUMBER``` and ```STRING``` are both recognized using the corresponding JSON productions. ```IDENT``` is what you'd expect. ```EOF``` recognizes the end of input.

Quoted identifiers are keywords, and are therefore not recognized by the ```IDENT``` production within that grammer. Other quoted strings are literal tokens, but currently, only if they fit within the cheezy rules for recognizing operator tokens. See src/scanner.es6 for the current specifics. Instead, the operator token recognizition for a given grammar should be based on which quoted strings actually appear in the grammar.

# Why is this only a proof of concept?

The lexer's rules and token types are built in.

The generated parser has most of the expense of a full backtracking parser with none of the correctness.

Ambiguous grammars are neither detected nor parsed correctly. Instead, the alternatives are tried in order (like a PEG), but an earlier successful match will not be backtracked because of later failures. In this toy, "|" is a prioritized committed choice. That's why, for example, the bare ```prim``` rule comes last above among the choices for ```term```.

Errors within the input to ```bnf``` are hard to debug.

Errors within the input to the generated tag (e.g., ```arith```) are hard to debug.

One issue with reporting good errors is unfixable, except by improving the template string mechanism in a future EcmaScript standard: The template string itself doesn't yet carry any source position information. If it did (e.g., ```template.sourceMap```), then template string tags could report errors in their input in terms of original source position. This would necessarily also expose code to its own source position, which is probably good.


text:
import React from 'react';
import PropTypes from 'prop-types';

import { Menu, MenuItem } from "@blueprintjs/core";

export default class InvestmentsMenu extends React.PureComponent {
  constructor(props, context) {
    super(props, context);
  }

  render(){
    const { toggleDialog } = this.props;

    return (
      <div>
        <Menu>
          <MenuItem text="Crypto-Exchanges" onClick={toggleDialog}/>
        </Menu>
      </div>
    );
  }
}

InvestmentsMenu.propTypes = {
  toggleDialog: PropTypes.func,
};


text:
title: Implementing a webhook receiver in Self-Hosted Asp.Net application
description: This article elaborates on how to create a OWIN self-host console application for the WebApi that recives webhooks.
type: how-to
page_title: Implementing a webhook receiver in Self-Hosted Asp.Net application
slug: implementing-a-webhook-receiver-in-self-hosted-asp-net-application
position:
tags: WebHook
ticketid: 1411427
res_type: kb
---

## Environment

		Product
		Progress® Telerik® Report Server

## Description
[Webhooks](https://en.wikipedia.org/wiki/Webhook) are user-defined HTTP callbacks which are usually triggered by some event, such as executing a data alert or modifying a report. When that event occurs, the report server makes an HTTP POST request to the URL configured for the webhook in order to notify the subscriber.

A step-by-step instructions on how to create and receive webhooks is provided in [Implement Webhooks](../implementer-guide/webhooks-implementation) documentation article.

This knowledge base article is an example of implementing a self-hosted custom webhook receiver.

## Solution

Implementation of a webhook could be divided into two major steps:
### 1. Creating a Webhook

For these steps, follow the [Create Webhooks section](../implementer-guide/webhooks-implementation#create-webhooks) of the documentation.

### 2. Receive Webhooks

To implement a webhook receiver in your self hosted console application follow these steps:

1. Install the following Nuget package and their dependencies:
  - [Microsoft.AspNet.WebHooks.Receivers.Custom](https://www.nuget.org/packages?q=Microsoft.AspNet.WebHooks.Receivers.Custom);
  - [Microsoft.AspNet.WebApi.Owin](https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Owin).

2. Initialize the custom webhook receiver in a new class called **Startup.cs**:

  ```C#
  public class Startup
  {
      // This code configures Web API. The Startup class is specified as a type
      // parameter in the WebApp.Start method.
      public void Configuration(IAppBuilder appBuilder)
      {
          // Configure Web API for self-host.
          HttpConfiguration config = new HttpConfiguration();

          // Set the assembly resolver so that WebHooks receiver controller is loaded.
          WebHookAssemblyResolver assemblyResolver = new WebHookAssemblyResolver();
          config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver);

          // Web API routes
          config.MapHttpAttributeRoutes();

          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );

          appBuilder.UseWebApi(config);

          // Initialize Custom WebHook receiver
          config.InitializeReceiveCustomWebHooks();
      }
  }
  ```
3. The receiver uses a shared **secret** to validate that the request comes from the report server. On the report server side the secret is set when creating the webhook. On the receiver it is provided by adding an application setting in the **App.config** file. The secret should be between 32 and 128 characters. For example:

  ```XML
  <appSettings>
    <add key="MS_WebHookReceiverSecret_Custom" value="12345678901234567890123456781012"/>
  </appSettings>
  ```
The value is a comma-separated list of values matching the *{id}* values for which webhooks have been registered, for example:

  ```
  value="12345678901234567890123456781012, 12345=11111122222233333344444455555511"
  ```
The following example shows a webhook with a secret without an identifier:

  ```
  WebHookUri: "http://<receiver host>/api/webhooks/incoming/custom",
  Secret: "12345678901234567890123456781012",
  ```
The following example shows a webhook with a secret identified by an {id} parameter:

  ```
  WebHookUri: "http://<receiver host>/api/webhooks/incoming/custom/12345",
  Secret: "11111122222233333344444455555511",
  ```
4. Once a webhook request from the report server has been validated by a receiver, it is ready to be processed by user code. This happens inside a handler.

  ```C#
  public class CustomWebHookHandler : WebHookHandler
  {
      public CustomWebHookHandler()
      {
          this.Receiver = CustomWebHookReceiver.ReceiverName;
      }

      public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
      {
          // Get data from WebHook
          CustomNotifications data = context.GetDataOrDefault<CustomNotifications>();

          // Get data from each notification in this WebHook
          foreach (IDictionary<string, object> notification in data.Notifications)
          {
              // Process data
          }

          return Task.FromResult(true);
      }
  }
  ```

Report server will resend a webhook notification 3 times if a response is not generated within a handful of seconds. This means that your handler must complete the processing within that time frame in order not for it to be called again. If the processing takes longer, or is better handled separately then a [Queued Processing](https://docs.microsoft.com/en-us/windows/win32/cossdk/benefits-of-queued-processing) approach can be used.

## Notes
The report server webhooks implementation is based on [ASP.NET WebHooks](https://github.com/aspnet/aspnetwebhooks). Further information can be found in the official [Resources](https://github.com/aspnet/aspnetwebhooks#resources) and [Samples](https://github.com/aspnet/aspnetwebhooks#samples).


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using BrandesBank.Models;

namespace BrandesBank.Controllers
{
    [AdminAuthorize]
    public class AdminController : Controller
    {
        private sitedbEntities db = new sitedbEntities();

        // GET: Admin
        [Route("Admin/Users")]
        public ActionResult Index()
        {
            var users = db.Users.Include(u => u.Roles);
            return View(users.ToList());
        }

        // GET: Admin/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null || id == 0)
            {
                return RedirectToAction("Error", "Home", new { errorMessage = HttpStatusCode.BadRequest.ToString() });
            }
            Users user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // GET: Admin/Create
        public ActionResult Create()
        {
            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "Name");
            return View();
        }

        // POST: Admin/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "UserID,UserName,Password,Name,Email,Address,RoleID")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(users);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "Name", users.RoleID);
            return View(users);
        }

        // GET: Admin/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "Name", users.RoleID);
            return View(users);
        }

        // POST: Admin/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "UserID,UserName,Password,Name,Email,Address,RoleID")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Entry(users).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "Name", users.RoleID);
            return View(users);
        }

        // GET: Admin/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Admin/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Users users = db.Users.Find(id);
            db.Users.Remove(users);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}


text:
import { DropReadModelMethod } from './types'

const dropReadModel: DropReadModelMethod = async (
  { inlineLedgerRunQuery, escapeId, schemaName, escapeStr },
  readModelName
) => {
  const rows = (await inlineLedgerRunQuery(
    `SELECT ${escapeId('CLS')}.${escapeId('relname')} AS ${escapeId(
      'tableName'
    )}
    FROM ${escapeId('pg_catalog')}.${escapeId('pg_class')} ${escapeId('CLS')}
    LEFT JOIN ${escapeId('pg_catalog')}.${escapeId(
      'pg_description'
    )} ${escapeId('DESC')}
    ON ${escapeId('CLS')}.${escapeId('oid')} = ${escapeId('DESC')}.${escapeId(
      'objoid'
    )}
    LEFT JOIN ${escapeId('pg_catalog')}.${escapeId('pg_namespace')} ${escapeId(
      'NS'
    )}
    ON ${escapeId('CLS')}.${escapeId('relnamespace')} = ${escapeId(
      'NS'
    )}.${escapeId('oid')}
    WHERE ${escapeId('DESC')}.${escapeId('description')} = ${escapeStr(
      `RESOLVE-${readModelName}`
    )}
    AND ${escapeId('NS')}.${escapeId('nspname')} = ${escapeStr(schemaName)}
    AND ${escapeId('CLS')}.${escapeId('relkind')} = ${escapeStr('r')}
    ;`
  )) as Array<{ tableName: string }>

  for (const { tableName } of rows) {
    await inlineLedgerRunQuery(
      `DROP TABLE ${escapeId(schemaName)}.${escapeId(tableName)};`
    )
  }
}

export default dropReadModel


text:
from fabric.api import sudo, env, put, run
import paramiko
import configuration as config
import sys, os, time

if os.stat('hosts_file').st_size == 0:
  print "hosts_file is empty\n"
  sys.exit(1)

env.hosts = open('hosts_file', 'r').readline().rstrip()
env.user = config.USERNAME
env.port = '22'
env.key_filename = config.KEY_FILE
env.warn_only = True
env.connection_attempts = 60
env.abort_on_prompts = True
env.disable_known_hosts = True
env.skip_bad_hosts = True

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def wait():
    while True:
      try:
        ssh.connect(env.hosts, username=env.user, key_filename=env.key_filename)
        break
      except Exception:
        time.sleep(10)

def test():
    run('echo hello')


text:
(function(){
    'use strict';

    angular.module('motech-admin')
        .factory('MessagesSettingsFactory', messagesSettingsFactory);

    messagesSettingsFactory.$inject = ['$resource', 'ServerService'];
    function messagesSettingsFactory ($resource, ServerService) {
        return $resource(ServerService.formatURL('module/admin/api/messages/rules'));
    }

})();


text:
package gov.hhs.fha.nhinc.docretrieve.entity;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author mweaver
 */
public class OutboundDocRetrieveStrategyImpl_g0Test {

    public OutboundDocRetrieveStrategyImpl_g0Test() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of execute method, of class OutboundDocRetrieveStrategyImpl_g0.
     */
    @Test
    public void testExecute() {
        System.out.println("execute");
        OutboundDocRetrieveOrchestratable message = null;
        OutboundDocRetrieveStrategyImpl_g0 instance = new OutboundDocRetrieveStrategyImpl_g0();
        instance.execute(message);
    }

}


text:
using namespace std;

int main(void) {
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  auto scheme_host_port = "https://localhost:8080";
#else
  auto scheme_host_port = "http://localhost:8080";
#endif

  if (auto res = httplib::Client(scheme_host_port).Get("/hi")) {
    cout << res->status << endl;
    cout << res->get_header_value("Content-Type") << endl;
    cout << res->body << endl;
  } else {
    cout << res.error() << endl;
  }

  return 0;
}


text:
package org.umlg.sqlg.step.barrier;

import org.apache.commons.lang3.tuple.Pair;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.MeanGlobalStep;
import org.umlg.sqlg.structure.traverser.SqlgTraverserGenerator;

/**
 * @author Pieter Martin (https://github.com/pietermartin)
 * Date: 2019/07/04
 */
public class SqlgAvgGlobalStep extends SqlgReducingStepBarrier<Pair<Number, Long>, Number> {

    public SqlgAvgGlobalStep(Traversal.Admin<?, ?> traversal) {
        super(traversal);
    }

    @Override
    protected Traverser.Admin<Number> produceFinalResult(Number result) {
        return SqlgTraverserGenerator.instance().generate(((MeanGlobalStep.MeanNumber) result).getFinal(), this, 1L, false, false);
    }

    @Override
    public Number reduce(Number meanNumber, Pair<Number, Long> bPair) {
        if (meanNumber == null) {
            meanNumber = new MeanGlobalStep.MeanNumber(0, 0);
        }
        return ((MeanGlobalStep.MeanNumber) meanNumber).add(new MeanGlobalStep.MeanNumber(bPair.getLeft(), bPair.getRight()));
    }

}


text:
from django.contrib import admin
from .models import Course, Classe, ClasseDetail

class ClasseDetailInline(admin.TabularInline):
    model = ClasseDetail
    extra = 0

@admin.register(Classe)
class ClasseAdmin(admin.ModelAdmin):
    inlines = [ClasseDetailInline]
    list_display = ('__str__', 'slug')

admin.site.register(Course)