text:
<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>

      <title>www.karolisram.com</title>

   <link>http://www.karolisram.com/</link>
   <description>Curious about Machine Learning, Data Analytics, E-commerce.</description>
   <language>en-uk</language>
   <managingEditor> Karolis Ramanauskas</managingEditor>
   <atom:link href="rss" rel="self" type="application/rss+xml" />

	<item>
	  <title>Analyzing Hacker News 📰 submissions: Scraping (Part 1)</title>
	  <link>//analyzing-hacker-news-submissions-scraping-part-1/</link>
	  <author>Karolis Ramanauskas</author>
	  <pubDate>2017-01-27T16:38:31+00:00</pubDate>
	  <guid>//analyzing-hacker-news-submissions-scraping-part-1/</guid>
	  <description><![CDATA[

During those days when I still read news (good ol' times) which is only a month ago, I was an avid lurker on Hacker News which is a great source of technology related news with a great community. It works in a similar way to Reddit with people submitting articles or asking questions, and other people voting them up.

In this series of blog posts, I aim to scrape data from Hacker News submissions and analyze the data to investigate all there is to investigate about the site such as which domains people upvote the most, which domains are the least likely to gain success, and so on.

It will not be an in-depth tutorial but should hopefully cover enough material so that anyone can replicate my scraping tactics and analysis techniques.

Setting up the scraper 🤖

Fortunately for us, Hacker News, despite its archaic HTML layout, is a very simple site with no AJAX loading and other fancy bits. Thus, scraping the site is extremely easy.

The entire scraper code fits into 45 lines, with another 45 dedicated to setting up the database and saving the results. Let's start at the top by importing all the necessary modules needed for the project:

import requests
import datetime
from sqlalchemy import Column, Integer, String, DateTime, create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from bs4 import BeautifulSoup
import os

Nothing fancy there. We will use requests module to fetch the HTML, and BeautifulSoup to parse it. Also, with the help of SQLAlchemy we are going to use SQLite to store the results for analysis.

Now, let's set up the database using SQLAlchemy's recommended Object Relational Mapper. Note that we use an absolute path to our database by using the environment variable HN_SCRAPER_HOME. This is necessary because later we will run our scraper bot with crontab which will run from the root directory and will save the database in the wrong place if a relative path was used.

engine = create_engine('sqlite:///'+os.environ['HN_SCRAPER_HOME']+'/database.db')
Base = declarative_base()

Now that we have our database setup, let's setup the tables for tracking Hacker News submissions.

Story_Info will act as a reference table that contains story submissions title, URL, a user that submitted the story, version and fetch date. The version number is kept because often stories title or link is modified. so we want to track if anything has changed and if it did, save a new version of the submission leaving the previous one intact.

Story_Tracker will be the fatty table here where we will keep track of stories rank, comments count and points at every given interval. Along with that, we will store whether the story is on the submission page, or the front page. This will allow us to analyze how many of the stories make to the front page, at what speed and so on.

class Story_Info(Base):
	__tablename__ = 'info'

	id = Column(Integer, primary_key=True)
	title = Column(String)
	url = Column(String)
	user = Column(String)
	version = Column(Integer, primary_key=True)
	fetch_date =  Column(DateTime, default=datetime.datetime.utcnow)

	def __repr__(self):
	   return "<Story_Info(id='%d',title='%s',url='%s',user='%s',version='%d')>" % (
	                    self.id,self.title,self.url,self.user,self.version)

class Story_Tracker(Base):
	__tablename__ = 'tracker'

	id = Column(Integer, ForeignKey('info.id'), primary_key=True)
	score = Column(Integer)
	rank = Column(Integer)
	front_page = Column(Integer)
	fetch_date =  Column(DateTime, primary_key=True, default=datetime.datetime.utcnow)

	def __repr__(self):
	   return "<Story_Tracker(id='%d',score='%s',rank='%s')>" % (
	                    self.id,self.score,self.rank)

Now comes the fun part, the HTML parser itself. The script is contained within a fetch_stories function which accepts two parameters - a URL from which to scrape submissions, and FRONT_PAGE indicating whether the stories in the link should be considered as being on the front page or not. I will not discuss the rest but I would gladly answer questions if anyone is curious 😉

def fetch_stories(url, front_page):
	html = requests.get(url)
	parser = BeautifulSoup(html.text, 'html.parser')

	story_links = parser.select("tr.athing")

	for idx, story in enumerate(story_links):
		info = story_links[idx].find_next_sibling("tr")

		id = story.get("id")
		rank = story_links[idx].select(".rank")[0].text

		score = info.select(".score")
		if score:
			score = score[0].text.split(" ")[0]
		else:
			score = 0

		user = info.select(".hnuser")
		if user:
			user = user[0].text
		else:
			user = ""

		story_link = story.select(".storylink")[0]
		url = story_link.get("href")
		title = story_link.text

		story_info = session.query(Story_Info).order_by(Story_Info.version.desc()).filter_by(id=int(id)).first()

		if story_info == None:
			story = Story_Info(id=int(id),title=title,url=url,user=user,version=1)
			session.add(story)
		else:
			any_changes = False
			if title != story_info.title or url != story_info.url or user != story_info.user:
				new_version = story_info.version + 1
				story = Story_Info(id=int(id),title=title,url=url,user=user,version=new_version)
				session.add(story)

		story = Story_Tracker(id=int(id),score=int(score),rank=int(score),front_page=front_page)
		session.add(story)
		session.commit()

fetch_stories(url="https://news.ycombinator.com/",front_page=1)
fetch_stories(url="https://news.ycombinator.com/newest",front_page=0)

Full code available at HN Scraper Analysis Github repository.

Running the scraper 🖥

Now that we have code for the scraper, we need to set it up on the server and leave it running. I did it via a free EC2 micro tier instance which should suffice for our needs.

Once EC2 instance is ready, transfer the files to the server as such:

scp -i key.pem /path/to/parser.py ubuntu@ec2-instance-ip.compute-1.amazonaws.com:~

Then SSH into the instance and setup the environment as such:

wget https://repo.continuum.io/archive/Anaconda3-4.2.0-Linux-x86_64.sh
bash Anaconda3-4.2.0-Linux-x86_64.sh
export PATH=~/anaconda3/bin:$PATH

The above will install Anaconda which is a truly awesome open source distribution of Python that contains close to anything you may need for big-data processing.

Finally, we need to set up the crontab so that it runs our script at a given interval, in this case, every 2 minutes.

Note that since in our script we use absolute path taken from an environment variable, we need to declare that as seen below. Also, we must make sure to use Anaconda's package and not the default Python found on Ubuntu systems. This can be done easily by specifying the python executable file. Finally, we save any errors in a parser-log.log file which will make debugging easier if anything nasty comes up.

HN_SCRAPER_HOME = /home/ubuntu/
*/2 * * * * /home/ubuntu/anaconda3/bin/python /home/ubuntu/parser.py >> /home/ubuntu/parser-log.log 2>&1

Once our scraper has run, the data will become available for inspection at /home/ubuntu/database.db.

Gotchas

One gotcha that I encountered is that new Ubuntu instances often fail to run crontab which is caused by the error no MTA is installed. So if you see that happening, execute the following command sudo apt-get install postfix and upon installation choose the local user option.

Will the database handle the data?

One question that worried me is whether the EC2 instance or the SQLite database will be able to handle the amount of data that we are going to scrape. SQLite has a theoretical limit of 140TB which is obviously going to be more than enough. On the other hand, AWS t2.micro instance has only 1GB of memory available which may be problematic.

To see if our EC2 instance will be big enough, let's first consider how many fetches of data we will perform. Since there are 86,400 minutes in 60 days, and we fetch new data every 2 minutes, we will execute 43200 requests to HN in total. Also, fortunately for us, each fetch of data only carries a measly 4kb of data meaning that all 43,200 requests will only take 43,200*4=172800kb which is just above 172mb. So we are safe! 🙌

Wrapping up

Now, we should have our scraper bot running successfully. All that is left for now is leave it alone to do its job and come back in 60 days with the data ready to analyze. Meanwhile, enjoy life! 🌻

	  ]]></description>
	</item>

</channel>
</rss>


text:
<?php

namespace VagueSoftware\Refuel2Bundle\Form\Base;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

/**
 * Class OpenWinType
 * @package VagueSoftware\Refuel2Bundle\Form\Base
 */
class OpenWinType extends AbstractType
{
    /**
     * @return string
     */
    public function getParent()
    {
        return ChoiceType::class;
    }
}

redpajama_set_name: RedPajamaGithub


text:
	Allow freedom of movement around a current place, much like the classic script works now.
	Not intended to be use with the current character script. This is the rotation component.
	Intended to be used with a SummedCamera, relative.

	@class SmoothRotatedCamera
]=]

local require = require(script.Parent.loader).load(script)

local CameraState = require("CameraState")
local getRotationInXZPlane = require("getRotationInXZPlane")
local Spring = require("Spring")
local SummedCamera = require("SummedCamera")

local SmoothRotatedCamera = {}
SmoothRotatedCamera.ClassName = "SmoothRotatedCamera"

-- Max/Min aim up and down
SmoothRotatedCamera._maxY = math.rad(80)
SmoothRotatedCamera._minY = math.rad(-80)
SmoothRotatedCamera._zoomGiveY = math.rad(5) -- Only on th

function SmoothRotatedCamera.new()
	local self = setmetatable({}, SmoothRotatedCamera)

	self.SpringX = Spring.new(0)
	self.SpringY = Spring.new(0)
	self.Speed = 15

	return self
end

function SmoothRotatedCamera:__add(other)
	return SummedCamera.new(self, other)
end

--[=[
	@param xyRotateVector Vector2 -- The delta rotation to apply
]=]
function SmoothRotatedCamera:RotateXY(xyRotateVector)
	self.AngleX = self.AngleX + xyRotateVector.x
	self.AngleY = self.AngleY + xyRotateVector.y
	self.TargetAngleX = self.AngleX
	self.TargetAngleY = self.AngleY
end

function SmoothRotatedCamera:__newindex(index, value)
	if index == "CFrame" then
		local xzrot = getRotationInXZPlane(value)
		self.AngleXZ = math.atan2(xzrot.lookVector.x, xzrot.lookVector.z) + math.pi

		local yrot = xzrot:toObjectSpace(value).lookVector.y
		self.AngleY = math.asin(yrot)
	elseif index == "TargetCFrame" then
		local xzrot = getRotationInXZPlane(value)
		self.TargetAngleXZ = math.atan2(xzrot.lookVector.x, xzrot.lookVector.z) + math.pi

		local yrot = xzrot:toObjectSpace(value).lookVector.y
		self.TargetAngleY = math.asin(yrot)
	elseif index == "AngleY" then
		self.SpringY.Value = value
	elseif index == "AngleX" or index == "AngleXZ" then
		self.SpringX.Value = value
	elseif index == "TargetAngleY" then
		self.SpringY.Target = value
	elseif index == "TargetAngleX" or index == "TargetAngleXZ" then
		self.SpringX.Target = value
	elseif index == "MaxY" then
		assert(value >= self.MinY, "MaxY must be greater than MinY")
		self._maxY = value
	elseif index == "MinY" then
		assert(value <= self.MaxY, "MinY must be less than MaxY")
		self._minY = value
	elseif index == "SpeedAngleX" or index == "SpeedAngleXZ" then
		self.SpringX.Speed = value
	elseif index == "SpeedAngleY" then
		self.SpringY.Speed = value
	elseif index == "Speed" then
		self.SpeedAngleX = value
		self.SpeedAngleY = value
	elseif index == "ZoomGiveY" then
		self._zoomGiveY = value
	elseif SmoothRotatedCamera[index] ~= nil or index == "SpringX" or index == "SpringY" then
		rawset(self, index, value)
	else
		error(index .. " is not a valid member or SmoothRotatedCamera")
	end
