text:
package org.springframework.test.context.support;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.SmartContextLoader;
import org.springframework.test.context.util.TestContextResourceUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;

/**
 * Abstract application context loader that provides a basis for all concrete
 * implementations of the {@link ContextLoader} SPI. Provides a
 * Template Method based approach for {@link #processLocations processing}
 * resource locations.
 *
 *
As of Spring 3.1, {@code AbstractContextLoader} also provides a basis
 * for all concrete implementations of the {@link SmartContextLoader} SPI. For
 * backwards compatibility with the {@code ContextLoader} SPI,
 * {@link #processContextConfiguration(ContextConfigurationAttributes)} delegates
 * to {@link #processLocations(Class, String...)}.
 *
 * @author Sam Brannen
 * @author Juergen Hoeller
 * @since 2.5
 * @see #generateDefaultLocations
 * @see #getResourceSuffixes
 * @see #modifyLocations
 */
public abstract class AbstractContextLoader implements SmartContextLoader {

	private static final String[] EMPTY_STRING_ARRAY = new String[0];

	private static final Log logger = LogFactory.getLog(AbstractContextLoader.class);

	// --- SmartContextLoader -----------------------------------------------

	/**
	 * For backwards compatibility with the {@link ContextLoader} SPI, the
	 * default implementation simply delegates to {@link #processLocations(Class, String...)},
	 * passing it the {@link ContextConfigurationAttributes#getDeclaringClass()
	 * declaring class} and {@link ContextConfigurationAttributes#getLocations()
	 * resource locations} retrieved from the supplied
	 * {@link ContextConfigurationAttributes configuration attributes}. The
	 * processed locations are then
	 * {@link ContextConfigurationAttributes#setLocations(String[]) set} in
	 * the supplied configuration attributes.
	 *
Can be overridden in subclasses — for example, to process
	 * annotated classes instead of resource locations.
	 * @since 3.1
	 * @see #processLocations(Class, String...)
	 */
	@Override
	public void processContextConfiguration(ContextConfigurationAttributes configAttributes) {
		String[] processedLocations = processLocations(configAttributes.getDeclaringClass(),
			configAttributes.getLocations());
		configAttributes.setLocations(processedLocations);
	}

	/**
	 * Prepare the {@link ConfigurableApplicationContext} created by this
	 * {@code SmartContextLoader} before bean definitions are read.
	 *
The default implementation:
	 *

	 *
Sets the active bean definition profiles from the supplied
	 * {@code MergedContextConfiguration} in the
	 * {@link org.springframework.core.env.Environment Environment} of the
	 * context.

	 *
Adds {@link PropertySource PropertySources} for all
	 * {@linkplain MergedContextConfiguration#getPropertySourceLocations()
	 * resource locations} and
	 * {@linkplain MergedContextConfiguration#getPropertySourceProperties()
	 * inlined properties} from the supplied {@code MergedContextConfiguration}
	 * to the {@code Environment} of the context.

	 *
Determines what (if any) context initializer classes have been supplied
	 * via the {@code MergedContextConfiguration} and instantiates and
	 * {@linkplain ApplicationContextInitializer#initialize invokes} each with the
	 * given application context.

	 *

	 *
Any {@code ApplicationContextInitializers} implementing
	 * {@link org.springframework.core.Ordered Ordered} or annotated with {@link
	 * org.springframework.core.annotation.Order @Order} will be sorted appropriately.

	 *

	 *

	 * @param context the newly created application context
	 * @param mergedConfig the merged context configuration
	 * @since 3.2
	 * @see TestPropertySourceUtils#addPropertiesFilesToEnvironment
	 * @see TestPropertySourceUtils#addInlinedPropertiesToEnvironment
	 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
	 * @see #loadContext(MergedContextConfiguration)
	 * @see ConfigurableApplicationContext#setId
	 */
	protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
		context.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles());
		TestPropertySourceUtils.addPropertiesFilesToEnvironment(context, mergedConfig.getPropertySourceLocations());
		TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, mergedConfig.getPropertySourceProperties());
		invokeApplicationContextInitializers(context, mergedConfig);
	}

	@SuppressWarnings("unchecked")
	private void invokeApplicationContextInitializers(ConfigurableApplicationContext context,
			MergedContextConfiguration mergedConfig) {
		Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses = mergedConfig.getContextInitializerClasses();
		if (initializerClasses.isEmpty()) {
			// no ApplicationContextInitializers have been declared -> nothing to do
			return;
		}

		List<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();
		Class<?> contextClass = context.getClass();

		for (Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>> initializerClass : initializerClasses) {
			Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass,
				ApplicationContextInitializer.class);
			Assert.isAssignable(initializerContextClass, contextClass, String.format(
				"Could not add context initializer [%s] since its generic parameter [%s] "
						+ "is not assignable from the type of application context used by this "
						+ "context loader [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
				contextClass.getName()));
			initializerInstances.add((ApplicationContextInitializer<ConfigurableApplicationContext>) BeanUtils.instantiateClass(initializerClass));
		}

		AnnotationAwareOrderComparator.sort(initializerInstances);
		for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
			initializer.initialize(context);
		}
	}

	// --- ContextLoader -------------------------------------------------------

	/**
	 * If the supplied {@code locations} are {@code null} or empty
	 * and {@link #isGenerateDefaultLocations()} returns {@code true},
	 * default locations will be {@link #generateDefaultLocations(Class)
	 * generated} (i.e., detected) for the specified {@link Class class}
	 * and the configured {@linkplain #getResourceSuffixes() resource suffixes};
	 * otherwise, the supplied {@code locations} will be
	 * {@linkplain #modifyLocations modified} if necessary and returned.
	 *
	 * @param clazz the class with which the locations are associated: to be
	 * used when generating default locations
	 * @param locations the unmodified locations to use for loading the
	 * application context (can be {@code null} or empty)
	 * @return a processed array of application context resource locations
	 * @since 2.5
	 * @see #isGenerateDefaultLocations()
	 * @see #generateDefaultLocations(Class)
	 * @see #modifyLocations(Class, String...)
	 * @see org.springframework.test.context.ContextLoader#processLocations(Class, String...)
	 * @see #processContextConfiguration(ContextConfigurationAttributes)
	 */
	@Override
	public final String[] processLocations(Class<?> clazz, String... locations) {
		return (ObjectUtils.isEmpty(locations) && isGenerateDefaultLocations()) ? generateDefaultLocations(clazz)
				: modifyLocations(clazz, locations);
	}

	/**
	 * Generate the default classpath resource locations array based on the
	 * supplied class.
	 *
	 *
For example, if the supplied class is {@code com.example.MyTest},
	 * the generated locations will contain a single string with a value of
	 * {@code "classpath:com/example/MyTest<suffix>"}, where {@code <suffix>}
	 * is the value of the first configured
	 * {@linkplain #getResourceSuffixes() resource suffix} for which the
	 * generated location actually exists in the classpath.
	 *
	 *
As of Spring 3.1, the implementation of this method adheres to the
	 * contract defined in the {@link SmartContextLoader} SPI. Specifically,
	 * this method will preemptively verify that the generated default
	 * location actually exists. If it does not exist, this method will log a
	 * warning and return an empty array.
	 *
	 *
Subclasses can override this method to implement a different
	 * default location generation strategy.
	 *
	 * @param clazz the class for which the default locations are to be generated
	 * @return an array of default application context resource locations
	 * @since 2.5
	 * @see #getResourceSuffixes()
	 */
	protected String[] generateDefaultLocations(Class<?> clazz) {
		Assert.notNull(clazz, "Class must not be null");

		String[] suffixes = getResourceSuffixes();
		for (String suffix : suffixes) {
			Assert.hasText(suffix, "Resource suffix must not be empty");
			String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName()) + suffix;
			String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
			ClassPathResource classPathResource = new ClassPathResource(resourcePath);

			if (classPathResource.exists()) {
				if (logger.isInfoEnabled()) {
					logger.info(String.format("Detected default resource location \"%s\" for test class [%s]",
						prefixedResourcePath, clazz.getName()));
				}
				return new String[] { prefixedResourcePath };
			}
			else if (logger.isDebugEnabled()) {
				logger.debug(String.format("Did not detect default resource location for test class [%s]: "
						+ "%s does not exist", clazz.getName(), classPathResource));
			}
		}

		if (logger.isInfoEnabled()) {
			logger.info(String.format("Could not detect default resource locations for test class [%s]: "
					+ "no resource found for suffixes %s.", clazz.getName(), ObjectUtils.nullSafeToString(suffixes)));
		}

		return EMPTY_STRING_ARRAY;
	}

	/**
	 * Generate a modified version of the supplied locations array and return it.
	 *
The default implementation simply delegates to
	 * {@link TestContextResourceUtils#convertToClasspathResourcePaths}.
	 *
Subclasses can override this method to implement a different
	 * location modification strategy.
	 * @param clazz the class with which the locations are associated
	 * @param locations the resource locations to be modified
	 * @return an array of modified application context resource locations
	 * @since 2.5
	 */
	protected String[] modifyLocations(Class<?> clazz, String... locations) {
		return TestContextResourceUtils.convertToClasspathResourcePaths(clazz, locations);
	}

	/**
	 * Determine whether or not default resource locations should be
	 * generated if the {@code locations} provided to
	 * {@link #processLocations(Class, String...)} are {@code null} or empty.
	 *
As of Spring 3.1, the semantics of this method have been overloaded
	 * to include detection of either default resource locations or default
	 * configuration classes. Consequently, this method can also be used to
	 * determine whether or not default configuration classes should be
	 * detected if the {@code classes} present in the
	 * {@link ContextConfigurationAttributes configuration attributes} supplied
	 * to {@link #processContextConfiguration(ContextConfigurationAttributes)}
	 * are {@code null} or empty.
	 *
Can be overridden by subclasses to change the default behavior.
	 * @return always {@code true} by default
	 * @since 2.5
	 */
	protected boolean isGenerateDefaultLocations() {
		return true;
	}

	/**
	 * Get the suffix to append to {@link ApplicationContext} resource
	 * locations when detecting default locations.
	 *
	 *
Subclasses must provide an implementation of this method that
	 * returns a single suffix. Alternatively subclasses may provide a
	 * no-op implementation of this method and override
	 * {@link #getResourceSuffixes()} in order to provide multiple custom
	 * suffixes.
	 *
	 * @return the resource suffix; never {@code null} or empty
	 * @since 2.5
	 * @see #generateDefaultLocations(Class)
	 * @see #getResourceSuffixes()
	 */
	protected abstract String getResourceSuffix();

	/**
	 * Get the suffixes to append to {@link ApplicationContext} resource
	 * locations when detecting default locations.
	 *
	 *
The default implementation simply wraps the value returned by
	 * {@link #getResourceSuffix()} in a single-element array, but this
	 * can be overridden by subclasses in order to support multiple suffixes.
	 *
	 * @return the resource suffixes; never {@code null} or empty
	 * @since 4.1
	 * @see #generateDefaultLocations(Class)
	 */
	protected String[] getResourceSuffixes() {
		return new String[] { getResourceSuffix() };
	}

}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->
<virtualhosts>
    <default>carbon</default>
    <virtualhost>
        <name>carbon</name>
        <carbon>
            <store>
                <!--class>org.apache.qpid.server.store.MemoryMessageStore</class-->
		<class>org.apache.qpid.server.store.DerbyMessageStore</class>
		<environment-path>repository/database/qpid/derbystore</environment-path>
            </store>

            <housekeeping>
                <threadCount>2</threadCount>
                <expiredMessageCheckPeriod>20000</expiredMessageCheckPeriod>
            </housekeeping>

            <exchanges>
                <exchange>
                    <type>direct</type>
                    <name>carbon.direct</name>
                    <durable>true</durable>
                </exchange>
                <exchange>
                    <type>topic</type>
                    <name>carbon.topic</name>
                </exchange>
            </exchanges>

	    <queues>
                <maximumQueueDepth>4235264</maximumQueueDepth>
                <!-- 4Mb -->
                <maximumMessageSize>2117632</maximumMessageSize>
                <!-- 2Mb -->
                <maximumMessageAge>600000</maximumMessageAge>
                <!-- 10 mins -->
                <maximumMessageCount>50</maximumMessageCount>
                <!-- 50 messages -->
            </queues>
        </carbon>
    </virtualhost>
