text:
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="robots" content="index, follow, all" />
        <title>FFMpeg\FFProbe\DataMapping | PHP-FFMpeg API</title>
                    <link rel="stylesheet" type="text/css" href="../../stylesheet.css">

Classes

Namespaces

Interfaces

Index

PHP-FFMpeg API

Namespace

FFMpeg\FFProbe\DataMapping

                    AbstractData

                    Format

                    Stream

                    StreamCollection

        Generated by Sami, the API Documentation Generator.


text:
package ly.stealth.mesos.kafka

import com.yammer.metrics.Metrics
import com.yammer.metrics.core._
import com.yammer.metrics.reporting.AbstractPollingReporter
import org.apache.log4j.Logger

import scala.collection.JavaConversions._
import scala.collection.mutable

class MetricsCollector(send: Broker.Metrics => Unit)
  extends AbstractPollingReporter(Metrics.defaultRegistry(), "kafka-metrics")
    with MetricProcessor[mutable.Map[String, Number]] {

  private val logger = Logger.getLogger(classOf[MetricsCollector])
  private val scopeLevelMetrics = Set("BrokerTopicMetrics", "RequestMetrics", "Log", "Partition")

  private def buildName(name: MetricName): String = {
    if (name.hasScope) {
      s"${name.getGroup},${name.getType},${name.getName},${name.getScope}"
    }
    else {
      s"${name.getGroup},${name.getType},${name.getName}"
    }
  }

  private def addMetric(name: MetricName, value: Number, metrics: mutable.Map[String, Number]): Unit = {
    if (name.hasScope && !scopeLevelMetrics.contains(name.getType)) {
      return
    }
    val displayName = buildName(name)
    metrics(displayName) = value
  }

  override def run(): Unit = {
    try {
      val metrics = new mutable.HashMap[String, Number]()
      for (entry <- getMetricsRegistry.groupedMetrics.entrySet()) {
        for (subEntry <- entry.getValue.entrySet()) {
          val metric = subEntry.getValue
          if (metric != null) {
            try {
              metric.processWith(this, subEntry.getKey, metrics)
            } catch {
              case e: Throwable =>
                logger.error("Error processing metrics:", e)
            }
          }
        }
      }
      send(new Broker.Metrics(metrics, System.currentTimeMillis()))
    }
    catch {
      case e: Throwable =>
        logger.error("Error collecting metrics", e)
    }
  }

  override def processGauge(name: MetricName, gauge: Gauge[_], context: mutable.Map[String, Number]): Unit = {
    val value = gauge.value()
    if (value.isInstanceOf[Integer] || value.isInstanceOf[Long] || value.isInstanceOf[Double]) {
      addMetric(name, value.asInstanceOf[Number], context)
    }
  }

  override def processMeter(name: MetricName, meter: Metered, context: mutable.Map[String, Number]): Unit =
    addMetric(name, meter.oneMinuteRate(), context)

  override def processHistogram(name: MetricName, histogram: Histogram, context: mutable.Map[String, Number]): Unit =
    addMetric(name, histogram.mean(), context)

  override def processTimer(name: MetricName, timer: Timer, context: mutable.Map[String, Number]): Unit =
    addMetric(name, timer.oneMinuteRate(), context)

  override def processCounter(name: MetricName, counter: Counter, context: mutable.Map[String, Number]): Unit =
    addMetric(name, counter.count(), context)
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;

namespace WebApplication
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
            );
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}


text:
import django

from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response

from django.contrib.auth import authenticate, login, logout
from django.contrib import messages

from ..models import Device

def list_all_devices_view(request):
    all_devices = Device.objects.all()
    context = {'all_devices' : all_devices}

    return render(request, 'device_list.html', context)

def delete_device_view(request, device_id):
    try:
        Device.objects.filter(id=device_id).delete()
        messages.success(request, 'Successfully deleted test')
    except:
        messages.error(request, 'Could not delete test')

    return HttpResponseRedirect(reverse('index'))

def sort_devices_view(request):
    sort_name = request.POST['name_to_sort']

    # sorting based on name
    all_devices = Device.objects.all()
    sorted_devices = []
    for grabbed_device in all_devices:
        if sort_name in grabbed_device.name:
            sorted_devices.append(grabbed_device)

    context = {'all_devices' : sorted_devices}

    return render(request, 'device_list.html', context)

def device_details_view(request, device_id):
    myDevice = get_object_or_404(Device, pk=device_id)
    context = {
        'device_name' : myDevice.name,
        'device' : myDevice
    }

    return render(request, 'device.html', context)

def edit_device_view(request, device_id):
    myDevice = get_object_or_404(Device, pk=device_id)
    context = {
        'device' : myDevice,
        'loop' : range(0,11)
    }

    return render(request, 'edit_device.html', context)