end

function SmoothRotatedCamera:SnapIntoBounds()
	self.TargetAngleY = math.clamp(self.TargetAngleY, self.MinY, self.MaxY)
end

function SmoothRotatedCamera:GetPastBounds(angle)
	if angle < self.MinY then
		return angle - self.MinY
	elseif angle > self.MaxY then
		return angle - self.MaxY
	else
		return 0
	end
end

function SmoothRotatedCamera:__index(index)
	if index == "CameraState" then
		local state = CameraState.new()
		state.CFrame = self.CFrame
		return state
	elseif index == "LookVector" then
		return self.Rotation.lookVector
	elseif index == "CFrame" then
		return CFrame.Angles(0, self.RenderAngleXZ, 0) * CFrame.Angles(self.RenderAngleY, 0, 0)
	elseif index == "TargetCFrame" then
		return CFrame.Angles(0, self.TargetAngleXZ, 0) * CFrame.Angles(self.TargetAngleY, 0, 0)
	elseif index == "RenderAngleY" then
		local angle = self.AngleY
		local past = self:GetPastBounds(angle)

		local timesOverBounds = math.abs(past) / self.ZoomGiveY
		local scale = (1 - 0.25 ^ math.abs(timesOverBounds))

		if past < 0 then
			return self.MinY - self.ZoomGiveY*scale
		elseif past > 0 then
			return self.MaxY + self.ZoomGiveY*scale
		else
			return angle
		end
	elseif index == "RenderAngleX" or index == "RenderAngleXZ" then
		return self.AngleX
	elseif index == "AngleY" then
		return self.SpringY.Value
	elseif index == "AngleX" or index == "AngleXZ" then
		return self.SpringX.Value
	elseif index == "TargetAngleY" then
		return self.SpringY.Target
	elseif index == "TargetAngleX" or index == "TargetAngleXZ" then
		return self.SpringX.Target
	elseif index == "SpeedAngleY" then
		return self.SpringX.Speed
	elseif index == "MaxY" then
		return self._maxY
	elseif index == "MinY" then
		return self._minY
	elseif index == "ZoomGiveY" then
		return self._zoomGiveY
	else
		return SmoothRotatedCamera[index]
	end
end

return SmoothRotatedCamera


text:
package com.eusoft.recite.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

/**
 * Created by xj on 2017/1/10.
 * 专用于horizontal两子view适配
 */

public class WrapLinearLayout extends LinearLayout {

    public WrapLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        View child_1 = getChildAt(0);
        View child_2 = getChildAt(1);
        int width = getMeasuredWidth() - getPaddingLeft()
                - getPaddingRight() - getHorizontalMargin(child_1)
                - getHorizontalMargin(child_2);
        int halfWidth = width / 2;
        if (child_1.getMeasuredWidth() >= halfWidth || child_2.getMeasuredWidth() >= halfWidth) {
            makeZeroToHorizontalMargin(child_1);
            makeZeroToHorizontalMargin(child_2);
            setOrientation(VERTICAL);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    private int getHorizontalMargin(View view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params instanceof MarginLayoutParams) {
            MarginLayoutParams p = (MarginLayoutParams) params;
            return p.leftMargin + p.rightMargin;
        }
        return 0;
    }

    private void makeZeroToHorizontalMargin(View view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params instanceof MarginLayoutParams) {
            MarginLayoutParams p = (MarginLayoutParams) params;
            p.leftMargin = p.rightMargin = 0;
        }
    }
}


text:
[ Under Development ]

This component allows users to get information about current and past issues.

Users will be able to:

See what issues are currently being discussed at recent meetings.

Select an issue and read what was said about it at past meetings.

See issues arranged by category (Zoning, Public Safety, Housing, etc. )

Compare issues by activity and amount of discussion.

Compare types of issues discussed across different communities.


text:
package org.radargun.stages.cache.background;

import org.radargun.Operation;
import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.stages.cache.generators.KeyGenerator;
import org.radargun.traits.BasicOperations;
import org.radargun.traits.Transactional;

import java.util.Random;

