text:
"use strict";

// Requires and node configuration
var node = require("./../variables.js");
var genesisblock = require("../../genesisBlock.json");

var block = {
    blockHeight : 0,
    id : 0,
    generatorPublicKey : "",
    totalAmount : 0,
    totalFee : 0
};

var testBlocksUnder101 = 0;

describe("POST /accounts/open", function () {

    it("When payload is over 2Mb. Should fail", function (done) {
        node.api.post("/accounts/open")
            .set("Accept", "application/json")
            .send({
                payload: new Buffer(8 * 1000 * 1000).toString()
            })
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.false;
                node.expect(res.body).to.have.property("error").to.equal("Error: request entity too large");
                // node.expect(res.body.error).to.have.property("limit").to.equal(2097152);
                done();
            });
    });
});

describe("GET /peers/version", function () {

    it("Should be ok", function (done) {
        node.api.get("/peers/version")
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("build").to.be.a("string");
                node.expect(res.body).to.have.property("version").to.be.a("string");
                done();
            });
    });
});

describe("GET /peers", function () {

    it("Using empty parameters. Should fail", function (done) {
        var state = "", os = "", shared = "", version = "", limit = "", offset = 0, orderBy = "";
        node.api.get("/peers?state="+state+"&os="+os+"&shared="+true+"&version="+version+"&limit="+limit+"&offset="+offset+"orderBy="+orderBy)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.false;
                node.expect(res.body).to.have.property("error");
                done();
            });
    });

    it("Using state. Should be ok", function (done) {
        var state = 1;
        node.api.get("/peers?state="+state)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("peers").that.is.an("array");
                if (res.body.peers.length > 0) {
                    for (var i = 0; i < res.body.peers.length; i++) {
                       node.expect(res.body.peers[i].state).to.equal(parseInt(state));
                    }
                }
                done();
            });
    });

    it("Using limit. Should be ok", function (done) {
        var limit = 3, offset = 0;
        node.api.get("/peers?&limit="+limit+"&offset="+offset)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("peers").that.is.an("array");

                // To check it need to have peers
                node.expect(res.body.peers.length).to.be.at.most(limit);
                done();
            });
    });

    it("Using orderBy. Should be ok", function (done) {
        var orderBy = "state:desc";
        node.api.get("/peers?orderBy="+orderBy)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("peers").that.is.an("array");

                if (res.body.peers.length > 0) {
                    for (var i = 0; i < res.body.peers.length; i++) {
                        if (res.body.peers[i+1] != null) {
                            node.expect(res.body.peers[i+1].state).to.at.most(res.body.peers[i].state);
                        }
                    }
                }

                done();
            });

    });

    it("Using limit > 100. Should fail", function (done) {
        var limit = 101;
        node.api.get("/peers?&limit="+limit)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.false;
                node.expect(res.body).to.have.property("error");
                done();
            });
    });

    it("Using invalid parameters. Should fail", function (done) {
        var state = "invalid", os = "invalid", shared = "invalid", version = "invalid", limit = "invalid", offset = "invalid", orderBy = "invalid";
        node.api.get("/peers?state="+state+"&os="+os+"&shared="+shared+"&version="+version+"&limit="+limit+"&offset="+offset+"orderBy="+orderBy)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.false;
                node.expect(res.body).to.have.property("error");
                done();
            });
    });
});

describe("GET /blocks/getHeight", function () {

    it("Should be ok", function (done) {
        node.api.get("/blocks/getHeight")
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                if (res.body.success == true && res.body.height != null) {
                    node.expect(res.body).to.have.property("height").to.be.above(0);
                    if (res.body.success == true) {
                        block.blockHeight = res.body.height;
                        if (res.body.height > 100) {
                            testBlocksUnder101 = true;
                        }
                    }
                } else {
                    console.log("Request failed or height is null");
                }
                done();
            });
    });
});

describe("GET /blocks/getFee", function () {

    it("Should be ok", function (done) {
        node.api.get("/blocks/getFee")
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                if (res.body.success == true && res.body.fee != null) {
                    node.expect(res.body).to.have.property("fee");
                    node.expect(res.body.fee).to.equal(node.Fees.transactionFee);
                } else {
                    console.log("Request failed or fee is null");
                }
                done();
            });
    });
});

describe("GET /blocks/getFees", function () {

    it.skip("Should be ok", function (done) {
        node.api.get("/blocks/getFees")
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
            // console.log(JSON.stringify(res.body));
            node.expect(res.body).to.have.property("success").to.be.true;
            if (res.body.success == true && res.body.fees != null) {
                node.expect(res.body).to.have.property("fees");
                node.expect(res.body.fees.send).to.equal(node.Fees.transactionFee);
                node.expect(res.body.fees.vote).to.equal(node.Fees.voteFee);
                node.expect(res.body.fees.dapp).to.equal(node.Fees.dappAddFee);
                node.expect(res.body.fees.secondsignature).to.equal(node.Fees.secondPasswordFee);
                node.expect(res.body.fees.delegate).to.equal(node.Fees.delegateRegistrationFee);
                node.expect(res.body.fees.multisignature).to.equal(node.Fees.multisignatureRegistrationFee);
            } else {
              console.log("Request failed or fees is null");
            }
            done();
          });
    });
});

describe("GET /blocks/getMagic", function () {

    it.skip("Get blockchain magic. Should be ok", function (done) {
        node.api.get("/blocks/getMagic")
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                if (res.body.success == true && res.body.magic != null) {
                    node.expect(res.body).to.have.property("magic");
                    node.expect(res.body.magic).to.equal(node.config.magic);
                } else {
                    console.log("Request failed or magic is null");
                }
                done();
            });
    });
});

describe("GET /blocks", function () {

    it("Using height. Should be ok", function (done) {
        var height = block.blockHeight, limit = 100, offset = 0;
        node.api.get("/blocks?height="+height+"&limit="+limit+"&offset="+offset)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                if (res.body.success == true && res.body.blocks != null) {
                    node.expect(res.body).to.have.property("blocks").that.is.an("array");
                    node.expect(res.body).to.have.property("count").to.equal(1);
                    node.expect(res.body.blocks.length).to.equal(1);
                    node.expect(res.body.blocks[0]).to.have.property("previousBlock");
                    node.expect(res.body.blocks[0]).to.have.property("totalAmount");
                    node.expect(res.body.blocks[0]).to.have.property("totalFee");
                    node.expect(res.body.blocks[0]).to.have.property("generatorId");
                    node.expect(res.body.blocks[0]).to.have.property("confirmations");
                    node.expect(res.body.blocks[0]).to.have.property("blockSignature");
                    node.expect(res.body.blocks[0]).to.have.property("numberOfTransactions");
                    node.expect(res.body.blocks[0].height).to.equal(block.blockHeight);
                    block.id = res.body.blocks[0].id;
                    block.generatorPublicKey = res.body.blocks[0].generatorPublicKey;
                    block.totalAmount = res.body.blocks[0].totalAmount;
                    block.totalFee = res.body.blocks[0].totalFee;
                } else {
                    console.log("Request failed or blocks array is null");
                }
                done();
            });
    });

    it("Using height < 100. Should be ok", function (done) {
        if (testBlocksUnder101) {
            var height = 10;
            node.api.get("/blocks?height="+height)
                .set("Accept", "application/json")
                .expect("Content-Type", /json/)
                .expect(200)
                .end(function (err, res) {
                    // console.log(JSON.stringify(res.body));
                    node.expect(res.body).to.have.property("success").to.be.true;
                    if (res.body.success == true && res.body.blocks != null) {
                        node.expect(res.body).to.have.property("count");
                        node.expect(res.body).to.have.property("blocks").that.is.an("array");
                        node.expect(res.body.blocks.length).to.equal(1);
                        node.expect(res.body.blocks[0]).to.have.property("previousBlock");
                        node.expect(res.body.blocks[0]).to.have.property("totalAmount");
                        node.expect(res.body.blocks[0]).to.have.property("totalFee");
                        node.expect(res.body.blocks[0]).to.have.property("generatorId");
                        node.expect(res.body.blocks[0]).to.have.property("confirmations");
                        node.expect(res.body.blocks[0]).to.have.property("blockSignature");
                        node.expect(res.body.blocks[0]).to.have.property("numberOfTransactions");
                        node.expect(res.body.blocks[0].height).to.equal(10);
                        block.id = res.body.blocks[0].id;
                        block.generatorPublicKey = res.body.blocks[0].generatorPublicKey;
                        block.totalAmount = res.body.blocks[0].totalAmount;
                        block.totalFee = res.body.blocks[0].totalFee;
                    } else {
                        console.log("Request failed or blocks array is null");
                    }
                    done();
                });
        } else {
            done();
        }
    });

    it("Using generatorPublicKey. Should be ok", function (done) {
        var generatorPublicKey = block.generatorPublicKey, limit = 100, offset = 0, orderBy = "";
        node.api.get("/blocks?generatorPublicKey="+generatorPublicKey+"&limit="+limit+"&offset="+offset)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("blocks").that.is.an("array");
                for (var i = 0; i < res.body.blocks.length; i++) {
                    node.expect(res.body.blocks[i].generatorPublicKey).to.equal(block.generatorPublicKey);
                }
                done();
            });
    });

    it("Using totalFee. Should be ok", function (done) {
        var totalFee = block.totalFee, limit = 100, offset = 0;
        node.api.get("/blocks?totalFee="+totalFee+"&limit="+limit+"&offset="+offset)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("blocks").that.is.an("array");
                for (var i = 0; i < res.body.blocks.length; i++) {
                    node.expect(res.body.blocks[i].totalFee).to.equal(block.totalFee);
                }
                done();
            });
    });

    it("Using totalAmount. Should be ok", function (done) {
        var totalAmount = block.totalAmount, limit = 100, offset = 0;
        node.api.get("/blocks?totalAmount="+totalAmount+"&limit="+limit+"&offset="+offset)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("blocks").that.is.an("array");
                for (var i = 0; i < res.body.blocks.length; i++) {
                    node.expect(res.body.blocks[i].totalAmount).to.equal(block.totalAmount);
                }
                done();
            });
    });

    it("Using previousBlock. Should be ok", function (done) {
        if (block.id != null) {
            var previousBlock = block.id;
            node.onNewBlock(function (err) {
                node.expect(err).to.be.not.ok;
                node.api.get("/blocks?previousBlock="+previousBlock)
                    .set("Accept", "application/json")
                    .expect("Content-Type", /json/)
                    .expect(200)
                    .end(function (err, res) {
                        // console.log(JSON.stringify(res.body));
                        node.expect(res.body).to.have.property("success").to.be.true;
                        node.expect(res.body).to.have.property("blocks").that.is.an("array");
                        node.expect(res.body.blocks).to.have.length(1);
                        node.expect(res.body.blocks[0].previousBlock).to.equal(previousBlock);
                        done();
                    });
            });
        }
    });

    it("Using orderBy. Should be ok", function (done) {
        var orderBy = "height:desc";
        node.api.get("/blocks?orderBy="+orderBy)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("blocks").that.is.an("array");
                for (var i = 0; i < res.body.blocks.length; i++) {
                    if (res.body.blocks[i+1] != null) {
                        node.expect(res.body.blocks[i].height).to.be.above(res.body.blocks[i+1].height);
                    }
                }
                done();
            });
    });
});

