text:
package com.vaadin.tests.components.combobox;

import com.vaadin.tests.components.TestBase;
import com.vaadin.v7.ui.AbstractSelect.NewItemHandler;
import com.vaadin.v7.ui.ComboBox;
import com.vaadin.v7.ui.TextArea;

@SuppressWarnings("serial")
public class NewItemsESCPress extends TestBase {

    @Override
    protected void setup() {
        final TextArea addedItems = new TextArea("Last added items:");
        addedItems.setRows(10);
        addComponent(addedItems);

        final ComboBox box = new ComboBox("New items are allowed");
        box.setNewItemsAllowed(true);
        box.setNewItemHandler(new NewItemHandler() {
            @Override
            public void addNewItem(String newItemCaption) {
                String value = addedItems.getValue();
                addedItems.setValue(value + newItemCaption + "\n");
                box.addItem(newItemCaption);
            }
        });
        box.setImmediate(true);
        addComponent(box);
    }

    @Override
    protected String getDescription() {
        return "Firefox flashes the previously entered value when holding the ESC-key.";
    }

    @Override
    protected Integer getTicketNumber() {
        return 5694;
    }

}


text:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

CREATE TABLE `answers` (
  `id` int(10) UNSIGNED NOT NULL,
  `exam_id` int(10) UNSIGNED NOT NULL,
  `question_id` int(10) UNSIGNED NOT NULL,
  `content` varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `exams_groups` (
  `id` int(10) UNSIGNED NOT NULL,
  `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `description` text COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `questions` (
  `id` int(10) UNSIGNED NOT NULL,
  `exam_id` int(10) UNSIGNED NOT NULL,
  `content` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `image` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `correct` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `exams` (
  `id` int(10) UNSIGNED NOT NULL,
  `group_id` int(10) UNSIGNED NOT NULL,
  `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `questions` int(10) UNSIGNED NOT NULL,
  `threshold` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE `answers`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `answers`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;

ALTER TABLE `exams_groups`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `exams_groups`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;

ALTER TABLE `questions`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `questions`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;

ALTER TABLE `exams`
  ADD PRIMARY KEY `id` (`id`);
ALTER TABLE `exams`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

redpajama_set_name: RedPajamaGithub


text:
/*! Penelope v0.0.0 - MIT license */

var expect = require('chai').expect,
    Penelope = require('../lib/Penelope.js');

describe('The Penelope tool', function() {
    it('should throw an Penelope if stylesheet data not supplied as string, array or multi-param strings', function() {
        penelope = new Penelope([]);
        expect(function() {penelope.run({})}).to.throw();
        expect(function() {penelope.run(0)}).to.throw();
        expect(function() {penelope.run(1, [], {})}).to.throw();
    });

    it('should not throw an exception if stylesheet data is supplied as string, array or multi-param strings', function() {
        penelope = new Penelope([]);
        expect(function() {penelope.run('body {background: #FFF;}')});
        expect(function() {penelope.run(array('body {background: #FFF;}'))});
        expect(function() {penelope.run('body {background: #FFF;}', 'body {background: #FFF;}')});
    });

    it('should run metrics on stylesheets', function() {
        var mockMetric = {id: 'mock-stylesheet-metric', type: 'stylesheet', aggregate: 'sum', measure: function() {return 1}};
        penelope = new Penelope([mockMetric]);
        expect(penelope.run('body {background: #FFF;}')).to.have.property('mock-stylesheet-metric');
    });

    it('should return sum values for sum metrics', function() {
        var mockMetric = {id: 'mock-stylesheet-metric', type: 'stylesheet', aggregate: 'sum', measure: function() {return 1}},
            stylesheet = 'body {background: #FFF;}';

        penelope = new Penelope([mockMetric]);
        var report = penelope.run([stylesheet, stylesheet, stylesheet]);

        expect(report).to.have.property('mock-stylesheet-metric');
        expect(report['mock-stylesheet-metric']).to.equal(3);
    });

    it('should return 0 for sum metrics with no data to report on', function() {
        var mockMetric = {id: 'mock-stylesheet-metric', type: 'rule', aggregate: 'sum', measure: function() {return 1}},
            stylesheet = '/* comment */';

        penelope = new Penelope([mockMetric]);
        var report = penelope.run([stylesheet, stylesheet, stylesheet]);

        expect(report).to.have.property('mock-stylesheet-metric');
        expect(report['mock-stylesheet-metric']).to.equal(0);
    });

    it('should return mean values for mean metrics', function() {
        var mockMetric = {id: 'mock-stylesheet-metric', type: 'stylesheet', aggregate: 'mean', measure: function() {return 1}},
            stylesheet = 'body {background: #FFF;}';

        penelope = new Penelope([mockMetric]);
        var report = penelope.run([stylesheet, stylesheet, stylesheet]);

        expect(report).to.have.property('mock-stylesheet-metric');
        expect(report['mock-stylesheet-metric']).to.equal(1);
    });

    it('should return 0 for mean metrics with no data to report on', function () {
        var mockMetric = {id: 'mock-stylesheet-metric', type: 'rule', aggregate: 'mean', measure: function() {return 1}},
            stylesheet = '/* comment */';

        penelope = new Penelope([mockMetric]);
        var report = penelope.run([stylesheet]);

        expect(report).to.have.property('mock-stylesheet-metric');
        expect(report['mock-stylesheet-metric']).to.equal(0);
    });

    it('should return max values for max metrics', function () {
        var mockIntMetric = {id: 'mock-int-metric', type: 'stylesheet', aggregate: 'max', measure: function(stylesheet) {return stylesheet.length;}},
            penelope = new Penelope([mockIntMetric]),
            report = penelope.run(['body {background: #FFF;}', 'body {background: #FFFFFF;}']);

        expect(report).to.have.property('mock-int-metric');
        expect(report['mock-int-metric']).to.equal(27);
    });

    it('should return 0 for max metrics with no data to report on', function () {
        var mockIntMetric = {id: 'mock-int-metric', type: 'rule', aggregate: 'max', measure: function(stylesheet) {return stylesheet.length;}},
            penelope = new Penelope([mockIntMetric]),
            report = penelope.run(['/* comment */']);

        expect(report).to.have.property('mock-int-metric');
        expect(report['mock-int-metric']).to.equal(0);
    });

    it('should return max values determined by an iterator function if one is present', function() {
        var mockStringMetric = {id: 'mock-string-metric', type: 'stylesheet', aggregate: 'max', measure: function(stylesheet) {return stylesheet;}, iterator: function(string) {return string.length}},
            penelope = new Penelope([mockStringMetric]),
            report = penelope.run(['body {background: #FFF;}', 'body {background: #FFFFFF;}']);

        expect(report).to.have.property('mock-string-metric');
        expect(report['mock-string-metric']).to.equal('body {background: #FFFFFF;}');
    });

    it('should return list values for list metrics', function () {
        var mockSingleMetric = {id: 'mock-single-list-item-metric', type: 'stylesheet', aggregate: 'list', measure: function(stylesheet) {return stylesheet}},
            mockMultipleMetric = {id: 'mock-multiple-list-item-metric', type: 'stylesheet', aggregate: 'list', measure: function(stylesheet) {return ['a', 'b']}},
            penelope = new Penelope([mockSingleMetric, mockMultipleMetric]),
            report = penelope.run(['body {background: #FFF;}', 'body {background: #FFF;}']);

        expect(report).to.have.property('mock-single-list-item-metric');
        expect(report['mock-single-list-item-metric']).to.be.an('array');
        expect(report['mock-single-list-item-metric']).to.have.length(2);
        expect(report['mock-single-list-item-metric'][0]).to.equal('body {background: #FFF;}');
        expect(report['mock-single-list-item-metric'][1]).to.equal('body {background: #FFF;}');
        expect(report['mock-multiple-list-item-metric']).to.be.an('array');
        expect(report['mock-multiple-list-item-metric']).to.have.length(4);
        expect(report['mock-multiple-list-item-metric'][0]).to.equal('a');
        expect(report['mock-multiple-list-item-metric'][1]).to.equal('b');
        expect(report['mock-multiple-list-item-metric'][0]).to.equal('a');
        expect(report['mock-multiple-list-item-metric'][1]).to.equal('b');
    });

    it('should return list values filtered by a filter function if one is present', function() {
        var mockMetric = {id: 'mock-list-metric', type: 'stylesheet', aggregate: 'list', measure: function(stylesheet) {return stylesheet}, filter: function(value, index, self) {return self.indexOf(value) === index;}},
            penelope = new Penelope([mockMetric]),
            report = penelope.run(['body {background: #FFF;}', 'body {background: #FFF;}']);

        expect(report).to.have.property('mock-list-metric');
        expect(report['mock-list-metric']).to.be.an('array');
        expect(report['mock-list-metric']).to.have.length(1);
        expect(report['mock-list-metric']).to.include('body {background: #FFF;}');
    });

    it('should return length values for length metrics', function () {
        var mockMetric = {id: 'mock-length-metric', type: 'stylesheet', aggregate: 'length', measure: function(stylesheet) {return stylesheet}},
        penelope = new Penelope([mockMetric]);
        report = penelope.run(['body {background: #FFF;}', 'body {background: #FFF;}', '']);

        expect(report).to.have.property('mock-length-metric');
        expect(report['mock-length-metric']).to.equal(2);
    });

    it('should run metrics on rules', function() {
        var mockMetric = {id: 'mock-rule-metric', type: 'rule', aggregate: 'sum', measure: function() {return 1}};
        penelope = new Penelope([mockMetric]),
        report = penelope.run('body {background: #FFF;} h1 {font-weight: bold;}');

        expect(report).to.have.property('mock-rule-metric');
        expect(report['mock-rule-metric']).to.equal(2);
    });

    it('should run metrics on nested rules', function () {
        var mockMetric = {id: 'mock-rule-metric', type: 'rule', aggregate: 'sum', measure: function() {return 1}};
        penelope = new Penelope([mockMetric]);
        report = penelope.run('body {background: #FFF;} ul { padding: 30px; li { float: left;}}');

        expect(report['mock-rule-metric']).to.equal(3);
    });

    it('should pass parent rule data to rule metrics', function () {
        var mockMetric = {id: 'mock-rule-metric', type: 'rule', aggregate: 'list', measure: function(rule, data) {return data.parentRules;}};
        penelope = new Penelope([mockMetric]);
        report = penelope.run('body {background: #FFF; ul {padding: 30px; li {float: left;}}}');

        expect(report['mock-rule-metric']).to.include('body {background: #FFF; ul {padding: 30px; li {float: left;}}}');
        expect(report['mock-rule-metric']).to.include('ul {padding: 30px; li {float: left;}}');
    });

    it('should pass child rule data to rule metrics', function () {
        var mockMetric = {id: 'mock-rule-metric', type: 'rule', aggregate: 'list', measure: function(rule, data) {return data.childRules;}};
        penelope = new Penelope([mockMetric]);

        report = penelope.run('body {background: #FFF;}');
        expect(report['mock-rule-metric']).to.have.length(0);

        report = penelope.run('body {background: #FFF; ul {padding: 30px;} li {float: left;}}');
        expect(report['mock-rule-metric']).to.include('ul {padding: 30px;}');
        expect(report['mock-rule-metric']).to.include('li {float: left;}');
    });

    it('should run metrics on media queries', function () {
        var mockMetric = {id: 'mock-media-query-metric', type: 'mediaquery', aggregate: 'list', measure: function(query) {return query;}};
            penelope = new Penelope([mockMetric]),
            report = penelope.run('@media handheld, (max-width: 700px) { body { margin: 100px; }} @import url(css/styles.css); body { margin: 0; }');
        expect(report).to.have.property('mock-media-query-metric');
        expect(report['mock-media-query-metric']).to.include('handheld');
        expect(report['mock-media-query-metric']).to.include('(max-width: 700px)');
    });

    it('should run metrics on rules inside media query blocks', function () {
        var mockMetric = {id: 'mock-media-query-metric', type: 'rule', aggregate: 'list', measure: function(rule) {return rule;}},
        penelope = new Penelope([mockMetric]),
        report = penelope.run('@media print {a {color: #000;} header {display: none;}}');
        expect(report).to.have.property('mock-media-query-metric');
        expect(report['mock-media-query-metric']).to.include('a {color: #000;}');
        expect(report['mock-media-query-metric']).to.include('header {display: none;}');
    });

    it('should run metrics on selectors', function() {
        var mockMetric = {id: 'mock-selector-metric', type: 'selector', aggregate: 'sum', measure: function() {return 1}};
        penelope = new Penelope([mockMetric]);
        report = penelope.run('body section {background: #FFF;} h1 {font-weight: bold;}');

        expect(report).to.have.property('mock-selector-metric');
        expect(report['mock-selector-metric']).to.equal(2);
    });

    it('should run metrics on identifiers', function() {
        var mockMetric = {id: 'mock-identifier-metric', type: 'identifier', aggregate: 'sum', measure: function() {return 1}};
        penelope = new Penelope([mockMetric]);

        report = penelope.run("body section :first-child {background: #FFF;} form#registration-form > input.username {font-weight: bold;}");
        expect(report).to.have.property('mock-identifier-metric');
        expect(report['mock-identifier-metric']).to.equal(7);
    });

    it('should run metrics on declarations', function() {
        var mockMetric = {id: 'mock-declaration-metric', type: 'declaration', aggregate: 'sum', measure: function() {return 1}};
        penelope = new Penelope([mockMetric]);

        report = penelope.run("body {margin: 0; padding: 0} a {color: #00f} h1 {font-weight: bold; color: #000;}");
        expect(report).to.have.property('mock-declaration-metric');
        expect(report['mock-declaration-metric']).to.equal(5);
    });

    it('should run metrics on properties', function() {
        var mockMetric = {id: 'mock-property-metric', type: 'property', aggregate: 'sum', measure: function() {return 1}};
        penelope = new Penelope([mockMetric]);

        report = penelope.run("body {margin: 0; padding: 0} a {color: #00f} h1 {font-weight: bold; color: #000;}");
        expect(report).to.have.property('mock-property-metric');
        expect(report['mock-property-metric']).to.equal(5);
    });

    it('should run metrics on values', function() {
        var mockMetric = {id: 'mock-value-metric', type: 'value', aggregate: 'sum', measure: function() {return 1}};
        penelope = new Penelope([mockMetric]);

        report = penelope.run("body {margin: 0; padding: 0} a {color: #00f} h1 {font-weight: bold; color: #000;}");
        expect(report).to.have.property('mock-value-metric');
        expect(report['mock-value-metric']).to.equal(5);
    });

    it('should return results for metrics measuring optional elements when those elements are not found', function () {
        var mockMetric = {id: 'mock-media-query-metric', type: 'mediaquery', aggregate: 'length', measure: function(query) {return query;}};
            penelope = new Penelope([mockMetric]),
            report = penelope.run('body { margin: 0; }');

        expect(report).to.have.property('mock-media-query-metric');
        expect(report['mock-media-query-metric']).to.equal(0);
    });
});


text:
FactoryGirl.define do
  factory :service do
    project factory: :empty_project
  end
end


text:
require 'spec_helper'

describe Lego::Value::Integer do

  describe '#parse' do
    subject { Lego::Value::Integer.new(opts) }

    let(:opts){ {} }

    context 'nil' do
      let(:opts){ {default: ->{ 42 } } }

      specify { subject.parse(nil).should be_just(42) }
      specify { subject.parse('').should be_just(42) }
    end

    context 'invalid integer' do
      specify { subject.parse('  ').should be_error("invalid integer: '  '") }
      specify { subject.parse(123.456).should be_error("invalid integer: '123.456'") }
      specify { subject.parse('2012-02').should be_error("invalid integer: '2012-02'") }
      specify { subject.parse('invalid').should be_error("invalid integer: 'invalid'") }
    end

    it 'parses integer' do
      subject.parse(123).should be_just(123)
    end

    it 'parses string integer' do
      subject.parse('-134').should be_just(-134)
    end

    context 'minimum' do
      let(:opts){ { min: 4 } }
      specify { subject.parse(4).should be_just(4) }
      specify { subject.parse(3).should be_error("less than minimum of 4: '3'") }
    end

    context 'maximum' do
      let(:opts){ { max: 4 } }
      specify { subject.parse(4).should be_just(4) }
      specify { subject.parse(5).should be_error("more than maximum of 4: '5'") }
    end

    context 'minimium and maximum' do
      let(:opts){ { min: 0, max: 4 } }
      specify { subject.parse(1).should be_just(1) }
      specify { subject.parse(-1).should be_error("less than minimum of 0: '-1'") }
      specify { subject.parse(5).should be_error("more than maximum of 4: '5'") }
    end
  end

  describe '#coerce' do
    context 'nothing' do
      context 'default' do
        it 'raises error' do
          expect{ subject.coerce(nil) }.to raise_error(Lego::CoerceError, 'missing value')
          expect{ subject.coerce('') }.to raise_error(Lego::CoerceError, 'missing value')
        end
      end

      context 'with :default handler' do
        subject { Lego::Value::Integer.new(default: handler) }

        context 'nil handler' do
          let(:handler) { ->{ nil } }
          specify { subject.coerce(nil).should be_nil }
        end

        context 'lambda handler' do
          let(:handler) { ->{ 42 } }
          specify { subject.coerce('').should == 42 }
        end
      end
    end

    context 'failure' do
      it 'raises error' do
        expect{ subject.coerce('foo') }.to raise_error(Lego::CoerceError, "invalid integer: 'foo'")
      end
    end

    context 'success' do
      it 'returns integer' do
        subject.coerce('42').should == 42
      end
    end
  end
end


text:
package org.neo4j.jdbc.bolt;

import org.junit.Test;
import org.mockito.Mockito;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Session;
import org.neo4j.jdbc.bolt.data.PerformanceTestData;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.io.IOException;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.TimeUnit;

/**
 * @author AgileLARUS
 * @since 3.0.0
 */
public class SamplePT {

	@Test public void launchBenchmark() throws Exception {

		PerformanceTestData.loadABCXYData();

		// @formatter:off
		Options opt = new OptionsBuilder()
				.include(this.getClass().getName() + ".*")
				.mode(Mode.AverageTime)
				.timeUnit(TimeUnit.MICROSECONDS)
				//Warmup
				.warmupTime(TimeValue.seconds(1))
				.warmupIterations(1)
				//Measurement
				.measurementTime(TimeValue.seconds(1))
				.measurementIterations(10)
				.threads(1)
				.forks(2)
				.shouldFailOnError(true)
				//.shouldDoGC(true)
				//.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining")
				//.addProfiler(WinPerfAsmProfiler.class)
				.build();

		new Runner(opt).run();
	}

	@State(Scope.Benchmark) public static class Data {
		@Setup public void initialize() throws ClassNotFoundException, SQLException, IOException {
			jdbcConnection = DriverManager.getConnection("jdbc:neo4j:bolt://localhost:7687?user=neo4j,password=test");
			jdbcConnectionDebug = DriverManager.getConnection("jdbc:neo4j:bolt://localhost:7687?user=neo4j,password=test,debug");
			driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "test"));
		}

		@TearDown public void close() throws ClassNotFoundException, SQLException, IOException {
			jdbcConnection.close();
			jdbcConnectionDebug.close();
			driver.close();
		}

		public String query = "MATCH (n) RETURN n";
		public Connection jdbcConnection;
		public Connection jdbcConnectionDebug;
		public org.neo4j.driver.Driver driver;

	}

	@Benchmark public void testSimpleQueryJDBC(Data data, Blackhole bh) throws ClassNotFoundException, SQLException {
		Connection conn = data.jdbcConnection;
		Statement stmt = conn.createStatement();
		bh.consume(stmt.executeQuery(data.query));
		stmt.close();
	}

	@Benchmark public void testSimpleQueryBoltDriver(Data data, Blackhole bh) {
		org.neo4j.driver.Driver driver = data.driver;
		Session session = driver.session();
		bh.consume(session.run(data.query));
		session.close();
	}

	@Benchmark public void testSimpleQueryWithDebugJDBC(Data data, Blackhole bh) throws SQLException {
		System.setOut(Mockito.mock(PrintStream.class));
		Connection conn = data.jdbcConnectionDebug;
		Statement stmt = conn.createStatement();
		bh.consume(stmt.executeQuery(data.query));
		stmt.close();
	}
}


