text:
#include <iostream>
#include <string>
#include <thread>
#include <cmath>

#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <tf/transform_broadcaster.h>
#include "boost/date_time/posix_time/posix_time.hpp"

#include "System.h"
#include "Converter.h"
#include "../common.h"

using namespace std;
using namespace ORB_SLAM2;
using namespace boost::posix_time;
namespace enc = sensor_msgs::image_encodings;

class ORB_Matcher
{
public:
	ORB_Matcher (ORB_SLAM2::System& pSL, ros::NodeHandle &nh) :
		SLAMSystem (pSL), rosnode(nh),
		lastImageTimestamp (0.0),
		gotFirstFrame (false),
		lastKeyframeId (0)
	{
		externalFrameFixed = (string)pSL.fsSettings["Localization.frame1"];
		externalFrameMoving = (string)pSL.fsSettings["Localization.frame2"];
		offsetKeyframe = SLAMSystem.fsSettings["ExternalLocalization.OffsetKeyframes"];

		cout << "TF: From " << externalFrameFixed << " to " << externalFrameMoving << endl;

		// Image Subscription
	    if ((int)SLAMSystem.fsSettings["Camera.compressed"]==0) {
	    	th = image_transport::TransportHints ("raw");
	    }
	    else if ((int)SLAMSystem.fsSettings["Camera.compressed"]==1) {
	    	th = image_transport::TransportHints ("compressed");
	    }
		imageBuf = new image_transport::ImageTransport(rosnode);

		// Result Publishers
		string poseTopic;
		rosnode.getParam("pose_topic", poseTopic);
		posePublisher = rosnode.advertise<geometry_msgs::PoseStamped> (poseTopic, 1);
		mTfBr = new tf::TransformBroadcaster();

		// start of debug preparation
		cout << std::fixed << setprecision(7);
		visualDebugView = imageBuf->advertise("framebuffer", 1);
	}

	~ORB_Matcher ()
	{
		delete (imageBuf);
		delete (mTfBr);
	}

	void imageCallback (const sensor_msgs::ImageConstPtr& msg)
	{
		// Activate this timer if you need time logging
		ptime rT1, rT2;
		rT1 = microsec_clock::local_time();

		// Copy the ros image message to cv::Mat.
		cv_bridge::CvImageConstPtr cv_ptr;
		try
		{
			cv_ptr = cv_bridge::toCvShare(msg);
		}
		catch (cv_bridge::Exception& e)
		{
			ROS_ERROR("cv_bridge exception: %s", e.what());
			return;
		}

		cv::Mat image;
		// Check if we need debayering
		if (enc::isBayer(msg->encoding)) {
			int code=-1;
			if (msg->encoding == enc::BAYER_RGGB8 ||
				msg->encoding == enc::BAYER_RGGB16) {
				code = cv::COLOR_BayerBG2BGR;
			}
			else if (msg->encoding == enc::BAYER_BGGR8 ||
					 msg->encoding == enc::BAYER_BGGR16) {
				code = cv::COLOR_BayerRG2BGR;
			}
			else if (msg->encoding == enc::BAYER_GBRG8 ||
					 msg->encoding == enc::BAYER_GBRG16) {
				code = cv::COLOR_BayerGR2BGR;
			}
			else if (msg->encoding == enc::BAYER_GRBG8 ||
					 msg->encoding == enc::BAYER_GRBG16) {
				code = cv::COLOR_BayerGB2BGR;
			}
			cv::cvtColor(cv_ptr->image, image, code);
		}
		else
			image = cv_ptr->image;

		const double imageTime = msg->header.stamp.toSec();
		lastImageTimestamp = imageTime;

		if (gotFirstFrame==false) {
			double fx2, fy2, cx2, cy2;
			recomputeNewCameraParameter (
				(double)SLAMSystem.fsSettings["Camera.fx"],
				(double)SLAMSystem.fsSettings["Camera.fy"],
				(double)SLAMSystem.fsSettings["Camera.cx"],
				(double)SLAMSystem.fsSettings["Camera.cy"],
				fx2, fy2, cx2, cy2,
				msg->width, msg->height,
				(int)SLAMSystem.fsSettings["Camera.WorkingResolution.Width"],
				(int)SLAMSystem.fsSettings["Camera.WorkingResolution.Height"]);
			// send camera parameters to tracker
			SLAMSystem.getTracker()->ChangeCalibration (fx2, fy2, cx2, cy2);
			gotFirstFrame = true;
		}

		// Processing before sending image to tracker
		// Do Resizing and cropping here
		cv::resize(image, image,
			cv::Size(
				(int)SLAMSystem.fsSettings["Camera.WorkingResolution.Width"],
				(int)SLAMSystem.fsSettings["Camera.WorkingResolution.Height"]
			));
		image = image(
			cv::Rect(
				(int)SLAMSystem.fsSettings["Camera.ROI.x0"],
				(int)SLAMSystem.fsSettings["Camera.ROI.y0"],
				(int)SLAMSystem.fsSettings["Camera.ROI.width"],
				(int)SLAMSystem.fsSettings["Camera.ROI.height"]
			)).clone();

		SLAMSystem.TrackMonocular(image, imageTime);

		// Reinsert TF publisher, but only for localization. Original ORB-SLAM2 removes it.
		bool tfOk = false;
		tf::Transform locRef;

		Frame &cframe = SLAMSystem.getTracker()->mCurrentFrame;
		if (SLAMSystem.getTracker()->trackingIsGood())
		{

			tf::Transform tfTcw = FramePose(&cframe);
			mTfBr->sendTransform(tf::StampedTransform(tfTcw, ros::Time(imageTime), "/ORB_SLAM/World", "/ORB_SLAM/Camera"));

	//		 Here, we use offset of external localization from the keyframe

				try {
					locRef = localizeByReference(tfTcw);
					publishPose(&locRef);
					tfOk = true;
//					lastDebugMessage = "";
				} catch (exception &e) {
//					lastDebugMessage = e.what();
					publishPose(NULL);
				}

		} else {
			publishPose (NULL);
		}

		rT2 = microsec_clock::local_time();
//		cputimeDebug = (rT2-rT1).total_microseconds() * 1e-6;

		// Debugging
		SLAMSystem.getFrameDrawer()->DrawFrame();
		cv::Mat framebufferDbg = SLAMSystem.getFrameDrawer()->getLastFrame();
		cv_bridge::CvImage bagImage;
		bagImage.image = framebufferDbg;
		bagImage.header.stamp = ros::Time(lastImageTimestamp);
		bagImage.encoding = "bgr8";
		visualDebugView.publish(bagImage.toImageMsg());
	}

private:
	tf::Transform localizeByReference (const tf::Transform &tfOrb, ORB_SLAM2::KeyFrame *kf)
	{
		lastKeyframeId = kf->mnId;

		ORB_SLAM2::KeyFrame *kOffset = SLAMSystem.getMap()->offsetKeyframe(kf, offsetKeyframe);
		if (kOffset==NULL)
			throw std::out_of_range("No offset keyframe found");

		if (kf->extPosition.empty() or kOffset->extPosition.empty())
			throw std::out_of_range("External reference of keyframe not found");

		tf::Transform kfTr = KeyFramePoseToTf(kf);
		tf::Transform extRef = getKeyFrameExtPose(kf);

		tf::Transform kfTrOffset = KeyFramePoseToTf(kOffset);
		tf::Transform extRefOffset = getKeyFrameExtPose(kOffset);
		return localizeByReference (tfOrb, kfTr, kfTrOffset, extRef, extRefOffset);
	}

	tf::Transform rotateAxes (const tf::Transform &cPose, const float roll=0, const float pitch=0, const float yaw=0)
	{
		tf::Transform rotation;
		rotation.setOrigin (tf::Vector3 (0,0,0));
		rotation.setRotation (tf::Quaternion(roll, pitch, yaw).normalize());
		return cPose * rotation;
	}

	/*
	 * Main routine for localization by reference
	 */
	tf::Transform localizeByReference (
	    	const tf::Transform &tfOrb,
			const tf::Transform &tfOrbMap, const tf::Transform &tfOrbMapOffset,
	    	const tf::Transform &realMapPose, const tf::Transform &realMapOffset)
	{
		double offDistO = cv::norm(
			tfToCv(tfOrbMap.getOrigin()) -
			tfToCv(tfOrbMapOffset.getOrigin()));
		double offDistE = cv::norm(
			tfToCv(realMapPose.getOrigin()) -
			tfToCv(realMapOffset.getOrigin()));
		double scale = offDistE / offDistO;

		// change orientation from camera to velodyne
		tf::Transform flipAxes;
		flipAxes.setOrigin(tf::Vector3(0, 0, 0));
		flipAxes.setRotation (tf::Quaternion(M_PI/2, 0, -M_PI/2).normalize());

		tf::Transform orbRel = tfOrbMap.inverse() * tfOrb;

		tf::Transform scaledRel = orbRel;
		scaledRel.setOrigin(orbRel.getOrigin() * scale);
		scaledRel = flipAxes*scaledRel;

		tf::Transform tfResult = realMapPose * scaledRel;

		// Still need to rotate axes
		return rotateAxes (tfResult, 0, M_PI/2, M_PI/2);
	}

	tf::Transform localizeByReference(const tf::Transform &tfOrb)
	{
		float fdirx = tfOrb.getRotation().x(),
			fdiry = tfOrb.getRotation().y(),
			fdirz = tfOrb.getRotation().z(),
			fdirnorm;
		fdirnorm = sqrtf(fdirx*fdirx + fdiry*fdiry + fdirz*fdirz);
		fdirx /= fdirnorm;
		fdiry /= fdirnorm;
		fdirz /= fdirnorm;

		ORB_SLAM2::KeyFrame *kfNear = SLAMSystem.getMap()->getNearestKeyFrame(
			tfOrb.getOrigin().x(),
			tfOrb.getOrigin().y(),
			tfOrb.getOrigin().z(),
			fdirx, fdiry, fdirz);
		if (kfNear==NULL)
			throw std::out_of_range("No nearest keyframe found");

		lastKeyframeId = kfNear->mnId;
		return localizeByReference (tfOrb, kfNear);
	}

	tf::Transform localizeByReference(Frame *sframe)
	{
	//	const tf::Transform
	}

	tf::Transform localizeByReference(const tf::Transform &tfOrb, ORB_SLAM2::Map *mapsrc, const int offsetNum)
	{
		float positiondir[6];
		tf2positiondirection(tfOrb, positiondir);

		ORB_SLAM2::KeyFrame *kfNear = mapsrc->getNearestKeyFrame(
			positiondir[0], positiondir[1], positiondir[2],
			positiondir[3], positiondir[4], positiondir[5]);
		if (kfNear==NULL)
			throw std::out_of_range("No keyframe found");
		ORB_SLAM2::KeyFrame *kOffset = mapsrc->offsetKeyframe(kfNear, offsetNum);
		if (kOffset==NULL)
			throw std::out_of_range("No offset keyframe found");

		tf::Transform kfTr = KeyFramePoseToTf(kfNear);
		tf::Transform extRef = getKeyFrameExtPose(kfNear);

		tf::Transform kfTrOffset = KeyFramePoseToTf(kOffset);
		tf::Transform extRefOffset = getKeyFrameExtPose(kOffset);

		return localizeByReference (tfOrb, kfTr, kfTrOffset, extRef, extRefOffset);
	}

