text:
package org.jtwig.resource;

import com.google.common.base.Optional;
import org.jtwig.resource.exceptions.ResourceException;
import org.jtwig.resource.loader.ResourceLoader;
import org.jtwig.resource.loader.TypedResourceLoader;
import org.jtwig.resource.metadata.ResourceMetadata;
import org.jtwig.resource.reference.ResourceReference;
import org.jtwig.resource.reference.ResourceReferenceExtractor;
import org.jtwig.resource.resolver.RelativeResourceResolver;
import org.jtwig.value.convert.string.StringConverter;
import org.jtwig.value.environment.ValueEnvironment;
import org.junit.Before;
import org.junit.Test;

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

import static junit.framework.TestCase.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ResourceServiceTest {
    private final HashMap<String, ResourceLoader> resourceLoaderMap = new HashMap<>();
    private final List<TypedResourceLoader> resourceLoaderList = new ArrayList<>();
    private final ArrayList<String> absoluteResourceTypes = new ArrayList<>();
    private final ArrayList<RelativeResourceResolver> relativeResourceResolvers = new ArrayList<>();
    private final ResourceReferenceExtractor resourceReferenceExtractor = mock(ResourceReferenceExtractor.class);

    private final ResourceService underTest = new ResourceService(resourceLoaderMap, resourceLoaderList, absoluteResourceTypes, relativeResourceResolvers, resourceReferenceExtractor);

    @Before
    public void setUp() throws Exception {
        resourceLoaderMap.clear();
        resourceLoaderList.clear();
        absoluteResourceTypes.clear();
        relativeResourceResolvers.clear();
    }

    @Test
    public void resolveAbsoluteSource() throws Exception {
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);

        absoluteResourceTypes.add("blah");
        when(source.getType()).thenReturn("blah");
        when(resourceReferenceExtractor.extract("path")).thenReturn(reference);

        ResourceReference result = underTest.resolve(source, "path");

        assertSame(reference, result);
    }

    @Test
    public void resolveAbsoluteTarget() throws Exception {
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);

        absoluteResourceTypes.add("blah");
        when(source.getType()).thenReturn("tu");
        when(reference.getType()).thenReturn("blah");
        when(resourceReferenceExtractor.extract("path")).thenReturn(reference);

        ResourceReference result = underTest.resolve(source, "path");

        assertSame(reference, result);
    }

    @Test
    public void resolveSameTypeNonAbsolute() throws Exception {
        ResourceReference expected = mock(ResourceReference.class);
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);
        RelativeResourceResolver relativeResourceResolver = mock(RelativeResourceResolver.class);

        relativeResourceResolvers.add(relativeResourceResolver);
        when(source.getType()).thenReturn("blah");
        when(reference.getType()).thenReturn("blah");
        when(resourceReferenceExtractor.extract("path")).thenReturn(reference);
        when(relativeResourceResolver.resolve(source, reference)).thenReturn(Optional.of(expected));

        ResourceReference result = underTest.resolve(source, "path");

        assertSame(expected, result);
    }

    @Test
    public void resolveAnyTargetNonAbsolute() throws Exception {
        ResourceReference expected = mock(ResourceReference.class);
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);
        RelativeResourceResolver relativeResourceResolver = mock(RelativeResourceResolver.class);

        relativeResourceResolvers.add(relativeResourceResolver);
        when(source.getType()).thenReturn("blah");
        when(reference.getType()).thenReturn("any");
        when(resourceReferenceExtractor.extract("path")).thenReturn(reference);
        when(relativeResourceResolver.resolve(source, reference)).thenReturn(Optional.of(expected));

        ResourceReference result = underTest.resolve(source, "path");

        assertSame(expected, result);
    }

    @Test
    public void resolveSameTypeNonAbsoluteNotFound() throws Exception {
        ResourceReference expected = mock(ResourceReference.class);
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);
        RelativeResourceResolver relativeResourceResolver = mock(RelativeResourceResolver.class);

        relativeResourceResolvers.add(relativeResourceResolver);
        when(source.getType()).thenReturn("blah");
        when(reference.getType()).thenReturn("blah");
        when(resourceReferenceExtractor.extract("path")).thenReturn(reference);
        when(relativeResourceResolver.resolve(source, reference)).thenReturn(Optional.<ResourceReference>absent());

        ResourceReference result = underTest.resolve(source, "path");

        assertSame(reference, result);
    }

    @Test
    public void resolveRelativeSourceAnyTarget() throws Exception {
        ResourceReference expected = mock(ResourceReference.class);
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);
        RelativeResourceResolver relativeResourceResolver = mock(RelativeResourceResolver.class);

        relativeResourceResolvers.add(relativeResourceResolver);
        when(source.getType()).thenReturn("blah");
        when(reference.getType()).thenReturn("any");
        when(resourceReferenceExtractor.extract("path")).thenReturn(reference);
        when(relativeResourceResolver.resolve(source, reference)).thenReturn(Optional.<ResourceReference>absent());

        ResourceReference result = underTest.resolve(source, "path");

        assertSame(reference, result);
    }

    @Test
    public void resolveRelativeDistinctTypes() throws Exception {
        ResourceReference expected = mock(ResourceReference.class);
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);
        RelativeResourceResolver relativeResourceResolver = mock(RelativeResourceResolver.class);

        relativeResourceResolvers.add(relativeResourceResolver);
        when(source.getType()).thenReturn("blah");
        when(reference.getType()).thenReturn("tu");
        when(resourceReferenceExtractor.extract("path")).thenReturn(reference);
        when(relativeResourceResolver.resolve(source, reference)).thenReturn(Optional.<ResourceReference>absent());

        ResourceReference result = underTest.resolve(source, "path");

        assertSame(reference, result);
    }

    @Test(expected = ResourceException.class)
    public void loadMetadataNoLoader() throws Exception {
        underTest.loadMetadata(new ResourceReference("haha", "path"));
    }

    @Test
    public void resolveGenericResourceFromString() throws Exception {
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);
        ResourceMetadata resourceMetadata = mock(ResourceMetadata.class);
        ValueEnvironment valueEnvironment = mock(ValueEnvironment.class);
        StringConverter stringConverter = mock(StringConverter.class);

        ResourceService underTest = mock(ResourceService.class);

        when(stringConverter.convert("path")).thenReturn("path");
        when(valueEnvironment.getStringConverter()).thenReturn(stringConverter);
        when(resourceMetadata.exists()).thenReturn(true);
        when(underTest.loadMetadata(reference)).thenReturn(resourceMetadata);
        when(underTest.resolve(source, "path")).thenReturn(reference);
        when(underTest.resolve(source, "path", valueEnvironment)).thenCallRealMethod();

        ResourceReference result = underTest.resolve(source, "path", valueEnvironment);

        assertSame(reference, result);
    }

    @Test
    public void resolveGenericResourceFromList() throws Exception {
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);
        ResourceMetadata resourceMetadata = mock(ResourceMetadata.class);
        ValueEnvironment valueEnvironment = mock(ValueEnvironment.class);
        StringConverter stringConverter = mock(StringConverter.class);

        ResourceService underTest = mock(ResourceService.class);

        List<String> pathsList = new ArrayList<>();
        pathsList.add("path1");
        pathsList.add("path2");

        when(stringConverter.convert(pathsList.get(0))).thenReturn(pathsList.get(0));
        when(valueEnvironment.getStringConverter()).thenReturn(stringConverter);
        when(resourceMetadata.exists()).thenReturn(true);
        when(underTest.loadMetadata(reference)).thenReturn(resourceMetadata);
        when(underTest.resolve(source, pathsList.get(0))).thenReturn(reference);
        when(underTest.resolve(source, pathsList, valueEnvironment)).thenCallRealMethod();

        ResourceReference result = underTest.resolve(source, pathsList, valueEnvironment);

        assertSame(reference, result);
    }

    @Test
    public void resolveGenericResourceFromArray() throws Exception {
        ResourceReference source = mock(ResourceReference.class);
        ResourceReference reference = mock(ResourceReference.class);
        ResourceMetadata resourceMetadata = mock(ResourceMetadata.class);
        ValueEnvironment valueEnvironment = mock(ValueEnvironment.class);
        StringConverter stringConverter = mock(StringConverter.class);

        ResourceService underTest = mock(ResourceService.class);

        String[] pathsList = new String[] {"path1", "path2"};

        when(stringConverter.convert(pathsList[0])).thenReturn(pathsList[0]);
        when(valueEnvironment.getStringConverter()).thenReturn(stringConverter);
        when(resourceMetadata.exists()).thenReturn(true);
        when(underTest.loadMetadata(reference)).thenReturn(resourceMetadata);
        when(underTest.resolve(source, pathsList[0])).thenReturn(reference);
        when(underTest.resolve(source, pathsList, valueEnvironment)).thenCallRealMethod();

        ResourceReference result = underTest.resolve(source, pathsList, valueEnvironment);

        assertSame(reference, result);
    }
}

redpajama_set_name: RedPajamaGithub


text:
use std::borrow::Cow;

use super::ByteBuf;
use crate::keytype::*;

/// Blacklist hashes.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Blacklist;

impl KeyType for Blacklist {
    /// Login key descriptions are free-form.
    type Description = Description;
    /// Login payloads are free-form.
    type Payload = ();

    fn name() -> &'static str {
        "keyring"
    }
}

/// The hash type to blacklist.
#[derive(Debug, Clone, Eq)]
// #[non_exhaustive]
pub enum HashType {
    /// x509 data
    Tbs,
    /// Custom hash type
    Other(Cow<'static, str>),
}

impl HashType {
    /// The name of the hash type.
    fn name(&self) -> &str {
        match *self {
            HashType::Tbs => "tbs",
            HashType::Other(ref s) => s,
        }
    }
}

impl PartialEq for HashType {
    fn eq(&self, rhs: &Self) -> bool {
        self.name() == rhs.name()
    }
}

/// The description of a blacklist key.
pub struct Description {
    /// The hash type to blacklist.
    pub hash_type: HashType,
    /// The hash to blacklist.
    pub hash: Vec<u8>,
}

impl KeyDescription for Description {
    fn description(&self) -> Cow<str> {
        format!("{}:{:x}", self.hash_type.name(), ByteBuf(&self.hash)).into()
    }
}


text:
package org.springframework.transaction.annotation;

import junit.framework.TestCase;

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.transaction.CallCountingTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * @author Rob Harrop
 * @author Juergen Hoeller
 */
public class AnnotationTransactionInterceptorTests extends TestCase {

	private CallCountingTransactionManager ptm;

	private AnnotationTransactionAttributeSource source;

	private TransactionInterceptor ti;

	public void setUp() {
		this.ptm = new CallCountingTransactionManager();
		this.source = new AnnotationTransactionAttributeSource();
		this.ti = new TransactionInterceptor(this.ptm, this.source);
	}

	public void testClassLevelOnly() {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new TestClassLevelOnly());
		proxyFactory.addAdvice(this.ti);

		TestClassLevelOnly proxy = (TestClassLevelOnly) proxyFactory.getProxy();

		proxy.doSomething();
		assertGetTransactionAndCommitCount(1);

		proxy.doSomethingElse();
		assertGetTransactionAndCommitCount(2);

		proxy.doSomething();
		assertGetTransactionAndCommitCount(3);

		proxy.doSomethingElse();
		assertGetTransactionAndCommitCount(4);
	}

	public void testWithSingleMethodOverride() {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new TestWithSingleMethodOverride());
		proxyFactory.addAdvice(this.ti);