text:
from .libindy import do_call, create_cb

from typing import Optional
from ctypes import *

import logging

async def create_wallet(pool_name: str,
                        name: str,
                        xtype: Optional[str],
                        config: Optional[str],
                        credentials: Optional[str]) -> None:
    """
    Creates a new secure wallet with the given unique name.

    :param pool_name: Name of the pool that corresponds to this wallet.
    :param name: Name of the wallet.
    :param xtype: (optional) Type of the wallet. Defaults to 'default'.
     Custom types can be registered with indy_register_wallet_type call.
    :param config: (optional) Wallet configuration json. List of supported keys are defined by wallet type.
     if NULL, then default config will be used.
    :param credentials: (optional) Wallet credentials json. List of supported keys are defined by wallet type.
     if NULL, then default config will be used.
    :return: Error code
    """

    logger = logging.getLogger(__name__)
    logger.debug("create_wallet: >>> pool_name: %r, name: %r, xtype: %r, config: %r, credentials: %r",
                 pool_name,
                 name,
                 xtype,
                 config,
                 credentials)

    if not hasattr(create_wallet, "cb"):
        logger.debug("create_wallet: Creating callback")
        create_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_pool_name = c_char_p(pool_name.encode('utf-8'))
    c_name = c_char_p(name.encode('utf-8'))
    c_xtype = c_char_p(xtype.encode('utf-8')) if xtype is not None else None
    c_config = c_char_p(config.encode('utf-8')) if config is not None else None
    c_credentials = c_char_p(credentials.encode('utf-8')) if credentials is not None else None

    await do_call('indy_create_wallet',
                  c_pool_name,
                  c_name,
                  c_xtype,
                  c_config,
                  c_credentials,
                  create_wallet.cb)

    logger.debug("create_wallet: <<<")

