text:
<instance description="" template="abilities">
	<group name="ability_bag">
		<group name="action_list">
			<list name="end_self_actions">
			</list>
			<list name="end_target_actions">
			</list>
			<list name="start_self_actions">
				<template_reference name="action" value="action\cancel_forced_attack">
					<uniqueid name="id" value="1073747909" />
				</template_reference>
				<template_reference name="action" value="action\apply_modifiers_action">
					<float name="duration" value="0" />
					<bool name="permanent" value="False" />
					<list name="modifiers">
						<template_reference name="modifier" value="modifiers\auto_target_enable_weapon_modifier">
							<enum name="application_type" value="apply_to_weapon" />
							<bool name="exclusive" value="False" />
							<string name="modifier_id" value="" />
							<string name="target_type_name" value="hardpoint_01" />
							<enum name="usage_type" value="enable" />
							<float name="value" value="-1" />
							<instance_reference name="tooltip" value="modifier_tooltip\auto_target_enable_weapon_modifier" />
						</template_reference>
					</list>
					<uniqueid name="id" value="1073747910" />
				</template_reference>
				<template_reference name="action" value="action\requirement_action">
					<bool name="check_self" value="False" />
					<bool name="global_fire_and_forget_on_success" value="False" />
					<bool name="instant_requirement_check" value="False" />
					<bool name="kill_action_on_failed_requirements" value="False" />
					<bool name="no_retrigger" value="False" />
					<bool name="validate_all_sub_actions" value="True" />
					<list name="requirement_table">
						<template_reference name="required" value="requirements\required_not">
							<enum name="reason" value="usage" />
							<locstring name="ui_name" value="0" />
							<list name="requirement_table">
								<template_reference name="required" value="requirements\required_in_state">
									<enum name="reason" value="usage" />
									<locstring name="ui_name" value="0" />
									<bool name="garrisoned" value="True" />
									<bool name="healed" value="False" />
									<float name="in_combat_since" value="-1" />
									<bool name="injured" value="False" />
									<bool name="leader" value="False" />
									<bool name="not_moving" value="False" />
									<bool name="not_retreating" value="False" />
									<bool name="pinned" value="False" />
									<bool name="suppressed" value="False" />
								</template_reference>
							</list>
						</template_reference>
					</list>
					<list name="action_table">
						<template_reference name="action" value="action\animator_set_state">
							<bool name="apply_to_leader_only" value="True" />
							<string name="do_action_state_name" value="on" />
							<bool name="retrigger" value="True" />
							<string name="state_machine_name" value="ability_hold_fire_state" />
							<string name="undo_action_state_name" value="off" />
							<uniqueid name="id" value="1073747911" />
						</template_reference>
					</list>
					<uniqueid name="id" value="1073747912" />
					<bool name="fire_and_forget_non_global" value="False" />
					<template_reference name="ui_help_text" value="tables\help_text_phrase">
						<int name="phrase_order" value="0" />
						<locstring name="phrase" value="0" />
					</template_reference>
				</template_reference>
				<template_reference name="action" value="action\ui_unit_modifier_action">
					<bool name="die_with_creator" value="False" />
					<template_reference name="ui_info" value="tables\ui_info">
						<locstring name="screen_name" value="11042898" />
						<locstring name="help_text" value="11085115" />
						<icon name="icon_name" value="Icons_abilities_hold_fire_on" />
						<string name="hotkey_name" value="" />
					</template_reference>
					<uniqueid name="id" value="1073747913" />
				</template_reference>
			</list>
			<list name="start_target_actions">
			</list>
		</group>
		<enum name="activation" value="toggle" />
		<bool name="can_interrupt" value="True" />
		<bool name="can_target_in_fow" value="False" />
		<float name="caster_close_in_distance" value="2" />
		<bool name="casters_can_evacuate" value="False" />
		<group name="cost">
			<float name="action" value="0" />
			<float name="command" value="0" />
			<float name="fuel" value="0" />
			<float name="manpower" value="0" />
			<float name="munition" value="0" />
			<float name="popcap" value="0" />
		</group>
		<string name="cursor_ghost_blueprint" value="" />
		<float name="cursor_ghost_blueprint_angle" value="0" />
		<bool name="disable_combat" value="False" />
		<bool name="disable_when_active" value="False" />
		<float name="duration_time" value="3" />
		<bool name="enable_in_building" value="True" />
		<bool name="enable_in_vehicle" value="False" />
		<bool name="engage_combat" value="False" />
		<float name="entity_busy_time" value="0" />
		<float name="facing_angle" value="5" />
		<bool name="facing_ignore" value="False" />
		<float name="final_close_in_distance" value="0" />
		<bool name="fire_and_forget" value="False" />
		<bool name="garrison_target" value="False" />
		<bool name="has_speech_code" value="True" />
		<float name="initial_delay_time" value="10" />
		<bool name="initial_recharge" value="False" />
		<bool name="is_default_action" value="False" />
		<bool name="move_back" value="False" />
		<float name="move_back_distance" value="10" />
		<float name="range" value="0" />
		<bool name="range_ignore" value="True" />
		<float name="recharge_time" value="0" />
		<bool name="refundable" value="True" />
		<bool name="require_no_shot_block" value="False" />
		<enum name="shared_timer" value="" />
		<bool name="shared_timer_player_wide" value="False" />
		<group name="speech_code_2">
			<string name="code_1" value="cm" />
			<string name="code_2" value="" />
			<string name="code_3" value="" />
		</group>
		<group name="speech_code_3">
			<string name="code_1" value="" />
			<string name="code_2" value="" />
			<string name="code_3" value="" />
		</group>
		<enum name="squad_caster" value="squad" />
		<enum name="target" value="tp_any" />
		<group name="target_special_validation">
			<template_reference name="target_special_validation" value="type_ability_target_type\all">
			</template_reference>
		</group>
		<float name="toggled_recharge_time_off" value="0" />
		<float name="toggled_recharge_time_on" value="1" />
		<group name="ui_cursor">
			<string name="cursor_bad" value="modal_ability_cancel" />
			<string name="cursor_good" value="modal_ability" />
			<string name="cursor_nonmodal_good" value="" />
		</group>
		<group name="ui_info">
			<locstring name="extra_text" value="0" />
			<locstring name="help_text" value="11042897" />
			<string name="hotkey_name" value="H" />
			<icon name="icon_name" value="Icons_abilities_hold_fire_off" />
			<string name="overlay_name" value="" />
			<bool name="reveal_for_decryption" value="False" />
			<locstring name="screen_name" value="11042898" />
			<icon name="icon_alternate_name" value="Icons_abilities_hold_fire_on" />
			<locstring name="brief_text" value="0" />
			<locstring name="help_text_alternate" value="11045364" />
			<locstring name="screen_name_alternate" value="11045661" />
			<locstring name="screen_name_short" value="0" />
		</group>
		<locstring name="ui_usage_txt" value="0" />
		<bool name="validate_actions" value="True" />
		<list name="global_self_actions">
		</list>
		<list name="requirements">
			<template_reference name="required" value="requirements\required_squad_upgrade">
				<enum name="reason" value="usage_and_display" />
				<locstring name="ui_name" value="0" />
				<bool name="include_queued" value="False" />
				<bool name="is_present" value="True" />
				<instance_reference name="upgrade_name" value="upgrade\german\commander\ability\ambush_camou_package" />
			</template_reference>
		</list>
		<enum name="ability_super" value="tp_none" />
		<int name="ui_position" value="22" />
		<bool name="ui_mini_map_capture" value="False" />
		<bool name="facing_ignore_during_active" value="False" />
		<instance_reference name="ui_range" value="" />
		<instance_reference name="ui_reticule" value="" />
		<float name="ui_reticule_radius_min" value="1" />
		<float name="ui_reticule_radius_max" value="1" />
		<enum name="pending_ability_out_of_range_behaviour" value="chase" />
		<enum name="ui_group" value="group_primary" />
		<string name="ui_targetable_sm_key" value="" />
		<string name="ui_targetable_on_key" value="" />
		<string name="ui_targetable_off_key" value="" />
		<enum name="ui_targetable_receiver" value="local" />
		<enum name="ui_combine_type" value="intersection" />
		<enum_table name="ui_modal_highlight">
			<bool name="world_sector" value="False" />
			<bool name="map_sector" value="False" />
			<bool name="map_sector_hq_link_extender" value="False" />
		</enum_table>
		<enum name="ui_group_cast_type" value="multi" />
		<list name="requirements_target">
		</list>
		<template_reference name="targeted_ability_option" value="options\none">
		</template_reference>
		<enum name="ui_direction_requirement" value="nondirectional" />
		<instance_reference name="cursor_ghost_ebp" value="" />
		<bool name="can_cast_whilst_constructing" value="False" />
		<list name="requirements_self_recharge">
		</list>
		<bool name="ability_super_event_cue" value="False" />
	</group>
	<uniqueid name="pbgid" value="110" />
</instance>


text:
<?php

namespace BackBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class BackBundle extends Bundle
{
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Security\Core\Tests\Authentication;

use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;

class AuthenticationTrustResolverTest extends \PHPUnit_Framework_TestCase
{
    public function testIsAnonymous()
    {
        $resolver = $this->getResolver();

        $this->assertFalse($resolver->isAnonymous(null));
        $this->assertFalse($resolver->isAnonymous($this->getToken()));
        $this->assertFalse($resolver->isAnonymous($this->getRememberMeToken()));
        $this->assertTrue($resolver->isAnonymous($this->getAnonymousToken()));
    }

    public function testIsRememberMe()
    {
        $resolver = $this->getResolver();

        $this->assertFalse($resolver->isRememberMe(null));
        $this->assertFalse($resolver->isRememberMe($this->getToken()));
        $this->assertFalse($resolver->isRememberMe($this->getAnonymousToken()));
        $this->assertTrue($resolver->isRememberMe($this->getRememberMeToken()));
    }

    public function testisFullFledged()
    {
        $resolver = $this->getResolver();

        $this->assertFalse($resolver->isFullFledged(null));
        $this->assertFalse($resolver->isFullFledged($this->getAnonymousToken()));
        $this->assertFalse($resolver->isFullFledged($this->getRememberMeToken()));
        $this->assertTrue($resolver->isFullFledged($this->getToken()));
    }

    protected function getToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
    }

    protected function getAnonymousToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken', null, array('', ''));
    }

    protected function getRememberMeToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', array('setPersistent'), array(), '', false);
    }

    protected function getResolver()
    {
        return new AuthenticationTrustResolver(
            'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken',
            'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'
        );
    }
}


text:
<?php

namespace Midnight\Crawler\Plugin;

use Midnight\Crawler\UriManager;
use Midnight\Utility\CrawlerException;