		TestWithSingleMethodOverride proxy = (TestWithSingleMethodOverride) proxyFactory.getProxy();

		proxy.doSomething();
		assertGetTransactionAndCommitCount(1);

		proxy.doSomethingElse();
		assertGetTransactionAndCommitCount(2);

		proxy.doSomethingCompletelyElse();
		assertGetTransactionAndCommitCount(3);

		proxy.doSomething();
		assertGetTransactionAndCommitCount(4);
	}

	public void testWithSingleMethodOverrideInverted() {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new TestWithSingleMethodOverrideInverted());
		proxyFactory.addAdvice(this.ti);

		TestWithSingleMethodOverrideInverted proxy = (TestWithSingleMethodOverrideInverted) proxyFactory.getProxy();

		proxy.doSomething();
		assertGetTransactionAndCommitCount(1);

		proxy.doSomethingElse();
		assertGetTransactionAndCommitCount(2);

		proxy.doSomethingCompletelyElse();
		assertGetTransactionAndCommitCount(3);

		proxy.doSomething();
		assertGetTransactionAndCommitCount(4);
	}

	public void testWithMultiMethodOverride() {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new TestWithMultiMethodOverride());
		proxyFactory.addAdvice(this.ti);

		TestWithMultiMethodOverride proxy = (TestWithMultiMethodOverride) proxyFactory.getProxy();

		proxy.doSomething();
		assertGetTransactionAndCommitCount(1);

		proxy.doSomethingElse();
		assertGetTransactionAndCommitCount(2);

		proxy.doSomethingCompletelyElse();
		assertGetTransactionAndCommitCount(3);

		proxy.doSomething();
		assertGetTransactionAndCommitCount(4);
	}

	public void testWithRollback() {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new TestWithRollback());
		proxyFactory.addAdvice(this.ti);

		TestWithRollback proxy = (TestWithRollback) proxyFactory.getProxy();

		try {
			proxy.doSomethingErroneous();
			fail("Should throw IllegalStateException");
		}
		catch (IllegalStateException ex) {
			assertGetTransactionAndRollbackCount(1);
		}

		try {
			proxy.doSomethingElseErroneous();
			fail("Should throw IllegalArgumentException");
		}
		catch (IllegalArgumentException ex) {
			assertGetTransactionAndRollbackCount(2);
		}
	}

	public void testWithInterface() {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new TestWithInterfaceImpl());
		proxyFactory.addInterface(TestWithInterface.class);
		proxyFactory.addAdvice(this.ti);

		TestWithInterface proxy = (TestWithInterface) proxyFactory.getProxy();

		proxy.doSomething();
		assertGetTransactionAndCommitCount(1);

		proxy.doSomethingElse();
		assertGetTransactionAndCommitCount(2);

		proxy.doSomethingElse();
		assertGetTransactionAndCommitCount(3);

		proxy.doSomething();
		assertGetTransactionAndCommitCount(4);
	}

	public void testCrossClassInterfaceMethodLevelOnJdkProxy() throws Exception {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new SomeServiceImpl());
		proxyFactory.addInterface(SomeService.class);
		proxyFactory.addAdvice(this.ti);

		SomeService someService = (SomeService) proxyFactory.getProxy();

		someService.bar();
		assertGetTransactionAndCommitCount(1);

		someService.foo();
		assertGetTransactionAndCommitCount(2);

		someService.fooBar();
		assertGetTransactionAndCommitCount(3);
	}

	public void testCrossClassInterfaceOnJdkProxy() throws Exception {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new OtherServiceImpl());
		proxyFactory.addInterface(OtherService.class);
		proxyFactory.addAdvice(this.ti);

		OtherService otherService = (OtherService) proxyFactory.getProxy();

		otherService.foo();
		assertGetTransactionAndCommitCount(1);
	}

	private void assertGetTransactionAndCommitCount(int expectedCount) {
		assertEquals(expectedCount, this.ptm.begun);
		assertEquals(expectedCount, this.ptm.commits);
	}

	private void assertGetTransactionAndRollbackCount(int expectedCount) {
		assertEquals(expectedCount, this.ptm.begun);
		assertEquals(expectedCount, this.ptm.rollbacks);
	}

	@Transactional
	public static class TestClassLevelOnly {

		public void doSomething() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}

		public void doSomethingElse() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}
	}

	@Transactional
	public static class TestWithSingleMethodOverride {

		public void doSomething() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}

		@Transactional(readOnly = true)
		public void doSomethingElse() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}

		public void doSomethingCompletelyElse() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}
	}

	@Transactional(readOnly = true)
	public static class TestWithSingleMethodOverrideInverted {

		@Transactional
		public void doSomething() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}

		public void doSomethingElse() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}

		public void doSomethingCompletelyElse() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}
	}

	@Transactional
	public static class TestWithMultiMethodOverride {

		@Transactional(readOnly = true)
		public void doSomething() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}

		@Transactional(readOnly = true)
		public void doSomethingElse() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}

		public void doSomethingCompletelyElse() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}
	}

	@Transactional(rollbackFor = IllegalStateException.class)
	public static class TestWithRollback {

		public void doSomethingErroneous() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			throw new IllegalStateException();
		}

		@Transactional(rollbackFor = IllegalArgumentException.class)
		public void doSomethingElseErroneous() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			throw new IllegalArgumentException();
		}
	}

	@Transactional
	public static interface TestWithInterface {

		public void doSomething();

		@Transactional(readOnly = true)
		public void doSomethingElse();
	}

	public static class TestWithInterfaceImpl implements TestWithInterface {

		public void doSomething() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}

		public void doSomethingElse() {
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
		}
	}

	public static interface SomeService {

		void foo();

		@Transactional
		void bar();

		@Transactional(readOnly = true)
		void fooBar();
	}

	public static class SomeServiceImpl implements SomeService {

		public void bar() {
		}

		@Transactional
		public void foo() {
		}

		@Transactional(readOnly = false)
		public void fooBar() {
		}
	}

	public static interface OtherService {

		void foo();
	}

	@Transactional
	public static class OtherServiceImpl implements OtherService {

		public void foo() {
		}
	}

}


text:
layout: page-project-overview
title: "Projects"
description: "Here are my projects"
header-img: "img/learnjs-bg.jpg"
order: 3
---

I am a front End Developer and I love JavaScript. Unfortunately I'm not brilliant at it so the purpose of this blog is to document my journey to become a better JavaScript developer

I do this stuff in my own time so I will add to it as and when I can but hopefully at least semi-regularly.

If you're reading this and have any advice, tips or criticism(preferably of the constructive variety) then I would love to hear it. Drop me a message on my contact form here


text:
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace UnicornClicker.UWP
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void Play_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(Game));
        }

        private void Scores_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(Scores));
        }
    }
}


text:
import React from 'react'
import DocumentTitle from 'react-document-title'
import { prefixLink } from 'gatsby-helpers'

const BUILD_TIME = new Date().getTime()

module.exports = React.createClass({
    displayName: 'HTML',
    propTypes: {
        body: React.PropTypes.string,
    },
    render() {
        const {body, route} = this.props
        const title = DocumentTitle.rewind()
        const font = <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic' rel='stylesheet' type='text/css' />
        let css
        if (process.env.NODE_ENV === 'production') {
            css = <style dangerouslySetInnerHTML={ { __html: require('!raw!./public/styles.css')} } />
        }
        return (
            <html lang="en">
              <head>
                <meta charSet="utf-8" />
                <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
                <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" />
                <title>{ title }</title>
                <meta property="og:type" content="website" />
                <meta property="og:image" content="https://tacrow.github.io/tacrow/img_og.png" />
                <meta property="og:site_name" content="tacrow" />
                <link rel="shortcut icon" href="../favicon.ico" />
                { /*font*/ }
                { css }
              </head>
              <body>
                <div id="react-mount" dangerouslySetInnerHTML={ {    __html: this.props.body} } />
                <script src={ prefixLink(`/bundle.js?t=${BUILD_TIME}`) } />
              </body>
            </html>
        );
    }
})


text:
require 'spec_helper'

RSpec.describe BrokerPool do
  context "empty broker list" do
    it "raises UnknownBroker error when trying to produce data" do
      expect { BrokerPool.new("test_client", [], 10_000).execute_api_call(0, :produce) }.to raise_error(BrokerPool::UnknownBroker)
    end
  end

  describe "fetching metadata" do
    context "single broker" do
      it "initializes connection properly" do
        @broker_pool = BrokerPool.new("test_client", ["localhost:9092"], 2_000)
        @broker = double('Poseidon::Connection', :topic_metadata => nil)

        expected_args = ["localhost", "9092", "test_client", 2_000]
        connection = double('conn').as_null_object

        expect(Connection).to receive(:new).with(*expected_args).and_return(connection)

        @broker_pool.fetch_metadata(Set.new)
      end
    end

    context "no seed brokers" do
      it "raises Error" do
        @broker_pool = BrokerPool.new("test_client", [], 10_000)
        expect { @broker_pool.fetch_metadata(Set.new) }.to raise_error(Errors::UnableToFetchMetadata)
      end
    end

    context "2 seed brokers" do
      before(:each) do
        @broker_pool = BrokerPool.new("test_client", ["first:9092","second:9092"], 10_000)
        @broker_1 = double('Poseidon::Connection_1', :topic_metadata => nil, :close => nil)
        @broker_2 = double('Poseidon::Connection_2', :topic_metadata => double('topic_metadata').as_null_object, :close => nil)
        allow(Connection).to receive(:new).and_return(@broker_1, @broker_2)
      end

      context ", first doesn't have metadata" do
        it "asks the second" do
          expect(@broker_2).to receive(:topic_metadata)

          @broker_pool.fetch_metadata(Set.new)
        end
      end

      it "cleans up its connections" do
        expect(@broker_1).to receive(:close)
        expect(@broker_2).to receive(:close)

        @broker_pool.fetch_metadata(Set.new)
      end
    end
  end

  context "which knowns about two brokers" do
    before(:each) do
      @broker_pool = BrokerPool.new("test_client", [], 10_000)
      @broker_pool.update_known_brokers({0 => { :host => "localhost", :port => 9092 }, 1 => {:host => "localhost", :port => 9093 }})
    end

    describe "when executing a call" do

      it "creates a connection for the correct broker" do
        c = double('conn').as_null_object
        expected_args = ["localhost", 9092, "test_client", 10_000]

        expect(Connection).to receive(:new).with(*expected_args).and_return(c)
        @broker_pool.execute_api_call(0, :produce)
      end

      it "it does so on the correct broker" do
        c = double('conn').as_null_object
        allow(Connection).to receive(:new).and_return(c)

        expect(c).to receive(:produce)
        @broker_pool.execute_api_call(0, :produce)
      end
    end

    describe "when executing two calls" do
      it "reuses the connection" do
        c = double('conn').as_null_object

        expect(Connection).to receive(:new).once.and_return(c)
        @broker_pool.execute_api_call(0, :produce)
        @broker_pool.execute_api_call(0, :produce)
      end
    end

    describe "executing a call for an unknown broker" do
      it "raises UnknownBroker" do
        expect { @broker_pool.execute_api_call(2, :produce) }.to raise_error(BrokerPool::UnknownBroker)
      end
    end
  end
end


text:
package com.twitter.finagle.redis

import java.lang.{Boolean => JBoolean, Long => JLong}
import java.net.InetSocketAddress
import com.twitter.finagle.redis.protocol._
import com.twitter.finagle.redis.util.ReplyFormat
import com.twitter.io.Buf
import com.twitter.util.{Duration, Future, Time}

