text:
import * as ex from '@excalibur';
import { TransformComponent } from '@excalibur';
import { ExcaliburAsyncMatchers, ExcaliburMatchers } from 'excalibur-jasmine';
import { GraphicsComponent } from '../engine/Graphics';
import { TestUtils } from './util/TestUtils';

describe('A Graphics ECS System', () => {
  let entities: ex.Entity[];
  let engine: ex.Engine;
  beforeEach(() => {
    jasmine.addMatchers(ExcaliburMatchers);
    jasmine.addAsyncMatchers(ExcaliburAsyncMatchers);

    engine = TestUtils.engine({ width: 100, height: 100 });
    entities = [
      new ex.Entity().addComponent(new ex.TransformComponent()).addComponent(new ex.GraphicsComponent()),
      new ex.Entity().addComponent(new ex.TransformComponent()).addComponent(new ex.GraphicsComponent()),
      new ex.Entity().addComponent(new ex.TransformComponent()).addComponent(new ex.GraphicsComponent())
    ];
    entities[0].get(TransformComponent).z = 10;
    entities[1].get(TransformComponent).z = 5;
    entities[2].get(TransformComponent).z = 1;
  });

  it('exists', () => {
    expect(ex.GraphicsSystem).toBeDefined();
  });

  it('sorts entities by transform.z', () => {
    const sut = new ex.GraphicsSystem();
    engine.currentScene._initialize(engine);
    sut.initialize(engine.currentScene);
    const es = [...entities];
    es.forEach(e => sut.notify(new ex.AddedEntity(e)));
    sut.preupdate();
    expect(sut.sortedTransforms.map(t => t.owner)).toEqual(entities.reverse());
  });

  it('draws entities with transform and graphics components', async () => {
    const sut = new ex.GraphicsSystem();
    const offscreenSystem = new ex.OffscreenSystem();
    engine.currentScene.camera.update(engine, 1);
    engine.currentScene._initialize(engine);
    offscreenSystem.initialize(engine.currentScene);
    sut.initialize(engine.currentScene);

    const rect = new ex.Rectangle({
      width: 25,
      height: 25,
      color: ex.Color.Yellow
    });

    const circle = new ex.Circle({
      radius: 13,
      color: ex.Color.Green
    });

    const rect2 = new ex.Rectangle({
      width: 25,
      height: 25,
      color: ex.Color.Red
    });

    entities[0].get(TransformComponent).pos = ex.vec(25, 25);
    entities[0].get(TransformComponent).rotation = Math.PI / 4;
    entities[0].get(GraphicsComponent).show(rect);

    entities[1].get(TransformComponent).pos = ex.vec(75, 75);
    entities[1].get(GraphicsComponent).show(circle);

    entities[2].get(TransformComponent).pos = ex.vec(75, 25);
    entities[2].get(TransformComponent).scale = ex.vec(2, 2);
    entities[2].get(GraphicsComponent).show(rect2);

    const offscreenRect = rect.clone();
    const offscreen = new ex.Entity().addComponent(new TransformComponent()).addComponent(new GraphicsComponent());
    offscreen.get(TransformComponent).pos = ex.vec(112.5, 112.5);
    offscreen.get(GraphicsComponent).show(offscreenRect);

    spyOn(rect, 'draw').and.callThrough();
    spyOn(circle, 'draw').and.callThrough();
    spyOn(rect2, 'draw').and.callThrough();
    spyOn(offscreenRect, 'draw').and.callThrough();

    entities.push(offscreen);
    engine.graphicsContext.clear();
    entities.forEach(e => sut.notify(new ex.AddedEntity(e)));

    offscreenSystem.update(entities);

    sut.preupdate();
    sut.update(entities, 1);

    expect(rect.draw).toHaveBeenCalled();
    expect(circle.draw).toHaveBeenCalled();
    expect(rect2.draw).toHaveBeenCalled();
    expect(offscreenRect.draw).not.toHaveBeenCalled();

    engine.graphicsContext.flush();
    await expectAsync(TestUtils.flushWebGLCanvasTo2D(engine.canvas)).toEqualImage('src/spec/images/GraphicsSystemSpec/graphics-system.png');
  });

  it('will interpolate body graphics when fixed update is enabled', async () => {
    const game = TestUtils.engine({
      fixedUpdateFps: 30
    });

    await TestUtils.runToReady(game);

    const actor = new ex.Actor({
      x: 100,
      y: 100,
      rotation: 2,
      scale: ex.vec(2, 2)
    });

    actor.body.__oldTransformCaptured = true;

    spyOn(game.graphicsContext, 'translate');
    spyOn(game.graphicsContext, 'rotate');
    spyOn(game.graphicsContext, 'scale');

    const graphicsSystem = new ex.GraphicsSystem();
    graphicsSystem.initialize(game.currentScene);
    graphicsSystem.preupdate();
    graphicsSystem.notify(new ex.AddedEntity(actor));

    game.currentFrameLagMs = 8; // current lag in a 30 fps frame
    graphicsSystem.update([actor], 30);

    expect(game.graphicsContext.translate).toHaveBeenCalledWith(24, 24);
  });

  it('will interpolate child body graphics when fixed update is enabled', async () => {
    const game = TestUtils.engine({
      fixedUpdateFps: 30
    });

    await TestUtils.runToReady(game);

    const parent = new ex.Actor({
      x: 10,
      y: 10
    });

    const actor = new ex.Actor({
      x: 100,
      y: 100,
      rotation: 2,
      scale: ex.vec(2, 2)
    });
    parent.addChild(actor);

    actor.body.__oldTransformCaptured = true;

    spyOn(game.graphicsContext, 'translate');
    spyOn(game.graphicsContext, 'rotate');
    spyOn(game.graphicsContext, 'scale');

    const graphicsSystem = new ex.GraphicsSystem();
    graphicsSystem.initialize(game.currentScene);
    graphicsSystem.preupdate();
    graphicsSystem.notify(new ex.AddedEntity(actor));

    game.currentFrameLagMs = 8; // current lag in a 30 fps frame
    graphicsSystem.update([actor], 30);

    expect(game.graphicsContext.translate).toHaveBeenCalledWith(24, 24);
  });

  it('will not interpolate body graphics if disabled', async () => {
    const game = TestUtils.engine({
      fixedUpdateFps: 30
    });

    await TestUtils.runToReady(game);

    const actor = new ex.Actor({
      x: 100,
      y: 100,
      rotation: 2,
      scale: ex.vec(2, 2)
    });

    actor.body.__oldTransformCaptured = true;

    spyOn(game.graphicsContext, 'translate');
    spyOn(game.graphicsContext, 'rotate');
    spyOn(game.graphicsContext, 'scale');

    const graphicsSystem = new ex.GraphicsSystem();
    graphicsSystem.initialize(game.currentScene);
    graphicsSystem.preupdate();
    graphicsSystem.notify(new ex.AddedEntity(actor));

    actor.body.enableFixedUpdateInterpolate = false;
    game.currentFrameLagMs = 8; // current lag in a 30 fps frame
    graphicsSystem.update([actor], 30);

    expect(game.graphicsContext.translate).toHaveBeenCalledWith(100, 100);
  });

  it('will multiply the opacity set on the context', async () => {
    const sut = new ex.GraphicsSystem();
    const offscreenSystem = new ex.OffscreenSystem();
    engine.currentScene.camera.update(engine, 1);
    engine.currentScene._initialize(engine);
    offscreenSystem.initialize(engine.currentScene);
    sut.initialize(engine.currentScene);

    engine.graphicsContext.opacity = .5;

    const actor = new ex.Actor({
      x: 10,
      y: 10,
      height: 10,
      width: 10,
      color: ex.Color.Red
    });
    actor.graphics.opacity = .5;

    sut.notify(new ex.AddedEntity(actor));

    offscreenSystem.update([actor]);

    engine.graphicsContext.clear();
    sut.preupdate();
    sut.update([actor], 1);

    engine.graphicsContext.flush();
    await expectAsync(TestUtils.flushWebGLCanvasTo2D(engine.canvas))
      .toEqualImage('src/spec/images/GraphicsSystemSpec/graphics-context-opacity.png');
  });
});


text:
				{{ __("Change") }}

					{{ __("Upload") }}
					{{ __("Remove") }}

{% if frm.meta.beta %}

{{ __("Experimental") }}

		{{ __("Click here to post bugs and suggestions") }}

{% endif %}

			{%= __("Feedback") %}

	{% if (frappe.help.has_help(doctype)) { %}

{{ __("Help") }}

	{% } %}

		<svg class="icon icon-sm"><use href="#icon-assign"></use></svg>
		{%= __("Assigned To") %}

		<button class="text-muted btn btn-default icon-btn add-assignment-btn">
			<svg class="icon icon-sm"><use href="#icon-add"></use></svg>
		</button>

		<svg class="icon icon-sm"><use href="#icon-attachment"></use></svg>
		{%= __("Attachments") %}

		<button class="data-pill btn">

				{%= __("Attach File") %}

			<svg class="icon icon-sm">
				<use href="#icon-add"></use>
			</svg>
		</button>

		<svg class="icon icon-sm"><use href="#icon-review"></use></svg>
		{%= __("Reviews") %}

		<button class="add-review-btn text-muted btn btn-default icon-btn">
			<svg class="icon icon-sm"><use href="#icon-add"></use></svg>
		</button>

		<svg class="icon icon-sm"><use href="#icon-share"></use></svg>
		{%= __("Shared With") %}

		<button class="share-doc-btn text-muted btn btn-default icon-btn">
			<svg class="icon icon-sm"><use href="#icon-add"></use></svg>
		</button>

		<svg class="icon icon-sm">
			<use href="#icon-link-url" class="like-icon"></use>
		</svg>
		{%= __("Followed by") %}

			{%= __("Follow") %}

			{%= __("Unfollow") %}

		<svg class="icon icon-sm"><use href="#icon-tag"></use></svg>
		{%= __("Tags") %}

					<svg class="icon icon-sm">
						<use href="#icon-heart" class="like-icon"></use>
					</svg>

			·

				<svg class="icon icon-sm">
					<use href="#icon-comment" class="comment-icon"></use>
				</svg>

			Follow

{% if(frappe.get_form_sidebar_extension) { %}
	{{ frappe.get_form_sidebar_extension() }}
{% } %}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: daniel
 * Date: 01.09.14
 * Time: 21:04
 */

namespace Cundd\PersistentObjectStore\Filter\Comparison;

/**
 * Comparison interface
 *
 * @package Cundd\PersistentObjectStore\Filter
 */
interface ComparisonInterface
{
    /**
     * The '=' comparison operator
     *
     * @api
     */
    const TYPE_EQUAL_TO = '$eq';

    /**
     * The '!=' comparison operator
     *
     * @api
     */
    const TYPE_NOT_EQUAL_TO = '$ne';

    /**
     * The '<' comparison operator
     *
     * @api
     */
    const TYPE_LESS_THAN = '$lt';

    /**
     * The '<=' comparison operator
     *
     * @api
     */
    const TYPE_LESS_THAN_OR_EQUAL_TO = '$lte';

    /**
     * The '>' comparison operator
     *
     * @api
     */
    const TYPE_GREATER_THAN = '$gt';

    /**
     * The '>=' comparison operator
     *
     * @api
     */
    const TYPE_GREATER_THAN_OR_EQUAL_TO = '$gte';

    /**
     * The 'like' comparison operator
     *
     * @api
     */
    const TYPE_LIKE = '$lk';

    /**
     * The 'contains' comparison operator for collections
     *
     * @api
     */
    const TYPE_CONTAINS = '$con';

    /**
     * The 'in' comparison operator
     *
     * @api
     */
    const TYPE_IN = '$in';

    /**
     * The 'is NULL' comparison operator
     *
     * @api
     */
    const TYPE_IS_NULL = '$null';

    /**
     * The 'is empty' comparison operator for collections
     *
     * @api
     */
    const TYPE_IS_EMPTY = '$em';

    /**
     * The 'and' comparison operator for collections
     *
     * @api
     */
    const TYPE_AND = '$and';

    /**
     * The 'or' comparison operator for collections
     *
     * @api
     */
    const TYPE_OR = '$or';

    /**
     * Performs the comparison against the given test value
     *
     * @param mixed $testValue
     * @return bool
     */
    public function perform($testValue);