class Matome extends AbstractPlugin implements PluginInterface
{

    /**
     * サイト名
     *
     * @var string
     **/
    protected $site_name = '無料エロ動画AV xvideosまとめ';

    /**
     * RSSフィードのURL
     *
     * @var string
     **/
    protected $rss_url = 'http://erodougaavdouga.blog.fc2.com/?xml';

    /**
     * DOMElementからエントリのURLを返す
     *
     * @param  $entry DOMElement
     * @return string
     **/
    public function getEntryUrl ($entry)
    {
        return $this->getNodeValueByTagName($entry, 'link');
    }

    /**
     * エントリの登録された日付を取得する
     *
     * @param $entry DOMElement
     * @return string
     */
    public function getEntryDate ($entry)
    {
        return $this->getDateByDcDate($entry);
    }

    /**
     * エントリのタイトルを取得する
     *
     * @param  simple_html_dom $html
     * @return string
     **/
    public function getEntryTitle ($html)
    {
        $query = 'html head title';
        $title_el = $html->find($query, 0);
        if (is_null($title_el)) throw new CrawlerException('タイトルを取得出来ませんでした');

        $title = trim(preg_replace('/\s-\s.*/', '', $title_el->plaintext));
        return $title;
    }

    /**
     * アイキャッチ画像のURLを取得する
     *
     * @param  simple_html_dom $html
     * @return string
     **/
    public function getEyeCatchUrl ($html)
    {
        $query = 'div.post div.postmain div a img';
        $img_el = $html->find($query, 0);

        if (is_null($img_el)) throw new CrawlerException('アイキャッチを取得出来ませんでした');
        if (!$img_el->hasAttribute('src')) throw new CrawlerException('src属性が見つかりませんでした');

        return $img_el->getAttribute('src');
    }

    /**
     * 動画のURLを取得する
     *
     * @param  simple_html_dom $html
     * @return array
     **/
    public function getMoviesUrl ($html)
    {
        $query = 'div#more iframe';
        $movies_els = $html->find($query);
        $movie_data = array();
        $manager    = new UriManager();

        // 動画はこちらテキストのリンクを取得する
        foreach ($movies_els as $movies_el) {
            $movie_data[] = $manager->resolve($movies_el->getAttribute('src'));
        }

        return $movie_data;
    }
}


text:
package co.cask.hydrator.plugin.batch.aggregator.function;

import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.hydrator.plugin.batch.aggregator.AggregationUtils;

/**
 * Calculates Variance
 */
public class Variance implements AggregateFunction<Double> {
  private final String fieldName;
  private final Schema outputSchema;
  private RunningStats stats;

  public Variance(String fieldName, Schema fieldSchema) {
    this.fieldName = fieldName;
    boolean isNullable = fieldSchema.isNullable();
    Schema.Type fieldType = isNullable ? fieldSchema.getNonNullable().getType() : fieldSchema.getType();
    if (!AggregationUtils.isNumericType(fieldType)) {
      throw new IllegalArgumentException(String.format(
        "Cannot compute variance on field %s because its type %s is not numeric", fieldName, fieldType));
    }
    outputSchema = isNullable ? Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)) : Schema.of(Schema.Type.DOUBLE);
  }

  @Override
  public void beginFunction() {
    stats = new RunningStats();
  }

  @Override
  public void operateOn(StructuredRecord record) {
    Object val = record.get(fieldName);
    if (val == null) {
      return;
    }
    double value = ((Number) val).doubleValue();
    stats.push(value);
  }

  @Override
  public Double getAggregate() {
    return stats.variance();
  }

  @Override
  public Schema getOutputSchema() {
    return outputSchema;
  }
}


text:
layout: post
title: "Australian Alpine Walking Track (the Top Bit)"
modified:
categories: posts
excerpt: Journal entries from walking the Northern 250km of the Australian Alpine Walking Track, from Dead Horse Gap (Thredbo) to Canberra
tags: [hiking]
image:
  feature: 2013-aawt/aawt-title.jpg
date: 2013-12-28T22:01:09+11:00
---

> At 6pm on December 20, 2013 a ute pulled over at Dead Horse Gap, in the Southern part of Kosciuszko National Park and just South of Thredbo.
>
> Three Canberrans got out of the ute and walked to the start of the bush. A few minutes later a sole person returned to the ute and drove back to Canberra.
>
> This is the journal I kept as we walked the 250km back to Canberra along the Northern third of the Australian Alpine Walking Track.

Our packs are fatter than us as we prepare to set out

### Day 0
Got to Dead Horse around 1800 so decided to get the big hill out of the way in dusk. 9.9km later stopped at Rawson's Pass. May not have been allowed to camp within 200m of the pass but we were 200m from the toilet and that seemed good enough.

Fairly warm night, rain came up when we went to bed but wind had dried it by morning.

This is probably (possibly?) South Ram's Head from the Dead Horse Gap track

After walking up Dead Horse Gap in Winter 2012 I swore I'd never do it again. How did I end up here?

Once atop the Gap it was smooth sailing into Rawson's Pass

A nice (if potentially clandestine) camping spot at the foot of Mt. Kosciuszko

### Day 1
Dead Horse to White's River. **Not** Schlink as planned. Killer day. **So** much more mountainous than I'd anticipated. And **so much** of it untracked.

When we eventually arrived at White's River Hut we discussed whether to bail on the trip. After talking through bailing, bailing at Kiandra and attempting to continue, we decided to continue. After all, what are PLB's for ... Right?

Fell asleep while Dani cooked dinner. Ate and slept again.

* Rodent holes in my pack: 2
* Heels with bilsters: 2

The stunning Main Range. It's amazing being up here

Lake Albina

More snow than I expected for Christmas

White's River Hut

### Day 2
On to Grey Mare Hut, 16.8km.

* Injuries: Right knee

Checked out Valentine's Hut en route, gorgeous! Adorned with love hearts, very quaint.

Valentine's Hut

Beautiful scenery, good trail. Skipped Valentine's Falls to avoid more arduous terrain after yesterday. Some sadist had put the hut 500m away from the trail up a damn big hill. And the toilet another 50m uphill.

Grey Mare Hut

Old gold mine is here with machinery and irrigation left behind, but I couldn't find the mine entrance.

### Day 3
On to Mackay's Hut today.

Word on the street is it's pronounced "Mackey's", and often spelled that way too - albeit incorrectly.

* Injuries: None, but it turns out, with enough rain, canvas rucksacks aren't actually waterproof.

A cool start to the day gave a lovely morning, then it started raining lightly. That was also quite nice at first. Morning tea at O'Keefe's Hut - very beautiful, lined with 1936 newspaper and housing a sparrow nest and pair of sparrows.

Got drenched between O'Keefe's and Mackay's when a pleasant sprinkle (not wearing goretex) turned into heavy rain and eventually **very** heavy rain. And we got drenched.

Started a decent fire in the hut and got our things dry. Dining table dinner by the fire with rock salt and freshly ground pepper!

Drying wet clothes, gear and pack in a steaming hut

Concerned the rain will block further river crossings to the North. It clears before dinner. But it *was* very heavy...

Mackay's Hut

### Day 4
Today's destination is 4 Mile Hut.

* Injuries: Chris gets gastro
* Attacks by hordes of ants: 1

Gastro Stop is amazing stuff!! Otherwise a fairly uneventful day. Had planned to set camp at 9 Mile Creek but were attacked by ants. Not just a little bit attacked. Every time something goes on the ground its colour changes to mostly black attacked.

