text:
"use strict";

const {strict: assert} = require("assert");

const _ = require("lodash");

const {set_global, with_field, zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

set_global("document", {});
const util = zrequire("util");

run_test("CachedValue", () => {
    let x = 5;

    const cv = new util.CachedValue({
        compute_value() {
            return x * 2;
        },
    });

    assert.equal(cv.get(), 10);

    x = 6;
    assert.equal(cv.get(), 10);
    cv.reset();
    assert.equal(cv.get(), 12);
});

run_test("get_reload_topic", () => {
    assert.equal(util.get_reload_topic({subject: "foo"}), "foo");
    assert.equal(util.get_reload_topic({topic: "bar"}), "bar");
});

run_test("extract_pm_recipients", () => {
    assert.equal(util.extract_pm_recipients("bob@foo.com, alice@foo.com").length, 2);
    assert.equal(util.extract_pm_recipients("bob@foo.com, ").length, 1);
});

run_test("is_pm_recipient", () => {
    const message = {to_user_ids: "31,32,33"};
    assert.ok(util.is_pm_recipient(31, message));
    assert.ok(util.is_pm_recipient(32, message));
    assert.ok(!util.is_pm_recipient(34, message));
});

run_test("lower_bound", () => {
    let arr = [10, 20, 30, 40, 50];
    assert.equal(util.lower_bound(arr, 5), 0);
    assert.equal(util.lower_bound(arr, 10), 0);
    assert.equal(util.lower_bound(arr, 15), 1);
    assert.equal(util.lower_bound(arr, 50), 4);
    assert.equal(util.lower_bound(arr, 55), 5);

    arr = [{x: 10}, {x: 20}, {x: 30}];

    function compare(a, b) {
        return a.x  {
    assert.ok(
        util.same_recipient(
            {type: "stream", stream_id: 101, topic: "Bar"},
            {type: "stream", stream_id: 101, topic: "bar"},
        ),
    );

    assert.ok(
        !util.same_recipient(
            {type: "stream", stream_id: 101, topic: "Bar"},
            {type: "stream", stream_id: 102, topic: "whatever"},
        ),
    );

    assert.ok(
        util.same_recipient(
            {type: "private", to_user_ids: "101,102"},
            {type: "private", to_user_ids: "101,102"},
        ),
    );

    assert.ok(
        !util.same_recipient(
            {type: "private", to_user_ids: "101,102"},
            {type: "private", to_user_ids: "103"},
        ),
    );

    assert.ok(
        !util.same_recipient({type: "stream", stream_id: 101, topic: "Bar"}, {type: "private"}),
    );

    assert.ok(!util.same_recipient({type: "private", to_user_ids: undefined}, {type: "private"}));

    assert.ok(!util.same_recipient({type: "unknown type"}, {type: "unknown type"}));

    assert.ok(!util.same_recipient(undefined, {type: "private"}));

    assert.ok(!util.same_recipient(undefined, undefined));
});

run_test("robust_uri_decode", () => {
    assert.equal(util.robust_uri_decode("xxx%3Ayyy"), "xxx:yyy");
    assert.equal(util.robust_uri_decode("xxx%3"), "xxx");

    let error_message;
    with_field(
        global,
        "decodeURIComponent",
        () => {
            throw new Error("foo");
        },
        () => {
            try {
                util.robust_uri_decode("%E0%A4%A");
            } catch (error) {
                error_message = error.message;
            }
        },
    );

    assert.equal(error_message, "foo");
});

run_test("dumb_strcmp", () => {
    with_field(Intl, "Collator", undefined, () => {
        const strcmp = util.make_strcmp();
        assert.equal(strcmp("a", "b"), -1);
        assert.equal(strcmp("c", "c"), 0);
        assert.equal(strcmp("z", "y"), 1);
    });
});

run_test("get_edit_event_orig_topic", () => {
    assert.equal(util.get_edit_event_orig_topic({orig_subject: "lunch"}), "lunch");
});

run_test("get_edit_event_prev_topic", () => {
    assert.equal(util.get_edit_event_prev_topic({prev_subject: "dinner"}), "dinner");
});

run_test("is_mobile", () => {
    window.navigator = {userAgent: "Android"};
    assert.ok(util.is_mobile());

    window.navigator = {userAgent: "Not mobile"};
    assert.ok(!util.is_mobile());
});

run_test("array_compare", () => {
    assert.ok(util.array_compare([], []));
    assert.ok(util.array_compare([1, 2, 3], [1, 2, 3]));
    assert.ok(!util.array_compare([1, 2], [1, 2, 3]));
    assert.ok(!util.array_compare([1, 2, 3], [1, 2]));
    assert.ok(!util.array_compare([1, 2, 3, 4], [1, 2, 3, 5]));
});

run_test("normalize_recipients", () => {
    assert.equal(
        util.normalize_recipients("ZOE@foo.com, bob@foo.com, alice@foo.com, AARON@foo.com "),
        "aaron@foo.com,alice@foo.com,bob@foo.com,zoe@foo.com",
    );
});

run_test("random_int", () => {
    const min = 0;
    const max = 100;

    _.times(500, () => {
        const val = util.random_int(min, max);
        assert.ok(min <= val);
        assert.ok(val <= max);
        assert.equal(val, Math.floor(val));
    });
});

run_test("all_and_everyone_mentions_regexp", () => {
    const messages_with_all_mentions = [
        "@**all**",
        "some text before @**all** some text after",
        "@**all** some text after only",
        "some text before only @**all**",
    ];

    const messages_with_everyone_mentions = [
        "@**everyone**",
        "some text before @**everyone** some text after",
        "@**everyone** some text after only",
        "some text before only @**everyone**",
    ];

    const messages_with_stream_mentions = [
        "@**stream**",
        "some text before @**stream** some text after",
        "@**stream** some text after only",
        "some text before only @**stream**",
    ];

    const messages_without_all_mentions = [
        "@all",
        "some text before @all some text after",
        "`@everyone`",
        "some_email@everyone.com",
        "`@**everyone**`",
        "some_email@**everyone**.com",
    ];

    const messages_without_everyone_mentions = [
        "some text before @everyone some text after",
        "@everyone",
        "`@everyone`",
        "some_email@everyone.com",
        "`@**everyone**`",
        "some_email@**everyone**.com",
    ];

    const messages_without_stream_mentions = [
        "some text before @stream some text after",
        "@stream",
        "`@stream`",
        "some_email@stream.com",
        "`@**stream**`",
        "some_email@**stream**.com",
    ];

    let i;
    for (i = 0; i < messages_with_all_mentions.length; i += 1) {
        assert.ok(util.find_wildcard_mentions(messages_with_all_mentions[i]));
    }

    for (i = 0; i < messages_with_everyone_mentions.length; i += 1) {
        assert.ok(util.find_wildcard_mentions(messages_with_everyone_mentions[i]));
    }

    for (i = 0; i < messages_with_stream_mentions.length; i += 1) {
        assert.ok(util.find_wildcard_mentions(messages_with_stream_mentions[i]));
    }

    for (i = 0; i < messages_without_all_mentions.length; i += 1) {
        assert.ok(!util.find_wildcard_mentions(messages_without_everyone_mentions[i]));
    }

    for (i = 0; i < messages_without_everyone_mentions.length; i += 1) {
        assert.ok(!util.find_wildcard_mentions(messages_without_everyone_mentions[i]));
    }

    for (i = 0; i < messages_without_stream_mentions.length; i += 1) {
        assert.ok(!util.find_wildcard_mentions(messages_without_stream_mentions[i]));
    }
});

run_test("move_array_elements_to_front", () => {
    const strings = ["string1", "string3", "string2", "string4"];
    const strings_selection = ["string4", "string1"];
    const strings_expected = ["string1", "string4", "string3", "string2"];
    const strings_no_selection = util.move_array_elements_to_front(strings, []);
    const strings_no_array = util.move_array_elements_to_front([], strings_selection);
    const strings_actual = util.move_array_elements_to_front(strings, strings_selection);
    const emails = [
        "test@zulip.com",
        "test@test.com",
        "test@localhost",
        "test@invalid@email",
        "something@zulip.com",
    ];
    const emails_selection = ["test@test.com", "test@localhost", "test@invalid@email"];
    const emails_expected = [
        "test@test.com",
        "test@localhost",
        "test@invalid@email",
        "test@zulip.com",
        "something@zulip.com",
    ];
    const emails_actual = util.move_array_elements_to_front(emails, emails_selection);
    assert.deepEqual(strings_no_selection, strings);
    assert.deepEqual(strings_no_array, []);
    assert.deepEqual(strings_actual, strings_expected);
    assert.deepEqual(emails_actual, emails_expected);
});

run_test("clean_user_content_links", () => {
    window.location.href = "http://zulip.zulipdev.com/";
    window.location.origin = "http://zulip.zulipdev.com";
    assert.equal(
        util.clean_user_content_links(
            'good ' +
                'upload ' +
                'invalid ' +
                'unsafe ' +
                'fragment',
        ),
        'good ' +
            'upload ' +
            "invalid " +
            "unsafe " +
            'fragment',
    );
});


text:
<?php

namespace Drupal\Core\TypedData\Plugin\DataType;

use Drupal\Core\TypedData\PrimitiveBase;
use Drupal\Core\TypedData\Type\StringInterface;

/**
 * The string data type.
 *
 * The plain value of a string is a regular PHP string. For setting the value
 * any PHP variable that casts to a string may be passed.
 *
 * @DataType(
 *   id = "string",
 *   label = @Translation("String")
 * )
 */
class StringData extends PrimitiveBase implements StringInterface {

  /**
   * {@inheritdoc}
   */
  public function getCastedValue() {
    return $this->getString();
  }

}

redpajama_set_name: RedPajamaGithub


text:
package nl.dirkkok.chemicalcraft.gui;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import nl.dirkkok.chemicalcraft.tileentity.ChemistryStandEntity;

public class ModGuiHandler implements IGuiHandler {
	public static final int CHEMISTRY_STAND_ENTITY_GUI = 0;
	public static final int ELECTROLYSIS_STAND_ENTITY_GUI = 1;

	@Override
	public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
		if (ID == CHEMISTRY_STAND_ENTITY_GUI)
			return new ContainerChemistryStandEntity(player.inventory,
													(ChemistryStandEntity) world.getTileEntity(new BlockPos(x, y, z)));
		else if (ID == ELECTROLYSIS_STAND_ENTITY_GUI)
			return new ContainerChemistryStandEntity(player.inventory,
					(ChemistryStandEntity) world.getTileEntity(new BlockPos(x, y, z)));

		return null;
	}

	@Override
	public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
		if (ID == CHEMISTRY_STAND_ENTITY_GUI)
			return new GuiChemistryStandEntity(player.inventory,
											  (ChemistryStandEntity) world.getTileEntity(new BlockPos(x, y, z)));
		else if (ID == ELECTROLYSIS_STAND_ENTITY_GUI)
			return new GuiChemistryStandEntity(player.inventory,
					(ChemistryStandEntity) world.getTileEntity(new BlockPos(x, y, z)));

		return null;
	}
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { inject, customElement } from 'aurelia-framework';
import { getLogger } from 'aurelia-logging';
var MdcDrawerPermanent = (function () {
    function MdcDrawerPermanent(element) {
        this.element = element;
        this.log = getLogger('mdc-drawer-permanent');
    }
    MdcDrawerPermanent.prototype.bind = function () { };
    MdcDrawerPermanent.prototype.attached = function () { };
    MdcDrawerPermanent = __decorate([
        customElement('mdc-drawer-permanent'),
        inject(Element),
        __metadata("design:paramtypes", [Element])
    ], MdcDrawerPermanent);
    return MdcDrawerPermanent;
}());
export { MdcDrawerPermanent };


text:
package net.firejack.platform.core.model.registry;

public interface IAllowDrag {
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="vibrate">
        <note>
            Frames file for 'vibrate' based on sentences in wsj.  Verbnet
            entries 47.3, 45.4; Framenet entry Move in place.
        </note>

        <roleset id="vibrate.01" name="(cause to) vibrate" vncls="47.3 45.4">
            <roles>
                <role descr="causer of vibration (rare)" n="0">
                    <vnrole vncls="47.3" vntheta="Agent"/><vnrole vncls="45.4" vntheta="Agent"/>
                </role>
                <role descr="thing vibrating" n="1">
                    <vnrole vncls="47.3" vntheta="Theme"/><vnrole vncls="45.4" vntheta="Patient"/>
                </role>
            </roles>

            <example name="ergative">
                <inflection aspect="ns" form="gerund" person="ns" tense="present" voice="active"/>
                <text>
                    The ghostly footsteps: ``Interstate 64 is a block away, and heavy
                    traffic can sure set [a house]-1 to *trace*-1 vibrating.''
                </text>
                <arg n="1">*trace*</arg>
                <rel>vibrating</rel>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
typedef enum {
    // TODO: Arrange these in trigonometric order.
    BodySystemTypeDigestive,
    BodySystemTypeUrinary,
    BodySystemTypeRespiratory,
    BodySystemTypeCirculatory,
    BodySystemTypeReproductive,
    BodySystemTypeMuscular,
    BodySystemTypeSkeletal,
    BodySystemTypeIntegumentary,
    BodySystemTypeNervous,
    BodySystemTypeEndocrine
} BodySystemType;

@interface Environment : NSObject

@property (nonatomic, assign) BodySystemType bodySystemType;
//@property (nonatomic, strong) ;

- (id)initWithBodySystemType:(BodySystemType)type;

@end


text:
Custom Day

{{::getMonthName(month)}}

                    {{::day}}

    <button type="button" class="primary-button" ng-click="GenerateMoreDays()">
        Show more
    </button>


text:
"use strict";

var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

var assert = _interopRequire(require("assert"));

var find = _interopRequire(require("./"));

var odd = function (x) {
  return x & 1;
};

it("fj-find", function () {
  assert.deepEqual(find(odd, [1, 2, 3]), 1);
  var findOdd = find(odd);
  assert.deepEqual(findOdd([1, 2, 3]), 1);
});


text:
using ::testing::_;
using ::testing::Invoke;
using ::testing::NotNull;
using ::testing::Return;

namespace media {

MockPipelineClient::MockPipelineClient() {}
MockPipelineClient::~MockPipelineClient() {}

MockPipeline::MockPipeline() {}
MockPipeline::~MockPipeline() {}

void MockPipeline::Start(Demuxer* demuxer,
                         std::unique_ptr<Renderer> renderer,
                         Client* client,
                         const PipelineStatusCB& seek_cb) {
  Start(demuxer, &renderer, client, seek_cb);
}

void MockPipeline::Resume(std::unique_ptr<Renderer> renderer,
                          base::TimeDelta timestamp,
                          const PipelineStatusCB& seek_cb) {
  Resume(&renderer, timestamp, seek_cb);
}

MockDemuxer::MockDemuxer() {}

MockDemuxer::~MockDemuxer() {}

std::string MockDemuxer::GetDisplayName() const {
  return "MockDemuxer";
}

MockDemuxerStream::MockDemuxerStream(DemuxerStream::Type type)
    : type_(type), liveness_(LIVENESS_UNKNOWN) {
}

MockDemuxerStream::~MockDemuxerStream() {}

DemuxerStream::Type MockDemuxerStream::type() const {
  return type_;
}

DemuxerStream::Liveness MockDemuxerStream::liveness() const {
  return liveness_;
}

AudioDecoderConfig MockDemuxerStream::audio_decoder_config() {
  DCHECK_EQ(type_, DemuxerStream::AUDIO);
  return audio_decoder_config_;
}

VideoDecoderConfig MockDemuxerStream::video_decoder_config() {
  DCHECK_EQ(type_, DemuxerStream::VIDEO);
  return video_decoder_config_;
}

void MockDemuxerStream::set_audio_decoder_config(
    const AudioDecoderConfig& config) {
  DCHECK_EQ(type_, DemuxerStream::AUDIO);
  audio_decoder_config_ = config;
}

void MockDemuxerStream::set_video_decoder_config(
    const VideoDecoderConfig& config) {
  DCHECK_EQ(type_, DemuxerStream::VIDEO);
  video_decoder_config_ = config;
}

void MockDemuxerStream::set_liveness(DemuxerStream::Liveness liveness) {
  liveness_ = liveness;
}

VideoRotation MockDemuxerStream::video_rotation() {
  return VIDEO_ROTATION_0;
}

std::string MockVideoDecoder::GetDisplayName() const {
  return "MockVideoDecoder";
}

MockVideoDecoder::MockVideoDecoder() {
  ON_CALL(*this, CanReadWithoutStalling()).WillByDefault(Return(true));
}

std::string MockAudioDecoder::GetDisplayName() const {
  return "MockAudioDecoder";
}

MockVideoDecoder::~MockVideoDecoder() {}

MockAudioDecoder::MockAudioDecoder() {}

MockAudioDecoder::~MockAudioDecoder() {}

MockRendererClient::MockRendererClient() {}

MockRendererClient::~MockRendererClient() {}

MockVideoRenderer::MockVideoRenderer() {}

MockVideoRenderer::~MockVideoRenderer() {}

MockAudioRenderer::MockAudioRenderer() {}

MockAudioRenderer::~MockAudioRenderer() {}

MockRenderer::MockRenderer() {}

MockRenderer::~MockRenderer() {}

MockTimeSource::MockTimeSource() {}

MockTimeSource::~MockTimeSource() {}

MockTextTrack::MockTextTrack() {}

MockTextTrack::~MockTextTrack() {}

MockDecryptor::MockDecryptor() {}

MockDecryptor::~MockDecryptor() {}

MockCdmContext::MockCdmContext() {}

MockCdmContext::~MockCdmContext() {}

int MockCdmContext::GetCdmId() const {
  return CdmContext::kInvalidCdmId;
}

}  // namespace media


text:
'use strict';

function itShouldReturnEmptyString (fn) {
  it('should return an empty string when given a faulsy value', function () {
    expect(fn(null)).toBe('');
    expect(fn('')).toBe('');
  });
}

describe('bcCountries.getIso2CodeByDigits(digits)', function () {

  itShouldReturnEmptyString(bcCountries.getIso2CodeByDigits);

  it('should return country code when given an exact dial code', function () {
    expect(bcCountries.getIso2CodeByDigits('966')).toEqual('sa');
    expect(bcCountries.getIso2CodeByDigits('44')).toEqual('gb');

    expect(bcCountries.getIso2CodeByDigits('1684')).toEqual('as');
    expect(bcCountries.getIso2CodeByDigits('1')).toEqual('us');
  });

  it('should return country code when given digits that start with the dial code', function () {
    expect(bcCountries.getIso2CodeByDigits('9665124478564')).toEqual('sa');
    expect(bcCountries.getIso2CodeByDigits('44452218321')).toEqual('gb');
    expect(bcCountries.getIso2CodeByDigits('16842178')).toEqual('as');
    expect(bcCountries.getIso2CodeByDigits('14455')).toEqual('us');
  });

  it('should return an empty string when given digits that do not start with a dial code', function () {
    expect(bcCountries.getIso2CodeByDigits('99999')).toEqual('');
    expect(bcCountries.getIso2CodeByDigits('044')).toEqual('');
  });
});

describe('bcCountries.getDialCodeByDigits(digits)', function () {

  itShouldReturnEmptyString(bcCountries.getDialCodeByDigits);

  it('should return dial code when given an exact dial code', function () {
    expect(bcCountries.getDialCodeByDigits('966')).toEqual('966');
    expect(bcCountries.getDialCodeByDigits('44')).toEqual('44');

    expect(bcCountries.getDialCodeByDigits('1684')).toEqual('1684');
    expect(bcCountries.getDialCodeByDigits('1')).toEqual('1');
  });

  it('should return dial code when given digits that start with the dial code', function () {
    expect(bcCountries.getDialCodeByDigits('9665124478564')).toEqual('966');
    expect(bcCountries.getDialCodeByDigits('44452218321')).toEqual('44');
    expect(bcCountries.getDialCodeByDigits('16842178')).toEqual('1684');
    expect(bcCountries.getDialCodeByDigits('14455')).toEqual('1');
  });

  it('should return an empty string when given digits that do not start with a dial code', function () {
    expect(bcCountries.getDialCodeByDigits('99999')).toEqual('');
    expect(bcCountries.getDialCodeByDigits('044')).toEqual('');
  });
});

describe('bcCountries.getCountryByIso2Code(iso2Code)', function () {

  it('should return null when the code is unknown or is a faulsy value', function () {
    expect(bcCountries.getCountryByIso2Code('abc')).toBe(null);
    expect(bcCountries.getCountryByIso2Code('def')).toBe(null);

    expect(bcCountries.getCountryByIso2Code(null)).toBe(null);
    expect(bcCountries.getCountryByIso2Code('')).toBe(null);
  });

  it('should return the correct fields', function () {
    expect(bcCountries.getCountryByIso2Code('gb')).toEqual({dialCode: '44', iso2Code: 'gb', name: 'United Kingdom'});
    expect(bcCountries.getCountryByIso2Code('us')).toEqual({dialCode: '1', iso2Code: 'us', name: 'United States'});
  });
});

describe('bcCountries.getAllCountries()', function () {

  it('should have 242 elements', function () {
    expect(bcCountries.getAllCountries().length).toEqual(242);
  });

  it('should returns the correct fields', function () {
    expect(bcCountries.getAllCountries()[3]).toEqual({dialCode: '1684', iso2Code: 'as', name: 'American Samoa'});
    expect(bcCountries.getAllCountries()[4]).toEqual({dialCode: '376', iso2Code: 'ad', name: 'Andorra'});
  });
});

describe('bcCountries.changeDialCode(number, newDialCode)', function () {

  it('should return the dial cial code prefixed when the number has a faulsy value', function () {
    expect(bcCountries.changeDialCode(null, '1648')).toEqual('+1648');
    expect(bcCountries.changeDialCode('', '966')).toEqual('+966');
    expect(bcCountries.changeDialCode('', '1')).toEqual('+1');
  });

  it('should return the same number formatted with the new dial code', function () {
    expect(bcCountries.changeDialCode('+966657-893-4754', '1')).toEqual('+1 657-893-4754');
    expect(bcCountries.changeDialCode('+44501234567', '966')).toEqual('+966 50 123 4567');
  });

  it('should return the number prefixed with the new dial code if it does not start with a dial code', function () {
    expect(bcCountries.changeDialCode('+8874', '1')).toEqual('+1 887-4');
    expect(bcCountries.changeDialCode('99', '966')).toEqual('+966 99');
  });
});

describe('bcCountries.isValidNumber(number)', function () {

  it('should return false when the number has a faulsy value', function () {
    expect(bcCountries.isValidNumber(null)).toBe(false);
    expect(bcCountries.isValidNumber('')).toBe(false);
  });

  it('should return false when the number does not start with a country dial code', function () {
    expect(bcCountries.isValidNumber('+8874')).toBe(false);
    expect(bcCountries.isValidNumber('99')).toBe(false);
  });

  it('should return false when the number does not start with a +', function () {
    expect(bcCountries.isValidNumber('966 50 123 4567')).toBe(false);
    expect(bcCountries.isValidNumber('1 657-893-4754')).toBe(false);
  });

  it('should return true when the number only when the number is an international valid number', function () {
    expect(bcCountries.isValidNumber('+966 50 123 4567')).toBe(true);
    expect(bcCountries.isValidNumber('+1 657-893-4754')).toBe(true);
  });
});

describe('bcCountries.formatNumber(number)', function () {

  itShouldReturnEmptyString(bcCountries.formatNumber);

  it('should return the same number when the number does not start with a dial code', function () {
    expect(bcCountries.formatNumber('999654')).toEqual('999654');
    expect(bcCountries.formatNumber('8844')).toEqual('8844');
  });

  it('should return a formatted number when the given number start with a dial code', function () {
    expect(bcCountries.formatNumber('+966501234567')).toEqual('+966 50 123 4567');
    expect(bcCountries.formatNumber('966501234567')).toEqual('+966 50 123 4567');
    expect(bcCountries.formatNumber('966')).toEqual('+966');
  });
});

describe('bcCountries.getDigits(number)', function () {

  itShouldReturnEmptyString(bcCountries.getDigits);

  it('should return digits', function () {
    expect(bcCountries.getDigits('+966 50 123 4567-abc')).toEqual('966501234567');
  });
});


text:
package scalan

import org.scalatest.BeforeAndAfterAll

import scalan.collections.{CollectionsDsl, CollectionsDslExp, CollectionsDslStd}
import scalan.compilation.language.MethodMappingDSL
import scalan.compilation.language.ScalaMapping._
import scalan.compilation.lms.collections.CollectionsBridgeScala
import scalan.compilation.lms.scalac.LmsCompilerScala
import scalan.compilation.lms.source2bin.SbtConfig
import scalan.it.BaseItTests
import scalan.util.{Exceptions, FileUtil}

trait MethodCallTestProg extends CollectionsDsl {

  lazy val emptyIf = fun { (in: Rep[(Boolean, (Double, Double))]) =>
    val Pair(x, Pair(y, z)) = in
    IF(x) THEN y ELSE z
  }

  lazy val exceptionWithIfFalse = fun { (p: Rep[(Int, (SThrowable, SThrowable))]) =>
    val Pair(n, Pair(t1, t2)) = p
    IF(n>0) THEN t2.getMessage ELSE t1.initCause(t2).getMessage
  }

  lazy val exceptionWithIfTrue = fun { (p: Rep[(Int, (SThrowable, SThrowable))]) =>
    //val Pair(n, Pair(t1, t2)) = p
    val Pair(n, Pair(t1, t2)) = p
    IF(n<=0) THEN t2.getMessage ELSE t1.initCause(t2).getMessage
  }

  lazy val arrayLengthFun = fun { (v: Rep[Array[Int]]) =>
    //v.arrayLength
    v.length
  }

  lazy val arrayOneArg = fun { (in: Rep[(Array[Double], Int)]) =>
    in._1.apply(in._2)
  }

  lazy val easyMap = fun { (in: Rep[(Array[Double], (Double, Double))]) =>
    val Pair(m0, Pair(vFrom, vTo)) = in
    val m:Rep[Array[Double]] = m0.map(x => x*x)
    m.reduce
  }

  lazy val mapWithLambda = fun { (in: Rep[(Array[Double], (Double, Double))]) =>
    val Pair(m0, Pair(vFrom, vTo)) = in
    def f(x:Rep[Double],y:Rep[Double], z:Rep[Double]): Rep[Double] = {
      x*y+z
    }

    val m:Rep[Array[Double]] = m0.map(x => f(x, vFrom, vTo))

    m.reduce
  }

  lazy val mapWithLambdaIf = fun { (in: Rep[(Array[Double], (Double, Double))]) =>
    val Pair(m0, Pair(vFrom, vTo)) = in
    def f(x:Rep[Double],y:Rep[Double], z:Rep[Double]): Rep[Double] = {
      IF(x===y) THEN z ELSE x
    }

    val m:Rep[Array[Double]] = m0.map(x => f(x, vFrom, vTo))

    m.reduce
  }

  lazy val mapWithLambdaIfGt = fun { (in: Rep[(Array[Double], (Double, Double))]) =>
    val Pair(m0, Pair(vFrom, vTo)) = in
    def f(x:Rep[Double],y:Rep[Double], z:Rep[Double]): Rep[Double] = {
      IF(x<y) THEN x ELSE z
    }

    val m:Rep[Array[Double]] = m0.map(x => f(x, vFrom, vTo))

    m.reduce
  }

  lazy val arrayLength = fun { v: Rep[Array[Int]] =>
    Collection(v).length
  }

  lazy val message = fun { (t: Rep[String]) => SThrowable(t).getMessage}
}

class MethodCallItTests extends BaseItTests[MethodCallTestProg](new CollectionsDslStd with MethodCallTestProg) with BeforeAndAfterAll {

  override def beforeAll() = {
    FileUtil.deleteIfExist(prefix)
  }

  class ProgStaged extends CollectionsDslExp with MethodCallTestProg

  val progStaged = new LmsCompilerScala(new ProgStaged) with CollectionsBridgeScala
  val defaultCompilers = compilers(progStaged)

  test("emptyIfTrue") {
    val in = (true, (5.0, 7.7))
    compareOutputWithStd(_.emptyIf)(in)
  }

  test("emptyIfFalse") {
    val in = (false, (5.0, 7.7))
    compareOutputWithStd(_.emptyIf)(in)
  }

//  ignore("exceptionWithIfTrue") {
//    //val in = Array(Array(2, 3), Array(4, 5))
//    import progSeq._
//    val in = (1, (SThrowable("branch true exception"), SThrowable("branch false exception") ))
//    compareOutputWithSequential(progStaged)(progSeq.exceptionWithIfTrue, progStaged.scalan.exceptionWithIfTrue, "exceptionWithIfTrue")(in)
//  }
//
//  test("exceptionWithIfFalse") {
//    //val in = Array(Array(2, 3), Array(4, 5))
//    val in = (1, (new Exception("branch true exception"), new Exception("branch false exception") ))
//    compareOutputWithSequential(progStaged)(progSeq.exceptionWithIfFalse, progStaged.scalan.exceptionWithIfFalse, "exceptionWithIfFalse")(in)
//  }
//
//  test("arrayLengthFun") {
//    val in = Array(4, 5, 6)
//    compareOutputWithSequential(progStaged)(progSeq.arrayLengthFun, progStaged.scalan.arrayLengthFun, "arrayLengthFun")(in)
//  }
//
//  test("arrayOneArg") {
//    val in = (Array(4.4, 5.0, 6.1), 2)
//    compareOutputWithSequential(progStaged)(progSeq.arrayOneArg, progStaged.scalan.arrayOneArg, "arrayOneArg")(in)
//  }
//
//  test("easyMap") {
//    val in = (Array(4.4, 5.0, 6.1), (5.0, 7.7))
//    compareOutputWithSequential(progStaged)(progSeq.easyMap, progStaged.scalan.easyMap, "easyMap")(in)
//  }
//
//  test("mapWithLambda") {
//    val in = (Array(4.4, 5.0, 6.1), (5.0, 7.7))
//    compareOutputWithSequential(progStaged)(progSeq.mapWithLambda, progStaged.scalan.mapWithLambda, "mapWithLambda")(in)
//  }
//
//  test("mapWithLambdaIf") {
//    val in = (Array(4.4, 5.0, 6.1), (5.0, 7.7))
//    compareOutputWithSequential(progStaged)(progSeq.mapWithLambdaIf, progStaged.scalan.mapWithLambdaIf, "mapWithLambdaIf")(in)
//  }
//
//  test("mapWithLambdaIfGt") {
//    val in = (Array(4.4, 5.0, 6.1), (5.5, 7.7))
//    compareOutputWithSequential(progStaged)(progSeq.mapWithLambdaIfGt, progStaged.scalan.mapWithLambdaIfGt, "mapWithLambdaIfGt")(in)
//  }

  val exceptionTestExp = new LmsCompilerScala(new ScalanDslExp {
    lazy val tElem = element[Throwable]
    lazy val defaultRep = tElem.defaultRepValue

    lazy val message = fun { (t: Rep[SThrowable]) => t.getMessage}

    lazy val initCause = fun { (p: Rep[(SThrowable, SThrowable)]) =>
      val Pair(t1, t2) = p
      t1.initCause(t2).getMessage
    }

    lazy val initCause2 = fun { (p: Rep[(SThrowable, (SThrowable, (SThrowable, (SThrowable, SThrowable))))]) =>
      val Pair(t1, Pair(t2, Pair(t3, Pair(t4, t5)))) = p
      t1.initCause(t2.initCause(t3.initCause(t4.initCause(t5)))).getMessage
    }

    lazy val withIfFalse = fun { (p: Rep[(SThrowable, SThrowable)]) =>
      val Pair(t1, t2) = p
      IF(false) THEN t2.getMessage ELSE t1.initCause(t2).getMessage
    }

    lazy val withIfTrue = fun { (p: Rep[(SThrowable, SThrowable)]) =>
      val Pair(t1, t2) = p
      IF(true) THEN t2.getMessage ELSE t1.initCause(t2).getMessage
    }
  })

//  test("Throwable Method Call") {
//    val originalText = "Exception message"
//    val text = getStagedOutput(exceptionTestExp)(exceptionTestExp.message, "ThrowableMethodCall", new Exception(originalText))
//    text should equal(originalText)
//    val text2 = getStagedOutput(exceptionTestExp)(exceptionTestExp.initCause, "ThrowableInitCauseMethodCall", (new Exception(originalText), new Exception("some text")))
//    text2 should equal(originalText)
//    val text3 = getStagedOutput(exceptionTestExp)(exceptionTestExp.initCause2, "ThrowableManyInitCauseMethodCall", (new Exception(originalText), (new Exception("some text"), (new Exception("some text"), (new Exception("some text"), new Exception("some text"))))))
//    text3 should equal(originalText)
//    val text4 = getStagedOutput(exceptionTestExp)(exceptionTestExp.withIfFalse, "IfFalseMethodCall", (new Exception("Exception message"), new Exception("some text")))
//    text4 should equal(originalText)
//    val text5 = getStagedOutput(exceptionTestExp)(exceptionTestExp.withIfTrue, "IfTrueMethodCall", (new Exception("Exception message"), new Exception("some text")))
//    text5 should equal("some text")
//  }

  val matricesExp = new LmsCompilerScala(new ProgStaged)

  test("LMS Method Call") {
    compareOutputWithExpected(_.arrayLength, compilers(matricesExp))(Array(2, 5, 6) -> 3)
  }

  val replaceMethExp = new LmsCompilerScala(new ProgStaged) {
    override def graphPasses(compilerConfig: CompilerConfig) = Seq(AllUnpackEnabler, invokeEnabler("skip_length_method") { (o, m) => !m.getName.equals("length")})
  }

  // TODO: Slow test
  test("Class Mapping") {
    if (isCI) {
      // takes extremely long to run on TeamCity
      pending
    }
    val sbtConfig = SbtConfig(scalaVersion = "2.11.7", mainPack = Some("scalan.imp"),
      extraClasses = Seq("scalan.imp.ArrayImp"), commands = Seq("package"))
    val conf = replaceMethExp.defaultCompilerConfig.withSbtConfig(sbtConfig)
    compareOutputWithExpected(_.arrayLength, compilers(cwc(matricesExp)(conf)))(Array(5, 9, 2) -> 3)
  }

  val jarReplaceExp = new LmsCompilerScala(new ProgStaged) {
    MapModuleScala[Exceptions].types(
      MapTypeScala[Exceptions#SThrowable]().to("scalan.it.lms.MappingMethodFromJar.TestMethod").methods(
        MapMethodScala("getMessage").to("testMessage").onCompanion.args('this)
      )
    )
  }

  // TODO: Slow test
  test("Mapping Method From Jar") {
    if (isCI) {
      // takes extremely long to run on TeamCity
      pending
    }
    val sbtConfig = SbtConfig(scalaVersion = "2.11.7", mainPack = Some("scalan.imp"),
      extraClasses = Seq("scalan.imp.ThrowableImp", "scalan.it.lms.MappingMethodFromJar.TestMethod"), commands = Seq("package"))
    val conf = jarReplaceExp.defaultCompilerConfig.withSbtConfig(sbtConfig)
    compareOutputWithExpected(_.message, compilers(cwc(jarReplaceExp)(conf)))("Original message" -> "Test Message")
  }
}


text:
<?php
require_once('simpletest/autorun.php');

require_once('../tee.php');

class SimpleTemplateTest extends UnitTestCase{
	function __construct()
	{
	        parent::__construct('Log test');
	}

	function testVariableReplacement()
	{
		$tee = new Tee();
		$tee->clean_cache();
		$tee->file(__DIR__.'/input_files/variables.phtml');
		$tee->strong = 'This should be bold';
		$output = file_get_contents(__DIR__.'/output_files/variables.html');
		$this->assertEqual($tee->render(),$output);

	}

	function testBadVariableReplacement()
	{
		$tee = new Tee();
		$tee->clean_cache();
		$tee->file(__DIR__.'/input_files/bad_variables.phtml');
		$tee->strong = 'This should be bold';
		$output = file_get_contents(__DIR__.'/output_files/bad_variables.html');
		$this->assertEqual($tee->render(),$output);

	}

	function testArrayReplacement()
	{
		$tee = new Tee();
		$tee->clean_cache();
		$tee->file(__DIR__.'/input_files/array_replacement.phtml');
		$tee->person = array('name' => 'Tester', 'age' => 20);
		$output = file_get_contents(__DIR__.'/output_files/array_replacement.html');
		$this->assertEqual($tee->render(),$output);
	}

}


text:
namespace NetworkSupervisor
{
    public enum ConnectionState
    {
        Disconnected,
        Connecting,
        Connected
    }
}


text:
"""Collectors."""

import subprocess
import datetime

def app_load_time():
    """Gets moment at which the app was loaded to memory.

    :return: datetime in iso format.

    """
    return datetime.datetime.now().isoformat()

def git_state():
    """Gets information about git repository state."""
    rev, author, msg, timestamp = _head_info()
    branch = _current_branch()
    timestamp = int(timestamp)
    to_datetime = datetime.datetime.fromtimestamp

    return {
        'rev': rev,
        'date': to_datetime(timestamp).isoformat(),
        'message': msg,
        'author': author,
        'branch': branch
    }

def _git(*args):
    return subprocess.check_output(['git'] + list(args),
                                   universal_newlines=True)

def _head_info():
    return _git('log', '--pretty=format:%H;%an;%s;%ct', '-1').split(';')

def _current_branch():
    branches = _git('branch').split()
    return branches[branches.index('*') + 1]


text:
<?php
namespace BiswarupAdhikari\ToyDB\Models;
use BiswarupAdhikari\ToyDB\Models\Model;
class Benchmark extends Model
{
	private $startTime;
	private $stopTime;
	private $results=array();
	public function start()
	{
		$this->startTime=microtime(true);
	}

	public function stop()
	{
		$this->stopTime=microtime(true);
		array_push($this->results,$this->stopTime - $this->startTime);
		$this->startTime=microtime(true);

	}
	public function results()
	{
		echo '
';
		foreach($this->results as $result)
		{
			echo '
'.$result.'
';
		}
		echo '
';
	}
}


text:
<?php

namespace sprak3000\AnimeNewsNetworkDataAPI\Enum\Anime;

use sprak3000\AnimeNewsNetworkDataAPI\Enum\AbstractProperty;

class Property extends AbstractProperty
{
    const KEY_ANIME = 'anime';
    const KEY_CAST = 'cast';
    const KEY_CREDIT = 'credit';
}


text:
package com.yoya.rdf.router.session.impl;

import com.yoya.sql.SqlRunner;

/**
 * Created by baihw on 16-8-8.
 *
 * 基于H2数据库的用户会话实现。
 */
public class H2Session extends RdbSession{

	public H2Session( String sessionId, int timeout ){
		super( sessionId, timeout );
	}

	/**
	 * 初次加载时检查初始化情况,如果是首次使用,则初始化需要的表结构。
	 */
	static{
		String sql = "select TABLE_NAME from INFORMATION_SCHEMA.TABLES where table_name = '".concat( TABLE_NAME ).concat( "'; " );
		Object tableName = SqlRunner.impl().queryScalar( sql );
		if( null == tableName ){
			StringBuilder sb = new StringBuilder();
			sb.append( "CREATE TABLE `" ).append( TABLE_NAME ).append( "` (" );
			sb.append( "`id` char(32) NOT NULL," );
			sb.append( "`data` MEDIUMTEXT," );
			sb.append( "`createTime` int NOT NULL," );
			sb.append( "`updateTime` int NOT NULL," );
			sb.append( "PRIMARY KEY (`id`)" );
			sb.append( ");" );
			sql = sb.toString();

			SqlRunner.impl().update( sql );
		}
	}

} // end class


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/accessibility/floating_accessibility_detailed_controller.h"

#include "ash/public/cpp/shell_window_ids.h"
#include "ash/resources/vector_icons/vector_icons.h"
#include "ash/shell.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/style/ash_color_provider.h"
#include "ash/system/accessibility/tray_accessibility.h"
#include "ash/system/tray/tray_background_view.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/wm/collision_detection/collision_detection_utils.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/wm/public/activation_client.h"

namespace ash {

namespace {

constexpr base::TimeDelta kAnimationDuration =
    base::TimeDelta::FromMilliseconds(150);
constexpr int kDetailedViewHeightDip = 350;

}  // namespace

class FloatingAccessibilityDetailedController::DetailedBubbleView
    : public TrayBubbleView {
 public:
  explicit DetailedBubbleView(TrayBubbleView::InitParams init_params)
      : TrayBubbleView(init_params) {}

  void UpdateAnchorRect(gfx::Rect anchor_rect,
                        views::BubbleBorder::Arrow alignment) {
    SetArrowWithoutResizing(alignment);
    SetAnchorRect(anchor_rect);
  }

  // views::View:
  const char* GetClassName() const override {
    return "FloatingAccessibilityDetailedView";
  }
};

FloatingAccessibilityDetailedController::
    FloatingAccessibilityDetailedController(Delegate* delegate)
    : DetailedViewDelegate(/*tray_controller*/ nullptr), delegate_(delegate) {
  Shell::Get()->activation_client()->AddObserver(this);
}

FloatingAccessibilityDetailedController::
    ~FloatingAccessibilityDetailedController() {
  Shell::Get()->activation_client()->RemoveObserver(this);
  if (!bubble_widget_ || bubble_widget_->IsClosed())
    return;
  bubble_widget_->CloseNow();
}

void FloatingAccessibilityDetailedController::Show(
    gfx::Rect anchor_rect,
    views::BubbleBorder::Arrow alignment) {
  if (bubble_view_)
    return;

  TrayBubbleView::InitParams init_params;
  init_params.delegate = this;
  init_params.parent_window = Shell::GetContainer(
      Shell::GetPrimaryRootWindow(), kShellWindowId_SettingBubbleContainer);
  init_params.anchor_mode = TrayBubbleView::AnchorMode::kRect;
  init_params.anchor_rect = anchor_rect;
  init_params.insets = gfx::Insets(0, kUnifiedMenuPadding, kUnifiedMenuPadding,
                                   kUnifiedMenuPadding);
  init_params.close_on_deactivate = false;
  init_params.corner_radius = kUnifiedTrayCornerRadius;
  init_params.has_shadow = false;
  init_params.translucent = true;
  init_params.show_by_click = true;

  bubble_view_ = new DetailedBubbleView(init_params);
  bubble_view_->SetArrowWithoutResizing(alignment);

  detailed_view_ = bubble_view_->AddChildView(
      std::make_unique<tray::AccessibilityDetailedView>(this));
  bubble_view_->SetPreferredSize(
      gfx::Size(kTrayMenuWidth, kDetailedViewHeightDip));
  bubble_view_->SetFocusBehavior(ActionableView::FocusBehavior::ALWAYS);
  detailed_view_->SetPaintToLayer();
  detailed_view_->layer()->SetFillsBoundsOpaquely(false);

  bubble_widget_ = views::BubbleDialogDelegateView::CreateBubble(bubble_view_);
  bubble_view_->SetCanActivate(true);
  TrayBackgroundView::InitializeBubbleAnimations(bubble_widget_);
  bubble_view_->InitializeAndShowBubble();

  // Focus on the bubble whenever it is shown.
  bubble_view_->RequestFocus();
}

void FloatingAccessibilityDetailedController::UpdateAnchorRect(
    gfx::Rect anchor_rect,
    views::BubbleBorder::Arrow alignment) {
  ui::ScopedLayerAnimationSettings settings(
      bubble_widget_->GetLayer()->GetAnimator());
  settings.SetPreemptionStrategy(
      ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
  settings.SetTransitionDuration(kAnimationDuration);
  settings.SetTweenType(gfx::Tween::EASE_OUT);
  bubble_view_->UpdateAnchorRect(anchor_rect, alignment);
}

void FloatingAccessibilityDetailedController::CloseBubble() {
  if (delegate_->GetBubbleWidget())
    delegate_->GetBubbleWidget()->Activate();
  if (!bubble_widget_ || bubble_widget_->IsClosed())
    return;
  bubble_widget_->Close();
}

void FloatingAccessibilityDetailedController::TransitionToMainView(
    bool restore_focus) {
  CloseBubble();
}

base::string16
FloatingAccessibilityDetailedController::GetAccessibleNameForBubble() {
  return l10n_util::GetStringUTF16(
      IDS_ASH_FLOATING_ACCESSIBILITY_DETAILED_MENU);
}

views::Button* FloatingAccessibilityDetailedController::CreateBackButton(
    views::ButtonListener* listener) {
  views::ImageButton* button = static_cast<views::ImageButton*>(
      DetailedViewDelegate::CreateBackButton(listener));
  gfx::ImageSkia image = gfx::CreateVectorIcon(
      kAutoclickCloseIcon, AshColorProvider::Get()->GetContentLayerColor(
                               AshColorProvider::ContentLayerType::kIconPrimary,
                               AshColorProvider::AshColorMode::kDark));
  button->SetImage(views::Button::STATE_NORMAL, image);
  button->SetTooltipText(l10n_util::GetStringUTF16(
      IDS_ASH_FLOATING_ACCESSIBILITY_DETAILED_MENU_CLOSE));

  return button;
}

views::Button* FloatingAccessibilityDetailedController::CreateHelpButton(
    views::ButtonListener* listener) {
  auto* button = DetailedViewDelegate::CreateHelpButton(listener);
  button->SetVisible(false);
  return button;
}

void FloatingAccessibilityDetailedController::BubbleViewDestroyed() {
  detailed_view_ = nullptr;
  bubble_view_ = nullptr;
  bubble_widget_ = nullptr;

  delegate_->OnDetailedMenuClosed();
  // Hammer time, |this| is destroyed in the previous call.
}

void FloatingAccessibilityDetailedController::OnAccessibilityStatusChanged() {
  if (detailed_view_)
    detailed_view_->OnAccessibilityStatusChanged();
}

void FloatingAccessibilityDetailedController::OnWindowActivated(
    ActivationReason reason,
    aura::Window* gained_active,
    aura::Window* lost_active) {
  if (!gained_active || !bubble_widget_)
    return;

  views::Widget* gained_widget =
      views::Widget::GetWidgetForNativeView(gained_active);
  // Do not close the view if our bubble was activated.
  // Also, do not close the view the floating menu was activated, since it
  // controls our visibility.
  if (gained_widget == bubble_widget_ ||
      gained_widget == delegate_->GetBubbleWidget())
    return;

  bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kLostFocus);
}

}  // namespace ash


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Univer.WorkflowLight.Definition;

namespace Univer.WorkflowLight.Definition
{
    public abstract class WorkflowDefinition
    {
    }
}


text:
package com.hayaisoftware.launcher.activities;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.hayaisoftware.launcher.ImageLoadingTask;
import com.hayaisoftware.launcher.LaunchableActivity;
import com.hayaisoftware.launcher.LaunchableActivityPrefs;
import com.hayaisoftware.launcher.LoadLaunchableActivityTask;
import com.hayaisoftware.launcher.PackageChangedReceiver;
import com.hayaisoftware.launcher.R;
import com.hayaisoftware.launcher.ShortcutNotificationManager;
import com.hayaisoftware.launcher.StatusBarColorHelper;
import com.hayaisoftware.launcher.Trie;
import com.hayaisoftware.launcher.comparators.AlphabeticalOrder;
import com.hayaisoftware.launcher.comparators.PinToTop;
import com.hayaisoftware.launcher.comparators.RecentOrder;
import com.hayaisoftware.launcher.comparators.UsageOrder;
import com.hayaisoftware.launcher.threading.SimpleTaskConsumerManager;
import com.hayaisoftware.launcher.util.ContentShare;

import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

public class SearchActivity extends Activity
        implements SharedPreferences.OnSharedPreferenceChangeListener {

    private static final int sNavigationBarHeightMultiplier = 1;
    private static final int sGridViewTopRowExtraPaddingInDP = 56;
    private static final int sMarginFromNavigationBarInDp = 16;
    private static final int sGridItemHeightInDp = 96;
    private static final int sInitialArrayListSize = 300;

    private final Pattern mPattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
    private int mStatusBarHeight;
    private ArrayList<LaunchableActivity> mActivityInfos;
    private ArrayList<LaunchableActivity> mShareableActivityInfos;
    private Trie<LaunchableActivity> mTrie;
    private ArrayAdapter<LaunchableActivity> mArrayAdapter;
    private HashMap<String, List<LaunchableActivity>> mLaunchableActivityPackageNameHashMap;
    private LaunchableActivityPrefs mLaunchableActivityPrefs;
    private SharedPreferences mSharedPreferences;
    private Context mContext;
    private Drawable mDefaultAppIcon;
    private SimpleTaskConsumerManager mImageLoadingConsumersManager;
    private ImageLoadingTask.SharedData mImageTasksSharedData;
    private int mIconSizePixels;
    private EditText mSearchEditText;
    private View mClearButton;
    private int mNumOfCores;
    private BroadcastReceiver mPackageChangedReceiver;

    private Comparator<LaunchableActivity> mPinToTopComparator;
    private Comparator<LaunchableActivity> mRecentOrderComparator;
    private Comparator<LaunchableActivity> mAlphabeticalOrderComparator;
    private Comparator<LaunchableActivity> mUsageOrderComparator;
    private InputMethodManager mInputMethodManager;
    private AdapterView mAppListView;
    private PackageManager mPm;
    private View mOverflowButtonTopleft;
    private int mColumnCount;
    //used only in function getAllSubwords. they are here as class fields to avoid
    // object re-allocation.
    private StringBuilder mWordSinceLastSpaceBuilder;
    private StringBuilder mWordSinceLastCapitalBuilder;
    private int mGridViewTopRowHeight;
    private int mGridViewBottomRowHeight;
    private boolean mShouldOrderByRecents;
    private boolean mShouldOrderByUsages;
    private final TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            mClearButton.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
            updateVisibleApps();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //do nothing
        }

        @Override
        public void afterTextChanged(Editable s) {
            //do nothing
        }

    };
    private boolean mDisableIcons;
    private boolean mAutoKeyboard;
    private boolean mIsCacheClear;

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

        setContentView(R.layout.activity_search);

        mPm = getPackageManager();

        final Resources resources = getResources();

        //fields:
        mLaunchableActivityPackageNameHashMap = new HashMap<>();
        mShareableActivityInfos = new ArrayList<>(sInitialArrayListSize);
        mActivityInfos = new ArrayList<>(sInitialArrayListSize);
        mTrie = new Trie<>();
        mWordSinceLastSpaceBuilder = new StringBuilder(64);
        mWordSinceLastCapitalBuilder = new StringBuilder(64);

        mSearchEditText = (EditText) findViewById(R.id.editText1);
        mAppListView = (GridView) findViewById(R.id.appsContainer);
        mClearButton = findViewById(R.id.clear_button);
        mOverflowButtonTopleft = findViewById(R.id.overflow_button_topleft);
        mContext = getApplicationContext();
        mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        mStatusBarHeight = StatusBarColorHelper.getStatusBarHeight(resources);
        final DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        final float displayDensity = displayMetrics.density;
        final int gridViewTopRowExtraPaddingInPixels =
                Math.round(displayDensity * sGridViewTopRowExtraPaddingInDP);
        final int marginFromNavigationBarInPixels =
                Math.round(displayDensity * sMarginFromNavigationBarInDp);
        final int gridItemHeightInPixels =
                Math.round(displayDensity * sGridItemHeightInDp);
        int statusBarMultiplierPaddings = setPaddingHeights();
        mGridViewTopRowHeight = statusBarMultiplierPaddings * mStatusBarHeight +
                gridViewTopRowExtraPaddingInPixels;
        mGridViewBottomRowHeight = gridItemHeightInPixels + sNavigationBarHeightMultiplier *
                StatusBarColorHelper.getNavigationBarHeight(getResources()) +
                marginFromNavigationBarInPixels;

        mColumnCount = resources.getInteger(R.integer.app_grid_columns);

        mSharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        setupPreferences();
        mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
        mLaunchableActivityPrefs = new LaunchableActivityPrefs(this);

        //noinspection deprecation
        mDefaultAppIcon = Resources.getSystem().getDrawable(
                android.R.mipmap.sym_def_app_icon);
        mIconSizePixels = resources.getDimensionPixelSize(R.dimen.app_icon_size);

        mPinToTopComparator = new PinToTop();
        mRecentOrderComparator = new RecentOrder();
        mAlphabeticalOrderComparator = new AlphabeticalOrder();
        mUsageOrderComparator = new UsageOrder();

        mNumOfCores = Runtime.getRuntime().availableProcessors();

        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addDataScheme("package");
        mPackageChangedReceiver = new PackageChangedReceiver();
        registerReceiver(mPackageChangedReceiver, filter);

        loadLaunchableApps();

        //loadShareableApps();
        setupImageLoadingThreads(resources);
        setupViews();

    }

    private void loadShareableApps() {
        List<ResolveInfo> infoList = ContentShare.getTextReceivers(mPm);

        for (ResolveInfo info : infoList) {
            final LaunchableActivity launchableActivity = new LaunchableActivity(
                    info.activityInfo, info.loadLabel(mPm).toString(), true);
            mShareableActivityInfos.add(launchableActivity);
        }
        updateApps(mShareableActivityInfos, false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsCacheClear = false;
        mSearchEditText.setText("");
        mSearchEditText.clearFocus();
        if (mAutoKeyboard) {
            mSearchEditText.requestFocus();
        }
    }

    public int setPaddingHeights() {
        int statusBarPaddings = 2;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            final Window window = getWindow();
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

            final View statusBarDummy = findViewById(R.id.statusBarDummyView);
            statusBarDummy.getLayoutParams().height = mStatusBarHeight;
            statusBarPaddings++;
        }

        final View topFillerView = findViewById(R.id.topFillerView);
        topFillerView.getLayoutParams().height = mStatusBarHeight;

        final View bottomFillerView = findViewById(R.id.bottomFillerView);
        bottomFillerView.getLayoutParams().height = mStatusBarHeight;

        return statusBarPaddings;
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

        if (mAutoKeyboard) {
            showKeyboard();

            //HACK putting showKeyboard event to the end of the Ui Thread running queue
            // to make sure the keyboard opens.
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showKeyboard();
                }
            });
        } else {
            hideKeyboard();
        }

    }

    private void setupViews() {

        mSearchEditText.addTextChangedListener(mTextWatcher);
        mSearchEditText.setImeActionLabel(getString(R.string.launch), EditorInfo.IME_ACTION_GO);
        mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_GO) {
                    Log.d("KEYBOARD", "ACTION_GO");
                    return openFirstActivity();
                }
                return false;
            }
        });
        mSearchEditText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    Log.d("KEYBOARD", "ENTER_KEY");
                    return openFirstActivity();
                }
                return false;
            }
        });
        registerForContextMenu(mAppListView);

        ((GridView) mAppListView).setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState != SCROLL_STATE_IDLE) {
                    hideKeyboard();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

            }
        });
        //noinspection unchecked
        mAppListView.setAdapter(mArrayAdapter);

        mAppListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position >= mColumnCount) {
                    launchActivity(mActivityInfos.get(position - mColumnCount));
                }
            }

        });

    }

    private boolean openFirstActivity() {
        if (!mActivityInfos.isEmpty()) {
            launchActivity(mActivityInfos.get(0));
            return true;
        }
        return false;
    }

    private void setupPreferences() {
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        if (mSharedPreferences.getBoolean(SettingsActivity.KEY_PREF_NOTIFICATION, false)) {
            final ShortcutNotificationManager shortcutNotificationManager = new ShortcutNotificationManager();
            final String strPriority =
                    mSharedPreferences.getString(SettingsActivity.KEY_PREF_NOTIFICATION_PRIORITY,
                            "low");
            final int priority = ShortcutNotificationManager.getPriorityFromString(strPriority);
            shortcutNotificationManager.showNotification(this, priority);
        }
        String order = mSharedPreferences.getString("pref_app_preferred_order", "recent");
        mShouldOrderByUsages = order.equals("usage");
        mShouldOrderByRecents = order.equals("recent");

        mDisableIcons =
                mSharedPreferences.getBoolean("pref_disable_icons", false);
        mAutoKeyboard =
                mSharedPreferences.getBoolean("pref_autokeyboard", false);
    }

    private void setupImageLoadingThreads(final Resources resources) {

        mImageLoadingConsumersManager =
                new SimpleTaskConsumerManager(getOptimalNumberOfThreads(resources),
                        mActivityInfos.size());
        mImageTasksSharedData = new ImageLoadingTask.SharedData(this, mPm, mContext, mIconSizePixels);
    }

    private int getOptimalNumberOfThreads(final Resources resources) {
        final int maxThreads = resources.getInteger(R.integer.max_imageloading_threads);
        int numThreads = mNumOfCores - 1;
        //clamp numThreads
        if (numThreads < 1) numThreads = 1;
        else if (numThreads > maxThreads) numThreads = maxThreads;
        return numThreads;
    }

    private void updateApps(final List<LaunchableActivity> updatedActivityInfos, boolean addToTrie) {

        for (LaunchableActivity launchableActivity : updatedActivityInfos) {
            final String packageName = launchableActivity.getComponent().getPackageName();
            mLaunchableActivityPackageNameHashMap.remove(packageName);
        }

        final String thisClassCanonicalName = this.getClass().getCanonicalName();
        for (LaunchableActivity launchableActivity : updatedActivityInfos) {
            final String className = launchableActivity.getComponent().getClassName();
            //don't show this activity in the launcher
            if (className.equals(thisClassCanonicalName)) {
                continue;
            }

            if (addToTrie) {
                final String activityLabel = launchableActivity.getActivityLabel();
                final List<String> subwords = getAllSubwords(stripAccents(activityLabel));
                for (String subword : subwords) {
                    mTrie.put(subword, launchableActivity);
                }
            }
            final String packageName = launchableActivity.getComponent().getPackageName();

            List<LaunchableActivity> launchableActivitiesToUpdate =
                    mLaunchableActivityPackageNameHashMap.remove(packageName);
            if (launchableActivitiesToUpdate == null) {
                launchableActivitiesToUpdate = new LinkedList<>();
            }
            launchableActivitiesToUpdate.add(launchableActivity);
            mLaunchableActivityPackageNameHashMap.put(packageName, launchableActivitiesToUpdate);
        }
        Log.d("SearchActivity", "updated activities: " + updatedActivityInfos.size());
        mLaunchableActivityPrefs.setAllPreferences(updatedActivityInfos);
        updateVisibleApps();
    }

    private List<String> getAllSubwords(String line) {
        final ArrayList<String> subwords = new ArrayList<>();
        for (int i = 0; i < line.length(); i++) {
            final char character = line.charAt(i);

            if (Character.isUpperCase(character) || Character.isDigit(character)) {
                if (mWordSinceLastCapitalBuilder.length() > 1) {
                    subwords.add(mWordSinceLastCapitalBuilder.toString().toLowerCase());
                }
                mWordSinceLastCapitalBuilder.setLength(0);

            }
            if (Character.isSpaceChar(character)) {
                subwords.add(mWordSinceLastSpaceBuilder.toString().toLowerCase());
                if (mWordSinceLastCapitalBuilder.length() > 1 &&
                        mWordSinceLastCapitalBuilder.length() !=
                                mWordSinceLastSpaceBuilder.length()) {
                    subwords.add(mWordSinceLastCapitalBuilder.toString().toLowerCase());
                }
                mWordSinceLastCapitalBuilder.setLength(0);
                mWordSinceLastSpaceBuilder.setLength(0);
            } else {
                mWordSinceLastCapitalBuilder.append(character);
                mWordSinceLastSpaceBuilder.append(character);
            }
        }
        if (mWordSinceLastSpaceBuilder.length() > 0) {
            subwords.add(mWordSinceLastSpaceBuilder.toString().toLowerCase());
        }
        if (mWordSinceLastCapitalBuilder.length() > 1
                && mWordSinceLastCapitalBuilder.length() != mWordSinceLastSpaceBuilder.length()) {
            subwords.add(mWordSinceLastCapitalBuilder.toString().toLowerCase());
        }
        mWordSinceLastSpaceBuilder.setLength(0);
        mWordSinceLastCapitalBuilder.setLength(0);
        return subwords;
    }

    private void updateVisibleApps() {
        final HashSet<LaunchableActivity> infoList =
                mTrie.getAllStartingWith(stripAccents(mSearchEditText.getText()
                        .toString().toLowerCase().trim()));
        mActivityInfos.clear();
        mActivityInfos.addAll(infoList);
        mActivityInfos.addAll(mShareableActivityInfos);
        sortApps();
        Log.d("DEBUG_SEARCH", mActivityInfos.size() + "");

        mArrayAdapter.notifyDataSetChanged();
    }

    private void sortApps() {
        Collections.sort(mActivityInfos, mAlphabeticalOrderComparator);

        if (mShouldOrderByRecents) {
            Collections.sort(mActivityInfos, mRecentOrderComparator);
        } else if(mShouldOrderByUsages) {
            Collections.sort(mActivityInfos, mUsageOrderComparator);
        }

        Collections.sort(mActivityInfos, mPinToTopComparator);
    }

    private void removeActivitiesFromPackage(String packageName) {
        final List<LaunchableActivity> launchableActivitiesToRemove =
                mLaunchableActivityPackageNameHashMap.remove(packageName);
        if (launchableActivitiesToRemove == null) {
            return;
        }
        boolean activityListChanged = false;

        for (LaunchableActivity launchableActivityToRemove : launchableActivitiesToRemove) {
            final String className = launchableActivityToRemove.getClassName();
            Log.d("SearchActivity", "removing activity " + className);
            String activityLabel = launchableActivityToRemove.getActivityLabel();
            final List<String> subwords = getAllSubwords(stripAccents(activityLabel));
            for (String subword : subwords) {
                mTrie.remove(subword, launchableActivityToRemove);
            }
            if (mActivityInfos.remove(launchableActivityToRemove))
                activityListChanged = true;
            //TODO DEBUGME if uncommented the next line causes a crash.
            //mLaunchableActivityPrefs.deletePreference(className);
        }

        if (activityListChanged)
            mArrayAdapter.notifyDataSetChanged();
    }

    private boolean isCurrentLauncher() {
        final Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        final ResolveInfo resolveInfo =
                mPm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return resolveInfo != null &&
                mContext.getPackageName().equals(resolveInfo.activityInfo.packageName);

    }

    private String stripAccents(final String s) {
        return mPattern.matcher(Normalizer.normalize(s, Normalizer.Form.NFKD)).replaceAll("");
    }

    private void loadLaunchableApps() {

        List<ResolveInfo> infoList = ContentShare.getLaunchableResolveInfos(mPm);
        mArrayAdapter = new ActivityInfoArrayAdapter(this,
                R.layout.app_grid_item, mActivityInfos);
        ArrayList<LaunchableActivity> launchablesFromResolve = new ArrayList<>(infoList.size());

        if (mNumOfCores <= 1) {
            for (ResolveInfo info : infoList) {
                final LaunchableActivity launchableActivity = new LaunchableActivity(
                        info.activityInfo, info.activityInfo.loadLabel(mPm).toString(), false);
                launchablesFromResolve.add(launchableActivity);
            }
        } else {
            SimpleTaskConsumerManager simpleTaskConsumerManager =
                    new SimpleTaskConsumerManager(mNumOfCores, infoList.size());

            LoadLaunchableActivityTask.SharedData sharedAppLoadData =
                    new LoadLaunchableActivityTask.SharedData(mPm, launchablesFromResolve);
            for (ResolveInfo info : infoList) {
                LoadLaunchableActivityTask loadLaunchableActivityTask =
                        new LoadLaunchableActivityTask(info, sharedAppLoadData);
                simpleTaskConsumerManager.addTask(loadLaunchableActivityTask);
            }

            //Log.d("MultithreadStartup","waiting for completion of all tasks");
            simpleTaskConsumerManager.destroyAllConsumers(true, true);
            //Log.d("MultithreadStartup", "all tasks ok");
        }
        updateApps(launchablesFromResolve, true);
    }

    private void showKeyboard() {
        mInputMethodManager.showSoftInput(mSearchEditText, 0);
    }

    private void hideKeyboard() {
        mInputMethodManager.hideSoftInputFromWindow(mSearchEditText.getWindowToken(), 0);
    }

    private void handlePackageChanged() {
        final SharedPreferences.Editor editor = mSharedPreferences.edit();
        final String[] packageChangedNames = mSharedPreferences.getString("package_changed_name", "")
                .split(" ");
        editor.putString("package_changed_name", "");
        editor.apply();

        for (String packageName : packageChangedNames) {
            packageName = packageName.trim();
            if (packageName.isEmpty()) continue;

            final Intent intent = new Intent();
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setPackage(packageName);
            Log.d("SearchActivity", "changed: " + packageName);
            final List<ResolveInfo> infoList = mPm.queryIntentActivities(intent, 0);

            //we don't actually need to run removeActivitiesFromPackage if the package
            // is being installed
            removeActivitiesFromPackage(packageName);

            if (infoList.isEmpty()) {
                Log.d("SearchActivity", "No activities in list. Uninstall detected!");
                updateVisibleApps();
            } else {
                Log.d("SearchActivity", "Activities in list. Install/update detected!");
                ArrayList<LaunchableActivity> launchablesFromResolve = new ArrayList<>(infoList.size());
                for (ResolveInfo info : infoList) {
                    final LaunchableActivity launchableActivity = new LaunchableActivity(
                            info.activityInfo, info.activityInfo.loadLabel(mPm).toString(), false);
                    launchablesFromResolve.add(launchableActivity);
                }
                updateApps(launchablesFromResolve, true);
            }

        }

    }

    @Override
    public void onBackPressed() {
        if (!isCurrentLauncher())
            moveTaskToBack(false);
    }

    @Override
    protected void onDestroy() {
        if (mImageLoadingConsumersManager != null)
            mImageLoadingConsumersManager.destroyAllConsumers(false);
        unregisterReceiver(mPackageChangedReceiver);
        Log.d("HayaiLauncher", "Hayai is ded");
        super.onDestroy();
    }

    public void showPopup(View v) {
        final PopupMenu popup = new PopupMenu(this, v);
        popup.setOnMenuItemClickListener(new PopupEventListener());
        final MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.search_activity_menu, popup.getMenu());
        popup.show();
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        //does this need to run in uiThread?
        if (key.equals("package_changed_name") && !sharedPreferences.getString(key, "").isEmpty()) {
            handlePackageChanged();
        } else if (key.equals("pref_app_preferred_order")) {
            String order = mSharedPreferences.getString("pref_app_preferred_order", "recent");
            mShouldOrderByUsages = order.equals("usage");
            mShouldOrderByRecents = order.equals("recent");

            //mShouldOrderByUsages = mSharedPreferences.getString("pref_app_preferred_order", "usages").equals("usages");
            sortApps();
            mArrayAdapter.notifyDataSetChanged();
        } else if (key.equals("pref_disable_icons")) {
            recreate();
        } else if (key.equals("pref_autokeyboard")) {
            mAutoKeyboard = mSharedPreferences.getBoolean("pref_autokeyboard", false);
        }

    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            showPopup(mOverflowButtonTopleft);
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (!mIsCacheClear && level == TRIM_MEMORY_COMPLETE)
            clearCaches();

    }

    private void clearCaches() {
        mIsCacheClear = true;
        for (LaunchableActivity launchableActivity : mActivityInfos) {
            launchableActivity.deleteActivityIcon();
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (menuInfo instanceof AdapterContextMenuInfo) {
            AdapterContextMenuInfo adapterMenuInfo = (AdapterContextMenuInfo) menuInfo;
            menu.setHeaderTitle(
                    ((LaunchableActivity) adapterMenuInfo.targetView
                            .findViewById(R.id.appIcon).getTag()).getActivityLabel());
        }
        final MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.app, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                final Intent intentSettings = new Intent(this, SettingsActivity.class);
                startActivity(intentSettings);
                return true;
            case R.id.action_refresh_app_list:
                recreate();
                return true;
            case R.id.action_system_settings:
                final Intent intentSystemSettings = new Intent(Settings.ACTION_SETTINGS);
                intentSystemSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intentSystemSettings);
                return true;
            case R.id.action_manage_apps:
                final Intent intentManageApps = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                intentManageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intentManageApps);
                return true;
            case R.id.action_set_wallpaper:
                final Intent intentWallpaperPicker = new Intent(Intent.ACTION_SET_WALLPAPER);
                startActivity(intentWallpaperPicker);
                return true;
            case R.id.action_about:
                final Intent intentAbout = new Intent(this, AboutActivity.class);
                startActivity(intentAbout);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                .getMenuInfo();
        final View itemView = info.targetView;
        final LaunchableActivity launchableActivity =
                (LaunchableActivity) itemView.findViewById(R.id.appIcon).getTag();
        switch (item.getItemId()) {
            case R.id.appmenu_launch:
                launchActivity(launchableActivity);
                return true;
            case R.id.appmenu_info:
                final Intent intent = new Intent(
                        Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:"
                        + launchableActivity.getComponent().getPackageName()));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                return true;
            case R.id.appmenu_onplaystore:
                final Intent intentPlayStore = new Intent(Intent.ACTION_VIEW);
                intentPlayStore.setData(Uri.parse("market://details?id=" +
                        launchableActivity.getComponent().getPackageName()));
                startActivity(intentPlayStore);
                return true;
            case R.id.appmenu_pin_to_top:
                launchableActivity.setPriority(launchableActivity.getPriority() == 0 ? 1 : 0);
                mLaunchableActivityPrefs.writePreference(launchableActivity.getClassName(),
                        launchableActivity.getLaunchTime(), launchableActivity.getPriority(), launchableActivity.getusagesQuantity());
                sortApps();
                mArrayAdapter.notifyDataSetChanged();
                return true;
            default:
                return false;
        }

    }

    public void onClickSettingsButton(View view) {
        showPopup(mOverflowButtonTopleft);

    }

    public void launchActivity(final LaunchableActivity launchableActivity) {

        hideKeyboard();
        try {
            startActivity(launchableActivity.getLaunchIntent(mSearchEditText.getText().toString()));
            launchableActivity.setLaunchTime();
            launchableActivity.addUsage();
            mLaunchableActivityPrefs.writePreference(launchableActivity.getClassName(),
                    launchableActivity.getLaunchTime(), launchableActivity.getPriority(), launchableActivity.getusagesQuantity());
            sortApps();
            mArrayAdapter.notifyDataSetChanged();
        } catch (ActivityNotFoundException e) {
            //this should only happen when the launcher still hasn't updated the file list after
            //an activity removal.
            Toast.makeText(mContext, getString(R.string.activity_not_found),
                    Toast.LENGTH_SHORT).show();
        }

    }

    public void onClickClearButton(View view) {
        mSearchEditText.setText("");
    }

    class PopupEventListener implements PopupMenu.OnMenuItemClickListener {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            return onOptionsItemSelected(item);
        }
    }

    class ActivityInfoArrayAdapter extends ArrayAdapter<LaunchableActivity> {
        final LayoutInflater inflater;

        public ActivityInfoArrayAdapter(final Context context, final int resource,
                                        final List<LaunchableActivity> activityInfos) {

            super(context, resource, activityInfos);
            inflater = getLayoutInflater();
        }

        @Override
        public int getCount() {
            return super.getCount() + mColumnCount;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final View view =
                    convertView != null ?
                            convertView : inflater.inflate(R.layout.app_grid_item, parent, false);
            final AbsListView.LayoutParams params =
                    (AbsListView.LayoutParams) view.getLayoutParams();

            if (position < mColumnCount) {
                params.height = mGridViewTopRowHeight;
                view.setLayoutParams(params);
                view.setVisibility(View.INVISIBLE);
            } else {
                if (position == (getCount() - 1)) {
                    params.height = mGridViewBottomRowHeight;
                } else {
                    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
                view.setLayoutParams(params);
                view.setVisibility(View.VISIBLE);
                final LaunchableActivity launchableActivity = getItem(position - mColumnCount);
                final CharSequence label = launchableActivity.getActivityLabel();
                final TextView appLabelView = (TextView) view.findViewById(R.id.appLabel);
                final ImageView appIconView = (ImageView) view.findViewById(R.id.appIcon);
                final View appShareIndicator = view.findViewById(R.id.appShareIndicator);
                final View appPinToTop = view.findViewById(R.id.appPinToTop);

                appLabelView.setText(label);

                appIconView.setTag(launchableActivity);
                if (!launchableActivity.isIconLoaded()) {
                    appIconView.setImageDrawable(mDefaultAppIcon);
                    if (!mDisableIcons)
                        mImageLoadingConsumersManager.addTask(
                                new ImageLoadingTask(appIconView, launchableActivity,
                                        mImageTasksSharedData));
                } else {
                    appIconView.setImageDrawable(
                            launchableActivity.getActivityIcon(mPm, mContext, mIconSizePixels));
                }
                appShareIndicator.setVisibility(
                        launchableActivity.isShareable() ? View.VISIBLE : View.GONE);
                appPinToTop.setVisibility(
                        launchableActivity.getPriority() > 0 ? View.VISIBLE : View.GONE);

            }
            return view;
        }

    }

}


