text:
package bots

import (
	"fmt"
	"log"
	"sync"
	"time"

	"github.com/ethereum/go-ethereum/rpc"
	"github.com/san-lab/banketh-quorum/banketh/cryptobank"
	"github.com/san-lab/banketh-quorum/lib/db"
	"github.com/san-lab/banketh-quorum/lib/ethapi"
	"github.com/san-lab/banketh-quorum/sancash/data"
)

const (
	SETTLE_BOT_CHECKUP_TIME   = 3 * time.Second
	REVIEW_BOT_CHECKUP_TIME   = 1 * time.Minute
	WAITTIME_ON_ERROR         = 1 * time.Second
	TIME_TO_RESET_ERROR_COUNT = 5 * time.Second
)

var ethclient *rpc.Client
var Quit_blockchain_sniffing_bot,
	Quit_settle_bot,
	Quit_review_bot chan bool

var TIME_LAGS = []time.Duration{0, 1, 2, 5, 5, 10, 15, 30, 60, 120, 300, 600, 900}
var ManyErrors = map[string]int{
	"blockchain_sniffing_bot": 0,
	"settle_bot":              0,
	"review_bot":              0,
}
var LastErrorTime = map[string]time.Time{
	"blockchain_sniffing_bot": time.Now(),
	"settle_bot":              time.Now(),
	"review_bot":              time.Now(),
}

func wait_on_error(which_bot string) {
	if time.Since(LastErrorTime[which_bot]) >= TIME_TO_RESET_ERROR_COUNT {
		ManyErrors[which_bot] = 0
	}
	time.Sleep(TIME_LAGS[ManyErrors[which_bot]] * time.Second)
	if ManyErrors[which_bot] < len(TIME_LAGS)-1 {
		ManyErrors[which_bot]++
	}
	LastErrorTime[which_bot] = time.Now()
}

func Init(client *rpc.Client) {
	ethclient = client
	go cryptobank.Blockchain_sniffing_bot(
		ethclient,
		&sync.Mutex{},
		data.DBNAME, data.DBTABLEBANKETHTRANSACTIONS, data.DBTABLELASTBLOCKANALYZED, data.DBTABLEEVENTS,
		wait_on_error,
		Quit_blockchain_sniffing_bot,
	)
	go settle_bot(Quit_settle_bot)
	go review_bot(Quit_review_bot)
	// go ethapi.Eth_price_bot(data.DBNAME, data.DBTABLEPRICES, data.DBTABLEEVENTS, Quit_eth_price_bot)
	// go ethapi.Currency_prices_bot(data.DBNAME, data.DBTABLEPRICES, data.DBTABLEEVENTS, Quit_currency_prices_bot)
}

func Kill() {
	Quit_blockchain_sniffing_bot <- true
	Quit_settle_bot <- true
	Quit_review_bot <- true
}

func settle_bot(quit chan bool) {
	d, err := db.ConnectDB(data.DBNAME)
	if err != nil {
		log.Fatal("Error connecting to DB:", err)
	}
	db_connected := true
	currentError := false
main_loop:
	for {
		select {
		case <-quit:
			return
		default:
			if db_connected {
				d.Close()
				db_connected = false
			}
			if currentError {
				wait_on_error("settle_bot")
				currentError = false
			} else {
				time.Sleep(SETTLE_BOT_CHECKUP_TIME)
			}

			if !db_connected {
				d, err = db.ConnectDB(data.DBNAME)
				if err != nil {
					log.Println("Error connecting to DB:", err)
					currentError = true
					continue main_loop
				}
				db_connected = true
			}

			pending_transactions, err := db.ReadTable(data.DBNAME, data.DBTABLETRANSACTIONS, &data.TransactionT{}, fmt.Sprintf("Status='%v'", data.TRANSACTION_STATUS_PENDING), "Time desc")
			if err != nil {
				db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
					"DB error found in settle_bot when trying to read transactions table [%v]\n", err)
				currentError = true
				continue main_loop
			}
			for _, v := range pending_transactions {
				thisT := v.(*data.TransactionT)
				mined, blockMined, _, successful, err := ethapi.Is_transaction_mined(ethclient, thisT.EthTrID)
				if err != nil {
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
						"Ethereum error - could not find transaction %v [%v]", thisT.EthTrID, err)
					currentError = true
					continue main_loop
				}
				if !mined {
					continue
				}
				if successful {
					thisT.Status = data.TRANSACTION_STATUS_SUCCESSFUL
				} else {
					thisT.Status = data.TRANSACTION_STATUS_FAILED
				}
				thisT.BlockNumber = blockMined
				err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
				if err != nil {
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
						"DB error found in settle_bot after calling db.WriteEntry when trying to update Status for transaction with hash %v [%v]", thisT.EthTrID, err)
					currentError = true
					continue main_loop
				}
				db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
					"Recorded confirmation of transaction with hash %v", thisT.EthTrID)
			} // loop pending transactions

			final_pending_transactions, err := db.ReadTable(data.DBNAME, data.DBTABLETRANSACTIONS, &data.TransactionT{}, fmt.Sprintf("Status!='%v' and Final='false'", data.TRANSACTION_STATUS_PENDING), "Time desc")
			if err != nil {
				db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
					"DB error found in settle_bot when trying to read transactions table [%v]\n", err)
				currentError = true
				continue main_loop
			}
			for _, v := range final_pending_transactions {
				thisT := v.(*data.TransactionT)
				mined, blockMined, blocks, successful, err := ethapi.Is_transaction_mined(ethclient, thisT.EthTrID)
				if err != nil {
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
						"Ethereum error - could not find transaction %v [%v]", thisT.EthTrID, err)
					currentError = true
					continue main_loop
				}
				if !mined {
					thisT.BlockNumber = 0
					thisT.Status = data.TRANSACTION_STATUS_PENDING
					err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
					if err != nil {
						db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
							"DB error found in settle_bot after calling db.WriteEntry when trying to update status (back to pending) for transaction with hash %v [%v]", thisT.EthTrID, err)
						currentError = true
						continue main_loop
					}
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
						"Amended Status for transaction with hash %v (back to pending)", thisT.EthTrID)
				}
				if thisT.BlockNumber != blockMined {
					thisT.BlockNumber = blockMined
					err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
					if err != nil {
						db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
							"DB error found in settle_bot after calling db.WriteEntry when trying to update BlockNumber for transaction with hash %v [%v]", thisT.EthTrID, err)
						currentError = true
						continue main_loop
					}
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
						"Amended BlockNumber for transaction with hash %v (changed before becoming final to %v)", thisT.EthTrID, thisT.BlockNumber)
				}
				if (successful && thisT.Status != data.TRANSACTION_STATUS_SUCCESSFUL) ||
					(!successful && thisT.Status != data.TRANSACTION_STATUS_FAILED) {
					if successful {
						thisT.Status = data.TRANSACTION_STATUS_SUCCESSFUL
					} else {
						thisT.Status = data.TRANSACTION_STATUS_FAILED
					}
					err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
					if err != nil {
						db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
							"DB error found in settle_bot after calling db.WriteEntry when trying to update result (successful or not) for transaction with hash %v [%v]", thisT.EthTrID, err)
						currentError = true
						continue main_loop
					}
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
						"Amended result (successful or not) for transaction with hash %v (status is %v)", thisT.EthTrID, thisT.Status)
				}

				if blocks >= cryptobank.BLOCK_CONFIRMATIONS_REQUIRED {
					thisT.Final = true
					err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
					if err != nil {
						db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
							"DB error found in settle_bot after calling db.WriteEntry when trying to update Final status for transaction with hash %v [%v]", thisT.EthTrID, err)
						currentError = true
						continue main_loop
					}
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
						"Recorded final confirmation of transaction with hash %v", thisT.EthTrID)
				}
			}

		}
	}
}