private[redis] trait KeyCommands { self: BaseClient =>
  import com.twitter.conversions.DurationOps._

  /**
   * Removes keys
   * @param keys list of keys to remove
   * @return Number of keys removed
   */
  def dels(keys: Seq[Buf]): Future[JLong] =
    doRequest(Del(keys)) {
      case IntegerReply(n) => Future.value(n)
    }

  /**
   * Serialize the value stored at key in a Redis-specific format and
   * returns it to the user
   * @param key
   * @return bytes, or none if the key did not exist
   */
  def dump(key: Buf): Future[Option[Buf]] =
    doRequest(Dump(key)) {
      case BulkReply(message) => Future.value(Some(message))
      case EmptyBulkReply => Future.None
    }

  /**
   * Checks if given key exists
   * @param key
   * @return true if key exists, false otherwise
   */
  def exists(key: Buf): Future[JBoolean] =
    doRequest(Exists(key)) {
      case IntegerReply(n) => Future.value(n == 1)
    }

  /**
   * Sets how long it will take the key to expire
   * @param key
   * @param ttl
   * @return boolean, true if it successfully set the ttl (time to live) on a valid key,
   * false otherwise.
   */
  def expire(key: Buf, ttl: JLong): Future[JBoolean] =
    doRequest(Expire(key, ttl)) {
      case IntegerReply(n) => Future.value(n == 1)
    }

  /**
   * Same effect and semantic as "expire", but takes an absolute Unix timestamp
   * @param key
   * @param ttl time-to-live as unix timestamp
   * @return boolean, true if it successfully set the ttl (time to live) on a valid key,
   * false otherwise.
   */
  def expireAt(key: Buf, ttl: JLong): Future[JBoolean] =
    doRequest(ExpireAt(key, Time.fromMilliseconds(ttl))) {
      case IntegerReply(n) => Future.value(n == 1)
    }

  /**
   * Returns all keys matching pattern
   * @param pattern
   * @return list of keys matching pattern
   */
  def keys(pattern: Buf): Future[Seq[Buf]] =
    doRequest(Keys(pattern)) {
      case MBulkReply(messages) => Future.value(ReplyFormat.toBuf(messages))
      case EmptyMBulkReply => Future.Nil
    }

  /**
   * Migrates all keys to the destination server
   * @param destAddr target redis server
   * @param keys list of keys to be migrated
   * @param timeout timeout before failing, defaults to 5 seconds
   * @return unit
   */
  def migrate(
    destAddr: InetSocketAddress,
    keys: Seq[Buf],
    timeout: Duration = 5.seconds
  ): Future[Unit] = {
    doRequest(Migrate(destAddr, keys, timeout)) {
      case StatusReply(_) => Future.Unit
      case ErrorReply(msg) => Future.exception(new ServerError(msg))
    }
  }

  /**
   * Move key from the currently selected database to the specified destination
   * database. When key already exists in the destination database, or it does
   * not exist in the source database, it does nothing.
   *
   * @param key, db
   * @return true if key was moved.
   *         false if key was not moved for any reason.
   */
  def move(key: Buf, db: Buf): Future[JBoolean] =
    doRequest(Move(key, db)) {
      case IntegerReply(n) => Future.value(n == 1)
    }

  /**
   * Set a key's time to live in milliseconds.
   *
   * @param key, milliseconds
   * @return true if the timeout was set.
   *         false if key does not exist or the timeout could not be set.
   * @see https://redis.io/commands/pexpire
   */
  def pExpire(key: Buf, milliseconds: JLong): Future[JBoolean] =
    doRequest(PExpire(key, milliseconds)) {
      case IntegerReply(n) => Future.value(n == 1)
    }

  /**
   * Set the expiration for a key as a UNIX timestamp specified in milliseconds.
   *
   * @param key, timestamp
   * @return true if the timeout was set.
   *         false if key does not exist or the timeout could not be set
   *         (see: EXPIRE).
   * @see https://redis.io/commands/pexpireat
   */
  def pExpireAt(key: Buf, timestamp: JLong): Future[JBoolean] =
    doRequest(PExpireAt(key, Time.fromMilliseconds(timestamp))) {
      case IntegerReply(n) => Future.value(n == 1)
    }

  /**
   * Get the time to live for a key in milliseconds.
   *
   * @param key
   * @return Time to live in milliseconds or None when key does not exist or
   *         does not have a timeout.
   * @see
   */
  def pTtl(key: Buf): Future[Option[JLong]] =
    doRequest(PTtl(key)) {
      case IntegerReply(n) =>
        // -2 indicates key doesn't exist, -1 is key exists but no ttl set.
        if (n != -2) Future.value(Some(n))
        else Future.value(None)
    }

  /**
   * Returns keys starting at cursor
   * @param cursor, count, pattern
   * @return cursor followed by matching keys
   */
  def scans(cursor: JLong, count: Option[JLong], pattern: Option[Buf]): Future[Seq[Buf]] =
    doRequest(Scan(cursor, count, pattern)) {
      case MBulkReply(messages) => Future.value(ReplyFormat.toBuf(messages))
      case EmptyMBulkReply => Future.Nil
    }

  /**
   * Gets the ttl of the given key.
   * @param key
   * @return Option containing either the ttl in seconds if the key exists
   * and has a timeout, or else nothing.
   */
  def ttl(key: Buf): Future[Option[JLong]] =
    doRequest(Ttl(key)) {
      case IntegerReply(n) =>
        if (n != -1) Future.value(Some(n))
        else Future.None
    }

  /**
   * Persist a key by removing it's expiration time
   * @param key
   * @return 1 if ttl was removed, 0 if key doesn't exist or doesn't have a ttl
   */
  def persist(key: Buf): Future[JLong] =
    doRequest(Persist(key)) {
      case IntegerReply(n) => Future.value(n)
    }
}


text:
package org.apache.beam.runners.dataflow.worker.fn.control;

import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleDescriptor;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.runners.core.StateNamespace;
import org.apache.beam.runners.core.StateNamespaces;
import org.apache.beam.runners.core.TimerInternals;
import org.apache.beam.runners.core.construction.CoderTranslation;
import org.apache.beam.runners.core.construction.RehydratedComponents;
import org.apache.beam.runners.core.construction.Timer;
import org.apache.beam.runners.dataflow.worker.DataflowExecutionContext;
import org.apache.beam.runners.fnexecution.control.*;
import org.apache.beam.runners.fnexecution.state.StateRequestHandler;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.fn.data.FnDataReceiver;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.values.KV;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TimerReceiver {
  private static final Logger LOG = LoggerFactory.getLogger(ProcessRemoteBundleOperation.class);
  private final StageBundleFactory stageBundleFactory;
  private final DataflowExecutionContext.DataflowStepContext stepContext;

  private final Map<String, Coder<BoundedWindow>> timerWindowCodersMap;
  private final Map<String, ProcessBundleDescriptors.TimerSpec> timerOutputIdToSpecMap;
  private final Map<String, ProcessBundleDescriptors.TimerSpec> timerIdToTimerSpecMap;
  private final Map<String, Object> timerIdToKey;
  private final Map<String, Object> timerIdToPayload;

  private final StateRequestHandler stateRequestHandler = StateRequestHandler.unsupported();
  private final BundleProgressHandler progressHandler = BundleProgressHandler.ignored();
  private OutputReceiverFactory receiverFactory =
      new OutputReceiverFactory() {
        @Override
        public FnDataReceiver<?> create(String pCollectionId) {
          return receivedElement -> receive(pCollectionId, receivedElement);
        }
      };

  public TimerReceiver(
      RunnerApi.Components components,
      DataflowExecutionContext.DataflowStepContext stepContext,
      StageBundleFactory stageBundleFactory) {
    this.stageBundleFactory = stageBundleFactory;
    this.stepContext = stepContext;

    this.timerIdToKey = new HashMap<>();
    this.timerIdToPayload = new HashMap<>();

    ProcessBundleDescriptors.ExecutableProcessBundleDescriptor executableProcessBundleDescriptor =
        stageBundleFactory.getProcessBundleDescriptor();

    ProcessBundleDescriptor processBundleDescriptor =
        executableProcessBundleDescriptor.getProcessBundleDescriptor();

    // Create and cache lookups so that we don't have to dive into the ProcessBundleDescriptor
    // later.
    this.timerIdToTimerSpecMap = createTimerIdToSpecMap(executableProcessBundleDescriptor);
    this.timerOutputIdToSpecMap = createTimerOutputIdToSpecMap(executableProcessBundleDescriptor);
    this.timerWindowCodersMap =
        createTimerWindowCodersMap(processBundleDescriptor, this.timerIdToTimerSpecMap, components);
  }

  // Fires all timers until the SDK stops scheduling timers.
  public void finish() {
    try {
      // In Batch, the input watermark advances from -inf to +inf once all elements are processed.
      // For timers, this means we only fire them at the end of the bundle.
      fireTimers();
    } catch (Exception e) {
      throw new RuntimeException("Failed to finish firing all timers", e);
    }
  }

  // Collects timer elements and sets the timer to fire later. Returns true if receivedElement is a
  // timer element and was handled. Returns false, if receivedElement is not a timer element.
  public boolean receive(String pCollectionId, Object receivedElement) {
    LOG.debug("Received element {} for pcollection {}", receivedElement, pCollectionId);
    // TODO(BEAM-6274): move this out into its own receiver class
    if (timerOutputIdToSpecMap.containsKey(pCollectionId)) {
      WindowedValue<KV<Object, Timer>> windowedValue =
          (WindowedValue<KV<Object, Timer>>) receivedElement;
      ProcessBundleDescriptors.TimerSpec timerSpec = timerOutputIdToSpecMap.get(pCollectionId);
      Timer timer = windowedValue.getValue().getValue();

      for (BoundedWindow window : windowedValue.getWindows()) {
        Coder<BoundedWindow> windowCoder = timerWindowCodersMap.get(timerSpec.timerId());
        StateNamespace namespace = StateNamespaces.window(windowCoder, window);

        TimeDomain timeDomain = timerSpec.getTimerSpec().getTimeDomain();
        String timerId = timerSpec.timerId();

        TimerInternals timerInternals = stepContext.namespacedToUser().timerInternals();
        timerInternals.setTimer(namespace, timerId, timer.getTimestamp(), timeDomain);

        timerIdToKey.put(timerId, windowedValue.getValue().getKey());
        timerIdToPayload.put(timerId, timer.getPayload());
      }
      return true;
    }
    return false;
  }

  // Continuously fires scheduled timers from the SDK Harness until the SDK Harness stops scheduling
  // timers.
  private void fireTimers() throws Exception {
    TimerInternals.TimerData timerData = stepContext.getNextFiredTimer(GlobalWindow.Coder.INSTANCE);
    while (timerData != null) {
      StateNamespaces.WindowNamespace windowNamespace =
          (StateNamespaces.WindowNamespace) timerData.getNamespace();
      BoundedWindow window = windowNamespace.getWindow();

      WindowedValue<KV<Object, Timer>> timerValue =
          WindowedValue.of(
              KV.of(
                  timerIdToKey.get(timerData.getTimerId()),
                  Timer.of(timerData.getTimestamp(), timerIdToPayload.get(timerData.getTimerId()))),
              timerData.getTimestamp(),
              Collections.singleton(window),
              PaneInfo.NO_FIRING);

      String timerInputPCollection =
          timerIdToTimerSpecMap.get(timerData.getTimerId()).inputCollectionId();

      fireTimer(timerInputPCollection, timerValue);

      timerData = stepContext.getNextFiredTimer(GlobalWindow.Coder.INSTANCE);
    }
  }

  @VisibleForTesting
  protected void fireTimer(String timerInputPCollection, WindowedValue<KV<Object, Timer>> timer)
      throws Exception {
    // TODO(BEAM-6274): check this for performance considerations.
    // Timers are allowed to A) fire other timers, and B) fire themselves. To implement this,
    // we send the timer to the SDK Harness, wait for any elements, then check if any additional
    // timers were fired.
    RemoteBundle timerRemoteBundle =
        stageBundleFactory.getBundle(receiverFactory, stateRequestHandler, progressHandler);
    timerRemoteBundle.getInputReceivers().get(timerInputPCollection).accept(timer);
    timerRemoteBundle.close();
  }

  // Fills the given maps from timer the TimerSpec definitions in the process bundle descriptor.
  private static Map<String, ProcessBundleDescriptors.TimerSpec> createTimerOutputIdToSpecMap(
      ProcessBundleDescriptors.ExecutableProcessBundleDescriptor processBundleDescriptor) {
    Map<String, ProcessBundleDescriptors.TimerSpec> timerOutputIdToTimerSpecMap = new HashMap<>();
    processBundleDescriptor
        .getTimerSpecs()
        .values()
        .forEach(
            transformTimerMap -> {
              for (ProcessBundleDescriptors.TimerSpec timerSpec : transformTimerMap.values()) {
                timerOutputIdToTimerSpecMap.put(timerSpec.outputCollectionId(), timerSpec);
              }
            });
    return timerOutputIdToTimerSpecMap;
  }

  // Fills the given maps from timer the TimerSpec definitions in the process bundle descriptor.
  private static Map<String, ProcessBundleDescriptors.TimerSpec> createTimerIdToSpecMap(
      ProcessBundleDescriptors.ExecutableProcessBundleDescriptor processBundleDescriptor) {
    Map<String, ProcessBundleDescriptors.TimerSpec> timerIdToTimerSpecMap = new HashMap<>();
    processBundleDescriptor
        .getTimerSpecs()
        .values()
        .forEach(
            transformTimerMap -> {
              for (ProcessBundleDescriptors.TimerSpec timerSpec : transformTimerMap.values()) {
                timerIdToTimerSpecMap.put(timerSpec.timerId(), timerSpec);
              }
            });
    return timerIdToTimerSpecMap;
  }

  // Retrieves all window coders for all TimerSpecs.
  private static Map<String, Coder<BoundedWindow>> createTimerWindowCodersMap(
      ProcessBundleDescriptor processBundleDescriptor,
      Map<String, ProcessBundleDescriptors.TimerSpec> timerIdToTimerSpecMap,
      RunnerApi.Components components) {
    Map<String, Coder<BoundedWindow>> timerWindowCodersMap = new HashMap<>();

    RehydratedComponents rehydratedComponents = RehydratedComponents.forComponents(components);

    // Find the matching PTransform per timer. Then, rehydrate the PTransform window coder and
    // associate it with its timer.
    for (RunnerApi.PTransform pTransform : processBundleDescriptor.getTransformsMap().values()) {
      for (String timerId : timerIdToTimerSpecMap.keySet()) {
        if (!pTransform.getInputsMap().containsKey(timerId)) {
          continue;
        }

        RunnerApi.Coder windowingCoder =
            getTimerWindowingCoder(pTransform, timerId, processBundleDescriptor);
        try {
          timerWindowCodersMap.put(
              timerId,
              (Coder<BoundedWindow>)
                  CoderTranslation.fromProto(windowingCoder, rehydratedComponents));
        } catch (IOException e) {
          String err =
              String.format(
                  "Failed to retrieve window coder for timerId %s. Failed with error: %s",
                  timerId, e.getMessage());
          LOG.error(err);
          throw new RuntimeException(err, e);
        }
      }
    }
    return timerWindowCodersMap;
  }

  // Retrieves the window coder for the given timer.
  private static RunnerApi.Coder getTimerWindowingCoder(
      RunnerApi.PTransform pTransform,
      String timerId,
      ProcessBundleDescriptor processBundleDescriptor) {
    String timerPCollectionId = pTransform.getInputsMap().get(timerId);
    RunnerApi.PCollection timerPCollection =
        processBundleDescriptor.getPcollectionsMap().get(timerPCollectionId);

    String windowingStrategyId = timerPCollection.getWindowingStrategyId();
    RunnerApi.WindowingStrategy windowingStrategy =
        processBundleDescriptor.getWindowingStrategiesMap().get(windowingStrategyId);

    String windowingCoderId = windowingStrategy.getWindowCoderId();
    return processBundleDescriptor.getCodersMap().get(windowingCoderId);
  }
}