And some bloody ants bit the bloody part of my blister (which I'd kicked into a rock washing myself at the gold mine and made bleed). And that bloody hurt. So on we went after grabbing desperately-needed water to 4 Mile Hut. Very cute original-style gold miner's hut.

Nothing but trail as far as the eye can see

### Day 5

#### Christmas!!!
...And on to Witses Hut

Christmas dawns to the most amazing sunrise I've ever seen

* Injuries: Dani gets gastro, and bonks a couple of km from the hut.

Uneventful walk in, Chris spends 90 minutes chopping firewood for the crazy-cold mornings while Dani snoozes. Very good looking hut, but made of timber slabs with gaps between them so neither fly-proof nor insulated. We manage to keep the fire going all night by not sleeping very much.

Old town hall at Kiandra along the way

Witses Hut

### Day 6
Today, Hainsworth Hut

* Injuries: None (?!?)

Top up water as soon as we find it (both water sources at Witses were either dry or too shallow to get drinking water).

Also a large herd of brumbies as we set out for the day. They may be pests but they're beautiful

Putting our shoes on after crossing the Tantangara River a 4WD approaches and we chat to some fly fishermen who are out for the day. They agree to send Craig a message for us since we've been unable to get phone reception. **YAY!**

Get distracted by random foot trails all through the untracked section and double back a bit. Dani gets pooped so I steal her food and water for the 5km before lunch.

Then I get pooped.

Lunch at Ghost Gully where several people are hanging around with lots of horsies. I say g'day to one guy as he walks nearby and get nothing in return. That's a shame.

Still more endless trails

The last 3.5km to the hut is fairly easy and we arrive about 1410ish.

Hut has no saw or toilet but the river is a beautiful temperature so the first order of business is to wash our clothes and ourselves.

Hainsworth Hut

Rain sets in long and hard early evening and, with a less-than-waterproof fireplace, the battle between fire and water commences. A fairly sleepless night and further gastro for Dani sees the night close.

A misty morning adds atmosphere to the seclusion

### Day 7
Oldfield's Hut - My old friend.

* Injuries: Does a slight graze and a bit of bleeding to my right Achilles from Dani chopping firewood onto me qualify?

A **freezing** morning sees us get away slightly later - 0710 - and power through to Bill Jones Hut for morning tea.

Bill Jones Hut

Beautiful scenery and the lovely smell of Eucalypt forest after rain but an otherwise uneventful day until the godawful slog up the start of Murray Gap trail.

When Mt. Bimberi appears in the distance we know we're getting close to the end

Arrived at Oldfield's Hut 1310, found dubious water in a barely-running stream, chopped firewood (well, Dani did the vast majority of that while I supervised) and relaxed.

Oldfield's Hut

Very satisfying to be mere kilometres from the ACT border!

Mt. Bimberi from Oldfield's Hut

> Apparently that's all that I wrote.
> To ease the suspense: We got out alive, although quite tired after the big day from Oldfield's Hut to the Orrorral Valley.


text:
#ifndef _STIM_CMD_COMMAND_DETECT_H
#define _STIM_CMD_COMMAND_DETECT_H

#include "stim/arg_parse.h"

namespace stim {

int command_detect(int argc, const char **argv);
SubCommandHelp command_detect_help();

}  // namespace stim

#endif


text:
describe Travis::API::V3::Services::Repository::Update, set_app: true do
  let(:repo) { Travis::API::V3::Models::Repository.where(owner_name: 'svenfuchs', name: 'minimal').first }

  before { Travis.config.applications = { app: { full_access: true, token: '12345' } } }
  after  { Travis.config.applications = {} }

  describe "not authenticated" do
    before  { patch("/v3/repo/#{repo.id}", com_id: 1) }
    example { expect(last_response.status).to be == 403 }
    example { expect(JSON.load(body)).to be == {
      "@type"         => "error",
      "error_type"    => "login_required",
      "error_message" => "login required"
    }}
  end

  describe "authenticated" do
    let(:headers) { { 'HTTP_AUTHORIZATION' => "internal app:12345" } }
    before { patch("/v3/repo/#{repo.id}", { com_id: 1 }, headers) }

    example { expect(last_response.status).to be == 200 }
    example { expect(repo.reload.com_id).to eq 1 }
  end

  describe "authenticated, missing repo" do
    let(:headers) { { 'HTTP_AUTHORIZATION' => "internal app:12345" } }
    before { patch("/v3/repo/9999999999", { com_id: 1 }, headers) }

    example { expect(last_response.status).to be == 404 }
    example { expect(JSON.load(body)).to be == {
      "@type"         => "error",
      "error_type"    => "not_found",
      "error_message" => "repository not found (or insufficient access)",
      "resource_type" => "repository"
    }}
  end

  describe "authenticated as a user" do
    let(:token)   { Travis::Api::App::AccessToken.create(user: repo.owner, app_id: 1) }
    let(:headers) {{ 'HTTP_AUTHORIZATION' => "token #{token}" }}
    before        { patch("/v3/repo/#{repo.id}", { com_id: 1 }, headers) }

    example { expect(last_response.status).to be == 403 }
    example { expect(JSON.load(body)).to be == {
      "@type"         => "error",
      "error_type"    => "insufficient_access",
      "error_message" => "forbidden"
    }}
  end

  context do
    let(:token)   { Travis::Api::App::AccessToken.create(user: repo.owner, app_id: 1) }
    let(:headers) { { 'HTTP_AUTHORIZATION' => "internal app:12345" } }

    describe "repo migrating" do
      before { repo.update_attributes(migration_status: "migrating") }
      before { patch("/v3/repo/#{repo.id}", { com_id: 1 }, headers) }

      example { expect(last_response.status).to be == 403 }
      example { expect(JSON.load(body)).to be == {
        "@type"         => "error",
        "error_type"    => "repo_migrated",
        "error_message" => "This repository has been migrated to travis-ci.com. Modifications to repositories, builds, and jobs are disabled on travis-ci.org. If you have any questions please contact us at support@travis-ci.com"
      }}
    end

    describe "repo migrating" do
      before { repo.update_attributes(migration_status: "migrated") }
      before { patch("/v3/repo/#{repo.id}", { com_id: 1 }, headers) }

      example { expect(last_response.status).to be == 403 }
      example { expect(JSON.load(body)).to be == {
        "@type"         => "error",
        "error_type"    => "repo_migrated",
        "error_message" => "This repository has been migrated to travis-ci.com. Modifications to repositories, builds, and jobs are disabled on travis-ci.org. If you have any questions please contact us at support@travis-ci.com"
      }}
    end
  end
end


text:
package org.elasticsearch.cluster.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.Assertions;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.cluster.AckedClusterStateTaskListener;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterState.Builder;
import org.elasticsearch.cluster.ClusterStatePublicationEvent;
import org.elasticsearch.cluster.ClusterStateTaskConfig;
import org.elasticsearch.cluster.ClusterStateTaskExecutor;
import org.elasticsearch.cluster.ClusterStateTaskExecutor.ClusterTasksResult;
import org.elasticsearch.cluster.ClusterStateTaskListener;
import org.elasticsearch.cluster.coordination.ClusterStatePublisher;
import org.elasticsearch.cluster.coordination.FailedToCommitClusterStateException;
import org.elasticsearch.cluster.metadata.ProcessClusterEventTimeoutException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.util.concurrent.CountDown;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.common.util.concurrent.FutureUtils;
import org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.node.Node;
import org.elasticsearch.threadpool.Scheduler;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import static org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory;

public class MasterService extends AbstractLifecycleComponent {
    private static final Logger logger = LogManager.getLogger(MasterService.class);

    public static final Setting<TimeValue> MASTER_SERVICE_SLOW_TASK_LOGGING_THRESHOLD_SETTING = Setting.positiveTimeSetting(
        "cluster.service.slow_master_task_logging_threshold",
        TimeValue.timeValueSeconds(10),
        Setting.Property.Dynamic,
        Setting.Property.NodeScope
    );

    public static final Setting<TimeValue> MASTER_SERVICE_STARVATION_LOGGING_THRESHOLD_SETTING = Setting.positiveTimeSetting(
        "cluster.service.master_service_starvation_logging_threshold",
        TimeValue.timeValueMinutes(5),
        Setting.Property.NodeScope
    );

    static final String MASTER_UPDATE_THREAD_NAME = "masterService#updateTask";

    ClusterStatePublisher clusterStatePublisher;

    private final String nodeName;

    private java.util.function.Supplier<ClusterState> clusterStateSupplier;

    private volatile TimeValue slowTaskLoggingThreshold;
    private final TimeValue starvationLoggingThreshold;

    protected final ThreadPool threadPool;

    private volatile PrioritizedEsThreadPoolExecutor threadPoolExecutor;
    private volatile Batcher taskBatcher;

    private final ClusterStateUpdateStatsTracker clusterStateUpdateStatsTracker = new ClusterStateUpdateStatsTracker();

    public MasterService(Settings settings, ClusterSettings clusterSettings, ThreadPool threadPool) {
        this.nodeName = Objects.requireNonNull(Node.NODE_NAME_SETTING.get(settings));

        this.slowTaskLoggingThreshold = MASTER_SERVICE_SLOW_TASK_LOGGING_THRESHOLD_SETTING.get(settings);
        clusterSettings.addSettingsUpdateConsumer(MASTER_SERVICE_SLOW_TASK_LOGGING_THRESHOLD_SETTING, this::setSlowTaskLoggingThreshold);

        this.starvationLoggingThreshold = MASTER_SERVICE_STARVATION_LOGGING_THRESHOLD_SETTING.get(settings);

        this.threadPool = threadPool;
    }

    private void setSlowTaskLoggingThreshold(TimeValue slowTaskLoggingThreshold) {
        this.slowTaskLoggingThreshold = slowTaskLoggingThreshold;
    }

    public synchronized void setClusterStatePublisher(ClusterStatePublisher publisher) {
        clusterStatePublisher = publisher;
    }

    public synchronized void setClusterStateSupplier(java.util.function.Supplier<ClusterState> clusterStateSupplier) {
        this.clusterStateSupplier = clusterStateSupplier;
    }

    @Override
    protected synchronized void doStart() {
        Objects.requireNonNull(clusterStatePublisher, "please set a cluster state publisher before starting");
        Objects.requireNonNull(clusterStateSupplier, "please set a cluster state supplier before starting");
        threadPoolExecutor = createThreadPoolExecutor();
        taskBatcher = new Batcher(logger, threadPoolExecutor);
    }

    protected PrioritizedEsThreadPoolExecutor createThreadPoolExecutor() {
        return EsExecutors.newSinglePrioritizing(
            nodeName + "/" + MASTER_UPDATE_THREAD_NAME,
            daemonThreadFactory(nodeName, MASTER_UPDATE_THREAD_NAME),
            threadPool.getThreadContext(),
            threadPool.scheduler(),
            new MasterServiceStarvationWatcher(
                starvationLoggingThreshold.getMillis(),
                threadPool::relativeTimeInMillis,
                () -> threadPoolExecutor
            )
        );
    }

    public ClusterStateUpdateStats getClusterStateUpdateStats() {
        return clusterStateUpdateStatsTracker.getStatistics();
    }

    @SuppressWarnings("unchecked")
    class Batcher extends TaskBatcher {

        Batcher(Logger logger, PrioritizedEsThreadPoolExecutor threadExecutor) {
            super(logger, threadExecutor);
        }

        @Override
        protected void onTimeout(List<? extends BatchedTask> tasks, TimeValue timeout) {
            threadPool.generic()
                .execute(
                    () -> tasks.forEach(
                        task -> ((UpdateTask) task).listener.onFailure(
                            task.source,
                            new ProcessClusterEventTimeoutException(timeout, task.source)
                        )
                    )
                );
        }

        @Override
        protected void run(Object batchingKey, List<? extends BatchedTask> tasks, String tasksSummary) {
            ClusterStateTaskExecutor<Object> taskExecutor = (ClusterStateTaskExecutor<Object>) batchingKey;
            List<UpdateTask> updateTasks = (List<UpdateTask>) tasks;
            runTasks(new TaskInputs(taskExecutor, updateTasks, tasksSummary));
        }

        class UpdateTask extends BatchedTask {
            final ClusterStateTaskListener listener;

            UpdateTask(
                Priority priority,
                String source,
                Object task,
                ClusterStateTaskListener listener,
                ClusterStateTaskExecutor<?> executor
            ) {
                super(priority, source, executor, task);
                this.listener = listener;
            }

            @Override
            public String describeTasks(List<? extends BatchedTask> tasks) {
                return ((ClusterStateTaskExecutor<Object>) batchingKey).describeTasks(
                    tasks.stream().map(BatchedTask::getTask).collect(Collectors.toList())
                );
            }
        }
    }

    @Override
    protected synchronized void doStop() {
        ThreadPool.terminate(threadPoolExecutor, 10, TimeUnit.SECONDS);
    }

    @Override
    protected synchronized void doClose() {}

    /**
     * The current cluster state exposed by the discovery layer. Package-visible for tests.
     */
    ClusterState state() {
        return clusterStateSupplier.get();
    }

    public static boolean isMasterUpdateThread() {
        return Thread.currentThread().getName().contains('[' + MASTER_UPDATE_THREAD_NAME + ']');
    }

    public static boolean assertNotMasterUpdateThread(String reason) {
        assert isMasterUpdateThread() == false
            : "Expected current thread [" + Thread.currentThread() + "] to not be the master service thread. Reason: [" + reason + "]";
        return true;
    }

    private void runTasks(TaskInputs taskInputs) {
        final String summary = taskInputs.summary;
        if (lifecycle.started() == false) {
            logger.debug("processing [{}]: ignoring, master service not started", summary);
            return;
        }

        logger.debug("executing cluster state update for [{}]", summary);
        final ClusterState previousClusterState = state();

        if (previousClusterState.nodes().isLocalNodeElectedMaster() == false && taskInputs.runOnlyWhenMaster()) {
            logger.debug("failing [{}]: local node is no longer master", summary);
            taskInputs.onNoLongerMaster();
            return;
        }

        final long computationStartTime = threadPool.rawRelativeTimeInMillis();
        final TaskOutputs taskOutputs = calculateTaskOutputs(taskInputs, previousClusterState);
        taskOutputs.notifyFailedTasks();
        final TimeValue computationTime = getTimeSince(computationStartTime);
        logExecutionTime(computationTime, "compute cluster state update", summary);

        if (taskOutputs.clusterStateUnchanged()) {
            final long notificationStartTime = threadPool.rawRelativeTimeInMillis();
            taskOutputs.notifySuccessfulTasksOnUnchangedClusterState();
            final TimeValue executionTime = getTimeSince(notificationStartTime);
            logExecutionTime(executionTime, "notify listeners on unchanged cluster state", summary);
            clusterStateUpdateStatsTracker.onUnchangedClusterState(computationTime.millis(), executionTime.millis());
        } else {
            final ClusterState newClusterState = taskOutputs.newClusterState;
            if (logger.isTraceEnabled()) {
                logger.trace("cluster state updated, source [{}]\n{}", summary, newClusterState);
            } else {
                logger.debug("cluster state updated, version [{}], source [{}]", newClusterState.version(), summary);
            }
            final long publicationStartTime = threadPool.rawRelativeTimeInMillis();
            try {
                final ClusterStatePublicationEvent clusterStatePublicationEvent = new ClusterStatePublicationEvent(
                    summary,
                    previousClusterState,
                    newClusterState,
                    computationTime.millis(),
                    publicationStartTime
                );

                // new cluster state, notify all listeners
                final DiscoveryNodes.Delta nodesDelta = newClusterState.nodes().delta(previousClusterState.nodes());
                if (nodesDelta.hasChanges() && logger.isInfoEnabled()) {
                    String nodesDeltaSummary = nodesDelta.shortSummary();
                    if (nodesDeltaSummary.length() > 0) {
                        logger.info(
                            "{}, term: {}, version: {}, delta: {}",
                            summary,
                            newClusterState.term(),
                            newClusterState.version(),
                            nodesDeltaSummary
                        );
                    }
                }

                logger.debug("publishing cluster state version [{}]", newClusterState.version());
                publish(clusterStatePublicationEvent, taskOutputs);
            } catch (Exception e) {
                handleException(summary, publicationStartTime, newClusterState, e);
            }
        }
    }

    private TimeValue getTimeSince(long startTimeMillis) {
        return TimeValue.timeValueMillis(Math.max(0, threadPool.rawRelativeTimeInMillis() - startTimeMillis));
    }

    protected void publish(ClusterStatePublicationEvent clusterStatePublicationEvent, TaskOutputs taskOutputs) {
        final PlainActionFuture<Void> fut = new PlainActionFuture<Void>() {
            @Override
            protected boolean blockingAllowed() {
                return isMasterUpdateThread() || super.blockingAllowed();
            }
        };
        clusterStatePublisher.publish(
            clusterStatePublicationEvent,
            fut,
            taskOutputs.createAckListener(threadPool, clusterStatePublicationEvent.getNewState())
        );

        // indefinitely wait for publication to complete
        try {
            FutureUtils.get(fut);
            onPublicationSuccess(clusterStatePublicationEvent, taskOutputs);
        } catch (Exception e) {
            onPublicationFailed(clusterStatePublicationEvent, taskOutputs, e);
        }
    }

    void onPublicationSuccess(ClusterStatePublicationEvent clusterStatePublicationEvent, TaskOutputs taskOutputs) {
        final long notificationStartTime = threadPool.rawRelativeTimeInMillis();
        taskOutputs.processedDifferentClusterState(clusterStatePublicationEvent.getOldState(), clusterStatePublicationEvent.getNewState());

        try {
            taskOutputs.clusterStatePublished(clusterStatePublicationEvent);
        } catch (Exception e) {
            logger.error(
                () -> new ParameterizedMessage(
                    "exception thrown while notifying executor of new cluster state publication [{}]",
                    clusterStatePublicationEvent.getSummary()
                ),
                e
            );
        }
        final TimeValue executionTime = getTimeSince(notificationStartTime);
        logExecutionTime(
            executionTime,
            "notify listeners on successful publication of cluster state (version: "
                + clusterStatePublicationEvent.getNewState().version()
                + ", uuid: "
                + clusterStatePublicationEvent.getNewState().stateUUID()
                + ')',
            clusterStatePublicationEvent.getSummary()
        );
        clusterStateUpdateStatsTracker.onPublicationSuccess(
            threadPool.rawRelativeTimeInMillis(),
            clusterStatePublicationEvent,
            executionTime.millis()
        );
    }

    void onPublicationFailed(ClusterStatePublicationEvent clusterStatePublicationEvent, TaskOutputs taskOutputs, Exception exception) {
        if (exception instanceof FailedToCommitClusterStateException) {
            final long notificationStartTime = threadPool.rawRelativeTimeInMillis();
            final long version = clusterStatePublicationEvent.getNewState().version();
            logger.warn(
                () -> new ParameterizedMessage(
                    "failing [{}]: failed to commit cluster state version [{}]",
                    clusterStatePublicationEvent.getSummary(),
                    version
                ),
                exception
            );
            taskOutputs.publishingFailed((FailedToCommitClusterStateException) exception);
            final long notificationMillis = threadPool.rawRelativeTimeInMillis() - notificationStartTime;
            clusterStateUpdateStatsTracker.onPublicationFailure(
                threadPool.rawRelativeTimeInMillis(),
                clusterStatePublicationEvent,
                notificationMillis
            );
        } else {
            assert false : exception;
            clusterStateUpdateStatsTracker.onPublicationFailure(threadPool.rawRelativeTimeInMillis(), clusterStatePublicationEvent, 0L);
            handleException(
                clusterStatePublicationEvent.getSummary(),
                clusterStatePublicationEvent.getPublicationStartTimeMillis(),
                clusterStatePublicationEvent.getNewState(),
                exception
            );
        }
    }

    private void handleException(String summary, long startTimeMillis, ClusterState newClusterState, Exception e) {
        final TimeValue executionTime = getTimeSince(startTimeMillis);
        final long version = newClusterState.version();
        final String stateUUID = newClusterState.stateUUID();
        final String fullState = newClusterState.toString();
        logger.warn(
            new ParameterizedMessage(
                "took [{}] and then failed to publish updated cluster state (version: {}, uuid: {}) for [{}]:\n{}",
                executionTime,
                version,
                stateUUID,
                summary,
                fullState
            ),
            e
        );
        // TODO: do we want to call updateTask.onFailure here?
    }

    private TaskOutputs calculateTaskOutputs(TaskInputs taskInputs, ClusterState previousClusterState) {
        ClusterTasksResult<Object> clusterTasksResult = executeTasks(taskInputs, previousClusterState);
        ClusterState newClusterState = patchVersions(previousClusterState, clusterTasksResult);
        return new TaskOutputs(
            taskInputs,
            previousClusterState,
            newClusterState,
            getNonFailedTasks(taskInputs, clusterTasksResult),
            clusterTasksResult.executionResults
        );
    }

    private ClusterState patchVersions(ClusterState previousClusterState, ClusterTasksResult<?> executionResult) {
        ClusterState newClusterState = executionResult.resultingState;

        if (previousClusterState != newClusterState) {
            // only the master controls the version numbers
            final var previousIndicesLookup = newClusterState.metadata().getIndicesLookup();
            Builder builder = incrementVersion(newClusterState);
            if (previousClusterState.routingTable() != newClusterState.routingTable()) {
                builder.routingTable(newClusterState.routingTable().withIncrementedVersion());
            }
            if (previousClusterState.metadata() != newClusterState.metadata()) {
                builder.metadata(newClusterState.metadata().withIncrementedVersion());
            }

            newClusterState = builder.build();
            assert previousIndicesLookup == newClusterState.metadata().getIndicesLookup();
        }

        return newClusterState;
    }

    public Builder incrementVersion(ClusterState clusterState) {
        return ClusterState.builder(clusterState).incrementVersion();
    }

    /**
     * Submits a cluster state update task; unlike {@link #submitStateUpdateTask(String, Object, ClusterStateTaskConfig,
     * ClusterStateTaskExecutor, ClusterStateTaskListener)}, submitted updates will not be batched.
     *
     * @param source     the source of the cluster state update task
     * @param updateTask the full context for the cluster state update
     *                   task
     *
     */
    public <T extends ClusterStateTaskConfig & ClusterStateTaskExecutor<T> & ClusterStateTaskListener> void submitStateUpdateTask(
        String source,
        T updateTask
    ) {
        submitStateUpdateTask(source, updateTask, updateTask, updateTask, updateTask);
    }

    /**
     * Submits a cluster state update task; submitted updates will be
     * batched across the same instance of executor. The exact batching
     * semantics depend on the underlying implementation but a rough
     * guideline is that if the update task is submitted while there
     * are pending update tasks for the same executor, these update
     * tasks will all be executed on the executor in a single batch
     *
     * @param source   the source of the cluster state update task
     * @param task     the state needed for the cluster state update task
     * @param config   the cluster state update task configuration
     * @param executor the cluster state update task executor; tasks
     *                 that share the same executor will be executed
     *                 batches on this executor
     * @param listener callback after the cluster state update task
     *                 completes
     * @param <T>      the type of the cluster state update task state
     *
     */
    public <T> void submitStateUpdateTask(
        String source,
        T task,
        ClusterStateTaskConfig config,
        ClusterStateTaskExecutor<T> executor,
        ClusterStateTaskListener listener
    ) {
        submitStateUpdateTasks(source, Collections.singletonMap(task, listener), config, executor);
    }

    /**
     * Output created by executing a set of tasks provided as TaskInputs
     */
    class TaskOutputs {
        final TaskInputs taskInputs;
        final ClusterState previousClusterState;
        final ClusterState newClusterState;
        final List<Batcher.UpdateTask> nonFailedTasks;
        final Map<Object, ClusterStateTaskExecutor.TaskResult> executionResults;

        TaskOutputs(
            TaskInputs taskInputs,
            ClusterState previousClusterState,
            ClusterState newClusterState,
            List<Batcher.UpdateTask> nonFailedTasks,
            Map<Object, ClusterStateTaskExecutor.TaskResult> executionResults
        ) {
            this.taskInputs = taskInputs;
            this.previousClusterState = previousClusterState;
            this.newClusterState = newClusterState;
            this.nonFailedTasks = nonFailedTasks;
            this.executionResults = executionResults;
        }

        void publishingFailed(FailedToCommitClusterStateException t) {
            nonFailedTasks.forEach(task -> task.listener.onFailure(task.source(), t));
        }

        void processedDifferentClusterState(ClusterState previousClusterState, ClusterState newClusterState) {
            nonFailedTasks.forEach(task -> task.listener.clusterStateProcessed(task.source(), previousClusterState, newClusterState));
        }

        void clusterStatePublished(ClusterStatePublicationEvent clusterStatePublicationEvent) {
            taskInputs.executor.clusterStatePublished(clusterStatePublicationEvent);
        }

        ClusterStatePublisher.AckListener createAckListener(ThreadPool threadPool, ClusterState newClusterState) {
            return new DelegatingAckListener(
                nonFailedTasks.stream()
                    .filter(task -> task.listener instanceof AckedClusterStateTaskListener)
                    .map(
                        task -> new AckCountDownListener(
                            (AckedClusterStateTaskListener) task.listener,
                            newClusterState.version(),
                            newClusterState.nodes(),
                            threadPool
                        )
                    )
                    .collect(Collectors.toList())
            );
        }

        boolean clusterStateUnchanged() {
            return previousClusterState == newClusterState;
        }

        void notifyFailedTasks() {
            // fail all tasks that have failed
            for (Batcher.UpdateTask updateTask : taskInputs.updateTasks) {
                assert executionResults.containsKey(updateTask.task) : "missing " + updateTask;
                final ClusterStateTaskExecutor.TaskResult taskResult = executionResults.get(updateTask.task);
                if (taskResult.isSuccess() == false) {
                    updateTask.listener.onFailure(updateTask.source(), taskResult.getFailure());
                }
            }
        }

        void notifySuccessfulTasksOnUnchangedClusterState() {
            nonFailedTasks.forEach(task -> {
                if (task.listener instanceof AckedClusterStateTaskListener) {
                    // no need to wait for ack if nothing changed, the update can be counted as acknowledged
                    ((AckedClusterStateTaskListener) task.listener).onAllNodesAcked(null);
                }
                task.listener.clusterStateProcessed(task.source(), newClusterState, newClusterState);
            });
        }
    }

    /**
     * Returns the tasks that are pending.
     */
    public List<PendingClusterTask> pendingTasks() {
        return Arrays.stream(threadPoolExecutor.getPending()).map(pending -> {
            assert pending.task instanceof SourcePrioritizedRunnable
                : "thread pool executor should only use SourcePrioritizedRunnable instances but found: "
                    + pending.task.getClass().getName();
            SourcePrioritizedRunnable task = (SourcePrioritizedRunnable) pending.task;
            return new PendingClusterTask(
                pending.insertionOrder,
                pending.priority,
                new Text(task.source()),
                task.getAgeInMillis(),
                pending.executing
            );
        }).collect(Collectors.toList());
    }

    /**
     * Returns the number of currently pending tasks.
     */
    public int numberOfPendingTasks() {
        return threadPoolExecutor.getNumberOfPendingTasks();
    }

    /**
     * Returns the maximum wait time for tasks in the queue
     *
     * @return A zero time value if the queue is empty, otherwise the time value oldest task waiting in the queue
     */
    public TimeValue getMaxTaskWaitTime() {
        return threadPoolExecutor.getMaxTaskWaitTime();
    }

    private SafeClusterStateTaskListener safe(ClusterStateTaskListener listener, Supplier<ThreadContext.StoredContext> contextSupplier) {
        if (listener instanceof AckedClusterStateTaskListener) {
            return new SafeAckedClusterStateTaskListener((AckedClusterStateTaskListener) listener, contextSupplier, logger);
        } else {
            return new SafeClusterStateTaskListener(listener, contextSupplier, logger);
        }
    }

    private static class SafeClusterStateTaskListener implements ClusterStateTaskListener {
        private final ClusterStateTaskListener listener;
        protected final Supplier<ThreadContext.StoredContext> context;
        private final Logger logger;

        SafeClusterStateTaskListener(ClusterStateTaskListener listener, Supplier<ThreadContext.StoredContext> context, Logger logger) {
            this.listener = listener;
            this.context = context;
            this.logger = logger;
        }

        @Override
        public void onFailure(String source, Exception e) {
            try (ThreadContext.StoredContext ignore = context.get()) {
                listener.onFailure(source, e);
            } catch (Exception inner) {
                inner.addSuppressed(e);
                logger.error(() -> new ParameterizedMessage("exception thrown by listener notifying of failure from [{}]", source), inner);
            }
        }

        @Override
        public void onNoLongerMaster(String source) {
            try (ThreadContext.StoredContext ignore = context.get()) {
                listener.onNoLongerMaster(source);
            } catch (Exception e) {
                logger.error(
                    () -> new ParameterizedMessage("exception thrown by listener while notifying no longer master from [{}]", source),
                    e
                );
            }
        }

        @Override
        public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
            try (ThreadContext.StoredContext ignore = context.get()) {
                listener.clusterStateProcessed(source, oldState, newState);
            } catch (Exception e) {
                logger.error(
                    () -> new ParameterizedMessage(
                        "exception thrown by listener while notifying of cluster state processed from [{}], old cluster state:\n"
                            + "{}\nnew cluster state:\n{}",
                        source,
                        oldState,
                        newState
                    ),
                    e
                );
            }
        }
    }

    private static class SafeAckedClusterStateTaskListener extends SafeClusterStateTaskListener implements AckedClusterStateTaskListener {
        private final AckedClusterStateTaskListener listener;
        private final Logger logger;

        SafeAckedClusterStateTaskListener(
            AckedClusterStateTaskListener listener,
            Supplier<ThreadContext.StoredContext> context,
            Logger logger
        ) {
            super(listener, context, logger);
            this.listener = listener;
            this.logger = logger;
        }

        @Override
        public boolean mustAck(DiscoveryNode discoveryNode) {
            return listener.mustAck(discoveryNode);
        }

        @Override
        public void onAllNodesAcked(@Nullable Exception e) {
            try (ThreadContext.StoredContext ignore = context.get()) {
                listener.onAllNodesAcked(e);
            } catch (Exception inner) {
                inner.addSuppressed(e);
                logger.error("exception thrown by listener while notifying on all nodes acked", inner);
            }
        }

        @Override
        public void onAckTimeout() {
            try (ThreadContext.StoredContext ignore = context.get()) {
                listener.onAckTimeout();
            } catch (Exception e) {
                logger.error("exception thrown by listener while notifying on ack timeout", e);
            }
        }

        @Override
        public TimeValue ackTimeout() {
            return listener.ackTimeout();
        }
    }

    private void logExecutionTime(TimeValue executionTime, String activity, String summary) {
        if (executionTime.getMillis() > slowTaskLoggingThreshold.getMillis()) {
            logger.warn(
                "took [{}/{}ms] to {} for [{}], which exceeds the warn threshold of [{}]",
                executionTime,
                executionTime.getMillis(),
                activity,
                summary,
                slowTaskLoggingThreshold
            );
        } else {
            logger.debug("took [{}] to {} for [{}]", executionTime, activity, summary);
        }
    }

    private static class DelegatingAckListener implements ClusterStatePublisher.AckListener {

        private final List<ClusterStatePublisher.AckListener> listeners;

        private DelegatingAckListener(List<ClusterStatePublisher.AckListener> listeners) {
            this.listeners = listeners;
        }

        @Override
        public void onCommit(TimeValue commitTime) {
            for (ClusterStatePublisher.AckListener listener : listeners) {
                listener.onCommit(commitTime);
            }
        }

        @Override
        public void onNodeAck(DiscoveryNode node, @Nullable Exception e) {
            for (ClusterStatePublisher.AckListener listener : listeners) {
                listener.onNodeAck(node, e);
            }
        }
    }

    private static class AckCountDownListener implements ClusterStatePublisher.AckListener {

        private static final Logger logger = LogManager.getLogger(AckCountDownListener.class);

        private final AckedClusterStateTaskListener ackedTaskListener;
        private final CountDown countDown;
        private final DiscoveryNode masterNode;
        private final ThreadPool threadPool;
        private final long clusterStateVersion;
        private volatile Scheduler.Cancellable ackTimeoutCallback;
        private Exception lastFailure;

        AckCountDownListener(
            AckedClusterStateTaskListener ackedTaskListener,
            long clusterStateVersion,
            DiscoveryNodes nodes,
            ThreadPool threadPool
        ) {
            this.ackedTaskListener = ackedTaskListener;
            this.clusterStateVersion = clusterStateVersion;
            this.threadPool = threadPool;
            this.masterNode = nodes.getMasterNode();
            int countDown = 0;
            for (DiscoveryNode node : nodes) {
                // we always wait for at least the master node
                if (node.equals(masterNode) || ackedTaskListener.mustAck(node)) {
                    countDown++;
                }
            }
            logger.trace("expecting {} acknowledgements for cluster_state update (version: {})", countDown, clusterStateVersion);
            this.countDown = new CountDown(countDown + 1); // we also wait for onCommit to be called
        }

        @Override
        public void onCommit(TimeValue commitTime) {
            TimeValue ackTimeout = ackedTaskListener.ackTimeout();
            if (ackTimeout == null) {
                ackTimeout = TimeValue.ZERO;
            }
            final TimeValue timeLeft = TimeValue.timeValueNanos(Math.max(0, ackTimeout.nanos() - commitTime.nanos()));
            if (timeLeft.nanos() == 0L) {
                onTimeout();
            } else if (countDown.countDown()) {
                finish();
            } else {
                this.ackTimeoutCallback = threadPool.schedule(this::onTimeout, timeLeft, ThreadPool.Names.GENERIC);
                // re-check if onNodeAck has not completed while we were scheduling the timeout
                if (countDown.isCountedDown()) {
                    ackTimeoutCallback.cancel();
                }
            }
        }

        @Override
        public void onNodeAck(DiscoveryNode node, @Nullable Exception e) {
            if (node.equals(masterNode) == false && ackedTaskListener.mustAck(node) == false) {
                return;
            }
            if (e == null) {
                logger.trace("ack received from node [{}], cluster_state update (version: {})", node, clusterStateVersion);
            } else {
                this.lastFailure = e;
                logger.debug(
                    () -> new ParameterizedMessage(
                        "ack received from node [{}], cluster_state update (version: {})",
                        node,
                        clusterStateVersion
                    ),
                    e
                );
            }

            if (countDown.countDown()) {
                finish();
            }
        }

        private void finish() {
            logger.trace("all expected nodes acknowledged cluster_state update (version: {})", clusterStateVersion);
            if (ackTimeoutCallback != null) {
                ackTimeoutCallback.cancel();
            }
            ackedTaskListener.onAllNodesAcked(lastFailure);
        }

        public void onTimeout() {
            if (countDown.fastForward()) {
                logger.trace("timeout waiting for acknowledgement for cluster_state update (version: {})", clusterStateVersion);
                ackedTaskListener.onAckTimeout();
            }
        }
    }

    private ClusterTasksResult<Object> executeTasks(TaskInputs taskInputs, ClusterState previousClusterState) {
        ClusterTasksResult<Object> clusterTasksResult;
        try {
            List<Object> inputs = taskInputs.updateTasks.stream().map(tUpdateTask -> tUpdateTask.task).collect(Collectors.toList());
            clusterTasksResult = taskInputs.executor.execute(previousClusterState, inputs);
            if (previousClusterState != clusterTasksResult.resultingState
                && previousClusterState.nodes().isLocalNodeElectedMaster()
                && (clusterTasksResult.resultingState.nodes().isLocalNodeElectedMaster() == false)) {
                throw new AssertionError("update task submitted to MasterService cannot remove master");
            }
        } catch (Exception e) {
            logger.trace(
                () -> new ParameterizedMessage(
                    "failed to execute cluster state update (on version: [{}], uuid: [{}]) for [{}]\n{}{}{}",
                    previousClusterState.version(),
                    previousClusterState.stateUUID(),
                    taskInputs.summary,
                    previousClusterState.nodes(),
                    previousClusterState.routingTable(),
                    previousClusterState.getRoutingNodes()
                ), // may be expensive => construct message lazily
                e
            );
            clusterTasksResult = ClusterTasksResult.builder()
                .failures(taskInputs.updateTasks.stream().map(updateTask -> updateTask.task)::iterator, e)
                .build(previousClusterState);
        }

        assert clusterTasksResult.executionResults != null;
        assert clusterTasksResult.executionResults.size() == taskInputs.updateTasks.size()
            : String.format(
                Locale.ROOT,
                "expected [%d] task result%s but was [%d]",
                taskInputs.updateTasks.size(),
                taskInputs.updateTasks.size() == 1 ? "" : "s",
                clusterTasksResult.executionResults.size()
            );
        if (Assertions.ENABLED) {
            ClusterTasksResult<Object> finalClusterTasksResult = clusterTasksResult;
            taskInputs.updateTasks.forEach(
                updateTask -> {
                    assert finalClusterTasksResult.executionResults.containsKey(updateTask.task) : "missing task result for " + updateTask;
                }
            );
        }

        return clusterTasksResult;
    }

    private List<Batcher.UpdateTask> getNonFailedTasks(TaskInputs taskInputs, ClusterTasksResult<Object> clusterTasksResult) {
        return taskInputs.updateTasks.stream().filter(updateTask -> {
            assert clusterTasksResult.executionResults.containsKey(updateTask.task) : "missing " + updateTask;
            final ClusterStateTaskExecutor.TaskResult taskResult = clusterTasksResult.executionResults.get(updateTask.task);
            return taskResult.isSuccess();
        }).collect(Collectors.toList());
    }

    /**
     * Represents a set of tasks to be processed together with their executor
     */
    private class TaskInputs {
        final String summary;
        final List<Batcher.UpdateTask> updateTasks;
        final ClusterStateTaskExecutor<Object> executor;

        TaskInputs(ClusterStateTaskExecutor<Object> executor, List<Batcher.UpdateTask> updateTasks, String summary) {
            this.summary = summary;
            this.executor = executor;
            this.updateTasks = updateTasks;
        }

        boolean runOnlyWhenMaster() {
            return executor.runOnlyOnMaster();
        }

        void onNoLongerMaster() {
            updateTasks.forEach(task -> task.listener.onNoLongerMaster(task.source()));
        }
    }

    /**
     * Submits a batch of cluster state update tasks; submitted updates are guaranteed to be processed together,
     * potentially with more tasks of the same executor.
     *
     * @param source   the source of the cluster state update task
     * @param tasks    a map of update tasks and their corresponding listeners
     * @param config   the cluster state update task configuration
     * @param executor the cluster state update task executor; tasks
     *                 that share the same executor will be executed
     *                 batches on this executor
     * @param <T>      the type of the cluster state update task state
     *
     */
    public <T> void submitStateUpdateTasks(
        final String source,
        final Map<T, ClusterStateTaskListener> tasks,
        final ClusterStateTaskConfig config,
        final ClusterStateTaskExecutor<T> executor
    ) {
        if (lifecycle.started() == false) {
            return;
        }
        final ThreadContext threadContext = threadPool.getThreadContext();
        final Supplier<ThreadContext.StoredContext> supplier = threadContext.newRestorableContext(true);
        try (ThreadContext.StoredContext ignore = threadContext.stashContext()) {
            threadContext.markAsSystemContext();

            List<Batcher.UpdateTask> safeTasks = tasks.entrySet()
                .stream()
                .map(e -> taskBatcher.new UpdateTask(config.priority(), source, e.getKey(), safe(e.getValue(), supplier), executor))
                .collect(Collectors.toList());
            taskBatcher.submitTasks(safeTasks, config.timeout());
        } catch (EsRejectedExecutionException e) {
            // ignore cases where we are shutting down..., there is really nothing interesting
            // to be done here...
            if (lifecycle.stoppedOrClosed() == false) {
                throw e;
            }
        }
    }

    private static class MasterServiceStarvationWatcher implements PrioritizedEsThreadPoolExecutor.StarvationWatcher {

        private final long warnThreshold;
        private final LongSupplier nowMillisSupplier;
        private final Supplier<PrioritizedEsThreadPoolExecutor> threadPoolExecutorSupplier;

        // accesses of these mutable fields are synchronized (on this)
        private long lastLogMillis;
        private long nonemptySinceMillis;
        private boolean isEmpty = true;

        MasterServiceStarvationWatcher(
            long warnThreshold,
            LongSupplier nowMillisSupplier,
            Supplier<PrioritizedEsThreadPoolExecutor> threadPoolExecutorSupplier
        ) {
            this.nowMillisSupplier = nowMillisSupplier;
            this.threadPoolExecutorSupplier = threadPoolExecutorSupplier;
            this.warnThreshold = warnThreshold;
        }

        @Override
        public synchronized void onEmptyQueue() {
            isEmpty = true;
        }

        @Override
        public void onNonemptyQueue() {
            final long nowMillis = nowMillisSupplier.getAsLong();
            final long nonemptyDurationMillis;
            synchronized (this) {
                if (isEmpty) {
                    isEmpty = false;
                    nonemptySinceMillis = nowMillis;
                    lastLogMillis = nowMillis;
                    return;
                }

                if (nowMillis - lastLogMillis < warnThreshold) {
                    return;
                }

                lastLogMillis = nowMillis;
                nonemptyDurationMillis = nowMillis - nonemptySinceMillis;
            }

            final PrioritizedEsThreadPoolExecutor threadPoolExecutor = threadPoolExecutorSupplier.get();
            final TimeValue maxTaskWaitTime = threadPoolExecutor.getMaxTaskWaitTime();
            logger.warn(
                "pending task queue has been nonempty for [{}/{}ms] which is longer than the warn threshold of [{}ms];"
                    + " there are currently [{}] pending tasks, the oldest of which has age [{}/{}ms]",
                TimeValue.timeValueMillis(nonemptyDurationMillis),
                nonemptyDurationMillis,
                warnThreshold,
                threadPoolExecutor.getNumberOfPendingTasks(),
                maxTaskWaitTime,
                maxTaskWaitTime.millis()
            );
        }
    }

    private static class ClusterStateUpdateStatsTracker {

        private long unchangedTaskCount;
        private long publicationSuccessCount;
        private long publicationFailureCount;

        private long unchangedComputationElapsedMillis;
        private long unchangedNotificationElapsedMillis;

        private long successfulComputationElapsedMillis;
        private long successfulPublicationElapsedMillis;
        private long successfulContextConstructionElapsedMillis;
        private long successfulCommitElapsedMillis;
        private long successfulCompletionElapsedMillis;
        private long successfulMasterApplyElapsedMillis;
        private long successfulNotificationElapsedMillis;

        private long failedComputationElapsedMillis;
        private long failedPublicationElapsedMillis;
        private long failedContextConstructionElapsedMillis;
        private long failedCommitElapsedMillis;
        private long failedCompletionElapsedMillis;
        private long failedMasterApplyElapsedMillis;
        private long failedNotificationElapsedMillis;

        synchronized void onUnchangedClusterState(long computationElapsedMillis, long notificationElapsedMillis) {
            unchangedTaskCount += 1;
            unchangedComputationElapsedMillis += computationElapsedMillis;
            unchangedNotificationElapsedMillis += notificationElapsedMillis;
        }

        synchronized void onPublicationSuccess(
            long currentTimeMillis,
            ClusterStatePublicationEvent clusterStatePublicationEvent,
            long notificationElapsedMillis
        ) {
            publicationSuccessCount += 1;
            successfulComputationElapsedMillis += clusterStatePublicationEvent.getComputationTimeMillis();
            successfulPublicationElapsedMillis += currentTimeMillis - clusterStatePublicationEvent.getPublicationStartTimeMillis();
            successfulContextConstructionElapsedMillis += clusterStatePublicationEvent.getPublicationContextConstructionElapsedMillis();
            successfulCommitElapsedMillis += clusterStatePublicationEvent.getPublicationCommitElapsedMillis();
            successfulCompletionElapsedMillis += clusterStatePublicationEvent.getPublicationCompletionElapsedMillis();
            successfulMasterApplyElapsedMillis += clusterStatePublicationEvent.getMasterApplyElapsedMillis();
            successfulNotificationElapsedMillis += notificationElapsedMillis;
        }

        synchronized void onPublicationFailure(
            long currentTimeMillis,
            ClusterStatePublicationEvent clusterStatePublicationEvent,
            long notificationMillis
        ) {
            publicationFailureCount += 1;
            failedComputationElapsedMillis += clusterStatePublicationEvent.getComputationTimeMillis();
            failedPublicationElapsedMillis += currentTimeMillis - clusterStatePublicationEvent.getPublicationStartTimeMillis();
            failedContextConstructionElapsedMillis += clusterStatePublicationEvent.maybeGetPublicationContextConstructionElapsedMillis();
            failedCommitElapsedMillis += clusterStatePublicationEvent.maybeGetPublicationCommitElapsedMillis();
            failedCompletionElapsedMillis += clusterStatePublicationEvent.maybeGetPublicationCompletionElapsedMillis();
            failedMasterApplyElapsedMillis += clusterStatePublicationEvent.maybeGetMasterApplyElapsedMillis();
            failedNotificationElapsedMillis += notificationMillis;
        }

        synchronized ClusterStateUpdateStats getStatistics() {
            return new ClusterStateUpdateStats(
                unchangedTaskCount,
                publicationSuccessCount,
                publicationFailureCount,
                unchangedComputationElapsedMillis,
                unchangedNotificationElapsedMillis,
                successfulComputationElapsedMillis,
                successfulPublicationElapsedMillis,
                successfulContextConstructionElapsedMillis,
                successfulCommitElapsedMillis,
                successfulCompletionElapsedMillis,
                successfulMasterApplyElapsedMillis,
                successfulNotificationElapsedMillis,
                failedComputationElapsedMillis,
                failedPublicationElapsedMillis,
                failedContextConstructionElapsedMillis,
                failedCommitElapsedMillis,
                failedCompletionElapsedMillis,
                failedMasterApplyElapsedMillis,
                failedNotificationElapsedMillis
            );
        }
    }

}