def save_device_view(request, device_id):
    device = get_object_or_404(Device, pk=device_id)

    device.notes = request.POST['device_notes']

    cpu = request.POST['device_cpu']
    motherboard = request.POST['device_motherboard']
    hard_drive = request.POST['device_hard_drive']
    sound = request.POST['device_sound']
    display_config = request.POST['device_display_config']
    graphics_card = request.POST['device_dedicated_graphics']
    manufacturer = request.POST['device_manufacturer']
    lan_chipset = request.POST['device_lan_network_chipset']
    wlan_chipset = request.POST['device_wlan_network_chipset']
    haiku_revision = request.POST['device_haiku_revision']
    rating = request.POST['device_rating']

    try:
        if str(request.POST['haiku_arch_x86']) == "on":
            device.haiku_arch = "x86"
    except:
        try:
            if str(request.POST['haiku_arch_x86_gcc2']) == "on":
                device.haiku_arch = "x86_gcc2"
        except:
            try:
                if str(request.POST['haiku_arch_x86_64']) == "on":
                    device.haiku_arch = "x86_64"
            except:
                device.haiku_arch = "Not Specified"

    try:
        if str(request.POST['group9']) == "on":
            device.is_working = "Passed"
    except:
        try:
            if str(request.POST['group10']) == "on":
                device.is_working = "Failed"
        except:
            device.is_working = "Not Specified"

    try:
        if str(request.POST['device_category_desktop']) == "on":
            device.category = "Desktop"
    except:
        try:
            if str(request.POST['device_category_notebook']) == "on":
                device.category = "Notebook"
        except:
            device.category = "Not Specified"

    try:
        if str(request.POST['group3']) == "on":
            device.is_sound_working = "Passed"
    except:
        try:
            if str(request.POST['group4']) == "on":
                device.is_sound_working = "Failed"
        except:
            device.is_sound_working = "Not Specified"

    try:
        if str(request.POST['group5']) == "on":
            device.is_display_working = "Passed"
    except:
        try:
            if str(request.POST['group6']) == "on":
                device.is_display_working = "Failed"
        except:
            device.is_display_working = "Not Specified"

    try:
        if str(request.POST['group7']) == "on":
            device.graphics_card_is_working = "Passed"
    except:
        try:
            if str(request.POST['group8']) == "on":
                device.graphics_card_is_working = "Failed"
        except:
            device.graphics_card_is_working = "Not Specified"

    try:
        if str(request.POST['device_usb2_pass']) == "on":
            device.does_usb2_work = "Passed"
    except:
        try:
            if str(request.POST['device_usb2_fail']) == "on":
                device.does_usb2_work = "Failed"
        except:
            device.does_usb2_work = "Not Specified"

    try:
        if str(request.POST['device_usb3_pass']) == "on":
            device.does_usb3_work = "Passed"
    except:
        try:
            if str(request.POST['device_usb3_fail']) == "on":
                device.does_usb3_work = "Failed"
        except:
            device.does_usb3_work = "Not Specified"

    try:
        if str(request.POST['device_optical_drive_pass']) == "on":
            device.does_optical_drive_work = "Passed"
    except:
        try:
            if str(request.POST['device_optical_drive_fail']) == "on":
                device.does_optical_drive_work = "Failed"
        except:
            device.does_optical_drive_work = "Not Specified"

    try:
        if str(request.POST['device_card_reader_pass']) == "on":
            device.does_card_reader_work = "Passed"
    except:
        try:
            if str(request.POST['device_card_reader_fail']) == "on":
                device.does_card_reader_work = "Failed"
        except:
            device.does_card_reader_work = "Not Specified"

    device.cpu = cpu
    device.motherboard = motherboard
    device.hard_dive = hard_drive
    device.sound = sound
    device.display_configuration = display_config
    device.graphics_card = graphics_card
    device.manufacturer = manufacturer
    device.lan_network_chipset = lan_chipset
    device.wlan_network_chipset = wlan_chipset
    device.haiku_revision = haiku_revision
    device.rating = rating

    try:
        device.save()
        messages.success(request, 'Successfully saved edits to desktop/notebook')
    except:
        messages.error(request, 'Could not save edits for desktop/notebook')

    return HttpResponseRedirect(reverse('index'))


text:
#region Session

<#
.Synopsis
   Create a new Nessus Session.
.DESCRIPTION
   Creates a new Nessus Session.
.EXAMPLE
   New-NessusSession -ComputerName 192.168.1.205 -Credentials (Get-Credential carlos) -Verbose
   VERBOSE: POST https://192.168.1.205:8834/session with -1-byte payload
   VERBOSE: received 60-byte response of content type application/json

    Id    : 0
    URI   : https://192.168.1.205:8834
    Token : 50168808199c1a2197d180fa62fb9cc3cb9108054911476a
#>
function New-NessusSession
{
    [CmdletBinding()]
    Param
    (
        # Nessus Server IP Address or FQDN to connect to.
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string[]]$ComputerName,

        # Port number of the Nessus web service. Default 8834
        [int]
        $Port = 8834,

        # Credentials for connecting to the Nessus Server
        [Parameter(Mandatory=$true,
        Position=1)]
        [Management.Automation.PSCredential]$Credentials
    )

    Begin
    {

    }
    Process
    {
        if ([System.Net.ServicePointManager]::CertificatePolicy.ToString() -ne 'IgnoreCerts')
        {
            $Domain = [AppDomain]::CurrentDomain
            $DynAssembly = New-Object System.Reflection.AssemblyName('IgnoreCerts')
            $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
            $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('IgnoreCerts', $false)
            $TypeBuilder = $ModuleBuilder.DefineType('IgnoreCerts', 'AutoLayout, AnsiClass, Class, Public, BeforeFieldInit', [System.Object], [System.Net.ICertificatePolicy])
            $TypeBuilder.DefineDefaultConstructor('PrivateScope, Public, HideBySig, SpecialName, RTSpecialName') | Out-Null
            $MethodInfo = [System.Net.ICertificatePolicy].GetMethod('CheckValidationResult')
            $MethodBuilder = $TypeBuilder.DefineMethod($MethodInfo.Name, 'PrivateScope, Public, Virtual, HideBySig, VtableLayoutMask', $MethodInfo.CallingConvention, $MethodInfo.ReturnType, ([Type[]] ($MethodInfo.GetParameters() | % {$_.ParameterType})))
            $ILGen = $MethodBuilder.GetILGenerator()
            $ILGen.Emit([Reflection.Emit.Opcodes]::Ldc_I4_1)
            $ILGen.Emit([Reflection.Emit.Opcodes]::Ret)
            $TypeBuilder.CreateType() | Out-Null

            # Disable SSL certificate validation
            [System.Net.ServicePointManager]::CertificatePolicy = New-Object IgnoreCerts
        }

        # Force usage of TSL1.2 as Nessus web server only supports this and will hang otherwise
        # Source: https://stackoverflow.com/questions/32355556/powershell-invoke-restmethod-over-https
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

        $SessionProps = New-Object -TypeName System.Collections.Specialized.OrderedDictionary

        foreach($computer in $ComputerName)
        {
            $URI = "https://$($computer):$($Port)"
            $RestMethodParams = @{
                'Method' = 'Post'
                'URI' =  "$($URI)/session"
                'Body' = @{'username' = $Credentials.UserName; 'password' = $Credentials.GetNetworkCredential().password}
                'ErrorVariable' = 'NessusLoginError'
            }

            $TokenResponse = Invoke-RestMethod @RestMethodParams
            if ($TokenResponse)
            {
                $SessionProps.add('URI', $URI)
                $SessionProps.Add('Credentials',$Credentials)
                $SessionProps.add('Token',$TokenResponse.token)
                $SessionIndex = $Global:NessusConn.Count
                $SessionProps.Add('SessionId', $SessionIndex)
                $sessionobj = New-Object -TypeName psobject -Property $SessionProps
                $sessionobj.pstypenames[0] = 'Nessus.Session'

                [void]$Global:NessusConn.Add($sessionobj)

                $sessionobj
            }
        }
    }
    End
    {
    }
}