async def open_wallet(name: str,
                      runtime_config: Optional[str],
                      credentials: Optional[str]) -> int:
    """
    Opens the wallet with specific name.
    Wallet with corresponded name must be previously created with indy_create_wallet method.
    It is impossible to open wallet with the same name more than once.

    :param name: Name of the wallet.
    :param runtime_config: (optional) Runtime wallet configuration json.
     if NULL, then default runtime_config will be used. Example:
        {
            "freshness_time": string (optional), Amount of minutes to consider wallet value as fresh. Defaults to 24*60.
            ... List of additional supported keys are defined by wallet type.
        }
    :param credentials: (optional) Wallet credentials json. List of supported keys are defined by wallet type.
     if NULL, then default credentials will be used.
    :return: Handle to opened wallet to use in methods that require wallet access.
    """

    logger = logging.getLogger(__name__)
    logger.debug("open_wallet: >>> name: %r, runtime_config: %r, credentials: %r",
                 name,
                 runtime_config,
                 credentials)

    if not hasattr(open_wallet, "cb"):
        logger.debug("open_wallet: Creating callback")
        open_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_int32))

    c_name = c_char_p(name.encode('utf-8'))
    c_runtime_config = c_char_p(runtime_config.encode('utf-8')) if runtime_config is not None else None
    c_credentials = c_char_p(credentials.encode('utf-8')) if credentials is not None else None

    res = await do_call('indy_open_wallet',
                        c_name,
                        c_runtime_config,
                        c_credentials,
                        open_wallet.cb)

    logger.debug("open_wallet: <<< res: %r", res)
    return res

async def close_wallet(handle: int) -> None:
    """
    Closes opened wallet and frees allocated resources.

    :param handle: wallet handle returned by indy_open_wallet.
    :return: Error code
    """

    logger = logging.getLogger(__name__)
    logger.debug("close_wallet: >>> handle: %i", handle)

    if not hasattr(close_wallet, "cb"):
        logger.debug("close_wallet: Creating callback")
        close_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_handle = c_int32(handle)

    await do_call('indy_close_wallet',
                  c_handle,
                  close_wallet.cb)

    logger.debug("close_wallet: <<<")

# pub extern fn indy_delete_wallet(command_handle: i32,
#                                    name: *const c_char,
#                                    credentials: *const c_char,
#                                    cb: Option<extern fn(xcommand_handle: i32, err: ErrorCode)>) -> ErrorCode {
async def delete_wallet(name: str,
                        credentials: Optional[str]) -> None:
    """
    Deletes created wallet.

    :param name: Name of the wallet to delete.
    :param credentials: (optional) Wallet credentials json. List of supported keys are defined by wallet type.
     if NULL, then default credentials will be used.
    :return:
    """

    logger = logging.getLogger(__name__)
    logger.debug("delete_wallet: >>> name: %r, credentials: %r",
                 name,
                 credentials)

    if not hasattr(delete_wallet, "cb"):
        logger.debug("delete_wallet: Creating callback")
        delete_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_name = c_char_p(name.encode('utf-8'))
    c_credentials = c_char_p(credentials.encode('utf-8')) if credentials is not None else None

    await do_call('indy_delete_wallet',
                  c_name,
                  c_credentials,
                  delete_wallet.cb)

    logger.debug("delete_wallet: <<<")


text:
package com.amazonaws.http.apache.client.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

import com.amazonaws.http.AmazonHttpClient;
import com.amazonaws.http.IdleConnectionReaper;
import com.amazonaws.http.apache.SdkProxyRoutePlanner;
import com.amazonaws.http.apache.utils.ApacheUtils;
import com.amazonaws.http.client.ConnectionManagerFactory;
import com.amazonaws.http.client.HttpClientFactory;
import com.amazonaws.http.conn.ClientConnectionManagerFactory;
import com.amazonaws.http.conn.SdkConnectionKeepAliveStrategy;
import com.amazonaws.http.protocol.SdkHttpRequestExecutor;
import com.amazonaws.http.settings.HttpClientSettings;

/**
 * Factory class that builds the apache http client from the settings.
 */
public class ApacheHttpClientFactory implements HttpClientFactory<ConnectionManagerAwareHttpClient> {

    private static final Log LOG = LogFactory.getLog(AmazonHttpClient.class);
    private final ConnectionManagerFactory<HttpClientConnectionManager>
            cmFactory = new ApacheConnectionManagerFactory();

    @Override
    public ConnectionManagerAwareHttpClient create(HttpClientSettings settings) {
        final HttpClientBuilder builder = HttpClients.custom();
        // Note that it is important we register the original connection manager with the
        // IdleConnectionReaper as it's required for the successful deregistration of managers
        // from the reaper. See https://github.com/aws/aws-sdk-java/issues/722.
        final HttpClientConnectionManager cm = cmFactory.create(settings);

        builder.setRequestExecutor(new SdkHttpRequestExecutor())
                .setKeepAliveStrategy(buildKeepAliveStrategy(settings))
                .disableRedirectHandling()
                .disableAutomaticRetries()
                .setConnectionManager(ClientConnectionManagerFactory.wrap(cm));

        // By default http client enables Gzip compression. So we disable it
        // here.
        // Apache HTTP client removes Content-Length, Content-Encoding and
        // Content-MD5 headers when Gzip compression is enabled. Currently
        // this doesn't affect S3 or Glacier which exposes these headers.
        //
        if (!(settings.useGzip())) {
            builder.disableContentCompression();
        }

        addProxyConfig(builder, settings);

        final ConnectionManagerAwareHttpClient httpClient = new SdkHttpClient(builder.build(), cm);

        if (settings.useReaper()) {
            IdleConnectionReaper.registerConnectionManager(cm);
        }

        return httpClient;
    }

    private void addProxyConfig(HttpClientBuilder builder,
                                HttpClientSettings settings) {
        if (isProxyEnabled(settings)) {

            LOG.info("Configuring Proxy. Proxy Host: " + settings.getProxyHost() + " " +
                    "Proxy Port: " + settings.getProxyPort());

            builder.setRoutePlanner(new SdkProxyRoutePlanner(
                    settings.getProxyHost(), settings.getProxyPort(), settings.getNonProxyHosts()));

            if (isAuthenticatedProxy(settings)) {
                builder.setDefaultCredentialsProvider(ApacheUtils
                        .newProxyCredentialsProvider(settings));
            }
        }
    }

    private ConnectionKeepAliveStrategy buildKeepAliveStrategy
            (HttpClientSettings settings) {
        return settings.getMaxIdleConnectionTime() > 0
                ? new SdkConnectionKeepAliveStrategy(settings.getMaxIdleConnectionTime())
                : null;
    }

    private boolean isAuthenticatedProxy(HttpClientSettings settings) {
        return settings.getProxyUsername() != null
                && settings.getProxyPassword() != null;
    }

    private boolean isProxyEnabled(HttpClientSettings settings) {
        return settings.getProxyHost() != null && settings.getProxyPort() > 0;
    }
}


text:
package elastic

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/olivere/elastic/v7/uritemplates"
)

// SnapshotStatusService returns information about the status of a snapshot.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/modules-snapshots.html
// for details.
type SnapshotStatusService struct {
	client *Client

	pretty     *bool       // pretty format the returned JSON response
	human      *bool       // return human readable values for statistics
	errorTrace *bool       // include the stack trace of returned errors
	filterPath []string    // list of filters used to reduce the response
	headers    http.Header // custom request-level HTTP headers

	repository        string
	snapshot          []string
	masterTimeout     string
	ignoreUnavailable *bool
}

// NewSnapshotStatusService creates a new SnapshotStatusService.
func NewSnapshotStatusService(client *Client) *SnapshotStatusService {
	return &SnapshotStatusService{
		client: client,
	}
}

// Pretty tells Elasticsearch whether to return a formatted JSON response.
func (s *SnapshotStatusService) Pretty(pretty bool) *SnapshotStatusService {
	s.pretty = &pretty
	return s
}

// Human specifies whether human readable values should be returned in
// the JSON response, e.g. "7.5mb".
func (s *SnapshotStatusService) Human(human bool) *SnapshotStatusService {
	s.human = &human
	return s
}

// ErrorTrace specifies whether to include the stack trace of returned errors.
func (s *SnapshotStatusService) ErrorTrace(errorTrace bool) *SnapshotStatusService {
	s.errorTrace = &errorTrace
	return s
}

// FilterPath specifies a list of filters used to reduce the response.
func (s *SnapshotStatusService) FilterPath(filterPath ...string) *SnapshotStatusService {
	s.filterPath = filterPath
	return s
}

// Header adds a header to the request.
func (s *SnapshotStatusService) Header(name string, value string) *SnapshotStatusService {
	if s.headers == nil {
		s.headers = http.Header{}
	}
	s.headers.Add(name, value)
	return s
}

// Headers specifies the headers of the request.
func (s *SnapshotStatusService) Headers(headers http.Header) *SnapshotStatusService {
	s.headers = headers
	return s
}

// Repository is the repository name.
func (s *SnapshotStatusService) Repository(repository string) *SnapshotStatusService {
	s.repository = repository
	return s
}

// Snapshot is the list of snapshot names. If not set, defaults to all snapshots.
func (s *SnapshotStatusService) Snapshot(snapshots ...string) *SnapshotStatusService {
	s.snapshot = append(s.snapshot, snapshots...)
	return s
}

// MasterTimeout specifies an explicit operation timeout for connection to master node.
func (s *SnapshotStatusService) MasterTimeout(masterTimeout string) *SnapshotStatusService {
	s.masterTimeout = masterTimeout
	return s
}

// buildURL builds the URL for the operation.
func (s *SnapshotStatusService) buildURL() (string, url.Values, error) {
	var err error
	var path string

	if s.repository != "" {
		if len(s.snapshot) > 0 {
			path, err = uritemplates.Expand("/_snapshot/{repository}/{snapshot}/_status", map[string]string{
				"repository": s.repository,
				"snapshot":   strings.Join(s.snapshot, ","),
			})
		} else {
			path, err = uritemplates.Expand("/_snapshot/{repository}/_status", map[string]string{
				"repository": s.repository,
			})
		}
	} else {
		path, err = uritemplates.Expand("/_snapshot/_status", nil)
	}
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if v := s.pretty; v != nil {
		params.Set("pretty", fmt.Sprint(*v))
	}
	if v := s.human; v != nil {
		params.Set("human", fmt.Sprint(*v))
	}
	if v := s.errorTrace; v != nil {
		params.Set("error_trace", fmt.Sprint(*v))
	}
	if len(s.filterPath) > 0 {
		params.Set("filter_path", strings.Join(s.filterPath, ","))
	}
	if s.masterTimeout != "" {
		params.Set("master_timeout", s.masterTimeout)
	}
	if v := s.ignoreUnavailable; v != nil {
		params.Set("ignore_unavailable", fmt.Sprint(*v))
	}
	return path, params, nil
}

// Validate checks if the operation is valid.
//
// Validation only fails if snapshot names were provided but no repository was
// provided.
func (s *SnapshotStatusService) Validate() error {
	if len(s.snapshot) > 0 && s.repository == "" {
		return fmt.Errorf("snapshots were specified but repository is missing")
	}
	return nil
}