func review_bot(quit chan bool) {
	d, err := db.ConnectDB(data.DBNAME)
	if err != nil {
		log.Fatal("Error connecting to DB:", err)
	}
	db_connected := true
	currentError := false
main_loop:
	for {
		select {
		case <-quit:
			return
		default:
			if db_connected {
				d.Close()
				db_connected = false
			}
			if currentError {
				wait_on_error("settle_bot")
				currentError = false
			} else {
				time.Sleep(REVIEW_BOT_CHECKUP_TIME)
			}
			if !db_connected {
				d, err = db.ConnectDB(data.DBNAME)
				if err != nil {
					log.Println("Error connecting to DB:", err)
					currentError = true
					continue main_loop
				}
				db_connected = true
			}
			closed_transactions, err := db.ReadTable(data.DBNAME, data.DBTABLETRANSACTIONS, &data.TransactionT{}, "(Final=true) and (age(now(), Time) < '"+cryptobank.AGE_TO_REVIEW_FINAL_STATE+"')", "Time desc")
			if err != nil {
				db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
					"DB error found in review_bot when trying to read transactions table [%v]\n", err)
				currentError = true
				continue main_loop
			}
			for _, v := range closed_transactions {
				thisT := v.(*data.TransactionT)
				mined, blockMined, blocks, successful, err := ethapi.Is_transaction_mined(ethclient, thisT.EthTrID)
				if err != nil {
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_ETHEREUM_ERROR,
						"Ethereum error - could not find transaction %v [%v]", thisT.EthTrID, err)
					currentError = true
					continue main_loop
				}
				if !mined {
					thisT.Status = data.TRANSACTION_STATUS_PENDING
					thisT.Final = false
					err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
					if err != nil {
						db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
							"DB error found in review_bot after calling db.WriteEntry when trying to update Status for transaction with hash %v [%v]\n", thisT.EthTrID, err)
						currentError = true
						continue main_loop
					}
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
						"Amended transaction with hash %v: it was recorded as final in the database, but the transaction is not mined!", thisT.EthTrID)
					continue
				}
				if blockMined != thisT.BlockNumber {
					thisT.BlockNumber = blockMined
					err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
					if err != nil {
						db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
							"DB error found in review_bot after calling db.WriteEntry when trying to update Status for transaction with hash %v [%v]\n", thisT.EthTrID, err)
						currentError = true
						continue main_loop
					}
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
						"Amended transaction with hash %v: recorded block number was incorrect", thisT.EthTrID)
					continue
				}

				if blocks < cryptobank.BLOCK_CONFIRMATIONS_REQUIRED {
					thisT.Final = false
					err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
					if err != nil {
						db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
							"DB error found in review_bot after calling db.WriteEntry when trying to update Status for transaction with hash %v [%v]\n", thisT.EthTrID, err)
						currentError = true
						continue main_loop
					}
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
						"Amended transaction with hash %v: it was recorded as final in the database, but not enough blocks have passed", thisT.EthTrID)
				}
				if (successful && thisT.Status != data.TRANSACTION_STATUS_SUCCESSFUL) || (!successful && thisT.Status != data.TRANSACTION_STATUS_FAILED) {
					old_status := thisT.Status
					if successful {
						thisT.Status = data.TRANSACTION_STATUS_SUCCESSFUL
					} else {
						thisT.Status = data.TRANSACTION_STATUS_FAILED
					}
					err = db.WriteEntry(data.DBNAME, data.DBTABLETRANSACTIONS, thisT)
					if err != nil {
						db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_DB_ERR,
							"DB error found in review_bot after calling db.WriteEntry when trying to update Status for transaction with hash %v [%v]", thisT.EthTrID, err)
						currentError = true
						continue main_loop
					}
					db.RegisterEventf(d, data.DBTABLEEVENTS, db.EVENT_INFO,
						"Amended transaction with hash %v: it was recorded as %v in the database, but the transaction was %v", thisT.EthTrID, old_status, thisT.Status)
				}
			}
		}
	}
}


text:
$(document).ready(function() {

  var ace = new Ace2Editor();
  ace.init("editorcontainer", "", function() {
    $("#editorloadingbox").hide();
  });
  ace.setProperty("showslinenumbers", false);
  ace.setProperty("autoscroll", true);
  ace.setEditable(false);

  Layout.onResize = ace.adjustSize;

  var user = {
    userId: clientVars.userId,
    name: clientVars.userName
    // ip, colorId, userAgent
  };

  var collab = getCollabClient(ace,
                               clientVars.collab_client_vars,
                               user,
                               { });

  function onChannelStateChange(state, info) {
    if (state == "CONNECTED") {
      $("#connstatusconnecting").css('display', 'none');
      $("#connstatusdisconnected").css('display', 'none');
      setTimeout(function() { collab.sendExtendedMessage({ type: "RUN_REQUEST", action: "state" }); }, 0);
    } else if (state == "DISCONNECTED") {
      $("#connstatusconnecting").css('display', 'none');
      $("#connstatusdisconnected").css('display', 'block');
    } else {
      $("#connstatusconnecting").css('display', 'block');
    }
  }

  collab.setOnChannelStateChange(onChannelStateChange);
  collab.setOnExtendedMessage("RUN_STATE_CHANGE", function(msg) {
    switch(msg.state) {
    case 'launched':
      $("#launch").hide();
      $("#terminate").show();
      $("#runstatus").html("Running");
      break;
    case 'terminated':
      $("#terminate").hide();
      $("#launch").show();
      $("#runstatus").html("");
      break;
    }
  });
  $("#launch").click(function() {
    collab.sendExtendedMessage({ type: "RUN_REQUEST", action: 'launch' });
    return false;
  });
  $("#terminate").click(function() {
    collab.sendExtendedMessage({ type: "RUN_REQUEST", action: 'terminate' });
    return false;
  });
});

redpajama_set_name: RedPajamaGithub


text:
@interface FDTwitterListTimelineController : FDTweetListController

#pragma mark - Constructors

- (id)initWithTwitterList: (FDTwitterList *)twitterList;

@end


text:
module IMF
  class ImageSource
    INITIAL_BUFFER_SIZE = 8192

    class InvalidSourceError < IMF::Error
    end

    def self.new(source)
      case source
      when self
        source
      else
        super
      end
    end

    def initialize(source)
      @buffer = '\0' * INITIAL_BUFFER_SIZE
      @read_size = 0
      @pos = 0

      case source
      when String
        init_with_path(source)
      when IO, File
        init_with_io(source)
      else
        init_with_readable(source)
      end
    end

    attr_reader :path

    def read(length = nil, outbuf = '')
      init_with_io(File.open(@path, 'rb')) unless @source

      if length.nil?
        data = @source.read
        @buffer[@read_size, data.length] = data
        @read_size += data.length
        beg, @pos = @pos, @read_size
        outbuf.replace @buffer[beg..-1]
      elsif length > 0
        tail_length = @read_size - @pos
        shortage_length = length - tail_length
        if shortage_length <= 0
          outbuf.replace @buffer[@pos, length]
          @pos += length
        else
          data = @source.read(shortage_length)
          @buffer[@read_size, data.length] = data
          @read_size += data.length
          beg, @pos = @pos, @read_size
          outbuf.replace @buffer[beg, length]
        end
      end

      outbuf
    end

    def rewind
      @pos = 0
    end

    private

    def init_with_path(path)
      unless File.exist? path
        raise Errno::ENOENT
      end

      if File.directory? path
        raise Errno::EISDIR
      end

      unless File.readable? path
        raise Errno::EPERM
      end

      @path = path
      @source = nil
    end

    def init_with_io(io)
      # check readability
      begin
        io.read_nonblock(0)
      rescue SystemCallError
        # ignored
      end

      @source = io
    end

    def init_with_readable(obj)
      if obj.respond_to?(:read)
        @source = obj
      else
        raise InvalidSourceError
      end
    end
  end
end


