text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ttp="http://stix.mitre.org/TTP-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/TTP-1 http://stix.mitre.org/XMLSchema/ttp/1.1.1/ttp.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-68b73148-2f27-45f2-82ea-135943f81fc7" version="1.1.1" timestamp="2013-10-15T15:29:00+00:00">
    <stix:TTPs>
        <stix:TTP id="example:ttp-55325307-e823-41f6-83bd-8554b60ffe80" timestamp="2014-12-22T16:35:44.357000+00:00" xsi:type='ttp:TTPType'>
            <ttp:Behavior>
                <ttp:Attack_Patterns>
                    <ttp:Attack_Pattern>
                        <ttp:Title>Unknown</ttp:Title>
                    </ttp:Attack_Pattern>
                </ttp:Attack_Patterns>
            </ttp:Behavior>
        </stix:TTP>
    </stix:TTPs>
    <stix:Incidents>
        <stix:Incident id="example:incident-015f6510-0510-4725-bc6e-5a5a4e9ed10e" timestamp="2014-04-27T19:37:03+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>Bolivian tourist site was compromised and a fraudulent secret shopper site was installed.</incident:Title>
            <incident:External_ID source="VERIS">E892301C-70B1-4264-9232-1C3BDA59B492</incident:External_ID>
            <incident:Time>
                <incident:Initial_Compromise precision="year">2013-01-01T00:00:00</incident:Initial_Compromise>
            </incident:Time>
            <incident:Reporter>
                <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                    <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">Spitler</xnl:NameLine>
  </xpil:PartyName>
</ExtSch:Specification>
                </stixCommon:Identity>
            </incident:Reporter>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">Amaru Bolivia</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>BO</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Web application</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property>
                        </incident:Property_Affected>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Integrity</incident:Property>
                            <incident:Description_Of_Effect>Modify data; Notes:added fraudulent /WMart directory that housed the scam site.</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Impact_Assessment>
                <incident:Impact_Qualification xsi:type="stixVocabs:ImpactQualificationVocab-1.0">Unknown</incident:Impact_Qualification>
            </incident:Impact_Assessment>
            <incident:Leveraged_TTPs>
                <incident:Leveraged_TTP>
                    <stixCommon:TTP idref="example:ttp-55325307-e823-41f6-83bd-8554b60ffe80" xsi:type='ttp:TTPType'/>
                </incident:Leveraged_TTP>
            </incident:Leveraged_TTPs>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-2f87a010-ce50-4bf2-9142-83fcb934f537" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Unknown</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3.0</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://news.softpedia.com/news/Hacked-Bolivian-Tourism-Site-Used-for-Secret-Shopper-Scam-389754.shtml</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-2f87a010-ce50-4bf2-9142-83fcb934f537" timestamp="2014-12-22T16:35:44.357000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>Unknown</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </ta:Identity>
            <ta:Type timestamp="2014-12-22T16:35:44.357000+00:00">
                <stixCommon:Value>Unknown</stixCommon:Value>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:35:44.357000+00:00">
                <stixCommon:Value>Unknown</stixCommon:Value>
            </ta:Motivation>
            <ta:Observed_TTPs>
                <ta:Observed_TTP>
                    <stixCommon:TTP idref="example:ttp-55325307-e823-41f6-83bd-8554b60ffe80" xsi:type='ttp:TTPType'/>
                </ta:Observed_TTP>
            </ta:Observed_TTPs>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
package org.takes.facets.fork;

import java.io.IOException;
import java.util.Locale;
import lombok.EqualsAndHashCode;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.misc.Opt;
import org.takes.rq.RqHeaders;

/**
 * Fork by host name.
 *
 *
Use this class in combination with {@link TkFork},
 * for example:
 *
 *
 Take take = new TkFork(
 *   new FkHost("www.example.com", new TkText("home")),
 *   new FkHost("doc.example.com", new TkText("doc is here"))
 * );

 *
 *
The class is immutable and thread-safe.
 *
 * @author Yegor Bugayenko (yegor@teamed.io)
 * @version $Id$
 * @see TkFork
 * @since 0.32
 */
@EqualsAndHashCode(callSuper = true)
public final class FkHost extends FkWrap {

    /**
     * Ctor.
     * @param host Host
     * @param take Take to use
     */
    public FkHost(final String host, final Take take) {
        super(FkHost.fork(host, take));
    }

    /**
     * Make fork.
     * @param host Host
     * @param take Take to use
     * @return Fork
     */
    private static Fork fork(final String host, final Take take) {
        return new Fork() {
            @Override
            public Opt<Response> route(final Request req) throws IOException {
                final String hst = new RqHeaders.Smart(
                    new RqHeaders.Base(req)
                ).single("host");
                final Opt<Response> rsp;
                if (host.toLowerCase(Locale.ENGLISH)
                    .equals(hst.toLowerCase(Locale.ENGLISH))) {
                    rsp = new Opt.Single<>(take.act(req));
                } else {
                    rsp = new Opt.Empty<>();
                }
                return rsp;
            }
        };
    }

}

redpajama_set_name: RedPajamaGithub


text:
/* tslint:disable */

import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ArtistRow_artist = {
    readonly name: string | null;
    readonly href: string | null;
    readonly artworks: {
        readonly " $fragmentRefs": FragmentRefs<"Fillwidth_artworks">;
    } | null;
    readonly " $fragmentRefs": FragmentRefs<"Follow_artist">;
    readonly " $refType": "ArtistRow_artist";
};
export type ArtistRow_artist$data = ArtistRow_artist;
export type ArtistRow_artist$key = {
    readonly " $data"?: ArtistRow_artist$data;
    readonly " $fragmentRefs": FragmentRefs<"ArtistRow_artist">;
};

const node: ReaderFragment = {
  "kind": "Fragment",
  "name": "ArtistRow_artist",
  "type": "Artist",
  "metadata": null,
  "argumentDefinitions": [],
  "selections": [
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "name",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "href",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "LinkedField",
      "alias": "artworks",
      "name": "artworksConnection",
      "storageKey": "artworksConnection(first:6)",
      "args": [
        {
          "kind": "Literal",
          "name": "first",
          "value": 6
        }
      ],
      "concreteType": "ArtworkConnection",
      "plural": false,
      "selections": [
        {
          "kind": "FragmentSpread",
          "name": "Fillwidth_artworks",
          "args": null
        }
      ]
    },
    {
      "kind": "FragmentSpread",
      "name": "Follow_artist",
      "args": null
    }
  ]
};
(node as any).hash = '165cde0cf105756da9745ed008809922';
export default node;


text:
module Sidekiq
  def self.hook_rails!
    if defined?(::ActiveRecord)
      ::ActiveRecord::Base.send(:include, Sidekiq::Extensions::ActiveRecord)
    end

    if defined?(::ActionMailer)
      ::ActionMailer::Base.extend(Sidekiq::Extensions::ActionMailer)
    end
  end

  class Rails < ::Rails::Engine
    config.autoload_paths << File.expand_path("#{config.root}/app/workers") if File.exist?("#{config.root}/app/workers")

    initializer 'sidekiq' do
      Sidekiq.hook_rails!
    end
  end if defined?(::Rails)
end


text:
require 'remote_server'

BLATMODE = ARGV.delete('--blat')
BASIC_BOOTSTRAP_MODE = ARGV.delete('--no-remote-run')

if ARGV.length < 2
  puts "usage is:"
  puts "bootstrap.rb <hostname> <password> [<username> [<server> [<mirror-url>]]] [--blat]"
  exit 1
end

options = {
  :hostname => ARGV[0],
  :password => ARGV[1],
  :username => ARGV[2],
  :server => ARGV[3],
  :mirror => (ARGV[4])
}

server = ServerList.read(options[:hostname])[options[:hostname]] || {}

options[:mirror] ||= server['mirror']
options[:server] ||= (server['server'] || options[:hostname])

RemoteServer.set_root_password(options[:server], options[:username], options[:password]) if options[:username] && options[:username] != 'root' && !BLATMODE

RemoteServer.connect(options[:server], 'root', options[:password]) do
  install_runtime_environment(options[:mirror] || 'http://mirror.internode.on.net/pub/ubuntu/ubuntu/') unless BLATMODE
  send_tarball

  unless BASIC_BOOTSTRAP_MODE
    run_bootstrap(options[:hostname])
    run_roles
  end
end


text:
require 'sinatra/base'
require 'webrick'
require 'webrick/https'
require 'openssl'

name = "/C=US/ST=SomeState/L=SomeCity/O=Organization/OU=Unit/CN=localhost"
ca  = OpenSSL::X509::Name.parse( name )
key = OpenSSL::PKey::RSA.new( 1024 )
crt = OpenSSL::X509::Certificate.new

crt.version = 2
crt.serial  = 1
crt.subject = ca
crt.issuer  = ca
crt.public_key = key.public_key
crt.not_before = Time.now
crt.not_after  = Time.now + 1 * 365 * 24 * 60 * 60 # 1 year

options = {
    Port:            ARGV.first.gsub( /\D/, '' ).to_i,
    SSLEnable:       true,
    SSLVerifyClient: OpenSSL::SSL::VERIFY_NONE,
    SSLCertificate:  crt,
    SSLPrivateKey:   key,
    SSLCertName:     [["CN", WEBrick::Utils::getservername]],
}

class MixedResourceHTTPSServer < Sinatra::Base

    get '/' do
        <<-EOHTML
            Vuln script
            OK script
            Relative script

            Vuln link
            OK link
            Relative link
        EOHTML
    end

    get '/vuln_script' do
        <<-EOHTML

        EOHTML
    end

    get '/ok_script' do
        <<-EOHTML

        EOHTML
    end

    get '/relative_script' do
        <<-EOHTML

        EOHTML
    end

    get '/vuln_link' do
        <<-EOHTML
            <link rel="stylesheet" type="text/css" href="http://localhost/theme.css" />
        EOHTML
    end

    get '/ok_script' do
        <<-EOHTML
            <link rel="stylesheet" type="text/css" href="https://localhost/secure_theme.css" />
        EOHTML
    end

    get '/relative_link' do
        <<-EOHTML
            <link rel="stylesheet" type="text/css" href="stuff/secure_theme.css" />
        EOHTML
    end

end

server = ::Rack::Handler::WEBrick
trap( :INT ) { server.shutdown }

server.run( MixedResourceHTTPSServer, options )


text:
graphite_reporter::graphite_reporter(std::string hostA, int portA) {
    connectorM = new graphite_connector(hostA, portA);
}

void graphite_reporter::connect(void) {
    connectorM->connect();
}

void graphite_reporter::disconnect(void) {
    connectorM->disconnect();
}

std::string graphite_reporter::sanitizeString(std::string stringA) {
    std::replace(stringA.begin(), stringA.end(), ' ', '-');
    return stringA;
}

template <class T>
void graphite_reporter::send(std::string metricA, T valueA) {
    std::string metric = sanitizeString(metricA);
    auto seconds =
            std::chrono::system_clock::now().time_since_epoch() /
                    std::chrono::seconds(1);
    std::stringstream ss;
    ss << metric << " " << valueA << " " << seconds << "\n" << std::endl;
    std::string message = ss.str();
    connectorM->write(message);
}


text:
package com.srcdevbin.buildbot.operations;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;

