text:
package com.example.contactstest;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ArrayAdapter<String> adapter;

    List<String> contactsList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView contactsView = (ListView) findViewById(R.id.contacts_view);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactsList);
        contactsView.setAdapter(adapter);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        } else {
            readContacts();
        }
    }

    private void readContacts() {
        Cursor cursor = null;
        try {
            //查询联系人数据
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    //获取联系人姓名
                    String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    //获取联系人手机号
                    String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    contactsList.add(displayName + "\n" + number);
                }
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    readContacts();
                } else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
    <title>Fight Club</title>

    Fight Club

    メニュー

    {% if info_msg is defined %}
    {{ info_msg }}

    {% endif %}
    {% block content %}
    {% endblock %}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Elkarte\Elkarte;

class Entity extends \ArrayObject
{
	public function __construct($input = null, $flags = 0, $iterator_class = 'ArrayIterator')
	{
		parent::__construct($this->getDefault(), $flags, $iterator_class);

		if (!empty($input))
		{
			$this->exchangeArray(array_merge($this->getArrayCopy(), (array) $input));
		}
	}

	/**
	 * Set the default for this object
	 * @return array the default array
	 */
	protected function getDefault()
	{
		return [];
	}

	/**
	 * Merge two entities.
	 * Should be used sparingly. Probably best to just use a loop and set the new values individually
	 *
	 * @param Entity $entity
	 * @return $this
	 */
	public function merge(Entity $entity)
	{
		$old = $this->getArrayCopy();
		$merge = array_merge($old, $entity->getArrayCopy());

		var_dump($old, $entity, $merge);
		$this->exchangeArray($merge);
		return $this;
	}

	/**
	 * @param $name
	 * @return mixed|void
	 */
	public function __get($name)
	{
		// It exists, just give it a shot
		if ($this->offsetExists($name))
		{
			return $this->offsetGet($name);
		}

		// A property exists with this name
		if (property_exists($this, $name))
		{
			return $this->$name;
		}

		// A method exists with this name
		if (method_exists($this, $name))
		{
			return $this->$name();
		}

		// Finally, try getMethodname
		$method = 'get' . ucfirst(str_replace(['_', '-'], '', $name));
		if (method_exists($this, $method))
		{
			return $this->$method();
		}
	}

	// @todo figure out why I was getting Notice: Indirect modification of overloaded property Elkarte\Boards\Category::$boards has no effect in /var/www/Elkarte2/Elkarte/src/Boards/Category.php on line 21
	/**
	 * Add a value to an internal array
	 *
	 * @param string|int $index
	 * @param mixed $value
	 * @param null|string|int $array_index
	 * @return array
	 */
	public function pushToArray($index, $value, $array_index = null)
	{
		$array = $this->offsetGet($index);

		if ($array_index === null)
		{
			$array[] = $value;
		}
		else
		{
			$array[$array_index] = $value;
		}

		$this->offsetSet($index, $array);

		return $array;
	}
}


text:
package com.google.android.exoplayer2.mediacodec;

import static java.lang.annotation.ElementType.TYPE_USE;

import android.media.MediaCodec;
import android.media.MediaCrypto;
import android.media.MediaFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.PersistableBundle;
import android.view.Surface;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.decoder.CryptoInfo;
import com.google.android.exoplayer2.util.TraceUtil;
import com.google.common.base.Supplier;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.ByteBuffer;

/**
 * A {@link MediaCodecAdapter} that operates the underlying {@link MediaCodec} in asynchronous mode,
 * routes {@link MediaCodec.Callback} callbacks on a dedicated thread that is managed internally,
 * and queues input buffers asynchronously.
 */
@RequiresApi(23)
/* package */ final class AsynchronousMediaCodecAdapter implements MediaCodecAdapter {

  /** A factory for {@link AsynchronousMediaCodecAdapter} instances. */
  public static final class Factory implements MediaCodecAdapter.Factory {
    private final Supplier<HandlerThread> callbackThreadSupplier;
    private final Supplier<HandlerThread> queueingThreadSupplier;
    private final boolean synchronizeCodecInteractionsWithQueueing;

    /**
     * Creates an factory for {@link AsynchronousMediaCodecAdapter} instances.
     *
     * @param trackType One of {@link C#TRACK_TYPE_AUDIO} or {@link C#TRACK_TYPE_VIDEO}. Used for
     *     labelling the internal thread accordingly.
     * @param synchronizeCodecInteractionsWithQueueing Whether the adapter should synchronize {@link
     *     MediaCodec} interactions with asynchronous buffer queueing. When {@code true}, codec
     *     interactions will wait until all input buffers pending queueing wil be submitted to the
     *     {@link MediaCodec}.
     */
    public Factory(@C.TrackType int trackType, boolean synchronizeCodecInteractionsWithQueueing) {
      this(
          /* callbackThreadSupplier= */ () ->
              new HandlerThread(createCallbackThreadLabel(trackType)),
          /* queueingThreadSupplier= */ () ->
              new HandlerThread(createQueueingThreadLabel(trackType)),
          synchronizeCodecInteractionsWithQueueing);
    }

    @VisibleForTesting
    /* package */ Factory(
        Supplier<HandlerThread> callbackThreadSupplier,
        Supplier<HandlerThread> queueingThreadSupplier,
        boolean synchronizeCodecInteractionsWithQueueing) {
      this.callbackThreadSupplier = callbackThreadSupplier;
      this.queueingThreadSupplier = queueingThreadSupplier;
      this.synchronizeCodecInteractionsWithQueueing = synchronizeCodecInteractionsWithQueueing;
    }

    @Override
    public AsynchronousMediaCodecAdapter createAdapter(Configuration configuration)
        throws IOException {
      String codecName = configuration.codecInfo.name;
      @Nullable AsynchronousMediaCodecAdapter codecAdapter = null;
      @Nullable MediaCodec codec = null;
      try {
        TraceUtil.beginSection("createCodec:" + codecName);
        codec = MediaCodec.createByCodecName(codecName);
        codecAdapter =
            new AsynchronousMediaCodecAdapter(
                codec,
                callbackThreadSupplier.get(),
                queueingThreadSupplier.get(),
                synchronizeCodecInteractionsWithQueueing);
        TraceUtil.endSection();
        codecAdapter.initialize(
            configuration.mediaFormat,
            configuration.surface,
            configuration.crypto,
            configuration.flags);
        return codecAdapter;
      } catch (Exception e) {
        if (codecAdapter != null) {
          codecAdapter.release();
        } else if (codec != null) {
          codec.release();
        }
        throw e;
      }
    }
  }

  @Documented
  @Retention(RetentionPolicy.SOURCE)
  @Target(TYPE_USE)
  @IntDef({STATE_CREATED, STATE_INITIALIZED, STATE_SHUT_DOWN})
  private @interface State {}

  private static final int STATE_CREATED = 0;
  private static final int STATE_INITIALIZED = 1;
  private static final int STATE_SHUT_DOWN = 2;

  private final MediaCodec codec;
  private final AsynchronousMediaCodecCallback asynchronousMediaCodecCallback;
  private final AsynchronousMediaCodecBufferEnqueuer bufferEnqueuer;
  private final boolean synchronizeCodecInteractionsWithQueueing;
  private boolean codecReleased;
  private @State int state;

  private AsynchronousMediaCodecAdapter(
      MediaCodec codec,
      HandlerThread callbackThread,
      HandlerThread enqueueingThread,
      boolean synchronizeCodecInteractionsWithQueueing) {
    this.codec = codec;
    this.asynchronousMediaCodecCallback = new AsynchronousMediaCodecCallback(callbackThread);
    this.bufferEnqueuer = new AsynchronousMediaCodecBufferEnqueuer(codec, enqueueingThread);
    this.synchronizeCodecInteractionsWithQueueing = synchronizeCodecInteractionsWithQueueing;
    this.state = STATE_CREATED;
  }

  private void initialize(
      @Nullable MediaFormat mediaFormat,
      @Nullable Surface surface,
      @Nullable MediaCrypto crypto,
      int flags) {
    asynchronousMediaCodecCallback.initialize(codec);
    TraceUtil.beginSection("configureCodec");
    codec.configure(mediaFormat, surface, crypto, flags);
    TraceUtil.endSection();
    bufferEnqueuer.start();
    TraceUtil.beginSection("startCodec");
    codec.start();
    TraceUtil.endSection();
    state = STATE_INITIALIZED;
  }

  @Override
  public boolean needsReconfiguration() {
    return false;
  }

  @Override
  public void queueInputBuffer(
      int index, int offset, int size, long presentationTimeUs, int flags) {
    bufferEnqueuer.queueInputBuffer(index, offset, size, presentationTimeUs, flags);
  }

  @Override
  public void queueSecureInputBuffer(
      int index, int offset, CryptoInfo info, long presentationTimeUs, int flags) {
    bufferEnqueuer.queueSecureInputBuffer(index, offset, info, presentationTimeUs, flags);
  }

  @Override
  public void releaseOutputBuffer(int index, boolean render) {
    codec.releaseOutputBuffer(index, render);
  }

  @Override
  public void releaseOutputBuffer(int index, long renderTimeStampNs) {
    codec.releaseOutputBuffer(index, renderTimeStampNs);
  }

  @Override
  public int dequeueInputBufferIndex() {
    return asynchronousMediaCodecCallback.dequeueInputBufferIndex();
  }

  @Override
  public int dequeueOutputBufferIndex(MediaCodec.BufferInfo bufferInfo) {
    return asynchronousMediaCodecCallback.dequeueOutputBufferIndex(bufferInfo);
  }

  @Override
  public MediaFormat getOutputFormat() {
    return asynchronousMediaCodecCallback.getOutputFormat();
  }

  @Override
  @Nullable
  public ByteBuffer getInputBuffer(int index) {
    return codec.getInputBuffer(index);
  }

  @Override
  @Nullable
  public ByteBuffer getOutputBuffer(int index) {
    return codec.getOutputBuffer(index);
  }

  @Override
  public void flush() {
    // The order of calls is important:
    // 1. Flush the bufferEnqueuer to stop queueing input buffers.
    // 2. Flush the codec to stop producing available input/output buffers.
    // 3. Flush the callback so that in-flight callbacks are discarded.
    // 4. Start the codec. The asynchronous callback will drop pending callbacks and we can start
    //    the codec now.
    bufferEnqueuer.flush();
    codec.flush();
    asynchronousMediaCodecCallback.flush();
    codec.start();
  }

  @Override
  public void release() {
    try {
      if (state == STATE_INITIALIZED) {
        bufferEnqueuer.shutdown();
        asynchronousMediaCodecCallback.shutdown();
      }
      state = STATE_SHUT_DOWN;
    } finally {
      if (!codecReleased) {
        codec.release();
        codecReleased = true;
      }
    }
  }

  @Override
  public void setOnFrameRenderedListener(OnFrameRenderedListener listener, Handler handler) {
    maybeBlockOnQueueing();
    codec.setOnFrameRenderedListener(
        (codec, presentationTimeUs, nanoTime) ->
            listener.onFrameRendered(
                AsynchronousMediaCodecAdapter.this, presentationTimeUs, nanoTime),
        handler);
  }

  @Override
  public void setOutputSurface(Surface surface) {
    maybeBlockOnQueueing();
    codec.setOutputSurface(surface);
  }

  @Override
  public void setParameters(Bundle params) {
    maybeBlockOnQueueing();
    codec.setParameters(params);
  }

  @Override
  public void setVideoScalingMode(@C.VideoScalingMode int scalingMode) {
    maybeBlockOnQueueing();
    codec.setVideoScalingMode(scalingMode);
  }

  @Override
  @RequiresApi(26)
  public PersistableBundle getMetrics() {
    maybeBlockOnQueueing();
    return codec.getMetrics();
  }

  @VisibleForTesting
  /* package */ void onError(MediaCodec.CodecException error) {
    asynchronousMediaCodecCallback.onError(codec, error);
  }

  @VisibleForTesting
  /* package */ void onOutputFormatChanged(MediaFormat format) {
    asynchronousMediaCodecCallback.onOutputFormatChanged(codec, format);
  }

  private void maybeBlockOnQueueing() {
    if (synchronizeCodecInteractionsWithQueueing) {
      try {
        bufferEnqueuer.waitUntilQueueingComplete();
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        // The playback thread should not be interrupted. Raising this as an
        // IllegalStateException.
        throw new IllegalStateException(e);
      }
    }
  }

  private static String createCallbackThreadLabel(@C.TrackType int trackType) {
    return createThreadLabel(trackType, /* prefix= */ "ExoPlayer:MediaCodecAsyncAdapter:");
  }

  private static String createQueueingThreadLabel(@C.TrackType int trackType) {
    return createThreadLabel(trackType, /* prefix= */ "ExoPlayer:MediaCodecQueueingThread:");
  }

  private static String createThreadLabel(@C.TrackType int trackType, String prefix) {
    StringBuilder labelBuilder = new StringBuilder(prefix);
    if (trackType == C.TRACK_TYPE_AUDIO) {
      labelBuilder.append("Audio");
    } else if (trackType == C.TRACK_TYPE_VIDEO) {
      labelBuilder.append("Video");
    } else {
      labelBuilder.append("Unknown(").append(trackType).append(")");
    }
    return labelBuilder.toString();
  }
}