text:
"use strict";

angular.module("people").controller("peopleExploreController", ['$scope','$route','$q','$window','peopleService','$rootScope', function ($scope, $route,$q,$window, peopleService,$rootScope) {

    $scope.classes = ['hansas', 'sadhus', 'yoginis'];

    $scope.relatedData = [];
    $scope.dynamicList = [];
    $scope.allRelatedData = [];

    var sortService = function(firstItem, secondItem){
        if(firstItem.type === 'reflection' && secondItem.type != 'reflection'){
            return firstItem.englishTitle.localeCompare(secondItem.translitTitle);
        }
        else if(firstItem.type != 'reflection' && secondItem.type === 'reflection'){
            return firstItem.translitTitle.localeCompare(secondItem.englishTitle);
        }
        else if(firstItem.type != 'reflection' && secondItem.type != 'reflection'){
            return firstItem.translitTitle.localeCompare(secondItem.translitTitle);
        }
        return firstItem.englishTitle.localeCompare(secondItem.englishTitle);
    };

    $scope.init = function(){
        $scope.person = {};
        var personId = $route.current.params.id;

        var songPromise = peopleService.getSongs(personId);
        var reflectionPromise = peopleService.getReflections(personId);
        var wordPromise = peopleService.getWords(personId);

        var promises = [songPromise, reflectionPromise, wordPromise];

        peopleService.getPerson(personId).then(function(response){
            $scope.person = new AjabShahar.peopleModel(response.data);
            $rootScope.pageSynopsis = {
                title:$scope.person.name,
                image:$scope.person.thumbnailImg,
                description:$scope.person.profile
            };
        });

        $q.all(promises).then(function(data){
            var songs = data[0].data.songs;
            songs.length > 0 ? $scope.dynamicList.push({name:"songs",selected:false}) : '';

            _.each(songs, function(song){
                $scope.relatedData.push(new AjabShahar.ThumbnailObject(song,"song"));
            });

            var reflections = data[1].data;

            _.each(reflections, function(reflection){
                $scope.relatedData.push(new AjabShahar.ThumbnailObject(reflection,"reflection"));
            });

            var words = data[2].data;
            _.each(words, function(word){
                $scope.relatedData.push(new AjabShahar.ThumbnailObject(word,"word"));
            });
            reflections.length > 0 || words.length > 0? $scope.dynamicList.push({name:"reflections",selected:false}) : '';

            $scope.relatedData = $scope.relatedData.sort(sortService);
            $scope.dynamicList.push({name:"all",selected:true});
            $scope.allRelatedData = angular.copy($scope.relatedData);

        });
    };

    $scope.applyFilter = function(criteria){
        if(criteria === 'all')
          $scope.relatedData = angular.copy($scope.allRelatedData);
        else{
            $scope.relatedData = _.filter($scope.allRelatedData,function(item){
                return criteria.indexOf(item.type) === 0 || criteria === 'reflections' && item.type === 'word' ;
            })
        }

        _.each($scope.dynamicList,function(item){
            item.selected = item.name === criteria
        })
    };

    $scope.selectThumbnail = function(thumbnail){
        $window.location.href = thumbnail.getUrl();
    };

    $scope.init();

}]);