public enum OperatingPool {
	CORE(10);

	private PausableThreadPoolExecutor executor;
	private PausableMonitorThread monitorThread;
	private int nThreads = 0;
	private static final int DEFAULT_MAX_POOL_SIZE = 10;
	private static final int CORE_POOL_SIZE = 2;
	private static final int QUEUE_SIZE = 10;
	private static final int KEEP_ALIVE_TIME = 10;

	private OperatingPool(int poolSize){
		if(poolSize < 0){
			nThreads = DEFAULT_MAX_POOL_SIZE;
		} else {
			nThreads = poolSize;
		}
	}

	public int getMaxPoolSize(){
		return executor.getMaximumPoolSize();
	}

	public synchronized PoolStatus getStatus(){
		synchronized(monitorThread){
			monitorThread.notify();
		}
		PoolStatus status = monitorThread.getStatus();
		return status;
	}

	public void restart(){
		stop();
		start(nThreads);
	}

	public synchronized PoolStatus stop(){
		List<Runnable> pendingTasks = shutdownExecutor();
		PoolStatus status = shutdownMonitor();
		status.setPendingTasks(pendingTasks);
		return status;
	}

	public synchronized PoolStatus start(){
		return start(DEFAULT_MAX_POOL_SIZE);
	}

	public PoolStatus start(int poolSize){
		executor = new PausableThreadPoolExecutor(CORE_POOL_SIZE, poolSize, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE));
		executor.prestartAllCoreThreads();

		// This object is shared between 2 threads
		// Synchronization is critical when accessing this object
		monitorThread = createAndStartMonitor(executor);

		return getStatus();
	}

	public void pause(){
		executor.pause();
	}

	public void resume(){
		executor.resume();
	}

	public synchronized void execute(Runnable work) throws RejectedExecutionException{
		executor.execute(work);
	}

	public synchronized List<Future<OperationResult>> invokeAll(Collection<Callable<OperationResult>> tasks) throws InterruptedException{
		return executor.invokeAll(tasks);
	}

	public synchronized OperationResult invokeAny(Collection<Callable<OperationResult>> tasks) throws InterruptedException, ExecutionException{
		return executor.invokeAny(tasks);
	}

	private List<Runnable> shutdownExecutor(){
		List<Runnable> pendingTasks = new ArrayList<Runnable>();
		if(executor != null){
			if(!executor.isShutdown()){
				pendingTasks.addAll(executor.shutdownNow());
			};
		}
		return pendingTasks;
	}

	private PoolStatus shutdownMonitor(){
		PoolStatus status;
		synchronized(monitorThread){
			monitorThread.notify();
			monitorThread.shutdown();
			status = monitorThread.getStatus();
		}
		return status;
	}

	private PausableMonitorThread createAndStartMonitor(PausableThreadPoolExecutor executor){
		PausableMonitorThread monitor = new PausableMonitorThread(executor);
		Thread monThread = new Thread(monitor);
		monThread.setName(String.format("BuildBot-OperatingPool-Monitor-%s", this));
		monThread.start();
		return monitor;
	}

}


text:
require "bundler/setup"
Bundler.setup
require "simplecov"
require "activerecord/oracle/queue"

RSpec.configure do |config|
  # some (optional) config here
end


text:
.overrides-view fieldset {
    border: none;
    padding: 0 0 5px 15px;
}

.overrides-view fieldset p {
    display: inline-block;
    padding: 0;
    margin: 0;
    border: 0;
}

.overrides-view fieldset p label {
    display: inline-block;
}

.overrides-view .field-error-message {
    display: none;
}

.overrides-view input[type='text']:focus::-webkit-input-placeholder {
    color: transparent !important;
}

/* Network tab */

.overrides-network fieldset {
    padding-top: 5px;
}

.overrides-network fieldset p {
    width: 100%;
    margin-left: 2px;
}

.overrides-network fieldset select {
    margin: 5px 0;
}

.overrides-network fieldset p label {
    cursor: default;
    margin-right: 5px;
}

.overrides-network fieldset input[type='text'] {
    display: block;
    width: 100%;
    max-width: 400px;
    min-width: 176px;
    margin: 5px 0;
}

/* Device tab */

.overrides-device {
    width: 100%;
}

.overrides-device input.numeric {
    text-align: right;
}

.overrides-device input[type=range] {
    width: 100%;
}

.overrides-device > label {
    display: block;
    margin-bottom: 7px;
    white-space: nowrap;
}

.overrides-device button {
    margin: 0 3px;
}

.overrides-device label {
    margin-bottom: 10px;
}

.overrides-device table {
    margin-bottom: 5px;
    white-space: nowrap !important;
}

.overrides-device > label {
    margin-bottom: 4px;
}

.overrides-device .help-footnote {
    border-top: 1px solid #EEEEEE;
    margin: 0;
    padding: 12px;
}

.overrides-view label {
    display: flex;
    height: auto;
}

.overrides-view fieldset[disabled] * {
    cursor: default !important;
}

.overrides-device .overrides-device-model-section {
    margin-bottom: 15px;
    white-space: nowrap;
}

.overrides-device .overrides-device-model-section > span {
    padding: 0 10px 0 3px;
}

.overrides-device .overrides-device-model-section select {
    width: 244px;
    height: 20px;
}

.custom-device-title-dialog {
    padding: 10px;
}

/* Media tab */

.overrides-media > label {
    margin-bottom: 4px;
}

/* Sensors tab */

.overrides-sensors > label {
    margin-bottom: 10px;
}

.overrides-device, .overrides-media, .overrides-network, .overrides-sensors {
    flex: none !important;
}

.overrides-sensors input {
    text-align: right;
}

.tabbed-pane-header-tab.overrides-activate {
    opacity: 0.8;
}

.tabbed-pane-header-tab.overrides-activate .tabbed-pane-header-tab-title::after {
    padding-left: 3px;
    content: "\2713";
    color: rgb(25, 100, 228);
}

.tabbed-pane-header-tab.overrides-activate.selected {
    opacity: 1;
}

.overrides-view input[type=text]:enabled:focus,
.overrides-view select:enabled:focus {
    -webkit-transition: border-color 200ms;
    border-color: rgb(77, 144, 254);
    outline: none;
}

.overrides-view input[type=text],
.overrides-view select {
    border: 1px solid #bfbfbf;
    border-radius: 2px;
    box-sizing: border-box;
    color: #444;
    font: inherit;
    border-width: 1px;
}

.overrides-view input[type=text] {
    margin: 0;
    min-height: 2em;
    padding: 3px;
}

.overrides-view input[readonly] {
    background-color: rgb(235, 235, 228);
}

.overrides-view .overrides-footer {
    flex: none;
    padding: 0 0 1px 3px;
    border-top: 1px solid rgb(203,203,203);
    background-color: #eee;
}

.overrides-view .overrides-footer::before {
    background-image: url(Images/statusbarButtonGlyphs.png);
    background-size: 320px 144px;
    width: 10px;
    height: 10px;
    content: "";
    position: relative;
    top: 2px;
    background-position: -202px -107px;
    float: left;
    margin-right: 4px;
}

@media (-webkit-min-device-pixel-ratio: 1.5) {
.overrides-view .overrides-footer::before {
    background-image: url(Images/statusbarButtonGlyphs_2x.png);
}
} /* media */

.overrides-view .overrides-footer .warning-icon-small {
    margin-right: 3px;
}

.overrides-splash-screen {
    padding: 10px 10px;
    flex: auto;
}

.overrides-splash-screen .status-bar {
    height: 16px;
    display: inline-block;
    margin-left: -4px;
    position: relative;
    top: -3px;
}

#overrides-reset-button,
#overrides-disable-button {
    margin: 9px 0 0 17px;
    display: block;
    width: 60px;
}

.overrides-enable-button {
    margin: 4px !important;
}


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using System;
using ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class MagickImageTests
    {
        public class TheFloodFillMethod
        {
            [Fact]
            public void ShouldThrowExceptionWhenColorIsNull()
            {
                Assert.Throws<ArgumentNullException>("color", () =>
                {
                    using (var image = new MagickImage(MagickColors.White, 2, 2))
                    {
                        image.FloodFill((MagickColor)null, 0, 0);
                    }
                });
            }

            [Fact]
            public void ShouldThrowExceptionWhenTargetColorIsNull()
            {
                Assert.Throws<ArgumentNullException>("target", () =>
                {
                    using (var image = new MagickImage(MagickColors.White, 2, 2))
                    {
                        image.FloodFill(MagickColors.Purple, 0, 0, null);
                    }
                });
            }

            [Fact]
            public void ShouldChangeTheColors()
            {
                using (var image = new MagickImage(MagickColors.White, 2, 2))
                {
                    image.FloodFill(MagickColors.Red, 0, 0);

                    ColorAssert.Equal(MagickColors.Red, image, 0, 0);
                    ColorAssert.Equal(MagickColors.Red, image, 0, 1);
                    ColorAssert.Equal(MagickColors.Red, image, 1, 0);
                    ColorAssert.Equal(MagickColors.Red, image, 1, 1);
                }
            }

            [Fact]
            public void ShouldChangeTheTargetColors()
            {
                using (var image = new MagickImage(MagickColors.White, 2, 2))
                {
                    using (var green = new MagickImage(MagickColors.Green, 1, 1))
                    {
                        image.Composite(green, 0, 0, CompositeOperator.Over);
                    }

                    image.FloodFill(MagickColors.Red, 0, 0, MagickColors.Green);

                    ColorAssert.Equal(MagickColors.Red, image, 0, 0);
                    ColorAssert.Equal(MagickColors.White, image, 0, 1);
                    ColorAssert.Equal(MagickColors.White, image, 1, 0);
                    ColorAssert.Equal(MagickColors.White, image, 1, 1);
                }
            }

            [Fact]
            public void ShouldChangeTheNeighboursWithTargetColor()
            {
                using (var image = new MagickImage(MagickColors.White, 2, 2))
                {
                    using (var green = new MagickImage(MagickColors.Green, 1, 1))
                    {
                        image.Composite(green, 0, 1, CompositeOperator.Over);
                    }

                    image.FloodFill(MagickColors.Red, 0, 0, MagickColors.Green);

                    ColorAssert.Equal(MagickColors.White, image, 0, 0);
                    ColorAssert.Equal(MagickColors.Red, image, 0, 1);
                    ColorAssert.Equal(MagickColors.White, image, 1, 0);
                    ColorAssert.Equal(MagickColors.White, image, 1, 1);
                }
            }

            [Fact]
            public void ShouldNotChangeTheTargetColors()
            {
                using (var image = new MagickImage(MagickColors.White, 2, 2))
                {
                    using (var green = new MagickImage(MagickColors.Green, 1, 1))
                    {
                        image.Composite(green, 1, 1, CompositeOperator.Over);
                    }

                    image.FloodFill(MagickColors.Red, 0, 0, MagickColors.Green);

                    ColorAssert.Equal(MagickColors.White, image, 0, 0);
                    ColorAssert.Equal(MagickColors.White, image, 0, 1);
                    ColorAssert.Equal(MagickColors.White, image, 1, 0);
                    ColorAssert.Equal(MagickColors.Green, image, 1, 1);
                }
            }

            [Fact]
            public void ShouldChangeTheColorsWithTheSameTransparency()
            {
                using (var image = new MagickImage(MagickColors.White, 2, 2))
                {
                    image.HasAlpha = true;

                    using (var pixels = image.GetPixelsUnsafe())
                    {
                        var pixel = pixels.GetPixel(1, 1);
                        pixel.SetChannel(3, 0);

                        pixels.SetPixel(pixel);
                    }

                    image.Settings.FillColor = MagickColors.Purple;
                    image.FloodFill(0, 0, 0);

                    ColorAssert.Equal(MagickColors.White, image, 0, 0);
                    ColorAssert.Equal(MagickColors.White, image, 0, 1);
                    ColorAssert.Equal(MagickColors.White, image, 1, 0);
                    ColorAssert.Equal(new MagickColor("#ffffff00"), image, 1, 1);
                }
            }
        }
    }
}