text:
#ifndef ISTEAMMUSICREMOTE_H
#define ISTEAMMUSICREMOTE_H
#ifdef _WIN32
#pragma once
#endif

#include "steam_api_common.h"
#include "isteammusic.h"

#define k_SteamMusicNameMaxLength 255
#define k_SteamMusicPNGMaxLength 65535

class ISteamMusicRemote
{
public:
	// Service Definition
 	virtual bool RegisterSteamMusicRemote( const char *pchName ) = 0;
 	virtual bool DeregisterSteamMusicRemote() = 0;
	virtual bool BIsCurrentMusicRemote() = 0;
	virtual bool BActivationSuccess( bool bValue ) = 0;

	virtual bool SetDisplayName( const char *pchDisplayName ) = 0;
	virtual bool SetPNGIcon_64x64( void *pvBuffer, uint32 cbBufferLength ) = 0;

	// Abilities for the user interface
	virtual bool EnablePlayPrevious(bool bValue) = 0;
	virtual bool EnablePlayNext( bool bValue ) = 0;
	virtual bool EnableShuffled( bool bValue ) = 0;
	virtual bool EnableLooped( bool bValue ) = 0;
	virtual bool EnableQueue( bool bValue ) = 0;
	virtual bool EnablePlaylists( bool bValue ) = 0;