// Do executes the operation.
func (s *SnapshotStatusService) Do(ctx context.Context) (*SnapshotStatusResponse, error) {
	// Check pre-conditions
	if err := s.Validate(); err != nil {
		return nil, err
	}

	// Get URL for request
	path, params, err := s.buildURL()
	if err != nil {
		return nil, err
	}

	// Get HTTP response
	res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
		Method:  "GET",
		Path:    path,
		Params:  params,
		Headers: s.headers,
	})
	if err != nil {
		return nil, err
	}

	// Return operation response
	ret := new(SnapshotStatusResponse)
	if err := json.Unmarshal(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}

type SnapshotStatusResponse struct {
	Snapshots []SnapshotStatus `json:"snapshots"`
}

type SnapshotStatus struct {
	Snapshot           string                         `json:"snapshot"`
	Repository         string                         `json:"repository"`
	UUID               string                         `json:"uuid"`
	State              string                         `json:"state"`
	IncludeGlobalState bool                           `json:"include_global_state"`
	ShardsStats        SnapshotShardsStats            `json:"shards_stats"`
	Stats              SnapshotStats                  `json:"stats"`
	Indices            map[string]SnapshotIndexStatus `json:"indices"`
}

type SnapshotShardsStats struct {
	Initializing int `json:"initializing"`
	Started      int `json:"started"`
	Finalizing   int `json:"finalizing"`
	Done         int `json:"done"`
	Failed       int `json:"failed"`
	Total        int `json:"total"`
}

type SnapshotStats struct {
	Incremental struct {
		FileCount   int    `json:"file_count"`
		Size        string `json:"size"`
		SizeInBytes int64  `json:"size_in_bytes"`
	} `json:"incremental"`

	Processed struct {
		FileCount   int    `json:"file_count"`
		Size        string `json:"size"`
		SizeInBytes int64  `json:"size_in_bytes"`
	} `json:"processed"`

	Total struct {
		FileCount   int    `json:"file_count"`
		Size        string `json:"size"`
		SizeInBytes int64  `json:"size_in_bytes"`
	} `json:"total"`

	StartTime         string `json:"start_time"`
	StartTimeInMillis int64  `json:"start_time_in_millis"`

	Time         string `json:"time"`
	TimeInMillis int64  `json:"time_in_millis"`

	NumberOfFiles  int `json:"number_of_files"`
	ProcessedFiles int `json:"processed_files"`

	TotalSize        string `json:"total_size"`
	TotalSizeInBytes int64  `json:"total_size_in_bytes"`
}

type SnapshotIndexStatus struct {
	ShardsStats SnapshotShardsStats                 `json:"shards_stats"`
	Stats       SnapshotStats                       `json:"stats"`
	Shards      map[string]SnapshotIndexShardStatus `json:"shards"`
}

type SnapshotIndexShardStatus struct {
	Stage  string        `json:"stage"` // initializing, started, finalize, done, or failed
	Stats  SnapshotStats `json:"stats"`
	Node   string        `json:"node"`
	Reason string        `json:"reason"` // reason for failure
}


text:
using AngularBreezeWebAPI.Model;

namespace AngularBreezeWebAPI.Model
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Prospect.ContactMethod")]
    public sealed class ContactMethod
    {
        public ContactMethod()
        {
            ContactNoteDetails = new HashSet<ContactNoteDetail>();
        }

        public int ContactMethodID { get; set; }

        [Required]
        [StringLength(50)]
        public string Description { get; set; }

        [Column(TypeName = "timestamp")]
        [MaxLength(8)]
        [Timestamp]
        public byte[] timestamp { get; set; }

        public ICollection<ContactNoteDetail> ContactNoteDetails { get; set; }
    }
}


text:
use crate::core::source::{MaybePackage, Source, SourceId};
use crate::core::GitReference;
use crate::core::{Dependency, Package, PackageId, Summary};
use crate::sources::git::utils::GitRemote;
use crate::sources::PathSource;
use crate::util::errors::CargoResult;
use crate::util::hex::short_hash;
use crate::util::Config;
use anyhow::Context;
use log::trace;
use std::fmt::{self, Debug, Formatter};
use url::Url;

pub struct GitSource<'cfg> {
    remote: GitRemote,
    manifest_reference: GitReference,
    locked_rev: Option<git2::Oid>,
    source_id: SourceId,
    path_source: Option<PathSource<'cfg>>,
    ident: String,
    config: &'cfg Config,
}

impl<'cfg> GitSource<'cfg> {
    pub fn new(source_id: SourceId, config: &'cfg Config) -> CargoResult<GitSource<'cfg>> {
        assert!(source_id.is_git(), "id is not git, id={}", source_id);

        let remote = GitRemote::new(source_id.url());
        let ident = ident(&source_id);

        let source = GitSource {
            remote,
            manifest_reference: source_id.git_reference().unwrap().clone(),
            locked_rev: match source_id.precise() {
                Some(s) => Some(git2::Oid::from_str(s).with_context(|| {
                    format!("precise value for git is not a git revision: {}", s)
                })?),
                None => None,
            },
            source_id,
            path_source: None,
            ident,
            config,
        };

        Ok(source)
    }

    pub fn url(&self) -> &Url {
        self.remote.url()
    }

    pub fn read_packages(&mut self) -> CargoResult<Vec<Package>> {
        if self.path_source.is_none() {
            self.update()?;
        }
        self.path_source.as_mut().unwrap().read_packages()
    }
}

fn ident(id: &SourceId) -> String {
    let ident = id
        .canonical_url()
        .raw_canonicalized_url()
        .path_segments()
        .and_then(|s| s.rev().next())
        .unwrap_or("");

    let ident = if ident == "" { "_empty" } else { ident };

    format!("{}-{}", ident, short_hash(id.canonical_url()))
}

impl<'cfg> Debug for GitSource<'cfg> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "git repo at {}", self.remote.url())?;

        match self.manifest_reference.pretty_ref() {
            Some(s) => write!(f, " ({})", s),
            None => Ok(()),
        }
    }
}

impl<'cfg> Source for GitSource<'cfg> {
    fn query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
        let src = self
            .path_source
            .as_mut()
            .expect("BUG: `update()` must be called before `query()`");
        src.query(dep, f)
    }

    fn fuzzy_query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
        let src = self
            .path_source
            .as_mut()
            .expect("BUG: `update()` must be called before `query()`");
        src.fuzzy_query(dep, f)
    }

    fn supports_checksums(&self) -> bool {
        false
    }

    fn requires_precise(&self) -> bool {
        true
    }

    fn source_id(&self) -> SourceId {
        self.source_id
    }

    fn update(&mut self) -> CargoResult<()> {
        let git_path = self.config.git_path();
        let git_path = self.config.assert_package_cache_locked(&git_path);
        let db_path = git_path.join("db").join(&self.ident);

        let db = self.remote.db_at(&db_path).ok();
        let (db, actual_rev) = match (self.locked_rev, db) {
            // If we have a locked revision, and we have a preexisting database
            // which has that revision, then no update needs to happen.
            (Some(rev), Some(db)) if db.contains(rev) => (db, rev),

            // If we're in offline mode, we're not locked, and we have a
            // database, then try to resolve our reference with the preexisting
            // repository.
            (None, Some(db)) if self.config.offline() => {
                let rev = db
                    .resolve(&self.manifest_reference, None)
                    .with_context(|| {
                        "failed to lookup reference in preexisting repository, and \
                         can't check for updates in offline mode (--offline)"
                    })?;
                (db, rev)
            }

            // ... otherwise we use this state to update the git database. Note
            // that we still check for being offline here, for example in the
            // situation that we have a locked revision but the database
            // doesn't have it.
            (locked_rev, db) => {
                if self.config.offline() {
                    anyhow::bail!(
                        "can't checkout from '{}': you are in the offline mode (--offline)",
                        self.remote.url()
                    );
                }
                self.config.shell().status(
                    "Updating",
                    format!("git repository `{}`", self.remote.url()),
                )?;

                trace!("updating git source `{:?}`", self.remote);

                self.remote.checkout(
                    &db_path,
                    db,
                    &self.manifest_reference,
                    locked_rev,
                    self.config,
                )?
            }
        };

        // Don't use the full hash, in order to contribute less to reaching the
        // path length limit on Windows. See
        // <https://github.com/servo/servo/pull/14397>.
        let short_id = db.to_short_id(actual_rev)?;

        // Check out `actual_rev` from the database to a scoped location on the
        // filesystem. This will use hard links and such to ideally make the
        // checkout operation here pretty fast.
        let checkout_path = git_path
            .join("checkouts")
            .join(&self.ident)
            .join(short_id.as_str());
        db.copy_to(actual_rev, &checkout_path, self.config)?;

        let source_id = self.source_id.with_precise(Some(actual_rev.to_string()));
        let path_source = PathSource::new_recursive(&checkout_path, source_id, self.config);

        self.path_source = Some(path_source);
        self.locked_rev = Some(actual_rev);
        self.path_source.as_mut().unwrap().update()
    }

    fn download(&mut self, id: PackageId) -> CargoResult<MaybePackage> {
        trace!(
            "getting packages for package ID `{}` from `{:?}`",
            id,
            self.remote
        );
        self.path_source
            .as_mut()
            .expect("BUG: `update()` must be called before `get()`")
            .download(id)
    }

    fn finish_download(&mut self, _id: PackageId, _data: Vec<u8>) -> CargoResult<Package> {
        panic!("no download should have started")
    }

    fn fingerprint(&self, _pkg: &Package) -> CargoResult<String> {
        Ok(self.locked_rev.as_ref().unwrap().to_string())
    }

    fn describe(&self) -> String {
        format!("Git repository {}", self.source_id)
    }

    fn add_to_yanked_whitelist(&mut self, _pkgs: &[PackageId]) {}

    fn is_yanked(&mut self, _pkg: PackageId) -> CargoResult<bool> {
        Ok(false)
    }
}

#[cfg(test)]
mod test {
    use super::ident;
    use crate::core::{GitReference, SourceId};
    use crate::util::IntoUrl;

    #[test]
    pub fn test_url_to_path_ident_with_path() {
        let ident = ident(&src("https://github.com/carlhuda/cargo"));
        assert!(ident.starts_with("cargo-"));
    }

    #[test]
    pub fn test_url_to_path_ident_without_path() {
        let ident = ident(&src("https://github.com"));
        assert!(ident.starts_with("_empty-"));
    }

    #[test]
    fn test_canonicalize_idents_by_stripping_trailing_url_slash() {
        let ident1 = ident(&src("https://github.com/PistonDevelopers/piston/"));
        let ident2 = ident(&src("https://github.com/PistonDevelopers/piston"));
        assert_eq!(ident1, ident2);
    }

    #[test]
    fn test_canonicalize_idents_by_lowercasing_github_urls() {
        let ident1 = ident(&src("https://github.com/PistonDevelopers/piston"));
        let ident2 = ident(&src("https://github.com/pistondevelopers/piston"));
        assert_eq!(ident1, ident2);
    }

    #[test]
    fn test_canonicalize_idents_by_stripping_dot_git() {
        let ident1 = ident(&src("https://github.com/PistonDevelopers/piston"));
        let ident2 = ident(&src("https://github.com/PistonDevelopers/piston.git"));
        assert_eq!(ident1, ident2);
    }

