text:
package org.apache.mesos.elasticsearch.executor.elasticsearch;

import org.apache.mesos.elasticsearch.executor.model.PortsModel;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

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

/**
 * Tests that ES node can be launched using provided settings.
 */
@RunWith(MockitoJUnitRunner.class)
public class ElasticsearchLauncherTest {
    @Test(expected = NullPointerException.class)
    public void shouldExceptionIfNullSettings() {
        new ElasticsearchLauncher(null);
    }

    @Test
    public void shouldLaunchWithDefaultSettings() throws InterruptedException {
        ElasticsearchSettings esSettings = new ElasticsearchSettings();
        ImmutableSettings.Builder settings = esSettings.defaultSettings()
                // Set local
                .put("node.local", true);
        // Remove zookeeper settings
        settings.remove("discovery.type");
        settings.remove("sonian.elasticsearch.zookeeper.settings.enabled");
        settings.remove("sonian.elasticsearch.zookeeper.client.host");
        settings.remove("sonian.elasticsearch.zookeeper.discovery.state_publishing.enabled");
        ElasticsearchLauncher elasticsearchLauncher = new ElasticsearchLauncher(settings);
        elasticsearchLauncher.launch();
    }

    @Test
    public void shouldLaunchWithRunTimeSettings() throws InterruptedException {
        ElasticsearchSettings esSettings = new ElasticsearchSettings();
        ImmutableSettings.Builder settings = esSettings.defaultSettings()
                // Set local
                .put("node.local", true);
        // Remove zookeeper settings
        settings.remove("discovery.type");
        settings.remove("sonian.elasticsearch.zookeeper.settings.enabled");
        settings.remove("sonian.elasticsearch.zookeeper.client.host");
        settings.remove("sonian.elasticsearch.zookeeper.discovery.state_publishing.enabled");
        ElasticsearchLauncher elasticsearchLauncher = new ElasticsearchLauncher(settings);
        elasticsearchLauncher.addRuntimeSettings(getClientPort());
        elasticsearchLauncher.launch();
    }

    @Test
    public void shouldBeAbleToAddRunTimeSettings() {
        // Given settings
        ImmutableSettings.Builder settings = mock(ImmutableSettings.Builder.class);
        Launcher launcher = new ElasticsearchLauncher(settings);

        // When add runtime
        ImmutableSettings.Builder runtimeSettings = spy(getClientPort());
        launcher.addRuntimeSettings(runtimeSettings);

        // Ensure settings are updated
        verify(settings, times(1)).put(runtimeSettings.build());
    }

    @Test
    public void shouldBeAbleToLoadSettingsFromResources() {
        ImmutableSettings.Builder esSettings = ImmutableSettings.builder().loadFromClasspath("elasticsearch.yml");
        assertNotNull(esSettings);
    }

    private ImmutableSettings.Builder getClientPort() {
        return ImmutableSettings.settingsBuilder().put(PortsModel.HTTP_PORT_KEY, "1234");

    }
}


text:
<?php

namespace App\Presenters;

use Nette\Utils\DateTime,
	Model,
	App\Forms;

/**
 * Intention presenter.
 */
class IntentionPresenter extends BasePresenter
{
	/** @var Model\IntentionManager @inject */
	public $intentionManager;

	public function handleIntention($date, $time, $intention = NULL, $id = NULL, $amount = NULL, $code = NULL)
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','add')) {
			if(isset($code) && $code > 0) {
				$priest = $this->intentionManager->getNameByCode($code);
				if(isset($priest->name) && $priest->name != '') {
					if(isset($intention) && $intention != '') {
						if(isset($id) && $id > 0) {
							$this->flashMessage('Intence pro vybranou mši je již zadaná!', 'danger');
						} else {
							$values = [
								'date' => $date,
								'time' => $time,
								'intention' => $intention,
								'amount' => $amount,
								'code' => $code
							];
							$valuesLog = [
								'date' => $date,
								'time' => $time,
								'intention' => $intention,
								'amount' => $amount,
								'code_id' => $code,
								'type' => 'insert',
								'ts' => new DateTime()
							];
							$this->intentionManager->save($values);
							$this->intentionManager->insertLog($valuesLog);
						}
					} else {
						$this->flashMessage('Nemáš zadanou intenci!', 'danger');
					}
				} else {
					$this->flashMessage('Chybně vložený kontrolní kód!', 'danger');
				}
			} else {
				$this->flashMessage('Nebylo zadáno heslo!', 'danger');
			}
		} else {
			$this->flashMessage('Nemáš práva k editaci intencí!', 'danger');
		}
	}

	public function renderDefault($date = NULL)
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','default')) {
			$navigation = $this['navigation'];
			$date = new DateTime($navigation->date);
			$this->template->date = $date->format('Y-m-d');
			$days = $date->format('j')-1;
			$date = $date->sub(new \DateInterval("P{$days}D"));
			$this->template->addFilter('czechDate', 'App\Helpers\Helpers::czechDate');
			$this->template->items = $this->intentionManager->findByDate($date->format('Y-m-d'));
			if($this->isAjax()) {
				$this->redrawControl();
			}
		} else {
			$this->flashMessage('Nemáš práva pro nahlížení do intencí.', 'danger');
			$this->redirect('Homepage:');
		}
	}

	public function renderExport($date = NULL)
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','export')) {
			$date = new DateTime($date);
			$this->template->addFilter('czechDate', 'App\Helpers\Helpers::czechDate');
			$this->template->date = $date->format('Y-m-d');
			$this->template->items = $this->intentionManager->findByDateWeek($date->format('Y-m-d'));
			if($this->isAjax()) {
				$this->redrawControl();
			}
		} else {
			$this->flashMessage('Nemáš práva pro export intencí pro tisk.', 'danger');
			$this->redirect('Intention:');
		}
	}

	public function renderStatement($date = NULL)
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','statement')) {
			$date = new DateTime($date);
			$this->template->addFilter('czechDate', 'App\Helpers\Helpers::czechDate');
			$this->template->addFilter('currency', 'App\Helpers\Helpers::currency');
			$this->template->date = $date->format('Y-m-d');
			$items = $this->intentionManager->findByDateMonth($date->format('Y-m-d'));
			$this->template->items = $items;
			$this->template->summary = $this->intentionManager->getSummary($items,$date);
			if($this->isAjax()) {
				$this->redrawControl();
			}
		} else {
			$this->flashMessage('Nemáš práva pro nahlížení do výkazu intencí.', 'danger');
			$this->redirect('Intention:');
		}
	}

	public function renderEdit($id, $date)
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','edit')) {
			$row = $this->intentionManager->getById($id);
			if (!$row) {
				$date = new DateTime($date);
				$this->flashMessage('Intence nenalezena.', 'danger');
				$this->redirect('Intention:Statement',$date->format('Y-m-d'));
			}
			$values['id'] = $row['id'];
			$values['date'] = $row['date']->format('Y-m-d');
			$values['time'] = $row['time']->format('%H:%I:%S');
			$values['intention'] = $row['intention'];
			$values['amount'] = $row['amount'];
			$this['intentionForm']->setDefaults($values);
		} else {
			$this->flashMessage('Nemáš práva pro editaci intencí.', 'danger');
			$this->redirect('Intention:');
		}
	}

	public function renderDelete($id, $date)
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','edit')) {
			$row = $this->intentionManager->getById($id);
			if (!$row) {
				$date = new DateTime($date);
				$this->flashMessage('Intence nenalezena.', 'danger');
				$this->redirect('Intention:Statement',$date->format('Y-m-d'));
			}
			$values['id'] = $row['id'];
			$values['date'] = $row['date']->format('Y-m-d');
			$values['time'] = $row['time']->format('%H:%I:%S');
			$values['intention'] = $row['intention'];
			$values['amount'] = $row['amount'];
			$this['intentionDeleteForm']->setDefaults($values);