text:
"""
Copyright 2017 Pani Networks Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"""

#
# A watcher plugin for observing a route spec config file for changes.
#

import datetime
import json
import logging
import os

import watchdog.events
import watchdog.observers

from vpcrouter.errors  import ArgsError
from vpcrouter.watcher import common

class RouteSpecChangeEventHandler(watchdog.events.FileSystemEventHandler):
    """
    Our own event handler class, to be used to process events on the route-spec
    file.

    """
    def __init__(self, *args, **kwargs):
        self._route_spec_fname   = kwargs['route_spec_fname']
        self._route_spec_abspath = kwargs['route_spec_abspath']
        self._q_route_spec       = kwargs['q_route_spec']
        self._plugin             = kwargs['plugin']

        del kwargs['route_spec_fname']
        del kwargs['route_spec_abspath']
        del kwargs['q_route_spec']
        del kwargs['plugin']

        super(RouteSpecChangeEventHandler, self).__init__(*args, **kwargs)

    def on_modified(self, event):
        if type(event) is watchdog.events.FileModifiedEvent and \
                                    event.src_path == self._route_spec_abspath:
            logging.info("Detected file change event for %s" %
                          self._route_spec_abspath)
            try:
                route_spec = read_route_spec_config(self._route_spec_fname)
                self._q_route_spec.put(route_spec)
                if self._plugin:
                    self._plugin.last_route_spec_update = \
                                            datetime.datetime.now()
            except ValueError as e:
                # In case of error in the config file, we don't send out a
                # message with a broken or empty list. Probably just temporary,
                # shouldn't stop operation of the system.
                logging.warning("Cannot parse route spec: %s" % str(e))