</virtualhosts>

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace backend\models;

use common\models\Admin;
use yii\base\Model;
use Yii;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $username;
    public $email;
    public $password;
    public $role;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\Admin', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'unique', 'targetClass' => '\common\models\Admin', 'message' => 'This email address has already been taken.'],
            ['role','required'],
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if ($this->validate()) {
            $user = new Admin();
            $user->username = $this->username;
            $user->email = $this->email;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->role=$this->role;
            if ($user->save()) {
                return $user;
            }
        }

        return null;
    }
}


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

    <item android:id="@+id/toDoReminderDoneMenuItem"
        app:showAsAction="always"
        android:title="@string/done_label"
        />

</menu>


text:
package org.gridkit.data.extractors.common;

import java.nio.ByteBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Extractors {

	@SuppressWarnings("unchecked")
	public static <V> V extract(Object source, BinaryExtractor<V> extractor) {
		BinaryExtractorSet set = extractor.newExtractorSet();
		final int id = set.addExtractor(extractor);
		set.compile();
		final Object[] result = new Object[1];
		set.extractAll(source, new VectorResultReceiver() {
			@Override
			public void push(int pid, Object part) {
				if (id == pid) {
					result[0] = part;
				}
				else {
					throw new IllegalArgumentException("Unknown argiment ID: " + pid);
				}

			}
		});
		return (V) result[0];
	}

	public static Object[] extractAll(Object source, BinaryExtractor<?>... extractors) {
		CompositeExtractorSet set = new CompositeExtractorSet();
		final int[] idmap = new int[extractors.length];
		for(int i = 0; i != idmap.length; ++i) {
			idmap[i] = set.addExtractor(extractors[i]);
		}

		final Object[] result = new Object[idmap.length];
		set.extractAll(source, new VectorResultReceiver() {
			@Override
			public void push(int pid, Object part) {
				for(int i = 0; i != idmap.length; ++i) {
					if (idmap[i] == pid) {
						result[i] = part;
					}
				}
			}
		});
		return result;
	}

	/**
	 * Creates empty {@link ChainedBinaryExtractor}, useful for building extractor using method chaining.
	 */
	public static ChainedBinaryExtractor<ByteBuffer> chain() {
		return  ChainedBinaryExtractor.chain();
	}

	/**
	 * Composes two extractor using {@link ChainedBinaryExtractor}.
	 */
	public static <V> ChainedBinaryExtractor<V> chain(BinaryExtractor<?> outter, BinaryExtractor<V> inner) {
		return  ChainedBinaryExtractor.chain(outter, inner);
	}

	/**
	 * Composes two extractor using {@link ChainedBinaryExtractor}.
	 */
	public static <V> ChainedBinaryExtractor<V> chain(BinaryExtractor<?> outter, BinaryExtractor<?> mid, BinaryExtractor<V> inner) {
		return  ChainedBinaryExtractor.chain(outter, mid).chain(inner);
	}

	public static BinaryExtractor<ByteBuffer> filter(BinaryExtractor<Boolean> predicate) {
		return new FilterExtractor<ByteBuffer>(predicate, VerbatimExtractor.INSTANCE);
	}

	public static String dump(BinaryExtractorSet set, int indent) {
		StringBuilder sb = new StringBuilder();
		set.dump(sb);
		if (indent == 0) {
			return sb.toString();
		}
		else {
			return indent(sb.toString(), indent);
		}
	}

	private static String indent(String string, int indent) {
		StringBuilder sb = new StringBuilder();

		Pattern regex = Pattern.compile("(\n)|(<[^/>]+>)|(<[/][^/>]+>)|(<[^/>]+[/]>)");
		Matcher m = regex.matcher(string);
		int ci = 0;
		int p = 0;
		while(true) {
			if (m.find(p)) {
				if (m.start() > p) {
					sb.append(string.substring(p, m.start()));
				}
				if ("\n".equals(m.group())) {
					sb.append("\n");
					for(int i = 0; i < ci * indent; ++i) {
						sb.append(' ');
					}
				}
				else if (m.group().endsWith("/>")) {
					sb.append(m.group());
				}
				else if (m.group().startsWith("</")) {
					--ci;
					// undo indentation before closing tag
					for(int i = 0; i < indent; ++i) {
						if (sb.charAt(sb.length() - 1) == ' ') {
							sb.setLength(sb.length() - 1);
						}
					}
					sb.append(m.group());
				}
				else {
					++ci;
					sb.append(m.group());
				}
				p = m.end();
			}
			else {
				sb.append(string.substring(p, string.length()));
				break;
			}
		}

		return sb.toString();
	}
}


text:
import {DOM, Element} from 'angular2/src/facade/dom';
import {normalizeBlank} from 'angular2/src/facade/lang';

export class NgElement {
  domElement:Element;
  constructor(domElement:Element) {
    this.domElement = domElement;
  }

  getAttribute(name:string) {
    return normalizeBlank(DOM.getAttribute(this.domElement, name));
  }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>iFrame message passing test</title>
		<meta name="description" content="iFrame message passing test">

		iFrame

			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

			But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

			On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

			But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

			On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

			But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

			On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

			But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

			On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.


text:
<feed xmlns="http://www.w3.org/2005/Atom">
<entry>
<content type="html"><span span=""></span></content>
</entry>
</feed>


text:
package testing

import (
	duckv1alpha1 "knative.dev/eventing/pkg/apis/duck/v1alpha1"
	"knative.dev/eventing/pkg/scheduler"
)

type VPodClient struct {
	store  *VPodStore
	lister scheduler.VPodLister
}

func NewVPodClient() *VPodClient {
	store := newVPodStore()
	return &VPodClient{
		store:  store,
		lister: newVPodLister(store),
	}
}

func (s *VPodClient) Create(ns, name string, vreplicas int32, placements []duckv1alpha1.Placement) scheduler.VPod {
	vpod := NewVPod(ns, name, vreplicas, placements)
	s.store.lock.Lock()
	defer s.store.lock.Unlock()
	s.store.vpods = append(s.store.vpods, vpod)
	return vpod
}

func (s *VPodClient) Append(vpod scheduler.VPod) {
	s.store.lock.Lock()
	defer s.store.lock.Unlock()
	s.store.vpods = append(s.store.vpods, vpod)
}

func (s *VPodClient) List() ([]scheduler.VPod, error) {
	return s.lister()
}


text:
import os
import sys
from distutils.core import setup

def read(filename):
    return open(os.path.join(os.path.dirname(__file__), filename)).read()

# Grab the version information
exec(open('cleveland/version.py').read())

if sys.version_info >= (3, 4):
    install_requires = []
else:
    install_requires = ['asyncio']

setup(name='cleveland',
      version=__version__,
      author='John Biesnecker',
      author_email='jbiesnecker@gmail.com',
      url='https://github.com/biesnecker/cleveland',
      packages=['cleveland'],
      package_dir={'cleveland': './cleveland'},
      install_requires=install_requires,
      description='Simple asyncio-based actors.',
      license='mit',
      long_description=read('README.txt')
)


text:
<gizmo-authenticator>

        <button onclick={logout}>Logout</button>

        URL<input type="text" value={url} name="url" onchange={onchange}/>
        Key<input type="text" value={key} name="key" onchange={onchange}/>
        Secret<input type="password" value={password} name="secret" onchange={onchange}/>
        <button onclick={login}>Login</button>

</gizmo-authenticator>


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

import com.facebook.presto.raptor.metadata.ColumnInfo;
import com.facebook.presto.raptor.metadata.ColumnStats;
import com.facebook.presto.raptor.metadata.DatabaseShardManager;
import com.facebook.presto.raptor.metadata.MetadataDao;
import com.facebook.presto.raptor.metadata.ShardInfo;
import com.facebook.presto.raptor.metadata.ShardManager;
import com.facebook.presto.raptor.metadata.ShardMetadata;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import io.airlift.testing.FileUtils;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.File;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.facebook.presto.raptor.metadata.MetadataDaoUtils.createMetadataTablesWithRetry;
import static com.facebook.presto.raptor.metadata.TestDatabaseShardManager.shardInfo;
import static com.facebook.presto.raptor.storage.TestOrcStorageManager.createOrcStorageManager;
import static com.facebook.presto.raptor.storage.TestShardRecovery.createShardRecoveryManager;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.util.stream.Collectors.toSet;
import static org.testng.Assert.assertEquals;

@Test(singleThreaded = true)
public class TestShardCompactionDiscovery
{
    private static final ReaderAttributes readerAttributes = new ReaderAttributes(new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE));

    private IDBI dbi;
    private Handle dummyHandle;
    private File dataDir;
    private ShardManager shardManager;

    @BeforeMethod
    public void setup()
    {
        dbi = new DBI("jdbc:h2:mem:test" + System.nanoTime());
        dummyHandle = dbi.open();
        dataDir = Files.createTempDir();
        shardManager = new DatabaseShardManager(dbi);
    }

    @AfterMethod
    public void teardown()
    {
        dummyHandle.close();
        FileUtils.deleteRecursively(dataDir);
    }