text:
package org.jbpm.services.task.impl.model.xml;

import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

import org.jbpm.services.task.impl.model.xml.InternalJaxbWrapper.GetterUser;
import org.kie.api.task.model.Attachment;
import org.kie.api.task.model.User;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

@XmlType(name="attachment")
@XmlAccessorType(XmlAccessType.FIELD)
@JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE, setterVisibility=JsonAutoDetect.Visibility.NONE, fieldVisibility=JsonAutoDetect.Visibility.ANY)
public class JaxbAttachment extends AbstractJaxbTaskObject<Attachment> implements Attachment {

    @XmlElement
    @XmlSchemaType(name = "long")
    private Long id;

    @XmlElement
    @XmlSchemaType(name = "string")
    private String name;

    @XmlElement
    @XmlSchemaType(name = "string")
    private String contentType;

    @XmlElement
    @XmlSchemaType(name = "dateTime")
    private Date attachedAt;

    @XmlElement(name="attached-by")
    @XmlSchemaType(name = "string")
    private String attachedBy;

    @XmlElement
    @XmlSchemaType(name = "int")
    private Integer size;

    @XmlElement(name="attachment-content-id")
    @XmlSchemaType(name = "long")
    private Long attachmentContentId;

    public JaxbAttachment() {
        super(Attachment.class);
    }

    public JaxbAttachment(Attachment attachment) {
        super(attachment, Attachment.class);
        User attacher = attachment.getAttachedBy();
        if( attacher != null ) {
            this.attachedBy = attacher.getId();
        }
    }

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public Date getAttachedAt() {
        return attachedAt;
    }

    @Override
    public User getAttachedBy() {
        return new GetterUser(this.attachedBy);
    }

    public String getAttachedById() {
        return this.attachedBy;
    }

    @Override
    public int getSize() {
        return whenNull(size, -1);
    }

    @Override
    public long getAttachmentContentId() {
        return whenNull(attachmentContentId, -1l);
    }

}


text:
package za.org.grassroot.services.integration;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.annotation.Transactional;
import za.org.grassroot.core.GrassrootApplicationProfiles;
import za.org.grassroot.core.domain.*;
import za.org.grassroot.core.enums.AccountType;
import za.org.grassroot.core.repository.RoleRepository;
import za.org.grassroot.core.repository.UserRepository;
import za.org.grassroot.services.AccountBroker;
import za.org.grassroot.services.GroupBroker;
import za.org.grassroot.services.UserManagementService;
import za.org.grassroot.services.exception.GroupAlreadyPaidForException;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import static org.junit.Assert.*;
import static za.org.grassroot.services.enums.GroupPermissionTemplate.DEFAULT_GROUP;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestContextConfig.class)
@ActiveProfiles(GrassrootApplicationProfiles.INMEMORY)
@Transactional
@WithMockUser(username = "0605550000", roles={"SYSTEM_ADMIN"})
public class AccountBrokerTest {

    private static final Logger log = LoggerFactory.getLogger(AccountBrokerTest.class);

    @Autowired
    private AccountBroker accountBroker;

    @Autowired
    private UserManagementService userManagementService;

    @Autowired
    private GroupBroker groupBroker;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRepository userRepository;

    private final String accountName = "testAccount";
    private final String billingEmail = "billingemail@cso.org";
    private final String groupName = "testGroup";
    private final String userNumber = "0605550000";
    private final String accountAdminNumber = "0605550011";

    private User testUser;
    private User testAdmin;
    private Group testGroup;

    @Before
    public void setUp() {
        testUser = userManagementService.loadOrCreateUser(userNumber);
        testAdmin = userManagementService.loadOrCreateUser(accountAdminNumber);
        testGroup = groupBroker.create(testUser.getUid(), groupName, null, new HashSet<>(), DEFAULT_GROUP, null, null, false);

        Role systemAdmin = new Role(BaseRoles.ROLE_SYSTEM_ADMIN, null);
        log.info("systemAdmin role: " + systemAdmin.describe());
        testUser.addStandardRole(systemAdmin);
        roleRepository.save(systemAdmin);
        userRepository.save(testUser);

        Role accountAdmin = new Role(BaseRoles.ROLE_ACCOUNT_ADMIN, null);
        roleRepository.save(accountAdmin);

        setAccountFields();
    }

    // this is cumbersome, but test isn't picking up the rest of the properties, or running init, so ...
    private void setAccountFields() {
        Map<AccountType, Boolean> messagesEnabled = new HashMap<>();
        messagesEnabled.put(AccountType.STANDARD, true);
        Map<AccountType, Integer> messagesCost = new HashMap<>();
        messagesCost.put(AccountType.STANDARD, 30);
        Map<AccountType, Integer> maxGroupSize = new HashMap<>();
        maxGroupSize.put(AccountType.STANDARD, 300);
        Map<AccountType, Integer> maxGroupNumber = new HashMap<>();
        maxGroupNumber.put(AccountType.STANDARD, 20);
        Map<AccountType, Integer> maxSubGroupDepth = new HashMap<>();
        maxSubGroupDepth.put(AccountType.STANDARD, 3);

        ReflectionTestUtils.setField(accountBroker, "messagesEnabled", messagesEnabled);
        ReflectionTestUtils.setField(accountBroker, "messagesCost", messagesCost);
        ReflectionTestUtils.setField(accountBroker, "maxGroupSize", maxGroupSize);
        ReflectionTestUtils.setField(accountBroker, "maxGroupNumber", maxGroupNumber);
        ReflectionTestUtils.setField(accountBroker, "maxSubGroupDepth", maxSubGroupDepth);
    }

    private Account createTestAccount(String billingEmail) {
        String accountUid = accountBroker.createAccount(testUser.getUid(), accountName, testAdmin.getUid(), billingEmail, AccountType.STANDARD);
        Account account = accountBroker.loadAccount(accountUid);
        return account;
    }

    @Test
    public void shouldSaveBilling() {
        String accountUid = accountBroker.createAccount(testUser.getUid(), accountName, testAdmin.getUid(), billingEmail, AccountType.STANDARD);
        Account account = accountBroker.loadAccount(accountUid);
        assertNotEquals(null,account.getId());
        assertEquals(billingEmail, account.getPrimaryEmail());
    }

    @Test
    public void shouldCreateWithAdmin() {

        Account account = createTestAccount(null);
        assertNotEquals(null, account.getId());
        assertNotNull(account.getAdministrators());
        assertEquals(1, account.getAdministrators().size());
        assertEquals(testAdmin.getId(), account.getAdministrators().iterator().next().getId());
        assertEquals(testAdmin.getAccountAdministered().getId(), account.getId());
        // note : role checking fails, appears to be for persistence reasons
    }

    @Test
    public void shouldCreateDetailedAccount() {
        Account account = createTestAccount(billingEmail);
        testUser = userManagementService.loadOrCreateUser(userNumber); // this makes full-object equal assertions fail, but without it, role tests fail
        assertNotEquals(null, account.getId());
        assertEquals(billingEmail, account.getPrimaryEmail());
        assertTrue(account.isEnabled());
        assertEquals(testAdmin.getId(), account.getAdministrators().iterator().next().getId()); // note: equals on User as whole fails for persistence reasons
        assertEquals(testAdmin.getAccountAdministered().getId(), account.getId()); // note: as above, full equals fails ... possibly within-test persistence issues
        // assertTrue(testUser.getStandardRoles().contains(roleRepository.findOneByNameAndRoleType(accountAdminRole, Role.RoleType.STANDARD))); // as above
    }

    @Test
    public void shouldAddAdmin() {
        Account account = createTestAccount(null);
        User admin2 = userManagementService.loadOrCreateUser("0605550022");
        assertEquals(account.getAdministrators().size(), 1);
        accountBroker.addAdministrator(testUser.getUid(), account.getUid(), admin2.getUid());
        assertEquals(account.getAdministrators().size(), 2);
        assertTrue(account.getAdministrators().contains(testAdmin));
        assertTrue(account.getAdministrators().contains(admin2));
        assertEquals(account, testAdmin.getAccountAdministered());
        assertEquals(account, admin2.getAccountAdministered());
        // assertTrue(testUser.getStandardRoles().contains(roleRepository.findOneByNameAndRoleType(accountAdminRole, Role.RoleType.STANDARD)));
    }

    @Test
    public void shouldRemoveAdmin() {
        Account account = createTestAccount(null);
        assertEquals(account.getAdministrators().size(), 1);
        // assertTrue(testUser.getStandardRoles().contains(roleRepository.findOneByNameAndRoleType(accountAdminRole, Role.RoleType.STANDARD)));
        // accountBroker.removeAdministrator(account, testUser); // note: need to fix this */
    }

    @Test
    public void shouldAddGroupToAccount() {
        // todo: add tests to check it fails if not done by admin
        // todo: add lots more asserts, to make sure group added is the actual group
        Account account = createTestAccount(null);
        accountBroker.addGroupToAccount(account.getUid(), testGroup.getUid(), testAdmin.getUid());
        assertTrue(testGroup.isPaidFor());
        assertNotNull(accountBroker.findAccountForGroup(testGroup.getUid()));
        assertEquals(accountBroker.findAccountForGroup(testGroup.getUid()).getId(), account.getId());
    }

    @Test
    public void shouldRemoveGroupFromAccount() {
        // todo: work out why the removeGroupFromAccount method is causing optimistic locking fail
        /*User testUser2 = userManagementService.loadOrCreateUser("0813074085");
        Group testGroup2 = groupManagementService.createNewGroup(testUser2, "lesetse");
        Account account2 = accountBroker.createAccount("some other name");
        accountBroker.addGroupToAccount(account2, testGroup2, testUser2);
        testGroup2 = accountBroker.removeGroupFromAccount(account2, testGroup2, testUser2);
        assertFalse(testGroup2.isPaidFor());*/
    }

    @Test(expected = GroupAlreadyPaidForException.class)
    public void shouldNotAllowDuplicatePaidGroups() {
        // todo: change this to try/catch, to handle it better
        Account account = createTestAccount(null);
        String account2Uid = accountBroker.createAccount(testUser.getUid(), accountName + "2", testAdmin.getUid(), null, AccountType.STANDARD);
        accountBroker.addGroupToAccount(account.getUid(), testGroup.getUid(), testAdmin.getUid());
        accountBroker.addGroupToAccount(account2Uid, testGroup.getUid(), testAdmin.getUid());
    }

}