describe("GET /blocks/get?id=", function () {

    it("Using genesisblock id. Should be ok", function (done) {
        var genesisblockId = genesisblock.id;

        node.api.get("/blocks/get?id=" + genesisblockId)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.true;
                node.expect(res.body).to.have.property("block").to.be.a("object");
                node.expect(res.body.block).to.have.property("id").to.be.a("string");
                done();
            });
    });

    it("Using unknown id. Should be fail", function (done) {
        var unknownId = "9928719876370886655";

        node.api.get("/blocks/get?id=" + unknownId)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.false;
                node.expect(res.body).to.have.property("error").to.be.a("string");
                done();
            });
    });

    it("Using no id. Should be fail", function (done) {
        node.api.get("/blocks/get?id=" + null)
            .set("Accept", "application/json")
            .expect("Content-Type", /json/)
            .expect(200)
            .end(function (err, res) {
                // console.log(JSON.stringify(res.body));
                node.expect(res.body).to.have.property("success").to.be.false;
                node.expect(res.body).to.have.property("error").to.be.a("string");
                done();
            });
    });
});


text:
namespace ozonewayland {

class WaylandSurface;
class WaylandWindow;

class WaylandShellSurface {
 public:
  // Creates shell surface for a given WaylandWindow. This can be either
  // wl_shell, xdg_shell or any shell which supports wayland protocol.
  // Ownership is passed to the caller.
  static WaylandShellSurface* CreateShellSurface(WaylandWindow* window);
  WaylandShellSurface();
  virtual ~WaylandShellSurface();

  WaylandSurface* Surface() const { return surface_; }

  virtual void UpdateShellSurface(WaylandWindow::ShellType type,
                                  WaylandShellSurface* shell_parent,
                                  unsigned x,
                                  unsigned y) const = 0;
  virtual void SetWindowTitle(const base::string16& title) = 0;
  virtual void Maximize() const = 0;

  // static functions.
  static void PopupDone();
  static void WindowResized(void *data, unsigned width, unsigned height);

 protected:
  void FlushDisplay() const;
  // The implementation should initialize the shell and set up all
  // necessary callbacks.
  virtual void InitializeShellSurface(WaylandWindow* window) = 0;

 private:
  WaylandSurface* surface_;
  DISALLOW_COPY_AND_ASSIGN(WaylandShellSurface);
};

}  // namespace ozonewayland

#endif  // OZONE_WAYLAND_SHELL_SURFACE_H_

redpajama_set_name: RedPajamaGithub


text:
import Ember from 'ember';
import Form from 'aeonvera/mixins/components/edit-form';

export default Ember.Component.extend(Form, {
  modelName: 'pricing-tier',
  saveSuccessPath: 'events.show.pricing-tiers.show',
  cancelPath: 'events.show.pricing-tiers',
  /* used for creating / navigating */
  parentAssociation: 'event',
  parentId: 'event_id'

});