    /**
     * Returns the type of the comparison from the comparison value against the given test data's property
     *
     * @return string one of the TYPE constants
     */
    public function getOperator();
}


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

#include "chrome/browser/ash/web_applications/help_app/help_app_notification_controller.h"

#include <memory>

#include "ash/constants/ash_features.h"
#include "base/feature_list.h"
#include "base/test/scoped_feature_list.h"
#include "base/version.h"
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "chrome/browser/ash/web_applications/help_app/help_app_discover_tab_notification.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/notifications/notification_display_service_tester.h"
#include "chrome/browser/notifications/system_notification_helper.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/chrome_version_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/account_id/account_id.h"
#include "components/language/core/browser/pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_service_factory.h"
#include "components/prefs/testing_pref_store.h"
#include "components/user_manager/scoped_user_manager.h"
#include "components/version_info/version_info.h"

namespace {
int CurrentMilestone() {
  return version_info::GetVersion().components()[0];
}
}  // namespace

namespace ash {

class HelpAppNotificationControllerTest : public BrowserWithTestWindowTest {
 public:
  HelpAppNotificationControllerTest()
      : user_manager_(new FakeChromeUserManager()),
        scoped_user_manager_(
            std::unique_ptr<FakeChromeUserManager>(user_manager_)) {}
  ~HelpAppNotificationControllerTest() override = default;

  std::unique_ptr<TestingProfile> CreateRegularProfile() {
    AccountId account_id_ =
        AccountId::FromUserEmailGaiaId("user@gmail.com", "12345");
    user_manager_->AddUser(account_id_);
    TestingProfile::Builder builder;
    builder.SetProfileName("user@gmail.com");
    std::unique_ptr<TestingProfile> profile = builder.Build();
    // Set profile creation version, otherwise it defaults to 1.0.0.0.
    ChromeVersionService::SetVersion(profile->GetPrefs(),
                                     version_info::GetVersionNumber());
    return profile;
  }

  std::unique_ptr<TestingProfile> CreateChildProfile() {
    std::unique_ptr<TestingProfile> profile = CreateRegularProfile();
    ChromeVersionService::SetVersion(profile->GetPrefs(),
                                     version_info::GetVersionNumber());
    profile->SetIsSupervisedProfile();
    return profile;
  }

  // Creates a PrefService and registers Autofill prefs.
  std::unique_ptr<PrefService> CreatePrefServiceAndRegisterPrefs() {
    scoped_refptr<user_prefs::PrefRegistrySyncable> registry(
        new user_prefs::PrefRegistrySyncable());
    HelpAppNotificationController::RegisterProfilePrefs(registry.get());
    HelpAppNotificationController::RegisterObsoletePrefsForMigration(
        registry.get());
    PrefServiceFactory factory;
    factory.set_user_prefs(base::MakeRefCounted<TestingPrefStore>());
    return factory.Create(registry);
  }

  void SetUp() override {
    BrowserWithTestWindowTest::SetUp();
    help_app_notification_controller_ =
        std::make_unique<HelpAppNotificationController>(profile());
    TestingBrowserProcess::GetGlobal()->SetSystemNotificationHelper(
        std::make_unique<SystemNotificationHelper>());
    notification_tester_ =
        std::make_unique<NotificationDisplayServiceTester>(nullptr);
    notification_tester_->SetNotificationAddedClosure(base::BindRepeating(
        &HelpAppNotificationControllerTest::OnNotificationAdded,
        base::Unretained(this)));
    scoped_feature_list_.InitWithFeatures(
        /*enabled_features=*/
        {features::kHelpAppDiscoverTabNotificationAllChannels,
         features::kReleaseNotesNotificationAllChannels},
        /*disabled_features=*/{});
    pref_service_ = CreatePrefServiceAndRegisterPrefs();
  }

  void TearDown() override {
    help_app_notification_controller_.reset();
    notification_tester_.reset();
    BrowserWithTestWindowTest::TearDown();
  }

  void OnNotificationAdded() { notification_count_++; }

 protected:
  bool HasDiscoverTabNotification() {
    return notification_tester_
        ->GetNotification(kShowHelpAppDiscoverTabNotificationId)
        .has_value();
  }

  bool HasReleaseNotesNotification() {
    return notification_tester_
        ->GetNotification("show_release_notes_notification")
        .has_value();
  }

  message_center::Notification GetDiscoverTabNotification() {
    return notification_tester_
        ->GetNotification(kShowHelpAppDiscoverTabNotificationId)
        .value();
  }

  message_center::Notification GetReleaseNotesNotification() {
    return notification_tester_
        ->GetNotification("show_release_notes_notification")
        .value();
  }

  PrefService* pref_service() { return pref_service_.get(); }

  FakeChromeUserManager* user_manager_;
  user_manager::ScopedUserManager scoped_user_manager_;
  int notification_count_ = 0;
  std::unique_ptr<HelpAppNotificationController>
      help_app_notification_controller_;
  std::unique_ptr<NotificationDisplayServiceTester> notification_tester_;
  base::test::ScopedFeatureList scoped_feature_list_;
  std::unique_ptr<PrefService> pref_service_;
};

// Tests for pref migration.
TEST_F(HelpAppNotificationControllerTest,
       PrefMigrationCopiesLatestMilestoneWhenNotificationLastShown) {
  ASSERT_EQ(-10, pref_service()->GetInteger(
                     prefs::kHelpAppNotificationLastShownMilestone));

  pref_service()->SetInteger(
      help_app::prefs::kObsoleteReleaseNotesLastShownMilestone, 80);
  pref_service()->SetInteger(
      help_app::prefs::kObsoleteDiscoverTabNotificationLastShownMilestone, 90);

  HelpAppNotificationController::MigrateObsoleteNotificationPrefs(
      pref_service());

  ASSERT_EQ(90, pref_service()->GetInteger(
                    prefs::kHelpAppNotificationLastShownMilestone));
}

TEST_F(HelpAppNotificationControllerTest,
       PrefMigrationWhenOnlyReleaseNotesPrefWasSet) {
  ASSERT_EQ(-10, pref_service()->GetInteger(
                     prefs::kHelpAppNotificationLastShownMilestone));
  ASSERT_EQ(-10, pref_service()->GetInteger(
                     help_app::prefs::kObsoleteReleaseNotesLastShownMilestone));
  ASSERT_EQ(
      -10,
      pref_service()->GetInteger(
          help_app::prefs::kObsoleteDiscoverTabNotificationLastShownMilestone));

  pref_service()->SetInteger(
      help_app::prefs::kObsoleteReleaseNotesLastShownMilestone, 80);

  HelpAppNotificationController::MigrateObsoleteNotificationPrefs(
      pref_service());

  ASSERT_EQ(80, pref_service()->GetInteger(
                    prefs::kHelpAppNotificationLastShownMilestone));
}

TEST_F(HelpAppNotificationControllerTest,
       PrefMigrationWhenOnlyDiscoverTabPrefWasSet) {
  ASSERT_EQ(-10, pref_service()->GetInteger(
                     prefs::kHelpAppNotificationLastShownMilestone));
  ASSERT_EQ(-10, pref_service()->GetInteger(
                     help_app::prefs::kObsoleteReleaseNotesLastShownMilestone));
  ASSERT_EQ(
      -10,
      pref_service()->GetInteger(
          help_app::prefs::kObsoleteDiscoverTabNotificationLastShownMilestone));

  pref_service()->SetInteger(
      help_app::prefs::kObsoleteDiscoverTabNotificationLastShownMilestone, 90);

  HelpAppNotificationController::MigrateObsoleteNotificationPrefs(
      pref_service());

  ASSERT_EQ(90, pref_service()->GetInteger(
                    prefs::kHelpAppNotificationLastShownMilestone));
}

TEST_F(HelpAppNotificationControllerTest,
       PrefMigrationWhenNoObsoletePrefWasSet) {
  ASSERT_EQ(-10, pref_service()->GetInteger(
                     prefs::kHelpAppNotificationLastShownMilestone));
  ASSERT_EQ(-10, pref_service()->GetInteger(
                     help_app::prefs::kObsoleteReleaseNotesLastShownMilestone));
  ASSERT_EQ(
      -10,
      pref_service()->GetInteger(
          help_app::prefs::kObsoleteDiscoverTabNotificationLastShownMilestone));

  HelpAppNotificationController::MigrateObsoleteNotificationPrefs(
      pref_service());

  ASSERT_EQ(-10, pref_service()->GetInteger(
                     prefs::kHelpAppNotificationLastShownMilestone));
  ASSERT_EQ(pref_service()->GetUserPrefValue(
                prefs::kHelpAppNotificationLastShownMilestone),
            nullptr);
}

TEST_F(HelpAppNotificationControllerTest, PrefMigrationHappensOnlyOnce) {
  pref_service()->SetInteger(
      help_app::prefs::kObsoleteReleaseNotesLastShownMilestone, 20);
  pref_service()->SetInteger(
      help_app::prefs::kObsoleteDiscoverTabNotificationLastShownMilestone, 30);

  HelpAppNotificationController::MigrateObsoleteNotificationPrefs(
      pref_service());

  ASSERT_EQ(30, pref_service()->GetInteger(
                    prefs::kHelpAppNotificationLastShownMilestone));

  pref_service()->SetInteger(
      help_app::prefs::kObsoleteReleaseNotesLastShownMilestone, 80);
  pref_service()->SetInteger(
      help_app::prefs::kObsoleteDiscoverTabNotificationLastShownMilestone, 90);

  HelpAppNotificationController::MigrateObsoleteNotificationPrefs(
      pref_service());

  ASSERT_EQ(30, pref_service()->GetInteger(
                    prefs::kHelpAppNotificationLastShownMilestone));
}

// Tests for regular profiles.
TEST_F(HelpAppNotificationControllerTest,
       DoesNotShowAnyNotificationIfNewRegularProfile) {
  std::unique_ptr<Profile> profile = CreateRegularProfile();
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  controller->MaybeShowReleaseNotesNotification();

  EXPECT_EQ(0, notification_count_);
  EXPECT_EQ(false, HasReleaseNotesNotification());

  controller->MaybeShowDiscoverNotification();

  EXPECT_EQ(0, notification_count_);
  EXPECT_EQ(false, HasDiscoverTabNotification());
}

TEST_F(HelpAppNotificationControllerTest,
       ShowsReleaseNotesNotificationIfShownInOlderMilestone) {
  std::unique_ptr<Profile> profile = CreateRegularProfile();
  profile->GetPrefs()->SetInteger(prefs::kHelpAppNotificationLastShownMilestone,
                                  20);
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  controller->MaybeShowReleaseNotesNotification();

  EXPECT_EQ(1, notification_count_);
  EXPECT_EQ(true, HasReleaseNotesNotification());
  EXPECT_EQ(CurrentMilestone(),
            profile->GetPrefs()->GetInteger(
                prefs::kHelpAppNotificationLastShownMilestone));
}

TEST_F(HelpAppNotificationControllerTest,
       DoesNotShowReleaseNotificationIfAlreadyShownInCurrentMilestone) {
  std::unique_ptr<Profile> profile = CreateRegularProfile();
  profile->GetPrefs()->SetInteger(prefs::kHelpAppNotificationLastShownMilestone,
                                  CurrentMilestone());
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  controller->MaybeShowReleaseNotesNotification();

  EXPECT_EQ(0, notification_count_);
  EXPECT_EQ(false, HasDiscoverTabNotification());
}

TEST_F(HelpAppNotificationControllerTest,
       DoesNotShowDiscoverNotificationIfNotChildProfile) {
  std::unique_ptr<Profile> profile = CreateRegularProfile();
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());
  profile->GetPrefs()->SetInteger(prefs::kHelpAppNotificationLastShownMilestone,
                                  20);

  controller->MaybeShowDiscoverNotification();

  EXPECT_EQ(0, notification_count_);
  EXPECT_EQ(false, HasDiscoverTabNotification());
}

// Tests for Child profile.
TEST_F(HelpAppNotificationControllerTest,
       DoesNotShowAnyNotificationIfNewChildProfile) {
  std::unique_ptr<Profile> profile = CreateChildProfile();
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  controller->MaybeShowReleaseNotesNotification();

  EXPECT_EQ(0, notification_count_);
  EXPECT_EQ(false, HasReleaseNotesNotification());

  controller->MaybeShowDiscoverNotification();

  EXPECT_EQ(0, notification_count_);
  EXPECT_EQ(false, HasDiscoverTabNotification());
}