	// Status
 	virtual bool UpdatePlaybackStatus( AudioPlayback_Status nStatus ) = 0;
	virtual bool UpdateShuffled( bool bValue ) = 0;
	virtual bool UpdateLooped( bool bValue ) = 0;
	virtual bool UpdateVolume( float flValue ) = 0; // volume is between 0.0 and 1.0

	// Current Entry
	virtual bool CurrentEntryWillChange() = 0;
	virtual bool CurrentEntryIsAvailable( bool bAvailable ) = 0;
	virtual bool UpdateCurrentEntryText( const char *pchText ) = 0;
	virtual bool UpdateCurrentEntryElapsedSeconds( int nValue ) = 0;
	virtual bool UpdateCurrentEntryCoverArt( void *pvBuffer, uint32 cbBufferLength ) = 0;
	virtual bool CurrentEntryDidChange() = 0;

	// Queue
	virtual bool QueueWillChange() = 0;
	virtual bool ResetQueueEntries() = 0;
	virtual bool SetQueueEntry( int nID, int nPosition, const char *pchEntryText ) = 0;
	virtual bool SetCurrentQueueEntry( int nID ) = 0;
	virtual bool QueueDidChange() = 0;

	// Playlist
	virtual bool PlaylistWillChange() = 0;
	virtual bool ResetPlaylistEntries() = 0;
	virtual bool SetPlaylistEntry( int nID, int nPosition, const char *pchEntryText ) = 0;
	virtual bool SetCurrentPlaylistEntry( int nID ) = 0;
	virtual bool PlaylistDidChange() = 0;
};