	tf2_msgs::TFMessage createTfMessage (const tf::Transform &srcTransform,
		const string &frameSrc, const string &frameTarget,
		double timestamp=-1)
	{
		ros::Time msgTime;
		tf2_msgs::TFMessage tfretval;

		if (timestamp>0)
			msgTime = ros::Time(timestamp);
		else msgTime = ros::Time::now();

		geometry_msgs::TransformStamped newTransform;
		newTransform.header.stamp = msgTime;
		newTransform.header.frame_id = frameSrc;
		newTransform.child_frame_id = frameTarget;
		newTransform.transform.translation.x = srcTransform.getOrigin().x();
		newTransform.transform.translation.y = srcTransform.getOrigin().y();
		newTransform.transform.translation.z = srcTransform.getOrigin().z();
		newTransform.transform.rotation.x = srcTransform.getRotation().x();
		newTransform.transform.rotation.y = srcTransform.getRotation().y();
		newTransform.transform.rotation.z = srcTransform.getRotation().z();
		newTransform.transform.rotation.w = srcTransform.getRotation().w();
		tfretval.transforms.push_back (newTransform);

		return tfretval;
	}

	tf::Transform getKeyFrameExtPose (const KeyFrame *kf)
	{
		tf::Transform Ext;

		if (kf->extPosition.empty() or kf->extOrientation.empty()) {
			Ext.setOrigin(tf::Vector3(NAN, NAN, NAN));
			Ext.setRotation(tf::Quaternion(NAN, NAN, NAN, NAN));
		}

		else {
			Ext.setOrigin (tf::Vector3(
				kf->extPosition.at<double>(0),
				kf->extPosition.at<double>(1),
				kf->extPosition.at<double>(2) ));
			Ext.setRotation(tf::Quaternion(
				kf->extOrientation.at<double>(0),
				kf->extOrientation.at<double>(1),
				kf->extOrientation.at<double>(2),
				kf->extOrientation.at<double>(3) ));
		}
		return Ext;
	}

	tf::Transform KeyFramePoseToTf (KeyFrame *kf)
	{
		tf::Transform kfpose;

		cv::Mat t = kf->GetCameraCenter();
		cv::Mat orient = kf->GetRotation().t();
		vector<float> q = ORB_SLAM2::Converter::toQuaternion(orient);

		kfpose.setOrigin(tf::Vector3(t.at<float>(0), t.at<float>(1), t.at<float>(2)));
		kfpose.setRotation(tf::Quaternion(q[0], q[1], q[2], q[3]));

		return kfpose;
	}

	cv::Vec3d tfToCv (const tf::Vector3 &pos)
	{
		cv::Vec3d cvVec;
		cvVec[0] = pos.x();
		cvVec[1] = pos.y();
		cvVec[2] = pos.z();
		return cvVec;
	}

	cv::Mat tfToCv (const tf::Transform &tfsrc)
	{
		cv::Mat rtval = cv::Mat::eye(4,4, CV_32F);
		rtval.rowRange(0, 3).col(3).at<float>(0) = tfsrc.getOrigin().x();
		rtval.rowRange(0, 3).col(3).at<float>(1) = tfsrc.getOrigin().y();
		rtval.rowRange(0, 3).col(3).at<float>(2) = tfsrc.getOrigin().z();

		tf::Matrix3x3 rot (tfsrc.getRotation());
		for (int i=0; i<3; i++) {
			for (int j=0; j<3; j++) {
				rtval.at<float>(i,j) = rot[i][j];
			}
		}
		return rtval;
	}

	void publishPose (const tf::Transform *pose)
	{
		geometry_msgs::PoseStamped gpose;
		gpose.header.frame_id = externalFrameFixed;
		gpose.header.stamp = ros::Time(lastImageTimestamp);

		if (pose==NULL) {
			gpose.pose.position.x =
			gpose.pose.position.y =
			gpose.pose.position.z = 1e15;
			gpose.pose.orientation.x = 1.0;
			gpose.pose.orientation.y = .0;
			gpose.pose.orientation.z = .0;
			gpose.pose.orientation.w = .0;
		}

		else {
			gpose.pose.position.x = pose->getOrigin().x();
			gpose.pose.position.y = pose->getOrigin().y();
			gpose.pose.position.z = pose->getOrigin().z();
			gpose.pose.orientation.x = pose->getRotation().x();
			gpose.pose.orientation.y = pose->getRotation().y();
			gpose.pose.orientation.z = pose->getRotation().z();
			gpose.pose.orientation.w = pose->getRotation().w();
			mTfBr->sendTransform (tf::StampedTransform(*pose, ros::Time(lastImageTimestamp), externalFrameFixed, externalFrameMoving));
		}

		posePublisher.publish (gpose);
	}

	void publishPoseWithCovariance (const tf::Transform *pose)
	{
		geometry_msgs::PoseWithCovarianceStamped gpose;
		gpose.header.frame_id = externalFrameFixed;
		gpose.header.stamp = ros::Time(lastImageTimestamp);

		// XXX: check how we can set the covariance

		if (pose==NULL) {
			gpose.pose.pose.position.x =
			gpose.pose.pose.position.y =
			gpose.pose.pose.position.z = 1e15;
			gpose.pose.pose.orientation.x = 1.0;
			gpose.pose.pose.orientation.y = .0;
			gpose.pose.pose.orientation.z = .0;
			gpose.pose.pose.orientation.w = .0;
		}

		else {
			gpose.pose.pose.position.x = pose->getOrigin().x();
			gpose.pose.pose.position.y = pose->getOrigin().y();
			gpose.pose.pose.position.z = pose->getOrigin().z();
			gpose.pose.pose.orientation.x = pose->getRotation().x();
			gpose.pose.pose.orientation.y = pose->getRotation().y();
			gpose.pose.pose.orientation.z = pose->getRotation().z();
			gpose.pose.pose.orientation.w = pose->getRotation().w();

			tf::StampedTransform tfMsg;
			tfMsg.stamp_ = ros::Time(lastImageTimestamp);
			tfMsg.frame_id_ = externalFrameFixed;
			tfMsg.child_frame_id_ = externalFrameMoving;
			tfMsg.setData(*pose);
			mTfBr->sendTransform(tfMsg);
		}

		posePublisher.publish(gpose);
	}

/*
 * Variable members
 */
private:
	tf::StampedTransform extPose;

	ros::NodeHandle &rosnode;
	ORB_SLAM2::System &SLAMSystem;
	ros::Publisher posePublisher;
	tf::TransformBroadcaster *mTfBr;

	// Debug
	image_transport::Publisher visualDebugView;

	string externalFrameFixed;
	string externalFrameMoving;

	double lastImageTimestamp;
	bool gotFirstFrame;

	// Logging
	uint32_t lastKeyframeId;
	int offsetKeyframe;

public:
	image_transport::TransportHints th;
	image_transport::ImageTransport *imageBuf;
	image_transport::Subscriber imageSub;

};