text:
package storage

import (
	"fmt"
	"os"
	"strconv"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/uuid"
	clientset "github.com/hyperhq/client-go/kubernetes"
	vsphere "k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere/vclib"
	"k8s.io/kubernetes/test/e2e/framework"
)

var _ = SIGDescribe("Volume Placement", func() {
	f := framework.NewDefaultFramework("volume-placement")
	var (
		c                  clientset.Interface
		ns                 string
		vsp                *vsphere.VSphere
		volumePaths        []string
		node1Name          string
		node1KeyValueLabel map[string]string
		node2Name          string
		node2KeyValueLabel map[string]string
		isNodeLabeled      bool
		err                error
	)
	BeforeEach(func() {
		framework.SkipUnlessProviderIs("vsphere")
		c = f.ClientSet
		ns = f.Namespace.Name
		framework.ExpectNoError(framework.WaitForAllNodesSchedulable(c, framework.TestContext.NodeSchedulableTimeout))
		if !isNodeLabeled {
			node1Name, node1KeyValueLabel, node2Name, node2KeyValueLabel = testSetupVolumePlacement(c, ns)
			isNodeLabeled = true
		}
		By("creating vmdk")
		vsp, err = getVSphere(c)
		Expect(err).NotTo(HaveOccurred())
		volumePath, err := createVSphereVolume(vsp, nil)
		Expect(err).NotTo(HaveOccurred())
		volumePaths = append(volumePaths, volumePath)
	})

	AfterEach(func() {
		for _, volumePath := range volumePaths {
			vsp.DeleteVolume(volumePath)
		}
		volumePaths = nil
	})

	/*
		Steps
		1. Remove labels assigned to node 1 and node 2
		2. Delete VMDK volume
	*/
	framework.AddCleanupAction(func() {
		// Cleanup actions will be called even when the tests are skipped and leaves namespace unset.
		if len(ns) > 0 {
			if len(node1KeyValueLabel) > 0 {
				framework.RemoveLabelOffNode(c, node1Name, "vsphere_e2e_label")
			}
			if len(node2KeyValueLabel) > 0 {
				framework.RemoveLabelOffNode(c, node2Name, "vsphere_e2e_label")
			}
		}
	})
	/*
		Steps

		1. Create pod Spec with volume path of the vmdk and NodeSelector set to label assigned to node1.
		2. Create pod and wait for pod to become ready.
		3. Verify volume is attached to the node1.
		4. Create empty file on the volume to verify volume is writable.
		5. Verify newly created file and previously created files exist on the volume.
		6. Delete pod.
		7. Wait for volume to be detached from the node1.
		8. Repeat Step 1 to 7 and make sure back to back pod creation on same worker node with the same volume is working as expected.

	*/

	It("should create and delete pod with the same volume source on the same worker node", func() {
		var volumeFiles []string
		pod := createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, volumePaths)

		// Create empty files on the mounted volumes on the pod to verify volume is writable
		// Verify newly and previously created files present on the volume mounted on the pod
		newEmptyFileName := fmt.Sprintf("/mnt/volume1/%v_1.txt", ns)
		volumeFiles = append(volumeFiles, newEmptyFileName)
		createAndVerifyFilesOnVolume(ns, pod.Name, []string{newEmptyFileName}, volumeFiles)
		deletePodAndWaitForVolumeToDetach(f, c, pod, vsp, node1Name, volumePaths)

		By(fmt.Sprintf("Creating pod on the same node: %v", node1Name))
		pod = createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, volumePaths)

		// Create empty files on the mounted volumes on the pod to verify volume is writable
		// Verify newly and previously created files present on the volume mounted on the pod
		newEmptyFileName = fmt.Sprintf("/mnt/volume1/%v_2.txt", ns)
		volumeFiles = append(volumeFiles, newEmptyFileName)
		createAndVerifyFilesOnVolume(ns, pod.Name, []string{newEmptyFileName}, volumeFiles)
		deletePodAndWaitForVolumeToDetach(f, c, pod, vsp, node1Name, volumePaths)
	})

	/*
		Steps

		1. Create pod Spec with volume path of the vmdk1 and NodeSelector set to node1's label.
		2. Create pod and wait for POD to become ready.
		3. Verify volume is attached to the node1.
		4. Create empty file on the volume to verify volume is writable.
		5. Verify newly created file and previously created files exist on the volume.
		6. Delete pod.
		7. Wait for volume to be detached from the node1.
		8. Create pod Spec with volume path of the vmdk1 and NodeSelector set to node2's label.
		9. Create pod and wait for pod to become ready.
		10. Verify volume is attached to the node2.
		11. Create empty file on the volume to verify volume is writable.
		12. Verify newly created file and previously created files exist on the volume.
		13. Delete pod.
	*/

	It("should create and delete pod with the same volume source attach/detach to different worker nodes", func() {
		var volumeFiles []string
		pod := createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, volumePaths)
		// Create empty files on the mounted volumes on the pod to verify volume is writable
		// Verify newly and previously created files present on the volume mounted on the pod
		newEmptyFileName := fmt.Sprintf("/mnt/volume1/%v_1.txt", ns)
		volumeFiles = append(volumeFiles, newEmptyFileName)
		createAndVerifyFilesOnVolume(ns, pod.Name, []string{newEmptyFileName}, volumeFiles)
		deletePodAndWaitForVolumeToDetach(f, c, pod, vsp, node1Name, volumePaths)

		By(fmt.Sprintf("Creating pod on the another node: %v", node2Name))
		pod = createPodWithVolumeAndNodeSelector(c, ns, vsp, node2Name, node2KeyValueLabel, volumePaths)

		newEmptyFileName = fmt.Sprintf("/mnt/volume1/%v_2.txt", ns)
		volumeFiles = append(volumeFiles, newEmptyFileName)
		// Create empty files on the mounted volumes on the pod to verify volume is writable
		// Verify newly and previously created files present on the volume mounted on the pod
		createAndVerifyFilesOnVolume(ns, pod.Name, []string{newEmptyFileName}, volumeFiles)
		deletePodAndWaitForVolumeToDetach(f, c, pod, vsp, node2Name, volumePaths)
	})

	/*
		Test multiple volumes from same datastore within the same pod
		1. Create volumes - vmdk2
		2. Create pod Spec with volume path of vmdk1 (vmdk1 is created in test setup) and vmdk2.
		3. Create pod using spec created in step-2 and wait for pod to become ready.
		4. Verify both volumes are attached to the node on which pod are created. Write some data to make sure volume are accessible.
		5. Delete pod.
		6. Wait for vmdk1 and vmdk2 to be detached from node.
		7. Create pod using spec created in step-2 and wait for pod to become ready.
		8. Verify both volumes are attached to the node on which PODs are created. Verify volume contents are matching with the content written in step 4.
		9. Delete POD.
		10. Wait for vmdk1 and vmdk2 to be detached from node.
	*/

	It("should create and delete pod with multiple volumes from same datastore", func() {
		By("creating another vmdk")
		volumePath, err := createVSphereVolume(vsp, nil)
		Expect(err).NotTo(HaveOccurred())
		volumePaths = append(volumePaths, volumePath)

		By(fmt.Sprintf("Creating pod on the node: %v with volume: %v and volume: %v", node1Name, volumePaths[0], volumePaths[1]))
		pod := createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, volumePaths)
		// Create empty files on the mounted volumes on the pod to verify volume is writable
		// Verify newly and previously created files present on the volume mounted on the pod
		volumeFiles := []string{
			fmt.Sprintf("/mnt/volume1/%v_1.txt", ns),
			fmt.Sprintf("/mnt/volume2/%v_1.txt", ns),
		}
		createAndVerifyFilesOnVolume(ns, pod.Name, volumeFiles, volumeFiles)
		deletePodAndWaitForVolumeToDetach(f, c, pod, vsp, node1Name, volumePaths)
		By(fmt.Sprintf("Creating pod on the node: %v with volume :%v and volume: %v", node1Name, volumePaths[0], volumePaths[1]))
		pod = createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, volumePaths)
		// Create empty files on the mounted volumes on the pod to verify volume is writable
		// Verify newly and previously created files present on the volume mounted on the pod
		newEmptyFilesNames := []string{
			fmt.Sprintf("/mnt/volume1/%v_2.txt", ns),
			fmt.Sprintf("/mnt/volume2/%v_2.txt", ns),
		}
		volumeFiles = append(volumeFiles, newEmptyFilesNames[0])
		volumeFiles = append(volumeFiles, newEmptyFilesNames[1])
		createAndVerifyFilesOnVolume(ns, pod.Name, newEmptyFilesNames, volumeFiles)
	})

	/*
		Test multiple volumes from different datastore within the same pod
		1. Create volumes - vmdk2 on non default shared datastore.
		2. Create pod Spec with volume path of vmdk1 (vmdk1 is created in test setup on default datastore) and vmdk2.
		3. Create pod using spec created in step-2 and wait for pod to become ready.
		4. Verify both volumes are attached to the node on which pod are created. Write some data to make sure volume are accessible.
		5. Delete pod.
		6. Wait for vmdk1 and vmdk2 to be detached from node.
		7. Create pod using spec created in step-2 and wait for pod to become ready.
		8. Verify both volumes are attached to the node on which PODs are created. Verify volume contents are matching with the content written in step 4.
		9. Delete POD.
		10. Wait for vmdk1 and vmdk2 to be detached from node.
	*/
	It("should create and delete pod with multiple volumes from different datastore", func() {
		By("creating another vmdk on non default shared datastore")
		var volumeOptions *vclib.VolumeOptions
		volumeOptions = new(vclib.VolumeOptions)
		volumeOptions.CapacityKB = 2097152
		volumeOptions.Name = "e2e-vmdk-" + strconv.FormatInt(time.Now().UnixNano(), 10)
		volumeOptions.Datastore = os.Getenv("VSPHERE_SECOND_SHARED_DATASTORE")
		volumePath, err := createVSphereVolume(vsp, volumeOptions)
		Expect(err).NotTo(HaveOccurred())
		volumePaths = append(volumePaths, volumePath)

		By(fmt.Sprintf("Creating pod on the node: %v with volume :%v  and volume: %v", node1Name, volumePaths[0], volumePaths[1]))
		pod := createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, volumePaths)

		// Create empty files on the mounted volumes on the pod to verify volume is writable
		// Verify newly and previously created files present on the volume mounted on the pod
		volumeFiles := []string{
			fmt.Sprintf("/mnt/volume1/%v_1.txt", ns),
			fmt.Sprintf("/mnt/volume2/%v_1.txt", ns),
		}
		createAndVerifyFilesOnVolume(ns, pod.Name, volumeFiles, volumeFiles)
		deletePodAndWaitForVolumeToDetach(f, c, pod, vsp, node1Name, volumePaths)

		By(fmt.Sprintf("Creating pod on the node: %v with volume :%v  and volume: %v", node1Name, volumePaths[0], volumePaths[1]))
		pod = createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, volumePaths)
		// Create empty files on the mounted volumes on the pod to verify volume is writable
		// Verify newly and previously created files present on the volume mounted on the pod
		newEmptyFileNames := []string{
			fmt.Sprintf("/mnt/volume1/%v_2.txt", ns),
			fmt.Sprintf("/mnt/volume2/%v_2.txt", ns),
		}
		volumeFiles = append(volumeFiles, newEmptyFileNames[0])
		volumeFiles = append(volumeFiles, newEmptyFileNames[1])
		createAndVerifyFilesOnVolume(ns, pod.Name, newEmptyFileNames, volumeFiles)
		deletePodAndWaitForVolumeToDetach(f, c, pod, vsp, node1Name, volumePaths)
	})

	/*
		Test Back-to-back pod creation/deletion with different volume sources on the same worker node
		    1. Create volumes - vmdk2
		    2. Create pod Spec - pod-SpecA with volume path of vmdk1 and NodeSelector set to label assigned to node1.
		    3. Create pod Spec - pod-SpecB with volume path of vmdk2 and NodeSelector set to label assigned to node1.
		    4. Create pod-A using pod-SpecA and wait for pod to become ready.
		    5. Create pod-B using pod-SpecB and wait for POD to become ready.
		    6. Verify volumes are attached to the node.
		    7. Create empty file on the volume to make sure volume is accessible. (Perform this step on pod-A and pod-B)
		    8. Verify file created in step 5 is present on the volume. (perform this step on pod-A and pod-B)
		    9. Delete pod-A and pod-B
		    10. Repeatedly (5 times) perform step 4 to 9 and verify associated volume's content is matching.
		    11. Wait for vmdk1 and vmdk2 to be detached from node.
	*/
	It("test back to back pod creation and deletion with different volume sources on the same worker node", func() {
		var (
			podA                *v1.Pod
			podB                *v1.Pod
			testvolumePathsPodA []string
			testvolumePathsPodB []string
			podAFiles           []string
			podBFiles           []string
		)

		defer func() {
			By("clean up undeleted pods")
			framework.ExpectNoError(framework.DeletePodWithWait(f, c, podA), "defer: Failed to delete pod ", podA.Name)
			framework.ExpectNoError(framework.DeletePodWithWait(f, c, podB), "defer: Failed to delete pod ", podB.Name)
			By(fmt.Sprintf("wait for volumes to be detached from the node: %v", node1Name))
			for _, volumePath := range volumePaths {
				framework.ExpectNoError(waitForVSphereDiskToDetach(c, vsp, volumePath, types.NodeName(node1Name)))
			}
		}()

		testvolumePathsPodA = append(testvolumePathsPodA, volumePaths[0])
		// Create another VMDK Volume
		By("creating another vmdk")
		volumePath, err := createVSphereVolume(vsp, nil)
		Expect(err).NotTo(HaveOccurred())
		volumePaths = append(volumePaths, volumePath)
		testvolumePathsPodB = append(testvolumePathsPodA, volumePath)

		for index := 0; index < 5; index++ {
			By(fmt.Sprintf("Creating pod-A on the node: %v with volume: %v", node1Name, testvolumePathsPodA[0]))
			podA = createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, testvolumePathsPodA)

			By(fmt.Sprintf("Creating pod-B on the node: %v with volume: %v", node1Name, testvolumePathsPodB[0]))
			podB = createPodWithVolumeAndNodeSelector(c, ns, vsp, node1Name, node1KeyValueLabel, testvolumePathsPodB)

			podAFileName := fmt.Sprintf("/mnt/volume1/podA_%v_%v.txt", ns, index+1)
			podBFileName := fmt.Sprintf("/mnt/volume1/podB_%v_%v.txt", ns, index+1)
			podAFiles = append(podAFiles, podAFileName)
			podBFiles = append(podBFiles, podBFileName)

			// Create empty files on the mounted volumes on the pod to verify volume is writable
			By("Creating empty file on volume mounted on pod-A")
			framework.CreateEmptyFileOnPod(ns, podA.Name, podAFileName)

			By("Creating empty file volume mounted on pod-B")
			framework.CreateEmptyFileOnPod(ns, podB.Name, podBFileName)

			// Verify newly and previously created files present on the volume mounted on the pod
			By("Verify newly Created file and previously created files present on volume mounted on pod-A")
			verifyFilesExistOnVSphereVolume(ns, podA.Name, podAFiles)
			By("Verify newly Created file and previously created files present on volume mounted on pod-B")
			verifyFilesExistOnVSphereVolume(ns, podB.Name, podBFiles)

			By("Deleting pod-A")
			framework.ExpectNoError(framework.DeletePodWithWait(f, c, podA), "Failed to delete pod ", podA.Name)
			By("Deleting pod-B")
			framework.ExpectNoError(framework.DeletePodWithWait(f, c, podB), "Failed to delete pod ", podB.Name)
		}
	})
})