text:
package biz.r2s.scaffolding.service.ejb;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import biz.r2s.scaffolding.meta.ClassScaffold;
import biz.r2s.scaffolding.meta.action.TypeActionScaffold;
import biz.r2s.scaffolding.security.PermissionFacade;
import biz.r2s.scaffolding.service.PermissionService;
@Stateless
@LocalBean
public class PermissionServiceEjbImpl implements PermissionService{
	private PermissionFacade  permissionFacade;

    public PermissionServiceEjbImpl(){
        permissionFacade = new PermissionFacade();
    }

    public Map<String, Object>  getPermission(ClassScaffold classScaffold, List<TypeActionScaffold> actions, List<String> fields) {
        return permissionFacade.getPermissionScaffold(classScaffold, actions, fields);
    }

    public Map<String, Object> getPermission(ClassScaffold classScaffold, List<TypeActionScaffold> actions) {
    	return permissionFacade.getPermissionScaffold(classScaffold, actions, null);
    }

    public Map<String, Object> getPermission(ClassScaffold classScaffold, TypeActionScaffold action, String field) {
    	return permissionFacade.getPermissionScaffold(classScaffold, Arrays.asList(action), Arrays.asList(field));
    }

    public Map<String, Object> getPermission(ClassScaffold classScaffold, TypeActionScaffold action) {
    	return permissionFacade.getPermissionScaffold(classScaffold, Arrays.asList(action), null);
    }

    public Map<String, Object> getPermission(ClassScaffold classScaffold) {
        return permissionFacade.getPermissionScaffold(classScaffold, null, null);
    }

    public Boolean hasPermission(ClassScaffold classScaffold, List<TypeActionScaffold> actions, List<String> fields) {
    	return permissionFacade.hasPermissionScaffold(classScaffold, actions, fields);
    }

    public Boolean hasPermission(ClassScaffold classScaffold, List<TypeActionScaffold> actions) {
    	return permissionFacade.hasPermissionScaffold(classScaffold, actions, null);
    }

    public Boolean hasPermission(ClassScaffold classScaffold, TypeActionScaffold action, String field) {
    	return permissionFacade.hasPermissionScaffold(classScaffold, Arrays.asList(action), Arrays.asList(field));
    }

    public Boolean hasPermission(ClassScaffold classScaffold, TypeActionScaffold action) {
    	return permissionFacade.hasPermissionScaffold(classScaffold, Arrays.asList(action), null);
    }

    public Boolean hasPermission(ClassScaffold classScaffold) {
    	return permissionFacade.hasPermissionScaffold(classScaffold, null, null);
    }
}


text:
class CreateTransactionDestroyEvent < ActiveRecord::Migration
  def change
    create_table :transaction_destroy_events do |t|
      t.string :transaction_id
      t.references :event, index: true
    end
  end
end


text:
<?php

namespace DifmBundle\Api;

use DifmBundle\Entity\Channel;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

/**
 * Class Channels
 * @package DifmBundle\Api
 */
class Channels
{
    /**
     * @const string
     */
    const CHANNELS = 'streamlist';

    /**
     * @var Client
     */
    private $client;

    /**
     * Channels constructor.
     * @param Client $client
     */
    public function __construct($client)
    {
        $this->client = $client;
    }

    /**
     * Loads channels response
     * @return Channel[]
     * @throws \InvalidArgumentException
     */
    public function loadChannels()
    {
        $request = new Request('GET', self::CHANNELS);
        $response = $this->client->send($request);
        $channels = json_decode($response->getBody());
        array_walk(
            $channels,
            function (&$channel) {
                $channel = new Channel(
                    $channel->id,
                    $channel->key,
                    $channel->name,
                    $channel->playlist
                );
            }
        );
        return $channels;
    }
}


text:
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;

namespace Altis.CommonLogin.Owin
{
    public class DebugAuthorisationFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("debug"), new string[] {});
        }
    }
}


text:
<?php

namespace leinonen\Yii2Monolog\Tests\Unit;

use yii\log\Logger;
use Psr\Log\LogLevel;
use yii\helpers\VarDumper;
use PHPUnit\Framework\TestCase;
use leinonen\Yii2Monolog\Yii2LogMessage;

class Yii2LogMessageTest extends TestCase
{
    /** @test */
    public function it_can_be_initialized_with_a_yii2_log_message()
    {
        $message = [
            'message',
            Logger::LEVEL_ERROR,
            'application',
            10,
            $this->getDummyStackTrace(),
            123,
        ];

        $logMessage = new Yii2LogMessage($message);

        $this->assertSame('message', $logMessage->getMessage());
        $this->assertSame(10, $logMessage->getTimestamp());
        $this->assertSame(
            [
                'category' => 'application',
                'trace' => $this->getDummyStackTrace(),
                'memory' => 123,
            ],
            $logMessage->getContext()
        );
    }

    /**
     * @test
     * @dataProvider psr3LogLevelDataProvider
     */
    public function it_converts_the_yii2_log_level_successfully_to_psr_3_log_level($yii2LogLevel, $psr3LogLevel)
    {
        $message = [
            'message',
            $yii2LogLevel,
            'application',
            10,
            $this->getDummyStackTrace(),
            123,
        ];

        $logMessage = new Yii2LogMessage($message);

        $this->assertSame($psr3LogLevel, $logMessage->getPsr3LogLevel());
    }

    /**
     * Data provider for PSR-3 Test.
     *
     * [
     *  $yii2LogLevel,
     *  $expectedLogLevel
     * ]
     *
     * @return array
     */
    public function psr3LogLevelDataProvider()
    {
        return [
            [
                Logger::LEVEL_ERROR,
                LogLevel::ERROR,
            ],
            [
                Logger::LEVEL_WARNING,
                LogLevel::WARNING,
            ],
            [
                Logger::LEVEL_INFO,
                LogLevel::INFO,
            ],
            [
                Logger::LEVEL_TRACE,
                LogLevel::DEBUG,
            ],
            [
                Logger::LEVEL_PROFILE,
                LogLevel::DEBUG,
            ],
            [
                Logger::LEVEL_PROFILE_BEGIN,
                LogLevel::DEBUG,
            ],
            [
                Logger::LEVEL_PROFILE_END,
                LogLevel::DEBUG,
            ],
        ];
    }

    /** @test */
    public function yiis_messages_can_be_also_arrays_instead_of_plain_strings()
    {
        $expectedArrayOutput = VarDumper::export(['an array as the log message']);
        $expectedMultiLevelArrayOutput = VarDumper::export([
            'an array as the log message' => ['with' => ['nested' => 'arrays']],
        ]);

        $messagesAndTheirExpectedResultsMap = [
            $expectedArrayOutput => [
                ['an array as the log message'],
                Logger::LEVEL_ERROR,
                'application',
                10,
                $this->getDummyStackTrace(),
                123,
            ],
            $expectedMultiLevelArrayOutput => [
                ['an array as the log message' => ['with' => ['nested' => 'arrays']]],
                Logger::LEVEL_ERROR,
                'application',
                10,
                $this->getDummyStackTrace(),
                123,
            ],
        ];

        foreach ($messagesAndTheirExpectedResultsMap as $expectedMessage => $yiisMessage) {
            $logMessage = new Yii2LogMessage($yiisMessage);

            $this->assertSame($expectedMessage, $logMessage->getMessage());
        }
    }

    /** @test */
    public function exceptions_are_extracted_to_monolog_context()
    {
        $runTimeException = new \RuntimeException('a runtime exception');
        $message = [
            $runTimeException,
            Logger::LEVEL_ERROR,
            'application',
            10,
            $this->getDummyStackTrace(),
            123,
        ];
        $logMessage = new Yii2LogMessage($message);

        $this->assertEquals('RuntimeException: a runtime exception', $logMessage->getMessage());
        $this->assertEquals($runTimeException, $logMessage->getException());
        $this->assertArrayHasKey('exception', $logMessage->getContext());
    }

    /**
     * @return array
     */
    private function getDummyStackTrace()
    {
        $trace = [
            'file' => __FILE__,
            'line' => 62,
            'function' => 'log',
            'class' => Logger::class,
            'type' => '->',
        ];

        return $trace;
    }
}