    @Test
    public void testTemporalShardDiscovery()
            throws Exception
    {
        List<ColumnInfo> columns = ImmutableList.of(new ColumnInfo(1, BIGINT), new ColumnInfo(2, BIGINT));
        long tableId = 1;
        shardManager.createTable(tableId, columns);
        createMetadataTablesWithRetry(dbi);
        dbi.onDemand(MetadataDao.class).updateTemporalColumnId(1, 1);

        Set<ShardInfo> nonTimeRangeShards = ImmutableSet.<ShardInfo>builder()
                .add(shardInfo(UUID.randomUUID(), "node1"))
                .add(shardInfo(UUID.randomUUID(), "node1"))
                .add(shardInfo(UUID.randomUUID(), "node1"))
                .build();
        shardManager.commitShards(tableId, columns, nonTimeRangeShards, Optional.empty());

        Set<ShardInfo> timeRangeShards = ImmutableSet.<ShardInfo>builder()
                .add(shardInfo(
                        UUID.randomUUID(),
                        "node1",
                        ImmutableList.of(new ColumnStats(1, 1, 10), new ColumnStats(2, 1, 10))))
                .add(shardInfo(
                        UUID.randomUUID(),
                        "node1",
                        ImmutableList.of(new ColumnStats(1, 2, 20), new ColumnStats(2, 2, 20))))
                .add(shardInfo(
                        UUID.randomUUID(),
                        "node1",
                        ImmutableList.of(new ColumnStats(1, 1, 10), new ColumnStats(2, 1, 10))))
                .build();
        shardManager.commitShards(tableId, columns, timeRangeShards, Optional.empty());

        StorageService storageService = new FileStorageService(dataDir);
        ShardRecoveryManager recoveryManager = createShardRecoveryManager(storageService, Optional.empty(), shardManager);
        StorageManager storageManager = createOrcStorageManager(storageService, Optional.empty(), recoveryManager);
        ShardCompactionManager shardCompactionManager = new ShardCompactionManager(
                dbi,
                "node1",
                shardManager,
                new ShardCompactor(storageManager, readerAttributes),
                new Duration(1, TimeUnit.HOURS),
                new DataSize(1, DataSize.Unit.MEGABYTE),
                100,
                10,
                true);

        Set<ShardMetadata> shardMetadata = shardManager.getNodeShards("node1");
        Set<ShardMetadata> temporalMetadata = shardCompactionManager.filterShardsWithTemporalMetadata(shardMetadata, 1, 1);
        assertEquals(temporalMetadata.stream().map(ShardMetadata::getShardUuid).collect(toSet()), timeRangeShards.stream().map(ShardInfo::getShardUuid).collect(toSet()));
    }
}


