text:
Bindings for [OpenVR](https://github.com/ValveSoftware/openvr) and the [Valve/HTC Vive](http://store.steampowered.com/universe/vr)

These are preliminary but working quite smoothly.

See https://github.com/lukexi/openvr-hs/blob/master/app/Main.hs for basic example usage.

The example has optional hooks for [Halive](https://github.com/lukexi/halive) so you can make live edits to your code.

You'll need a few dependencies until I release the bindings on Hackage:
```
git clone --recursive git@github.com:lukexi/openvr-hs.git
git clone git@github.com:lukexi/glfw-pal.git
git clone git@github.com:lukexi/gl-pal.git
git clone git@github.com:lukexi/linear-extra.git
git clone git@github.com:lukexi/lens-extra.git
git clone git@github.com:lukexi/halive.git
```

Run the demo with `stack test :cubes` or `cabal test cubes`.

The build system expects a 64bit [MSYS2](https://msys2.github.io) installation.

You must use GHC 7.10.3 or greater.

Feel free to contact me via the issues tab or [@lukexi](http://twitter.com/lukexi) if you need any help getting set up.


text:
from functools import partial

from django.contrib.admin.sites import AdminSite
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.test import TestCase
from mock import patch

from opendebates.admin import SubmissionAdmin
from opendebates.models import Submission
from opendebates.tests.factories import SubmissionFactory, UserFactory, DebateFactory

# Force the reverse() used here in the tests to always use the full
# urlconf, despite whatever machinations have taken place due to the
# DebateMiddleware.
old_reverse = reverse
reverse = partial(old_reverse, urlconf='opendebates.urls')

# mock objects to make the admin think we're superusers.
# mostly copied from
# https://github.com/django/django/blob/master/tests/modeladmin/tests.py#L23-L32

class MockRequest(object):
    POST = {}
    META = {}
    scheme = 'http'

class MockSuperUser(object):
    def has_perm(self, perm):
        return True

    def is_authenticated(self):
        return True

class RemoveSubmissionsTest(TestCase):
    def setUp(self):
        self.site = AdminSite()
        self.admin = SubmissionAdmin(Submission, self.site)
        self.password = 'secretpassword'
        self.user = UserFactory(password=self.password, is_staff=True, is_superuser=True)
        assert self.client.login(username=self.user.username, password=self.password)
        self.submission = SubmissionFactory()
        self.queryset = Submission.objects.all()
        self.changelist_url = reverse('admin:opendebates_submission_changelist')

    def tearDown(self):
        Site.objects.clear_cache()

    def test_get(self):
        """
        GETting the intermediate page should have specified text and the PK of
        the chosen submissions.
        """
        request = MockRequest()
        request.user = MockSuperUser()
        request.debate = DebateFactory()

        rsp = self.admin.remove_submissions(request, self.queryset)
        self.assertEqual(rsp.status_code, 200)
        self.assertContains(rsp, 'remove the selected submissions?')
        self.assertContains(rsp, self.submission.pk)

    @patch('opendebates.admin.send_email')
    def test_post(self, mock_send_email):
        """
        POSTing the form should cause submissions to be removed and email to be
        sent.
        """
        data = {
            'post': 'Yes',
            'action': 'remove_submissions',
            '_selected_action': [self.submission.pk, ]
        }
        rsp = self.client.post(self.changelist_url, data=data)
        self.assertRedirects(rsp, self.changelist_url)
        # Now submission should not be approved
        submission = Submission.objects.get()
        self.assertFalse(submission.approved)
        # and 1 email should have been sent
        self.assertEqual(mock_send_email.call_count, 1)

        submission = Submission.objects.get(id=self.submission.pk)
        self.assertIsNotNone(submission.moderated_at)

    @patch('opendebates.admin.send_email')
    def test_post_multiple(self, mock_send_email):
        "POSTing multiple submissions works as well."
        data = {
            'post': 'Yes',
            'action': 'remove_submissions',
            '_selected_action': [SubmissionFactory().pk, SubmissionFactory().pk]
        }
        rsp = self.client.post(self.changelist_url, data=data)
        self.assertRedirects(rsp, self.changelist_url)
        removed_submissions = Submission.objects.filter(approved=False)
        self.assertEqual(removed_submissions.count(), 2)
        sub1, sub2 = removed_submissions
        self.assertIsNotNone(sub1.moderated_at)
        self.assertIsNotNone(sub2.moderated_at)
        untouched_submission = Submission.objects.filter(approved=True)
        self.assertEqual(untouched_submission.count(), 1)
        # and 2 emails have been sent
        self.assertEqual(mock_send_email.call_count, 2)

    @patch('opendebates.admin.send_email')
    def test_dont_send_email_if_already_unapproved(self, mock_send_email):
        "If submission was already unapproved, don't bug the user again."
        data = {
            'post': 'Yes',
            'action': 'remove_submissions',
            '_selected_action': [SubmissionFactory(approved=False).pk]
        }
        rsp = self.client.post(self.changelist_url, data=data)
        self.assertRedirects(rsp, self.changelist_url)
        removed_submissions = Submission.objects.filter(approved=False)
        self.assertEqual(removed_submissions.count(), 1)
        # and ZERO emails have been sent
        self.assertEqual(mock_send_email.call_count, 0)

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe AOP do
  context 'param filter aspects with module concerns' do
    let( :mod1 ){ aop_module{
      def a1 a; a.succ end
      def b1 b; 2*b end
    } }

    let( :mod2 ){ aop_module{
      def b3 b; 3*b end
    }}

    before do
      mod2.send :include, mod1
      class_under_test.send :include, mod2
      class_under_test.new_method :x do |a| a end
    end

    context 'using the simplest module as concern' do
      before do
        class_under_test.param_filter mod1 do |*args|
          args.first.succ
        end
      end
      it 'filters the module\'s method' do
        expect( subject.a1 0 ).to eq 2
      end
      it 'but the other module\'s one not so much' do
        expect( subject.b3 1 ).to eq 3
      end
    end # context 'using the simplest module as concern'

    context 'using the complex module as concern' do
      before do
        class_under_test.param_filter mod2 do |*args|
          args.first.succ
        end
      end
      it 'filters the module\'s method' do
        expect( subject.b3 0 ).to eq 3
      end
      it 'but the sub module\'s one not so much' do
        expect( subject.a1 0 ).to eq 1
      end
    end # context 'using the complex module as concern'

    context 'using the complex module as concern (with include included)' do
      shared_examples_for 'including included' do
        it 'filters the module\'s method' do
          expect( subject.b3 0 ).to eq 3
        end
        it 'and the sub module\'s one too' do
          expect( subject.a1 0 ).to eq 2
        end
      end

      context 'method' do
        before do
          class_under_test.new_method :filter do |*a|
            a.first.succ
          end
          class_under_test.param_filter mod2, :filter, include_included: true
        end
        it_behaves_like 'including included'
      end # context 'method'
      context 'block' do
        before do
          class_under_test.param_filter mod2, include_included: true do |*a|
            a.first.succ
          end
        end
        it_behaves_like 'including included'
      end # context 'method'
    end

  end # context 'param filter aspects with module concerns'
end # describe AOP


text:
chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.create({ url: chrome.extension.getURL("index.html") });
});


text:
/*
 * 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.
 */
package org.kitei.guice.robotlegs;

import com.google.inject.Inject;

public class ImmutableFoo implements Foo
{
    private final String value;

    @Inject
    public ImmutableFoo(final String value)
    {
        this.value = value;
    }

    public String getValue()
    {
        return value;
    }
}


text:
package br.com.objectos.way.relational;

import com.google.inject.ImplementedBy;

/**
 * @author marcio.endo@objectos.com.br (Marcio Endo)
 */
@ImplementedBy(ListInsertableExecGuice.class)
interface ListInsertableExec {

  void execute(AbstractListInsertable insertable);

}


text:
import test from 'ava';
import queryString from '..';

test('stringify', t => {
	t.is(queryString.stringify({foo: 'bar'}), 'foo=bar');
	t.is(queryString.stringify({
		foo: 'bar',
		bar: 'baz'
	}), 'bar=baz&foo=bar');
});

test('different types', t => {
	t.is(queryString.stringify(), '');
	t.is(queryString.stringify(0), '');
});

test('URI encode', t => {
	t.is(queryString.stringify({'foo bar': 'baz faz'}), 'foo%20bar=baz%20faz');
	t.is(queryString.stringify({'foo bar': 'baz\'faz'}), 'foo%20bar=baz%27faz');
});

test('no encoding', t => {
	t.is(queryString.stringify({'foo:bar': 'baz:faz'}, {encode: false}), 'foo:bar=baz:faz');
});

test('handle array value', t => {
	t.is(queryString.stringify({
		abc: 'abc',
		foo: ['bar', 'baz']
	}), 'abc=abc&foo=bar&foo=baz');
});

test('array order', t => {
	t.is(queryString.stringify({
		abc: 'abc',
		foo: ['baz', 'bar']
	}), 'abc=abc&foo=baz&foo=bar');
});

test('handle empty array value', t => {
	t.is(queryString.stringify({
		abc: 'abc',
		foo: []
	}), 'abc=abc');
});

test('should not encode undefined values', t => {
	t.is(queryString.stringify({
		abc: undefined,
		foo: 'baz'
	}), 'foo=baz');
});

test('should encode null values as just a key', t => {
	t.is(queryString.stringify({
		'x y z': null,
		abc: null,
		foo: 'baz'
	}), 'abc&foo=baz&x%20y%20z');
});

test('handle null values in array', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: [null, 'baz']
	}), 'bar&bar=baz&foo');
});

test('handle undefined values in array', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: [undefined, 'baz']
	}), 'bar=baz&foo');
});

test('handle undefined and null values in array', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: [undefined, null, 'baz']
	}), 'bar&bar=baz&foo');
});

test('strict encoding', t => {
	t.is(queryString.stringify({foo: '\'bar\''}), 'foo=%27bar%27');
	t.is(queryString.stringify({foo: ['\'bar\'', '!baz']}), 'foo=%27bar%27&foo=%21baz');
});

test('loose encoding', t => {
	t.is(queryString.stringify({foo: '\'bar\''}, {strict: false}), 'foo=\'bar\'');
	t.is(queryString.stringify({foo: ['\'bar\'', '!baz']}, {strict: false}), 'foo=\'bar\'&foo=!baz');
});

test('array stringify representation with array indexes', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', 'two']
	}, {
		arrayFormat: 'index'
	}), 'bar[0]=one&bar[1]=two&foo');
});

test('array stringify representation with array brackets', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', 'two']
	}, {
		arrayFormat: 'bracket'
	}), 'bar[]=one&bar[]=two&foo');
});

test('array stringify representation with array brackets and null value', t => {
	t.is(queryString.stringify({
		foo: ['a', null, ''],
		bar: [null]
	}, {
		arrayFormat: 'bracket'
	}), 'bar[]&foo[]=a&foo[]&foo[]=');
});

test('array stringify representation with array commas', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', 'two']
	}, {
		arrayFormat: 'comma'
	}), 'bar=one,two&foo');
});

test('array stringify representation with array commas, null & empty string', t => {
	t.is(queryString.stringify({
		c: [null, 'a', '', null],
		b: [null],
		a: ['']
	}, {
		arrayFormat: 'comma'
	}), 'a=&b=&c=,a,,');
});