func testSetupVolumePlacement(client clientset.Interface, namespace string) (node1Name string, node1KeyValueLabel map[string]string, node2Name string, node2KeyValueLabel map[string]string) {
	nodes := framework.GetReadySchedulableNodesOrDie(client)
	if len(nodes.Items) < 2 {
		framework.Skipf("Requires at least %d nodes (not %d)", 2, len(nodes.Items))
	}
	node1Name = nodes.Items[0].Name
	node2Name = nodes.Items[1].Name
	node1LabelValue := "vsphere_e2e_" + string(uuid.NewUUID())
	node1KeyValueLabel = make(map[string]string)
	node1KeyValueLabel["vsphere_e2e_label"] = node1LabelValue
	framework.AddOrUpdateLabelOnNode(client, node1Name, "vsphere_e2e_label", node1LabelValue)

	node2LabelValue := "vsphere_e2e_" + string(uuid.NewUUID())
	node2KeyValueLabel = make(map[string]string)
	node2KeyValueLabel["vsphere_e2e_label"] = node2LabelValue
	framework.AddOrUpdateLabelOnNode(client, node2Name, "vsphere_e2e_label", node2LabelValue)
	return node1Name, node1KeyValueLabel, node2Name, node2KeyValueLabel
}

func createPodWithVolumeAndNodeSelector(client clientset.Interface, namespace string, vsp *vsphere.VSphere, nodeName string, nodeKeyValueLabel map[string]string, volumePaths []string) *v1.Pod {
	var pod *v1.Pod
	var err error
	By(fmt.Sprintf("Creating pod on the node: %v", nodeName))
	podspec := getVSpherePodSpecWithVolumePaths(volumePaths, nodeKeyValueLabel, nil)

	pod, err = client.CoreV1().Pods(namespace).Create(podspec)
	Expect(err).NotTo(HaveOccurred())
	By("Waiting for pod to be ready")
	Expect(framework.WaitForPodNameRunningInNamespace(client, pod.Name, namespace)).To(Succeed())

	By(fmt.Sprintf("Verify volume is attached to the node:%v", nodeName))
	for _, volumePath := range volumePaths {
		isAttached, err := verifyVSphereDiskAttached(client, vsp, volumePath, types.NodeName(nodeName))
		Expect(err).NotTo(HaveOccurred())
		Expect(isAttached).To(BeTrue(), "disk:"+volumePath+" is not attached with the node")
	}
	return pod
}