text:
module GraphQL
  module Models
    class RelationLoader < GraphQL::Batch::Loader
      attr_reader :model_class

      def initialize(model_class)
        @model_class = model_class
      end

      def perform(load_requests)
        # Group the requests to load by id into a single relation, and we'll fan it back out after
        # we have the results

        relations = []
        id_requests = load_requests.select { |r| r.load_type == :id }
        id_relation = model_class.where(id: id_requests.map(&:load_target))

        relations.push(id_relation) if id_requests.any?
        relations_to_requests = {}

        # Gather up all of the requests to load a relation, and map the relations back to their requests
        load_requests.select { |r| r.load_type == :relation }.each do |request|
          relation = request.load_target
          relations.push(relation) unless relations.detect { |r| r.object_id == relation.object_id }
          relations_to_requests[relation.object_id] ||= []
          relations_to_requests[relation.object_id].push(request)
        end

        # We need to build a query that will return all of the rows that match any of the relations.
        # But in addition, we also need to know how that relation sorted them. So we pull any ordering
        # information by adding RANK() columns to the query, and we determine whether that row belonged
        # to the query by adding CASE columns.

        # Map each relation to a SQL query that selects only the ID column for the rows that match it
        selection_clauses = relations.map do |relation|
          relation.unscope(:select).select(model_class.primary_key).to_sql
        end

        # Generate a CASE column that will tell us whether the row matches this particular relation
        slicing_columns = relations.each_with_index.map do |_relation, index|
          %{ CASE WHEN "#{model_class.table_name}"."#{model_class.primary_key}" IN (#{selection_clauses[index]}) THEN 1 ELSE 0 END AS "in_relation_#{index}" }
        end

        # For relations that have sorting applied, generate a RANK() column that tells us how the rows are
        # sorted within that relation
        sorting_columns = relations.each_with_index.map do |relation, index|
          arel = relation.arel
          next nil unless arel.orders.any?

          order_by = arel.orders.map do |expr|
            if expr.is_a?(Arel::Nodes::SqlLiteral)
              expr.to_s
            else
              expr.to_sql
            end
          end

          %{ RANK() OVER (ORDER BY #{order_by.join(', ')}) AS "sort_relation_#{index}" }
        end

        sorting_columns.compact!

        # Build the query that will select any of the rows that match the selection clauses
        main_relation = model_class
          .where("id in ((#{selection_clauses.join(") UNION (")}))")
          .select(%( "#{model_class.table_name}".* ))

        main_relation = slicing_columns.reduce(main_relation) { |relation, memo| relation.select(memo) }
        main_relation = sorting_columns.reduce(main_relation) { |relation, memo| relation.select(memo) }

        # Run the query
        result = main_relation.to_a

        # Now multiplex the results out to all of the relations that had asked for values
        relations.each_with_index do |relation, index|
          slice_col = "in_relation_#{index}"
          sort_col = "sort_relation_#{index}"

          matching_rows = result.select { |r| r[slice_col] == 1 }.sort_by { |r| r[sort_col] }

          if relation.object_id == id_relation.object_id
            pk = relation.klass.primary_key

            id_requests.each do |request|
              row = matching_rows.detect { |r| r[pk] == request.load_target }
              fulfill(request, row)
            end
          else
            relations_to_requests[relation.object_id].each do |request|
              fulfill_request(request, matching_rows)
            end
          end
        end
      end

      def fulfill_request(request, result)
        result = request.ensure_cardinality(result)
        request.fulfilled(result)
        fulfill(request, result)
      end
    end
  end
end


text:
import { alpha, lighten } from '@material-ui/core/styles';

const foo = alpha('#aaa');


text:
package org.jboss.arquillian.impl.client.deployment.tool;

import java.io.File;

import junit.framework.Assert;

import org.jboss.arquillian.impl.DynamicServiceLoader;
import org.jboss.arquillian.impl.client.deployment.tool.ToolingDeploymentFormatter;
import org.jboss.arquillian.spi.ServiceLoader;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;

/**
 * ToolingDeploymentFormatterTestCase
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
public class ToolingDeploymentFormatterTestCase
{

   @Test
   public void shouldBeAbleToExportArchive() throws Exception
   {
      String content = ShrinkWrap
            .create(WebArchive.class, "test.jar")
            .addAsResource(new File("src/test/resources/tooling/arquillian.xml"), ArchivePaths.create("resource.xml"))
            .addAsResource("tooling/arquillian.xml", ArchivePaths.create("resource2.xml"))
            .addAsResource(new File("src/test/resources/tooling/arquillian.xml").toURI().toURL(),
                  ArchivePaths.create("resource3.xml")).addClass(ToolingDeploymentFormatterTestCase.class)
            .addAsServiceProvider(ServiceLoader.class, DynamicServiceLoader.class)
            .addAsLibrary(ShrinkWrap.create(JavaArchive.class, "test.jar").addClass(ToolingDeploymentFormatter.class))
            .toString(new ToolingDeploymentFormatter(getClass()));

      // TODO: do some output Assertions..
      Assert.assertNotNull(content);
      System.out.println(content);
   }
}


text:
#import "DVTDocumentLocation.h"

@class IDETest, NSImage, NSString;

@interface IDEBotIntegrationTestsDocumentLocation : DVTDocumentLocation
{
    NSString *_navigableItem_name;
    IDETest *_test;
    NSString *_testName;
}

@property(copy, nonatomic) NSString *testName; // @synthesize testName=_testName;
@property(retain, nonatomic) IDETest *test; // @synthesize test=_test;
- (void).cxx_destruct;
- (unsigned long long)hash;
- (BOOL)isEqual:(id)arg1;
- (id)description;
- (id)initWithDocumentURL:(id)arg1 botExecutionName:(id)arg2 timestamp:(id)arg3 test:(id)arg4 testName:(id)arg5;
- (id)initWithDocumentURL:(id)arg1 botExecutionName:(id)arg2 timestamp:(id)arg3;
@property(readonly, nonatomic) NSImage *navigableItem_image;
@property(readonly, nonatomic) NSString *navigableItem_name;

@end


text:
package org.docksidestage.remote.maihama.showbase.wx.remogen.method.samename;

import org.lastaflute.core.util.Lato;

/**
 * The bean class as return for remote API of GET /wx/remogen/method/samename.
 * @author FreeGen
 */
public class RemoteWxRemogenMethodSamenameGetReturn extends org.docksidestage.bizfw.remoteapi.AbstractListGetReturn {

    /** The property of sea. (NullAllowed) */
    public String sea;

    /** The property of land. (NullAllowed) */
    public Integer land;

    /** The property of iamResult. (NullAllowed) */
    public String iamResult;

    @Override
    public String toString() {
        return Lato.string(this);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Basic Test Suite</title>

  <link rel="stylesheet" href="../node_modules/grunt-contrib-qunit/test/libs/qunit.css" media="screen">

this had better work.


text:
//TODO ƒRƒƒ"ƒg'̒ljÁAƒ\[ƒX'̐®—

#include <cassert>
#include "../Game/ResourceManager.h"
#include "../Game/StageConfig.h"
#include "CatGameLib.h"
#include "SceneManager.h"
#include "../Game/FileManager.h"
#include "Edit.h"

#define COUNTER 25

using namespace std;
using namespace CatGameLib;
using namespace MagicalBook;

static StageConfig* stageConfig = StageConfig::getInstance();

Edit::Edit() : editBgm(nullptr),
			   materialLogo(nullptr),
			   chipTable(nullptr),
			   save(nullptr),
			   redo(nullptr),
			   undo(nullptr),
			   pointer(nullptr)
{

	editBgm = LibSound::create("bgm/edit.wav");

	materialLogo = CatGameLib::LibSprite::create("logo/material.png");

	gridSize[Grid::S] = CatGameLib::LibSprite::create("background/grid14.png");
	gridSize[Grid::M] = CatGameLib::LibSprite::create("background/grid16.png");
	gridSize[Grid::L] = CatGameLib::LibSprite::create("background/grid18.png");

	chipTable = CatGameLib::LibSprite::create("background/chipTable.png");

	//'fÞ
	materials[MaterialNum::Chip] = LibSprites::create("mapchip/mapchip.png", 34, 34);
	materials[MaterialNum::Player] = LibSprites::create("player/player.png", 34, 68);
	materials[MaterialNum::Enemy] = LibSprites::create("enemy/crayon_red.png", 34, 68);
	materials[MaterialNum::Door] = LibSprites::create("gimmick/door_up.png", 42, 68);
	materials[MaterialNum::Gimmick] = LibSprites::create("gimmick/gimmick_up.png", 34, 68);

	save = CatGameLib::LibSprite::create("logo/save.png");

	pointer = CatGameLib::LibSprite::create("logo/pointer.png");
}

Edit::~Edit()
{
}

void Edit::init(void)
{
	input = LibInput::getInstance();

	books = ResourceManager::getInstance() -> getSprites("books");

	back = ResourceManager::getInstance() -> getSprite("back");

	volume = 0;
	volumeFlag = true;

	//‰¹º
	editBgm -> setVolume(0.0f);
	editBgm -> setLoop(true);

	books -> setPosition(sWHeaf + 200, sHHeaf);

	stageConfig -> setSizeNumber(stageConfig -> getSizeNumber());
	stageConfig -> setBgNumber(stageConfig -> getBgNumber());
	stageConfig -> setMusicNumber(stageConfig -> getMusicNumber());

	gridSize[stageConfig -> getSizeNumber()] -> setPosition(sWHeaf - 170, sHHeaf);
	gridSize[stageConfig -> getSizeNumber()] -> setScale(1.0f);
	gridSize[stageConfig -> getSizeNumber()] -> setAlpha(0.0f);

	for(int i = 1; i <= ResourceManager::BG_Count; i++)
	{
		string bgName = "game_bg" + to_string(i);
		bgTextures.push_back(ResourceManager::getInstance() -> getSprite(bgName.c_str()));
		bgTextures[i - 1] -> setPosition(sWHeaf - 170, sHHeaf);
		bgTextures[i - 1] -> setScale(0.7f);
		bgTextures[i - 1] -> setAlpha(0.0f);
	}

	//'fÞ
	materials[MaterialNum::Chip] -> setPosition(sWHeaf + 350, sHHeaf + 200);
	materials[MaterialNum::Player] -> setPosition(sWHeaf + 350, sHHeaf + 68);
	materials[MaterialNum::Enemy] -> setPosition(sWHeaf + 400, sHHeaf + 68);
	materials[MaterialNum::Door] -> setPosition(sWHeaf + 450, sHHeaf + 68);
	materials[MaterialNum::Gimmick] -> setPosition(sWHeaf + 500, sHHeaf + 68);

	for(int i = 0; i < MaterialNum::MaterialCount; i++)
	{
		materials[i] -> setScale(1.0f);
		materials[i] -> setAlpha(0.0f);
	}

	materialLogo -> setPosition(sWHeaf +450, sHHeaf + 300);
	materialLogo -> setScale(1.5f);
	materialLogo -> setAlpha(0.0f);

	chipTable -> setPosition(sWHeaf + 450, sHHeaf);
	chipTable -> setScale(1.0f);
	chipTable -> setAlpha(0.0f);

	pointer -> setPosition(sWHeaf + 350+17, sHHeaf + 200-17);
	pointer -> setScale(1.0f);
	pointer -> setAlpha(0.0f);

	save -> setPosition(sWHeaf + 550, sHHeaf - 200);
	save -> setScale(0.7f);
	save -> setAlpha(0.0f);

	back -> setPosition(sWHeaf + 450, sHHeaf - 300);
	back -> setScale(0.8f);
	back -> setAlpha(0.0f);

	screenSize = LibMain::getInstance() -> getScreenSize();

	if(stageConfig -> getSizeNumber() == 0)
	{
		stageSize = Small;
	}
	else if(stageConfig -> getSizeNumber() == 1)
	{
		stageSize = Medium;
	}
	else if(stageConfig -> getSizeNumber() == 2)
	{
		stageSize = Large;
	}

	chipCount = stageSize.x * stageSize.y;

	chipPosition.resize(chipCount);

	for(int y = 0; y < stageSize.y; y++)
	{
		for(int x = 0, posX = stageSize.x - 1; x < stageSize.x; x++, posX--)
		{
			const int arrayNumber = y * stageSize.x + x;
			chipPosition[arrayNumber].x = drawStartingPos.x + posX * chipSize.x;
			chipPosition[arrayNumber].y = drawStartingPos.y + y * chipSize.y;
		}
	}

	counter = 0;

	chipNum = 1;
	chipState = 0;
	chipDirection = 0;
	chipCounter = 0;
	chipHave = 0;

	materialRow = 1;
	materialCol = 1;

	materialSetRow = 1;
	materialSetCol = 1;

	anime_number = BOOK_ANM_MIN;

	edit_work = Fadein;
	edit_set_work = MaterialSelect;
}

void Edit::update(void)
{
	playSound();

	editDraw();

	materialDraw();

	switch (edit_work)
	{
	case Fadein:
		pictFade();
		break;
	case EditSet:
		edit();
		break;
	case BackAnimation:
	//	backAnimation();
		break;
	case Animation:
	//	animation();
		break;
	case Next:
	//	next();
		break;

	default:
		assert(!"•s³'ȏó'Ô");
		break;
	}

	//' 'ƂŏÁ'·
	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_X))
	{
		LibSound::allStop();
		SceneManager::getInstance() -> createScene(SceneManager::SceneNumber::EditSelect);
	}

}

/**
 *	@brief ‰¹ºÄ¶
 *
 *	@author	Tatsuya Maeda
 */
void Edit::playSound(void)
{
	if (editBgm -> getState() != LibSound::Play)
	{
		editBgm -> play();
	}

	if (volumeFlag == false)
	{
		volume -= BGM_FADE;
		editBgm -> setVolume(volume);
	}
	else if(volume <= MAX_VOLUME && volumeFlag == true)
	{
		volume += BGM_FADE;
		editBgm -> setVolume(volume);
	}
}

//ƒtƒF[ƒhƒCƒ"
void Edit::pictFade(void)
{
	if(gridSize[stageConfig -> getSizeNumber()] -> getAlpha() < 255)
	{
		gridSize[stageConfig -> getSizeNumber()] -> setAlpha(gridSize[stageConfig -> getSizeNumber()] -> getAlpha() + 5);
	}

	if(bgTextures[stageConfig -> getBgNumber()] -> getAlpha() < 255)
	{
		bgTextures[stageConfig -> getBgNumber()] -> setAlpha(bgTextures[stageConfig -> getBgNumber()] -> getAlpha() + 5);
	}

	if(materialLogo -> getAlpha() < 255)
	{
		materialLogo -> setAlpha(materialLogo -> getAlpha() + 5);
	}

	if(chipTable -> getAlpha() < 255)
	{
		chipTable -> setAlpha(chipTable -> getAlpha() + 5);
	}

	if(pointer -> getAlpha() < 255)
	{
		pointer -> setAlpha(pointer -> getAlpha() + 5);
	}

	//'fÞ
	for(int i = 0; i < MaterialNum::MaterialCount; i++)
	{
		if (materials[i] -> getAlpha() < 255)
		{
			materials[i] -> setAlpha(materials[i] -> getAlpha() + FADE);
		}
		else
		{
			materials[i] -> setAlpha(255);
		}
	}

	if(save -> getAlpha() < 255)
	{
		save -> setAlpha(save -> getAlpha() + 5);
	}

	if(back -> getAlpha() < 255)
	{
		back -> setAlpha(back -> getAlpha() + 5);
	}
	else
	{
		edit_work = EditSet;
	}

}

void Edit::edit(void)
{
	switch (edit_set_work)
	{
	case MaterialSelect:
		materialSelect();
		break;
	case MaterialSet:
		materialSet();
		break;
	default:
		assert(!"•s³'ȏó'Ô");
		break;
	}
}

//'fÞ'I'ð
void Edit::materialSelect(void)
{
	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Z))
	{
		materialSetRow = stageSize.x / 2;
		materialSetCol = stageSize.y / 2;

		if(materialRow == 1)
		{
			chipHave = 1;
			if(materialCol == 1)
			{
				chipNum = 1;
			}
			else if(materialCol == 2)
			{
				chipNum = 5;
			}
			else if(materialCol == 3)
			{
				chipNum = 9;
			}
			else if(materialCol == 4)
			{
				chipNum = 13;
			}
			else if(materialCol == 5)
			{
				chipNum = 17;
			}
		}
		else if(materialRow == 2)
		{
			chipHave = 1;
			if(materialCol == 1)
			{
				chipNum = 21;
			}
			else if(materialCol == 2)
			{
				chipNum = 25;
			}
			else if(materialCol == 3)
			{
				chipNum = 29;
			}
			else if(materialCol == 4)
			{
				chipNum = 33;
			}
		}
		else if(materialRow == 3)
		{
			chipState = materialCol;
			chipHave = 2;
		}
		edit_set_work = MaterialSet;
	}

	if(materialRow == 1 && materialCol == 5)
	{
		if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Up))
		{
			materialRow--;
			materialCol--;
		}
	}
	else
	{
		if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Up))
		{
			materialRow--;
		}
		if (input -> getKeyboardState(LibInput::KeyBoardNumber::Key_Up))
		{
			counter++;
			if(counter >= COUNTER && counter % 5 == 1)
			{
				materialRow--;
			}
		}
		else if (input -> getKeyboardUpState(LibInput::KeyBoardNumber::Key_Up))
		{
			counter = 0;
		}
	}
	if(materialRow == 1 && materialCol == 5)
	{
		if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Down))
		{
			materialRow++;
			materialCol--;
		}
	}
	else
	{
		if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Down))
		{
			materialRow++;
		}

		if (input -> getKeyboardState(LibInput::KeyBoardNumber::Key_Down))
		{
			counter++;
			if(counter >= COUNTER && counter % 5 == 1)
			{
				materialRow++;
			}
		}
		else if (input -> getKeyboardUpState(LibInput::KeyBoardNumber::Key_Down))
		{
			counter = 0;
		}
	}

	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Left))
	{
		if(materialRow % 4 != 0)
		{
			materialCol--;
		}
	}
	if (input -> getKeyboardState(LibInput::KeyBoardNumber::Key_Left))
	{
		counter++;
		if(counter >= COUNTER && counter % 5 == 1)
		{
			materialCol--;
		}
	}
	else if (input -> getKeyboardUpState(LibInput::KeyBoardNumber::Key_Left))
	{
		counter = 0;
	}

	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Right))
	{
		if(materialRow % 4 != 0)
		{
			materialCol++;
		}
	}
	if (input -> getKeyboardState(LibInput::KeyBoardNumber::Key_Right))
	{
		counter++;
		if(counter >= COUNTER && counter % 5 == 1)
		{
			materialCol++;
		}
	}
	else if (input -> getKeyboardUpState(LibInput::KeyBoardNumber::Key_Right))
	{
		counter = 0;
	}

	materialRow = LibBasicFunc::wrap(materialRow, 0, 4);
	if(materialRow == 1)
	{
		materialCol = LibBasicFunc::wrap(materialCol, 0, 6);
	}
	else
	{
		materialCol = LibBasicFunc::wrap(materialCol, 0, 5);
	}

	if(materialRow % 4 == 0)
	{
		pointer -> setPosition(sWHeaf + 450, sHHeaf - 310);
		back -> setScale(1.0f);
	}
	else if(materialRow % 4 == 3)
	{
		pointer -> setPositionY(sHHeaf + 200-17 - (materialRow - 1 + 1) * 50);
		back -> setScale(0.8f);
	}
	else
	{
		pointer -> setPositionY(sHHeaf + 200-17 - (materialRow - 1) * 60);
		back -> setScale(0.8f);
	}

	if(materialRow == 1)
	{
		if(materialCol % 6 == 0)
		{
			materialSetRow = 1;
			edit_set_work = MaterialSet;
		}
		else
		{
			pointer -> setPositionX(sWHeaf + 350+17 + (materialCol - 1) * 50);
		}
	}
	else
	{
		if(materialRow % 4 != 0)
		{
			if(materialCol % 5 == 0)
			{
				materialSetRow = 1;
				edit_set_work = MaterialSet;
			}
			else
			{
				pointer -> setPositionX(sWHeaf + 350+17 + (materialCol - 1) * 50);
			}
		}
	}

	if(chipHave == 0)
	{
		if(materialCol == 4 || materialCol == 5)
		{
			materialSetCol = 1;
		}
		else if(materialCol == 1)
		{
			materialSetCol = stageSize.x;
		}
	}
	else if(chipHave == 1)
	{
//		chip -> setPosition(pointer -> getPositionX()-17, pointer -> getPositionY()+17);
	}
	else if(chipHave == 2)
	{
		/*if(materialCol == 1)
		{
			player -> setPosition(pointer -> getPositionX()-17, pointer -> getPositionY()+34);
		}
		else if(materialCol == 2)
		{
			enemy -> setPosition(pointer -> getPositionX()-17, pointer -> getPositionY()+34);
		}
		else if(materialCol == 3)
		{
			door -> setPosition(pointer -> getPositionX()-21, pointer -> getPositionY()+34);
		}
		else if(materialCol == 4)
		{
			gimmick -> setPosition(pointer -> getPositionX()-17, pointer -> getPositionY()+34);
		}*/
	}
}