    #[test]
    fn test_canonicalize_idents_different_protocols() {
        let ident1 = ident(&src("https://github.com/PistonDevelopers/piston"));
        let ident2 = ident(&src("git://github.com/PistonDevelopers/piston"));
        assert_eq!(ident1, ident2);
    }

    fn src(s: &str) -> SourceId {
        SourceId::for_git(&s.into_url().unwrap(), GitReference::DefaultBranch).unwrap()
    }
}


text:
using BrewLib.UserInterface;
using BrewLib.UserInterface.Skinning.Styles;
using BrewLib.Util;
using OpenTK;
using StorybrewEditor.ScreenLayers;
using StorybrewEditor.UserInterface.Skinning.Styles;
using System;

namespace StorybrewEditor.UserInterface
{
    public class PathSelector : Widget
    {
        private readonly PathSelectorMode mode;

        private readonly LinearLayout layout;
        private readonly Textbox textbox;
        private readonly Button button;

        public override Vector2 MinSize => layout.MinSize;
        public override Vector2 MaxSize => layout.MaxSize;
        public override Vector2 PreferredSize => layout.PreferredSize;

        public string LabelText { get { return textbox.LabelText; } set { textbox.LabelText = value; } }
        public string Value { get { return textbox.Value; } set { textbox.Value = value; } }

        public string Filter = "All files (*.*)|*.*";
        public string SaveExtension = "";

        public event EventHandler OnValueChanged;
        public event EventHandler OnValueCommited;

        public PathSelector(WidgetManager manager, PathSelectorMode mode) : base(manager)
        {
            this.mode = mode;

            Add(layout = new LinearLayout(manager)
            {
                AnchorFrom = BoxAlignment.Centre,
                AnchorTo = BoxAlignment.Centre,
                Horizontal = true,
                Fill = true,
                FitChildren = true,
                Children = new Widget[]
                {
                    textbox = new Textbox(manager)
                    {
                        AnchorFrom = BoxAlignment.BottomLeft,
                        AnchorTo = BoxAlignment.BottomLeft,
                    },
                    button = new Button(manager)
                    {
                        Icon = IconFont.FolderOpen,
                        Tooltip = "Browse",
                        AnchorFrom = BoxAlignment.BottomRight,
                        AnchorTo = BoxAlignment.BottomRight,
                        CanGrow = false,
                    },
                },
            });

            textbox.OnValueChanged += (sender, e) => OnValueChanged?.Invoke(this, EventArgs.Empty);
            textbox.OnValueCommited += (sender, e) => OnValueCommited?.Invoke(this, EventArgs.Empty);
            button.OnClick += (sender, e) =>
            {
                switch (mode)
                {
                    case PathSelectorMode.Folder:
                        Manager.ScreenLayerManager.OpenFolderPicker(LabelText, textbox.Value, (path) => textbox.Value = path);
                        break;
                    case PathSelectorMode.OpenFile:
                        Manager.ScreenLayerManager.OpenFilePicker(LabelText, textbox.Value, null, Filter, (path) => textbox.Value = path);
                        break;
                    case PathSelectorMode.OpenDirectory:
                        Manager.ScreenLayerManager.OpenFilePicker(LabelText, "", textbox.Value, Filter, (path) => textbox.Value = path);
                        break;
                    case PathSelectorMode.SaveFile:
                        Manager.ScreenLayerManager.OpenSaveLocationPicker(LabelText, textbox.Value, SaveExtension, Filter, (path) => textbox.Value = path);
                        break;
                }
            };
        }

        protected override WidgetStyle Style => Manager.Skin.GetStyle<PathSelectorStyle>(BuildStyleName());

        protected override void ApplyStyle(WidgetStyle style)
        {
            base.ApplyStyle(style);
            var pathSelectorStyle = (PathSelectorStyle)style;

            layout.StyleName = pathSelectorStyle.LinearLayoutStyle;
            textbox.StyleName = pathSelectorStyle.TextboxStyle;
            button.StyleName = pathSelectorStyle.ButtonStyle;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
            }
            base.Dispose(disposing);
        }

        protected override void Layout()
        {
            base.Layout();
            layout.Size = Size;
        }
    }

    public enum PathSelectorMode
    {
        Folder,
        OpenFile,
        OpenDirectory,
        SaveFile,
    }
}


text:
\documentclass[version=last, fontsize=12pt]{scrlttr2}   % references message.lco

\usepackage{letterAlinz}

% http://tex.stackexchange.com/a/54077
% firsthead
\begin{document}

\LoadLetterOptions{letterStyleAlinz, example}

\setkomavar{yourref}{}
\setkomavar{yourmail}{}
\setkomavar{myref}{}
\setkomavar{customer}{}
\setkomavar{invoice}{}
\setkomavar{place}{Leipzig}
\setkomavar{date}{\today}

\setkomavar{title}{Mahnung}
\addtokomafont{title}{\scshape\color{red}}

\setkomavar{subject}{Ein wichtiger Betreff}
\begin{letter}[%
%    subject=untitled,% underlined, centered, right, afteropening
    headsepline=true,%
    footsepline=false,%
    fromlogo%
]{%
    Marianne Beispielmann\\
    Kreisverkehr 12a\\
    23421 Eckstadt%
}

\opening{Sehr geehrte \usekomavar{toname},}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.

Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.

Suspendisse lectus leo, consectetur in tempor sit amet, placerat quis neque. Etiam luctus porttitor lorem, sed suscipit est rutrum non. Curabitur lobortis nisl a enim congue semper. Aenean commodo ultrices imperdiet. Vestibulum ut justo vel sapien venenatis tincidunt. Phasellus eget dolor sit amet ipsum dapibus condimentum vitae quis lectus. Aliquam ut massa in turpis dapibus convallis. Praesent elit lacus, vestibulum at malesuada et, ornare et est. Ut augue nunc, sodales ut euismod non, adipiscing vitae orci. Mauris ut placerat justo. Mauris in ultricies enim. Quisque nec est eleifend nulla ultrices egestas quis ut quam. Donec sollicitudin lectus a mauris pulvinar id aliquam urna cursus. Cras quis ligula sem, vel elementum mi. Phasellus non ullamcorper urna.

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In euismod ultrices facilisis. Vestibulum porta sapien adipiscing augue congue id pretium lectus molestie. Proin quis dictum nisl. Morbi id quam sapien, sed vestibulum sem. Duis elementum rutrum mauris sed convallis. Proin vestibulum magna mi. Aenean tristique hendrerit magna, ac facilisis nulla hendrerit ut. Sed non tortor sodales quam auctor elementum. Donec hendrerit nunc eget elit pharetra pulvinar. Suspendisse id tempus tortor. Aenean luctus, elit commodo laoreet commodo, justo nisi consequat massa, sed vulputate quam urna quis eros. Donec vel.

\closing{Mit freundlichen Grüßen,}

\ps PS: Leider vergas ich Ihnen mitzuteilen das Sie das Licht ausmachen müssen!

\setkomavar*{enclseparator}{Anlage}
\encl{{%
    \small%
    \begin{itemize}%
        \item Nichts
    \end{itemize}%
}}

\cc{%
    Frau Mustermann\\
    Die Nachbarin
}
\end{letter}

\end{document}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author Alban Gaignard <alban.gaignard@univ-nantes.fr>
 */
public class VarNameRegex {

    public VarNameRegex() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    // TODO add test methods here.
    // The methods must be annotated with annotation @Test. For example:
    //
    @Test
    public void hello() {
        Pattern pattern = Pattern.compile("\\?[a-zA-Z]+_[0-9]+");

        Matcher m1 = pattern.matcher("?o_22");
        Matcher m2 = pattern.matcher("?ab_254");
        Matcher m3 = pattern.matcher("?AB_2");
        Matcher m4 = pattern.matcher("?xY_1092");
        Assert.assertTrue(m1.matches());
        Assert.assertTrue(m2.matches());
        Assert.assertTrue(m3.matches());
        Assert.assertTrue(m4.matches());

        Matcher m5 = pattern.matcher("?xY");
        Matcher m6 = pattern.matcher("?x54");
        Assert.assertFalse(m5.matches());
        Assert.assertFalse(m6.matches());
    }
}


text:
from __future__ import unicode_literals

import re

from .common import InfoExtractor
from ..compat import compat_b64decode
from ..utils import (
    qualities,
    sanitized_Request,
)

class DumpertIE(InfoExtractor):
    _VALID_URL = r'(?P<protocol>https?)://(?:www\.)?dumpert\.nl/(?:mediabase|embed)/(?P<id>[0-9]+/[0-9a-zA-Z]+)'
    _TESTS = [{
        'url': 'http://www.dumpert.nl/mediabase/6646981/951bc60f/',
        'md5': '1b9318d7d5054e7dcb9dc7654f21d643',
        'info_dict': {
            'id': '6646981/951bc60f',
            'ext': 'mp4',
            'title': 'Ik heb nieuws voor je',
            'description': 'Niet schrikken hoor',
            'thumbnail': r're:^https?://.*\.jpg$',
        }
    }, {
        'url': 'http://www.dumpert.nl/embed/6675421/dc440fe7/',
        'only_matching': True,
    }]

    def _real_extract(self, url):
        mobj = re.match(self._VALID_URL, url)
        video_id = mobj.group('id')
        protocol = mobj.group('protocol')

        url = '%s://www.dumpert.nl/mediabase/%s' % (protocol, video_id)
        req = sanitized_Request(url)
        req.add_header('Cookie', 'nsfw=1; cpc=10')
        webpage = self._download_webpage(req, video_id)

        files_base64 = self._search_regex(
            r'data-files="([^"]+)"', webpage, 'data files')

        files = self._parse_json(
            compat_b64decode(files_base64).decode('utf-8'),
            video_id)

        quality = qualities(['flv', 'mobile', 'tablet', '720p'])

        formats = [{
            'url': video_url,
            'format_id': format_id,
            'quality': quality(format_id),
        } for format_id, video_url in files.items() if format_id != 'still']
        self._sort_formats(formats)

        title = self._html_search_meta(
            'title', webpage) or self._og_search_title(webpage)
        description = self._html_search_meta(
            'description', webpage) or self._og_search_description(webpage)
        thumbnail = files.get('still') or self._og_search_thumbnail(webpage)

        return {
            'id': video_id,
            'title': title,
            'description': description,
            'thumbnail': thumbnail,
            'formats': formats
        }


text:
//
//  ========================================================================
//  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.client.helperClasses;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ssl.SslSocketConnector;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.ssl.SslContextFactory;

/* ------------------------------------------------------------ */
/**
 */
public abstract class AbstractSslServerAndClientCreator implements ServerAndClientCreator
{
    private static final Logger LOG = Log.getLogger(AbstractSslServerAndClientCreator.class);

    /* ------------------------------------------------------------ */
    public Server createServer() throws Exception
    {
        Server server = new Server();
        // SslSelectChannelConnector connector = new SslSelectChannelConnector();
        SslSocketConnector connector = new SslSocketConnector();

        String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath();

        connector.setPort(0);
        SslContextFactory cf = connector.getSslContextFactory();
        cf.setKeyStorePath(keystore);
        cf.setKeyStorePassword("storepwd");
        cf.setKeyManagerPassword("keypwd");

        server.setConnectors(new Connector[]{ connector });
        server.setHandler(new GenericServerHandler());
        server.start();
        return server;
    }

}