#define STEAMMUSICREMOTE_INTERFACE_VERSION "STEAMMUSICREMOTE_INTERFACE_VERSION001"

// Global interface accessor
inline ISteamMusicRemote *SteamMusicRemote();
STEAM_DEFINE_USER_INTERFACE_ACCESSOR( ISteamMusicRemote *, SteamMusicRemote, STEAMMUSICREMOTE_INTERFACE_VERSION );

// callbacks
#if defined( VALVE_CALLBACK_PACK_SMALL )
#pragma pack( push, 4 )
#elif defined( VALVE_CALLBACK_PACK_LARGE )
#pragma pack( push, 8 )
#else
#error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx
#endif

STEAM_CALLBACK_BEGIN( MusicPlayerRemoteWillActivate_t, k_iSteamMusicRemoteCallbacks + 1)
STEAM_CALLBACK_END(0)

STEAM_CALLBACK_BEGIN( MusicPlayerRemoteWillDeactivate_t, k_iSteamMusicRemoteCallbacks + 2 )
STEAM_CALLBACK_END(0)

STEAM_CALLBACK_BEGIN( MusicPlayerRemoteToFront_t, k_iSteamMusicRemoteCallbacks + 3 )
STEAM_CALLBACK_END(0)

STEAM_CALLBACK_BEGIN( MusicPlayerWillQuit_t, k_iSteamMusicRemoteCallbacks + 4 )
STEAM_CALLBACK_END(0)