#			$this['intentionDeleteForm']['intention']->
			$this['intentionDeleteForm']['intention']->setAttribute('readonly','readonly');
			$this['intentionDeleteForm']['amount']->setAttribute('readonly','readonly');
			$this['intentionDeleteForm']['save']->caption = 'Smazat intenci';
		} else {
			$this->flashMessage('Nemáš práva pro editaci intencí.', 'danger');
			$this->redirect('Intention:');
		}
	}

	protected function createComponentIntentionForm($name)
	{
		$form = new Forms\IntentionForm($this, $name);
		$form->onSuccess[] = [$this, 'intentionFormSubmitted'];
		return $form;
	}

	protected function createComponentIntentionDeleteForm($name)
	{
		$form = new Forms\IntentionForm($this, $name);
		$form->onSuccess[] = [$this, 'intentionDeleteFormSubmitted'];
		return $form;
	}

	public function intentionFormSubmitted(Forms\IntentionForm $form)
	{
		$values = $form->getValues();
		$date = new DateTime($values['date']);
		$result = $this->intentionManager->save($values);
		$values['date'] = null;
		if ($result === 'inserted') {
			$this->flashMessage('Nová intence byla vložena', 'success');
		} elseif($result === 'updated') {
			$this->flashMessage('Intence byla upravena.', 'success');
		} elseif($result === 'deleted') {
			$this->flashMessage('Intence byla smazána.', 'success');
		} elseif($result === 'nocode') {
			$this->flashMessage('Nebyl zadán kontrolní kód.', 'danger');
		} elseif($result === 'falsecode') {
			$this->flashMessage('Chybně zadaný kontrolní kód.', 'danger');
		} elseif($result === FALSE) {
			$this->flashMessage('Došlo k chybě při ukládání.', 'danger');
		}
		$this->redirect('Intention:Statement',$date->format('Y-m-d'));
	}

	public function intentionDeleteFormSubmitted(Forms\IntentionForm $form)
	{
		$values = $form->getValues();
		$date = new DateTime($values['date']);
		if(isset($values['code']) && $values['code'] > 0) {
			$priest = $this->intentionManager->getNameByCode($values['code']);
			if(isset($priest->name) && $priest->name != '') {
				$result = $this->intentionManager->deleteById($values['id']);
				$valuesLog = [
					'date' => $values['date'],
					'time' => $values['time'],
					'intention' => $values['intention'],
					'amount' => $values['amount'],
					'code_id' => $values['code'],
					'type' => 'delete',
					'ts' => new DateTime()
				];
				$this->intentionManager->insertLog($valuesLog);
				if ($result !== false) {
					$this->flashMessage('Intence byla smazána.', 'success');
				} else {
					$this->flashMessage('Došlo k chybě při mazání intence.', 'danger');
				}
				$this->redirect('Intention:Statement',$date->format('Y-m-d'));
			} else {
				$this->flashMessage('Chybně zadaný kontrolní kód.', 'danger');
			}
		} else {
			$this->flashMessage('Nezadaný kontrolní kód.', 'danger');
		}
	}

	public function renderCode()
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','code')) {
			$items = $this->intentionManager->findAllCode();
			$this->template->items = $items;
			if($this->isAjax()) {
				$this->redrawControl();
			}
		} else {
			$this->flashMessage('Nemáš práva pro nahlížení a editaci kontrolních kódů.', 'danger');
			$this->redirect('Intention:');
		}
	}

	public function renderAddCode()
	{
		if(!$this->getUser()->isLoggedIn() && !$this->getUser()->isAllowed('Intention','code')) {
			$this->flashMessage('Nemáš práva pro editaci kontrolních kódů.', 'danger');
			$this->redirect('Intention:');
		}
	}

	public function renderEditCode($id)
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','code')) {
			$row = $this->intentionManager->getCodeById($id);
			if (!$row) {
				$date = new DateTime($date);
				$this->flashMessage('Přístupový kód nenalezen.', 'danger');
				$this->redirect('Intention:Code');
			}
			$this['codeForm']->setDefaults($row);
		} else {
			$this->flashMessage('Nemáš práva pro editaci kontrolních kódů.', 'danger');
			$this->redirect('Intention:');
		}
	}

	protected function createComponentCodeForm($name)
	{
		$form = new Forms\CodeForm($this, $name);
		$form->onSuccess[] = [$this, 'codeFormSubmitted'];
		return $form;
	}

	public function codeFormSubmitted(Forms\CodeForm $form)
	{
		$values = $form->getValues();
		$result = $this->intentionManager->saveCode($values);

		if ($result == 'inserted') {
			$this->flashMessage('Nový kód byl vložen', 'success');
		} elseif($result == 'updated') {
			$this->flashMessage('Kód byl upraven.', 'success');
		} elseif($result == 'duplicate') {
			$this->flashMessage('Kód již existuje, zvol jiný kód.', 'danger');
		} else {
			$this->flashMessage('Došlo k chybě při ukládání.', 'danger');
		}
		$this->redirect('Intention:Code');
	}

	public function handleDisableCode($id) {
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','code')) {
			$row = $this->intentionManager->getCodeById($id);
			if ($row) {
				$result = $this->intentionManager->disableCode($id);
				if ($result) {
					$this->flashMessage('Přístupový kód zablokován.', 'success');
				} else {
					$this->flashMessage('Došlo k chybě při blokování bezpečnostního kódu.', 'danger');
				}
				$this->redirect('Intention:Code');
			}
		} else {
			$this->flashMessage('Nemáš práva pro editaci přístupových kódů.', 'danger');
			$this->redirect('Intention:');
		}
	}

	public function renderProtocol($date)
	{
		if($this->getUser()->isLoggedIn() && $this->getUser()->isAllowed('Intention','protocol')) {
			$navigation = $this['navigation'];
			$date = new DateTime($navigation->date);
			$this->template->addFilter('czechDate', 'App\Helpers\Helpers::czechDate');
			$this->template->addFilter('currency', 'App\Helpers\Helpers::currency');
			$this->template->addFilter('type', 'App\Helpers\Helpers::type');
			$vp = $this['vp'];
			$paginator = $vp->getPaginator();
	#		$date = $date ? $date : new DateTime();
			$by = ['date>=' => $date->format('Y-m-1'), 'date<=' => $date->format('Y-m-t')];
			$paginator->itemCount = $this->intentionManager->getCountLogBy($by);
			$this->template->page = $paginator->page;
			$this->template->items = $this->intentionManager->findLogBy($by,$paginator->itemsPerPage,$paginator->offset);
		} else {
			$this->flashMessage('Nemáš práva pro nahlížení do protokolu intencí.', 'danger');
			$this->redirect('Intention:');
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace ImageProcessor.Plugins.Effects.Tests
{
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using FluentAssertions;
    using Xunit;

    public class BiTonalTests : BaseTest
    {
        [Fact]
        public void Different_dark_color_yield_different_images()
        {
            foreach (string file in this.images)
            {
                // arrange
                using (ImageFactory factory = new ImageFactory())
                {
                    factory.Load(file);

                    BiTonal processor = new BiTonal();
                    processor.DynamicParameter = new BiTonalParameters() { DarkColor = Color.Black };

                    BiTonal processor2 = new BiTonal();
                    processor2.DynamicParameter = new BiTonalParameters() { DarkColor = Color.DarkCyan };

                    // act
                    Bitmap result = new Bitmap(processor.ProcessImage(factory));
                    Bitmap result2 = new Bitmap(processor2.ProcessImage(factory));
                    result2.Save(string.Format("{0}/{1}_bitonal_dark_color2.jpg", Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)), ImageFormat.Jpeg);

                    // assert
                    result.Equals(result2).Should().BeFalse("because different parameters should yield different images");
                }
            }
        }

        [Fact]
        public void Different_light_color_yield_different_images()
        {
            foreach (string file in this.images)
            {
                // arrange
                using (ImageFactory factory = new ImageFactory())
                {
                    factory.Load(file);

                    BiTonal processor = new BiTonal();
                    processor.DynamicParameter = new BiTonalParameters() { LightColor = Color.White };

                    BiTonal processor2 = new BiTonal();
                    processor2.DynamicParameter = new BiTonalParameters() { LightColor = Color.Cyan };

                    // act
                    Bitmap result = new Bitmap(processor.ProcessImage(factory));
                    Bitmap result2 = new Bitmap(processor2.ProcessImage(factory));
                    result2.Save(string.Format("{0}/{1}_bitonal_light_color2.jpg", Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)), ImageFormat.Jpeg);

                    // assert
                    result.Equals(result2).Should().BeFalse("because different parameters should yield different images");
                }
            }
        }

        [Fact]
        public void Different_threshold_yield_different_images()
        {
            foreach (string file in this.images)
            {
                // arrange
                using (ImageFactory factory = new ImageFactory())
                {
                    factory.Load(file);

                    BiTonal processor = new BiTonal();
                    processor.DynamicParameter = new BiTonalParameters() { Threshold = 155 };

                    BiTonal processor2 = new BiTonal();
                    processor2.DynamicParameter = new BiTonalParameters() { Threshold = 200 };

                    // act
                    Bitmap result = new Bitmap(processor.ProcessImage(factory));
                    Bitmap result2 = new Bitmap(processor2.ProcessImage(factory));
                    result2.Save(string.Format("{0}/{1}_bitonal_threshold2.jpg", Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)), ImageFormat.Jpeg);

                    // assert
                    result.Equals(result2).Should().BeFalse("because different parameters should yield different images");
                }
            }
        }

        [Fact]
        public override void Image_is_processed()
        {
            foreach (string file in this.images)
            {
                // arrange
                using (ImageFactory factory = new ImageFactory())
                {
                    factory.Load(file);

                    BiTonal processor = new BiTonal();
                    processor.DynamicParameter = new BiTonalParameters();

                    // act
                    Action act = () =>
                    {
                        Image img = processor.ProcessImage(factory);
                        img.Save(string.Format("{0}/{1}_bitonal_default.jpg", Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)), ImageFormat.Jpeg);
                    };

                    // assert
                    act.ShouldNotThrow("because the image should have been processed without error");
                }
            }
        }
    }
}


