text:
(function () {
    'use strict';

    describe('statuses', function () {
        var github;
        var token = '44046cd4b4b85afebfe3ccaec13fd8c08cc80aad';

        beforeEach(function () {
            github = new Github();
            client.authenticate({
                type: 'oauth',
                token: token
            });
        });

        it('should successfully execute GET /repos/:user/:repo/statuses/:sha (get)', function (done) {
            var callback = function (err, res) {
                expect(err).toBeNull();
                done();
            };

            github.statuses.get(
                {
                    user: 'String',
                    repo: 'String',
                    sha: 'String'
                },
                callback
            );
        });

        it('should successfully execute POST /repos/:user/:repo/statuses/:sha (create)', function (done) {
            var callback = function (err, res) {
                expect(err).toBeNull();
                done();
            };

            github.statuses.create(
                {
                    user: 'String',
                    repo: 'String',
                    sha: 'String',
                    state: 'String',
                    target_url: 'String',
                    description: 'String'
                },
                callback
            );
        });

    });
}());


text:
import apt
import sys
import subprocess
import argparse
import shutil
import os.path

def configure_client():
    cache = apt.Cache()
    if cache['openvpn'].is_installed:
        # OpenVPN client is already installed! Let's not do anything and move out of the loop
        pass
    else:
        # Oopsie! OpenVPN client is not installed! Let's get on with it, shall we?
        try:
            subprocess.check_call(['apt-get', '--assume-yes', 'install', 'openvpn'])
        except subprocess.CalledProcessError as e:
            print 'Installation failed:', e

    parser = argparse.ArgumentParser(description = 'Accepting source & destination arguments from commandline')
    parser.add_argument('source', metavar = 'SOURCE_PATH', help = 'full path to ipredator conf file')
    parser.add_argument('-d', '--destination', metavar = 'DESTINATION_PATH: OPTIONAL', nargs = '?', default = '/etc/openvpn', help = 'Directory to copy the conf file to. defaults to /etc/openvpn')
    parser.add_argument('user', metavar = 'USERNAME', help = 'IPredator username')
    parser.add_argument('password', metavar = 'PASSWORD', help = 'IPredator password')
    args = parser.parse_args()

    # Copying the IPredator configuration file from source to destination

    try:
        shutil.copy(args.source, args.destination)
    except IOError as e:
        print e

    # Check if update-resolv-conf exists and if it does, append few lines to IPredator-CLI-Password.conf

    if os.path.isfile(args.destination + '/update-resolv-conf'):
        dns_conf = 'script-security 2\nup /etc/openvpn/update-resolv-conf\ndown /etc/openvpn/update-resolv-conf'
        with open(args.destination + '/IPredator-CLI-Password.conf', 'a') as confFile:
            confFile.writelines(dns_conf)
    else:
        sys.exit('update-resolv-conf does not exist!')

    # Creating /etc/openvpn/IPredator.auth file & appending credentials to it

    try:
        subprocess.check_call(['touch', '/etc/openvpn/IPredator.auth'])
    except subprocess.CalledProcessError as e:
        print e

    with open('/etc/openvpn/IPredator.auth', 'w') as authFile:
        authFile.write(args.user + '\n')
        authFile.write(args.password)

    # Changing the ownership and permissions on files

    subprocess.call(['chown', 'root:root', '/etc/openvpn/IPredator-CLI-Password.conf'])
    subprocess.call(['chown', 'root:root', '/etc/openvpn/IPredator.auth'])
    subprocess.call(['chmod', '400', '/etc/openvpn/IPredator-CLI-Password.conf'])
    subprocess.call(['chmod', '400', '/etc/openvpn/IPredator.auth'])

if __name__ == '__main__':
    configure_client()

redpajama_set_name: RedPajamaGithub


text:
namespace Digipost.Signature.Api.Client.Core.Internal.Asice
{
    public class DocumentBundle
    {
        public DocumentBundle(byte[] bundleBytes)
        {
            BundleBytes = bundleBytes;
        }

        public byte[] BundleBytes { get; internal set; }
    }
}


text:
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import Immutable from 'immutable';

import Typeahead from '../src/index';

const { expect } = global;

const SimpleOptionTemplate = (props) => {
  const getStyle = () => {
    if (props.selected) {
      return {
        backgroundColor: 'blue',
        color: 'white',
      };
    }
    return {};
  };

  const getClasses = () => {
    if (props.selected) {
      return 'rtex-option-item rtex-option-selected';
    }
    return 'rtex-option-item';
  };

  return (

      {props.data.name}

);
};

SimpleOptionTemplate.propTypes = {
  selected: React.PropTypes.bool,
  data: React.PropTypes.object,
};

const documentEventsMap = {};

beforeEach(() => {
  sinon.stub(console, 'error').callsFake((warning) => { throw new Error(warning); });
  sinon.stub(document, 'addEventListener').callsFake((event, cb) => {
    documentEventsMap[event] = cb;
  });
});

afterEach(() => {
  /* eslint-disable no-console */
  console.error.restore();
  /* eslint-enable no-console */
  document.addEventListener.restore();
});

it('Typeahead should raise error on ignoring optionTemplate prop', () => {
  try {
    mount(<Typeahead />);
  } catch (e) {
    expect(e.message).toContain('`optionTemplate` is marked as required');
  }
});

it('Typeahead should raise error on ignoring displayKey prop', () => {
  try {
    const templateFn = () => null;
    mount(<Typeahead optionTemplate={templateFn} />);
  } catch (e) {
    expect(e.message).toContain('`displayKey` is marked as required');
  }
});

it('Typeahead should display value', () => {
  const templateFn = () => null;
  const component = mount(
    <Typeahead
      value="test"
      displayKey={'name'}
      optionTemplate={templateFn}
    />);
  expect(component.find('.rtex-input').props().value).toEqual('test');
});

it('Typeahead should hide/display spinner', () => {
  const templateFn = () => null;
  const component = mount(
    <Typeahead
      value="test"
      showLoading
      displayKey={'name'}
      optionTemplate={templateFn}
    />);
  expect(component.find('.rtex-spinner').length).toEqual(1);

  component.setProps({ showLoading: false });

  expect(component.find('.rtex-spinner').length).toEqual(0);
});

it('Typeahead should not raise onFetchData for not empty value', () => {
  const templateFn = () => null;

  const onFetchData = sinon.spy();

  mount(
    <Typeahead
      value="fetch"
      showLoading
      debounceRate={0}
      displayKey={'name'}
      optionTemplate={templateFn}
      onFetchData={onFetchData}
    />);

  expect(onFetchData.called).toBeTruthy();
});

it('Typeahead should raise onChange when value changed', () => {
  const templateFn = () => null;
  const onChange = sinon.spy();

  const component = mount(
    <Typeahead
      value="change"
      showLoading
      displayKey={'name'}
      optionTemplate={templateFn}
      onChange={onChange}
    />);

  const event = { target: { value: 'value changed' } };
  component.find('.rtex-input').at(0).simulate('change', event);
  expect(onChange.called).toBeTruthy();
});

it('Typeahead should show list of items when Down Arrow key presses', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="change"
      showLoading
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  component.find('.rtex-input').at(0).simulate('keyDown', { key: 'ArrowDown' });
  const container = component.find('.rtex-is-open');
  expect(container.length).toEqual(1);
  const items = container.find('.rtex-option-item');
  expect(items.length).toEqual(3);
});

it('Typeahead should move selection for item when ArrowDown pressed', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value=""
      showLoading
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const selectedItem1 = component.find('.rtex-is-open .rtex-option-selected');
  expect(selectedItem1.text()).toEqual('value 1');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const selectedItem2 = component.find('.rtex-is-open .rtex-option-selected');
  expect(selectedItem2.text()).toEqual('value 2');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const selectedItem3 = component.find('.rtex-is-open .rtex-option-selected');
  expect(selectedItem3.text()).toEqual('value 3');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const selectedItem1Again = component.find('.rtex-is-open .rtex-option-selected');
  expect(selectedItem1Again.text()).toEqual('value 1');
});

it('Typeahead should move selection for item when ArrowUp pressed', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value=""
      showLoading
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');

  inputComponent.simulate('keyDown', { key: 'ArrowUp' });
  const selectedItem2 = component.find('.rtex-is-open .rtex-option-selected');
  expect(selectedItem2.text()).toEqual('value 2');

  inputComponent.simulate('keyDown', { key: 'ArrowUp' });
  const selectedItem3 = component.find('.rtex-is-open .rtex-option-selected');
  expect(selectedItem3.text()).toEqual('value 1');

  inputComponent.simulate('keyDown', { key: 'ArrowUp' });
  const selectedItem2Again = component.find('.rtex-is-open .rtex-option-selected');
  expect(selectedItem2Again.text()).toEqual('value 3');

  inputComponent.simulate('keyDown', { key: 'ArrowUp' });
  const selectedItem1 = component.find('.rtex-is-open .rtex-option-selected');
  expect(selectedItem1.text()).toEqual('value 2');
});

it('Typeahead should show options on focus and hide options when <Esc> pressed', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="value 1"
      showLoading
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);

  inputComponent.simulate('focus');
  expect(component.find('.rtex-is-open').length).toEqual(1);

  inputComponent.simulate('keyDown', { key: 'Esc' });
  expect(component.find('.rtex-is-open').length).toEqual(0);
});