test('array stringify representation with array commas, null & empty string (skip both)', t => {
	t.is(queryString.stringify({
		c: [null, 'a', '', null],
		b: [null],
		a: ['']
	}, {
		skipNull: true,
		skipEmptyString: true,
		arrayFormat: 'comma'
	}), 'c=a');
});

test('array stringify representation with array commas and 0 value', t => {
	t.is(queryString.stringify({
		foo: ['a', null, 0],
		bar: [null]
	}, {
		arrayFormat: 'comma'
	}), 'bar=&foo=a,,0');
});

test('array stringify representation with a bad array format', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', 'two']
	}, {
		arrayFormat: 'badinput'
	}), 'bar=one&bar=two&foo');
});

test('array stringify representation with array indexes and sparse array', t => {
	const fixture = ['one', 'two'];
	fixture[10] = 'three';
	t.is(queryString.stringify({bar: fixture}, {arrayFormat: 'index'}), 'bar[0]=one&bar[1]=two&bar[2]=three');
});

test('array stringify representation with brackets and separators with empty array', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: []
	}, {
		arrayFormat: 'bracket-separator'
	}), 'bar[]&foo');
});

test('array stringify representation with brackets and separators with single value', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one']
	}, {
		arrayFormat: 'bracket-separator'
	}), 'bar[]=one&foo');
});

test('array stringify representation with brackets and separators with multiple values', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', 'two', 'three']
	}, {
		arrayFormat: 'bracket-separator'
	}), 'bar[]=one,two,three&foo');
});

test('array stringify representation with brackets and separators with a single empty string', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['']
	}, {
		arrayFormat: 'bracket-separator'
	}), 'bar[]=&foo');
});

test('array stringify representation with brackets and separators with a multiple empty string', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['', 'two', '']
	}, {
		arrayFormat: 'bracket-separator'
	}), 'bar[]=,two,&foo');
});

test('array stringify representation with brackets and separators with dropped empty strings', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['', 'two', '']
	}, {
		arrayFormat: 'bracket-separator',
		skipEmptyString: true
	}), 'bar[]=two&foo');
});

test('array stringify representation with brackets and separators with dropped null values', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', null, 'three', null, '', 'six']
	}, {
		arrayFormat: 'bracket-separator',
		skipNull: true
	}), 'bar[]=one,three,,six');
});

test('should sort keys in given order', t => {
	const fixture = ['c', 'a', 'b'];
	const sort = (key1, key2) => fixture.indexOf(key1) - fixture.indexOf(key2);

	t.is(queryString.stringify({a: 'foo', b: 'bar', c: 'baz'}, {sort}), 'c=baz&a=foo&b=bar');
});

test('should not sort when sort is false', t => {
	const fixture = {
		story: 'a',
		patch: 'b',
		deployment: 'c',
		lat: 10,
		lng: 20,
		sb: 'd',
		sc: 'e',
		mn: 'f',
		ln: 'g',
		nf: 'h',
		srs: 'i',
		destination: 'g'
	};
	t.is(queryString.stringify(fixture, {sort: false}), 'story=a&patch=b&deployment=c&lat=10&lng=20&sb=d&sc=e&mn=f&ln=g&nf=h&srs=i&destination=g');
});

test('should disable sorting', t => {
	t.is(queryString.stringify({
		c: 'foo',
		b: 'bar',
		a: 'baz'
	}, {
		sort: false
	}), 'c=foo&b=bar&a=baz');
});

test('should ignore null when skipNull is set', t => {
	t.is(queryString.stringify({
		a: 1,
		b: null,
		c: 3
	}, {
		skipNull: true
	}), 'a=1&c=3');
});

test('should ignore emptyString when skipEmptyString is set', t => {
	t.is(queryString.stringify({
		a: 1,
		b: '',
		c: 3
	}, {
		skipEmptyString: true
	}), 'a=1&c=3');
});

test('should ignore undefined when skipNull is set', t => {
	t.is(queryString.stringify({
		a: 1,
		b: undefined,
		c: 3
	}, {
		skipNull: true
	}), 'a=1&c=3');
});

test('should ignore both null and undefined when skipNull is set', t => {
	t.is(queryString.stringify({
		a: undefined,
		b: null
	}, {
		skipNull: true
	}), '');
});

test('should ignore both null and undefined when skipNull is set for arrayFormat', t => {
	t.is(queryString.stringify({
		a: [undefined, null, 1, undefined, 2, null],
		b: null,
		c: 1
	}, {
		skipNull: true
	}), 'a=1&a=2&c=1');

	t.is(queryString.stringify({
		a: [undefined, null, 1, undefined, 2, null],
		b: null,
		c: 1
	}, {
		skipNull: true,
		arrayFormat: 'bracket'
	}), 'a[]=1&a[]=2&c=1');

	t.is(queryString.stringify({
		a: [undefined, null, 1, undefined, 2, null],
		b: null,
		c: 1
	}, {
		skipNull: true,
		arrayFormat: 'comma'
	}), 'a=1,2&c=1');

	t.is(queryString.stringify({
		a: [undefined, null, 1, undefined, 2, null],
		b: null,
		c: 1
	}, {
		skipNull: true,
		arrayFormat: 'index'
	}), 'a[0]=1&a[1]=2&c=1');
});

test('should ignore empty string when skipEmptyString is set for arrayFormat', t => {
	t.is(queryString.stringify({
		a: ['', 1, '', 2],
		b: '',
		c: 1
	}, {
		skipEmptyString: true
	}), 'a=1&a=2&c=1');

	t.is(queryString.stringify({
		a: ['', 1, '', 2],
		b: '',
		c: 1
	}, {
		skipEmptyString: true,
		arrayFormat: 'bracket'
	}), 'a[]=1&a[]=2&c=1');

	t.is(queryString.stringify({
		a: ['', 1, '', 2],
		b: '',
		c: 1
	}, {
		skipEmptyString: true,
		arrayFormat: 'comma'
	}), 'a=1,2&c=1');

	t.is(queryString.stringify({
		a: ['', 1, '', 2],
		b: '',
		c: 1
	}, {
		skipEmptyString: true,
		arrayFormat: 'index'
	}), 'a[0]=1&a[1]=2&c=1');

	t.is(queryString.stringify({
		a: ['', '', '', ''],
		c: 1
	}, {
		skipEmptyString: true
	}), 'c=1');
});

test('stringify throws TypeError for invalid arrayFormatSeparator', t => {
	t.throws(_ => queryString.stringify({}, {arrayFormatSeparator: ',,'}), {
		instanceOf: TypeError
	});
	t.throws(_ => queryString.stringify({}, {arrayFormatSeparator: []}), {
		instanceOf: TypeError
	});
});

test('array stringify representation with (:list) colon-list-separator', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', 'two']
	}, {
		arrayFormat: 'colon-list-separator'
	}), 'bar:list=one&bar:list=two&foo');
});

test('array stringify representation with (:list) colon-list-separator with null values', t => {
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', '']
	}, {
		arrayFormat: 'colon-list-separator'
	}), 'bar:list=one&bar:list=&foo');
	t.is(queryString.stringify({
		foo: null,
		bar: ['one', null]
	}, {
		arrayFormat: 'colon-list-separator'
	}), 'bar:list=one&bar:list=&foo');
});


text:
<?php

namespace Torchbox\Thankq\Api;

class doPledgeSearchResponse
{

    /**
     * @var esitWSdoPledgeSearchResult $doPledgeSearchResult
     */
    protected $doPledgeSearchResult = null;

    /**
     * @param esitWSdoPledgeSearchResult $doPledgeSearchResult
     */
    public function __construct($doPledgeSearchResult)
    {
      $this->doPledgeSearchResult = $doPledgeSearchResult;
    }

    /**
     * @return esitWSdoPledgeSearchResult
     */
    public function getDoPledgeSearchResult()
    {
      return $this->doPledgeSearchResult;
    }

    /**
     * @param esitWSdoPledgeSearchResult $doPledgeSearchResult
     * @return \Torchbox\Thankq\Api\doPledgeSearchResponse
     */
    public function setDoPledgeSearchResult($doPledgeSearchResult)
    {
      $this->doPledgeSearchResult = $doPledgeSearchResult;
      return $this;
    }

}


text:
THEME=$1
CMD=$2

CONFIG=data/$THEME.config.toml

echo "Theme is $THEME"

if [[ $CMD == "new" ]]; then
	echo -n -e "input category directory name\n>> "
	read dirname
	echo -n -e "input post name\n>> "
	read postname
	hugo --config $CONFIG new $dirname/$postname.md
	exit $?
fi


text:
'use strict';

/* jshint -W030 */
/* jshint -W110 */
var chai = require('chai')
  , expect = chai.expect
  , Utils = require(__dirname + '/../../lib/utils')
  , Support = require(__dirname + '/support');