text:
package com.naiive.zhihudaily.common.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.naiive.zhihudaily.AppContext;

/**
 * Created by wangzhe on 16/5/22.
 */
public abstract class BaseFragment extends Fragment {

    protected View mRootView;
    protected Context mContext;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null)
            mRootView = inflater.inflate(getLayoutId(), container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        onBindView(savedInstanceState);
        onInitView(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        onSubscribe();
    }

    @Override
    public void onPause() {
        super.onPause();
        onUnSubscribe();
    }

    protected Context getApplicationContext() {
        return getAttachContext() == null ? AppContext.getContext() : getAttachContext().getApplicationContext();
    }

    protected Context getAttachContext(){
        return mContext;
    }

    protected abstract int getLayoutId();

    protected abstract void onBindView(Bundle savedInstanceState);

    protected abstract void onInitView(Bundle savedInstanceState);

    protected abstract void onSubscribe();

    protected abstract void onUnSubscribe();

    public <V extends View> V view$(@IdRes int id) {

        return view$(getView(), id);
    }

    public <V extends View> V view$(View view, @IdRes int id) {

        return (V) view.findViewById(id);
    }

}


text:
.Post-List {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.Post-Container {
  padding: 8px;
  text-align: justify;
}

.Post-List > div.Post-Container > div.Post-Title-Active::before {
  content: "\2605";
  font-size: 12pt;
  margin-right: 8px;
  color: rgb(58, 105, 255);
}

.Post-List > div.Post-Container > div.Post-Title {
  cursor: pointer;
  font-size: 12pt;
  font-weight: 700;
  text-align: left;
  text-transform: capitalize;
}

.Post-List > div.Post-Container > div.Post-Body {
  font-size: 11pt;
  font-weight: 400;
}


text:
package edu.ua.cs.teaser.syntext;

import edu.ua.cs.teaser.io.Filenames;

import rx.util.functions.Action1;

import java.nio.file.Path;

public class WriteSyntaxAnnotatedCorpus implements Action1<SyntaxAnnotatedCorpus> {

    private final Path outputDir;

    public WriteSyntaxAnnotatedCorpus(final Path outputDir) {
        this.outputDir = outputDir;
    }

    @Override
    public void call(final SyntaxAnnotatedCorpus corpus) {
        final String filename = Filenames.makeFilename(outputDir.toString(), corpus.getName(), "sacorpus");
        new SyntaxAnnotatedCorpusWriter(corpus).write(Filenames.normalize(filename));
    }
}


text:
package com.ecommerce.ecommerpizzas.view.fragment.implement;

import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ecommerce.ecommerpizzas.R;
import com.ecommerce.ecommerpizzas.deps.DaggerDeps;
import com.ecommerce.ecommerpizzas.deps.Deps;
import com.ecommerce.ecommerpizzas.models.entity.MyCart;
import com.ecommerce.ecommerpizzas.presenter.post.OrderPresenter;
import com.ecommerce.ecommerpizzas.utils.NetworkModule;
import com.ecommerce.ecommerpizzas.utils.Service;
import com.ecommerce.ecommerpizzas.view.fragment.AddUserFragment;
import com.ecommerce.ecommerpizzas.view.fragment.BaseFragment;
import com.google.android.gms.vision.text.Line;
import com.google.android.gms.vision.text.Text;
import com.google.firebase.iid.FirebaseInstanceId;

import java.io.File;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindDrawable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Asus on 31/05/2017.
 */

public class FragmentPembayaran extends BaseFragment implements AddUserFragment {
    @BindView(R.id.text_name)
    TextView userName;
    @BindView(R.id.textContact)
    TextView contactNo;
    @BindView(R.id.textAddress)
    TextView alamat;
    @BindView(R.id.text_email)
    TextView emailTextView;
    @BindView(R.id.text_order_date)
    TextView oderDate;
    @BindView(R.id.btn_cash)
    ImageButton btnCash;
    @BindView(R.id.btn_credit)
    ImageButton btnCredit;
    @BindView(R.id.btn_debet)
    ImageButton btnDebet;
    @BindView(R.id.layout_cash)
    LinearLayout layoutCash;
    @BindView(R.id.layout_credit)
    LinearLayout layoutCredit;
    @BindView(R.id.layout_debet)
    LinearLayout layoutDebet;
    @BindDrawable(R.drawable.shape_radius_layout_red)
    Drawable backgrounLayoutRed;
    @BindDrawable(R.drawable.shape_radius_layout)
    Drawable backgrounLayout;

    String dateNow, idOrder, name,email,contactNumber,address;
    String paymentMethod = "Cash";

    @Inject
    public Service service;
    Deps deps;
    public ProgressDialog dialog;

    @Override
    public void initView() {
        view = inflater.inflate(R.layout.pembayaran, container, false);
        ButterKnife.bind(this, view);

        File cacheFile = new File(getActivity().getBaseContext().getCacheDir(), "responses");
        deps = DaggerDeps.builder().networkModule(new NetworkModule(cacheFile)).build();
        deps.inject(this);
        changeBackgrounLayout(true, false, false);
        loadData();
    }

    private void loadData() {
        Date dtnow = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy HH:mm");
        dateNow = sdf.format(dtnow);

        // prepare variable
        idOrder = System.currentTimeMillis()+"";
        idOrder = idOrder.substring(idOrder.length()-8, idOrder.length());
        name = getValueSharedPreference("userName").toString();
        email = getValueSharedPreference("email").toString();
        contactNumber = getValueSharedPreference("contactNo").toString();
        address = getValueSharedPreference("alamat").toString();

        userName.setText(name);
        contactNo.setText(contactNumber);
        alamat.setText(address);
        emailTextView.setText(email);
        oderDate.setText("Order Date : "+dateNow);
    }

    @Override
    public void showWait() {
        dialog = ProgressDialog.show(getActivity(), "","Loading. Please wait...", true);
    }

    @Override
    public void removeWait() {
        dialog.dismiss();
    }

    @Override
    public void onFailure(String appErrorMessage) {
        dialog.dismiss();
        createToast("Sory... Something Wrong... \n Try again later");
    }

    @OnClick(R.id.submit_order)
    public void submitOrder(){
        Date dtnow = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy HH:mm");
        String dateNow = sdf.format(dtnow);

        String subTotal = "";
        String total = "";
        List<MyCart> myCartList = new ArrayList<>();
        List<MyCart> myCartList1 = new ArrayList<>();

        // get My Cart
        try {
            openDatabaseHelper();
            myCartList = myCartsDao.queryForAll();
            double sumPrice = 0;
            for (MyCart myCart : myCartList) {
                sumPrice += Double.parseDouble(myCart.getHarga());
                if(myCartList1.size()==0){
                    myCartList1.add(myCart);
                }
            }
            subTotal = String.format("%,.2f", sumPrice);
            total = String.format("%,.2f", (sumPrice + 15000));

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbh.close();
        }

            // prepare variable
        String statusOrder = "1";
        String statusOrderDesc = "Waiting Respon";
        String delveryFee = dateNow;

        String token = FirebaseInstanceId.getInstance().getToken();

        OrderPresenter orderPresenter = new OrderPresenter(this, service);

//         submit header
        orderPresenter.postHeader(
                idOrder,
                name.isEmpty()?"-":name,
                email.isEmpty()?"-":email,
                contactNumber.isEmpty()?"-":contactNumber,
                address.isEmpty()?"-":address,
                statusOrder,
                statusOrderDesc,
                delveryFee,
                subTotal,
                total,
                token,
                paymentMethod
        );

        // submit order detail
        orderPresenter.postDetail(myCartList,idOrder);

        // update status order
        saveSharedPreference("statusOrder", 1);
    }

    @OnClick(R.id.btn_cash)
    public void cashClick(){
        changeBackgrounLayout(true, false, false);
    }

    @OnClick(R.id.btn_credit)
    public void creditClick(){
        changeBackgrounLayout(false, false, true);
    }

    @OnClick(R.id.btn_debet)
    public void debetClick(){
        changeBackgrounLayout(false, true, false);
    }

    public void changeBackgrounLayout(boolean cash, boolean debet, boolean credit){
        if(cash) {
            layoutCash.setBackground(backgrounLayoutRed);
            layoutCredit.setBackground(backgrounLayout);
            layoutDebet.setBackground(backgrounLayout);
            paymentMethod = "Cash";
        }
        if(credit) {
            layoutCash.setBackground(backgrounLayout);
            layoutCredit.setBackground(backgrounLayoutRed);
            layoutDebet.setBackground(backgrounLayout);
            paymentMethod = "Credit Card";
        }
        if(debet) {
            layoutCash.setBackground(backgrounLayout);
            layoutCredit.setBackground(backgrounLayout);
            layoutDebet.setBackground(backgrounLayoutRed);
            paymentMethod = "Debet Card";
        }
    }
}


text:
package vulcan

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/mailgun/iptools"
)