/**
 * Common operations for all logic types.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public abstract class AbstractLogic implements Logic {

   protected static final Operation GET_NULL = BasicOperations.GET.derive("Null");
   protected final Log log = LogFactory.getLog(getClass());
   protected final boolean trace = log.isTraceEnabled();

   protected BackgroundOpsManager manager;
   protected KeyGenerator keyGenerator;
   protected final int operations;
   protected final int transactionSize;
   protected Stressor stressor;
   protected Transactional.Transaction ongoingTx;

   protected AbstractLogic(BackgroundOpsManager manager) {
      this.manager = manager;
      this.keyGenerator = manager.getKeyGenerator();
      this.transactionSize = manager.getGeneralConfiguration().getTransactionSize();
      this.operations = manager.getGeneralConfiguration().puts + manager.getGeneralConfiguration().gets + manager.getGeneralConfiguration().removes;
   }

   @Override
   public void finish() {
      if (transactionSize > 0 && ongoingTx != null) {
         try {
            ongoingTx.rollback();
         } catch (Exception e) {
            log.error("Error while ending transaction", e);
         }
      }
   }

   @Override
   public void setStressor(Stressor stressor) {
      this.stressor = stressor;
   }

   public Operation getOperation(Random rand) {
      int r = rand.nextInt(operations);
      if (r < manager.getGeneralConfiguration().gets) {
         return BasicOperations.GET;
      } else if (r < manager.getGeneralConfiguration().gets + manager.getGeneralConfiguration().puts) {
         return BasicOperations.PUT;
      } else return BasicOperations.REMOVE;
   }

}


text:
webui-seed
==========

seed = mongo + express + angular + bootstrap


text:
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::SaveArg;
using ::testing::StrictMock;

namespace media {

ACTION_P(RunClosure, closure) {
  closure.Run();
}

MATCHER_P(HasTimestamp, ms, "") {
  *result_listener << "has timestamp " << arg->timestamp().InMilliseconds();
  return arg->timestamp().InMilliseconds() == ms;
}

// Arbitrary value. Has to be larger to cover any timestamp value used in tests
// and kTimeToDeclareHaveNothing.
static const int kVideoDurationInMs = 10000;

class VideoRendererImplTest : public ::testing::Test {
 public:
  VideoRendererImplTest()
      : decoder_(new MockVideoDecoder()),
        demuxer_stream_(DemuxerStream::VIDEO) {
    ScopedVector<VideoDecoder> decoders;
    decoders.push_back(decoder_);

    renderer_.reset(new VideoRendererImpl(
        message_loop_.message_loop_proxy(),
        decoders.Pass(),
        media::SetDecryptorReadyCB(),
        base::Bind(&StrictMock<MockCB>::Display, base::Unretained(&mock_cb_)),
        true));

    demuxer_stream_.set_video_decoder_config(TestVideoConfig::Normal());

    // We expect these to be called but we don't care how/when.
    EXPECT_CALL(demuxer_stream_, Read(_)).WillRepeatedly(
        RunCallback<0>(DemuxerStream::kOk,
                       scoped_refptr<DecoderBuffer>(new DecoderBuffer(0))));
    EXPECT_CALL(statistics_cb_object_, OnStatistics(_))
        .Times(AnyNumber());
    EXPECT_CALL(*this, OnTimeUpdate(_))
        .Times(AnyNumber());
  }

  virtual ~VideoRendererImplTest() {}

  // Callbacks passed into Initialize().
  MOCK_METHOD1(OnTimeUpdate, void(base::TimeDelta));

  void Initialize() {
    InitializeWithLowDelay(false);
  }

  void InitializeWithLowDelay(bool low_delay) {
    // Monitor decodes from the decoder.
    EXPECT_CALL(*decoder_, Decode(_, _))
        .WillRepeatedly(Invoke(this, &VideoRendererImplTest::DecodeRequested));

    EXPECT_CALL(*decoder_, Reset(_))
        .WillRepeatedly(Invoke(this, &VideoRendererImplTest::FlushRequested));

    // Initialize, we shouldn't have any reads.
    InitializeRenderer(PIPELINE_OK, low_delay);
  }

  void InitializeRenderer(PipelineStatus expected, bool low_delay) {
    SCOPED_TRACE(base::StringPrintf("InitializeRenderer(%d)", expected));
    WaitableMessageLoopEvent event;
    CallInitialize(event.GetPipelineStatusCB(), low_delay, expected);
    event.RunAndWaitForStatus(expected);
  }

  void CallInitialize(const PipelineStatusCB& status_cb,
                      bool low_delay,
                      PipelineStatus decoder_status) {
    EXPECT_CALL(*decoder_, Initialize(_, _, _, _)).WillOnce(
        DoAll(SaveArg<3>(&output_cb_), RunCallback<2>(decoder_status)));
    renderer_->Initialize(
        &demuxer_stream_,
        low_delay,
        status_cb,
        base::Bind(&MockStatisticsCB::OnStatistics,
                   base::Unretained(&statistics_cb_object_)),
        base::Bind(&VideoRendererImplTest::OnTimeUpdate,
                   base::Unretained(this)),
        base::Bind(&StrictMock<MockCB>::BufferingStateChange,
                   base::Unretained(&mock_cb_)),
        ended_event_.GetClosure(),
        error_event_.GetPipelineStatusCB(),
        base::Bind(&VideoRendererImplTest::GetTime, base::Unretained(this)),
        base::Bind(&VideoRendererImplTest::GetDuration,
                   base::Unretained(this)));
  }

  void StartPlaying() {
    SCOPED_TRACE("StartPlaying()");
    renderer_->StartPlaying();
    message_loop_.RunUntilIdle();
  }

  void Flush() {
    SCOPED_TRACE("Flush()");
    WaitableMessageLoopEvent event;
    renderer_->Flush(event.GetClosure());
    event.RunAndWait();
  }

  void Destroy() {
    SCOPED_TRACE("Destroy()");
    renderer_.reset();
  }

  // Parses a string representation of video frames and generates corresponding
  // VideoFrame objects in |decode_results_|.
  //
  // Syntax:
  //   nn - Queue a decoder buffer with timestamp nn * 1000us
  //   abort - Queue an aborted read
  //   error - Queue a decoder error
  //
  // Examples:
  //   A clip that is four frames long: "0 10 20 30"
  //   A clip that has a decode error: "60 70 error"
  void QueueFrames(const std::string& str) {
    std::vector<std::string> tokens;
    base::SplitString(str, ' ', &tokens);
    for (size_t i = 0; i < tokens.size(); ++i) {
      if (tokens[i] == "abort") {
        scoped_refptr<VideoFrame> null_frame;
        decode_results_.push_back(
            std::make_pair(VideoDecoder::kAborted, null_frame));
        continue;
      }

      if (tokens[i] == "error") {
        scoped_refptr<VideoFrame> null_frame;
        decode_results_.push_back(
            std::make_pair(VideoDecoder::kDecodeError, null_frame));
        continue;
      }

      int timestamp_in_ms = 0;
      if (base::StringToInt(tokens[i], &timestamp_in_ms)) {
        gfx::Size natural_size = TestVideoConfig::NormalCodedSize();
        scoped_refptr<VideoFrame> frame = VideoFrame::CreateFrame(
            VideoFrame::YV12,
            natural_size,
            gfx::Rect(natural_size),
            natural_size,
            base::TimeDelta::FromMilliseconds(timestamp_in_ms));
        decode_results_.push_back(std::make_pair(VideoDecoder::kOk, frame));
        continue;
      }

      CHECK(false) << "Unrecognized decoder buffer token: " << tokens[i];
    }
  }

  bool IsReadPending() {
    return !decode_cb_.is_null();
  }

  void WaitForError(PipelineStatus expected) {
    SCOPED_TRACE(base::StringPrintf("WaitForError(%d)", expected));
    error_event_.RunAndWaitForStatus(expected);
  }

  void WaitForEnded() {
    SCOPED_TRACE("WaitForEnded()");
    ended_event_.RunAndWait();
  }

  void WaitForPendingRead() {
    SCOPED_TRACE("WaitForPendingRead()");
    if (!decode_cb_.is_null())
      return;

    DCHECK(wait_for_pending_decode_cb_.is_null());

    WaitableMessageLoopEvent event;
    wait_for_pending_decode_cb_ = event.GetClosure();
    event.RunAndWait();

    DCHECK(!decode_cb_.is_null());
    DCHECK(wait_for_pending_decode_cb_.is_null());
  }

  void SatisfyPendingRead() {
    CHECK(!decode_cb_.is_null());
    CHECK(!decode_results_.empty());

    // Post tasks for OutputCB and DecodeCB.
    scoped_refptr<VideoFrame> frame = decode_results_.front().second;
    if (frame)
      message_loop_.PostTask(FROM_HERE, base::Bind(output_cb_, frame));
    message_loop_.PostTask(
        FROM_HERE, base::Bind(base::ResetAndReturn(&decode_cb_),
                              decode_results_.front().first));
    decode_results_.pop_front();
  }

  void SatisfyPendingReadWithEndOfStream() {
    DCHECK(!decode_cb_.is_null());

    // Return EOS buffer to trigger EOS frame.
    EXPECT_CALL(demuxer_stream_, Read(_))
        .WillOnce(RunCallback<0>(DemuxerStream::kOk,
                                 DecoderBuffer::CreateEOSBuffer()));

    // Satify pending |decode_cb_| to trigger a new DemuxerStream::Read().
    message_loop_.PostTask(
        FROM_HERE,
        base::Bind(base::ResetAndReturn(&decode_cb_), VideoDecoder::kOk));

    WaitForPendingRead();

    message_loop_.PostTask(
        FROM_HERE,
        base::Bind(base::ResetAndReturn(&decode_cb_), VideoDecoder::kOk));
  }

  void AdvanceTimeInMs(int time_ms) {
    DCHECK_EQ(&message_loop_, base::MessageLoop::current());
    base::AutoLock l(lock_);
    time_ += base::TimeDelta::FromMilliseconds(time_ms);
    DCHECK_LE(time_.InMicroseconds(), GetDuration().InMicroseconds());
  }

 protected:
  // Fixture members.
  scoped_ptr<VideoRendererImpl> renderer_;
  MockVideoDecoder* decoder_;  // Owned by |renderer_|.
  NiceMock<MockDemuxerStream> demuxer_stream_;
  MockStatisticsCB statistics_cb_object_;

  // Use StrictMock<T> to catch missing/extra callbacks.
  class MockCB {
   public:
    MOCK_METHOD1(Display, void(const scoped_refptr<VideoFrame>&));
    MOCK_METHOD1(BufferingStateChange, void(BufferingState));
  };
  StrictMock<MockCB> mock_cb_;

 private:
  base::TimeDelta GetTime() {
    base::AutoLock l(lock_);
    return time_;
  }

  base::TimeDelta GetDuration() {
    return base::TimeDelta::FromMilliseconds(kVideoDurationInMs);
  }

  void DecodeRequested(const scoped_refptr<DecoderBuffer>& buffer,
                       const VideoDecoder::DecodeCB& decode_cb) {
    DCHECK_EQ(&message_loop_, base::MessageLoop::current());
    CHECK(decode_cb_.is_null());
    decode_cb_ = decode_cb;

    // Wake up WaitForPendingRead() if needed.
    if (!wait_for_pending_decode_cb_.is_null())
      base::ResetAndReturn(&wait_for_pending_decode_cb_).Run();

    if (decode_results_.empty())
      return;

    SatisfyPendingRead();
  }

  void FlushRequested(const base::Closure& callback) {
    DCHECK_EQ(&message_loop_, base::MessageLoop::current());
    decode_results_.clear();
    if (!decode_cb_.is_null()) {
      QueueFrames("abort");
      SatisfyPendingRead();
    }

    message_loop_.PostTask(FROM_HERE, callback);
  }

  base::MessageLoop message_loop_;

  // Used to protect |time_|.
  base::Lock lock_;
  base::TimeDelta time_;

  // Used for satisfying reads.
  VideoDecoder::OutputCB output_cb_;
  VideoDecoder::DecodeCB decode_cb_;
  base::TimeDelta next_frame_timestamp_;

  WaitableMessageLoopEvent error_event_;
  WaitableMessageLoopEvent ended_event_;

  // Run during DecodeRequested() to unblock WaitForPendingRead().
  base::Closure wait_for_pending_decode_cb_;

  std::deque<std::pair<
      VideoDecoder::Status, scoped_refptr<VideoFrame> > > decode_results_;

  DISALLOW_COPY_AND_ASSIGN(VideoRendererImplTest);
};

TEST_F(VideoRendererImplTest, DoNothing) {
  // Test that creation and deletion doesn't depend on calls to Initialize()
  // and/or Destroy().
}

TEST_F(VideoRendererImplTest, DestroyWithoutInitialize) {
  Destroy();
}

TEST_F(VideoRendererImplTest, Initialize) {
  Initialize();
  Destroy();
}

TEST_F(VideoRendererImplTest, InitializeAndStartPlaying) {
  Initialize();
  QueueFrames("0 10 20 30");
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  StartPlaying();
  Destroy();
}

TEST_F(VideoRendererImplTest, DestroyWhileInitializing) {
  CallInitialize(NewExpectedStatusCB(PIPELINE_ERROR_ABORT), false, PIPELINE_OK);
  Destroy();
}

TEST_F(VideoRendererImplTest, DestroyWhileFlushing) {
  Initialize();
  QueueFrames("0 10 20 30");
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  StartPlaying();
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_NOTHING));
  renderer_->Flush(NewExpectedClosure());
  Destroy();
}

TEST_F(VideoRendererImplTest, Play) {
  Initialize();
  QueueFrames("0 10 20 30");
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  StartPlaying();
  Destroy();
}

TEST_F(VideoRendererImplTest, FlushWithNothingBuffered) {
  Initialize();
  StartPlaying();

  // We shouldn't expect a buffering state change since we never reached
  // BUFFERING_HAVE_ENOUGH.
  Flush();
  Destroy();
}

TEST_F(VideoRendererImplTest, EndOfStream_ClipDuration) {
  Initialize();
  QueueFrames("0");
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  StartPlaying();

  // Next frame has timestamp way past duration. Its timestamp will be adjusted
  // to match the duration of the video.
  QueueFrames(base::IntToString(kVideoDurationInMs + 1000));
  SatisfyPendingRead();
  WaitForPendingRead();

  // Queue the end of stream frame and wait for the last frame to be rendered.
  SatisfyPendingReadWithEndOfStream();

  EXPECT_CALL(mock_cb_, Display(HasTimestamp(kVideoDurationInMs)));
  AdvanceTimeInMs(kVideoDurationInMs);
  WaitForEnded();

  Destroy();
}

TEST_F(VideoRendererImplTest, DecodeError_Playing) {
  Initialize();
  QueueFrames("0 10 20 30");
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  StartPlaying();

  QueueFrames("error");
  SatisfyPendingRead();
  WaitForError(PIPELINE_ERROR_DECODE);
  Destroy();
}

TEST_F(VideoRendererImplTest, DecodeError_DuringStartPlaying) {
  Initialize();
  QueueFrames("error");
  StartPlaying();
  Destroy();
}

TEST_F(VideoRendererImplTest, StartPlaying_Exact) {
  Initialize();
  QueueFrames("50 60 70 80 90");

  EXPECT_CALL(mock_cb_, Display(HasTimestamp(60)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  AdvanceTimeInMs(60);
  StartPlaying();
  Destroy();
}

TEST_F(VideoRendererImplTest, StartPlaying_RightBefore) {
  Initialize();
  QueueFrames("50 60 70 80 90");

  EXPECT_CALL(mock_cb_, Display(HasTimestamp(50)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  AdvanceTimeInMs(59);
  StartPlaying();
  Destroy();
}

TEST_F(VideoRendererImplTest, StartPlaying_RightAfter) {
  Initialize();
  QueueFrames("50 60 70 80 90");

  EXPECT_CALL(mock_cb_, Display(HasTimestamp(60)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  AdvanceTimeInMs(61);
  StartPlaying();
  Destroy();
}

TEST_F(VideoRendererImplTest, StartPlaying_LowDelay) {
  // In low-delay mode only one frame is required to finish preroll.
  InitializeWithLowDelay(true);
  QueueFrames("0");

  // Expect some amount of have enough/nothing due to only requiring one frame.
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH))
      .Times(AnyNumber());
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_NOTHING))
      .Times(AnyNumber());
  StartPlaying();

  QueueFrames("10");
  SatisfyPendingRead();

  WaitableMessageLoopEvent event;
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(10)))
      .WillOnce(RunClosure(event.GetClosure()));
  AdvanceTimeInMs(10);
  event.RunAndWait();

  Destroy();
}

TEST_F(VideoRendererImplTest, PlayAfterStartPlaying) {
  Initialize();
  QueueFrames("0 10 20 30");
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  StartPlaying();

  // Check that there is an outstanding Read() request.
  EXPECT_TRUE(IsReadPending());

  Destroy();
}

// Verify that a late decoder response doesn't break invariants in the renderer.
TEST_F(VideoRendererImplTest, DestroyDuringOutstandingRead) {
  Initialize();
  QueueFrames("0 10 20 30");
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  StartPlaying();

  // Check that there is an outstanding Read() request.
  EXPECT_TRUE(IsReadPending());

  Destroy();
}

TEST_F(VideoRendererImplTest, VideoDecoder_InitFailure) {
  InitializeRenderer(DECODER_ERROR_NOT_SUPPORTED, false);
  Destroy();
}

TEST_F(VideoRendererImplTest, Underflow) {
  Initialize();
  QueueFrames("0 10 20 30");
  EXPECT_CALL(mock_cb_, Display(HasTimestamp(0)));
  EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH));
  StartPlaying();

  // Advance time slightly. Frames should be dropped and we should NOT signal
  // having nothing.
  AdvanceTimeInMs(100);

  // Advance time more. Now we should signal having nothing.
  {
    SCOPED_TRACE("Waiting for BUFFERING_HAVE_NOTHING");
    WaitableMessageLoopEvent event;
    EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_NOTHING))
        .WillOnce(RunClosure(event.GetClosure()));
    AdvanceTimeInMs(3000); // Must match kTimeToDeclareHaveNothing.
    event.RunAndWait();
  }

  // Receiving end of stream should signal having enough.
  {
    SCOPED_TRACE("Waiting for BUFFERING_HAVE_ENOUGH");
    WaitableMessageLoopEvent event;
    EXPECT_CALL(mock_cb_, BufferingStateChange(BUFFERING_HAVE_ENOUGH))
        .WillOnce(RunClosure(event.GetClosure()));
    SatisfyPendingReadWithEndOfStream();
    event.RunAndWait();
  }

  WaitForEnded();
  Destroy();
}

}  // namespace media


text:
from binascii import hexlify

import pytest
from plenum.common.util import friendlyToRaw

from indy_client.test.cli.constants import INVALID_SYNTAX
from indy_client.test.cli.helper import createUuidIdentifier, addNym, \
    createHalfKeyIdentifierAndAbbrevVerkey, createCryptonym
from indy_common.roles import Roles
from indy_node.test.helper import check_str_is_base58_compatible

CURRENT_VERKEY_FOR_NYM = 'Current verkey for NYM {dest} is {verkey}'
CURRENT_VERKEY_FOR_NYM_WITH_ROLE = 'Current verkey for NYM {dest} is ' \
                                   '{verkey} with role {role}'
CURRENT_VERKEY_IS_SAME_AS_IDENTIFIER = \
    'Current verkey is same as identifier {dest}'
NYM_NOT_FOUND = 'NYM {dest} not found'

def testSendGetNymSucceedsForExistingUuidDest(
        be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier, abbrevVerkey = createHalfKeyIdentifierAndAbbrevVerkey()
    addNym(be, do, trusteeCli, idr=uuidIdentifier, verkey=abbrevVerkey)

    parameters = {
        'dest': uuidIdentifier,
        'verkey': abbrevVerkey
    }

    be(trusteeCli)
    do('send GET_NYM dest={dest}',
       mapper=parameters, expect=CURRENT_VERKEY_FOR_NYM, within=2)

def testSendGetNymFailsForNotExistingUuidDest(
        be, do, poolNodesStarted, trusteeCli):

    parameters = {
        'dest': createUuidIdentifier()
    }

    be(trusteeCli)
    do('send GET_NYM dest={dest}',
       mapper=parameters, expect=NYM_NOT_FOUND, within=2)

def test_get_nym_returns_role(
        be, do, poolNodesStarted, trusteeCli):
    current_role = Roles.TRUST_ANCHOR
    uuidIdentifier, abbrevVerkey = createHalfKeyIdentifierAndAbbrevVerkey()
    addNym(be, do, trusteeCli, idr=uuidIdentifier, verkey=abbrevVerkey,
           role=current_role)

    parameters = {
        'dest': uuidIdentifier,
        'verkey': abbrevVerkey,
        'role': current_role
    }

    do('send GET_NYM dest={dest}',
       mapper=parameters, expect=CURRENT_VERKEY_FOR_NYM_WITH_ROLE, within=2)
    new_role = ''
    addNym(be, do, trusteeCli, idr=uuidIdentifier, verkey=abbrevVerkey,
           role=new_role)
    do('send GET_NYM dest={dest}',
       mapper=parameters, expect=CURRENT_VERKEY_FOR_NYM, within=2)

def testSendGetNymFailsIfCryptonymIsPassedAsDest(
        be, do, poolNodesStarted, trusteeCli):

    parameters = {
        'dest': createCryptonym()
    }

    be(trusteeCli)
    do('send GET_NYM dest={dest}',
       mapper=parameters, expect=NYM_NOT_FOUND, within=2)

def testSendGetNymFailsIfDestIsPassedInHexFormat(
        be, do, poolNodesStarted, trusteeCli):

    # Sometimes hex representation can use only base58 compatible characters
    while True:
        uuidIdentifier, abbrevVerkey = createHalfKeyIdentifierAndAbbrevVerkey()
        hexEncodedUuidIdentifier = hexlify(
            friendlyToRaw(uuidIdentifier)).decode()
        if not check_str_is_base58_compatible(hexEncodedUuidIdentifier):
            break

    addNym(be, do, trusteeCli, idr=uuidIdentifier, verkey=abbrevVerkey)

    parameters = {
        'dest': hexEncodedUuidIdentifier
    }

    be(trusteeCli)
    do('send GET_NYM dest={dest}',
       mapper=parameters,
       expect="should not contain the following chars",
       within=2)

def testSendGetNymFailsIfDestIsInvalid(
        be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier = createUuidIdentifier()
    invalidIdentifier = uuidIdentifier[:-4]

    parameters = {
        'dest': invalidIdentifier
    }

    be(trusteeCli)
    do('send GET_NYM dest={dest}',
       mapper=parameters, expect="b58 decoded value length", within=2)

def testSendGetNymHasInvalidSyntaxIfDestIsEmpty(
        be, do, poolNodesStarted, trusteeCli):

    parameters = {
        'dest': ''
    }

    be(trusteeCli)
    do('send GET_NYM dest={dest}',
       mapper=parameters, expect=INVALID_SYNTAX, within=2)

def testSendGetNymHasInvalidSyntaxIfDestIsOmitted(
        be, do, poolNodesStarted, trusteeCli):

    be(trusteeCli)
    do('send GET_NYM', expect=INVALID_SYNTAX, within=2)

def testSendGetNymHasInvalidSyntaxIfUnknownParameterIsPassed(
        be, do, poolNodesStarted, trusteeCli):

    uuidIdentifier, abbrevVerkey = createHalfKeyIdentifierAndAbbrevVerkey()
    addNym(be, do, trusteeCli, idr=uuidIdentifier, verkey=abbrevVerkey)

    parameters = {
        'dest': uuidIdentifier,
        'extra': 42
    }

    be(trusteeCli)
    do('send GET_NYM dest={dest} extra={extra}',
       mapper=parameters, expect=INVALID_SYNTAX, within=2)


text:
begin;
--Hungarian GIFI / Magyar gyûjtõkódok -- amelyek csak példaként szolgálnak
INSERT INTO gifi (accno,description) VALUES ('114','Tárgyi eszközök');
INSERT INTO gifi (accno,description) VALUES ('119','Tárgyi eszközök ÉCS');
INSERT INTO gifi (accno,description) VALUES ('261','Áruk');
INSERT INTO gifi (accno,description) VALUES ('311','Vevõk');
INSERT INTO gifi (accno,description) VALUES ('381','Pénztár');
INSERT INTO gifi (accno,description) VALUES ('384','Bank');
INSERT INTO gifi (accno,description) VALUES ('454','Szállítók');
INSERT INTO gifi (accno,description) VALUES ('466','Visszaigényelhetõ ÁFA');
INSERT INTO gifi (accno,description) VALUES ('467','Fizetendõ ÁFA');
INSERT INTO gifi (accno,description) VALUES ('520','Bérleti díj');
INSERT INTO gifi (accno,description) VALUES ('521','Telefon');
INSERT INTO gifi (accno,description) VALUES ('599','Egyéb költségek');
INSERT INTO gifi (accno,description) VALUES ('814','ELÁBÉ');
INSERT INTO gifi (accno,description) VALUES ('870','Árfolyamveszteség');
INSERT INTO gifi (accno,description) VALUES ('911','Árbevétel');
INSERT INTO gifi (accno,description) VALUES ('970','Árfolyamnyereség');
INSERT INTO gifi (accno,description) VALUES ('1','BEFEKTETETT ESZKÖZÖK');
INSERT INTO gifi (accno,description) VALUES ('2','KÉSZLETEK');
INSERT INTO gifi (accno,description) VALUES ('3','KÖVETELÉSEK');
INSERT INTO gifi (accno,description) VALUES ('4','KÖTELEZETTSÉGEK');
INSERT INTO gifi (accno,description) VALUES ('5','KÖLTSÉGEK');
INSERT INTO gifi (accno,description) VALUES ('8','RÁFORDÍTÁSOK');
INSERT INTO gifi (accno,description) VALUES ('9','BEVÉTELEK');
--
commit;


text:
{
  if (node.type === "Literal" && typeof node.value === "string") {
    return node.value;
  } else if (node.type === "BinaryExpression" && node.operator === "+") {
    var l = getLiteralString(node.left);
    var r = getLiteralString(node.right);

    if (l !== null && r !== null) {
      return l + r;
    }
  }

  return null;
}


text:
/* @import "https://cdn.bootcss.com/material-design-lite/1.3.0/material.min.css"; */
/* @import 'https://unpkg.com/material-design-lite@1.3.0/dist/material.cyan-teal.min.css'; */
@import 'https://cdn.bootcdn.net/ajax/libs/material-design-lite/1.3.0/material.blue_grey-teal.min.css';
/* @import "https://cdn.bootcss.com/Swiper/3.4.2/css/swiper.min.css"; */
/* @import 'https://unpkg.com/mdi@2.2.43/css/materialdesignicons.min.css'; */
@import 'https://ga.system.jspm.io/npm:mdi@2.2.43/css/materialdesignicons.min.css';
@import 'https://cdn.jsdelivr.net/npm/open-sans-all@0.1.3/css/open-sans.min.css';