text:
// Copyright (c) 2017 Till Kolditz
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
 * AN_scalar_8_16_u_inv.cpp
 *
 *  Created on: 07.01.2018
 *      Author: Till Kolditz - Till.Kolditz@gmail.com
 */

#include <AN/AN_scalar.hpp>

namespace coding_benchmark {

    template
    struct AN_scalar_8_16_u_inv<1> ;
    template
    struct AN_scalar_8_16_u_inv<2> ;
    template
    struct AN_scalar_8_16_u_inv<4> ;
    template
    struct AN_scalar_8_16_u_inv<8> ;
    template
    struct AN_scalar_8_16_u_inv<16> ;
    template
    struct AN_scalar_8_16_u_inv<32> ;
    template
    struct AN_scalar_8_16_u_inv<64> ;
    template
    struct AN_scalar_8_16_u_inv<128> ;
    template
    struct AN_scalar_8_16_u_inv<256> ;
    template
    struct AN_scalar_8_16_u_inv<512> ;
    template
    struct AN_scalar_8_16_u_inv<1024> ;

}


text:
package io.novaordis.release.version;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * @author Ovidiu Feodorov <ovidiu@novaordis.com>
 * @since 12/16/16
 */
public class VersionUtilTest {

    // Constants -------------------------------------------------------------------------------------------------------

    private static final Logger log = LoggerFactory.getLogger(VersionUtilTest.class);

    // Static ----------------------------------------------------------------------------------------------------------

    // Attributes ------------------------------------------------------------------------------------------------------

    // Constructors ----------------------------------------------------------------------------------------------------

    // Public ----------------------------------------------------------------------------------------------------------

    // Tests -----------------------------------------------------------------------------------------------------------

    // fromCanonicalString() -------------------------------------------------------------------------------------------

    @Test
    public void fromCanonicalString_Null() throws Exception {

        try {
            VersionUtil.fromCanonicalString(null);
            fail("should have thrown exception");
        }
        catch(IllegalArgumentException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertEquals("null argument", msg);
        }
    }

    @Test
    public void fromCanonicalString() throws Exception {

        String s = "1.0.0";

        Version v = VersionUtil.fromCanonicalString(s);

        assertEquals(new Version("1.0.0"), v);
    }

    @Test
    public void fromCanonicalString_NeedsTrimming() throws Exception {

        String s = "   1.0.0 \t\t ";

        Version v = VersionUtil.fromCanonicalString(s);

        assertEquals(new Version("1.0.0"), v);
    }

    @Test
    public void fromCanonicalString_InvalidVersion() throws Exception {

        try {
            VersionUtil.fromCanonicalString("not a version");
            fail("should have thrown exception");
        }
        catch(VersionFormatException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertTrue(msg.matches(".*invalid.*not a version.*"));
        }
    }

    // fromVersionCommandOutput() --------------------------------------------------------------------------------------

    @Test
    public void fromVersionCommandOutput_regularVersionCommandOutput() throws Exception {

        String s = "version 1.0.1-SNAPSHOT-3\n" +
                "release date 12/05/16";

        Version v = VersionUtil.fromVersionCommandOutput(s);
        assertEquals(new Version("1.0.1-SNAPSHOT-3"), v);
    }

    @Test
    public void fromVersionCommandOutput_firstLine() throws Exception {

        String s = "version 1.0.1-SNAPSHOT-3";

        Version v = VersionUtil.fromCommandStdout(s);
        assertEquals(new Version("1.0.1-SNAPSHOT-3"), v);
    }

    // fromCommandStdout() ---------------------------------------------------------------------------------------------

    @Test
    public void fromCommandStdout_Null() throws Exception {

        try {
            VersionUtil.fromCommandStdout(null);
            fail("should have thrown exception");
        }
        catch(IllegalArgumentException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertEquals("null argument", msg);
        }
    }

    @Test
    public void fromCommandStdout_canonical() throws Exception {

        String s = "1.2.3";

        Version v = VersionUtil.fromCommandStdout(s);
        assertEquals(new Version("1.2.3"), v);
    }

    @Test
    public void fromCommandStdout_regularVersionCommandOutput() throws Exception {

        String s = "version 1.0.1-SNAPSHOT-3\n" +
                "release date 12/05/16";

        Version v = VersionUtil.fromCommandStdout(s);
        assertEquals(new Version("1.0.1-SNAPSHOT-3"), v);
    }

    @Test
    public void fromCommandStdout_InvalidVersion() throws Exception {

        String s = "something";

        try {

            VersionUtil.fromCommandStdout(s);
            fail("should throw exception");
        }
        catch(VersionFormatException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertEquals("invalid version content: something", msg);
        }
    }

    // Package protected -----------------------------------------------------------------------------------------------

    // Protected -------------------------------------------------------------------------------------------------------

    // Private ---------------------------------------------------------------------------------------------------------

    // Inner classes ---------------------------------------------------------------------------------------------------

}


text:
using System;
using System.Collections.Generic;
using FileSearcher.Plugin.CSharp.Criteria;
using System.Windows.Forms;

namespace FileSearcher.Plugin.CSharp
{
    public class DotNetPlugin : IPluginFacade
    {
        private DotNetTabPage _tabPage;

        public Guid PluginId { get { return new Guid("f8bc1486-3613-45f6-89fb-69ef58d45b51"); } }

        public string TabTitle { get { return ".NET projects"; } }

        public UserControl BuildTabPage()
        {
            return _tabPage ?? (_tabPage = new DotNetTabPage());
        }

        public ICriterionPlugin[] GetCriterion()
        {
            if (_tabPage == null)
                throw new InvalidOperationException("Cannot get the options if the tab is not yet generated.");

            var list = new List<ICriterionPlugin>();

            var options = _tabPage.GetOptions();
            if (options.AssemblyName != null)
                list.Add(new AssemblyNameCriterion(options.AssemblyName));
            else if (!string.IsNullOrEmpty(options.AssemblyPath))
                list.Add(new AssemblyLocationCriterion(options.AssemblyPath));
            else if (!string.IsNullOrEmpty(options.AssembliesFolder))
                list.Add(new AssemblyInFolderCriterion(options.AssembliesFolder));

            return list.ToArray();
        }

        public IViewBuilderFactory GetViewBuilderFactory()
        {
            return null;
        }
    }
}


text:
copyright:
years: 2016, 2017
lastupdated: "2017-02-06"

---