it('Typeahead should select item by press <Enter>', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="value 1"
      showLoading
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  inputComponent.simulate('keyDown', { key: 'Enter' });
  expect(inputComponent.prop('value')).toEqual('value 2');
  expect(component.find('.rtex-is-open').length).toEqual(0);
});

test('Typeahead should show hint for value', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="valu"
      showLoading
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent = component.find('.rtex-hint').at(0);
  expect(hintComponent.prop('value')).toEqual('value 1');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent2 = component.find('.rtex-hint').at(0);
  expect(hintComponent2.prop('value')).toEqual('value 2');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent3 = component.find('.rtex-hint').at(0);
  expect(hintComponent3.prop('value')).toEqual('value 3');
});

test('Typeahead should not show hint if hint disabled', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="valu"
      showLoading
      hint={false}
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent = component.find('.rtex-hint').at(0);
  expect(hintComponent.prop('value')).toEqual('');
});

test('Typeahead should autocomplete by press <Tab> by hint for value', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="valu"
      showLoading
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent = component.find('.rtex-hint').at(0);
  expect(hintComponent.prop('value')).toEqual('value 2');
  inputComponent.simulate('keyDown', { key: 'Tab' });
  expect(inputComponent.prop('value')).toEqual('value 2');
});

test('Typeahead should autocomplete by press <End> by hint for value', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="valu"
      showLoading
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent = component.find('.rtex-hint').at(0);
  expect(hintComponent.prop('value')).toEqual('value 2');
  inputComponent.simulate('keyDown', { key: 'End' });
  expect(inputComponent.prop('value')).toEqual('value 2');
});

test('Typeahead should not autocomplete by press <Tab> if hint disabled', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="valu"
      showLoading
      hint={false}
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent = component.find('.rtex-hint').at(0);
  expect(hintComponent.prop('value')).toEqual('');
  inputComponent.simulate('keyDown', { key: 'Tab' });
  expect(inputComponent.prop('value')).toEqual('valu');
});

test('Typeahead should not autocomplete by press <End> if hint disabled', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="valu"
      showLoading
      hint={false}
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent = component.find('.rtex-hint').at(0);
  expect(hintComponent.prop('value')).toEqual('');
  inputComponent.simulate('keyDown', { key: 'End' });
  expect(inputComponent.prop('value')).toEqual('valu');
});

test('Typeahead should select option by click on it', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value="valu"
      showLoading
      hint={false}
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');
  const container = component.find('.rtex-is-open');
  container.find('.rtex-option-item').at(1).simulate('click', {
    nativeEvent: { stopImmediatePropagation: () => {} },
  });
  expect(inputComponent.prop('value')).toEqual('value 2');
  const containerClosed = component.find('.rtex-is-open');
  expect(containerClosed.length).toEqual(0);
});

test('Typeahead should close option list if click on different div', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(

      <Typeahead
        value="valu"
        showLoading
        hint={false}
        displayKey={'name'}
        options={options}
        optionTemplate={SimpleOptionTemplate}
      />

);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  expect(component.find('.rtex-is-open').length).toEqual(1);

  documentEventsMap.click();

  expect(component.find('.rtex-is-open').length).toEqual(0);
});

test('Typeahead should move spinner to left for RTL when chnage event raised', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  sinon.stub(window, 'getComputedStyle').callsFake(() => ({ direction: 'rtl' }));

  const component = mount(

      <Typeahead
        value="valu"
        showLoading
        hint={false}
        displayKey={'name'}
        options={options}
        optionTemplate={SimpleOptionTemplate}
      />

);
  const event = { target: { value: 'value changed' } };
  component.find('.rtex-input').at(0).simulate('change', event);

  window.getComputedStyle.restore();

  expect(component.find('.rtex-spinner').prop('dir')).toEqual('rtl');
});

test('Typeahead should move spinner to left for RTL when new props sets', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  sinon.stub(window, 'getComputedStyle').callsFake(() => ({ direction: 'rtl' }));

  const component = mount(
    <Typeahead
      value="valu"
      showLoading
      hint={false}
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  component.setProps({ value: 'value 1' });

  window.getComputedStyle.restore();

  expect(component.find('.rtex-spinner').prop('dir')).toEqual('rtl');
});

test('Typeahead should set default value for minLength', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value=""
      showLoading
      hint={false}
      displayKey={'name'}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  expect(component.prop('minLength')).toEqual(1);
});

test('Typeahead should raise Fetch event if value >= minLength', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const onFetchData = sinon.spy();

  const component = mount(
    <Typeahead
      value=""
      showLoading
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      onFetchData={onFetchData}
    />);

  const event = { target: { value: 'v' } };
  component.find('.rtex-input').at(0).simulate('change', event);

  expect(onFetchData.callCount).toEqual(0);

  const event2 = { target: { value: 'val' } };
  component.find('.rtex-input').at(0).simulate('change', event2);

  expect(onFetchData.callCount).toEqual(0);

  const event3 = { target: { value: 'valu' } };
  component.find('.rtex-input').at(0).simulate('change', event3);

  expect(onFetchData.callCount).toEqual(1);

  const event4 = { target: { value: 'value' } };
  component.find('.rtex-input').at(0).simulate('change', event4);

  expect(onFetchData.callCount).toEqual(2);
});

test('Typeahead should receive rateLimitBy types ["none", "trottle", "debounce"]', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  expect(component.prop('rateLimitBy')).toEqual('none');

  expect(() => {
    component.setProps({ rateLimitBy: 'trottle' });
  }).not.toThrow();
  expect(component.prop('rateLimitBy')).toEqual('trottle');

  expect(() => {
    component.setProps({ rateLimitBy: 'debounce' });
  }).not.toThrow();
  expect(component.prop('rateLimitBy')).toEqual('debounce');

  expect(() => {
    component.setProps({ rateLimitBy: 'none' });
  }).not.toThrow();
  expect(component.prop('rateLimitBy')).toEqual('none');

  expect(() => {
    component.setProps({ rateLimitBy: 'unknown' });
  }).toThrowError(/Invalid prop `rateLimitBy` of value `unknown`/);
});

test('Typeahead should set rateLimitWait as number', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
    />);

  // check default value
  expect(component.prop('rateLimitWait')).toEqual(100);

  expect(() => {
    component.setProps({ rateLimitWait: '100' });
  }).toThrowError(/Invalid prop `rateLimitWait` of type `string`/);
});

test('Typeahead check debounce rateLimitBy', (done) => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const onFetchData = sinon.spy();

  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'debounce'}
      onFetchData={onFetchData}
    />);

  const typeData = 'value 1 testing debounce';
  for (let i = 1; i < (typeData.length - 1); i += 1) {
    const event = { target: { value: typeData.substring(0, i) } };
    component.find('.rtex-input').at(0).simulate('change', event);
  }

  setTimeout(() => {
    try {
      expect(onFetchData.callCount).toBeLessThanOrEqual(1);
      done();
    } catch (e) {
      done.fail(e);
    }
  }, 201);
});

test('Typeahead check trottle rateLimitBy', (done) => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const onFetchData = sinon.spy();

  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'trottle'}
      onFetchData={onFetchData}
    />);

  const typeData = 'value 1 testing !';
  for (let i = 1; i < (typeData.length - 1); i += 1) {
    const event = { target: { value: typeData.substring(0, i) } };
    component.find('.rtex-input').at(0).simulate('change', event);
  }

  setTimeout(() => {
    try {
      expect(onFetchData.callCount).toBeLessThanOrEqual(3);
      done();
    } catch (e) {
      done.fail(e);
    }
  }, 201);
});

test('Typeahead check "none" rateLimitBy', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const onFetchData = sinon.spy();

  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      onFetchData={onFetchData}
    />);

  const typeData = 'value 1 testing!';
  const input = component.find('.rtex-input').at(0);
  for (let i = 0, len = typeData.length; i < len; i += 1) {
    input.simulate('change', { target: { value: typeData.substring(0, i) } });
  }

  expect(onFetchData.callCount).toEqual(12);
});

test('Typeahead check showEmpty', () => {
  const options = [];

  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      showEmpty
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');

  const emptyContainer = component.find('.rtex-is-open .rtex-empty');
  expect(emptyContainer.length).toEqual(1);
  expect(emptyContainer.text()).toEqual('No items');

  component.setProps({ showEmpty: false });

  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(0);
});

test('Typeahead check showEmpty with custom template', () => {
  const options = [];

  const EmptyTemplate = () => (
Custom empty template
);

  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      emptyTemplate={EmptyTemplate}
      showEmpty
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');

  const emptyContainer = component.find('.rtex-is-open .rtex-empty');
  expect(emptyContainer.length).toEqual(1);
  expect(emptyContainer.text()).toEqual('Custom empty template');

  component.setProps({ showEmpty: false });

  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(0);
});

test('Typeahead check hide empty custom template with <Esc>', () => {
  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={[]}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      showEmpty
    />);

  let inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');

  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(1);

  inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('keyDown', { key: 'Esc' });

  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(0);
});

