text:
traymonkey
==========

A small systray app to do things in response to the focused application changing.

The original aim was to have a way to have my system volume maxed when XBMC was launched
and focused. What TrayMonkey does right now is that, through simple ini configuration, it
can set a volume value (or restore the last value before a set) on focusing / defocusing
any application, as configured with a right-match on the application path (so, for
example, if you have an application at C:\Program Files\SomeApp\Version01\someapp.exe,
you can match it with any of:
someapp.exe
Version01\someapp.exe
01\someapp.exe
(etc).
Also matches are case-insensitive.

When I have the time and need, I'd like to extend this tray app to respond to application
launches / closes, so you could, for instance, close your email application when opening
Steam, or something similar. For now, it's just a handy way to not have to concern myself
with setting the system volume to max when XBMC runs and reducing it afterwards.

Please note that the TrayMonkey repo has a checkin of the CoreAudio API project,
found at

http://www.codeproject.com/Articles/18520/Vista-Core-Audio-API-Master-Volume-Control

This project is used to manipulate the system volume. All rights and kudos for that code
go to the original author and it is at the discretion of the original author that
I may remove this code. But I really hope I don't have to (:


text:
<!DOCTYPE html>
<!--
Copyright 2017 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/value/diagnostics/date_range.html">
<link rel="import" href="/tracing/value/ui/diagnostic_span.html">

<script>
'use strict';

tr.b.unittest.testSuite(function() {
  test('instantiate_one', function() {
    const diagnostic = new tr.v.d.DateRange(1496693745398);
    const span = tr.v.ui.createDiagnosticSpan(diagnostic);
    assert.strictEqual('TR-V-UI-DATE-RANGE-SPAN', span.tagName);
    this.addHTMLOutput(span);
  });

  test('instantiate_merged', function() {
    const diagnostic = new tr.v.d.DateRange(1496693745398);
    diagnostic.addDiagnostic(new tr.v.d.DateRange(1496693745399));
    const span = tr.v.ui.createDiagnosticSpan(diagnostic);
    assert.strictEqual('TR-V-UI-DATE-RANGE-SPAN', span.tagName);
    this.addHTMLOutput(span);
  });
});
</script>

redpajama_set_name: RedPajamaGithub


text:
package iso20022

// Provides information about the corporate action security option.
type SecuritiesOption35 struct {

	// Identification of the financial instrument.
	FinancialInstrumentIdentification *SecurityIdentification14 `xml:"FinInstrmId"`

	// Specifies whether the value is a debit or credit.
	CreditDebitIndicator *CreditDebitCode `xml:"CdtDbtInd"`

	// Specifies that the security identified  is a temporary security identification used for processing reasons, for example, contra security used in the US.
	TemporaryFinancialInstrumentIndicator *TemporaryFinancialInstrumentIndicator1Choice `xml:"TempFinInstrmInd,omitempty"`

	// Quantity of securities that have been posted (credit or debit) to the safekeeping account.
	PostingQuantity *Quantity6Choice `xml:"PstngQty"`

	// Location where the financial instruments are/will be safekept.
	SafekeepingPlace *SafekeepingPlaceFormat3Choice `xml:"SfkpgPlc,omitempty"`

	// Specifies how fractions resulting from derived securities will be processed or how prorated decisions will be rounding, if provided with a pro ration rate.
	FractionDisposition *FractionDispositionType23Choice `xml:"FrctnDspstn,omitempty"`

	// Currency in which the cash disbursed from an interest or dividend payment is offered.
	CurrencyOption *ActiveCurrencyCode `xml:"CcyOptn,omitempty"`

	// Provides information about the dates related to securities movement.
	DateDetails *SecurityDate6 `xml:"DtDtls"`

	// Provides information about the rates related to securities movement.
	RateDetails *CorporateActionRate29 `xml:"RateDtls,omitempty"`

	// Provides information about the prices related to securities movement.
	PriceDetails *CorporateActionPrice39 `xml:"PricDtls,omitempty"`

	// Identifies the chain of receiving settlement parties.
	ReceivingSettlementParties *SettlementParties24 `xml:"RcvgSttlmPties,omitempty"`

	// Identifies the chain of delivering settlement parties.
	DeliveringSettlementParties *SettlementParties24 `xml:"DlvrgSttlmPties,omitempty"`
}

func (s *SecuritiesOption35) AddFinancialInstrumentIdentification() *SecurityIdentification14 {
	s.FinancialInstrumentIdentification = new(SecurityIdentification14)
	return s.FinancialInstrumentIdentification
}

func (s *SecuritiesOption35) SetCreditDebitIndicator(value string) {
	s.CreditDebitIndicator = (*CreditDebitCode)(&value)
}

func (s *SecuritiesOption35) AddTemporaryFinancialInstrumentIndicator() *TemporaryFinancialInstrumentIndicator1Choice {
	s.TemporaryFinancialInstrumentIndicator = new(TemporaryFinancialInstrumentIndicator1Choice)
	return s.TemporaryFinancialInstrumentIndicator
}

func (s *SecuritiesOption35) AddPostingQuantity() *Quantity6Choice {
	s.PostingQuantity = new(Quantity6Choice)
	return s.PostingQuantity
}

func (s *SecuritiesOption35) AddSafekeepingPlace() *SafekeepingPlaceFormat3Choice {
	s.SafekeepingPlace = new(SafekeepingPlaceFormat3Choice)
	return s.SafekeepingPlace
}

func (s *SecuritiesOption35) AddFractionDisposition() *FractionDispositionType23Choice {
	s.FractionDisposition = new(FractionDispositionType23Choice)
	return s.FractionDisposition
}

func (s *SecuritiesOption35) SetCurrencyOption(value string) {
	s.CurrencyOption = (*ActiveCurrencyCode)(&value)
}

func (s *SecuritiesOption35) AddDateDetails() *SecurityDate6 {
	s.DateDetails = new(SecurityDate6)
	return s.DateDetails
}

func (s *SecuritiesOption35) AddRateDetails() *CorporateActionRate29 {
	s.RateDetails = new(CorporateActionRate29)
	return s.RateDetails
}

func (s *SecuritiesOption35) AddPriceDetails() *CorporateActionPrice39 {
	s.PriceDetails = new(CorporateActionPrice39)
	return s.PriceDetails
}

func (s *SecuritiesOption35) AddReceivingSettlementParties() *SettlementParties24 {
	s.ReceivingSettlementParties = new(SettlementParties24)
	return s.ReceivingSettlementParties
}

func (s *SecuritiesOption35) AddDeliveringSettlementParties() *SettlementParties24 {
	s.DeliveringSettlementParties = new(SettlementParties24)
	return s.DeliveringSettlementParties
}


text:
<resources>
    <string name="app_name">AudioExample</string>
</resources>


text:
FactoryBot.define do
  factory :kegerator do
    name { "Bender" }
    min_temp { 44 }
    max_temp { 46 }
    alarm_temp { 48 }
    temperature_sensor
  end
end


text:
package com.netflix.zuul;

import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.zuul.monitoring.Tracer;
import com.netflix.zuul.monitoring.TracerFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;
import java.util.Collections;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;

/**
 * Base abstract class for ZuulFilters. The base class defines abstract methods to define:
 * filterType() - to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering,
 * "route" for routing to an origin, "post" for post-routing filters, "error" for error handling.
 * We also support a "static" type for static responses see  StaticResponseFilter.
 * Any filterType made be created or added and run by calling FilterProcessor.runFilters(type)
 *

 * filterOrder() must also be defined for a filter. Filters may have the same  filterOrder if precedence is not
 * important for a filter. filterOrders do not need to be sequential.
 *

 * ZuulFilters may be disabled using Archius Properties.
 *

 * By default ZuulFilters are static; they don't carry state. This may be overridden by overriding the isStaticFilter() property to false
 *
 * @author Mikey Cohen
 *         Date: 10/26/11
 *         Time: 4:29 PM
 */
public abstract class ZuulFilter implements IZuulFilter, Comparable<ZuulFilter> {

    private final DynamicBooleanProperty filterDisabled =
            DynamicPropertyFactory.getInstance().getBooleanProperty(disablePropertyName(), false);

    /**
     * to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering,
     * "route" for routing to an origin, "post" for post-routing filters, "error" for error handling.
     * We also support a "static" type for static responses see  StaticResponseFilter.
     * Any filterType made be created or added and run by calling FilterProcessor.runFilters(type)
     *
     * @return A String representing that type
     */
    abstract public String filterType();

    /**
     * filterOrder() must also be defined for a filter. Filters may have the same  filterOrder if precedence is not
     * important for a filter. filterOrders do not need to be sequential.
     *
     * @return the int order of a filter
     */
    abstract public int filterOrder();

    /**
     * By default ZuulFilters are static; they don't carry state. This may be overridden by overriding the isStaticFilter() property to false
     *
     * @return true by default
     */
    public boolean isStaticFilter() {
        return true;
    }

    /**
     * The name of the Archaius property to disable this filter. by default it is zuul.[classname].[filtertype].disable
     *
     * @return
     */
    public String disablePropertyName() {
        return "zuul." + this.getClass().getSimpleName() + "." + filterType() + ".disable";
    }

    /**
     * If true, the filter has been disabled by archaius and will not be run
     *
     * @return
     */
    public boolean isFilterDisabled() {
        return filterDisabled.get();
    }

    /**
     * runFilter checks !isFilterDisabled() and shouldFilter(). The run() method is invoked if both are true.
     *
     * @return the return from ZuulFilterResult
     */
    public ZuulFilterResult runFilter() {
        ZuulFilterResult zr = new ZuulFilterResult();
        if (!filterDisabled.get()) {
            if (shouldFilter()) {
                Tracer t = TracerFactory.instance().startMicroTracer("ZUUL::" + this.getClass().getSimpleName());
                try {
                    Object res = run();
                    zr = new ZuulFilterResult(res, ExecutionStatus.SUCCESS);
                } catch (Throwable e) {
                    t.setName("ZUUL::" + this.getClass().getSimpleName() + " failed");
                    zr = new ZuulFilterResult(ExecutionStatus.FAILED);
                    zr.setException(e);
                } finally {
                    t.stopAndLog();
                }
            } else {
                zr = new ZuulFilterResult(ExecutionStatus.SKIPPED);
            }
        }
        return zr;
    }

    public int compareTo(ZuulFilter filter) {
        return this.filterOrder() - filter.filterOrder();
    }

    public static class TestUnit {
        @Mock
        private ZuulFilter f1;
        @Mock
        private ZuulFilter f2;

        @Before
        public void before() {
            MockitoAnnotations.initMocks(this);
        }

        @Test
        public void testSort() {

            when(f1.filterOrder()).thenReturn(1);
            when(f2.filterOrder()).thenReturn(10);
            when(f1.compareTo(any(ZuulFilter.class))).thenCallRealMethod();
            when(f2.compareTo(any(ZuulFilter.class))).thenCallRealMethod();

            ArrayList<ZuulFilter> list = new ArrayList<ZuulFilter>();
            list.add(f2);
            list.add(f1);

            Collections.sort(list);

            assertSame(f1, list.get(0));
        }

        @Test
        public void testShouldFilter() {
            class TestZuulFilter extends ZuulFilter {

                @Override
                public String filterType() {
                    return null;
                }

                @Override
                public int filterOrder() {
                    return 0;
                }

                public boolean shouldFilter() {
                    return false;
                }

                public Object run() {
                    return null;
                }
            }

            TestZuulFilter tf1 = spy(new TestZuulFilter());
            TestZuulFilter tf2 = spy(new TestZuulFilter());

            when(tf1.shouldFilter()).thenReturn(true);
            when(tf2.shouldFilter()).thenReturn(false);

            try {
                tf1.runFilter();
                tf2.runFilter();
                verify(tf1, times(1)).run();
                verify(tf2, times(0)).run();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }

        }

    }
}


text:
<?php

namespace frontend\widgets;

/**
 * Alert widget renders a message from session flash. All flash messages are displayed
 * in the sequence they were assigned using setFlash. You can set message as following:
 *
 * ```php
 * \Yii::$app->getSession()->setFlash('error', 'This is the message');
 * \Yii::$app->getSession()->setFlash('success', 'This is the message');
 * \Yii::$app->getSession()->setFlash('info', 'This is the message');
 * ```
 *
 * Multiple messages could be set as follows:
 *
 * ```php
 * \Yii::$app->getSession()->setFlash('error', ['Error 1', 'Error 2']);
 * ```
 *
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @author Alexander Makarov <sam@rmcreative.ru>
 */
class Alert extends \yii\bootstrap\Widget
{
    /**
     * @var array the alert types configuration for the flash messages.
     * This array is setup as $key => $value, where:
     * - $key is the name of the session flash variable
     * - $value is the bootstrap alert type (i.e. danger, success, info, warning)
     */
    public $alertTypes = [
        'error'   => 'alert-danger',
        'danger'  => 'alert-danger',
        'success' => 'alert-success',
        'info'    => 'alert-info',
        'warning' => 'alert-warning'
    ];

    /**
     * @var array the options for rendering the close button tag.
     */
    public $closeButton = [];

    public function init()
    {
        parent::init();

        $session = \Yii::$app->getSession();
        $flashes = $session->getAllFlashes();
        $appendCss = isset($this->options['class']) ? ' ' . $this->options['class'] : '';

        foreach ($flashes as $type => $data) {
            if (isset($this->alertTypes[$type])) {
                $data = (array) $data;
				$js = '
				';
				echo $js."\n";
                foreach ($data as $i => $message) {
                    /* initialize css class for each alert box */
                    $this->options['class'] = $this->alertTypes[$type] . $appendCss;

                    /* assign unique id to each alert box */
                    $this->options['id'] = $this->getId() . '-' . $type . '-' . $i;

                    /*echo \yii\bootstrap\Alert::widget([
                        'body' => $message,
                        'closeButton' => $this->closeButton,
                        'options' => $this->options,
                    ]);*/
                    //TODO: wrap in widget

                    echo '
options['id'].'" class="alert '.$this->options['class'].'">закрыть'.$message.'
';
                }

                $session->removeFlash($type);
            }
        }
    }
}


text:
package mcjty.container;

/**
 * Use this in case you want a container with no slots (for example, for energy storage only).
 */
public class EmptyContainerFactory extends ContainerFactory {

    private static EmptyContainerFactory instance = null;

    public static synchronized EmptyContainerFactory getInstance() {
        if (instance == null) {
            instance = new EmptyContainerFactory();
        }
        return instance;
    }

}


text:
package main

/* Purpose of this subpackage is to support `go install` */

import (
	"github.com/alexzorin/onapp/cmd"
)

func main() {
	cmd.Start()
}


text:
if(!dojo._hasResource["dojox.charting.Series"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.charting.Series"] = true;
dojo.provide("dojox.charting.Series");

dojo.require("dojox.charting.Element");
/*=====
dojox.charting.__SeriesCtorArgs = function(plot){
	//	summary:
	//		An optional arguments object that can be used in the Series constructor.
	//	plot: String?
	//		The plot (by name) that this series belongs to.
	this.plot = plot;
}
=====*/
dojo.declare("dojox.charting.Series", dojox.charting.Element, {
	//	summary:
	//		An object representing a series of data for plotting on a chart.
	constructor: function(chart, data, kwArgs){
		//	summary:
		//		Create a new data series object for use within charting.
		//	chart: dojox.charting.Chart2D
		//		The chart that this series belongs to.
		//	data: Array|Object:
		//		The array of data points (either numbers or objects) that
		//		represents the data to be drawn. Or it can be an object. In
		//		the latter case, it should have a property "data" (an array),
		//		destroy(), and setSeriesObject().
		//	kwArgs: dojox.charting.__SeriesCtorArgs?
		//		An optional keyword arguments object to set details for this series.
		dojo.mixin(this, kwArgs);
		if(typeof this.plot != "string"){ this.plot = "default"; }
		this.update(data);
	},

	clear: function(){
		//	summary:
		//		Clear the calculated additional parameters set on this series.
		this.dyn = {};
	},

	update: function(data){
		//	summary:
		//		Set data and make this object dirty, so it can be redrawn.
		//	data: Array|Object:
		//		The array of data points (either numbers or objects) that
		//		represents the data to be drawn. Or it can be an object. In
		//		the latter case, it should have a property "data" (an array),
		//		destroy(), and setSeriesObject().
		if(dojo.isArray(data)){
			this.data = data;
		}else{
			this.source = data;
			this.data = this.source.data;
			if(this.source.setSeriesObject){
				this.source.setSeriesObject(this);
			}
		}
		this.dirty = true;
		this.clear();
	}
});

}


text:
using SharpBoostVoronoi.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharpBoostVoronoi.Input
{
    public class Segment
    {
        public Point Start{ get; set; }
        public Point End { get; set; }

        public Segment(Point start, Point end)
        {
            Start = start;
            End = end;
        }

        public Segment(int x1, int y1, int x2, int y2)
        {
            Start = new Point(x1, y1);
            End = new Point(x2, y2);
        }

        public override string ToString()
        {
            return String.Format("Start: {0}, End: {1}", Start.ToString(), End.ToString());
        }
    }
}


text:
using abremir.AllMyBricks.Data.Configuration;
using abremir.AllMyBricks.Data.Interfaces;
using abremir.AllMyBricks.Data.Models;
using abremir.AllMyBricks.Data.Repositories;
using abremir.AllMyBricks.Data.Tests.Configuration;
using abremir.AllMyBricks.Data.Tests.Shared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NFluent;
using System;
using System.Linq;

namespace abremir.AllMyBricks.Data.Tests.Repositories
{
    [TestClass]
    public class SubthemeRepositoryTests : DataTestsBase
    {
        private static ISubthemeRepository _subthemeRepository;

        [ClassInitialize]
        public static void ClassInitialize(TestContext _)
        {
            _subthemeRepository = new SubthemeRepository(MemoryRepositoryService);
        }

        [DataTestMethod]
        [DataRow(null, null)]
        [DataRow(ModelsSetup.StringEmpty, null)]
        [DataRow(null, ModelsSetup.StringEmpty)]
        [DataRow(ModelsSetup.StringEmpty, ModelsSetup.StringEmpty)]
        public void Get_InvalidParameters_ReturnsNull(string themeName, string subthemeName)
        {
            var subtheme = _subthemeRepository.Get(themeName, subthemeName);

            Check.That(subtheme).IsNull();
        }

        [DataTestMethod]
        [DataRow(ModelsSetup.ThemeUnderTestName, ModelsSetup.NonExistentSubthemeName)]
        [DataRow(ModelsSetup.NonExistentThemeName, ModelsSetup.SubthemeUnderTestName)]
        public void Get_SubthemeDoesNotExist_ReturnsNull(string themeName, string subthemeName)
        {
            var subthemeUnderTest = ModelsSetup.GetSubthemeUnderTest(subthemeName == ModelsSetup.SubthemeUnderTestName ? ModelsSetup.SubthemeUnderTestName : Guid.NewGuid().ToString());
            subthemeUnderTest.Theme = InsertData(ModelsSetup.GetThemeUnderTest(themeName == ModelsSetup.ThemeUnderTestName ? themeName : Guid.NewGuid().ToString()));

            InsertData(subthemeUnderTest);

            var subtheme = _subthemeRepository.Get(themeName, subthemeName);

            Check.That(subtheme).IsNull();
        }

        [TestMethod]
        public void Get_SubthemeExists_ReturnModel()
        {
            var subthemeUnderTest = ModelsSetup.GetSubthemeUnderTest(Guid.NewGuid().ToString());

            InsertData(subthemeUnderTest.Theme);
            InsertData(subthemeUnderTest);

            var subtheme = _subthemeRepository.Get(subthemeUnderTest.Theme.Name, subthemeUnderTest.Name);

            Check.That(subtheme).IsNotNull();
            Check.That(subtheme.Name).IsEqualTo(subthemeUnderTest.Name);
        }

        [TestMethod]
        public void All_NoSubthemes_ReturnsEmpty()
        {
            var allSubthemes = _subthemeRepository.All();

            Check.That(allSubthemes).IsEmpty();
        }

        [TestMethod]
        public void All_HasSubthemes_ReturnsModels()
        {
            var listOfThemesUnderTest = InsertData(ModelsSetup.ListOfThemesUnderTest);

            var listOfSubthemesUnderTest = ModelsSetup.ListOfSubthemesUnderTest;
            listOfSubthemesUnderTest[0].Theme = listOfThemesUnderTest[0];
            listOfSubthemesUnderTest[1].Theme = listOfThemesUnderTest[0];

            InsertData(listOfSubthemesUnderTest);

            var allSubthemes = _subthemeRepository.All();

            Check.That(allSubthemes.Select(subtheme => subtheme.Name)).IsEquivalentTo(listOfSubthemesUnderTest.Select(subtheme => subtheme.Name));
        }

        [TestMethod]
        public void AllForYear_NoSubthemesForYear_ReturnsEmpty()
        {
            var listOfThemesUnderTest = InsertData(ModelsSetup.ListOfThemesUnderTest);

            var listOfSubthemesUnderTest = ModelsSetup.ListOfSubthemesUnderTest;
            listOfSubthemesUnderTest[0].Theme = listOfThemesUnderTest[0];
            listOfSubthemesUnderTest[1].Theme = listOfThemesUnderTest[0];

            InsertData(listOfSubthemesUnderTest);

            var allSubthemesForYear = _subthemeRepository.AllForYear(ModelsSetup.FirstThemeYearTo + 1);

            Check.That(allSubthemesForYear).IsEmpty();
        }

        [TestMethod]
        public void AllForYear_YearIsLessThanMinimumConstant_ReturnsEmpty()
        {
            var listOfThemesUnderTest = InsertData(ModelsSetup.ListOfThemesUnderTest);

            var listOfSubthemesUnderTest = ModelsSetup.ListOfSubthemesUnderTest;
            listOfSubthemesUnderTest[0].Theme = listOfThemesUnderTest[0];
            listOfSubthemesUnderTest[1].Theme = listOfThemesUnderTest[0];

            InsertData(listOfSubthemesUnderTest);

            var allSubthemesForYear = _subthemeRepository.AllForYear(Constants.MinimumSetYear - 1);

            Check.That(allSubthemesForYear).IsEmpty();
        }

        [DataTestMethod]
        [DataRow(ModelsSetup.FirstSubthemeYearFrom, 1)]
        [DataRow(ModelsSetup.SecondSubthemeYearFrom, 2)]
        public void AllForYear_HasSubthemesForYear_ReturnsModels(short year, int expectedCount)
        {
            var listOfThemesUnderTest = InsertData(ModelsSetup.ListOfThemesUnderTest);

            var listOfSubthemesUnderTest = ModelsSetup.ListOfSubthemesUnderTest;
            listOfSubthemesUnderTest[0].Theme = listOfThemesUnderTest[0];
            listOfSubthemesUnderTest[1].Theme = listOfThemesUnderTest[0];

            InsertData(listOfSubthemesUnderTest);

            var allSubthemesForYear = _subthemeRepository.AllForYear(year);

            Check.That(allSubthemesForYear).CountIs(expectedCount);
        }

        [DataTestMethod]
        [DataRow(null)]
        [DataRow(ModelsSetup.StringEmpty)]
        public void AllForTheme_InvalidThemeName_ReturnsEmpty(string themeName)
        {
            var listOfThemesUnderTest = InsertData(ModelsSetup.ListOfThemesUnderTest);

            var listOfSubthemesUnderTest = ModelsSetup.ListOfSubthemesUnderTest;
            listOfSubthemesUnderTest[0].Theme = listOfThemesUnderTest[0];
            listOfSubthemesUnderTest[1].Theme = listOfThemesUnderTest[0];

            InsertData(listOfSubthemesUnderTest);

            var allSubthemesForTheme = _subthemeRepository.AllForTheme(themeName);

            Check.That(allSubthemesForTheme).IsEmpty();
        }

        [TestMethod]
        public void AllForTheme_NoSubthemesForTheme_ReturnsEmpty()
        {
            var listOfThemesUnderTest = InsertData(ModelsSetup.ListOfThemesUnderTest);

            var listOfSubthemesUnderTest = ModelsSetup.ListOfSubthemesUnderTest;
            listOfSubthemesUnderTest[0].Theme = listOfThemesUnderTest[0];
            listOfSubthemesUnderTest[1].Theme = listOfThemesUnderTest[0];

            InsertData(listOfSubthemesUnderTest);

            var allSubthemesForTheme = _subthemeRepository.AllForTheme(ModelsSetup.NonExistentThemeName);

            Check.That(allSubthemesForTheme).IsEmpty();
        }

        [TestMethod]
        public void AllForTheme_HasSubthemesForTheme_ReturnsModels()
        {
            var listOfThemesUnderTest = InsertData(ModelsSetup.ListOfThemesUnderTest);

            var listOfSubthemesUnderTest = ModelsSetup.ListOfSubthemesUnderTest;
            listOfSubthemesUnderTest[0].Theme = listOfThemesUnderTest[0];
            listOfSubthemesUnderTest[1].Theme = listOfThemesUnderTest[0];

            InsertData(listOfSubthemesUnderTest);

            var allSubthemesForTheme = _subthemeRepository.AllForTheme(listOfThemesUnderTest[0].Name);

            Check.That(allSubthemesForTheme).CountIs(listOfSubthemesUnderTest.Length);
        }

        [TestMethod]
        public void AddOrUpdate_NullSubtheme_ReturnsNull()
        {
            Subtheme subthemeUnderTest = null;

            var subtheme = _subthemeRepository.AddOrUpdate(subthemeUnderTest);

            Check.That(subtheme).IsNull();
        }

        [DataTestMethod]
        [DataRow(null)]
        [DataRow(ModelsSetup.StringEmpty)]
        public void AddOrUpdate_InvalidSubtheme_ReturnsNull(string subthemeName)
        {
            var subthemeUnderTest = new Subtheme { Name = subthemeName };

            var subtheme = _subthemeRepository.AddOrUpdate(subthemeUnderTest);

            Check.That(subtheme).IsNull();
        }

        [TestMethod]
        public void AddOrUpdate_NullTheme_ReturnsNull()
        {
            var subthemeUnderTest = new Subtheme { Name = ModelsSetup.NonExistentSubthemeName };

            var subtheme = _subthemeRepository.AddOrUpdate(subthemeUnderTest);

            Check.That(subtheme).IsNull();
        }

        [DataTestMethod]
        [DataRow(null)]
        [DataRow(ModelsSetup.StringEmpty)]
        public void AddOrUpdate_InvalidTheme_ReturnsNull(string themeName)
        {
            var subthemeUnderTest = new Subtheme { Name = ModelsSetup.NonExistentSubthemeName, Theme = new Theme { Name = themeName } };

            var subtheme = _subthemeRepository.AddOrUpdate(subthemeUnderTest);

            Check.That(subtheme).IsNull();
        }

        [TestMethod]
        public void AddOrUpdate_SubthemeYearFromIsLessThanMinimumConstant_ReturnsNull()
        {
            var subthemeUnderTest = ModelsSetup.GetSubthemeUnderTest(Guid.NewGuid().ToString());
            subthemeUnderTest.YearFrom = Constants.MinimumSetYear - 1;

            var subtheme = _subthemeRepository.AddOrUpdate(subthemeUnderTest);

            Check.That(subtheme).IsNull();
        }

        [TestMethod]
        public void AddOrUpdate_ThemeYearFromIsLessThanMinimumConstant_ReturnsNull()
        {
            var subthemeUnderTest = ModelsSetup.GetSubthemeUnderTest(Guid.NewGuid().ToString());
            subthemeUnderTest.Theme.YearFrom = Constants.MinimumSetYear - 1;

            var subtheme = _subthemeRepository.AddOrUpdate(subthemeUnderTest);

            Check.That(subtheme).IsNull();
        }

        [TestMethod]
        public void AddOrUpdate_NewValidSubtheme_InsertsModel()
        {
            var subthemeUnderTest = ModelsSetup.GetSubthemeUnderTest(Guid.NewGuid().ToString());

            InsertData(subthemeUnderTest.Theme);

            _subthemeRepository.AddOrUpdate(subthemeUnderTest);

            var subtheme = _subthemeRepository.Get(subthemeUnderTest.Theme.Name, subthemeUnderTest.Name);

            Check.That(subtheme).IsNotNull();
            Check.That(subtheme.Name).IsEqualTo(subthemeUnderTest.Name);
        }

        [TestMethod]
        public void AddOrUpdate_ExistingValidSubtheme_UpdatesModel()
        {
            var subtheme = ModelsSetup.GetSubthemeUnderTest(Guid.NewGuid().ToString());

            InsertData(subtheme.Theme);

            _subthemeRepository.AddOrUpdate(subtheme);

            var subthemeUnderTest = _subthemeRepository.Get(subtheme.Theme.Name, subtheme.Name);

            subthemeUnderTest.SetCount = 66;
            subthemeUnderTest.YearTo = 2099;

            _subthemeRepository.AddOrUpdate(subthemeUnderTest);

            var savedSubtheme = _subthemeRepository.Get(subtheme.Theme.Name, subtheme.Name);

            Check.That(savedSubtheme).IsNotNull();
            Check.That(savedSubtheme.SetCount).IsEqualTo(subthemeUnderTest.SetCount);
            Check.That(savedSubtheme.YearTo).IsEqualTo(subthemeUnderTest.YearTo);
        }
    }
}


text:
using System;
using Aspose.Cloud;

namespace CSharp.Document.SplitResources
{
    class SplitToAnyFormat
    {
        public static void Run()
        {
            string inputfile = "doc-sample.doc";

            // Upload input file from local directory to Cloud Storage
            Common.UploadFile(inputfile, string.Empty);

            // Split specific pages to any Supported Format
            WordsSplitResultResponse wordsSplitResultResponse = Common.WordsService.SplitDocument(inputfile, SplitDocumentFormat.Png, 1, 2, Common.FOLDER);

            Console.WriteLine("\nInput file splitted successfully to Png Format.");
        }
    }
}


text:
require 'api/lib/restresource'
require 'api/resources/files/files.objects'

module MojuraAPI

	class FileDownloadResource < RestResource

		def name
			'Downloads'
		end

		def description
			'Download resource for files, which are a core object in Mojura.'
		end

		def get(params)
			file = DbFile.new(params[:ids][0])
			options = {}
			if file.is_image?
				options[:auto_create] = true
				if params[:type] == 'thumb'
					options[:size] = 128
				elsif params[:type] == 'avatar'
					options[:size] = 128
					options[:type] = 'cropped'
				else
					options[:size] = params[:size] if params.include?(:size)
					options[:type] = params[:type] || 'auto'
				end
			end
			return API.send_file(file.get_real_filename(options), :filename => file.title, :mime_type => file.mime_type)
		end

		def get_conditions
			{
				description: 'Returns the filedata of the specified file.',
				attributes: {
					size: {required: false, type: Integer, description: 'For images: Maximum size (width or height) of the image. Needs to be specified if use auto, height, width or cropped type.'},
					type: {required: false, type: String, description: 'For images: Type of resizing. Could be one of the following types thumb, avatar, auto, height, width or cropped. Default is auto. The thumb and avatar types use predefined sizes.'},
				}
			}
		end

	end

	API.register_resource(FileDownloadResource.new('files', 'downloads', '[fileid]/download'))

end


text:
'use strict';

var fs = require('fs'),
    path = require('path'),
    util = require('util'),
    assert = require('assert');

function ensureModuleExistsAndHaveAllTheTests(appPath, modulePath, testPath) {
    assert.ok(fs.existsSync(testPath), 'No test was found for module "' + modulePath + '". File expected: ' + testPath);

    var moduleName = modulePath.replace(appPath, ''),
        module = require(modulePath),
        test = require(testPath),
        property,
        mainTestName;

    if( typeof module === 'object' && !Array.isArray(module)) {
        for ( property in module ) {
            if ( module.hasOwnProperty(property) ) {
                assert.ok(property in test, 'No tests found for "' + property + '" from "' + moduleName + '" in "' + testPath + '"');
            }
        }
    } else {
        mainTestName = path.basename(modulePath, path.extname(modulePath));
        assert.ok(mainTestName in test, 'Module "' + moduleName + '" does not expose an object, in this case a test named "' + mainTestName + '" is required');
    }
}

function shouldBeValidated(filePath, options) {
    var shouldBeIgnored = options.ignore.some(function(ignore){
        if(util.isRegExp(ignore)) {
            return ignore.test(filePath);
        }

        return filePath.indexOf(ignore) !== -1;
    });

    return !shouldBeIgnored && path.extname(filePath) === '.js';
}

function readDirectoryRecursively(directoryPath, options, callback){
    var contents = fs.readdirSync(directoryPath);

    contents.forEach(function(content){
        var contentPath = path.join(directoryPath, content);

        if( fs.lstatSync(contentPath).isDirectory() && contentPath.indexOf('node_modules') === -1) {
            readDirectoryRecursively(contentPath, options, callback);
        } else if ( shouldBeValidated(contentPath, options) ) {
            callback(contentPath);
        }
    });
}

function parseOptions(options) {
    if(typeof options === 'undefined') {
        options = {};
    }

    var defaults = {
        ignore: options.ignore || []
    };

    return defaults;
}

module.exports = function(appPath, testsPath, options){
    if ( typeof testsPath === 'object' ) {
        options = testsPath;
        testsPath = undefined;
    }

    if ( typeof testsPath === 'undefined' ) {
        testsPath = appPath;
        appPath = path.resolve(path.join(testsPath, '/..'));
    }

    options = parseOptions(options);

    readDirectoryRecursively(appPath, options, function(modulePath){
        if( modulePath.indexOf(testsPath) !== -1 ) {
            return;
        }

        var moduleExtension = path.extname(modulePath),
            testPath = path.join(testsPath, modulePath.replace(appPath, '').replace(moduleExtension, 'Test' + moduleExtension));

        ensureModuleExistsAndHaveAllTheTests(appPath, modulePath, testPath);
    });
};


text:
struct JoystickState {
	unsigned char LX, LY, LZ;
	unsigned char RX, RY, RZ;
};

class Joystick
{
	public:
        void Init();
        JoystickState GetJoystickAxises();

    private:
        void DebugJoystick(JoystickState state);
        void ScaleAxisValues(int *x, int *y, int *z);
        bool IsCenter(int axisValue);
        int Clamp(int value, int min, int max);
};

#endif


text:
import sys

if sys.version_info < (3, 7):
    from ._hoverlabel import Hoverlabel
    from ._marker import Marker
    from ._stream import Stream
    from . import hoverlabel
else:
    from _plotly_utils.importers import relative_import

    __all__, __getattr__, __dir__ = relative_import(
        __name__,
        [".hoverlabel"],
        ["._hoverlabel.Hoverlabel", "._marker.Marker", "._stream.Stream"],
    )


text:
extern char** list;
extern int numEnt, lastDir;

void retrieveDir(char * path);
void freeDir(void);
void updateBrowser(void);
void drawList(void);
void setListedDir(void);

#endif


text:
typedef struct SNode
{
	ElemType data;
	struct SNode *next;
}SNode,*ptrNode;
typedef struct
{
	ptrNode top;
	int len;
}Stack;
Status InitStack(Stack &S);
Status DestoryStack(Stack &S);
Status ClearStack(Stack &S);
Status StackEmpty(Stack S);
int StackLength(Stack S);
Status GetTop(Stack S,ElemType &e);
Status Push(Stack &S,ElemType e);
Status Pop(Stack &S,ElemType &e);
Status StackTraverse(Stack S,Status (*visit)(ElemType));
#endif


text:
UDataTableFunctionLibrary::UDataTableFunctionLibrary(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
}

void UDataTableFunctionLibrary::EvaluateCurveTableRow(UCurveTable* CurveTable, FName RowName, float InXY, TEnumAsByte<EEvaluateCurveTableResult::Type>& OutResult, float& OutXY)
{
	FCurveTableRowHandle Handle;
	Handle.CurveTable = CurveTable;
	Handle.RowName = RowName;

	bool found = Handle.Eval(InXY, &OutXY);

	if (found)
	{
	    OutResult = EEvaluateCurveTableResult::RowFound;
	}
	else
	{
	    OutResult = EEvaluateCurveTableResult::RowNotFound;
	}
}

bool UDataTableFunctionLibrary::Generic_GetDataTableRowFromName(UDataTable* Table, FName RowName, void* OutRowPtr)
{
	bool bFoundRow = false;

	if (OutRowPtr && Table)
	{
		void* RowPtr = Table->FindRowUnchecked(RowName);

		if (RowPtr != NULL)
		{
			UScriptStruct* StructType = Table->RowStruct;

			if (StructType != NULL)
			{
				StructType->CopyScriptStruct(OutRowPtr, RowPtr);
				bFoundRow = true;
			}
		}
	}

	return bFoundRow;
}

bool UDataTableFunctionLibrary::GetDataTableRowFromName(UDataTable* Table, FName RowName, FTableRowBase& OutRow)
{
	// We should never hit this!  stubs to avoid NoExport on the class.
	check(0);
	return false;
}

void UDataTableFunctionLibrary::GetDataTableRowNames(UDataTable* Table, TArray<FName>& OutRowNames)
{
	if (Table)
	{
		OutRowNames = Table->GetRowNames();
	}
	else
	{
		OutRowNames.Empty();
	}
}


text:
package org.robolectric.shadows;

import android.accessibilityservice.AccessibilityService;
import android.view.accessibility.AccessibilityEvent;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.TestRunners;

import static org.assertj.core.api.Assertions.assertThat;
import static org.robolectric.Shadows.shadowOf;

@RunWith(TestRunners.MultiApiSelfTest.class)
public class ShadowAccessibilityServiceTest {
  private MyService service ;
  private ShadowAccessibilityService shadow;

  @Before
  public void setup() {
    service = Robolectric.setupService(MyService.class);
    shadow = shadowOf(service);
  }

  /**
   * After performing a global action, it should be recorded.
   */
  @Test
  public void shouldRecordPerformedAction(){
    service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
    assertThat(shadow.getGlobalActionsPerformed().size()).isEqualTo(1);
    assertThat(shadow.getGlobalActionsPerformed().get(0)).isEqualTo(1);
  }

  public static class MyService extends AccessibilityService {
    @Override
    public void onDestroy() {
      super.onDestroy();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent arg0) {
      //Do nothing
    }

    @Override
    public void onInterrupt() {
      //Do nothing
    }
  }
}


text:
package org.kuali.rice.ksb.messaging;

import org.kuali.rice.ksb.api.messaging.AsynchronousCall;
import org.kuali.rice.ksb.api.messaging.AsynchronousCallback;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;

public class TestCallback implements AsynchronousCallback {
	/**
	 *
	 */
	private static final long serialVersionUID = 8558495197148582373L;

	public static boolean callbackCalled;

	public static List<Long> CURRENT_MILLIS_WHEN_CALLED;

	public static int NUMBER_CALL_BACKS = 0;

	public static Map<QName, Integer> SERVICE_CALL_COUNT_TRACKED = new HashMap<QName, Integer>();
	public static Map<QName, List<AsynchronousCall>> SERVICES_CALLS_TRACKED = new HashMap<QName, List<AsynchronousCall>>();

	static {
		CURRENT_MILLIS_WHEN_CALLED = new ArrayList<Long>();
	}

	private int numberCallbacks = 0;

	public static boolean isCallbackCalled() {
		return callbackCalled;
	}

	public static void setCallbackCalled(boolean callbackCalled) {
		TestCallback.callbackCalled = callbackCalled;
	}

	public synchronized void callback(Serializable returnObject, AsynchronousCall methodCall) {
		CURRENT_MILLIS_WHEN_CALLED.add(System.currentTimeMillis());
		NUMBER_CALL_BACKS++;
		setCallbackCalled(true);
		this.numberCallbacks++;
		QName serviceName = methodCall.getServiceConfiguration().getServiceName();
		Integer callCount = SERVICE_CALL_COUNT_TRACKED.get(serviceName);
		if (callCount == null) {
			SERVICE_CALL_COUNT_TRACKED.put(methodCall.getServiceConfiguration().getServiceName(), 1);
		} else {
			SERVICE_CALL_COUNT_TRACKED.put(methodCall.getServiceConfiguration().getServiceName(), callCount + 1);
		}

		List<AsynchronousCall> serviceCallsTracked = SERVICES_CALLS_TRACKED.get(serviceName);
		if (serviceCallsTracked == null) {
			serviceCallsTracked = new ArrayList<AsynchronousCall>();
			SERVICES_CALLS_TRACKED.put(serviceName, serviceCallsTracked);
		}
		serviceCallsTracked.add(methodCall);

		System.out.println("!!!Callback called number callbacks " + this.numberCallbacks);
	}

	public static void clearCallbacks() {
		NUMBER_CALL_BACKS = 0;
		SERVICE_CALL_COUNT_TRACKED = new HashMap<QName, Integer>();
	}

	/**
	 * sometimes it's more convenient to use a non static counter above when
	 * doing in memory queueing. Other times when doing persistent async
	 * messaging a static counter is needed. Everything could be converted to
	 * this method if the tests using the above method clear the static count
	 * before putting testing against callbacks.
	 *
	 * @param callbacks
	 * @param millisDelay
	 */
	public void pauseUntilNumberCallbacksUsingStaticCounter(int callbacks, QName serviceName) {
		int numPauses = 0;
		while (true) {
			synchronized (this.getClass()) {
				if (serviceName == null) {
					if (NUMBER_CALL_BACKS >= callbacks) {
						System.out.println("!!!Returning number callback met");
						return;
					}
				} else {
					if (SERVICE_CALL_COUNT_TRACKED.get(serviceName) != null && SERVICE_CALL_COUNT_TRACKED.get(serviceName) >= callbacks) {
						System.out.println("!!!Returning number callback met for service " + serviceName);
						return;
					}
						// attributes will not be an exact match.
					for (Map.Entry<QName, Integer> serviceCall : SERVICE_CALL_COUNT_TRACKED.entrySet()) {
						if (serviceCall.getKey().getLocalPart().lastIndexOf(serviceName.getLocalPart()) > -1 && serviceCall.getKey().getNamespaceURI().equals(serviceName.getNamespaceURI()) && serviceCall.getValue() >= callbacks) {
							System.out.println("!!!Returning number callback met for service " + serviceName);
							return;
						}
					}
				}
			}
			if (numPauses > 60 * 1) {
				return;
			}
			try {
				numPauses++;
				System.out.println("!!!Test callback pausing for 1 second");
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			    // nothing to do
			}
		}
	}
}


text:
<link rel="import" href="src/core-transition/core-transition.html">
<link rel="import" href="core_meta.html">
<script type="application/dart" src="core_transition.dart"></script>


text:
package com.blinkbox.books.spray

import org.scalatest.{FunSuite, Matchers}
import spray.http.StringRendering

class BearerHttpChallengeTests extends FunSuite with Matchers {

  test("A challenge with no params renders correctly") {
    val challenge = new BearerHttpChallenge()
    val rendering = new StringRendering()
    challenge.render(rendering)
    rendering.get should be("""Bearer""")
  }

  test("A challenge with error and error_description params renders correctly") {
    val challenge = new BearerHttpChallenge(Map("error" -> "invalid_token", "error_description" -> "The access token expired"))
    val rendering = new StringRendering()
    challenge.render(rendering)
    rendering.get should be("""Bearer error="invalid_token", error_description="The access token expired"""")
  }

  test("A challenge with error, error_reason and error_description params renders correctly") {
    val challenge = new BearerHttpChallenge(Map("error" -> "invalid_token", "error_reason" -> "unverified_identity", "error_description" -> "User identity must be reverified"))
    val rendering = new StringRendering()
    challenge.render(rendering)
    rendering.get should be("""Bearer error="invalid_token", error_reason="unverified_identity", error_description="User identity must be reverified"""")
  }

}


text:
<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

	<title>Bank of Contoso [savings, loans, credit]</title>

  <link rel="manifest" href="manifest.json">

  <link rel="stylesheet" href="lib/css/main.min.css"/>

            Bank of Contoso

Acount info

          My Accounts

          favorites

          Bill Pay

          Check Upload

            Github

            About

            Support

                    Contact Ino

                      Profile

                      Contact Us

                      Logout

                    Notifications

                    update contact information

                Bank of Contoso

                Welcome Alfred Koholic


text:
/* global d3 */
/* global topojson */

(function(){
  'use strict';

  var defaultColorScale = d3.scale.quantize()
    .domain([0,255])
    .range(["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"]);
    // RdYlGn[10]

  var worldGeoJSON = {
    type: 'FeatureCollection',
    features: [
      {
        type: 'Feature',
        properties: {},
        geometry: {
          type: 'Polygon',
          coordinates: null
        }
      }
    ]
  };

  worldGeoJSON.features[0].geometry.coordinates = [
    d3.range(-179.9999,179.9999).map(function(x) {return [x, 89.9999];}),
    d3.range(89.9999,-89.9999,-1).map(function(x) {return [179.9999, x];}),
    d3.range(179.9999,-179.9999,-1).map(function(x) {return [x, -89.9999];}),
    d3.range(-89.9999,89.9999).map(function(x) {return [-179.9999, x];}
  )];

  var Grid = function(data, gridSize, bbox) {
    // represents a gridded data set.  Unless bbox is supplied,
    // it's assumed to have global coverage
    this.data = data;
    this.rows = gridSize[1];
    this.cols = gridSize[0];
    this.bbox = bbox; // optional, currently unused
  };

  var Layer = function(options) {
    this.zIndex = options ? options.zIndex : 1;
    this.options = options || {strokeColor: 'rgba(100,100,100,.8)', fillColor: 'rgba(237,178,48,1)'};
    this.geojson = null;
    this.grid = null;
  };

  var GridMap = function(container, options) {
    var self = this;

    this.rotateLatitude = 0.0;
    this.rotateLongitude = 0.0;

    this.container = d3.select(container);

    var rect = this.container.node().getBoundingClientRect();
    this.width = rect.width | 0;
    this.height = rect.height | 0;

    this.grids = [];
    this.layers = [];

    this.options = options;

    this.seaColor = options.seaColor || 'rgba(21,98,180,.8)';
    this.graticuleColor = options.graticuleColor || 'rgba(255,255,255,.3)';

    self.area = 1; // minimum area threshold for simplification

    var simplify = d3.geo.transform({
      point: function(x, y, z) {
        if (z >= self.area) {
          this.stream.point(x, y);
        }
      }
    });

    this.projection = options.projection || d3.geo.aitoff();
    this.projection
      .translate([this.width/2, this.height/2])
      .scale(this.width/6)
      .clipExtent([[0, 0], [self.width, self.height]])
      .precision(0.1);

    this.canvas = this.container
      .append('canvas')
      .style('position', 'absolute')
      .style('top', '0px')
      .style('left', '0px')
      .attr('width', self.width)
      .attr('height', self.height);

    this.hud = this.container
      .append('canvas')
      .style('position', 'absolute')
      .style('top', '0px')
      .style('left', '0px')
      .style('z-index', '2')
      .attr('width', self.width)
      .attr('height', self.height);

    this.context = this.canvas.node().getContext('2d');
    this.hudContext = this.hud.node().getContext('2d');

    this.colorScale = options.colorScale || defaultColorScale;

    this.simplifyingPath = d3.geo.path()
      .projection({stream: function(s) {return simplify.stream(self.projection.stream(s));}})
      .context(this.context);

    this.path = d3.geo.path()
      .projection(this.projection)
      .context(this.context);

    this.hudPath = d3.geo.path()
      .projection(this.projection)
      .context(this.hudContext);

    this.init = function() {
      this.initEvents();
    };

    this.destroy = function() {
      this.canvas.remove();
      this.hudCanvas.remove();
      this.grids = [];
      this.geojson = null;
    };

    this.getCell = function(cellId) {
      // return value if we have a grid and the grid contains a nonzero alpha channel from
      // (RGBA) values
      var grid = this.getGrid();

      if (grid && grid.data[cellId*4 + 3]) {
        return grid.data[cellId*4];
      }
    };

    this.cellIdToLonLat = function(cellId, grid) {
      /**
       * given a cellId, returns an array containing the [lon,lat] of the
       * upper left corner  points
       * @param {Number} cellId
       * @return {Array} coordinates
       */

      var rows = 360;
      var cols = 720;
      if (grid) {
        rows = grid.rows;
        cols = grid.cols;
      }
      var _id = cellId - 1;
      var lon = -180 + (_id % cols)/cols * rows;
      var lat = 90 - (~~(_id / cols)) * (180 / rows);
      return [lon, lat];
    };

    this.cellCache = [];

    this.cellIdToCoordinates = function(cellId, grid) {
      /**
       * given a cellId, returns an array of arrays containing the [lon,lat] of the corner
       * points
       * @param {Number} cellId
       * @param {Grid} grid to query, optional
       * @return {Array} coordinates
       */

      if (this.cellCache[cellId]) {
        return this.cellCache[cellId];
      }

      var rows = 360;
      var cols = 720;
      if (grid) {
        rows = grid.rows;
        cols = grid.cols;
      }
      var xSize = 360 / cols;
      var ySize = 180 / rows;

      var lonLat = this.cellIdToLonLat(cellId, grid);
      var coordinates = [
        lonLat,
        [lonLat[0] + xSize, lonLat[1]],
        [lonLat[0] + xSize, lonLat[1] - ySize],
        [lonLat[0], lonLat[1] - ySize],
        lonLat
      ];
      this.cellCache[cellId] = coordinates;
      return coordinates;
    };

    this.getGrid = function() {
      /**
       * returns 'the' grid
       */

      // FIXME: is picking the first grid good enough?
      var grid = null;
      for (var i=0; i < this.layers.length; i++) {
        if (this.layers[i].grid) {
          return this.layers[i].grid;
        }
      }
    };

    this.coordinatesToCellId = function(coords) {
      var lon = coords[0];
      var lat = coords[1];

      var grid = this.getGrid();

      var rows = grid.rows;
      var cols = grid.cols;

      var row = ~~(rows - (lat + 90) / 180  * rows);
      var col = ~~((lon + 180) / 360  * cols);

      var cellId = row * cols + col + 1;
      return cellId;
    };

    this.updateHUD = function(cellId, coords, cell) {
      var coordFormat = d3.format(' >+7.3f');

      var fontSize = self.options.hud.fontSize || 30;
      var verticalOffset = self.options.hud.verticalOffset || 10;
      var fontColor = self.options.hud.fontColor || 'white';
      var fontFace = self.options.hud.fontFace || 'monospace';

      var font = fontSize + 'px ' + fontFace;
      var h = fontSize + verticalOffset;
      var gradient = self.hudContext.createLinearGradient(0,self.height-h,0,self.height);
      gradient.addColorStop(0, 'rgba(0,0,0,0.0');
      gradient.addColorStop(1, 'rgba(0,0,0,1.0');

      self.hudContext.clearRect(0, 0, self.width, self.height);
      self.hudContext.fillStyle = gradient;
      self.hudContext.fillRect(0,self.height-(h), self.width, self.height);

      var s = '';

      s = 'cell: ' + cellId + ' ( ' + coordFormat(coords[0]) + '°,' + coordFormat(coords[1]) + '° )';

      var coordinates = self.cellIdToCoordinates(cellId, self.grids[0]);

      var feature = {
        type: 'Feature',
        geometry: {
          type: 'Polygon',
          coordinates: [coordinates]
        },
      };

      if (cell !== undefined) {
        s += ' value: ' + cell;
      }

      self.hudContext.font = font;
      self.hudContext.fillStyle = fontColor;
      self.hudContext.fillText(s, 0, self.height - verticalOffset);

      self.hudContext.beginPath();
      self.hudContext.strokeStyle = 'white';
      self.hudContext.lineWidth = 2;
      self.hudPath(feature);
      self.hudContext.stroke();
    };

    this.onMouseMove = function() {
      if (!self.options.onCellHover && !self.options.hud) {
        return;
      }
      var coords = self.projection.invert(d3.mouse(this));

      if (!coords) {
        return;
      }
      var cellId = null;
      var cell = null;

      if (coords[0] && coords[1] && coords[0] > -180 && coords[0] < 180 && coords[1] > -90 && coords[1] < 90) {
        cellId = self.coordinatesToCellId(coords);
        cell = self.getCell(cellId);
        if (cell) {
          if (self.options.onCellHover) {
            self.options.onCellHover(cell);
          }
        }
      }
      if (self.options.hud && cellId) {
        self.updateHUD(cellId, coords, cell);
      }
    }
    this.initEvents = function() {

      var scale = 150;
      var drag = d3.behavior.drag()
        .on('dragstart', function () {
        })
        .on('drag', function () {
          self.rotateLongitude += 100 * d3.event.dx / zoom.scale();
          self.rotateLatitude -= 100 * d3.event.dy / zoom.scale();
          self.projection.rotate([self.rotateLongitude, self.rotateLatitude]);
          self.drawWorld();
          self.drawGeoJSONLayers();
          self.drawGraticule();
          self.draw();
        })
        .on('dragend', function () {
          self.draw();
        });

      var zoom = d3.behavior.zoom()
        .on('zoomstart', function() {
        })
        .on('zoomend', function() {
          self.draw();
        })
        .on('zoom', function(d) {
          if (zoom.scale() >= 2000 || zoom.scale() <= self.width/6) {
            return;
          }
          scale = d3.event.scale;
          self.area = 20000 / scale / scale;
          self.projection.scale(scale);
          self.drawWorld();
          self.drawGeoJSONLayers();
          self.drawGraticule();
          self.draw();
        })
        .scale(this.width/6)
        .scaleExtent([this.width/6, 2000]);

      this.container.call(drag);
      this.container.call(zoom);

      this.container.on('mousemove', self.onMouseMove);
      d3.select(window).on('resize', self.resize);
    };

    var graticule = d3.geo.graticule()();

    this.drawWorld = function() {
      this.context.clearRect(0, 0, this.width, this.height);

      //draw world background (the sea)
      this.context.beginPath();
      this.path(worldGeoJSON);
      this.context.closePath();
      this.context.fillStyle = this.seaColor;
      this.context.fill();
    };

    this.drawGeoJSONLayer = function(layer) {

      self.context.beginPath();
      self.simplifyingPath(layer.geojson);
      self.context.strokeStyle = layer.options.strokeColor;
      self.context.lineWidth = 0.5;
      self.context.stroke();

      self.context.fillStyle = layer.options.fillColor;
      self.context.fill();
    };

    this.drawGrid = function(grid) {

      var image = this.context.getImageData(0, 0, this.width, this.height);
      var imageData = image.data;

      for (var y = 0; y < this.height; y++) {
        for (var x = 0; x < this.width; x++) {
          var p = this.projection.invert([x, y]);

          if (!p) {
            continue;
          }

          var λ = p[0];
          var φ = p[1];

          if (λ > 180 || λ < -180 || φ > 90 || φ < -90) {
            continue;
          }
          var i = (x + this.width * y) * 4;

          // Add 1 because cell IDs are defined to be 1-based instead
          // of our 0-based arrays.
          var q = ~~((~~((90 - φ) / 180 * grid.rows) * grid.cols + (180 + λ) / 360 * grid.cols + 1.0));

          if (grid.data[q*4+3] === 0) {
            // skip where alpha is 0;
            continue;
          }
          imageData[i] = grid.data[q*4];
          imageData[i+1] = grid.data[q*4+1];
          imageData[i+2] = grid.data[q*4+2];
          imageData[i+3] = grid.data[q*4+3];
        }
      }
      self.context.putImageData(image, 0, 0);
    };

    this.drawGraticule = function() {
      this.context.beginPath();
      this.path(graticule);
      this.context.closePath();
      this.context.lineWidth = 1;
      this.context.strokeStyle = this.graticuleColor;
      this.context.stroke();
    };

    this.drawGeoJSONLayers = function() {
      for (var i=0; i<self.layers.length; i++) {
        var layer = self.layers[i];
        if (layer.geojson) {
          self.drawGeoJSONLayer(layer);
        }
      }
    };

    this.dispatch = d3.dispatch('drawStart', 'drawEnd');

    this._draw = function() {

      /**
        * clears the canvas,
        * draws the background
        * draws data layers
        * draws graticule
        */

      self.dispatch.drawStart();

      self.drawWorld();

      for (var i=0; i<self.layers.length; i++) {
        var layer = self.layers[i];

        if (layer.geojson) {
          self.drawGeoJSONLayer(layer);
        } else if (layer.grid) {
          self.drawGrid(layer.grid);
        }
      }

      self.drawGraticule();

      self.dispatch.drawEnd();
    };

    var debounceLock = false;

    var debounce = function(fn, timeout) {
      var timeoutID = -1;
      return function() {
        if (debounceLock) {
          console.log('debounce contention');
          return;
        }
        debounceLock = true;
        if (timeoutID > -1) {
          window.clearTimeout(timeoutID);
        }
        timeoutID = window.setTimeout(fn, timeout);
        debounceLock = false;
      };
    };

    self.draw = debounce(self._draw, 500);

    this._resize = function() {
      self.width = parseInt(self.container.style('width'), 10);
      self.canvas.attr('width', self.width);
      self.hud.attr('width', self.width);
      self.projection
        .translate([self.width/2, self.height/2])
        .clipExtent([[0, 0], [self.width, self.height]]);
      self.draw();
    };

    this.resize = debounce(self._resize, 200);

    this.panToCentroid = function() {
      console.debug('panToCentroid needs updating');
      return;
      var centroid = d3.geo.centroid(this.geojson);
      var rotation = this.projection.rotate();
      rotation[0] = -centroid[0]; // note the '-'
      this.projection.rotate(rotation);
    };

    this.setData = function(data, options) {
      var layer = new Layer(options);

      if (data.constructor === ArrayBuffer) {
        var grid = this.arrayBufferToGrid(data, options.gridSize);
        layer.grid = grid;
      } else if (data.constructor === Uint8ClampedArray) {
        var grid = new Grid(data, options.gridSize);
        layer.grid = grid;
      } else {
        // assume GeoJSON
        if (data.type === 'Topology') {
          // it is topojson
          topojson.presimplify(data);
          // FIXME: this isn't good.  hardcoded assuming only countries data
          // and immediately converting topojson to geojson.
          data = topojson.feature(data, data.objects.countries);
        }
        layer.geojson = data;
      }
      self.layers.push(layer);
      self.draw();
    };

    this.uInt8ArrayToGeoJSON = function(array) {
      console.debug('uInt8ArrayToGeoJSON is deprecated. Use setData');

      // given a UInt8ClampedArray containing data in
      // RGBA format, returns GeoJSON

      // The format is expected to be
      // a sequence of Uint8 elements representing RGBA
      // values for each cell from cell ID 1 to the final cell ID,
      // in column first order.

      var geojson = {
         type: "FeatureCollection",
         features: []
      };

      for (var i=0; i<array.length; i+=4) {
        var cell_id = i/4 + 1;
        var r = array[i];
        var g = array[i+1];
        var b = array[i+2];
        var a = array[i+3];

        if (r === 0 && g === 0 && b === 0 && a === 0) {
          continue;
        }
        var coordinates = this.cellIdToCoordinates(cell_id);

        var feature = {
           type: 'Feature',
           id: i,
           geometry: {
               type: 'Polygon',
               coordinates: [coordinates]
           },
           properties: {
            rgba: [r,g,b,a]
          }
        };
        geojson.features.push(feature);
      }

      return geojson;
    };

    this.arrayBufferToGrid = function(buff, gridSize) {
      // given an ArrayBuffer buff containing data in
      // packed binary format, returns a Grid

      // The packed binary format is expected to be
      // a sequence of Uint32 elements in which the most
      // significant byte is the cell value and the
      // lowest 3 bytes represent the cell ID.

      var w = gridSize[1];
      var h = gridSize[0];

      var data = new Uint8ClampedArray(w*h*4);

      var typedArray = new Uint32Array(buff);

      for (var i=0; i<typedArray.length; i++) {
        var packed = typedArray[i];
        var cellId = (packed & 0xfffff) << 2;
        // unpack most significant byte, the data value.
        // note the triple arrow, which fills in 0s instead of 1s.
        var value = packed >>> 24;

        var color = d3.rgb(self.colorScale(value));
        var alpha = 255;

        data[cellId+0] = color.r;
        data[cellId+1] = color.g;
        data[cellId+2] = color.b;
        data[cellId+3] = alpha;
      }
      return new Grid(data, gridSize);
    };

    this.arrayBufferToGeoJSON = function(buff) {
      // given an ArrayBuffer buff containing data in
      // packed binary format, returns GeoJSON

      // The packed binary format is expected to be
      // a sequence of Uint32 elements in which the most
      // significant byte is the cell value and the
      // lowest 3 bytes represent the cell ID.

      var geojson = {
        type: 'FeatureCollection',
        features: [],
        _cache: {} // for quickly locating a feature by id
      };

      var typedArray = new Uint32Array(buff);

      for (var i=0; i<typedArray.length; i++) {
        var packed = typedArray[i];
        var cellId = packed & 0xfffff;
        // unpack most significant byte, the data value.
        // note the triple arrow, which fills in 0s instead of 1s.
        var value = packed >>> 24;
        var coordinates = this.cellIdToCoordinates(cellId);
        var feature = {
           type: 'Feature',
           id: i,
           geometry: {
               type: 'Polygon',
               coordinates: [coordinates]
           },
           properties: {
            cellId: cellId,
            value: value
          }
        };
        geojson.features.push(feature);
        geojson._cache[cellId] = feature;
      }
      return geojson;
    };

    this.init();
  };

  d3.geo.GridMap = GridMap;

})();


text:
<?php
namespace Yaf\Exception ;

/**
 * @link http://www.php.net/manual/en/class.yaf-exception-loadfaild.php
 */
class LoadFailed extends \Yaf\Exception {

}


text: Software architecture section


text:
package io.github.msurdi.redeye.core.lucene;

import io.github.msurdi.redeye.api.Indexable;
import io.github.msurdi.redeye.api.Query;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.store.SimpleFSDirectory;

import java.io.File;
import java.io.IOException;

/**
 * Implementation of an lucene for {@link io.github.msurdi.redeye.api.Query} instances.
 */
public class QueryIndex extends AbstractIndex<Query> {
    private static final String NAME_FIELD = "name";
    private static final String QUERY_FIELD = "query";
    private static final String DESCRIPTION_FIELD = "description";

    public QueryIndex() {
        super(new RAMDirectory());
    }

    public QueryIndex(File path) throws IOException {
        super(new SimpleFSDirectory(path));
    }

    @Override
    protected Query buildEntity(Document document) {
        return Query.builder().id(document.get(Indexable.ID_FIELD))
                .name(document.get(NAME_FIELD))
                .query(document.get(QUERY_FIELD))
                .description(document.get(DESCRIPTION_FIELD))
                .build();
    }

    @Override
    protected Document buildDocument(String id, Query query) {
        Document doc = new Document();
        doc.add(new StringField(Indexable.ID_FIELD, id, Field.Store.YES));
        doc.add(new TextField(NAME_FIELD, query.getName(), Field.Store.YES));
        doc.add(new StringField(QUERY_FIELD, query.getQuery(), Field.Store.YES));
        doc.add(new TextField(DESCRIPTION_FIELD, query.getDescription(), Field.Store.YES));
        return doc;
    }

}


text:
package com.outbrain.selenium.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketTestWaitCondition {
  private final String host;
  private final int port;
  private final int timeout;

  public SocketTestWaitCondition(final String host, final int port, final int timeout) {
    this.host = host;
    this.port = port;
    this.timeout = timeout;
  }

  public boolean checkCondition(final long elapsedTimeInMs) {
    Socket socket = null;
    try {
      socket = new Socket();
      socket.bind(null);
      socket.connect(new InetSocketAddress(host, port), timeout);
      socket.close();
      return true;
    } catch (final IOException e) {
      return false;
    } finally {
      if (socket != null) {
        try {
          socket.close();
        } catch (final IOException e) {
          // ignore
        }
      }
    }
  }
}


text:
<?php

class SolrQueryException extends Exception {
}

?>