def read_route_spec_config(fname):
    """
    Read, parse and sanity check the route spec config file.

    The config file needs to be in this format:

    {
        "<CIDR-1>" : [ "host-1-ip", "host-2-ip", "host-3-ip" ],
        "<CIDR-2>" : [ "host-4-ip", "host-5-ip" ],
        "<CIDR-3>" : [ "host-6-ip", "host-7-ip", "host-8-ip", "host-9-ip" ]
    }

    Returns the validated route config.

    """
    try:
        try:
            f = open(fname, "r")
        except IOError as e:
            # Cannot open file? Doesn't exist?
            raise ValueError("Cannot open file: " + str(e))
        data = json.loads(f.read())
        f.close()
        # Sanity checking on the data object
        data = common.parse_route_spec_config(data)

    except ValueError as e:
        logging.error("Config ignored: %s" % str(e))
        data = None

    return data

class Configfile(common.WatcherPlugin):
    """
    Implements the WatcherPlugin interface for the 'configfile' plugin.

    Establishes a watcher thread, which detectes any changes to the config
    file and re-reads it.

    The plugin adds a command line argument to vpc-router:

    -f / --file: The name of the config file, which should be monitored.

    """
    def __init__(self, *args, **kwargs):
        super(Configfile, self).__init__(*args, **kwargs)
        self.last_route_spec_update = None

    def start(self):
        """
        Start the configfile change monitoring thread.

        """
        fname = self.conf['file']
        logging.info("Configfile watcher plugin: Starting to watch route spec "
                     "file '%s' for changes..." % fname)

        # Initial content of file needs to be processed at least once, before
        # we start watching for any changes to it. Therefore, we will write it
        # out on the queue right away.
        route_spec = {}
        try:
            route_spec = read_route_spec_config(fname)
            if route_spec:
                self.last_route_spec_update = datetime.datetime.now()
                self.q_route_spec.put(route_spec)
        except ValueError as e:
            logging.warning("Cannot parse route spec: %s" % str(e))

        # Now prepare to watch for any changes in that file.  Find the parent
        # directory of the config file, since this is where we will attach a
        # watcher to.
        abspath    = os.path.abspath(fname)
        parent_dir = os.path.dirname(abspath)

        # Create the file watcher and run in endless loop
        handler = RouteSpecChangeEventHandler(
                                    route_spec_fname   = fname,
                                    route_spec_abspath = abspath,
                                    q_route_spec       = self.q_route_spec,
                                    plugin             = self)
        self.observer_thread = watchdog.observers.Observer()
        self.observer_thread.name = "ConfMon"
        self.observer_thread.schedule(handler, parent_dir)
        self.observer_thread.start()

    def stop(self):
        """
        Stop the config change monitoring thread.

        """
        self.observer_thread.stop()
        self.observer_thread.join()
        logging.info("Configfile watcher plugin: Stopped")

    def get_info(self):
        """
        Return plugin information.

        """
        return {
            self.get_plugin_name() : {
                "version" : self.get_version(),
                "params" : {
                    "file" : self.conf['file']
                },
                "stats" : {
                    "last_route_spec_update" :
                        self.last_route_spec_update.isoformat()
                        if self.last_route_spec_update else "(no update, yet)"
                }
            }
        }

    @classmethod
    def add_arguments(cls, parser, sys_arg_list=None):
        """
        Arguments for the configfile mode.

        """
        parser.add_argument('-f', '--file', dest='file', required=True,
                            help="config file for routing groups "
                                 "(only in configfile mode)")
        return ["file"]

    @classmethod
    def check_arguments(cls, conf):
        """
        Sanity checks for options needed for configfile mode.

        """
        try:
            # Check we have access to the config file
            f = open(conf['file'], "r")
            f.close()
        except IOError as e:
            raise ArgsError("Cannot open config file '%s': %s" %
                            (conf['file'], e))