test('Typeahead check not show empty template if items present', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      showEmpty
    />);

  const inputComponent = component.find('.rtex-input').at(0);

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });

  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(0);
  expect(component.find('.rtex-is-open').length).toEqual(1);
});

test('Typeahead check show template with <DownArrow>', () => {
  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={[]}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      showEmpty
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(1);

  inputComponent.simulate('keyDown', { key: 'Esc' });
  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(0);

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(1);
});

test('Typeahead check show template on focused input', () => {
  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={[]}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      showEmpty
    />);

  const inputComponent = component.find('.rtex-input').at(0);

  inputComponent.simulate('focus');
  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(1);
});

test('Typeahead check close empty template by click outside of component', () => {
  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={[]}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      showEmpty
    />);

  const inputComponent = component.find('.rtex-input').at(0);

  inputComponent.simulate('focus');
  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(1);

  documentEventsMap.click();

  expect(component.find('.rtex-is-open .rtex-empty').length).toEqual(0);
});

test('Typeahead check showing placeholder', () => {
  const PlaceholderText = 'Placeholder for input';
  const component = mount(
    <Typeahead
      value=""
      hint={false}
      displayKey={'name'}
      minLength={4}
      options={[]}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      showEmpty
      placeholder={PlaceholderText}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  expect(inputComponent.prop('placeholder')).toEqual(PlaceholderText);
});

test('Typeahead check not showing placeholder if hint value present', () => {
  const options = [
    { id: 1, name: 'value 1' },
    { id: 2, name: 'value 2' },
    { id: 3, name: 'value 3' },
  ];

  const PlaceholderText = 'Placeholder for input';
  const component = mount(
    <Typeahead
      value="valu"
      hint
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      placeholder={PlaceholderText}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });

  const hintComponent = component.find('.rtex-hint').at(0);
  expect(hintComponent.prop('value')).toEqual('value 1');

  expect(component.find('.rtex-input').at(0).prop('placeholder')).toEqual('');
});