// TODO(b/187774783): Remove this when discover tab is supported in all locales.
TEST_F(HelpAppNotificationControllerTest,
       DoesNotShowDiscoverNotificationIfSystemLanguageNotEnglish) {
  std::unique_ptr<Profile> profile = CreateChildProfile();
  g_browser_process->SetApplicationLocale("fr");
  profile->GetPrefs()->SetInteger(prefs::kHelpAppNotificationLastShownMilestone,
                                  20);
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  controller->MaybeShowDiscoverNotification();

  EXPECT_EQ(0, notification_count_);
  EXPECT_EQ(false, HasDiscoverTabNotification());
}

TEST_F(HelpAppNotificationControllerTest,
       ShowsDiscoverNotificationIfShownInPreviousMilestone) {
  std::unique_ptr<Profile> profile = CreateChildProfile();
  profile->GetPrefs()->SetInteger(prefs::kHelpAppNotificationLastShownMilestone,
                                  91);
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  controller->MaybeShowDiscoverNotification();

  EXPECT_EQ(1, notification_count_);
  EXPECT_EQ(true, HasDiscoverTabNotification());
  EXPECT_EQ(CurrentMilestone(),
            profile->GetPrefs()->GetInteger(
                prefs::kHelpAppNotificationLastShownMilestone));
}

TEST_F(HelpAppNotificationControllerTest,
       DoesNotShowMoreThanOneNotificationPerMilestone) {
  std::unique_ptr<Profile> profile = CreateChildProfile();
  profile->GetPrefs()->SetInteger(prefs::kHelpAppNotificationLastShownMilestone,
                                  91);
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  controller->MaybeShowDiscoverNotification();

  EXPECT_EQ(1, notification_count_);
  EXPECT_EQ(true, HasDiscoverTabNotification());

  controller->MaybeShowReleaseNotesNotification();

  EXPECT_EQ(1, notification_count_);
  EXPECT_EQ(false, HasReleaseNotesNotification());
}

// Tests for suggestion chips.
TEST_F(HelpAppNotificationControllerTest,
       UpdatesReleaseNotesChipPrefWhenReleaseNotesNotificationShown) {
  std::unique_ptr<Profile> profile = CreateRegularProfile();
  profile->GetPrefs()->SetInteger(prefs::kHelpAppNotificationLastShownMilestone,
                                  20);
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  EXPECT_EQ(0, profile->GetPrefs()->GetInteger(
                   prefs::kReleaseNotesSuggestionChipTimesLeftToShow));

  controller->MaybeShowReleaseNotesNotification();

  EXPECT_EQ(3, profile->GetPrefs()->GetInteger(
                   prefs::kReleaseNotesSuggestionChipTimesLeftToShow));
}

TEST_F(HelpAppNotificationControllerTest,
       UpdatesDiscoverTabChipPrefWhenDiscoverTabNotificationShown) {
  std::unique_ptr<Profile> profile = CreateChildProfile();
  profile->GetPrefs()->SetInteger(prefs::kHelpAppNotificationLastShownMilestone,
                                  20);
  std::unique_ptr<HelpAppNotificationController> controller =
      std::make_unique<HelpAppNotificationController>(profile.get());

  EXPECT_EQ(0, profile->GetPrefs()->GetInteger(
                   prefs::kReleaseNotesSuggestionChipTimesLeftToShow));

  controller->MaybeShowDiscoverNotification();

  EXPECT_EQ(3, profile->GetPrefs()->GetInteger(
                   prefs::kDiscoverTabSuggestionChipTimesLeftToShow));
}

}  // namespace ash


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Welcome to use WeLive!</title>


text:
module Homeseed
  class Connection
    include Logging
    attr_reader :servers, :user, :has_password

    def initialize(params={})
      raise ConnectionError, 'servers and/or user not specified' unless params[:servers] and params[:user]
      @servers = params[:servers].split(',')
      @user = params[:user]
      @commands = []
      @logger = params[:logger] || logger

      if params[:has_password]
        cli = HighLine.new
        @password = cli.ask("Enter password: ") { |q| q.echo = false }
      else
        @password = params[:password] || ''
      end

      push_commands(params)
    end

    def push_commands(params={})
      if params[:command]
        @commands.push(*params[:command])
      elsif params[:files]
        push_bash_files(params[:files])
      elsif params[:file]
        push_bash_file(params[:file])
      elsif params[:url]
        push_url_commands(params[:url])
      elsif params[:upload_files]
        @remote_path = params[:remote_path] || '/tmp/'
        @upload_files = params[:upload_files].split(',')
      end
    end

    def config_file_path(file)
      File.expand_path("../../../config/#{file}", __FILE__)
    end

    def push_bash_files(files)
      @files = files
      @files.each do |file|
        push_bash_file(file)
      end
    end

    def push_bash_file(file)
      @file = file
      yml_commands = YAML.load_file(file)
      push_yml_commands(yml_commands)
    end

    def push_url_commands(url)
      response =  HTTParty.get(url)
      raise HTTPartyError unless response.code == 200
      yml_commands = YAML.load(response.body)
      push_yml_commands(yml_commands)
    end

    def push_yml_commands(yml_commands)
      commands = []
      self.process_hash(commands, '', yml_commands)
      @commands.push(*commands)
    end

    def process_hash(commands, current_key, obj)
      if obj.is_a?(Hash)
        obj.each do |new_key, value|
          combined_key = [current_key, new_key].delete_if { |k| k == '' }.join(" ")
          process_hash(commands, combined_key, value)
        end
      elsif obj.is_a?(Array)
        obj.each do |value|
          combined_key = [current_key, value].delete_if { |k| k == '' }.join(" ")
          commands << combined_key
        end
      else
        combined_key = [current_key, obj].delete_if { |k| k == '' }.join(" ")
        commands << combined_key
      end
    end

    def exec(params={})
      if @servers.include?('localhost')
        local_exec
      else
        ssh_exec
      end
    end

    def local_exec
      commands = @commands.join('; ') + ';'
      @logger.info "localhost exec: #{commands}"

      Open3.popen2e('/bin/bash') do |stdin, stdout_err, wait_thr|
        @commands.each do |command|
          stdin.puts(command)
        end
        stdin.close
        while line = stdout_err.gets
          log_exec(line)
        end
      end
    end

    def ssh_exec
      Hash[@servers.map do |server|
        commands = @commands.join('; ') + ';'
        @logger.info "ssh #{@user}@#{server} exec: #{commands}"

        exit_status = nil
        exit_signal = nil

        Net::SSH.start(server, @user, password: @password) do |ssh|
          ssh.open_channel do |channel|
            channel.exec("bash -l") do |ch,success|
              ch.send_data "#{commands}\n"

              ch.on_data do |c,data|
                log_exec(data)
              end

              ch.on_extended_data do |c,type,data|
                log_exec(data)
              end

              ch.on_request("exit-status") do |c,data|
                exit_status = data.read_long
              end

              ch.on_request("exit-signal") do |c,data|
                exit_signal = data.read_long
              end

              ch.send_data "exit\n"
            end
          end
        end
        [server, { exit_status: exit_status, exit_signal: exit_signal }]
      end]
    end

    def log_exec(data)
      data_lines = data.split(/[\r,\n]/)
      data_lines.each do |data_line|
        unless data_line == ''
          if data_line.match(/error|failed|fatal/i)
            @logger.error data_line
          else
            @logger.info data_line
          end
        end
      end
    end

    def scp_upload
      raise ConnectionError, 'cannot scp to localhost' if @servers.include?('localhost')
      @servers.each do |server|
        @upload_files.each do |upload_file|
          @logger.info "starting scp #{upload_file} #{@user}@#{server}:#{@remote_path}"
          begin
            Net::SCP.start(server, @user) { |scp| scp.upload!(upload_file, @remote_path) }
            @logger.info "finished scp #{upload_file} #{@user}@#{server}:#{@remote_path}"
          rescue => err
            @logger.error "scp FAILED #{err}"
          end
        end
      end
    end
  end
end


text:
<?php

/**
 * Created by PhpStorm.
 * User: iodine
 * Date: 16/5/21
 * Time: 上午12:44
 */
require_once "../request_and_respond/DSDRequestResponder.php";
require_once "../account_management/DSDAccountManager.php";
require_once "../account_management/DSDAuthorizationChecker.php";

class DSDRequestAccountHandler{
    public static function register(){
        self::registerAccount(DSDAccountManager::USER);
    }

    public static function registerAccount($type){
        Utils::ensureKeys($GLOBALS["data"], ["username", "email", "password"]);
        if(!$uid=DSDAccountManager::addAccount($GLOBALS["data"]["username"], $GLOBALS["data"]["email"],$type, $GLOBALS["data"]["password"])){
            DSDRequestResponder::respond(false, "Email已经被注册过了");
        }
        DSDRequestResponder::respond(true, null, DSDAccountManager::issueAccessTokenWithID($uid));
    }

    public static function login(){
        self::loginWithType(DSDAccountManager::USER);
    }
    public static function logout(){
        $res = DSDAccountManager::invalidateAccessToken(DSDAuthorizationChecker::getCurrentToken());
        DSDRequestResponder::respond($res);
    }
    public static function loginWithType($type){
        $res=DSDAccountManager::checkAccount($GLOBALS["data"]["email"], $GLOBALS["data"]["password"], $type);
        if($res["success"]){
            DSDRequestResponder::respond(true, null, array(
                "token"=>DSDAccountManager::issueAccessTokenWithID(DSDAccountManager::uidForEmail($GLOBALS["data"]["email"])),
                "type"=>$type
            ));
        }else{
            DSDRequestResponder::respond(false, $res["msg"]);
        }
    }
}


text:
use crate::math::{Isometry, Point};
use crate::partitioning::{VisitStatus, Visitor};
use crate::query::PointQuery;
use na::RealField;

// FIXME: add a point cost fn.

/// Spatial partitioning structure visitor collecting nodes that may contain a given point.
pub struct PointInterferencesCollector<'a, N: 'a + RealField, T: 'a> {
    /// Point to be tested.
    pub point: &'a Point<N>,
    /// The data contained by the nodes which bounding volume contain `self.point`.
    pub collector: &'a mut Vec<T>,
}

impl<'a, N: RealField, T> PointInterferencesCollector<'a, N, T> {
    /// Creates a new `PointInterferencesCollector`.
    #[inline]
    pub fn new(
        point: &'a Point<N>,
        buffer: &'a mut Vec<T>,
    ) -> PointInterferencesCollector<'a, N, T> {
        PointInterferencesCollector {
            point: point,
            collector: buffer,
        }
    }
}

impl<'a, N, T, BV> Visitor<T, BV> for PointInterferencesCollector<'a, N, T>
where
    N: RealField,
    T: Clone,
    BV: PointQuery<N>,
{
    #[inline]
    fn visit(&mut self, bv: &BV, t: Option<&T>) -> VisitStatus {
        if bv.contains_point(&Isometry::identity(), self.point) {
            if let Some(t) = t {
                self.collector.push(t.clone());
            }
            VisitStatus::Continue
        } else {
            VisitStatus::Stop
        }
    }
}


text:
regenerate:
	go install github.com/gogo/protobuf/protoc-gen-gogo
	protoc --gogo_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:../../../../ --proto_path=../../../../:../protobuf/:. *.proto

restore:
	cp gogo.pb.golden gogo.pb.go

preserve:
	cp gogo.pb.go gogo.pb.golden


text:
import Ember from "ember-metal/core";
import create from "ember-metal/platform/create";
import { getFirstKey, getTailPath } from "ember-metal/path_cache";
import { addObserver, removeObserver } from "ember-metal/observer";
import { isStream } from 'ember-metal/streams/utils';
import Subscriber from "ember-metal/streams/subscriber";
import Dependency from "ember-metal/streams/dependency";

/**
  @module ember-metal
*/

/**
  @private
  @class Stream
  @namespace Ember.stream
  @constructor
*/
function Stream(fn, label) {
  this.init(label);
  this.compute = fn;
}

var KeyStream;
var ProxyMixin;