text:
DashX - A Node.js/ReactJS Dashboard
---------------------------

This module is under development. For any question please email me@miladrk.com

![alt tag](./Animation.gif)

Steps to setup and use the tool :

1. get the source from git

`git clone https://github.com/milianoo/dashx.git`

2. install node dependencies

`npm install`

3. install bower dependencies

`bower install`

4. generate js bundle

`webpack`

Project plan
------------

Iteration 1
===========

1. create dashboard basic design
2. add basic widget to dashboard
3. load basic info for widget
4. setup timer to reload widget

Iteration 2
===========

1. add widgets on-the-fly from the UI
2. configure widget data source and display info
3. configure OAuth for widgets if needed
4. setup config/template for each widget
5. enhance UI of widget

iteration 3
===========

1. ability to re-size widgets
2. drag-n-drop widgets
3. error handling
4. generate new widget using grunt
5. load widgets on load from config file

iteration 4
===========

1. save config files in database
2. easier connection to social networks (oauth 2.0 required)
3. display data from other social networks as widgets

iteration 5
===========

1. dashboard as a service
2. single config file for each dashboard
3. generate individual url for each dashboard

# License

> The MIT License (MIT)
>
> Copyright (c) 2016 Milad Rezazadeh
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using MarginTrading.AzureRepositories.Contract;
using MarginTrading.Backend.Core;
using MarginTrading.Backend.Core.Settings;
using MarginTrading.Backend.Core.TradingConditions;

namespace MarginTrading.Backend.Services.TradingConditions
{
    public class AccountGroupManager : IStartable
    {
        private readonly AccountGroupCacheService _accountGroupCacheService;
        private readonly IAccountGroupRepository _repository;
        private readonly MarginSettings _settings;
        private readonly IClientNotifyService _clientNotifyService;

        public AccountGroupManager(
            AccountGroupCacheService accountGroupCacheService,
            IAccountGroupRepository accountGroupRepository,
            MarginSettings settings,
            IClientNotifyService clientNotifyService)
        {
            _accountGroupCacheService = accountGroupCacheService;
            _repository = accountGroupRepository;
            _settings = settings;
            _clientNotifyService = clientNotifyService;
        }

        public void Start()
        {
            UpdateAccountGroupCache().Wait();
        }

        public async Task UpdateAccountGroupCache()
        {
            var accountGroups = (await _repository.GetAllAsync()).ToList();
            _accountGroupCacheService.InitAccountGroupsCache(accountGroups);
        }

        public async Task AddAccountGroupsForTradingCondition(string tradingConditionId)
        {
            foreach (var asset in _settings.BaseAccountAssets)
            {
                await _repository.AddOrReplaceAsync(new AccountGroup
                {
                    BaseAssetId = asset,
                    MarginCall = LykkeConstants.DefaultMarginCall,
                    StopOut = LykkeConstants.DefaultStopOut,
                    TradingConditionId = tradingConditionId
                });
            }

            await UpdateAccountGroupCache();
        }

        public async Task<IAccountGroup> AddOrReplaceAccountGroupAsync(IAccountGroup accountGroup)
        {
            await _repository.AddOrReplaceAsync(accountGroup);
            await UpdateAccountGroupCache();

            await _clientNotifyService.NotifyTradingConditionsChanged(accountGroup.TradingConditionId);

            return accountGroup;
        }
    }
}


text:
require 'tc_helper.rb'

class TestHyperlink < Test::Unit::TestCase

  def setup
    @p = Axlsx::Package.new
    ws = @p.workbook.add_worksheet
    @test_img =  File.dirname(__FILE__) + "/../../examples/image1.jpeg"
    @image = ws.add_image :image_src => @test_img, :hyperlink => "http://axlsx.blogspot.com"
    @hyperlink = @image.hyperlink
  end

  def teardown
  end

  def test_href
    assert_nothing_raised { @hyperlink.href = "http://axlsx.blogspot.com" }
    assert_equal(@hyperlink.href, "http://axlsx.blogspot.com")
  end

  def test_tgtFrame
    assert_nothing_raised { @hyperlink.tgtFrame = "http://axlsx.blogspot.com" }
    assert_equal(@hyperlink.tgtFrame, "http://axlsx.blogspot.com")
  end

  def test_tooltip
    assert_nothing_raised { @hyperlink.tooltip = "http://axlsx.blogspot.com" }
    assert_equal(@hyperlink.tooltip, "http://axlsx.blogspot.com")
  end

  def test_invalidUrl
    assert_nothing_raised { @hyperlink.invalidUrl = "http://axlsx.blogspot.com" }
    assert_equal(@hyperlink.invalidUrl, "http://axlsx.blogspot.com")
  end

  def test_action
    assert_nothing_raised { @hyperlink.action = "flee" }
    assert_equal(@hyperlink.action, "flee")
  end

  def test_endSnd
    assert_nothing_raised { @hyperlink.endSnd = "true" }
    assert_raise(ArgumentError) {@hyperlink.endSnd = "bob"}
    assert_equal(@hyperlink.endSnd, "true")
  end

  def test_highlightClick
    assert_nothing_raised { @hyperlink.highlightClick = false }
    assert_raise(ArgumentError) {@hyperlink.highlightClick = "bob"}
    assert_equal(@hyperlink.highlightClick, false )
  end

  def test_history
    assert_nothing_raised { @hyperlink.history = false }
    assert_raise(ArgumentError) {@hyperlink.history = "bob"}
    assert_equal(@hyperlink.history, false )
  end

  def test_to_xml_string
    doc = Nokogiri::XML(@p.workbook.worksheets.first.drawing.to_xml_string)
    assert(doc.xpath("//a:hlinkClick"))
  end
end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DifficultyRatable : MonoBehaviour
{
    [SerializeField]
    protected Difficulty _difficulty;
    internal Difficulty Difficulty {get{ return _difficulty; }}
}


text:
<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Migrations;

use Jivoo\Setup\InstallerSnippet;
use Jivoo\Setup\AsyncTaskBase;
use Jivoo\Databases\MigratableDatabase;

/**
 * Migration updater. Migrates tables.
 */
class MigrationUpdater extends InstallerSnippet {

  /**
   * @var string Name of database being migrated.
   */
  protected $dbName = 'default'; // TODO: set this somewhere

  /**
   * @var \Jivoo\Databases\Database Database being migrated.
   */
  protected $db = null;