@import "/src/css/index.dark.css" only screen and (prefers-color-scheme: dark);

html, body{
  /* background:url(/img/cdbg_1010.png) repeat center;background-size: 15px; */
  background: whitesmoke;
  margin: 0;padding: 0;
  -webkit-overflow-scrolling: touch;
  width: 100%;
  height: 100%;
}
html{
  font-family: sans-serif;
}
html *{
  font-family: 'Open Sans', serif, fantasy, sans-serif;
}
::-webkit-scrollbar{
  width: 0;
}

[cloak] *{
  display: none;
}
[cloak]::before,
[cloak]::after{
  display: block;
  content: '';
  width: 5vmin;
  height: 5vmin;
  margin: -3vmin auto auto -3vmin;
  border-radius: 999pt;
  border: .2em solid transparent;
  border-top-color: lightseagreen;
  position: absolute;
  top: 50%;
  left: 50%;
  animation: rotating 2s ease-in-out infinite;
}
[cloak]::after{
  border-color: transparent lightseagreen transparent transparent;
  animation-delay: .2s;
}
@keyframes rotating{
  to{
    transform: rotate(720deg);
  }
}


text:
package com.boztalay.trafficsim.street;

import com.boztalay.trafficsim.TrafficSim;
import com.boztalay.trafficsim.math.Point;
import com.boztalay.trafficsim.math.Vector;

import java.util.ArrayList;

public class StreetMap {
    private ArrayList<Street> streets;
    private ArrayList<Intersection> intersections;

    private Point mapSize;

    public StreetMap(int mapWidth, int mapHeight) {
        streets = new ArrayList<Street>();
        intersections = new ArrayList<Intersection>();

        mapSize = new Point(mapWidth, mapHeight);

        generateStreets();
        detectIntersections();
    }