<#
.Synopsis
   Get one or more current Nessus Sessions.
.DESCRIPTION
   Get one or more current Nessus Sessions.
.EXAMPLE
    Get-NessusSession

    Id    : 0
    URI   : https://192.168.1.205:8834
    Token : 50168808199c1a2197d180fa62fb9cc3cb9108054911476a

    Id    : 1
    URI   : https://192.168.1.205:8834
    Token : 2683f239b257c7729a9b501a2b916c7022a730d20b536c12

.EXAMPLE
    Get-NessusSession -SessionId 1

    Id    : 1
    URI   : https://192.168.1.205:8834
    Token : 2683f239b257c7729a9b501a2b916c7022a730d20b536c12
#>
function Get-NessusSession
{
    [CmdletBinding()]
    param(

        # Nessus session Id
        [Parameter(Mandatory=$false,
                   ParameterSetName = 'Index',
                   Position=0)]
        [Alias('Index')]
        [int32[]]
        $SessionId = @()
    )

    Begin{}
    Process
    {
        if ($Index.Count -gt 0)
        {
            foreach($i in $SessionId)
            {
                foreach($Connection in $Global:NessusConn)
                {
                    if ($Connection.SessionId -eq $i)
                    {
                        $Connection
                    }
                }
            }
        }
        else
        {
            # Return all sessions.
            $return_sessions = @()
            foreach($s in $Global:NessusConn){$s}
        }
    }
    End{}
}

<#
.Synopsis
   Closes one or more Nessus Sessions.
.DESCRIPTION
   Closes one or more Nessus Sessions.
.EXAMPLE
    Remove-NessusSession -Id 1 -Verbose
    VERBOSE: Removing server session 1
    VERBOSE: Disposing of connection
    VERBOSE: DELETE https://192.168.1.205:8834/session with 0-byte payload
    VERBOSE: received 4-byte response of content type application/json
    VERBOSE: Removing session from $Global:NessusConn
    VERBOSE: Session 1 removed.

#>
function Remove-NessusSession
{
    [CmdletBinding()]
    param(

        # Nessus session Id
        [Parameter(Mandatory=$true,
                   Position=0,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('Index')]
        [int32[]]
        $SessionId = @()
    )

    Begin{}
    Process
    {
        # Finding and saving sessions in to a different Array so they can be
        # removed from the main one so as to not generate an modification
        # error for a collection in use.
        $connections = $Global:NessusConn
        $toremove = New-Object -TypeName System.Collections.ArrayList

        if ($SessionId.Count -gt 0)
        {
            foreach($i in $SessionId)
            {
                Write-Verbose -Message "Removing server session $($i)"

                foreach($Connection in $connections)
                {
                    if ($Connection.SessionId -eq $i)
                    {
                        [void]$toremove.Add($Connection)
                    }
                }
            }

            foreach($Connection in $toremove)
            {
                Write-Verbose -Message 'Disposing of connection'
                $RestMethodParams = @{
                    'Method'        = 'Delete'
                    'URI'           =  "$($connection.URI)/session"
                    'Headers'       = @{'X-Cookie' = "token=$($Connection.Token)"}
                    'ErrorVariable' = 'DisconnectError'
                    'ErrorAction' = 'SilentlyContinue'
                }
                try
                {
                    $RemoveResponse = Invoke-RestMethod @RestMethodParams
                }
                catch
                {
                    Write-Verbose -Message "Session with Id $($connection.SessionId) seems to have expired."
                }

                Write-Verbose -message "Removing session from `$Global:NessusConn"
                $Global:NessusConn.Remove($Connection)
                Write-Verbose -Message "Session $($i) removed."
            }
         }
    }
    End{}
}

<#
.Synopsis
   Get detailed information on one or more Nessus Sessions.
.DESCRIPTION
   Get detailed information on one or more Nessus Sessions.
.EXAMPLE
    Get-NessusSessionInfo -SessionId 0 -Verbose
    VERBOSE: Removing server session 0
    VERBOSE: GET https://192.168.1.205:8834/session with 0-byte payload
    VERBOSE: received 196-byte response of content type application/json

    Id         : 2
    Name       : carlos
    UserName   : carlos
    Email      :
    Type       : local
    Permission : Sysadmin
    LastLogin  : 2/23/2015 8:58:49 PM
    Groups     :
    Connectors :
#>
function Get-NessusSessionInfo
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('Index')]
        [int32[]]$SessionId = @()
    )

    Begin
    {
         $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0
    }
    Process
    {
        $connections = $Global:NessusConn
        $ToProcess = New-Object -TypeName System.Collections.ArrayList

        foreach($i in $SessionId)
        {
            Write-Verbose "Removing server session $($i)"

            foreach($Connection in $connections)
            {
                if ($Connection.SessionId -eq $i)
                {
                    [void]$ToProcess.Add($Connection)
                }
            }

            foreach ($Connection in $ToProcess)
            {
                $RestMethodParams = @{
                    'Method'        = 'Get'
                    'URI'           =  "$($connection.URI)/session"
                    'Headers'       = @{'X-Cookie' = "token=$($Connection.Token)"}
                    'ErrorVariable' = 'NessusSessionError'
                }
                $SessInfo = Invoke-RestMethod @RestMethodParams
                if($SessInfo -is [psobject])
                {
                    $SessionProps = [ordered]@{}
                    $SessionProps.Add('Id', $SessInfo.id)
                    $SessionProps.Add('Name', $SessInfo.name)
                    $SessionProps.Add('UserName', $SessInfo.UserName)
                    $SessionProps.Add('Email', $SessInfo.Email)
                    $SessionProps.Add('Type', $SessInfo.Type)
                    $SessionProps.Add('Permission', $PermissionsId2Name[$SessInfo.permissions])
                    $SessionProps.Add('LastLogin', $origin.AddSeconds($SessInfo.lastlogin).ToLocalTime())
                    $SessionProps.Add('Groups', $SessInfo.groups)
                    $SessionProps.Add('Connectors', $SessInfo.connectors)

                    $SessInfoObj = New-Object -TypeName psobject -Property $SessionProps
                    $SessInfoObj.pstypenames[0] = 'Nessus.SessionInfo'
                    $SessInfoObj
                }
            }
        }
    }
    End{}
}