describe(Support.getTestDialectTeaser('Utils'), function() {
  describe('removeCommentsFromFunctionString', function() {
    it('removes line comments at the start of a line', function() {
      var functionWithLineComments = function() {
        // noot noot
      };

      var string = functionWithLineComments.toString()
        , result = Utils.removeCommentsFromFunctionString(string);

      expect(result).not.to.match(/.*noot.*/);
    });

    it('removes lines comments in the middle of a line', function() {
      var functionWithLineComments = function() {
        alert(1); // noot noot
      };

      var string = functionWithLineComments.toString()
        , result = Utils.removeCommentsFromFunctionString(string);

      expect(result).not.to.match(/.*noot.*/);
    });

    it('removes range comments', function() {
      var s = function() {
        alert(1); /*
          noot noot
        */
        alert(2); /*
          foo
        */
      }.toString();

      var result = Utils.removeCommentsFromFunctionString(s);

      expect(result).not.to.match(/.*noot.*/);
      expect(result).not.to.match(/.*foo.*/);
      expect(result).to.match(/.*alert\(2\).*/);
    });
  });

  describe('argsArePrimaryKeys', function() {
    it('doesn\'t detect primary keys if primareyKeys and values have different lengths', function() {
      expect(Utils.argsArePrimaryKeys([1, 2, 3], [1])).to.be.false;
    });

    it('doesn\'t detect primary keys if primary keys are hashes or arrays', function() {
      expect(Utils.argsArePrimaryKeys([[]], [1])).to.be.false;
    });

    it('detects primary keys if length is correct and data types are matching', function() {
      expect(Utils.argsArePrimaryKeys([1, 2, 3], ['INTEGER', 'INTEGER', 'INTEGER'])).to.be.true;
    });

    it('detects primary keys if primary keys are dates and lengths are matching', function() {
      expect(Utils.argsArePrimaryKeys([new Date()], ['foo'])).to.be.true;
    });
  });

  describe('underscore', function() {
    describe('underscoredIf', function() {
      it('is defined', function() {
        expect(Utils.underscoredIf).to.be.ok;
      });

      it('underscores if second param is true', function() {
        expect(Utils.underscoredIf('fooBar', true)).to.equal('foo_bar');
      });

      it('doesn\'t underscore if second param is false', function() {
        expect(Utils.underscoredIf('fooBar', false)).to.equal('fooBar');
      });
    });

    describe('camelizeIf', function() {
      it('is defined', function() {
        expect(Utils.camelizeIf).to.be.ok;
      });

      it('camelizes if second param is true', function() {
        expect(Utils.camelizeIf('foo_bar', true)).to.equal('fooBar');
      });

      it('doesn\'t camelize if second param is false', function() {
        expect(Utils.underscoredIf('fooBar', true)).to.equal('foo_bar');
      });
    });
  });

  describe('format', function() {
    it('should format where clause correctly when the value is truthy', function() {
      var where = ['foo = ?', 1];
      expect(Utils.format(where)).to.equal('foo = 1');
    });

    it('should format where clause correctly when the value is false', function() {
      var where = ['foo = ?', 0];
      expect(Utils.format(where)).to.equal('foo = 0');
    });
  });

  describe('cloneDeep', function() {
    it('should clone objects', function() {
      var obj = {foo: 1}
        , clone = Utils.cloneDeep(obj);

      expect(obj).to.not.equal(clone);
    });

    it('should clone nested objects', function() {
      var obj = {foo: {bar: 1}}
        , clone = Utils.cloneDeep(obj);

      expect(obj.foo).to.not.equal(clone.foo);
    });

    it('should not call clone methods on plain objects', function() {
      expect(function() {
        Utils.cloneDeep({
          clone: function() {
            throw new Error('clone method called');
          }
        });
      }).to.not.throw();
    });

    it('should not call clone methods on arrays', function() {
      expect(function() {
        var arr = [];
        arr.clone = function() {
          throw new Error('clone method called');
        };

        Utils.cloneDeep(arr);
      }).to.not.throw();
    });
  });

  describe('validateParameter', function() {
    describe('method signature', function() {
      it('throws an error if the value is not defined', function() {
        expect(function() {
          Utils.validateParameter();
        }).to.throw('No value has been passed.');
      });

      it('does not throw an error if the value is not defined and the parameter is optional', function() {
        expect(function() {
          Utils.validateParameter(undefined, Object, { optional: true });
        }).to.not.throw();
      });

      it('throws an error if the expectation is not defined', function() {
        expect(function() {
          Utils.validateParameter(1);
        }).to.throw('No expectation has been passed.');
      });
    });

    describe('expectation', function() {
      it('uses the instanceof method if the expectation is a class', function() {
        expect(Utils.validateParameter(new Number(1), Number)).to.be.true; // jshint ignore:line
      });
    });

    describe('failing expectations', function() {
      it('throws an error if the expectation does not match', function() {
        expect(function() {
          Utils.validateParameter(1, String);
        }).to.throw(/The parameter.*is no.*/);
      });
    });
  });

  if (Support.getTestDialect() === 'postgres') {
    describe('json', function() {
      var queryGenerator = require('../../lib/dialects/postgres/query-generator.js');

      it('successfully parses a complex nested condition hash', function() {
        var conditions = {
          metadata: {
            language: 'icelandic',
            pg_rating: { 'dk': 'G' }
          },
          another_json_field: { x: 1 }
        };
        var expected = "metadata#>>'{language}' = 'icelandic' and metadata#>>'{pg_rating,dk}' = 'G' and another_json_field#>>'{x}' = '1'";
        expect(queryGenerator.handleSequelizeMethod(new Utils.Json(conditions))).to.deep.equal(expected);
      });

      it('successfully parses a string using dot notation', function() {
        var path = 'metadata.pg_rating.dk';
        expect(queryGenerator.handleSequelizeMethod(new Utils.Json(path))).to.equal("metadata#>>'{pg_rating,dk}'");
      });

      it('allows postgres json syntax', function() {
        var path = 'metadata->pg_rating->>dk';
        expect(queryGenerator.handleSequelizeMethod(new Utils.Json(path))).to.equal(path);
      });

      it('can take a value to compare against', function() {
        var path = 'metadata.pg_rating.is';
        var value = 'U';
        expect(queryGenerator.handleSequelizeMethod(new Utils.Json(path, value))).to.equal("metadata#>>'{pg_rating,is}' = 'U'");
      });
    });
  }

  describe('inflection', function() {
    it('works better than lingo ;)', function() {
      expect(Utils.pluralize('buy')).to.equal('buys');
      expect(Utils.pluralize('holiday')).to.equal('holidays');
      expect(Utils.pluralize('days')).to.equal('days');
      expect(Utils.pluralize('status')).to.equal('statuses');

      expect(Utils.singularize('status')).to.equal('status');
    });
  });
});


text:
package org.peerbox.events;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import net.engio.mbassy.listener.Handler;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class MessageBusTest {

	private MessageBus messageBus;

	@Before
	public void setUp() throws Exception {
		messageBus = new MessageBus();
	}

	@After
	public void tearDown() throws Exception {
		if (messageBus != null) {
			messageBus.shutdown();
			messageBus = null;
		}
	}

	@Test
	public void testMessageBus() {
		TestListener listener = new TestListener();
		messageBus.subscribe(listener);

		assertFalse(listener.messageReceived);
		messageBus.publish(new TestMessage());
		assertTrue(listener.messageReceived);
	}

	private class TestMessage implements IMessage {

	}

	private class TestListener {
		boolean messageReceived = false;

		@Handler
		private void testMessageHandler(TestMessage msg) {
			messageReceived = true;
		}
	}

}


text:
$(function() {
    generateNav2("#nav", window.navRoot);
    generateNav2("#m-nav", window.navRoot);
    activeNav("#nav");
    activeNav("#m-nav");
    console.log(window.navRoot);

    $(".accordion li a").on("click",function() {
        var $this = $(this);
        expandNav($(this));
    });

    var $mobMenu                = $('#m-nav'),
        $toc                 = $("#toc"),
        $tocSticky           = $('.nav .ui.sticky'),
        $fullHeightContainer = $('.pusher > .full.height');

    // create sidebar sticky
    $tocSticky.sticky({
        silent: true,
        context: $fullHeightContainer
    });

    // launch buttons
    $mobMenu.sidebar('attach events', '.launch.button, .view-ui, .launch.item');

    function expandNav($this) {
        var $targetContent = $($this.parent().find(" > ul"));
        $this.toggleClass("expaned");
        $this.find("i.icon.angle").toggleClass("right");
        $this.find("i.icon.angle").toggleClass("down");
        $targetContent.slideToggle("fast");
    }

    function activeNav(id) {
        var path = location.pathname;
        console.log(path);

        $(id).find("a").each(function (idx, item) {
            console.log($(this).attr("href"));
            if ($(this).attr("href") === path) {
                $(this).addClass("active");
                var parentULs = $(this).parents('ul.sub');
                var parentLi = $(this).parent();
                var parentLis = parentLi.parents('li');
                parentLis.each(function(){
                    // $(this).trigger('click');
                    var $this = $(this).find('>a');
                    expandNav($this);
                });

            } else {
                $(this).removeClass("active");
            }
        });

    }

    function generateNav2(id, root) {
        if (root == null) {
            return;
        }
        var rootItem = $("
")
            .append(
                $("").addClass("title").attr("href", "/").append(
                    $("").addClass("ui logo icon image")
                        .append(
                            $("").attr("src", "/assets/images/z.jpg")
                        )
                ).append(
                    $("").text("Tung Docs")
                )
            );

        var rootCategory = $("
").append($("").addClass("title").attr("href", '/category/' + root.id)
            .append(
                $("").text(root.name)
            ));
        var wrp = $(id).append(rootItem).append(rootCategory).append(generateSubNavs2(root.subNavs, "1."));
        // $(id).append(wrp);
    }

    function generateSubNavs2(nodeList, taxis) {
        var result = [];
        var reg = /(\d+)\.$/;
        taxis=taxis+"";

        for (var k in nodeList) {
            var node = nodeList[k];
            // if (node.subNavs.length == 0) {
            if (node.type == 'LINK') {
                result.push(generateNavAItem2(node, taxis));
            } else {
                result.push(generateNavGroupItem2(node, taxis, taxis));
            }

            var matchs = taxis.match(reg);
            var newTaxNum = 1 + matchs[1]*1;
            taxis = taxis.replace(reg , newTaxNum+".");
        }
        return result;
    }

    function generateNavAItem2(node, taxis) {
        var li = $("
").append($("").attr("href", '/category/' + navRoot.id + '/article/' + node.id).addClass("title").attr("data-id", node.id).html(
            taxis + " " + node.name
        ));
        return li;

    }

    function generateNavGroupItem2(node, taxis) {
        var li = $("
").append($("").addClass("title").attr("data-id", node.id).html(
            "" + taxis + " " + node.name + ''
        )).append(
            $("
").addClass("sub").append(
                generateSubNavs2(node.subNavs, taxis+"1.")
            )
        );

        return li;
    }

});


text:
/* FILE: objtree.c */

/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/
/*                                                                        */
/*          Obect Tree Traversal Routines for the Cutplaen Editariat      */
/*                                                                        */
/* Author: WAK/LJE                                   Date: October 22,1990*/
/*                                                                        */
/* Copyright (C) 1988,1989,1990,1991 William Kessler and Laurence Edwards.*/
/* All Rights Reserved.                                                   */
/*                                                                        */
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/

#define OBJTREEMODULE

#include <config.h>

#include <platform_gl.h>

#include <cutplane.h>
#include <update.h>

/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/
/*                 Object tree manipulation Routines                      */
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/

  void
reset_motherworld_ptr(objptr reset_obj, worldptr new_world)
{
  reset_obj->motherworld = new_world;
}

  void
transfer_moved_obj_props(worldptr oldworld, worldptr neworld)
{	/* go through proplists in new world and look for objs in old world */
  listptr oldproplist,newproplist;
  objptr containingobj;
  proptr thisprop,nextprop;
  int i;
  ;
  for (i=0; i < next_available_property; i++)
  {
    oldproplist = oldworld->world_proplists[i];
    newproplist = neworld->world_proplists[i];
    thisprop = oldproplist->first.prop;
    while (thisprop != Nil)
    {
      nextprop = thisprop->next;
      containingobj = (objptr) find_largergrain(thisprop->owner,Obj_type);
      if (containingobj->motherworld == neworld)
      {			/* move properties instances to childs world */
	rem_elem(oldproplist,(elemptr) thisprop);
	append_elem(newproplist, (elemptr) thisprop);
      }
      thisprop = nextprop;	/* can't just do thisprop=thisprop->next */
				/* because thisprop is now at the end of*/
    }				/* the neworld proplist so the next==Nil!! */
  }
}

  void
insert_parent(objptr child, objptr newparent)
{				/* insert an object as a parent above child */
  objptr oldparent;
  worldptr oldworld;
  ;
  if (newparent->motherworld != child->motherworld)
  {
    oldworld = newparent->motherworld;
    if (newparent->children->numelems == 0)
      newparent->motherworld = child->motherworld;
    else
      apply_to_descendants(newparent,reset_motherworld_ptr,child->motherworld);
    transfer_moved_obj_props(oldworld,child->motherworld);
  }
  oldparent = child->parent;
  if (oldparent == Nil)		/* child is root */
  {
    child->motherworld->root = newparent;
    newparent->parent = Nil;
  }
  else
  {
    append_elem(oldparent->children, (elemptr) newparent);
    rem_elem(oldparent->children, (elemptr) child);
    newparent->parent = oldparent->parent;
  }
  append_elem(newparent->children, (elemptr) child);
  child->parent = newparent;
}

  void