    private void generateStreets() {
        //Outline
        float halfRoadWidth = Street.ROAD_WIDTH / 2.0f;

        streets.add(new Street(new Point(halfRoadWidth,                         halfRoadWidth), new Vector(TrafficSim.radians(  0.0f), mapSize.x - Street.ROAD_WIDTH), 2.0f));
        streets.add(new Street(new Point(mapSize.x - halfRoadWidth,             halfRoadWidth), new Vector(TrafficSim.radians( 90.0f), mapSize.y - Street.ROAD_WIDTH), 2.0f));
        streets.add(new Street(new Point(mapSize.x - halfRoadWidth, mapSize.y - halfRoadWidth), new Vector(TrafficSim.radians(180.0f), mapSize.x - Street.ROAD_WIDTH), 2.0f));
        streets.add(new Street(new Point(halfRoadWidth,             mapSize.y - halfRoadWidth), new Vector(TrafficSim.radians(270.0f), mapSize.y - Street.ROAD_WIDTH), 2.0f));

        //Crossroads
        streets.add(new Street(new Point(halfRoadWidth, mapSize.y / 2.0f), new Vector(TrafficSim.radians( 0.0f), mapSize.x - Street.ROAD_WIDTH), 2.0f));
        streets.add(new Street(new Point(mapSize.x / 2.0f, halfRoadWidth), new Vector(TrafficSim.radians(90.0f), mapSize.y - Street.ROAD_WIDTH), 2.0f));
    }

    private void detectIntersections() {
        for(int i = 0; i < streets.size(); i++) {
            for(int j = i + 1; j < streets.size(); j++) {
                findIntersectionsOfStreets(streets.get(i), streets.get(j));
            }
        }
    }

    private void findIntersectionsOfStreets(Street street1, Street street2) {
        Vector vector1 = street1.getStreetVector();
        Vector vector2 = street2.getStreetVector();

        if(areVectorsParallel(vector1, vector2)) {
            return;
        }

        //Do all the heavy lifting up front
        float sinTheta2 = TrafficSim.sin(vector2.angle);
        if(sinTheta2 == 0.0f) {
            //This is to prevent a divide by zero issue
            Vector tempVector = vector1;
            vector1 = vector2;
            vector2 = tempVector;

            Street tempStreet = street1;
            street1 = street2;
            street2 = tempStreet;

            sinTheta2 = TrafficSim.sin(vector2.angle);
        }

        float sinTheta1 = TrafficSim.sin(vector1.angle);
        float cosTheta2 = TrafficSim.cos(vector2.angle);
        float sinTheta2MinusTheta1 = TrafficSim.sin(vector2.angle - vector1.angle);

        //I derived this big mess in my notebook...
        float pointOfIntersectionOnStreet1 = ((sinTheta2 * (street2.getOrigin().x - street1.getOrigin().x)) + (cosTheta2 * (street1.getOrigin().y - street2.getOrigin().y))) /
                                                                                sinTheta2MinusTheta1;

        if(pointOfIntersectionOnStreet1 < 0.0f || pointOfIntersectionOnStreet1 > vector1.magnitude) {
            //This means that the vectors can't intersect because they don't actually touch.
            //The point of intersection isn't actually on the vector.
            return;
        }

        //If the point of intersection on vector 1 exists, then let's find where vector 1 intersects vector 2.
        //I also derived this in my notebook
        float pointOfIntersectionOnStreet2 = (street1.getOrigin().y - street2.getOrigin().y + (pointOfIntersectionOnStreet1 * sinTheta1)) /
                                                                                sinTheta2;

        if(pointOfIntersectionOnStreet2 < 0.0f || (pointOfIntersectionOnStreet2 > vector2.magnitude)) {
            //Same thing happened for vector 2. They can't touch because the point of intersection on
            //this vector isn't actually on the vector. The vector would have to extend in some direction
            //to touch the first vector
            return;
        }

        //If we make it here, it means that the two streets do intersect, and we know where along those streets
        //the intersection happened. Now we have to make the Intersection and link everything up

        Intersection intersection = new Intersection();
        intersection.addStreet(street1, pointOfIntersectionOnStreet1);
        intersection.addStreet(street2, pointOfIntersectionOnStreet2);

        intersections.add(intersection);

        street1.addIntersection(intersection);
        street2.addIntersection(intersection);
    }

    private boolean areVectorsParallel(Vector vector1, Vector vector2) {
        return (vector1.angle == vector2.angle);
    }

    public ArrayList<Street> getStreets() {
        return streets;
    }

    public void draw() {
        TrafficSim.app.pushMatrix();

        for(Street street : streets) {
            street.draw();
        }

        for(Intersection intersection : intersections) {
            intersection.draw();
        }

        TrafficSim.app.popMatrix();
    }
}


text:
<?php

$dictionary['Lead']['fields']['SecurityGroups'] = array (
  	'name' => 'SecurityGroups',
    'type' => 'link',
	'relationship' => 'securitygroups_leads',
	'module'=>'SecurityGroups',
	'bean_name'=>'SecurityGroup',
    'source'=>'non-db',
	'vname'=>'LBL_SECURITYGROUPS',
);

?>


text:
package org.opendatakit.database.queries;

import android.os.Parcel;
import android.os.Parcelable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import org.opendatakit.utilities.ODKFileUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * This holds the list of objects that are bind arguments to the SQLite database.
 * The objects are primitive objects (String, Integer, Long, Float, Double, Boolean)
 */
@SuppressWarnings("serial")
public class BindArgs implements Parcelable, Serializable {

  /**
   * Used in OdkDatabaseServiceImpl, probably more
   */
  @SuppressWarnings("WeakerAccess")
  public final Object[] bindArgs;

  public BindArgs() {
    bindArgs = null;
  }

  public BindArgs(Object[] args) {
    bindArgs = args;
    if ( args != null ) {
      for (Object o : args) {
        if (o == null) continue;
        if (o instanceof String) continue;
        if (o instanceof Integer) continue;
        if (o instanceof Boolean) continue;
        if (o instanceof Double) continue;
        if (o instanceof Float) continue;
        if (o instanceof Long) continue;
        throw new IllegalArgumentException("bind args must be a primitive type");
      }
    }
  }

  public BindArgs(String fromJSON) {
    if ( fromJSON == null || fromJSON.isEmpty()) {
      bindArgs = new Object[0];
      return;
    }

    TypeReference<ArrayList<Object>> type = new TypeReference<ArrayList<Object>>() {};
    try {
      ArrayList<Object> values = ODKFileUtils.mapper.readValue(fromJSON, type);
      if ( values == null ) {
        bindArgs = new Object[0];
      } else {
        bindArgs = values.toArray(new Object[values.size()]);
      }
    } catch (IOException ignored) {
      // not expected
      throw new IllegalStateException("Unable to deserialize bindArgs");
    }
  }

  /**
   * Used in IntentUtil
   * @return the arguments, encoded to json
   */
  @SuppressWarnings("unused")
  public String asJSON() {
    try {
      return ODKFileUtils.mapper.writeValueAsString(bindArgs);
    } catch (JsonProcessingException ignored) {
      // not expected
      throw new IllegalStateException("Unable to serialize bindArgs");
    }
  }

  private static void marshallObject(Parcel out, Object toMarshall) {
    if (toMarshall == null) {
      out.writeInt(0);
    } else if ( toMarshall instanceof String ) {
      out.writeInt(1);
      out.writeString((String) toMarshall);
    } else if ( toMarshall instanceof Integer ) {
      out.writeInt(2);
      out.writeInt((Integer) toMarshall);
    } else if ( toMarshall instanceof Boolean ) {
      if ( (Boolean) toMarshall ) {
        out.writeInt(3);
      } else {
        out.writeInt(4);
      }
    } else if ( toMarshall instanceof Double ) {
      out.writeInt(5);
      out.writeDouble((Double) toMarshall);
    } else if ( toMarshall instanceof Float ) {
      out.writeInt(6);
      out.writeFloat((Float) toMarshall);
    } else if ( toMarshall instanceof Long ) {
      out.writeInt(7);
      out.writeLong((Long) toMarshall);
    } else {
      throw new IllegalStateException("should have been prevented in constructor");
    }
  }

  private static Object unmarshallObject(Parcel in) {
    int dataType = in.readInt();
    switch(dataType) {
    case 0:
      return null;
    case 1:
      return in.readString();
    case 2:
      return in.readInt();
    case 3:
      return Boolean.TRUE;
    case 4:
      return Boolean.FALSE;
    case 5:
      return in.readDouble();
    case 6:
      return in.readFloat();
    case 7:
      return in.readLong();
    default:
      throw new IllegalStateException("should have been prevented in constructor");
    }
  }

  protected BindArgs(Parcel in) {
    int dataCount = in.readInt();
    if (dataCount < 0) {
      bindArgs = null;
    } else {
      Object[] result = new Object[dataCount];
      for ( int i = 0 ; i < dataCount ; ++i ) {
        result[i] = unmarshallObject(in);
      }
      bindArgs = result;
    }
  }

  @Override public void writeToParcel(Parcel dest, int flags) {
    if (bindArgs == null) {
      dest.writeInt(-1);
    } else {
      dest.writeInt(bindArgs.length);
      for (Object bindArg : bindArgs) {
        marshallObject(dest, bindArg);
      }
    }
  }

  @Override public int describeContents() {
    return 0;
  }

  public static final Creator<BindArgs> CREATOR = new Creator<BindArgs>() {
    @Override public BindArgs createFromParcel(Parcel in) {
      return new BindArgs(in);
    }

    @Override public BindArgs[] newArray(int size) {
      return new BindArgs[size];
    }
  };
}


text:
/**
 *
 */
package com.sjsu.cmpe273Server.dto;

/**
 * @author bhargav
 *
 */
public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }

}


text:
$(document).ready(function() {
    if (!Raphael.svg) {
        window.location = './notsupported.html';
    }

    // suppress select events
    $(window).bind('selectstart', function(event) {
        event.preventDefault();
    });

    // initialize visualization
    Panel.init();
    Controller.init();
});


text:
cask 'the-unarchiver' do
  version '3.11.2,113:1504002485'
  sha256 'fd7c412af8da923429878d33343b05c9fe8dd8906488875050212f4424a048aa'

  # devmate.com/cx.c3.theunarchiver was verified as official when first introduced to the cask
  url "https://dl.devmate.com/cx.c3.theunarchiver/#{version.after_comma.before_colon}/#{version.after_colon}/TheUnarchiver-#{version.after_comma.before_colon}.zip"
  appcast 'https://updates.devmate.com/cx.c3.theunarchiver.xml',
          checkpoint: 'b76f0a4ff7cc381181e7c46d5fea6d0b62dc07d10aa1751b882a0b6674fa82aa'
  name 'The Unarchiver'
  homepage 'https://theunarchiver.com/'

  auto_updates true
  depends_on macos: '>= :lion'

  app 'The Unarchiver.app'

  zap delete: [
                '~/Library/Caches/cx.c3.theunarchiver',
                '~/Library/Cookies/cx.c3.theunarchiver.binarycookies',
                '~/Library/Saved Application State/cx.c3.theunarchiver.savedState',
              ],
      trash:  '~/Library/Preferences/cx.c3.theunarchiver.plist'