#endregion


text:
import { Injectable } from '@angular/core';

import { Action } from '@ngrx/store';
import { Actions, Effect } from '@ngrx/effects';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import 'rxjs/add/operator/mergeMap';
import * as commodities from '../actions/commodity';
import { IUserInfo } from 'app/core/models/user-info';
import { AccountService } from '../services/account.service';

@Injectable()
export class CommoditiesEffects {
	@Effect()
	loadBook$: Observable<Action> = this.action$
		.ofType(commodities.LOAD)
		.switchMap(() => this.accountService.getCommodities())
		.map(b => new commodities.LoadSuccessAction(b))
		.catch(e => of(new commodities.LoadFailAction()));

	constructor(private action$: Actions, private accountService: AccountService) {
	}
}


text:
import React from 'react';

export default class SearchBar extends React.Component {
  callSearch() {
    let query = this.refs.searchInput.value;
    this.props.doSearch(query);
  }

  render() {
    const { query, count } = this.props;

    return (

        <input
          type="text"
          className="SearchBar-input"
          ref="searchInput"
          placeholder="Search keywords..."
          value={query}
          onChange={this.callSearch.bind(this)}
        />

{count} images found

    )
  }
}


text:
'use strict';

var IntegrationApi = require('./integration_api');

class SuiteApi extends IntegrationApi {

  sendMessage(message, integrationInstanceId) {
    console.log('Method integration.sendMessage() is deprecated. Use integration.messageToService() instead.');
    this.messageToService(message, integrationInstanceId);
  }

  messageToService(message, targetInstanceId) {
    this.window.$('#integration-' + targetInstanceId)[0].contentWindow.postMessage(message, '*');
  }

  messageToSuite(message) {
    this.window.postMessage(this.setMessageSource(message), '*');
  }

  static create(global) {
    return new SuiteApi(global);
  }

}

module.exports = SuiteApi;


text:
<?php

if ( !is_user_logged_in () ) { // Not logged in
	wp_redirect( esc_url( home_url( '/', 'https' ) ) );
	exit;
}

// Add landing page body class to the head.
add_filter( 'body_class', 'genesis_sample_add_body_class' );
function genesis_sample_add_body_class( $classes ) {

	$classes[] = 'landing-page';

	return $classes;

}

// Remove Skip Links.
remove_action ( 'genesis_before_header', 'genesis_skip_links', 5 );

// Dequeue Skip Links Script.
add_action( 'wp_enqueue_scripts', 'genesis_sample_dequeue_skip_links' );
function genesis_sample_dequeue_skip_links() {
	wp_dequeue_script( 'skip-links' );
}

// Force full width content layout.
add_filter( 'genesis_site_layout', '__genesis_return_full_width_content' );

// Remove site header elements.
remove_action( 'genesis_header', 'genesis_header_markup_open', 5 );
remove_action( 'genesis_header', 'genesis_do_header' );
remove_action( 'genesis_header', 'genesis_header_markup_close', 15 );

// Remove navigation.
remove_theme_support( 'genesis-menus' );

// Remove breadcrumbs.
remove_action( 'genesis_before_loop', 'genesis_do_breadcrumbs' );

// Remove footer widgets.
remove_action( 'genesis_before_footer', 'genesis_footer_widget_areas' );

// Remove site footer elements.
remove_action( 'genesis_footer', 'genesis_footer_markup_open', 5 );
remove_action( 'genesis_footer', 'genesis_do_footer' );
remove_action( 'genesis_footer', 'genesis_footer_markup_close', 15 );

remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'gift_object_loop' );
function gift_object_loop () {
	get_template_part( 'templates/single', 'object' );
}

genesis();


text:
module Fleximage

  # Renders a .flexi template
  class LegacyView #:nodoc:
    class TemplateDidNotReturnImage < RuntimeError #:nodoc:
    end

    def initialize(view)
      @view = view
    end

    def render(template, local_assigns = {})
      # process the view
      result = @view.instance_eval do

        # Shorthand color creation
        def color(*args)
          if args.size == 1 && args.first.is_a?(String)
            args.first
          else
            Magick::Pixel.new(*args)
          end
        end

        # inject assigns into instance variables
        assigns.each do |key, value|
          instance_variable_set "@#{key}", value
        end

        # inject local assigns into reader methods
        local_assigns.each do |key, value|
          class << self; self; end.send(:define_method, key) { value }
        end

        #execute the template
        eval(template)
      end

      # Raise an error if object returned from template is not an image record
      unless result.class.include?(Fleximage::Model::InstanceMethods)
        raise TemplateDidNotReturnImage, ".flexi template was expected to return a model instance that acts_as_fleximage, but got an instance of <#{result.class}> instead."
      end

      # Figure out the proper format
      requested_format = (@view.params[:format] || :jpg).to_sym
      raise 'Image must be requested with an image type format.  jpg, gif and png only are supported.' unless [:jpg, :gif, :png].include?(requested_format)

      # Set proper content type
      @view.controller.headers["Content-Type"] = Mime::Type.lookup_by_extension(requested_format.to_s).to_s

      # get rendered result
      rendered_image = result.output_image(:format => requested_format)

      # Return image data
      return rendered_image
    ensure

      # ensure garbage collection happens after every flex image render
      rendered_image.dispose!
      GC.start
    end
  end