type Endpoint struct {
	ID   string
	Name string
	URL  string
}

func NewEndpoint(name, listenIP string, listenPort int) (*Endpoint, error) {
	id, err := makeEndpointID(listenPort)
	if err != nil {
		return nil, fmt.Errorf("failed to make endpoint ID: %v", err)
	}
	return NewEndpointWithID(id, name, listenIP, listenPort)
}

func NewEndpointWithID(id string, name string, listenIP string, listenPort int) (*Endpoint, error) {
	url, err := makeEndpointURL(listenIP, listenPort)
	if err != nil {
		return nil, fmt.Errorf("failed to make endpoint URL: %v", err)
	}
	return &Endpoint{
		ID:   id,
		Name: name,
		URL:  url,
	}, nil
}

func (e *Endpoint) BackendSpec() (string, error) {
	out, err := json.Marshal(&backend{Type: "http"})
	if err != nil {
		return "", err
	}
	return string(out), nil
}

func (e *Endpoint) ServerSpec() (string, error) {
	out, err := json.Marshal(&server{URL: e.URL})
	if err != nil {
		return "", err
	}
	return string(out), nil
}

func (e *Endpoint) String() string {
	return fmt.Sprintf("Endpoint(ID=%v, Name=%v, URL=%v)", e.ID, e.Name, e.URL)
}

// Construct an endpoint ID in the format of <hostname>_<port>.
func makeEndpointID(listenPort int) (string, error) {
	hostname, err := os.Hostname()
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%v_%v", hostname, listenPort), nil
}

// Construct an endpoint URL by determining the private IP address of the host.
func makeEndpointURL(listenIP string, listenPort int) (string, error) {
	// if an app is listening on a specific IP, use it
	if listenIP != "0.0.0.0" {
		return fmt.Sprintf("http://%v:%v", listenIP, listenPort), nil
	}

	// otherwise find a private IP
	privateIPs, err := iptools.GetPrivateHostIPs()
	if err != nil {
		return "", fmt.Errorf("failed to obtain host's private IPs: %v", err)
	}

	if len(privateIPs) == 0 {
		return "", fmt.Errorf("no host's private IPs are found")
	}

	return fmt.Sprintf("http://%v:%v", privateIPs[0], listenPort), nil
}

type backend struct {
	Type string
}

type server struct {
	URL string
}


text:
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using NGauge.Specs.Writer.Factories;
using NGauge.Specs.Writer.Services;
using NSubstitute;
using Ploeh.AutoFixture.Xunit2;
using Xunit;

namespace NGauge.Specs.Writer.Tests.Services
{
    public sealed class CodeSavingServiceTests
    {
        [Fact]
        public void ctor_IndentedTextWriterFactoryRequired()
        {
            Assert.Throws<ArgumentNullException>(
                "indentedTextWriterFactory",
                () => new CodeSavingService(
                    null,
                    Substitute.For<CodeDomProvider>()));
        }

        [Fact]
        public void ctor_CodeDomProviderRequired()
        {
            Assert.Throws<ArgumentNullException>(
                "codeDomProvider",
                () => new CodeSavingService(
                    Substitute.For<IIndentedTextWriterFactory>(),
                    null));
        }

        [Fact]
        public void Save_GeneratedCodeRequired()
        {
            var codeSavingService = CreateCodeSavingService();

            Assert.Throws<ArgumentNullException>(
                "generatedCode",
                () => codeSavingService.Save(
                    null,
                    "some path"));
        }

        [Theory]
        [InlineData("")]
        [InlineData(" ")]
        [InlineData(null)]
        public void Save_PathRequired(string path)
        {
            var codeSavingService = CreateCodeSavingService();

            Assert.Throws<ArgumentNullException>(
                "path",
                () => codeSavingService.Save(
                    Substitute.For<CodeCompileUnit>(),
                    path));
        }

        [Fact]
        public void Save_GeneratedCodeMustHaveAtLeastOneNamespace()
        {
            var codeSavingService = CreateCodeSavingService();

            Assert.Throws<ArgumentException>(
                "generatedCode",
                () => codeSavingService.Save(new CodeCompileUnit(), "some path"));
        }

        [Fact]
        public void Save_GeneratedCodeFirstNamespaceMustHaveAtLeastOneType()
        {
            var codeSavingService = CreateCodeSavingService();
            var generatedCode = new CodeCompileUnit();
            generatedCode.Namespaces.Add(new CodeNamespace());

            Assert.Throws<ArgumentException>(
                "generatedCode",
                () => codeSavingService.Save(generatedCode, "some path"));
        }

        [Theory]
        [InlineData("")]
        [InlineData(" ")]
        [InlineData(null)]
        public void Save_GeneratedCodeFirstNamespaceFirstTypeMustHaveName(string name)
        {
            var codeSavingService = CreateCodeSavingService();

            Assert.Throws<ArgumentException>(
                "generatedCode",
                () => codeSavingService.Save(GetMockGeneratedCode(name), "some path"));
        }

        [Theory, AutoData]
        public void Save_CreatesIndentedTextWriterWithExpectedPath(string path)
        {
            var indentedTextWriterFactory = GetMockIndentedTextWriterFactory();
            var codeSavingService = CreateCodeSavingService(indentedTextWriterFactory: indentedTextWriterFactory);

            codeSavingService.Save(GetMockGeneratedCode("some name"), path);

            indentedTextWriterFactory
                .Received()
                .Create(path, Arg.Any<string>());
        }

        [Theory, AutoData]
        public void Save_CreatesIndentedTextWriterWithExpectedFileName(string expectedName)
        {
            var indentedTextWriterFactory = GetMockIndentedTextWriterFactory();
            var codeSavingService = CreateCodeSavingService(indentedTextWriterFactory: indentedTextWriterFactory);
            var generatedCode = GetMockGeneratedCode(expectedName);

            codeSavingService.Save(generatedCode, "some path");

            indentedTextWriterFactory
                .Received()
                .Create(Arg.Any<string>(), Arg.Is<string>(name => name.StartsWith(expectedName) && name.EndsWith(".cs")));
        }

        [Fact]
        public void Save_GeneratesCodeFromCompiledUnit()
        {
            const string path = "some path";
            var indentedTextWriter = Substitute.For<TextWriter>();
            var indentedTextWriterFactory = Substitute.For<IIndentedTextWriterFactory>();
            indentedTextWriterFactory
                .Create(path, Arg.Any<string>())
                .Returns(indentedTextWriter);
            var codeDomProvider = Substitute.For<CodeDomProvider>();
            var codeSavingService = CreateCodeSavingService(
                indentedTextWriterFactory: indentedTextWriterFactory,
                codeDomProvider: codeDomProvider);
            var generatedCode = GetMockGeneratedCode("some name");

            codeSavingService.Save(generatedCode, path);

            codeDomProvider
                .Received()
                .GenerateCodeFromCompileUnit(
                    generatedCode,
                    indentedTextWriter,
                    Arg.Any<CodeGeneratorOptions>());
        }