//'fÞ"z'u
void Edit::materialSet(void)
{
	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Z))
	{
//		chip -> setPosition(chip -> getPosition());
	}

	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Up))
	{
		materialSetRow--;
	}
	if (input -> getKeyboardState(LibInput::KeyBoardNumber::Key_Up))
	{
		counter++;
		if(counter >= COUNTER && counter % 5 == 1)
		{
			materialSetRow--;
		}
	}
	else if (input -> getKeyboardUpState(LibInput::KeyBoardNumber::Key_Up))
	{
		counter = 0;
	}

	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Down))
	{
		materialSetRow++;
	}
	if (input -> getKeyboardState(LibInput::KeyBoardNumber::Key_Down))
	{
		counter++;
		if(counter >= COUNTER && counter % 5 == 1)
		{
			materialSetRow++;
		}
	}
	else if (input -> getKeyboardUpState(LibInput::KeyBoardNumber::Key_Down))
	{
		counter = 0;
	}

	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Left))
	{
		materialSetCol--;
	}
	if (input -> getKeyboardState(LibInput::KeyBoardNumber::Key_Left))
	{
		counter++;
		if(counter >= COUNTER && counter % 5 == 1)
		{
			materialSetCol--;
		}
	}
	else if (input -> getKeyboardUpState(LibInput::KeyBoardNumber::Key_Left))
	{
		counter = 0;
	}

	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_Right))
	{
		materialSetCol++;
	}
	if (input -> getKeyboardState(LibInput::KeyBoardNumber::Key_Right))
	{
		counter++;
		if(counter >= COUNTER && counter % 5 == 1)
		{
			materialSetCol++;
		}
	}
	else if (input -> getKeyboardUpState(LibInput::KeyBoardNumber::Key_Right))
	{
		counter = 0;
	}

	chipDirection = LibBasicFunc::wrap(chipDirection, 0, 4);

	if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_D))
	{
		chipDirection--;

		if(chipDirection != -1)
		{
			chipNum -= 1;
		}
		else
		{
			chipNum += 3;
		}
	}
	else if (input -> getKeyboardDownState(LibInput::KeyBoardNumber::Key_F))
	{
		chipDirection++;

		if(chipDirection != 4)
		{
			chipNum += 1;
		}
		else
		{
			chipNum -= 3;
		}
	}

	if(chipHave == 1)
	{
//		chip -> setPosition(pointer -> getPositionX()-17, pointer -> getPositionY()+17);
	}
	else if(chipHave == 2)
	{
		/*if(chipState == 1)
		{
			player -> setPosition(pointer -> getPositionX()-17, pointer -> getPositionY()+34);
		}
		else if(chipState == 2)
		{
			enemy -> setPosition(pointer -> getPositionX()-17, pointer -> getPositionY()+34);
		}
		else if(chipState == 3)
		{
			door -> setPosition(pointer -> getPositionX()-18, pointer -> getPositionY()+34);
		}
		else if(chipState == 4)
		{
			gimmick -> setPosition(pointer -> getPositionX()-17, pointer -> getPositionY()+34);
		}*/
	}

	if(stageConfig -> getSizeNumber() == 0)
	{
		materialSetRow = CatGameLib::LibBasicFunc::wrap(materialSetRow, 0, 14);
		materialSetCol = CatGameLib::LibBasicFunc::wrap(materialSetCol, 0, 15);
	}
	else if(stageConfig -> getSizeNumber() == 1)
	{
		materialSetRow = CatGameLib::LibBasicFunc::wrap(materialSetRow, 0, 16);
		materialSetCol = CatGameLib::LibBasicFunc::wrap(materialSetCol, 0, 17);
	}
	else if(stageConfig -> getSizeNumber() == 2)
	{
		materialSetRow = CatGameLib::LibBasicFunc::wrap(materialSetRow, 0, 18);
		materialSetCol = CatGameLib::LibBasicFunc::wrap(materialSetCol, 0, 19);
	}

	if(stageConfig -> getSizeNumber() == 0)
	{
		if(materialSetRow % 14 == 0)
		{
			pointer -> setPositionY(sHHeaf + 35 * (materialSetRow - stageSize.y / 2));
		}
		else
		{
			pointer -> setPositionY(sHHeaf - 35 * (materialSetRow - stageSize.y / 2));
		}

		if(materialSetCol % 15 == 0)
		{
			materialRow = 1;
			chipHave = 0;
			chipDirection = 0;
			edit_set_work = MaterialSelect;
		}
		else
		{
			pointer -> setPositionX(sWHeaf - 170 + 35 * (materialSetCol - stageSize.y / 2));
		}
	}
	else if(stageConfig -> getSizeNumber() == 1)
	{
		if(materialSetRow % 16 == 0)
		{
			pointer -> setPositionY(sHHeaf + 35 * (materialSetRow - stageSize.y / 2));
		}
		else
		{
			pointer -> setPositionY(sHHeaf - 35 * (materialSetRow - stageSize.y / 2));
		}

		if(materialSetCol % 17 == 0)
		{
			materialRow = 1;
			chipHave = 0;
			chipDirection = 0;
			edit_set_work = MaterialSelect;
		}
		else
		{
			pointer -> setPositionX(sWHeaf - 170 + 35 * (materialSetCol - stageSize.y / 2));
		}
	}
	else if(stageConfig -> getSizeNumber() == 2)
	{
		if(materialSetRow % 18 == 0)
		{
			pointer -> setPositionY(sHHeaf + 35 * (materialSetRow - stageSize.y / 2));
		}
		else
		{
			pointer -> setPositionY(sHHeaf - 35 * (materialSetRow - stageSize.y / 2));
		}

		if(materialSetCol % 19 == 0)
		{
			materialRow = 1;
			chipHave = 0;
			chipDirection = 0;
			edit_set_work = MaterialSelect;
		}
		else
		{
			pointer -> setPositionX(sWHeaf - 170 + 35 * (materialSetCol - stageSize.y / 2));
		}
	}

	if(materialSetCol == 1)
	{
		materialCol = 5;
	}
	else if(materialSetCol == stageSize.x)
	{
		materialCol = 1;
	}
}

void Edit::editDraw(void)
{
	ResourceManager::getInstance() -> getSprite("floor") -> draw();
	books -> draw(anime_number);
	bgTextures[stageConfig -> getBgNumber()] -> draw();
	gridSize[stageConfig -> getSizeNumber()] -> draw();

	if(chipHave == 1)
	{
//		chip -> draw(chipNum);
	}
	else if(chipHave == 2)
	{
		/*if(chipState == 1)
		{
			player -> draw(0);
		}
		else if(chipState == 2)
		{
			enemy -> draw(0);
		}
		else if(chipState == 3)
		{
			door -> draw(0);
		}
		else if(chipState == 4)
		{
			gimmick -> draw(0);
		}*/
	}

	materialLogo -> draw();
	chipTable -> draw();

	chipCounter = 0;

	save -> draw();

	back -> draw();

	pointer -> draw();
}

void Edit::materialDraw(void)
{
	for(int i = 1; i <= 36; i += 4)
	{
		chipCounter = CatGameLib::LibBasicFunc::wrap(chipCounter, 0, 5);

		if(i <= 5 * 4)
		{
			materials[MaterialNum::Chip] -> setPosition(sWHeaf + 350 + chipCounter * 50, sHHeaf + 200);
		}
		else if(i > 5 * 4 && i <= 36)
		{
			materials[MaterialNum::Chip] -> setPosition(sWHeaf + 350 + chipCounter * 50, sHHeaf + 140);
		}
		chipCounter++;

		materials[MaterialNum::Chip] -> draw(i);
	}

	for(int i = 1; i < MaterialNum::MaterialCount; i++)
	{
		materials[i] -> draw(0);
	}
}

/*
void Edit::editChipSetDraw(void)
{
	materialLogo -> draw();
	chipTable -> draw();

	for(int i = 1; i <= 36; i += 4)
	{
		chipCounter = CatGameLib::LibBasicFunc::wrap(chipCounter, 0, 5);

		if(i <= 5 * 4)
		{
			chip -> setPosition(sWHeaf + 350 + chipCounter * 50, sHHeaf + 200);
		}
		else if(i > 5 * 4 && i <= 36)
		{
			chip -> setPosition(sWHeaf + 350 + chipCounter * 50, sHHeaf + 140);
		}
		chipCounter++;

		chip -> draw(i);
	}
	chipCounter = 0;

	ResourceManager::getInstance() -> getSprites("player") -> draw(0);
	ResourceManager::getInstance() -> getSprites("enemy") -> draw(0);
	ResourceManager::getInstance() -> getSprites("door") -> draw(0);
	ResourceManager::getInstance() -> getSprites("gimmick") -> draw(0);

	back -> draw();
}*/


text:
<%= polyglot.t('CheckExchanges') %>

      <%= polyglot.t('SendPayment') %>

      <%=
        polyglot.t('buyFlow.SendBTCtoAddress', {
          amount: '',
          recipient: ''
        })
      %>

        <input type="checkbox" class="textSize11px fieldItem thin" id="BuyWizardQRDetailsInput">
         <%= polyglot.t('AdditionalPaymentDataInfo') %>

       <%= polyglot.t('buyFlow.OpenAddress') %>
       <%= polyglot.t('buyFlow.RefreshPayment') %>

        <%= polyglot.t('buyFlow.paymentNote') %>

        <%= polyglot.t('transactions.BuyerPaidMessageHelp') %>