end


text:
package org.lodder.subtools.sublibrary.util.prompter;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import org.codehaus.plexus.components.interactivity.Prompter;

import lombok.Setter;
import lombok.experimental.Accessors;

public class PrompterBuilderValue {

    private PrompterBuilderValue() {
        // util class
    }

    public static ValueBuilderToObjectMapperIntf getValue() {
        return new ValueBuilder<>();
    }

    public static <T> ValueBuilderValidatorMapperIntf<T> toObjectMapper(Function<String, T> toObjectMapper) {
        return new ValueBuilder<>().toObjectMapper(toObjectMapper);
    }

    public interface ValueBuilderToObjectMapperIntf {
        <T> ValueBuilderValidatorMapperIntf<T> toObjectMapper(Function<String, T> toObjectMapper);
    }

    public interface ValueBuilderValidatorMapperIntf<T> extends ValueBuilderOtherMapperIntf<T> {
        ValueBuilderOtherMapperIntf<T> validator(Predicate<String> validator);
    }

    public interface ValueBuilderOtherMapperIntf<T> extends ValueBuilderOther2MapperIntf<T> {
        ValueBuilderOtherMapperIntf<T> objectValidator(Predicate<T> validator);

        ValueBuilderOtherMapperIntf<T> defaultValue(T defaultValue);

        ValueBuilderOtherMapperIntf<T> defaultValueSupplier(Supplier<T> defaultValueSupplier);

        @Override
        ValueBuilderOtherMapperIntf<T> message(String message, Object... replacements);

        @Override
        Optional<T> prompt(Prompter prompter);
    }

    public interface ValueBuilderOther2MapperIntf<T> {

        ValueBuilderOtherMapperIntf<T> message(String message, Object... replacements);

        ValueBuilderOtherMapperIntf<T> errorMessage(String errorMessage, Object... replacements);

        Optional<T> prompt(Prompter prompter);
    }

    // ------- \\
    // Builder \\
    // ------- \\

    @Setter
    @Accessors(fluent = true, chain = true)
    public static class ValueBuilder<T> implements ValueBuilderToObjectMapperIntf, ValueBuilderValidatorMapperIntf<T>,
            ValueBuilderOtherMapperIntf<T>, ValueBuilderOther2MapperIntf<T> {
        private Function<String, T> toObjectMapper;
        private Predicate<String> validator;
        private Predicate<T> objectValidator;
        private T defaultValue;
        private Supplier<T> defaultValueSupplier;
        private String message;
        private String errorMessage;

        private ValueBuilder() {
            // hide constructor
        }

        @Override
        public <S> ValueBuilderValidatorMapperIntf<S> toObjectMapper(Function<String, S> toObjectMapper) {
            this.toObjectMapper = (Function<String, T>) toObjectMapper;
            return (ValueBuilderValidatorMapperIntf<S>) this;
        }

        @Override
        public ValueBuilder<T> message(String message, Object... replacements) {
            this.message = String.format(message, replacements);
            return this;
        }

        @Override
        public ValueBuilder<T> errorMessage(String errorMessage, Object... replacements) {
            this.errorMessage = String.format(errorMessage, replacements);
            return this;
        }

        @Override
        public Optional<T> prompt(Prompter prompter) {
            return PrompterBuilderCommon.prompt(prompter, toObjectMapper, validator, objectValidator, defaultValue,
                    defaultValueSupplier, message, errorMessage);
        }
    }
}


text:
package org.locationtech.geomesa.accumulo.data

import org.junit.runner.RunWith
import org.locationtech.geomesa.accumulo.TestWithMultipleSfts
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.index.index.attribute.AttributeIndex
import org.locationtech.geomesa.index.index.id.IdIndex
import org.locationtech.geomesa.index.index.z2.Z2Index
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

@RunWith(classOf[JUnitRunner])
class DateIndexTest extends Specification with TestWithMultipleSfts {

  val spec = "name:String:index=full,dtg:Date,*geom:Point:srid=4326"

  val attributeValues = Array("foo", "1950-01-01T00:00:00.000Z", "POINT (10 10)")

  "GeoMesa" should {
    "fail to index dates before the epoch" >> {
      val sft = createNewSchema(spec)
      addFeature(sft, ScalaSimpleFeature.create(sft, "1", attributeValues: _*)) must throwAn[Exception]
    }
    "allow indexing dates before the epoch with z3 and date disabled" >> {
      import org.locationtech.geomesa.utils.geotools.RichSimpleFeatureType.RichSimpleFeatureType
      val sft = createNewSchema(spec + ";geomesa.ignore.dtg='true'", None)
      sft.getDtgField must beNone
      sft.getIndices.map(_.name) must containTheSameElementsAs(Seq(Z2Index.name, AttributeIndex.name, IdIndex.name))
      addFeature(sft, ScalaSimpleFeature.create(sft, "1", attributeValues: _*)) must not(throwAn[Exception])
    }
  }
}


text:
function fileList = trkGetFileList(fileVar)