{:new_window: target="blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Recursos beta do {{site.data.keyword.iot_full}}
{: #beta_features}

No desenvolvimento contínuo do {{site.data.keyword.iot_full}}, novos recursos são incluídos continuamente e são, às vezes, oferecidos inicialmente como recursos beta. Alguns desses recursos podem requerer o registro beta.
{:shortdesc}

Use a navegação do site para explorar os recursos beta atuais do {{site.data.keyword.iot_short_notm}} nesta seção. Os tópicos para recursos beta também são incluídos em outras seções quando aplicável.


text:
function dfList(el) {
	var listTemplate = el.querySelector('[class$="inputListTemplate"]');
	var indices = document.querySelector('[name="' + el.id + '.indices"]') || el.querySelector('[name$=".indices"]');
	// TODO: tune this to work if the indexes are out of order (eg. 3,5,2,8,6)
	var nextIndex = parseInt(indices.value.match(/[0-9]+$/, 'g'), 10) + 1 || 0;

	var matchMinusOne = new RegExp("\-1");
	var matchListTemplate = new RegExp("inputListTemplate");
	var matchNumber = new RegExp("[0-9]+", "g");

	el.addEventListener("click", manageCodes, false);

	function manageCodes(ev) {
		if (ev.target.name == 'add') { // TODO: tune this to work with nested form lists
			var clone = listTemplate.cloneNode(true);
			clone.className = clone.className.replace(matchListTemplate, 'inputListItem');
			clone.className = clone.className.replace(matchMinusOne, nextIndex);
			clone.id = clone.id.replace(matchMinusOne, nextIndex);
			clone.style.display = '';
			clone.disabled = false;

			var f = clone.querySelectorAll('input, select, textarea, button, label, fieldset, output');
			for (var i = 0, len = f.length; i < len; i++) {
				f[i].id = f[i].id.replace(matchMinusOne, nextIndex);
				//f[i].className = f[i].className.replace(matchListTemplate, 'inputListItem');
				f[i].className = f[i].className.replace(matchMinusOne, nextIndex);
				f[i].style.display = '';

				// output and label elements can have a `for` attribute
				if (f[i].getAttribute('for')) {
					f[i].setAttribute('for', f[i].getAttribute('for').replace(matchMinusOne, nextIndex));
				}

				f[i].disabled = false;

				if (f[i].name) {
					f[i].name = f[i].name.replace(matchMinusOne, nextIndex);
				}

				// this allows us to set specific values to the index value,
				// handy for manipulating radio values that span a list of forms
				if (f[i].getAttribute('data-value') == 'index') {
					f[i].value = nextIndex;
				}
			}

			// if the add button and the template element have the same parent node,
			// insert the clone ahead of the add button.  otherwise, insert it as
			// last child of the template's parent element.
			if (listTemplate.parentNode == ev.target.parentNode) {
				ev.target.parentNode.insertBefore(clone, ev.target);
			} else {
				listTemplate.parentNode.appendChild(clone);
			}
			indices.value = (indices.value.length == 0 ? '' : indices.value + ',') + nextIndex;
			nextIndex++;
		} else if (ev.target.name && ev.target.name.match(/\.remove$/)) { // TODO: tune this to work with nested form lists
			// find the parent element for the given remove button's listItem
			var listItem = document.getElementById(ev.target.name.replace(/\.remove$/, ''));
			// remove it
			listItem.parentNode.removeChild(listItem);
			// adjust the indices to account for the removed element
			var oldCounter = listItem.id.match(matchNumber).pop();
			var regex = new RegExp("((^|,)" + oldCounter + "((?=,)|$))|(," + oldCounter + "$)");
			indices.value = indices.value.replace(regex, '');
		}
	}
}

var lists = document.querySelectorAll('.inputList');
for (var i = 0; i < lists.length; i++) {
	dfList(lists[i]);
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace xBindSampleModel
{
    public sealed class DOModel : DependencyObject
    {
        public DOModel()
        {
            YangObj = new YangContainer(this);
        }

        public void UpdateValues()
        {
            this.IntPropertyDP++;
            YinPropertyDP = 65;
        }

        public YangContainer YangObj
        {
            get;
            set;
        }

        public int IntPropertyDP
        {
            get { return (int)GetValue(IntPropertyDPProperty); }
            set { SetValue(IntPropertyDPProperty, value); }
        }
        #region IntPropertyDP DP
        private const string IntPropertyDPName = "IntPropertyDP";
        private static readonly DependencyProperty _IntPropertyDPProperty =
            DependencyProperty.Register(IntPropertyDPName, typeof(int), typeof(DataModel), new PropertyMetadata(0));
        public static DependencyProperty IntPropertyDPProperty {  get { return _IntPropertyDPProperty; } }
        #endregion

        public double YinPropertyDP
        {
            get { return (double)GetValue(YinPropertyDPProperty); }
            set { SetValue(YinPropertyDPProperty, value); }
        }
        #region YinPropertyDP DP
        private const string YinPropertyDPName = "YinPropertyDP";
        private static readonly DependencyProperty _YinPropertyDPProperty =
            DependencyProperty.Register(YinPropertyDPName, typeof(double), typeof(DataModel), new PropertyMetadata(0, YinCallback));
        public static DependencyProperty YinPropertyDPProperty { get { return _YinPropertyDPProperty; } }
        #endregion

        public static void YinCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DOModel inst = d as DOModel;
            double value = (double)e.NewValue;
            if (inst.YangObj.Value != value)
            {
                inst.YangObj.Value = value;
            }
        }
    }

    public sealed class YangContainer : INotifyPropertyChanged
    {
        private DOModel _parent;

        public YangContainer(DOModel parent)
        {
            _parent = parent;
        }

        private double _value;
        public double Value
        {
            get { return _value; }
            set
            {
                if (value != _value)
                {
                    _value = value;
                    NotifyPropertyChanged();
                    _parent.YinPropertyDP = value;
                }
            }
        }

        #region INPC

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.semantic.data;

import com.semantic.data.xml.HashMapEntryTypeAdapter;
import com.semantic.data.xml.URITypeWrapper;
import com.semantic.model.*;
import com.semantic.model.filter.*;
import com.semantic.util.property.JAXBKey;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 *
 * @author Christian Plonka (cplonka81@gmail.com)
 */
public class JAXBStorage {

    private final List<Class> context = new ArrayList<Class>();

    public JAXBStorage() {
        initStorage();
    }

    private void initStorage() {
        addAdapter(URI.class, new URITypeWrapper());
        /* */
        addToContext(SNode.class);
        addToContext(JAXBKey.class);
        addToContext(OntologyNode.class);
        addToContext(OModel.class);
        addToContext(OMinMaxFilter.class);
        addToContext(OFileDateFilter.class);
        addToContext(OFileSizeFilter.class);
        addToContext(OImageAspectRatioFilter.class);
        addToContext(OImageResolutionFilter.class);
        addToContext(OKeywordFilter.class);
        addToContext(OMimeTypeFilter.class);
        addToContext(ODirectoryNode.class);
        addToContext(OFileSystem.class);
        addToContext(OMusicFilter.class);
        addToContext(OVectorFileFilter.class);
        addToContext(OPowerPointFilter.class);
        addToContext(OGeoHashFilter.class);
        addToContext(ORGBFilter.class);
        addToContext(OHasUserTagFilter.class);
        addToContext(OHasGPSFilter.class);
        addToContext(IQueryGenerator.CLAUSE.class);
        addToContext(OWordFilter.class);
        addToContext(OCalcFilter.class);
        addToContext(OFixedFileDateFilter.class);
    }

    public void addToContext(Class clazz) {
        context.add(clazz);
    }

    public void removeFromContext(Class clazz){
        context.remove(clazz);
    }

    public <T> void addAdapter(Class<T> clazz, XmlAdapter<?, T> adapter) {
        addToContext(adapter.getClass());
        HashMapEntryTypeAdapter.addAdapter(clazz, adapter);
    }

    public <T> void removeAdapter(Class<T> clazz) {
        HashMapEntryTypeAdapter.removeAdapter(clazz);
    }

    public JAXBContext createContext() throws JAXBException {
        return JAXBContext.newInstance(context.toArray(new Class[context.size()]));
    }
}


text:
Warhelper
=========

A set of tools to help out players of wargames


text:
package de.dakror.liturfaliarcest.game.item;

import org.json.JSONArray;

/**
 * @author Dakror
 */
public class ItemStack {
	Item item;
	int amount;

	public ItemStack(Item item, int amount) {
		this.item = item;
		this.amount = amount;
	}

	public ItemStack(Item item) {
		this(item, 1);
	}

	public Item getItem() {
		return item;
	}

	public int getAmount() {
		return amount;
	}

	public void addAmount(int amount) {
		this.amount += amount;
	}

	public void setAmount(int amount) {
		this.amount = amount;
	}

	public boolean isFull() {
		return amount == item.getStack();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof ItemStack) return item.equals(((ItemStack) obj).item) && amount == ((ItemStack) obj).amount;
		return false;
	}

	public JSONArray getData() {
		JSONArray a = new JSONArray();
		a.put(item.getId());
		a.put(amount);
		return a;
	}
}


text:
package com.vladmihalcea.flexypool.connection;

import java.sql.Connection;

/**
 * ConnectionProxyFactory - There are several ways to create a Connection Decorator/Proxy. The main goal is
 * to intercept the close() method calls so that we can inject our metrics logic. The Decorator approach requires more
 * manual coding but delivers better performance than a Dynamic Proxy. The Proxy is much more flexible, but it has an
 * additional execution overhead.
 *
 * @author Vlad Mihalcea
 */
public abstract class ConnectionProxyFactory {

    /**
     * Creates a ConnectionProxy for the specified target and attaching the
     * following callback.
     *
     * @param target                 connection to proxy
     * @param connectionPoolCallback attaching connection lifecycle listener
     * @return ConnectionProxy
     */
    public Connection newInstance(Connection target, ConnectionPoolCallback connectionPoolCallback) {
        return proxyConnection(target, new ConnectionCallback(connectionPoolCallback));
    }

    /**
     * Proxy the given connection
     *
     * @param target   connection to proxy
     * @param callback attaching connection lifecycle listener
     * @return proxy connection
     */
    protected abstract Connection proxyConnection(Connection target, ConnectionCallback callback);
}


text:
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');

gulp.task('browserify', function() {
  return browserify('./src/script.js')
    .transform(babelify)
    .require('./src/script.js', { entry: true })
    .bundle()
    .on("error", function (err) { console.log("Error: " + err.message); })
    .pipe(source('doge.min.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest('./'));
});

gulp.task('watch', ['browserify'], function() {
  gulp.watch('src/script.js', ['browserify']);
});

gulp.task('default', ['browserify']);


text:
<?php
namespace TYPO3\CMS\Extbase\Security\Cryptography;

/**
 * A hash service which should be used to generate and validate hashes.
 *
 * It will use some salt / encryption key in the future.
 *
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser Public License, version 3 or later
 */
class HashService implements \TYPO3\CMS\Core\SingletonInterface
{
    /**
     * Generate a hash (HMAC) for a given string
     *
     * @param string $string The string for which a hash should be generated
     * @return string The hash of the string
     * @throws \TYPO3\CMS\Extbase\Security\Exception\InvalidArgumentForHashGenerationException if something else than a string was given as parameter
     */
    public function generateHmac($string)
    {
        if (!is_string($string)) {
            throw new \TYPO3\CMS\Extbase\Security\Exception\InvalidArgumentForHashGenerationException('A hash can only be generated for a string, but "' . gettype($string) . '" was given.', 1255069587);
        }
        $encryptionKey = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
        if (!$encryptionKey) {
            throw new \TYPO3\CMS\Extbase\Security\Exception\InvalidArgumentForHashGenerationException('Encryption Key was empty!', 1255069597);
        }
        return hash_hmac('sha1', $string, $encryptionKey);
    }

    /**
     * Appends a hash (HMAC) to a given string and returns the result
     *
     * @param string $string The string for which a hash should be generated
     * @return string The original string with HMAC of the string appended
     * @see generateHmac()
     * @todo Mark as API once it is more stable
     */
    public function appendHmac($string)
    {
        $hmac = $this->generateHmac($string);
        return $string . $hmac;
    }

    /**
     * Tests if a string $string matches the HMAC given by $hash.
     *
     * @param string $string The string which should be validated
     * @param string $hmac The hash of the string
     * @return bool TRUE if string and hash fit together, FALSE otherwise.
     */
    public function validateHmac($string, $hmac)
    {
        return $this->generateHmac($string) === $hmac;
    }

    /**
     * Tests if the last 40 characters of a given string $string
     * matches the HMAC of the rest of the string and, if true,
     * returns the string without the HMAC. In case of a HMAC
     * validation error, an exception is thrown.
     *
     * @param string $string The string with the HMAC appended (in the format 'string<HMAC>')
     * @return string the original string without the HMAC, if validation was successful
     * @see validateHmac()
     * @throws \TYPO3\CMS\Extbase\Security\Exception\InvalidArgumentForHashGenerationException if the given string is not well-formatted
     * @throws \TYPO3\CMS\Extbase\Security\Exception\InvalidHashException if the hash did not fit to the data.
     * @todo Mark as API once it is more stable
     */
    public function validateAndStripHmac($string)
    {
        if (!is_string($string)) {
            throw new \TYPO3\CMS\Extbase\Security\Exception\InvalidArgumentForHashGenerationException('A hash can only be validated for a string, but "' . gettype($string) . '" was given.', 1320829762);
        }
        if (strlen($string) < 40) {
            throw new \TYPO3\CMS\Extbase\Security\Exception\InvalidArgumentForHashGenerationException('A hashed string must contain at least 40 characters, the given string was only ' . strlen($string) . ' characters long.', 1320830276);
        }
        $stringWithoutHmac = substr($string, 0, -40);
        if ($this->validateHmac($stringWithoutHmac, substr($string, -40)) !== true) {
            throw new \TYPO3\CMS\Extbase\Security\Exception\InvalidHashException('The given string was not appended with a valid HMAC.', 1320830018);
        }
        return $stringWithoutHmac;
    }
}


text:
layout: post
title: "Hobgoblin Iron Shadow"
date: 2017-09-10
tags: [medium, humanoid, cr2, volos-guide]
---

**Medium humanoid (goblinoid), lawful evil**

**Armor Class** 15

**Hit Points** 32 (5d8+10)

**Speed** 40 ft.

|   STR   |   DEX   |   CON   |   INT   |   WIS   |   CHA   |
|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
| 14 (+2) | 16 (+3) | 15 (+2) | 14 (+2) | 15 (+2) | 11 (0) |

**Skills** Acrobatics +5, Athletics +4, Stealth +5

**Senses** darkvision 60 ft.

**Languages** Common, Goblin

**Challenge** 2 (450 XP)

***Spellcasting.*** The hobgoblin is a 2nd-level spellcaster. Its spellcasting ability is Intelligence (spell save DC 12, +4 to hit with spell attacks). It has the following wizard spells prepared:

Cantrips (at will): minor illusion, prestidigitation, true strike

1st level (3 slots): charm person, disguise self, expeditious retreat, silent image

***Unarmored Defense.*** While the hobgoblin is wearing no armor and wielding no shield, its AC includes its Wisdom modifier.

**Actions**

***Multiattack.*** The hobgoblin makes four attacks, each of which can be an unarmed strike or a dart attack. It can also use Shadow Jaunt once, either before or after one of the attacks.

***Unarmed Strike.*** Melee Weapon Attack: +5 to hit, reach 5 it, one target. Hit: 5 (1d4+3) bludgeoning damage.

***Dart.*** Ranged Weapon Attack: +5 to hit, range 20/60 it, one target. Hit: 5 (1d4+3) piercing damage.

***Shadow Jaunt.*** The hobgoblin magically teleports, along with any equipment it is wearing or carrying, up to 30 feet to an unoccupied space it can see. Both the space it is leaving and its destination must be in dim light or darkness.


text:
# Sheets: bottom

[Bottom sheets](https://material.io/components/sheets-bottom) are surfaces containing supplementary content that are anchored to the bottom of the screen.

![Bottom sheet with 4 options.](docs/assets/bottom-sheet-hero.png)

**Contents**

* [Using bottom sheets](#using-bottom-sheets)
* [Standard bottom sheet](#standard-bottom-sheet)
* [Modal bottom sheet](#modal-bottom-sheet)
* [Expanding bottom sheet](#expanding-bottom-sheet)

- - -

## Using bottom sheets

Bottom sheets are supplementary surfaces primarily used on mobile.

### Installing

In order to install with [Cocoapods](https://guides.cocoapods.org/using/getting-started.html), first add the component to your `Podfile`:

```bash
pod 'MaterialComponents/BottomSheet'
```

Then run the installer:

```bash
pod install
```

From there, import the relevant target or file.

#### Swift
```swift
import MaterialComponents.MaterialBottomSheet
```

#### Objective-C
```objc
#import "MaterialBottomSheet.h"
```

### Making bottom sheets accessible

As a user of the bottom sheet component, it is up to you to determine that its contents are accessible. The bottom sheet ccomponent does not have any specific APIs for managing the accessibility of a bottom sheet's contents. `MDCBottomSheetController` does, however, have such APIs for the scrim:

* `isScrimAccessibilityElement`
* `scrimAccessibilityLabel`
* `scrimAccessibilityHint`
* `scrimAccessibilityTraits`

We recommend giving all of these properties appropriate values for your use case.

**Types**

There are three types suitable for different use cases:
1. Standard bottom sheets display content that complements the screen's primary content and remain visible while users interact with the primary content
1. [Modal bottom sheets](#modal-bottom-sheet) are an alternative to inline menus or simple dialogs on mobile and provide room for additional items, longer descriptions, and iconography, and must be dismissed in order to interact with the underlying content
1. [Expanding bottom sheets](#expanding-bottom-sheet) provide a small, collapsed surface that can be expanded by the user to access a key feature or task to offer the persistent access of a standard sheet with the space and focus of a modal sheet.

![Composite image of bottom sheet types](docs/assets/bottom-sheet-types.png)

_**Note:** Standard bottom sheets aren't supported on iOS. This is because the iOS bottom sheet implementation makes use of custom view controller transitions, which do not allow interaction with the presenting view controller, even when the presented view controller does not take up the whole screen._

## Modal bottom sheet

Modal bottom sheets present a set of choices while blocking interaction with the rest of the screen. They are an alternative to inline menus and simple dialogs on mobile, providing additional room for content, iconography, and actions.

Modal bottom sheets are used in mobile apps only.

### Modal bottom sheet examples

#### Basic modal sheet example

Use `MDCBottomSheetController` and its accompanying presentation controller class, `MDCBottomSheetPresentationController`, to achieve a modal bottom sheet on iOS.

* [`MDCBottomSheetController`GitHub source](https://github.com/material-components/material-components-ios/blob/develop/components/BottomSheet/src/MDCBottomSheetController.h)
* [`MDCBottomSheetPresentationController` GitHub source](https://github.com/material-components/material-components-ios/blob/develop/components/BottomSheet/src/MDCBottomSheetPresentationController.h)

![Bottom sheet with grey slider on top of a grey background](docs/assets/modal-bottom-sheet.png)

Something like the above example can be achieved using the code below.

#### Swift
```swift
// View controller the bottom sheet will hold
let viewController: ViewController = ViewController()
// Initialize the bottom sheet with the view controller just created
let bottomSheet: MDCBottomSheetController = MDCBottomSheetController(contentViewController: viewController)
// At this point perform any customizations, like adding a slider, for example.
// Present the bottom sheet
present(bottomSheet, animated: true, completion: nil)
```

#### Objective-C
```objc
// View controller the bottom sheet will hold
ViewController *viewController = [[ViewController alloc] init];
// Initialize the bottom sheet with the view controller just created
MDCBottomSheetController *bottomSheet = [[MDCBottomSheetController alloc] initWithContentViewController:viewController];
// At this point perform any customizations, like adding a slider, for example.
// Present the bottom sheet
[self presentViewController:bottomSheet animated:true completion:nil];
```

#### Behavioral customizations

You can also choose to have your bottom sheet not be dismissable when dragged downwards by using the `dismissOnDraggingDownSheet` property on `MDCBottomSheetController`.

#### Swift
```swift
let viewController: ViewController = ViewController()
let bottomSheet: MDCBottomSheetController = MDCBottomSheetController(contentViewController: viewController)

bottomSheet.dismissOnDraggingDownSheet = false

present(bottomSheet, animated: true, completion: nil)
```

#### Objective-C
```objc
ViewController *viewController = [[ViewController alloc] init];
MDCBottomSheetController *bottomSheet = [[MDCBottomSheetController alloc] initWithContentViewController:viewController];

bottomSheet.dismissOnDraggingDownSheet = NO;

[self presentViewController:bottomSheet animated:true completion:nil];
```

### Anatomy and key properties

The following shows the anatomy of a modal bottom sheet:

![Modal bottom sheet anatomy](docs/assets/modal-bottom-sheet-anatomy.png)

1. Sheet
2. Contents
3. Scrim

_**Note: A bottom sheet similar to the one shown above is easily attainable with the [ActionSheet](https://github.com/material-components/material-components-ios/tree/develop/components/ActionSheet) component, which makes use of `MDCBottomSheetPresentationController`.**_

#### Sheet properties

                 | **Attribute**             | **Related methods**                                    | **Default value**
----------------------| --------------------------| ------------------------------------------------------ | -----------------
**Sheet height**      | `preferredSheetHeight`          | `-[MDCBottomSheetPresentationController setPreferredSheetHeight:]`
 `-[MDCBottomSheetPresentationController preferredSheetHeight]` | N/A
**Elevation**             | `elevation`          | `-[MDCBottomSheetPresentationController setElevation:]`
 `-[MDCBottomSheetPresentationController elevation]`| 16

#### Contents properties

                 | **Attribute**             | **Related methods**                                    | **Default value**
----------------------| --------------------------| ------------------------------------------------------ | -----------------
**Contents**      | `contentViewController`       | `-[MDCBottomSheetController initWithContentViewController:]`
 `-[MDCBottomSheetController contentViewController]` | N/A
**Elevation**             | `elevation`          | `-[MDCBottomSheetPresentationController setElevation:]`
 `-[MDCBottomSheetPresentationController elevation]`| 16
**Title text**             | `title`          | `-[MDCActionSheetComtroller setTitle:]`
 `-[MDCActionSheetComtroller title]` | `nil`
**Message text**             | `message`          | `-[MDCActionSheetComtroller setMessage:]`
 `-[MDCActionSheetComtroller message]` | `nil`
**Title font**             | `titleFont`          | `-[MDCActionSheetComtroller setTitleFont:]`
 `-[MDCActionSheetComtroller titleFont]` | `nil`
**Message font**             | `messageFont`          | `-[MDCActionSheetComtroller setMessageFont:]`
 `-[MDCActionSheetComtroller messageFont]` | `nil`
**Action font**             | `actionFont`          | `-[MDCActionSheetComtroller setActionFont:]`
 `-[MDCActionSheetComtroller actionFont]` | `nil`
**Ripple color**             | `rippleColor`          | `-[MDCActionSheetComtroller setRippleColor:]`
 `-[MDCActionSheetComtroller rippleColor]` | `nil`
**Background color**             | `backgroundColor`          | `-[MDCActionSheetComtroller -setBackgroundColor:]`
 `-[MDCActionSheetComtroller backgroundColor]` | `nil`
**Title text color**             | `titleTextColor`          | `-[MDCActionSheetComtroller -setTitleTextColor:]`
 `-[MDCActionSheetComtroller titleTextColor]` | `nil`
**Message text color**             | `messageTextColor`          | `-[MDCActionSheetComtroller -setMessageTextColor:]`
 `-[MDCActionSheetComtroller messageTextColor]` | `nil`
**Action text color**             | `actionTextColor`          | `-[MDCActionSheetComtroller -setActionTextColor:]`
 `-[MDCActionSheetComtroller actionTextColor]` | `nil`
**Action tint color**             | `actionTintColor`          | `-[MDCActionSheetComtroller -setActionTintColor:]`
 `-[MDCActionSheetComtroller actionTintColor]` | `nil`

#### Scrim properties

                 | **Attribute**             | **Related methods**                                    | **Default value**
----------------------| --------------------------| ------------------------------------------------------ | -----------------
**Color**      | `scrimColor`          | `-[MDCBottomSheetPresentationController setScrimColor:]`
 `-[MDCBottomSheetPresentationController scrimColor]` | White at 40% opacity

## Expanding bottom sheet

An expanding bottom sheet is a surface anchored to the bottom of the screen that users can expand to access a feature or task. It can be used for:

* **Persistently displaying a cross-app feature**, such as a shopping cart
* **Collecting and acting on user selections** from a set of items, such as photos in a gallery
* **Supporting tasks**, such as chat and comments
* **Indirect navigation between items**, such as videos in a playlist

Expanding bottom sheets are recommended for use on mobile and tablet.

### Expanding bottom sheet example

To generate an expanding bottom sheet on iOS, set the `trackingScrollView` property on your `MDCBottomSheetController`. If the `contentSize` of the scroll view has a large enough height the bottom sheet will expand to the top.

#### Swift
```swift
bottomSheet.trackingScrollView = scrollView
```

#### Objective-C
```objc
bottomSheet.trackingScrollView = self.scrollView;
```


text:
<?php

namespace CaseRu;

/**
 * @link https://github.com/tikhonov24/case-ru-api
 * @version 1.2b
 * @author Tikhonov Alexander <123546.90@mail.ru>
 */
interface ResponseInterface
{
	public function getResponse();
	public function getSimpleXml();
	public function getItems();
}


text:
#include "talk/base/fakesslidentity.h"
#include "talk/base/gunit.h"
#include "talk/base/thread.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/fakesession.h"
#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/p2ptransport.h"
#include "talk/p2p/base/rawtransport.h"
#include "talk/p2p/base/sessionmessages.h"
#include "talk/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"

using cricket::Candidate;
using cricket::Candidates;
using cricket::Transport;
using cricket::FakeTransport;
using cricket::TransportChannel;
using cricket::FakeTransportChannel;
using cricket::TransportRole;
using cricket::TransportDescription;
using cricket::WriteError;
using cricket::ParseError;
using talk_base::SocketAddress;

class TransportTest : public testing::Test,
                      public sigslot::has_slots<> {
 public:
  TransportTest()
      : thread_(talk_base::Thread::Current()),
        transport_(new FakeTransport(
            thread_, thread_, "test content name", NULL)),
        channel_(NULL),
        connecting_signalled_(false) {
    transport_->SignalConnecting.connect(this, &TransportTest::OnConnecting);
  }
  ~TransportTest() {
    transport_->DestroyAllChannels();
  }
  bool SetupChannel() {
    channel_ = CreateChannel(1);
    return (channel_ != NULL);
  }
  FakeTransportChannel* CreateChannel(int component) {
    return static_cast<FakeTransportChannel*>(
        transport_->CreateChannel(component));
  }

 protected:
  void OnConnecting(Transport* transport) {
    connecting_signalled_ = true;
  }

  talk_base::Thread* thread_;
  talk_base::scoped_ptr<FakeTransport> transport_;
  FakeTransportChannel* channel_;
  bool connecting_signalled_;
};

class FakeCandidateTranslator : public cricket::CandidateTranslator {
 public:
  void AddMapping(int component, const std::string& channel_name) {
    name_to_component[channel_name] = component;
    component_to_name[component] = channel_name;
  }

  bool GetChannelNameFromComponent(
      int component, std::string* channel_name) const {
    if (component_to_name.find(component) == component_to_name.end()) {
      return false;
    }
    *channel_name = component_to_name.find(component)->second;
    return true;
  }
  bool GetComponentFromChannelName(
      const std::string& channel_name, int* component) const {
    if (name_to_component.find(channel_name) == name_to_component.end()) {
      return false;
    }
    *component = name_to_component.find(channel_name)->second;
    return true;
  }

  std::map<std::string, int> name_to_component;
  std::map<int, std::string> component_to_name;
};

// Test that calling ConnectChannels triggers an OnConnecting signal.
TEST_F(TransportTest, TestConnectChannelsDoesSignal) {
  EXPECT_TRUE(SetupChannel());
  transport_->ConnectChannels();
  EXPECT_FALSE(connecting_signalled_);

  EXPECT_TRUE_WAIT(connecting_signalled_, 100);
}

// Test that DestroyAllChannels kills any pending OnConnecting signals.
TEST_F(TransportTest, TestDestroyAllClearsPosts) {
  EXPECT_TRUE(transport_->CreateChannel(1) != NULL);

  transport_->ConnectChannels();
  transport_->DestroyAllChannels();

  thread_->ProcessMessages(0);
  EXPECT_FALSE(connecting_signalled_);
}

// Tests that SetRole and SetTiebreaker are properly passed down to channels.
TEST_F(TransportTest, TestSetRoleAndTiebreaker) {
  transport_->SetRole(cricket::ROLE_CONTROLLED);
  transport_->SetTiebreaker(99U);
  EXPECT_TRUE(SetupChannel());
  EXPECT_EQ(cricket::ROLE_CONTROLLED, channel_->role());
  EXPECT_EQ(99U, channel_->tiebreaker());
  transport_->SetRole(cricket::ROLE_CONTROLLING);
  EXPECT_EQ(cricket::ROLE_CONTROLLING, channel_->role());
}

// Tests that we can properly serialize/deserialize candidates.
TEST_F(TransportTest, TestP2PTransportWriteAndParseCandidate) {
  Candidate test_candidate(
      "", 1, "udp",
      talk_base::SocketAddress("2001:db8:fefe::1", 9999),
      738197504, "abcdef", "ghijkl", "foo", "testnet", 50, "");
  Candidate test_candidate2(
      "", 2, "tcp",
      talk_base::SocketAddress("192.168.7.1", 9999),
      1107296256, "mnopqr", "stuvwx", "bar", "testnet2", 100, "");
  talk_base::SocketAddress host_address("www.google.com", 24601);
  host_address.SetResolvedIP(talk_base::IPAddress(0x0A000001));
  Candidate test_candidate3(
      "", 3, "spdy", host_address, 1476395008, "yzabcd",
      "efghij", "baz", "testnet3", 150, "");
  WriteError write_error;
  ParseError parse_error;
  talk_base::scoped_ptr<buzz::XmlElement> elem;
  cricket::Candidate parsed_candidate;
  cricket::P2PTransportParser parser;

  FakeCandidateTranslator translator;
  translator.AddMapping(1, "test");
  translator.AddMapping(2, "test2");
  translator.AddMapping(3, "test3");

  EXPECT_TRUE(parser.WriteGingleCandidate(test_candidate, &translator,
                                          elem.accept(), &write_error));
  EXPECT_EQ("", write_error.text);
  EXPECT_EQ("test", elem->Attr(buzz::QN_NAME));
  EXPECT_EQ("udp", elem->Attr(cricket::QN_PROTOCOL));
  EXPECT_EQ("2001:db8:fefe::1", elem->Attr(cricket::QN_ADDRESS));
  EXPECT_EQ("9999", elem->Attr(cricket::QN_PORT));
  EXPECT_EQ("0.34", elem->Attr(cricket::QN_PREFERENCE));
  EXPECT_EQ("abcdef", elem->Attr(cricket::QN_USERNAME));
  EXPECT_EQ("ghijkl", elem->Attr(cricket::QN_PASSWORD));
  EXPECT_EQ("foo", elem->Attr(cricket::QN_TYPE));
  EXPECT_EQ("testnet", elem->Attr(cricket::QN_NETWORK));
  EXPECT_EQ("50", elem->Attr(cricket::QN_GENERATION));

  EXPECT_TRUE(parser.ParseGingleCandidate(elem.get(), &translator,
                                          &parsed_candidate, &parse_error));
  EXPECT_TRUE(test_candidate.IsEquivalent(parsed_candidate));

  EXPECT_TRUE(parser.WriteGingleCandidate(test_candidate2, &translator,
                                          elem.accept(), &write_error));
  EXPECT_EQ("test2", elem->Attr(buzz::QN_NAME));
  EXPECT_EQ("tcp", elem->Attr(cricket::QN_PROTOCOL));
  EXPECT_EQ("192.168.7.1", elem->Attr(cricket::QN_ADDRESS));
  EXPECT_EQ("9999", elem->Attr(cricket::QN_PORT));
  EXPECT_EQ("0.51", elem->Attr(cricket::QN_PREFERENCE));
  EXPECT_EQ("mnopqr", elem->Attr(cricket::QN_USERNAME));
  EXPECT_EQ("stuvwx", elem->Attr(cricket::QN_PASSWORD));
  EXPECT_EQ("bar", elem->Attr(cricket::QN_TYPE));
  EXPECT_EQ("testnet2", elem->Attr(cricket::QN_NETWORK));
  EXPECT_EQ("100", elem->Attr(cricket::QN_GENERATION));

  EXPECT_TRUE(parser.ParseGingleCandidate(elem.get(), &translator,
                                          &parsed_candidate, &parse_error));
  EXPECT_TRUE(test_candidate2.IsEquivalent(parsed_candidate));

  // Check that an ip is preferred over hostname.
  EXPECT_TRUE(parser.WriteGingleCandidate(test_candidate3, &translator,
                                          elem.accept(), &write_error));
  EXPECT_EQ("test3", elem->Attr(cricket::QN_NAME));
  EXPECT_EQ("spdy", elem->Attr(cricket::QN_PROTOCOL));
  EXPECT_EQ("10.0.0.1", elem->Attr(cricket::QN_ADDRESS));
  EXPECT_EQ("24601", elem->Attr(cricket::QN_PORT));
  EXPECT_EQ("0.69", elem->Attr(cricket::QN_PREFERENCE));
  EXPECT_EQ("yzabcd", elem->Attr(cricket::QN_USERNAME));
  EXPECT_EQ("efghij", elem->Attr(cricket::QN_PASSWORD));
  EXPECT_EQ("baz", elem->Attr(cricket::QN_TYPE));
  EXPECT_EQ("testnet3", elem->Attr(cricket::QN_NETWORK));
  EXPECT_EQ("150", elem->Attr(cricket::QN_GENERATION));

  EXPECT_TRUE(parser.ParseGingleCandidate(elem.get(), &translator,
                                          &parsed_candidate, &parse_error));
  EXPECT_TRUE(test_candidate3.IsEquivalent(parsed_candidate));
}


text:
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Waf.BookLibrary.Reporting.Applications.Test")]


text:
// ***********************************************************************
// Assembly         : EveLib.EveCrest
// Author           : Lars Kristian
// Created          : 12-19-2014
//
// Last Modified By : Lars Kristian
// Last Modified On : 12-19-2014
// ***********************************************************************
// <copyright file="ImageHref.cs" company="">
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************

using System.Runtime.Serialization;

namespace eZet.EveLib.EveCrestModule.Models.Links {
    /// <summary>
    ///     Class ImageHref.
    /// </summary>
    [DataContract]
    public class ImageHref {
        /// <summary>
        ///     Gets or sets the URI.
        /// </summary>
        /// <value>The URI.</value>
        [DataMember(Name = "href")]
        public string Uri { get; set; }

        /// <summary>
        ///     Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
        public override string ToString() {
            return Uri;
        }
    }
}


text:
import * as cheerio from 'cheerio';
import * as entities from 'html-entities';
import {EducationDetail} from './interfaces/EducationDetail';
import {EduWork} from './interfaces/EduWork';

export const eduwork_common = (element: Cheerio): EduWork => {
    return {
        section: element.attr('data-pnref') || '',
        text: element.children('div').text() || '',
        items: element.children('ul').children('li').toArray().map((item: CheerioElement) => {
            const itemElement = cheerio.load(item)('li');
            const data = itemElement.find('a').next('div');  // find div after link with image
            const link = data.find('a');
            const caption = link.parent().next('div');
            const _tmp = caption.next('div').text();
            const additional = _tmp ? [_tmp] : [];
            const retval: EducationDetail = {
                url: link.attr('href') || '',
                caption: link.text() || '',
                text: []
            };
            link.remove();
            const text = caption.text();
            if (text) {
                const delim = caption.find('[role="presentation"]').html();
                retval.text = delim ? text.split(entities.XmlEntities.decode(delim)) : [text];
            }
            itemElement.find('li').toArray().forEach((li: CheerioElement) => {
                additional.push(cheerio.load(li)('li').text());
            });
            if (additional.length) retval.additional = additional;
            return retval;
        })
    };
};


text:
<ion-header>
    <ion-navbar color="primary">
        <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
        <ion-title>O Teatro</ion-title>
    </ion-navbar>
</ion-header>

<ion-content class="ion-content-color-light">

        <ion-slides autoplay="1000" loop="true" speed="3000">
            <ion-slide>

            </ion-slide>
            <ion-slide>

            </ion-slide>
            <ion-slide>

            </ion-slide>
            <ion-slide>

            </ion-slide>
            <ion-slide>

            </ion-slide>
        </ion-slides>

O Teatro FACISA é um dos empreendimentos do Centro de Ensino Superior e Desenvolvimento – CESED. Localizado na cidade de Campina Grande/PB e inaugurado no dia 28 de novembro de 2012, é uma referência no que tange à imponência de sua infraestrutura.
            Possui mecanismos cênicos de alto padrão equiparando-se aos grandes teatros do sul e sudeste do Brasil, o que lhe permite entrar na rota de apresentação de grandes espetáculos nacional e internacional.Dado a esse perfil, oferecerá espaço para
            apresentações de dança, circo-teatro, música, além de eventos de natureza acadêmicas e empresarial: seminários e congressos. A Paraíba, assim como estados circunvizinhos terão um espaço versátil.

 A sala de espetáculos comporta 716 espectadores sentados, em seus diversos setores – plateia, plateia superior e camarotes. Suas dependências contam ainda com bar, total acesso para pessoas portadoras de necessidades especiais, além de ambientes
            para eventos menores e coquetéis.

Localiza-se, no Campus do CESED/FACISA, no bairro do Itararé, garante segurança e conforto ao público, disponibiliza estacionamento para 600 vagas.

            <ion-label>Ler mais...</ion-label>

                Palco e Mecanismo Cênico

O Teatro FACISA priorizou a utilização do smais modernos mecanismos cênicos, desde os equipamentos utilizados nos bastidores à iluminação, acústica, aos elementos de conforto, segurança e acessibilidade ao público. Com área total de 2.624,95m²,
                com palco de 273,37m², e altura de 6m e a boca de cena 9 a 12m, com 7 varas de cenário e 16 de iluminação. Tem capacidade para 716 lugares, as poltronas são extremamente conforáveis, havendo poltronas especiais nos camarotes e na grande
                plateia, adaptadas para PNEs (pessoas com necessidades especiais). A plateia se divide em: plateia principal, balcão nobre e camarotes. Na parte térrea, o teatro conta com um grande Foyer, lounge, bar/café, e uma cozinha industrial para
                dar apoio aos eventos. Buscando um ambiente tão confortável para o público quanto para o artista, o projeto inclui um amplo backstage, contendo três bem equipados e luxuosos camarins. O complexo agrega ainda salas de aula e ensaios para
                dança, música e teatro.

O Teatro utiliza os mais modernos equipamentos, destacando os sistemas de iluminação e sonorização. Além de um cuidadoso projeto acústico, para atender a usos distintos. A concepção dos ambientes valoriza elementos de conforto, segurança e
                acessibilidade ao público.

                Acústica

Com a preocupação de garantir o conforto acústico do Teatro, o projeto conta com desenhos específicos que contribuem para a propagação sonora, a exemplo do forro, o qual distribui maneira uniforme, com alcance em todas as área da plateia,
                e o tratamento das paredes laterais, que eliminam o paralelismo. Além disso, foram utilizados materiais especiais de absorção, permitindo o múltiplo uso do espaço, respeitando as variações sonoras de cada modalidade de espetáculo sem comprometer
                a audibilidade e nitidez. O isolamento sonoro é dado pela utilização de paredes, duplas, materiais isolantes no sistema de ar condicionado, portas e acessos por antecâmaras acústicas.

                Sonorização

Os equipamentos utilizados no projeto sonora são da marca Toa, líder mundial em sonorização profissional. O som de última geração, possui processamento 7.1 em todos os ambientes, com mais de 4000 watts de potência, divididos em 27 caixas acústicas

distribuídas na platéia.

Console: Mix Digital Allen & Heath T.112 Live com IDR de 48 canais de entrada e 24 de saída; podendo chegar a 64 canais de entrada. Controles Touchscreen e Analógicos.

P.A.: Sistema de som line Array Speaker TOA (Japonês) Passivo. Duas colunas de caixa sendo (L) e (R) com a mesma configuração abaixo por coluna:

                02 Caixas SR-C8L com potência de 360W;

 02 Caixas SR-C8S com potência de 360W;

 01 Caixa C-15C Subwoofer type bass reflex aéreo com potência de 450W;

 01 subwoofer de base modelo FB120B 200W

</ion-content>


text:
{% load i18n %}
<form {% if submit_url %}action="{{ submit_url }}"{% endif %} method="post" class="dk-form">
  {% csrf_token %}
  {% for field in form.visible_fields %}

        {{ field.label }}: {% if field.field.required %}({% trans "required" %}){% endif %}

        {% if field.field.help_text %}

          {{ field.field.help_text }}
        {% endif %}

        {{ field }}

      {{ field.errors }}

  {% endfor %}
  {# these are, for the most part, unused #}
  {% for field in form.hidden_fields %}{{ field }}{% endfor %}

    <input class="submit-question" type="submit" value="{% trans submit_value %}">  {% trans submit_and %}

</form>


text:
import { mount } from "enzyme";
import React from "react";
import { GlobalNav as VanillaGlobalNav } from "hig-vanilla";
import ProfileAdapter from "./ProfileAdapter";

describe("TopNav ProfileAdapter", () => {
  it("implements the hig interface", () => {
    expect(mockInstance => {
      const wrapper = mount(
        <ProfileAdapter
          higInstance={mockInstance}
          open
          image="/my-image.png"
          name="Tom Petty"
          email="tom.petty@email.com"
          profileSettingsLabel="Settings"
          profileSettingsLink="http://autodesk.com"
          signOutLabel="Sign out"
          signOutLink="/sign-out"
          onSignOutClick={() => {}}
          onProfileSettingsClick={() => {}}
          onProfileImageClick={() => {}}
          onProfileClickOutside={() => {}}
        />
      );
      wrapper.props().higInstance.close();
    }).toImplementHIGInterfaceOf(
      VanillaGlobalNav._partials.TopNav._partials.Profile
    );
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="@color/a1_color" />

    <corners android:radius="@dimen/common_round_corner_radius" />

</shape>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SpriteMaker
{
    /// <summary>
    /// we need a serializable object witha  gradient to show a nice gradient editor. see the comment in DrawPerlin.cs
    /// </summary>
    public class ScriptableGradientAsset : ScriptableObject
    {
        public Gradient gradient;
    }
}


text:
    #pragma interface "clntdata.h"
#endif

#include "wx/defs.h"
#include "wx/string.h"
#include "wx/hashmap.h"

#if wxABI_VERSION >= 20602

typedef int (*wxShadowObjectMethod)(void*, void*);
WX_DECLARE_STRING_HASH_MAP_WITH_DECL(
    wxShadowObjectMethod,
    wxShadowObjectMethods,
    class WXDLLIMPEXP_BASE
);
WX_DECLARE_STRING_HASH_MAP_WITH_DECL(
    void *,
    wxShadowObjectFields,
    class WXDLLIMPEXP_BASE
);

class WXDLLIMPEXP_BASE wxShadowObject
{
public:
    wxShadowObject() { }

    void AddMethod( const wxString &name, wxShadowObjectMethod method )
    {
        wxShadowObjectMethods::iterator it = m_methods.find( name );
        if (it == m_methods.end())
            m_methods[ name ] = method;
        else
            it->second = method;
    }

    bool InvokeMethod( const wxString &name, void* window, void* param, int* returnValue )
    {
        wxShadowObjectMethods::iterator it = m_methods.find( name );
        if (it == m_methods.end())
            return false;
        wxShadowObjectMethod method = it->second;
        int ret = (*method)(window, param);
        if (returnValue)
            *returnValue = ret;
        return true;
    }

    void AddField( const wxString &name, void* initialValue = NULL )
    {
        wxShadowObjectFields::iterator it = m_fields.find( name );
        if (it == m_fields.end())
            m_fields[ name ] = initialValue;
        else
            it->second = initialValue;
    }

    void SetField( const wxString &name, void* value )
    {
        wxShadowObjectFields::iterator it = m_fields.find( name );
        if (it == m_fields.end())
            return;
        it->second = value;
    }

    void* GetField( const wxString &name, void *defaultValue = NULL )
    {
        wxShadowObjectFields::iterator it = m_fields.find( name );
        if (it == m_fields.end())
            return defaultValue;
        return it->second;
    }

private:
    wxShadowObjectMethods   m_methods;
    wxShadowObjectFields    m_fields;
};

#endif // wxABI_VERSION

// ----------------------------------------------------------------------------

// what kind of client data do we have?
enum wxClientDataType
{
    wxClientData_None,    // we don't know yet because we don't have it at all
    wxClientData_Object,  // our client data is typed and we own it
    wxClientData_Void     // client data is untyped and we don't own it
};

class WXDLLIMPEXP_BASE wxClientData
{
public:
    wxClientData() { }
    virtual ~wxClientData() { }
};

class WXDLLIMPEXP_BASE wxStringClientData : public wxClientData
{
public:
    wxStringClientData() : m_data() { }
    wxStringClientData( const wxString &data ) : m_data(data) { }
    void SetData( const wxString &data ) { m_data = data; }
    const wxString& GetData() const { return m_data; }

private:
    wxString  m_data;
};

// This class is a mixin that provides storage and management of "client
// data."  The client data stored can either be a pointer to a wxClientData
// object in which case it is managed by the container (i.e. it will delete
// the data when it's destroyed) or an untyped pointer which won't be deleted
// by the container - but not both of them
//
// NOTE:  This functionality is currently duplicated in wxEvtHandler in order
//        to avoid having more than one vtable in that class hierarchy.

class WXDLLIMPEXP_BASE wxClientDataContainer
{
public:
    wxClientDataContainer();
    virtual ~wxClientDataContainer();

    void SetClientObject( wxClientData *data ) { DoSetClientObject(data); }
    wxClientData *GetClientObject() const { return DoGetClientObject(); }

    void SetClientData( void *data ) { DoSetClientData(data); }
    void *GetClientData() const { return DoGetClientData(); }

protected:
    // The user data: either an object which will be deleted by the container
    // when it's deleted or some raw pointer which we do nothing with. Only
    // one type of data can be used with the given window, i.e. you cannot set
    // the void data and then associate the container with wxClientData or vice
    // versa.
    union
    {
        wxClientData *m_clientObject;
        void         *m_clientData;
    };

    // client data accessors
    virtual void DoSetClientObject( wxClientData *data );
    virtual wxClientData *DoGetClientObject() const;

    virtual void DoSetClientData( void *data );
    virtual void *DoGetClientData() const;

    // what kind of data do we have?
    wxClientDataType m_clientDataType;

};

// not Motif-specific, but currently used only under Motif,
// compiled to make wxMotif and wxGTK base libraries compatible
#if defined(__WXMOTIF__) || wxABI_VERSION >= 20602

#include "wx/vector.h"

struct WXDLLIMPEXP_BASE wxClientDataDictionaryPair
{
    wxClientDataDictionaryPair( size_t idx ) : index( idx ), data( 0 ) { }

    size_t index;
    wxClientData* data;
};

_WX_DECLARE_VECTOR(
    wxClientDataDictionaryPair,
    wxClientDataDictionaryPairVector,
    WXDLLIMPEXP_BASE
);

// this class is used internally to maintain the association between items
// of (some subclasses of) wxControlWithItems and their client data
// NOTE: this class does not keep track of whether it contains
// wxClientData or void*. The client must ensure that
// it does not contain a mix of the two, and that
// DestroyData is called if it contains wxClientData
class WXDLLIMPEXP_BASE wxClientDataDictionary
{
public:
    wxClientDataDictionary() {}

    // deletes all the data
    void DestroyData()
    {
        for( size_t i = 0, end = m_vec.size(); i != end; ++i )
            delete m_vec[i].data;
        m_vec.clear();
    }

    // if data for the given index is not present, add it,
    // if it is present, delete the old data and replace it with
    // the new one
    void Set( size_t index, wxClientData* data, bool doDelete )
    {
        size_t ptr = Find( index );

        if( !data )
        {
            if( ptr == m_vec.size() ) return;
            if( doDelete )
                delete m_vec[ptr].data;
            m_vec.erase( ptr );
        }
        else
        {
            if( ptr == m_vec.size() )
            {
                m_vec.push_back( wxClientDataDictionaryPair( index ) );
                ptr = m_vec.size() - 1;
            }

            if( doDelete )
                delete m_vec[ptr].data;
            m_vec[ptr].data = data;
        }
    }

    // get the data associated with the given index,
    // return 0 if not found
    wxClientData* Get( size_t index ) const
    {
        size_t it = Find( index );
        if( it == m_vec.size() ) return 0;
        return (wxClientData*)m_vec[it].data; // const cast
    }

    // delete the data associated with the given index
    // it also decreases by one the indices of all the elements
    // with an index greater than the given index
    void Delete( size_t index, bool doDelete )
    {
        size_t todel = m_vec.size();

        for( size_t i = 0, end = m_vec.size(); i != end; ++i )
        {
            if( m_vec[i].index == index )
                todel = i;
            else if( m_vec[i].index > index )
                --(m_vec[i].index);
        }

        if( todel != m_vec.size() )
        {
            if( doDelete )
                delete m_vec[todel].data;
            m_vec.erase( todel );
        }
    }
private:
    // returns MyVec.size() if not found
    size_t Find( size_t index ) const
    {
        for( size_t i = 0, end = m_vec.size(); i != end; ++i )
        {
            if( m_vec[i].index == index )
                return i;
        }

        return m_vec.size();
    }

    wxClientDataDictionaryPairVector m_vec;
};

#endif // __WXMOTIF__

// ----------------------------------------------------------------------------
#endif


text:
#ifndef DVPSOV_H
#define DVPSOV_H

#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */
#include "dcmtk/dcmdata/dctk.h"
#include "dcmtk/dcmpstat/dpdefine.h"

class DicomImage;

/** an overlay contained in a presentation state (internal use only).
 *  This class manages the data structures comprising a single overlay
 *  (one instance of the Overlay Plane Module repeating elements)
 *  that is contained in a Presentation State object.
 */

class DCMTK_DCMPSTAT_EXPORT DVPSOverlay
{
public:
  /// default constructor
  DVPSOverlay();

  /// copy constructor
  DVPSOverlay(const DVPSOverlay& copy);

  /** clone method.
   *  @return a pointer to a new DVPSOverlay object containing
   *  a copy of this object.
   */
  DVPSOverlay *clone() const { return new DVPSOverlay(*this); }

  /// destructor
  virtual ~DVPSOverlay();

  /** reads the specified overlay group from a DICOM dataset.
   *  The DICOM elements of the Overlay Plane module are copied
   *  from the dataset to this object. The OverlayData element, which is
   *  optional in the Overlay Plane Module but required for presentation states,
   *  must be present.
   *  The completeness of the overlay plane (presence of all required elements,
   *  value multiplicity) is checked.
   *  If this method returns an error code, the object is in undefined state afterwards.
   *  @param dset the DICOM dataset from which the overlay is to be read
   *  @param ovGroup the lower byte of the overlay group to be read
   *  @param asGroup the lower byte of the overlay group to be assigned to the
   *    overlay plane in the presentation state. Default: identical to ovGroup.
   *  @return EC_Normal if successful, an error code otherwise.
   */
  OFCondition read(DcmItem &dset, Uint8 ovGroup, Uint8 asGroup=0xFF);

  /** writes the overlay plane managed by this object to a DICOM dataset.
   *  Copies of the DICOM element managed by this object are inserted into
   *  the DICOM dataset.
   *  @param dset the DICOM dataset to which the overlay is written
   *  @return EC_Normal if successful, an error code otherwise.
   */
  OFCondition write(DcmItem &dset);

  /** get group number of overlay repeating group managed by this object.
   *  @return the lower byte of the overlay group
   */
  Uint8 getOverlayGroup() const { return overlayGroup; }

  /** sets the group number for the overlay repeating group managed
   *  by this object.
   *  @param newGroup lower byte of the repeating group number.
   */
  void setOverlayGroup(Uint8 newGroup) { overlayGroup = newGroup; }

  /** checks if the overlay is suitable as a bitmap shutter
   *  for an image with the given image size. Checks overlay type,
   *  origin and size.
   *  @param x image width in pixels
   *  @param y image height in pixels
   *  @return OFTrue if the specified overlay group matches the image size.
   */
  OFBool isSuitableAsShutter(unsigned long x, unsigned long y);

  /** gets the overlay label if present.
   *  If the label string is absent, this method returns NULL.
   *  @return overlay label
   */
  const char *getOverlayLabel();

  /** gets the overlay description if present.
   *  If the label string is absent, this method returns NULL.
   *  @return overlay description
   */
  const char *getOverlayDescription();

  /** checks whether this overlay is ROI type.
   *  @return OFTrue if overlay is ROI, OFFalse if overlay is Graphic.
   */
  OFBool isROI();

  /** retrieve origin and size values for this overlay
   *  @param originX horizontal origin returned in this parameter
   *  @param originY vertical origin returned in this parameter
   *  @param sizeX horizontal size returned in this parameter
   *  @param sizeY vertical size returned in this parameter
   *  @return EC_Normal if successful, an error code otherwise
   */
  OFCondition getValues(
    Sint16& originX,
    Sint16& originY,
    Uint16& sizeX,
    Uint16& sizeY);

  /// return reference to overlay data
  DcmOverlayData& getData() { return overlayData; }

  /// return reference to overlay label
  DcmLongString& getLabel() { return overlayLabel; }

  /// return reference to overlay description
  DcmLongString& getDescription() { return overlayDescription; }

private:

  /// private undefined assignment operator
  DVPSOverlay& operator=(const DVPSOverlay&);

  /// lower byte of the overlay repeating group managed by this object
  Uint8                    overlayGroup;
  /// VR=US, VM=1, Type=1
  DcmUnsignedShort         overlayRows;
  /// VR=US, VM=1, Type=1
  DcmUnsignedShort         overlayColumns;
  /// VR=CS, VM=1, Type=1
  DcmCodeString            overlayType;
  /// VR=SS, VM=2, Type=1
  DcmSignedShort           overlayOrigin;
  /// VR=US, VM=1, Type=1
  DcmUnsignedShort         overlayBitsAllocated;
  /// VR=US, VM=1, Type=1
  DcmUnsignedShort         overlayBitPosition;
  /// VR=OW, VM=1, Type=1C
  DcmOverlayData           overlayData;
  /// VR=LO, VM=1, Type=3
  DcmLongString            overlayDescription;
  /// VR=LO, VM=1, Type=3
  DcmLongString            overlayLabel;

};

#endif


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

package org.chromium.components.paintpreview.player;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import org.chromium.components.signin.AccountManagerFacadeProvider;
import org.chromium.components.signin.test.util.FakeAccountManagerFacade;
import org.chromium.content_public.browser.test.NativeLibraryTestUtils;

/**
 * Loads native and initializes the browser process for Paint Preview instrumentation tests.
 */
public class PaintPreviewTestRule implements TestRule {
    /**
     * {@link AccountManagerFacadeProvider#getInstance()} is called in the browser initialization
     * path. If we don't mock {@link AccountManagerFacade}, we'll run into a failed assertion.
     */
    private void setUp() {
        AccountManagerFacadeProvider.setInstanceForTests(new FakeAccountManagerFacade());
        NativeLibraryTestUtils.loadNativeLibraryAndInitBrowserProcess();
    }

    @Override
    public Statement apply(final Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                setUp();
                try {
                    base.evaluate();
                } finally {
                    AccountManagerFacadeProvider.resetInstanceForTests();
                }
            }
        };
    }
}


text:
!
!  Copyright 2016 ARTED developers
!
!  Licensed under the Apache License, Version 2.0 (the "License");
!  you may not use this file except in compliance with the License.
!  You may obtain a copy of the License at
!
!      http://www.apache.org/licenses/LICENSE-2.0
!
!  Unless required by applicable law or agreed to in writing, software
!  distributed under the License is distributed on an "AS IS" BASIS,
!  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
!  See the License for the specific language governing permissions and
!  limitations under the License.
!
Subroutine Fermi_Dirac_distribution
  use Global_Variables
  use communication
  use misc_routines, only: get_wtime
  implicit none
  real(8) :: chemical_potential
  real(8) :: chem_max,chem_min,elec_num
  real(8) :: beta_FD
  real(8),allocatable :: occ_l(:,:),esp_l(:,:),esp_temp(:,:)
  real(8) s,st
  integer :: ik,ib
  real(8) :: timer1,timer2

  timer1=get_wtime()
  beta_FD=1d0/(KbTev/(2d0*Ry))
  allocate(occ_l(NB,NK),esp_l(NB,NK),esp_temp(NB,NK))
  occ_l=0d0 ; esp_l=0d0
  esp_l(:,NK_s:NK_e)=esp(:,NK_s:NK_e)
  call comm_summation(esp_l,esp_temp,NB*NK,proc_group(2))
  chem_max=maxval(esp_temp)
  chem_min=minval(esp_temp)
  if(comm_is_root())then
    write(*,*)'max esp =',chem_max
    write(*,*)'min esp =',chem_min
  end if
  chemical_potential=0.5d0*(chem_max+chem_min)
  do

    do ik=NK_s,NK_e
      do ib=1,NB
        occ_l(ib,ik)=2.d0/(NKxyz)*wk(ik) &
          &/(exp(beta_FD*(esp(ib,ik)-chemical_potential))+1d0)
      end do
    end do

    st=sum(occ_l(:,NK_s:NK_e))
    call comm_summation(st,s,proc_group(2))
    elec_num=s

    if(abs(elec_num-dble(Nelec)) <= 1d-6)exit
    if(elec_num-dble(Nelec) > 0d0)then
      chem_max=chemical_potential
      chemical_potential=0.5d0*(chem_max+chem_min)
    else
      chem_min=chemical_potential
      chemical_potential=0.5d0*(chem_max+chem_min)
    end if
    if(chem_max-chem_min < 1d-10)exit

  end do

  call comm_summation(occ_l,occ,NB*NK,proc_group(2))
  st=sum(occ_l(Nelec/2+1:NB,NK_s:NK_e))
  call comm_summation(st,s,proc_group(2))

  timer2=get_wtime()
  if(comm_is_root())then
    write(*,*)'Fermi-Dirac dist. time=',timer2-timer1,'sec'
    write(*,*)'chemical potential =',chemical_potential
    write(*,*)'elec_num =',elec_num
    write(*,*)'excited electron =',s
!    open(126,file='occ.dat')
!    do ik=1,NK
!      do ib=1,NB
!        write(126,*)ik,ib,occ(ib,ik)
!      end do
!    end do
!    close(126)
  end if

  return
end Subroutine Fermi_Dirac_distribution


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p67;

import org.gradle.test.performance.mediummonolithicjavaproject.p66.Production1338;

public class Production1347 {

    private Production1338 property0;

    public Production1338 getProperty0() {
        return property0;
    }

    public void setProperty0(Production1338 value) {
        property0 = value;
    }

    private Production1342 property1;

    public Production1342 getProperty1() {
        return property1;
    }

    public void setProperty1(Production1342 value) {
        property1 = value;
    }

    private Production1346 property2;

    public Production1346 getProperty2() {
        return property2;
    }

    public void setProperty2(Production1346 value) {
        property2 = value;
    }

    private String property3;

    public String getProperty3() {
        return property3;
    }

    public void setProperty3(String value) {
        property3 = value;
    }

    private String property4;

    public String getProperty4() {
        return property4;
    }

    public void setProperty4(String value) {
        property4 = value;
    }

    private String property5;

    public String getProperty5() {
        return property5;
    }

    public void setProperty5(String value) {
        property5 = value;
    }

    private String property6;

    public String getProperty6() {
        return property6;
    }

    public void setProperty6(String value) {
        property6 = value;
    }

    private String property7;

    public String getProperty7() {
        return property7;
    }

    public void setProperty7(String value) {
        property7 = value;
    }

    private String property8;

    public String getProperty8() {
        return property8;
    }

    public void setProperty8(String value) {
        property8 = value;
    }

    private String property9;

    public String getProperty9() {
        return property9;
    }

    public void setProperty9(String value) {
        property9 = value;
    }

}


text:
package com.mapswithme.maps.maplayer;

public interface OnGuidesLayerToggleListener
{
  void onGuidesLayerSelected();
}


text:
layout: page
title: Petty Media Executive Retreat
date: 2016-05-24
author: Elizabeth Steele
tags: weekly links, java
status: published
summary: Nullam non posuere erat, sit.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/20/2017
  endDate: 04/25/2017
  ctyhocn: CHILYHX
  groupCode: PMER
published: true
---
Nunc nec mattis diam. Aliquam eget fringilla justo. Vivamus augue est, maximus in consequat ac, rutrum vel ipsum. Vivamus dolor lectus, accumsan et ligula eu, pellentesque interdum dolor. Nam vulputate molestie diam ut venenatis. Aenean ac placerat tortor. Fusce suscipit quam luctus posuere commodo. In facilisis consequat magna, id consectetur leo congue vel. In dictum massa pellentesque libero sollicitudin iaculis.

* Aenean vitae ligula sit amet tellus pretium blandit et ac sapien.

Nunc sagittis tempor eleifend. Fusce eu sollicitudin purus, at egestas augue. Vestibulum massa tellus, sollicitudin at tellus id, auctor finibus eros. Maecenas scelerisque leo quis massa euismod egestas. Donec sed eros sit amet magna vestibulum vestibulum. Donec porta tempor ex, at lacinia ipsum dignissim vel. Suspendisse purus justo, finibus id lacus eu, finibus vestibulum diam. Nam nec ligula id turpis aliquet sollicitudin quis id ligula. Proin at metus accumsan, venenatis ipsum et, rhoncus lacus. Curabitur ut tortor diam.


text:
using SE.DSP.Foundation.Infrastructure.BaseClass;
using SE.DSP.Foundation.Infrastructure.BE.Entities;
using SE.DSP.Foundation.Infrastructure.Constant;
using System;
using System.ServiceModel;
namespace SE.DSP.Foundation.API
{
    [ServiceContract]
    public interface IServiceProviderService
    {
        [OperationContract]
        ServiceProviderDto CreateServiceProvider(ServiceProviderDto dto);

        [OperationContract]
        ServiceProviderDto ModifyServiceProvider(ServiceProviderDto dto);

        [OperationContract]
        void DeleteServiceProvider(DtoBase dto);

        [OperationContract]
        ServiceProviderDto[] GetServiceProviders(ServiceProviderFilter filter);

        [OperationContract]
        long GetMaxServiceProviderId();

        [OperationContract]
        ServiceProviderCalcInfo[] GetServiceProviderCalcInfos();

        [OperationContract]
        ServiceProviderDto SendInitPassword(long spId);

        [OperationContract]
        ParentCalcStatus GetSpCalcStatus(long spId);

        [OperationContract]
        void UpdateServiceProvider(ServiceProviderEntity entity);
    }
}


text:
namespace GPSCheck
{
    partial class PlayControl
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.trackBar1 = new System.Windows.Forms.TrackBar();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.button3 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
            this.SuspendLayout();
            //
            // trackBar1
            //
            this.trackBar1.LargeChange = 1;
            this.trackBar1.Location = new System.Drawing.Point(12, 12);
            this.trackBar1.Maximum = 100;
            this.trackBar1.Name = "trackBar1";
            this.trackBar1.Size = new System.Drawing.Size(248, 45);
            this.trackBar1.TabIndex = 0;
            this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(21, 60);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(35, 12);
            this.label1.TabIndex = 3;
            this.label1.Text = "Time:";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(21, 100);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(53, 12);
            this.label2.TabIndex = 4;
            this.label2.Text = "Address:";
            //
            // button3
            //
            this.button3.Image = global::Properties.Resources.geo_fence_48px_1169457_easyicon_net;
            this.button3.Location = new System.Drawing.Point(391, 12);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(32, 32);
            this.button3.TabIndex = 5;
            this.button3.UseVisualStyleBackColor = true;
            //
            // button2
            //
            this.button2.Image = global::Properties.Resources.Pause_48px_1077378_easyicon_net;
            this.button2.Location = new System.Drawing.Point(333, 12);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(32, 32);
            this.button2.TabIndex = 2;
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // button1
            //
            this.button1.Image = global::Properties.Resources.Play_32px_1072866_easyicon_net;
            this.button1.Location = new System.Drawing.Point(279, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(32, 32);
            this.button1.TabIndex = 1;
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.ForeColor = System.Drawing.Color.Red;
            this.label3.Location = new System.Drawing.Point(87, 60);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(0, 12);
            this.label3.TabIndex = 6;
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(87, 100);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(0, 12);
            this.label4.TabIndex = 7;
            //
            // PlayControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(443, 152);
            this.ControlBox = false;
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.trackBar1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Name = "PlayControl";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
            this.Text = "PlayControl";
            this.TopMost = true;
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TrackBar trackBar1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
    }
}


text:
- Mauricio Jost <mauriciojostx@gmail.com>
- Michael Friis <friism@gmail.com>


text:
package com.github.sixro.downloadservlet;

import static org.junit.Assert.*;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.jmock.Expectations;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.*;

public class RequestToDownloadServletTest {

	@Rule public JUnitRuleMockery context = new JUnitRuleMockery();
	private HttpServletRequest request = context.mock(HttpServletRequest.class);
	private HttpServletResponse response = context.mock(HttpServletResponse.class);
	private RequestToDownloadServlet servlet = new RequestToDownloadServlet();

	@Test public void write_the_request_content_in_output_setting_contenttype_and_disposition_using_request_input() throws ServletException, IOException {
		final String csv = "a,b\n1,2";
		final StringWriter output = new StringWriter();

		context.checking(new Expectations() {{
			oneOf(request).getParameter("mimeType");
				will(returnValue("text/csv"));
			oneOf(response).setContentType("text/csv");

			oneOf(request).getParameter("filename");
				will(returnValue("example1.csv"));
			oneOf(response).setHeader("Content-disposition", "attachment; filename=example1.csv");

			oneOf(request).getParameter("content");
				will(returnValue(csv));

			oneOf(response).getWriter();
				will(returnValue(new PrintWriter(output)));
		}});

		servlet.doPost(request, response);

		assertEquals(csv, output.toString());
	}

}