end


text:
class AddPathLocksUserIdForeignKey < ActiveRecord::Migration[6.0]
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false
  CONSTRAINT_NAME = 'fk_path_locks_user_id'

  disable_ddl_transaction!

  def up
    with_lock_retries do
      add_foreign_key(:path_locks, :users, on_delete: :cascade, validate: false, name: CONSTRAINT_NAME)
      remove_foreign_key_if_exists(:path_locks, column: :user_id, on_delete: nil)
    end
  end

  def down
    fk_exists = foreign_key_exists?(:path_locks, :users, column: :user_id, on_delete: nil)

    unless fk_exists
      with_lock_retries do
        add_foreign_key(:path_locks, :users, column: :user_id, validate: false)
      end
    end

    remove_foreign_key_if_exists(:path_locks, column: :user_id, name: CONSTRAINT_NAME)

    fk_name = concurrent_foreign_key_name(:path_locks, :user_id, prefix: 'fk_rails_')
    validate_foreign_key(:path_locks, :user_id, name: fk_name)
  end
end


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

namespace Bijectiv.KernelFactory
{
    using System;
    using System.Linq;
    using System.Linq.Expressions;

    using Bijectiv.Configuration;
    using Bijectiv.Utilities;

    using JetBrains.Annotations;

    /// <summary>
    /// A task that creates all triggers with a given cause.
    /// </summary>
    public class CreateTriggersTask : IInjectionTask
    {
        /// <summary>
        /// The reason that the trigger is invoked.
        /// </summary>
        private readonly TriggeredBy triggeredBy;

        /// <summary>
        /// Initialises a new instance of the <see cref="CreateTriggersTask"/> class.
        /// </summary>
        /// <param name="triggeredBy">
        /// The reason that the trigger is invoked.
        /// </param>
        public CreateTriggersTask(TriggeredBy triggeredBy)
        {
            this.triggeredBy = triggeredBy;
        }

        /// <summary>
        /// Gets the reason that the trigger is invoked.
        /// </summary>
        public TriggeredBy TriggeredBy
        {
            get { return this.triggeredBy; }
        }

        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <param name="scaffold">
        /// The scaffold on which the <see cref="IInjection"/> is being built.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when any parameter is null.
        /// </exception>
        public void Execute(InjectionScaffold scaffold)
        {
            if (scaffold == null)
            {
                throw new ArgumentNullException("scaffold");
            }

            scaffold
                .UnprocessedFragments
                .OfType<InjectionTriggerFragment>()
                .Where(candidate => candidate.TriggeredBy == this.TriggeredBy)
                .ForEach(fragment => this.ProcessFragment(fragment, scaffold));
        }

        /// <summary>
        /// Processes a <see cref="InjectionTriggerFragment"/> fragment.
        /// </summary>
        /// <param name="fragment">
        /// The fragment.
        /// </param>
        /// <param name="scaffold">
        /// The scaffold on which the <see cref="IInjection"/> is being built.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when any parameter is null.
        /// </exception>
        protected internal virtual void ProcessFragment(
            [NotNull] InjectionTriggerFragment fragment,
            [NotNull] InjectionScaffold scaffold)
        {
            if (fragment == null)
            {
                throw new ArgumentNullException("fragment");
            }

            if (scaffold == null)
            {
                throw new ArgumentNullException("scaffold");
            }

            var parameter = Expression.Convert(
                scaffold.Variables.First(candidate => candidate.Name == "injectionParameters"),
                fragment.ParameterType);

            var trigger = fragment.Trigger;
            var expression = trigger.Target == null
                ? Expression.Call(trigger.Method, parameter)
                : Expression.Call(Expression.Constant(trigger.Target), trigger.Method, new Expression[] { parameter });

            scaffold.Expressions.Add(expression);
            scaffold.ProcessedFragments.Add(fragment);
        }
    }
}


text:
package org.coursera.symptomserver.handlers;

import org.coursera.symptomserver.errors.ErrorInfo;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.coursera.symptomserver.errors.ValidationError;
import org.coursera.symptomserver.exceptions.AccessException;
import org.coursera.symptomserver.exceptions.GeneralException;
import org.coursera.symptomserver.exceptions.NotFoundException;
import org.coursera.symptomserver.utils.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Global Exception handler controller. All Exceptions that occurs in the server are managed here.
 */
@ControllerAdvice
public class GlobalControllerExceptionHandler {

    private static final Logger logger = Logger.getLogger(GlobalControllerExceptionHandler.class.getName());

    @Autowired
    private MessageSource messages;

    /**
     * This method receives errors from JPA layer that corresponds to ConstraintViolationException class
     *
     * @param req a HttpServletRequest object. Useful to Know requestUri that calls Rest method
     * @param cve a ConstraintViolationException object. Contains constraint object information
     * @return a ValidationError object to client with the error information and HttpStatus.INTERNAL_SERVER_ERROR status code
     * @see org.coursera.symptomserver.errors.ValidationError
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ValidationError handleConstraintValidationException(HttpServletRequest req, ConstraintViolationException cve) {
        try {
            ValidationError ve = ValidationUtils.processConstraintsViolations(cve, messages, LocaleContextHolder.getLocale());
            ve.setURI(req.getRequestURI());
            return ve;
        } catch (Exception e) {
            logger.log(Level.ALL, "handleConstraintValidationException", e);
            return null;
        } finally {
            logger.log(Level.ALL, "handleConstraintValidationException", cve);
        }
    }

    /**
     * This method receives errors that corresponds to MethodArgumentNotValidException class. This exception class
     * Occurs when methods' arguments are not valid
     *
     * @param req a HttpServletRequest object. Useful to Know requestUri that calls Rest method
     * @param marve a MethodArgumentNotValidException object with error information
     * @return a ValidationError object to client with the error information and HttpStatus.BAD_REQUEST status code
     * @see org.coursera.symptomserver.errors.ValidationError
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ValidationError processValidationError(HttpServletRequest req, MethodArgumentNotValidException marve) {
        try {
            BindingResult result = marve.getBindingResult();
            List<FieldError> fieldErrors = result.getFieldErrors();
            ValidationError ve = ValidationUtils.processFieldErrors(fieldErrors, messages, LocaleContextHolder.getLocale());
            ve.setURI(req.getRequestURI());
            return ve;
        } catch (Exception e) {
            logger.log(Level.ALL, "processValidationError", e);
            return null;
        } finally {
            logger.log(Level.ALL, "processValidationError", marve);
        }
    }

    /**
     * This method receives errors that corresponds to HttpMediaTypeNotAcceptableException class.
     *
     * @param req a HttpServletRequest object. Useful to Know requestUri that calls Rest method
     * @param ex a HttpMediaTypeNotAcceptableException object. Corresponds to original Exception
     * @return a ErrorInfo object to client with the error information and HttpStatus.NOT_ACCEPTABLE status code
     * @see org.coursera.symptomserver.errors.ErrorInfo
     */
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    @ResponseBody
    public ErrorInfo handleMediaExcepton(HttpServletRequest req, HttpMediaTypeNotAcceptableException ex) {
    	ex.printStackTrace();
        logger.log(Level.ALL, "handleMediaExcepton", ex);
        String mensaje = messages.getMessage("CONTENTTYPE_ERROR", null, LocaleContextHolder.getLocale());
        return new ErrorInfo(req.getRequestURI(), ex, mensaje);
    }