func createAndVerifyFilesOnVolume(namespace string, podname string, newEmptyfilesToCreate []string, filesToCheck []string) {
	// Create empty files on the mounted volumes on the pod to verify volume is writable
	By(fmt.Sprintf("Creating empty file on volume mounted on: %v", podname))
	createEmptyFilesOnVSphereVolume(namespace, podname, newEmptyfilesToCreate)

	// Verify newly and previously created files present on the volume mounted on the pod
	By(fmt.Sprintf("Verify newly Created file and previously created files present on volume mounted on: %v", podname))
	verifyFilesExistOnVSphereVolume(namespace, podname, filesToCheck)
}

func deletePodAndWaitForVolumeToDetach(f *framework.Framework, c clientset.Interface, pod *v1.Pod, vsp *vsphere.VSphere, nodeName string, volumePaths []string) {
	By("Deleting pod")
	framework.ExpectNoError(framework.DeletePodWithWait(f, c, pod), "Failed to delete pod ", pod.Name)

	By("Waiting for volume to be detached from the node")
	for _, volumePath := range volumePaths {
		framework.ExpectNoError(waitForVSphereDiskToDetach(c, vsp, volumePath, types.NodeName(nodeName)))
	}
}


text:
package com.allogy.app.media;

import java.util.ArrayList;

import com.hsl.txtreader.DocFile;

/**
 * @author Corey Cowart
 */

public class PDFBook extends EBook {
	private int numPages;
	private int bookLength;
	private ArrayList<String> TabOfConts;
	private ArrayList<String> Sections;

	public PDFBook (String fileName) {

		//the DocFile class allows quick access to data such as the number of pages in a document
		DocFile docfile = new DocFile(fileName);
		numPages = docfile.getNumPages();

		TabOfConts = new ArrayList<String>();
		Sections = new ArrayList<String>();
		bookLength = 0;

		/*First, this loop populates the table of contents with the corresponding page numbers
		 * since the current code cannot assess the meta data of the pdf file to determine inherent
		 * section titles
		 *
		 * Second, it extracts the text from each page individually and populates the bookContents
		 * array list with all of the actual text from the pdf file
		 *
		 * Finally, it accumulates the length of each section to get an overall book length.
		 */
		for (int i = 1; i <= numPages; i++){
			String currentSection = "Page " + i;
			TabOfConts.add(currentSection);

			StringBuffer content = docfile.getPageContent(i);
			String noTags = removeTags(content);
			Sections.add(noTags);

			bookLength += noTags.length();
		}
	}
	/*
	 *Since the PDF library being used translates the PDFs into html rather than just stripping the plain
	 *text out of them, this method is used to remove the html tags and introduce line breaks where needed.
	 */
    public static String removeTags (StringBuffer mContentStringBuffer){
    	String originalString = mContentStringBuffer.toString();
    	String newString = "";
    	String currentTag = "";

    	for (int i =0; i < originalString.length(); i++){
    		String currentChar = ""+originalString.charAt(i);
    		if (originalString.charAt(i) == '<'){

    			i++;

    			while(originalString.charAt(i) != '>'){
    				String currentTagChar = ""+originalString.charAt(i);
    				currentTag = currentTag+currentTagChar;
    				i++;
    			}
       			if (currentTag.equals("br")){
    				newString = newString+"\n";
    			}
    			currentTag = "";
    		}
    		else{
    			String currentRealChar = ""+originalString.charAt(i);
    			newString = newString+currentRealChar;
    		}
    	}
    	newString += "\n\n";
    	return newString;
    }

    /*
     * Returns the Array list that contains all of the pdf's text
     */
    public ArrayList<String> getSections() {
	    return Sections;
	}

    /*
     * Returns the pdf's table of contents
     */
	protected ArrayList<String> getTabOfConts() {
		return TabOfConts;
    }
}


text:
class Choice{
    constructor(_id, text, nextScene){
        this._id = _id;
        this.text = text;
        this.nextScene = nextScene;
    }

    getChoiceFilters = function(){
        return [];
    };
}


text:
namespace ch1 {
namespace s1 {
namespace ex20 {

// method is recursive
double Ln(size_t) {
    return 0.;
}

}  // namespace ex20
}  // namespace s1
}  // namespace ch1


text:
#include <stdlib.h>
#include <stdint.h>
#include <getopt.h>
#include <dlfcn.h>

#include <iostream>
#include <list>

#include "hogl/detail/ringbuf.hpp"
#include "hogl/detail/magic.hpp"
#include "hogl/plugin/format.hpp"
#include "hogl/format-basic.hpp"

#include "tools/coredump.hpp"
#include "tools/recovery-engine.hpp"

__HOGL_PRIV_NS_USING__;

// Command line args {
static struct option main_lopts[] = {
   {"help",    0, 0, 'h'},
   {"format",  1, 0, 'f'},
   {"plugin",  1, 0, 'p'},
   {"dump-rings",  0, 0, 'R'},
   {"dump-areas",  0, 0, 'A'},
   {"all",         0, 0, 'a'},
   {0, 0, 0, 0}
};

static char main_sopts[] = "hf:p:RAa";

static char main_help[] =
   "hogl-recover - HOGL log recovery from core dumps\n"
   "Usage:\n"
      "\thogl-recover [options] <core.dump.file> [executable.file]\n"
   "Options:\n"
      "\t--help -h              Display help text\n"
      "\t--format -f <fmt>      Format of the log records\n"
      "\t--plugin -p <fmt.so>   Plugin used for formating records\n"
      "\t--dump-rings -R        Dump recovered ring buffers\n"
      "\t--dump-areas -A        Dump recovered areas\n"
      "\t--all -a               Dump all buffers and records even if they were already flushed\n";
// }

int main(int argc, char *argv[])
{
	char *log_format = 0;
	char *fmt_plugin = 0;
	int opt;

	bool dump_rings = false;
	bool dump_areas = false;

	unsigned int flags = 0;

	// Parse command line args
	while ((opt = getopt_long(argc, argv, main_sopts, main_lopts, NULL)) != -1) {
		switch (opt) {
		case 'f':
			log_format = strdup(optarg);
			break;

		case 'p':
			fmt_plugin = strdup(optarg);
			break;

		case 'A':
			dump_areas = true;
			break;

		case 'R':
			dump_rings = true;
			break;

		case 'a':
			flags |= hogl::recovery_engine::DUMP_ALL;
			break;

		case 'h':
		default:
			fmt::printf("%s", main_help);
			exit(0);
		}
	}

	argc -= optind;
	argv += optind;

	if (argc < 1) {
		fmt::printf("%s", main_help);
		exit(1);
	}

	const char *corefile = argv[0];
	const char *execfile = 0;
	if (argc == 2)
		execfile = argv[1];

	// Load coredump file
	hogl::coredump  core(corefile, execfile);
	if (core.failed) {
		fmt::fprintf(stderr, "Failed to load core and executable files\n");
		exit(1);
	}

	// Create format handler
	void *plugin_handle = 0;
	hogl::plugin::format *plugin_ops = 0;
	hogl::format *fmt = 0;

	if (fmt_plugin) {
    		// Load plugin library
    		plugin_handle = dlopen(fmt_plugin, RTLD_LAZY);
    		if (!plugin_handle) {
			fmt::fprintf(stderr, "Failed to load formater plugin: %s\n", dlerror());
			exit(1);
    		}
    		// Reset errors
    		dlerror();

    		// Load the symbols
    		plugin_ops = (hogl::plugin::format *) dlsym(plugin_handle, "__hogl_plugin_format");
    		const char* dlsym_error = dlerror();
    		if (dlsym_error) {
			fmt::fprintf(stderr, "Failed to load plugin symbols: %s\n", dlsym_error);
			exit(1);
    		}

		fmt = plugin_ops->create(log_format);
		if (!fmt) {
			fmt::fprintf(stderr, "Failed to initialize format plugin\n");
			exit(1);
		}
	} else
		fmt = new hogl::format_basic(log_format);

	// Create recovery engine
	hogl::recovery_engine *engine = new hogl::recovery_engine(core, *fmt, flags);

	if (dump_rings)
		engine->dump_rings();

	if (dump_areas)
		engine->dump_areas();

	if (!dump_rings && !dump_areas) {
		engine->dump_outbufs();
		engine->dump_records();
	}

	// Cleanup
	delete engine;

	if (fmt_plugin) {
		plugin_ops->release(fmt);
		dlclose(plugin_handle);
	} else
		delete fmt;

	return 0;
}


text:
declare const $: any;
declare const ScrollMagic: any;
declare const firebase: any;
import { FullWindowToggleController } from './components/FullWindowToggleController';
import { MenuController } from './components/MenuController';
import { ShowcaseController } from './components/ShowcaseController';

import { HeaderController } from './sections/HeaderController';
import { AnnounceController } from './sections/AnnounceController';
import { GalleryController } from './sections/GalleryController';
import { StoryController } from './sections/StoryController';
import { RSVPController } from './sections/RSVPController';
import { ProgramController } from './sections/ProgramController';

//db init
const config = {
    apiKey: "AIzaSyCiAAj1bTaHLocP5P-PlNZ7dEz0BOxUAj0",
    databaseURL: "https://mywed-f3944.firebaseio.com"
};
firebase.initializeApp(config);

//controllers
const windowWidth = $(window).width() as number;
const windowHeight = $(window).height() as number;
let scrollMagicController = new ScrollMagic.Controller();

new FullWindowToggleController();
new MenuController(windowHeight);
new ShowcaseController();
new HeaderController(scrollMagicController, windowHeight, windowWidth);
new AnnounceController(scrollMagicController, windowHeight, windowWidth);
new GalleryController(scrollMagicController, windowHeight, windowWidth);
new StoryController(scrollMagicController, windowHeight, windowWidth);
new RSVPController(scrollMagicController, windowHeight, windowWidth);


text:
'use strict';

/**
 * Expose `Validate`.
 */
module.exports = Validate;

/**
 * Module dependencies.
 */
var utils = require('../../utils'),
    Abstract = require('./abstract')
;

/**
 * Initialize a new Validate data interpreter.
 */
function Validate() {
}

utils.extend(Abstract, Validate);

/**
 * @interface {danf:manipulation.dataInterpreter}
 */
Object.defineProperty(Validate.prototype, 'order', {
    value: 1800
});

/**
 * @interface {danf:manipulation.dataInterpreter}
 */
Validate.prototype.interpret = function(name, value, contract, parameters) {
    // Validate the value.
    if (
        (parameters.final || undefined === parameters.final) &&
        null != value &&
        contract.validate
    ) {
        Object.checkType(contract.validate, 'function');

        try {
            var validatedValue = contract.validate(value, parameters);
        } catch (error) {
            throw new Error(
                'The expected value for "{0}" is {1}; {2} given instead.'.format(
                    name,
                    error.message,
                    Object.getTypeString(value, true)
                )
            );
        }

        if (null != validatedValue) {
            value = validatedValue;
        }
    }

    return value;
}


text:
"""
Class to study households' total wealth (financial + housing) distribution, for validation purposes, based on Wealth and
Assets Survey data.

@author: Adrian Carro
"""

from __future__ import division
import pandas as pd
import numpy as np

# Read Wealth and Assets Survey data for households
root = r""  # ADD HERE PATH TO WAS DATA FOLDER
chunk = pd.read_csv(root + r"/was_wave_3_hhold_eul_final.dta", usecols={"w3xswgt", "HFINWW3_sum", "HFINWNTW3_sum",
                                                                        "DVFNSValW3_aggr", "DVCACTvW3_aggr",
                                                                        "DVCASVVW3_aggr", "DVSaValW3_aggr",
                                                                        "DVCISAVW3_aggr", "DVCaCrValW3_aggr",
                                                                        "HPROPWW3", "DVPropertyW3", "DVHValueW3",
                                                                        "DVHseValW3_sum", "DVBltValW3_sum"})