text:
"use strict";

var mumble = require('../');
var fs = require('fs');

var options = {};
try {
    options = {
        key: fs.readFileSync( 'key.pem' ),
        cert: fs.readFileSync( 'key.pem' )
    };
} catch( e ) {
    console.log( 'Could not load private/public certificate files.' );
    console.log( 'Trying to connect without client certificate.' );
}

var tree = "";

function buildChannelTree(channel, level) {
    for(var i = 0; i < level; i++) {
        tree += "   ";
    }
    tree += "  - " + channel.name + ": ";
    for(var u in channel.users) {
        var user = channel.users[u];
        tree += user.name + ", ";
    }
    tree += "\n";
    for(var c in channel.children) {
        buildChannelTree(channel.children[c], level + 1);
    }
}

console.log( 'Connecting' );
mumble.connect( process.env.MUMBLE_URL, options, function ( error, connection ) {
    if(error) { throw new Error(error); }
    console.log('Connected');
    connection.on('ready', function() {
        console.log("Ready!");
        buildChannelTree(connection.rootChannel, 0);
        console.log(tree);
        console.log("Those were all channels!");
        console.log("Users:");
        var list = connection.users();
        for(var key in list) {
            var user = list[key];
            console.log("  - " + user.name + " in channel " + user.channel.name);
        }
        console.log("\nThose were all users!");
    });
    connection.on('channel-move', function(channel, from, to) {
        console.log("Channel " + channel.name + " was moved from " + from.name + " to " + to.name );
    });
    connection.on('channel-links-add', function(channel, links) {
        for(var key in links) {
            console.log("Channel " + links[key].name + " was linked to " + channel.name);
        }
    });
    connection.on('channel-links-remove', function(channel, links) {
        for(var key in links) {
            console.log("Channel " + links[key].name + " was unlinked from " + channel.name);
        }
    });
    connection.on('channel-rename', function(channel, oldName, newName) {
        console.log("Channel " + oldName + " was renamed to " + newName);
    });
    connection.on('user-mute', function(user, muted, actor) {
        console.log("User " + user.name + " changed mute to: " + muted + " by " + actor.name );
    });
    connection.on('user-self-deaf', function(user, deaf, actor) {
        console.log("User " + user.name + " changed deaf to: " + deaf + " by " + actor.name );
    });
    connection.on('user-self-mute', function(user, muted, actor) {
        console.log("User " + user.name + " changed self-mute to: " + muted + " by " + actor.name );
    });
    connection.on('user-suppress', function(user, suppress, actor) {
        console.log("User " + user.name + " changed suppress to: " + suppress + " by " + actor.name );
    });
    connection.on('user-move', function(user, fromChannel, toChannel, actor) {
        console.log("User " + user.name + " moved from channel " + fromChannel.name + " to " + toChannel.name + " by " + actor.name );
    });
    connection.on('user-recording', function( user, state , actor) {
        console.log("User " + user.name + ( state ? ' started' : ' stopped' ) + " recording"  + " by " + actor.name );
    });
    connection.on('user-disconnect', function(user) {
        console.log("User " + user.name + " disconnected");
    });
    connection.on('user-connect', function(user) {
        console.log("User " + user.name + " connected");
    });
    connection.on('channel-create', function(channel) {
        console.log("Channel " + channel.name + " created");
    });
    connection.on('channel-remove', function(channel) {
        console.log("Channel " + channel.name + " removed");
    });
    connection.on('message', function(message, actor) {
        if( handleCommand( message, actor, connection ) ) {
            return;
        }

        actor.sendMessage("I received: '" + message + "'");
        connection.user.channel.sendMessage("I received: '" + message + "'");
    });
    connection.on('voice-start', function( user ) {
        console.log( 'User ' + user.name + ' started voice transmission' );
    });
    connection.on('voice-end', function( user ) {
        console.log( 'User ' + user.name + ' ended voice transmission' );
    });
    connection.authenticate('ExampleUser');
});

var commands = [
    {
        command: /!channel permissions: (.*)/,
        action: function( context, channelName ) {
            var channel = context.connection.channelByName( channelName );
            if( !channel ) {
                return context.actor.sendMessage( 'Unknown channel: ' + channelName );
            }

            channel.getPermissions( function( err, permissions ) {
                if( err ) { return context.actor.sendMessage( 'Error: ' + err ); }
                context.actor.sendMessage( channelName + ' permissions: ' + JSON.stringify( permissions ) );
            });
        }
    },
    {
        command: /!msg ([^:]+): (.*)/,
        action: function( context, names, message ) {

            var recipients = { session: [], channelId: [] };

            names = names.split( ',' );
            for( var n in names ) {
                var name = names[n];

                var user = context.connection.userByName( name );
                if( user ) {
                    recipients.session.push( user.session );
                }

                var channel = context.connection.channelByName( name );
                if( channel ) {
                    recipients.channelId.push( channel.id );
                }
            }

            context.connection.sendMessage( message, recipients );
        }
    },
    {
        command: /!create ([^.]+)\.(.*)/,
        action: function( context, parent, name ) {

            var parent = context.connection.channelByName( parent );
            parent.addSubChannel( name );
        }
    },
    {
        command: /!remove (.+)/,
        action: function( context, name ) {

            var channel = context.connection.channelByName( name );
            channel.remove();
        }
    },

    {
        command: /!join (.+)/,
        action: function( context, name ) {

            var channel = context.connection.channelByPath( name );
            channel.join();
        }
    },
];

var handleCommand = function( message, actor, connection ) {
    for( var c in commands ) {
        var cmd = commands[c];

        var match = cmd.command.exec( message );
        if( !match ) {
            continue;
        }

        var params = match.slice(1);
        params.unshift({ message: message, actor: actor, connection: connection });
        cmd.action.apply( null, params );

        return true;
    }
};


text:
package org.joyrest.maven.gendoc;

public enum Content {
	ALL,
	PATH,
	METHOD,
	CONSUMES,
	PRODUCES,
	REQUEST,
	RESPONSE,
	ASPECTS,
	READERS,
	WRITERS,
	EXCEPTION_HANDLERS
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../">
  <title data-ice="title">src/configurators/Positioning.js | guide4you</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

<meta name="description" content="A configurable web client for geo-applications. Uses OpenLayers. Suitable for mobile devices."><meta property="twitter:card" content="summary"><meta property="twitter:title" content="guide4you"><meta property="twitter:description" content="A configurable web client for geo-applications. Uses OpenLayers. Suitable for mobile devices.">

  Home

  Reference
  Source

    <input class="search-input">

CAttributions

CDebug

CFeaturePopup

CFeatureTooltip

CG4UMap

CL10N

CListenerOrganizerMixin

CMessageDisplay

CModule

CMove

CPopupModifierManager

CStyling

FmultiplyExtent

FcreateMapInternal

FgetRegisteredModules

FregisterModule

FasObject

FasyncImageLoad

FcheckFor

Feven

FfinishAllImages

FgetConfig

Fhtml2Text

Fmixin

FmixinAsClass

Fodd

Foffset

FrecursiveSelect

FshowInteractionActivity

FurlDirname

FurlIsAbsolute

FurlJoin

FurlNormalize

FurlRelative

Fcopy

FcopyDeep

Fmerge

FmergeDeep

Ftake

FfilterText

FrestoreText

VolEventTypes

VcssClasses

VkeyCodes

TFeaturePopupOptions

TFeatureTooltipOptions

TConfigs

TG4UMapOptions

TL10NOptions

TLocalizable

TMessageConstructorOptions

TMessageDisplayOptions

TMessageReducedDisplayOptions

TMoveOptions

TSingleMoveOptions

TPopupContent

TShowWMSFeatureInfoOptions

TStyleLike

TStyleObject

TURLConfig

TURLLike

apiCFeatureAPI

CGeometryAPI

CKMLAPI

CMeasureAPI

CPlacesAPI

CPrintToScaleAPI

TAPIOptions

configuratorsCControlFactory

CLayerConfigurator

CLayerFactory

CMapConfigurator

CUIConfigurator

VLayerType

TControlFactoryOptions

TControlsConfig

TAnyLayerConfig

TAnyLayerConfig

TBingLayerConfig

TBingLayerConfig

TCategoryLayerConfig

TCategoryLayerConfig

TEmptyLayerConfig

TEmptyLayerConfig

TFeatureConfig

TFeatureConfig

TGeoJSONLayerConfig

TGeoJSONLayerConfig

TInternalLayerConfig

TInternalLayerConfig

TInternalSourceConfig

TInternalSourceConfig

TKMLLayerConfig

TKMLLayerConfig

TLayerConfig

TOSMLayerConfig

TOSMLayerConfig

TSilentGroupLayerConfig

TSilentGroupLayerConfig

TSourceConfig

TSourceConfig

TStamenLayerConfig

TStamenLayerConfig

TTileWMSLayerConfig

TTileWMSLayerConfig

TVectorSourceConfig

TVectorSourceConfig

TWMSLayerConfig

TWMSLayerConfig

TWMTSLayerConfig

TWMTSLayerConfig

TWMTSSSourceConfig

TWMTSSSourceConfig

TXYZLayerConfig

TXYZLayerConfig

Tg4uLayerOptions

Tg4uLayerOptions

TKineticOptions

TMapConfig

TMobileLayoutOptions

TProjectionConfig

Tg4uViewOptions

TFloat

THideableElement

TPositionedElement

TPositioningOptions

controlsCActivatableMixin

CActiveGroup

CArrowButtons

CAttribution

CCombinedZoom

CZoom

CZoomSlider

CComposedControl

CControlLogicMixin

CGeolocationButton

CHelpButton

CInfoButton

CLanguageSwitcherButton

CLanguageSwitcherMenu

CLayerSelector

CLegendViewer

CLinkButton

CLogo

CMeasurementButton

CMobileControls

CMousePosition

COverviewMap

CPrintButton

CRewireMixin

CScaleLine

CShiftableComposedControl

CSingleDrawButton

CWindowDecorator

CZoomToBbox

VControl

TArrowButtonOptions

TCombinedZoomOptions

TZoomOptions

TComposedControlOptions

Tg4uControlOptions

TGeoLocationButtonOptions

THelpButtonOptions

TInfoButtonOptions

TLanguageSwitcherButtonOptions

TLanguageSwitcherMenuOptions

TLayerButton

TLayerSelectorOptions

TLinkButtonOptions

TLogoOptions

TMeasurementButtonOptions

TMousePositionOptions

TOverviewMapOptions

TShiftableComposedControlOptions

TDrawButtonsOptions

TStaticOverviewMapOptions

TWindowDecoratorOptions

htmlCButtonBox

CCheckGroup

CDropdown

CHistory

CShield

CWindow

FaddTooltip

FchangeTooltip

FgetInFront

TButtonBoxOptions

TDropdownOptions

TEntry

TElementPosition

TOnTopOptions

TShieldOptions

TWindowOptions

interactionsCClickableInteraction

TFeatureInteractionOptions

TMapEventInteractionOptions

layerSelectorCAccordion

CButton

CElement

CGroupElement

CLayerButton

CMultiButton

CWMSLayerButton

FlayerConfigConverter

TButtonActions

TButtonConfig

TGroupButtonConfig

TLayerButtonConfig

TLayerSelectorOptions

TWMSLayerButtonConfig

layersCBaseLayerMixin

CEmptyImageLayer

CGroupLayer

CLayerLoadProcessCountMixin

CProvideMapMixin

CSilentGroupLayer

CVectorImageLayer

VImageLayer

VTileLayer

TBaseLayerMixinOptions

TVectorLayerOptions

searchCSearchControl

TSearchControlOptions

TSearchControlModuleOptions

TSearchViewOptions

search/connectorsCG4USearchV2Connector

CG4UServerSearchConnector

CNominatimSearchConnector

CNominatimSearchConnector

TSearchConnectorOptions

sourcesCClusterSource

CTileWMSSource

CQueryVectorSource

CQueryWMSMixin

CSourceServerVector

CWMTSSource

VQueryImageWMSSource

VQueryTileWMSSource

TArcGISRESTFeatureSourceOptions

TWMSFeatureInfoOptions

TWMSSSourceConfig

TQuerySourceOptions

TSourceServerVectorOptions

urlapiCLinkGenerator

CMarker

CQuery

CURLAPI

CURLAPIModule

TLinkGeneratorOptions

TMarkerOptions

TURLAPIOptions

TURLParameter

urlapi/controlsCCloseWindowButton

CLinkGeneratorButton

CMaximizeButton

TCloseWindowButtonOptions

TLinkGeneratorButtonOptions

TMaximizeButtonOptions

urlapi/handlingVavailableLayersParam

VcenterParam

VcloseButtonParam

VconfigurationFileParam

VfitRectangleParam

VlanguageParam

VlayerConfigurationFileParam

VmarkerParam

VresponsivenessParam

VrotationParam

VsearchParam

VvisibleLayersParam

VzoomParam

src/configurators/Positioning.js

import $ from 'jquery'
import uniq from 'lodash/uniq'

import { cssClasses } from '../globals'
import { ListenerOrganizerMixin } from '../ListenerOrganizerMixin'
import { mixinAsClass } from '../utilities'

/**
 * This describes the floating directions of an element. It can be an array, then it will move from the center to the
 * first specified direction and after that it moves in the second direction. If it is set to 'fixed' it is not
 * positioned via Positioning.
 * @typedef {string[]|string} Float
 */

/**
 * @typedef {Object} HideableElement
 * @property {Control} control
 * @property {number} importance
 * @property {number} order
 * @property {Float} [float] first and second direction or special value 'fixed'
 * @property {HideableElement[]} [hideableChildren]
 */

/**
 * @typedef {HideableElement} PositionedElement
 * @property {string[]} float first and second direction or special value 'fixed'
 * @property {number} minWidth
 * @property {number} minHeight
 * @property {{width: number, height: number}} size
 */

/**
 * @typedef {object} PositioningOptions
 * @property {number} [padding=5]
 * @property {number} [spacing=10]
 * @property {HTMLElement} viewport
 */

export class Positioning extends mixinAsClass(ListenerOrganizerMixin) {
  /**
   * @param {PositioningOptions} options
   */
  constructor (options) {
    super()
    /**
     * @type {jQuery|HTMLElement}
     * @private
     */
    this.$viewport_ = $(options.viewport)

    /**
     * The padding between the controls
     * @type {number}
     * @private
     */
    this.padding_ = options.padding || 5

    /**
     * The space between the controls and the edges of the map
     * @type {number}
     * @private
     */
    this.spacing_ = options.spacing || 10

    /**
     * The hidden controle
     * @type {jQuery}
     * @private
     */
    this.hidden$Elements_ = []

    this.init()
  }