add_child(objptr parent, objptr newchild)
{				/* add an object as a child below parent */
  worldptr oldworld;
  ;
  if (newchild->motherworld != parent->motherworld)
  {
    oldworld = newchild->motherworld;
    if (newchild->children->numelems == 0)
      newchild->motherworld = parent->motherworld;
    else
      apply_to_descendants(newchild,reset_motherworld_ptr,parent->motherworld);
    transfer_moved_obj_props(oldworld,parent->motherworld);
  }
  append_elem(parent->children,(elemptr) newchild);
  newchild->parent = parent;
}

  void
swap_child_with_parent(objptr child)
{
  objptr parent,thischild;
  listptr temp;
  ;
  parent = child->parent;
  temp = child->children;
  child->children = parent->children;
  parent->children = temp;

  child->parent = parent->parent;
  parent->parent = child;
  /* remove child from parent children and put in parent->parent children */
  /* also remove parent from parent->parent children and put in child children */
  rem_elem(parent->children, (elemptr) child);
  append_elem(child->parent->children, (elemptr) child);
  rem_elem(child->parent->children, (elemptr) parent);
  append_elem(child->children, (elemptr) parent);
  /* make sure childs children and parents children point to their new parents */
  thischild = child->children->first.obj;
  while (thischild)
  {
    thischild->parent = child;
    thischild = thischild->next;
  }
  thischild = parent->children->first.obj;
  while (thischild)
  {
    thischild->parent = parent;
    thischild = thischild->next;
  }
}

/* Removes a single obj from the tree, returning the object that was */
/* removed. Attaches the children to the parent of the removed object. */

  objptr
remove_obj(objptr removed_obj)
{
  objptr parent_of_removed,thisobj;
  ;
  if (removed_obj->parent == Nil)	/* this is a root */
    parent_of_removed = make_parentobj_noshell(removed_obj);
  else
    parent_of_removed = removed_obj->parent;
  rem_elem(parent_of_removed->children,(elemptr) removed_obj);
  thisobj = removed_obj->children->first.obj;
  while (thisobj)
  {
    thisobj->parent = parent_of_removed;
    thisobj = thisobj->next;
  }
  transfer_list_contents(removed_obj->children,parent_of_removed->children);
  removed_obj->linked = FALSE;

  return(removed_obj);
}

/* Removes an obj from the tree, returning the object that was removed. */
/* Does not attach the children to the removed object's parent; thus it */
/* removes an entire branch of the tree. */

  objptr
remove_obj_branch(objptr removed_obj)
{
  objptr parent_of_removed;
  ;
  if (removed_obj->parent == Nil)	/* this is a root */
    parent_of_removed = make_parentobj_noshell(removed_obj);
  else
    parent_of_removed = removed_obj->parent;

  rem_elem(parent_of_removed->children,(elemptr) removed_obj);
  removed_obj->linked = FALSE;

  return(removed_obj);
}

  void
adopt_obj_branch(objptr master,objptr slave,Boolean linked)
{
  remove_obj_branch(slave);
  add_child(master,slave);
  slave->linked = linked;
}

  void
adopt_obj(objptr master,objptr slave,Boolean linked)
{
  remove_obj(slave);
  add_child(master,slave);
  slave->linked = linked;
}

/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*			Object Utility Routines                   	*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  void
get_obj_shells(objptr this_obj,listptr cull_list)
{
  shellptr thishell;
  ;
  thishell = First_obj_shell(this_obj);
  while (thishell != Nil)
  {
    add_to_featurelist(cull_list, (featureptr) thishell);
    thishell = thishell->next;
  }
}

/* Recursive routine that walks down the object tree from the given */
/* feature's object, getting subfeatures as it goes. The recursion */
/* is postorder (root last). */

  void
get_descendents(objptr this_obj,objptr mother_obj,
		listptr cull_list)
{
  objptr recurse_obj;
  shellptr thishell;
  ;
  /* First, recurse on the children of this object.  */
  recurse_obj = this_obj->children->first.obj;
  if (recurse_obj != Nil)	/* don't descend if at a leaf */
    do
    {
      get_descendents(recurse_obj,mother_obj,cull_list);
      recurse_obj = recurse_obj->next;
    } while (recurse_obj != Nil);

  if (this_obj == mother_obj)
    return;			/* don't store mother object too! */
  /* Now, add the shells for this object to the cull_list. */
  get_obj_shells(this_obj,cull_list);
}

  objptr
get_unlinked_ancestor(objptr thisobj)
{
  if (thisobj->linked)
    return(thisobj);
  return(get_unlinked_ancestor(thisobj->parent));
}

  void
apply_to_descendants(objptr thisobj,
		     void (*thefunction)(), void *function_data)
{
  objptr thischild;
  ;
  (*thefunction)(thisobj,function_data);
  thischild = thisobj->children->first.obj;
  while (thischild)	/* don't descend if at a leaf */
  {
    apply_to_descendants(thischild,thefunction,function_data);
    thischild = thischild->next;
  }
}

  void
apply_to_unlinked_descendants(objptr thisobj,
			      void (*thefunction)(), void *function_data)
{
  objptr thischild;
  ;
  (*thefunction)(thisobj,function_data);
  thischild = thisobj->children->first.obj;
  while (thischild)	/* don't descend if at a leaf or at a linked child */
  {
    if (thischild->linked == FALSE)
      apply_to_unlinked_descendants(thischild,thefunction,function_data);
    thischild = thischild->next;
  }
}

  void