<%= polyglot.t('buyFlow.paymentSent') %>

    <% if(ob.user.refund_address === ""){ %>

          <%= polyglot.t('buyFlow.BitcoinWallet') %>

<%= polyglot.t('buyFlow.HaveWallet') %>

<%= polyglot.t('buyFlow.QuickSetup') %>

            <%= polyglot.t('No') %>

            <%= polyglot.t('Yes') %>

          <%= polyglot.t('buyFlow.CreateWallet') %>

                    Airbitz
                    <%= polyglot.t('walletProviders.WalletOnly') %>

<%= polyglot.t('walletProviders.AirbitzTagline') %>

                    Coinbase
                    <%= polyglot.t('walletProviders.ExchangeAndWallet') %>

<%= polyglot.t('walletProviders.CoinbaseTagline') %>

                    Samourai Wallet
                    <%= polyglot.t('walletProviders.WalletOnly') %>

<%= polyglot.t('walletProviders.SamouraiTagline') %>

                    RushWallet
                    <%= polyglot.t('walletProviders.WalletOnly') %>

<%= polyglot.t('walletProviders.RushWalletTagline') %>

                    Breadwallet
                    <%= polyglot.t('walletProviders.WalletOnly') %>

<%= polyglot.t('walletProviders.BreadwalletTagline') %>

                    Mycelium
                    <%= polyglot.t('walletProviders.WalletOnly') %>

<%= polyglot.t('walletProviders.MyceliumTagline') %>

                    Blockchain.info
                    <%= polyglot.t('walletProviders.ExchangeAndWallet') %>

<%= polyglot.t('walletProviders.BlockchaininfoTagline') %>

                    Coinkite
                    <%= polyglot.t('walletProviders.WalletOnly') %>

<%= polyglot.t('walletProviders.CoinkiteTagline') %>

                    BitGo
                    <%= polyglot.t('walletProviders.WalletOnly') %>

<%= polyglot.t('walletProviders.BitGoTagline') %>

            <%= polyglot.t('Back') %>

            <%= polyglot.t('IHaveAWalletNow') %>

    <% } %>

        <%= polyglot.t('PaymentType') %>

          <% if(ob.vendor_offer.listing.moderators && ob.vendor_offer.listing.moderators.length > 0){ %>
            <% if(ob.vendor_offer.listing.moderators.length != 1 || ob.vendor_offer.listing.moderators[0].guid != ob.user.guid){ %>

                  <input type="radio" name="radioPaymentType" class="marginTop4" id="buyWizardPaymentTypeModerated" />

                      <%= polyglot.t('buyFlow.ModeratedPayment') %>
                      <%= polyglot.t('Recommended') %>

                      <%= polyglot.t('buyFlow.ModeratedPaymentDescription') %>

<%= polyglot.t('Moderators') %>

<%= polyglot.t('buyFlow.DisputeFee') %> <span class="ion-help-circled fontSize12 custCol-text tooltip tooltip-left" data-tooltip="<%= polyglot.t('buyFlow.ModeratorFeeHelper') %>">

                    <% _.each(ob.vendor_offer.listing.moderators, function(moderator, i) { %>
                      <% if(moderator.guid != ob.user.guid){ %>
                        <% moderator.numFee = moderator.fee.replace(/[^\d.-]/g, ''); %>

                            <label for="buyWizardModeratorRadio<%= i %>" class="textOpacity1 clickable">

                                    <input type="radio" class="js-buyWizardModeratorRadio floatLeft" name="moderator" id="buyWizardModeratorRadio<%= i %>" value="<%= i %>"/>
                                    <label class="customRadioButtonModerator" for="buyWizardModeratorRadio<%= i %>">

                                  <div class="thumbnail thumbnail-large-slim floatLeft marginLeft7"
                                       <% if(moderator.avatar){ %>
                                       style="width: 32px; height: 32px; background-image: url(<%= ob.serverUrl %>get_image?hash=<%= moderator.avatar %>&guid=<%= moderator.guid %>), url(imgs/defaultUser.png);">
                                       <% } else { %>
                                       style="background-image: url(imgs/defaultUser.png); width: 32px; height: 32px;">
                                       <% } %>

                                      <div class="noOverflow width260px floatLeft marginLeft7  marginTop2 fontSize13"
                                           title="<% if(moderator.handle){ %><%= moderator.handle %><% } else { %><%= moderator.guid %><% } %>">
                                        <%= moderator.name %>

                                        <% if(moderator.handle){ %><%= moderator.handle %><% } else { %><%= moderator.guid %><% } %>

<%= ob.intlNumFormat(moderator.numFee) %>%

                      <% } %>
                    <% }); %>

          <% } %>
          <% } %>

                <input type="radio" name="radioPaymentType" class="marginTop4" id="buyWizardPaymentTypeDirect" />

<%= window.polyglot.t('buyFlow.DirectPayment') %>

                    <%= polyglot.t('buyFlow.DirectPaymentDescription') %>

                <input type="radio" class="fieldItem js-buyWizardModeratorRadio hide" name="moderator" id="buyWizardNoModerator" value="direct" <% if(ob.vendor_offer.listing.moderators && ob.vendor_offer.listing.moderators.length === 0){ %>checked<% } %> />

         <% if(ob.user.refund_address === ""){ %>

            <%= polyglot.t('Back') %>

        <% }else{ %>
          <%= polyglot.t('Cancel') %>
        <% } %>
        <a class="js-buyWizardModNext <% if(ob.vendor_offer.listing.moderators != null && ob.vendor_offer.listing.moderators.length > 0){ print('disabled'); } %> nextButton marginLeft80">
          <%= polyglot.t('Next') %>

        <%= polyglot.t('RefundAddress') %>

<%= polyglot.t('RefundAddressInfo') %>

          <form class="flexRow custCol-border borderTop" id="buyWizardBitcoinReturnForm">

              <input type="text" name="refund_address" class="fieldItem custCol-text" id="buyWizardBitcoinAddressInput"
                     placeholder="<%= polyglot.t('BitcoinReturnAddressPlaceholder') %>"
                     pattern="<%= config.bitcoinValidationRegex %>"
                     value="<%= ob.user.refund_address %>" required />
              <% if(config.testnet) { %>

                <span class="btn btn-txt custCol-secondary tooltip tooltip-left tooltip-box" data-tooltip="<%= polyglot.t('TestnetAddressHelp') %>">
                   <%= polyglot.t('TestnetAddress') %>

              <% } %>

          </form>

              <%= polyglot.t('buyFlow.CantFindAddress') %>

            <%= polyglot.t('buyFlow.NeedTempAddress') %>
            <span class="ion-help-circled fontSize12 custCol-text tooltip tooltip-left" data-tooltip="<%= polyglot.t('buyFlow.NeedTempAddressHelper') %>">

          <%= polyglot.t('Back') %>

          <%= polyglot.t('Next') %>

          <%= polyglot.t('ShipTo') %>
          <%= polyglot.t('NewAddress') %>

          <%= polyglot.t('ShipTo') %>

          <form id="buyWizardNewAddressForm" class="js-buyWizardNewAddress flex-border flexExpand custCol-primary hide">

                  <%= polyglot.t('ShipToName') %>

                <input type="text" name="new_ship_to_name" class="fieldItem custCol-text" id="buyWizardNameInput" required/>

                  <%= polyglot.t('ShipToStreet') %>

                <input type="text" name="new_ship_to_street" class="fieldItem custCol-text" id="buyWizardStreetInput" required/>

                  <%= polyglot.t('ShipToCity') %>

                <input type="text" name="new_ship_to_city" class="fieldItem custCol-text" id="buyWizardCityInput" required/>

                  <%= polyglot.t('ShipToState') %>

                <input type="text" name="new_ship_to_state" class="fieldItem custCol-text js-buyWizardStateInput" id="buyWizardStateInput" required/>

                  <%= polyglot.t('ShipToPostalCode') %>

                <input type="text" name="new_ship_to_street" class="fieldItem custCol-text js-buyWizardPostalInput" id="buyWizardPostalInput" required/>

                  <%= polyglot.t('ShipToCountry') %>

          </form>

          <%= polyglot.t('Back') %>

          <%= polyglot.t('Next') %>

        <%= polyglot.t('Cancel') %>
        <%= polyglot.t('Save') %>

          <%= polyglot.t('OrderDetails') %>

          <%= polyglot.t('OrderSummary') %>

      <div class="order-confirmation-image" style="background-image: url(<%= ob.serverUrl %>get_image?hash=<%= ob.vendor_offer.listing.item.image_hashes[0] %><%= ob.imageExtension %>), url(imgs/defaultBanner.png);">

          <%= polyglot.t('Back') %>

        <% if(ob.ownPage){ %>

          <%= polyglot.t('buyFlow.BuyOwnProductMsg') %>

        <% } else { %>

          <%= polyglot.t('buyFlow.PayForOrder') %>

        <% } %>
        <%= polyglot.t('PaymentPending') %>
        <%= polyglot.t('Close') %>


text:
import copy

from passtools import PassTools
from passtools.pt_pass import Pass
from passtools.pt_template import Template

# API User:
# STEP 1: Retrieve your API key from your Account view on the PassTools website
my_api_key = "your-key-goes-in-here"

# STEP 2:
# You'll always configure the api, providing your api key.
# This is required!
PassTools.configure(api_key = my_api_key)

# Let's create a new pass from a template.
# Start by retrieving a template using the same method used in Ex1_Templates.py
# This is a bit contrived, since you would probably know the ID of the template
# you wanted to use, but for this example we'll get the whole list and use the latest
list_response = Template.list()
template_header_list = list_response["templateHeaders"]
the_template_id = template_header_list[0]['id']

get_response = Template.get(the_template_id)

# Now create a new pass from the template.
test_pass = Pass.create(the_template_id, get_response['fieldsModel'])

print 25*"#"
print "New Pass at start"
print test_pass
print 25*"#"

# And let's update the "relevantDate" field in that pass
# Note that as of this writing, the RelevantDate argument is not format-validated
# so you _must_ ensure that the date you pass in confirms to ISO-8601
pass_fields = copy.deepcopy(test_pass["passFields"])
print 25*"#"
print "Start pass update..."
if "relevantDate" in pass_fields:
    pass_fields["relevantDate"]["value"] = "2012-01-01T12:00-08:00"

    # Call 'update', passing the modifications as input
    update_response = Pass.update(test_pass['id'], pass_fields)
    print update_response

    # At this point, you could retrieve the updated pass, download it, etc.
    updated_pass = Pass.get(test_pass['id'])

    print "Updated Pass..."
    print updated_pass
    print 25*"#"
    # The update will be returned; note that the ID is the same, the serial number is the same,
    # and the change to RelevantDate has been incorporated.

else:
    print "No relevantDate to update"


text:
package com.tle.web.sections.standard.dialog;

import com.tle.web.sections.SectionId;
import com.tle.web.sections.js.JSCallable;
import com.tle.web.sections.standard.dialog.renderer.DialogRenderer;
import com.tle.web.sections.standard.js.DelayedRenderer;

public interface Dialog extends SectionId, DelayedRenderer<DialogRenderer> {
  JSCallable getOpenFunction();

  JSCallable getCloseFunction();
}


text:
<CreateTagsResponse xmlns="http://ec2.amazonaws.com/doc/2012-03-01/">
  <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>
  <return>true</return>
</CreateTagsResponse>


text:
local PANEL = {}

function PANEL:Init()

	self.pnlCanvas:DockPadding( 2, 2, 2, 2 )

end

function PANEL:AddItem( item )

	item:Dock( TOP )
	DScrollPanel.AddItem( self, item )
	self:InvalidateLayout()

end

function PANEL:Add( name )

	local Category = vgui.Create( "DCollapsibleCategory", self )
	Category:SetLabel( name )
	Category:SetList( self )

	self:AddItem( Category )

	return Category

end

function PANEL:Paint( w, h )

	derma.SkinHook( "Paint", "CategoryList", self, w, h )
	return false

end

function PANEL:UnselectAll()

	for k, v in pairs( self:GetChildren() ) do

		if ( v.UnselectAll ) then
			v:UnselectAll()
		end

	end

end