text:
package nutchat.view.swinggui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.TitledBorder;

import nutchat.model.IMessage;
import nutchat.model.IUser;
import nutchat.model.MessageDispatcher;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * Represents single-user chat panel with chat history and a new message field.
 *
 * @author Amadeusz Sadowski 2014
 *
 */
public class ChatPanel extends JPanel
{
    private static final long serialVersionUID = 1L;
    private final DefaultListModel<IMessage> listModel;
    private final IUser chatPartner;
    private final MessageDispatcher dispatcher;

    /**
     * Create the panel.
     */
    public ChatPanel(final IUser chatPartner, List<IMessage> chat,
                    final MessageDispatcher dispatcher)
    {
        this.chatPartner = chatPartner;
        this.dispatcher = dispatcher;

        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWidths = new int[] { 0 };
        gridBagLayout.rowHeights = new int[] { 0 };
        gridBagLayout.columnWeights = new double[] { 1.0 };
        gridBagLayout.rowWeights = new double[] { 1.0 };
        setLayout(gridBagLayout);

        JSplitPane splitPane = new JSplitPane();
        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
        GridBagConstraints gbc_splitPane = new GridBagConstraints();
        gbc_splitPane.insets = new Insets(0, 0, 5, 0);
        gbc_splitPane.fill = GridBagConstraints.BOTH;
        gbc_splitPane.gridx = 0;
        gbc_splitPane.gridy = 0;
        add(splitPane, gbc_splitPane);

        JPanel newMessagePanel = new JPanel();
        newMessagePanel.setBorder(new TitledBorder(null, "Enter message:", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        splitPane.setRightComponent(newMessagePanel);
        GridBagLayout gbl_newMessagePanel = new GridBagLayout();
        gbl_newMessagePanel.columnWidths = new int[] { 1, 0 };
        gbl_newMessagePanel.rowHeights = new int[] { 1, 0, 0 };
        gbl_newMessagePanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
        gbl_newMessagePanel.rowWeights = new double[] { 1.0, 0.0, Double.MIN_VALUE };
        newMessagePanel.setLayout(gbl_newMessagePanel);

        final JTextArea newMessageTextArea = new JTextArea();
        newMessageTextArea.addKeyListener(new KeyAdapter()
            {
                @Override
                public void keyPressed(KeyEvent arg0)
                {
                    if (arg0.isShiftDown() && arg0.getKeyCode() == KeyEvent.VK_ENTER)
                    {
                        newMessageTextArea.append("\n");
                        arg0.consume();
                    }
                    else if (arg0.getKeyCode() == KeyEvent.VK_ENTER)
                    {
                        ChatPanel.this.dispatcher.sendMessage(ChatPanel.this.chatPartner,
                                        newMessageTextArea.getText());
                        newMessageTextArea.setText("");
                        arg0.consume();
                    }
                }
            });
        newMessageTextArea.setTabSize(4);
        GridBagConstraints gbc_newMessageTextArea = new GridBagConstraints();
        gbc_newMessageTextArea.insets = new Insets(5, 5, 0, 5);
        gbc_newMessageTextArea.fill = GridBagConstraints.BOTH;
        gbc_newMessageTextArea.gridx = 0;
        gbc_newMessageTextArea.gridy = 0;
        newMessagePanel.add(newMessageTextArea, gbc_newMessageTextArea);

        JLabel sendHintLabel = new JLabel("Press Enter to send");
        GridBagConstraints gbc_sendHintLabel = new GridBagConstraints();
        gbc_sendHintLabel.insets = new Insets(5, 5, 5, 5);
        gbc_sendHintLabel.anchor = GridBagConstraints.EAST;
        gbc_sendHintLabel.gridx = 0;
        gbc_sendHintLabel.gridy = 1;
        newMessagePanel.add(sendHintLabel, gbc_sendHintLabel);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportBorder(new TitledBorder(null, String.format("Chat with %s:",
                        chatPartner.getUserName()), TitledBorder.LEADING, TitledBorder.TOP, null,
                        null));
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        splitPane.setLeftComponent(scrollPane);

        listModel = new DefaultListModel<>();
        for (IMessage message : chat)
        {
            listModel.addElement(message);
        }

        JList<IMessage> chatMessagesList = new JList<>(listModel);
        chatMessagesList.setEnabled(false);
        scrollPane.setViewportView(chatMessagesList);
    }

    /**
     * Appends new message to message list.
     *
     * @param message
     *            - the message to be appended.
     */
    public void showNewMessage(IMessage message)
    {
        listModel.addElement(message);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>role_usage_grants</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.0.5 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="The Information Schema"
HREF="information-schema.html"><LINK
REL="PREVIOUS"
TITLE="role_table_grants"
HREF="infoschema-role-table-grants.html"><LINK
REL="NEXT"
TITLE="routine_privileges"
HREF="infoschema-routine-privileges.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2011-09-22T22:21:03">

PostgreSQL 9.0.5 Documentation

Prev	Fast Backward	Chapter 34. The Information Schema	Fast Forward	Next

34.31. <TT
CLASS="LITERAL"
>role_usage_grants</TT
>

   The view <TT
CLASS="LITERAL"
>role_usage_grants</TT
> identifies
   <TT
CLASS="LITERAL"
>USAGE</TT
> privileges granted on various kinds of
   objects where the grantor or grantee is a currently enabled role.
   Further information can be found under
   <TT
CLASS="LITERAL"
>usage_privileges</TT
>.  The only effective difference
   between this view and <TT
CLASS="LITERAL"
>usage_privileges</TT
> is that
   this view omits objects that have been made accessible to the
   current user by way of a grant to public.

Table 34-29. <TT
CLASS="LITERAL"
>role_usage_grants</TT
> Columns

<COL><COL><COL>

Name	Data Type	Description

<TT
CLASS="LITERAL"
>grantor</TT
>	<TT
CLASS="TYPE"
>sql_identifier</TT
>	The name of the role that granted the privilege

<TT
CLASS="LITERAL"
>grantee</TT
>	<TT
CLASS="TYPE"
>sql_identifier</TT
>	The name of the role that the privilege was granted to

<TT
CLASS="LITERAL"
>object_catalog</TT
>	<TT
CLASS="TYPE"
>sql_identifier</TT
>	Name of the database containing the object (always the current database)

<TT
CLASS="LITERAL"
>object_schema</TT
>	<TT
CLASS="TYPE"
>sql_identifier</TT
>	Name of the schema containing the object, if applicable,
      else an empty string

<TT
CLASS="LITERAL"
>object_name</TT
>	<TT
CLASS="TYPE"
>sql_identifier</TT
>	Name of the object

<TT
CLASS="LITERAL"
>object_type</TT
>	<TT
CLASS="TYPE"
>character_data</TT
>	<TT
CLASS="LITERAL"
>DOMAIN</TT
> or <TT
CLASS="LITERAL"
>FOREIGN DATA WRAPPER</TT
> or <TT
CLASS="LITERAL"
>FOREIGN SERVER</TT
>

<TT
CLASS="LITERAL"
>privilege_type</TT
>	<TT
CLASS="TYPE"
>character_data</TT
>	Always <TT
CLASS="LITERAL"
>USAGE</TT
>

<TT
CLASS="LITERAL"
>is_grantable</TT
>	<TT
CLASS="TYPE"
>yes_or_no</TT
>	<TT
CLASS="LITERAL"
>YES</TT
> if the privilege is grantable, <TT
CLASS="LITERAL"
>NO</TT
> if not

Prev	Home	Next

<TT
CLASS="LITERAL"
>role_table_grants</TT
>	Up	<TT
CLASS="LITERAL"
>routine_privileges</TT
>


text:
package executor

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"

	dockertypes "github.com/docker/engine-api/types"
	"github.com/gogo/protobuf/proto"
	log "github.com/golang/glog"
	bindings "github.com/mesos/mesos-go/executor"
	mesos "github.com/mesos/mesos-go/mesosproto"
	mutil "github.com/mesos/mesos-go/mesosutil"
	"k8s.io/kubernetes/contrib/mesos/pkg/executor/messages"
	"k8s.io/kubernetes/contrib/mesos/pkg/node"
	"k8s.io/kubernetes/contrib/mesos/pkg/podutil"
	"k8s.io/kubernetes/contrib/mesos/pkg/runtime"
	"k8s.io/kubernetes/contrib/mesos/pkg/scheduler/executorinfo"
	"k8s.io/kubernetes/contrib/mesos/pkg/scheduler/meta"
	"k8s.io/kubernetes/pkg/api"
	apierrors "k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/kubelet/container"
	"k8s.io/kubernetes/pkg/kubelet/dockertools"
	kruntime "k8s.io/kubernetes/pkg/runtime"
	utilruntime "k8s.io/kubernetes/pkg/util/runtime"
)

type stateType int32

const (
	disconnectedState stateType = iota
	connectedState
	suicidalState
	terminalState
)

func (s *stateType) get() stateType {
	return stateType(atomic.LoadInt32((*int32)(s)))
}

func (s *stateType) transition(from, to stateType) bool {
	return atomic.CompareAndSwapInt32((*int32)(s), int32(from), int32(to))
}

func (s *stateType) transitionTo(to stateType, unless ...stateType) bool {
	if len(unless) == 0 {
		atomic.StoreInt32((*int32)(s), int32(to))
		return true
	}
	for {
		state := s.get()
		for _, x := range unless {
			if state == x {
				return false
			}
		}
		if s.transition(state, to) {
			return true
		}
	}
}

// KubernetesExecutor is an mesos executor that runs pods
// in a minion machine.
type Executor struct {
	state                stateType
	lock                 sync.Mutex
	terminate            chan struct{}                     // signals that the executor is shutting down
	outgoing             chan func() (mesos.Status, error) // outgoing queue to the mesos driver
	dockerClient         dockertools.DockerInterface
	suicideWatch         suicideWatcher
	suicideTimeout       time.Duration
	shutdownAlert        func()          // invoked just prior to executor shutdown
	kubeletFinished      <-chan struct{} // signals that kubelet Run() died
	exitFunc             func(int)
	staticPodsConfigPath string
	staticPodsFilters    podutil.Filters
	launchGracePeriod    time.Duration
	nodeInfos            chan<- NodeInfo
	initCompleted        chan struct{} // closes upon completion of Init()
	registry             Registry
	watcher              *watcher
	kubeAPI              kubeAPI
	nodeAPI              nodeAPI
}

type Config struct {
	APIClient         *clientset.Clientset
	Docker            dockertools.DockerInterface
	ShutdownAlert     func()
	SuicideTimeout    time.Duration
	KubeletFinished   <-chan struct{} // signals that kubelet Run() died
	ExitFunc          func(int)
	LaunchGracePeriod time.Duration
	NodeInfos         chan<- NodeInfo
	Registry          Registry
	Options           []Option // functional options
}

// Option is a functional option type for Executor
type Option func(*Executor)

func (k *Executor) isConnected() bool {
	return connectedState == (&k.state).get()
}

// New creates a new kubernetes executor.
func New(config Config) *Executor {
	launchGracePeriod := config.LaunchGracePeriod
	if launchGracePeriod == 0 {
		// this is the equivalent of saying "the timer never expires" and simplies nil
		// timer checks elsewhere in the code. it's a little hacky but less code to
		// maintain that alternative approaches.
		launchGracePeriod = time.Duration(math.MaxInt64)
	}
	k := &Executor{
		state:             disconnectedState,
		terminate:         make(chan struct{}),
		outgoing:          make(chan func() (mesos.Status, error), 1024),
		dockerClient:      config.Docker,
		suicideTimeout:    config.SuicideTimeout,
		kubeletFinished:   config.KubeletFinished,
		suicideWatch:      &suicideTimer{},
		shutdownAlert:     config.ShutdownAlert,
		exitFunc:          config.ExitFunc,
		launchGracePeriod: launchGracePeriod,
		nodeInfos:         config.NodeInfos,
		initCompleted:     make(chan struct{}),
		registry:          config.Registry,
	}
	if config.APIClient != nil {
		k.kubeAPI = &clientAPIWrapper{config.APIClient.Core()}
		k.nodeAPI = &clientAPIWrapper{config.APIClient.Core()}
	}

	// apply functional options
	for _, opt := range config.Options {
		opt(k)
	}

	runtime.On(k.initCompleted, k.runSendLoop)

	k.watcher = newWatcher(k.registry.watch())
	runtime.On(k.initCompleted, k.watcher.run)

	return k
}

// StaticPods creates a static pods Option for an Executor
func StaticPods(configPath string, f podutil.Filters) Option {
	return func(k *Executor) {
		k.staticPodsFilters = f
		k.staticPodsConfigPath = configPath
	}
}

// Done returns a chan that closes when the executor is shutting down
func (k *Executor) Done() <-chan struct{} {
	return k.terminate
}

func (k *Executor) Init(driver bindings.ExecutorDriver) {
	defer close(k.initCompleted)

	k.killKubeletContainers()
	k.resetSuicideWatch(driver)

	k.watcher.addFilter(func(podEvent *PodEvent) bool {
		switch podEvent.eventType {
		case PodEventIncompatibleUpdate:
			log.Warningf("killing %s because of an incompatible update", podEvent.FormatShort())
			k.killPodTask(driver, podEvent.taskID)
			// halt processing of this event; when the pod is deleted we'll receive another
			// event for that.
			return false

		case PodEventDeleted:
			// an active pod-task was deleted, alert mesos:
			// send back a TASK_KILLED status, we completed the pod-task lifecycle normally.
			k.resetSuicideWatch(driver)
			k.sendStatus(driver, newStatus(mutil.NewTaskID(podEvent.taskID), mesos.TaskState_TASK_KILLED, "pod-deleted"))
		}
		return true
	})

	//TODO(jdef) monitor kubeletFinished and shutdown if it happens
}

func (k *Executor) isDone() bool {
	select {
	case <-k.terminate:
		return true
	default:
		return false
	}
}

// Registered is called when the executor is successfully registered with the slave.
func (k *Executor) Registered(
	driver bindings.ExecutorDriver,
	executorInfo *mesos.ExecutorInfo,
	frameworkInfo *mesos.FrameworkInfo,
	slaveInfo *mesos.SlaveInfo,
) {
	if k.isDone() {
		return
	}

	log.Infof(
		"Executor %v of framework %v registered with slave %v\n",
		executorInfo, frameworkInfo, slaveInfo,
	)

	if !(&k.state).transition(disconnectedState, connectedState) {
		log.Errorf("failed to register/transition to a connected state")
	}

	k.initializeStaticPodsSource(executorInfo)

	annotations, err := annotationsFor(executorInfo)
	if err != nil {
		log.Errorf(
			"cannot get node annotations from executor info %v error %v",
			executorInfo, err,
		)
	}

	if slaveInfo != nil {
		_, err := k.nodeAPI.createOrUpdate(
			slaveInfo.GetHostname(),
			node.SlaveAttributesToLabels(slaveInfo.Attributes),
			annotations,
		)

		if err != nil {
			log.Errorf("cannot update node labels: %v", err)
		}
	}

	k.lock.Lock()
	defer k.lock.Unlock()

	if slaveInfo != nil && k.nodeInfos != nil {
		k.nodeInfos <- nodeInfo(slaveInfo, executorInfo) // leave it behind the upper lock to avoid panics
	}
}

// Reregistered is called when the executor is successfully re-registered with the slave.
// This can happen when the slave fails over.
func (k *Executor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {
	if k.isDone() {
		return
	}
	log.Infof("Reregistered with slave %v\n", slaveInfo)
	if !(&k.state).transition(disconnectedState, connectedState) {
		log.Errorf("failed to reregister/transition to a connected state")
	}

	if slaveInfo != nil {
		_, err := k.nodeAPI.createOrUpdate(
			slaveInfo.GetHostname(),
			node.SlaveAttributesToLabels(slaveInfo.Attributes),
			nil, // don't change annotations
		)

		if err != nil {
			log.Errorf("cannot update node labels: %v", err)
		}
	}

	if slaveInfo != nil && k.nodeInfos != nil {
		// make sure nodeInfos is not nil and send new NodeInfo
		k.lock.Lock()
		defer k.lock.Unlock()
		if k.isDone() {
			return
		}
		k.nodeInfos <- nodeInfo(slaveInfo, nil)
	}
}

// initializeStaticPodsSource unzips the data slice into the static-pods directory
func (k *Executor) initializeStaticPodsSource(executorInfo *mesos.ExecutorInfo) {
	if data := executorInfo.GetData(); len(data) > 0 && k.staticPodsConfigPath != "" {
		log.V(2).Infof("extracting static pods config to %s", k.staticPodsConfigPath)
		err := podutil.WriteToDir(
			k.staticPodsFilters.Do(podutil.Gunzip(executorInfo.Data)),
			k.staticPodsConfigPath,
		)
		if err != nil {
			log.Errorf("failed to initialize static pod configuration: %v", err)
		}
	}
}

// Disconnected is called when the executor is disconnected from the slave.
func (k *Executor) Disconnected(driver bindings.ExecutorDriver) {
	if k.isDone() {
		return
	}
	log.Infof("Slave is disconnected\n")
	if !(&k.state).transition(connectedState, disconnectedState) {
		log.Errorf("failed to disconnect/transition to a disconnected state")
	}
}

// LaunchTask is called when the executor receives a request to launch a task.
// The happens when the k8sm scheduler has decided to schedule the pod
// (which corresponds to a Mesos Task) onto the node where this executor
// is running, but the binding is not recorded in the Kubernetes store yet.
// This function is invoked to tell the executor to record the binding in the
// Kubernetes store and start the pod via the Kubelet.
func (k *Executor) LaunchTask(driver bindings.ExecutorDriver, taskInfo *mesos.TaskInfo) {
	if k.isDone() {
		return
	}

	log.Infof("Launch task %v\n", taskInfo)

	taskID := taskInfo.GetTaskId().GetValue()
	if p := k.registry.pod(taskID); p != nil {
		log.Warningf("task %v already launched", taskID)
		// Not to send back TASK_RUNNING or TASK_FAILED here, because
		// may be duplicated messages
		return
	}

	if !k.isConnected() {
		log.Errorf("Ignore launch task because the executor is disconnected\n")
		k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,
			messages.ExecutorUnregistered))
		return
	}

	obj, err := kruntime.Decode(api.Codecs.UniversalDecoder(), taskInfo.GetData())
	if err != nil {
		log.Errorf("failed to extract yaml data from the taskInfo.data %v", err)
		k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,
			messages.UnmarshalTaskDataFailure))
		return
	}
	pod, ok := obj.(*api.Pod)
	if !ok {
		log.Errorf("expected *api.Pod instead of %T: %+v", pod, pod)
		k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,
			messages.UnmarshalTaskDataFailure))
		return
	}

	k.resetSuicideWatch(driver)

	// run the next step aync because it calls out to apiserver and we don't want to block here
	go k.bindAndWatchTask(driver, taskInfo, time.NewTimer(k.launchGracePeriod), pod)
}

