text:
<?php
/**
 * Created by Oleg Galaburda on 02.12.15.
 */

namespace aw {

  use \PHPUnit_Framework_TestCase as TestCase;

  class CallableCollectionAddTest_CallableCollectionCallable extends CallableCollection{
    public function __invoke() {

    }
  }

  class CallableCollectionAddTest extends TestCase {
    public $collection;
    public function setUp(){
      $this->collection = new CallableCollection();
    }

    public function testCreate() {
      $this->assertTrue(is_array($this->collection->items));
      $this->assertEmpty($this->collection->items);
      $this->assertEquals(0, $this->collection->getCount());
    }

    public function testAddItem() {
      $handler1 = function(){
        return 1;
      };
      $handler2 = function(){
        return 2;
      };
      $this->assertEquals(0, $this->collection->getCount());
      $this->collection->addItem($handler1);
      $this->assertEquals(1, $this->collection->getCount());
      $this->assertSame($handler1, $this->collection->getItemAt(0));
      $this->collection->addItem($handler2);
      $this->assertEquals(2, $this->collection->getCount());
      $this->assertSame($handler2, $this->collection->getItemAt(1));
    }
  }

  class CallableCollectionGetTest extends TestCase {
    public $collection;
    public $handler1;
    public $handler2;
    public $handler3;

    public function setUp(){
      $this->collection = new CallableCollection();
      $this->handler1 = function(){
        return 1;
      };
      $this->collection->addItem($this->handler1);
      $this->handler2 = function(){
        return 2;
      };
      $this->collection->addItem($this->handler2);
      $this->handler3 = function(){
        return 3;
      };
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testAddSelf() {
      $collection = new CallableCollectionAddTest_CallableCollectionCallable();
      $collection->addItem($collection);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testAddSame() {
      $this->collection->addItem($this->handler1);
    }

    public function testGet() {
      $this->assertSame($this->handler1, $this->collection->getItemAt(0));
      $this->assertSame($this->handler2, $this->collection->getItemAt(1));
      $this->assertNull($this->collection->getItemAt(10));
    }

    public function testHas() {
      $this->assertTrue($this->collection->hasItem($this->handler1));
      $this->assertTrue($this->collection->hasItem($this->handler2));
      $this->assertFalse($this->collection->hasItem($this->handler3));
    }

    public function testFindItem() {
      $this->assertEquals(0, $this->collection->getItemIndex($this->handler1));
      $this->assertEquals(1, $this->collection->getItemIndex($this->handler2));
      $this->assertEquals(-1, $this->collection->getItemIndex($this->handler3));
    }

    public function testSet() {
      $this->collection->setItem(0, $this->handler3);
      $this->assertEquals(2, $this->collection->getCount());
      $this->assertSame($this->handler3, $this->collection->getItemAt(0));
      $this->assertNotSame($this->handler1, $this->collection->getItemAt(0));
      $this->assertSame($this->handler2, $this->collection->getItemAt(1));
      $this->collection->setItem(50, $this->handler3);
      $this->assertSame($this->handler3, $this->collection->getItemAt(50));
      $this->assertEquals(3, $this->collection->getCount());
    }

    public function testRemoveItems() {
      $this->collection->addItem($this->handler3);
      $this->assertEquals(3, $this->collection->getCount());
      $this->assertTrue($this->collection->removeItem($this->handler2));
      $this->assertEquals(2, $this->collection->getCount());
      $this->assertSame($this->handler1, $this->collection->getItemAt(0));
      $this->assertNull($this->collection->getItemAt(1));
      $this->assertSame($this->handler3, $this->collection->getItemAt(2));
      $this->assertTrue($this->collection->removeItem($this->handler1));
      $this->assertNull($this->collection->getItemAt(0));
      $this->assertNull($this->collection->getItemAt(1));
      $this->assertSame($this->handler3, $this->collection->getItemAt(2));
      $this->assertTrue($this->collection->removeItem($this->handler3));
      $this->assertEquals(0, $this->collection->getCount());
      $this->assertNull($this->collection->getItemAt(0));
      $this->assertNull($this->collection->getItemAt(1));
      $this->assertNull($this->collection->getItemAt(3));
      $this->assertFalse($this->collection->removeItem($this->handler3));
    }

    public function testPopIndices() {
      $this->collection->addItem($this->handler3);
      $this->assertEquals(3, $this->collection->getCount());
      $this->assertTrue($this->collection->removeItemAt(2));
      $this->assertEquals(2, $this->collection->getCount());
      $this->assertFalse($this->collection->removeItemAt(2));
      $this->assertSame($this->handler1, $this->collection->getItemAt(0));
      $this->assertSame($this->handler2, $this->collection->getItemAt(1));
      $this->assertTrue($this->collection->removeItemAt(1));
      $this->assertSame($this->handler1, $this->collection->getItemAt(0));
      $this->assertTrue($this->collection->removeItemAt(0));
      $this->assertSame(null, $this->collection->getItemAt(0));
      $this->assertFalse($this->collection->removeItemAt(0));
    }

    public function testClear() {
      $this->collection->removeAll();
      $this->assertEquals(0, $this->collection->getCount());
      $this->assertEquals(null, $this->collection->getItemAt(0));
    }

    public function testList() {
      $this->assertEquals([$this->handler1, $this->handler2], $this->collection->getItems());
      $this->collection->removeItemAt(0);
      $this->assertEquals([1 => $this->handler2], $this->collection->getItems());
    }
  }
}


text:
package org.eclipse.jetty.spdy.frames;

import org.eclipse.jetty.spdy.api.Headers;
import org.eclipse.jetty.spdy.api.ReplyInfo;

public class SynReplyFrame extends ControlFrame
{
    private final int streamId;
    private final Headers headers;

    public SynReplyFrame(short version, byte flags, int streamId, Headers headers)
    {
        super(version, ControlFrameType.SYN_REPLY, flags);
        this.streamId = streamId;
        this.headers = headers;
    }

    public int getStreamId()
    {
        return streamId;
    }

    public Headers getHeaders()
    {
        return headers;
    }

    public boolean isClose()
    {
        return (getFlags() & ReplyInfo.FLAG_CLOSE) == ReplyInfo.FLAG_CLOSE;
    }