% check if we are given a cell list of files, or a directory + filter
switch class(fileVar)

    % if we are given string (directory + filter), look in the directory for image files
    case 'char'
        % break source into a path, filter, and extension
        [pth, filter, ext] = fileparts(fileVar);
        pth = [pth filesep];
        source_folder = pth;

        % list of filetypes imread can open
        valid_filetypes = {'.bmp', '.gif', '.jpg', '.jpeg', '.tif', '.tiff', '.png',...
            '.BMP', '.GIF', '.JPG', '.JPEG', '.TIF', '.TIFF', '.PNG'};

        % check if a file filter is provided, if so use it to generate a list
        % of source filenames
        if ~isempty(filter)
            d = dir([source_folder filter]);
            fileList = cell(numel(d),1);
            for i = 1:numel(d)
                fileList{i} = [source_folder d(i).name];
            end

            % if a file filter is not provided, generate a list of source filanames
            % searching for all valid filetypes
        else
            fileList = {};
            for k = 1:numel(valid_filetypes)
                d = dir([source_folder '*' valid_filetypes{k}]);
                for i = 1:numel(d)
                    fileList{end+1} = [source_folder d(i).name]; %#ok<AGROW>
                end
            end
            fileList = fileList';

        end

    case 'cell'
        % in the case we are given a cell list of file names
        fileList = {};
        for i = 1:numel(fileVar)
            if strcmpi(finfo(fileVar{i}), 'im')
                fileList{i} = fileVar{i}; %#ok<AGROW>
            else
                error('Neuritetracker: invalid file provided %s', fileVar{i});
            end
        end
end

% keyboard;
% check if we have found any valid files in the folder
if numel(fileList) == 0
    error('NEURITETRACKER:trkGetFileList', 'No files found for string: %s', fileVar);
end

% read the first provided image, check that it is monochromatic, store
% its size in the options structure, and determine the working image
% size we will use
I = imread(fileList{1});
if numel(size(I)) == 3
    error('NEURITETRACKER:trkGetFileList', 'Non-monochromatic image provided. Monochromatic images expected. Store each channel as a separate image and try again.');
end

% sort the filenames intelligently in case they do not have leading zeros
fileList = sort_nat(fileList);


text:
using XOutput.Common.Devices;

namespace XOutput.App.Devices.Input.Keyboard
{
    public class KeyboardSource : InputSource
    {

        public KeyboardSource(IInputDevice inputDevice, string name, int offset) : base(inputDevice, name, SourceTypes.Button, offset)
        {

        }