        [Fact]
        public void Save_FlushesIndentedTextWriter()
        {
            var indentedTextWriter = Substitute.For<TextWriter>();
            var indentedTextWriterFactory = Substitute.For<IIndentedTextWriterFactory>();
            indentedTextWriterFactory
                .Create(Arg.Any<string>(), Arg.Any<string>())
                .Returns(indentedTextWriter);

            var codeSavingService = CreateCodeSavingService(indentedTextWriterFactory: indentedTextWriterFactory);

            codeSavingService.Save(GetMockGeneratedCode("some name"), "some path");

            indentedTextWriter
                .Received()
                .Flush();
        }

        private static ICodeSavingService CreateCodeSavingService(
            IIndentedTextWriterFactory indentedTextWriterFactory = null, CodeDomProvider codeDomProvider = null)
        {
            return new CodeSavingService(
                indentedTextWriterFactory ?? GetMockIndentedTextWriterFactory(),
                codeDomProvider           ?? Substitute.For<CodeDomProvider>());
        }

        private static IIndentedTextWriterFactory GetMockIndentedTextWriterFactory()
        {
            var factory = Substitute.For<IIndentedTextWriterFactory>();

            factory
                .Create(Arg.Any<string>(), Arg.Any<string>())
                .Returns(Substitute.For<TextWriter>());

            return factory;
        }

        private static CodeCompileUnit GetMockGeneratedCode(string expectedName)
        {
            var generatedCode = new CodeCompileUnit();
            var type = new CodeTypeDeclaration(expectedName);
            var ns = new CodeNamespace();

            ns.Types.Add(type);
            generatedCode.Namespaces.Add(ns);

            return generatedCode;
        }
    }
}


text:
<!doctype html>

  <meta charset="UTF-8">
  <title>Lavender Contrast</title>

PrettyPrint

This theme is for Google Code Prettify which can be used to syntax highlight code within a &ltpre> tag.

To use, simply copy and paste the CSS from the source of this document into your project, and use with an existing code prettify setup. You can either add the 'theme-lavender-contrast' class each &ltpre> element, or just remove it from the CSS to style all of them.

Enjoy!

<?php

// app/controllers/ArticleController.php

class ArticleController extends BaseController
{
    public function showIndex()
    {
        return View::make('index');
    }

    public function showSingle($articleId)
    {
        return View::make('single');
    }
}


text:
var yargs = require("yargs")
             .usage("Usage: $0 [path]")
             .alias("o", "output")
             .boolean("h")
             .alias("h", "help")
             .demand(1);

var argv = yargs.argv;

var vvalues = require('./vvalues');
var fs = require("fs");

exports.run = function() {
    var infile = argv._[0];
    var outfile = argv.output;

    var code = fs.readFileSync(infile, "utf8");
    var compiled = vvalues.compile(code);

    if (outfile) {
        fs.writeFileSync(outfile, compiled);
    } else {
        console.log(compiled);
    }
}


text:
Week of {{ todayDate }}

<weekchart [dayOfWeek]=todayDoW [content]=week></weekchart>


text:
/* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */

using System;
using System.Text;
using Razorvine.Pickle;
using Razorvine.Pyro;

namespace Pyrolite.TestPyroEcho
{

/// <summary>
/// Test Pyro with the Pyro echo server.
/// </summary>
public class TestEcho {

	public static void Main(String[] args) {
		try {
			Test();
		} catch (Exception x) {
			Console.WriteLine("unhandled exception: {0}",x);
		}
	}

	public static void Test() {

		Console.WriteLine("Testing Pyro echo server (make sure it's running on localhost 9999)...");
		Console.WriteLine("Pyrolite version: "+Config.PYROLITE_VERSION);

		setConfig();

		PyroProxy p=new PyroProxy("localhost",9999,"test.echoserver");

		Object x=42;
		Console.WriteLine("echo param:");
		PrettyPrint.print(x);
		Object result=p.call("echo", x);
		Console.WriteLine("return value:");
		PrettyPrint.print(result);

		String s="This string is way too long. This string is way too long. This string is way too long. This string is way too long. ";
		s=s+s+s+s+s;
		Console.WriteLine("echo param:");
		PrettyPrint.print(s);
		result=p.call("echo", s);
		Console.WriteLine("return value:");
		PrettyPrint.print(result);

		Console.WriteLine("error test.");
		try {
			result=p.call("error");
		} catch (PyroException e) {
			Console.WriteLine("Pyro Exception (expected)! {0}",e.Message);
			Console.WriteLine("Pyro Exception cause: {0}",e.InnerException);
			Console.WriteLine("Pyro Exception remote traceback:\n>>>\n{0}<<<",e._pyroTraceback);
		}

		Console.WriteLine("shutting down the test echo server.");
		p.call("shutdown");
	}

	static void setConfig()
	{
		string hmackey=Environment.GetEnvironmentVariable("PYRO_HMAC_KEY");
		if(hmackey!=null) {
			Config.HMAC_KEY=Encoding.UTF8.GetBytes(hmackey);
		}
		string tracedir=Environment.GetEnvironmentVariable("PYRO_TRACE_DIR");
		if(tracedir!=null) {
			Config.MSG_TRACE_DIR=tracedir;
		}
	}
}

}


text:
package stuff;

import processing.core.PApplet;

import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.SimpleLinesMarker;
import de.fhpotsdam.unfolding.marker.SimplePointMarker;
import de.fhpotsdam.unfolding.providers.Google;
import de.fhpotsdam.unfolding.utils.MapUtils;

/**
 * Simple example with three markers, managed by the MarkerManager. Displays two point markers, and one line marker.
 *
 * Managing and drawing the markers is handled internally, with all markers cut-off at the border of the map.
 * Unfolding's simple marker (SimpleMarker, SimpleLinesMarker, and SimplePolygonMarker) provide some styling
 * functionality. For more customization you need to create your own Marker classes.
 */
@SuppressWarnings("serial")
public class MarkerManager extends PApplet {

	UnfoldingMap map;

	public void setup() {
		size(800, 600, OPENGL);

		map = new UnfoldingMap(this, new Google.GoogleMapProvider());

		map.zoomToLevel(3);
		map.panTo(new Location(40f, -42f));
		MapUtils.createDefaultEventDispatcher(this, map);

		// Create Markers from Locations
		Location berlinLocation = new Location(52.5f, 13.4f);
		Location mexicoCityLocation = new Location(19.4f, -99.1f);

		// Point Markers
		SimplePointMarker berlinMarker = new SimplePointMarker(berlinLocation);
		SimplePointMarker mexicoCityMarker = new SimplePointMarker(mexicoCityLocation);
		// Line Marker
		SimpleLinesMarker connectionMarker = new SimpleLinesMarker(berlinLocation, mexicoCityLocation);

		// Add Markers to the maps default MarkerManager
		map.addMarkers(berlinMarker, mexicoCityMarker, connectionMarker);

		// Adapt style
		berlinMarker.setColor(color(255, 20, 0, 50));
		berlinMarker.setStrokeColor(color(255, 0, 0));
		berlinMarker.setStrokeWeight(1);
	}

	public void draw() {
		background(240);

		// Drawing Markers in handled internally
		map.draw();
	}

}