STEAM_CALLBACK_BEGIN( MusicPlayerWantsPlay_t, k_iSteamMusicRemoteCallbacks + 5 )
STEAM_CALLBACK_END(0)

STEAM_CALLBACK_BEGIN( MusicPlayerWantsPause_t, k_iSteamMusicRemoteCallbacks + 6 )
STEAM_CALLBACK_END(0)

STEAM_CALLBACK_BEGIN( MusicPlayerWantsPlayPrevious_t, k_iSteamMusicRemoteCallbacks + 7 )
STEAM_CALLBACK_END(0)

STEAM_CALLBACK_BEGIN( MusicPlayerWantsPlayNext_t, k_iSteamMusicRemoteCallbacks + 8 )
STEAM_CALLBACK_END(0)

STEAM_CALLBACK_BEGIN( MusicPlayerWantsShuffled_t, k_iSteamMusicRemoteCallbacks + 9 )
	STEAM_CALLBACK_MEMBER( 0, bool, m_bShuffled )
STEAM_CALLBACK_END(1)

STEAM_CALLBACK_BEGIN( MusicPlayerWantsLooped_t, k_iSteamMusicRemoteCallbacks + 10 )
	STEAM_CALLBACK_MEMBER(0, bool, m_bLooped )
STEAM_CALLBACK_END(1)