# List of household variables currently used
# HFINWW3_sum                   Gross Financial Wealth (financial assets only)
# HFINWNTW3_sum                 Household Net financial Wealth (financial assets minus financial liabilities)

# Rename the different measures of financial wealth
chunk.rename(columns={"w3xswgt": "Weight"}, inplace=True)
chunk.rename(columns={"HFINWW3_sum": "GrossFinancialWealth"}, inplace=True)
chunk.rename(columns={"HFINWNTW3_sum": "NetFinancialWealth"}, inplace=True)
chunk["LiqFinancialWealth"] = chunk["DVFNSValW3_aggr"].astype(float) + chunk["DVCACTvW3_aggr"].astype(float)\
                           + chunk["DVCASVVW3_aggr"].astype(float) + chunk["DVSaValW3_aggr"].astype(float)\
                           + chunk["DVCISAVW3_aggr"].astype(float) + chunk["DVCaCrValW3_aggr"].astype(float)
# Rename the different measures of housing wealth
chunk.rename(columns={"HPROPWW3": "NetPropertyWealth"}, inplace=True)
chunk.rename(columns={"DVPropertyW3": "GrossPropertyWealth"}, inplace=True)
chunk["GrossHousingWealth"] = chunk["DVHValueW3"].astype(float) + chunk["DVHseValW3_sum"].astype(float)\
                           + chunk["DVBltValW3_sum"].astype(float)
# Filter down to keep only these columns
chunk = chunk[["Weight", "NetFinancialWealth", "GrossFinancialWealth", "LiqFinancialWealth",
               "NetPropertyWealth", "GrossPropertyWealth", "GrossHousingWealth"]]

# Create wealth bins for histograms
min_wealth_bin = 2.0
max_wealth_bin = 16.0
wealth_bin_edges = np.linspace(min_wealth_bin, max_wealth_bin, 57)

# For each combination of housing wealth and financial wealth measures...
financial_wealth_measures = ["NetFinancialWealth", "GrossFinancialWealth", "LiqFinancialWealth"]
housing_wealth_measures = ["NetPropertyWealth", "GrossPropertyWealth", "GrossHousingWealth"]
for financial_wealth_measure in financial_wealth_measures:
    for housing_wealth_measure in housing_wealth_measures:
        # ...add total wealth column
        chunk["TotalWealth"] = chunk[financial_wealth_measure].astype(float)\
                               + chunk[housing_wealth_measure].astype(float)
        # For the sake of using logarithmic scales, filter out any zero and negative values
        temp_chunk = chunk[(chunk["TotalWealth"] > 0.0)]
        # ...create a histogram
        frequency = np.histogram(np.log(temp_chunk["TotalWealth"].values), bins=wealth_bin_edges, density=True,
                                 weights=temp_chunk["Weight"].values)[0]
        # ...and print the distribution to a file
        with open(financial_wealth_measure + "-" + housing_wealth_measure + "-Weighted.csv", "w") as f:
            f.write("# Log Total Wealth (" + financial_wealth_measure + " + " + housing_wealth_measure
                    + ") (lower edge), Log Total Wealth (" + financial_wealth_measure + " + " + housing_wealth_measure
                    + ") (upper edge), Probability\n")
            for element, wealthLowerEdge, wealthUpperEdge in zip(frequency, wealth_bin_edges[:-1],
                                                                 wealth_bin_edges[1:]):
                f.write("{}, {}, {}\n".format(wealthLowerEdge, wealthUpperEdge, element))


text:
import InfoData = require('../../../infodata');
import PouchDatabase = require('./pouchdb/pouchdatabase');
//
class DataService extends PouchDatabase {
  constructor(xurl?: string, gen?: InfoData.IItemGenerator){
    super(xurl,gen);
  }
}// class DataService
var dataService = new DataService();
export = dataService;


text:
title: Functions of Work section
slug: work-section
menu: Functions of Work section
metadata:
    description: Die Webbasierte Anleitung für DIGAME vom Zentrum elektronische Medien ZEM.
    keywords: DIGAME,ZEM,Zentrum elektronische Medien,Mediathek Admin,Mediathek,Bilddatenbank,Bildverwaltung,Bundesverwaltung,Eidgenossenschaft,Schweizerische Eidgenossenschaft,VBS,Bundesamt für Verteidigung, Bevölkerungsschutz und Sport
    author: Stefan Eckstein | Zentrum elektronische Medien (ZEM)
    robots: index, follow
process:
	twig: true
taxonomy:
    category: backendanleitung
    tag: [digame, Anleitung, ZEM]
visible: true
---

## 'Functions' of Work section

***

In the Work section a search can be made for media assets or new media assets can be created.

{{ media['functions.png'].html() }}
###### Fig. 7: 'Overview of Menu section'.

### Simple search

If the text box is left empty during the search (1) and the 'Go' button is pressed, the search is subject to no restrictions. All media assets within the organisation are displayed. Any text can be entered into the text box or even an asset ID. This will reduce the number of media assets. Only those media assets will be sought whose metadata contain the corresponding words. You must take into account that a match will be sought in all metadata. If for instance a name has been entered, it may be found in the title, in the description or even in the author.

### Extended search

With the 'Extended search' button (3), a detailed search can be started. The options for an extended search are the same as those for defining a filter.

***

## Creating media assets

New media assets can be made by pressing the 'Create assets' button (as shown in (2) in Fig. 7 'Overview of Menu section'). A file explorer window opens where the respective original file can be selected out of which a media asset is to be generated. It is possible to select several files and make media assets out of them. It is also possible to create media assets directly from original files that are united in a ZIP file.

{{ media['progress.png'].html() }}
###### Fig. 8: 'Indication of progress while creating an asset'.

The progress bar (1) shows overall progress of media asset generation. Below the bar, all files are displayed that are being uploaded. Each file has its own progress bar (2) indicating its current status. The button (3) has two different states: when files are being uploaded and media assets are being generated, the button is designated with 'Background'. In this state the user can hide the dialogue and continue working in DIGAME (the user is informed when the process has been completed). As soon as all uploads have been completed and the media assets have been created, the button is designated with 'Close'. It serves to close the dialogue window.

The following formats can be processed by DIGAME:

- Pictures: .jpg, .png, .tiff, .eps
- Films: .mp4, .mv4, .mov
- Documents: .pdf, .doc
- Archive: .zip

Information: preview pictures cannot be automatically generated for eps files. The preview picture has to be added manually.

***


text:
import {AbstractTextDisplay} from "../../phaser_expansions/AbstractTextDisplay";
import {EncounterState} from "../../../states/encounterstate/EncounterState";
export class StaticTextDisplay extends AbstractTextDisplay {
    private background: Phaser.Graphics;
    private spacebarAnimation: Phaser.Sprite;
    //https://phaser.io/examples/v2/text/display-text-word-by-word

    constructor(public state: EncounterState, public rectanglex: number, public  rectangley: number, public text: string, public textboxheight: number, public textboxwidth: number, private callback: any) {
        super(state.game, rectanglex, rectangley, text, StaticTextDisplay.getStyle());
        this.prefixTextWithHashTag();
        this.setText(this.getFirstTextChunk(this.text));
        this.setTextBounds(rectanglex, textboxheight, textboxwidth, textboxheight);

        this.addBackground(rectanglex, textboxheight, textboxwidth);
        //TODO: Spacebar is hidden if text is too long.
        this.addSpacebar();
    }

    private addBackground(rectanglex: number, textboxheight: number, textboxwidth: number) {
        this.background = this.state.game.add.graphics(0, 0);
        this.background.beginFill(0x008080, 1);
        this.background.drawRect(rectanglex, textboxheight, textboxwidth, textboxheight);
    }

    private addSpacebar() {
        this.spacebarAnimation = this.state.game.add.sprite(590, 550, "pressSpace", 0);
        this.spacebarAnimation.animations.add("blink");
        this.spacebarAnimation.animations.play("blink", 1, true);
    }

    getStyle(): Phaser.PhaserTextStyle {
        return StaticTextDisplay.getStyle();
    }

    static getStyle() {
        return {
            align: "left",
            font: 'bold 36pt Arial',
            fill: 'white',
            wordWrap: true,
            wordWrapWidth: 800,
            backgroundColor: "#008080",
            boundsAlignH: "left",
            boundsAlignV: "center"
        };
    }

    private prefixTextWithHashTag() {
        if (!this.text.startsWith("#")) {
            this.text = "#" + this.text;
        }
        return this.text;
    }

    public destroy() {
        this.background.destroy(true);
        this.spacebarAnimation.destroy(true);
        super.destroy();
    }

    public performCallback() {
        if (this.callback) {
            return this.callback();
        }
    }

    public hasCallback(): boolean {
        return this.callback;
    }
}


text:
<?php

// ** Make sure all objects associated with the Muhimbi client can be resolved
require_once(__DIR__ . '/../../client/autoload.php');

// !!!! ENTER YOUR API KEY HERE !!!!
$api_key = '';

//** Was a file uploaded?
if($_FILES["file"]['size'] > 0)
{
    //** Make sure an api key has been entered
    if($api_key == '') {
        echo 'Please update the sample code and enter the API Key that came with your subscription.';
        exit;
    }

    // ** Specify the API key associated with your subscription.
    MuhimbiPDFOnline\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', $api_key);

    // ** The service's host name is already set, but for debugging purposes you may want to switch between 'http' and 'https'.'
    MuhimbiPDFOnline\Client\Configuration::getDefaultConfiguration()->setHost('https://api.muhimbi.com/api');

    // ** We are dealing with the Security Api, so instantiate the relevant class
    $api_instance = new MuhimbiPDFOnline\Client\Api\SecureApi();

    // ** We need to fill out the data for the security operation
    $input_data = new MuhimbiPDFOnline\Client\Model\SecureDocumentData();

    // ** Always pass the name of the input file, or if unknown pass any name, but with the correct file extension.
    $input_data->setSourceFileName($_FILES["file"]["name"]);

    // ** Pass the content of the uploaded file, making sure it is base64 encoded.
    $input_data->setSourceFileContent(base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));

    // ** Optionally specify a password for 'opening' the document
    $input_data->setOpenPassword('open');

    // ** When applying security restrictions PDF (e.g. 'Print|ContentCopy'), always specify an 'owner password', in this example the password is set to 'owner'
    $input_data->setOwnerPassword('owner');
    // ** Optionally specify the PDF security restrictions to apply, a combination of 'Print|HighResolutionPrint|ContentCopy|Annotations|FormFields|ContentAccessibility|DocumentAssembly''
    $input_data->setSecurityOptions('Print|ContentCopy');

    //** If you are expecting long running operations then consider longer timeouts
    //** Also keep an eye on the maximum upload size in your php.ini (e.g. post_max_size = 10M, upload_max_filesize = 10M)
    ini_set('default_socket_timeout', 300);
    set_time_limit ( 300 );

    try {
        // ** Apply the security settings.
        $result = $api_instance->secureDocument($input_data);

        // ** Send the converted file back to the user
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"secured_" . $input_data->getSourceFileName() . "\"");
        echo base64_decode($result->getProcessedFileContent());
        exit;
    } catch (Exception $e) {
        echo 'Exception when calling API: ', $e->getMessage(), PHP_EOL;
    }
}
?>

    <form action="secure_document.php" method="post" enctype="multipart/form-data">