        internal bool Refresh(bool pressed)
        {
            return RefreshValue(pressed ? 1 : 0);
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>beetl-core</artifactId>
	<parent>
		<groupId>org.beetl</groupId>
		<artifactId>beetl-parent</artifactId>
		<version>2.2.6-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<packaging>jar</packaging>
	<dependencies>
		<dependency>
			<groupId>org.antlr</groupId>
			<artifactId>antlr4-runtime</artifactId>
		</dependency>
		<dependency>
			<groupId>com.jfinal</groupId>
			<artifactId>jfinal</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.nutz</groupId>
			<artifactId>nutz</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.struts.xwork</groupId>
			<artifactId>xwork-core</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.jodd</groupId>
			<artifactId>jodd-madvoc</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.2.1</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<phase>deploy</phase>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.9.1</version>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<phase>deploy</phase>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<testFailureIgnore>true</testFailureIgnore>
					<properties>
						<property>
							<name>listener</name>
							<value>org.beetl.test.DotTestListener</value>
						</property>
					</properties>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<excludes>
						<exclude>**/*.xml</exclude>
						<exclude>**/*.g4</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
'use strict';

angular.module('lemur')

  .config(function config($routeProvider) {
    $routeProvider.when('/users', {
      templateUrl: '/angular/users/view/view.tpl.html',
      controller: 'UsersViewController'
    });
  })

  .controller('UsersViewController', function ($scope, $modal, UserApi, UserService, ngTableParams) {
    $scope.filter = {};
    $scope.usersTable = new ngTableParams({
      page: 1,            // show first page
      count: 10,          // count per page
      sorting: {
        id: 'desc'     // initial sorting
      },
      filter: $scope.filter
    }, {
      total: 0,           // length of data
      getData: function ($defer, params) {
        UserApi.getList(params.url()).then(
          function (data) {
              params.total(data.total);
              $defer.resolve(data);
          }
        );
      }
    });

    $scope.remove = function (account) {
      account.remove().then(function () {
        $scope.usersTable.reload();
      });
    };

    $scope.edit = function (userId) {
      var modalInstance = $modal.open({
        animation: true,
        templateUrl: '/angular/users/user/user.tpl.html',
        controller: 'UsersEditController',
        size: 'lg',
        resolve: {
          editId: function () {
            return userId;
          }
        }
      });

      modalInstance.result.then(function () {
        $scope.usersTable.reload();
      });

    };

    $scope.create = function () {
      var modalInstance = $modal.open({
        animation: true,
        controller: 'UsersCreateController',
        templateUrl: '/angular/users/user/user.tpl.html',
        size: 'lg'
      });

      modalInstance.result.then(function () {
        $scope.usersTable.reload();
      });

    };

    $scope.toggleFilter = function (params) {
      params.settings().$scope.show_filter = !params.settings().$scope.show_filter;
    };

  });


text: """Unit test package for ahps_alerts."""


text:
package orm

import (
	"fmt"
	"reflect"
)

type m2mModel struct {
	*sliceTableModel
	baseTable *Table
	rel       *Relation

	buf       []byte
	dstValues map[string][]reflect.Value
	columns   map[string]string
}

var _ tableModel = (*m2mModel)(nil)

func newM2MModel(join *join) *m2mModel {
	baseTable := join.BaseModel.Table()
	joinModel := join.JoinModel.(*sliceTableModel)
	dstValues := dstValues(joinModel.Root(), joinModel.Path(), baseTable.PKs)
	return &m2mModel{
		sliceTableModel: joinModel,
		baseTable:       baseTable,
		rel:             join.Rel,

		dstValues: dstValues,
		columns:   make(map[string]string),
	}
}

func (m *m2mModel) NewModel() ColumnScanner {
	m.strct = reflect.New(m.table.Type).Elem()
	m.structTableModel.NewModel()
	return m
}

func (m *m2mModel) AddModel(_ ColumnScanner) error {
	m.buf = modelIdMap(m.buf[:0], m.columns, m.baseTable.ModelName+"_", m.baseTable.PKs)
	dstValues, ok := m.dstValues[string(m.buf)]
	if !ok {
		return fmt.Errorf("pg: can't find dst value for model id=%q", m.buf)
	}
	for _, v := range dstValues {
		v.Set(reflect.Append(v, m.strct))
	}
	return nil
}

func (m *m2mModel) ScanColumn(colIdx int, colName string, b []byte) error {
	ok, err := m.sliceTableModel.scanColumn(colIdx, colName, b)
	if ok {
		return err
	}

	m.columns[colName] = string(b)
	return nil
}


text:
import os
import time

from ev3dev.ev3 import *

Sound.beep()


text:
'use strict';

import Backbone from 'backbone';

class DonorsModalModel extends Backbone.Model {

}

DonorsModalModel.prototype.defaults = {
  'donorsOpen': false
};

export default new DonorsModalModel();


text:
layout: post
title:  "Investiture of Stone"
date:   2015-11-19
tags: [druid, sorcerer, warlock, wizard, level6]
---

**6th-level transmutation**

**Casting Time**: 1 action

**Range**: Self

**Components**: V, S

**Duration**: Concentration, up to 10 minutes

Until the spell ends, bits of rock spread across your body, and you gain the following benefits:

* You have resistance to bludgeoning, piercing, and slashing damage from nonmagical weapons.
* You can use your action to create a small earthquake on the ground in a 15-foot radius centered on you. Other creatures on that ground must succeed on a Dexterity saving throw or be knocked prone.
* You can move across difficult terrain made of earth or stone without spending extra movement. You can move through solid earth or stone as if it was air and without destabilizing it, but you can't end your movement there. If you do so, you are ejected to the nearest unoccupied space, this spell ends, and you are stunned until the end of your next turn


text:
  After adding the options for specific underlying stock,  you can set the filter criteria with SetFilter method to pull contracts using the specified min and max strike and expiration range values you need for a given symbol.

Method
Parameters

SetFilter(
min strike,
max strike,
minexpiry,
maxExpiry)
min Strike, max Strike: The min and max strike rank relative to market price
min Expiry, max Expiry: The range of time to expiration to include, for example, TimeSpan.FromDays(10) would exclude contracts expiring in less than 10 days

  Here parameters min Strike and max Strike are the relative multipliers with respect to the market price. We use Google(NASDAQ: GOOG) as an example to describe the filter criteria. If today is 01/03/2017, the market price of underlying stock is $776, the strike prices of GOOG options are spaced $2.5. Then SetFilter(-1, +2, timedelta(0), timedelta(90)) will fist look up at the money contracts with strike being K=$777.5 (Here K is 777.5 the next closest multiple to the underlying price of 775 since rarely will an option be ATM exactly). Then SetFilter will look for options with strikes between and including ( 777.5 - 2.5*1, 777.5 + 2.5*2). The time to expiration of these options are restricted within 90 days from now on.

  For the strike, the exchange normally chooses the strike prices at which options can be written so that they are spaced $2.50, $5, or $10 apart. Typically the spacing is $2.50 when the stock price is between $5 and $25, $5 when the stock price is between $25 and $200, and $10 for stock prices above $200. So you should carefully choose the parameters of min strike and max Strike in case there are no contracts that satisfy the filter criteria if the range is too small, less than the minimum units of strike prices change.

  For the expiry, there are many expiration dates that apply to the different series of options. An option cycle is the pattern of months in which options contracts expire. There are three kinds of common option cycles. The options on the January cycle have contracts available in the first month of each quarter (January, April, July and October). Options assigned to the February cycle use the middle month of each quarter (February, May, August and November). And options in the March cycle have options available during the last month of each quarter (March, June, September and December). In addition, individual stock options typically expire in the current month and the subsequent month.

# filter the contracts with strikes between (market price - 10, market price + 10)
option.SetFilter(-10,10)
# filter the contracts which expires more than 30 days but no longer than 60 days
option.SetFilter(TimeSpan.FromDays(30),TimeSpan.FromDays(60))
# filter the contracts with strikes between(ATM Strike - 10 * strike space value, market price + 10 * strike space value) and with expiration days less than 180 days
option.SetFilter(-10, +10, timedelta(0), timedelta(180))


text:
<?php

namespace CL\BelgianNationalNumberBundle\Model;

/**
 * A class that represent a Belgian National Number
 *
 * @author julien.fastre@champs-libres.coop
 */
class BelgianNationalNumber {

    private $inversed_date;

    private $daily_counter;

    private $control_digit;

    public function getInversedDate() {
        return $this->inversed_date;
    }

    public function getDailyCounter() {
        return $this->daily_counter;
    }

    public function getControlDigit() {
        return $this->control_digit;
    }

    public function setInversedDate($inversed_date) {
        $this->inversed_date = $this->_sanitize($inversed_date);
    }

    public function setDailyCounter($daily_counter) {
        $this->daily_counter = $this->_sanitize($daily_counter);
    }

    public function setControlDigit($control_digit) {
        $this->control_digit = $this->_sanitize($control_digit);
    }

    public function __toString() {
        return $this->getInversedDate()
                .'-'.$this->getDailyCounter()
                .'-'.$this->getControlDigit();
    }

    public function fromString($string) {
        $a = explode('-', $string);
        $this->setInversedDate($a[0]);
        $this->setDailyCounter($a[1]);
        $this->setControlDigit($a[2]);
    }

    private function _sanitize($string){
        return filter_var($string, FILTER_SANITIZE_NUMBER_INT);
    }

}


text:
var express = require('express');
var morgan = require('morgan');

var hostname = 'localhost';
var port = 3100;

var app = express();

app.use(morgan('dev'));

function auth(req, res, next){
  var authHeader = req.headers.authorization;
  console.log(authHeader);
  if (!authHeader){
    var err = new Error('You are not authenticated!');
    err.status = 401;
    next(err);
    return;
  }

  var auth = new Buffer(authHeader.split(' ')[1], 'base64').toString().split(':');
  var user = auth[0];
  var pass = auth[1];
  console.log("test print auth var: " + auth);

  if (user == 'admin' && pass == 'password') {
    next(); //authorized
  }
  else {
    var err = new Error('You are not authenticated!');
    err.status = 401;
    next(err);
  }
}

app.use(auth);

app.use(express.static('./public'));
app.use(function(err, req, res, next){
  res.writeHead(err.status || 500, {
    'WWW-Authenticate': 'Basic',
    'Content-Type': 'text/plain'
  });
  res.end(err.message);
});

app.listen(port, hostname, function(){
  console.log(`Server running at http://${hostname}:${port}`);
});


text:
package gatt

import "errors"

var notImplemented = errors.New("not implemented")

type State int

const (
	StateUnknown      State = 0
	StateResetting    State = 1
	StateUnsupported  State = 2
	StateUnauthorized State = 3
	StatePoweredOff   State = 4
	StatePoweredOn    State = 5
)

func (s State) String() string {
	str := []string{
		"Unknown",
		"Resetting",
		"Unsupported",
		"Unauthorized",
		"PoweredOff",
		"PoweredOn",
	}
	return str[int(s)]
}

// Device defines the interface for a BLE device.
// Since an interface can't define fields(properties). To implement the
// callback support for cerntain events, deviceHandler is defined and
// implementation of Device on different platforms should embed it in
// order to keep have keep compatible in API level.
// Package users can use the Handler to set these handlers.
type Device interface {
	Init(stateChanged func(Device, State)) error

	// Advertise advertise AdvPacket
	Advertise(a *AdvPacket) error

	// AdvertiseNameAndServices advertises device name, and specified service UUIDs.
	// It tres to fit the UUIDs in the advertising packet as much as possible.
	// If name doesn't fit in the advertising packet, it will be put in scan response.
	AdvertiseNameAndServices(name string, ss []UUID) error

	// AdvertiseIBeaconData advertise iBeacon with given manufacturer data.
	AdvertiseIBeaconData(b []byte) error

	// AdvertisingIbeacon advertises iBeacon with specified parameters.
	AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error

	// StopAdvertising stops advertising.
	StopAdvertising() error

	// RemoveAllServices removes all services that are currently in the database.
	RemoveAllServices() error

	// Add Service add a service to database.
	AddService(s *Service) error

	// SetServices set the specified service to the database.
	// It removes all currently added services, if any.
	SetServices(ss []*Service) error

	// Scan discovers surounding remote peripherals that have the Service UUID specified in ss.
	// If ss is set to nil, all devices scanned are reported.
	// dup specifies weather duplicated advertisement should be reported or not.
	// When a remote peripheral is discovered, the PeripheralDiscovered Handler is called.
	Scan(ss []UUID, dup bool)

	// StopScanning stops scanning.
	StopScanning()

	// Connect connects to a remote peripheral.
	Connect(p Peripheral)

	// CancelConnection disconnects a remote peripheral.
	CancelConnection(p Peripheral)

	// Handle registers the specified handlers.
	Handle(h ...Handler)

	// Option sets the options specified.
	Option(o ...Option) error
}

// deviceHandler is the handlers(callbacks) of the Device.
type deviceHandler struct {
	// stateChanged is called when the device states changes.
	stateChanged func(d Device, s State)

	// connect is called when a remote central device connects to the device.
	centralConnected func(c Central)

	// disconnect is called when a remote central device disconnects to the device.
	centralDisconnected func(c Central)

	// peripheralDiscovered is called when a remote peripheral device is found during scan procedure.
	peripheralDiscovered func(p Peripheral, a *Advertisement, rssi int)

	// peripheralConnected is called when a remote peripheral is conneted.
	peripheralConnected func(p Peripheral, err error)

	// peripheralConnected is called when a remote peripheral is disconneted.
	peripheralDisconnected func(p Peripheral, err error)
}

// A Handler is a self-referential function, which registers the options specified.
// See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.
type Handler func(Device)

// Handle registers the specified handlers.
func (d *device) Handle(hh ...Handler) {
	for _, h := range hh {
		h(d)
	}
}

// CentralConnected returns a Handler, which sets the specified function to be called when a device connects to the server.
func CentralConnected(f func(Central)) Handler {
	return func(d Device) { d.(*device).centralConnected = f }
}

// CentralDisconnected returns a Handler, which sets the specified function to be called when a device disconnects from the server.
func CentralDisconnected(f func(Central)) Handler {
	return func(d Device) { d.(*device).centralDisconnected = f }
}

// PeripheralDiscovered returns a Handler, which sets the specified function to be called when a remote peripheral device is found during scan procedure.
func PeripheralDiscovered(f func(Peripheral, *Advertisement, int)) Handler {
	return func(d Device) { d.(*device).peripheralDiscovered = f }
}

// PeripheralConnected returns a Handler, which sets the specified function to be called when a remote peripheral device connects.
func PeripheralConnected(f func(Peripheral, error)) Handler {
	return func(d Device) { d.(*device).peripheralConnected = f }
}

// PeripheralDisconnected returns a Handler, which sets the specified function to be called when a remote peripheral device disconnects.
func PeripheralDisconnected(f func(Peripheral, error)) Handler {
	return func(d Device) { d.(*device).peripheralDisconnected = f }
}

// An Option is a self-referential function, which sets the option specified.
// Most Options are platform-specific, which gives more fine-grained control over the device at a cost of losing portibility.
// See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.
type Option func(Device) error

// Option sets the options specified.
// Some options can only be set before the device is initialized; they are best used with NewDevice instead of Option.
func (d *device) Option(opts ...Option) error {
	var err error
	for _, opt := range opts {
		err = opt(d)
	}
	return err
}