// determine whether we need to start a suicide countdown. if so, then start
// a timer that, upon expiration, causes this executor to commit suicide.
// this implementation runs asynchronously. callers that wish to wait for the
// reset to complete may wait for the returned signal chan to close.
func (k *Executor) resetSuicideWatch(driver bindings.ExecutorDriver) <-chan struct{} {
	ch := make(chan struct{})
	go func() {
		defer close(ch)
		k.lock.Lock()
		defer k.lock.Unlock()

		if k.suicideTimeout < 1 {
			return
		}

		if k.suicideWatch != nil {
			if !k.registry.empty() {
				k.suicideWatch.Stop()
				return
			}
			if k.suicideWatch.Reset(k.suicideTimeout) {
				// valid timer, reset was successful
				return
			}
		}

		//TODO(jdef) reduce verbosity here once we're convinced that suicide watch is working properly
		log.Infof("resetting suicide watch timer for %v", k.suicideTimeout)

		k.suicideWatch = k.suicideWatch.Next(k.suicideTimeout, driver, jumper(k.attemptSuicide))
	}()
	return ch
}

func (k *Executor) attemptSuicide(driver bindings.ExecutorDriver, abort <-chan struct{}) {
	k.lock.Lock()
	defer k.lock.Unlock()

	// this attempt may have been queued and since been aborted
	select {
	case <-abort:
		//TODO(jdef) reduce verbosity once suicide watch is working properly
		log.Infof("aborting suicide attempt since watch was cancelled")
		return
	default: // continue
	}

	// fail-safe, will abort kamikaze attempts if there are tasks
	if !k.registry.empty() {
		log.Errorf("suicide attempt failed, there are still running tasks")
		return
	}

	log.Infoln("Attempting suicide")
	if (&k.state).transitionTo(suicidalState, suicidalState, terminalState) {
		//TODO(jdef) let the scheduler know?
		//TODO(jdef) is suicide more graceful than slave-demanded shutdown?
		k.doShutdown(driver)
	}
}

func podStatusData(pod *api.Pod, status api.PodStatus) ([]byte, string, error) {
	podFullName := container.GetPodFullName(pod)
	data, err := json.Marshal(api.PodStatusResult{
		ObjectMeta: api.ObjectMeta{
			Name:     podFullName,
			SelfLink: "/podstatusresult",
		},
		Status: status,
	})
	return data, podFullName, err
}