  /**
   * {@inheritdoc}
   */
  protected function setup() {
    $this->appendStep('migrate');
  }

  /**
   * {@inheritdoc}
   */
  public function before() {
    $this->m->units->run('Migrations');

    $name = $this->dbName;
    $this->db = $this->m->Databases->$name->getConnection();
  }

  /**
   * Installer step: Migrate tables.
   * clean or initialize.
   * @param array $data POST data.
   * @return \Jivoo\Routing\Response|string Response.
   */
  public function migrate($data = null) {
    $this->viewData['title'] = tr('Migrating database');
    $task = new MigrateTask($this->m->Migrations, $this->dbName);
    if ($this->runAsync($task)) {
      $this->m->Migrations->finalize($this->dbName);
      return $this->next();
    }
    return $this->render();
  }
}

/**
 * Asynchronous task for migrating tables.
 */
class MigrateTask extends AsyncTaskBase {
  /**
   * @var Migrations
   */
  private $migrations;

  /**
   * @var string
   */
  private $name;

  /**
   * @var string[]
   */
  private $missing = array();

  /**
   * @var int
   */
  private $count = 0;

  /**
   * Construct migration task.
   * @param Migrations $migrations Migrations module.
   * @param string $dbName Name of database to migrate.
   */
  public function __construct(Migrations $migrations, $dbName) {
    $this->migrations = $migrations;
    $this->name = $dbName;
  }

  /**
   * {@inheritdoc}
   */
  public function suspend() {
    return array(
      'missing' => $this->missing,
      'count' => $this->count
    );
  }