Please specify the document (.pdf, .docx, .xlsx or .pptx) to secure.

      <input type="file" name="file" />

In this example the resulting document will require a password to open (the password is 'open').

      For PDF printing and content copying are restricted.

      For MS Office documents the owner password (it is 'owner') litfs editing restrictions.

      <input type="submit" value="Secure" />
    </form>


text:
package gachon.mobile.programming.android.finalproject.models;

import java.util.ArrayList;

public class FavoritesCategoryData {
    private boolean isSuccess;
    private ArrayList<FavoritesCategoryCodeData> data;

    public boolean isSuccess() {
        return isSuccess;
    }

    public ArrayList<FavoritesCategoryCodeData> getData() {
        return data;
    }
}


text:
package org.springframework.scheduling.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.scheduling.support.DelegatingErrorHandlingRunnable;
import org.springframework.scheduling.support.TaskUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

/**
 * {@link org.springframework.beans.factory.FactoryBean} that sets up
 * a {@link java.util.concurrent.ScheduledExecutorService}
 * (by default: a {@link java.util.concurrent.ScheduledThreadPoolExecutor})
 * and exposes it for bean references.
 *
 *
Allows for registration of {@link ScheduledExecutorTask ScheduledExecutorTasks},
 * automatically starting the {@link ScheduledExecutorService} on initialization and
 * cancelling it on destruction of the context. In scenarios that only require static
 * registration of tasks at startup, there is no need to access the
 * {@link ScheduledExecutorService} instance itself in application code at all;
 * ScheduledExecutorFactoryBean is then just being used for lifecycle integration.
 *
 *
Note that {@link java.util.concurrent.ScheduledExecutorService}
 * uses a {@link Runnable} instance that is shared between repeated executions,
 * in contrast to Quartz which instantiates a new Job for each execution.
 *
 *
WARNING: {@link Runnable Runnables} submitted via a native
 * {@link java.util.concurrent.ScheduledExecutorService} are removed from
 * the execution schedule once they throw an exception. If you would prefer
 * to continue execution after such an exception, switch this FactoryBean's
 * {@link #setContinueScheduledExecutionAfterException "continueScheduledExecutionAfterException"}
 * property to "true".
 *
 * @author Juergen Hoeller
 * @since 2.0
 * @see #setPoolSize
 * @see #setThreadFactory
 * @see ScheduledExecutorTask
 * @see java.util.concurrent.ScheduledExecutorService
 * @see java.util.concurrent.ScheduledThreadPoolExecutor
 */
@SuppressWarnings("serial")
public class ScheduledExecutorFactoryBean extends ExecutorConfigurationSupport
		implements FactoryBean<ScheduledExecutorService> {

	private int poolSize = 1;

	private ScheduledExecutorTask[] scheduledExecutorTasks;

	private boolean continueScheduledExecutionAfterException = false;

	private boolean exposeUnconfigurableExecutor = false;

	private ScheduledExecutorService exposedExecutor;

	/**
	 * Set the ScheduledExecutorService's pool size.
	 * Default is 1.
	 */
	public void setPoolSize(int poolSize) {
		Assert.isTrue(poolSize > 0, "'poolSize' must be 1 or higher");
		this.poolSize = poolSize;
	}

	/**
	 * Register a list of ScheduledExecutorTask objects with the ScheduledExecutorService
	 * that this FactoryBean creates. Depending on each ScheduledExecutorTask's settings,
	 * it will be registered via one of ScheduledExecutorService's schedule methods.
	 * @see java.util.concurrent.ScheduledExecutorService#schedule(java.lang.Runnable, long, java.util.concurrent.TimeUnit)
	 * @see java.util.concurrent.ScheduledExecutorService#scheduleWithFixedDelay(java.lang.Runnable, long, long, java.util.concurrent.TimeUnit)
	 * @see java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate(java.lang.Runnable, long, long, java.util.concurrent.TimeUnit)
	 */
	public void setScheduledExecutorTasks(ScheduledExecutorTask... scheduledExecutorTasks) {
		this.scheduledExecutorTasks = scheduledExecutorTasks;
	}

	/**
	 * Specify whether to continue the execution of a scheduled task
	 * after it threw an exception.
	 *
Default is "false", matching the native behavior of a
	 * {@link java.util.concurrent.ScheduledExecutorService}.
	 * Switch this flag to "true" for exception-proof execution of each task,
	 * continuing scheduled execution as in the case of successful execution.
	 * @see java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate
	 */
	public void setContinueScheduledExecutionAfterException(boolean continueScheduledExecutionAfterException) {
		this.continueScheduledExecutionAfterException = continueScheduledExecutionAfterException;
	}

	/**
	 * Specify whether this FactoryBean should expose an unconfigurable
	 * decorator for the created executor.
	 *
Default is "false", exposing the raw executor as bean reference.
	 * Switch this flag to "true" to strictly prevent clients from
	 * modifying the executor's configuration.
	 * @see java.util.concurrent.Executors#unconfigurableScheduledExecutorService
	 */
	public void setExposeUnconfigurableExecutor(boolean exposeUnconfigurableExecutor) {
		this.exposeUnconfigurableExecutor = exposeUnconfigurableExecutor;
	}

	@Override
	protected ExecutorService initializeExecutor(
			ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {

		ScheduledExecutorService executor =
				createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);

		// Register specified ScheduledExecutorTasks, if necessary.
		if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
			registerTasks(this.scheduledExecutorTasks, executor);
		}

		// Wrap executor with an unconfigurable decorator.
		this.exposedExecutor = (this.exposeUnconfigurableExecutor ?
				Executors.unconfigurableScheduledExecutorService(executor) : executor);

		return executor;
	}

	/**
	 * Create a new {@link ScheduledExecutorService} instance.
	 *
The default implementation creates a {@link ScheduledThreadPoolExecutor}.
	 * Can be overridden in subclasses to provide custom {@link ScheduledExecutorService} instances.
	 * @param poolSize the specified pool size
	 * @param threadFactory the ThreadFactory to use
	 * @param rejectedExecutionHandler the RejectedExecutionHandler to use
	 * @return a new ScheduledExecutorService instance
	 * @see #afterPropertiesSet()
	 * @see java.util.concurrent.ScheduledThreadPoolExecutor
	 */
	protected ScheduledExecutorService createExecutor(
			int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {

		return new ScheduledThreadPoolExecutor(poolSize, threadFactory, rejectedExecutionHandler);
	}

	/**
	 * Register the specified {@link ScheduledExecutorTask ScheduledExecutorTasks}
	 * on the given {@link ScheduledExecutorService}.
	 * @param tasks the specified ScheduledExecutorTasks (never empty)
	 * @param executor the ScheduledExecutorService to register the tasks on.
	 */
	protected void registerTasks(ScheduledExecutorTask[] tasks, ScheduledExecutorService executor) {
		for (ScheduledExecutorTask task : tasks) {
			Runnable runnable = getRunnableToSchedule(task);
			if (task.isOneTimeTask()) {
				executor.schedule(runnable, task.getDelay(), task.getTimeUnit());
			}
			else {
				if (task.isFixedRate()) {
					executor.scheduleAtFixedRate(runnable, task.getDelay(), task.getPeriod(), task.getTimeUnit());
				}
				else {
					executor.scheduleWithFixedDelay(runnable, task.getDelay(), task.getPeriod(), task.getTimeUnit());
				}
			}
		}
	}

	/**
	 * Determine the actual Runnable to schedule for the given task.
	 *
Wraps the task's Runnable in a
	 * {@link org.springframework.scheduling.support.DelegatingErrorHandlingRunnable}
	 * that will catch and log the Exception. If necessary, it will suppress the
	 * Exception according to the
	 * {@link #setContinueScheduledExecutionAfterException "continueScheduledExecutionAfterException"}
	 * flag.
	 * @param task the ScheduledExecutorTask to schedule
	 * @return the actual Runnable to schedule (may be a decorator)
	 */
	protected Runnable getRunnableToSchedule(ScheduledExecutorTask task) {
		return (this.continueScheduledExecutionAfterException ?
				new DelegatingErrorHandlingRunnable(task.getRunnable(), TaskUtils.LOG_AND_SUPPRESS_ERROR_HANDLER) :
				new DelegatingErrorHandlingRunnable(task.getRunnable(), TaskUtils.LOG_AND_PROPAGATE_ERROR_HANDLER));
	}

	@Override
	public ScheduledExecutorService getObject() {
		return this.exposedExecutor;
	}

	@Override
	public Class<? extends ScheduledExecutorService> getObjectType() {
		return (this.exposedExecutor != null ? this.exposedExecutor.getClass() : ScheduledExecutorService.class);
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

}


text:
FIND_PATH(
	BLOCKSRUNTIME_INCLUDE_DIRS
	NAMES
	Block.h Block_private.h
	HINTS
	/Library/Frameworks
	$ENV{HOME}/include
	/usr/local/include
	/usr/include
	/opt/local/include
	$ENV{SystemDrive}/QtDispatch/include
	$ENV{ProgramFiles}/QtDispatch/include
)

set(CMAKE_FIND_FRAMEWORK LAST)

FIND_LIBRARY(
	BLOCKSRUNTIME_LIBRARY_DEBUG
	NAMES
	BlocksRuntimeD libBlocksRuntimeD
	HINTS
	/Library/Frameworks
	$ENV{HOME}/lib
	/usr/local/lib
	/usr/lib
	/opt/local/lib
	$ENV{SystemDrive}/BlocksRuntime/lib
	$ENV{ProgramFiles}/BlocksRuntime/lib
)

FIND_LIBRARY(
	BLOCKSRUNTIME_LIBRARY_RELEASE
	NAMES
	BlocksRuntime libBlocksRuntime
	HINTS
	/Library/Frameworks
	$ENV{HOME}/lib
	/usr/local/lib
	/usr/lib
	/opt/local/lib
	$ENV{SystemDrive}/BlocksRuntime/lib
	$ENV{ProgramFiles}/BlocksRuntime/lib
)

IF (BLOCKSRUNTIME_LIBRARY_DEBUG AND NOT BLOCKSRUNTIME_LIBRARY_RELEASE)
	SET(BLOCKSRUNTIME_LIBRARIES ${BLOCKSRUNTIME_LIBRARY_DEBUG})
ENDIF ()

IF (BLOCKSRUNTIME_LIBRARY_RELEASE AND NOT BLOCKSRUNTIME_LIBRARY_DEBUG)
	SET(BLOCKSRUNTIME_LIBRARIES ${BLOCKSRUNTIME_LIBRARY_RELEASE})
ENDIF ()

IF (BLOCKSRUNTIME_LIBRARY_DEBUG AND BLOCKSRUNTIME_LIBRARY_RELEASE)
	SET(BLOCKSRUNTIME_LIBRARIES debug ${BLOCKSRUNTIME_LIBRARY_DEBUG} optimized ${BLOCKSRUNTIME_LIBRARY_RELEASE})
ENDIF ()

FIND_PACKAGE_HANDLE_STANDARD_ARGS(
	BlocksRuntime
	DEFAULT_MSG
	BLOCKSRUNTIME_INCLUDE_DIRS
	BLOCKSRUNTIME_LIBRARIES
)

MARK_AS_ADVANCED(
	BLOCKSRUNTIME_INCLUDE_DIRS
	BLOCKSRUNTIME_LIBRARIES
	BLOCKSRUNTIME_LIBRARY_DEBUG
	BLOCKSRUNTIME_LIBRARY_RELEASE
)