function PANEL:GenerateExample( ClassName, PropertySheet, Width, Height )

	local ctrl = vgui.Create( ClassName )
	ctrl:SetSize( 300, 300 )

	local Cat = ctrl:Add( "Test category with text contents" )
	Cat:Add( "Item 1" )
	Cat:Add( "Item 2" )

	-- The contents can be any panel, even a DPanelList
	local Cat2 = ctrl:Add( "Test category with panel contents" )
	Cat2:SetTall( 100 )
	local Contents = vgui.Create( "DButton" )
	Contents:SetText( "This is the content of the category" )
	Cat2:SetContents( Contents )

	ctrl:InvalidateLayout( true )

	PropertySheet:AddSheet( ClassName, ctrl, nil, true, true )

end

derma.DefineControl( "DCategoryList", "", PANEL, "DScrollPanel" )


text:
import { TestBed, inject, async } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { HeaderComponent } from 'app/components/header/header.component';
import { AuthService } from 'app/services/auth.service';

describe('HeaderComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        NgbModule.forRoot(),
        HttpModule,
        RouterTestingModule,
      ],
      providers: [
      ],
      declarations: [
        HeaderComponent
      ],
    }).compileComponents();
  });

  it('should create the header', async(() => {
    inject([AuthService], () => {
      const fixture = TestBed.createComponent(HeaderComponent);
      const header = fixture.debugElement.componentInstance;
      expect(header).toBeTruthy();
    });
  }));
});


text:
package com.evolveum.midpoint.prism.impl.query;

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

import com.evolveum.midpoint.prism.PrismContainerValue;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.OrFilter;
import com.evolveum.midpoint.util.exception.SchemaException;

public class OrFilterImpl extends NaryLogicalFilterImpl implements OrFilter {

    public OrFilterImpl(List<ObjectFilter> condition) {
        super(condition);
    }

    public static OrFilter createOr(ObjectFilter... conditions){
        List<ObjectFilter> filters = new ArrayList<>();
        Collections.addAll(filters, conditions);
        return new OrFilterImpl(filters);
    }

    public static OrFilter createOr(List<ObjectFilter> conditions){
        return new OrFilterImpl(conditions);
    }

    @SuppressWarnings("CloneDoesntCallSuperClone")
    @Override
    public OrFilterImpl clone() {
        return new OrFilterImpl(getClonedConditions());
    }

    @Override
    public OrFilterImpl cloneEmpty() {
        return new OrFilterImpl(new ArrayList<>());
    }

    @Override
    protected String getDebugDumpOperationName() {
        return "OR";
    }