test('Typeahead should work with Immutable Record', () => {
  const Item = Immutable.Record({ id: 0, name: '' });
  const options = Immutable.List([
    new Item({ id: 1, name: 'value 1' }),
    new Item({ id: 2, name: 'value 2' }),
    new Item({ id: 3, name: 'value 3' }),
  ]);

  const PlaceholderText = 'Placeholder for input';
  const component = mount(
    <Typeahead
      value=""
      hint
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      placeholder={PlaceholderText}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('keyDown', { key: 'ArrowDown' });

  expect(component.find('.rtex-option-item').length).toEqual(3);
});

test('Typeahead should select item of Immutable Record', () => {
  const Item = Immutable.Record({ id: 0, name: '' });
  const options = Immutable.List([
    new Item({ id: 1, name: 'value 1' }),
    new Item({ id: 2, name: 'value 2' }),
    new Item({ id: 3, name: 'value 3' }),
  ]);

  const PlaceholderText = 'Placeholder for input';
  const component = mount(
    <Typeahead
      value=""
      hint
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      placeholder={PlaceholderText}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  inputComponent.simulate('focus');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const selectedItem = component.find('.rtex-option-item .rtex-option-selected');
  expect(selectedItem.text()).toEqual('value 1');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const selectedItem2 = component.find('.rtex-option-item .rtex-option-selected');
  expect(selectedItem2.text()).toEqual('value 2');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const selectedItem3 = component.find('.rtex-option-item .rtex-option-selected');
  expect(selectedItem3.text()).toEqual('value 3');
});

test('Typeahead should choose item of Immutable Record by press <Enter>', () => {
  const Item = Immutable.Record({ id: 0, name: '' });
  const options = Immutable.List([
    new Item({ id: 1, name: 'value 1' }),
    new Item({ id: 2, name: 'value 2' }),
    new Item({ id: 3, name: 'value 3' }),
  ]);

  const PlaceholderText = 'Placeholder for input';
  const component = mount(
    <Typeahead
      value=""
      hint
      displayKey={'name'}
      minLength={4}
      options={options}
      optionTemplate={SimpleOptionTemplate}
      rateLimitBy={'none'}
      placeholder={PlaceholderText}
    />);

  const inputComponent = component.find('.rtex-input').at(0);
  expect(inputComponent.prop('value')).toEqual('');
  inputComponent.simulate('focus');

  inputComponent.simulate('keyDown', { key: 'ArrowDown' });
  const selectedItem = component.find('.rtex-option-item .rtex-option-selected');
  expect(selectedItem.text()).toEqual('value 1');

  inputComponent.simulate('keyDown', { key: 'Enter' });
  expect(component.find('.rtex-input').at(0).prop('value')).toEqual('value 1');
});

test('Typeahead should receive any type in value', () => {
  const templateFn = () => null;
  expect(() => {
    mount(
      <Typeahead
        value={123}
        displayKey={'name'}
        optionTemplate={templateFn}
      />);
  }).not.toThrow();
});

test('Typeahead should correctly show hint', () => {
  const component = mount(
    <Typeahead
      value={12}
      hint
      options={[{ id: 123, name: 'aaaaaa' }]}
      displayKey={'id'}
      optionTemplate={SimpleOptionTemplate}
    />);

  component.find('.rtex-input').simulate('focus');

  expect(component.find('.rtex-is-open').length).toEqual(1);
  expect(component.find('.rtex-option-item').length).toEqual(1);

  const input = component.find('.rtex-input').at(0);
  input.simulate('keyDown', { key: 'ArrowDown' });
  const hintComponent = component.find('.rtex-hint').at(0);
  expect(hintComponent.prop('value')).toEqual('123');
});

test('Typeahead should correctly receive Object or array', () => {
  const component = mount(
    <Typeahead
      value={{ id: 1, name: 'test' }}
      hint
      options={[]}
      displayKey={'id'}
      optionTemplate={SimpleOptionTemplate}
    />);

  expect(component.find('.rtex-input').props().value).toEqual('[object Object]');

  component.setProps({ value: [1, 2, 3] });

  expect(component.find('.rtex-input').props().value).toEqual('1,2,3');
});

test('Typeahead should correctly update values and trigger events for 2 elements', () => {
  /* eslint-disable no-undef */
  const fetchSecond = jest.fn();
  const fetchFirst = jest.fn();
  const changeSecond = jest.fn();
  const changeFirst = jest.fn();
  /* eslint-enable no-undef */

  const component = mount(

      <Typeahead
        hint
        className="first"
        value=""
        options={[]}
        onFetchData={fetchFirst}
        onChange={changeFirst}
        displayKey={'id'}
        optionTemplate={SimpleOptionTemplate}
      />

      <Typeahead
        hint
        className="second"
        value=""
        options={[]}
        onFetchData={fetchSecond}
        onChange={changeSecond}
        displayKey={'name'}
        optionTemplate={SimpleOptionTemplate}
      />

);

  component.find('.first.rtex-input').simulate('change', { target: { value: 'info' } });
  expect(component.find('.first.rtex-input').props().value).toEqual('info');
  expect(fetchFirst).toHaveBeenCalledTimes(1);
  expect(changeFirst).toHaveBeenCalledTimes(1);
  expect(changeFirst.mock.calls[0][0].target).toEqual({ value: 'info' });

  component.find('.second.rtex-input').simulate('change', { target: { value: 12 } });
  expect(component.find('.second.rtex-input').props().value).toEqual('12');
  expect(fetchSecond).toHaveBeenCalledTimes(1);
  expect(changeSecond).toHaveBeenCalledTimes(1);
  expect(changeSecond.mock.calls[0][0].target).toEqual({ value: 12 });
});

test('Typeahead should correctly trigger onOptionClick value for 2 typeahead', () => {
  /* eslint-disable no-undef */
  const optionClickSecond = jest.fn();
  const optionClickFirst = jest.fn();
  /* eslint-enable no-undef */

  const component = mount(

        <Typeahead
          hint
          className="first"
          value=""
          options={[{ id: 1, name: 'Item 1' }, { id: 1, name: 'Item 2' }]}
          displayKey={'id'}
          onOptionClick={optionClickFirst}
          optionTemplate={SimpleOptionTemplate}
        />

        <Typeahead
          hint
          className="second"
          value=""
          options={[{ id: 10, name: 'Item 10' }, { id: 11, name: 'Item 11' }]}
          displayKey={'name'}
          onOptionClick={optionClickSecond}
          optionTemplate={SimpleOptionTemplate}
        />

);

  const input = component.find('.first.rtex-input');
  input.simulate('focus');
  input.simulate('keyDown', { key: 'ArrowDown' });
  const container = component.find('.first_block .rtex-is-open');
  const items = container.find('.rtex-option-item');

  expect(items.length).toEqual(2);
  items.at(0).simulate('click', { nativeEvent: { stopImmediatePropagation: () => {} } });
  expect(optionClickFirst).toBeCalledWith({ id: 1, name: 'Item 1' }, 0);
  expect(optionClickFirst).toHaveBeenCalledTimes(1);
  expect(input.props().value).toEqual('1');

  const input2 = component.find('.second.rtex-input');
  input2.simulate('focus');
  input2.simulate('keyDown', { key: 'ArrowDown' });
  const container2 = component.find('.second_block .rtex-is-open');
  const items2 = container2.find('.rtex-option-item');

  expect(items2.length).toEqual(2);
  items2.at(0).simulate('click', { nativeEvent: { stopImmediatePropagation: () => {} } });
  expect(optionClickSecond).toBeCalledWith({ id: 10, name: 'Item 10' }, 0);
  expect(optionClickSecond).toHaveBeenCalledTimes(1);
  expect(input2.props().value).toEqual('Item 10');
});

test('Typeahead should correctly trigger onOptionChange value for 2 typeahead', () => {
  /* eslint-disable no-undef */
  const optionOptionChangeSecond = jest.fn();
  const optionOptionChangeFirst = jest.fn();
  /* eslint-enable no-undef */

  const component = mount(

        <Typeahead
          hint
          className="first"
          value=""
          options={[{ id: 1, name: 'Item 1' }, { id: 1, name: 'Item 2' }]}
          displayKey={'id'}
          onOptionChange={optionOptionChangeFirst}
          optionTemplate={SimpleOptionTemplate}
        />

        <Typeahead
          hint
          className="second"
          value=""
          options={[{ id: 10, name: 'Item 10' }, { id: 11, name: 'Item 11' }]}
          displayKey={'name'}
          onOptionChange={optionOptionChangeSecond}
          optionTemplate={SimpleOptionTemplate}
        />

);

  const input = component.find('.first.rtex-input');
  input.simulate('focus');
  input.simulate('keyDown', { key: 'ArrowDown' });
  input.simulate('keyDown', { key: 'Enter' });

  expect(optionOptionChangeFirst).toBeCalledWith({ id: 1, name: 'Item 1' }, 0);
  expect(optionOptionChangeFirst).toHaveBeenCalledTimes(1);
  expect(input.props().value).toEqual('1');

  const input2 = component.find('.second.rtex-input');
  input2.simulate('focus');
  input2.simulate('keyDown', { key: 'ArrowDown' });
  input2.simulate('keyDown', { key: 'Enter' });

  expect(optionOptionChangeSecond).toBeCalledWith({ id: 10, name: 'Item 10' }, 0);
  expect(optionOptionChangeSecond).toHaveBeenCalledTimes(1);
  expect(input2.props().value).toEqual('Item 10');
});


text:
<?php

/**
 * Plus Directional Indicator
 *
 * @phpstub
 *
 * @param array $high
 * @param array $low
 * @param array $close
 * @param integer $timePeriod
 *
 * @return array Returns an array with calculated data or false on failure.
 */
function trader_plus_di($high, $low, $close, $timePeriod = NULL)
{
}


text:
GeoServer-Datenverzeichnis auslagern
====================================

Es wird empfohlen das GeoServer-Datenverzeichnis (siehe [hier](../basics/folderstructure.md))
auszulagern. Der entscheidende Vorteil besteht darin, dass sich etwa ein GeoServer
im Produktivbetrieb auf diese Weise elegant zu einer aktuelleren Version updaten
lässt, ohne dass die Daten/Konfigurationen des GeoServers verloren gehen bzw.
separat gesichert werden müssen.

Um das Datenverzeichnis auszulagern, führen Sie die folgenden Schritte durch:

1. Wir kopieren das bestehende Datenverzeichnis aus der GeoServer-Installation
   (data\_dir/) in ein neues Verzeichnis (gs\_data\_dir/) in unserem Home-Verzeichnis,
   welches anschließend als Datenverzeichnis des GeoServers verwendet werden soll:

<xmp style="margin:0; font-size: .85em;">cp -r {{ book.geoServerPhysicalPath}}data_dir/ /home/user/gs_data_dir
</xmp>

2. Das Datenverzeichnis des GeoServers wird über die Umgebungsvariable (GEOSERVER\_DATA\_DIR)
  gesteuert. Bei einer klassischen WAR-Installation, etwa auf einem Tomcat, kann
  dieser Wert in der Datei (`web.xml`) gesetzt werden. Im Falle der OSGeoLive müssen
  wir diese Variable jedoch im Startup-Skript des GeoServers setzen. Führen Sie
  bitte den folgenden Befehl aus, um das Skript startup.sh mit dem Texteditor
  *leafpad* und den benötigten root-Rechten zu öffnen:

<xmp style="margin:0; font-size: .85em;">sudo leafpad {{ book.geoServerPhysicalPath}}bin/startup.sh
</xmp>

3. Fügen Sie an den Anfang der Datei folgende Zuweisung ein, um das in Schritt 1
   erstellte Verzeichnis als GeoServer-Datenverzeichnis zu verwenden (und
   speichern Sie anschließend die Datei):
```
GEOSERVER_DATA_DIR=/home/user/gs_data_dir
```
4. Starten Sie den GeoServer neu und beobachten Sie anschließend im Abschnitt
   *Serverstatus*, wie sich der Pfad des Datenverzeichnisses verändert hat.
![](../assets/data_dir.png)

> **note**
>
> Analog zur obigen Konfiguration kann auch das Verzeichnis für den GeoWebCache
> (GWC) gesteuert werden. In diesem Fall muss die Variable GEOWEBCACHE\_CACHE\_DIR gesetzt werden.

Der folgende [Abschnitt](gui.md) liefert wertvolle Hinweise zur
Problemlösung und Performanceoptimierung für den GeoServer im Produktivbetrieb.


text:
package dump

import (
	"container/heap"
	"sort"
	"strconv"
	"strings"

	"github.com/xueqiu/rdr/decoder"
)

// NewCounter return a pointer of Counter
func NewCounter() *Counter {
	h := &entryHeap{}
	heap.Init(h)
	p := &prefixHeap{}
	heap.Init(p)
	return &Counter{
		largestEntries:     h,
		largestKeyPrefixes: p,
		lengthLevel0:       100,
		lengthLevel1:       1000,
		lengthLevel2:       10000,
		lengthLevel3:       100000,
		lengthLevel4:       1000000,
		lengthLevelBytes:   map[typeKey]uint64{},
		lengthLevelNum:     map[typeKey]uint64{},
		keyPrefixBytes:     map[typeKey]uint64{},
		keyPrefixNum:       map[typeKey]uint64{},
		typeBytes:          map[string]uint64{},
		typeNum:            map[string]uint64{},
		separators:         ":;,_- ",
		slotBytes:          map[int]uint64{},
		slotNum:            map[int]uint64{},
	}
}

// Counter for redis memory useage
type Counter struct {
	largestEntries     *entryHeap
	largestKeyPrefixes *prefixHeap
	lengthLevel0       uint64
	lengthLevel1       uint64
	lengthLevel2       uint64
	lengthLevel3       uint64
	lengthLevel4       uint64
	lengthLevelBytes   map[typeKey]uint64
	lengthLevelNum     map[typeKey]uint64
	keyPrefixBytes     map[typeKey]uint64
	keyPrefixNum       map[typeKey]uint64
	separators         string
	typeBytes          map[string]uint64
	typeNum            map[string]uint64
	slotBytes          map[int]uint64
	slotNum            map[int]uint64
}

// Count by various dimensions
func (c *Counter) Count(in <-chan *decoder.Entry) {
	for e := range in {
		c.count(e)
	}
	// get largest prefixes
	c.calcuLargestKeyPrefix(1000)
}

// GetLargestEntries from heap, num max is 500
func (c *Counter) GetLargestEntries(num int) []*decoder.Entry {
	res := []*decoder.Entry{}

	// get a copy of c.largestEntries
	for i := 0; i < c.largestEntries.Len(); i++ {
		entries := *c.largestEntries
		res = append(res, entries[i])
	}
	sort.Sort(sort.Reverse(entryHeap(res)))
	if num < len(res) {
		res = res[:num]
	}
	return res
}

//GetLargestKeyPrefixes from heap
func (c *Counter) GetLargestKeyPrefixes() []*PrefixEntry {
	res := []*PrefixEntry{}

	// get a copy of c.largestKeyPrefixes
	for i := 0; i < c.largestKeyPrefixes.Len(); i++ {
		entries := *c.largestKeyPrefixes
		res = append(res, entries[i])
	}
	sort.Sort(sort.Reverse(prefixHeap(res)))
	return res
}

// GetLenLevelCount from map
func (c *Counter) GetLenLevelCount() []*PrefixEntry {
	res := []*PrefixEntry{}

	// get a copy of lengthLevelBytes and lengthLevelNum
	for key := range c.lengthLevelBytes {
		entry := &PrefixEntry{}
		entry.Type = key.Type
		entry.Key = key.Key
		entry.Bytes = c.lengthLevelBytes[key]
		entry.Num = c.lengthLevelNum[key]
		res = append(res, entry)
	}
	return res
}

func (c *Counter) count(e *decoder.Entry) {
	c.countLargestEntries(e, 500)
	c.countByType(e)
	c.countByLength(e)
	c.countByKeyPrefix(e)
	c.countBySlot(e)
}

func (c *Counter) countLargestEntries(e *decoder.Entry, num int) {
	heap.Push(c.largestEntries, e)
	l := c.largestEntries.Len()
	if l > num {
		heap.Pop(c.largestEntries)
	}
}

func (c *Counter) countByLength(e *decoder.Entry) {
	key := typeKey{
		Type: e.Type,
		Key:  strconv.FormatUint(c.lengthLevel0, 10),
	}

	add := func(c *Counter, key typeKey, e *decoder.Entry) {
		c.lengthLevelBytes[key] += e.Bytes
		c.lengthLevelNum[key]++
	}

	// must lengthLevel4 > lengthLevel3 > lengthLevel2 ...
	if e.NumOfElem > c.lengthLevel4 {
		key.Key = strconv.FormatUint(c.lengthLevel4, 10)
		add(c, key, e)
	} else if e.NumOfElem > c.lengthLevel3 {
		key.Key = strconv.FormatUint(c.lengthLevel3, 10)
		add(c, key, e)
	} else if e.NumOfElem > c.lengthLevel2 {
		key.Key = strconv.FormatUint(c.lengthLevel2, 10)
		add(c, key, e)
	} else if e.NumOfElem > c.lengthLevel1 {
		key.Key = strconv.FormatUint(c.lengthLevel1, 10)
		add(c, key, e)
	} else if e.NumOfElem > c.lengthLevel0 {
		key.Key = strconv.FormatUint(c.lengthLevel0, 10)
		add(c, key, e)
	}
}

func (c *Counter) countByType(e *decoder.Entry) {
	c.typeNum[e.Type]++
	c.typeBytes[e.Type] += e.Bytes
}

func (c *Counter) countByKeyPrefix(e *decoder.Entry) {
	// reset all numbers to 0
	k := strings.Map(func(c rune) rune {
		if c >= 48 && c <= 57 { //48 == "0" 57 == "9"
			return '0'
		}
		return c
	}, e.Key)
	prefixes := getPrefixes(k, c.separators)
	key := typeKey{
		Type: e.Type,
	}
	for _, prefix := range prefixes {
		if len(prefix) == 0 {
			continue
		}
		key.Key = prefix
		c.keyPrefixBytes[key] += e.Bytes
		c.keyPrefixNum[key]++
	}
}

func (c *Counter) countBySlot(e *decoder.Entry) {
	if len(e.Key) > 0 {
		slot := Slot(e.Key)

		c.slotNum[slot]++
		c.slotBytes[slot] += e.Bytes
	}
}

func (c *Counter) calcuLargestKeyPrefix(num int) {
	for key := range c.keyPrefixBytes {
		k := &PrefixEntry{}
		k.Type = key.Type
		k.Key = key.Key
		k.Bytes = c.keyPrefixBytes[key]
		k.Num = c.keyPrefixNum[key]
		delete(c.keyPrefixBytes, key)
		delete(c.keyPrefixNum, key)

		heap.Push(c.largestKeyPrefixes, k)
		l := c.largestKeyPrefixes.Len()
		if l > num {
			heap.Pop(c.largestKeyPrefixes)
		}
	}
}

type entryHeap []*decoder.Entry

func (h entryHeap) Len() int {
	return len(h)
}
func (h entryHeap) Less(i, j int) bool {
	return h[i].Bytes < h[j].Bytes
}
func (h entryHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *entryHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func (h *entryHeap) Push(e interface{}) {
	*h = append(*h, e.(*decoder.Entry))
}

type typeKey struct {
	Type string
	Key  string
}

type prefixHeap []*PrefixEntry

// PrefixEntry record value by prefix
type PrefixEntry struct {
	typeKey
	Bytes uint64
	Num   uint64
}

func (h prefixHeap) Len() int {
	return len(h)
}
func (h prefixHeap) Less(i, j int) bool {
	if h[i].Bytes < h[j].Bytes {
		return true
	} else if h[i].Bytes == h[j].Bytes {
		if h[i].Num < h[j].Num {
			return true
		} else if h[i].Num == h[j].Num {
			if h[i].Key > h[j].Key {
				return true
			}
		}
	}
	return false

}
func (h prefixHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *prefixHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func (h *prefixHeap) Push(k interface{}) {
	*h = append(*h, k.(*PrefixEntry))
}

func appendIfMissing(slice []int, i int) []int {
	for _, ele := range slice {
		if ele == i {
			return slice
		}
	}
	return append(slice, i)
}

func removeDuplicatesUnordered(elements []string) []string {
	encountered := map[string]bool{}

	// Create a map of all unique elements.
	for v := range elements {
		encountered[elements[v]] = true
	}

	// Place all keys from the map into a slice.
	result := []string{}
	for key := range encountered {
		result = append(result, key)
	}
	return result
}

func getPrefixes(s, sep string) []string {
	res := []string{}
	sepIdx := strings.IndexAny(s, sep)
	if sepIdx < 0 {
		res = append(res, s)
	}
	for sepIdx > -1 {
		r := s[:sepIdx+1]
		if len(res) > 0 {
			r = res[len(res)-1] + s[:sepIdx+1]
		}
		res = append(res, r)
		s = s[sepIdx+1:]
		sepIdx = strings.IndexAny(s, sep)
	}
	// Trim all suffix of separators
	for i := range res {
		for hasAnySuffix(res[i], sep) {
			res[i] = res[i][:len(res[i])-1]
		}
	}
	res = removeDuplicatesUnordered(res)
	return res
}

func hasAnySuffix(s, suffix string) bool {
	for _, c := range suffix {
		if strings.HasSuffix(s, string(c)) {
			return true
		}
	}
	return false
}

// support for sorting of slots
type SlotEntry struct {
	Slot int
	Size uint64
}

type slotHeap []*SlotEntry

func (h slotHeap) Len() int {
	return len(h)
}
func (h slotHeap) Less(i, j int) bool {
	return h[i].Size > h[j].Size
}
func (h slotHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *slotHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func (h *slotHeap) Push(e interface{}) {
	*h = append(*h, e.(*SlotEntry))
}


text:
layout: post
title:  "Circular Matrix"
date:   2015-02-20 23:25:49
---

####Program
to display a circular matrix using Java on BlueJ
import java.io.*;

There you go.


text:
{{ if .Site.Params.widgets.categories }}
{{ if isset .Site.Taxonomies "categories" }}
{{ if not (eq (len .Site.Taxonomies.categories) 0) }}

Kategorien

            {{ range $name, $items := .Site.Taxonomies.categories }}

{{ $name }} ({{ len $items }})

            {{ end }}

{{ end }}
{{ end }}
{{ end }}


text:
module.exports = {
  collectCoverageFrom: [
    '**/*.{js,jsx,ts,tsx}',
    '!**/*.d.ts',
    '!**/node_modules/**',
  ],
  moduleNameMapper: {
    // Handle CSS imports (with CSS modules)
    // https://jestjs.io/docs/webpack#mocking-css-modules
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',

    // Handle CSS imports (without CSS modules)
    '^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',

    // Handle image imports
    // https://jestjs.io/docs/webpack#handling-static-assets
    '^.+\\.(jpg|jpeg|png|gif|webp|svg)$': `<rootDir>/__mocks__/fileMock.js`,

    // Handle module aliases
    '^@/components/(.*)$': '<rootDir>/components/$1',
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  transform: {
    // Use babel-jest to transpile tests with the next/babel preset
    // https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
    '^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
  },
  transformIgnorePatterns: [
    '/node_modules/',
    '^.+\\.module\\.(css|sass|scss)$',
  ],
}


text:
# Structure description

We will use `@colabo-flow/b-audit` puzzle as an example.

+ `params.ts` - contains global parameters of the puzzle used in other files (like the puzzle name, etc)
+ `audit-db-vo.ts` - contains VO (Value Objects) used in the database part of the backend puzzle. Note that isomoprhic VOs are stored in the isomporhipc puzzle (`@colabo-flow/i-audit`)
+ `audit-db-schema.ts` - creates DB (Mongo) Schema for the puzzle, adds all DB plugins, like `pluginAuditing` from `@colabo-knalledge/b-storage-mongo` and provides it to the global space
+ `audit-db.ts` - provides DB access functionality. It is agnostic in a sense that it can be used from the RESTfull API (Express.js) or from a service (through gRPC @ ColaboFlow, or RabbitMQ service, etc)
+ `audit-api.ts` - provides RESTfull (through Express.js framework) interface to the puzzle's business logic

**NOTE 1**: isomoprhic VOs are stored in the isomporhipc puzzle (`@colabo-flow/i-audit` in `colabo/src/isomorphic/dev_puzzles/flow/audit`)

**NOTE 2**: `@colabo-flow/s-audit` puzzle contains ***description*** of the gRPC interface (without implementation)

**NOTE 3**: Service `@colabo-flow/service-audit` (and more specifically `colabo/src/services/services/colaboflow-audit/index.ts`) contains ***implementation*** of the gRPC interface (as an additional interface to the business logic of the `@colabo-flow/b-audit` puzzle)

# Procedure

## 1. Create a backend puzzle

See in the [Example](colabo/src/tools/EXAMPLES.md) an example for the `@colabo-flow/b-audit` puzzle creation, by `colabo` CLI tools.

## 2. Integrate in the backend

Integrate it as an offering and dependency in the `colabo/src/backend/colabo.config.js`
    + then `yarn` it (in `colabo/src/backend`)

## 3. Integrate in the backend app

Integrate it as a dependency in the `colabo/src/backend/apps/colabo-space/colabo.config.js`
    + then `yarn` it (in `colabo/src/backend/apps/colabo-space/`)

## 4. Extend app

In `colabo/src/backend/apps/colabo-space/index.ts`

add new puzzle

```ts
import * as ColaboFlowAudit from '@colabo-flow/b-audit';
ColaboFlowAudit.initialize(expressApp);
```

## 5. Make puzzle's index.ts

In `colabo/src/backend/dev_puzzles/flow/audit/index.ts`:

```ts
// import { ColaboFlowAudit } from './lib/audit';
// it gets all HTTP verb methods (index, post, ...) available
import * as ColaboFlowAuditAPI from './lib/audit';

const API_ROUTE = 'colabo-flow/audit';

export function initialize(app) {
    console.log("[puzzle(colabo-flow/audit) - /index.js] Registering ColaboFlow Audit API to: %s", API_ROUTE);

    var colaboFlowAudit = app.resource(API_ROUTE, ColaboFlowAuditAPI, { id: 'type?/:actionType?/:searchParam?' });
}
```

## 6. Make puzzle's business logic

In `colabo/src/backend/dev_puzzles/flow/audit/lib/audit.ts`:

```ts
const MODULE_NAME: string = "@colabo-flow/b-audit";

import { AuditedAction } from '@colabo-flow/i-audit';

import { GetPuzzle } from '@colabo-utils/i-config';
let puzzleConfig: any = GetPuzzle(MODULE_NAME);

var accessId = 0;

function resSendJsonProtected(res, data) {
    // http://tobyho.com/2011/01/28/checking-types-in-javascript/
    if (data !== null && typeof data === 'object') { // http://stackoverflow.com/questions/8511281/check-if-a-variable-is-an-object-in-javascript
        res.set('Content-Type', 'application/json');
        // JSON Vulnerability Protection
        // http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/
        // https://docs.angularjs.org/api/ng/service/$http#description_security-considerations_cross-site-request-forgery-protection
        res.send(")]}',\n" + JSON.stringify(data));
    } else if (typeof data === 'string') { // http://stackoverflow.com/questions/4059147/check-if-a-variable-is-a-string
        res.send(data);
    } else {
        res.send(data);
    }
};

export class ColaboFlowAudit {

    constructor(protected req: any, protected res: any) {

    }

    index(callback: Function = null) {
        let result = "Hello from audit";

        // TODO: read audits from the database

        if (result) {
            if (callback) callback(null, result);
            if (this.res) resSendJsonProtected(this.res, { data: result, accessId: accessId, success: true });
        } else {
            let msg = "Missing result";
            let err = {
                content: msg
            };
            if (callback) callback(err, null);
            if (this.res) resSendJsonProtected(this.res, { data: null, accessId: accessId, success: false, msg: msg });
        }
    }

    create(callback: Function = null) {
        // create audit in the db
        // let audit: AuditedAction = {
        //     _id: "ffffffffffff"
        // };

        let body: string = this.req.body;
        console.log("[ColaboFlowAudit.post] body: %s", JSON.stringify(body));
        let result:any = {
            // db: audit,
            body: body
        }
        if (callback) callback(null, result);
        if (this.res) resSendJsonProtected(this.res, { data: result, accessId: accessId, success: true });
    }
} // CLASS END

// curl -v -H "Content-Type: application/json" -X GET http://127.0.0.1:8001/colabo-flow/audit/type-right/action-single/test1.json

export function index(req: any, res: any) {
    let colaboFlowAudit: ColaboFlowAudit = new ColaboFlowAudit(req, res);
    colaboFlowAudit.index();
}

/*
curl -i -X POST \
-H "Content-Type: application/json" \
--data '{"name":"Donald","surname":"Duck"}' \
http://localhost:8001/colabo-flow/audit
*/

// https://stackoverflow.com/questions/15651510/can-typescript-export-a-function
// https://www.sitepoint.com/understanding-module-exports-exports-node-js/

export function create(req: any, res: any) {
    let colaboFlowAudit: ColaboFlowAudit = new ColaboFlowAudit(req, res);
    colaboFlowAudit.create();
}
```

## 7. Build puzzle

```sh
cd colabo/src/backend/dev_puzzles/flow/audit
tsc
```

## 8. Build backend app

```sh
cd colabo/src/backend/apps/colabo-space
tsc
```

## 9. Run backend app

```sh
cd colabo/src/backend/apps/colabo-space
npm start
```


text:
echo_status() {
  local args="${@}"
  tput setaf 4
  tput bold
  echo -e "- $args"
  tput sgr0
}

db_max_count=24;
no_daemon=true;
skip_perm=false;
test=false;
USAGE="USAGE: . run.sh [options]
OPTIONS:
--background              \t run supervisord in background.
--skip-perm               \t skip fixing permissions step.
--db-max-count <INT>      \t number of attempt to connect to the database. Default is at 24.
--test                    \t only run test.
"

while [[ $# -gt 0 ]]; do
  case $1 in
    --skip-perm)
      skip_perm=true;
    ;;
    --background)
      no_daemon=false;
    ;;
    --db-max-count)
      shift # shift from key to value
      db_max_count=$1;
    ;;
    --test)
      test=true;
    ;;
    *)
      echo -e "${USAGE}"
      return 0
  esac
  shift
done

echo_status "Starting up..."

# Create Salt Config
echo "file_client: local" > /etc/salt/minion
echo "postgres.host: '${TETHYS_DB_HOST}'" >> /etc/salt/minion
echo "postgres.port: '${TETHYS_DB_PORT}'" >> /etc/salt/minion
echo "postgres.user: '${TETHYS_DB_USERNAME}'" >> /etc/salt/minion
echo "postgres.pass: '${TETHYS_DB_PASSWORD}'" >> /etc/salt/minion
echo "postgres.bins_dir: '${CONDA_HOME}/envs/${CONDA_ENV_NAME}/bin'" >> /etc/salt/minion

if [[ $test = false ]]; then
  # Set extra ENVs
  export NGINX_USER=$(grep 'user .*;' /etc/nginx/nginx.conf | awk '{print $2}' | awk -F';' '{print $1}')

  # Apply States
  echo_status "Checking if DB is ready"

  db_check_count=0

  until ${CONDA_HOME}/envs/${CONDA_ENV_NAME}/bin/pg_isready -h ${TETHYS_DB_HOST} -p ${TETHYS_DB_PORT} -U postgres; do
    if [[ $db_check_count -gt $db_max_count ]]; then
      >&2 echo "DB was not available in time - exiting"
      exit 1
    fi
    >&2 echo "DB is unavailable - sleeping"
    db_check_count=`expr $db_check_count + 1`
    sleep 5
  done
fi

echo_status "Enforcing start state... (This might take a bit)"
salt-call --local state.apply

if [[ $test = false ]]; then
  if [[ $skip_perm = false ]]; then
    echo_status "Fixing permissions"
    find ${STATIC_ROOT} ! -user ${NGINX_USER} -print0 | xargs -0 -I{} chown ${NGINX_USER}: {}
    find ${WORKSPACE_ROOT} ! -user ${NGINX_USER} -print0 | xargs -0 -I{} chown ${NGINX_USER}: {}
    find ${TETHYS_PERSIST} ! -user ${NGINX_USER} -print0 | xargs -0 -I{} chown ${NGINX_USER}: {}
    find ${TETHYSAPP_DIR} ! -user ${NGINX_USER} -print0 | xargs -0 -I{} chown ${NGINX_USER}: {}
    find ${TETHYS_HOME} ! -user ${NGINX_USER} -print0 | xargs -0 -I{} chown ${NGINX_USER}: {}
  fi

  echo_status "Starting supervisor"

  # Start Supervisor
  /usr/bin/supervisord $([[ $no_daemon = true ]] && printf %s "-n")

  echo_status "Done!"

  # Watch Logs
  echo_status "Watching logs"
  tail -qF /var/log/supervisor/* /var/log/nginx/* /var/log/tethys/*
fi


text:
package com.teamltt.carcare.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public interface IObdSocket {

    void connect() throws IOException;

    InputStream getInputStream() throws IOException;

    OutputStream getOutputStream() throws IOException;

    boolean isConnected();

    void close() throws IOException;

}


text:
package com.gh.mygreen.xlsmapper.fieldaccessor;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellReference;
import org.junit.Before;

import static org.assertj.core.api.Assertions.*;

import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;

import com.gh.mygreen.xlsmapper.util.Utils;

/**
 * {@link ArrayLabelSetterFactory}のテスタ
 *
 * @since 2.0
 * @author T.TSUCHIE
 *
 */
@RunWith(Enclosed.class)
public class ArrayLabelSetterFactoryTest {

    /**
     * ラベル情報が無い場合
     *
     */
    public static class NotLabel {

        private ArrayLabelSetterFactory setterFactory;

        @Before
        public void setUp() throws Exception {
            this.setterFactory = new ArrayLabelSetterFactory();
        }

        @Test
        public void testCreate() {

            Optional<ArrayLabelSetter> labelSetter = setterFactory.create(SampleRecord.class, "test");
            assertThat(labelSetter).isEmpty();

        }

        private static class SampleRecord {

        }

    }

    /**
     * マップ型のフィールドのラベル情報の場合
     *
     */
    public static class ByMapField {

        private ArrayLabelSetterFactory setterFactory;

        @Before
        public void setUp() throws Exception {
            this.setterFactory = new ArrayLabelSetterFactory();
        }

        /**
         * フィールドのタイプがMapではない場合
         */
        @Test
        public void testCreateWithNoMap() {

            Optional<ArrayLabelSetter> labelSetter = setterFactory.create(NoMapRecord.class, "test");
            assertThat(labelSetter).isEmpty();

        }

        /**
         * マップのGenericsのクラスタイプがサポート対象外の場合
         */
        @Test
        public void testCreateWithNoSupportType() {

            Optional<ArrayLabelSetter> labelSetter = setterFactory.create(NoSupportTypeRecord.class, "test");
            assertThat(labelSetter).isEmpty();

        }

        /**
         * マップのタイプが{@link String}の場合
         */
        @Test
        public void testCreateWithString() {

            Optional<ArrayLabelSetter> labelSetter = setterFactory.create(StringRecord.class, "test");
            assertThat(labelSetter).isNotEmpty();

            {
                // ラベル情報を設定する
                StringRecord record = new StringRecord();

                ArrayLabelSetter accessor = labelSetter.get();
                String label = "サンプル";

                accessor.set(record, label, 1);

                assertThat(record.labels)
                    .hasSize(1)
                    .containsEntry("test[1]", label);
            }

        }

        /**
         * Map形式ではない場合
         *
         */
        private static class NoMapRecord {

            String labels;

        }

        /**
         * 値がサポートしていないクラスタイプの場合
         *
         */
        private static class NoSupportTypeRecord {

            Map<String, CellReference> labels;

        }

        private static class StringRecord {

            Map<String, String> labels;

        }

    }

    /**
     * メソッドによるラベル情報を格納する場合
     *
     */
    public static class ByMethod {

        private ArrayLabelSetterFactory setterFactory;

        @Before
        public void setUp() throws Exception {
            this.setterFactory = new ArrayLabelSetterFactory();
        }

        @Test
        public void testCreateWithString() {

            Optional<ArrayLabelSetter> labelSetter = setterFactory.create(StringRecord.class, "test");
            assertThat(labelSetter).isNotEmpty();

            {
                // ラベル情報を設定する
                StringRecord record = new StringRecord();

                ArrayLabelSetter accessor = labelSetter.get();
                String label = "サンプル";

                accessor.set(record, label, 1);

                assertThat(record.labelList)
                    .hasSize(2)
                    .containsExactly(null, "サンプル");
            }

        }

        private static class StringRecord {

            private List<String> labelList = new ArrayList<>();

            public void setTestLabel(int index, String label) {
                Utils.addListWithIndex(labelList, label, index);
            }

        }

    }

    /**
     * フィールドによるラベル情報を格納する場合
     *
     */
    public static class ByField {

        private ArrayLabelSetterFactory setterFactory;

        @Before
        public void setUp() throws Exception {
            this.setterFactory = new ArrayLabelSetterFactory();
        }

        @Test
        public void testCreateWithString() {

            Optional<ArrayLabelSetter> labelSetter = setterFactory.create(StringRecord.class, "test");
            assertThat(labelSetter).isNotEmpty();

            {
                // ラベル情報を設定する
                StringRecord record = new StringRecord();

                ArrayLabelSetter accessor = labelSetter.get();
                String label = "サンプル";

                accessor.set(record, label, 1);

                assertThat(record.testLabel)
                    .hasSize(2)
                    .containsExactly(null, "サンプル");
            }

        }

        @Test
        public void testCreateWithNotSupportType() {

            Optional<ArrayLabelSetter> labelSetter = setterFactory.create(NotSupportTypeRecord.class, "test");
            assertThat(labelSetter).isEmpty();

        }

        private static class StringRecord {

            private List<String> testLabel;

        }

        private static class NotSupportTypeRecord {

            private List<Cell> testLabel;

        }
    }

}


text:
@extends ('site.layouts.default')
@section('content')

Plot Map!

    <canvas id="ex1" width="400" height="1200"
           style="border: 1px solid #cccccc;">
    HTML5 Canvas not supported
</canvas>

{{-- Scripts --}}

@stop


text:
class E38 : public State {
 public:
    E38();
    bool transition(Automaton *automaton, ValuableToken s);
    inline int getStateNumber(){return 38;}
};

#endif  // STATE_E38_H_


text:
class cIGZAllocatorService;
class cIGZCanvas;
class cIGZClipboardManager;
class cIGZCommandServer;
class cIGZDrawSystem;
class cIGZFileSystem;
class cIGZFontSys;
class cIGZGraphicSystem;
class cIGZGraphicSystem2;
class cIGZLanguageManager;
class cIGZLuaScriptServer;
class cIGZMessageServer;
class cIGZMessageServer2;
class cIGZPersistResourceManager;
class cIGZRadio;
class cIGZRealtimeDebugDisplay;
class cIGZRegistry;
class cIGZSndMgr;
class cIGZSndSys;
class cIGZTestService;
class cIGZUIScriptService;
class cIGZWWWSystem;
class cIGZWinCtrlMgr;
class cIGZWinIMEServer;
class cIGZWinMgr;
class cIHitDebugInfo;
class cIHitMan;
class cIS3DMaterialManager;
class cIS3DTextureBindingFactory;
class cISC4AEMSEvents;
class cISC4AnimationTickManager;
class cISC4App;
class cISC4AudioScapeManager;
class cISC4GameDataRegistry;
class cISC4Simulator;
class cISCExemplarCache;
class nGZLog_cIService;


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Xunit;

namespace Microsoft.CodeAnalysis.UnitTests
{
    public struct DiagnosticResultLocation
    {
        public DiagnosticResultLocation(string path, int line, int column)
        {
            Assert.True(line >= 0 || column >= 0, "At least one of line and column must be > 0");
            Assert.True(line >= -1 && column >= -1, "Both line and column must be >= -1");

            this.Path = path;
            this.Line = line;
            this.Column = column;
        }

        public string Path;
        public int Line;
        public int Column;
    }

    public struct DiagnosticResult
    {
        private DiagnosticResultLocation[] _locations;

        public DiagnosticResultLocation[] Locations
        {
            get
            {
                if (_locations == null)
                {
                    _locations = new DiagnosticResultLocation[] { };
                }

                return _locations;
            }

            set
            {
                _locations = value;
            }
        }

        public DiagnosticSeverity Severity { get; set; }

        public string Id { get; set; }

        public string Message { get; set; }

        public string Path
        {
            get
            {
                return this.Locations.Length > 0 ? this.Locations[0].Path : "";
            }
        }

        public int Line
        {
            get
            {
                return this.Locations.Length > 0 ? this.Locations[0].Line : -1;
            }
        }

        public int Column
        {
            get
            {
                return this.Locations.Length > 0 ? this.Locations[0].Column : -1;
            }
        }
    }
}


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 io.trino.plugin.hive.metastore.thrift;

import io.trino.plugin.hive.authentication.HiveMetastoreAuthentication;
import org.apache.thrift.transport.TTransport;

import java.util.Optional;

import static com.google.common.base.Preconditions.checkArgument;

public class NoHiveMetastoreAuthentication
        implements HiveMetastoreAuthentication
{
    @Override
    public TTransport authenticate(TTransport rawTransport, String hiveMetastoreHost, Optional<String> delegationToken)
    {
        checkArgument(delegationToken.isEmpty(), "delegation token is not supported");
        return rawTransport;
    }
}


text:
<?php

namespace model\media;

use \DataObject as DataObject;
use \Model as Model;
use \Logger as Logger;
use \SQL as SQL;
use \db\Qualifier as Qualifier;

use \model\media\Story_Arc_Series as Story_Arc_Series;

/* import related objects */
use \model\media\Story_Arc as Story_Arc;
use \model\media\Story_ArcDBO as Story_ArcDBO;
use \model\media\Series as Series;
use \model\media\SeriesDBO as SeriesDBO;

abstract class _Story_Arc_SeriesDBO extends DataObject
{
	public $story_arc_id;
	public $series_id;

	public function pkValue()
	{
		return $this->{Story_Arc_Series::id};
	}

	public function modelName()
	{
		return "Story_Arc_Series";
	}

	public function dboName()
	{
		return "\model\media\Story_Arc_SeriesDBO";
	}

	// to-one relationship
	public function story_arc()
	{
		if ( isset( $this->story_arc_id ) ) {
			$model = Model::Named('Story_Arc');
			return $model->objectForId($this->story_arc_id);
		}
		return false;
	}

	public function setStory_arc(Story_ArcDBO $obj = null)
	{
		if ( isset($obj, $obj->id) && (isset($this->story_arc_id) == false || $obj->id != $this->story_arc_id) ) {
			parent::storeChange( Story_Arc_Series::story_arc_id, $obj->id );
			$this->saveChanges();
		}
	}

	// to-one relationship
	public function series()
	{
		if ( isset( $this->series_id ) ) {
			$model = Model::Named('Series');
			return $model->objectForId($this->series_id);
		}
		return false;
	}

	public function setSeries(SeriesDBO $obj = null)
	{
		if ( isset($obj, $obj->id) && (isset($this->series_id) == false || $obj->id != $this->series_id) ) {
			parent::storeChange( Story_Arc_Series::series_id, $obj->id );
			$this->saveChanges();
		}
	}

	/** Attributes */

}

?>


text: Simple Identicon generator.


text:
require 'tk'
require 'tkextlib/tcllib.rb'

# TkPackage.require('widget::dialog', '1.2')
TkPackage.require('widget::dialog')

module Tk::Tcllib
  module Widget
    class Dialog < TkWindow
      PACKAGE_NAME = 'widget::dialog'.freeze
      def self.package_name
        PACKAGE_NAME
      end

      def self.package_version
        begin
          TkPackage.require('widget::dialog')
        rescue
          ''
        end
      end
    end
  end
end

class Tk::Tcllib::Widget::Dialog
  TkCommandNames = ['::widget::dialog'.freeze].freeze

  def __boolval_optkeys
    ['separator', 'synchronous', 'transient']
  end
  private :__boolval_optkeys

  def create_self(keys)
    if keys and keys != None
      tk_call_without_enc(self.class::TkCommandNames[0], @path,
                          *hash_kv(keys, true))
    else
      tk_call_without_enc(self.class::TkCommandNames[0], @path)
    end
  end
  private :create_self

  def add(what, *args)
    window(tk_send('add', *args))
  end

  def get_frame
    window(tk_send('getframe'))
  end

  def set_widget(widget)
    tk_send('setwidget', widget)
    self
  end

  def display
    tk_send('display')
    self
  end
  alias show display

  def cancel
    tk_send('cancel')
    self
  end

  def close(reason = None)
    tk_send('close', reason)
  end

  def withdraw
    tk_send('withdraw')
    self
  end
end


text:
<md-dialog class="template manager dialog">
    <md-dialog-content>

Templates

            <md-select placeholder="New template" ng-model="selectedKey">
                <md-option ng-repeat="(key, value) in templates" value="{{key}}">{{key}}</md-option>
            </md-select>

        <md-input-container>
            Name
            <input autocomplete="off" ng-model="templateKey">
        </md-input-container>

            <md-button class="md-primary" ng-if="canBeRemoved" ng-click="remove()">
                Remove
            </md-button>
            <md-button class="md-primary" ng-if="!selectedKey" ng-click="add()">
                Add
            </md-button>
            <md-button class="md-primary" ng-if="selectedKey" ng-click="add()">
                Replace
            </md-button>

            Tip: Classeur uses Mustache templates, for example:

{{file.name}}
{{{file.content.text}}}
{{{file.content.html}}}

        <md-button class="md-primary" target="_blank" ng-href="http://classeur.io/help/templates/">
            More about templates...
        </md-button>
    </md-dialog-content>

        <md-button ng-click="cancel()" class="md-primary">
            Cancel
        </md-button>
        <md-button ng-click="ok()" class="md-primary">
            Ok
        </md-button>

</md-dialog>


text:
import doppelbot.cli
doppelbot.cli.main()


text:
package com.github.pyknic.stiletto.testprovider;

/**
 * @author Emil Forslund
 * @since  1.0.4
 */
public interface Providable {

}


text:
class UpdateRelations < ActiveRecord::Migration
  def up
    Spree::Relation.where(relatable_type: 'Product').update_all(relatable_type: 'Spree::Product')
    Spree::Relation.where(related_to_type: 'Product').update_all(related_to_type: 'Spree::Product')
  end

  def down
    Spree::Relation.where(relatable_type: 'Spree::Product').update_all(relatable_type: 'Product')
    Spree::Relation.where(related_to_type: 'Spree::Product').update_all(related_to_type: 'Product')
  end
end


text:
<?php

/**
 * @category Proffer
 * @package FileType.php
 *
 * @author David Yell <neon1024@gmail.com>
 * @when 03/03/15
 *
 */

namespace Proffer\Database\Type;

use Cake\Database\Type;

class FileType extends Type
{
    /**
     * Prevent the marhsaller changing the upload array into a string
     *
     * @param mixed $value Passed upload array
     * @return mixed
     */
    public function marshal($value)
    {
        return $value;
    }
}


text:
#include "lua_includes.h"
#include "push_pointer_internal.h"
#include "oolua_config.h"

namespace OOLUA
{
	namespace INTERNAL
	{
#if OOLUA_DEBUG_CHECKS == 1
		void if_check_enabled_check_type_is_registered(lua_State* l, char const* name)
		{
			lua_getfield(l, LUA_REGISTRYINDEX, name);
			if( lua_isnil(l,-1) )
			{
				lua_pop(l,1);
				luaL_error(l,"%s %s %s","the type",name,"is not registered with this Lua State");
			}
			else lua_pop(l,1);
		}
#else
		void if_check_enabled_check_type_is_registered(lua_State* /*l*/, char const* /*name*/){}
#endif

		void set_owner_if_change(Owner owner, Lua_ud* ud)
		{
			if(owner != No_change)
			{
				userdata_gc_value(ud, owner == Lua ? true : false);
			}
		}

	}
}


text:
package socketeer.plugins.connection;

import socketeer.sterconfig;
import socketeer.stersourcesink;

public class sterchannelRC extends sterchannel {

	sterchanneIRCimpl sci;

	public boolean setConfigProfileSourceSink(stersourcesink sosi, sterconfig conf, String profile) {
		sterchanneIRCimpl sci = new sterchanneIRCimpl(this);
		sci.setNickLoginChannel(
				conf.getChannelParameterByKey(profile, "nick"),
				conf.getChannelParameterByKey(profile, "login"),
				conf.getChannelTopic(profile),
				conf.getChannelParameterByKey(profile, "uid")
				);
		if (sci.connect(conf.getChannelHost(profile), conf.getChannelPort(profile)) == true) {
			Thread irct = new Thread(sci);
			irct.start();
		} else {
			return false;
		}
		return super.setConfigProfileSourceSink(sosi, conf, profile);
	}

	public void send(String destination, String message) {
		sci.send(destination,message);
	}

	public String getProtocolID() {
		return "IRC";
	}

}


text:
package com.netflix.spinnaker.igor.concourse;

import static java.util.Collections.emptyList;

import com.netflix.spinnaker.igor.concourse.client.model.Job;
import com.netflix.spinnaker.igor.concourse.client.model.Pipeline;
import com.netflix.spinnaker.igor.concourse.client.model.Team;
import com.netflix.spinnaker.igor.concourse.service.ConcourseService;
import com.netflix.spinnaker.igor.service.BuildServices;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@ConditionalOnProperty("concourse.enabled")
@RequestMapping("/concourse")
public class ConcourseController {
  private final BuildServices buildServices;

  public ConcourseController(BuildServices buildServices) {
    this.buildServices = buildServices;
  }

  @GetMapping("/{buildMaster}/teams")
  public List<String> getTeams(@PathVariable("buildMaster") String buildMaster) {
    return getService(buildMaster)
        .map(
            service ->
                service.teams().stream().map(Team::getName).sorted().collect(Collectors.toList()))
        .orElse(emptyList());
  }

  @GetMapping("/{buildMaster}/teams/{team}/pipelines")
  public List<String> getPipelines(
      @PathVariable("buildMaster") String buildMaster, @PathVariable("team") String team) {
    return getService(buildMaster)
        .map(
            service ->
                service.pipelines().stream()
                    .filter(p -> team.equals(p.getTeamName()))
                    .map(Pipeline::getName)
                    .sorted()
                    .collect(Collectors.toList()))
        .orElse(emptyList());
  }

  @GetMapping("/{buildMaster}/teams/{team}/pipelines/{pipeline}/jobs")
  public List<String> getJobs(
      @PathVariable("buildMaster") String buildMaster,
      @PathVariable("team") String team,
      @PathVariable("pipeline") String pipeline) {
    // don't sort so that we leave the jobs in the order in which they appear in the pipeline
    return getService(buildMaster)
        .map(
            service ->
                service.getJobs().stream()
                    .filter(
                        j -> team.equals(j.getTeamName()) && pipeline.equals(j.getPipelineName()))
                    .map(Job::getName)
                    .collect(Collectors.toList()))
        .orElse(emptyList());
  }

  @GetMapping("/{buildMaster}/teams/{team}/pipelines/{pipeline}/resources")
  public List<String> getResourceNames(
      @PathVariable("buildMaster") String buildMaster,
      @PathVariable("team") String team,
      @PathVariable("pipeline") String pipeline) {
    return getService(buildMaster)
        .map(
            service ->
                service.getResourceNames(team, pipeline).stream()
                    .sorted()
                    .collect(Collectors.toList()))
        .orElse(emptyList());
  }

  private Optional<ConcourseService> getService(String buildMaster) {
    return Optional.ofNullable((ConcourseService) buildServices.getService(buildMaster));
  }
}


text:
require File.join(File.dirname(__FILE__), 'super_tag')

[ Account, Campaign, Contact, Lead, Opportunity ].each do |klass|
  klass.class_eval do
    include SuperTag
    def customfields
      self.tags.inject({}){|r, t| r[t.name] = self.send("tag#{t.id}"); r }
    end
  end
end


text:
@interface UIView (Layout)
-(void)addOnLayoutMutation:(VIEW_MUTATION)mutation;

- (void)addOnMoveToSuperviewMutation:(VIEW_MUTATION)mutation;

- (NSNumber *)contentHeight;

- (NSNumber *)contentWidth;
@end