text:
title: "On CNN's Anderson Cooper discussing ISIS"
layout: page
---
I appeared on CNN's Anderson Cooper show discussing ISIS. Here's the [transcript](http://www.cnn.com/TRANSCRIPTS/1501/29/acd.01.html) (will post the video soon), and here's a [related article on CNN.com](http://www.cnn.com/2015/02/03/world/isis-execution-video/index.html)


text:
local uiGutModel = Ui(Ui.UI_GUTMODEL);

local IMAGE_HEAD		= "ImgHead";
local IMAGE_FOOT		= "ImgFoot";
local PROGRESS_TIME		= 10;

uiGutModel.Init=function(self)
	self.nLoadCompleted   	= 0;
	self.tbOpeningCallback	= {};
	self.tbEndingCallback	= {};
end

uiGutModel.OnOpen=function(self)
	UiManager:SwitchUiModel(2);
end

uiGutModel.OnClose=function(self)
    UiManager:SwitchUiModel(0);
end

uiGutModel.Opening=function(self)	-- ¿ªÄ»
    Prg_SetTime(self.UIGROUP, IMAGE_HEAD, PROGRESS_TIME, 0);
    Prg_SetTime(self.UIGROUP, IMAGE_FOOT, PROGRESS_TIME, 0);
end

uiGutModel.Ending=function(self)	-- лĻ
	Prg_SetTime(self.UIGROUP, IMAGE_HEAD, PROGRESS_TIME, 1);
	Prg_SetTime(self.UIGROUP, IMAGE_FOOT, PROGRESS_TIME, 1);
end

uiGutModel.OnProgressFull=function(self, szWnd)
    if (szWnd == IMAGE_FOOT) then
        if self.nLoadCompleted == 0 then
        	for _, tbCall in ipairs(self.tbOpeningCallback) do
        		Lib:CallBack({ tbCall[2], tbCall[1], tbCall[3] });
        	end
        	self.tbOpeningCallback = {};
            self.nLoadCompleted = 1;
        else
            for _, tbCall in ipairs(self.tbEndingCallback) do
				Lib:CallBack({ tbCall[2], tbCall[1], tbCall[3] });
        	end
        	self.tbEndingCallback = {};
            UiManager:CloseWindow(self.UIGROUP);
            self.nLoadCompleted = 0;
        end
    end
end

-- ¾çÇéģʽµÄÈë¿Úº¯Êý
uiGutModel.GutBegin=function(self, varTable, varFunc, tbParam)
	if varTable and varFunc then
		table.insert(self.tbOpeningCallback, { varTable, varFunc, tbParam });
	end
--	if UiManager:WindowVisible(self.UIGROUP) ~= 1 then
--		UiManager:OpenWindow(self.UIGROUP);
--		self:Opening();
--	else
		self.nLoadCompleted = 0;
		Prg_SetTime(self.UIGROUP, IMAGE_HEAD, 0);
		self:OnProgressFull(IMAGE_FOOT)
		Prg_SetTime(self.UIGROUP, IMAGE_FOOT, 0);
--	end
end

uiGutModel.GutEnd=function(self, varTable, varFunc, tbParam)
	if varTable and varFunc then
		table.insert(self.tbEndingCallback, { varTable, varFunc, tbParam });
	end
	self:Ending();
end


text:
module Corkboard
  class Engine < ::Rails::Engine
    isolate_namespace Corkboard
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

	<form action="/comment/reply/161127" accept-charset="UTF-8" method="post" id="comment-form">

				Név:
				JohnDoe

				Hozzászólás: *

						<textarea cols="60" rows="15" name="comment" id="edit-comment" class="form-textarea resizable required processed html">--
							<a href="http://hupper.ajnasz.hu">HUP Firefox extension</a> | <a href="https://github.com/Ajnasz/hupper/issues">Hupper hibajelentés</a></textarea>

Engedélyezett HTML elemek: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <center> <hr> <del> <q> <blockquote>

BBCode jelölők használata engedélyezett, az URL-ek automatikusan linkké alakulnak

A sorokat és bekezdéseket automatikusan felismeri a rendszer.

További információ a formázási lehetőségekről

			<input name="form_token" id="edit-form-token" value="00000000000000000000000000000000" type="hidden">
			<input name="form_id" id="edit-comment-form" value="comment_form" type="hidden">
			<input name="op" id="edit-preview" value="Előnézet" class="form-submit" type="submit">

	</form>


text:
<?php

namespace MariusMandal\YrBundle\Entity;
use stdClass;

class Credit {
	private $comment;
	private $link;

	public function __construct( $raw_xml ) {
		$this->setComment( XMLformatter::toString( $raw_xml->credit->comment ) );

		$attributes = $raw_xml->credit->link->attributes();
		$this->setLink( XMLformatter::toString( $attributes->url ), XMLformatter::toString( $attributes->text ) );
	}

	public function setComment( $comment ) {
		$this->comment = $comment;
	}
	public function getComment() {
		return $this->comment;
	}

	public function setLink( $url, $text ) {
		$this->link = new stdClass();
		$this->link->url = $url;
		$this->link->text = $text;
	}
	public function getLink() {
		return $this->link;
	}
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M1.85,22.8V12.725H22.15V22.8ZM1.85,11.275V1.2H22.15V11.275Z"/>
</vector>


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TravelAgency.BLL.BLL;

namespace TravelAgency.DAL.Tests
{
    [TestClass]
    public class OfferTest
    {
        private static TravelAgencyService service;
        [ClassInitialize]
        public static void ClassInitialize(TestContext context)
        {
            service = new TravelAgencyService();
        }
        [ClassCleanup]
        public static void ClassCleanup()
        {
            service.Dispose();
        }
        [TestMethod]
        public void ReserveOffer()
        {
            service.ClearReservationTables();
            service.Save();

            bool actual = service.IsOfferReserved(1, 1, 1);
            Assert.IsFalse(actual);

            // Reserve attraction
            service.ReserveOffer(1, 1, 1);
            actual = service.IsOfferReserved(1, 1, 1);
            Assert.IsTrue(actual);

        }
        [TestMethod]
        public void ReserveAttraction()
        {
            service.ClearReservationTables();
            service.Save();

            bool actual = service.IsAttractionReserved(1, 1, 1);
            Assert.IsFalse(actual);

            service.ReserveOffer(19, 1, 1);
            // Reserve attraction
            service.ReserveAttraction(1, 1, 1);
            actual = service.IsAttractionReserved(1, 1, 1);
            Assert.IsTrue(actual);
        }

    }
}


text:
import Wrapper from '../wrapper';
import * as Radio from 'radio';

var modalChannel = Radio.channel('modal');
var overlayChannel = Radio.channel('overlay');

var ModalWrapper = Wrapper.extend({
  template: 'modalWrapper',

  className: 'modal-wrapper',

  ui: {
    close: '.close'
  },

  events: {
    'click @ui.close': 'destroyView'
  },

  region: '.modal-window',

  initialize() {
    this.listenTo(overlayChannel, 'click', this.destroyView);
    modalChannel.comply({
      show: this.showView,
      hide: this.destroyView
    }, this);
  },

  onShowView(view) {
    overlayChannel.command('show');
    this.$el.addClass('show');
  },

  onBeforeDestroyView() {
    overlayChannel.command('hide');
    this.$el.removeClass('show');
  }
});

var modalWrapper = new ModalWrapper();
modalWrapper.render();

var body = document.getElementsByTagName('body')[0];
body.appendChild(modalWrapper.el);

export default modalWrapper;


text:
package versioned.host.exp.exponent.modules.api.components.maps;

import com.facebook.react.bridge.ReactApplicationContext;
import com.google.android.gms.maps.GoogleMapOptions;

public class AirMapLiteManager extends AirMapManager {

    private static final String REACT_CLASS = "AIRMapLite";

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

    public AirMapLiteManager(ReactApplicationContext context) {
        super(context);
        this.googleMapOptions = new GoogleMapOptions().liteMode(true);
    }

}


text:
asdf plugin-add ruby https://github.com/asdf-vm/asdf-ruby.git

asdf plugin-add nodejs https://github.com/asdf-vm/asdf-nodejs.git
bash ~/.asdf/plugins/nodejs/bin/import-release-team-keyring

asdf plugin-add elm https://github.com/vic/asdf-elm.git

asdf plugin-add erlang https://github.com/asdf-vm/asdf-erlang.git
asdf plugin-add elixir https://github.com/asdf-vm/asdf-elixir.git


text:
package graph.math;

/**
 * A line defined with k and n parameters, where y=k*x +n
 * @author Renata
 */
public class Line {

	private Double k;
	private Double n;

	/**
	 * Constructs a line given k and n parameters
	 * @param k k line parameter
	 * @param n n line parameter
	 */
	public Line(Double k, Double n) {
		super();
		this.k = k;
		this.n = n;
	}

	/**
	 * @return k parameter
	 */
	public Double getK() {
		return k;
	}

	/**
	 * @param k k value to set
	 */
	public void setK(Double k) {
		this.k = k;
	}

	/**
	 * @return n parameter
	 */
	public Double getN() {
		return n;
	}

	/**
	 * @param n n value to set
	 */
	public void setN(Double n) {
		this.n = n;
	}

	@Override
	public String toString() {
		return "Line [k=" + k + ", n=" + n + "]";
	}
}


text:
package br.gov.sibbr.json.response.eol;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class EOLAudio extends EOLDataObject {

	private String eolMediaURL;
	private String mediaURL;

	/**
	 *
	 * @param identifier
	 * @param dataObjectVersionID
	 * @param dataType
	 * @param vettedStatus
	 * @param dataRating
	 * @param mimeType
	 * @param title
	 * @param language
	 * @param license
	 * @param rights
	 * @param rightsHolder
	 * @param source
	 * @param description
	 * @param mediaURL
	 * @param eolMediaURL
	 * @param agents
	 */
	public EOLAudio(String identifier, String dataObjectVersionID,
			String dataType, String vettedStatus, String dataRating,
			String mimeType, String title, String language, String license,
			String rights, String rightsHolder, String source,
			String description, String mediaURL, String eolMediaURL,
			List<EOLAgent> agents) {
		setIdentifier(identifier);
		setDataObjectVersionID(dataObjectVersionID);
		setDataType(dataType);
		setVettedStatus(vettedStatus);
		setDataRating(dataRating);
		setMimeType(mimeType);
		setTitle(title);
		setLanguage(language);
		setLicense(license);
		setRights(rights);
		setRightsHolder(rightsHolder);
		setSource(source);
		setDescription(description);
		setMediaURL(mediaURL);
		setEolMediaUrl(eolMediaURL);
		setAgents(agents);
	}

	public static ArrayList<EOLAudio> processJSON(JSONArray json) {
		ArrayList<EOLAudio> images = new ArrayList<EOLAudio>();
		try {
			for (int i = 0; i < json.length(); i++) {
				JSONObject item = (JSONObject) json.get(i);
				// Check object has mime type:
				if (!item.isNull("mimeType")) {
					String mime = (String) item.get("mimeType");
					// Ensure lower case:
					mime = mime.toLowerCase();
					// Check this is an audio object:
					if (mime.contains("ogg") || mime.contains("mp3")
							|| mime.contains("wav") || mime.contains("mp4")) {
						String identifier = "";
						if (!item.isNull("identifier"))
							identifier = (String) item.get("identifier");

						String dataObjectVersionID = "";
						if (!item.isNull("dataObjectVersionID"))
							dataObjectVersionID = item.get(
									"dataObjectVersionID").toString();

						String dataType = "";
						if (!item.isNull("dataType"))
							dataType = (String) item.get("dataType");

						String vettedStatus = "";
						if (!item.isNull("vettedStatus"))
							vettedStatus = item.get("vettedStatus").toString();

						String dataRating = "";
						if (!item.isNull("dataRating"))
							dataRating = item.get("dataRating").toString();

						String mimeType = "";
						if (!item.isNull("mimeType"))
							mimeType = (String) item.get("mimeType");

						String title = "";
						if (!item.isNull("title"))
							title = (String) item.get("title");

						String language = "";
						if (!item.isNull("language"))
							language = (String) item.get("language");

						String license = "";
						if (!item.isNull("license"))
							license = (String) item.get("license");

						String rights = "";
						if (!item.isNull("rights"))
							rights = (String) item.get("rights");

						String rightsHolder = "";
						if (!item.isNull("rightsHolder"))
							rightsHolder = (String) item.get("rightsHolder");

						String source = "";
						if (!item.isNull("source"))
							source = (String) item.get("source");

						String description = "";
						if (!item.isNull("description"))
							description = (String) item.get("description");

						String mediaUrl = "mediaURL";
						if (!item.isNull("mediaURL"))
							mediaUrl = (String) item.get("mediaURL");

						String eolMediaUrl = "";
						if (!item.isNull("eolMediaURL"))
							eolMediaUrl = (String) item.get("eolMediaURL");

						List<EOLAgent> agents = null;
						if (!item.isNull("agents"))
							agents = EOLAgent.processJSON((JSONArray) item
									.getJSONArray("agents"));

						// Create new EOLImage and add to list:
						images.add(new EOLAudio(identifier,
								dataObjectVersionID, dataType, vettedStatus,
								dataRating, mimeType, title, language, license,
								rights, rightsHolder, source, description,
								mediaUrl, eolMediaUrl, agents));
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return images;
	}

	/**
	 * Default toString method
	 */
	public String toString() {
		String output = "\n";
		output += " title: " + getTitle();
		output += " eolMediaUrl: " + getEolMediaUrl();
		output += " mediaURL: " + getMediaURL();
		output += super.toString();
		return output;
	}

	/**
	 * @return the eolThumbnail
	 */
	public String getEolMediaUrl() {
		return eolMediaURL;
	}

	/**
	 * @param eolMediaUrl
	 *            the eolThumbnail to set
	 */
	public void setEolMediaUrl(String eolMediaUrl) {
		this.eolMediaURL = eolMediaUrl;
	}

	/**
	 * @return the mediaURL
	 */
	public String getMediaURL() {
		return mediaURL;
	}

	/**
	 * @param mediaURL
	 *            the mediaURL to set
	 */
	public void setMediaURL(String mediaURL) {
		this.mediaURL = mediaURL;
	}
}


text:
/* jslint node: true */
'use strict';

var _ = require('lodash');

_.noConflict();

function typeName(bold, italics) {
	var type = 'normal';
	if (bold && italics) {
		type = 'bolditalics';
	} else if (bold) {
		type = 'bold';
	} else if (italics) {
		type = 'italics';
	}
	return type;
}

function FontProvider(fontDescriptors, pdfDoc) {
	this.fonts = {};
	this.pdfDoc = pdfDoc;
	this.fontCache = {};

	for (var font in fontDescriptors) {
		if (fontDescriptors.hasOwnProperty(font)) {
			var fontDef = fontDescriptors[font];

			this.fonts[font] = {
				normal: fontDef.normal,
				bold: fontDef.bold,
				italics: fontDef.italics,
				bolditalics: fontDef.bolditalics
			};
		}
	}
}

FontProvider.prototype.provideFont = function (familyName, bold, italics) {
	var type = typeName(bold, italics);
	if (!this.fonts[familyName] || !this.fonts[familyName][type]) {
		throw new Error('Font \'' + familyName + '\' in style \'' + type + '\' is not defined in the font section of the document definition.');
	}

	this.fontCache[familyName] = this.fontCache[familyName] || {};

	if (!this.fontCache[familyName][type]) {
		var def = this.fonts[familyName][type];
		if (!Array.isArray(def)) {
			def = [def];
		}
		this.fontCache[familyName][type] = this.pdfDoc.font.apply(this.pdfDoc, def)._font;
	}

	return this.fontCache[familyName][type];
};

module.exports = FontProvider;


text:
import paramiko
import requests
import sys
import time
import threading
import os
import logging

from paramiko import SSHException
from termcolor import colored

logger = logging.getLogger('MasterSSH')
logger.setLevel(logging.INFO)
logging.basicConfig(format='[%(asctime)s] %(threadName)s: %(message)s', datefmt='%Y/%m/%d %H:%M:%S')

class MasterSSH:
    connection_pool = {}
    selected_servers = []
    credentials = []
    config = None

    commandPool = []

    """
    Initalize everything
    """

    def __init__(self, args):
        # Set logging to debug
        if args.verbose:
            logger.setLevel(logging.DEBUG)

        self.config = args

        cred_source_type = None
        cred_source_path = None

        # Validate that file exists and assign it as credentials source
        if args.cred_file:
            if os.path.isfile(args.cred_file):
                cred_source_path = args.cred_file
                cred_source_type = 'file'
            else:
                self.print_error("%s does not exist!" % args.cred_file)
                sys.exit(1)

        # Assign URL as credentials source
        if args.cred_url:
            cred_source_path = args.cred_url
            cred_source_type = 'url'

        # If there are specific servers selected, store their names
        if args.servers:
            self.selected_servers = args.servers.strip().split(',')

        # If credentials path has not been defined, show an error
        if cred_source_path and args.manual:
            self.print_error("You need to specify a credentials getting method [--cred-url, --cred-file, --manual]")
            sys.exit(1)

        # If credentials source is file, pull info from it
        if cred_source_type == 'file':
            with open(cred_source_path, 'r') as f:
                for line in f.readlines():
                    data = line.strip().split(',')

                    self.credentials.append({
                        'name': data[0],
                        'host': data[1],
                        'username': data[2],
                        'password': data[3]
                    })

        # If credentials source is an URL, download the data
        if cred_source_type == 'url':
            try:
                request = requests.get(cred_source_path)
            except requests.ConnectionError:
                self.print_error("Failed to download data! Please check your URL.")
                sys.exit(1)
            except requests.HTTPError:
                self.print_error("Bad HTTP request!")
                sys.exit(1)
            except requests.Timeout:
                self.print_error("Connection to your domain timed out, please check your server!")
                sys.exit(1)
            except requests.TooManyRedirects:
                self.print_error("There are too many redirects for your URL, check your server configuration!")
                sys.exit(1)
            except Exception as e:
                self.print_error("Something went wrong!")
                self.print_exception(e)
                sys.exit(1)

            response = request.text.strip()

            if request.status_code not in [200, 301, 302]:
                self.print_error("%s did not respond correctly: %s!" % (cred_source_path, request.status_code))
                sys.exit(1)

            if response == "":
                self.print_error("%s does not contain any data!" % cred_source_path)
                sys.exit(1)

            for line in response.split('\n'):
                data = line.split(',')

                if len(data) == 4:
                    self.credentials.append({
                        'name': data[0].strip(),
                        'host': data[1].strip(),
                        'username': data[2].strip(),
                        'password': data[3].strip()
                    })

    """
    Create connection threads
    """

    def create_connections(self):
        if self.credentials:
            self.print_message("Connecting to %s servers..." % len(self.credentials))

        thread_pool = {}
        thread_pos = 1
        use_selected_servers = False

        if len(self.selected_servers) > 0:
            use_selected_servers = True

        for cred in self.credentials:
            # If there are specific servers user wants to use, use them ...
            if use_selected_servers:
                if cred['name'] in self.selected_servers:
                    thread_pool[thread_pos] = threading.Thread(target=self.connect, name=cred['name'], args=(cred['name'], cred['host'], cred['username'], cred['password'], self.config.port, self.config.connection_timeout))
                    thread_pool[thread_pos].daemon = True
                    thread_pool[thread_pos].start()
                    thread_pos += 1

            # ... if not, use all of them
            else:
                thread_pool[thread_pos] = threading.Thread(target=self.connect, name=cred['name'], args=(cred['name'], cred['host'], cred['username'], cred['password'], self.config.port, self.config.connection_timeout))
                thread_pool[thread_pos].daemon = True
                thread_pool[thread_pos].start()
                thread_pos += 1

        for i in range(1, thread_pos):
            thread_pool[i].join()

        self.print_success("Welcome to master-ssh!")

    """
    Connect to the server
    """

    def connect(self, name, host, username, password, port, timeout):
        tries = 1
        max_tries = self.config.max_retries

        while tries <= max_tries:
            try:
                client = paramiko.SSHClient()
                client.set_log_channel('SSHClient')
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(host, username=username, password=password, port=port, timeout=timeout)
                client.get_transport().set_keepalive(30)

                self.connection_pool[name] = client
                self.print_success("Successfully connected!")

                return
            except paramiko.ssh_exception.AuthenticationException:
                self.print_error("Failed to connect - Wrong login details!")
                return
            except Exception as e:
                self.print_error("Failed to connect! Retrying (%s/%s)" % (tries, max_tries))
                self.print_exception(e)

                tries += 1
                time.sleep(self.config.retry_delay)

        self.print_error("Unable to connect, giving up!")

    """
    Create connection closing threads
    """

    def close_connections(self):
        thread_pool = {}
        thread_pos = 1

        for name in self.connection_pool:
            thread_pool[thread_pos] = threading.Thread(target=self.exit, name=name, args=(name,))
            thread_pool[thread_pos].daemon = True
            thread_pool[thread_pos].start()
            thread_pos += 1

        for i in range(1, thread_pos):
            thread_pool[i].join()

        self.print_success("Bye, bye!")

    """
    Close all open connections
    """

    def exit(self, name):
        try:
            if self.connection_pool[name].get_transport():
                if self.connection_pool[name].get_transport().is_active():
                    self.connection_pool[name].exec_command('exit', timeout=self.config.exit_timeout)
        except Exception as e:
            self.print_exception(e)

        self.connection_pool[name].close()
        self.print_action("Disconnected!")

    """
    Listen for user commands
    """

    def listen(self):

        while True:
            # Listen for user input
            try:
                cmd = input('master-ssh$ ').strip()
            except KeyboardInterrupt:
                self.close_connections()
                break

            if cmd == "":
                self.print_error('Please enter your command!')
            elif cmd == "exit":
                self.close_connections()
                break
            else:

                # Check for internal commands
                if cmd.startswith('#'):

                    """
                    INTERNAL COMMANDS
                    """

                    if cmd == "#help" or cmd == "#":
                        print('{: <5}'.format('Welcome to MasterSSH!'))
                        print('Made by Jaan Porkon')
                        print('https://github.com/JaanPorkon/master-ssh')
                        print('')
                        print('Examples:')
                        print('')
                        print('{param: <55}{help}'.format(param='#list', help='Lists all connections.'))
                        print('{param: <55}{help}'.format(param='#connect [host] [user] [password] [port] [name]', help='Connects to a new server. Port and name are optional!'))
                        print('{param: <55}{help}'.format(param='#disconnect [host]', help='Disconnects the host.'))
                        print('{param: <55}{help}'.format(param='#ignore [host,host2,...] [command]', help='Does not send a command to ignored servers.'))
                        print('')

                    # List all connections
                    elif cmd == "#list":
                        for name, connection in self.connection_pool.items():
                            is_alive = connection.get_transport().is_active()

                            if is_alive:
                                self.print_action("%s is active!" % name)
                            else:
                                self.print_server_error("%s is disconnected!" % name)

                    elif cmd.startswith('#connect'):
                        data = cmd.replace('#connect', '').strip().split(' ')
                        data_length = len(data)

                        if data_length < 3:
                            self.print_error('Not enough arguments! Use: #connect [host] [user] [password] [port] [name] - port and name are optional!')
                        else:
                            fields = {'host': data[0], 'user': data[1], 'password': data[2], 'port': int(self.config.port), 'name': data[0]}

                            if data_length == 4:
                                fields['port'] = int(data[3])
                            elif data_length == 5:
                                fields['port'] = int(data[3])
                                fields['name'] = data[4]

                            self.connect(fields['name'], fields['host'], fields['user'], fields['password'], fields['port'])

                    # Disconnect specific servers from the pool
                    elif cmd.startswith('#disconnect'):
                        servers = cmd.replace('#disconnect', '').strip()

                        for server in servers.split(','):
                            if server in self.connection_pool:
                                server = server.strip()
                                connection = self.connection_pool[server]

                                try:
                                    if connection.get_transport().is_active():
                                        connection.exec_command('exit', timeout=self.config.exit_timeout)
                                        connection.close()

                                        self.connection_pool.pop(server)
                                        self.print_success("%s successfully disconnected!" % server)
                                    else:
                                        self.connection_pool.pop(server)

                                except Exception as e:
                                    self.print_error('Unable to disconnect: %s!' % server)
                                    self.print_exception(e)

                            else:
                                self.print_error("%s does not exist!" % server)

                        if len(self.connection_pool) == 0:
                            self.print_message("Connection pool is empty, closing the program..")
                            sys.exit(0)

                    else:

                        """
                        SERVER COMMANDS
                        """

                        # If user wishes to ignore specific servers, do so ...
                        use_ignore_list = cmd.startswith("#ignore")
                        ignored_server_list = []

                        servers, command = cmd.replace('#ignore ', '').split(' ', 1)

                        for server in servers.split(','):
                            ignored_server_list.append(server)

                        thread_pool = {}
                        thread_pos = 1

                        if use_ignore_list:
                            for name, connection in self.connection_pool.items():
                                if name not in ignored_server_list:
                                    thread_pool[thread_pos] = threading.Thread(target=self.execute, name=name, args=(command.strip(), connection, int(self.config.cmd_timeout)))
                                    thread_pool[thread_pos].daemon = True
                                    thread_pool[thread_pos].start()
                                    thread_pos += 1
                        else:
                            for name, connection in self.connection_pool.items():
                                thread_pool[thread_pos] = threading.Thread(target=self.execute, name=name, args=(command.strip(), connection, int(self.config.cmd_timeout)))
                                thread_pool[thread_pos].daemon = True
                                thread_pool[thread_pos].start()
                                thread_pos += 1

                        for i in range(1, thread_pos):
                            thread_pool[i].join()

                # If user haven't defined any internal commands, send user's command to all of the servers
                else:
                    if len(self.connection_pool) == 0:
                        self.print_error('There are no active connections!')
                    else:
                        thread_pool = {}
                        thread_pos = 1

                        for name, connection in self.connection_pool.items():
                            thread_pool[thread_pos] = threading.Thread(target=self.execute, name=name, args=(cmd, connection, int(self.config.cmd_timeout)))
                            thread_pool[thread_pos].daemon = True
                            thread_pool[thread_pos].start()
                            thread_pos += 1

                        for i in range(1, thread_pos):
                            thread_pool[i].join()

    """
    Execute user's command
    """

    def execute(self, cmd, connection, timeout):
        try:
            stdin, stdout, stderr = connection.exec_command(cmd, timeout=timeout)

            error = ""

            for line in stderr:
                error += '%s\n' % line.strip()

            error = error.strip()

            if error != "":
                self.print_server_error(error)

            response = ""

            for line in stdout:
                response += '%s\n' % line.strip()

            response = response.strip()

            if response != "":
                self.print_server_action(response)
        except SSHException as e:
            self.print_error('Unable to execute the command!')
            self.print_exception(e)
        except Exception as e:
            self.print_error('Something went wrong!')
            self.print_exception(e)

    """
    Helper methods
    """

    def print_message(self, message):
        logger.info(colored(message, color='green'))

    def print_action(self, message):
        logger.info(colored(message, color='green'))

    def print_success(self, message):
        logger.info(colored(message, color='green'))

    def print_error(self, message):
        logger.error(colored(message, on_color='on_red', attrs=['bold']))

    def print_exception(self, err):
        logger.exception(err)

    def print_server_action(self, message):
        logger.info('\n%s' % colored(message, color='green'))

    def print_server_error(self, message):
        logger.error('\n%s' % colored(message, on_color='on_red', attrs=['bold']))


text:
Styx history synchronizer
=========================

Project status: development.

# Protocol
Server and client uses custom protocol based on protobuf. To generate protobuf
code for client and server, use `styx-messages/Build-Protobuf.ps1` file.

# Server
Styx server is written in Scala. It listens on 6060 port (default) for
incoming client connections.

## Running
To run the server, install `sbt` and use

    $ sbt run

# Client
For now, the only client is Miranda NG plugin.

## Building

### Compiler

Current client code is compatible only with MSVS IDE.

### Libraries

You'll need a boost logging library.

### Process

First of all, if you not plan to debug your code inside IDE, you're
free to disable the post-build action. Then, build projects as always.

## Using
Copy `*.dll` and `*.pdb` files to folder `Miranda/Plugins`. Start Miranda and
use main menu command `Enable Styx`.


text:
module Hyalite
  class SimpleEventPlugin
    EVENT_TYPES = {
      blur: {
        phasedRegistrationNames: {
          bubbled: :onBlur,
          captured: :onBlurCapture
        }
      },
      click: {
        phasedRegistrationNames: {
          bubbled: :onClick,
          captured: :onClickCapture
        }
      },
      contextMenu: {
        phasedRegistrationNames: {
          bubbled: :onContextMenu,
          captured: :onContextMenuCapture
        }
      },
      copy: {
        phasedRegistrationNames: {
          bubbled: :onCopy,
          captured: :onCopyCapture
        }
      },
      cut: {
        phasedRegistrationNames: {
          bubbled: :onCut,
          captured: :onCutCapture
        }
      },
      doubleClick: {
        phasedRegistrationNames: {
          bubbled: :onDoubleClick,
          captured: :onDoubleClickCapture
        }
      },
      drag: {
        phasedRegistrationNames: {
          bubbled: :onDrag,
          captured: :onDragCapture
        }
      },
      dragEnd: {
        phasedRegistrationNames: {
          bubbled: :onDragEnd,
          captured: :onDragEndCapture
        }
      },
      dragEnter: {
        phasedRegistrationNames: {
          bubbled: :onDragEnter,
          captured: :onDragEnterCapture
        }
      },
      dragExit: {
        phasedRegistrationNames: {
          bubbled: :onDragExit,
          captured: :onDragExitCapture
        }
      },
      dragLeave: {
        phasedRegistrationNames: {
          bubbled: :onDragLeave,
          captured: :onDragLeaveCapture
        }
      },
      dragOver: {
        phasedRegistrationNames: {
          bubbled: :onDragOver,
          captured: :onDragOverCapture
        }
      },
      dragStart: {
        phasedRegistrationNames: {
          bubbled: :onDragStart,
          captured: :onDragStartCapture
        }
      },
      drop: {
        phasedRegistrationNames: {
          bubbled: :onDrop,
          captured: :onDropCapture
        }
      },
      focus: {
        phasedRegistrationNames: {
          bubbled: :onFocus,
          captured: :onFocusCapture
        }
      },
      focusin: {
        phasedRegistrationNames: {
          bubbled: :onFocusIn,
          captured: :onFocusInCapture
        }
      },
      focusout: {
        phasedRegistrationNames: {
          bubbled: :onFocusOut,
          captured: :onFocusOutCapture
        }
      },
      input: {
        phasedRegistrationNames: {
          bubbled: :onInput,
          captured: :onInputCapture
        }
      },
      keyDown: {
        phasedRegistrationNames: {
          bubbled: :onKeyDown,
          captured: :onKeyDownCapture
        }
      },
      keyPress: {
        phasedRegistrationNames: {
          bubbled: :onKeyPress,
          captured: :onKeyPressCapture
        }
      },
      keyUp: {
        phasedRegistrationNames: {
          bubbled: :onKeyUp,
          captured: :onKeyUpCapture
        }
      },
      load: {
        phasedRegistrationNames: {
          bubbled: :onLoad,
          captured: :onLoadCapture
        }
      },
      error: {
        phasedRegistrationNames: {
          bubbled: :onError,
          captured: :onErrorCapture
        }
      },
      mouseDown: {
        phasedRegistrationNames: {
          bubbled: :onMouseDown,
          captured: :onMouseDownCapture
        }
      },
      mouseMove: {
        phasedRegistrationNames: {
          bubbled: :onMouseMove,
          captured: :onMouseMoveCapture
        }
      },
      mouseOut: {
        phasedRegistrationNames: {
          bubbled: :onMouseOut,
          captured: :onMouseOutCapture
        }
      },
      mouseOver: {
        phasedRegistrationNames: {
          bubbled: :onMouseOver,
          captured: :onMouseOverCapture
        }
      },
      mouseUp: {
        phasedRegistrationNames: {
          bubbled: :onMouseUp,
          captured: :onMouseUpCapture
        }
      },
      paste: {
        phasedRegistrationNames: {
          bubbled: :onPaste,
          captured: :onPasteCapture
        }
      },
      reset: {
        phasedRegistrationNames: {
          bubbled: :onReset,
          captured: :onResetCapture
        }
      },
      scroll: {
        phasedRegistrationNames: {
          bubbled: :onScroll,
          captured: :onScrollCapture
        }
      },
      submit: {
        phasedRegistrationNames: {
          bubbled: :onSubmit,
          captured: :onSubmitCapture
        }
      },
      touchCancel: {
        phasedRegistrationNames: {
          bubbled: :onTouchCancel,
          captured: :onTouchCancelCapture
        }
      },
      touchEnd: {
        phasedRegistrationNames: {
          bubbled: :onTouchEnd,
          captured: :onTouchEndCapture
        }
      },
      touchMove: {
        phasedRegistrationNames: {
          bubbled: :onTouchMove,
          captured: :onTouchMoveCapture
        }
      },
      touchStart: {
        phasedRegistrationNames: {
          bubbled: :onTouchStart,
          captured: :onTouchStartCapture
        }
      },
      wheel: {
        phasedRegistrationNames: {
          bubbled: :onWheel,
          captured: :onWheelCapture
        }
      }
    }

    TOP_LEVEL_EVENTS_TO_DISPATCH_CONFIG = {
      topBlur: EVENT_TYPES[:blur],
      topClick: EVENT_TYPES[:click],
      topContextMenu: EVENT_TYPES[:contextMenu],
      topCopy: EVENT_TYPES[:copy],
      topCut: EVENT_TYPES[:cut],
      topDoubleClick: EVENT_TYPES[:doubleClick],
      topDrag: EVENT_TYPES[:drag],
      topDragEnd: EVENT_TYPES[:dragEnd],
      topDragEnter: EVENT_TYPES[:dragEnter],
      topDragExit: EVENT_TYPES[:dragExit],
      topDragLeave: EVENT_TYPES[:dragLeave],
      topDragOver: EVENT_TYPES[:dragOver],
      topDragStart: EVENT_TYPES[:dragStart],
      topDrop: EVENT_TYPES[:drop],
      topError: EVENT_TYPES[:error],
      topFocus: EVENT_TYPES[:focus],
      topFocusIn: EVENT_TYPES[:focusin],
      topFocusOut: EVENT_TYPES[:focusout],
      topInput: EVENT_TYPES[:input],
      topKeyDown: EVENT_TYPES[:keyDown],
      topKeyPress: EVENT_TYPES[:keyPress],
      topKeyUp: EVENT_TYPES[:keyUp],
      topLoad: EVENT_TYPES[:load],
      topMouseDown: EVENT_TYPES[:mouseDown],
      topMouseMove: EVENT_TYPES[:mouseMove],
      topMouseOut: EVENT_TYPES[:mouseOut],
      topMouseOver: EVENT_TYPES[:mouseOver],
      topMouseUp: EVENT_TYPES[:mouseUp],
      topPaste: EVENT_TYPES[:paste],
      topReset: EVENT_TYPES[:reset],
      topScroll: EVENT_TYPES[:scroll],
      topSubmit: EVENT_TYPES[:submit],
      topTouchCancel: EVENT_TYPES[:touchCancel],
      topTouchEnd: EVENT_TYPES[:touchEnd],
      topTouchMove: EVENT_TYPES[:touchMove],
      topTouchStart: EVENT_TYPES[:touchStart],
      topWheel: EVENT_TYPES[:wheel]
    }

    def initialize
      TOP_LEVEL_EVENTS_TO_DISPATCH_CONFIG.each do |type, dispatch_config|
        dispatch_config[:dependencies] = [type]
      end
    end

    def event_types
      EVENT_TYPES
    end

    def extract_event(top_level_type, top_level_target, top_level_target_id, event)
      dispatch_config = TOP_LEVEL_EVENTS_TO_DISPATCH_CONFIG[top_level_type]
      return [] unless dispatch_config

      SyntheticEvent.new(event).tap do |synthetic_event|
        InstanceHandles.traverse_two_phase(top_level_target_id) do |target_id, upwards|
          listener = BrowserEvent.listener_at_phase(target_id, dispatch_config, upwards ? :bubbled : :captured)
          synthetic_event.add_listener(listener, target_id) if listener
        end
      end
    end
  end
end


text:
/* @flow */

const path = require('path');

if (!process.env.PRODUCT_DIR) {
  throw new Error('No PRODUCT_DIR set.');
}

// Try to load the context...
try {
  module.exports = Object.freeze(
    // noFlow
    require( // eslint-disable-line import/no-dynamic-require, global-require
      path.join(
        process.env.PRODUCT_DIR,
        'context.json',
      ),
    ),
  );
} catch (e) {
  throw new Error('Could not load context.json');
}


text: export { Query as default } from "./";


text:
<?php

/**
 * twSubscriptionMailQueue module helper.
 *
 * @package    subscription
 * @subpackage twSubscriptionMailQueue
 * @author     Your name here
 */
class twSubscriptionMailQueueGeneratorHelper extends BaseTwSubscriptionMailQueueGeneratorHelper
{
}


text:
class AbstractProcessor:

    def onPropertyModified(self, descriptor, oldValue, newValue):
        """ generated source for method onPropertyModified """

    def init(self, context):
        """ generated source for method init """

    def process(self, context, records):
        """ generated source for method process """


text:
// Copyright 2019-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIKit.h>

#import "MDCAvailability.h"
#import "MDCButton.h"
#import "MDCAlertController.h"
#import "UIFont+MaterialScalable.h"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wprivate-header"
#import "MDCDialogShadowedView.h"
#import "UIColor+MaterialDynamic.h"
#import "MDCSnapshotTestCase.h"
#import "UIView+MDCSnapshot.h"
#pragma clang diagnostic pop

#import "MDCAlertController+ButtonForAction.h"
#import "MDCFontScaler.h"

NS_ASSUME_NONNULL_BEGIN

static NSDictionary<UIContentSizeCategory, NSNumber *> *CustomScalingCurve(void) {
  static NSDictionary<UIContentSizeCategory, NSNumber *> *scalingCurve;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    scalingCurve = @{
      UIContentSizeCategoryExtraSmall : @99,
      UIContentSizeCategorySmall : @98,
      UIContentSizeCategoryMedium : @97,
      UIContentSizeCategoryLarge : @96,
      UIContentSizeCategoryExtraLarge : @95,
      UIContentSizeCategoryExtraExtraLarge : @94,
      UIContentSizeCategoryExtraExtraExtraLarge : @93,
      UIContentSizeCategoryAccessibilityMedium : @92,
      UIContentSizeCategoryAccessibilityLarge : @91,
      UIContentSizeCategoryAccessibilityExtraLarge : @90,
      UIContentSizeCategoryAccessibilityExtraExtraLarge : @89,
      UIContentSizeCategoryAccessibilityExtraExtraExtraLarge : @88
    };
  });
  return scalingCurve;
}

/** A test fake window that allows overriding its @c traitCollection. */
@interface MDCAlertControllerCustomTraitCollectionTestsWindowFake : UIWindow

/** Set to override the value of @c traitCollection. */
@property(nonatomic, strong) UITraitCollection *traitCollectionOverride;

@end

@implementation MDCAlertControllerCustomTraitCollectionTestsWindowFake

- (UITraitCollection *)traitCollection {
  return self.traitCollectionOverride ?: [super traitCollection];
}

@end

/**
 A @c MDCAlertController test fake to override the @c traitCollection to test for dynamic type.
 */
@interface AlertControllerCustomTraitCollectionSnapshotTestFake : MDCAlertController
@property(nonatomic, strong) UITraitCollection *traitCollectionOverride;
@end

@implementation AlertControllerCustomTraitCollectionSnapshotTestFake

- (UITraitCollection *)traitCollection {
  return self.traitCollectionOverride ?: [super traitCollection];
}

@end

/** An @c MDCDialogShadowedView test fake to override the @c traitCollection to test. */
@interface ShadowViewCustomTraitCollectionSnapshotTestFake : MDCDialogShadowedView
@property(nonatomic, strong) UITraitCollection *traitCollectionOverride;
@end

@implementation ShadowViewCustomTraitCollectionSnapshotTestFake

- (UITraitCollection *)traitCollection {
  return self.traitCollectionOverride ?: [super traitCollection];
}

@end

@interface MDCAlertControllerCustomTraitCollectionTests : MDCSnapshotTestCase
@property(nonatomic, strong, nullable)
    AlertControllerCustomTraitCollectionSnapshotTestFake *alertController;
@end

@implementation MDCAlertControllerCustomTraitCollectionTests

- (void)setUp {
  [super setUp];

  // Uncomment below to recreate all the goldens (or add the following line to the specific
  // test you wish to recreate the golden for).
  //  self.recordMode = YES;

  self.alertController = [[AlertControllerCustomTraitCollectionSnapshotTestFake alloc] init];
  self.alertController.title = @"Material";
  self.alertController.message =
      @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt "
      @"ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation "
      @"ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in "
      @"reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur "
      @"sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id "
      @"est laborum.";
  MDCAlertAction *fakeAction = [MDCAlertAction actionWithTitle:@"Foo"
                                                       handler:^(MDCAlertAction *action){
                                                       }];
  [self.alertController addAction:fakeAction];
  MDCFontScaler *titleFontScaler = [MDCFontScaler scalerForMaterialTextStyle:MDCTextStyleSubtitle1];
  UIFont *titleFont = [UIFont fontWithName:@"Zapfino" size:14];
  titleFont = [titleFontScaler scaledFontWithFont:titleFont];
  titleFont = [titleFont mdc_scaledFontAtDefaultSize];
  self.alertController.titleFont = titleFont;
  MDCFontScaler *messageFontScaler = [MDCFontScaler scalerForMaterialTextStyle:MDCTextStyleBody2];
  UIFont *messageFont = [UIFont fontWithName:@"Zapfino" size:14];
  messageFont = [messageFontScaler scaledFontWithFont:messageFont];
  messageFont = [messageFont mdc_scaledFontAtDefaultSize];
  self.alertController.messageFont = messageFont;
  MDCFontScaler *buttonFontScaler = [MDCFontScaler scalerForMaterialTextStyle:MDCTextStyleButton];
  UIFont *buttonFont = [UIFont fontWithName:@"Zapfino" size:14];
  buttonFont = [buttonFontScaler scaledFontWithFont:buttonFont];
  buttonFont = [buttonFont mdc_scaledFontAtDefaultSize];
  for (MDCAlertAction *action in self.alertController.actions) {
    [[self.alertController buttonForAction:action] setTitleFont:buttonFont
                                                       forState:UIControlStateNormal];
  }
  self.alertController.view.bounds = CGRectMake(0, 0, 300, 300);
}

- (void)tearDown {
  self.alertController = nil;

  [super tearDown];
}

- (void)generateSnapshotAndVerifyForView:(UIView *)view {
  [view layoutIfNeeded];
  UIView *snapshotView = [view mdc_addToBackgroundView];
  [self snapshotVerifyView:snapshotView];
}

/** Used to set the @c UIContentSizeCategory on an @c MDCAlertController. */
- (void)setAlertControllerContentSizeCategory:(UIContentSizeCategory)sizeCategory {
  UITraitCollection *traitCollection = [[UITraitCollection alloc] init];
  traitCollection =
      [UITraitCollection traitCollectionWithPreferredContentSizeCategory:sizeCategory];

  self.alertController.traitCollectionOverride = traitCollection;
}

#pragma mark - Dynamic Type

/**
 Tests the original MDCTypography behavior for Dynamic Type.

 @note The output depends on the host simulator and is equal to
       @c testSystemFontScaledWhenScaledFontUnavailableForContentSizeAXXXL as a result.
 */
- (void)testSystemFontScaledWhenScaledFontUnavailableForContentSizeExtraSmall {
  // Given

  UIFont *originalFont = [UIFont fontWithName:@"Zapfino" size:20];
  UIFontMetrics *fontMetrics = [UIFontMetrics metricsForTextStyle:UIFontTextStyleHeadline];
  self.alertController.messageFont = [fontMetrics scaledFontForFont:originalFont];
  self.alertController.titleFont = [fontMetrics scaledFontForFont:originalFont];
  for (MDCAlertAction *action in self.alertController.actions) {
    [[self.alertController buttonForAction:action] setTitleFont:originalFont
                                                       forState:UIControlStateNormal];
  }
  [self setAlertControllerContentSizeCategory:UIContentSizeCategoryExtraSmall];

  // When
  [self.alertController loadViewIfNeeded];
  self.alertController.adjustsFontForContentSizeCategory = YES;

  // Then
  [self generateSnapshotAndVerifyForView:self.alertController.view];
}

/**
 Tests the original MDCTypography behavior for Dynamic Type.

 @note The output depends on the host simulator and is equal to
       @c testSystemFontScaledWhenScaledFontUnavailableForContentSizeExtraSmall as a result.
 */
- (void)testSystemFontScaledWhenScaledFontUnavailableForContentSizeAXXXL {
  // Given

  // Although the font is initialized with point size 1, the MDCTypography behavior will select
  // a fixed point size for the font at the current UIContentSizeCategory (of the host app),
  // which is not 1.
  UIFont *originalFont = [UIFont fontWithName:@"Zapfino" size:20];
  UIFontMetrics *fontMetrics = [UIFontMetrics metricsForTextStyle:UIFontTextStyleHeadline];
  self.alertController.messageFont = [fontMetrics scaledFontForFont:originalFont];
  self.alertController.titleFont = [fontMetrics scaledFontForFont:originalFont];
  for (MDCAlertAction *action in self.alertController.actions) {
    [[self.alertController buttonForAction:action] setTitleFont:originalFont
                                                       forState:UIControlStateNormal];
  }
  [self
      setAlertControllerContentSizeCategory:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge];

  // When
  [self.alertController loadViewIfNeeded];
  self.alertController.adjustsFontForContentSizeCategory = YES;

  // Then
  [self generateSnapshotAndVerifyForView:self.alertController.view];
}

/** Tests behavior when a font generated from a FontScaler is provided. */
- (void)testFontScalerFontScaledForContentSizeExtraSmall {
  // Given
  UIFont *originalFont = [UIFont fontWithName:@"Zapfino" size:20];
  UIFontMetrics *fontMetrics = [UIFontMetrics metricsForTextStyle:UIFontTextStyleHeadline];
  self.alertController.messageFont = [fontMetrics scaledFontForFont:originalFont];
  self.alertController.titleFont = [fontMetrics scaledFontForFont:originalFont];
  for (MDCAlertAction *action in self.alertController.actions) {
    [[self.alertController buttonForAction:action] setTitleFont:originalFont
                                                       forState:UIControlStateNormal];
  }
  [self setAlertControllerContentSizeCategory:UIContentSizeCategoryExtraSmall];

  // When
  [self.alertController loadViewIfNeeded];
  self.alertController.adjustsFontForContentSizeCategory = YES;

  // Then
  [self generateSnapshotAndVerifyForView:self.alertController.view];
}

/** Tests behavior when a font generated from a FontScaler is provided. */
- (void)testFontScalerFontScaledForContentSizeAXXXL {
  // Given
  UIFont *originalFont = [UIFont fontWithName:@"Zapfino" size:1];
  // Simulates a font scaler by providing scaling curve dictionary.
  originalFont.mdc_scalingCurve = CustomScalingCurve();
  self.alertController.messageFont = originalFont;
  self.alertController.titleFont = originalFont;
  for (MDCAlertAction *action in self.alertController.actions) {
    [[self.alertController buttonForAction:action] setTitleFont:originalFont
                                                       forState:UIControlStateNormal];
  }
  [self
      setAlertControllerContentSizeCategory:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge];

  // When
  [self.alertController loadViewIfNeeded];
  self.alertController.adjustsFontForContentSizeCategory = YES;

  // Then
  [self generateSnapshotAndVerifyForView:self.alertController.view];
}

/**
 Test that @c adjustsFontForContentSizeCategory will scale an appropriate font to a larger
 size when the preferred content size category increases.
 */
- (void)testAdjustsFontForContentSizeUpscalesUIFontMetricsFontsForSizeCategoryAXXXL {
  // Given
  UIFontMetrics *bodyMetrics = [UIFontMetrics metricsForTextStyle:UIFontTextStyleBody];
  UITraitCollection *extraSmallTraits = [UITraitCollection
      traitCollectionWithPreferredContentSizeCategory:UIContentSizeCategoryExtraSmall];

  UIFont *titleFont = [UIFont fontWithName:@"Zapfino" size:20];
  XCTAssertNotNil(titleFont);
  titleFont = [bodyMetrics scaledFontForFont:titleFont
               compatibleWithTraitCollection:extraSmallTraits];
  self.alertController.titleFont = titleFont;

  UIFont *messageFont = [UIFont fontWithName:@"Zapfino" size:15];
  messageFont = [bodyMetrics scaledFontForFont:messageFont
                 compatibleWithTraitCollection:extraSmallTraits];
  self.alertController.messageFont = messageFont;

  UIFont *buttonFont = [UIFont fontWithName:@"Zapfino" size:20];
  buttonFont = [bodyMetrics scaledFontForFont:buttonFont
                compatibleWithTraitCollection:extraSmallTraits];
  for (MDCAlertAction *action in self.alertController.actions) {
    MDCButton *button = [self.alertController buttonForAction:action];
    button.titleLabel.font = buttonFont;
  }

  self.alertController.adjustsFontForContentSizeCategory = YES;
  [self.alertController loadViewIfNeeded];

  // The initial size is calculated without constraints, so start the view bounds there.
  CGSize alertSize = self.alertController.preferredContentSize;
  self.alertController.view.bounds = CGRectMake(0, 0, alertSize.width, alertSize.height);

  // Create a window so the Alert's view can inherit the trait environment.
  MDCAlertControllerCustomTraitCollectionTestsWindowFake *window =
      [[MDCAlertControllerCustomTraitCollectionTestsWindowFake alloc] init];
  [window makeKeyWindow];
  window.hidden = NO;
  [window addSubview:self.alertController.view];

  // When
  window.traitCollectionOverride =
      [UITraitCollection traitCollectionWithPreferredContentSizeCategory:
                             UIContentSizeCategoryAccessibilityExtraExtraExtraLarge];
  [window traitCollectionDidChange:nil];
  // Recalculates the preferredContentSize of the AlertController.
  [self.alertController.view layoutIfNeeded];
  alertSize = self.alertController.preferredContentSize;
  window.bounds = CGRectMake(0, 0, alertSize.width, alertSize.height);
  self.alertController.view.frame = window.bounds;

  // Then
  // Can't add a UIWindow to a UIView, so just screenshot the window directly.
  [window layoutIfNeeded];
  [self snapshotVerifyView:window];
}

/**
 Test that @c adjustsFontForContentSizeCategory will scale an appropriate font to a
 smaller size when the preferred content size category decreases.
 */
- (void)testAdjustsFontForContentSizeDownscalesUIFontMetricsFontsForSizeCategoryXS {
  // Given
  UIFontMetrics *bodyMetrics = [UIFontMetrics metricsForTextStyle:UIFontTextStyleBody];
  UITraitCollection *aXXXLTraits =
      [UITraitCollection traitCollectionWithPreferredContentSizeCategory:
                             UIContentSizeCategoryAccessibilityExtraExtraExtraLarge];

  UIFont *titleFont = [UIFont fontWithName:@"Zapfino" size:20];
  XCTAssertNotNil(titleFont);
  titleFont = [bodyMetrics scaledFontForFont:titleFont compatibleWithTraitCollection:aXXXLTraits];
  self.alertController.titleFont = titleFont;

  UIFont *messageFont = [UIFont fontWithName:@"Zapfino" size:15];
  messageFont = [bodyMetrics scaledFontForFont:messageFont
                 compatibleWithTraitCollection:aXXXLTraits];
  self.alertController.messageFont = messageFont;

  UIFont *buttonFont = [UIFont fontWithName:@"Zapfino" size:20];
  buttonFont = [bodyMetrics scaledFontForFont:buttonFont compatibleWithTraitCollection:aXXXLTraits];
  for (MDCAlertAction *action in self.alertController.actions) {
    MDCButton *button = [self.alertController buttonForAction:action];
    button.titleLabel.font = buttonFont;
  }

  self.alertController.adjustsFontForContentSizeCategory = YES;
  [self.alertController loadViewIfNeeded];

  // The initial size is calculated without constraints, so start the view bounds there.
  CGSize alertSize = self.alertController.preferredContentSize;
  self.alertController.view.bounds = CGRectMake(0, 0, alertSize.width, alertSize.height);

  // Create a window so the Alert's view can inherit the trait environment.
  MDCAlertControllerCustomTraitCollectionTestsWindowFake *window =
      [[MDCAlertControllerCustomTraitCollectionTestsWindowFake alloc] init];
  [window makeKeyWindow];
  window.hidden = NO;
  [window addSubview:self.alertController.view];

  // When
  window.traitCollectionOverride = [UITraitCollection
      traitCollectionWithPreferredContentSizeCategory:UIContentSizeCategoryExtraSmall];
  [window traitCollectionDidChange:nil];
  // Recalculates the preferredContentSize of the AlertController.
  [self.alertController.view layoutIfNeeded];
  alertSize = self.alertController.preferredContentSize;
  window.bounds = CGRectMake(0, 0, alertSize.width, alertSize.height);
  self.alertController.view.frame = window.bounds;

  // Then
  // Can't add a UIWindow to a UIView, so just screenshot the window directly.
  [window layoutIfNeeded];
  [self snapshotVerifyView:window];
}

#pragma mark - Dynamic Color

- (void)testDynamicColorSupport {
#if MDC_AVAILABLE_SDK_IOS(13_0)
  if (@available(iOS 13.0, *)) {
    // Given
    UIColor *titleColor = [UIColor colorWithUserInterfaceStyleDarkColor:UIColor.greenColor
                                                           defaultColor:UIColor.blackColor];
    UIColor *messageColor = [UIColor colorWithUserInterfaceStyleDarkColor:UIColor.purpleColor
                                                             defaultColor:UIColor.blackColor];
    UIColor *backgroundColor = [UIColor colorWithUserInterfaceStyleDarkColor:UIColor.blueColor
                                                                defaultColor:UIColor.blackColor];
    self.alertController.titleColor = titleColor;
    self.alertController.messageColor = messageColor;
    self.alertController.backgroundColor = backgroundColor;

    // When
    self.alertController.traitCollectionOverride =
        [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark];

    // Then
    UIView *snapshotView = [self.alertController.view
        mdc_addToBackgroundViewWithInsets:UIEdgeInsetsMake(50, 50, 50, 50)];
    [self snapshotVerifyViewForIOS13:snapshotView];
  }
#endif  // MDC_AVAILABLE_SDK_IOS(13_0)
}

- (void)testDynamicColorSupportForTrackingView {
#if MDC_AVAILABLE_SDK_IOS(13_0)
  if (@available(iOS 13.0, *)) {
    // Given
    UIColor *shadowColor = [UIColor colorWithUserInterfaceStyleDarkColor:UIColor.greenColor
                                                            defaultColor:UIColor.blackColor];
    ShadowViewCustomTraitCollectionSnapshotTestFake *trackingView =
        [[ShadowViewCustomTraitCollectionSnapshotTestFake alloc] init];
    trackingView.frame = CGRectMake(0, 0, 100, 200);
    trackingView.shadowColor = shadowColor;
    trackingView.backgroundColor = UIColor.whiteColor;

    // When
    trackingView.traitCollectionOverride =
        [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark];
    [trackingView layoutIfNeeded];

    // Then
    UIView *snapshotView =
        [trackingView mdc_addToBackgroundViewWithInsets:UIEdgeInsetsMake(50, 50, 50, 50)];
    [self snapshotVerifyViewForIOS13:snapshotView];
  }
#endif  // MDC_AVAILABLE_SDK_IOS(13_0)
}

@end

NS_ASSUME_NONNULL_END


text:
# Copyright 2007, Frank Scholz <coherence@beebits.net>
# Copyright 2008, Jean-Michel Sizun <jm.sizun@free.fr>

from twisted.internet import defer

from coherence.upnp.core import utils
from coherence.upnp.core.utils import ReverseProxyUriResource

from coherence.upnp.core.DIDLLite import classChooser, Container, Resource, DIDLElement

from coherence.backend import BackendStore
from coherence.backend import BackendItem

from urlparse import urlsplit

from coherence.extern.galleryremote import Gallery

class ProxyGallery2Image(ReverseProxyUriResource):

    def __init__(self, uri):
        ReverseProxyUriResource.__init__(self, uri)

    def render(self, request):
        del request.received_headers['referer']
        return ReverseProxyUriResource.render(self, request)

class Gallery2Item(BackendItem):
    logCategory = 'gallery2_item'

    def __init__(self, id, obj, parent, mimetype, urlbase, UPnPClass,update=False):
        self.id = id

        self.name = obj.get('title')#.encode('utf-8')
        if self.name == None:
            self.name = obj.get('name')
        if self.name == None:
            self.name = id

        self.mimetype = mimetype

        self.gallery2_id = obj.get('gallery2_id')

        self.parent = parent
        if parent:
            parent.add_child(self,update=update)

        if parent == None:
            parent_id = -1
        else:
            parent_id = parent.get_id()

        self.item = UPnPClass(id, parent_id, self.name)
        if isinstance(self.item, Container):
            self.item.childCount = 0
        self.child_count = 0
        self.children = None

        if( len(urlbase) and urlbase[-1] != '/'):
            urlbase += '/'

        if parent == None:
            self.gallery2_url = None
            self.url = urlbase + str(self.id)
        elif self.mimetype == 'directory':
            #self.gallery2_url = parent.store.get_url_for_album(self.gallery2_id)
            self.url = urlbase + str(self.id)
        else:
            self.gallery2_url = parent.store.get_url_for_image(self.gallery2_id)
            self.url = urlbase + str(self.id)
            self.location = ProxyGallery2Image(self.gallery2_url)

        if self.mimetype == 'directory':
            self.update_id = 0
        else:
            res = Resource(self.gallery2_url, 'http-get:*:%s:*' % self.mimetype)
            res.size = None
            self.item.res.append(res)

    def remove(self):
        if self.parent:
            self.parent.remove_child(self)
        del self.item

    def add_child(self, child, update=False):
        if self.children == None:
            self.children = []
        self.children.append(child)
        self.child_count += 1
        if isinstance(self.item, Container):
            self.item.childCount += 1
        if update == True:
            self.update_id += 1

    def remove_child(self, child):
        #self.info("remove_from %d (%s) child %d (%s)" % (self.id, self.get_name(), child.id, child.get_name()))
        if child in self.children:
            self.child_count -= 1
            if isinstance(self.item, Container):
                self.item.childCount -= 1
            self.children.remove(child)
            self.update_id += 1

    def get_children(self,start=0,request_count=0):
        def process_items(result = None):
            if self.children == None:
                return  []
            if request_count == 0:
                return self.children[start:]
            else:
                return self.children[start:request_count]

        if (self.children == None):
            d = self.store.retrieveItemsForAlbum(self.gallery2_id, self)
            d.addCallback(process_items)
            return d
        else:
            return process_items()

    def get_child_count(self):
        return self.child_count

    def get_id(self):
        return self.id

    def get_update_id(self):
        if hasattr(self, 'update_id'):
            return self.update_id
        else:
            return None

    def get_path(self):
        return self.url

    def get_name(self):
        return self.name

    def get_parent(self):
        return self.parent

    def get_item(self):
        return self.item

    def get_xml(self):
        return self.item.toString()

    def __repr__(self):
        return 'id: ' + str(self.id)

class Gallery2Store(BackendStore):

    logCategory = 'gallery2_store'

    implements = ['MediaServer']

    description = ('Gallery2', 'exposes the photos from a Gallery2 photo repository.', None)

    options = [{'option':'name', 'text':'Server Name:', 'type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
       {'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
       {'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
       {'option':'server_url','text':'Server URL:','type':'string'},
       {'option':'username','text':'User ID:','type':'string','group':'User Account'},
       {'option':'password','text':'Password:','type':'string','group':'User Account'},
    ]

    def __init__(self, server, **kwargs):
        BackendStore.__init__(self,server,**kwargs)

        self.next_id = 1000
        self.config = kwargs
        self.name = kwargs.get('name','gallery2Store')

        self.wmc_mapping = {'16': 1000}

        self.update_id = 0
        self.store = {}

        self.gallery2_server_url = self.config.get('server_url', 'http://localhost/gallery2')
        self.gallery2_username = self.config.get('username',None)
        self.gallery2_password = self.config.get('password',None)

        self.store[1000] = Gallery2Item( 1000, {'title':'Gallery2','gallery2_id':'0','mimetype':'directory'}, None,
                                                        'directory', self.urlbase,Container,update=True)
        self.store[1000].store = self

        self.gallery2_remote = Gallery(self.gallery2_server_url, 2)
        if not None in [self.gallery2_username, self.gallery2_password]:
            d = self.gallery2_remote.login(self.gallery2_username, self.gallery2_password)
            d.addCallback(lambda x : self.retrieveAlbums('0', self.store[1000]))
            d.addCallback(self.init_completed)
        else:
            d = self.retrieveAlbums('0', self.store[1000])
            d.addCallback(self.init_completed)

    def __repr__(self):
        return self.__class__.__name__

    def append( self, obj, parent):
        if isinstance(obj, basestring):
            mimetype = 'directory'
        else:
            mimetype = obj['mimetype']

        UPnPClass = classChooser(mimetype)
        id = self.getnextID()
        update = False
        #if hasattr(self, 'update_id'):
        #    update = True

        item = Gallery2Item( id, obj, parent, mimetype, self.urlbase,
                                        UPnPClass, update=update)
        self.store[id] = item
        self.store[id].store = self
        if hasattr(self, 'update_id'):
            self.update_id += 1
            if self.server:
                self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
            #if parent:
            #    value = (parent.get_id(),parent.get_update_id())
            #    if self.server:
            #        self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)

        if mimetype == 'directory':
            return self.store[id]

        return None

    def len(self):
        return len(self.store)

    def get_by_id(self,id):
        if isinstance(id, basestring):
            id = id.split('@',1)
            id = id[0]
        try:
            id = int(id)
        except ValueError:
            id = 1000

        if id == 0:
            id = 1000
        try:
            return self.store[id]
        except:
            return None

    def getnextID(self):
        self.next_id += 1
        return self.next_id

    def get_url_for_image(self, gallery2_id):
        url = self.gallery2_remote.get_URL_for_image(gallery2_id)
        return url

    def upnp_init(self):
        self.current_connection_id = None
        if self.server:
            self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
                                                                  'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
                                                                  'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
                                                                  'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
                                                                  'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
                                                                  'http-get:*:image/jpeg:*,'
                                                                  'http-get:*:image/gif:*,'
                                                                  'http-get:*:image/png:*',
                                                                default=True)

    def retrieveAlbums(self, album_gallery2_id, parent):
        d = self.gallery2_remote.fetch_albums()

        def gotAlbums (albums):
            if albums :
                albums = [album for album in albums.values() if album.get('parent') == album_gallery2_id]
                if album_gallery2_id == '0' and len(albums) == 1:
                    album = albums[0]
                    self.store[1000].gallery2_id = album.get('name')
                    self.store[1000].name = album.get('title')
                    self.store[1000].description = album.get('summary')
                else:
                    for album in albums:
                        gallery2_id = album.get('name')
                        parent_gallery2_id = album.get('parent')
                        title = album.get('title')
                        description = album.get('summary')
                        store_item = {
                                  'name':id,
                                  'gallery2_id':gallery2_id,
                                  'parent_id':parent_gallery2_id,
                                  'title':title,
                                  'description':description,
                                  'mimetype':'directory',
                                    }
                        self.append(store_item, parent)

        d.addCallback(gotAlbums)
        return d

    def retrieveItemsForAlbum (self, album_id, parent):
        # retrieve subalbums
        d1 = self.retrieveAlbums(album_id, parent)

        # retrieve images
        d2 = self.gallery2_remote.fetch_album_images(album_id)

        def gotImages(images):
            if images :
                for image in images:
                    image_gallery2_id = image.get('name')
                    parent_gallery2_id = image.get('parent')
                    thumbnail_gallery2_id = image.get('thumbName')
                    resized_gallery2_id = image.get('resizedName')
                    title = image.get('title')
                    description = image.get('description')

                    gallery2_id =  resized_gallery2_id
                    if gallery2_id == '':
                        gallery2_id = image_gallery2_id

                    store_item = {
                                  'name':id,
                                  'gallery2_id':gallery2_id,
                                  'parent_id':parent_gallery2_id,
                                  'thumbnail_gallery2_id':thumbnail_gallery2_id,
                                  'title':title,
                                  'description':description,
                                  'mimetype':'image/jpeg',
                                }
                    self.append(store_item, parent)

        d2.addCallback(gotImages)
        dl = defer.DeferredList([d1,d2])
        return dl

def main():

    f = Gallery2Store(None)

    def got_upnp_result(result):
        print "upnp", result

    f.upnp_init()

if __name__ == '__main__':

    from twisted.internet import reactor

    reactor.callWhenRunning(main)
    reactor.run()


text:
for (var i in politicos) {
    var politico = politicos[i];
    $('#comboPart').append("<option id='" + i + "'>"+politico+"</option>");
}

function comboPoliticos(){
    var politicoId = document.getElementById("comboPart").selectedIndex;
    createTags(politicoId, "#visCaracterizante");
    createTags(politicoId, "#visDescaracterizante");
}

$(document).ready(function() {
    $("select").select2();
});

function createTags(politicoId, div){
    var words = [];

    for (var palavraId in palavras){
        var palavra = palavras[palavraId];
        var importancia = Number(model[politicoId][palavraId]);
        if (importancia && importancia > 0 && div == "#visCaracterizante"){
            words.push({"key": palavra, "value": importancia})
        }
        if (importancia && importancia < 0 && div == "#visDescaracterizante"){
            words.push({"key": palavra, "value": -importancia})
        }
    }
    words.sort(function (x, y){return y.value - x.value});
    words = words.slice(0, 200).map(function(x){ return {key: x.key, value: Math.log(1 + x.value)}});
    createWordCloud(words, div);
}

function createWordCloud(tags, div){
    $(div).empty();

    //var fill = d3.interpolateReds()
    //var fill = d3.scale.category20b();
    var w = 1200,
        h = 600;

    //var w = window.innerWidth,
    //h = window.innerHeight;

    var max,
        fontSize;

    var layout = d3.layout.cloud()
        .timeInterval(Infinity)
        .size([w, h])
        .fontSize(function(d) {
            return fontSize(+d.value);
        })
        .text(function(d) {
            return d.key;
        })
        .on("end", draw);

    var svg = d3.select(div).append("svg")
        .attr("width", w)
        .attr("height", h);

    var vis = svg.append("g").attr("transform", "translate(" + [w >> 1, h >> 1] + ")");

    update();

    window.onresize = function(event) {
        update();
    };

    function draw(data, bounds) {
        var w = 1200,
            h = 600;

        svg.attr("width", w).attr("height", h);

        scale = bounds ? Math.min(
                w / Math.abs(bounds[1].x - w / 2),
                w / Math.abs(bounds[0].x - w / 2),
                h / Math.abs(bounds[1].y - h / 2),
                h / Math.abs(bounds[0].y - h / 2)) / 2 : 1;

        var text = vis.selectAll("text")
                .data(data, function(d) {
                    return d.text.toLowerCase();
                });
        text.transition()
                .duration(1000)
                .attr("transform", function(d) {
                    return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
                })
                .style("font-size", function(d) {
                    return d.size + "px";
                });
        text.enter().append("text")
                .attr("text-anchor", "middle")
                .attr("transform", function(d) {
                    return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
                })
                .style("font-size", function(d) {
                    return d.size + "px";
                })
                .style("opacity", 1e-6)
                .transition()
                .duration(1000)
                .style("opacity", 1);
        text.style("font-family", function(d) {
            return d.font;
        })
                .style("fill", function(d) {
                    if(div=='#visCaracterizante'){
                        return d3.interpolateBlues('0.'+d.size);
                    }else{
                        return d3.interpolateReds('0.'+d.size);
                    }

                })
                .text(function(d) {
                    return d.text;
                });

        vis.transition().attr("transform", "translate(" + [w >> 1, h >> 1] + ")scale(" + scale + ")");
    }

    function update() {
        layout.font('impact').spiral('archimedean');
        fontSize = d3.scale['sqrt']().range([10, 70]);
        if (tags.length){
            fontSize.domain([+tags[tags.length - 1].value || 1, +tags[0].value]);
        }
        layout.stop().words(tags).start();
    }
}

comboPoliticos();