    /**
     * This method receives errors that corresponds to HttpMediaTypeNotSupportedException class.
     *
     * @param req a HttpServletRequest object. Useful to Know requestUri that calls Rest method
     * @param ex a HttpMediaTypeNotSupportedException object. Corresponds to original Exception
     * @return a ErrorInfo object to client with the error information and HttpStatus.BAD_REQUEST status code
     * @see org.coursera.symptomserver.errors.ErrorInfo
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    public ErrorInfo handleMediaNotSuported(HttpServletRequest req, HttpMediaTypeNotSupportedException ex) {
    	ex.printStackTrace();
        logger.log(Level.ALL, "handleMediaNotSuported", ex);
        String mensaje = messages.getMessage("CONTENTTYPE_ERROR", null, LocaleContextHolder.getLocale());
        return new ErrorInfo(req.getRequestURI(), ex, mensaje);
    }

    /**
     * This method receives errors that corresponds to AccessException class.
     *
     * @param req a HttpServletRequest object. Useful to Know requestUri that calls Rest method
     * @param ex a AccessException object. Corresponds to original Exception
     * @return a ErrorInfo object to client with the error information and HttpStatus.UNAUTHORIZED status code
     * @see org.coursera.symptomserver.errors.ErrorInfo
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AccessException.class)
    @ResponseBody
    public ErrorInfo handleNotAuthorized(HttpServletRequest req, AccessException ex) {
    	ex.printStackTrace();
        logger.log(Level.DEBUG, "handleNotAuthorized", ex);
        String mensaje = messages.getMessage(ex.getErrorCode(), null, LocaleContextHolder.getLocale());
        return new ErrorInfo(req.getRequestURI(), ex, mensaje);
    }

    /**
     * This method receives errors that corresponds to NotFoundException class.
     *
     * @param req a HttpServletRequest object. Useful to Know requestUri that calls Rest method
     * @param ex a NotFoundException object. Corresponds to original Exception
     * @return a ErrorInfo object to client with the error information and HttpStatus.UNAUTHORIZED status code
     * @see org.coursera.symptomserver.errors.ErrorInfo
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NotFoundException.class)
    @ResponseBody
    public ErrorInfo handleNotFount(HttpServletRequest req, NotFoundException ex) {
    	ex.printStackTrace();
        logger.log(Level.DEBUG, "handleNotFount", ex);
        String mensaje = messages.getMessage(ex.getErrorCode(), null, LocaleContextHolder.getLocale());
        return new ErrorInfo(req.getRequestURI(), ex, mensaje);
    }

    /**
     * This method receives errors that corresponds to GeneralException class.
     *
     * @param req a HttpServletRequest object. Useful to Know requestUri that calls Rest method
     * @param ex a GeneralException object. Corresponds to original Exception
     * @return a ErrorInfo object to client with the error information and HttpStatus.BAD_REQUEST status code
     * @see org.coursera.symptomserver.errors.ErrorInfo
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(GeneralException.class)
    @ResponseBody
    public ErrorInfo handleGeneralException(HttpServletRequest req, GeneralException ex) {
    	ex.printStackTrace();
        logger.log(Level.DEBUG, "handleGeneralException", ex);
        String mensaje = messages.getMessage(ex.getErrorCode(), null, LocaleContextHolder.getLocale());
        return new ErrorInfo(req.getRequestURI(), ex, mensaje);
    }

    /**
     * This method receives errors that corresponds to Exception class.
     *
     * @param req a HttpServletRequest object. Useful to Know requestUri that calls Rest method
     * @param ex a Exception object. Corresponds to original Exception
     * @return a ErrorInfo object to client with the error information and HttpStatus.INTERNAL_SERVER_ERROR status code
     * @see org.coursera.symptomserver.errors.ErrorInfo
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ErrorInfo handleInternalError(HttpServletRequest req, Exception ex) {
    	ex.printStackTrace();
        logger.log(Level.DEBUG, "handleInternalError", ex);
        String mensaje = messages.getMessage("GENERAL_ERROR", null, LocaleContextHolder.getLocale());
        return new ErrorInfo(req.getRequestURI(), ex, mensaje);
    }

}


text:
class PageCache
  def self.logger
    RAILS_DEFAULT_LOGGER
  end

  def logger
    RAILS_DEFAULT_LOGGER
  end

  def self.public_path
    ActionController::Base.page_cache_directory
  end

  # Delete all file save in path_cache by page_cache system
  def self.sweep_all
    logger.debug "PageCache - sweep_all called by #{caller[1].inspect}"
    CacheInformation.all.each{|c| c.destroy}
  end

  def self.sweep_theme_cache
    logger.debug "PageCache - sweep_theme_cache called by #{caller[1].inspect}"
    self.zap_pages(%{images/theme stylesheets/theme javascripts/theme})
  end

  def self.zap_pages(paths)
    logger.debug "PageCache - About to zap: #{paths.inspect}"
    srcs = paths.inject([]) { |o,v|
      o + Dir.glob(public_path + "/#{v}")
    }
    return true if srcs.empty?
    logger.debug "PageCache - About to delete: #{srcs.inspect}"
    trash = RAILS_ROOT + "/tmp/typodel.#{UUID.random_create}"
    FileUtils.makedirs(trash)
    FileUtils.mv(srcs, trash, :force => true)
    FileUtils.rm_rf(trash)
  end

  # DEPRECATED
  #
  # It's now deprecated. It's use only in migration
  # (20090311160502_create_cache_informations.rb)
  # Doesn't use anyway. The cache is now manage by CacheInformation
  # Method to swepp_all cache is allways self.sweep_all
  #
  # DEPRECATED
  def self.old_sweep_all
    logger.debug "PageCache - sweep_all called by #{caller[1].inspect}"
    unless Blog.default.nil?
      self.zap_pages(%w{index.* articles.* pages page
                     pages.* feedback feedback.*
                     comments comments.*
                     category categories.* xml
                     sitemap.xml
                     *.rss *.atom
                     tag tags.* category archives.*})

      self.zap_pages((1990..2020))
      self.zap_pages([*1990..2020].collect { |y| "#{y}.*" })
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveSupport::Rescuable</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.1.6

            Module
            ActiveSupport::Rescuable

/Users/Sean/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/activesupport-4.1.6/lib/active_support/rescuable.rb

Rescuable module adds support for easier
exception handling.

Namespace

          MODULE
          ActiveSupport::Rescuable::ClassMethods

Methods

H

                handler_for_rescue

R

                rescue_with_handler

Instance Public methods

              handler_for_rescue(exception)

            Link

                Source:
                show

# File ../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/activesupport-4.1.6/lib/active_support/rescuable.rb, line 85
def handler_for_rescue(exception)
  # We go from right to left because pairs are pushed onto rescue_handlers
  # as rescue_from declarations are found.
  _, rescuer = self.class.rescue_handlers.reverse.detect do |klass_name, handler|
    # The purpose of allowing strings in rescue_from is to support the
    # declaration of handler associations for exception classes whose
    # definition is yet unknown.
    #
    # Since this loop needs the constants it would be inconsistent to
    # assume they should exist at this point. An early raised exception
    # could trigger some other handler and the array could include
    # precisely a string whose corresponding constant has not yet been
    # seen. This is why we are tolerant to unknown constants.
    #
    # Note that this tolerance only matters if the exception was given as
    # a string, otherwise a NameError will be raised by the interpreter
    # itself when rescue_from CONSTANT is executed.
    klass = self.class.const_get(klass_name) rescue nil
    klass ||= klass_name.constantize rescue nil
    exception.is_a?(klass) if klass
  end

  case rescuer
  when Symbol
    method(rescuer)
  when Proc
    if rescuer.arity == 0
      Proc.new { instance_exec(&rescuer) }
    else
      Proc.new { |_exception| instance_exec(_exception, &rescuer) }
    end
  end
end

              rescue_with_handler(exception)

            Link

Tries to rescue the exception by looking up and calling a registered
handler.

                Source:
                show

# File ../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/activesupport-4.1.6/lib/active_support/rescuable.rb, line 78
def rescue_with_handler(exception)
  if handler = handler_for_rescue(exception)
    handler.arity != 0 ? handler.call(exception) : handler.call
    true # don't rely on the return value of the handler
  end
end


text:
package im.actor.core.api;
/*
 *  Generated by the Actor API Scheme generator.  DO NOT EDIT!
 */

import im.actor.runtime.bser.*;
import im.actor.runtime.collections.*;
import static im.actor.runtime.bser.Utils.*;
import im.actor.core.network.parser.*;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

public class ApiMessageSearchItem extends BserObject {

    private ApiMessageSearchResult result;

    public ApiMessageSearchItem(@NotNull ApiMessageSearchResult result) {
        this.result = result;
    }

    public ApiMessageSearchItem() {

    }

    @NotNull
    public ApiMessageSearchResult getResult() {
        return this.result;
    }

    @Override
    public void parse(BserValues values) throws IOException {
        this.result = values.getObj(1, new ApiMessageSearchResult());
    }

    @Override
    public void serialize(BserWriter writer) throws IOException {
        if (this.result == null) {
            throw new IOException();
        }
        writer.writeObject(1, this.result);
    }

    @Override
    public String toString() {
        String res = "struct MessageSearchItem{";
        res += "}";
        return res;
    }

}


text:
package com.ebayopensource.webrex.resource.expression;

public enum ResourceExpressionType {
	RES, TYPE, NAMESPACE, NODE
}


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.DataProtectionBackup.Models
{
    /// <summary> Elements class for feature request. </summary>
    public partial class BackupSupportedFeature
    {
        /// <summary> Initializes a new instance of BackupSupportedFeature. </summary>
        internal BackupSupportedFeature()
        {
            ExposureControlledFeatures = new ChangeTrackingList<string>();
        }

        /// <summary> Initializes a new instance of BackupSupportedFeature. </summary>
        /// <param name="featureName"> support feature type. </param>
        /// <param name="supportStatus"> feature support status. </param>
        /// <param name="exposureControlledFeatures"> support feature type. </param>
        internal BackupSupportedFeature(string featureName, FeatureSupportStatus? supportStatus, IReadOnlyList<string> exposureControlledFeatures)
        {
            FeatureName = featureName;
            SupportStatus = supportStatus;
            ExposureControlledFeatures = exposureControlledFeatures;
        }

        /// <summary> support feature type. </summary>
        public string FeatureName { get; }
        /// <summary> feature support status. </summary>
        public FeatureSupportStatus? SupportStatus { get; }
        /// <summary> support feature type. </summary>
        public IReadOnlyList<string> ExposureControlledFeatures { get; }
    }
}


text:
package elegit;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.Dialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.controlsfx.control.CheckListView;

import java.util.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by connellyj on 7/7/16.
 *
 * Class that initializes a given pop up window
 */
public class PopUpWindows {

    static final Logger logger = LogManager.getLogger();

    /**
     * Informs the user that they are about to commit a conflicting file
     *
     * @return String user's response to the dialog
     */
    static String showCommittingConflictingFileAlert() {
        String resultType;

        Alert alert = new Alert(Alert.AlertType.WARNING);

        ButtonType resolveButton = new ButtonType("Open Editor");
        ButtonType addButton = new ButtonType("Add");
        ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
        ButtonType helpButton = new ButtonType("Help", ButtonBar.ButtonData.HELP);

        alert.getButtonTypes().setAll(helpButton, resolveButton, addButton, cancelButton);

        alert.setResizable(true);
        alert.getDialogPane().setPrefSize(450, 200);

        alert.setTitle("Warning: conflicting file");
        alert.setHeaderText("You're adding a conflicting file");
        alert.setContentText("You can open an editor to resolve the conflicts, or add the changes anyways. What do you want to do?");

        ImageView img = new ImageView(new javafx.scene.image.Image("/elegit/images/conflict.png"));
        img.setFitHeight(40);
        img.setFitWidth(80);
        img.setPreserveRatio(true);
        alert.setGraphic(img);

        Optional<ButtonType> result = alert.showAndWait();

        if (result.orElse(null) == resolveButton) {
            logger.info("Chose to resolve conflicts");
            resultType = "resolve";
        } else if (result.orElse(null) == addButton) {
            logger.info("Chose to add file");
            resultType = "add";
        } else if (result.orElse(null) == helpButton) {
            logger.info("Chose to get help");
            resultType = "help";
        } else {
            // User cancelled the dialog
            logger.info("Cancelled dialog");
            resultType = "cancel";
        }

        return resultType;
    }

    /**
     * Asks the user for permission to log anonymous usage data
     * @return true if the user selected yes to
     */
    public static boolean getLoggingPermissions() {
        Alert window = new Alert(Alert.AlertType.INFORMATION);

        ButtonType okButton = new ButtonType("Share");
        ButtonType buttonTypeCancel = new ButtonType("Don't Share", ButtonBar.ButtonData.CANCEL_CLOSE);

        window.getButtonTypes().setAll(okButton, buttonTypeCancel);
        window.setResizable(true);
        window.getDialogPane().setPrefSize(300, 200);
        window.setTitle("Usage Data");
        window.setHeaderText("Share anonymous usage data");
        window.setContentText("Click Share if you want to share anonymous usage data with us, " +
                "which helps us improve this tool. This can be changed at any time with the " +
                "preferences menu.");
        Optional<ButtonType> result = window.showAndWait();

        return result.orElse(null) == okButton;
    }

    /**
     * Shows a window with instructions on how to fix a conflict
     */
    static void showConflictingHelpAlert() {
        Platform.runLater(() -> {
            Alert window = new Alert(Alert.AlertType.INFORMATION);
            window.setResizable(true);
            window.getDialogPane().setPrefSize(550, 350);
            window.setTitle("How to fix conflicting files");
            window.setHeaderText("How to fix conflicting files");
            window.setContentText("1. First, open up the file that is marked as conflicting.\n" +
                                  "2. In the file, you should see something like this:\n\n" +
                                  "\t<<<<<< <branch_name>\n" +
                                  "\tChanges being made on the branch that is being merged into.\n" +
                                  "\tIn most cases, this is the branch that you currently have checked out (i.e. HEAD).\n" +
                                  "\t=======\n" +
                                  "\tChanges made on the branch that is being merged in.\n" +
                                  "\t>>>>>>> <branch name>\n\n" +
                                  "3. Delete the contents you don't want to keep after the merge\n" +
                                  "4. Remove the markers (<<<<<<<, =======, >>>>>>>) git put in the file\n" +
                                  "5. Done! You can now safely add and commit the file");
            window.showAndWait();
        });
    }