Stream.prototype = {
  isStream: true,

  init(label) {
    this.label = makeLabel(label);
    this.isActive = false;
    this.isDirty = true;
    this.isDestroyed = false;
    this.cache = undefined;
    this.children = undefined;
    this.subscriberHead = null;
    this.subscriberTail = null;
    this.dependencyHead = null;
    this.dependencyTail = null;
    this.observedProxy = null;
  },

  _makeChildStream(key) {
    KeyStream = KeyStream || Ember.__loader.require('ember-metal/streams/key-stream').default;
    return new KeyStream(this, key);
  },

  removeChild(key) {
    delete this.children[key];
  },

  getKey(key) {
    if (this.children === undefined) {
      this.children = create(null);
    }

    var keyStream = this.children[key];

    if (keyStream === undefined) {
      keyStream = this._makeChildStream(key);
      this.children[key] = keyStream;
    }

    return keyStream;
  },

  get(path) {
    var firstKey = getFirstKey(path);
    var tailPath = getTailPath(path);

    if (this.children === undefined) {
      this.children = create(null);
    }

    var keyStream = this.children[firstKey];

    if (keyStream === undefined) {
      keyStream = this._makeChildStream(firstKey, path);
      this.children[firstKey] = keyStream;
    }

    if (tailPath === undefined) {
      return keyStream;
    } else {
      return keyStream.get(tailPath);
    }
  },

  value() {
    // TODO: Ensure value is never called on a destroyed stream
    // so that we can uncomment this assertion.
    //
    // Ember.assert("Stream error: value was called after the stream was destroyed", !this.isDestroyed);

    // TODO: Remove this block. This will require ensuring we are
    // not treating streams as "volatile" anywhere.
    if (!this.isActive) {
      this.isDirty = true;
    }

    var willRevalidate = false;

    if (!this.isActive && this.subscriberHead) {
      this.activate();
      willRevalidate = true;
    }

    if (this.isDirty) {
      if (this.isActive) {
        willRevalidate = true;
      }

      this.cache = this.compute();
      this.isDirty = false;
    }

    if (willRevalidate) {
      this.revalidate(this.cache);
    }

    return this.cache;
  },

  addMutableDependency(object) {
    var dependency = new Dependency(this, object);

    if (this.isActive) {
      dependency.subscribe();
    }

    if (this.dependencyHead === null) {
      this.dependencyHead = this.dependencyTail = dependency;
    } else {
      var tail = this.dependencyTail;
      tail.next = dependency;
      dependency.prev = tail;
      this.dependencyTail = dependency;
    }

    return dependency;
  },

  addDependency(object) {
    if (isStream(object)) {
      this.addMutableDependency(object);
    }
  },

  subscribeDependencies() {
    var dependency = this.dependencyHead;
    while (dependency) {
      var next = dependency.next;
      dependency.subscribe();
      dependency = next;
    }
  },

  unsubscribeDependencies() {
    var dependency = this.dependencyHead;
    while (dependency) {
      var next = dependency.next;
      dependency.unsubscribe();
      dependency = next;
    }
  },

  maybeDeactivate() {
    if (!this.subscriberHead && this.isActive) {
      this.isActive = false;
      this.unsubscribeDependencies();
      this.deactivate();
    }
  },

  activate() {
    this.isActive = true;
    this.subscribeDependencies();
  },

  revalidate(value) {
    if (value !== this.observedProxy) {
      this._clearObservedProxy();

      ProxyMixin = ProxyMixin || Ember.__loader.require('ember-runtime/mixins/-proxy').default;

      if (ProxyMixin.detect(value)) {
        addObserver(value, 'content', this, this.notify);
        this.observedProxy = value;
      }
    }
  },

  _clearObservedProxy() {
    if (this.observedProxy) {
      removeObserver(this.observedProxy, 'content', this, this.notify);
      this.observedProxy = null;
    }
  },

  deactivate() {
    this._clearObservedProxy();
  },

  compute() {
    throw new Error("Stream error: compute not implemented");
  },

  setValue() {
    throw new Error("Stream error: setValue not implemented");
  },

  notify() {
    this.notifyExcept();
  },

  notifyExcept(callbackToSkip, contextToSkip) {
    if (!this.isDirty) {
      this.isDirty = true;
      this.notifySubscribers(callbackToSkip, contextToSkip);
    }
  },

  subscribe(callback, context) {
    Ember.assert("You tried to subscribe to a stream but the callback provided was not a function.", typeof callback === 'function');

    var subscriber = new Subscriber(callback, context, this);
    if (this.subscriberHead === null) {
      this.subscriberHead = this.subscriberTail = subscriber;
    } else {
      var tail = this.subscriberTail;
      tail.next = subscriber;
      subscriber.prev = tail;
      this.subscriberTail = subscriber;
    }

    var stream = this;
    return function(prune) {
      subscriber.removeFrom(stream);
      if (prune) { stream.prune(); }
    };
  },

  prune() {
    if (this.subscriberHead === null) {
      this.destroy(true);
    }
  },

  unsubscribe(callback, context) {
    var subscriber = this.subscriberHead;

    while (subscriber) {
      var next = subscriber.next;
      if (subscriber.callback === callback && subscriber.context === context) {
        subscriber.removeFrom(this);
      }
      subscriber = next;
    }
  },

  notifySubscribers(callbackToSkip, contextToSkip) {
    var subscriber = this.subscriberHead;

    while (subscriber) {
      var next = subscriber.next;

      var callback = subscriber.callback;
      var context = subscriber.context;

      subscriber = next;

      if (callback === callbackToSkip && context === contextToSkip) {
        continue;
      }

      if (context === undefined) {
        callback(this);
      } else {
        callback.call(context, this);
      }
    }
  },

  destroy(prune) {
    if (!this.isDestroyed) {
      this.isDestroyed = true;

      this.subscriberHead = this.subscriberTail = null;
      this.maybeDeactivate();

      var dependencies = this.dependencies;

      if (dependencies) {
        for (var i=0, l=dependencies.length; i<l; i++) {
          dependencies[i](prune);
        }
      }

      this.dependencies = null;
      return true;
    }
  }
};

Stream.wrap = function(value, Kind, param) {
  if (isStream(value)) {
    return value;
  } else {
    return new Kind(value, param);
  }
};

function makeLabel(label) {
  if (label === undefined) {
    return "(no label)";
  } else {
    return label;
  }
}

export default Stream;


text:
You'll want to set the `DJANGO_SETTINGS_MODULE` when you use the `heroku local`
command. I usually just set it to:

        export DJANGO_SETTINGS_MODULE=hub.settings.server

## Load a database backup from Heroku and install it locally:

1. heroku pg:backups capture
2. heroku pg:backups public-url <backup_num>  #=>backup_url
   -  get backup_num with cmd "heroku pgbackups"
3. curl -o latest.dump "<backup_url>"

Then locally do:

    $ pg_restore --verbose --clean --no-acl --no-owner \
      -h localhost -U hub -d hub latest.dump

(your database must exist before can do this)

How I do this (Ben):

    heroku pg:backups capture HEROKU_POSTGRESQL_OLIVE_URL --app aashe-hub-stage
    heroku pg:backups public-url b### --app aashe-hub-stage
    curl -o latest.dump "<backup_url>"

    # Rename the exiting hub database and create new DB called hub

    # Restore: (For some reason I have to run this twice)
    pg_restore --verbose --clean --no-acl --no-owner -h localhost -d hub latest.dump


text:
package org.apache.sling.discovery.commons.providers.base;

import static org.junit.Assert.fail;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEventListener;
import org.apache.sling.discovery.commons.providers.BaseTopologyView;

public class DummyListener implements TopologyEventListener {

    private List<TopologyEvent> allEvents = new LinkedList<TopologyEvent>();
    private List<TopologyEvent> events = new LinkedList<TopologyEvent>();
    private TopologyEvent lastEvent;

    public synchronized void handleTopologyEvent(TopologyEvent event) {
        events.add(event);
        allEvents.add(event);
        lastEvent = event;
    }

    public synchronized List<TopologyEvent> getEvents() {
        return Collections.unmodifiableList(events);
    }

    public synchronized int countEvents() {
        return events.size();
    }

    public synchronized TopologyEvent getLastEvent() {
        return lastEvent;
    }

    public synchronized void clearEvents() {
        events.clear();
    }

    public BaseTopologyView getLastView() {
        if (lastEvent==null) {
            return null;
        } else {
            switch(lastEvent.getType()) {
            case TOPOLOGY_INIT:
            case PROPERTIES_CHANGED:
            case TOPOLOGY_CHANGED: {
                return (BaseTopologyView) lastEvent.getNewView();
            }
            case TOPOLOGY_CHANGING:{
                return (BaseTopologyView) lastEvent.getOldView();
            }
            default: {
                fail("no other types supported yet");
            }
            }
        }
        return null;
    }

}


text:
This is an iOS, Objective-C, Cocoa Touch, iPhone, iPad category for `NSDate`. It gives `NSDate` the ability to report times like `"A moment ago"`, `"30 seconds ago"`, `"5 minutes ago"`, `"Yesterday"`, `"Last month"`, `"2 years ago"`, and so on.

This functionality has variously been referred to as a "time ago", "time since", "relative date", or "fuzzy date" feature.

`NSDate+TimeAgo` currently supports the following languages:

- en (English)
- es (Spanish)
- zh_Hans (Chinese Simplified)
- zh_Hant (Chinese Traditional)
- pt (Portuguese)
- fr (French)
- it (Italian)
- ru (Russian)
- de (German)
- nl (Dutch)
- hu (Hungarian)
- fi (Finnish)
- ja (Japanese)
- vi (Vietnamese)
- ro (Romanian)
- da (Danish)
- cs (Czech)
- nb (Norwegian)
- lv (Latvian)
- tr (Turkish)
- ko (Korean)
- bg (Bulgarian)
- he (Hebrew)
- ar (Arabic)
- gre (Greek)
- pl (Polish)
- sv (Swedish)
- th (Thai)

If you know a language not listed here, please consider submitting a translation. [Localization codes by language](http://stackoverflow.com/questions/3040677/locale-codes-for-iphone-lproj-folders).

This project is user driven (by people like you). Pull requests close faster than issues (merged or rejected).

## Use

1.  `Add` the files to your project - manually or via Cocoapods (`pod 'NSDate+TimeAgo'`)
2.  Import the header using  `#import "NSDate+TimeAgo.h"`
3.  Call the `timeAgo` method in the following way:

<pre>
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:0];
NSString *ago = [date timeAgo];
NSLog(@"Output is: \"%@\"", ago);
2011-11-12 17:19:25.608 Proj[0:0] Output is: "41 years ago"
</pre>

2 other methods are available:

* `dateTimeAgo`: returns times with only strings of the type: "*{value}* *{unit}* ago"
* `dateTimeUntilNow`: returns only "yesterday" / "this morning" / "last week" / "this month" -- less precise than `dateTimeAgo` but more natural

Those three methods can be interchanged as they have the same signature.

## Future Directions

Would be nice to

1.  add customization options (e.g., should it report seconds or just "a minute ago")
2.  add string customization
3.  have more localizations
4.  make `dateTimeUntilNow` more precise: instead of "Last week" use "Last Friday", "Last Monday" etc.
5.  other

## License

Released under ISC (similar to 2-clause BSD)

http://wikipedia.org/wiki/ISC_license

## Credits

Originally based on code Christopher Pickslay posted to Forrst. Used with permission. http://twitter.com/cpickslay

Ramon Torres began support for internationalization/localization. Added `es` strings. http://rtorres.me/

Dennis Zhuang added `zh_Hans` Chinese Simplified strings. http://fnil.net/

Mozart Petter added `pt_BR` Brazilian Portuguese strings. http://www.mozartpetter.com/

Stéphane Gerardot added `fr` French strings.

Marco Sanson added `it` Italian strings. http://marcosanson.tumblr.com/

Almas Adilbek added `ru` Russian strings. Extended logic to support Russian idioms. http://mixdesign.kz/

Mallox51 added `de` German strings. https://github.com/Mallox51

Tieme van Veen added `nl` Dutch strings. http://www.tiemevanveen.nl

Árpád Goretity added `hu` Hungarian strings. http://apaczai.elte.hu/~13akga/

Anajavi added `fi` Finnish strings. https://github.com/anajavi

Tonydyb added `ja` Japanese strings.

Vinhnx added `vi` Vietnamese strings. http://vinhnx.github.io/

Ronail added `zh_Hant` Traditional Chinese strings. https://github.com/ronail

SorinAntohi added `ro` Romanian strings. https://github.com/SorinAntohi

spookd added `da` Danish strings. https://github.com/spookd