  /**
   * {@inheritdoc}
   */
  public function resume(array $data) {
    if (isset($data['count']))
      $this->count = $data['count'];
    if (isset($data['waiting'])) {
      $this->missing = $data['missing'];
    }
    else {
      $this->missing = $this->migrations->check($this->name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function isDone() {
    return count($this->missing) == 0;
  }

  /**
   * {@inheritdoc}
   */
  public function run() {
    $this->progress($this->count / ($this->count + count($this->missing)) * 100);
    $migration = $this->missing[0];
    $this->status(tr('Running migration "%1"...', $migration));
    $this->migrations->run($this->name, $migration);
    $migration = array_shift($this->missing);
    $this->count++;
  }
}


text:
An OAuth2 compliant NodeJS Coinbase API library

[![Build Status](https://secure.travis-ci.org/mdp/NCoinbase.png)](http://travis-ci.org/mdp/NCoinbase)

## Quick Overview

- Implements all the v1 API methods
- Every API method allows callbacks or returns promises
- Automatically refreshes expired tokens (and fires an event)

## Installation

    npm install ncoinbase

## Usage

### Setting up the client

    var Coinbase = require('ncoinbase').Coinbase,
        api = new Coinbase({
          "id": "api_id",
          "secret": "api_secret",
          "redirect_uri": "http://localhost:4000/callback",
          "scope": "balance request"
        });

### Creating and API consumer (user)

    // Assuming we pulled the users credentials
    // from the database and assigned them to 'user'
    credentials = new Credentials(user);
    consumer = api.createConsumer(credentials);

### Accessing the API

    req.coinbase.account_balance(function (err, resp) {
      console.log("My Account balance is: " + resp.amount );
    });

#### Using Promises

    req.coinbase.account_balance()
      .then(function (resp) {
        console.log("Resp", resp);
        res.send(resp);
      })
      .catch(function (err) {
        console.log("Err", err);
        res.send("API Request failed: " + err.message);
      });

#### Refreshing expired tokens

Expired tokens will be automatically refreshed when you attempt an API call.
You can, and should, listen for this for the 'updatedCredentials' event and
save the new credentials.

    consumer.on('updatedCredentials', function (credentials) {
      user.credentials = credentials;
      user.save();
    });
    // Let's assume the users credentials are expired
    // and we need to use the refresh token.
    consumer.account_balance(function (err, resp) {
      // This will still work, but before the 'account_balance'
      // request is made, the credentials will be refreshed,
      // and the 'updatedCredentials' event will be fired.
      console.log("I have " + resp.amount + " many bitcoins!!!");
    });

## Example web application

### Clone the repo and 'npm install'

    git clone https://github.com/mdp/NCoinbase.git
    cd NCoinbase
    npm install

    node example/server.js

### Authenticate with Coinbase

Now visit [http://localhost:4000](http://localhost:4000) to authenticate

### Exercise the API

After authenticating you should see your account details on the index page.
You can also try [http://localhost:4000/my_balance](http://localhost:4000/my_balance)
for your account balance.

### The nitty gritty

The example app show several library features

- Watching for expired/refreshed credentials and updating the session [example/server.js#L27](mdp/NCoinbase/blob/master/example/server.js#L27)
- Using promises with an error catch [example/server.js#L49](mdp/NCoinbase/blob/master/example/server.js#L49)
- Passing in a callback function [example/server.js#L61](mdp/NCoinbase/blob/master/example/server.js#L61)

## Testing

    git clone https://github.com/mdp/NCoinbase.git
    cd NCoinbase
    npm install
    npm test


text:
from setuptools import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
   ##  don't do this unless you want a globally visible script
   # scripts=['bin/myscript'],
   packages=['vigir_generic_params'],
   package_dir={'': 'src'}
)

setup(**d)


text:
package hyweb.jo.fun.ende;

import hyweb.jo.IJOFunction;

/**
 *
 * @author william
 */
public class md5 implements IJOFunction<String, String> {
    private  IJOFunction<String, byte[]> fun = new md5_bytes();
    @Override
    public String exec(String text) throws Exception {
        return fun.exec(text.getBytes("UTF-8"));
    }
}


text:
package com.android.layoutlib.bridge.android;

import com.android.ide.common.rendering.api.RenderParams;
import com.android.ide.common.rendering.api.SessionParams.Key;

/**
 * This contains all known keys for the {@link RenderParams#getFlag(Key)}.
 *

 * The IDE has its own copy of this class which may be newer or older than this one.
 *

 * Constants should never be modified or removed from this class.
 */
public final class RenderParamsFlags {

    public static final Key<String> FLAG_KEY_ROOT_TAG =
            new Key<String>("rootTag", String.class);
    public static final Key<Boolean> FLAG_KEY_DISABLE_BITMAP_CACHING =
            new Key<Boolean>("disableBitmapCaching", Boolean.class);
    public static final Key<Boolean> FLAG_KEY_RENDER_ALL_DRAWABLE_STATES =
            new Key<Boolean>("renderAllDrawableStates", Boolean.class);
    /**
     * To tell LayoutLib that the IDE supports RecyclerView.
     *

     * Default is false.
     */
    public static final Key<Boolean> FLAG_KEY_RECYCLER_VIEW_SUPPORT =
            new Key<Boolean>("recyclerViewSupport", Boolean.class);
    /**
     * The application package name. Used via
     * {@link com.android.ide.common.rendering.api.LayoutlibCallback#getFlag(Key)}
     */
    public static final Key<String> FLAG_KEY_APPLICATION_PACKAGE =
            new Key<String>("applicationPackage", String.class);

    // Disallow instances.
    private RenderParamsFlags() {}
}


text:
// Datawrapper
(function(){

    // Require Underscore, if we're on the server, and it's not already present.
    var root = this;
    var _ = root._;
    var $ = root.jQuery || root.Zepto || root.ender;

    // Datawrapper.Utils
    // -----------------

    var Utils = Datawrapper.Utils = function() {

        this.initialize();

    };

    _.extend(Utils.prototype, {

        initialize: function() {
            this.initializeSignUp();
            this.initializeLogout();

            $('a[data-toggle=modal]').click(function(e) {
                var a = $(e.target),
                    tgt = $(a.data('target'));
                tgt.modal();
            });

            this.Errors = {};
        },

        checkPasswordStrength: function(pwd) {
            //return $.trim(pwd).length > 7;
            return true;
        },

        checkPassword: function(curPwd, pwd, pwd2) {
            var msg, errFields;
            if (curPwd === '') {
                errFields = '#cur-pwd';
                msg = Datawrapper.Messages.provideCurPwd;
            }
            else if (pwd.length < 4) {
                errFields = '#pwd';
                msg = Datawrapper.Messages.pwdTooShort;
            }
            else if (pwd != pwd2) {
                errFields = '#pwd,#pwd2';
                msg = Datawrapper.Messages.pwdMismatch;
            }
            if (msg) {
                DW.logError(
                    msg, $(errFields.split(',')[0]).parents('.control-group')
                );
                $(errFields).parents('.control-group').addClass('error');
                return false;
            }
            return true;
        },

        clearAlerts: function () {
            $('.alert').remove();
            $('.error').removeClass('error');
        },

        refreshHeader: function() {
            location.reload();
            return;
        },

        initializeSignUp: function() {

            function refreshSalt() {
                $.getJSON('/api/auth/salt', function(res) {
                   if (res.status == 'ok') {
                      $('#btn-register, .btn-login').data('salt', res.data.salt);
                   }
                });
            }

            $('a[href=#login], a[href=#signup]').click(function(e) {
                $('#dwLoginForm').modal();
                $('#dwLoginForm .alert').remove();
                var a = $(e.target);
                var clickedLogin = a.attr('href') == '#login';
                if (clickedLogin) {
                    $('#dwLoginForm .login-email').focus();
                } else {
                    $('#register-email').focus();
                    $('.row-login').css('opacity', 0.5);
                    $('.row-login *').click(function() {
                        $('.row-login').css('opacity', 1);
                    });
                }
                if (a.data('target')) $('#dwLoginForm .login-form').data('target', a.data('target'));

                var logEmail = $('#home-login .login-form .login-email'),
                    logPwd = $('#home-login .login-form .login-pwd');
                if (logEmail.val() !== '') $('#register-email').val(logEmail.val());
                if (logPwd.val() !== '') $('#register-pwd').val(logPwd.val());

                refreshSalt();
                return false;
            });

            refreshSalt();

            $('#btn-register').click(function() {
               var pwd = $.trim($('#register-pwd').val()),
                   pwd2 = $.trim($('#register-pwd-2').val()),
                   auth_salt = $('#btn-register').data('salt');

               if (pwd == pwd2) {
                  if (true) {
                     var payload = {
                        email: $('#register-email').val(),
                        pwd: CryptoJS.HmacSHA256(pwd, auth_salt).toString(),
                        pwd2: CryptoJS.HmacSHA256(pwd2, auth_salt).toString()
                     };
                     $.ajax({
                        url: '/api/users',
                        type: 'POST',
                        data: JSON.stringify(payload),
                        dataType: 'json',
                        context: this,
                        success: function(data) {
                            if (data.status == 'ok') {
                                // If the registration went well, clear sign up form
                                $('.signup-form input').val('');
                                // and close popup. User should be logged in now.
                                DW.logMessage('Yeah, sign up went well! You are logged in now...', '.signup-form');
                                setTimeout(function() {
                                    $('#dwLoginForm').modal('hide');
                                    DW.refreshHeader();
                                }, 1000);
                            } else {
                                DW.logError(data.code, '.signup-form');
                            }
                        }
                     });
                  } else {
                     alert('Error: password is to unsecure. please chose a password with at least 8 characters');
                  }
               } else {
                  alert('Error: password mismatch');
               }
            });

            function loginEvent(evt) {
                var loginForm = $(evt.target).parents('.login-form'),
                    lgBtn = $('.btn-login', loginForm),
                    pwd = $('.login-pwd', loginForm).val(),
                    auth_salt = lgBtn.data('salt'),
                    payload = {
                        email: $('.login-email', loginForm).val(),
                        pwhash: CryptoJS.HmacSHA256(pwd, auth_salt).toString(),
                        keeplogin: $('.keep-login', loginForm).attr('checked') == 'checked'
                    };
                if (pwd === '') {
                    $('.login-pwd', loginForm).parent().addClass('error');
                    return false;
                }

                $('.control-group', loginForm).removeClass('error');

                $.ajax({
                    url: '/api/auth/login',
                    type: 'POST',
                    dataType: 'json',
                    data: JSON.stringify(payload),
                    success: function(data) {
                        if (data.status == "ok") {
                            $('#dwLoginForm').modal('hide');
                            $('input', loginForm).val('');
                            if (loginForm.data('target')) location.href = loginForm.data('target');
                            else {
                                if (location.pathname == "/login") location.pathname = "/";
                                else location.reload();
                            }
                        } else {
                            if (data.code == 'login-invalid') {
                                $('.login-pwd', loginForm).parent().addClass('error');
                            } else if (data.code == 'login-email-unknown') {
                                $('.login-email', loginForm).parent().addClass('error');
                            }
                            DW.logError(data.message, loginForm);
                        }
                    }
                });
            }

            // log in on login button click
            $('.btn-login').click(loginEvent);
            // log in on email,pwd enter press
            $('.login-form input').keyup(function(evt) {
                if (evt.keyCode == 13) loginEvent(evt);
            });

        },

        initializeLogout: function() {
            $('a[href=#logout]').click(function() {
                $.ajax({
                    url: '/api/auth/logout',
                    type: 'POST',
                    success: function(data) {
                        // DW.refreshHeader();
                        // sometimes it's a good idea to redirect
                        location.href = '/';
                    }
                });
                return false;
            });
        },

        logMessage: function(msg, parent, type) {
            if (!_.isFunction(parent.prepend)) parent = $(parent);
            $('.alert', parent).remove();
            if (type === undefined) type = 'success';
            var alert = $('
');
            alert.append('×');
            alert.append('
'+msg+'
');
            parent.prepend(alert);
            $(".alert").alert();
        },

        logError: function(msg, parent) {
            this.logMessage(msg, parent, 'error');
        },

        resendActivationMail: function(msgElement) {
            var req = $.ajax({
                url: '/api/account/resend-activation',
                type: 'POST',
                dataType: 'json'
            });
            if (msgElement) {
                req.done(function(res) {
                    if (res.status == 'ok') {
                        DW.logMessage(res.data, msgElement);
                    } else {
                        DW.logError(res.message, msgElement);
                    }
                });
            }
            return req;
        },

        popupChart: function (id, preview) {
            $.getJSON('/api/charts/'+id, function(res) {
                if (res.status == "ok") {
                    var chart = res.data,
                        chartUrl = preview ? 'http://' + DW.__domain + '/chart/' + chart.id + '/preview' :
                            'http://' + DW.__chartCacheDomain + '/' + chart.id + '/index.html';
                        chartIframe = $(''),
                        wrapper = $('

'),
                        overlay = wrapper.overlay({
                            onClose: function() {
                                location.hash = '';
                            }
                        });
                    wrapper.append('☓');
                    wrapper.append(chartIframe);

                    chartIframe.css({
                        width: chart.metadata.publish['embed-width'],
                        height: chart.metadata.publish['embed-height'],
                        background: (chart.metadata.publish['background'] || '#fff'),
                        border: '10px solid '+(chart.metadata.publish['background'] || '#fff'),
                        'border-radius': 10
                    });
                    overlay.open();
                    if (location.hash != '#/' + chart.id) {
                        location.hash = '#/' + chart.id;
                    }
                }
            });
        },

        /*
         * creates a PNG snapshot of a chart in a given iframe
         */
        snapshot: function (iframe, chart_id, thumb_id, width, height, callback) {

            function px(s) {
                return Math.floor(Number(s.substr(0, s.length-2)));
            }

            var body = iframe.get(0).contentDocument,
                win = iframe.get(0).contentWindow;

            if ($('svg', body).get(0) === undefined) return false;

            var svg = $('svg', body),
                c = win.vis.__canvas,
                x = c.lpad + (c.lpad2 || 0),
                y = 0,
                w = c.w - x - c.rpad,
                h = c.h - y - c.bpad,
                scale = Math.max(width / c.w, height / c.h);

            var canvas = document.createElement("canvas"),
                ctx = canvas.getContext("2d");

            canvas.width = c.w * scale;
            canvas.height = c.h * scale;

            ctx.fillStyle = win.vis.theme.colors.background;
            ctx.fillRect(0, 0, c.w * scale, c.h * scale);
            ctx.drawSvg(svg.get(0).innerSVG, 0, 0, c.w * scale, c.h * scale);

            var tempCanvas = document.createElement("canvas"),
                tCtx = tempCanvas.getContext("2d");

            tempCanvas.width = width;
            tempCanvas.height = height;

            //console.log( * scale);
            tCtx.drawImage(canvas, -x + (width - c.w * scale) * 0.5, -y);

            var imgData = tempCanvas.toDataURL("image/png");
            $.ajax({
                url: '/api/charts/' + chart_id + '/thumbnail/' + thumb_id,
                type: 'PUT',
                data: imgData,
                processData: false,
                dataType: 'json',
                success: function(res) {
                    if (res.status == "ok") (callback || function() {})();
                    else console.error(res);
                }
            });
        }
    });

    // -- now run datawrapper user interface
    $(function() {
        window.DW = new Datawrapper.Utils();
    });

}).call(this);


text:
Start

    npm start --production

> Casper

> The default theme for [Ghost](http://github.com/tryghost/ghost/).

> To download, visit the [releases](https://github.com/TryGhost/Casper/releases) page.


text:
<?php

namespace Respect\Validation\Exceptions\CountrySubdivision;

use Respect\Validation\Exceptions\CountrySubdivisionException;

/**
 * Exception class for Mayotte country subdivision.
 *
 * ISO 3166-1 alpha-2: YT
 */
class YtCountrySubdivisionException extends CountrySubdivisionException
{
    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => '{{name}} must be a country subdivision of Mayotte',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => '{{name}} must not be a country subdivision of Mayotte',
        ),
    );
}


text:
package org.emmalanguage
package examples.ml.classification

import api.Meta.Projections._
import api._
import examples.ml.model._

import breeze.linalg.{Vector => Vec}

class FlinkNaiveBayesIntegrationSpec extends BaseNaiveBayesIntegrationSpec with FlinkAware {

  def naiveBayes(input: String, lambda: Double, modelType: MType): Set[Model] =
    withDefaultFlinkEnv(implicit flink => emma.onFlink {
      // read the input
      val data = for (line <- DataBag.readText(input)) yield {
        val record = line.split(",").map(_.toDouble)
        LVector(record.head, Vec(record.slice(1, record.length)))
      }
      // classification
      val result = NaiveBayes(lambda, modelType)(data)
      // collect the result locally
      result.collect().toSet[Model]
    })
}


text:
package com.intellij.xdebugger.impl.ui;

import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.fileTypes.PlainTextFileType;
import com.intellij.openapi.project.Project;
import com.intellij.ui.EditorTextField;
import javax.annotation.Nonnull;

public final class TextViewer extends EditorTextField {
  private final boolean myEmbeddedIntoDialogWrapper;
  private final boolean myUseSoftWraps;

  public TextViewer(@Nonnull Project project, boolean embeddedIntoDialogWrapper, boolean useSoftWraps) {
    this(createDocument(""), project, embeddedIntoDialogWrapper, useSoftWraps);
  }

  public TextViewer(@Nonnull String initialText, @Nonnull Project project) {
    this(createDocument(initialText), project, false, false);
  }

  public TextViewer(@Nonnull Document document, @Nonnull Project project, boolean embeddedIntoDialogWrapper, boolean useSoftWraps) {
    super(document, project, PlainTextFileType.INSTANCE, true, false);

    myEmbeddedIntoDialogWrapper = embeddedIntoDialogWrapper;
    myUseSoftWraps = useSoftWraps;
    setFontInheritedFromLAF(false);
  }

  private static Document createDocument(@Nonnull String initialText) {
    final Document document = EditorFactory.getInstance().createDocument(initialText);
    if (document instanceof DocumentImpl) {
      ((DocumentImpl)document).setAcceptSlashR(true);
    }
    return document;
  }

  @Override
  protected EditorEx createEditor() {
    final EditorEx editor = super.createEditor();
    editor.setHorizontalScrollbarVisible(true);
    editor.setCaretEnabled(true);
    editor.setVerticalScrollbarVisible(true);
    editor.setEmbeddedIntoDialogWrapper(myEmbeddedIntoDialogWrapper);
    editor.getComponent().setPreferredSize(null);
    editor.getSettings().setUseSoftWraps(myUseSoftWraps);
    return editor;
  }
}


text:
<settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <servers>

    <!-- Releases -->
    <server>
      <id>klauke-enterprises-maven-releases</id>
      <password>${env.NEXUS_PASSWORD}</password>
      <username>${env.NEXUS_USERNAME}</username>
    </server>

    <!-- Snapshots -->
    <server>
      <id>klauke-enterprises-maven-snapshots</id>
      <password>${env.NEXUS_PASSWORD}</password>
      <username>${env.NEXUS_USERNAME}</username>
    </server>

  </servers>
</settings>


text:
package org.komamitsu.fluency.fluentd;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLHandshakeException;

import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ClosedByInterruptException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class MockTCPServer
{
    private static final Logger LOG = LoggerFactory.getLogger(MockTCPServer.class);
    private final boolean sslEnabled;
    private final AtomicLong lastEventTimeStampMilli = new AtomicLong();
    private final AtomicInteger threadSeqNum = new AtomicInteger();
    private ExecutorService executorService;
    private ServerTask serverTask;
    // TODO Make this class immutable
    private List<Runnable> tasks = new ArrayList<>();

    public MockTCPServer(boolean sslEnabled)
    {
        this.sslEnabled = sslEnabled;
    }

    protected EventHandler getEventHandler()
    {
        return new EventHandler()
        {
            @Override
            public void onConnect(Socket acceptSocket)
            {
            }

            @Override
            public void onReceive(Socket acceptSocket, int len, byte[] data)
            {
            }

            @Override
            public void onClose(Socket acceptSocket)
            {
            }
        };
    }

    public synchronized void start()
            throws Exception
    {
        if (executorService == null) {
            this.executorService = Executors.newCachedThreadPool(new ThreadFactory()
            {
                @Override
                public Thread newThread(Runnable r)
                {
                    return new Thread(r, String.format("accepted-socket-worker-%d", threadSeqNum.getAndAdd(1)));
                }
            });
        }

        if (serverTask == null) {
            serverTask = new ServerTask(executorService, lastEventTimeStampMilli, getEventHandler(),
                    sslEnabled ? SSLTestSocketFactories.createServerSocket() : new ServerSocket(), tasks);
            executorService.execute(serverTask);
            tasks.add(serverTask);
        }

        for (int i = 0; i < 10; i++) {
            int localPort = serverTask.getLocalPort();
            if (localPort > 0) {
                return;
            }
            TimeUnit.MILLISECONDS.sleep(500);
        }
        throw new IllegalStateException("Local port open timeout");
    }

    public void waitUntilEventsStop()
            throws InterruptedException
    {
        for (int i = 0; i < 20; i++) {
            if (lastEventTimeStampMilli.get() + 2000 < System.currentTimeMillis()) {
                return;
            }
            TimeUnit.MILLISECONDS.sleep(500);
        }
        throw new IllegalStateException("Events didn't stop in the expected time");
    }

    @Override
    public String toString()
    {
        return "MockTCPServer{" +
                "serverTask=" + serverTask +
                ", sslEnabled=" + sslEnabled +
                '}';
    }

    public int getLocalPort()
    {
        return serverTask.getLocalPort();
    }

    public synchronized void stop()
            throws IOException
    {
        stop(false);
    }

    public synchronized void stop(boolean immediate)
            throws IOException
    {
        if (executorService == null) {
            return;
        }
        LOG.debug("Stopping MockTCPServer... {}", this);
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
                LOG.debug("Shutting down MockTCPServer and child tasks... {}", this);
                executorService.shutdownNow();
            }
        }
        catch (InterruptedException e) {
            LOG.warn("ExecutorService.shutdown() was failed: {}", this, e);
            Thread.currentThread().interrupt();
        }

        if (immediate) {
            LOG.debug("Closing related sockets {}", this);
            for (Runnable runnable : tasks) {
                if (runnable instanceof ServerTask) {
                    ((ServerTask) runnable).close();
                } else if (runnable instanceof ServerTask.AcceptTask) {
                    ((ServerTask.AcceptTask) runnable).close();
                }
            }
        }

        executorService = null;
        serverTask = null;
    }

    public interface EventHandler
    {
        void onConnect(Socket acceptSocket);

        void onReceive(Socket acceptSocket, int len, byte[] data);

        void onClose(Socket acceptSocket);
    }

    private static class ServerTask
            implements Runnable
    {
        private final ServerSocket serverSocket;
        private final ExecutorService serverExecutorService;
        private final EventHandler eventHandler;
        private final AtomicLong lastEventTimeStampMilli;
        private final List<Runnable> tasks;

        private ServerTask(
                ExecutorService executorService,
                AtomicLong lastEventTimeStampMilli,
                EventHandler eventHandler,
                ServerSocket serverSocket,
                List<Runnable> tasks
                )
                throws IOException
        {
            this.serverExecutorService = executorService;
            this.lastEventTimeStampMilli = lastEventTimeStampMilli;
            this.eventHandler = eventHandler;
            this.serverSocket = serverSocket;
            if (!serverSocket.isBound()) {
                serverSocket.bind(null);
            }
            this.tasks = tasks;
        }

        public int getLocalPort()
        {
            return serverSocket.getLocalPort();
        }

        @Override
        public String toString()
        {
            return "ServerTask{" +
                    "serverSocket=" + serverSocket +
                    '}';
        }

        @Override
        public void run()
        {
            while (!serverExecutorService.isShutdown()) {
                try {
                    LOG.debug("ServerTask: accepting... this={}, local.port={}", this, getLocalPort());
                    Socket acceptSocket = serverSocket.accept();
                    LOG.debug("ServerTask: accepted. this={}, local.port={}, remote.port={}", this, getLocalPort(), acceptSocket.getPort());
                    AcceptTask acceptTask = new AcceptTask(serverExecutorService, lastEventTimeStampMilli, eventHandler, acceptSocket);
                    serverExecutorService.execute(acceptTask);
                    tasks.add(acceptTask);
                }
                catch (RejectedExecutionException e) {
                    LOG.debug("ServerTask: ServerSocket.accept() failed[{}]: this={}", e.getMessage(), this);
                }
                catch (ClosedByInterruptException e) {
                    LOG.debug("ServerTask: ServerSocket.accept() failed[{}]: this={}", e.getMessage(), this);
                }
                catch (IOException e) {
                    LOG.warn("ServerTask: ServerSocket.accept() failed[{}]: this={}", e.getMessage(), this);
                }
            }
            try {
                serverSocket.close();
            }
            catch (IOException e) {
                LOG.warn("ServerTask: ServerSocketChannel.close() failed", e);
            }
            LOG.info("ServerTask: Finishing ServerTask...: this={}", this);
        }

        private void close()
                throws IOException
        {
            serverSocket.close();
        }

        private static class AcceptTask
                implements Runnable
        {
            private final Socket acceptSocket;
            private final EventHandler eventHandler;
            private final ExecutorService serverExecutorService;
            private final AtomicLong lastEventTimeStampMilli;

            private AcceptTask(ExecutorService serverExecutorService, AtomicLong lastEventTimeStampMilli, EventHandler eventHandler, Socket acceptSocket)
            {
                this.serverExecutorService = serverExecutorService;
                this.lastEventTimeStampMilli = lastEventTimeStampMilli;
                this.eventHandler = eventHandler;
                this.acceptSocket = acceptSocket;
            }

            private void close()
                    throws IOException
            {
                acceptSocket.close();
            }

            @Override
            public void run()
            {
                LOG.debug("AcceptTask: connected. this={}, local={}, remote={}",
                        this, acceptSocket.getLocalPort(), acceptSocket.getPort());
                try {
                    eventHandler.onConnect(acceptSocket);
                    byte[] byteBuf = new byte[512 * 1024];
                    while (!serverExecutorService.isShutdown()) {
                        try {
                            int len = acceptSocket.getInputStream().read(byteBuf);
                            if (len <= 0) {
                                LOG.debug("AcceptTask: closed. this={}, local={}, remote={}",
                                        this, acceptSocket.getLocalPort(), acceptSocket.getPort());
                                eventHandler.onClose(acceptSocket);
                                try {
                                    acceptSocket.close();
                                }
                                catch (IOException e) {
                                    LOG.warn("AcceptTask: close() failed: this={}", this, e);
                                }
                                break;
                            }
                            else {
                                eventHandler.onReceive(acceptSocket, len, byteBuf);
                                lastEventTimeStampMilli.set(System.currentTimeMillis());
                            }
                        }
                        catch (IOException e) {
                            LOG.warn("AcceptTask: recv() failed: this={}, message={}, cause={}",
                                    this, e.getMessage(), e.getCause() == null ? "" : e.getCause().getMessage());
                            if (e instanceof SSLHandshakeException && e.getCause() instanceof EOFException) {
                                eventHandler.onClose(acceptSocket);
                                break;
                            }
                            if (acceptSocket.isClosed()) {
                                eventHandler.onClose(acceptSocket);
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
                finally {
                    try {
                        LOG.debug("AcceptTask: Finished. Closing... this={}, local={}, remote={}",
                                this, acceptSocket.getLocalPort(), acceptSocket.getPort());
                        acceptSocket.close();
                    }
                    catch (IOException e) {
                        LOG.warn("AcceptTask: close() failed", e);
                    }
                }
            }
        }
    }
}


text:
import { Queue, Scheduler, MultiWorker } from "node-resque";
import { api, log, Initializer } from "../index";

export interface ResqueApi {
  connectionDetails: {
    [key: string]: any;
  };
  queue?: Queue;
  scheduler?: Scheduler;
  multiWorker?: MultiWorker;
  startQueue?: Function;
  stopQueue?: Function;
  startScheduler?: Function;
  stopScheduler?: Function;
  startMultiWorker?: Function;
  stopMultiWorker?: Function;
  workerLogging?: any;
  schedulerLogging?: any;
}

/**
 * The node-resque workers and scheduler which process tasks.
 * see https://github.com/actionhero/node-resque
 */
export class Resque extends Initializer {
  constructor() {
    super();
    this.name = "resque";
    this.loadPriority = 600;
    this.startPriority = 200;
    this.stopPriority = 100;
  }

  async initialize(config) {
    if (config.redis.enabled === false) {
      return;
    }

    const resqueOverrides = config.tasks.resque_overrides;

    api.resque = {
      queue: null,
      multiWorker: null,
      scheduler: null,
      connectionDetails: Object.assign(
        {},
        config.tasks.connectionOptions.tasks,
        {
          redis: api.redis.clients.tasks
        }
      ),

      startQueue: async () => {
        let ActionheroQueue = Queue;
        if (resqueOverrides && resqueOverrides.queue) {
          ActionheroQueue = resqueOverrides.queue;
        }
        api.resque.queue = new ActionheroQueue(
          { connection: api.resque.connectionDetails },
          api.tasks.jobs
        );

        api.resque.queue.on("error", error => {
          log(error, "error", "[api.resque.queue]");
        });

        await api.resque.queue.connect();
      },

      stopQueue: async () => {
        if (api.resque.queue) {
          return api.resque.queue.end();
        }
      },

      startScheduler: async () => {
        let ActionheroScheduler = Scheduler;
        if (resqueOverrides && resqueOverrides.scheduler) {
          ActionheroScheduler = resqueOverrides.scheduler;
        }
        if (config.tasks.scheduler === true) {
          api.resque.schedulerLogging = config.tasks.schedulerLogging;
          api.resque.scheduler = new ActionheroScheduler({
            connection: api.resque.connectionDetails,
            timeout: config.tasks.timeout,
            stuckWorkerTimeout: config.tasks.stuckWorkerTimeout
          });

          api.resque.scheduler.on("error", error => {
            log(error, "error", "[api.resque.scheduler]");
          });

          await api.resque.scheduler.connect();
          api.resque.scheduler.on("start", () => {
            log("resque scheduler started", api.resque.schedulerLogging.start);
          });
          api.resque.scheduler.on("end", () => {
            log("resque scheduler ended", api.resque.schedulerLogging.end);
          });
          api.resque.scheduler.on("poll", () => {
            log("resque scheduler polling", api.resque.schedulerLogging.poll);
          });
          api.resque.scheduler.on("working_timestamp", timestamp => {
            log(
              `resque scheduler working timestamp ${timestamp}`,
              api.resque.schedulerLogging.working_timestamp
            );
          });
          api.resque.scheduler.on("transferred_job", (timestamp, job) => {
            log(
              `resque scheduler enqueuing job ${timestamp}`,
              api.resque.schedulerLogging.transferred_job,
              job
            );
          });
          api.resque.scheduler.on("master", state => {
            log("This node is now the Resque scheduler master", "notice");
          });
          api.resque.scheduler.on(
            "cleanStuckWorker",
            (workerName, errorPayload, delta) => {
              log("cleaned stuck worker", "warning", {
                workerName,
                errorPayload,
                delta
              });
            }
          );

          api.resque.scheduler.start();
        }
      },

      stopScheduler: async () => {
        if (api.resque.scheduler) {
          return api.resque.scheduler.end();
        }
      },

      startMultiWorker: async () => {
        let ActionheroMultiWorker = MultiWorker;
        if (resqueOverrides && resqueOverrides.multiWorker) {
          ActionheroMultiWorker = resqueOverrides.multiWorker;
        }
        api.resque.workerLogging = config.tasks.workerLogging;
        api.resque.schedulerLogging = config.tasks.schedulerLogging;

        api.resque.multiWorker = new ActionheroMultiWorker(
          {
            connection: api.resque.connectionDetails,
            queues: config.tasks.queues,
            timeout: config.tasks.timeout,
            checkTimeout: config.tasks.checkTimeout,
            minTaskProcessors: config.tasks.minTaskProcessors,
            maxTaskProcessors: config.tasks.maxTaskProcessors,
            maxEventLoopDelay: config.tasks.maxEventLoopDelay
          },
          api.tasks.jobs
        );

        // normal worker emitters
        api.resque.multiWorker.on("start", workerId => {
          log("[ worker ] started", api.resque.workerLogging.start, {
            workerId
          });
        });
        api.resque.multiWorker.on("end", workerId => {
          log("[ worker ] ended", api.resque.workerLogging.end, {
            workerId
          });
        });
        api.resque.multiWorker.on(
          "cleaning_worker",
          (workerId, worker, pid) => {
            log(
              `[ worker ] cleaning old worker ${worker}, (${pid})`,
              api.resque.workerLogging.cleaning_worker
            );
          }
        );
        api.resque.multiWorker.on("poll", (workerId, queue) => {
          log(`[ worker ] polling ${queue}`, api.resque.workerLogging.poll, {
            workerId
          });
        });
        api.resque.multiWorker.on("job", (workerId, queue, job) => {
          log(`[ worker ] working job ${queue}`, api.resque.workerLogging.job, {
            workerId,
            class: job.class,
            queue: job.queue
          });
        });
        api.resque.multiWorker.on(
          "reEnqueue",
          (workerId, queue, job, plugin) => {
            log(
              "[ worker ] reEnqueue job",
              api.resque.workerLogging.reEnqueue,
              {
                workerId,
                plugin: plugin,
                class: job.class,
                queue: job.queue
              }
            );
          }
        );
        api.resque.multiWorker.on("pause", workerId => {
          log("[ worker ] paused", api.resque.workerLogging.pause, {
            workerId
          });
        });

        api.resque.multiWorker.on(
          "failure",
          (workerId, queue, job, failure) => {
            api.exceptionHandlers.task(failure, queue, job, workerId);
          }
        );
        api.resque.multiWorker.on("error", (error, workerId, queue, job) => {
          api.exceptionHandlers.task(error, queue, job, workerId);
        });

        api.resque.multiWorker.on("success", (workerId, queue, job, result) => {
          const payload = {
            workerId,
            class: job.class,
            queue: job.queue,
            result
          };

          log(
            "[ worker ] job success",
            api.resque.workerLogging.success,
            payload
          );
        });

        // multiWorker emitters
        api.resque.multiWorker.on("internalError", error => {
          log(error, api.resque.workerLogging.internalError);
        });
        api.resque.multiWorker.on("multiWorkerAction", (verb, delay) => {
          log(
            `[ multiworker ] checked for worker status: ${verb} (event loop delay: ${delay}ms)`,
            api.resque.workerLogging.multiWorkerAction
          );
        });

        if (config.tasks.minTaskProcessors > 0) {
          api.resque.multiWorker.start();
        }
      },

      stopMultiWorker: async () => {
        if (api.resque.multiWorker && config.tasks.minTaskProcessors > 0) {
          return api.resque.multiWorker.stop();
        }
      }
    };
  }

  async start(config) {
    if (config.redis.enabled === false) {
      return;
    }

    if (
      config.tasks.minTaskProcessors === 0 &&
      config.tasks.maxTaskProcessors > 0
    ) {
      config.tasks.minTaskProcessors = 1;
    }

    await api.resque.startQueue();
    await api.resque.startScheduler();
    await api.resque.startMultiWorker();
  }

  async stop(config) {
    if (config.redis.enabled === false) {
      return;
    }

    await api.resque.stopScheduler();
    await api.resque.stopMultiWorker();
    await api.resque.stopQueue();
  }
}


text:
package org.brooth.jeta.apt.processors;

import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.squareup.javapoet.*;
import org.brooth.jeta.apt.MetacodeUtils;
import org.brooth.jeta.apt.ProcessingException;
import org.brooth.jeta.apt.RoundContext;
import org.brooth.jeta.collector.TypeCollector;
import org.brooth.jeta.collector.TypeCollectorMetacode;

import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Oleg Khalidov (brooth@gmail.com)
 */
public class TypeCollectorProcessor extends AbstractProcessor {

    public TypeCollectorProcessor() {
        super(TypeCollector.class);
    }

    public boolean process(TypeSpec.Builder builder, RoundContext context) {
        final Element element = context.elements().iterator().next();
        builder.addSuperinterface(ClassName.get(TypeCollectorMetacode.class));

        TypeName annotationClassTypeName = ParameterizedTypeName.get(ClassName.get(Class.class),
                WildcardTypeName.subtypeOf(Annotation.class));
        ParameterizedTypeName listTypeName = ParameterizedTypeName.get(ClassName.get(List.class),
                ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(TypeName.OBJECT)));

        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getTypeCollection")
                .addAnnotation(Override.class)
                .addModifiers(Modifier.PUBLIC)
                .returns(listTypeName)
                .addParameter(annotationClassTypeName, "annotation");

        List<?> valueList = (List<?>) MetacodeUtils.getAnnotationValue(element, annotationElement, "value");
        if (valueList == null)
            throw new ProcessingException("Failed to process " + element.toString() +
                    ", check its source code for compilation errors");
        for (Object valueStr : valueList) {
            String annotationStr = valueStr.toString().replace(".class", "");
            Set<? extends Element> annotatedElements = context.roundEnv().getElementsAnnotatedWith(
                    processingContext.processingEnv().getElementUtils().getTypeElement(annotationStr));

            annotatedElements = FluentIterable.from(annotatedElements)
                    .transform(new Function<Element, Element>() {
                        public Element apply(Element input) {
                            return MetacodeUtils.typeElementOf(input);
                        }
                    }).toSet();

            methodBuilder
                    .beginControlFlow("if(annotation == $L.class)", annotationStr)
                    .addStatement("$T result = new $T($L)", listTypeName, ParameterizedTypeName.get(
                                    ClassName.get(ArrayList.class), ParameterizedTypeName.get(ClassName.get(Class.class),
                                            WildcardTypeName.subtypeOf(TypeName.OBJECT))),
                            annotatedElements.size());

            for (Element annotatedElement : annotatedElements) {
                methodBuilder.addStatement("result.add($L.class)", annotatedElement.toString());
            }

            methodBuilder
                    .addStatement("return result")
                    .endControlFlow();
        }

        methodBuilder.addStatement("return null");
        builder.addMethod(methodBuilder.build());
        return false;
    }

    @Override
    public boolean ignoreUpToDate() {
        return true;
    }
}