text:
Ansible playbook to setup a multimedia server in Centos that includes:

  - Plex Media Server [https://www.plex.tv/](https://www.plex.tv/).
  - BitTorrent client [https://transmissionbt.com/](https://transmissionbt.com/)
  - Download torrent files automatically using [http://flexget.com/](http://flexget.com/)

## Testing

You can test everything with Vagrant. Just run the following command to setup and provision the whole environment:

    vagrant up

If you want to apply any modification to the default configuration just re-provision your VM running:

    vagrant provision

If you are not interested anymore, just run the following command to remove the VM and save some space.

    vagrant destroy

## Installation

So you finally decide to install this playbook, great!. Before running your Ansible playbook against your machine you need to:

 - modify your *inventory/all* file to include your ip address.
 - run Ansible playbook:

    ansible-playbook -i inventory/all site.yml -K

## Plex Media Server

Plex should be accessible at http://your_ip/plex

### Plugins/Channels/Bundles

You basically have two options:

  - Install plugins from a git repo such as [Plex plug-ins git repo](https://github.com/plexinc-plugins).
  - Copying a zip bundle inside the "*files*" folder in plex-server role.

#### Git repo
Add plugins needed to *git_plex_plugins* property in plex-server role.

    git_plex_plugins:
      - "https://github.com/plexinc-plugins/ABC.bundle.git"
      - "https://github.com/plexinc-plugins/Vimeo.bundle.git"

#### Zip bundle
Copy your zip bundle inside the "*files*" folder in the plex-server role, and ansible will install it for you.

## Transmission

Transmission BitTorrent web client should be accessible at http://your_ip/transmission

- Username: transmission
- Password: transmission

## Flexget


text:
#ifndef Py_CURSES_H
#define Py_CURSES_H

#ifdef __APPLE__
/*
** On Mac OS X 10.2 [n]curses.h and stdlib.h use different guards
** against multiple definition of wchar_t.
*/
#ifdef	_BSD_WCHAR_T_DEFINED_
#define _WCHAR_T
#endif
#endif

#ifdef __FreeBSD__
/*
** On FreeBSD, [n]curses.h and stdlib.h/wchar.h use different guards
** against multiple definition of wchar_t and wint_t.
*/
#ifdef	_XOPEN_SOURCE_EXTENDED
#ifndef __FreeBSD_version
#include <osreldate.h>
#endif
#if __FreeBSD_version >= 500000
#ifndef __wchar_t
#define __wchar_t
#endif
#ifndef __wint_t
#define __wint_t
#endif
#else
#ifndef _WCHAR_T
#define _WCHAR_T
#endif
#ifndef _WINT_T
#define _WINT_T
#endif
#endif
#endif
#endif

#ifdef HAVE_NCURSES_H
#include <ncurses.h>
#else
#include <curses.h>
#ifdef HAVE_TERM_H
/* for tigetstr, which is not declared in SysV curses */
#include <term.h>
#endif
#endif

#ifdef HAVE_NCURSES_H
/* configure was checking <curses.h>, but we will
   use <ncurses.h>, which has all these features. */
#ifndef WINDOW_HAS_FLAGS
#define WINDOW_HAS_FLAGS 1
#endif
#ifndef MVWDELCH_IS_EXPRESSION
#define MVWDELCH_IS_EXPRESSION 1
#endif
#endif

#ifdef __cplusplus
extern "C" {
#endif

#define PyCurses_API_pointers 4

/* Type declarations */

typedef struct {
	PyObject_HEAD
	WINDOW *win;
} PyCursesWindowObject;

#define PyCursesWindow_Check(v)	 ((v)->ob_type == &PyCursesWindow_Type)

#ifdef CURSES_MODULE
/* This section is used when compiling _cursesmodule.c */

#else
/* This section is used in modules that use the _cursesmodule API */

static void **PyCurses_API;

#define PyCursesWindow_Type (*(PyTypeObject *) PyCurses_API[0])
#define PyCursesSetupTermCalled  {if (! ((int (*)(void))PyCurses_API[1]) () ) return NULL;}
#define PyCursesInitialised      {if (! ((int (*)(void))PyCurses_API[2]) () ) return NULL;}
#define PyCursesInitialisedColor {if (! ((int (*)(void))PyCurses_API[3]) () ) return NULL;}

#define import_curses() \
{ \
  PyObject *module = PyImport_ImportModule("_curses"); \
  if (module != NULL) { \
    PyObject *module_dict = PyModule_GetDict(module); \
    PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \
    if (PyCObject_Check(c_api_object)) { \
      PyCurses_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
    } \
  } \
}
#endif

/* general error messages */
static char *catchall_ERR  = "curses function returned ERR";
static char *catchall_NULL = "curses function returned NULL";

/* Function Prototype Macros - They are ugly but very, very useful. ;-)

   X - function name
   TYPE - parameter Type
   ERGSTR - format string for construction of the return value
   PARSESTR - format string for argument parsing
   */

#define NoArgNoReturnFunction(X) \
static PyObject *PyCurses_ ## X (PyObject *self) \
{ \
  PyCursesInitialised \
  return PyCursesCheckERR(X(), # X); }

#define NoArgOrFlagNoReturnFunction(X) \
static PyObject *PyCurses_ ## X (PyObject *self, PyObject *args) \
{ \
  int flag = 0; \
  PyCursesInitialised \
  switch(PyTuple_Size(args)) { \
  case 0: \
    return PyCursesCheckERR(X(), # X); \
  case 1: \
    if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; \
    if (flag) return PyCursesCheckERR(X(), # X); \
    else return PyCursesCheckERR(no ## X (), # X); \
  default: \
    PyErr_SetString(PyExc_TypeError, # X " requires 0 or 1 arguments"); \
    return NULL; } }

#define NoArgReturnIntFunction(X) \
static PyObject *PyCurses_ ## X (PyObject *self) \
{ \
 PyCursesInitialised \
 return PyInt_FromLong((long) X()); }

#define NoArgReturnStringFunction(X) \
static PyObject *PyCurses_ ## X (PyObject *self) \
{ \
  PyCursesInitialised \
  return PyString_FromString(X()); }

#define NoArgTrueFalseFunction(X) \
static PyObject *PyCurses_ ## X (PyObject *self) \
{ \
  PyCursesInitialised \
  if (X () == FALSE) { \
    Py_INCREF(Py_False); \
    return Py_False; \
  } \
  Py_INCREF(Py_True); \
  return Py_True; }

#define NoArgNoReturnVoidFunction(X) \
static PyObject *PyCurses_ ## X (PyObject *self) \
{ \
  PyCursesInitialised \
  X(); \
  Py_INCREF(Py_None); \
  return Py_None; }

#ifdef __cplusplus
}
#endif

#endif /* !defined(Py_CURSES_H) */


text:
//
//  GameplayScene.h
//  SurvivalDungeon
//
//  Created by Marlon Andrade on 16/02/2015.
//
//

#ifndef __SurvivalDungeon__GameplayScene__
#define __SurvivalDungeon__GameplayScene__

#include "cocos2d.h"

#include "Game.h"
#include "Turn.h"

class DungeonLayer;
class HudLayer;
class PlayerTurnLayer;
class TurnChangeLayer;

class GameplayScene : public cocos2d::Scene {
  CC_SYNTHESIZE_RETAIN(cocos2d::EventListenerCustom*,
                       _actionDicesRolledListener,
                       ActionDicesRolledListener);
  CC_SYNTHESIZE_RETAIN(cocos2d::EventListenerCustom*,
                       _levelAdvancedListener,
                       LevelAdvancedListener);
  CC_SYNTHESIZE_RETAIN(cocos2d::EventListenerCustom*,
                       _experienceChangedListener,
                       ExperienceChangedListener);
  CC_SYNTHESIZE_RETAIN(cocos2d::EventListenerCustom*,
                       _coinsChangedListener,
                       CoinsChangedListener);
  CC_SYNTHESIZE_RETAIN(cocos2d::EventListenerCustom*,
                       _characterDiedListener,
                       CharacterDiedListener);
  CC_SYNTHESIZE_RETAIN(cocos2d::EventListenerCustom*,
                       _turnHasStartedListener,
                       TurnHasStartedListener);
  CC_SYNTHESIZE_RETAIN(cocos2d::EventListenerCustom*,
                       _turnHasEndedListener,
                       TurnHasEndedListener);

public:
  virtual bool init();
  CREATE_FUNC(GameplayScene);

  DungeonLayer* getDungeonLayer();

private:
  void _setupChildren();

  void _setupEventHandlers();

  HudLayer* _getHudLayer();
  PlayerTurnLayer* _getPlayerTurnLayer();
  TurnChangeLayer* _getTurnChangeLayer();

  void _roomsHasBeenPlaced(cocos2d::Vector<RoomPlacementData*> placements);

#pragma mark - Events
  void _handleActionDicesRolled(cocos2d::EventCustom* event);
  void _handleLevelAdvanced(cocos2d::EventCustom* event);
  void _handleExperienceChanged(cocos2d::EventCustom* event);
  void _handleCoinsChanged(cocos2d::EventCustom* event);
  void _handleCharacterDied(cocos2d::EventCustom* event);
  void _handleTurnHasStarted(cocos2d::EventCustom* event);
  void _handleTurnHasEnded(cocos2d::EventCustom* event);

};

#endif /* defined(__SurvivalDungeon__GameplayScene__) */


text:
package com.amazonaws.geo.model;

import com.amazonaws.services.dynamodbv2.model.BatchWriteItemResult;

public class BatchWritePointResult {
	private BatchWriteItemResult batchWriteItemResult;

	public BatchWritePointResult(BatchWriteItemResult batchWriteItemResult) {
		this.batchWriteItemResult = batchWriteItemResult;
	}

	public BatchWriteItemResult getBatchWriteItemResult() {
		return batchWriteItemResult;
	}
}


text:
package org.apache.activemq.artemis.protocol.amqp.proton;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.activemq.artemis.core.server.ServerProducer;
import org.apache.activemq.artemis.core.server.impl.ServerProducerImpl;
import org.apache.activemq.artemis.protocol.amqp.broker.AMQPSessionCallback;
import org.apache.activemq.artemis.protocol.amqp.client.ProtonClientSenderContext;
import org.apache.activemq.artemis.protocol.amqp.exceptions.ActiveMQAMQPException;
import org.apache.activemq.artemis.protocol.amqp.exceptions.ActiveMQAMQPInternalErrorException;
import org.apache.activemq.artemis.protocol.amqp.proton.transaction.ProtonTransactionHandler;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.transaction.Coordinator;
import org.apache.qpid.proton.amqp.transport.ErrorCondition;
import org.apache.qpid.proton.engine.Receiver;
import org.apache.qpid.proton.engine.Sender;
import org.apache.qpid.proton.engine.Session;
import org.jboss.logging.Logger;

public class AMQPSessionContext extends ProtonInitializable {

   private static final Logger log = Logger.getLogger(AMQPSessionContext.class);
   protected final AMQPConnectionContext connection;

   protected final AMQPSessionCallback sessionSPI;

   protected final Session session;

   protected Map<Receiver, ProtonServerReceiverContext> receivers = new ConcurrentHashMap<>();

   protected Map<Sender, ProtonServerSenderContext> senders = new ConcurrentHashMap<>();

   protected boolean closed = false;

   protected final AmqpTransferTagGenerator tagCache = new AmqpTransferTagGenerator();

   public AMQPSessionContext(AMQPSessionCallback sessionSPI, AMQPConnectionContext connection, Session session) {
      this.connection = connection;
      this.sessionSPI = sessionSPI;
      this.session = session;
   }

   protected Map<Object, ProtonServerSenderContext> serverSenders = new ConcurrentHashMap<>();

   @Override
   public void initialise() throws Exception {
      if (!isInitialized()) {
         super.initialise();

         if (sessionSPI != null) {
            try {
               sessionSPI.init(this, connection.getSASLResult());
            } catch (Exception e) {
               throw new ActiveMQAMQPInternalErrorException(e.getMessage(), e);
            }
         }
      }
   }

   /**
    * @param consumer
    * @param queueName
    */
   public void disconnect(Object consumer, String queueName) {
      ProtonServerSenderContext protonConsumer = senders.remove(consumer);
      if (protonConsumer != null) {
         try {
            protonConsumer.close(false);
         } catch (ActiveMQAMQPException e) {
            protonConsumer.getSender().setTarget(null);
            protonConsumer.getSender().setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
         }
      }
   }

   public byte[] getTag() {
      return tagCache.getNextTag();
   }

   public void replaceTag(byte[] tag) {
      tagCache.returnTag(tag);
   }

   public void close() {
      if (closed) {
         return;
      }

      // Making a copy to avoid ConcurrentModificationException during the iteration
      Set<ProtonServerReceiverContext> receiversCopy = new HashSet<>();
      receiversCopy.addAll(receivers.values());

      for (ProtonServerReceiverContext protonProducer : receiversCopy) {
         try {
            protonProducer.close(false);
         } catch (Exception e) {
            log.warn(e.getMessage(), e);
         }
      }
      receivers.clear();

      Set<ProtonServerSenderContext> protonSendersClone = new HashSet<>();
      protonSendersClone.addAll(senders.values());

      for (ProtonServerSenderContext protonConsumer : protonSendersClone) {
         try {
            protonConsumer.close(false);
         } catch (Exception e) {
            log.warn(e.getMessage(), e);
         }
      }
      senders.clear();
      try {
         if (sessionSPI != null) {
            sessionSPI.close();
         }
      } catch (Exception e) {
         log.warn(e.getMessage(), e);
      }
      closed = true;
   }

   public void removeReceiver(Receiver receiver) {
      sessionSPI.removeProducer(receiver.getName());
      receivers.remove(receiver);
   }

   public void addTransactionHandler(Coordinator coordinator, Receiver receiver) {
      ProtonTransactionHandler transactionHandler = new ProtonTransactionHandler(sessionSPI, connection);

      coordinator.setCapabilities(Symbol.getSymbol("amqp:local-transactions"), Symbol.getSymbol("amqp:multi-txns-per-ssn"), Symbol.getSymbol("amqp:multi-ssns-per-txn"));

      receiver.setContext(transactionHandler);
      connection.lock();
      try {
         receiver.open();
         receiver.flow(connection.getAmqpCredits());
      } finally {
         connection.unlock();
      }
   }

   public void addSender(Sender sender) throws Exception {
      // TODO: Remove this check when we have support for global link names
      boolean outgoing = (sender.getContext() != null && sender.getContext().equals(true));
      ProtonServerSenderContext protonSender = outgoing ? new ProtonClientSenderContext(connection, sender, this, sessionSPI) : new ProtonServerSenderContext(connection, sender, this, sessionSPI);

      try {
         protonSender.initialise();
         senders.put(sender, protonSender);
         serverSenders.put(protonSender.getBrokerConsumer(), protonSender);
         sender.setContext(protonSender);
         connection.lock();
         try {
            sender.open();
         } finally {
            connection.unlock();
         }

         protonSender.start();
      } catch (ActiveMQAMQPException e) {
         senders.remove(sender);
         sender.setSource(null);
         sender.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
         connection.lock();
         try {
            sender.close();
         } finally {
            connection.unlock();
         }
      }
   }

   public void removeSender(Sender sender) throws ActiveMQAMQPException {
      senders.remove(sender);
      ProtonServerSenderContext senderRemoved = senders.remove(sender);
      if (senderRemoved != null) {
         serverSenders.remove(senderRemoved.getBrokerConsumer());
      }
   }

   public void addReceiver(Receiver receiver) throws Exception {
      try {
         ProtonServerReceiverContext protonReceiver = new ProtonServerReceiverContext(sessionSPI, connection, this, receiver);
         protonReceiver.initialise();
         receivers.put(receiver, protonReceiver);
         ServerProducer serverProducer = new ServerProducerImpl(receiver.getName(), "AMQP", receiver.getTarget().getAddress());
         sessionSPI.addProducer(serverProducer);
         receiver.setContext(protonReceiver);
         connection.lock();
         try {
            receiver.open();
         } finally {
            connection.unlock();
         }
      } catch (ActiveMQAMQPException e) {
         receivers.remove(receiver);
         receiver.setTarget(null);
         receiver.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
         connection.lock();
         try {
            receiver.close();
         } finally {
            connection.unlock();
         }
      }
   }
}