text:
package net.mostlyoriginal.api.system.camera;

import com.artemis.systems.VoidEntitySystem;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;

/**
 * Setup and manages basic orthographic camera.
 *
 * @author Daan van Yperen
 */
public class CameraSystem extends VoidEntitySystem {

    public final OrthographicCamera camera;
    public final OrthographicCamera guiCamera;
    public final float zoomFactorInverter;

    /**
     * @param zoom How much
     */
    public CameraSystem( float zoom ) {

        zoomFactorInverter = 1f/zoom;

        camera = new OrthographicCamera(Gdx.graphics.getWidth() * zoomFactorInverter, Gdx.graphics.getHeight() * zoomFactorInverter);
        camera.setToOrtho(false, Gdx.graphics.getWidth() * zoomFactorInverter, Gdx.graphics.getHeight() * zoomFactorInverter);
        camera.update();

        guiCamera = new OrthographicCamera(Gdx.graphics.getWidth() * zoomFactorInverter, Gdx.graphics.getHeight() * zoomFactorInverter);
        guiCamera.setToOrtho(false, Gdx.graphics.getWidth() * zoomFactorInverter, Gdx.graphics.getHeight() * zoomFactorInverter);
        guiCamera.update();
    }

    public float getPixelWidth()
    {
        return Gdx.graphics.getWidth() * zoomFactorInverter;
    }