// async continuation of LaunchTask
func (k *Executor) bindAndWatchTask(driver bindings.ExecutorDriver, task *mesos.TaskInfo, launchTimer *time.Timer, pod *api.Pod) {
	success := false
	defer func() {
		if !success {
			k.killPodTask(driver, task.TaskId.GetValue())
			k.resetSuicideWatch(driver)
		}
	}()

	// allow a recently failed-over scheduler the chance to recover the task/pod binding:
	// it may have failed and recovered before the apiserver is able to report the updated
	// binding information. replays of this status event will signal to the scheduler that
	// the apiserver should be up-to-date.
	startingData, _, err := podStatusData(pod, api.PodStatus{})
	if err != nil {
		log.Errorf("failed to generate pod-task starting data for task %v pod %v/%v: %v",
			task.TaskId.GetValue(), pod.Namespace, pod.Name, err)
		k.sendStatus(driver, newStatus(task.TaskId, mesos.TaskState_TASK_FAILED, err.Error()))
		return
	}

	err = k.registry.bind(task.TaskId.GetValue(), pod)
	if err != nil {
		log.Errorf("failed to bind task %v pod %v/%v: %v",
			task.TaskId.GetValue(), pod.Namespace, pod.Name, err)
		k.sendStatus(driver, newStatus(task.TaskId, mesos.TaskState_TASK_FAILED, err.Error()))
		return
	}

	// send TASK_STARTING
	k.sendStatus(driver, &mesos.TaskStatus{
		TaskId:  task.TaskId,
		State:   mesos.TaskState_TASK_STARTING.Enum(),
		Message: proto.String(messages.CreateBindingSuccess),
		Data:    startingData,
	})

	// within the launch timeout window we should see a pod-task update via the registry.
	// if we see a Running update then we need to generate a TASK_RUNNING status update for mesos.
	handlerFinished := false
	handler := &watchHandler{
		expiration: watchExpiration{
			timeout: launchTimer.C,
			onEvent: func(taskID string) {
				if !handlerFinished {
					// launch timeout expired
					k.killPodTask(driver, task.TaskId.GetValue())
				}
			},
		},
		onEvent: func(podEvent *PodEvent) (bool, error) {
			switch podEvent.eventType {
			case PodEventUpdated:
				log.V(2).Infof("Found status: '%v' for %s", podEvent.pod.Status, podEvent.FormatShort())

				if podEvent.pod.Status.Phase != api.PodRunning {
					// still waiting for pod to transition to a running state, so
					// we're not done monitoring yet; check back later..
					break
				}

				data, podFullName, err := podStatusData(podEvent.pod, podEvent.pod.Status)
				if err != nil {
					return false, fmt.Errorf("failed to marshal pod status result: %v", err)
				}

				defer k.sendStatus(driver, &mesos.TaskStatus{
					TaskId:  task.TaskId,
					State:   mesos.TaskState_TASK_RUNNING.Enum(),
					Message: proto.String("pod-running:" + podFullName),
					Data:    data,
				})
				fallthrough

			case PodEventDeleted:
				// we're done monitoring because pod has been deleted
				handlerFinished = true
				launchTimer.Stop()
			}
			return handlerFinished, nil
		},
	}
	k.watcher.forTask(task.TaskId.GetValue(), handler)
	success = true
}

// KillTask is called when the executor receives a request to kill a task.
func (k *Executor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {
	k.killPodTask(driver, taskId.GetValue())
}

// deletes the pod and task associated with the task identified by taskID and sends a task
// status update to mesos. also attempts to reset the suicide watch.
func (k *Executor) killPodTask(driver bindings.ExecutorDriver, taskID string) {
	pod := k.registry.pod(taskID)
	if pod == nil {
		log.V(1).Infof("Failed to remove task, unknown task %v\n", taskID)
		k.sendStatus(driver, newStatus(&mesos.TaskID{Value: &taskID}, mesos.TaskState_TASK_LOST, "kill-pod-task"))
		return
	}

	// force-delete the pod from the API server
	// TODO(jdef) possibly re-use eviction code from stock k8s once it lands?
	err := k.kubeAPI.killPod(pod.Namespace, pod.Name)
	if err != nil {
		log.V(1).Infof("failed to delete task %v pod %v/%v from apiserver: %+v", taskID, pod.Namespace, pod.Name, err)
		if apierrors.IsNotFound(err) {
			k.sendStatus(driver, newStatus(&mesos.TaskID{Value: &taskID}, mesos.TaskState_TASK_LOST, "kill-pod-task"))
		}
	}
}

// FrameworkMessage is called when the framework sends some message to the executor
func (k *Executor) FrameworkMessage(driver bindings.ExecutorDriver, message string) {
	if k.isDone() {
		return
	}
	if !k.isConnected() {
		log.Warningf("Ignore framework message because the executor is disconnected\n")
		return
	}

	log.Infof("Receives message from framework %v\n", message)
	//TODO(jdef) master reported a lost task, reconcile this! @see framework.go:handleTaskLost
	if strings.HasPrefix(message, messages.TaskLost+":") {
		taskId := message[len(messages.TaskLost)+1:]
		if taskId != "" {
			// TODO(jdef) would it make more sense to check the status of the task and
			// just replay the last non-terminal message that we sent if the task is
			// still active?

			// clean up pod state
			k.sendStatus(driver, newStatus(&mesos.TaskID{Value: &taskId}, mesos.TaskState_TASK_LOST, messages.TaskLostAck))
			k.killPodTask(driver, taskId)
		}
		return
	}

	switch message {
	case messages.Kamikaze:
		k.attemptSuicide(driver, nil)
	}
}

// Shutdown is called when the executor receives a shutdown request.
func (k *Executor) Shutdown(driver bindings.ExecutorDriver) {
	k.lock.Lock()
	defer k.lock.Unlock()
	k.doShutdown(driver)
}

// assumes that caller has obtained state lock
func (k *Executor) doShutdown(driver bindings.ExecutorDriver) {
	defer func() {
		log.Errorf("exiting with unclean shutdown: %v", recover())
		if k.exitFunc != nil {
			k.exitFunc(1)
		}
	}()

	(&k.state).transitionTo(terminalState)

	// signal to all listeners that this KubeletExecutor is done!
	close(k.terminate)
	close(k.nodeInfos)

	if k.shutdownAlert != nil {
		func() {
			utilruntime.HandleCrash()
			k.shutdownAlert()
		}()
	}

	log.Infoln("Stopping executor driver")
	_, err := driver.Stop()
	if err != nil {
		log.Warningf("failed to stop executor driver: %v", err)
	}

	log.Infoln("Shutdown the executor")

	// according to docs, mesos will generate TASK_LOST updates for us
	// if needed, so don't take extra time to do that here.
	k.registry.shutdown()

	select {
	// the main Run() func may still be running... wait for it to finish: it will
	// clear the pod configuration cleanly, telling k8s "there are no pods" and
	// clean up resources (pods, volumes, etc).
	case <-k.kubeletFinished:

	//TODO(jdef) attempt to wait for events to propagate to API server?

	// TODO(jdef) extract constant, should be smaller than whatever the
	// slave graceful shutdown timeout period is.
	case <-time.After(15 * time.Second):
		log.Errorf("timed out waiting for kubelet Run() to die")
	}
	log.Infoln("exiting")
	if k.exitFunc != nil {
		k.exitFunc(0)
	}
}

// Destroy existing k8s containers
func (k *Executor) killKubeletContainers() {
	if containers, err := dockertools.GetKubeletDockerContainers(k.dockerClient, true); err == nil {
		opts := dockertypes.ContainerRemoveOptions{
			RemoveVolumes: true,
			Force:         true,
		}
		for _, container := range containers {
			log.V(2).Infof("Removing container: %v", container.ID)
			if err := k.dockerClient.RemoveContainer(container.ID, opts); err != nil {
				log.Warning(err)
			}
		}
	} else {
		log.Warningf("Failed to list kubelet docker containers: %v", err)
	}
}

// Error is called when some error happens.
func (k *Executor) Error(driver bindings.ExecutorDriver, message string) {
	log.Errorln(message)
}

func newStatus(taskId *mesos.TaskID, state mesos.TaskState, message string) *mesos.TaskStatus {
	return &mesos.TaskStatus{
		TaskId:  taskId,
		State:   &state,
		Message: proto.String(message),
	}
}

func (k *Executor) sendStatus(driver bindings.ExecutorDriver, status *mesos.TaskStatus) {
	select {
	case <-k.terminate:
	default:
		k.outgoing <- func() (mesos.Status, error) { return driver.SendStatusUpdate(status) }
	}
}

func (k *Executor) sendFrameworkMessage(driver bindings.ExecutorDriver, msg string) {
	select {
	case <-k.terminate:
	default:
		k.outgoing <- func() (mesos.Status, error) { return driver.SendFrameworkMessage(msg) }
	}
}

func (k *Executor) runSendLoop() {
	defer log.V(1).Info("sender loop exiting")
	for {
		select {
		case <-k.terminate:
			return
		default:
			if !k.isConnected() {
				select {
				case <-k.terminate:
				case <-time.After(1 * time.Second):
				}
				continue
			}
			sender, ok := <-k.outgoing
			if !ok {
				// programming error
				panic("someone closed the outgoing channel")
			}
			if status, err := sender(); err == nil {
				continue
			} else {
				log.Error(err)
				if status == mesos.Status_DRIVER_ABORTED {
					return
				}
			}
			// attempt to re-queue the sender
			select {
			case <-k.terminate:
			case k.outgoing <- sender:
			}
		}
	}
}

func annotationsFor(ei *mesos.ExecutorInfo) (annotations map[string]string, err error) {
	annotations = map[string]string{}
	if ei == nil {
		return
	}

	var buf bytes.Buffer
	if err = executorinfo.EncodeResources(&buf, ei.GetResources()); err != nil {
		return
	}

	annotations[meta.ExecutorIdKey] = ei.GetExecutorId().GetValue()
	annotations[meta.ExecutorResourcesKey] = buf.String()

	return
}


text:
/**
  * Automatically generated file. Please do not edit.
  * @author Highcharts Config Generator by Karasiq
  * @see [[http://api.highcharts.com/highmaps]]
  */
package com.highmaps.config

import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._

/**
  * @note JavaScript name: series<treemap>-data
  */
@js.annotation.ScalaJSDefined
class SeriesTreemapData extends com.highcharts.HighchartsGenericObject {

  /**
    *
Only for treemap. Use this option to build a tree structure. The
    * value should be the id of the point which is the parent. If no points
    * has a matching id, or this option is undefined, then the parent will
    * be set to the root.

    * @example Point parent
Example where parent id is not matching
    * @since 4.1.0
    */
  val parent: js.UndefOr[String] = js.undefined

  /**
    *
The value of the point, resulting in a relative area of the point
    * in the treemap.

    */
  val value: js.UndefOr[Double] = js.undefined

  /**
    *
Serves a purpose only if a colorAxis object is defined in the chart
    * options. This value will decide which color the point gets from the
    * scale of the colorAxis.

    * @since 4.1.0
    */
  val colorValue: js.UndefOr[Double] = js.undefined

  /**
    *
The color of the point. In heat maps the point color is rarely set
    * explicitly, as we use the color to denote the value. Options for
    * this are set in the colorAxis configuration.

    * @example Mark the highest point
    */
  val color: js.UndefOr[String | js.Object] = js.undefined

  /**
    *
Point padding for a single point.

    * @example Point padding on tiles
    */
  val pointPadding: js.UndefOr[Double] = js.undefined

  /**
    *
Point specific options for the draggable-points module. Overrides options on
    * series.dragDrop.

    *
Requires the draggable-points module.

    * @since 6.2.0
    */
  val dragDrop: js.UndefOr[CleanJsObject[SeriesTreemapDataDragDrop]] = js.undefined

  /**
    *
The id of a series in the drilldown.series
    * array to use for a drilldown for this point.

    * @example Basic drilldown
    * @since 3.0.8
    */
  val drilldown: js.UndefOr[String] = js.undefined

  /**
    *
An additional, individual class name for the data point's graphic
    * representation.

    * @since 5.0.0
    */
  val className: js.UndefOr[String] = js.undefined

  /**
    *
A specific color index to use for the point, so its graphic representations
    * are given the class name highcharts-color-{n}. In styled mode this will
    * change the color of the graphic. In non-styled mode, the color by is set by
    * the fill attribute, so the change in class name won't have a visual effect
    * by default.

    * @since 5.0.0
    */
  val colorIndex: js.UndefOr[Double] = js.undefined

  /**
    *
Individual data label for each point. The options are the same as
    * the ones for plotOptions.series.dataLabels.

    * @example Show a label for the last value
    */
  val dataLabels: js.Any = js.undefined

  /**
    *
A description of the point to add to the screen reader information
    * about the point. Requires the Accessibility module.

    * @since 5.0.0
    */
  val description: js.UndefOr[String] = js.undefined

  /**
    *
An id for the point. This can be used after render time to get a
    * pointer to the point object through chart.get().

    * @example Remove an id'd point
    * @since 1.2.0
    */
  val id: js.UndefOr[String] = js.undefined

  /**
    *
The rank for this point's data label in case of collision. If two
    * data labels are about to overlap, only the one with the highest labelrank
    * will be drawn.

    */
  val labelrank: js.UndefOr[Double] = js.undefined

  /**
    *
The name of the point as shown in the legend, tooltip, dataLabel
    * etc.

    * @example Point names
    */
  val name: js.UndefOr[String] = js.undefined

  /**
    *
Whether the data point is selected initially.

    */
  val selected: js.UndefOr[Boolean] = js.undefined

  /**
    *
Individual point events

    */
  val events: js.UndefOr[CleanJsObject[SeriesTreemapDataEvents]] = js.undefined
}

object SeriesTreemapData {
  /**
    * @param parent
Only for treemap. Use this option to build a tree structure. The. value should be the id of the point which is the parent. If no points. has a matching id, or this option is undefined, then the parent will. be set to the root.

    * @param value
The value of the point, resulting in a relative area of the point. in the treemap.

    * @param colorValue
Serves a purpose only if a colorAxis object is defined in the chart. options. This value will decide which color the point gets from the. scale of the colorAxis.

    * @param color
The color of the point. In heat maps the point color is rarely set. explicitly, as we use the color to denote the value. Options for. this are set in the colorAxis configuration.

    * @param pointPadding
Point padding for a single point.

    * @param dragDrop
Point specific options for the draggable-points module. Overrides options on. series.dragDrop.
.
Requires the draggable-points module.

    * @param drilldown
The id of a series in the drilldown.series. array to use for a drilldown for this point.

    * @param className
An additional, individual class name for the data point's graphic. representation.

    * @param colorIndex
A specific color index to use for the point, so its graphic representations. are given the class name highcharts-color-{n}. In styled mode this will. change the color of the graphic. In non-styled mode, the color by is set by. the fill attribute, so the change in class name won't have a visual effect. by default.

    * @param dataLabels
Individual data label for each point. The options are the same as. the ones for plotOptions.series.dataLabels.

    * @param description
A description of the point to add to the screen reader information. about the point. Requires the Accessibility module.

    * @param id
An id for the point. This can be used after render time to get a. pointer to the point object through chart.get().

    * @param labelrank
The rank for this point's data label in case of collision. If two. data labels are about to overlap, only the one with the highest labelrank. will be drawn.

    * @param name
The name of the point as shown in the legend, tooltip, dataLabel. etc.

    * @param selected
Whether the data point is selected initially.

    * @param events
Individual point events

    */
  def apply(parent: js.UndefOr[String] = js.undefined, value: js.UndefOr[Double] = js.undefined, colorValue: js.UndefOr[Double] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, pointPadding: js.UndefOr[Double] = js.undefined, dragDrop: js.UndefOr[CleanJsObject[SeriesTreemapDataDragDrop]] = js.undefined, drilldown: js.UndefOr[String] = js.undefined, className: js.UndefOr[String] = js.undefined, colorIndex: js.UndefOr[Double] = js.undefined, dataLabels: js.UndefOr[js.Any] = js.undefined, description: js.UndefOr[String] = js.undefined, id: js.UndefOr[String] = js.undefined, labelrank: js.UndefOr[Double] = js.undefined, name: js.UndefOr[String] = js.undefined, selected: js.UndefOr[Boolean] = js.undefined, events: js.UndefOr[CleanJsObject[SeriesTreemapDataEvents]] = js.undefined): SeriesTreemapData = {
    val parentOuter: js.UndefOr[String] = parent
    val valueOuter: js.UndefOr[Double] = value
    val colorValueOuter: js.UndefOr[Double] = colorValue
    val colorOuter: js.UndefOr[String | js.Object] = color
    val pointPaddingOuter: js.UndefOr[Double] = pointPadding
    val dragDropOuter: js.UndefOr[CleanJsObject[SeriesTreemapDataDragDrop]] = dragDrop
    val drilldownOuter: js.UndefOr[String] = drilldown
    val classNameOuter: js.UndefOr[String] = className
    val colorIndexOuter: js.UndefOr[Double] = colorIndex
    val dataLabelsOuter: js.Any = dataLabels
    val descriptionOuter: js.UndefOr[String] = description
    val idOuter: js.UndefOr[String] = id
    val labelrankOuter: js.UndefOr[Double] = labelrank
    val nameOuter: js.UndefOr[String] = name
    val selectedOuter: js.UndefOr[Boolean] = selected
    val eventsOuter: js.UndefOr[CleanJsObject[SeriesTreemapDataEvents]] = events
    com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesTreemapData {
      override val parent: js.UndefOr[String] = parentOuter
      override val value: js.UndefOr[Double] = valueOuter
      override val colorValue: js.UndefOr[Double] = colorValueOuter
      override val color: js.UndefOr[String | js.Object] = colorOuter
      override val pointPadding: js.UndefOr[Double] = pointPaddingOuter
      override val dragDrop: js.UndefOr[CleanJsObject[SeriesTreemapDataDragDrop]] = dragDropOuter
      override val drilldown: js.UndefOr[String] = drilldownOuter
      override val className: js.UndefOr[String] = classNameOuter
      override val colorIndex: js.UndefOr[Double] = colorIndexOuter
      override val dataLabels: js.Any = dataLabelsOuter
      override val description: js.UndefOr[String] = descriptionOuter
      override val id: js.UndefOr[String] = idOuter
      override val labelrank: js.UndefOr[Double] = labelrankOuter
      override val name: js.UndefOr[String] = nameOuter
      override val selected: js.UndefOr[Boolean] = selectedOuter
      override val events: js.UndefOr[CleanJsObject[SeriesTreemapDataEvents]] = eventsOuter
    })
  }
}