  init () {
    this.detachAllListeners()

    /**
     * @type {HideableElement[]}
     * @private
     */
    this.all_ = []

    /**
     * All Controls stored according their position on the map
     * @type {object}
     * @private
     */
    this.corners_ = {
      left: {
        top: {
          counterclockwise: [],
          clockwise: []
        },
        bottom: {
          counterclockwise: [],
          clockwise: []
        }
      },
      right: {
        top: {
          counterclockwise: [],
          clockwise: []
        },
        bottom: {
          counterclockwise: [],
          clockwise: []
        }
      }
    }

    /**
     * This number tracks the order in which controls are added
     * @type {number}
     * @private
     */
    this.order_ = 0
  }

  getArray_ (float) {
    let x, y, direction
    switch (float[0]) {
      case 'top':
        y = 'top'
        x = float[1]
        if (x === 'left') {
          direction = 'clockwise'
        } else if (x === 'right') {
          direction = 'counterclockwise'
        }
        break
      case 'right':
        x = 'right'
        y = float[1]
        if (y === 'top') {
          direction = 'clockwise'
        } else if (y === 'bottom') {
          direction = 'counterclockwise'
        }
        break
      case 'bottom':
        y = 'bottom'
        x = float[1]
        if (x === 'left') {
          direction = 'counterclockwise'
        } else {
          direction = 'clockwise'
        }
        break
      case 'left':
        x = 'left'
        y = float[1]
        if (y === 'top') {
          direction = 'counterclockwise'
        } else {
          direction = 'clockwise'
        }
    }

    return this.corners_[x][y][direction]
  }

  /**
   * Add a control to the positioning.
   * @param {Control} control
   * @param {Object} [parentMeta] the meta information of the parent control
   */
  addControl (control, parentMeta) {
    // check if control needs to be positioned
    if (control.get$Element().parents().hasClass('ol-viewport')) {
      if (!parentMeta || !parentMeta.control.isWindowed()) {
        // gather metainformation
        /** @type {HideableElement} */
        const metaElem = {
          control,
          order: this.order_++,
          importance: control.getImportance()
        }

        control.on('change:visible', e => {
          const index = this.hidden$Elements_.indexOf(control.get$Element())
          if (e.oldValue && index > -1) {
            this.hidden$Elements_.splice(index, 1)
          }
          this.positionElements()
        })

        // repositioning if collapsible elements changes size
        this.listenAt(control).on('change:size', () => {
          this.positionElements()
        })

        if (!parentMeta) {
          const float = metaElem.control.getFloat() || ['top', 'left']

          if (float === 'fixed') {
            return
          }

          this.getArray_(float).push(metaElem)

          this.all_.push(metaElem)

          if (metaElem.control.getControls) {
            metaElem.hideableChildren = []
            for (const child of metaElem.control.getControls()) {
              this.addControl(child, metaElem)
            }
          }
        } else if (!parentMeta.control.isWindowed()) {
          metaElem.importance = control.getImportance()
          parentMeta.hideableChildren.push(metaElem)
          this.all_.push(metaElem)
        }
      }
    }
  }

  /**
   * Gets the element in a corner
   * @param {string} x
   * @param {string} y
   * @returns {HideableElement}
   * @private
   */
  getCorner_ (x, y) {
    let cwi = 0
    let ccwi = 0

    let cwElem = this.corners_[x][y].clockwise[cwi++]
    let ccwElem = this.corners_[x][y].counterclockwise[ccwi++]

    while (cwElem && !Positioning.isElemVisible_(cwElem)) {
      cwElem = this.corners_[x][y].clockwise[cwi++]
    }

    while (ccwElem && !Positioning.isElemVisible_(ccwElem)) {
      ccwElem = this.corners_[x][y].counterclockwise[ccwi++]
    }

    if (cwElem || ccwElem) {
      if (!cwElem) {
        return ccwElem
      } else if (!ccwElem) {
        return cwElem
      } else {
        if (cwElem.order < ccwElem.order) {
          return cwElem
        } else {
          return ccwElem
        }
      }
    }
  }

  static isElemVisible_ (elem) {
    return elem.control.get$Element().is(':visible')
  }

  /**
   * Gets all elements at one edge
   * @param side
   * @returns {*|Array.<Element>}
   * @private
   */
  getEdge_ (side) {
    let x1, x2, y1, y2
    if (side === 'top') {
      x1 = 'left'
      x2 = 'right'
      y1 = y2 = 'top'
    } else if (side === 'right') {
      x1 = x2 = 'right'
      y1 = 'top'
      y2 = 'bottom'
    } else if (side === 'bottom') {
      x1 = 'right'
      x2 = 'left'
      y1 = y2 = 'bottom'
    } else if (side === 'left') {
      x1 = x2 = 'left'
      y1 = 'bottom'
      y2 = 'top'
    }

    const clockwise = this.corners_[x1][y1].clockwise.filter(Positioning.isElemVisible_)
    const counterclockwise = this.corners_[x2][y2].counterclockwise.filter(Positioning.isElemVisible_)

    const arr = []
    let c = this.getCorner_(x1, y1)
    if (c) {
      arr.push(c)
    }
    arr.push(...clockwise)
    arr.push(...counterclockwise)
    c = this.getCorner_(x2, y2)
    if (c) {
      arr.push(c)
    }
    return uniq(arr)
  }

  /**
   * Initializes all elements
   * @private
   */
  beforePositioning_ () {
    const elems = new Set(this.all_)

    this.hidden$Elements_.forEach($e => $e.removeClass(cssClasses.hidden))
    this.hidden$Elements_ = []

    /**
     * @param {PositionedElement} elem
     */
    const forEach = elem => {
      if (Positioning.isElemVisible_(elem)) {
        if (elem.control.beforePositioning) {
          elem.control.beforePositioning()
        }

        if (elem.hideableChildren) {
          for (const child of elem.hideableChildren) {
            forEach(child)
          }
        }

        elem.control.get$Element().position({ top: 0, left: 0 })
        if (elem.control.release) {
          elem.control.release('height')
          elem.control.release('width')
        }
        elem.size = this.measureExpandedElement_(elem)
      }

      elems.delete(elem)
    }

    for (const elem of elems) {
      forEach(elem)
    }
  }

  /**
   * called after positioning
   * @private
   */
  afterPositioning_ () {
    const elems = new Set(this.all_)

    /**
     * @param {PositionedElement} elem
     */
    const forEach = elem => {
      if (elem.control.afterPositioning) {
        elem.control.afterPositioning()
      }

      if (elem.hideableChildren) {
        for (const child of elem.hideableChildren) {
          forEach(child)
        }
      }

      elems.delete(elem)
    }

    for (const elem of elems) {
      forEach(elem)
    }
  }

  /**
   * Calculates summed length of all elements on one edge
   * @param {PositionedElement[]} edgeElems
   * @param {string} dim
   * @returns {number}
   * @private
   */
  calculateLength_ (edgeElems, dim) {
    if (edgeElems.length === 0) {
      return 0
    }

    let length = this.padding_ * 2

    let firstElement = true

    for (const elem of edgeElems) {
      length += elem.size[dim]
      if (firstElement) {
        firstElement = false
      } else {
        length += this.spacing_
      }
    }

    return length
  }

  calculateSide_ (side, availableSpace) {
    const dim = (side === 'top' || side === 'bottom') ? 'width' : 'height'
    let elems = this.getEdge_(side)
    let wantedSpace = this.calculateLength_(elems, dim)
    let changed = false

    while (wantedSpace > availableSpace) {
      if (this.squeezeElements_(elems, dim, wantedSpace - availableSpace)) {
        break
      }
      this.hideLeastImportant_(elems)
      elems = this.getEdge_(side)
      wantedSpace = this.calculateLength_(elems, dim)
      changed = true
    }
    return changed
  }