    public float getPixelHeight()
    {
        return Gdx.graphics.getHeight() * zoomFactorInverter;
    }

    @Override
    protected void processSystem() {

    }
}


text:
<?php

//common environment attributes including search paths. not specific to Learnosity
include_once '../env_config.php';

//site scaffolding
include_once 'includes/header.php';

//common Learnosity config elements including API version control vars
include_once '../lrn_config.php';

use LearnositySdk\Request\Init;
use LearnositySdk\Utils\Uuid;

$security = [
    'consumer_key' => $consumer_key,
    'domain'       => $domain
];

//simple api request object for item list view, with optional creation of items
$request = [
    'mode' => 'activity_list',
    'user' => [
        'id' => 'demos-site',
        'firstname' => 'Demos',
        'lastname' => 'User',
        'email' => 'demos@learnosity.com'
    ]
];

$Init = new Init('author', $security, $consumer_secret, $request);
$signedRequest = $Init->generate();

?>

Browse Activities in Your Item Bank

The activity list mode allows authors to browse and search the Learnosity hosted item bank for existing activities.
                In this demo, we've enabled creation of new activities, but this functionality can be disabled as needed.

<?php
include_once 'views/modals/initialisation-preview.php';
include_once 'includes/footer.php';


text:
var GetFastValue = require('../utils/object/GetFastValue');

var Purchase = function (data)
{
    return {
        developerPayload: GetFastValue(data, 'developerPayload', ''),
        paymentID: GetFastValue(data, 'paymentID', ''),
        productID: GetFastValue(data, 'productID', ''),
        purchaseTime: GetFastValue(data, 'purchaseTime', ''),
        purchaseToken: GetFastValue(data, 'purchaseToken', ''),
        signedRequest: GetFastValue(data, 'signedRequest', '')
    };
};

module.exports = Purchase;


text:
#ifndef TimingFunction_h
#define TimingFunction_h

#include "platform/animation/AnimationUtilities.h" // For blend()
#include "platform/animation/UnitBezier.h"
#include "platform/heap/Handle.h"
#include "platform/heap/Heap.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/WTFString.h"

namespace blink {

class PLATFORM_EXPORT TimingFunction : public RefCounted<TimingFunction> {
public:

    enum Type {
        LinearFunction, CubicBezierFunction, StepsFunction
    };

    virtual ~TimingFunction() { }

    Type type() const { return m_type; }

    virtual String toString() const = 0;

    // Evaluates the timing function at the given fraction. The accuracy parameter provides a hint as to the required
    // accuracy and is not guaranteed.
    virtual double evaluate(double fraction, double accuracy) const = 0;

    // This function returns the minimum and maximum values obtainable when
    // calling evaluate();
    virtual void range(double* minValue, double* maxValue) const = 0;

    enum RangeHalf {
        Lower, // Timing function values < 0.5
        Upper // Timing function values >= 0.5
    };

    struct PartitionRegion {
        RangeHalf half;
        double start; // inclusive
        double end; // exclusive

        PartitionRegion(RangeHalf half, double start, double end)
            : half(half)
            , start(start)
            , end(end)
        { }
    };

    // Partitions the timing function into a number of regions,
    // representing the ranges in which the function's value is < 0.5
    // and >= 0.5, and hence whether interpolation 0 or 1 should be
    // used.
    virtual void partition(Vector<PartitionRegion>& regions) const = 0;

protected:
    TimingFunction(Type type)
        : m_type(type)
    {
    }

private:
    Type m_type;
};

class PLATFORM_EXPORT LinearTimingFunction final : public TimingFunction {
public:
    static LinearTimingFunction* shared()
    {
        DEFINE_STATIC_REF(LinearTimingFunction, linear, (adoptRef(new LinearTimingFunction())));
        return linear;
    }

    virtual ~LinearTimingFunction() { }

    virtual String toString() const override;

    virtual double evaluate(double fraction, double) const override;
    virtual void range(double* minValue, double* maxValue) const override;
    virtual void partition(Vector<PartitionRegion>& regions) const override;
private:
    LinearTimingFunction()
        : TimingFunction(LinearFunction)
    {
    }
};

class PLATFORM_EXPORT CubicBezierTimingFunction final : public TimingFunction {
public:
    enum SubType {
        Ease,
        EaseIn,
        EaseOut,
        EaseInOut,
        Custom
    };

    static PassRefPtr<CubicBezierTimingFunction> create(double x1, double y1, double x2, double y2)
    {
        return adoptRef(new CubicBezierTimingFunction(Custom, x1, y1, x2, y2));
    }

    static CubicBezierTimingFunction* preset(SubType subType)
    {
        switch (subType) {
        case Ease:
            {
                DEFINE_STATIC_REF(CubicBezierTimingFunction, ease, (adoptRef(new CubicBezierTimingFunction(Ease, 0.25, 0.1, 0.25, 1.0))));
                return ease;
            }
        case EaseIn:
            {
                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeIn, (adoptRef(new CubicBezierTimingFunction(EaseIn, 0.42, 0.0, 1.0, 1.0))));
                return easeIn;
            }
        case EaseOut:
            {
                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeOut, (adoptRef(new CubicBezierTimingFunction(EaseOut, 0.0, 0.0, 0.58, 1.0))));
                return easeOut;
            }
        case EaseInOut:
            {
                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeInOut, (adoptRef(new CubicBezierTimingFunction(EaseInOut, 0.42, 0.0, 0.58, 1.0))));
                return easeInOut;
            }
        default:
            ASSERT_NOT_REACHED();
            return 0;
        }
    }

    virtual ~CubicBezierTimingFunction() { }

    virtual String toString() const override;

    virtual double evaluate(double fraction, double accuracy) const override;
    virtual void range(double* minValue, double* maxValue) const override;
    virtual void partition(Vector<PartitionRegion>& regions) const override;

    double x1() const { return m_x1; }
    double y1() const { return m_y1; }
    double x2() const { return m_x2; }
    double y2() const { return m_y2; }

    SubType subType() const { return m_subType; }

private:
    explicit CubicBezierTimingFunction(SubType subType, double x1, double y1, double x2, double y2)
        : TimingFunction(CubicBezierFunction)
        , m_x1(x1)
        , m_y1(y1)
        , m_x2(x2)
        , m_y2(y2)
        , m_subType(subType)
    {
    }

    // Finds points on the cubic bezier that cross the given horizontal
    // line, storing their x values in solution1-3 and returning the
    // number of solutions found.
    size_t findIntersections(double intersectionY, double& solution1, double& solution2, double& solution3) const;

    double m_x1;
    double m_y1;
    double m_x2;
    double m_y2;
    SubType m_subType;
    mutable OwnPtr<UnitBezier> m_bezier;
};

class PLATFORM_EXPORT StepsTimingFunction final : public TimingFunction {
public:
    enum StepAtPosition {
        Start,
        Middle,
        End
    };

    static PassRefPtr<StepsTimingFunction> create(int steps, StepAtPosition stepAtPosition)
    {
        return adoptRef(new StepsTimingFunction(steps, stepAtPosition));
    }

    static StepsTimingFunction* preset(StepAtPosition position)
    {
        DEFINE_STATIC_REF(StepsTimingFunction, start, create(1, Start));
        DEFINE_STATIC_REF(StepsTimingFunction, middle, create(1, Middle));
        DEFINE_STATIC_REF(StepsTimingFunction, end, create(1, End));
        switch (position) {
        case Start:
            return start;
        case Middle:
            return middle;
        case End:
            return end;
        default:
            ASSERT_NOT_REACHED();
            return end;
        }
    }

    virtual ~StepsTimingFunction() { }

    virtual String toString() const override;

    virtual double evaluate(double fraction, double) const override;
    virtual void range(double* minValue, double* maxValue) const override;
    virtual void partition(Vector<PartitionRegion>& regions) const override;

    int numberOfSteps() const { return m_steps; }
    StepAtPosition stepAtPosition() const { return m_stepAtPosition; }

private:
    StepsTimingFunction(int steps, StepAtPosition stepAtPosition)
        : TimingFunction(StepsFunction)
        , m_steps(steps)
        , m_stepAtPosition(stepAtPosition)
    {
    }

    int m_steps;
    StepAtPosition m_stepAtPosition;
};

PLATFORM_EXPORT bool operator==(const LinearTimingFunction&, const TimingFunction&);
PLATFORM_EXPORT bool operator==(const CubicBezierTimingFunction&, const TimingFunction&);
PLATFORM_EXPORT bool operator==(const StepsTimingFunction&, const TimingFunction&);

PLATFORM_EXPORT bool operator==(const TimingFunction&, const TimingFunction&);
PLATFORM_EXPORT bool operator!=(const TimingFunction&, const TimingFunction&);

#define DEFINE_TIMING_FUNCTION_TYPE_CASTS(typeName) \
    DEFINE_TYPE_CASTS( \
        typeName##TimingFunction, TimingFunction, value, \
        value->type() == TimingFunction::typeName##Function, \
        value.type() == TimingFunction::typeName##Function)

DEFINE_TIMING_FUNCTION_TYPE_CASTS(Linear);
DEFINE_TIMING_FUNCTION_TYPE_CASTS(CubicBezier);
DEFINE_TIMING_FUNCTION_TYPE_CASTS(Steps);

} // namespace blink

#endif // TimingFunction_h


text:
<?php

namespace Sberbank\Entity;

class OrderBundle extends AbstractEntity
{
    protected string $orderCreationDate = '';

    protected ?array $customerDetails = null;

    protected array $cartItems = [];

    /**
     * @return mixed
     */
    public function getOrderCreationDate()
    {
        return $this->orderCreationDate;
    }

    /**
     * @param mixed $orderCreationDate
     * @return OrderBundle
     */
    public function setOrderCreationDate($orderCreationDate): OrderBundle
    {
        $this->orderCreationDate = $orderCreationDate;
        return $this;
    }

    /**
     * @return array
     */
    public function getCustomerDetails(): array
    {
        return $this->customerDetails;
    }

    /**
     * @param mixed $customerDetails
     * @return OrderBundle
     */
    public function setCustomerDetails(array $customerDetails): OrderBundle
    {
        $this->customerDetails = $customerDetails;
        return $this;
    }

    /**
     * @return array
     */
    public function getCartItems(): array
    {
        return $this->cartItems;
    }

    /**
     * @param Item[]|array $cartItems
     * @return OrderBundle
     */
    public function setCartItems(array $cartItems): OrderBundle
    {
        foreach ($cartItems as $cartItem) {
            if ($cartItem instanceof AbstractEntity) {
                $this->cartItems['items'][] = $cartItem->toArray();
            } else {
                $this->cartItems['items'][] = $cartItem;
            }
        }

        return $this;
    }

}