text:
"use strict";

var UI          = require("./lib/UI");
var config      = require("./lib/config");
var Events      = require("events").EventEmitter;

/**
 * These hooks are for attaching functionality to BrowserSync
 */
module.exports.hooks = {
    /**
     * Client JS is added to each connected client
     */
    "client:js": require("fs").readFileSync(__dirname + config.defaults.clientJs)
};

/**
 * BrowserSync Plugin interface
 * @param {Object} opts
 * @param {BrowserSync} bs
 * @param {Function} cb
 * @returns {UI}
 */
module.exports["plugin"] = function (opts, bs, cb) {
    var ui = new UI(opts, bs, new Events());
    ui.cb = cb || function () { /*noop*/ };
    ui.init();
    return ui;
};

module.exports["plugin:name"]       = config.defaults.pluginName;


text:
import DS from 'ember-data';
import BackboneElement from 'ember-fhir/models/backbone-element';

const { belongsTo } = DS;

export default BackboneElement.extend({
  contentAttachment: belongsTo('attachment', { async: false }),
  contentReference: belongsTo('reference', { async: false })
});


text:
do {                                                                                \
    ccGLEnable( _mask.glServerState );                                              \
    NSAssert1(_mask.shaderProgram, @"No shader program set for node: %@", _mask);   \
    [_mask.shaderProgram use];                                                      \
    [_mask.shaderProgram setUniformsForBuiltins];                                   \
} while(0)                                                                          \

@implementation TBSpriteMask

-(id) initWithSprite:(CCSprite*)sprite andMaskSprite:(CCSprite*)maskSprite
{
    return [self initWithSprite:sprite andMaskSprite:maskSprite andType:FALSE];
}

-(id) initWithSprite:(CCSprite*)sprite andMaskFile:(NSString*)maskFile
{
    return [self initWithSprite:sprite andMaskFile:maskFile andType:FALSE];
}

-(id) initWithFile:(NSString *)file andMaskSprite:(CCSprite*)maskSprite
{
    return [self initWithFile:file andMaskSprite:maskSprite andType:FALSE];
}

-(id) initWithFile:(NSString *)file andMaskFile:(NSString*)maskFile;
{
    return [self initWithFile:file andMaskFile:maskFile andType:FALSE];
}

-(id) initWithSprite:(CCSprite*)sprite andMaskSprite:(CCSprite*)maskSprite andType:(BOOL)type;
{
    self = [super init];
    if (self) {
        _mask = [sprite retain];
        _type = type;
        [self builtWithTexture:_mask andTexture:[[maskSprite texture] retain]];
    }
    return self;
}

-(id) initWithSprite:(CCSprite*)sprite andMaskFile:(NSString*)maskFile andType:(BOOL)type;
{
    self = [super init];
    if(self){
        _mask = [sprite retain];
        _type = type;
        [self builtWithTexture:_mask andTexture:[[CCTextureCache sharedTextureCache] addImage:maskFile]];
    }
    return self;
}

-(id) initWithFile:(NSString *)file andMaskSprite:(CCSprite*)maskSprite andType:(BOOL)type;
{
    self = [super init];
    if (self) {
        _mask = [[CCSprite alloc] initWithFile:file];
        _type = type;
        [self builtWithTexture:_mask andTexture:[[maskSprite texture] retain]];
    }
    return self;
}

-(id) initWithFile:(NSString *)file andMaskFile:(NSString*)maskFile andType:(BOOL)type;
{
    self = [super init];
    if (self) {
        _mask = [[CCSprite alloc] initWithFile:file];
        _type = type;
        [self builtWithTexture:_mask andTexture:[[CCTextureCache sharedTextureCache] addImage:maskFile]];
    }
    return self;
}

- (void)builtWithTexture:(CCSprite *)mask andTexture:(CCTexture2D*)texture
{
    [_mask setAnchorPoint:CGPointZero];
    [self buildMaskWithTexture:texture];
}

-(void) buildMaskWithTexture:(CCTexture2D*)texture
{
    NSString *shaderName =  _type ? @"MaskPositive.fsh" : @"MaskNegative.fsh";
    const GLchar * fragmentSource = (GLchar*) [[NSString stringWithContentsOfFile:[[CCFileUtils sharedFileUtils] fullPathFromRelativePath:shaderName] encoding:NSUTF8StringEncoding error:nil] UTF8String];

    _mask.shaderProgram = [[CCGLProgram alloc] initWithVertexShaderByteArray:ccPositionTextureA8Color_vert
                                                    fragmentShaderByteArray:fragmentSource];
    [_mask.shaderProgram addAttribute:kCCAttributeNamePosition index:kCCVertexAttrib_Position];
    [_mask.shaderProgram addAttribute:kCCAttributeNameTexCoord index:kCCVertexAttrib_TexCoords];
    [_mask.shaderProgram addAttribute:kCCAttributeNameColor index:kCCVertexAttrib_Color];
    [_mask.shaderProgram link];
    [_mask.shaderProgram updateUniforms];

    _maskLocation = glGetUniformLocation(_mask.shaderProgram->_program, "u_overlayTexture");
    glUniform1i(_maskLocation, 1);
    _maskTexture = texture;
    [_maskTexture setAliasTexParameters];

    [_mask.shaderProgram use];
    ccGLBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, [_maskTexture name]);
    glActiveTexture(GL_TEXTURE0);
}