STEAM_CALLBACK_BEGIN( MusicPlayerWantsVolume_t, k_iSteamMusicCallbacks + 11 )
	STEAM_CALLBACK_MEMBER(0, float, m_flNewVolume)
STEAM_CALLBACK_END(1)

STEAM_CALLBACK_BEGIN( MusicPlayerSelectsQueueEntry_t, k_iSteamMusicCallbacks + 12 )
	STEAM_CALLBACK_MEMBER(0, int, nID )
STEAM_CALLBACK_END(1)

STEAM_CALLBACK_BEGIN( MusicPlayerSelectsPlaylistEntry_t, k_iSteamMusicCallbacks + 13 )
	STEAM_CALLBACK_MEMBER(0, int, nID )
STEAM_CALLBACK_END(1)

STEAM_CALLBACK_BEGIN( MusicPlayerWantsPlayingRepeatStatus_t, k_iSteamMusicRemoteCallbacks + 14 )
	STEAM_CALLBACK_MEMBER(0, int, m_nPlayingRepeatStatus )
STEAM_CALLBACK_END(1)

#pragma pack( pop )

#endif // #define ISTEAMMUSICREMOTE_H


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;
using SimpleLogger.Logging.Formatters;

namespace SimpleLogger.Logging.Module
{
    public class EmailSenderLoggerModule : LoggerModule
    {
        private readonly SmtpServerConfiguration _smtpServerConfiguration;