Barrett Jacobsen added `cs` Czech strings.  https://github.com/barrettj

Dmitry Shmidt added `nb` Norwegian strings. https://github.com/shmidt

Martins Rudens added `lv` Latvian strings. https://github.com/rudensm

Osman Saral added `tr` Turkish strings. https://github.com/osrl

analogstyle added `ko` Korean strings. http://almacreative.net/

Flavio Caetano fixed `pt` Portuguese strings. http://flaviocaetano.com

kolarski added `bg` Bulgarian strings. http://github.com/kolarski

Vladimir Kofman added `he` Hebrew strings. https://github.com/vladimirkofman

Viraf Sarkari added `ar` Arabic, `gre` Greek, `pl` Polish, `sv` Swedish, and `th` Thai strings. https://github.com/viraf


text:
package io.fabric8.java.generator.testing;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.github.difflib.text.DiffRow;
import com.github.difflib.text.DiffRowGenerator;
import io.fabric8.zjsonpatch.JsonDiff;
import io.fabric8.zjsonpatch.JsonPatch;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class KubernetesResourceDiff {

  // ANSI colors for the shell
  private static final String ANSI_RESET = "\u001B[0m";
  private static final String ANSI_RED = "\u001B[31m";
  private static final String ANSI_GREEN = "\u001B[32m";

  private final String source1;
  private final String source2;

  private ObjectMapper yamlMapper = new ObjectMapper(
      new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));

  public KubernetesResourceDiff(String source1, String source2) {
    this.source1 = source1;
    this.source2 = source2;
  }

  public List<JsonNode> getListOfDiffs() {
    try {
      JsonNode source1Json = yamlMapper.readTree(this.source1);
      JsonNode source2Json = yamlMapper.readTree(this.source2);
      JsonNode diff = JsonDiff.asJson(source1Json, source2Json);
      List<JsonNode> aggregatedDiffs = StreamSupport.stream(diff.spliterator(), false).collect(Collectors.toList());

      if (!aggregatedDiffs.isEmpty()) {
        JsonNode generatedDiff = JsonPatch.apply(diff, source1Json);

        DiffRowGenerator generator = DiffRowGenerator.create()
            .showInlineDiffs(true)
            .inlineDiffByWord(true)
            .oldTag(b -> Boolean.TRUE.equals(b) ? ANSI_RED : ANSI_RESET)
            .newTag(b -> Boolean.TRUE.equals(b) ? ANSI_GREEN : ANSI_RESET)
            .build();

        List<DiffRow> rows = generator.generateDiffRows(
            Arrays.asList(
                yamlMapper.writeValueAsString(source1Json).split("\n")),
            Arrays.asList(
                yamlMapper.writeValueAsString(generatedDiff).split("\n")));

        int maxWidth = 0;
        for (DiffRow row : rows) {
          maxWidth = Math.max(
              maxWidth,
              Math.max(
                  row.getOldLine()
                      .getBytes(StandardCharsets.UTF_8).length,
                  row.getNewLine()
                      .getBytes(StandardCharsets.UTF_8).length));
        }

        // Result should looks similar to: https://www.yamldiff.com/
        for (DiffRow row : rows) {
          System.err.printf(
              "%-" + maxWidth + "s %-" + maxWidth + "s\n",
              row.getOldLine(),
              row.getNewLine());
        }
      }

      return aggregatedDiffs;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}


text:
#include "modules/audio_coding/codecs/opus/opus_interface.h"
#include "modules/audio_coding/codecs/opus/opus_inst.h"
#include "modules/audio_coding/neteq/tools/neteq_quality_test.h"
#include BOSS_WEBRTC_U_rtc_base__flags_h //original-code:"rtc_base/flags.h"

using testing::InitGoogleTest;

namespace webrtc {
namespace test {
namespace {

static const int kOpusBlockDurationMs = 20;
static const int kOpusSamplingKhz = 48;

DEFINE_int(bit_rate_kbps, 32, "Target bit rate (kbps).");

DEFINE_int(complexity, 10, "Complexity: 0 ~ 10 -- defined as in Opus"
    "specification.");

DEFINE_int(maxplaybackrate, 48000, "Maximum playback rate (Hz).");

DEFINE_int(application, 0, "Application mode: 0 -- VOIP, 1 -- Audio.");

DEFINE_int(reported_loss_rate, 10, "Reported percentile of packet loss.");

DEFINE_bool(fec, false, "Enable FEC for encoding (-nofec to disable).");

DEFINE_bool(dtx, false, "Enable DTX for encoding (-nodtx to disable).");

DEFINE_int(sub_packets, 1, "Number of sub packets to repacketize.");

}  // namespace

class NetEqOpusQualityTest : public NetEqQualityTest {
 protected:
  NetEqOpusQualityTest();
  void SetUp() override;
  void TearDown() override;
  int EncodeBlock(int16_t* in_data, size_t block_size_samples,
                  rtc::Buffer* payload, size_t max_bytes) override;
 private:
  WebRtcOpusEncInst* opus_encoder_;
  OpusRepacketizer* repacketizer_;
  size_t sub_block_size_samples_;
  int bit_rate_kbps_;
  bool fec_;
  bool dtx_;
  int complexity_;
  int maxplaybackrate_;
  int target_loss_rate_;
  int sub_packets_;
  int application_;
};

NetEqOpusQualityTest::NetEqOpusQualityTest()
    : NetEqQualityTest(kOpusBlockDurationMs * FLAG_sub_packets,
                       kOpusSamplingKhz,
                       kOpusSamplingKhz,
                       NetEqDecoder::kDecoderOpus),
      opus_encoder_(NULL),
      repacketizer_(NULL),
      sub_block_size_samples_(
          static_cast<size_t>(kOpusBlockDurationMs * kOpusSamplingKhz)),
      bit_rate_kbps_(FLAG_bit_rate_kbps),
      fec_(FLAG_fec),
      dtx_(FLAG_dtx),
      complexity_(FLAG_complexity),
      maxplaybackrate_(FLAG_maxplaybackrate),
      target_loss_rate_(FLAG_reported_loss_rate),
      sub_packets_(FLAG_sub_packets) {
  // Flag validation
  RTC_CHECK(FLAG_bit_rate_kbps >= 6 && FLAG_bit_rate_kbps <= 510)
      << "Invalid bit rate, should be between 6 and 510 kbps.";

  RTC_CHECK(FLAG_complexity >= -1 && FLAG_complexity <= 10)
      << "Invalid complexity setting, should be between 0 and 10.";

  RTC_CHECK(FLAG_application == 0 || FLAG_application == 1)
      << "Invalid application mode, should be 0 or 1.";

  RTC_CHECK(FLAG_reported_loss_rate >= 0 && FLAG_reported_loss_rate <= 100)
      << "Invalid packet loss percentile, should be between 0 and 100.";

  RTC_CHECK(FLAG_sub_packets >= 1 && FLAG_sub_packets <= 3)
      << "Invalid number of sub packets, should be between 1 and 3.";

  // Redefine decoder type if input is stereo.
  if (channels_ > 1) {
    decoder_type_ = NetEqDecoder::kDecoderOpus_2ch;
  }
  application_ = FLAG_application;
}

void NetEqOpusQualityTest::SetUp() {
  // Create encoder memory.
  WebRtcOpus_EncoderCreate(&opus_encoder_, channels_, application_);
  ASSERT_TRUE(opus_encoder_);

  // Create repacketizer.
  repacketizer_ = opus_repacketizer_create();
  ASSERT_TRUE(repacketizer_);

  // Set bitrate.
  EXPECT_EQ(0, WebRtcOpus_SetBitRate(opus_encoder_, bit_rate_kbps_ * 1000));
  if (fec_) {
    EXPECT_EQ(0, WebRtcOpus_EnableFec(opus_encoder_));
  }
  if (dtx_) {
    EXPECT_EQ(0, WebRtcOpus_EnableDtx(opus_encoder_));
  }
  EXPECT_EQ(0, WebRtcOpus_SetComplexity(opus_encoder_, complexity_));
  EXPECT_EQ(0, WebRtcOpus_SetMaxPlaybackRate(opus_encoder_, maxplaybackrate_));
  EXPECT_EQ(0, WebRtcOpus_SetPacketLossRate(opus_encoder_,
                                            target_loss_rate_));
  NetEqQualityTest::SetUp();
}

void NetEqOpusQualityTest::TearDown() {
  // Free memory.
  EXPECT_EQ(0, WebRtcOpus_EncoderFree(opus_encoder_));
  opus_repacketizer_destroy(repacketizer_);
  NetEqQualityTest::TearDown();
}

int NetEqOpusQualityTest::EncodeBlock(int16_t* in_data,
                                      size_t block_size_samples,
                                      rtc::Buffer* payload, size_t max_bytes) {
  EXPECT_EQ(block_size_samples, sub_block_size_samples_ * sub_packets_);
  int16_t* pointer = in_data;
  int value;
  opus_repacketizer_init(repacketizer_);
  for (int idx = 0; idx < sub_packets_; idx++) {
    payload->AppendData(max_bytes, [&] (rtc::ArrayView<uint8_t> payload) {
        value = WebRtcOpus_Encode(opus_encoder_,
                                  pointer, sub_block_size_samples_,
                                  max_bytes, payload.data());

        Log() << "Encoded a frame with Opus mode "
              << (value == 0 ? 0 : payload[0] >> 3)
              << std::endl;

        return (value >= 0) ? static_cast<size_t>(value) : 0;
      });

    if (OPUS_OK != opus_repacketizer_cat(repacketizer_,
                                         payload->data(), value)) {
      opus_repacketizer_init(repacketizer_);
      // If the repacketization fails, we discard this frame.
      return 0;
    }
    pointer += sub_block_size_samples_ * channels_;
  }
  value = opus_repacketizer_out(repacketizer_, payload->data(),
                                static_cast<opus_int32>(max_bytes));
  EXPECT_GE(value, 0);
  return value;
}

TEST_F(NetEqOpusQualityTest, Test) {
  Simulate();
}

}  // namespace test
}  // namespace webrtc


text:
Configurable soundboard for Discord

The goal of this project is to create an easily-configurable, self-hosted soundboard for Discord communities. Inspired by [airhornbot](https://github.com/hammerandchisel/airhornbot), my community wanted a similar bot tailored to our personal in-jokes and lore. This project uses much of the same data structures and Discord API calls as airhornbot, but is less focused on organizing sounds into collections and more focused on providing a growable list of specific commands.

TODO:
* Track stats on sound usage
* Improve process of inviting bot to server (how does Discord Music Bot Work?)
* Move persistence away from flat file into some sort of true database system

## Installation Instructions

### Set up a Discord Application

Before you pull or run any code, browse to your [Discord My Apps](https://discordapp.com/developers/applications/me) page and create a new app. The name and icon don't matter- just choose something fun that your community will appreciate. Once your app is created, you'll need to click the **Create a Bot User** button. Once you've done that, you should be able to access your Token, which you'll need to plug into Discord Soundboard to use.

You also need to invite your bot to your server, which you can do right now. Take the following URL, and replace the client ID with the client ID listed on your application's page:

`https://discordapp.com/oauth2/authorize?&client_id=YOUR_CLIENT_ID_HERE&scope=bot&permissions=0 `

You should be directed to a standardized Discord authorization prompt, which will allow you to add your bot to your server, provided you have the correct permissions.

### Install Go

I'm not going to get into the weeds of installing Go on your system, but following [Golang's getting started](https://golang.org/doc/install) page should get you 99% of the way there. Just make sure that you set your `GOPATH` environment variable so that `go get` and `go install` work correctly.

### Pull From Github

Once you have Go installed and ready to "go" (:wink:), pull down this project with `go get github.com/mkolas/discord-soundboard`.

### Configure

In `discord-soundboard/config/config.json`, replace the Token value from the existing dummy string with the bot token provided by the Discord My Apps page.

You can also set a Status value, which will set the default status of the bot on Discord's member list. This is useful if you want to point your community members to the URL of your upload form, for example.

If you'd like to run on a port other than 8000, you can also set an alternative Port in this configuration file.

### Run!

The bot can then be run with `go run main.go` from the `$GOPATH/src/github.com/mkolas/discord-soundboard` directory. More preferably, you can run `go install` which will create a `discord-soundboard` execuable in `$GOPATH/bin`. You'll have to copy the `config` and `sounds` directories over to `$GOPATH/bin`, but running from the `bin` directory will allow you to keep an installed binary away from any code you may choose to modify.

A simple website for creating and managing sounds a

### Commands

Typing `!commands` in your Discord chat should cause the Soundboard to output the list of available commands in the system. Each command should be prefixed with a `!`. This prefix character will be configuable eventually.

### Creating Sounds

Sounds can be added to the Soundboard in one of two ways:

1. Using [dca-rs](https://github.com/nstafie/dca-rs), you can generate .dca files and then add them to `config/sounds.csv`. Each row should identify the location of the sound (from `sounds/`) and the command (without `!` prefix) used to play it. Using `dca-rs`, the command to generate a sound should be `./dca-rs -i <input wav file> --raw > <output file>`. Make sure that you don't forget the `--raw` flag!
2. Using the supplied web page and service, sounds can be added by browsing to `localhost:<port>/dsb/upload.html` and submitting the form. Just make sure that `dca-rs` and `ffmpeg` are available on your `PATH`, otherwise this might not work. This is not completely battle tested right now, but should work for simple sound management.

Note: it has come to my attention that dca-rs has been removed from GitHub and is no longer available.

### Questions, Comments, Concerns?

Please feel free to get at me- I'd love more folks to be able to experience this wonderful and weird project.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Duality;

namespace YMR.ComplexBody.Core
{
	/// <summary>
	/// Defines a Duality core plugin.
	/// </summary>
	public class ComplexBodyCorePlugin : CorePlugin
	{
		// Override methods here for global logic
	}
}


text:
<?php

namespace DOMPDFModule\Mvc\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use DOMPDFModule\View\Renderer\PdfRenderer;

class ViewPdfRendererFactory implements FactoryInterface
{
    /**
     * Create and return the PDF view renderer
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return PdfRenderer
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $viewManager = $serviceLocator->get('ViewManager');

        $pdfRenderer = new PdfRenderer();
        $pdfRenderer->setResolver($viewManager->getResolver());
        $pdfRenderer->setHtmlRenderer($viewManager->getRenderer());
        $pdfRenderer->setEngine($serviceLocator->get('dompdf'));

        return $pdfRenderer;
    }
}


text:
let util = require('./test_util');

describe('source locations', function() {
  it('cucumber 1 provides source locations to protractor', function() {
    return util
      .runOne(
        'test/cucumber/conf/cucumber1Conf.js --cucumberOpts.tags @sourceLocation'
      )
      .expectExitCode(0)
      .expectEvents([
        {
          emitterEvent: 'testPass',
          category: 'Running Cucumber with Protractor: Wrapping WebDriver',
          name: 'Given I go on "index.html"',
          sourceLocation: {
            filePath: /.*\/protractor-cucumber-framework\/test\/cucumber\/features\/cucumber1\.feature/,
            line: 14,
            column: 1
          }
        },
        {
          emitterEvent: 'testPass',
          category: 'Running Cucumber with Protractor: Wrapping WebDriver',
          name: 'Then the title should equal "My AngularJS App"',
          sourceLocation: {
            filePath: /.*\/protractor-cucumber-framework\/test\/cucumber\/features\/cucumber1\.feature/,
            line: 15,
            column: 1
          }
        }
      ])
      .run();
  });

  it('cucumber 2 provides source locations to protractor', function() {
    return util
      .runOne(
        'test/cucumber/conf/cucumber2Conf.js --cucumberOpts.tags @cucumber2'
      )
      .cucumberVersion2()
      .expectExitCode(0)
      .expectEvents([
        {
          emitterEvent: 'testPass',
          category: 'Running Cucumber 2 with Protractor: Using Cucumber 2',
          name: 'Given I go on "index.html"',
          sourceLocation: {
            filePath: /.*\/protractor-cucumber-framework\/test\/cucumber\/features\/cucumber2\.feature/,
            line: 5,
            column: 1
          }
        },
        {
          emitterEvent: 'testPass',
          category: 'Running Cucumber 2 with Protractor: Using Cucumber 2',
          name: 'Then the title should equal "My AngularJS App"',
          sourceLocation: {
            filePath: /.*\/protractor-cucumber-framework\/test\/cucumber\/features\/cucumber2\.feature/,
            line: 6,
            column: 1
          }
        }
      ])
      .run();
  });

  it('cucumber 3 provides source locations to protractor', function() {
    return util
      .runOne(
        'test/cucumber/conf/cucumber3Conf.js --cucumberOpts.tags @cucumber3'
      )
      .cucumberVersion3()
      .expectExitCode(0)
      .expectEvents([
        {
          emitterEvent: 'testPass',
          category: 'Running Cucumber 3 with Protractor: Using Cucumber 3',
          name: 'Given I go on "index.html"',
          sourceLocation: {
            filePath: /.*\/cucumber\/features\/cucumber3\.feature/,
            line: 5,
            column: 5
          }
        },
        {
          emitterEvent: 'testPass',
          category: 'Running Cucumber 3 with Protractor: Using Cucumber 3',
          name: 'Then the title should equal "My AngularJS App"',
          sourceLocation: {
            filePath: /.*\/cucumber\/features\/cucumber3\.feature/,
            line: 6,
            column: 5
          }
        }
      ])
      .run();
  });
});


text:
This module provide an asyncio API for the the Tkinter event loop

License: MIT (see LICENSE)

Requirements
============

-  Unix platform (it doesn't work on Windows because of the lack of
   **Tcl\_CreateFileHandler** on this platform)
-  Python >= 3.5

Installation
============

.. code:: sh

    python setup.py install

Usage
=====

**aiotkinter** expose an event loop policy (which based on the default
event loop policy of **asyncio**) so the only thing you have to do is to
set the global event loop policy with an instance of
**TkinterEventLoopPolicy**:

.. code:: python

    import asyncio
    import aiotkinter

    asyncio.set_event_loop_policy(aiotkinter.TkinterEventLoopPolicy())
    loop = asyncio.get_event_loop()
    loop.run_forever()


text:
/*
 * ======== Standard MSP430 includes ========
 */

#include <stdio.h>

// bsp modules required
#include "board.h"
#include "uart0.h"
//#include "uart1.h"
#include "spi.h"
#include "bsp_timer.h"
#include "leds.h"

// dpa framework
#include "dpa_library.h"

//=========================== defines =========================================

#define BSP_TIMER_PERIOD     	32 		// 32@32kHz = 1ms
#define USER_TIMER_PERIOD	1000		// 1000@1ms = 1s

static const uint8_t requestToSend[]       	= "Req: ";
static const uint8_t confirmationToSend[]  	= "Con: ";
static const uint8_t responseToSend[]       	= "Res: ";
static const uint8_t endingToSend[] 		= "\r\n\n";

#define CONFIRMATION			1
#define RESPONSE			2

#define NO_WAITING			0
#define CONFIRMATION_WAITING		1
#define RESPONSE_WAITING		2

#define COORDINATOR			0x00
#define NODE1				0x01
#define NODE2				0x02
#define NODE3				0x03
#define NODE4				0x04
#define NODE5				0x05
#define LOCAL               0xFC

//=========================== variables =======================================

typedef enum {
	GLED_PULSE,
	RLED_PULSE
}DPA_RQ;

typedef struct {
   // uart
   volatile uint8_t uart0Done;
   uint8_t uart0_lastTxByteIndex;
   //volatile uint8_t uart1Done;
   // spi
   uint8_t txbuf[1];
   uint8_t rxbuf[1];
   // dpa
   volatile	uint16_t dpaTimeoutCnt;
   uint16_t	dpaStep;
   T_DPA_PACKET myDpaRequest;
   char *ptrRequest;
   uint8_t debugRequest;
   T_DPA_PACKET myDpaAnswer;
   char *ptrAnswer;
   //debug
   uint8_t debugAnswer;
   uint8_t debugActive;
   char debugString[128];
   //timer
   volatile uint16_t swTimer;
   volatile uint8_t swTimerAck;
   volatile uint8_t ticks;
   DPA_RQ cmds;
} app_vars_t;

app_vars_t app_vars;

//=========================== prototypes ======================================

void MyDpaAnswerHandler(T_DPA_PACKET *MyDpaAnswer);
void MyDpaLibTimeoutHandler(void);
void MyDpaLibRequests(void);

//dpa requests
void DpaLedG(uint16_t addr, uint8_t cmd);
void DpaLedR(uint16_t addr, uint8_t cmd);

//user timer
void MySwTimerTimeoutHandler(void);

//debug
void MyDebugMessages(void);

//dpa driver timing
void cb_compare(void);

//usb interface 115200
void cb_uart0TxDone(void);
void cb_uart0RxCb(void);

//dpa interface 115200
//void cb_uart1TxDone(void);
//void cb_uart1RxCb(void);

//=========================== main ============================================

int mote_main(void) {

	// clear local variable
	memset(&app_vars,0,sizeof(app_vars_t));
	app_vars.swTimer = USER_TIMER_PERIOD;

	// initialize the board
	board_init();

	// setup UART0
	uart0_setCallbacks(cb_uart0TxDone,cb_uart0RxCb);
	uart0_enableInterrupts();

	// setup UART1
	//uart1_setCallbacks(cb_uart1TxDone,cb_uart1RxCb);
	//uart1_enableInterrupts();

	// setup BSP timer
	bsp_timer_set_callback(cb_compare);
	bsp_timer_scheduleIn(BSP_TIMER_PERIOD);

	DPA_Init();					// DPA library initialization
	DPA_SetAnswerHandler(MyDpaAnswerHandler);	// set DPA response handler

	for (;;) {

		// dpa msgs
		if(app_vars.swTimerAck == TRUE) {
/*
			// to test basic spi communication
			leds_red_toggle();

			app_vars.txbuf[0] = 0x00;

			spi_txrx(
         			app_vars.txbuf,
         			sizeof(app_vars.txbuf),
         			SPI_BUFFER,
         			app_vars.rxbuf,
         			sizeof(app_vars.rxbuf),
         			SPI_FIRST,
         			SPI_LAST
      			);

			if(app_vars.rxbuf[0] == 0x80)
				leds_green_toggle();
*/

			MyDpaLibRequests();				// function for sending DPA requests - SPI/UART1
			app_vars.swTimerAck = FALSE;
		}

		// debug msgs
		if(!app_vars.debugActive) {				// only if there no debug processing already on
			if(app_vars.debugRequest == TRUE || \
					(app_vars.debugAnswer == CONFIRMATION) || (app_vars.debugAnswer == RESPONSE))  {
				MyDebugMessages();			// function for printing DEBUG messages - UART0
			}
		}

		DPA_LibraryDriver();					// DPA library handler
	}
}

/**
 * DPA requests sending
 *
 * @param 	none
 * @return 	none
 *
 **/
void MyDpaLibRequests(void) {
	// if DPA library is busy, or dpa operation in progress, then return
	if (DPA_GetStatus() != DPA_READY || app_vars.dpaStep != NO_WAITING) {
		leds_red_toggle();
		return;
	}

	// 100ms before sending another request
	app_vars.ticks = 100;
	while(app_vars.ticks)
		;

	switch(app_vars.cmds) {

		case GLED_PULSE:
			DpaLedG(COORDINATOR, CMD_LED_PULSE);
			app_vars.debugRequest = TRUE;
		break;

		case RLED_PULSE:
			DpaLedR(NODE1, CMD_LED_PULSE);
			//DpaLedR(COORDINATOR, CMD_LED_PULSE);
			app_vars.debugRequest = TRUE;
		break;

		default:
		break;
	}

	leds_green_toggle();

	if (app_vars.myDpaRequest.NAdr == 0x00 || app_vars.myDpaRequest.NAdr == 0xFC)
		app_vars.dpaStep = RESPONSE_WAITING;			// dpa answer would be response
	else
		app_vars.dpaStep = CONFIRMATION_WAITING;		// dpa answer would be confirmation
}
//=============================================================================

/**
 * DPA answer handler
 *
 * @param 	pointer to DPA answer packet
 * @return 	none
 *
 **/
void MyDpaAnswerHandler(T_DPA_PACKET *dpaAnswerPkt) {

	if (app_vars.dpaStep == CONFIRMATION_WAITING
			&& dpaAnswerPkt->Extension.Confirmation.StatusConfirmation
					== STATUS_CONFIRMATION) {
		app_vars.dpaStep = RESPONSE_WAITING;
		app_vars.dpaTimeoutCnt = DPA_GetEstimatedTimeout();

		memcpy(&app_vars.myDpaAnswer, dpaAnswerPkt, sizeof(app_vars.myDpaAnswer));
		app_vars.debugAnswer = CONFIRMATION;

		return;
	}

	if (app_vars.dpaStep == RESPONSE_WAITING
			&& dpaAnswerPkt->Extension.Response.ResponseCode == STATUS_NO_ERROR) {
		app_vars.dpaStep = NO_WAITING;
		app_vars.dpaTimeoutCnt = 0;

		// ANY USER CODE FOR DPA RESPONSE PROCESSING
		memcpy(&app_vars.myDpaAnswer, dpaAnswerPkt, sizeof(app_vars.myDpaAnswer));
		app_vars.debugAnswer = RESPONSE;

		app_vars.cmds++;
		app_vars.cmds %= 2;

		return;
	}

	// ANY USER CODE FOR ASYNCHRONOUS DPA MESSAGES PROCESSING
}
//=============================================================================

/**
 * DPA response timeout handler
 *
 * @param 	none
 * @return 	none
 *
 **/
void MyDpaLibTimeoutHandler(void) {
	app_vars.dpaStep = NO_WAITING;

	// ANY USER CODE FOR OPERATION TIMEOUT HANDLING
	app_vars.cmds++;
	app_vars.cmds %= 2;
}
//=============================================================================

/**
 * DPA request to drive ledG peripheral
 *
 * @param 	addr
 * @param 	cmd
 * @return
 *
 **/
void DpaLedG(uint16_t addr, uint8_t cmd) {
	app_vars.myDpaRequest.NAdr = addr;
	app_vars.myDpaRequest.PNum = PNUM_LEDG;
	app_vars.myDpaRequest.PCmd = cmd;
	app_vars.myDpaRequest.HwProfile = HW_PROFILE_DO_NOT_CHECK;

	// initial timeout 1s for either confirmation or response
	app_vars.dpaTimeoutCnt = 1000;

	DPA_SendRequest(&app_vars.myDpaRequest, 0);
}

/**
 * DPA request to drive ledR peripheral
 *
 * @param 	addr
 * @param 	cmd
 * @return
 *
 **/
void DpaLedR(uint16_t addr, uint8_t cmd) {
	app_vars.myDpaRequest.NAdr = addr;
	app_vars.myDpaRequest.PNum = PNUM_LEDR;
	app_vars.myDpaRequest.PCmd = cmd;
	app_vars.myDpaRequest.HwProfile = HW_PROFILE_DO_NOT_CHECK;

	// initial timeout 1s for either confirmation or response
	app_vars.dpaTimeoutCnt = 1000;

	DPA_SendRequest(&app_vars.myDpaRequest, 0);
}

/**
 * User timer timeout handler
 *
 * @param 	none
 * @return 	none
 *
 **/
void MySwTimerTimeoutHandler(void) {
	app_vars.swTimerAck = TRUE;
}
//=============================================================================

/**
 * Printing messages over UART(USB)
 *
 * @param 	none
 * @return 	none
 *
 **/
void MyDebugMessages(void) {
		uint8_t i = 0;

		//number of bytes from extension block
		uint8_t len = 10;

		app_vars.uart0Done = 0;
		app_vars.uart0_lastTxByteIndex = 0;
		memset(&app_vars.debugString,0,sizeof(app_vars.debugString));

		if (app_vars.debugRequest) {
			// message type
			memcpy(app_vars.debugString, requestToSend, sizeof(requestToSend));

			// message data
			sprintf(app_vars.debugString + sizeof(requestToSend), "%x    %x    %x    %x    ", app_vars.myDpaRequest.NAdr \
																				    		, app_vars.myDpaRequest.PNum \
																				    		, app_vars.myDpaRequest.PCmd \
																				    		, app_vars.myDpaRequest.HwProfile);

			app_vars.ptrRequest = (char*)&app_vars.myDpaRequest.Extension.Plain.Data;
			//first 5 elemets from extension
			for(i=0; i<len; i++) {
				sprintf(app_vars.debugString + sizeof(requestToSend) + 4*5 + (i*5), "%x    ", *app_vars.ptrRequest);
				app_vars.ptrRequest++;
			}

			// message ending
			memcpy(app_vars.debugString + sizeof(requestToSend) + 4*5 + len*5, endingToSend, sizeof(endingToSend));

			app_vars.ptrRequest = (char*)&app_vars.debugString;
			uart0_writeByte(*app_vars.ptrRequest);
		}
		else if(app_vars.debugAnswer == CONFIRMATION) {
			// message type
			memcpy(app_vars.debugString, confirmationToSend, sizeof(confirmationToSend));

			// message header
			sprintf(app_vars.debugString + sizeof(confirmationToSend), "%x    %x    %x    %x    ", app_vars.myDpaAnswer.NAdr \
																					 	 	 	 , app_vars.myDpaAnswer.PNum \
																					 	 	 	 , app_vars.myDpaAnswer.PCmd \
																					 	 	 	 , app_vars.myDpaAnswer.HwProfile);

			// message data
			sprintf(app_vars.debugString + sizeof(confirmationToSend) + 4*5, "%x    %x    %x    %x    %x    ", app_vars.myDpaAnswer.Extension.Confirmation.StatusConfirmation \
																					   	   	       	    	 , app_vars.myDpaAnswer.Extension.Confirmation.DpaValue \
																					   	   	       	    	 , app_vars.myDpaAnswer.Extension.Confirmation.Hops \
																					   	   	       	    	 , app_vars.myDpaAnswer.Extension.Confirmation.TimeSlotLength \
																					   	   	       	    	 , app_vars.myDpaAnswer.Extension.Confirmation.HopsResponse);

			// message ending
			memcpy(app_vars.debugString + sizeof(confirmationToSend) + 4*5 + 5*5, endingToSend, sizeof(endingToSend));
		}
		else if (app_vars.debugAnswer == RESPONSE) {
			// message type
			memcpy(app_vars.debugString, responseToSend, sizeof(responseToSend));

			// message header
			sprintf(app_vars.debugString + sizeof(responseToSend), "%x    %x    %x    %x    ", app_vars.myDpaAnswer.NAdr \
																						 	 , app_vars.myDpaAnswer.PNum \
																						 	 , app_vars.myDpaAnswer.PCmd \
																						 	 , app_vars.myDpaAnswer.HwProfile);

			// message data
			sprintf(app_vars.debugString + sizeof(responseToSend) + 4*5, "%x    %x    ", app_vars.myDpaAnswer.Extension.Response.ResponseCode \
																	           	   	   , app_vars.myDpaAnswer.Extension.Response.DpaValue );

			app_vars.ptrAnswer = (char*)&app_vars.myDpaAnswer.Extension.Response.Data;
			//first 5 elemets from extension
			for(i=0; i<len; i++) {
				sprintf(app_vars.debugString + sizeof(responseToSend) + 6*5 + (i*5), "%x    ", *app_vars.ptrAnswer);
				app_vars.ptrAnswer++;
			}

			// message ending
			memcpy(app_vars.debugString + sizeof(responseToSend) + 6*5 + len*5, endingToSend, sizeof(endingToSend));
		}

		app_vars.ptrAnswer = (char*)&app_vars.debugString;
		uart0_writeByte(*app_vars.ptrAnswer);

		app_vars.debugActive = TRUE;

		/*
		while(!app_vars.uart0Done)
			;
		*/
}
//=============================================================================

/**
 * Send DPA byte over UART
 *
 * @param 	Tx_Byte to send
 * @return 	none
 *
 **/
/*
void DPA_SendUartByte(UINT8 Tx_Byte) {
	app_vars.uart1Done = 0;

	//send byte
	uart1_writeByte(Tx_Byte);

	while (!app_vars.uart1Done)
		;
}
*/
//=============================================================================

/**
 * Send DPA byte over SPI
 *
 * @param       Tx_Byte to send
 * @return      Received Rx_Byte
 *
 **/
uint8_t DPA_SendSpiByte(UINT8 Tx_Byte) {

	app_vars.txbuf[0] = Tx_Byte;

	spi_txrx(
         	app_vars.txbuf,
         	sizeof(app_vars.txbuf),
         	SPI_BUFFER,
         	app_vars.rxbuf,
         	sizeof(app_vars.rxbuf),
         	SPI_FIRST,
         	SPI_LAST
      	);

	return app_vars.rxbuf[0];
}
//=============================================================================

/**
 * 1ms timer callback
 *
 * @param 	none
 * @return 	none
 *
 **/
void cb_compare(void) {

	// dpa timing
	DPA_SetTimmingFlag();													// set 1ms flag

	if (app_vars.dpaTimeoutCnt) {
		if ((--app_vars.dpaTimeoutCnt) == 0) {
			leds_yellow_toggle();
			MyDpaLibTimeoutHandler();										// if timeout expired, call timeout handler
		}
	}

	if (app_vars.swTimer) {													// sw timer, call timeout handler
		if ((--app_vars.swTimer) == 0) {
			MySwTimerTimeoutHandler();
			app_vars.swTimer = USER_TIMER_PERIOD;
		}
	}

	if(app_vars.ticks) {													// delay timer
		--app_vars.ticks;
	}

	// schedule again
	bsp_timer_scheduleIn(BSP_TIMER_PERIOD);
}
//=============================================================================

/**
 * UART0 Tx callback
 *
 * @param 	none
 * @return 	none
 *
 **/
void cb_uart0TxDone(void) {
	app_vars.uart0_lastTxByteIndex++;

	if(app_vars.debugRequest) {
		app_vars.ptrRequest++;

		if(app_vars.uart0_lastTxByteIndex < sizeof(app_vars.debugString)) {
			uart0_writeByte(*app_vars.ptrRequest);
		} else {
			app_vars.debugRequest = FALSE;
			app_vars.debugActive = FALSE;
			//app_vars.uart0Done = 1;
		}
	}
	else if (app_vars.debugAnswer) {
		app_vars.ptrAnswer++;

		if(app_vars.uart0_lastTxByteIndex < sizeof(app_vars.debugString)) {
			uart0_writeByte(*app_vars.ptrAnswer);
		} else {
			app_vars.debugAnswer = FALSE;
			app_vars.debugActive = FALSE;
			//app_vars.uart0Done = 1;
		}
	}
}
//=============================================================================

/**
 * UART0 Rx callback
 *
 * @param 	none
 * @return 	none
 *
 **/
void cb_uart0RxCb(void) {
}
//=============================================================================

/**
 * UART1 Tx callback
 *
 * @param 	none
 * @return 	none
 *
 **/
/*
void cb_uart1TxDone(void) {
	app_vars.uart1Done = 1;
}
*/
//=============================================================================

/**
 * UART1 Rx callback
 *
 * @param 	none
 * @return 	none
 *
 **/
/*
void cb_uart1RxCb(void) {
   uint8_t byte;

   // read received byte
   byte = uart1_readByte();

   // load that byte to dpa library
   DPA_ReceiveUartByte(byte);
}
*/
//=============================================================================


text:
from __future__ import absolute_import

from datetime import datetime

from flask_sqlalchemy import SQLAlchemy, _SessionSignalEvents

try:
    from unittest2 import TestCase
except ImportError:
    from unittest import TestCase

# Monkey patching for flask-sqlalchemy <= 1.0 (disable events)
_SessionSignalEvents.session_signal_before_commit = staticmethod(lambda s: s)
_SessionSignalEvents.session_signal_after_commit = staticmethod(lambda s: s)

db = SQLAlchemy()

usermessages = db.Table(
    'users_usermessages',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('message_id', db.Integer, db.ForeignKey('message.id'))
)

class Profile(db.Model):
    __tablename__ = 'profile'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=False)
    user = db.relationship("User", uselist=False, backref="profile")

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    score = db.Column(db.SmallInteger, default=50, nullable=False)
    created_at = db.Column(
        db.DateTime, default=datetime.utcnow, nullable=False)
    username = db.Column(db.String(20), nullable=False)
    profile_id = db.Column(db.Integer, db.ForeignKey(
        'profile.id'), nullable=False)

    messages = db.relationship(
        "Message", secondary=usermessages, backref="users")

class Role(db.Model):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)

    user = db.relation(User)

class Message(db.Model):
    __tablename__ = 'message'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(20))

class Node(db.Model):
    __tablename__ = 'node'
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('node.id'))
    children = db.relation(
        'Node',
        cascade='all',
        backref=db.backref('parent', remote_side='Node.id'))

class MixerTestFlask(TestCase):

    def setUp(self):
        from flask import Flask

        self.app = Flask(__name__)
        self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
        db.init_app(self.app)

    def test_base(self):
        from mixer.backend.flask import Mixer

        mixer = Mixer(commit=True)
        mixer.init_app(self.app)

        with self.app.test_request_context():
            db.create_all()

            node = mixer.blend('tests.test_flask.Node')
            self.assertTrue(node.id)
            self.assertFalse(node.parent)

            role = mixer.blend('tests.test_flask.Role')
            self.assertTrue(role.user)
            self.assertEqual(role.user_id, role.user.id)

            user = mixer.blend(User)
            self.assertTrue(user.id)
            self.assertTrue(user.username)
            self.assertEqual(user.score, 50)
            self.assertTrue(user.created_at)
            self.assertTrue(user.profile)
            self.assertEqual(user.profile.user, user)

            user = mixer.blend(User, username='test')
            self.assertEqual(user.username, 'test')

            role = mixer.blend(
                'tests.test_flask.Role', user__username='test2')
            self.assertEqual(role.user.username, 'test2')

            users = User.query.all()
            role = mixer.blend('tests.test_flask.Role', user=mixer.SELECT)
            self.assertTrue(role.user in users)

            role = mixer.blend('tests.test_flask.Role', user=mixer.RANDOM)
            self.assertTrue(role.user)

            profile = mixer.blend('tests.test_flask.Profile')
            user = mixer.blend(User, profile=profile)
            self.assertEqual(user.profile, profile)

            user = mixer.blend(User, score=mixer.RANDOM)
            self.assertNotEqual(user.score, 50)

            user = mixer.blend(User, username=lambda: 'callable_value')
            self.assertEqual(user.username, 'callable_value')

            # m2m
            messages = mixer.cycle(3).blend(Message)
            user = mixer.blend(User, messages=messages)
            self.assertEqual(len(user.messages), 3)

            user = mixer.blend(User, messages=mixer.RANDOM)
            self.assertEqual(len(user.messages), 1)

            user = mixer.blend(User, messages__content='message_content')
            self.assertEqual(len(user.messages), 1)
            self.assertEqual(user.messages[0].content, 'message_content')

    def test_default_mixer(self):
        from mixer.backend.flask import mixer

        test = mixer.blend(User)
        self.assertTrue(test.username)

# lint_ignore=F0401


text:
var chai = require('chai'),
    sinonChai = require('sinon-chai')

chai.use(sinonChai)
chai.config.includeStack = true

global.expect = chai.expect
global.AssertionError = chai.AssertionError
global.Assertion = chai.Assertion
global.assert = chai.assert


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

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="tableLevelConstraint" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj13590.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj16095.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj16357.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqljconstrchar.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj42154" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>tableLevelConstraint</title>

tableLevelConstraint

[ CONSTRAINT constraintName ]
{
    CHECK ( searchCondition ) |
    {
        PRIMARY KEY ( simpleColumnName [ , simpleColumnName ]* ) |
        UNIQUE ( simpleColumnName [ , simpleColumnName ]* ) |
        FOREIGN KEY ( simpleColumnName [ , simpleColumnName ]* )
            REFERENCES clause
    }
} [ constraintCharacteristics ]

A searchCondition is any
boolean expression that
meets the requirements specified in
Requirements for search conditions.

If a constraintName is
not specified, Derby
generates a unique constraint name.

Parent topic: CONSTRAINT clause

Related reference

columnLevelConstraint

REFERENCES clause

constraintCharacteristics


text:
package me.wondertwo.august0802.db;

/**
 * Created by wondertwo on 2016/9/2.
 */
public class PassageTable {
    private int id;
    private String passage_title;
    private String passage_url;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getPassage_title() {
        return passage_title;
    }

    public void setPassage_title(String passage_title) {
        this.passage_title = passage_title;
    }

    public String getPassage_url() {
        return passage_url;
    }

    public void setPassage_url(String passage_url) {
        this.passage_url = passage_url;
    }
}


text:
<form role="search" method="get" id="searchform" action="<?php echo home_url('/'); ?>">

			<input type="text" value="" name="s" id="s" placeholder="<?php esc_attr_e('Search', 'FoundationPress'); ?>">

			<input type="submit" id="searchsubmit" value="<?php esc_attr_e('Search', 'FoundationPress'); ?>" class="prefix button">

</form>


text:
declare interface CsvOptions {
	objectMode: boolean,
	delimiter: string
}

declare function csv(csvOptions: CsvOptions): NodeJS.ReadWriteStream;
declare module 'csv-streamify' {
	export = csv;
}


text:
import moduleInitializer from '../../../_lib/module-initializer';
import Component         from './max-length-validator.component';

describe('validation :: validators :: maxLength', () => {
  let valueSetter;

  beforeEach(async done => {
    ({valueSetter} = await moduleInitializer(Component));
    done();
  });

  it('marks input as invalid', async done => {
    let control = await valueSetter('name', 'Dmitriy');
    expect(control.invalid).toBe(true);
    done();
  });

  it('marks input as valid', async done => {
    let control = await valueSetter('name', 'Dmit');
    expect(control.valid).toBe(true);
    done();
  });
});


text:
import sys
from distutils.core import setup
import py2exe
from glob import glob
from os.path import join, dirname

setup(windows=[{'script': 'launcher.py', "icon_resources": [(0, join(dirname(sys.argv[0]), 'heatmap_icon.ico'))]}],
      options={"py2exe": {"includes": ["sip"], 'bundle_files': 2, 'compressed': True}}, requires=['PyQt4'],
      zipfile=None,
      data_files=[('.', glob(join(r'C:\Python34\Lib\site-packages', 'cHeatmap-x86.dll'))),
                  ('.', [join(dirname(sys.argv[0]), 'heatmap_icon.png')])],)


text:
package hudson.tools;

import hudson.FilePath;
import hudson.model.DownloadService.Downloadable;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.slaves.NodeSpecific;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.net.URL;

/**
 * Partial convenience implementation of {@link ToolInstaller} that just downloads
 * an archive from the URL and extracts it.
 *
 *

 * Each instance of this is configured to download from a specific URL identified by an ID.
 *
 * @author Kohsuke Kawaguchi
 * @since 1.308
 */
public abstract class DownloadFromUrlInstaller extends ToolInstaller {
    public final String id;

    protected DownloadFromUrlInstaller(String id) {
        // this installer implementation is designed for platform independent binary,
        // and as such we don't provide the label support
        super(null);
        this.id = id;
    }

    /**
     * Checks if the specified expected location already contains the installed version of the tool.
     *
     * This check needs to run fairly efficiently. The current implementation uses the souce URL of {@link Installable},
     * based on the assumption that released bits do not change its content.
     */
    protected boolean isUpToDate(FilePath expectedLocation, Installable i) throws IOException, InterruptedException {
        FilePath marker = expectedLocation.child(".installedFrom");
        return marker.exists() && marker.readToString().equals(i.url);
    }

    /**
     * Gets the {@link Installable} identified by {@link #id}.
     *
     * @return null if no such ID is found.
     */
    public Installable getInstallable() throws IOException {
        for (Installable i : ((DescriptorImpl<?>)getDescriptor()).getInstallables())
            if(id.equals(i.id))
                return i;
        return null;
    }

    public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException {
        FilePath expected = preferredLocation(tool, node);

        Installable inst = getInstallable();
        if(inst==null) {
            log.getLogger().println("Invalid tool ID "+id);
            return expected;
        }

        if (inst instanceof NodeSpecific) {
            inst = (Installable) ((NodeSpecific) inst).forNode(node, log);
        }

        if(isUpToDate(expected,inst))
            return expected;

        if(expected.installIfNecessaryFrom(new URL(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) {
            expected.child(".timestamp").delete(); // we don't use the timestamp
            FilePath base = findPullUpDirectory(expected);
            if(base!=null && base!=expected)
                base.moveAllChildrenTo(expected);
            // leave a record for the next up-to-date check
            expected.child(".installedFrom").write(inst.url,"UTF-8");
            expected.act(new ZipExtractionInstaller.ChmodRecAPlusX());
        }

        return expected;
    }

    /**
     * Often an archive contains an extra top-level directory that's unnecessary when extracted on the disk
     * into the expected location. If your installation sources provide that kind of archives, override
     * this method to find the real root location.
     *
     *

     * The caller will "pull up" the discovered real root by throw away the intermediate directory,
     * so that the user-configured "tool home" directory contains the right files.
     *
     *

     * The default implementation applies some heuristics to auto-determine if the pull up is necessary.
     * This should work for typical archive files.
     *
     * @param root
     *      The directory that contains the extracted archive. This directory contains nothing but the
     *      extracted archive. For example, if the user installed
     *      http://archive.apache.org/dist/ant/binaries/jakarta-ant-1.1.zip , this directory would contain
     *      a single directory "jakarta-ant".
     *
     * @return
     *      Return the real top directory inside {@code root} that contains the meat. In the above example,
     *      <tt>root.child("jakarta-ant")</tt> should be returned. If there's no directory to pull up,
     *      return null.
     */
    protected FilePath findPullUpDirectory(FilePath root) throws IOException, InterruptedException {
        // if the directory just contains one directory and that alone, assume that's the pull up subject
        // otherwise leave it as is.
        List<FilePath> children = root.list();
        if(children.size()!=1)    return null;
        if(children.get(0).isDirectory())
            return children.get(0);
        return null;
    }

    public static abstract class DescriptorImpl<T extends DownloadFromUrlInstaller> extends ToolInstallerDescriptor<T> {

        @SuppressWarnings("deprecation") // intentionally adding dynamic item here
        protected DescriptorImpl() {
            Downloadable.all().add(createDownloadable());
        }

        protected Downloadable createDownloadable() {
            return new Downloadable(getId());
        }

        /**
         * This ID needs to be unique, and needs to match the ID token in the JSON update file.
         *

         * By default we use the fully-qualified class name of the {@link DownloadFromUrlInstaller} subtype.
         */
        public String getId() {
            return clazz.getName().replace('$','.');
        }

        /**
         * List of installable tools.
         *
         *

         * The UI uses this information to populate the drop-down. Subtypes can override this method
         * if it wants to change the way the list is filled.
         *
         * @return never null.
         */
        public List<? extends Installable> getInstallables() throws IOException {
            JSONObject d = Downloadable.get(getId()).getData();
            if(d==null)     return Collections.emptyList();
            return Arrays.asList(((InstallableList)JSONObject.toBean(d,InstallableList.class)).list);
        }
    }

    /**
     * Used for JSON databinding to parse the obtained list.
     */
    public static class InstallableList {
        // initialize with an empty array just in case JSON doesn't have the list field (which shouldn't happen.)
        public Installable[] list = new Installable[0];
    }

    /**
     * Downloadable and installable tool.
     */
    public static class Installable {
        /**
         * Used internally to uniquely identify the name.
         */
        public String id;
        /**
         * This is the human readable name.
         */
        public String name;
        /**
         * URL.
         */
        public String url;
    }

    /**
     * Convenient abstract class to implement a NodeSpecificInstallable based on an existing Installable
     * @since TODO
     */
    public abstract class NodeSpecificInstallable extends Installable implements NodeSpecific<NodeSpecificInstallable> {

        public NodeSpecificInstallable(Installable inst) {
            this.id = inst.id;
            this.name = inst.name;
            this.url = inst.url;
        }
    }
}


text:
class Activemq < Formula
  desc "Apache ActiveMQ: powerful open source messaging server"
  homepage "https://activemq.apache.org/"
  url "https://www.apache.org/dyn/closer.cgi?path=/activemq/5.11.2/apache-activemq-5.11.2-bin.tar.gz"
  sha256 "db475dffe3004a619f437347258ff07a60bce60c38dc05edca8d03ede5a64418"

  depends_on :java => "1.6+"

  def install
    rm_rf Dir["bin/linux-x86-*"] unless OS.linux?
    libexec.install Dir["*"]
    (bin/"activemq").write_env_script libexec/"bin/activemq", Language::Java.java_home_env("1.6+")
    (bin/"activemq-admin").write_env_script libexec/"bin/activemq-admin", Language::Java.java_home_env("1.6+")
  end

  test do
    system "#{bin}/activemq-admin", "browse", "-h"
  end
end