-(void) draw
{
    DRAW_SETUP();

    ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex);
    ccGLBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    [_mask.shaderProgram setUniformsForBuiltins];

    glActiveTexture(GL_TEXTURE0);
    glBindTexture( GL_TEXTURE_2D, [_mask.texture name] );
    glUniform1i(_textureLocation, 0);

    glActiveTexture(GL_TEXTURE1);
    glBindTexture( GL_TEXTURE_2D, [_maskTexture name] );
    glUniform1i(_maskLocation, 1);

    #define kQuadSize sizeof(_mask.quad.bl)
    ccV3F_C4B_T2F_Quad q = _mask.quad;
    long offset = (long)&q;

    NSInteger diff = offsetof( ccV3F_C4B_T2F, vertices);
    glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff));

    diff = offsetof( ccV3F_C4B_T2F, texCoords);
    glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff));

    diff = offsetof( ccV3F_C4B_T2F, colors);
    glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff));

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glActiveTexture(GL_TEXTURE0);
}

-(void)updateWithSprite:(CCSprite*)sprite
{
    [_mask.shaderProgram release];
    [_mask release];
    _mask = nil;

    _mask = [sprite retain];
    [self builtWithTexture:_mask andTexture:_maskTexture];
}

-(void)updateWithFile:(NSString *)file
{
    [self updateWithSprite:[[CCSprite alloc] initWithFile:file]];
}

-(CCTexture2D *)getTexture
{
    CCRenderTexture *renderTexture = [CCRenderTexture renderTextureWithWidth:_mask.contentSize.width height:_mask.contentSize.height];
    [renderTexture begin];
    _mask.flipY = YES;
    [_mask draw];
    _mask.flipY = NO;
    [renderTexture end];

    return renderTexture.sprite.texture;
}

- (void)dealloc
{
    [_mask release];
    _mask = nil;

    [_maskTexture release];
    _maskTexture = nil;

    [_mask.shaderProgram release];

    [super dealloc];
}

@end


text:
import Type from 'union-type';

const T = () => true;
const Result = Type({
  Ok: [T],
  Error: [T]
});

export default Result;


text:
@protocol Runnable <NSObject>

-(void)run;

@end


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ElementInfoHelper.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Reflection
{
    using System.ComponentModel.DataAnnotations;
    using System.Linq;

    using Kephas.ComponentModel.DataAnnotations;
    using Kephas.Runtime;

    /// <summary>
    /// Extension methods for <see cref="IElementInfo"/>.
    /// </summary>
    public static class ElementInfoHelper
    {
        /// <summary>
        /// The display info key.
        /// </summary>
        public const string DisplayInfoKey = "__DisplayInfo";

        /// <summary>
        /// Tries to compute the <see cref="IDisplayInfo"/> from the provided <see cref="IElementInfo"/>.
        /// </summary>
        /// <param name="elementInfo">Information describing the element.</param>
        /// <returns>
        /// A <see cref="IDisplayInfo"/> or <c>null</c>.
        /// </returns>
        public static IDisplayInfo? GetDisplayInfo(IElementInfo? elementInfo)
        {
            if (elementInfo == null)
            {
                return null;
            }

            if (elementInfo[DisplayInfoKey] is IDisplayInfo displayInfo)
            {
                return displayInfo;
            }

            var annotations = elementInfo?.Annotations;
            displayInfo = annotations?.OfType<IDisplayInfo>().FirstOrDefault();
            if (displayInfo == null)
            {
                displayInfo = annotations
                    ?.OfType<IAttributeProvider>()
                    .Select(p => p.GetAttribute<DisplayInfoAttribute>())
                    .FirstOrDefault(a => a != null);

                if (displayInfo == null)
                {
                    var displayAttribute = ComputeDisplayAttribute(elementInfo);
                    if (displayAttribute != null)
                    {
                        displayInfo = new DisplayAttributeAdapter(displayAttribute);
                    }
                }
            }

            if (displayInfo == null)
            {
                displayInfo = new DisplayInfoAttribute();
            }

            elementInfo[DisplayInfoKey] = displayInfo;
            return displayInfo;
        }

        /// <summary>
        /// Tries to get the display attribute from the provided <see cref="IElementInfo"/>.
        /// </summary>
        /// <param name="elementInfo">Information describing the element.</param>
        /// <returns>
        /// A <see cref="IDisplayInfo"/> attribute or <c>null</c>.
        /// </returns>
        private static DisplayAttribute? ComputeDisplayAttribute(IElementInfo? elementInfo)
        {
            if (elementInfo == null)
            {
                return null;
            }

            var annotations = elementInfo?.Annotations;
            var displayAttribute = annotations?.OfType<DisplayAttribute>().FirstOrDefault();
            if (displayAttribute != null)
            {
                return displayAttribute;
            }

            displayAttribute = annotations
                ?.OfType<IAttributeProvider>()
                .Select(p => p.GetAttribute<DisplayAttribute>())
                .FirstOrDefault(a => a != null);

            return displayAttribute;
        }
    }
}


text:
[Ladybug Analysis Tools]( http://ladybug-analysis-tools.github.io/ )  »

A Bauhaus building in TelAviv
[Engel House]( #https://ladybug-analysis-tools.github.io/3d-models/json/engel-house/AngelHouse_Bauhaus-in-Israel.json )

External links

[Recent real estate listing]( send-to.html#http://giordanadicastro1.blogspot.com/2016/03/apartment-of-rare-beauty-in-heart-of.html?view=snapshot )


text:
package com.indra.sofia2.ssapandroid.ssap.exceptions;

public class NotSupportedMessageTypeException extends Exception {

	private static final long serialVersionUID = 1L;

	public NotSupportedMessageTypeException(String message){
		super(message);
	}

	public NotSupportedMessageTypeException(String message,Exception e){
		super(message,e);
	}

	public NotSupportedMessageTypeException(Exception e) {
		super(e);
	}

}


text:
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace C4Server.Test
{
    public class ServerListenerFacts
    {
        const string IpAddress = "127.0.0.1";
        const int Port = 4444;

        class UpdateRequestHeaderHandler : DelegatingHandler
        {
            readonly string m_key;
            readonly string m_value;

            public UpdateRequestHeaderHandler(string key, string value)
            {
                m_key = key;
                m_value = value;
            }

            protected override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request,
                CancellationToken cancellationToken)
            {
                request.Headers.Add(m_key, m_value);
                return base.SendAsync(request, cancellationToken);
            }
        }

        [Fact]
        public async Task should_get_hello_world_response()
        {
            var serverListener = new ServerListener(IpAddress, Port,
                (request, stream) =>
                {
                    WriteResponse(stream);
                });
            serverListener.Start();

            using (serverListener)
            using (var httpClient = new HttpClient())
            {
                var message = await httpClient.GetAsync("http://127.0.0.1:4444");
                var content = await message.Content.ReadAsStringAsync();

                Assert.Equal("Hello world", content);
            }
        }

        [Fact]
        public async Task should_handle_multiple_get_requests()
        {
            var serverListener = new ServerListener(IpAddress, Port,
                (request, stream) =>
                {
                    WriteResponse(stream);
                });
            serverListener.Start();

            using (serverListener)
            using (var httpClient = new HttpClient())
            {
                HttpResponseMessage message = await httpClient.GetAsync("http://127.0.0.1:4444");
                string content = await message.Content.ReadAsStringAsync();

                Assert.Equal(HttpStatusCode.OK, message.StatusCode);
                Assert.Equal("Hello world", content);

                message = await httpClient.GetAsync("http://127.0.0.1:4444");
                content = await message.Content.ReadAsStringAsync();

                Assert.Equal(HttpStatusCode.OK, message.StatusCode);
                Assert.Equal("Hello world", content);
            }
        }

        [Fact]
        public async Task should_get_request_line()
        {
            string method = null;
            string version = null;

            var serverListener = new ServerListener(IpAddress, Port,
                (request, stream) =>
                {
                    method = request.RequestLine.Method;
                    version = request.RequestLine.Version;
                    WriteResponse(stream);
                });
            serverListener.Start();

            using (serverListener)
            using (var httpClient = new HttpClient())
            {
                var message = await httpClient.GetAsync("http://127.0.0.1:4444");
                Assert.Equal(HttpStatusCode.OK, message.StatusCode);
                Assert.Equal("GET", method);
                Assert.Equal("HTTP/1.1", version);
            }
        }

        [Theory]
        [InlineData("http://127.0.0.1:4444", "/")]
        [InlineData("http://127.0.0.1:4444/?id=1", "/?id=1")]
        [InlineData("http://127.0.0.1:4444/account/1/show.aspx?id=1", "/account/1/show.aspx?id=1")]
        public async Task should_get_request_target(string uri, string expectedUri)
        {
            string requestUri = null;

            var serverListener = new ServerListener(IpAddress, Port,
                (request, stream) =>
                {
                    requestUri = request.RequestLine.RequestTarget;
                    WriteResponse(stream);
                });
            serverListener.Start();

            using (serverListener)
            using (var httpClient = new HttpClient())
            {
                var message = await httpClient.GetAsync(uri);
                Assert.Equal(HttpStatusCode.OK, message.StatusCode);
                Assert.Equal(expectedUri, requestUri);
            }
        }

        [Fact]
        public async Task should_get_request_headers()
        {
            IReadOnlyDictionary<string, string> headers = null;

            var serverListener = new ServerListener(
                IpAddress,
                Port,
                (request, stream) =>
                {
                    headers = request.Headers;
                    WriteResponse(stream);
                });
            serverListener.Start();

            using (serverListener)
            using (
                var httpClient =
                    new HttpClient(
                        CreateUpdateRequestHeaderHandler("X-Custom-Header", "Goodjob"),
                        true))
            {
                var message = await httpClient.GetAsync("http://127.0.0.1:4444");
                Assert.Equal(HttpStatusCode.OK, message.StatusCode);
                Assert.Equal("Goodjob", headers["X-Custom-Header"]);
            }
        }

        static UpdateRequestHeaderHandler CreateUpdateRequestHeaderHandler(string key, string value)
        {
            return new UpdateRequestHeaderHandler(key, value)
            {
                InnerHandler = new HttpClientHandler()
            };
        }

        static void WriteResponse(Stream stream)
        {
            byte[] content = Encoding.UTF8.GetBytes("Hello world");

            var response = new C4Response(stream) {StatusCode = HttpStatusCode.OK};
            response.Headers["Content-Type"] = "text/html;charset=utf-8";
            response.Headers["Content-Length"] = content.Length.ToString(CultureInfo.InvariantCulture);
            response.Headers["Connection"] = "close";
            response.GetOutputStream().Write(content, 0, content.Length);
            response.End();
        }
    }
}