        public string Sender { get; set; }
        public IList<string> Recipients { get; private set; }
        public bool EnableSsl { get; set; }

        private readonly string _subject;
        private readonly ILoggerFormatter _loggerFormatter;

        public EmailSenderLoggerModule(SmtpServerConfiguration smtpServerConfiguration)
            : this(smtpServerConfiguration, GenerateSubjectName()) { }

        public EmailSenderLoggerModule(SmtpServerConfiguration smtpServerConfiguration, string subject)
            : this(smtpServerConfiguration, subject, new DefaultLoggerFormatter()) { }

        public EmailSenderLoggerModule(SmtpServerConfiguration smtpServerConfiguration, ILoggerFormatter loggerFormatter)
            : this(smtpServerConfiguration, GenerateSubjectName(), loggerFormatter) { }

        public EmailSenderLoggerModule(SmtpServerConfiguration smtpServerConfiguration, string subject, ILoggerFormatter loggerFormatter)
        {
            _smtpServerConfiguration = smtpServerConfiguration;
            _subject = subject;
            _loggerFormatter = loggerFormatter;

            Recipients = new List<string>();
        }

        public override string Name
        {
            get { return "EmailSenderLoggerModule"; }
        }

        public override void ExceptionLog(Exception exception)
        {
            if (string.IsNullOrEmpty(Sender) || Recipients.Count == 0)
                throw new NullReferenceException("Not specified email sender and recipient. ");

            var body = MakeEmailBodyFromLogHistory();
            var client = new SmtpClient(_smtpServerConfiguration.Host, _smtpServerConfiguration.Port)
            {
                EnableSsl = EnableSsl,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(_smtpServerConfiguration.UserName, _smtpServerConfiguration.Password)
            };

            foreach (var recipient in Recipients)
            {
                using (var mailMessage = new MailMessage(Sender, recipient, _subject, body))
                {
                    client.Send(mailMessage);
                }
            }
        }