    @Override
    public boolean match(PrismContainerValue value, MatchingRuleRegistry matchingRuleRegistry) throws SchemaException {
        for (ObjectFilter filter : getConditions()){
            if (filter.match(value, matchingRuleRegistry)){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean equals(Object obj, boolean exact) {
        return super.equals(obj, exact) && obj instanceof OrFilter;
    }

}


text:
"""
    werkzeug.contrib.limiter
    ~~~~~~~~~~~~~~~~~~~~~~~~

    A middleware that limits incoming data.  This works around problems with
    Trac_ or Django_ because those directly stream into the memory.

    .. _Trac: http://trac.edgewall.org/
    .. _Django: http://www.djangoproject.com/

    :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from warnings import warn

from werkzeug import LimitedStream

class StreamLimitMiddleware(object):
    """Limits the input stream to a given number of bytes.  This is useful if
    you have a WSGI application that reads form data into memory (django for
    example) and you don't want users to harm the server by uploading tons of
    data.

    Default is 10MB
    """

    def __init__(self, app, maximum_size=1024 * 1024 * 10):
        self.app = app
        self.maximum_size = maximum_size

    def __call__(self, environ, start_response):
        limit = min(limit, int(environ.get('CONTENT_LENGTH') or 0))
        environ['wsgi.input'] = LimitedStream(environ['wsgi.input'], limit)
        return self.app(environ, start_response)


text:
Random Word Maker is (surprisingly) as its name implies:

> A random word maker

Specifically this random word maker aims to serve as an aid in the creative process when wanting to come up with a name for a team/product/business/etc.

To get a random word simply press the random button!

### Tech

This simple site was made using:

* [Twitter Bootstrap] - great UI boilerplate for modern web apps
* [Random word API] - The easiest way to get a random word

[Twitter Bootstrap]:http://twitter.github.com/bootstrap/
[Random word API]:http://randomword.setgetgo.com/


text:
from os import path as os_path
from re import compile as re_compile

cwd = re_compile(".*\/").search(os_path.realpath(__file__)).group(0)

parameters = {
       "port" : 10000,
       "sslport" : -1,
       "host" : "127.0.0.1",
#       "host" : "0.0.0.0",
       "keepsession" : True,
#       "keepsession" : False,
       "debug_host" : False,
#       "test" : cwd + "logs/",
       "log" : False,
       "tlog" : False,
       "cert" : cwd + "mica/mica.crt",
       "privkey" : False,
       "slaves" : False,
       "slave_port" : False,
       "scratch" : cwd + "mica/",
       "duplicate_logger" : False,
       "couch_adapter_type" : "AndroidMicaServerCouchbaseMobile",
       "transreset" : False,
       "transcheck" : False,
       "mobileinternet" : False,

       "main_server" : "readalien.com",
       "couch_server" : "db.readalien.com",
       "couch_proto" : "https",
       "couch_port" : "443",

       "trans_id" : False,
       "trans_secret" : False,

        # Only used during development by uncommenting
        # a hard-coded HTTP listener for debugging purposes.
        # couchdb listener is not enabled in the app store
       "local_database" : "mica",
#           "local_username" : "admin",
#           "local_password" : "devtest",
       "local_username" : False,
       "local_password" : False,
       "local_port" : 5984,
}


text:
package org.ugate.gui.view;

import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;

import org.ugate.gui.ControlBar;
import org.ugate.gui.ControlPane;
import org.ugate.gui.GuiUtil;
import org.ugate.gui.components.Gauge.IndicatorType;
import org.ugate.gui.components.UGateGaugeBox;
import org.ugate.resources.RS;
import org.ugate.resources.RS.KEY;
import org.ugate.service.entity.RemoteNodeType;
import org.ugate.service.entity.jpa.RemoteNode;

/**
 * Sensor/Gate control view
 */
public class AlarmThresholds extends ControlPane {

	/**
	 * Constructor
	 *
	 * @param controlBar the control bar
	 */
	public AlarmThresholds(final ControlBar controlBar) {
		super(controlBar);
		int ci = -1;
		int ri = -1;
		addThresholdChildren(++ci, ++ri);
		addDelayChildren(ci, ++ri);
	}

	protected void addThresholdChildren(final int columnIndex, final int rowIndex) {
		int ci = columnIndex;
		int ri = rowIndex;

		final String feet = RS.rbLabel(KEY.FEET);
		final Label sonarThresholdLabel = createLabel(KEY.SONAR_THRESHOLD, feet);
		final UGateGaugeBox<RemoteNode> sonarTripGauge = new UGateGaugeBox<>(
				controlBar.getRemoteNodePA(),
				RemoteNodeType.SONAR_DISTANCE_THRES_FEET,
				RemoteNodeType.SONAR_DISTANCE_THRES_INCHES,
				IndicatorType.NEEDLE, THRESHOLD_SIZE_SCALE, 1d,
				RemoteNodeType.SONAR_DISTANCE_THRES_FEET.getMin().intValue(), 0d, 180d,
				RemoteNodeType.SONAR_DISTANCE_THRES_FEET.getMax().intValue() - 1,
				3, FORMAT_SONAR, RS.IMG_RULER, GuiUtil.COLOR_SONAR);
		//sonarTripGauge.gauge.tickMarkLabelFillProperty.set(Color.WHITE);
		controlBar.addHelpTextTrigger(sonarTripGauge, RS.rbLabel(KEY.SONAR_THRESHOLD_DESC, feet));
		sonarTripGauge.gauge.setIntensity(80d, 15d, 5d);
		sonarTripGauge.setMaxWidth(200d);
		final Parent sonarCell = createCell(sonarThresholdLabel, sonarTripGauge);

		add(sonarCell, ci, ri);

		final Label mwThreshold = createLabel(KEY.MW_THRESHOLD, feet);
		final UGateGaugeBox<RemoteNode> mwTripGauge = new UGateGaugeBox<>(
				controlBar.getRemoteNodePA(),
				RemoteNodeType.MW_SPEED_THRES_CYCLES_PER_SEC, null,
				IndicatorType.NEEDLE, THRESHOLD_SIZE_SCALE, 1d,
				RemoteNodeType.MW_SPEED_THRES_CYCLES_PER_SEC.getMin().intValue(), 0d, 180d,
				RemoteNodeType.MW_SPEED_THRES_CYCLES_PER_SEC.getMax().intValue() - 1,
				0, FORMAT_MW, RS.IMG_SPEEDOMETER, GuiUtil.COLOR_MW);
		controlBar.addHelpTextTrigger(mwTripGauge, RS.rbLabel(KEY.MW_THRESHOLD_DESC, feet));
		final Parent mwCell = createCell(mwThreshold, mwTripGauge);
		add(mwCell, ++ci, ri);

		final Label laserThreshold = createLabel(KEY.LASER_THRESHOLD, RS.rbLabel(KEY.FEET), feet);
		final UGateGaugeBox<RemoteNode> laserTripGauge = new UGateGaugeBox<>(
				controlBar.getRemoteNodePA(),
				RemoteNodeType.LASER_DISTANCE_THRES_FEET,
				RemoteNodeType.LASER_DISTANCE_THRES_INCHES,
				IndicatorType.NEEDLE, THRESHOLD_SIZE_SCALE, 4d,
				RemoteNodeType.LASER_DISTANCE_THRES_FEET.getMin().intValue(), 0d, 180d,
				RemoteNodeType.LASER_DISTANCE_THRES_FEET.getMax().intValue(),
				3, FORMAT_LASER, RS.IMG_RULER, GuiUtil.COLOR_LASER);
		//laserTripGauge.gauge.tickMarkLabelFillProperty.set(Color.WHITE);
		controlBar.addHelpTextTrigger(laserTripGauge, RS.rbLabel(KEY.LASER_THRESHOLD_DESC, feet));
		laserTripGauge.gauge.setIntensity(100d, 0d, 0d);
		final Parent laserCell = createCell(laserThreshold, laserTripGauge);
		add(laserCell, ++ci, ri);
	}

	protected void addDelayChildren(final int columnIndex, final int rowIndex) {
		final VBox sp = new VBox();
		final Label sonarDelayLabel = createLabel(KEY.SONAR_ALARM_DELAY);
		final UGateGaugeBox<RemoteNode> sonarTripRateGauge = new UGateGaugeBox<>(
				controlBar.getRemoteNodePA(),
				RemoteNodeType.SONAR_DELAY_BTWN_TRIPS, null,
				IndicatorType.NEEDLE, DELAY_SIZE_SCALE, 1d,
				RemoteNodeType.SONAR_DELAY_BTWN_TRIPS.getMin().intValue(), 0d, 180d,
				RemoteNodeType.SONAR_DELAY_BTWN_TRIPS.getMax().intValue() + 1, 0,
				FORMAT_DELAY, RS.IMG_STOPWATCH, GuiUtil.COLOR_SONAR);
		controlBar.addHelpTextTrigger(sonarTripRateGauge, RS.rbLabel(KEY.SONAR_ALARM_DELAY_DESC));
		sonarTripRateGauge.gauge.setIntensity(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT);
		sp.getChildren().addAll(sonarDelayLabel, sonarTripRateGauge);

		final VBox pp = new VBox();
		final Label pirDelay = createLabel(KEY.PIR_ALARM_DELAY);
		final UGateGaugeBox<RemoteNode> pirTripRateGauge = new UGateGaugeBox<>(
				controlBar.getRemoteNodePA(),
				RemoteNodeType.PIR_DELAY_BTWN_TRIPS, null,
				IndicatorType.NEEDLE, DELAY_SIZE_SCALE, 1d,
				RemoteNodeType.PIR_DELAY_BTWN_TRIPS.getMin().intValue(), 0d, 180d,
				RemoteNodeType.PIR_DELAY_BTWN_TRIPS.getMax().intValue() + 1, 0,
				FORMAT_DELAY, RS.IMG_STOPWATCH, GuiUtil.COLOR_PIR);
		controlBar.addHelpTextTrigger(pirTripRateGauge, RS.rbLabel(KEY.PIR_ALARM_DELAY_DESC));
		pirTripRateGauge.gauge.setIntensity(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT);
		pp.getChildren().addAll(pirDelay, pirTripRateGauge);

		final VBox mp = new VBox();
		final Label mwDelay = createLabel(KEY.MW_ALARM_DELAY);
		final UGateGaugeBox<RemoteNode> mwTripRateGauge = new UGateGaugeBox<>(
				controlBar.getRemoteNodePA(),
				RemoteNodeType.MW_DELAY_BTWN_TRIPS, null, IndicatorType.NEEDLE,
				DELAY_SIZE_SCALE, 1d,
				RemoteNodeType.MW_DELAY_BTWN_TRIPS.getMin().intValue(), 0d, 180d,
				RemoteNodeType.MW_DELAY_BTWN_TRIPS.getMax().intValue() + 1, 0, FORMAT_DELAY,
				RS.IMG_STOPWATCH, GuiUtil.COLOR_MW);
		controlBar.addHelpTextTrigger(mwTripRateGauge, RS.rbLabel(KEY.MW_ALARM_DELAY_DESC));
		mwTripRateGauge.gauge.setIntensity(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT);
		mp.getChildren().addAll(mwDelay, mwTripRateGauge);

		final VBox lp = new VBox();
		final Label laserDelay = createLabel(KEY.LASER_ALARM_DELAY);
		final UGateGaugeBox<RemoteNode> laserTripRateGauge = new UGateGaugeBox<>(
				controlBar.getRemoteNodePA(),
				RemoteNodeType.LASER_DELAY_BTWN_TRIPS, null,
				IndicatorType.NEEDLE, DELAY_SIZE_SCALE, 1d,
				RemoteNodeType.LASER_DELAY_BTWN_TRIPS.getMin().intValue(), 0d, 180d,
				RemoteNodeType.LASER_DELAY_BTWN_TRIPS.getMax().intValue() + 1, 0,
				FORMAT_DELAY, RS.IMG_STOPWATCH, GuiUtil.COLOR_LASER);
		controlBar.addHelpTextTrigger(laserTripRateGauge, RS.rbLabel(KEY.LASER_ALARM_DELAY_DESC));
		laserTripRateGauge.gauge.setIntensity(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT);
		lp.getChildren().addAll(laserDelay, laserTripRateGauge);

		final HBox p = new HBox(CHILD_PADDING);
		p.setAlignment(Pos.CENTER);
		p.getChildren().addAll(sp, pp, mp, lp);
		final Parent cell = createCell(p);
		add(cell, columnIndex, rowIndex, 3, 1);
	}
}


text:
import six
import json

from django.conf import settings
from django import forms
from django.forms import widgets
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe

class LocationWidget(widgets.TextInput):
    def __init__(self, **kwargs):
        attrs = kwargs.pop('attrs', None)

        self.options = dict(settings.LOCATION_FIELD)
        self.options['field_options'] = {
            'based_fields': kwargs.pop('based_fields'),
        }

        super(LocationWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        if value is not None:
            try:
                if isinstance(value, six.string_types):
                    lat, lng = value.split(',')
                else:
                    lng = value.x
                    lat = value.y

                value = '%s,%s' % (
                    float(lat),
                    float(lng),
                )
            except ValueError:
                value = ''
        else:
            value = ''

        if '-' not in name:
            prefix = ''
        else:
            prefix = name[:name.rindex('-') + 1]

        self.options['field_options']['prefix'] = prefix

        attrs = attrs or {}
        attrs['data-location-field-options'] = json.dumps(self.options)

        text_input = super(LocationWidget, self).render(name, value, attrs)

        return render_to_string('location_field/map_widget.html', {
            'field_name': name,
            'field_input': mark_safe(text_input)
        })

    @property
    def media(self):
        return forms.Media(**settings.LOCATION_FIELD['resources.media'])


text:
package org.javers.core.json.typeadapter.util;

import org.javers.core.json.BasicStringTypeAdapter;

import java.sql.Time;

/**
 * Serializes java.sql.Time to JSON String using ISO util format yyyy-MM-dd'T'HH:mm:ss.SSS
 *
 * @author bartosz walacik
 */
class JavaSqlTimeTypeAdapter extends BasicStringTypeAdapter<Time> {

    @Override
    public String serialize(Time sourceValue) {
        return UtilTypeCoreAdapters.serialize(sourceValue);
    }

    @Override
    public Time deserialize(String serializedValue) {
        java.util.Date date =  UtilTypeCoreAdapters.deserializeToUtilDate(serializedValue);
        return new Time(date.getTime());
    }

    @Override
    public Class getValueType() {
        return Time.class;
    }
}


text:
#ifndef SimTK_SimTKCOMMON_PARALLEL_WORK_QUEUE_H_
#define SimTK_SimTKCOMMON_PARALLEL_WORK_QUEUE_H_

#include "ParallelExecutor.h"
#include "PrivateImplementation.h"

namespace SimTK {

class ParallelWorkQueue;
class ParallelWorkQueueImpl;

// We only want the template instantiation to occur once. This symbol is defined in the SimTK core
// compilation unit that defines the ParallelWorkQueue class but should not be defined any other time.
#ifndef SimTK_SIMTKCOMMON_DEFINING_PARALLEL_WORK_QUEUE
    extern template class PIMPLHandle<ParallelWorkQueue, ParallelWorkQueueImpl>;
#endif

/**
 * This class is used for performing multithreaded computations.\ It maintains a queue of tasks to be
 * executed, and a pool of threads for executing them.  To use it, define one or more subclasses of
 * ParallelWorkQueue::Task that performs computations.  Then create a ParallelWorkQueue and add Tasks
 * to it:
 *
 * <pre>
 * ParallelWorkQueue queue(20);
 * queue.addTask(new MyTask());
 * </pre>
 *
 * Each Task's execute() method will be called, and then the Task will be deleted.  The invocations are
 * done in parallel on multiple threads, so you cannot make any assumptions about what order they will occur in
 * or which ones will happen at the same time.
 *
 * The threads are created in the ParallelWorkQueue's constructor and remain active until it is deleted.
 * This means that creating a ParallelWorkQueue is a somewhat expensive operation, but it may then be
 * used repeatedly for executing various calculations.  By default, the number of threads is chosen
 * to be equal to the number of available processor cores.  You can optionally specify a different number
 * of threads to create.  For example, using more threads than processors can sometimes lead to better
 * processor utilitization.  Alternatively, if only four Tasks will be executed, you might specify
 * min(4, ParallelExecutor::getNumProcessors()) to avoid creating extra threads that will never
 * have any work to do.
 */

class SimTK_SimTKCOMMON_EXPORT ParallelWorkQueue : public PIMPLHandle<ParallelWorkQueue, ParallelWorkQueueImpl> {
public:
    class Task;
    /**
     * Construct a ParallelWorkQueue.
     *
     * @param queueSize  the maximum number of Tasks that can be in the queue waiting to start executing at any time
     * @param numThreads the number of threads to create.  By default, this is set equal to the number of processors.
     */
    explicit ParallelWorkQueue(int queueSize, int numThreads = ParallelExecutor::getNumProcessors());
    /**
     * Add a Task to the queue.  If the queue is currently full, this method will block until space is freed up in
     * the queue by the worker threads.  The queue assumes ownership of the Task object and deletes it once it has
     * finished executing.
     *
     * @param task      the Task to add to the queue
     */
    void addTask(Task* task);
    /**
     * Block until all Tasks that have been added to the queue finish executing.
     */
    void flush();
};

/**
 * Concrete subclasses of this abstract class represent tasks that can be executed by a ParallelWorkQueue.
 */

class ParallelWorkQueue::Task {
public:
    virtual ~Task() {
    }
    /**
     * This method defines the task to be performed.  At some point after the Task is added to a
     * ParallelWorkQueue, this method will be called by one of the worker threads.
     */
    virtual void execute() = 0;
};

} // namespace SimTK

#endif // SimTK_SimTKCOMMON_PARALLEL_WORK_QUEUE_H_


text:
package org.apache.camel.component.zookeeper;

import java.util.concurrent.CountDownLatch;

import org.apache.camel.RuntimeCamelException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ConnectionHolder watches for Connection based events from
 * {@link ZooKeeper} and can be used to block until a connection has been
 * established.
 */
public class ConnectionHolder implements Watcher {
    private static final Logger LOG = LoggerFactory.getLogger(ConnectionHolder.class);

    private CountDownLatch connectionLatch = new CountDownLatch(1);

    private ZooKeeperConfiguration configuration;

    private ZooKeeper zookeeper;

    public ConnectionHolder(ZooKeeperConfiguration configuration) {
        this.configuration = configuration;
    }

    public ZooKeeper getZooKeeper() {
        if (zookeeper != null) {
            return zookeeper;
        }
        if (configuration.getConnectString() == null) {
            throw new RuntimeCamelException("Cannot create ZooKeeper connection as connection string is null. Have servers been configured?");
        }
        try {
            zookeeper = new ZooKeeper(configuration.getConnectString(), configuration.getTimeout(), this);
        } catch (Exception e) {
            throw RuntimeCamelException.wrapRuntimeCamelException(e);
        }
        awaitConnection();
        return zookeeper;
    }

    public boolean isConnected() {
        return connectionLatch.getCount() == 0;
    }

    public void awaitConnection() {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Awaiting Connection event from Zookeeper cluster {}", configuration.getConnectString());
        }
        try {
            connectionLatch.await();
        } catch (InterruptedException e) {
            throw RuntimeCamelException.wrapRuntimeCamelException(e);
        }
    }

    @Override
    public void process(WatchedEvent event) {
        if (event.getState() == KeeperState.SyncConnected) {
            connectionLatch.countDown();
        }
        connectionLatch.countDown();
    }

    public void closeConnection() {
        try {
            if (zookeeper != null) {
                zookeeper.close();
                zookeeper = null;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Shutting down connection to Zookeeper cluster {}", configuration.getConnectString());
            }
        } catch (InterruptedException e) {
            LOG.warn("Error closing zookeeper connection " + configuration.getConnectString() + ". This exception will be ignored.", e);
        }
    }
}