apply_to_descendants_with_prop(objptr thisobj,property chosen_prop,
			       void (*thefunction)(), void *function_data)
{
  objptr thischild;
  ;
  (*thefunction)(thisobj,function_data);
  thischild = thisobj->children->first.obj;
  while (thischild)	/* don't descend if at a leaf or doesn't have this */
			/* property, e.g. visible. */
  {
    if (has_property((featureptr) thischild, chosen_prop))
      apply_to_descendants_with_prop(thischild,chosen_prop,thefunction,
				     function_data);
    thischild = thischild->next;
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Руслан
 * Date: 18.09.2016
 * Time: 20:35
 */

namespace maestroprog\tplmaster\interfaces;

use maestroprog\tplmaster\Block;

interface BlockEditor
{

    function addBlock(string $class, string $tag = 'div'): BlockEditor;

    function addElement(string $tag, string $class): ElementEditor;
}


text:
import React from "react";
import PropTypes from "prop-types";
import injectSheet from "react-jss";
import MenuItem from "@material-ui/core/MenuItem";
import MenuList from "@material-ui/core/MenuList";
import IconButton from "@material-ui/core/IconButton";
import { Manager, Target, Popper } from "react-popper";
import ClickAwayListener from "@material-ui/core/ClickAwayListener";
import Grow from "@material-ui/core/Grow";
import Paper from "@material-ui/core/Paper";
import classNames from "classnames";
import FilterListIcon from "@material-ui/icons/FilterList";

const styles = theme => ({
  fontSizeSetter: {
    [`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: {}
  },
  open: {
    color: theme.bars.colors.icon
  },
  popperClose: {
    pointerEvents: "none"
  },
  popper: {
    zIndex: 1
  }
});

class CategoryFilter extends React.Component {
  state = {
    open: false
  };

  componentWillUnmount() {
    clearTimeout(this.timeout);
  }

  handleClick = () => {
    this.setState({ open: !this.state.open });
  };

  handleClose = () => {
    if (!this.state.open) {
      return;
    }

    this.timeout = setTimeout(() => {
      this.setState({ open: false });
    });
  };

  handleFiltering = e => {
    const category = e.target.innerText.trim();
    this.props.filterCategory(category);
    this.handleClose();
  };

  render() {
    const { classes, categories } = this.props;
    const { open } = this.state;

    return (
      <nav className={classes.fontSizeSetter}>
        <Manager>
          <Target>
            <IconButton
              aria-label="Filter by category"
              aria-haspopup="true"
              onClick={this.handleClick}
              title="Filter the list by category"
              className={classes.open}
            >
              <FilterListIcon />
            </IconButton>
          </Target>
          <Popper
            placement="bottom-end"
            eventsEnabled={open}
            className={`${classNames({ [classes.popperClose]: !open })} ${classes.popper}`}
          >
            <ClickAwayListener onClickAway={this.handleClose}>
              <Grow in={open} id="cat-menu-list" style={{ transformOrigin: "0 0 0" }}>
                <Paper>
                  <MenuList role="menu">
                    <MenuItem key="all" onClick={this.handleFiltering}>
                      all posts
                    </MenuItem>
                    {categories.map(category => (
                      <MenuItem key={category} onClick={this.handleFiltering}>
                        {category}
                      </MenuItem>
                    ))}
                  </MenuList>
                </Paper>
              </Grow>
            </ClickAwayListener>
          </Popper>
        </Manager>
      </nav>
    );
  }
}

CategoryFilter.propTypes = {
  classes: PropTypes.object.isRequired,
  categories: PropTypes.array.isRequired,
  filterCategory: PropTypes.func.isRequired
};

export default injectSheet(styles)(CategoryFilter);


text:
'use strict';

angular.module('copayApp.controllers').controller('importController',
  function($scope, $rootScope, $timeout, $log, profileService, configService, notification, go, sjcl, gettext, ledger, trezor, derivationPathHelper, platformInfo, bwcService, ongoingProcess) {

    var isChromeApp = platformInfo.isChromeApp;
    var isDevel = platformInfo.isDevel;
    var reader = new FileReader();
    var defaults = configService.getDefaults();
    var errors = bwcService.getErrors();
    $scope.bwsurl = defaults.bws.url;
    $scope.derivationPath = derivationPathHelper.default;
    $scope.account = 1;
    $scope.importErr = false;

    var updateSeedSourceSelect = function() {
      $scope.seedOptions = [];

      if (isChromeApp) {
        $scope.seedOptions.push({
          id: 'ledger',
          label: 'Ledger Hardware Wallet',
        });
      }

      if (isChromeApp || isDevel) {
        $scope.seedOptions.push({
          id: 'trezor',
          label: 'Trezor Hardware Wallet',
        });
        $scope.seedSource = $scope.seedOptions[0];
      }
    };

    $scope.processWalletInfo = function(code) {
      if (!code) return;

      $scope.importErr = false;
      $scope.error = null;
      var parsedCode = code.split('|');

      if (parsedCode.length != 5) {
        /// Trying to import a malformed wallet export QR code
        $scope.error = gettext('Incorrect code format');
        return;
      }

      var info = {
        type: parsedCode[0],
        data: parsedCode[1],
        network: parsedCode[2],
        derivationPath: parsedCode[3],
        hasPassphrase: parsedCode[4] == 'true' ? true : false
      };

      if (info.type == 1 && info.hasPassphrase)
        $scope.error = gettext('Password required. Make sure to enter your password in advanced options');

      $scope.derivationPath = info.derivationPath;
      $scope.testnetEnabled = info.network == 'testnet' ? true : false;

      $timeout(function() {
        $scope.words = info.data;
        $rootScope.$apply();
      }, 1);
    };

    $scope.setType = function(type) {
      $scope.type = type;
      $scope.error = null;
      $timeout(function() {
        $rootScope.$apply();
      }, 1);
    };

    var _importBlob = function(str, opts) {
      var str2, err;
      try {
        str2 = sjcl.decrypt($scope.password, str);
      } catch (e) {
        err = gettext('Could not decrypt file, check your password');
        $log.warn(e);
      };

      if (err) {
        $scope.error = err;
        $timeout(function() {
          $rootScope.$apply();
        });
        return;
      }

      ongoingProcess.set('importingWallet', true);
      opts.compressed = null;
      opts.password = null;

      $timeout(function() {
        profileService.importWallet(str2, opts, function(err, walletId) {
          ongoingProcess.set('importingWallet', false);
          if (err) {
            $scope.error = err;
          } else {
            $rootScope.$emit('Local/WalletImported', walletId);
            notification.success(gettext('Success'), gettext('Your wallet has been imported correctly'));
            go.walletHome();
          }
        });
      }, 100);
    };

    var _importExtendedPrivateKey = function(xPrivKey, opts) {
      ongoingProcess.set('importingWallet', true);
      $timeout(function() {
        profileService.importExtendedPrivateKey(xPrivKey, opts, function(err, walletId) {
          ongoingProcess.set('importingWallet', false);
          if (err) {
            if (err instanceof errors.NOT_AUTHORIZED) {
              $scope.importErr = true;
            } else {
              $scope.error = err;
            }
            return $timeout(function() {
              $scope.$apply();
            });
          }

          $rootScope.$emit('Local/WalletImported', walletId);
          notification.success(gettext('Success'), gettext('Your wallet has been imported correctly'));
          go.walletHome();
        });
      }, 100);
    };

    /*
      IMPORT FROM PUBLIC KEY - PENDING

    var _importExtendedPublicKey = function(xPubKey, opts) {
      ongoingProcess.set('importingWallet', true);
      $timeout(function() {
        profileService.importExtendedPublicKey(opts, function(err, walletId) {
          ongoingProcess.set('importingWallet', false);
          if (err) {
            $scope.error = err;
            return $timeout(function() {
              $scope.$apply();
            });
          }
          $rootScope.$emit('Local/WalletImported', walletId);
          notification.success(gettext('Success'), gettext('Your wallet has been imported correctly'));
          go.walletHome();
        });
      }, 100);
    };
    */

    var _importMnemonic = function(words, opts) {
      ongoingProcess.set('importingWallet', true);

      $timeout(function() {
        profileService.importMnemonic(words, opts, function(err, walletId) {
          ongoingProcess.set('importingWallet', false);

          if (err) {
            if (err instanceof errors.NOT_AUTHORIZED) {
              $scope.importErr = true;
            } else {
              $scope.error = err;
            }
            return $timeout(function() {
              $scope.$apply();
            });
          }

          $rootScope.$emit('Local/WalletImported', walletId);
          notification.success(gettext('Success'), gettext('Your wallet has been imported correctly'));
          go.walletHome();
        });
      }, 100);
    };

    $scope.setDerivationPath = function() {
      if ($scope.testnetEnabled)
        $scope.derivationPath = derivationPathHelper.defaultTestnet;
      else
        $scope.derivationPath = derivationPathHelper.default;
    };

    $scope.getFile = function() {
      // If we use onloadend, we need to check the readyState.
      reader.onloadend = function(evt) {
        if (evt.target.readyState == FileReader.DONE) { // DONE == 2
          var opts = {};
          opts.bwsurl = $scope.bwsurl;
          _importBlob(evt.target.result, opts);
        }
      }
    };

    $scope.importBlob = function(form) {
      if (form.$invalid) {
        $scope.error = gettext('There is an error in the form');
        $timeout(function() {
          $scope.$apply();
        });
        return;
      }

      var backupFile = $scope.file;
      var backupText = form.backupText.$modelValue;
      var password = form.password.$modelValue;

      if (!backupFile && !backupText) {
        $scope.error = gettext('Please, select your backup file');
        $timeout(function() {
          $scope.$apply();
        });

        return;
      }

      if (backupFile) {
        reader.readAsBinaryString(backupFile);
      } else {
        var opts = {};
        opts.bwsurl = $scope.bwsurl;
        _importBlob(backupText, opts);
      }
    };

    $scope.importMnemonic = function(form) {
      if (form.$invalid) {
        $scope.error = gettext('There is an error in the form');
        $timeout(function() {
          $scope.$apply();
        });
        return;
      }

      var opts = {};
      if ($scope.bwsurl)
        opts.bwsurl = $scope.bwsurl;

      var pathData = derivationPathHelper.parse($scope.derivationPath);
      if (!pathData) {
        $scope.error = gettext('Invalid derivation path');
        return;
      }
      opts.account = pathData.account;
      opts.networkName = pathData.networkName;
      opts.derivationStrategy = pathData.derivationStrategy;

      var words = form.words.$modelValue || null;
      $scope.error = null;

      if (!words) {
        $scope.error = gettext('Please enter the recovery phrase');
      } else if (words.indexOf('xprv') == 0 || words.indexOf('tprv') == 0) {
        return _importExtendedPrivateKey(words, opts);
      } else if (words.indexOf('xpub') == 0 || words.indexOf('tpuv') == 0) {
        return _importExtendedPublicKey(words, opts);
      } else {
        var wordList = words.split(/[\u3000\s]+/);

        if ((wordList.length % 3) != 0) {
          $scope.error = gettext('Wrong number of recovery words:') + wordList.length;
        }
      }

      if ($scope.error) {
        $timeout(function() {
          $scope.$apply();
        });
        return;
      }

      var passphrase = form.passphrase.$modelValue;
      opts.passphrase = form.passphrase.$modelValue || null;

      _importMnemonic(words, opts);
    };

    $scope.importTrezor = function(account, isMultisig) {
      trezor.getInfoForNewWallet(isMultisig, account, function(err, lopts) {
        ongoingProcess.clear();
        if (err) {
          $scope.error = err;
          $scope.$apply();
          return;
        }

        lopts.externalSource = 'trezor';
        lopts.bwsurl = $scope.bwsurl;
        ongoingProcess.set('importingWallet', true);
        $log.debug('Import opts', lopts);

        profileService.importExtendedPublicKey(lopts, function(err, walletId) {
          ongoingProcess.set('importingWallet', false);
          if (err) {
            $scope.error = err;
            return $timeout(function() {
              $scope.$apply();
            });
          }
          $rootScope.$emit('Local/WalletImported', walletId);
          notification.success(gettext('Success'), gettext('Your wallet has been imported correctly'));
          go.walletHome();
        });
      }, 100);
    };

    $scope.importHW = function(form) {
      if (form.$invalid || $scope.account < 0) {
        $scope.error = gettext('There is an error in the form');
        $timeout(function() {
          $scope.$apply();
        });
        return;
      }
      $scope.error = '';
      $scope.importErr = false;

      var account = +$scope.account;

      if ($scope.seedSourceId == 'trezor') {
        if (account < 1) {
          $scope.error = gettext('Invalid account number');
          return;
        }
        account = account - 1;
      }

      switch ($scope.seedSourceId) {
        case ('ledger'):
          ongoingProcess.set('connectingledger', true);
          $scope.importLedger(account);
          break;
        case ('trezor'):
          ongoingProcess.set('connectingtrezor', true);
          $scope.importTrezor(account, $scope.isMultisig);
          break;
        default:
          throw ('Error: bad source id');
      };
    };

    $scope.setSeedSource = function() {

      if (!$scope.seedSource) return;
      $scope.seedSourceId = $scope.seedSource.id;
      $timeout(function() {
        $rootScope.$apply();
      });
    };

    $scope.importLedger = function(account) {
      ledger.getInfoForNewWallet(true, account, function(err, lopts) {
        ongoingProcess.clear();
        if (err) {
          $scope.error = err;
          $scope.$apply();
          return;
        }

        lopts.externalSource = 'ledger';
        lopts.bwsurl = $scope.bwsurl;
        ongoingProcess.set('importingWallet', true);
        $log.debug('Import opts', lopts);

        profileService.importExtendedPublicKey(lopts, function(err, walletId) {
          ongoingProcess.set('importingWallet', false);
          if (err) {
            $scope.error = err;
            return $timeout(function() {
              $scope.$apply();
            });
          }
          $rootScope.$emit('Local/WalletImported', walletId);
          notification.success(gettext('Success'), gettext('Your wallet has been imported correctly'));
          go.walletHome();
        });
      }, 100);
    };

    updateSeedSourceSelect();
    $scope.setSeedSource('new');
  });


text:
package java.io;

/**
 * This exception is thrown when there is some sort of problem with a
 * class during a serialization operation.  This could be:

 *
the serial version of the class doesn't match

 *
the class contains unknown datatypes

 *
the class does not have an accessible no-arg constructor

 *
.
 *
 *
The field classname will contain the name of the
 * class that caused the problem if known.  The getMessage() method
 * for this exception will always include the name of that class
 * if known.
 *
 * @author Aaron M. Renn (arenn@urbanophile.com)
 * @since 1.1
 * @status updated to 1.4
 */
public class InvalidClassException extends ObjectStreamException
{
  /**
   * Compatible with JDK 1.1+.
   */
  private static final long serialVersionUID = -4333316296251054416L;

  /**
   * The name of the class which encountered the error.
   *
   * @serial the classname causing the error
   */
  public String classname;

  /**
   * Create an exception with a descriptive error message, but a null
   * classname.
   *
   * @param message the descriptive error message
   */
  public InvalidClassException(String message)
  {
    super(message);
  }

  /**
   * Create an exception with a descriptive error message, and the name of
   * the class that caused the problem.
   *
   * @param classname the name of the faulty class
   * @param message the descriptive error message
   */
  public InvalidClassException(String classname, String message)
  {
    super(message);
    this.classname = classname;
  }

  /**
   * Returns the descriptive error message for this exception. It will
   * include the class name that caused the problem if known, in the format:
   * [classname][; ][super.getMessage()].
   *
   * @return A descriptive error message, may be null
   */
  public String getMessage()
  {
    String msg = super.getMessage();
    if (msg == null)
      return classname;
    return (classname == null ? "" : classname + "; ") + msg;
  }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../libc/constant.PF_LINK.html">

Redirecting to ../../../../libc/constant.PF_LINK.html...


text:
<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

    <classPathEntry location="mysql-connector-java-8.0.20.jar"/>

    <context id="simple" targetRuntime="MyBatis3">

        <property name="autoDelimitKeywords" value="true"/>

        <property name="javaFileEncoding" value="utf-8"/>

        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>

        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="false"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/game_server_1?serverTimezone=UTC" userId="root"
                        password="123456"/>

        <javaTypeResolver>

            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="com.codebroker.mybatis.gameserver1.model"
                            targetProject="D:\Users\Documents\github\CodeBrokerGit\GameServer\src\main\java">

            <property name="enableSubPackages" value="false"/>

            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"
                         targetProject="D:\Users\Documents\github\CodeBrokerGit\GameServer\src\main\resource\gameserver1">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <javaClientGenerator targetPackage="com.codebroker.mybatis.gameserver1.mapper"
                             targetProject="D:\Users\Documents\github\CodeBrokerGit\GameServer\src\main\java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

            <property name="useActualColumnNames" value="true"/>

            <property name="useActualColumnNames" value="true"/>

    </context>
</generatorConfiguration>


text:
require_relative '../../spec_helper'
require_relative 'fixtures/classes'
require_relative 'shared/value'

describe "Hash#has_value?" do
  it_behaves_like :hash_value_p, :has_value?
end


text:
package datasources;

import org.junit.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.util.ArrayList;
import java.util.Collection;

import datasources.DummyDataProvider;
import models.Person;

/**
 * This class implements test-cases that verify code contained in the
 * DummyDataProvider class.
 * @author Nash
 */
public class DummyDataProviderTest {

	private DummyDataProvider mdp;
	private ArrayList<Person> persons;
	private Person bart;

	/**
	 * This method is a setup hook for test-cases, which ensures that each
	 * test-case is dealing with known values.
	 */
	@Before
	public void setUp() throws Exception {
		mdp = new DummyDataProvider();
		persons = mdp.getPersons();
		bart = new Person(101,"Bart","Simpsons",1987,"Springfield","USA");
	}

	/**
	 * This method tests the side-effect of calling constructor i.e. populating
	 * the dummy data-collection.
	 */
	@Test
	public void constructorInvokePopulateCollection() {
		assertFalse(persons.isEmpty());
	}

	/**
	 * This method tests the returned data-type of getPersons() method to match
	 * with the IDataSource interface specification.
	 */
	@Test
	public void getPersonsReturnCollectionType() {
		Collection<Object> expectedDataCollection = new ArrayList<>();
		assertThat(expectedDataCollection, instanceOf(persons.getClass()));
	}

	/**
	 * This method tests the getPersons() method's return data-type item to match
	 * with the IDataSource interface specification.
	 */
	@Test
	public void getPersonsReturnCollectionItemType() {
		Person expectedType = bart;
		assertThat(expectedType, instanceOf(persons.get(0).getClass()));
	}

	/**
	 * This method tests the number of rows contained within the dummy
	 * data-collection.
	 */
	@Test
	public void getPersonsReturnCollectionSize() {
		int expectedSize = 3;
		assertEquals(expectedSize, persons.size());
	}

	/**
	 * This method tests if getPersons() method is an infinite loop
	 */
	@Test(timeout=1000) // milliseconds, i.e. 1000=1sec
	public void getPersonsInInfiniteLoop() {
		assertNotNull(mdp.getPersons());
	}

}


text:
var Task = function(name){
	this.name = name;
	this.completed = false;
}

Task.prototype.complete = function() {
	console.log("completing task: " + this.name)
	this.completed = true;
};

Task.prototype.save = function() {
	console.log("saving task " + this.name);
};

module.exports = Task;


text:
import { Event } from 'vs/base/common/event';
import { IPosition } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { StandardTokenType } from 'vs/editor/common/encodedTokenAttributes';
import { ContiguousMultilineTokens } from 'vs/editor/common/tokens/contiguousMultilineTokens';
import { LineTokens } from 'vs/editor/common/tokens/lineTokens';
import { SparseMultilineTokens } from 'vs/editor/common/tokens/sparseMultilineTokens';

/**
 * Provides tokenization related functionality of the text model.
*/
export interface ITokenizationTextModelPart {
	/**
	 * @internal
	 */
	setTokens(tokens: ContiguousMultilineTokens[]): void;

	/**
	 * Replaces all semantic tokens with the provided `tokens`.
	 * @internal
	 */
	setSemanticTokens(tokens: SparseMultilineTokens[] | null, isComplete: boolean): void;

	/**
	 * Merges the provided semantic tokens into existing semantic tokens.
	 * @internal
	 */
	setPartialSemanticTokens(range: Range, tokens: SparseMultilineTokens[] | null): void;

	/**
	 * @internal
	 */
	hasCompleteSemanticTokens(): boolean;

	/**
	 * @internal
	 */
	hasSomeSemanticTokens(): boolean;

	/**
	 * Flush all tokenization state.
	 * @internal
	 */
	resetTokenization(): void;

	/**
	 * Force tokenization information for `lineNumber` to be accurate.
	 * @internal
	 */
	forceTokenization(lineNumber: number): void;

	/**
	 * If it is cheap, force tokenization information for `lineNumber` to be accurate.
	 * This is based on a heuristic.
	 * @internal
	 */
	tokenizeIfCheap(lineNumber: number): void;

	/**
	 * Check if calling `forceTokenization` for this `lineNumber` will be cheap (time-wise).
	 * This is based on a heuristic.
	 * @internal
	 */
	isCheapToTokenize(lineNumber: number): boolean;

	/**
	 * Get the tokens for the line `lineNumber`.
	 * The tokens might be inaccurate. Use `forceTokenization` to ensure accurate tokens.
	 * @internal
	 */
	getLineTokens(lineNumber: number): LineTokens;

	/**
	* Returns the standard token type for a character if the character were to be inserted at
	* the given position. If the result cannot be accurate, it returns null.
	* @internal
	*/
	getTokenTypeIfInsertingCharacter(lineNumber: number, column: number, character: string): StandardTokenType;

	/**
	 * @internal
	*/
	tokenizeLineWithEdit(position: IPosition, length: number, newText: string): LineTokens | null;

	/**
	 * @internal
	 */
	tokenizeViewport(startLineNumber: number, endLineNumber: number): void;

	getLanguageId(): string;
	getLanguageIdAtPosition(lineNumber: number, column: number): string;

	setLanguageId(languageId: string): void;

	readonly backgroundTokenizationState: BackgroundTokenizationState;
	readonly onBackgroundTokenizationStateChanged: Event<void>;
}

export const enum BackgroundTokenizationState {
	Uninitialized = 0,
	InProgress = 1,
	Completed = 2,
}


text:
# A PAPI Test Driver.

use strict;
use warnings;
use FileHandle;
use LWP::Simple;

my $username = 'santiago.paredes@ll.mit.edu';
my $pass = "!asecret";
my $useBasicAuthorization = undef;

sub useBasicAuthorization
{
	$useBasicAuthorization = shift;
}

#
# Some primitives
#
sub doJSONOp
{
	my $op = shift;
	my $url = shift;
	my $json = shift;
	my $req = HTTP::Request->new($op => $url);
	$req->content_type('application/json');
	$req->content($json);
	$req->authorization_basic( "$username", "$pass" )
		if defined($useBasicAuthorization);

	my $ua = LWP::UserAgent->new; # You might want some options here
	my $res = $ua->request($req);
	return $res;
}

sub doJSONDelete
{
	my $url = shift;
	my $json = shift;
	return doJSONOp('DELETE', $url, $json);
}

sub doJSONGet
{
	my $url = shift;
	my $json = shift;
	return doJSONOp('GET', $url, $json);
}

sub doJSONPut
{
	my $url = shift;
	my $json = shift;
	return doJSONOp('PUT', $url, $json);
}

sub doJSONPost
{
	my $url = shift;
	my $json = shift;
	return doJSONOp('POST', $url, $json);
}
1;


text:
id: 56533eb9ac21ba0edf2244cd
title: Accessing Nested Arrays
challengeType: 1
isHidden: false
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
forumTopicId: 16160
---

## Description

As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.
Here is an example of how to access a nested array:

```js
var ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
```

## Instructions

Retrieve the second tree from the variable myPlants using object dot and array bracket notation.

## Tests

```yml
tests:
  - text: <code>secondTree</code> should equal "pine".
    testString: assert(secondTree === "pine");
  - text: Your code should use dot and bracket notation to access <code>myPlants</code>.
    testString: assert(/=\s*myPlants\[1\].list\[1\]/.test(code));

```

## Challenge Seed

```js
// Setup
var myPlants = [
  {
    type: "flowers",
    list: [
      "rose",
      "tulip",
      "dandelion"
    ]
  },
  {
    type: "trees",
    list: [
      "fir",
      "pine",
      "birch"
    ]
  }
];

// Only change code below this line

var secondTree = ""; // Change this line

```

### After Test

```js
(function(x) {
  if(typeof x != 'undefined') {
    return "secondTree = " + x;
  }
  return "secondTree is undefined";
})(secondTree);
```

## Solution

```js
var myPlants = [
  {
    type: "flowers",
    list: [
      "rose",
      "tulip",
      "dandelion"
    ]
  },
  {
    type: "trees",
    list: [
      "fir",
      "pine",
      "birch"
    ]
  }
];

// Only change code below this line

var secondTree = myPlants[1].list[1];
```


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
|	example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
|	http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
|	$route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
|	$route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/

$route['default_controller'] = "home/chome";
$route['404_override'] = '';

$route['trang-chu'] = "home/chome";
$route['san-pham/(:any)'] = "home/cproducts/showDetailProducts/$1";
$route['update-san-pham'] = "home/cproducts/updateProducts";
$route['profile'] = "home/cusers/profile";
$route['dang-ky'] = "home/cusers/signup";
$route['active'] = "home/cusers/active";
$route['cart'] = "home/cproducts/view_cart";
$route['up-product'] = "home/cproducts/upProducts";
$route['thanh-toan-tai-nha'] = "home/cproducts/payhome";
$route['thanh-toan-truc-tuyen'] = "home/cproducts/payonline";

///////////////////////////////////////
//For pages those have a static name
$route['{default_controller}/{default_method}/about.html'] = "{original_controller}/{original_method}";

//rule to rout request with number values
$route['{default_controller}/{default_method}/(:num)'] = "{original_controller}/{original_method}/$1";

//rule to rout request with regular expression values
$route['{default_controller}/{default_method}/([a-z]+)-{delimiter}'] = "{original_controller}/{original_method}/$1";

/* End of file routes.php */
/* Location: ./application/config/routes.php */


text:
title: "Use secrets management in Sensu"
linkTitle: "Use Secrets Management"
description: "Sensu's secrets management allows you to avoid exposing secrets like usernames and passwords in your Sensu configuration. In this guide, you'll learn how to use Sensu's built-in secrets provider or HashiCorp Vault and refer to external secrets in your Sensu configuration."
weight: 1
version: "5.20"
product: "Sensu Go"
platformContent: False
menu:
  sensu-go-5.20:
    parent: manage-secrets
---

**COMMERCIAL FEATURE**: Access the Env and VaultProvider secrets provider datatypes in the packaged Sensu Go distribution.
For more information, see [Get started with commercial features][20].

Sensu's secrets management allows you to avoid exposing secrets like usernames, passwords, and access keys in your Sensu configuration.
In this guide, you'll learn how to use Sensu's built-in secrets provider, `Env`, or [HashiCorp Vault][1] as your external [secrets provider][2] and authenticate without exposing your secrets.
You'll set up your PagerDuty Integration Key as a secret and create a PagerDuty handler definition that requires the secret.
Your Sensu backend can then execute the handler with any check.

To follow this guide, you'll need to [install the Sensu backend][5], have at least one [Sensu agent][11] running, and [install and configure sensuctl][7].

Secrets are configured via [secrets resources][8].
A secret resource definition refers to the secrets provider (`Env` or `VaultProvider`) and an ID (the named secret to fetch from the secrets provider).

This guide only covers the handler use case, but you can use secrets management in handler, mutator, and check execution.
When a check configuration references a secret, the Sensu backend will only transmit the check's execution requests to agents that are connected via mutually authenticated transport layer security (mTLS)-encrypted websockets. Read more about [enabling mTLS][15].

The secret included in your Sensu handler will be exposed to Sensu services at runtime as an environment variable.
Sensu only exposes secrets to Sensu services like environment variables and automatically redacts secrets from all logs, the API, and the web UI.

## Retrieve your PagerDuty Integration Key

The example in this guide uses the [PagerDuty][31] Integration Key as a secret and a PagerDuty handler definition that requires the secret.

Here's how to find your Integration Key in PagerDuty so you can set it up as your secret:

1. Log in to your PagerDuty account.
2. In the **Configuration** drop-down menu, select **Services**.
3. Click your Sensu service.
4. Click the **Integrations** tab. The Integration Key is listed in the second column.

PagerDuty Integration Key location

Make a note of your Integration Key — you'll need it to create your [backend environment variable][28] or [HashiCorp Vault secret][29].

## Use Env for secrets management

The [Sensu Go commercial distribution][1] includes a built-in secrets provider, `Env`, that exposes secrets from [environment variables][21] on your Sensu backend nodes.
The `Env` secrets provider is automatically created with an empty `spec` when you start your Sensu backend.

### Create your backend environment variable

To use the built-in `Env` secrets provider, you will add your secret as a backend environment variable.

First, make sure you have created the files you need to store [backend environment variables][21].

Then, run the following code, replacing `INTEGRATION_KEY` with your PagerDuty Integration Key:

{{< language-toggle >}}

{{}}
$ echo 'SENSU_PAGERDUTY_KEY=INTEGRATION_KEY' | sudo tee -a /etc/default/sensu-backend
$ sudo systemctl restart sensu-backend
{{}}

{{}}
$ echo 'SENSU_PAGERDUTY_KEY=INTEGRATION_KEY' | sudo tee -a /etc/sysconfig/sensu-backend
$ sudo systemctl restart sensu-backend
{{}}

{{< /language-toggle >}}

This configures the `SENSU_PAGERDUTY_KEY` environment variable to your PagerDuty Integration Key in the context of the sensu-backend process.

### Create your Env secret

Now you'll use `sensuctl create` to create your secret.
This code creates a secret named `pagerduty_key` that refers to the environment variable ID `SENSU_PAGERDUTY_KEY`.
Run:

{{}}
cat << EOF | sensuctl create
---
type: Secret
api_version: secrets/v1
metadata:
  name: pagerduty_key
  namespace: default
spec:
  id: SENSU_PAGERDUTY_KEY
  provider: env
EOF
{{}}

You can securely pass your PagerDuty Integration Key in Sensu checks, handlers, and mutators by referring to the `pagerduty_key` secret.
Skip to the [add a handler][19] section, where you'll use your `pagerduty_key` secret in your handler definition.

## Use HashiCorp Vault for secrets management

This section explains how to use [HashiCorp Vault][1] as your external [secrets provider][2] to authenticate via the HashiCorp Vault integration's [token auth method][3] or [TLS certificate auth method][4].

{{% notice note %}}
**NOTE**: You must set up [HashiCorp Vault](https://www.vaultproject.io/docs/install/) to use `VaultProvider` secrets management in production.
The examples in this guide use the [Vault dev server](https://www.vaultproject.io/docs/concepts/dev-server/), which is useful for learning and experimenting.
The Vault dev server gives you access to a preconfigured, running Vault server with in-memory storage that you can use right away.
Follow the [HashiCorp Learn curriculum](https://learn.hashicorp.com/vault) when you are ready to set up a production server in Vault.

In addition, this guide uses the [Vault KV secrets engine](https://www.vaultproject.io/api/secret/kv/kv-v2.html).
Using the Vault KV secrets engine with the Vault dev server requires v2 connections.
For this reason, in the `VaultProvider` spec in these examples, the client `version` value is **v2**.
{{% /notice %}}

### Configure your Vault authentication method (token or TLS)

If you use [HashiCorp Vault][1] as your external [secrets provider][2], you can authenticate via the HashiCorp Vault integration's [token][3] or [transport layer security (TLS) certificate][4] authentication method.

#### Vault token authentication

Follow the steps in this section to use HashiCorp Vault as your external [secrets provider][2] to authenticate with the HashiCorp Vault integration's [token auth method][3].

##### Retrieve your Vault root token

{{% notice note %}}
**NOTE**: The examples in this guide use the `Root Token` for the the [Vault dev server](https://learn.hashicorp.com/vault/getting-started/dev-server), which gives you access to a preconfigured, running Vault server with in-memory storage that you can use right away.
Follow the [HashiCorp Learn curriculum](https://learn.hashicorp.com/vault) when you are ready to set up a production server in Vault.
{{% /notice %}}

To retrieve your Vault root token:

1. [Download and install][25] the Vault edition for your operating system.
2. Open a terminal window and run `vault server -dev`.

The command output includes a `Root Token` line.
Find this line in your command output and copy the `Root Token` value.
You will use it next to create your Vault secrets provider.

HashiCorp Vault Root Token location

Leave the Vault dev server running.
Because you aren't using TLS, you will need to set `VAULT_ADDR=http://127.0.0.1:8200` in your shell environment.

##### Create your Vault secrets provider

{{% notice note %}}
**NOTE**: In Vault's dev server, TLS is not enabled, so you won't be able to use certificate-based authentication.
{{% /notice %}}

Use `sensuctl create` to create your secrets provider, `vault`.
In the code below, replace `ROOT_TOKEN` with the `Root Token` value for your Vault dev server.
Then, run:

{{}}
cat << EOF | sensuctl create
---
type: VaultProvider
api_version: secrets/v1
metadata:
  name: vault
spec:
  client:
    address: http://localhost:8200
    token: ROOT_TOKEN
    version: v2
    tls: null
    max_retries: 2
    timeout: 20s
    rate_limiter:
      limit: 10
      burst: 100
EOF
{{}}

To continue, skip ahead to [create your Vault secret][29].

#### Vault TLS certificate authentication

This section explains how use HashiCorp Vault as your external [secrets provider][2] to authenticate with the HashiCorp Vault integration's [TLS certificate auth method][4].

{{% notice note %}}
**NOTE**: You will need to set up [HashiCorp Vault](https://www.vaultproject.io/docs/install/) in production to use TLS certificate-based authentication. In Vault's dev server, TLS is not enabled. Follow the [HashiCorp Learn curriculum](https://learn.hashicorp.com/vault) when you are ready to set up a production server in Vault.
{{% /notice %}}

First, in your Vault, [enable and configure certificate authentication][32].
For example, your Vault might be configured for certificate authentication like this:

{{}}
vault write auth/cert/certs/sensu-backend \
    display_name=sensu-backend \
    policies=sensu-backend-policy \
    certificate=@sensu-backend-vault.pem \
    ttl=3600
{{}}

Second, configure your `VaultProvider` in Sensu:

{{}}
---
type: VaultProvider
api_version: secrets/v1
metadata:
  name: vault
spec:
  client:
    address: https://vault.example.com:8200
    version: v2
    tls:
      ca_cert: /path/to/your/ca.pem
      client_cert: /etc/sensu/ssl/sensu-backend-vault.pem
      client_key: /etc/sensu/ssl/sensu-backend-vault-key.pem
      cname: sensu-backend.example.com
    max_retries: 2
    timeout: 20s
    rate_limiter:
      limit: 10
      burst: 100
{{}}

The certificate you specify for `tls.client_cert` should be the same certificate you configured in your Vault for certificate authentication.

Next, [create your Vault secret][29].

### Create your Vault secret

First, retrieve your [PagerDuty Integration Key][30] (the secret you will set up in Vault).

Next, open a new terminal and run `vault kv put secret/pagerduty key=INTEGRATION_KEY`.
Replace `INTEGRATION_KEY` with your PagerDuty Integration Key.
This writes your secret into Vault.

In this example, the name of the secret is `pagerduty`.
The `pagerduty` secret contains a key, and you specified that the `key` value is your PagerDuty Integration Key.
The `id` value for your secret will be `secret/pagerduty#key`.

{{% notice note %}}
**NOTE**: The `id` value for secrets that target a HashiCorp Vault must start with the name of the secret's path in Vault.
The Vault dev server is preconfigured with the `secret` keyspace already set up, and Sensu requires the `secret/` path for the `id` value.
{{% /notice %}}

Run `vault kv get secret/pagerduty` to see the secret you just set up.

Use `sensuctl create` to create your `vault` secret:

{{}}
cat << EOF | sensuctl create
---
type: Secret
api_version: secrets/v1
metadata:
  name: pagerduty_key
  namespace: default
spec:
  id: secret/pagerduty#key
  provider: vault
EOF
{{}}

Now you can securely pass your PagerDuty Integration Key in the handlers, and mutators by referring to the `pagerduty_key` secret.
In the [add a handler][19] section, you'll use your `pagerduty_key` secret in your handler definition.

## Add a handler

### Register the PagerDuty Handler asset

To begin, register the [Sensu PagerDuty Handler asset][23] with [`sensuctl asset add`][22]:

{{}}
sensuctl asset add sensu/sensu-pagerduty-handler:1.2.0 -r pagerduty-handler
{{}}

This example uses the `-r` (rename) flag to specify a shorter name for the asset: `pagerduty-handler`.

{{% notice note %}}
**NOTE**: You can [adjust the asset definition](../../../guides/install-check-executables-with-assets/#adjust-the-asset-definition) according to your Sensu configuration if needed.
{{% /notice %}}

Run `sensuctl asset list --format yaml` to confirm that the asset is ready to use.

With this handler, Sensu can trigger and resolve PagerDuty incidents.
However, you still need to add your secret to the handler spec so that it requires your backend to request secrets from your secrets provider.

### Add your secret to the handler spec

To create a handler definition that uses your `pagerduty_key` secret, run:

{{}}
cat << EOF | sensuctl create
---
api_version: core/v2
type: Handler
metadata:
  namespace: default
  name: pagerduty
spec:
  type: pipe
  command: pagerduty-handler --token $PD_TOKEN
  secrets:
  - name: PD_TOKEN
    secret: pagerduty_key
  runtime_assets:
  - pagerduty-handler
  timeout: 10
  filters:
  - is_incident
EOF
{{}}

Now that your handler is set up and Sensu can create incidents in PagerDuty, you can automate this workflow by adding your `pagerduty` handler to your Sensu service check definitions.
See [Monitor server resources][24] to learn more.

## Next steps

Read the [secrets][9] or [secrets providers][10] reference for in-depth secrets management documentation.

[1]: https://www.vaultproject.io/docs/what-is-vault/
[2]: ../../../reference/secrets-providers/
[3]: https://www.vaultproject.io/docs/auth/token/
[4]: https://www.vaultproject.io/docs/auth/cert/
[5]: ../../deploy-sensu/install-sensu/#install-the-sensu-backend
[6]: ../../deploy-sensu/install-sensu/#install-sensu-agents
[7]: ../../deploy-sensu/install-sensu/#install-sensuctl
[8]: ../../../api/secrets/
[9]: ../../../reference/secrets/
[10]: ../../../reference/secrets-providers/
[11]: ../../deploy-sensu/install-sensu/#install-sensu-agents
[12]: https://www.vaultproject.io/docs/concepts/lease.html#lease-durations-and-renewal
[13]: ../../../api/secrets#providers-provider-put
[14]: ../../../api/secrets#secrets-secret-put
[15]: ../../deploy-sensu/secure-sensu/#sensu-agent-mtls-authentication
[17]: ../../../reference/secrets-providers#tls-vault
[19]: #add-a-handler
[20]: ../../../commercial/
[21]: ../../../reference/backend/#configuration-via-environment-variables
[22]: ../../../sensuctl/sensuctl-bonsai/#install-asset-definitions
[23]: https://bonsai.sensu.io/assets/sensu/sensu-pagerduty-handler
[24]: ../../../guides/monitor-server-resources/
[25]: https://www.vaultproject.io/downloads/
[28]: #create-your-backend-environment-variable
[29]: #create-your-vault-secret
[30]: #retrieve-your-pagerduty-integration-key
[31]: https://www.pagerduty.com/
[32]: https://www.vaultproject.io/docs/auth/cert/#configuration


text:
"""
    @file FWPWebsite.Google_App_Engine.fwerks
    =========================================
    FWerks is a quick and dirty framework for creating WSGI application callables
    using the Werkzeug utilities. The WSGI application constructor is built by
    the class `App` defined in this file. Check out the docs string for `App` to
    learn a lot more about how this process works.

    @author Kris Walker <kixxauth@gmail.com>
    @copyright (c) 2010 by The Fireworks Project.
    @license MIT, see LICENSE for more details.
"""

import logging

from werkzeug.exceptions import HTTPException, MethodNotAllowed, InternalServerError

class App(object):
    """Create a WSGI conforming callable application.
    -------------------------------------------------

    From PEP 333:
    The application object is simply a callable object that accepts two
    arguments. The term "object" should not be misconstrued as requiring an
    actual object instance: a function, method, class, or instance with a
    __call__    method are all acceptable for use as an application object.The
    application object must accept two positional arguments. For the sake of
    illustration, we have named them environ and start_response, but they are not
    required to have these names.

    In our case, to create the application the `App` constructor needs to be
    passed a url map, handler dictionary, and exception handler dictionary. The
    resulting `App` callable is designed to be passed to the Google App Engine
    `run_bare_wsgi_app()` function like this::

        from fwerks import App, Handler
        from google.appengine.ext.webapp.util import run_bare_wsgi_app

        class IndexHandler(Handler):
            def get(self):
                return werkzeug.Response('Hello World!')

        handler_map = [('/', 'index', IndexHandler)]
        my_awesome_app = App(handler_map)

        def main():
            run_bare_wsgi_app(my_awesome_app)

        if __name__ == "__main__":
            main()

    See [PEP 333](http://www.python.org/dev/peps/pep-0333/) for more info:

    As you can see we're using the Werkzeug utility framework to create the WSGI
    application:    http://werkzeug.pocoo.org/

    """
    def __init__(self, url_map, handlers, error_handlers={}):
        self.url_map = url_map
        self.handlers = handlers
        self.error_handlers = error_handlers

    def __call__(self, environ, start_response):
        try:
            # Construct a Werkzeug adapter object that is bound to the CGI
            # environment for this request.
            url_adapter = self.url_map.bind_to_environ(environ)

            # Dispatch the request to the correct handler and method.
            endpoint, matched_values = url_adapter.match()
            handler = self.handlers.get(endpoint)(endpoint, environ)
            response = handler(matched_values)

        # One particularly interesting thing about Werkzeug is that HTTPException
        # objects are WSGI conforming callable objects. So, if we can catch them,
        # we can use them to form the response.
        except HTTPException, e:
            error_handler = self.error_handlers.get(e.name, None)
            if error_handler and callable(error_handler):
                try:
                    response = error_handler(e, environ)
                except Exception, handlerex:
                    logging.warn('Caught exception in error handler %.', e.name)
                    logging.exception(handlerex)
                    response = e
            else:
                logging.debug('No exception handler for %s.', e.name)
                response = e

        except Exception, e:
            logging.warn('Caught unexpected exception.')
            logging.exception(e)
            error_handler = self.error_handlers.get('*', None)
            if error_handler and callable(error_handler):
                logging.debug('Calling error handler.')
                try:
                    response = error_handler(e, environ)
                except Exception, handlerex:
                    logging.warn('Caught exception in error handler.')
                    logging.exception(handlerex)
                    response = InternalServerError()
            else:
                logging.debug('Using default error handler.')
                response = InternalServerError()

        return response(environ, start_response)

class Handler(object):
    """Request handler base class.
    ------------------------------

    All request handlers should be subclasses of this class.    Handler subclasses
    should define any HTTP methods they wish to support by defining methods named
    'get', 'post', 'put', 'delete', 'head', or 'options'.

    Handler methods will be called when a request matching their path rule and
    method name arrives. Any parameters defined in the routing rule which was
    passed to `werkzeug.Rule()` will be passed to the handler method. See the
    [Werkzeug documentation on rule
    formatting](http://werkzeug.pocoo.org/documentation/0.6.2/routing.html#rule-format)
    to see how rules work.

    @property {string} name: The name of a Handler instance is simply the endpoint
    string which was set by the url map and was routed here by the dispatcher.
    @property {dict} environ: The CGI environment dictionary in case the instance
    needs access to it.

    """
    methods = ['get', 'post', 'put', 'delete', 'head', 'options']

    def __init__(self, endpoint, environ):
        self.name = endpoint
        self.environ = environ

    def __call__(self, arguments):
        method_handler = getattr(self, self.request.method.lower(), None)

        if callable(method_handler):
            return method_handler(**arguments)

        allowed = [m.upper() \
                for m in Handler.methods if getattr(self, m, None)]
        raise MethodNotAllowed(allowed)

class User(object):

    def __init__(self, session):
        pass


text:
<mvc:View
	xmlns:mvc="sap.ui.core.mvc"
	xmlns="sap.m"
	xmlns:form="sap.ui.layout.form"
	xmlns:uxap="sap.uxap"
	xmlns:sap.ui.layout="sap.ui.layout"
	controllerName="sap.ui.rta.test.rtaOpenUI5Only.Root" >

	<Page title="{i18n>appTitle}" id="page">
		<headerContent>
			<Button text="{i18n>btnAdapt}" visible="{view>/showAdaptButton}" press=".switchToAdaptionMode" />
		</headerContent>
		<content>
			<sap.ui.layout:VerticalLayout width="100%">
				<sap.ui.layout:VerticalLayout id="layout1">
					<Toolbar id="toolbar">
						<Button text="UI5 Button1" id="UI5Button1" />
						<Button text="UI5 Button2" id="UI5Button2" />
						<Button text="UI5 Button3" id="UI5Button3" />
					</Toolbar>
				</sap.ui.layout:VerticalLayout>

				<sap.ui.layout:VerticalLayout width="100%" class="sapUiLargeMarginTop">
					<!--This Form is bound to EntityType02 in the controller -->
					<form:Form id="MainForm" title="Form with  assigned bound to EntityType02" editable="true" >
						<form:layout>
							<form:ResponsiveGridLayout/>
						</form:layout>
						<form:formContainers>
							<!--This Group is bound to EntityType01 in the controller -->
							<form:FormContainer id="GroupEntityType01" title="Group1 bound to  EntityType01" >
								<form:FormElement id="EntityType01.Prop1" label="Prop1">
									<Input editable="true" value="{Property01}"/>
								</form:FormElement>
								<form:FormElement id="EntityType01.Prop2" label="Prop2">
									<Input value="{Property02}"/>
								</form:FormElement>
								<form:FormElement id="EntityType01.Prop3" label="Prop3">
									<TextArea value="{Property03}"/>
								</form:FormElement>
								<form:FormElement id="EntityType02.EntityType02_Property02" label="Field bound to EntityType02" >
									<Input value="{EntityType02_Property02}"/>
								</form:FormElement>
								<form:FormElement label="i18n Bound Value" id="EntityType01.I18NTest" >
									<Input value="{i18n>groupElementLabelText}" />
								</form:FormElement>
								<form:FormElement label="Invisible field" id="EntityType01.Property04.Invisible" visible="false">
									<Input value="{Property04}" />
								</form:FormElement>
								<form:FormElement label="Ignored Property05 bound" id="EntityType01.BoundButton" >
									<Button text="{Property05}"></Button>
								</form:FormElement>
								<form:FormElement label="No-Bound-Field" id="EntityType01.BoundButton34" >
									<Button text="{i18n>buttonText}"></Button>
									<TextArea value="Some Text"></TextArea>
								</form:FormElement>
								<form:FormElement id="EntityType01.UnboundButton" >
									<Button text="No Binding"></Button>
								</form:FormElement>
								<form:FormElement id="EntityType01.CommonProperty" visible="false" label="CommonProp">
									<Input value="{CommonPropertyName}" />
								</form:FormElement>
								<form:FormElement label="Invisible complex property" id="EntityType01.ComplexProperty031.Invisible" visible="false">
									<Input value="{EntityType01_Complex/ComplexProperty031}" />
								</form:FormElement>
								<form:FormElement label="Invisible property without binding" id="InvisibleNoBinding" visible="false">
									<Input />
								</form:FormElement>
								<form:FormElement id="EntityType01.Prop9" visible="false" label="Invisible with binding inside (revealable)">
									<TextArea value="{Property09}"/>
								</form:FormElement>
								<form:FormElement id="EntityType01.Prop10" visible="false" label="Invisible with binding inside (not revealable)">
									<TextArea value="{DELETED_CUSTOM_FIELD}"/>
								</form:FormElement>
							</form:FormContainer>
							<!--This Group is bound to EntityType02 because the form is bound to EntityType02 -->
							<form:FormContainer id="GroupEntityType02" title="Group2 bound to EntityType02" >
								<form:FormElement id="EntityType02.CompProp1" label="CompProp1">
									<Input editable="true" value="{EntityType02_Complex/ComplexProperty01}"/>
								</form:FormElement>
								<form:FormElement id="EntityType02.CompProp2" label="CompProp2">
									<Input value="{EntityType02_Complex/ComplexProperty02}"/>
								</form:FormElement>
								<form:FormElement label="Property02 bound button" id="EntityType02.Prop2Button" >
									<Button text="{EntityType02_Property02}"></Button>
								</form:FormElement>
								<form:FormElement label="{i18n>customLabel}" id="ComplexBindingCase">
									<TextArea id="mytextarea" value="{EntityType02_Property03} {EntityType02_Complex/ComplexProperty02}"/>
								</form:FormElement>
								<form:FormElement label="No-Bound-Field" id="EntityType02.BoundButton34" >
									<Button text="{i18n>buttonText}"></Button>
									<TextArea value="Some Text"></TextArea>
								</form:FormElement>
								<form:FormElement id="EntityType02.UnboundButton" label="unbound">
									<Button text="No Binding"></Button>
								</form:FormElement>
								<form:FormElement label="Partially visible combined field, real use case from SD CustomerReturn_OP_F1708Type" id="EntityType02.PartiallyVisible" >
									<Input value="{EntityType02_Property05}"/>
									<Input value="{EntityType02_Property06}" visible="false"/>
								</form:FormElement>
								<form:FormElement id="EntityType02.CommonProperty" visible="false" label="CommonProp">
									<Input value="{CommonPropertyName}" />
								</form:FormElement>
								<form:FormElement label="NavigationLabel01" id="EntityType02.NavigationProperty" visible="false">
									<Input value="{to_EntityType02Nav/NavProperty}"/>
								</form:FormElement>
								<form:FormElement label="IncorrectNavigationProperty" id="EntityType02.IncorrectNavigationProperty" visible="false">
									<Input value="{to_NonexistentEntity/NavProperty}"/>
								</form:FormElement>
								<form:FormElement label="Field with absolute binding" id="EntityType02.AbsoluteBinding" visible="false">
									<Input value="{/ModelName/PropertyName}"/>
								</form:FormElement>
								<form:FormElement label="Field with binding to non-existent model" id="NonExistentModel" visible="false">
									<Input value="{NonExistentModel>PropertyName}"/>
								</form:FormElement>
							</form:FormContainer>
						</form:formContainers>
					</form:Form>
				</sap.ui.layout:VerticalLayout>
			</sap.ui.layout:VerticalLayout>
		</content>
	</Page>
</mvc:View>