        private static string GenerateSubjectName()
        {
            var currentDate = DateTime.Now;
            return string.Format("SimpleLogger {0} {1}", currentDate.ToShortDateString(), currentDate.ToShortTimeString());
        }

        private string MakeEmailBodyFromLogHistory()
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("Simple logger - email module");

            foreach (var logMessage in Logger.Messages)
                stringBuilder.AppendLine(_loggerFormatter.ApplyFormat(logMessage));

            return stringBuilder.ToString();
        }
    }

    public class SmtpServerConfiguration
    {
        public string UserName { get; private set; }
        public string Password { get; private set; }
        public string Host { get; private set; }
        public int Port { get; private set; }

        public SmtpServerConfiguration(string userName, string password, string host, int port)
        {
            UserName = userName;
            Password = password;
            Host = host;
            Port = port;
        }
    }
}


text:
//
// file : matcher.hpp
// in : file:///home/tim/projects/alphyn/alphyn/matcher.hpp
//
// created by : Timothée Feuillet on linux-vnd3.site
// date: Mon Feb 22 2016 18:19:28 GMT+0100 (CET)
//
//
// Copyright (c) 2016 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

#ifndef __N_8759293292066131115_1257610498__MATCHER_HPP__
# define __N_8759293292066131115_1257610498__MATCHER_HPP__

#include <tools/ct_string.hpp>
#include <tools/regexp/regexp.hpp>
#include <tools/execute_pack.hpp>

namespace neam
{
  namespace ct
  {
    namespace alphyn
    {
      /// \brief Matches a regular expression
      template<const char *RegExpString, size_t StartIndex = 0, size_t EndIndex = size_t(-1)>
      struct regexp
      {
        static constexpr size_t re_string_len = ct::strlen(RegExpString);
        static constexpr size_t stored_string_size = (EndIndex > re_string_len ? re_string_len : EndIndex) - StartIndex;

        template<size_t... Indexes>
        struct string_storage
        {
          static constexpr char reg_exp_string[stored_string_size + 1] = {RegExpString[StartIndex + Indexes]..., '\0'};
        };
        template<size_t Current, size_t... Indexes> struct string_holder : public string_holder<Current - 1, Current - 1, Indexes...> {};
        template<size_t... Indexes> struct string_holder<0, Indexes...> : public string_storage<Indexes...> {};

        using regtype = neam::ct::regexp<string_holder<stored_string_size>::reg_exp_string>;

        static constexpr long match(const char *s, long index)
        {
          return regtype::match(s, index);
        }
      };

      // "normal" implementation of the regexp matcher (no storage overhead)
      template<const char *RegExpString>
      struct regexp<RegExpString, 0, size_t(-1)>
      {
        using regtype = neam::ct::regexp<RegExpString>;

        static constexpr long match(const char *s, long index)
        {
          return regtype::match(s, index);
        }
      };

      /// \brief Matches a string
      /// \note The string must matches whole
      template<const char *String, size_t StartIndex = 0, size_t EndIndex = ct::strlen(String)>
      struct string
      {
        static constexpr size_t string_len = ct::strlen(String);
        static constexpr size_t end_index = (EndIndex > string_len ? string_len : EndIndex);

        static constexpr long match(const char *s, long index)
        {
          size_t i = index;
          size_t j = StartIndex;
          for (; s[i] != '\0' && j < end_index && String[j] == s[i]; ++i, ++j);
          if (j < end_index)
            return -1;
          return i;
        }
      };

      /// \brief Matches a single letter (one of the list)
      template<const char... Char>
      struct letter
      {
        static constexpr long match(const char *s, long index)
        {
          const char c = s[index];
          bool matched = false;
          NEAM_EXECUTE_PACK((c == Char) ? (matched = true) : false);
          return matched ? index + 1 : -1;
        }
      };
    } // namespace alphyn
  } // namespace ct
} // namespace neam

#endif /*__N_8759293292066131115_1257610498__MATCHER_HPP__*/


text:
package org.kie.scanner;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class KieModuleMetaDataImplTest {

    @Test
    public void testIsProcessFile() {
        assertTrue(KieModuleMetaDataImpl.isProcessFile("abc.bpmn"));
        assertTrue(KieModuleMetaDataImpl.isProcessFile("abc.bpmn2"));
        assertTrue(KieModuleMetaDataImpl.isProcessFile("abc.bpmn-cm"));
        assertFalse(KieModuleMetaDataImpl.isProcessFile("abc.bpmn2-cm"));
    }

    @Test
    public void testIsFormFile() {
        assertTrue(KieModuleMetaDataImpl.isFormFile("abc.frm"));
        assertFalse(KieModuleMetaDataImpl.isFormFile("abc.form"));
    }
}


text:
/*  "use strict";
var browserSync = require('browser-sync');

function flaskMiddleware (req, res, next) {
    // Adapted directly from Browsersync exampes:
    //   https://github.com/Browsersync/recipes/tree/master/recipes/middleware.css.injection

    var parsed = require("url").parse(req.url);
    if (parsed.pathname.match(/\api/)) {
        return goFlask(parsed.pathname).then(function (o) {
            res.setHeader('Content-Type', 'text/css');
            res.end(o.css);
        });
    }
    next();

    function goFlask(src) {
        var f = require('fs').readFileSync('app' + src).toString();
        return ;
    }
}
*/

// module.exports = {
//     "files" : "./**/*.{html,htm,css,js}",
//     "server" : {
//         "baseDir" : "./" ,
//         "middleware" : {
//             2 : flaskMiddleware
//         }
//     },
//     "https" : false,
//     "browser" : ["google-chrome", "firefox"],
//     "watchOptions":{ ignored: 'node_modules' }
// }

var proxyMiddleware = require('http-proxy-middleware');
var fallbackMiddleware = require('connect-history-api-fallback');

module.exports = {
    server: {
        middleware: {
            1: proxyMiddleware('/api', {
                target: 'http://127.0.0.1:5000',
                changeOrigin: false   // for vhosted sites, changes host header to match to target's host
            }),

            2: fallbackMiddleware({
                index: '/index.html', verbose: true
            })
        }
    }
};


text:
'use strict';

/**
 * Parameters supplied to the Update Reference Data Set operation.
 *
 */
class ReferenceDataSetUpdateParameters {
  /**
   * Create a ReferenceDataSetUpdateParameters.
   * @member {object} [tags] Key-value pairs of additional properties for the
   * reference data set.
   */
  constructor() {
  }

  /**
   * Defines the metadata of ReferenceDataSetUpdateParameters
   *
   * @returns {object} metadata of ReferenceDataSetUpdateParameters
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ReferenceDataSetUpdateParameters',
      type: {
        name: 'Composite',
        className: 'ReferenceDataSetUpdateParameters',
        modelProperties: {
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = ReferenceDataSetUpdateParameters;


text:
package org.wscale.mountains.mapper;

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

import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wscale.commons.dto.ItemCollection;
import org.wscale.mountains.domain.MountainEntity;
import org.wscale.mountains.dto.Mountain;

@Component
public class MountainMapper extends DozerBeanMapper {

    @Autowired
    private DozerBeanMapper mapper;

    public Mountain mapEntityToDTO(final MountainEntity mountainEntity) {
        return this.mapper.map(mountainEntity, Mountain.class);
    }

    /**
     * Map the MountainEntry objects from the business layer to Mountain DTO objects with the help of Dozer framework.
     * @param mountainEntityList - The list of MountainEntities which whould be mapped.
     * @return - The result Mountains object.
     */
    public ItemCollection<Mountain> mapEntitiesToDTO(final List<MountainEntity> mountainEntityList) {
        final List<Mountain> mountainList = new ArrayList<>();
        for (final MountainEntity mountainEntity : mountainEntityList) {
            mountainList.add(mapEntityToDTO(mountainEntity));
        }
        return new ItemCollection<>(mountainList);
    }

    public MountainEntity mapDTOToEntity(final Mountain mountain) {
        return this.mapper.map(mountain, MountainEntity.class);
    }
}


text:
package continuations

import scala.annotation.tailrec
import scala.collection.immutable.Stream
import scala.util.continuations._

object Generators {
  sealed trait Trampoline[+T]
  case object Done extends Trampoline[Nothing]
  case class Continue[T](result : T, next : Unit => Trampoline[T]) extends Trampoline[T]

  class Generator[T](var cont : Unit => Trampoline[T]) extends Iterator[T] {
    def next : T = {
      cont() match {
        case Continue(r, nextCont) => cont = nextCont; r
        case _ => sys.error("Generator exhausted")
      }
    }

    def hasNext = cont() != Done
  }

  type Gen[T] = cps[Trampoline[T]]

  def generator[T](body : => Unit @Gen[T]) : Generator[T] = {
    new Generator((Unit) => reset { body ; Done })
  }

  def yld[T](t : T) : Unit @Gen[T] =
    shift { (cont : Unit => Trampoline[T]) => Continue(t, cont) }
}

object TestGenerators {
  import Generators._

  def main(args : Array[String]) {
    val fibs = generator {
      //@tailrec
      def fib(s0 : Int, s1 : Int) : Unit @Gen[Int] = {
        yld(s0)
        fib(s1, s0+s1)
      }

      fib(0, 1)
    }

    for(i <- fibs take 10)
      println(i)
  }
}