int main (int argc, char *argv[])
{
//	const string mapPath = (argc==3) ? argv[2] : string();
	const string orbVocabFile (ORB_SLAM_VOCABULARY);
//	const string configFile = argv[1];

	ros::init(argc, argv, "orb_matching", ros::init_options::AnonymousName);
	ros::start();
	ros::NodeHandle nodeHandler ("~");

	string mapPath;
	nodeHandler.getParam("map_file", mapPath);

	string configFile;
	nodeHandler.getParam("configuration_file", configFile);

	ORB_SLAM2::System SLAM(orbVocabFile,
		configFile,
		ORB_SLAM2::System::MONOCULAR,
		false,
		mapPath,
		System::LOCALIZATION);

	ORB_Matcher Matcher (SLAM, nodeHandler);
	string imageTopic;
	nodeHandler.getParam("image_topic", imageTopic);
	Matcher.imageSub = Matcher.imageBuf->subscribe (imageTopic, 1, &ORB_Matcher::imageCallback, &Matcher, Matcher.th);
	cerr << "ORB Localizer ready" << endl;
	ros::spin();

	SLAM.Shutdown();
	ros::shutdown();

	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics.CodeAnalysis;
using Domain.MasterData.ProductAggregate;
using FluentValidation;

namespace Domain.MasterData.Validations
{
    [ExcludeFromCodeCoverage]
    public sealed class ProductValidator : AbstractValidator<Product>
    {
        public ProductValidator()
        {
            RuleFor(t => t.Name).NotEmpty();
            RuleFor(t => t.ProductCategoryId).NotEqual(0);
            RuleFor(t => t.LastModifiedBy).NotEmpty();
            RuleFor(t => t.Id).NotEmpty();
        }
    }
}


text:
module Organizer
  module Group
    module Operation
      module Loader
        include Organizer::Error

        def self.load(_definitions_keeper, _group_definitions)
          return _group_definitions if _group_definitions.blank?

          _group_definitions.each do |group_definition|
            _definitions_keeper.groups_parent_item_operations.each do |operation|
              group_definition.parent_item_operations << operation
            end

            _definitions_keeper.groups_item_operations.each do |operation|
              group_definition.item_operations << operation
            end
          end

          _group_definitions
        end
      end
    end
  end
end


text:
<?php
/**
 * Paradox Labs, Inc.
 * http://www.paradoxlabs.com
 * 717-431-3330
 *
 * Need help? Open a ticket in our support system:
 *  http://support.paradoxlabs.com
 *
 * @author      Ryan Hoerr <support@paradoxlabs.com>
 * @license     http://store.paradoxlabs.com/license.html
 */

namespace ParadoxLabs\TokenBase\Controller\Paymentinfo;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Result\PageFactory;

/**
 * Save the card create/edit form
 */
class Save extends \ParadoxLabs\TokenBase\Controller\Paymentinfo
{
    /**
     * @var \Magento\Quote\Model\Quote\PaymentFactory
     */
    protected $paymentFactory;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $checkoutSession;

    /**
     * @param Context $context
     * @param Session $customerSession *Proxy
     * @param PageFactory $resultPageFactory
     * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
     * @param \Magento\Framework\Registry $registry
     * @param \ParadoxLabs\TokenBase\Model\CardFactory $cardFactory
     * @param \ParadoxLabs\TokenBase\Api\CardRepositoryInterface $cardRepository
     * @param \ParadoxLabs\TokenBase\Helper\Data $helper
     * @param \ParadoxLabs\TokenBase\Helper\Address $addressHelper
     * @param \Magento\Quote\Model\Quote\PaymentFactory $paymentFactory
     * @param \Magento\Checkout\Model\Session $checkoutSession *Proxy
     */
    public function __construct(
        Context $context,
        Session $customerSession,
        PageFactory $resultPageFactory,
        \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
        \Magento\Framework\Registry $registry,
        \ParadoxLabs\TokenBase\Model\CardFactory $cardFactory,
        \ParadoxLabs\TokenBase\Api\CardRepositoryInterface $cardRepository,
        \ParadoxLabs\TokenBase\Helper\Data $helper,
        \ParadoxLabs\TokenBase\Helper\Address $addressHelper,
        \Magento\Quote\Model\Quote\PaymentFactory $paymentFactory,
        \Magento\Checkout\Model\Session $checkoutSession
    ) {
        $this->paymentFactory   = $paymentFactory;
        $this->checkoutSession  = $checkoutSession;

        parent::__construct(
            $context,
            $customerSession,
            $resultPageFactory,
            $formKeyValidator,
            $registry,
            $cardFactory,
            $cardRepository,
            $helper,
            $addressHelper
        );
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        $id            = $this->getRequest()->getParam('id');
        $method        = $this->getRequest()->getParam('method');

        if ($this->formKeyIsValid() === true && $this->methodIsValid() === true) {
            /**
             * Convert inputs into an address and payment object for storage.
             */
            try {
                /**
                 * Load the card and verify we are actually the cardholder before doing anything.
                 */

                /** @var \ParadoxLabs\TokenBase\Model\Card $card */
                if (!empty($id)) {
                    $card = $this->cardRepository->getByHash($id);
                } else {
                    $card = $this->cardFactory->create();
                    $card->setMethod($card->getMethod() ?: $method);
                }

                $card       = $card->getTypeInstance();
                $customer   = $this->helper->getCurrentCustomer();

                if ($card && (empty($id) || ($card->getHash() == $id && $card->hasOwner($customer->getId())))) {
                    /**
                     * Process address data
                     */
                    $newAddrId    = (int)$this->getRequest()->getParam('billing_address_id');

                    if ($newAddrId > 0) {
                        // Existing address
                        $newAddr = $this->addressHelper->repository()->getById($newAddrId);

                        if ($newAddr->getCustomerId() != $customer->getId()) {
                            throw new LocalizedException(__('An error occurred. Please try again.'));
                        }
                    } else {
                        // New address
                        $newAddr = $this->addressHelper->buildAddressFromInput(
                            $this->getRequest()->getParam('billing', []),
                            is_array($card->getAddress()) ? $card->getAddress() : [],
                            true
                        );
                    }

                    /**
                     * Process payment data
                     */
                    $cardData = $this->getRequest()->getParam('payment');
                    $cardData['method']     = $method;
                    $cardData['card_id']    = $card->getId() > 0 ? $card->getHash() : '';

                    if (isset($cardData['cc_number'])) {
                        $cardData['cc_last4'] = substr($cardData['cc_number'], -4);
                        $cardData['cc_bin']   = substr($cardData['cc_number'], 0, 6);
                    }

                    /** @var \Magento\Quote\Model\Quote\Payment $newPayment */
                    $newPayment = $this->paymentFactory->create();
                    $newPayment->setQuote($this->checkoutSession->getQuote());
                    $newPayment->getQuote()->getBillingAddress()->setCountryId($newAddr->getCountryId());
                    $newPayment->importData($cardData);

                    /**
                     * Save payment data
                     */
                    $card->setMethod($method);
                    $card->setActive(1);
                    $card->setCustomer($customer);
                    $card->setAddress($newAddr);
                    $card->importPaymentInfo($newPayment);

                    $card = $this->cardRepository->save($card);

                    $this->session->unsData('tokenbase_form_data');

                    $this->messageManager->addSuccessMessage(__('Payment data saved successfully.'));
                } else {
                    $this->messageManager->addErrorMessage(__('Invalid Request.'));
                }
            } catch (\Exception $e) {
                $this->session->setData('tokenbase_form_data', $this->getRequest()->getParams());

                $this->helper->log($method, (string)$e);
                $this->messageManager->addErrorMessage(__($e->getMessage()));

                $this->recordSessionFailure($e);
            }
        } else {
            $this->messageManager->addErrorMessage(__('Invalid Request.'));
        }

        $resultRedirect->setPath('*/*', ['method' => $method, '_secure' => true]);
        return $resultRedirect;
    }

    /**
     * Record each save failure on their session. If they fail too many times in a given period, block access. This is
     * to help prevent credit card validation abuse, trying to store CCs until one works.
     *
     * @param \Exception $e
     * @return void
     */
    protected function recordSessionFailure(\Exception $e)
    {
        $failures = $this->session->getData('tokenbase_failures');
        if (is_array($failures) === false) {
            $failures = [];
        }

        $failures[time()] = $e->getMessage();

        $this->session->setData('tokenbase_failures', $failures);
    }
}


text:
	<title>Hannah McGill's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Hannah McGill's panel show appearances

Hannah McGill has appeared in 8 episodes between 2017-2019. Note that these appearances may be for more than one person if multiple people have the same name.

2017

2018

2019

2019-03-22 / Breaking The News

2018-12-15 / Breaking The News

2018-07-14 / Breaking The News

2018-04-14 / Breaking The News

2018-03-02 / Breaking The News

2017-11-11 / Breaking The News

2017-07-15 / Breaking The News

2017-03-10 / Breaking The News


text:
var CORS_PROXY_URL = "http://localhost:9292/";

var POUCH_DB_NAME  = "idb://flashcards_tests";
// my local dev instance:
//var COUCH_DB_PATH  = "127.0.0.1:5984/test_replic";
// Pouch CI test instance:
//var COUCH_DB_PATH = "127.0.0.1:2020/perf-results"

// db with documents to load into Pouch before running tests
var COUCH_DATASET = "pouchdb.iriscouch.com:80/perf-flashcards_tests";

// local and remote results db: results are persisted locally and then replicated to remote Couch
var POUCH_RESULTS_DB_NAME = "idb://flashcards_tests_results";
var COUCH_RESULTS_DB_PATH = "127.0.0.1:5984/flashcards_test_results";

var replic = function() {
  Pouch.destroy("idb://replic_test", function() {
    Pouch("idb://replic_test", function(err, db) {
      console.info("Pouch")
      console.info(err);
      db.replicate.from("http://127.0.0.1:2020/perf-flashcards_tests/", function(err, result) {
        console.info("replicate from")
        console.info(err);
        db.info(function(err, info) {
          console.info("info");
          console.info(err);
          console.log(info);
        });
      });
    });
    });
}

var replot = function() {
  // replot
  var docId = $(this).attr("class").split(" ")[1].substr(2, 50); // FIXME: !!that 50
  Pouch(POUCH_RESULTS_DB_NAME, function(err, db) {
    db.get(docId, function(err, doc) {
      var sample = doc.sample;
      var graphData = $.map(sample, function(val, idx) {
        return {x: idx, y: val};
      });

      var graph = new Rickshaw.Graph({
        element: document.querySelector("#chart"),
        renderer: "bar",
        series: [{
          data: graphData,
          color: "steelblue"
        }]
      });
      graph.render();
      var hoverDetail = new Rickshaw.Graph.HoverDetail( {
        graph: graph
      } );

      // var xAxis = new Rickshaw.Graph.Axis.Time( {
      //     graph: graph,
      //     ticksTreatment: "glow"
      // } );

      var yAxis = new Rickshaw.Graph.Axis.Y({
        graph: graph,
        timeUnit: (new Rickshaw.Fixtures.Time()).unit("second"),
        ticksTreatment: "glow"
      });
      yAxis.render();
    });
  });
};

var logMessage = function(message) {
  console.info(message);
  $("#messages>ul").append("
" + message + "
")
}

var test = function() {
  // Wipe out existing db and create a fresh one from Couch first.

  Pouch.destroy(POUCH_DB_NAME, function() {
    logMessage("local db reset");
    Pouch(POUCH_DB_NAME, function(err, db) {
    db.replicate.from(CORS_PROXY_URL + COUCH_DATASET, function(err, result) {

      console.log(err);
      console.log(result);

      logMessage("replicated dataset from Couch");
      logMessage("running the test suite... this can take a while");
      db.info(function(err, info) {
        console.info(info);
      });

      var doc = {"side1": "oproerpolitie", "side2": "riot police"};
      var suite = new Benchmark.Suite("pouchTestSuite", {
        async: false,
        minSamples: 5,
        maxTime: 60
      });
      suite.add("Pouchdb#post", function() {
        db.post(doc);
      }).on("complete", function() {
        var bench = this;
        var stats = bench[0].stats;

        // save results
        Pouch(POUCH_RESULTS_DB_NAME, function(err, db) {
          // TODO: Record browser info here.
          var testId = new Date().getTime();
          var doc = {
            "_id": String(testId),
            "sample": stats.sample,
            "mean": stats.mean,
            "deviation": stats.deviation
          };
          db.put(doc, function(err, resp) {
            db.replicate.to(CORS_PROXY_URL+COUCH_RESULTS_DB_PATH, function(err, results) {
              // Update body tag for CI
              document.body.attributes["data-results-id"] = testId;
              document.body.attributes["class"] = "complete";

              logMessage("replicated test result data");
              $("#pastRunsDiv").show();
              db.replicate.from(CORS_PROXY_URL+COUCH_RESULTS_DB_PATH, function(err, results) {
                db.allDocs(function(err, resp) {
                  $.each(resp.rows, function(idx, val) {
                    var $li = $("
" + val.id + "
");
                    $("#pastRuns").append($li);
                    $li.click(replot);
                  });
                });
              });
            });
          });
        });
      }).run();
    });
  })
  });

}


text:
@interface BrowserViewModel : NSObject
{
    NSInteger _currentIndex;
    NSInteger _lastIndex;
    BOOL _needMove;
    BOOL _moveDirection;
}
@property (strong, nonatomic) NSMutableArray* array;

@property (weak, nonatomic) Settings* settings;

- (id)initWithSettings:(Settings*)settings;

- (void)add:(id)object;
- (id)remove;
- (void)goTo:(NSInteger)index;

- (NSInteger)count;
- (id)currentObject;
- (id)lastObject;
- (id)objectAtIndex:(NSInteger)index;
- (NSInteger)currentIndex;
- (NSInteger)lastIndex;

- (BOOL)canAdd;
- (BOOL)canRemove;
- (BOOL)canSwitch;
- (BOOL)needMove;
- (BOOL)moveDirection;

@end


text:
package org.assertj.core.internal.paths;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.error.ShouldEndWithPath.shouldEndWith;
import static org.assertj.core.test.TestFailures.wasExpectingAssertionError;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Test;

public class Paths_assertEndsWithRaw_Test extends MockPathsBaseTest {

  @Test
  public void should_fail_if_actual_is_null() {
	thrown.expectAssertionError(actualIsNull());
	paths.assertEndsWithRaw(info, null, other);
  }

  @Test
  public void should_fail_if_other_is_null() {
	try {
	  paths.assertEndsWithRaw(info, actual, null);
	  fail("expected a NullPointerException here");
	} catch (NullPointerException e) {
	  assertThat(e).hasMessage("the expected end path should not be null");
	}
  }

  @Test
  public void should_fail_if_actual_does_not_end_with_other() {
	// This is the default, but let's make this explicit
	when(actual.endsWith(other)).thenReturn(false);

	try {
	  paths.assertEndsWithRaw(info, actual, other);
	  wasExpectingAssertionError();
	} catch (AssertionError e) {
	  verify(failures).failure(info, shouldEndWith(actual, other));
	}
  }

  @Test
  public void should_succeed_if_actual_ends_with_other() {
	when(actual.endsWith(other)).thenReturn(true);

	paths.assertEndsWithRaw(info, actual, other);
  }
}


text:
<%--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
--%>
<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>
<html>
  <head>
    <title>JSP 2.0 Examples - Repeat SimpleTag Handler</title>
  </head>
  <body>
    <h1>JSP 2.0 Examples - Repeat SimpleTag Handler</h1>
    <hr>
    <p>This tag handler accepts a "num" parameter and repeats the body of the
    tag "num" times.  It's a simple example, but the implementation of
    such a tag in JSP 2.0 is substantially simpler than the equivalent
    JSP 1.2-style classic tag handler.</p>
    <p>The body of the tag is encapsulated in a "JSP Fragment" and passed
    to the tag handler, which then executes it five times, inside a
    for loop.  The tag handler passes in the current invocation in a
    scoped variable called count, which can be accessed using the EL.</p>
    <br>
    <b><u>Result:</u></b><br>
    <mytag:repeat num="5">
      Invocation ${count} of 5<br>
    </mytag:repeat>
  </body>
</html>


text:
'use strict';

var stypeToService = require('./stype-to-service');
var parseProduct = require('./parse-product');

/**
* Flattens data and formats it for Dimple graphs
* @param {Object} full response from usage API
* @return {Object} usage totals, usage summary by product, and array of formatted graph data
*/
var flatten = function flatten(response) {
  if (!response.data) {
    return response;
  }

  var data = {
    period: response.period,
    credits: 0,
    products: [],
    graphData: [],
    startCredits: parseInt(response.data[0].credits[0][0], 10),
    endCredits: parseInt(response.data[0].credits[response.data[0].credits.length - 1][0], 10),
    startTime: response.startTime,
    endTime: response.endTime
  };

  response.data.forEach(function (service, index) {
    var product = parseProduct(service);
    var name = stypeToService(service.stype);

    if (product) {
      product.name = name;
      data.products.push(product);
    }

    service.totalCredits = 0;
    service.credits.forEach(function (entry) {
      service.totalCredits += parseFloat(entry[1]);
    });

    if (service.totalCredits > 0) {
      data.credits += service.totalCredits;

      service.credits.forEach(function (entry) {
        data.graphData.push({
          name: name,
          date: parseInt(entry[0], 10),
          credits: parseFloat(entry[1])
        });
      });
    }
  });

  data.credits = Math.round(data.credits * 100) / 100;

  return data;
};

module.exports = flatten;


text:
- change mod id to 'thingies'
- change classes / namespaces to get rid of 'tesla'

#future
- add 'not-instant-first-run' machines (machines that start to fill the work buffer when a valid recipe is locked in)
- make 'power kiln' recipes take different power amounts
- make all recipes take different amount of power
- replace 'crop farmer' with the 'misc farmer' machine via upgrades
- make simple/multi tanks behave like 1 big tank vertically (maybe cube size for simple tank)
- add a quarry machine
- add 'strategy' addons for pump and quarry
- add CT and API support to all non-farming machines (including the ones with Secondary Outputs, might be dependent on the support for that being added to TCL)
- add power cost to item liquefier recipes

#1.0.15
- fixed #42: Electric Butcher
- fixed #39: Butcher has no drops
- fixed #36: Powered Pump consumes Fluids

#1.0.14
- acacia trees should not leave blocks behind anymore
- tree farm now handles IC2 rubber trees
- fixed #33: Pump recipe error
- fixed #21: Tree compat: Integrated Dynamics
- fixed ugly crash with pump on server side

#1.0.13
- simple and multi tanks now have fluid caps in item mode
- moved to MMD servers
- jar should now be signed
- removed a bit of log spam

#1.0.12
- new TCL version
- new forgelin

#1.0.11
- fixed crop cloner seed duplication bug
- added fluid pump machine
- added 'void storage' upgrade for tanks (keep accepting fluids even if full)
- added craft tweaker support to most machines
- added api support to most machines
- updated to latest forge
- fixed fluid solidifier jei recipe display

#1.0.10
- added support (tree farm) for forestry trees
- added support (crop farm) for rustic stake crops
- added 'misc farmer' machine (only farms based on addons)
    - 'tree fruit picker' addon only works with this machine now
    - added 'bush picker' addon that will work with this and harvest bushes from various mods (using the optional BushMasterCore lib)
- added 'compound maker' machine (to replace item compound producer)
    - supports 2 input fluid tanks... and 6 total input stacks
    - just 1 output slot!
- first version of the 'possible' 6x ore processing
    - ore -\> teslified lump -\> augmented lump -\> powder -\> ingot
- new textures for teslified lumps and augmented lumps

#1.0.9 - HFs
- fixed some missing/broken recipes
- fixed problem with redstone fluid textures on server side

#1.0.9
- improved some GUIs (mainly about the order of the side config colors)
- added 'incinerator' custom recipes json
- added 'powered kiln' custom recipes json
- localize all the things!

#1.0.8
- added 'fluid compound producer' (combines fluids into other fluids)
- added config files for extra recipes to various machines
    - "{registry_name}-base.json" - this is the default recipes config generated by the mod
    - "{registry_name}-extra.json" - extra recipes file that is loaded, if it exists, but will never be created/overwrited by the mod
    - check "-base.json" files for examples of the recipe structure
- improved liquid xp storage machine
- added 'player xp addon' - you put it into a 'liquid xp storage' and you can convert stored liquid xp to/from player xp
- fixed some of the default recipes for 'powder maker'

#1.0.7
- fixed 'powered kiln' recipes to support vanilla items
- 'item compound producer' is no longer WIP
- 'fluid solidifier' JEI screen got an update


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingBottom="@dimen/frame_padding_vertical"
                android:paddingLeft="@dimen/frame_padding_horizontal"
                android:paddingRight="@dimen/frame_padding_horizontal"
                android:paddingTop="@dimen/frame_padding_vertical">

    <!-- Profile selection -->
    <android.support.v7.widget.CardView
        android:id="@+id/profile_spinner_card"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        card_view:cardCornerRadius="2dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingBottom="10dp"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingTop="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="15dp"
                android:fontFamily="sans-serif-medium"
                android:text="Profile:"
                android:textSize="17dp">
            </TextView>

            <TextView
                android:id="@+id/profile_spinner_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:width="205dp"
                android:ellipsize="end"
                android:fontFamily="sans-serif-light"
                android:maxLines="1"
                android:scrollHorizontally="true"
                android:text="@string/profile_spinner_default_text"
                android:textSize="17dp">
            </TextView>
        </LinearLayout>
    </android.support.v7.widget.CardView>

    <Spinner
        android:id="@+id/profile_spinner"
        android:layout_width="322dp"
        android:layout_height="43dp"
        android:layout_alignLeft="@id/profile_spinner_card"
        android:layout_marginLeft="-1dp"
        android:layout_marginTop="19dp"
        android:dropDownWidth="322dp"
        android:visibility="invisible">
    </Spinner>

    <!-- Circular progress bar -->
    <RelativeLayout
        android:id="@+id/progress_circular_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/profile_spinner_card"
        android:layout_marginTop="20dp"
        android:gravity="bottom">

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="325dp"
            android:layout_height="325dp"
            android:layout_centerHorizontal="true"
            android:max="100"
            android:progress="100"
            android:progressDrawable="@drawable/circular_underlay">
        </ProgressBar>

        <ProgressBar
            android:id="@+id/progress_circular"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="325dp"
            android:layout_height="325dp"
            android:layout_centerHorizontal="true"
            android:max="10000"
            android:progress="0"
            android:progressDrawable="@drawable/circular"
            android:rotation="-90">
        </ProgressBar>

        <!-- Time -->
        <LinearLayout
            android:id="@+id/timer_time_container"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="105dp">

            <TextView
                android:id="@+id/text_time_minutes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:text="00"
                android:textSize="@dimen/time_text_size">
            </TextView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:text=":"
                android:textSize="@dimen/time_text_size">
            </TextView>

            <TextView
                android:id="@+id/text_time_seconds"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:text="00"
                android:textSize="@dimen/time_text_size">
            </TextView>
        </LinearLayout>

        <TextView
            android:id="@+id/text_round_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/timer_time_container"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:fontFamily="sans-serif-light"
            android:text="@string/round_number_default_text"
            android:textSize="18dp">
        </TextView>
    </RelativeLayout>

    <!-- Controls -->
    <Button
        android:id="@+id/button_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progress_circular_container"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:backgroundTint="@color/colorAccent"
        android:paddingBottom="@dimen/button_padding_vertical"
        android:paddingLeft="@dimen/button_padding_horizontal"
        android:paddingRight="@dimen/button_padding_horizontal"
        android:paddingTop="@dimen/button_padding_vertical"
        android:text="@string/button_start"
        android:textColor="#FFFFFF"
        android:textSize="@dimen/button_text">
    </Button>

    <RelativeLayout
        android:id="@+id/pause_stop_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progress_circular_container"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:visibility="invisible">

        <Button
            android:id="@+id/button_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorAccent"
            android:paddingBottom="@dimen/button_padding_vertical"
            android:paddingLeft="@dimen/button_padding_horizontal"
            android:paddingRight="@dimen/button_padding_horizontal"
            android:paddingTop="@dimen/button_padding_vertical"
            android:text="@string/button_pause"
            android:textColor="#FFFFFF"
            android:textSize="@dimen/button_text">
        </Button>

        <Button
            android:id="@+id/button_stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_toRightOf="@id/button_pause"
            android:backgroundTint="@color/colorAccent"
            android:paddingBottom="@dimen/button_padding_vertical"
            android:paddingLeft="@dimen/button_padding_horizontal"
            android:paddingRight="@dimen/button_padding_horizontal"
            android:paddingTop="@dimen/button_padding_vertical"
            android:text="@string/button_stop"
            android:textColor="#FFFFFF"
            android:textSize="@dimen/button_text">
        </Button>

        <Button
            android:id="@+id/button_resume"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:backgroundTint="@color/colorAccent"
            android:paddingBottom="@dimen/button_padding_vertical"
            android:paddingLeft="23dp"
            android:paddingRight="22dp"
            android:paddingTop="@dimen/button_padding_vertical"
            android:text="@string/button_resume"
            android:textColor="#FFFFFF"
            android:textSize="@dimen/button_text"
            android:visibility="invisible">
        </Button>
    </RelativeLayout>
</RelativeLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="error">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </Console>

        <File name="log" fileName="F:\\log\\test.log" append="true">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <File name="ERROR" fileName="F:\\log\\error.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <RollingFile name="RollingFile" fileName="F:\\log\\web.log" filePattern="F:\\log\\$${date:yyyy-MM}\\web-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
            <SizeBasedTriggeringPolicy size="2MB"/>
        </RollingFile>

        <Console name="ConsoleTest" target="SYSTEM_OUT">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="%msg%n"/>
        </Console>

        <!-- <JDBC name="JDBCTest" tableName="jdbcTest">
	      <ConnectionFactory class="cn.ot.data.log4j.ConnectionFactory" method="getPoolConnection" />

	      <Column name="msg" pattern="%msg" />
	    </JDBC>   -->

	    <!-- <Kafka name="KfkaTest" topic="test">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
            <PatternLayout pattern="%msg" />
            <Property name="bootstrap.servers">192.168.20.102:9092</Property>
        </Kafka>   -->
    </appenders>

    <loggers>
        <root level="trace">
            <appender-ref ref="ConsoleTest"/>
        </root>
        <logger name="test" level="info">
        	<appender-ref ref="ConsoleTest" />
        </logger>
        <logger name="test1" level="info">
        	<appender-ref ref="log" />
        </logger>
    </loggers>

</configuration>


text:
package org.openmhealth.reference.data.mongodb;

import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import org.mongojack.DBQuery.Query;
import org.mongojack.JacksonDBCollection;
import org.mongojack.internal.MongoJackModule;
import org.openmhealth.reference.data.UserBin;
import org.openmhealth.reference.domain.Schema;
import org.openmhealth.reference.domain.User;
import org.openmhealth.reference.domain.mongodb.MongoUser;
import org.openmhealth.reference.exception.OmhException;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.MongoException;
import com.mongodb.QueryBuilder;

/**
 * <p>
 * The MongoDB implementation of the interface to the database-backed
 * collection of users.
 * </p>
 *
 * @author John Jenkins
 */
public class MongoUserBin extends UserBin {
	/**
	 * The object mapper that should be used to parse {@link Schema}s.
	 */
	private static final ObjectMapper JSON_MAPPER;
	static {
		// Create the object mapper.
		ObjectMapper mapper = new ObjectMapper();

		// Create the FilterProvider.
		SimpleFilterProvider filterProvider = new SimpleFilterProvider();
		filterProvider.setFailOnUnknownId(false);
		mapper.setFilters(filterProvider);

		// Finally, we must configure the mapper to work with the MongoJack
		// configuration.
		JSON_MAPPER = MongoJackModule.configure(mapper);
	}

	/**
	 * Default constructor that creates any tables and indexes if necessary.
	 */
	protected MongoUserBin() {
		// Get the collection to add indexes to.
		DBCollection collection =
			MongoDao.getInstance().getDb().getCollection(DB_NAME);

		// Ensure that there is an index on the username.
		collection
			.ensureIndex(
				new BasicDBObject(User.JSON_KEY_USERNAME, 1),
				DB_NAME + "_" + User.JSON_KEY_USERNAME + "_unique",
				true);

		// Ensure that there is an index on the username.
		collection
			.ensureIndex(
				new BasicDBObject(User.JSON_KEY_REGISTRATION_KEY, 1),
				DB_NAME + "_" + User.JSON_KEY_REGISTRATION_KEY,
				false);
	}

	/*
	 * (non-Javadoc)
	 * @see org.openmhealth.reference.data.UserBin#createUser(org.openmhealth.reference.domain.User)
	 */
	@Override
	public void createUser(final User user) throws OmhException {
		// Validate the input.
		if(user == null) {
			throw new OmhException("The user is null.");
		}

		// Get the user collection.
		JacksonDBCollection<User, Object> collection =
			JacksonDBCollection
				.wrap(
					MongoDao.getInstance()
						.getDb()
						.getCollection(DB_NAME),
					User.class,
					Object.class,
					JSON_MAPPER);

		// Save the user.
		try {
			collection.insert(user);
		}
		catch(MongoException.DuplicateKey e) {
			throw
				new OmhException(
					"A user with that username already exists.",
					e);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.openmhealth.reference.data.UserBin#getUser(java.lang.String)
	 */
	@Override
	public User getUser(final String username) throws OmhException {
		// Validate the parameter.
		if(username == null) {
			throw new OmhException("The username is null.");
		}

		// Get the authentication token collection.
		JacksonDBCollection<MongoUser, Object> collection =
			JacksonDBCollection
				.wrap(
					MongoDao.getInstance()
						.getDb()
						.getCollection(DB_NAME),
					MongoUser.class,
					Object.class,
					JSON_MAPPER);

		// Build the query.
		QueryBuilder queryBuilder = QueryBuilder.start();

		// Add the authentication token to the query
		queryBuilder.and(MongoUser.JSON_KEY_USERNAME).is(username);

		// Execute query.
		DBCursor<MongoUser> result = collection.find(queryBuilder.get());

		// If multiple authentication tokens were returned, that is a violation
		// of the system.
		if(result.count() > 1) {
			throw
				new OmhException(
					"Multiple users exist with the same username: " +
						username);
		}

		// If no tokens were returned, then return null.
		if(result.count() == 0) {
			return null;
		}
		else {
			return result.next();
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.openmhealth.reference.data.UserBin#getUserFormRegistration(java.lang.String)
	 */
	@Override
	public User getUserFromRegistrationId(
		final String registrationId)
		throws OmhException {

		// Validate the parameter.
		if(registrationId == null) {
			throw new OmhException("The registration ID is null.");
		}

		// Get the authentication token collection.
		JacksonDBCollection<MongoUser, Object> collection =
			JacksonDBCollection
				.wrap(
					MongoDao.getInstance()
						.getDb()
						.getCollection(DB_NAME),
					MongoUser.class,
					Object.class,
					JSON_MAPPER);

		// Build the query.
		QueryBuilder queryBuilder = QueryBuilder.start();

		// Add the authentication token to the query
		queryBuilder
			.and(MongoUser.JSON_KEY_REGISTRATION_KEY)
			.is(registrationId);

		// Execute query.
		DBCursor<MongoUser> result = collection.find(queryBuilder.get());

		// If multiple authentication tokens were returned, that is a violation
		// of the system.
		if(result.count() > 1) {
			throw
				new OmhException(
					"Multiple users exist with the same registration ID: " +
						registrationId);
		}

		// If no tokens were returned, then return null.
		if(result.count() == 0) {
			return null;
		}
		else {
			return result.next();
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.openmhealth.reference.data.UserBin#updateUser(org.openmhealth.reference.domain.User)
	 */
	@Override
	public void updateUser(final User user) throws OmhException {
		// Validate the input.
		if(user == null) {
			throw new OmhException("The user is null.");
		}

		// Get the user collection.
		JacksonDBCollection<User, Object> collection =
			JacksonDBCollection
				.wrap(
					MongoDao.getInstance()
						.getDb()
						.getCollection(DB_NAME),
					User.class,
					Object.class,
					JSON_MAPPER);

		// Ensure that we are only updating the user with the same user-name.
		Query query = DBQuery.is(User.JSON_KEY_USERNAME, user.getUsername());

		// Save the user.
		try {
			collection.update(query, user);
		}
		catch(MongoException e) {
			throw new OmhException("An internal error occurred.", e);
		}
	}
}


text:
{{<govuk_template}}

{{$head}}
  {{>includes/elements_head}}

{{/head}}

{{$propositionHeader}}
  {{>includes/govuk_evlprop}}
{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}

<link href="/public/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />

  Back  to the previous question

  <form action="evl-paymethod" method="get" class="form">

  <input type="hidden" name="nextbacklink" value="evl-renewal-period">
  <input type="hidden" name="regmark" value="{{defaultreg}}">
  <input type="hidden" name="kind" value="{{kind}}">

Choose how to pay

You can pay by card or set up a direct debit.

    <input id="radio-inline-1" type="radio"  name="paymethod" value="dd">
    Pay by Direct Debit

Or

    <input id="radio-inline-4" type="radio"  name="paymethod" value="card">
    Pay by card

  </fieldset>

  Comparison tables for rates of vehicle tax (V149)

    <input type="submit" class="button" value="Continue">

Cancel application

</form>

{{/content}}

{{$bodyEnd}}
  {{>includes/elements_scripts}}
{{/bodyEnd}}

{{/govuk_template}}


text: Cluster Setup


text:
package Maraton2011_3Septiembre.src;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Locale;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class binpacking1 {
	static BufferedReader input;

	static StringTokenizer _stk;
	static String readln() throws IOException{
		String l=input.readLine();
		if(l!=null) _stk=new StringTokenizer(l," ");
		return l;
	}

	static String next(){return _stk.nextToken();}
	static int nextInt(){return Integer.parseInt(next());}

	public static void main(String[] args) throws Exception {
		Locale.setDefault(Locale.US);
//		input=new BufferedReader(new InputStreamReader(System.in));
		input=new BufferedReader(new FileReader("b.in"));
		while(true) {
			readln();
			int n = nextInt();
			if(n == 0)
				break;
			readln();
			int l = nextInt();
			ArrayList<Integer> items = new ArrayList<Integer>();
//			PriorityQueue<Integer> leer=new PriorityQueue<Integer>();
			for(int i = 0; i < n; i++) {
				readln();
				items.add(nextInt());
			}
			Collections.sort(items);

//			items=new ArrayList<Integer>(leer);
			int respuesta = 0;

			//System.out.println(items.toString());
			//for(int i = 0; i < items.size(); i++) {

			int tamt=0;
			int pos = 0;
			//for(int pos = items.size()-1; pos > -1; pos--) {
			while(true) {
				pos=items.size()-1;
				if(pos<0)
					break;

				int mayor = items.remove(pos);

				if(items.size()==0){
					respuesta++;
					break;
				}

				if(mayor == l) {
					respuesta++;
					continue;
				}

				int tamannoPos= l-mayor;
//				System.out.println("ajjaja"+mayor);

				int k=Collections.binarySearch(items, tamannoPos);
				//System.out.println(items.toString());
				//System.out.println("mayor = "+mayor+ " k = "+k+" tamannoPos = "+ tamannoPos );

				if(k==items.size())
				{
					respuesta++;
					int tmp = items.remove(k-1);
					//System.out.printf("sise mayor %d otro %d respuesta = %d\n",mayor, tmp, respuesta);
					continue;
				}
				else if(k>=0)
				{
					int tmp = items.remove(k);
					respuesta++;
					//System.out.printf("mayor %d otro %d respuesta = %d\n",mayor, tmp, respuesta);
					continue;
				}
				else if(k<0){
					int tmp = ((k*-1)-2);
					if(mayor + items.get((tmp >= 0)? tmp: 0) > l) {
						respuesta++;
						continue;
					}
					int tmp2 = items.remove((tmp >= 0)? tmp: 0);

					//System.out.printf("mayor %d otro %d respuesta = %d\n",mayor, tmp2, respuesta);
//					System.out.println("i"+i);
					respuesta++;
				}
			}
			System.out.println(respuesta);
		}

	}

	/*static boolean check(int bins, int tam) {

		return false;
	}*/
}


text:
package netpool

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"time"
)

// NewWriterConn a new writer connection
func NewWriterConn(protocol string, host string, timeout time.Duration) (net.Conn, error) {
	if protocol == "tcp" || protocol == "udp" || protocol == "unix" {
		conn, err := net.DialTimeout(protocol, host, timeout)
		return conn, err
	} else if protocol == "http" || protocol == "https" {
		return NewWriterHttpConn(protocol, host, timeout)
	}
	return nil, fmt.Errorf("Invalid connection protocol")
}

/** the net.Conn interface for ease

Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
Close() error
LocalAddr() Addr
RemoteAddr() Addr
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error

*/

/************************/
/****** HTTP CONN *******/
/************************/

// WriterHttpConn a special http "writer" that acts like a net.Conn for writing
type WriterHttpConn struct {
	Timeout time.Duration
	Proto   string
	Host    string
	Method  string

	url    *url.URL
	tr     *http.Transport
	client *http.Client

	t int
}

// HTTPAddr net.Addr interface
type HTTPAddr struct {
	Name string
}

// Network tcp
func (ha HTTPAddr) Network() string {
	return "tcp"
}

// String http url
func (ha HTTPAddr) String() string {
	return ha.Name
}

// NewWriterHttpConn http socket: basically delegate the dial timeout
func NewWriterHttpConn(protocol string, host string, timeout time.Duration) (*WriterHttpConn, error) {
	// the "host" may be url + path
	w := new(WriterHttpConn)
	w.Proto = protocol
	w.Host = host
	w.Timeout = timeout
	// the input may have a PATH as well, but we may need to host as some point
	w.url, _ = url.Parse(protocol + "://" + host)
	w.Method = "POST"
	w.tr = &http.Transport{}
	w.client = &http.Client{
		Transport: w.tr,
		Timeout:   timeout,
	}
	// start the closer
	go w.closeIdle()
	return w, nil
}

// periodically close idle cons to avoid leakage
func (w *WriterHttpConn) closeIdle() {
	tick := time.NewTicker(time.Duration(1 * time.Second))
	for range tick.C {
		w.tr.CloseIdleConnections()
	}
}

// Write send bytes to http endpoint
func (w *WriterHttpConn) Write(b []byte) (n int, err error) {
	reader := bytes.NewReader(b)
	req, err := http.NewRequest(w.Method, w.url.Scheme+"://"+w.url.Host+w.url.Path, reader)
	//log.Debug(w.url.Scheme+"://"+w.url.Host+w.url.Path)
	if err != nil {
		log.Error("Request failed to construct: %s", err)
		return 0, err
	}

	res, err := w.client.Do(req)

	if err != nil {
		log.Error("post request failed: `%s`", err)
		return 0, err
	}
	io.Copy(ioutil.Discard, res.Body)
	res.Body.Close()
	return len(b), nil
}

func (w *WriterHttpConn) LocalAddr() net.Addr {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return addrs[0]
	}
	return nil
}

func (w *WriterHttpConn) RemoteAddr() net.Addr {
	return HTTPAddr{
		Name: w.url.Host,
	}
}

// Close no-op
func (w *WriterHttpConn) Close() (err error) {
	return nil
}

// Read no-op
func (w *WriterHttpConn) Read(b []byte) (n int, err error) {
	// not reading
	return 0, nil
}

// SetDeadline no-op
func (w *WriterHttpConn) SetDeadline(t time.Time) error {
	return nil
}

// SetReadDeadline no-op
func (w *WriterHttpConn) SetReadDeadline(t time.Time) error {
	return nil
}

// SetWriteDeadline no-op
func (w *WriterHttpConn) SetWriteDeadline(t time.Time) error {
	return nil
}


text:
using System;
using System.Diagnostics;

namespace KnxNet.Core
{
	[DebuggerDisplay("Group Address = {" + nameof(ToString) + "()}")]
	public class KnxAddress
	{
		private byte[] _value = new byte[2];

		public KnxAddress()
		{
		}

		public KnxAddress(byte area, byte line, byte busdevice)
		{
			Area = area;
			Line = line;
			BusDevice = busdevice;
		}

		public static KnxAddress Parse(string input)
		{
			string[] vals = input.Split(new [] {"."}, StringSplitOptions.RemoveEmptyEntries);

			if (vals.Length != 3)
				throw new Exception("Could not parse, not enough .");

			return new KnxAddress((byte) int.Parse(vals[0]), (byte) int.Parse(vals[1]), (byte) int.Parse(vals[2]));
		}

		public byte[] Value
		{
			get => _value;
			set
			{
				if (_value == null || _value.Length != 2)
					throw new ArgumentException("Must be 2 long", nameof(value));

				_value = value;
			}
		}

		public byte Area
		{
			get => (byte) (Value[0] >> 4);
			set
			{
				Value[0] &= 0x0F;
				Value[0] |= (byte) (value << 4);
			}
		}

		public byte Line
		{
			get => (byte) (Value[0] & 0x0F);
			set
			{
				Value[0] &= 0xF0;
				Value[0] |= (byte) (value & 0xF0);
			}
		}

		public byte BusDevice
		{
			get => Value[1];
			set => Value[1] = value;
		}

		public override string ToString()
		{
			return $"{Area}.{Line}.{BusDevice}";
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<ws>
    <settings>
        <stage width="1366px" height="768px" create="yes" center="yes" resize="yes" />
        <triggers>
            <trigger name="increase_duration_trigger" event="keyup" key="UP_ARROW" scene="increase_duration_scene" />
            <trigger name="decrease_duration_trigger" event="keyup" key="DOWN_ARROW" scene="decrease_duration_scene" />
            <trigger name="change_effect" event="keyup" key="E" scene="change_effect_scene" />
            <trigger name="change_direction" event="keyup" key="D" scene="change_direction_scene" />
            <trigger name="change_easing" event="keyup" key="SPACE" scene="change_easing_scene" />
        </triggers>
    </settings>
    <assets>

        <imagepack name="cecile" x="0" y="0" z="1000">
            <image src="../../story/assets/images/cecile/smile.png" name="smile" />
        </imagepack>

        <background name="bg" src="../../story/assets/images/Rainbow_A_01.jpg" width="100%" height="100%" />

        <textbox name="tb" cssid="tb" />

        <character name="n" textbox="tb"></character>

        <animation name="my_anim">
            <group>
                <do action="move" asset="cecile" x="0" y="-500" duration="2000" easing="linear" />
            </group>
            <group>
                <do action="move" asset="cecile" x="0" y="-0" duration="2000" easing="linear" />
            </group>
        </animation>

    </assets>
    <scenes>

        <scene id="increase_duration_scene">
            <var name="duration" action="increase" value="100" />
        </scene>

        <scene id="decrease_duration_scene">
            <var name="duration" action="decrease" value="100" />
        </scene>

        <scene id="change_effect_scene">
            <with var="effect">
                <when is="fade">
                    <var name="effect" value="slide" />
                </when>
                <when is="slide">
                    <var name="effect" value="fade" />
                </when>
            </with>
        </scene>

        <scene id="change_direction_scene">
            <with var="direction">
                <when is="left">
                    <var name="direction" value="top" />
                </when>
                <when is="top">
                    <var name="direction" value="right" />
                </when>
                <when is="right">
                    <var name="direction" value="bottom" />
                </when>
                <when is="bottom">
                    <var name="direction" value="left" />
                </when>
            </with>
        </scene>

        <scene id="change_easing_scene">
            <with var="easing">
                <when is="sineEaseOut">
                    <var name="easing" value="easeOutBounce" />
                </when>
                <when is="easeOutBounce">
                    <var name="easing" value="sineEaseOut" />
                </when>
            </with>
        </scene>

        <scene id="start">
            <trigger name="increase_duration_trigger" action="activate" />
            <trigger name="decrease_duration_trigger" action="activate" />
            <trigger name="change_effect" action="activate" />
            <trigger name="change_direction" action="activate" />
            <trigger name="change_easing" action="activate" />

            <set_vars
                names="x, y, xAnchor, yAnchor, effect, duration, direction, easing"
                values="50%, 100%, 50%, 100%, fade, 1000, left, sineEaseOut" />

            <set asset="cecile" image="smile" />

            <show asset="bg" />
            <show asset="tb" />

            <start asset="my_anim" />

            <show asset="cecile" duration="0" />

            <goto scene="doNothingLoop" />

        </scene>

        <scene id="doNothingLoop">
            <wait duration="5000" />
            <goto scene="doNothingLoop" />
        </scene>

        <scene id="loop">

            <goto scene="loop" />
        </scene>

        <scene id="move_sprite_to_center">
            <move asset="cecile" x="{$x}" y="{$y}" xAnchor="{$xAnchor}" yAnchor="{$yAnchor}" duration="0" />
        </scene>

        <scene id="show_sprite">
            <show asset="cecile" effect="{$effect}" direction="{$direction}"
                  duration="{$duration}" easing="{$easing}" />

            <wait />
        </scene>

        <scene id="hide_sprite">
            <hide asset="cecile" effect="{$effect}" direction="{$direction}"
                  duration="{$duration}" easing="{$easing}" />

            <wait />
        </scene>

        <scene id="log_vars">
            <line s="n" stop="false">
                effect [E]: {$effect}

                direction [D]: {$direction}

                duration [UP/DOWN]: {$duration}

                easing [SPACE]: {$easing}
            </line>
        </scene>

    </scenes>
</ws>


text:
using System;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace stNet
{
    public static partial class stRSS
    {
        public class RSSWriter
        {
            private RSSFeedRoot _rss = null;

            public RSSWriter(RSSFeedChannel rsschannel)
            {
                this._rss = new RSSFeedRoot();
                this._rss.channel = ((rsschannel == null) ? new RSSFeedChannel() : rsschannel);
            }
            ~RSSWriter()
            {
                this.Clear();
            }
            public void Add(RSSFeedItem rssitem)
            {
                if (rssitem != null)
                {
                    this._rss.channel.items.Add(rssitem);
                }
            }
            public void Clear()
            {
                if (this._rss != null)
                {
                    this._rss.channel.items.Clear();
                }
            }
            public bool WriteStream(Stream stm, stCore.IMessage iLog = null)
            {
                if (this._rss == null)
                {
                    return false;
                }
                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(RSSFeedRoot));
                    serializer.Serialize(stm, this._rss);
                    return true;
                }
                catch (Exception e)
                {
                    if (iLog != null)
                    {
                        iLog.LogError(e.Message);
                    }
                    return false;
                }
            }
            public string WriteString(stCore.IMessage iLog = null)
            {
                if (this._rss == null)
                {
                    return String.Empty;
                }
                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(RSSFeedRoot));
                    using (StringWriter sw = new StringWriter())
                    {
                        using (XmlWriter xw = XmlWriter.Create(sw, new XmlWriterSettings()
                            {
                                Encoding = new UTF8Encoding(false),
                                Indent = true,
                                NewLineOnAttributes = true,
                            })
                        )
                        {
                            serializer.Serialize(xw, this._rss);
                            return sw.ToString();
                        }
                    }
                }
                catch (Exception e)
                {
                    if (iLog != null)
                    {
                        iLog.LogError(e.Message);
                    }
                }
                return String.Empty;
            }
        }
    }
}


text:
package whisk.core.controller

import java.time.Clock
import java.time.Instant

import scala.concurrent.Future
import scala.util.Failure
import scala.util.Success
import spray.client.pipelining.Post

import akka.actor.ActorSystem
import spray.client.pipelining._
import spray.http.BasicHttpCredentials
import spray.http.HttpRequest
import spray.http.StatusCodes.BadRequest
import spray.http.StatusCodes.InternalServerError
import spray.http.StatusCodes.OK
import spray.http.Uri
import spray.http.Uri.Path
import spray.httpx.SprayJsonSupport.sprayJsonMarshaller
import spray.httpx.SprayJsonSupport.sprayJsonUnmarshaller
import spray.httpx.marshalling.ToResponseMarshallable.isMarshallable
import spray.json.JsObject
import spray.json.JsString
import spray.json.DefaultJsonProtocol.RootJsObjectFormat
import spray.routing.Directive.pimpApply
import spray.routing.directives.OnCompleteFutureMagnet.apply
import spray.routing.directives.ParamDefMagnet.apply
import spray.routing.RequestContext
import whisk.common.TransactionId
import whisk.core.entitlement.Collection
import whisk.core.entity.ActivationResponse
import whisk.core.entity.EntityPath
import whisk.core.entity.Parameters
import whisk.core.entity.SemVer
import whisk.core.entity.Status
import whisk.core.entity.TriggerLimits
import whisk.core.entity.WhiskActivation
import whisk.core.entity.WhiskEntityStore
import whisk.core.entity.WhiskTrigger
import whisk.core.entity.WhiskTriggerPut
import whisk.core.entity.types.ActivationStore
import whisk.core.entity.types.EntityStore
import whisk.http.ErrorResponse.terminate
import spray.httpx.UnsuccessfulResponseException
import spray.http.StatusCodes
import whisk.core.entity.Identity
import whisk.core.entity.FullyQualifiedEntityName

/**
 * A singleton object which defines the properties that must be present in a configuration
 * in order to implement the triggers API.
 */
object WhiskTriggersApi {
    def requiredProperties = WhiskServices.requiredProperties ++
        WhiskEntityStore.requiredProperties
}

/** A trait implementing the triggers API. */
trait WhiskTriggersApi extends WhiskCollectionAPI {
    services: WhiskServices =>

    protected override val collection = Collection(Collection.TRIGGERS)

    /** An actor system for timed based futures. */
    protected implicit val actorSystem: ActorSystem

    /** Database service to CRUD triggers. */
    protected val entityStore: EntityStore

    /** Database service to get activations. */
    protected val activationStore: ActivationStore

    /** Path to Triggers REST API. */
    protected val triggersPath = "triggers"

    /**
     * Creates or updates trigger if it already exists. The PUT content is deserialized into a WhiskTriggerPut
     * which is a subset of WhiskTrigger (it eschews the namespace and entity name since the former is derived
     * from the authenticated user and the latter is derived from the URI). The WhiskTriggerPut is merged with
     * the existing WhiskTrigger in the datastore, overriding old values with new values that are defined.
     * Any values not defined in the PUT content are replaced with old values.
     *
     * Responses are one of (Code, Message)
     * - 200 WhiskAction as JSON
     * - 400 Bad Request
     * - 409 Conflict
     * - 500 Internal Server Error
     */
    override def create(user: Identity, entityName: FullyQualifiedEntityName)(implicit transid: TransactionId) = {
        parameter('overwrite ? false) { overwrite =>
            entity(as[WhiskTriggerPut]) { content =>
                putEntity(WhiskTrigger, entityStore, entityName.toDocId, overwrite,
                    update(content) _,
                    () => { create(content, entityName) },
                    postProcess = Some { trigger =>
                        completeAsTriggerResponse(trigger)
                    })
            }
        }
    }

    /**
     * Fires trigger if it exists. The POST content is deserialized into a Payload and posted
     * to the loadbalancer.
     *
     * Responses are one of (Code, Message)
     * - 200 ActivationId as JSON
     * - 404 Not Found
     * - 500 Internal Server Error
     */
    override def activate(user: Identity, entityName: FullyQualifiedEntityName, env: Option[Parameters])(implicit transid: TransactionId) = {
        entity(as[Option[JsObject]]) {
            payload =>
                getEntity(WhiskTrigger, entityStore, entityName.toDocId, Some {
                    trigger: WhiskTrigger =>
                        val args = trigger.parameters.merge(payload)
                        val triggerActivationId = activationIdFactory.make()
                        info(this, s"[POST] trigger activation id: ${triggerActivationId}")

                        val triggerActivation = WhiskActivation(
                            namespace = user.namespace.toPath, // all activations should end up in the one space regardless trigger.namespace,
                            entityName.name,
                            user.subject,
                            triggerActivationId,
                            Instant.now(Clock.systemUTC()),
                            Instant.EPOCH,
                            response = ActivationResponse.success(payload orElse Some(JsObject())),
                            version = trigger.version,
                            duration = None)
                        info(this, s"[POST] trigger activated, writing activation record to datastore: $triggerActivationId")
                        val saveTriggerActivation = WhiskActivation.put(activationStore, triggerActivation) map {
                            _ => triggerActivationId
                        }

                        val url = Uri(s"http://localhost:${whiskConfig.servicePort}")
                        val pipeline: HttpRequest => Future[JsObject] = (
                            addCredentials(BasicHttpCredentials(user.authkey.uuid.toString, user.authkey.key.toString))
                            ~> sendReceive
                            ~> unmarshal[JsObject])

                        trigger.rules.map {
                            _.filter {
                                case (ruleName, rule) => rule.status == Status.ACTIVE
                            } foreach {
                                case (ruleName, rule) =>
                                    val ruleActivation = WhiskActivation(
                                        namespace = user.namespace.toPath, // all activations should end up in the one space regardless trigger.namespace,
                                        ruleName.name,
                                        user.subject,
                                        activationIdFactory.make(),
                                        Instant.now(Clock.systemUTC()),
                                        Instant.EPOCH,
                                        cause = Some(triggerActivationId),
                                        response = ActivationResponse.success(),
                                        version = trigger.version,
                                        duration = None)
                                    info(this, s"[POST] rule ${ruleName} activated, writing activation record to datastore")
                                    WhiskActivation.put(activationStore, ruleActivation)

                                    val actionNamespace = rule.action.path.root.asString
                                    val actionPath = {
                                        rule.action.path.relativePath.map {
                                            pkg => (Path.SingleSlash + pkg.namespace) / rule.action.name.asString
                                        } getOrElse {
                                            Path.SingleSlash + rule.action.name.asString
                                        }
                                    }.toString

                                    val actionUrl = Path("/api/v1") / "namespaces" / actionNamespace / "actions"

                                    pipeline(Post(url.withPath(actionUrl + actionPath), args)) onComplete {
                                        case Success(o) =>
                                            info(this, s"successfully invoked ${rule.action} -> ${o.fields("activationId")}")
                                        case Failure(usr: UnsuccessfulResponseException) if usr.response.status == StatusCodes.NotFound =>
                                            info(this, s"action ${rule.action} could not be found")
                                        case Failure(t) =>
                                            warn(this, s"action ${rule.action} could not be invoked due to ${t.getMessage}")
                                    }
                            }
                        }

                        onComplete(saveTriggerActivation) {
                            case Success(activationId) =>
                                complete(OK, activationId.toJsObject)
                            case Failure(t: Throwable) =>
                                error(this, s"[POST] storing trigger activation failed: ${t.getMessage}")
                                terminate(InternalServerError)
                        }
                })
        }
    }

    /**
     * Deletes trigger.
     *
     * Responses are one of (Code, Message)
     * - 200 WhiskTrigger as JSON
     * - 404 Not Found
     * - 409 Conflict
     * - 500 Internal Server Error
     */
    override def remove(user: Identity, entityName: FullyQualifiedEntityName)(implicit transid: TransactionId) = {
        deleteEntity(WhiskTrigger, entityStore, entityName.toDocId, (t: WhiskTrigger) => Future.successful({}), postProcess = Some { trigger =>
            completeAsTriggerResponse(trigger)
        })
    }

    /**
     * Gets trigger. The trigger name is prefixed with the namespace to create the primary index key.
     *
     * Responses are one of (Code, Message)
     * - 200 WhiskTrigger has JSON
     * - 404 Not Found
     * - 500 Internal Server Error
     */
    override def fetch(user: Identity, entityName: FullyQualifiedEntityName, env: Option[Parameters])(implicit transid: TransactionId) = {
        getEntity(WhiskTrigger, entityStore, entityName.toDocId, Some { trigger =>
            completeAsTriggerResponse(trigger)
        })
    }

    /**
     * Gets all triggers in namespace.
     *
     * Responses are one of (Code, Message)
     * - 200 [] or [WhiskTrigger as JSON]
     * - 500 Internal Server Error
     */
    override def list(user: Identity, namespace: EntityPath, excludePrivate: Boolean)(implicit transid: TransactionId) = {
        // for consistency, all the collections should support the same list API
        // but because supporting docs on actions is difficult, the API does not
        // offer an option to fetch entities with full docs yet; see comment in
        // Actions API for more.
        val docs = false
        parameter('skip ? 0, 'limit ? collection.listLimit, 'count ? false) {
            (skip, limit, count) =>
                listEntities {
                    WhiskTrigger.listCollectionInNamespace(entityStore, namespace, skip, limit, docs) map {
                        list =>
                            val triggers = if (docs) {
                                list.right.get map { WhiskTrigger.serdes.write(_) }
                            } else list.left.get
                            FilterEntityList.filter(triggers, excludePrivate)
                    }
                }
        }
    }

    /** Creates a WhiskTrigger from PUT content, generating default values where necessary. */
    private def create(content: WhiskTriggerPut, triggerName: FullyQualifiedEntityName)(implicit transid: TransactionId): Future[WhiskTrigger] = {
        val newTrigger = WhiskTrigger(
            triggerName.path,
            triggerName.name,
            content.parameters getOrElse Parameters(),
            content.limits getOrElse TriggerLimits(),
            content.version getOrElse SemVer(),
            content.publish getOrElse false,
            content.annotations getOrElse Parameters())
        validateTriggerFeed(newTrigger)
    }

    /** Updates a WhiskTrigger from PUT content, merging old trigger where necessary. */
    private def update(content: WhiskTriggerPut)(trigger: WhiskTrigger)(implicit transid: TransactionId): Future[WhiskTrigger] = {
        val newTrigger = WhiskTrigger(
            trigger.namespace,
            trigger.name,
            content.parameters getOrElse trigger.parameters,
            content.limits getOrElse trigger.limits,
            content.version getOrElse trigger.version.upPatch,
            content.publish getOrElse trigger.publish,
            content.annotations getOrElse trigger.annotations,
            trigger.rules).
            revision[WhiskTrigger](trigger.docinfo.rev)

        // feed must be specified in create, and cannot be added as a trigger update
        content.annotations flatMap { _.get(Parameters.Feed) } map { _ =>
            Future failed {
                RejectRequest(BadRequest, "A trigger feed is only permitted when the trigger is created")
            }
        } getOrElse {
            Future successful newTrigger
        }
    }

    /**
     * Validates a trigger feed annotation.
     * A trigger feed must be a valid entity name, e.g., one of 'namespace/package/name'
     * or 'namespace/name', or just 'name'.
     *
     * TODO: check if the feed actually exists. This is deferred because the macro
     * operation of creating a trigger and initializing the feed is handled as one
     * atomic operation in the CLI and the UI. At some point these may be promoted
     * to a single atomic operation in the controller; at which point, validating
     * the trigger feed should execute the action (verifies it is a valid name that
     * the subject is entitled to) and iff that succeeds will the trigger be created
     * or updated.
     */
    private def validateTriggerFeed(trigger: WhiskTrigger)(implicit transid: TransactionId) = {
        trigger.annotations.get(Parameters.Feed) map {
            case JsString(f) if (EntityPath.validate(f)) =>
                Future successful trigger
            case _ => Future failed {
                RejectRequest(BadRequest, "Feed name is not valid")
            }
        } getOrElse {
            Future successful trigger
        }
    }

    /**
     * Completes an HTTP request with a WhiskRule including the computed Status
     *
     * @param rule the rule to send
     * @param status the status to include in the response
     */
    private def completeAsTriggerResponse(trigger: WhiskTrigger): RequestContext => Unit = {
        complete(OK, trigger.withoutRules)
    }
}


text:
package mesosphere.marathon.integration.setup

import mesosphere.marathon.api.v2.json.{ V2AppUpdate, V2Group }
import mesosphere.marathon.event._
import mesosphere.marathon.event.http.EventSubscribers
import mesosphere.marathon.state.Timestamp
import mesosphere.marathon.upgrade.DeploymentPlan
import play.api.libs.json._

/**
  * Formats for JSON objects which do not need write support in the production code.
  */
object V2TestFormats {
  import mesosphere.marathon.api.v2.json.Formats._

  implicit lazy val DeploymentPlanReads: Reads[DeploymentPlan] = Reads { js =>
    JsSuccess(
      DeploymentPlan(
        original = (js \ "original").as[V2Group].toGroup(),
        target = (js \ "target").as[V2Group].toGroup(),
        version = (js \ "version").as[Timestamp]).copy(id = (js \ "id").as[String]
        )
    )
  }

  implicit lazy val SubscribeReads: Reads[Subscribe] = Json.reads[Subscribe]
  implicit lazy val UnsubscribeReads: Reads[Unsubscribe] = Json.reads[Unsubscribe]
  implicit lazy val EventStreamAttachedReads: Reads[EventStreamAttached] = Json.reads[EventStreamAttached]
  implicit lazy val EventStreamDetachedReads: Reads[EventStreamDetached] = Json.reads[EventStreamDetached]
  implicit lazy val AddHealthCheckReads: Reads[AddHealthCheck] = Json.reads[AddHealthCheck]
  implicit lazy val RemoveHealthCheckReads: Reads[RemoveHealthCheck] = Json.reads[RemoveHealthCheck]
  implicit lazy val FailedHealthCheckReads: Reads[FailedHealthCheck] = Json.reads[FailedHealthCheck]
  implicit lazy val HealthStatusChangedReads: Reads[HealthStatusChanged] = Json.reads[HealthStatusChanged]
  implicit lazy val GroupChangeSuccessReads: Reads[GroupChangeSuccess] = Json.reads[GroupChangeSuccess]
  implicit lazy val GroupChangeFailedReads: Reads[GroupChangeFailed] = Json.reads[GroupChangeFailed]
  implicit lazy val DeploymentSuccessReads: Reads[DeploymentSuccess] = Json.reads[DeploymentSuccess]
  implicit lazy val DeploymentFailedReads: Reads[DeploymentFailed] = Json.reads[DeploymentFailed]
  //  implicit lazy val DeploymentStatusReads: Reads[DeploymentStatus] = Json.reads[DeploymentStatus]
  //  implicit lazy val DeploymentStepSuccessReads: Reads[DeploymentStepSuccess] = Json.reads[DeploymentStepSuccess]
  //  implicit lazy val DeploymentStepFailureReads: Reads[DeploymentStepFailure] = Json.reads[DeploymentStepFailure]
  implicit lazy val MesosStatusUpdateEventReads: Reads[MesosStatusUpdateEvent] = Json.reads[MesosStatusUpdateEvent]
  implicit lazy val MesosFrameworkMessageEventReads: Reads[MesosFrameworkMessageEvent] =
    Json.reads[MesosFrameworkMessageEvent]
  implicit lazy val SchedulerDisconnectedEventReads: Reads[SchedulerDisconnectedEvent] =
    Json.reads[SchedulerDisconnectedEvent]
  implicit lazy val SchedulerRegisteredEventWritesReads: Reads[SchedulerRegisteredEvent] =
    Json.reads[SchedulerRegisteredEvent]
  implicit lazy val SchedulerReregisteredEventWritesReads: Reads[SchedulerReregisteredEvent] =
    Json.reads[SchedulerReregisteredEvent]

  implicit lazy val eventSubscribersReads: Reads[EventSubscribers] = Reads { subscribersJson =>
    JsSuccess(EventSubscribers(urls = (subscribersJson \ "callbackUrls").asOpt[Set[String]].getOrElse(Set.empty)))
  }

  implicit lazy val v2AppUpdateWrite: Writes[V2AppUpdate] = Writes { update =>
    Json.obj(
      "id" -> update.id.map(_.toString),
      "cmd" -> update.cmd,
      "args" -> update.args,
      "user" -> update.user,
      "env" -> update.env,
      "instances" -> update.instances.map(_.toInt),
      "cpus" -> update.cpus.map(_.toDouble),
      "mem" -> update.mem.map(_.toDouble),
      "disk" -> update.disk.map(_.toDouble),
      "executor" -> update.executor,
      "constraints" -> update.constraints,
      "uris" -> update.uris,
      "storeUrls" -> update.storeUrls,
      "ports" -> update.ports,
      "requirePorts" -> update.requirePorts,
      "backoffSeconds" -> update.backoff.map(_.toSeconds),
      "backoffFactor" -> update.backoffFactor,
      "maxLaunchDelaySeconds" -> update.maxLaunchDelay.map(_.toSeconds),
      "container" -> update.container,
      "healthChecks" -> update.healthChecks,
      "dependencies" -> update.dependencies,
      "upgradeStrategy" -> update.upgradeStrategy,
      "labels" -> update.labels,
      "version" -> update.version,
      "acceptedResourceRoles" -> update.acceptedResourceRoles
    )
  }
}


text:
var chai = require('chai')
  , Strategy = require('../lib/strategy');

describe('Strategy', function() {

  describe('that encounters an error during verification', function() {
    var strategy = new Strategy(function(token, done) {
      return done(new Error('something went wrong'));
    });

    describe('handling a request', function() {
      var err;

      before(function(done) {
        chai.passport(strategy)
          .error(function(e) {
            err = e;
            done();
          })
          .req(function(req) {
            req.headers.authorization = 'Bearer vF9dft4qmT';
          })
          .authenticate();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceof(Error);
        expect(err.message).to.equal('something went wrong');
      });
    });
  });

});


text:
package com.brainbeanapps.rosty.printseditordemo.adapter.holder;

import android.view.View;

import com.brainbeanapps.rosty.printseditordemo.R;
import com.brainbeanapps.rosty.printseditorlib.widget.PrintBackgroundView;

/**
 * Created by rosty on 7/8/2015.
 */
public class BasePrintsHolder extends BaseHolder {

    private PrintBackgroundView printBackgroundView;

    public BasePrintsHolder(View container) {
        super(container);

        printBackgroundView = (PrintBackgroundView) container.findViewById(R.id.prints_background);
    }

    public PrintBackgroundView getPrintBackgroundView() {
        return printBackgroundView;
    }
}


text:
package org.culturegraph.mf.stream.source;

import java.io.FileNotFoundException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import org.culturegraph.mf.exceptions.MetafactureException;
import org.culturegraph.mf.framework.DefaultObjectPipe;
import org.culturegraph.mf.framework.ObjectReceiver;
import org.culturegraph.mf.framework.annotations.Description;
import org.culturegraph.mf.framework.annotations.In;
import org.culturegraph.mf.framework.annotations.Out;
import org.culturegraph.mf.util.ResourceUtil;

/**
 * Opens a resource or file and passes a reader for it to the receiver.
 *
 * @author Christoph Böhme
 *
 */
@Description("Opens a resource.")
@In(String.class)
@Out(java.io.Reader.class)
public final class ResourceOpener
		extends DefaultObjectPipe<String, ObjectReceiver<Reader>> implements Opener{

	private String encoding = "UTF-8";

	/**
	 * Returns the encoding used to open the resource.
	 *
	 * @return current default setting
	 */
	public String getEncoding() {
		return encoding;
	}

	/**
	 * Sets the encoding used to open the resource.
	 *
	 * @param encoding new encoding
	 */
	public void setEncoding(final String encoding) {
		this.encoding = encoding;
	}

	@Override
	public void process(final String file) {
		try {
			getReceiver().process(ResourceUtil.getReader(file, encoding));
		} catch (FileNotFoundException e) {
			throw new MetafactureException(e);
		} catch (UnsupportedEncodingException e) {
			throw new MetafactureException(e);
		}
	}

}