  positionElementsCorner_ (x, y) {
    const corner = this.getCorner_(x, y)
    if (corner) {
      let xLength = this.padding_
      let yLength = this.padding_
      let $elem = corner.control.get$Element()

      $elem.removeClass(cssClasses.hidden).css({ [x]: xLength, [y]: yLength })

      xLength += $elem.outerWidth() + this.spacing_
      yLength += $elem.outerHeight() + this.spacing_

      let xDirection, yDirection

      if (x === 'left' && y === 'top') {
        xDirection = 'clockwise'
        yDirection = 'counterclockwise'
      } else if (x === 'right' && y === 'top') {
        xDirection = 'counterclockwise'
        yDirection = 'clockwise'
      } else if (x === 'right' && y === 'bottom') {
        xDirection = 'clockwise'
        yDirection = 'counterclockwise'
      } else if (x === 'left' && y === 'bottom') {
        xDirection = 'counterclockwise'
        yDirection = 'clockwise'
      }

      // x
      for (const elem of this.corners_[x][y][xDirection]
        .filter(el => Positioning.isElemVisible_(el) && el !== corner)) {
        $elem = elem.control.get$Element()
        $elem.css({ [x]: xLength, [y]: this.padding_ })
        xLength += $elem.outerWidth() + this.spacing_
      }

      // y
      for (const elem of this.corners_[x][y][yDirection]
        .filter(el => Positioning.isElemVisible_(el) && el !== corner)) {
        $elem = elem.control.get$Element()
        $elem.css({ [x]: this.padding_, [y]: yLength })
        yLength += $elem.outerHeight() + this.spacing_
      }
    }
  }

  /**
   * (Re-)Position the controls on the map
   */
  positionElements () {
    const width = this.$viewport_.innerWidth()
    const height = this.$viewport_.innerHeight()

    this.beforePositioning_()

    // calculation
    const processSides = new Set(['top', 'left', 'bottom', 'right'])

    while (processSides.size) {
      if (processSides.has('top')) {
        if (this.calculateSide_('top', width)) {
          processSides.add('left')
          processSides.add('right')
        }

        processSides.delete('top')
      }

      if (processSides.has('right')) {
        if (this.calculateSide_('right', height)) {
          processSides.add('top')
          processSides.add('bottom')
        }

        processSides.delete('right')
      }

      if (processSides.has('bottom')) {
        if (this.calculateSide_('bottom', width)) {
          processSides.add('left')
          processSides.add('right')
        }

        processSides.delete('bottom')
      }

      if (processSides.has('left')) {
        if (this.calculateSide_('left', height)) {
          processSides.add('top')
          processSides.add('bottom')
        }

        processSides.delete('left')
      }
    }

    // positioning

    this.positionElementsCorner_('left', 'top')
    this.positionElementsCorner_('right', 'top')
    this.positionElementsCorner_('right', 'bottom')
    this.positionElementsCorner_('left', 'bottom')

    this.afterPositioning_()
  }

  /**
   * Tries to squeeze the elements on one edge to fit the space. Returns true if it did work, false otherwise.
   * @param {PositionedElement[]} elems
   * @param {string} side
   * @param {number} neededSpace
   * @private
   * @returns {boolean}
   */
  squeezeElements_ (elems, side, neededSpace) {
    const squeezableElements = []

    function insert (item, x = 0, y = squeezableElements.length) {
      if (y === x) {
        squeezableElements.splice(x, 0, item)
      } else {
        const p = Math.floor((x + y) / 2)
        if (item.importance <= squeezableElements[p].importance) {
          insert(item, x, p)
        } else {
          insert(item, p + 1, y)
        }
      }
    }

    /**
     * @param {PositionedElement[]} elems
     */
    function findSqueezables (elems) {
      for (const elem of elems) {
        if (elem.control.isSqueezable && elem.control.isSqueezable(side)) {
          insert(elem)
        } else if (elem.hideableChildren) {
          findSqueezables(elem.hideableChildren)
        }
      }
    }

    findSqueezables(elems)

    for (const elem of squeezableElements) {
      neededSpace -= elem.control.squeezeBy(side, neededSpace)

      if (neededSpace <= 0) {
        return true
      }
    }

    for (const elem of squeezableElements) {
      elem.control.release(side)
    }

    return false
  }

  /**
   * Expands element to maximum size
   * @param {PositionedElement} elem
   * @returns {Array}
   * @private
   */
  expandElement_ (elem) {
    const expanded = []

    if (elem.hideableChildren) {
      for (const child of elem.hideableChildren) {
        expanded.push(...this.expandElement_(child))
      }
    }
    if (elem.control.getCollapsible && elem.control.getCollapsible()) {
      if (elem.control.getCollapsed()) {
        elem.control.setCollapsed(false, true)
        expanded.push(elem.control)
      }
    }

    return expanded
  }

  /**
   * measures size of the element
   * @param {PositionedElement} elem
   * @returns {{width: number, height: number}}
   * @private
   */
  measureExpandedElement_ (elem) {
    const $elem = elem.control.get$Element()
    return { width: $elem.outerWidth(), height: $elem.outerHeight() }
  }

  /**
   * Hides the least important element of the given ones.
   * @param {PositionedElement[]} elems visible elements
   * @private
   */
  hideLeastImportant_ (elems) {
    let leastImportant = elems[0]
    for (const elem of elems.slice(1)) {
      if (elem.importance < leastImportant.importance) {
        leastImportant = elem
      }
    }

    let childHidden = false
    if (leastImportant.hideableChildren) {
      const hideableChildren = leastImportant.hideableChildren.filter(Positioning.isElemVisible_)
      if (hideableChildren.length > 1) {
        this.hideLeastImportant_(hideableChildren)
        childHidden = true
      }
    }

    if (childHidden) {
      leastImportant.size = this.measureExpandedElement_(leastImportant)
    } else {
      leastImportant.control.get$Element().addClass(cssClasses.hidden)
      this.hidden$Elements_.push(leastImportant.control.get$Element())
    }
  }
}

  Generated by ESDoc(1.1.0)


text:
<?php
/**
 * FormView item control
 *
 * @author Frederic BAYLE <contact (at) made-in-softland (dot) com>
 * @version 2017-07-08
 */

namespace EDP\Web\Controls;

/**
 * FormView item control
 */
class FormViewItem extends PlaceHolder
{
    /**
     * Gets the FormView control DataItem
     *
     * @return mixed FormView control DataItem
     */
    protected function &GetDataItem()
    {
        return $this->GetNamingContainer()->DataItem;
    }
}


text:
<?php

namespace Jeloo\LaraMigrations;

use Illuminate\Support\Str;
use Illuminate\Support\Facades\Schema;

class SchemaParser implements SchemaParserInterface
{

    /**
     * @var array
     */
    private $input;

    /**
     * @var array
     */
    private $availableTypes = [
        'integer', 'string'
    ];

    /**
     * @var array
     */
    private $possibleColTypes = [
        'integer' => ['id', '.+_id'],
        'string'  => ['email', 'name', 'title'],
        'text'    => ['description', 'path']
    ];

    public function __construct(array $input)
    {
        $this->input = $input;
    }

    /**
     * @{inheritdoc}
     */
    public function parse()
    {
        return array_map(function ($colSettings) {
            $type = $this->parseType($colSettings);

            $schema = [
                'name'       => $this->getName($colSettings),
                'type'       => $type,
                'properties' => $this->parseProperties($colSettings, $type)
            ];

            if (
                array_search('foreign', $schema['properties']) !== false &&
                $relatedTable = $this->guessRelatedTableByName($colSettings)
            ) {
                $schema['belongsTo'] = $relatedTable;
            }

            return $schema;

        }, $this->input);
    }

    /**
     * @param array $colSettings
     * @return string
     */
    protected function getName(array $colSettings)
    {
        return $colSettings[0];
    }

    /**
     * @param array $colSettings
     * @return string - the type
     * @throws \Exception
     */
    protected function parseType(array $colSettings)
    {
        if ($intersect = array_intersect($this->availableTypes, $colSettings)) {
            return array_shift($intersect);
        }

        if (! $type = $this->guessTypeByName($this->getName($colSettings))) {
            $type = 'string';
        }

        return $type;
    }

    /**
     * @param $name
     * @return bool|string
     */
    protected function guessTypeByName($name)
    {
        foreach ($this->possibleColTypes as $type => $names) {
            $regex = sprintf('/^(%s)/', implode('|', $this->possibleColTypes[$type]));
            if (preg_match($regex, $name)) {
                return $type;
            }
        }

        return false;
    }

    /**
     * @param array $colSettings
     * @param string $type
     * @return array
     */
    protected function parseProperties(array $colSettings, $type)
    {
        //exclude name column
        $result = array_except($colSettings, 0);
        $typeIndex = array_search($type, $colSettings);

        $result = $typeIndex ? array_except($result, $typeIndex) : $result;
        // add foreign attribute if column looks like foreign column
        if (Str::endsWith($this->getName($colSettings), '_id')) {
           $result = array_merge($result, ['foreign', 'unsigned', 'nullable']);
        }

        return array_values($result);
    }

    /**
     * @param array $colSettings
     * @return bool|string
     */
    protected function guessRelatedTableByName(array $colSettings)
    {
        if (Str::endsWith($this->getName($colSettings), '_id')) {
            $table = str_replace('_id', '', $this->getName($colSettings));
            return Schema::hasTable($table) ? $table : Str::plural($table);
        }

        return false;
    }

}


text:
class CLampBeamProxy : public CEntityMaterialProxy
{
public:
						CLampBeamProxy( void );
	virtual				~CLampBeamProxy( void );
	virtual bool		Init( IMaterial *pMaterial, KeyValues* pKeyValues );
	virtual void		OnBind( C_BaseEntity *pC_BaseEntity );

private:

	IMaterialVar		*m_pFadeValue;
};

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CLampBeamProxy::CLampBeamProxy( void )
{
	m_pFadeValue = NULL;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CLampBeamProxy::~CLampBeamProxy( void )
{
}

//-----------------------------------------------------------------------------
// Purpose: Get pointer to the color value
// Input  : *pMaterial -
//-----------------------------------------------------------------------------
bool CLampBeamProxy::Init( IMaterial *pMaterial, KeyValues* pKeyValues )
{
	assert( pMaterial );

	// Need to get the color variable.
	bool found;
	m_pFadeValue = pMaterial->FindVar( "$alpha", &found );
	return found;
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *pC_BaseEntity -
//-----------------------------------------------------------------------------
#define FADE_DIST	150

void CLampBeamProxy::OnBind( C_BaseEntity *pEnt )
{
	if( !m_pFadeValue )
	{
		return;
	}

	Vector vecLocal;

	vecLocal = pEnt->GetAbsOrigin() - CurrentViewOrigin();
	VectorNormalize( vecLocal );

	float fade;
	fade = 1.0 - fabs( vecLocal.z );

	m_pFadeValue->SetFloatValue( fade );
}

EXPOSE_INTERFACE( CLampBeamProxy, IMaterialProxy, "lampbeam" IMATERIAL_PROXY_INTERFACE_VERSION );