    @Override
    public String toString()
    {
        return String.format("%s stream=%d close=%b", super.toString(), getStreamId(), isClose());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package io.quarkus.arc.deployment;

import java.util.List;

import org.jboss.jandex.DotName;

import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.TestAnnotationBuildItem;
import io.quarkus.deployment.builditem.TestClassBeanBuildItem;

public class TestsAsBeansProcessor {

    @BuildStep
    public void testAnnotations(List<TestAnnotationBuildItem> items, BuildProducer<BeanDefiningAnnotationBuildItem> producer) {
        for (TestAnnotationBuildItem item : items) {
            producer.produce(new BeanDefiningAnnotationBuildItem(DotName.createSimple(item.getAnnotationClassName())));
        }
    }

    @BuildStep
    public void testClassBeans(List<TestClassBeanBuildItem> items, BuildProducer<AdditionalBeanBuildItem> producer) {
        if (items.isEmpty()) {
            return;
        }

        AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder();
        for (TestClassBeanBuildItem item : items) {
            builder.addBeanClass(item.getTestClassName());
        }
        producer.produce(builder.build());
    }

}


text:
package explorviz.capacity_manager.capacitymgt.scaling.strategies;

import java.util.Map;

import explorviz.capacity_manager.node.repository.Node;

public interface IScalingStrategy {
	public void analyze(Map<Node, Double> averageCPUUtilizations);

}


text:
title: "Creative Tutorials ep. 2 with Alfie Carpenter"
location-display-name: "BLOC: Building Libraries on Creativity"
format: recording
link: icCoI4NcgEc
category: crafts
service: youtube
---


text:
NS_TINY_BEGIN

class Settings
{
public:
	static Settings* getInstance();

	~Settings();

	bool init();
	void release();

	bool isFullScreen();
	void setFullScreen(bool value);

	bool isEnabledLight();
	void enableLight(bool value);

	const Size& getWindowSize();
	void setWindowSize(const Size& size);

	float getFrameRate();
	void setFrameRate(float frameRate);

	const Vec2& getMouseStartPosition();
	void setMouseStartPosition(const Vec2& position);

	const Vec2& getWindowStartPosition();
	void setWindowStartPosition(const Vec2& position);

private:
	static Settings* _instance;

	bool _isFullScreen;
	bool _lightEnabled;
	Size _windowSize;

	float _frameRate;

	Vec2 _mouseStartPosition;
	Vec2 _windowStartPosition;
};

NS_TINY_END


text:
import { CALL_API } from '../../middleware/api';

export const PROFILE_REQUEST = 'PROFILE_REQUEST';
export const PROFILE_SUCCESS = 'PROFILE_SUCCESS';
export const PROFILE_FAILURE = 'PROFILE_FAILURE';

export const fetchUserPosts = (userName) => {
  return {
    [CALL_API]: {
      endpoint: `/post/user/${userName}`,
      types: [
        PROFILE_REQUEST,
        PROFILE_SUCCESS,
        PROFILE_FAILURE
      ],
    }
  }
};


text:
<?php

namespace Routeria\Exception;

class InvalidPathException extends \Exception {
	public function __construct($path, $code = 100)
	{
		$message = 'Invalid path for routing "' . $path . '". Valid pattern must match regex #^/(?:([^/\s]+/)*[^/\s]+)?$#';
		parent::__construct($message, $code);
	}
}


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Drug Injury Relief Payment Standard</英文法規名稱>
<中文法規名稱>藥害救濟給付標準</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=L0030024</法規網址>
<最新英文異動日期>20210901</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件 />
<沿革內容><![CDATA[1. Promulgated by the Executive Yuan, the Department of Health Order Wei-Shu-Yao-Tzu No. 0890025292, on October 27th, 2000; The Regulations shall be effective on the day of the promulgation.
2. Article 3, 4, 5, 7 amended and promulgated by the Executive Yuan, the Department of Health Order Wei-Shu-Yao-Tzu No. 09020080231, on December 21st, 2001.
3. Article 5 amended and promulgated by the Executive Yuan, the Department of Health Order Wei-Shu-Yao-Tzu No. 0950316727, on September 20th, 2006
4. Article 5 amended and promulgated by the Executive Yuan, the Department of Health Order Wei-Shu-Yao-Tzu No. 0980302512, on May 7th, 2009
   Promulgated by the Executive Yuan Notice Yuan-Tai-Gui-Zi No. 1020141353, the related authorities and responsibilities previously belonged to the Department of Health in Paragraph 2, Article 4, shall be transferred under the charge of "Ministry of Health and Welfare" since July 23th, 2013 on July 19th, 2013.
5. Article 4 amended and promulgated by the Ministry of Health and Welfare Order Bu-Shou-Shi-Zi No. 103203338, on October 23rd, 2014.
6. Article 7 amended and promulgated by the Ministry of Health and Welfare Order Bu-Shou-Shi-Zi No. 1051413143, on December 26th, 2016.
7.Article 3, 4 amended and promulgated, and Article 5-1 added by the Ministry of Health and Welfare Order Wei-Shou-Shi-Zi No. 1101406547, on September 1st, 2021.
]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[These regulations are promulgated pursuant to the Paragraph 2 of Article 4 of the Drug Injury Relief Act (hereinafter referred to as the Act).]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The drug injury relief payment shall be classified into death payment, disable payment and severe illness payment. The payment shall be determined according to this standard.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[For drug injury relief applications, the maximum amount of relief is NT$3,000,000 for cases that have been reasonably determined to have resulted in death due to adverse drug reactions. If the deceased's autopsy report is attached and reviewed and the cause of death cannot be identified for any other reason, the drug injury relief payment shall be paid accordingly. When the autopsy report is not attached and reviewed, and the cause of death cannot be identified as a result of adverse drug reactions, the drug injury relief payment shall not be approved.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[When an application for relief payment from a drug-related injury is reviewed and reasonably determined to have been caused by adverse drug reactions, the amount shall be paid according to the following levels of disability. After the review, where the cause of disability cannot be reasonably attributed to other reasons, the relief shall be paid up to the maximum amount specified below:
1. Profound disabilities: The maximum shall be paid for NT$3,000,000.
2. Severe disabilities: The maximum shall be paid for NT$2,250,000.
3. Moderate disabilities: The maximum shall be paid for NT$1,950,000.
4. Mild disabilities: The maximum shall be paid for NT$1,750,000.
The disability identification levels set out in the previous paragraph are those announced by the Ministry of Health and Welfare.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[In the case of drug injury relief application is reviewed and may be reasonably identified as the severe illness caused by adverse reaction of drug, the payment shall be the necessary medical expenses listed on the official receipt issued by medical institutions and clinics. After the review, when the cause of severe illness cannot be identified reasonably by other reasons, shall also be paid accordingly pursuant to the preceding statement. However, when there is a necessity to occupy a unit of Intensive Care Unit or Burn Intensive Care Unit, the relief payment shall be paid additionally accordingly.
The total payment pursuant to the previous paragraph shall be limited up to NT$600,000; if the total payment is less than NT$10,000, the payment shall be paid as NT$10,000.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5-1</條號>
    <條文內容><![CDATA[After the amendment and enforcement of this Standard on September 1, 2021, drug injury events that occurred shall be paid in accordance with the drug injury relief payment amounts specified in Article 3 and Article 4; drug-related injuries that occurred before the amendment shall be paid according to the amounts specified before the amendment.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[Where there is a lappage of the reasons for relief, the payment selection shall be the one with the higher rate; the one with the lower rate may make up to the difference of payment deficiency.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 7</條號>
    <條文內容><![CDATA[The expenses from pathological autopsy, disability appraisal and other appraisals shall all be paid by the Drug Injury Relief Fund.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 8</條號>
    <條文內容><![CDATA[This standard shall be effective as of the date of promulgation.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
require 'spec_helper'

describe QuadrigaCX::Client, :vcr do
  def safe_limit_buy(book: :btc_cad)
    worst_price = subject.order_book.bids.last[0]
    subject.limit_buy(price: worst_price, amount: 1, book: book)
  end

  def safe_limit_sell(book: :btc_cad)
    worst_price = subject.order_book.asks.last[0]
    subject.limit_sell(price: worst_price, amount: 0.01, book: book)
  end

  describe 'public' do
    describe '#ticker' do
      it 'returns trading information' do
        ticker = subject.ticker

        expect(ticker.high).not_to be_nil
        expect(ticker.low).not_to be_nil
      end
    end

    describe '#order_book' do
      let(:order_book_cad) { subject.order_book }
      let(:order_book_usd) { subject.order_book(book: :btc_usd) }

      it 'returns a list of all open orders' do
        expect(order_book_cad.timestamp).not_to be_nil
        expect(order_book_cad.bids.first.length).to equal 2
        expect(order_book_cad.asks.first.length).to equal 2
      end

      it 'returns a USD order book' do
        expect(order_book_usd.bids.first).to_not equal(order_book_cad.bids.first)
      end

      context 'when using the group option' do
        let!(:order) { safe_limit_buy }
        after { subject.cancel_order(id: order.id) }

        it 'does not group same price orders' do
          ungrouped_bids = subject.order_book(group: 0).bids
          expect(ungrouped_bids[-2][0]).to eq(ungrouped_bids.last[0])
        end
      end
    end

    describe '#transactions' do
      let(:transactions_cad) { subject.transactions }
      let(:transactions_usd) { subject.transactions(book: :btc_usd) }

      it 'returns a list of recent trades' do
        expect(transactions_cad.first.date).not_to be_nil
        expect(transactions_cad.first.price).not_to be_nil
      end

      it 'returns a list of USD trades' do
        expect(transactions_usd.first.price).not_to equal(transactions_cad.first.price)
      end
    end
  end

  describe 'private' do
    describe '#balance' do
      it 'returns all account balances' do
        balance = subject.balance

        expect(balance.cad_balance).not_to be_nil
        expect(balance.btc_balance).not_to be_nil
      end
    end

    describe '#limit_buy' do
      describe 'errors' do
        it 'throws an error when no price is provided' do
          expect { subject.limit_buy }.to raise_error(QuadrigaCX::ConfigurationError)
        end

        it 'throws an error when exceeding balance' do
          expect { subject.limit_buy(price: 1_000_000, amount: 1) }.to raise_error(QuadrigaCX::AboveMaximumOrderValue)
        end

        it 'throws an error when the amount is too small' do
          expect { subject.limit_buy(price: 100, amount: 0.00000001) }.to raise_error(QuadrigaCX::BelowMinimumOrderValue)
        end

        it 'throws an error when exceeding available balance' do
          expect { subject.limit_buy(price: 4999, amount: 1) }.to raise_error(QuadrigaCX::ExceedsAvailableBalance)
        end
      end

      let(:order_cad) { safe_limit_buy }
      let(:order_usd) { safe_limit_buy(book: :btc_usd) }

      after { subject.cancel_order(id: order_cad.id) && subject.cancel_order(id: order_usd.id) }

      it 'places a limit buy order_cad' do
        expect(order_cad.datetime).not_to be_nil
        expect(order_cad.id).not_to be_nil
        expect(order_cad.price).not_to be_nil
      end

      it 'places a USD limit buy order' do
        expect(order_cad.price).not_to equal(order_usd.price)
      end
    end

    describe '#limit_sell' do
      describe 'errors' do
        it 'throws an error when no price is provided' do
          expect { subject.limit_sell }.to raise_error(QuadrigaCX::ConfigurationError)
        end
      end

      let(:order_cad) { safe_limit_sell }
      let(:order_usd) { safe_limit_sell(book: :btc_usd) }

      after { subject.cancel_order(id: order_cad.id) && subject.cancel_order(id: order_usd.id) }

      it 'places a limit sell order' do
        expect(order_cad.datetime).not_to be_nil
        expect(order_cad.id).not_to be_nil
        expect(order_cad.price).not_to be_nil
      end

      it 'places a USD limit sell order' do
        expect(order_cad.price).not_to equal(order_usd.price)
      end
    end

    describe '#market_buy' do
      let(:market_buy_cad) { subject.market_buy(amount: 5.00) }
      let(:market_buy_usd) { subject.market_buy(amount: 5.00, book: :btc_usd) }

      it 'places a market buy order' do
        expect(market_buy_cad.amount).not_to be_nil
        expect(market_buy_cad.orders_matched.first.price).not_to be_nil
      end

      it 'places a USD market buy order' do
        expect(market_buy_cad.orders_matched.first.price).not_to equal(market_buy_usd.orders_matched.first.price)
      end
    end

    describe '#market_sell' do
      let(:market_sell_cad) { subject.market_sell(amount: 0.01) }
      let(:market_sell_usd) { subject.market_sell(amount: 0.01, book: :btc_usd) }

      it 'places a market sell order' do
        expect(market_sell_cad.amount).not_to be_nil
        expect(market_sell_cad.orders_matched.first.price).not_to be_nil
      end

      it 'places a USD market sell order' do
        expect(market_sell_cad.orders_matched.first.price).not_to equal(market_sell_usd.orders_matched.first.price)
      end
    end

    describe '#cancel_order' do
      let(:order) { safe_limit_buy }

      it 'cancels an order' do
        response = subject.cancel_order(id: order.id)
        expect(response).to be true
      end
    end

    describe '#open_orders' do
      let(:open_orders_cad) { subject.open_orders }
      let(:open_orders_usd) { subject.open_orders(book: :btc_usd) }
      let!(:orders) { [safe_limit_buy, safe_limit_buy(book: :btc_usd)] }

      after { orders.each { |order| subject.cancel_order(id: order.id) } }

      it 'lists open orders' do
        expect(open_orders_cad.first.datetime).not_to be_nil
        expect(open_orders_cad.first.type).not_to be_nil
        expect(open_orders_cad.first.price).not_to be_nil
      end

      it 'lists USD open orders' do
        expect(open_orders_cad.first.price).not_to equal open_orders_usd.first.price
      end
    end

    describe '#lookup_order' do
      let(:lookup_order) { subject.lookup_order(id: '1na3tujn948erx1xlbfu8yw93f8y41vgja5if6zdegvwk8pcked34l48sh1or189') }

      it 'looks up an order' do
        expect(lookup_order.first.amount).to_not be_nil
        expect(lookup_order.first.book).to_not be_nil
        expect(lookup_order.first.created).to_not be_nil
        expect(lookup_order.first.id).to_not be_nil
        expect(lookup_order.first.price).to_not be_nil
        expect(lookup_order.first.status).to_not be_nil
        expect(lookup_order.first.type).to_not be_nil
        expect(lookup_order.first.updated).to_not be_nil
      end
    end

    describe '#withdraw' do
      context 'valid coin type' do
        it 'success in withdrawal' do
          coin = QuadrigaCX::Coin::BITCOIN
          response = subject.withdraw(coin, amount: 0.01, address: '1DVLFma28jEgTCUjQ32FUYe12bRzvywAfr')
          expect(response).to eq('ok')
        end
      end

      context 'no coin type' do
        it 'failure in withdrawal' do
          expect do
            subject.withdraw(nil, amount: 0.01, address: '1DVLFma28jEgTCUjQ32FUYe12bRzvywAfr')
          end.to raise_error(QuadrigaCX::ConfigurationError)
        end
      end

      context 'invalid coin type' do
        it 'failure in withdrawal' do
          coin = 'DummyCoin'
          expect do
            subject.withdraw(coin, amount: 0.01, address: '1DVLFma28jEgTCUjQ32FUYe12bRzvywAfr')
          end.to raise_error(QuadrigaCX::ConfigurationError)
        end
      end
    end

    describe '#deposit_address' do
      context 'valid coin type' do
        it 'success in retrieving deposit address for valid coin type' do
          coin = QuadrigaCX::Coin::BITCOIN
          response = subject.deposit_address(coin)
          expect(response.length).to be_between(26, 35)
          expect(response.class).to eq(String)
        end
      end

      context 'invalid coin type' do
        it 'failure in retrieving deposit address' do
          expect do
            subject.deposit_address(nil)
          end.to raise_error(QuadrigaCX::ConfigurationError)
        end
      end

      context 'invalid coin type' do
        it 'failure in retrieving deposit address' do
          coin = 'DummyCoin'
          expect do
            subject.deposit_address(coin)
          end.to raise_error(QuadrigaCX::ConfigurationError)
        end
      end
    end

    describe '#user_transactions' do
      let(:user_transactions_cad) { subject.user_transactions }
      let(:user_transactions_usd) { subject.user_transactions(order_book: :btc_usd) }

      it 'returns a list of transactions' do
        expect(user_transactions_cad.first.id).to be_kind_of(String)
        expect(user_transactions_cad.first.datetime).not_to be_nil
        expect(user_transactions_cad.first.rate).not_to be_nil
      end

      it 'returns a list of USD transactions' do
        expect(user_transactions_cad.first.rate).not_to equal(user_transactions_usd.first.rate)
      end

      it 'returns a list of limited transactions' do
        limit    = 5
        response = subject.user_transactions(limit: limit)
        expect(response.length).to equal limit
      end
    end
  end
end


text:
from __future__ import (absolute_import, print_function,
                        division, unicode_literals)

import os
import sys
from datetime import datetime
from collections import defaultdict

from ..persistence import persistence
from ..cross_version import builtins

class ExecutionProvider(object):

    def __init__(self, metascript, depth_context, depth_threshold):
        # Indicates when activations should be collected
        #   (only after the first call to the script)
        self.enabled = False
        self.script = metascript['path']
        # which function types ('non-user' or 'all')
        #   should be considered for the threshold
        self.depth_context = depth_context
        # how deep we want to go when capturing function activations?
        self.depth_threshold = depth_threshold
        self.metascript = metascript
        self.trial_id = metascript['trial_id']
        self.event_map = defaultdict(lambda: self.trace_empty, {})
        self.default_profile = sys.getprofile()
        self.default_trace = sys.gettrace()

    def trace_empty(self, frame, event, arg):
        pass

    def tracer(self, frame, event, arg):
        self.event_map[event](frame, event, arg)

    def store(self):
        pass

    def teardown(self):
        sys.setprofile(self.default_profile)
        sys.settrace(self.default_trace)

    def tearup(self):
        pass

class StoreOpenMixin(ExecutionProvider):

    def __init__(self, *args):
        super(StoreOpenMixin, self).__init__(*args)
        persistence.std_open = open
        builtins.open = self.new_open(open)

    def add_file_access(self, file_access):
        'The class that uses this mixin must override this method'
        pass

    def new_open(self, old_open):
        'Wraps the open buildin function to register file access'
        def open(name, *args, **kwargs):  # @ReservedAssignment
            if self.enabled:
                # Create a file access object with default values
                file_access = {
                    'name': name,
                    'mode': 'r',
                    'buffering': 'default',
                    'content_hash_before': None,
                    'content_hash_after': None,
                    'timestamp': datetime.now()
                }

                if os.path.exists(name):
                    # Read previous content if file exists
                    with old_open(name, 'rb') as f:
                        file_access['content_hash_before'] = persistence.put(
                            f.read())

                # Update with the informed keyword arguments (mode / buffering)
                file_access.update(kwargs)
                # Update with the informed positional arguments
                if len(args) > 0:
                    file_access['mode'] = args[0]
                elif len(args) > 1:
                    file_access['buffering'] = args[1]

                self.add_file_access(file_access)
            return old_open(name, *args, **kwargs)

        return open

    def teardown(self):
        'Restores default open'
        builtins.open = persistence.std_open
        super(StoreOpenMixin, self).teardown()


text:
<!doctype html>
<html>
<head>
  <title>capture</title>
  <!--<script src="../../../components/platform-dev/platform.js"></script>
  <link rel="import" src="../../../components/polymer/polymer.html">-->
</head>
<body unresolved>
  <div>
    <button>Go</button>
  </div>
  <script>
    /*document.addEventListener('WebComponentsReady', function() {
      console.log('first!');
    });

    document.addEventListener('WebComponentsReady', function() {
      console.log('second, capture');
    }, true);*/

    var b = document.querySelector('button');
    var d = document.querySelector('div');

    b.addEventListener('click', function() {
      console.log(this.localName, 'first!');
    });

    b.addEventListener('click', function() {
      console.log(this.localName, 'second, capture');
    }, true);

    d.addEventListener('click', function() {
      console.log(this.localName, 'first!');
    });

    d.addEventListener('click', function() {
      console.log(this.localName, 'second, capture');
    }, true);
  </script>
</body>
</html>


text:
"""Create Event Source Mapping trigger for AWS Lambda"""
import argparse
import logging

from ...args import add_app, add_debug, add_env, add_region
from ...consts import LOGGING_FORMAT
from .event_source_mapping import create_event_source_mapping_trigger

def main():
    """Create Event Source Mapping trigger for AWS Lambda"""
    logging.basicConfig(format=LOGGING_FORMAT)

    parser = argparse.ArgumentParser(description=main.__doc__)
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_region(parser)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    assert create_event_source_mapping_trigger(**vars(args))

if __name__ == '__main__':
    main()


text:
require File.join(File.dirname(__FILE__), "/../../../../spec_helper")

describe "/admin/materials/pluggable_scm/edit.html.erb" do
  include GoUtil, FormUI

  SCM_PLUGIN_ID = 'my.scm.plugin'
  SCM_PLUGIN_TEMPLATE = "<input ng-model=\"KEY1\" type=\"text\"><input ng-model=\"key2\" type=\"text\">"

  before :each do
    in_params(:pipeline_name => 'pipeline_name')

    assign(:cruise_config, config = BasicCruiseConfig.new)
    set(config, 'md5', 'md5-1')

    view.stub(:admin_pluggable_scm_update_path).and_return('admin_pluggable_scm_update_path')
    configuration = Configuration.new([ConfigurationPropertyMother.create('KEY1', false, 'value1'), ConfigurationPropertyMother.create('key2', false, 'value2')].to_java(ConfigurationProperty))
    scm = SCMMother.create('scm-id', 'scm-name', SCM_PLUGIN_ID, '1', configuration)
    scm.setAutoUpdate(false)
    filters = Filter.new([IgnoredFiles.new('/sugar'), IgnoredFiles.new('/jaggery')].to_java(IgnoredFiles))
    pluggable_scm = PluggableSCMMaterialConfig.new(nil, scm, 'dest', filters)
    assign(:material, @material = pluggable_scm)
    assign(:meta_data_store, @meta_data_store = SCMMetadataStore.getInstance())

    setup_meta_data
  end

  after :each do
    @meta_data_store.clear()
  end

  it "should render the warning, pipelines used in link" do
    render

    expect(response.body).to have_selector('.warnings', text: 'This is a global copy. All pipelines using this SCM will be affected.')
    expect(response.body).to have_selector("a#show_pipelines_used_in", :text => 'Show pipelines using this SCM')
    expect(response.body).to have_selector("#pipelines_used_in")
  end

  it "should render the config md5, form buttons and flash message" do
    render

    expect(response.body).to have_selector('#message_pane')

    Capybara.string(response.body).find("form[action='admin_pluggable_scm_update_path'][method='post']").tap do |form|
      expect(form).to have_selector("input[id='config_md5'][type='hidden'][value='md5-1']")
      expect(form).to have_selector("button[type='submit']", :text => 'SAVE')
      expect(form).to have_selector("button", :text => 'Cancel')
    end
  end

  it "should render the config conflict message" do
    assign(:config_file_conflict, true)

    render

    expect(response.body).to have_selector('#config_save_actions')
  end

  it "should render the required message" do
    render

    expect(response.body).to have_selector('.required .asterisk')
  end

  it "should render name, check-connection, auto-update, destination & filter" do
    render

    expect(response.body).to have_selector(".popup_form input[type='text'][name='material[#{com.thoughtworks.go.domain.scm.SCM::NAME}]'][value='scm-name']")
    expect(response.body).to have_selector(".popup_form button#check_connection_pluggable_scm", :text => 'CHECK CONNECTION')
    expect(response.body).to have_selector(".popup_form #pluggable_scm_check_connection_message", :text => '')
    expect(response.body).to have_selector(".popup_form input[type='checkbox'][name='material[#{com.thoughtworks.go.domain.scm.SCM::AUTO_UPDATE}]']")
    expect(response.body).to have_selector(".popup_form input[type='text'][name='material[#{PluggableSCMMaterialConfig::FOLDER}]'][value='dest']")
    expect(response.body).to have_selector(".popup_form textarea[name='material[#{PluggableSCMMaterialConfig::FILTER}]']", :text => '/sugar,/jaggery')
  end

  it "should render plugin template and data for a new pluggable SCM" do
    render

    Capybara.string(response.body).find('div.plugged_material#material_angular_pluggable_material_my_scm_plugin').tap do |div|
      template_text = text_without_whitespace(div.find('div.plugged_material_template'))
      expect(template_text).to eq(SCM_PLUGIN_TEMPLATE)

      data_for_template = JSON.parse(div.find('span.plugged_material_data', :visible => false).text)
      expect(data_for_template.keys.sort).to eq(['KEY1', 'key2'])
      expect(data_for_template['KEY1']).to eq({'value' => 'value1'})
      expect(data_for_template['key2']).to eq({'value' => 'value2'})
    end
  end

  it "should display edit pluggable SCM material view with errors" do
    scm_errors = config_error(com.thoughtworks.go.domain.scm.SCM::NAME, 'Material Name is so wrong')
    scm_errors.add(com.thoughtworks.go.domain.scm.SCM::AUTO_UPDATE, 'AUTO_UPDATE is wrong')
    set(@material.getSCMConfig(), 'errors', scm_errors)

    pluggable_scm_errors = config_error(PluggableSCMMaterialConfig::FOLDER, 'Folder is wrong')
    set(@material, "errors", pluggable_scm_errors)
    @ignored_file = IgnoredFiles.new('/sugar')
    @material.setFilter(Filter.new([@ignored_file].to_java(IgnoredFiles)))
    set(@ignored_file, 'configErrors', config_error(com.thoughtworks.go.config.materials.IgnoredFiles::PATTERN, 'Filter is wrong'))

    render

    Capybara.string(response.body).find('.popup_form').tap do |popup_form|
      expect(popup_form).to have_selector('div.form_error', :text => 'Material Name is so wrong')
      expect(popup_form).to have_selector('div.form_error', :text => 'AUTO_UPDATE is wrong')
      expect(popup_form).to have_selector('div.form_error', :text => 'Folder is wrong')
      expect(popup_form).to have_selector('div.form_error', :text => 'Filter is wrong')
    end
  end

  def setup_meta_data
    @meta_data_store.clear()

    scm_view = double('SCMView')
    scm_view.stub(:displayValue).and_return('Display Name')
    scm_view.stub(:template).and_return(SCM_PLUGIN_TEMPLATE)
    @meta_data_store.addMetadataFor(SCM_PLUGIN_ID, SCMConfigurations.new, scm_view)
  end

  def text_without_whitespace element
    element.native.inner_html.gsub(/^[\n ]*/, '').gsub(/[\n ]*$/, '')
  end
end


text:
package com.ebay.jetstream.event.support.channel;

import com.ebay.jetstream.spring.context.support.AbstractApplicationEvent;

public final class ResumeEvent extends AbstractApplicationEvent {
  private static final long serialVersionUID = 1L;

  public ResumeEvent(Object source) {
    super(source);
  }
}


text:
namespace Akka.Persistence.ServiceFabric
{
    using System.Fabric;
    using System.Threading.Tasks;
    using Akka.Persistence.ServiceFabric.Snapshot;
    using Microsoft.ServiceFabric.Data;
    using Microsoft.ServiceFabric.Services.Runtime;

    public class AkkaStatefulService : StatefulService
    {
        public static StatefulServiceContext ServiceContext;

        public static StatefulService StatefulService;

        public AkkaStatefulService(StatefulServiceContext context)
            : this(context, new InitializationCallbackAdapter())
        {
        }

        public AkkaStatefulService(StatefulServiceContext context, InitializationCallbackAdapter adapter)
            : base(context, new ReliableStateManager(context, new ReliableStateManagerConfiguration(onInitializeStateSerializersEvent: adapter.OnInitialize)))
        {
            adapter.StateManager = this.StateManager;
            ServiceContext = context;
            StatefulService = this;
        }
    }

    public class InitializationCallbackAdapter
    {
        public IReliableStateManager StateManager { get; set; }

        public Task OnInitialize()
        {
            this.StateManager.TryAddStateSerializer(new SnapshotEntrySerializer());
            return Task.FromResult(true);
        }

    }
}


text:
<?php
class CaisseEntrees{
	//attributes
	private $_id;
	private $_montant;
	private $_designation;
	private $_dateOperation;
	private $_utilisateur;

	//le constructeur
    public function __construct($data){
        $this->hydrate($data);
    }

    //la focntion hydrate sert à attribuer les valeurs en utilisant les setters d'une façon dynamique!
    public function hydrate($data){
        foreach ($data as $key => $value){
            $method = 'set'.ucfirst($key);

            if (method_exists($this, $method)){
                $this->$method($value);
            }
        }
    }

	//setters
	public function setId($id){
        $this->_id = $id;
    }

	public function setDesignation($designation){
        $this->_designation = $designation;
    }

	public function setMontant($montant){
        $this->_montant = $montant;
    }

	public function setDateOperation($dateOperation){
        $this->_dateOperation = $dateOperation;
    }

	public function setUtilisateur($utilisateur){
        $this->_utilisateur = $utilisateur;
    }

	//getters
	public function id(){
        return $this->_id;
    }

	public function designation(){
        return $this->_designation;
    }

	public function montant(){
        return $this->_montant;
    }

	public function dateOperation(){
        return $this->_dateOperation;
    }

	public function utilisateur(){
        return $this->_utilisateur;
    }
}


text: Advertisement web site for window repair company


text:
import React, {Component,PropTypes} from 'react';
import styles from './RightDetail.less';

export default class RightDetail  extends Component {
    static defaultProps = {
    };
    static propTypes = {
    };
    constructor (props) {
        super(props);
    };
    componentWillMount () {}
    componentDidMount  () {}
    shouldComponentUpdate () {
        return true;
    }
    componentWillUpdate () {}
    componentDidUpdate () {}
    componentWillUnmount () {}

    render () {
        return (
            <div className={"fl vh100 " + styles.RightDetail}>
                {this.props.children}
            </div>
        );
    }
}


text:
layout: post
title: New Developer API Reference
description: Avalara introduces new developer API reference documentation
date: 2017-07-03 12:00
author: Ted Spence
comments: true
categories: [avatax]
product: blog
doctype: blog
disqus: 1
redirect_to: https://www.avalara.com/us/en/blog/2017/07/developer-api-reference.html
---

As part of our commitment to the [Open API initiative](https://www.openapis.org/), Avalara's development team knows that the quality of the documentation we use matters.  Our customers rely on us to make tax simple: our documentation can help you to learn how to properly design your software so you can charge the correct amount of tax every time.  That's why Avalara spends so much time updating our developer documentation, and why we've introduced a new layout to our API reference pages.

Single Page Per Method

Our new site layout features one web page for each API method in our documentation.  This makes it easy to share commonly used documentation such as the [CreateTransaction](/api-reference/avatax/rest/v2/methods/Transactions/CreateTransaction/), [ResolveAddress](/api-reference/avatax/rest/v2/methods/Addresses/ResolveAddress/), and [RefundTransaction](/api-reference/avatax/rest/v2/methods/Transactions/RefundTransaction/) API calls.

You can glance at these pages and easily determine:

* What is this API's purpose?
* What's the URL of this REST API?
* What parameters and values should I pass to the API?

Here's a sample of one of our API methods, RefundTransaction:

Documentation for Structured Objects

In AvaTax, every structured object you use or receive is called a `Model`.  Avalara has written [documentation for every model used by AvaTax](/api-reference/avatax/rest/v2/models/) to help you understand what each object is and how it works.  For example, if you're interested in learning about the [AddressInfo](/api-reference/avatax/rest/v2/models/AddressInfo/) model, you can click on the link to its documentation and easily see:

* The name of each member field
* The data type (for example, string, numeric, boolean, date, or so on)
* If the field is a string, the minimum and maximum length of the string
* A description of the purpose of each field
* If available, a sample value for the field

At the end of each page, we aim to show a sample object for each type, so you can understand how to construct one yourself.  Our team is even working to add links to show exactly which API uses each model, so you can directly jump back and forth between an API method and the data it uses.

Here's a sample object that shows how you can use this documentation:

Try Every API

Even more exciting, you're invited to visit our developer website and try out each API interactively!  For example [ListCountries](/api-reference/avatax/rest/v2/methods/Definitions/ListCountries/) is the API that provides access to the ISO 3166 country code database.  (Avalara maintains a subscription to the ISO country code definition system so that our customers don't have to!)  You can visit the web page for the [ListCountries API](/api-reference/avatax/rest/v2/methods/Definitions/ListCountries/) and click on "Try ListCountries Now".  You'll be able to click the `Submit` button and see, in just a few moments, the exact response that you would receive if you called it with your production account credentials!

This Try-It-Now functionality is available - now - for every API in Avalara's REST v2 suite.  Use it as a great way to get started and understand how the product would respond - use it as a way to preview results - or just to play around with new features before writing code against them.

Exploration encouraged!

The best feature of our implementation of Open API is that we now support software development kits for many popular programming languages, and each of those software development kits is updated monthly as our API definition is refined.  All of our help text and commentary is available as context-sensitive help in each SDK, available in most integrated development environments.

We also encourage you to leave comments at the bottom of each API.  Avalara uses Disqus, an online discussion platform, to allow our visitors to share comments and questions about any API they like.  Write us a question, comment, or complaint anytime!  Our team loves feedback from developers - you're what makes Avalara such a great way to simplify sales tax.

Thanks for reading!

-- Ted Spence, Director, AvaTax Core Engine


text:
'use strict';

var app = angular.module('myApp.access-token.services', ['ngResource']);

app.factory('RefreshToken', ['$q', '$http', function($q, $http) {

  var refresh = function(token) {
    var deferred = $q.defer();
    $http({
      method: 'GET',
      url: '/auth/refreshToken',
      params: {token: token}
    }).then(function(msg) {
      deferred.resolve(msg);
    }, function(err) {
      deferred.reject(err);
    });
    return deferred.promise;
  };

  return {
    refresh: refresh,
  };

}]);

app.factory('AccessToken', ['$cookies', '$q', function($cookies, $q) {

  var domain = function() {
    var uri = new window.URI(window.location.href);
    var host = uri.domain();
    return '.' + host;
  };

  var set = function(token) {
    $cookies.put('_cta', token, { domain: domain() });
    return true;
  };

  var del = function() {
    var d = domain();
    $cookies.remove('_cta', { domain: d });
    $cookies.remove('_cta');
  };

  var get = function() {
    var ls;

    //prefere url token to cookie
    var params = document.location.href.match(/[?&]token=([0-9a-f]+)/);
    if (params) {
      ls = params[1];
      set(ls);
    } else {
      ls = $cookies.get('_cta', { domain: domain() });
    }

    return ls;
  };

  return {
    set: set,
    del: del,
    get: get,
  };

}]);


text:
FROM golang:1.17-buster AS dockerize

RUN apt-get update \
    && apt-get install -y --no-install-recommends openssl git

RUN go install github.com/jwilder/dockerize@latest

# Final build image
FROM ubuntu:focal

ENV TZ="UTC"

# Add Dockerize
COPY --from=dockerize /go/bin/dockerize /usr/local/bin

# Run base build process
COPY ./util/docker/web /bd_build/

RUN chmod a+x /bd_build/*.sh \
    && /bd_build/prepare.sh \
    && /bd_build/add_user.sh \
    && /bd_build/setup.sh \
    && /bd_build/cleanup.sh \
    && rm -rf /bd_build

#
# START Operations as `azuracast` user
#
USER azuracast

WORKDIR /var/azuracast/www

COPY --chown=azuracast:azuracast ./composer.json ./composer.lock ./
RUN composer install \
    --no-dev \
    --no-ansi \
    --no-autoloader \
    --no-interaction

COPY --chown=azuracast:azuracast . .

RUN composer dump-autoload --optimize --classmap-authoritative \
    && touch /var/azuracast/.docker

VOLUME ["/var/azuracast/www_tmp", "/var/azuracast/uploads", "/var/azuracast/backups", "/var/azuracast/sftpgo/persist"]

#
# END Operations as `azuracast` user
#
USER root

EXPOSE 80 2022

# Sensible default environment variables.
ENV LANG="en_US.UTF-8" \
    APPLICATION_ENV="production" \
    ENABLE_ADVANCED_FEATURES="false" \
    MYSQL_HOST="mariadb" \
    MYSQL_PORT=3306 \
    MYSQL_USER="azuracast" \
    MYSQL_PASSWORD="azur4c457" \
    MYSQL_DATABASE="azuracast" \
    ENABLE_REDIS="true" \
    REDIS_HOST="redis" \
    REDIS_PORT=6379 \
    REDIS_DB=1 \
    NGINX_RADIO_PORTS="default" \
    NGINX_WEBDJ_PORTS="default" \
    PREFER_RELEASE_BUILDS="false" \
    COMPOSER_PLUGIN_MODE="false" \
    ADDITIONAL_MEDIA_SYNC_WORKER_COUNT=0 \
    PROFILING_EXTENSION_ENABLED=0 \
    PROFILING_EXTENSION_ALWAYS_ON=0 \
    PROFILING_EXTENSION_HTTP_KEY=dev \
    PROFILING_EXTENSION_HTTP_IP_WHITELIST=*

# Entrypoint and default command
ENTRYPOINT ["/usr/local/bin/uptime_wait"]
CMD ["/usr/local/bin/my_init"]


text:
use test;
db.oauthclients.insert({clientId: "superID", clientSecret: "superSecret"});


text:
actions        :create, :create_if_missing, :delete
default_action :create

attribute :name,       kind_of: String, name_attribute: true
# linux/netfilter/x_tables.h doesn't restrict chains very tightly.  Just a string token
# with a max length of XT_EXTENSION_MAXLEN (29 in all 3.x headers I could find)
attribute :chain,      kind_of: String, default: 'INPUT',  regex: /^\w{1,29}$/
attribute :table,      kind_of: String, default: 'filter', equal_to: %w{filter nat mangle raw}
attribute :rule,       kind_of: [ Array, String ],  default: []
attribute :ip_version, kind_of: [ Array, Integer ], default: [4, 6], equal_to: [ [4, 6], 4, 6 ]

def initialize(*args)
  super
  @action = :create

  # Include iptables-ng::install recipe
  @run_context.include_recipe('iptables-ng::install')
end


text:
'use strict';

define(['js/product/model', 'js/product/view'], function(Model, View) {
    var controller = function() {

    };

    controller.prototype = {
        init: function(id){
            Model.getProduct(id).done(function(data,datas) {
                var view = new View();
                view.init(data,datas);
            });
        }
    };

    var ctr = new controller();
    return ctr;
});


text:
<?php

use Phinx\Migration\AbstractMigration;

class CreateSubscribedTable extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change()
    {
        $table = $this->table('subscriptions');
        $table->addColumn('directory_id', 'integer')
              ->addColumn('user_id', 'integer')
              ->addForeignKey('directory_id', 'directories', 'id', ['delete'=> 'CASCADE', 'update'=> 'CASCADE'])
              ->addForeignKey('user_id', 'users', 'id', ['delete'=> 'CASCADE', 'update'=> 'CASCADE'])
              ->create();
    }
}


text:
wait_for_port_open() {
  port="$1"

  while ! nc -z localhost $port; do
    sleep 0.1
  done
}

wait_for_port_close() {
  port="$1"

  while nc -z localhost $port; do
    sleep 0.1
  done
}

node "integration/fixtures/apps/simple/server.js" 13051 &
wait_for_port_open 13051

node "integration/fixtures/apps/other/server.js" 13052 &
wait_for_port_open 13052

node "integration/fixtures/apps/simple.thing/server.js" 13053 &
wait_for_port_open 13053

export ZAS_DNS_PORT=13043
export ZAS_HTTP_PORT=13044
export XDG_CONFIG_HOME="$(pwd)/integration/fixtures/config"

target/debug/zas 1>&2 &

bats integration

pkill -P $$ || true

wait_for_port_close $ZAS_DNS_PORT
wait_for_port_close $ZAS_HTTP_PORT
wait_for_port_close 13051
wait_for_port_close 13052
wait_for_port_close 13053


text:
<?php

namespace Tga\AudienceBundle\Browser;

/**
 * UserAgent informations storage
 *
 * @author Titouan Galopin <galopintitouan@gmail.com>
 */
class UserAgent implements \Serializable
{
	const PLATFORM_ANDROID = 'Android';
	const PLATFORM_IPHONE = 'iPhone';
	const PLATFORM_IPOD = 'iPod';
	const PLATFORM_IPAD = 'iPad';
	const PLATFORM_LINUX = 'Linux';
	const PLATFORM_MAC = 'Mac OS';
	const PLATFORM_WINDOWS = 'Windows';

	const BROWSER_IE = 'Internet Explorer';
	const BROWSER_FIREFOX = 'Mozilla Firefox';
	const BROWSER_CHROME = 'Google Chrome';
	const BROWSER_SAFARI = 'Apple Safari';
	const BROWSER_OPERA = 'Opera';
	const BROWSER_NETSCAPE = 'Netscape';

	static $mobilePlatforms = array(
		self::PLATFORM_ANDROID,
		self::PLATFORM_IPOD,
		self::PLATFORM_IPAD,
		self::PLATFORM_IPHONE
	);

	/**
	 * @var string
	 */
	protected $browser;

	/**
	 * @var string
	 */
	protected $browserVersion;

	/**
	 * @var string
	 */
	protected $platform;

	/**
	 * @var boolean
	 */
	protected $isMobile;

	/**
	 * Constructor
	 */
	public function __construct()
	{
		$this->browser = 'Unknown';
		$this->browserVersion = 'Unknown';
		$this->platform = 'Unknown';
		$this->isMobile = false;
	}

	/**
	 * Serialize the object
	 *
	 * @implements \Serializable
	 * @return string
	 */
	public function serialize()
	{
		return serialize(array($this->browser, $this->browserVersion, $this->platform, $this->isMobile));
	}

	/**
	 * Unserialize the string
	 *
	 * @implements \Serializable
	 * @param string $serialized
	 */
	public function unserialize($serialized)
	{
		list($this->browser, $this->browserVersion, $this->platform, $this->isMobile) = unserialize($serialized);
	}

	/**
	 * @param string $browser
	 * @return UserAgent
	 */
	public function setBrowser($browser)
	{
		$this->browser = $browser;

		return $this;
	}

	/**
	 * @return string
	 */
	public function getBrowser()
	{
		return $this->browser;
	}

	/**
	 * @param string $browserVersion
	 * @return UserAgent
	 */
	public function setBrowserVersion($browserVersion)
	{
		$this->browserVersion = $browserVersion;

		return $this;
	}

	/**
	 * @return string
	 */
	public function getBrowserVersion()
	{
		return $this->browserVersion;
	}

	/**
	 * @param boolean $isMobile
	 * @return UserAgent
	 */
	public function setIsMobile($isMobile)
	{
		$this->isMobile = $isMobile;

		return $this;
	}

	/**
	 * @return boolean
	 */
	public function getIsMobile()
	{
		return $this->isMobile;
	}

	/**
	 * @param string $platform
	 * @return UserAgent
	 */
	public function setPlatform($platform)
	{
		$this->platform = $platform;

		if (in_array($platform, self::$mobilePlatforms)) {
			$this->isMobile = true;
		} else {
			$this->isMobile = false;
		}

		return $this;
	}

	/**
	 * @return string
	 */
	public function getPlatform()
	{
		return $this->platform;
	}
}


text:
package de.spricom.dessert.classfile.constpool;

import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;

public class FieldTypeTest {

    @Test
    public void testIsFieldDescriptor() {
        check("B");
        check("[[[[Z");
        check("[Lde/spricom/sample/Sample_Test$1;");
        assertThat(FieldType.isFieldDescriptor("Lde/spricom/Test")).isFalse();
    }

    private void check(String descriptor) {
        assertThat(FieldType.isFieldDescriptor(descriptor)).as(descriptor).isTrue();
    }
}


text:
<?php
/**
 * Created by Malik Abiola.
 * Date: 10/02/2016
 * Time: 16:10
 * IDE: PhpStorm
 * Create one time transactions.
 */
namespace MAbiola\Paystack\Models;

use MAbiola\Paystack\Abstractions\BaseTransaction;
use MAbiola\Paystack\Contracts\TransactionContract;
use MAbiola\Paystack\Exceptions\PaystackInvalidTransactionException;

class OneTimeTransaction extends BaseTransaction implements TransactionContract
{
    //    protected $transactionResource;

    private $transactionRef;
    private $amount;
    private $email;
    private $plan;

    /**
     * OneTimeTransaction constructor.
     *
     * @param $transactionRef
     * @param $amount
     * @param $email
     * @param $plan
     */
    protected function __construct($transactionRef, $amount, $email, $plan)
    {
        $this->transactionRef = $transactionRef;
        $this->amount = $amount;
        $this->email = $email;
        $this->plan = $plan;

//        $this->transactionResource = $transactionResource;
    }

    /**
     * Make a new one time transaction object.
     *
     * @param $amount
     * @param $email
     * @param $plan
     *
     * @return static
     */
    public static function make($amount, $email, $plan)
    {
        return new static(self::generateTransactionRef(), $amount, $email, $plan);
    }

    /**
     * Initialize one time transaction to get payment url.
     *
     * @return \Exception|mixed|PaystackInvalidTransactionException
     */
    public function initialize()
    {
        return !is_null($this->transactionRef) ?
           $this->getTransactionResource()->initialize($this->_requestPayload()) :
            new PaystackInvalidTransactionException(
                json_decode(
                    json_encode(
                        [
                            'message' => 'Transaction Reference Not Generated.',
                        ]
                    ),
                    false
                )
            );
    }

    /**
     * Get transaction request body.
     *
     * @return string
     */
    public function _requestPayload()
    {
        $payload = [
            'amount'    => $this->amount,
            'reference' => $this->transactionRef,
            'email'     => $this->email,
        ];

        if (!empty($this->plan)) {
            $payload['plan'] = $this->plan;
        }

        return $this->toJson($payload);
    }
}


text:
/**
 * Search
 * For now, not a menu app
 * But, it could get its own page for advanced search
 */
var srch = require('../apps/search/searchmodel'),
    constants = require('../core/constants');

exports.plugin = function(app, environment, ppt, isPrivatePortal) {
	var myEnvironment = environment,
        SearchModel = new srch(environment);

	  function isPrivate(req,res,next) {
		    if (isPrivatePortal) {
		      if (req.isAuthenticated()) {return next();}
		      res.redirect('/login');
			} else {
				{return next();}
			}
		  }

/*	function __get(req,callback) {
		  var query = req.query["srch-term"];
		  SearchModel.runSearch(query, req.user, "en",0,50, function(err,data) {
			  console.log("Search.__get "+err+" "+JSON.stringify(data));
			  var result =  myEnvironment.getCoreUIData(req);
			  result.query = query;
			  //TODO if data, add it to hits;
			  result.hits = data;
			  console.log("Search.__get+ "+JSON.stringify(result));
			  callback( result);
		  });
	} */
  /////////////////
  // Routes
  /////////////////
/*  app.get('/search', function(req,res) {
	  var data = __get(req, function(data) {
		    res.render('searchhits',data);

	  });
  });*/

  app.get("/search", function(req,res) {
	  var query = req.query["srch-term"];
	  console.log("SEARCH "+query);
	  var data = environment.getCoreUIData(req);
	  data.start=0;
	  data.count=constants.MAX_HIT_COUNT; //pagination size
	  data.total=0;
	  data.querystring = query;
	  data.query="/search/index/"+query;
	  res.render('searchhits',data);
  });

  app.get("/search/index/:id", isPrivate,function(req,res) {
	  var q = req.params.id;
	  var start = parseInt(req.query.start);
	  var count = parseInt(req.query.count);
	  SearchModel.runSearch(q, req.user, "en",start,count, function(data, countsent, totalavailable) {
		  var cursor = start+countsent;
		  //} else {
		//	  cursor = start-countsent;
		 // }
		//  if (cursor < 0) {cursor = 0;}
		//  topicMapEnvironment.logDebug("BLOG INDEX2 "+start+" "+countsent+" "+isNext+" "+cursor);
		  var json = {};
		  json.start = cursor;
		  json.count = constants.MAX_HIT_COUNT; //pagination size
		  json.total = totalavailable;
		  json.table = data;
		  try {
			  res.set('Content-type', 'text/json');
		  }  catch (e) { }
	      res.json(json);
	  });
  });

};


text:
import assertString from './util/assertString';

export default function unescape(str) {
  assertString(str);
  return (str.replace(/"/g, '"')
    .replace(/'/g, "'")
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(///g, '/')
    .replace(/\/g, '\\')
    .replace(/`/g, '`')
    .replace(/&/g, '&'));
  // & replacement has to be the last one to prevent
  // bugs with intermediate strings containing escape sequences
  // See: https://github.com/validatorjs/validator.js/issues/1827
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.configure = void 0;
var tslib_1 = require("tslib");
var ok_modal_attribute_1 = require("./resources/ok-modal-attribute");
var dismiss_modal_attribute_1 = require("./resources/dismiss-modal-attribute");
var attach_focus_attribute_1 = require("./resources/attach-focus-attribute");
var ux_modal_configuration_1 = require("./ux-modal-configuration");
var aurelia_framework_1 = require("aurelia-framework");
function configure(frameworkConfig, callback) {
    frameworkConfig.globalResources([
        attach_focus_attribute_1.AttachFocusAttribute,
        dismiss_modal_attribute_1.DismissModalAttribute,
        ok_modal_attribute_1.OkModalAttribute,
        aurelia_framework_1.PLATFORM.moduleName('./ux-modal'),
    ]);
    if (typeof callback === 'function') {
        var config = frameworkConfig.container.get(ux_modal_configuration_1.UxDefaultModalConfiguration);
        callback(config);
    }
}
exports.configure = configure;
var ux_modal_theme_1 = require("./ux-modal-theme");
Object.defineProperty(exports, "UxModalTheme", { enumerable: true, get: function () { return ux_modal_theme_1.UxModalTheme; } });
var ux_modal_1 = require("./ux-modal");
Object.defineProperty(exports, "UxModal", { enumerable: true, get: function () { return ux_modal_1.UxModal; } });
tslib_1.__exportStar(require("./ux-modal-service"), exports);
tslib_1.__exportStar(require("./ux-modal-configuration"), exports);
//# sourceMappingURL=index.js.map


text:
package com.taobao.zeus.store.mysql;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.taobao.zeus.model.DebugHistory;
import com.taobao.zeus.model.JobStatus.Status;
import com.taobao.zeus.store.DebugHistoryManager;
import com.taobao.zeus.store.mysql.persistence.DebugHistoryPersistence;
import com.taobao.zeus.store.mysql.tool.PersistenceAndBeanConvert;

public class MysqlDebugHistoryManager extends HibernateDaoSupport implements DebugHistoryManager{

	@Override
	public DebugHistory addDebugHistory(DebugHistory history) {
		DebugHistoryPersistence persist=PersistenceAndBeanConvert.convert(history);
		getHibernateTemplate().save(persist);
		history.setId(String.valueOf(persist.getId()));
		return history;
	}

	@Override
	public DebugHistory findDebugHistory(String id) {
		DebugHistoryPersistence persist= (DebugHistoryPersistence) getHibernateTemplate().get(DebugHistoryPersistence.class, Long.valueOf(id));
		return PersistenceAndBeanConvert.convert(persist);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DebugHistory> pagingList(final String fileId, final int start, final int limit) {
		return (List<DebugHistory>) getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query query=session.createQuery("select id,fileId,startTime,endTime,executeHost,status,script,log from com.taobao.zeus.store.mysql.persistence.DebugHistoryPersistence" +
						" where fileId=? order by id desc");
				query.setParameter(0, Long.valueOf(fileId));
				query.setMaxResults(limit);
				query.setFirstResult(start);
				List<Object[]> list=query.list();
				List<DebugHistory> result=new ArrayList<DebugHistory>();
				for(Object[] o:list){
					DebugHistory history=new DebugHistory();
					history.setId(String.valueOf(o[0]));
					history.setFileId(String.valueOf(o[1]));
					history.setStartTime((Date) o[2]);
					history.setEndTime((Date) o[3]);
					history.setExecuteHost(String.valueOf(o[4]));
					history.setStatus(o[5]==null?null:Status.parser(String.valueOf(o[5])));
					history.setScript(String.valueOf(o[6]));
					history.setLog(String.valueOf(o[7]));
					result.add(history);
				}
				return result;
			}
		});
	}

	@Override
	public int pagingTotal(String fileId) {
		Number number=(Number) getHibernateTemplate().find("select count(*) from com.taobao.zeus.store.mysql.persistence.DebugHistoryPersistence where fileId="+fileId)
		.iterator().next();
		return number.intValue();
	}

	@Override
	public void updateDebugHistory(DebugHistory history) {
		DebugHistoryPersistence org=(DebugHistoryPersistence) getHibernateTemplate().get(DebugHistoryPersistence.class, Long.valueOf(history.getId()));

		DebugHistoryPersistence persist=PersistenceAndBeanConvert.convert(history);
		persist.setGmtModified(new Date());
		persist.setGmtCreate(org.getGmtCreate());
		persist.setLog(org.getLog());
		getHibernateTemplate().update(persist);
	}

	@Override
	public void updateDebugHistoryLog(final String id,final  String log) {
		getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query query=session.createQuery("update com.taobao.zeus.store.mysql.persistence.DebugHistoryPersistence set log=? where id=?");
				query.setParameter(0, log);
				query.setParameter(1, Long.valueOf(id));
				query.executeUpdate();
				return null;
			}
		});
	}

}


text:
using System.Collections;
using System.Collections.Generic;
using Svg.ExCSS.Model.Extensions;

// ReSharper disable once CheckNamespace
namespace Svg.ExCSS
{
    public class MediaTypeList : IEnumerable<string>
    {
        private readonly List<string> _media;
        private string _buffer;

        internal MediaTypeList()
        {
            _buffer = string.Empty;
            _media = new List<string>();
        }

        public string this[int index]
        {
            get
            {
                if (index < 0 || index >= _media.Count)
                {
                    return null;
                }

                return _media[index];
            }
            set
            {
                _media[index] = value;
            }
        }

        public int Count
        {
            get { return _media.Count; }
        }

        public string MediaType
        {
            get { return _buffer; }
            set
            {
                _buffer = string.Empty;
                _media.Clear();

                if (string.IsNullOrEmpty(value))
                {
                    return;
                }

                var entries = value.SplitOnCommas();

                foreach (var t in entries)
                {
                    AppendMedium(t);
                }
            }
        }

        internal MediaTypeList AppendMedium(string newMedium)
        {
            if (_media.Contains(newMedium))
            {
                return this;
            }

            _media.Add(newMedium);
            _buffer += (string.IsNullOrEmpty(_buffer) ? string.Empty : ",") + newMedium;

            return this;
        }

        public override string ToString()
        {
            return ToString(false);
        }

        public string ToString(bool friendlyFormat, int indentation = 0)
        {
            return friendlyFormat
                ? string.Join(", ", _media.ToArray())
                : string.Join(",", _media.ToArray());
        }

        public IEnumerator<string> GetEnumerator()
        {
            return ((IEnumerable<string>) _media).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


text:
package ua.com.fielden.platform.gis.gps.actors;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;

import org.apache.log4j.Logger;

import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.gis.MapUtils;
import ua.com.fielden.platform.gis.gps.AbstractAvlMachine;
import ua.com.fielden.platform.gis.gps.AbstractAvlMessage;
import ua.com.fielden.platform.persistence.HibernateUtil;
import ua.com.fielden.platform.utils.Pair;
import akka.actor.ActorRef;
import akka.actor.UntypedActor;

/**
 * This actor is responsible for messages processing for concrete machine.
 *
 * @author TG Team
 *
 */
public abstract class AbstractAvlMachineActor<MESSAGE extends AbstractAvlMessage, MACHINE extends AbstractAvlMachine<MESSAGE>> extends UntypedActor {
    private final MessagesComparator<MESSAGE> messagesComparator;
    protected static int jdbcInsertBatchSize = 100;
    private static int windowSize = 5;
    private static int windowSize2 = 10;
    private static int windowSize3 = 30;
    private final Logger logger = Logger.getLogger(AbstractAvlMachineActor.class);

    private MACHINE machine;
    private final LinkedList<Packet<MESSAGE>> incomingPackets = new LinkedList<>();
    private final LinkedList<Packet<MESSAGE>> inspectionBuffer = new LinkedList<>();
    private final Blackout<MESSAGE> blackout;
    private MESSAGE latestGpsMessage;
    private MESSAGE lastProcessedMessage;
    private final HibernateUtil hibUtil;
    private ActorRef machinesCounterRef;

    public AbstractAvlMachineActor(final EntityFactory factory, final MACHINE machine, final MESSAGE lastMessage, final HibernateUtil hibUtil, final ActorRef machinesCounterRef) {
        this.machinesCounterRef = machinesCounterRef;

        messagesComparator = new MessagesComparator<MESSAGE>();
        blackout = new Blackout<MESSAGE>(messagesComparator);

        this.machine = machine;
        this.latestGpsMessage = lastMessage;
        this.lastProcessedMessage = lastMessage;

        this.hibUtil = hibUtil;
        // do not forget to invoke processTempMessages()!
    }

    @Override
    public void preStart() {
        super.preStart();

        machinesCounterRef.tell(new MachineActorStarted(this.machine.getKey(), this.machine.getDesc()), getSelf());
        machinesCounterRef = null;
    }

    protected abstract void processTempMessages(final MACHINE machine) throws Exception;

    protected abstract void persistTemporarily(final Packet<MESSAGE> packet) throws Exception;

    protected abstract void persistError(final Packet<MESSAGE> packet) throws Exception;

    protected abstract void persist(final Collection<MESSAGE> messages, final MESSAGE latestPersistedMessage) throws Exception;

    private Pair<Packet<MESSAGE>, Packet<MESSAGE>> categoriseByViolations(final Packet<MESSAGE> packet, final MESSAGE lastProcesseMessage) {
        if (lastProcesseMessage == null) {
            return new Pair<Packet<MESSAGE>, Packet<MESSAGE>>(packet, null);
        }

        final Packet<MESSAGE> goodPart = new Packet<MESSAGE>(new Date(packet.getCreated()), messagesComparator);
        final Packet<MESSAGE> badPart = new Packet<MESSAGE>(new Date(packet.getCreated()), messagesComparator);

        for (final MESSAGE message : packet.getMessages()) {
            if (message.getGpsTime().getTime() <= lastProcesseMessage.getGpsTime().getTime()) {
                badPart.add(message);
            } else {
                goodPart.add(message);
            }
        }

        return new Pair<Packet<MESSAGE>, Packet<MESSAGE>>(goodPart, badPart);
    }

    protected final void processSinglePacket(final Packet<MESSAGE> originalPacket, final boolean onStart) throws Exception {
        final Pair<Packet<MESSAGE>, Packet<MESSAGE>> categorisedByViolations = categoriseByViolations(originalPacket, lastProcessedMessage);
        final Packet<MESSAGE> packetWithViolatingMessages = categorisedByViolations.getValue();
        if (packetWithViolatingMessages != null && !packetWithViolatingMessages.isEmpty()) {
            persistError(packetWithViolatingMessages);
        }

        final Packet<MESSAGE> packet = categorisedByViolations.getKey();

        if (!packet.isEmpty()) {

            if (latestGpsMessage != null && latestGpsMessage.getGpsTime().getTime() > packet.getStart().getGpsTime().getTime()) {
                for (final MESSAGE message : packet.getMessages()) {
                    if (message.getGpsTime().getTime() < latestGpsMessage.getGpsTime().getTime()) {
                        message.setStatus(1);
                    }
                }
            }

            if (latestGpsMessage == null || latestGpsMessage.getGpsTime().getTime() < packet.getFinish().getGpsTime().getTime()) {
                final MESSAGE oldLatestGpsMessage = latestGpsMessage;
                latestGpsMessage = packet.getFinish();
                processLatestGpsMessage(oldLatestGpsMessage, latestGpsMessage);
            }

            if (!onStart) {
                persistTemporarily(packet);
            }

            incomingPackets.add(packet);
            if (fillBuffer()) {
                final Packet<MESSAGE> first = inspectionBuffer.poll();

                if (blackout.getFinish() != null && blackout.getFinish().getGpsTime().getTime() >= first.getStart().getGpsTime().getTime()) {
                    blackout.add(first);
                } else {
                    final int maximumIndexOfPacketBreakingChronologyOfFirstPacket = findMaximumIndexOfPacketBreakingChronologyOfGivenPacket(first);
                    final boolean blackoutHappened = maximumIndexOfPacketBreakingChronologyOfFirstPacket != -1;
                    if (blackoutHappened) {
                        blackout.add(first);
                        moveFirstPacketsFromBufferIntoBlackout(maximumIndexOfPacketBreakingChronologyOfFirstPacket + 1);
                    } else {
                        final int chronologyBreakingIndex = findMaximumIndexOfNeighboringChronologyBreakingPacket();
                        final boolean validationSucceeded = chronologyBreakingIndex == -1;

                        if (validationSucceeded) {
                            if (blackout.getMessages().size() > 0) {
                                final MESSAGE blackoutLastMessage = blackout.getFinish();
                                final MESSAGE blackoutStart = blackout.getStart();
                                final Collection<MESSAGE> messages = blackout.reset();
                                persist(messages, lastProcessedMessage);
                                lastProcessedMessage = blackoutLastMessage;
                            }
                            persist(first.getMessages(), lastProcessedMessage);
                            lastProcessedMessage = first.getFinish();
                        } else {
                            blackout.add(first);
                            moveFirstPacketsFromBufferIntoBlackout(chronologyBreakingIndex + 1);
                        }
                    }
                }
            }
        }
    }

    /**
     * Provides custom processing action after new 'latest GPS message' has been arrived.
     *
     * @param oldLatestGpsMessage
     * @param newLatestGpsMessage
     */
    protected void processLatestGpsMessage(final MESSAGE oldLatestGpsMessage, final MESSAGE newLatestGpsMessage) {
    }

    @Override
    public void onReceive(final Object data) throws Exception {
        try {
            if (data instanceof Packet) {
                final Packet<MESSAGE> packet = (Packet<MESSAGE>) data;
                for (final MESSAGE message : packet.getMessages()) {
                    completeMessage(message);
                }
                processSinglePacket(packet, false);
            } else if (data instanceof LastMessagesRequest) {
                final LastMessagesRequest lastMessageRequest = (LastMessagesRequest) data;
                // System.out.println("Запит про останнє повідомлення для машини " + machine + " після " + glm.getAfterDate() + ". Received: " + new Date() + " для актора " + getSelf());

                if (latestGpsMessage != null
                        && (lastMessageRequest.getAfterDate() == null || latestGpsMessage.getGpsTime().getTime() > lastMessageRequest.getAfterDate().getTime())) {
                    final MESSAGE lastMessage = completeMessageCopy(produceIncompleteLastMessage(latestGpsMessage), latestGpsMessage);
                    getSender().tell(new LastMessage<MESSAGE>(lastMessageRequest.getMachineId(), lastMessage), getSelf());
                } else {
                    getSender().tell(new NoLastMessage(), getSelf());
                }
            } else if (data instanceof Changed) {
                promoteChangedMachine((Changed<MACHINE>) data);
            } else {
                unhandled(data);
            }
        } catch (final Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    protected void promoteChangedMachine(final Changed<MACHINE> changedMachine) {
        setMachine(changedMachine.getValue());
        logger.info("An existent machine, that has been changed [" + changedMachine.getValue() + "], has been sucessfully promoted to its machine actor.");
    }

    private MESSAGE produceIncompleteLastMessage(final MESSAGE message) {
        final MESSAGE copy = createMessage();
        copy.setX(message.getX());
        copy.setY(message.getY());
        copy.setVectorSpeed(message.getVectorSpeed());
        copy.setVectorAngle(message.getVectorAngle());
        copy.setGpsTime(message.getGpsTime());
        copy.setTravelledDistance(message.getTravelledDistance());
        return copy;
    }

    protected final BigDecimal calcDistance(final MESSAGE prevMessage, final MESSAGE currMessage) {
        return new BigDecimal(MapUtils.calcDistance(prevMessage.getX(), //
                prevMessage.getY(), //
                currMessage.getX(), //
                currMessage.getY())).setScale(2, RoundingMode.HALF_UP);
    }

    private int findMaximumIndexOfPacketBreakingChronologyOfGivenPacket(final Packet<MESSAGE> firstPacket) {
        for (int i = inspectionBuffer.size() - 1; i >= 0; i--) {
            final Packet<MESSAGE> currPacket = inspectionBuffer.get(i);
            if (!(currPacket.getStart().getGpsTime().getTime() > firstPacket.getFinish().getGpsTime().getTime())) {
                return i;
            }
        }
        return -1;
    }

    private int findMaximumIndexOfNeighboringChronologyBreakingPacket() {
        Date prevPacketStart = inspectionBuffer.get(inspectionBuffer.size() - 1).getStart().getGpsTime();
        for (int i = inspectionBuffer.size() - 2; i >= 0; i--) {
            final Packet<MESSAGE> currPacket = inspectionBuffer.get(i);
            if (!(currPacket.getFinish().getGpsTime().getTime() < prevPacketStart.getTime())) {
                return i + 1;
            }
            prevPacketStart = currPacket.getStart().getGpsTime();
        }
        return -1;
    }

    private void moveFirstPacketsFromBufferIntoBlackout(final int qty) {
        for (int index = 0; index < qty; index++) {
            final Packet<MESSAGE> packet = inspectionBuffer.poll();
            blackout.add(packet);
        }
    }

    private boolean fillBuffer() {
        int index = 1;
        final int limit = calcNewWindowSize(calcAvgPacketSize()) - inspectionBuffer.size();

        while (index <= limit) {
            final Packet<MESSAGE> p = incomingPackets.poll();
            if (p != null) {
                inspectionBuffer.add(p);
            } else {
                return false;
            }

            index = index + 1;
        }
        return true;
    }

    private float calcAvgPacketSize() {
        if (inspectionBuffer.size() == 0) {
            return 0;
        }

        Integer totalSize = 0;
        for (final Packet<MESSAGE> packet : inspectionBuffer) {
            totalSize = totalSize + packet.getMessages().size();
        }
        return totalSize / inspectionBuffer.size();
    }

    private int calcNewWindowSize(final float recentAvgPacketSize) {
        if (recentAvgPacketSize < 1.1) {
            return windowSize;
        } else if (recentAvgPacketSize < 1.3) {
            return windowSize2;
        } else {
            return windowSize3;
        }
    }

    /**
     * A method to create empty GPS message.
     *
     * @return
     */
    protected abstract MESSAGE createMessage();

    /**
     * A method to fill GPS message with client-specific data.
     *
     * @param message
     * @return
     */
    protected abstract MESSAGE completeMessage(final MESSAGE message);

    /**
     * A method to fill GPS message with client-specific data.
     *
     * @param populateData
     * @return
     */
    protected abstract MESSAGE completeMessageCopy(final MESSAGE populateData, final MESSAGE messageToCopyFrom);

    protected MACHINE getMachine() {
        return machine;
    }

    protected void setMachine(final MACHINE machine) {
        this.machine = machine;
    }

    protected HibernateUtil getHibUtil() {
        return hibUtil;
    }

    public MessagesComparator<MESSAGE> getMessagesComparator() {
        return messagesComparator;
    }
}


text:
package chain

type Handler interface {
	Handle(i *Invocation)
}


text:
""" Utility module handle program args and give help

    --------------------------------------------------------------------------
    File:     utilsArgsParse.py

    Overview:  Python module to parse and validate program parameters
               against those required by the program whether mandatory
               or optional.
               Also give help information on arguments required by the
               program.

    Gotchas:   None.

    Copyright: None.
    --------------------------------------------------------------------------

"""

# Python modules:
import getopt  # Parse command line arguments

# Third party modules:

# In-house modules:

# Instantiations:

# User facing text:
strMsgErrorInvalidParameters = "Invalid parameters entered, -h for help. \nYou entered:\n"
strMsgErrorInvalidNoParams = "No parameters entered, -h for help\n"
strMsgErrorNumberParameters = "Number of parameters entered incorrect, %d parameters required. You entered:\n"
strMsgArgFileNotImplemented = "Sorry the --argFile is not implemented"

#++---------------------------------------------------------------------------
# Details: Validate the arguments passed in against the mandatory and
#          optional arguments specified. The argument format for the parameters
#          is required to work with the module getopt function getopt().
#          Parameter vDictArgReq specifies which parameters are mandatory and
#          which are optional. The format is for example:
#            dictArgReq = {"-h": "o", # o = optional, m = mandatory
#                          "-m": "m",
#                          "--targetDir": "m",
#                          "--cfgBldDir": "o" }
# Args:    vArgv - (R) List of arguments and values.
#          vstrListArgs - (R) List of small arguments.
#          vListLongArgs - (R) List of long arguments.
#          vDictArgReq - (R) Map of arguments required.
#          vstrHelpInfo - (R) Formatted help text.
# Returns: Int - 0 success.
#                1 success display information, do nothing else.
#                -1 error invalid parameters.
#                -2 error incorrect number of mandatory parameters.
#          Dict - Map of arguments names to argument values
#          Str - Error message.
# Throws:  None.
#--

def parse(vArgv, vstrListArgs, vListLongArgs, vDictArgReq, vstrHelpInfo):
    dictArgs = {}
    dictDummy = {}
    strDummy = ""

    # Validate parameters above and error on not recognised
    try:
        dictOptsNeeded, dictArgsLeftOver = getopt.getopt(vArgv,
                                                         vstrListArgs,
                                                         vListLongArgs)
    except getopt.GetoptError:
        strMsg = strMsgErrorInvalidParameters
        strMsg += str(vArgv)
        return (-1, dictDummy, strMsg)

    if len(dictOptsNeeded) == 0:
        strMsg = strMsgErrorInvalidNoParams
        return (-1, dictDummy, strMsg)

    # Look for help -h before anything else
    for opt, arg in dictOptsNeeded:
        if opt == '-h':
            return (1, dictDummy, vstrHelpInfo)

    # Look for the --argFile if found ignore other command line arguments
    for opt, arg in dictOptsNeeded:
        if opt == '--argsFile':
            return (1, dictDummy, strMsgArgFileNotImplemented)

    # Count the number of mandatory args required (if any one found)
    countMandatory = 0
    for opt, man in list(vDictArgReq.items()):
        if man == "m":
            countMandatory = countMandatory + 1

    # Extract short args
    listArgs = []
    for arg in vstrListArgs:
        if (arg == '-h') or (arg == ':'):
            continue
        listArgs.append(arg)

    # Append to arg dictionary the option and its value
    bFoundNoInputValue = False
    countMandatoryOpts = 0
    for opt, val in dictOptsNeeded:
        match = 0
        for arg in listArgs:
            argg = "-" + arg
            if opt == argg:
                if "m" == vDictArgReq[opt]:
                    countMandatoryOpts = countMandatoryOpts + 1
                dictArgs[opt] = val
                match = 1
                break
        if match == 0:
            for arg in vListLongArgs:
                argg = "--" + arg.rstrip('=')
                if opt == argg:
                    if "m" == vDictArgReq[opt]:
                        countMandatoryOpts = countMandatoryOpts + 1
                    dictArgs[opt] = val
                    if arg[-1:] == '=' and val.__len__() == 0:
                        bFoundNoInputValue = True
                    break

    # Do any of the long arguments not have a value attached
    if bFoundNoInputValue:
        strMsg = strMsgErrorInvalidParameters
        strMsg += str(vArgv)
        return (-1, dictDummy, strMsg)

    # Debug only
    # print countMandatoryOpts
    # print countMandatory

    # Do we have the exact number of mandatory arguments
    if (countMandatoryOpts > 0) and (countMandatory != countMandatoryOpts):
        strMsg = strMsgErrorNumberParameters % countMandatory
        strMsg += str(vArgv)
        return (-2, dictDummy, strMsg)

    return (0, dictArgs, strDummy)


text:
Announcing the release of Greek Bible (Version 1):

#### Links:

- [Greek Bible App](http://www.toldpro.com/Apps/GreekBible/V1/)
- [GitHub Source Code](https://github.com/ricklove/GreekBibleApp/tree/ReleaseV1)
- [PhoneGap - Latest Version](https://build.phonegap.com/apps/783113/install)

#### Screenshots

![](http://3.bp.blogspot.com/-K8XN4KrXizM/UvhqtHBgsgI/AAAAAAAAAZU/y60uVKzaRHY/s1600/image-756633.png)
![](http://3.bp.blogspot.com/-K8XN4KrXizM/UvhqtHBgsgI/AAAAAAAAAZU/y60uVKzaRHY/s320/image-756633.png)
![](http://3.bp.blogspot.com/--b4054jPFsI/UvhqtnqWfJI/AAAAAAAAAZg/PDIFSp0G1uU/s1600/image-758332.png)
![](http://3.bp.blogspot.com/--b4054jPFsI/UvhqtnqWfJI/AAAAAAAAAZg/PDIFSp0G1uU/s320/image-758332.png)
![](http://3.bp.blogspot.com/-MuUG4dCEUF0/UvhquNIcl5I/AAAAAAAAAZs/5hOgW8uDy28/s1600/image-760743.png)
![](http://3.bp.blogspot.com/-MuUG4dCEUF0/UvhquNIcl5I/AAAAAAAAAZs/5hOgW8uDy28/s320/image-760743.png)

#### Summary

Greek Bible displays the Greek New Testament with color coded morphology.

The color cording allows the reader to quickly see associated words in the greek text.

#### Features
- Read the Greek of any New Testament Book from the SBL Greek New Testament
- View details for each word:
	- View the Lemma (the root word)
	- View the Part of Speech
	- View the Morphology
- View the color coding for the Part of Speech and Morpology to quickly see associated words

##### MorphGNT

The MorphGNT includes a parsed morphological tagging of the SBL Greek New Testament.
This work was created by James Tauber as part of his doctorite in linguistics.

More information about MorphGNT is found at:
[http://morphgnt.org]()

##### The SBL Greek New Testament

With the work of textual criticism far from complete, there is a continual need for fresh research and analysis.
The SBLGNT, edited by Michael W. Holmes, utilizes a wide range of printed editions, all the major critical apparatuses,
and the latest technical resources and manuscript discoveries to establish the text.

The result is a critically edited text that differs from the Nestle-Aland/United Bible Societies text in more than 540 variation units.

More information about the SBL Greek New Testament is found at:
[http://sblgnt.com]()

#### License

##### Attribution
- MorphGNT
	- MorphGNT.org
- SBL Greek New Testament
	- Copyright 2010 by the Society of Biblical Literature and Logos Bible Software
	- SBL Greek New Testament: [http://sblgnt.com]()
	- Society of Biblical Literature: [http://www.sbl-site.org]()
	- Logos Bible Software: [http://www.logos.com]()

---

### Developer Notes

#### Overview

The project was a great success for my first 5HourApp. Although, it took about 8 hours plus some extra time researching tools and setting up the environment.

I was able to rewrite the entire GreekBible. I only used a few pieces of logic from the oldGreekBible.
It was unneccesary to reuse code because the frameworks I used actually made the code very simple to write from scratch.

Bottom Line: I was able to write a $5,000 web app that runs everywhere in about 8 hours. That's not bad!

##### 5-Hour App

This proves that the 5HourApp concept is valid. I can actually create a fully functioning app to release in around 5 hours.
The important part is to trim features and identify the most important user features to implement.

##### Feature Oriented Software Development

I feature organized my code files. This enabled me to focus on one feature at a time. It also allowed me to have a good separation of concerns between user features
and the underlying system features that they need to function.

I identified two possible ways to divide a ViewModel across multiple files. In this project I used a mainViewState with a sub object for each feature.

An alternative would be to use typescript interfaces and a static object that is gradually implemented.

##### KnockoutJS

KnockoutJS is great! This was my first time to use it and it was a pleasure. I highly recommend it! I will be using it as my UI framework of choice.

##### jQueryMobile

jQueryMobile worked fine with all the defaults in place.
However, one bug cost me about an hour because the generated jQueryMobile UI did not match the native UI behind it.

Next time something is not changing, inspect the DOM and see if there is a lone SPAN tag that doesn't match the actual $(element).val() or $(element).text().
Ensure that the proper refresh call is being made for jQueryMobile, which is different for each element type.

I created a refreshJQM Knockout binding to deal with this. I will expand it to automatically call the proper refresh code according to the bound element type.

#### File Structure

- Notes
	- Developer Notes
		- Required Tools
		- Setup
		- Interesting Techniques
	- Release Notes
		- Summary
		- Feature Descriptions
		- Version Changes
	- ScreenShots
- Scripts
	- js
		- Javascript Source Files (Not Generated)
		- External: Code from outside sources and libraries
	- ts
		- TypeScript
		- *.ts files: TypeScript Source Code
		- *.js files: Generated Javascript
		- External: Code from outside sources and libraries
		- Core: Definitions for core types
		- System: Features that are invisible to the user, but provide functionality for the User Features
		- User: Features which represent the user tasks and concerns
- Styles
	- css
		- CSS Source Files (not generated)
	- sass
		- Sass Files created using Compass
		- *.scss - Sassy CSS source
		- *.css - Generated CSS

#### Environment & Project Setup (Pre-Project)

##### Tools

- Visual Studio Express 2012 - Web
- Git Extensions for Windows
- TypeScript for VS
	- To Enable Compile on Save:
		- Tools/Options
		- > Text Editor/TypeScript/Project/General
		- > Automatically Compile...
	- TODO: Create a bat file to produce one js file for release (Indivudual files is good during Testing)
- NuGet Package Manager - VS Extension
- FAIL: Chutzpah Console (Extensions not Enabled for VS Express)
	- Download Console and unzipped to my Tools Folder
	- Created a bat file to run all the tests in the ts directory
		- chutzpah.console.exe ../WebSite/Scripts/ts /testMode TypeScript /openInBrowser
	- FAIL: This takes a long time to run and it failed to run a valid test. Testing in browser with a qunit tag enables debugging in browser and is fast.

##### Libraries

- jQuery Mobile
	- Copied Code from Demo to get started
		- jQuery.js
		- jQueryMobile.js
		- Default Theme Css
		- Images
	- TypeScript Definitions
		- NuGet PM> Install-Package jquery.TypeScript.DefinitelyTyped
		- FAILED: NuGet PM> Install-Package jquerymobile.TypeScript.DefinitelyTyped
		- NuGet PM> Install-Package jquerymobile.TypeScript.DefinitelyTyped -Version 0.1.2
- QUnit
	- QUnit JS & CSS
	- TypeScript Definitions
		- NuGet PM> Install-Package qunit.TypeScript.DefinitelyTyped

- KnockoutJS
	- knockout JS
	- TypeScript Definitions
		- NuGet PM> Install-Package knockout.TypeScript.DefinitelyTyped

- LinqJS
	- linq JS
	- TypeScript Definitions
		- NuGet PM> Install-Package linq.TypeScript.DefinitelyTyped

#### Future

- QUnit Pavlov Plugin - BDD
	- This looks like a good plugin to enable Behavior Driven Design language for QUnit tests
	- Would Require a TypeScript Definition File to be created

#### Bugs

- BUG: jQueryMobile was not updating the visible part of a select element (the native element was being updated, but the span on top was remaining an old value)
	- FIX: (<any>$(element)).selectmenu('refresh');
- FAIL: Chutzpah Console caused wasted time and is unneccessary

---

### Work Hours

#### Hour 1

- Created the structure for the DisplayGreekText feature
- Problems:
	- Running the qunit test for loading the sample text fails using Chutzpah

#### Hour 2

- Parsed the data from a chapter of text
	- Used oldGreekBible's parsing code as a starting place
- Passing Tests

#### Hour 3

- Displayed the passage text on screen with the details
	- Used oldGreekBible's formatting of the details

#### Hour 4

- Started to implement ChoosePassage
- Problems:
	- TypeScript does not support Partial classes, so had to pause to think about how to implement that
	- Slow Today
	- Not finished implementing ChoosePassage

#### Hour 5

- Divided Data into Chapters
- Binding Book and Chapter values to UI
- Triggering Reload on Book/Chapter change
- Started: Debugging UI binding
- Started: LoadPassage

#### Hour 6

- BUG: Chapter Select was not updating
	- FIX (1 hour): Finally discovered it was jQueryMobile not refreshing the UI

#### Hour 7

- Display Color Coding
- Finished Up Tasks
- Removed Unprintable Characters
- Removed QUnit results

#### Hour 8

##### Goals:
- [X] Display Verse Numbers
- [X] Create Release Branch
- [X] Write Blog
- [X] Publish
- [X] Publish Blog


text:
module GenreConcern
  extend ActiveSupport::Concern

  included do
    helper_method :favorite_or_unfavorite_genre
    helper_method :favorite_genre_transaction
  end

  def favorite_genre_transaction(student, genre)
    @favorite_genre_transaction = FavoriteGenre.where(genre_id: genre.id).where(student_id: current_student.id).order(:id).last
  end

  def favorite_or_unfavorite_genre(student, genre)
    if favorite_genre_transaction(student, genre)
      if favorite_genre_transaction(student, genre).favorite == true
        @favorite_or_unfavorite_genre = "favorite"
      else
        @favorite_or_unfavorite_genre = "unfavorite"
      end
    else
      @favorite_or_unfavorite_genre = "unfavorite"
    end
  end
end