    /**
     * Shows a window with some info about git reset
     */
    static void showResetHelpAlert() {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.getDialogPane().setPrefSize(300, 300);
            alert.setTitle("Reset Help");
            alert.setHeaderText("What is reset?");
            ImageView img = new ImageView(new Image("/elegit/images/undo.png"));
            img.setFitHeight(60);
            img.setFitWidth(60);
            alert.setGraphic(img);
            alert.setContentText("Move the current branch tip backward to the selected commit, " +
                                 "reset the staging area to match, " +
                                 "but leave the working directory alone. " +
                                 "All changes made since the selected commit will reside in the working directory.");
            alert.showAndWait();
        });
    }

    /**
     * Show a window with info about git revert
     */
    static void showRevertHelpAlert() {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.getDialogPane().setPrefWidth(500);
            alert.setTitle("Revert Help");
            alert.setHeaderText("What is revert?");
            ImageView img = new ImageView(new Image("/elegit/images/undo.png"));
            img.setFitHeight(60);
            img.setFitWidth(60);
            alert.setGraphic(img);
            alert.setContentText("Basically, git revert takes your current files, " +
                    "and deletes any changes from the commit(s) you give it, making a new commit. " +
                    "See\n\nhttp://dmusican.github.io/Elegit/jekyll/update/2016/08/04/what-is-revert.html\n\n" +
                    "for more information");
            alert.showAndWait();
        });
    }

    /**
     * Shows a warning about checking out files from the index
     *
     * @return
     */
    public static boolean showCheckoutAlert() {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        ButtonType checkout = new ButtonType("Checkout");
        ButtonType cancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
        alert.getButtonTypes().setAll(checkout, cancel);

        alert.setTitle("Checkout Warning");
        alert.setContentText("Are you sure you want to checkout the selected files?\n" +
                "This will discard all changes that have not been added (staged).");
        Optional<ButtonType> result = alert.showAndWait();
        return result.isPresent() && result.get() == checkout;
    }

    /**
     * Informs the user that they are adding a previously conflicting file
     *
     * @return String result from user input
     */
    static String showAddingingConflictingThenModifiedFileAlert() {
        String resultType;

        Alert alert = new Alert(Alert.AlertType.INFORMATION);

        ButtonType commitButton = new ButtonType("Add");
        ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);

        alert.getButtonTypes().setAll(commitButton, buttonTypeCancel);

        alert.setResizable(true);
        alert.getDialogPane().setPrefSize(300, 200);

        alert.setTitle("Adding previously conflicting file");
        alert.setHeaderText("You are adding a conflicting file that was recently modified to the commit");
        alert.setContentText("If the file is what you want it to be, you should commit. Otherwise, modify the file accordingly.");

        Optional<ButtonType> result = alert.showAndWait();

        if (result.orElse(null) == commitButton) {
            logger.info("Chose to add");
            resultType = "add";
        } else {
            // User cancelled the dialog
            logger.info("Cancelled dialog");
            resultType = "cancel";
        }

        return resultType;
    }

    /**
     * Informs the user that they are tracking ignored files
     *
     * @param trackedIgnoredFiles collections of files being ignored
     */
    static void showTrackingIgnoredFilesWarning(Collection<String> trackedIgnoredFiles) {
        Platform.runLater(() -> {
            if (trackedIgnoredFiles.size() > 0) {
                String fileStrings = "";
                for (String s : trackedIgnoredFiles) {
                    fileStrings += "\n" + s;
                }
                Alert alert = new Alert(Alert.AlertType.WARNING, "The following files are being tracked by Git, " +
                                                                 "but also match an ignore pattern. If you want to ignore these files, remove them from Git.\n" + fileStrings);
                alert.showAndWait();
            }
        });
    }

    /**
     * Informs the user that there are conflicting files so they can't checkout a different branch
     *
     * @param conflictingPaths conflicting files
     */
    public static void showCheckoutConflictsAlert(List<String> conflictingPaths) {
        logger.warn("Checkout conflicts warning");
        String conflictList = "";
        for (String pathName : conflictingPaths) {
            conflictList += "\n" + pathName;
        }
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Conflicting files");
        alert.setHeaderText("Can't checkout that branch");
        alert.setContentText("You can't switch to that branch because of the following conflicting files between that branch and your current branch: "
                             + conflictList);

        alert.showAndWait();
    }

    /**
     * Informs the user that there were conflicts
     *
     * @param conflictingPaths conflicting files
     */
    public static void showMergeConflictsAlert(List<String> conflictingPaths) {
        logger.warn("Merge conflicts warning");
        String conflictList = "";
        for (String pathName : conflictingPaths) {
            conflictList += "\n" + pathName;
        }
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Conflicting files");
        alert.setHeaderText("Can't complete merge");
        alert.setContentText("There were conflicts in the following files: "
                             + conflictList);

        alert.showAndWait();
    }

    public static RemoteBranchHelper showTrackDifRemoteBranchDialog(ObservableList<RemoteBranchHelper> remoteBranches) {
        Dialog dialog = new Dialog();
        dialog.getDialogPane().setPrefSize(320, 100);
        dialog.setTitle("Track a remote branch locally");

        Text trackText = new Text("Track ");
        Text localText = new Text(" locally.");

        ComboBox<RemoteBranchHelper> dropdown = new ComboBox<>(remoteBranches);
        dropdown.setPromptText("select a remote branch...");

        HBox hBox = new HBox(trackText, dropdown, localText);
        hBox.setSpacing(10);
        hBox.setAlignment(Pos.CENTER);

        dialog.getDialogPane().setContent(hBox);

        ButtonType trackButton = new ButtonType("Track");
        ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);

        dialog.getDialogPane().getButtonTypes().addAll(trackButton, cancelButton);

        Optional<?> result = dialog.showAndWait();

        if (result.orElse(null) == trackButton) {
            dialog.close();
            return dropdown.getSelectionModel().getSelectedItem();
        }

        return null;
    }

    public static boolean showForceDeleteBranchAlert() {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("Deleting unmerged branch");
        alert.setHeaderText("The branch you are trying to delete is unmerged");
        alert.setContentText("The work done on this branch is not represented in any other local branch. " +
                             "If you delete it, you will lose any local work done on this branch. " +
                             "What would you like to do?");

        ButtonType deleteButton = new ButtonType("Force delete branch");
        ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);

        alert.getButtonTypes().clear();
        alert.getButtonTypes().addAll(deleteButton, cancelButton);

        Optional<?> result = alert.showAndWait();

        return result.orElse(null) == deleteButton;
    }

    static String pickRemoteToPushTo(Set<String> remotes) {
        ReentrantLock lock = new ReentrantLock();
        Condition finishedAlert = lock.newCondition();

        final String[] result = new String[1];

        Platform.runLater(() -> {
            try {
                lock.lock();

                Alert alert = new Alert(Alert.AlertType.NONE);
                alert.setTitle("Multiple remotes found");
                alert.setHeaderText("There are multiple remote repositories associated with this repository.\nPick one to push to.");

                ComboBox<String> remoteRepos = new ComboBox<>();
                remoteRepos.setPromptText("Choose a remote...");
                remoteRepos.setItems(FXCollections.observableArrayList(remotes));

                ButtonType okButton = new ButtonType("OK", ButtonBar.ButtonData.OK_DONE);
                ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);

                alert.getDialogPane().setContent(remoteRepos);
                alert.getButtonTypes().addAll(cancelButton, okButton);

                Optional<?> alertResult = alert.showAndWait();

                if (alertResult.isPresent()) {
                    if (alertResult.get() == okButton) {
                        result[0] = remoteRepos.getSelectionModel().getSelectedItem();
                    }
                }

                finishedAlert.signal();
            } finally {
                lock.unlock();
            }
        });

        lock.lock();

        try {
            finishedAlert.await();

            if (result[0] != null) {
                return result[0];
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        return "cancel";
    }

    public static String getCommitMessage() {
        Alert alert = new Alert(Alert.AlertType.NONE);
        alert.setTitle("Commit message");
        alert.setResizable(true);

        TextArea textArea = new TextArea();
        textArea.setPromptText("Commit Message...");
        textArea.setWrapText(true);
        textArea.setPrefSize(250, 150);
        textArea.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);

        HBox hBox = new HBox(textArea);
        hBox.setAlignment(Pos.CENTER);

        ButtonType okButton = new ButtonType("Commit", ButtonBar.ButtonData.OK_DONE);
        ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);

        alert.getDialogPane().setContent(hBox);
        alert.getButtonTypes().addAll(cancelButton, okButton);

        Optional<?> alertResult = alert.showAndWait();

        if (alertResult.isPresent()) {
            if (alertResult.get() == okButton && !textArea.getText().equals("")) {
                return textArea.getText();
            }
        }
        return "cancel";
    }

    static ArrayList<LocalBranchHelper> getUntrackedBranchesToPush(ArrayList<LocalBranchHelper> branches) {

        final ArrayList<LocalBranchHelper> result = new ArrayList<>(branches.size());

        Alert alert = new Alert(Alert.AlertType.NONE);
        alert.setTitle("Untracked local branches");
        alert.setHeaderText("The branches below are not tracked remotely.\n" +
                            "Select the branches you want to create an upstream remote branch for.");

        CheckListView<LocalBranchHelper> untrackedBranches = new CheckListView<>(FXCollections.observableArrayList(branches));

        ButtonType okButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
        ButtonType trackButton = new ButtonType("Track Branches", ButtonBar.ButtonData.APPLY);
        alert.getDialogPane().setContent(untrackedBranches);
        alert.getButtonTypes().addAll(trackButton, okButton);

        Optional<?> alertResult = alert.showAndWait();

        if (alertResult.isPresent()) {
            if (alertResult.get() == trackButton) {
                result.addAll(untrackedBranches.getCheckModel().getCheckedItems());
            }
        }

        if (result.size() > 0)
            return result;
        else
            return null;
    }

    static boolean trackCurrentBranchRemotely(String branchName) {

        final boolean[] result = new boolean[1];
        result[0] = false;

        Alert alert = new Alert(Alert.AlertType.NONE);
        alert.setTitle("push -u");

        Label branchLabel = new Label(branchName);
        HBox branchBox = new HBox(branchLabel);
        // The CSS style classes weren't working here
        branchBox.setStyle("    -fx-background-color: #1E90FF;\n" +
                           "    -fx-background-radius: 5;\n" +
                           "    -fx-padding: 0 3 0 3;");
        branchLabel.setStyle("    -fx-text-fill: #FFFFFF;\n" +
                             "    -fx-font-size: 14px;\n" +
                             "    -fx-font-weight: bold;\n" +
                             "    -fx-text-align: center;");

        Text txt1 = new Text(" is not currently tracked remotely.");
        Text txt2 = new Text("Would you like to create an upstream remote branch?");
        txt1.setFont(new Font(14));
        txt2.setFont(new Font(14));

        HBox hBox = new HBox(branchBox, txt1);

        VBox vBox = new VBox(hBox, txt2);
        vBox.setSpacing(10);
        vBox.setAlignment(Pos.CENTER);

        ButtonType okButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
        ButtonType trackButton = new ButtonType("Yes", ButtonBar.ButtonData.APPLY);

        alert.getDialogPane().setContent(vBox);
        alert.getButtonTypes().addAll(trackButton, okButton);

        Optional<?> alertResult = alert.showAndWait();

        if (alertResult.isPresent()) {
            if (alertResult.get() == trackButton) {
                result[0] = true;
            }
        }

        return result[0];
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Keywords" content="" />
<meta name="Description" content="" />

<link type="image/x-icon" rel="shortcut icon" href="" />
<link type="image/x-icon" rel="icon" href="" />

<title>CodeIgniter RestFull API with Doctrine</title>

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

			Loading the content...
            Loading depends on your connection speed!