text:
package org.apache.camel.converter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Properties;
import java.util.stream.Stream;

import org.apache.camel.Converter;
import org.apache.camel.Exchange;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.support.InputStreamIterator;
import org.apache.camel.util.IOHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Some core java.io based Type Converters
 */
@Converter(generateBulkLoader = true)
public final class IOConverter {

    private static final Logger LOG = LoggerFactory.getLogger(IOConverter.class);

    /**
     * Utility classes should not have a public constructor.
     */
    private IOConverter() {
    }

    @Converter(order = 1)
    public static InputStream toInputStream(Stream stream, Exchange exchange) {
        Iterator it = stream.iterator();
        return new InputStreamIterator(exchange.getContext().getTypeConverter(), it);
    }

    @Converter(order = 2)
    public static InputStream toInputStream(URL url) throws IOException {
        return IOHelper.buffered(url.openStream());
    }

    @Converter(order = 3)
    public static InputStream toInputStream(File file) throws IOException {
        return IOHelper.buffered(new FileInputStream(file));
    }

    @Converter(order = 4)
    public static BufferedReader toReader(File file, Exchange exchange) throws IOException {
        return IOHelper.toReader(file, ExchangeHelper.getCharsetName(exchange));
    }

    @Converter(order = 5)
    public static File toFile(String name) {
        return new File(name);
    }

    @Converter(order = 6)
    public static OutputStream toOutputStream(File file) throws FileNotFoundException {
        return IOHelper.buffered(new FileOutputStream(file));
    }

    @Converter(order = 7)
    public static BufferedWriter toWriter(File file, Exchange exchange) throws IOException {
        FileOutputStream os = new FileOutputStream(file, false);
        return IOHelper.toWriter(os, ExchangeHelper.getCharsetName(exchange));
    }

    @Converter(order = 8)
    public static Reader toReader(InputStream in, Exchange exchange) throws IOException {
        return IOHelper.buffered(new InputStreamReader(in, ExchangeHelper.getCharsetName(exchange)));
    }

    @Converter(order = 9)
    public static Reader toReader(byte[] data, Exchange exchange) throws IOException {
        return toReader(new ByteArrayInputStream(data), exchange);
    }

    @Converter(order = 10)
    public static Writer toWriter(OutputStream out, Exchange exchange) throws IOException {
        return IOHelper.buffered(new OutputStreamWriter(out, ExchangeHelper.getCharsetName(exchange)));
    }

    @Converter(order = 11)
    public static Reader toReader(String text) {
        // no buffering required as the complete string input is already passed
        // over as a whole
        return new StringReader(text);
    }

    @Converter(order = 12)
    public static InputStream toInputStream(String text, Exchange exchange) throws IOException {
        return toInputStream(text.getBytes(ExchangeHelper.getCharsetName(exchange)));
    }

    @Converter(order = 13)
    public static InputStream toInputStream(StringBuffer buffer, Exchange exchange) throws IOException {
        return toInputStream(buffer.toString(), exchange);
    }

    @Converter(order = 14)
    public static InputStream toInputStream(StringBuilder builder, Exchange exchange) throws IOException {
        return toInputStream(builder.toString(), exchange);
    }

    @Converter(order = 15)
    public static InputStream toInputStream(BufferedReader buffer, Exchange exchange) throws IOException {
        return toInputStream(toString(buffer), exchange);
    }

    @Converter(order = 16)
    public static String toString(byte[] data, Exchange exchange) throws IOException {
        return new String(data, ExchangeHelper.getCharsetName(exchange));
    }

    @Converter(order = 17)
    public static String toString(File file, Exchange exchange) throws IOException {
        return toString(toReader(file, exchange));
    }

    @Converter(order = 18)
    public static byte[] toByteArray(File file) throws IOException {
        InputStream is = toInputStream(file);
        try {
            return toBytes(is);
        } finally {
            IOHelper.close(is, "file", LOG);
        }
    }

    @Converter(order = 19)
    public static byte[] toByteArray(BufferedReader reader, Exchange exchange) throws IOException {
        String s = toString(reader);
        return toByteArray(s, exchange);
    }

    @Converter(order = 20)
    public static String toString(URL url, Exchange exchange) throws IOException {
        InputStream is = toInputStream(url);
        try {
            return toString(is, exchange);
        } finally {
            IOHelper.close(is, "url", LOG);
        }
    }

    @Converter(order = 21)
    public static String toString(BufferedReader reader) throws IOException {
        return IOHelper.toString(reader);
    }

    @Converter(order = 22)
    public static String toString(Reader reader) throws IOException {
        return IOHelper.toString(reader);
    }

    @Converter(order = 23)
    public static byte[] toByteArray(Reader reader, Exchange exchange) throws IOException {
        return toByteArray(IOHelper.buffered(reader), exchange);
    }

    @Converter(order = 24)
    public static byte[] toByteArray(String value, Exchange exchange) throws IOException {
        return value.getBytes(ExchangeHelper.getCharsetName(exchange));
    }

    @Converter(order = 25)
    public static String toString(InputStream in, Exchange exchange) throws IOException {
        return toString(toReader(in, exchange));
    }

    @Converter(order = 26)
    public static InputStream toInputStream(byte[] data) {
        // no buffering required as the complete byte input is already passed
        // over as a whole
        return new ByteArrayInputStream(data);
    }

    @Converter(order = 27)
    public static ObjectOutput toObjectOutput(OutputStream stream) throws IOException {
        if (stream instanceof ObjectOutput) {
            return (ObjectOutput) stream;
        } else {
            return new ObjectOutputStream(IOHelper.buffered(stream));
        }
    }

    @Converter(order = 28)
    public static ObjectInput toObjectInput(final InputStream stream, final Exchange exchange) throws IOException {
        if (stream instanceof ObjectInput) {
            return (ObjectInput) stream;
        } else {
            return new ObjectInputStream(IOHelper.buffered(stream)) {
                @Override
                protected Class<?> resolveClass(ObjectStreamClass objectStreamClass)
                        throws IOException, ClassNotFoundException {
                    // need to let Camel be able to resolve class using ClassResolver SPI, to let class loading
                    // work in OSGi and other containers
                    Class<?> answer = null;
                    String name = objectStreamClass.getName();
                    if (exchange != null) {
                        LOG.trace("Loading class {} using Camel ClassResolver", name);
                        answer = exchange.getContext().getClassResolver().resolveClass(name);
                    }
                    if (answer == null) {
                        LOG.trace("Loading class {} using JDK default implementation", name);
                        answer = super.resolveClass(objectStreamClass);
                    }
                    return answer;
                }
            };
        }
    }

    @Converter(order = 29)
    public static byte[] toBytes(InputStream stream) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOHelper.copy(IOHelper.buffered(stream), bos);

        // no need to close the ByteArrayOutputStream as it's close()
        // implementation is noop
        return bos.toByteArray();
    }

    @Converter(order = 30)
    public static byte[] toByteArray(ByteArrayOutputStream os) {
        return os.toByteArray();
    }

    @Converter(order = 31)
    public static ByteBuffer covertToByteBuffer(InputStream is) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        IOHelper.copyAndCloseInput(is, os);
        return ByteBuffer.wrap(os.toByteArray());
    }

    @Converter(order = 32)
    public static String toString(ByteArrayOutputStream os, Exchange exchange) throws IOException {
        return os.toString(ExchangeHelper.getCharsetName(exchange));
    }

    @Converter(order = 33)
    public static InputStream toInputStream(ByteArrayOutputStream os) {
        // no buffering required as the complete byte array input is already
        // passed over as a whole
        return new ByteArrayInputStream(os.toByteArray());
    }

    @Converter(order = 34)
    public static Properties toProperties(File file) throws IOException {
        return toProperties(new FileInputStream(file));
    }

    @Converter(order = 35)
    public static Properties toProperties(InputStream is) throws IOException {
        Properties prop = new Properties();
        try {
            prop.load(is);
        } finally {
            IOHelper.close(is);
        }
        return prop;
    }

    @Converter(order = 36)
    public static Properties toProperties(Reader reader) throws IOException {
        Properties prop = new Properties();
        try {
            prop.load(reader);
        } finally {
            IOHelper.close(reader);
        }
        return prop;
    }

}


text:
<iterator-tree description="main query">
  <SequentialIterator>
    <CtxVarDeclareIterator varid="4" varname="seq">
      <FnDocIterator>
        <SingletonIterator value="xs:string(person_events.xml)"/>
      </FnDocIterator>
    </CtxVarDeclareIterator>
    <ElementIterator>
      <SingletonIterator value="xs:QName(,,result)"/>
      <EnclosedIterator attr_cont="false">
        <TupleStreamIterator>
          <GroupByIterator>
            <LetIterator>
              <LetVariable name="person" materialize="true"/>
              <WindowIterator>
                <WindowVariable name="w">
                  <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,event)" typename="*" nill-allowed="false">
                    <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,stream)" typename="*" nill-allowed="false">
                      <CtxVarIterator varid="4" varname="seq" varkind="global"/>
                    </ChildAxisIterator>
                  </ChildAxisIterator>
                </WindowVariable>
                <WinCondVariable name="start-CurrentIn"/>
                <WinCondVariable name="start-CurrentInCurrentOut"/>
                <FnBooleanIterator>
                  <TypedValueCompareIterator_STRING>
                    <PromoteIterator type="xs:anyAtomicType">
                      <FnDataIterator>
                        <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,direction)" typename="*" nill-allowed="false">
                          <ForVarIterator varname="s"/>
                        </ChildAxisIterator>
                      </FnDataIterator>
                    </PromoteIterator>
                    <SingletonIterator value="xs:string(in)"/>
                  </TypedValueCompareIterator_STRING>
                </FnBooleanIterator>
                <WinCondVariable name="end-CurrentIn"/>
                <WinCondVariable name="end-CurrentInCurrentOut"/>
                <AndIterator>
                  <TypedValueCompareIterator_STRING>
                    <PromoteIterator type="xs:anyAtomicType">
                      <FnDataIterator>
                        <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,person)" typename="*" nill-allowed="false">
                          <ForVarIterator varname="s"/>
                        </ChildAxisIterator>
                      </FnDataIterator>
                    </PromoteIterator>
                    <PromoteIterator type="xs:anyAtomicType">
                      <FnDataIterator>
                        <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,person)" typename="*" nill-allowed="false">
                          <ForVarIterator varname="e"/>
                        </ChildAxisIterator>
                      </FnDataIterator>
                    </PromoteIterator>
                  </TypedValueCompareIterator_STRING>
                  <TypedValueCompareIterator_STRING>
                    <PromoteIterator type="xs:anyAtomicType">
                      <FnDataIterator>
                        <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,direction)" typename="*" nill-allowed="false">
                          <ForVarIterator varname="e"/>
                        </ChildAxisIterator>
                      </FnDataIterator>
                    </PromoteIterator>
                    <SingletonIterator value="xs:string(out)"/>
                  </TypedValueCompareIterator_STRING>
                </AndIterator>
                <TupleSourceIterator/>
              </WindowIterator>
              <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,person)" typename="*" nill-allowed="false">
                <ForVarIterator varname="s"/>
              </ChildAxisIterator>
            </LetIterator>
            <Spec>
              <TreatIterator quant="?">
                <FnDataIterator>
                  <LetVarIterator varname="person"/>
                </FnDataIterator>
              </TreatIterator>
              <GroupVariable/>
            </Spec>
            <Spec>
              <LetVarIterator varname="person"/>
              <NonGroupVariable/>
            </Spec>
            <Spec>
              <GenericArithIterator_SubtractOperation>
                <CastIterator type="xs:dateTime">
                  <FnDataIterator>
                    <AttributeAxisIterator test-kind="match_name_test" qname="xs:QName(,,time)" typename="*" nill-allowed="false">
                      <ForVarIterator varname="e"/>
                    </AttributeAxisIterator>
                  </FnDataIterator>
                </CastIterator>
                <CastIterator type="xs:dateTime">
                  <FnDataIterator>
                    <AttributeAxisIterator test-kind="match_name_test" qname="xs:QName(,,time)" typename="*" nill-allowed="false">
                      <ForVarIterator varname="s"/>
                    </AttributeAxisIterator>
                  </FnDataIterator>
                </CastIterator>
              </GenericArithIterator_SubtractOperation>
              <NonGroupVariable/>
            </Spec>
          </GroupByIterator>
          <ElementIterator>
            <SingletonIterator value="xs:QName(,,working-time)"/>
            <FnConcatIterator>
              <EnclosedIterator attr_cont="false">
                <LetVarIterator varname="person" targetPos="1"/>
              </EnclosedIterator>
              <ElementIterator>
                <SingletonIterator value="xs:QName(,,time)"/>
                <EnclosedIterator attr_cont="false">
                  <FnSumIterator>
                    <LetVarIterator varname="workingTime"/>
                  </FnSumIterator>
                </EnclosedIterator>
              </ElementIterator>
            </FnConcatIterator>
          </ElementIterator>
        </TupleStreamIterator>
      </EnclosedIterator>
    </ElementIterator>
  </SequentialIterator>
</iterator-tree>

redpajama_set_name: RedPajamaGithub


text:
 <head>
        <meta charset=utf-8>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Register</title>
        <!-- Load Roboto font -->
        <link href='http://fonts.googleapis.com/css?family=Roboto:400,300,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
        <!-- Load css styles -->
        <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
        <link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.css" />
        <link rel="stylesheet" type="text/css" href="css/stylemain_register.css" />
        <link rel="stylesheet" type="text/css" href="css/pluton.css" />
        <link rel="stylesheet" type="text/css" href="css/style1_register.css" />
        <!--[if IE 7]>
            <link rel="stylesheet" type="text/css" href="css/pluton-ie7.css" />
        <![endif]-->
        <link rel="stylesheet" type="text/css" href="css/jquery.cslider_register.css" />
        <link rel="stylesheet" type="text/css" href="css/jquery.bxslider.css" />
        <link rel="stylesheet" type="text/css" href="css/animate.css" />
        <!-- Fav and touch icons -->
        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144.png">
        <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114.png">
        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/apple-touch-icon-72.png">
        <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57.png">
        <link rel="shortcut icon" href="images/ico/favicon.ico">
    </head>


text:
namespace Sass {

  union Sass_Value* ast_node_to_sass_value (const Expression* val);
  Value* sass_value_to_ast_node (Memory_Manager& mem, const union Sass_Value* val);

}
#endif


text:
import fetch from './fetch'
import util from 'utils'
import _ from 'lodash'
import querystring from 'querystring'

export default function fetchAPI (api, body, rest, multipartFormData = true) {
  let { url, method } = api
  let config = {
    headers: {
      Accept: 'application/json',
      'X-Requested-With': 'XMLHttpRequest'
    },
    credentials: 'include',
    method: method
  }
  if (_.isFunction(url)) {
    let dept = util.getConfig(location.pathname).dept
    url = url(dept)
  }
  if (method === 'GET') {
    if (body) {
      if (rest) {
        url = url + `${body}`
      } else {
        // 增加对象格式的兼容 by jican@bytedance.com
        let params = _.isPlainObject(body) ? querystring.stringify(body) : body
        url = url + `?${params}`
      }
    }
  } else {
    if (multipartFormData) {
      const formData = new FormData()
      for (let name in body) {
        // stringify object by jican@bytedance.com
        let value = _.isObjectLike(body[name]) ? JSON.stringify(body[name]) : body[name]
        formData.append(name, value)
      }
      config.body = formData
    } else {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.body = querystring.stringify(body)
    }
  }
  return fetch.request(url, config)
}


text:
package org.springframework.expression.spel;

import org.springframework.expression.ParseException;
import org.springframework.lang.Nullable;

/**
 * Root exception for Spring EL related exceptions. Rather than holding a hard coded
 * string indicating the problem, it records a message key and the inserts for the
 * message. See {@link SpelMessage} for the list of all possible messages that can occur.
 *
 * @author Andy Clement
 * @author Juergen Hoeller
 * @since 3.0
 */
@SuppressWarnings("serial")
public class SpelParseException extends ParseException {

	private final SpelMessage message;

	private final Object[] inserts;

	public SpelParseException(@Nullable String expressionString, int position, SpelMessage message, Object... inserts) {
		super(expressionString, position, message.formatMessage(inserts));
		this.message = message;
		this.inserts = inserts;
	}

	public SpelParseException(int position, SpelMessage message, Object... inserts) {
		super(position, message.formatMessage(inserts));
		this.message = message;
		this.inserts = inserts;
	}

	public SpelParseException(int position, Throwable cause, SpelMessage message, Object... inserts) {
		super(position, message.formatMessage(inserts), cause);
		this.message = message;
		this.inserts = inserts;
	}

	/**
	 * Return the message code.
	 */
	public SpelMessage getMessageCode() {
		return this.message;
	}

	/**
	 * Return the message inserts.
	 */
	public Object[] getInserts() {
		return this.inserts;
	}

}


text:
//  (C) Copyright Edward Diener 2011-2015
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#if !defined(BOOST_VMD_GET_TYPE_HPP)
#define BOOST_VMD_GET_TYPE_HPP

#include <boost/vmd/detail/setup.hpp>

#if BOOST_PP_VARIADICS

#include <boost/vmd/detail/sequence_type.hpp>

/*

  The succeeding comments in this file are in doxygen format.

*/

/** \file
*/

/** \def BOOST_VMD_GET_TYPE(...)

    \brief Returns the type of a sequence as a VMD type.

    ...       = variadic parameters.

    The first variadic parameter is required and is the sequence whose type we are getting.

    The optional variadic parameters are return type parameters.

    The macro returns the type of a sequence as a VMD type. The type of an empty sequence
    is always BOOST_VMD_TYPE_EMPTY and the type of a multi-element is always
    BOOST_VMD_TYPE_SEQUENCE. The type of a single-element sequence is the
    type of that single element.

    The type returned can be modified by specifying an optional return type parameter.

    If BOOST_VMD_RETURN_TYPE, the default, is specified the specific type of the element
    is returned.

    If BOOST_VMD_RETURN_TYPE_ARRAY is specified
    an array type is returned if the element is an array, else a tuple
    type is returned if the element is a tuple, else the actual type
    is returned for non-tuple data.

    If BOOST_VMD_RETURN_TYPE_LIST is specified
    a list type is returned if the element is a list, else a tuple
    type is returned if the element is a tuple, else the actual type
    is returned for non-tuple data.

    If BOOST_VMD_RETURN_TYPE_TUPLE is specified
    a tuple type is returned for all tuple-like data, else the actual type
    is returned for non-tuple data.

    If BOOST_VMD_RETURN_NO_TYPE is specified it is ignored since the macro
    always returns the type of the sequence.

    If more than one return type optional parameter is specified the last
    one specified determines the return type.

    returns = the type of the sequence as a VMD type.

*/

#define BOOST_VMD_GET_TYPE(...) \
    BOOST_VMD_DETAIL_SEQUENCE_TYPE(__VA_ARGS__) \
/**/

/** \def BOOST_VMD_GET_TYPE_D(d,...)

    \brief Returns the type of a sequence as a VMD type. Re-entrant version.

    d         = The next available BOOST_PP_WHILE iteration.
    ...       = variadic parameters.

    The first variadic parameter is required and is the sequence whose type we are getting.

    The optional variadic parameters are return type parameters.

    The macro returns the type of a sequence as a VMD type. The type of an empty sequence
    is always BOOST_VMD_TYPE_EMPTY and the type of a multi-element is always
    BOOST_VMD_TYPE_SEQUENCE. The type of a single-element sequence is the
    type of that single element.

    The type returned can be modified by specifying an optional return type parameter.

    If BOOST_VMD_RETURN_TYPE, the default, is specified the specific type of the element
    is returned.

    If BOOST_VMD_RETURN_TYPE_ARRAY is specified
    an array type is returned if the element is an array, else a tuple
    type is returned if the element is a tuple, else the actual type
    is returned for non-tuple data.

    If BOOST_VMD_RETURN_TYPE_LIST is specified
    a list type is returned if the element is a list, else a tuple
    type is returned if the element is a tuple, else the actual type
    is returned for non-tuple data.

    If BOOST_VMD_RETURN_TYPE_TUPLE is specified
    a tuple type is returned for all tuple-like data, else the actual type
    is returned for non-tuple data.

    If BOOST_VMD_RETURN_NO_TYPE is specified it is ignored since the macro
    always returns the type of the sequence.

    If more than one return type optional parameter is specified the last
    one specified determines the return type.

    returns = the type of the sequence as a VMD type.

*/

#define BOOST_VMD_GET_TYPE_D(d,...) \
    BOOST_VMD_DETAIL_SEQUENCE_TYPE_D(d,__VA_ARGS__) \
/**/

#endif /* BOOST_PP_VARIADICS */
#endif /* BOOST_VMD_GET_TYPE_HPP */


text:
package com.minkov.demos.mvp.PersonDetails;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.minkov.demos.mvp.base.BaseDrawerActivity;
import com.minkov.demos.mvp.R;

import javax.inject.Inject;

/**
 * Implementation of {@link com.minkov.demos.mvp.PersonDetails.PersonDetailsContacts.View}
 */
public class PersonDetailsActivity extends BaseDrawerActivity {
    /**
     * Value for setting values in intents
     */
    public static final String EXTRA_PERSON_KEY = "EXTRA_PERSON_ID";

    @SuppressWarnings("CheckStyle")
    @Inject
    PersonDetailsContacts.Presenter mPresenter;

    @SuppressWarnings("CheckStyle")
    PersonDetailsFragment mView;

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

        String id = getIntent().getStringExtra(EXTRA_PERSON_KEY);

        mView = PersonDetailsFragment.newInstance();
        mPresenter.setPersonId(id);
        mView.setPresenter(mPresenter);

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame_content, mView)
                .commit();
    }

    @Override
    protected Toolbar getToolbar() {
        return findViewById(R.id.toolbar);
    }
}


text:
from contextlib import contextmanager

import os
import re
import pickle
import tempfile

# global settings
# -----------------------------------------------------------------------------
class Config(object):
    # main paper information repo file
    db_path = 'db.p'
    # intermediate processing folders
    pdf_dir = os.path.join('data', 'pdf')
    txt_dir = os.path.join('data', 'txt')
    thumbs_dir = os.path.join('static', 'thumbs')
    # intermediate pickles
    tfidf_path = 'tfidf.p'
    meta_path = 'tfidf_meta.p'
    sim_path = 'sim_dict.p'
    user_sim_path = 'user_sim.p'
    # sql database file
    db_serve_path = 'db2.p' # an enriched db.p with various preprocessing info
    database_path = 'as.db'
    serve_cache_path = 'serve_cache.p'

    beg_for_hosting_money = 1 # do we beg the active users randomly for money? 0 = no.
    banned_path = 'banned.txt' # for twitter users who are banned
    tmp_dir = 'tmp'

# Context managers for atomic writes courtesy of
# http://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python
@contextmanager
def _tempfile(*args, **kws):
    """ Context for temporary file.

    Will find a free temporary filename upon entering
    and will try to delete the file on leaving

    Parameters
    ----------
    suffix : string
        optional file suffix
    """

    fd, name = tempfile.mkstemp(*args, **kws)
    os.close(fd)
    try:
        yield name
    finally:
        try:
            os.remove(name)
        except OSError as e:
            if e.errno == 2:
                pass
            else:
                raise e

@contextmanager
def open_atomic(filepath, *args, **kwargs):
    """ Open temporary file object that atomically moves to destination upon
    exiting.

    Allows reading and writing to and from the same filename.

    Parameters
    ----------
    filepath : string
        the file path to be opened
    fsync : bool
        whether to force write the file to disk
    kwargs : mixed
        Any valid keyword arguments for :code:`open`
    """
    fsync = kwargs.pop('fsync', False)

    with _tempfile(dir=os.path.dirname(filepath)) as tmppath:
        with open(tmppath, *args, **kwargs) as f:
            yield f
            if fsync:
                f.flush()
                os.fsync(file.fileno())
        os.rename(tmppath, filepath)

def safe_pickle_dump(obj, fname):
    with open_atomic(fname, 'wb') as f:
        pickle.dump(obj, f, -1)

# arxiv utils
# -----------------------------------------------------------------------------

def strip_version(idstr):
    """ identity function if arxiv id has no version, otherwise strips it. """
    parts = idstr.split('v')
    return parts[0]

# "1511.08198v1" is an example of a valid arxiv id that we accept
def isvalidid(pid):
  return re.match('^\d+\.\d+(v\d+)?$', pid)


text:
#include "config.h"

#include "core/layout/svg/LayoutSVGImage.h"

#include "core/layout/ImageQualityController.h"
#include "core/layout/LayoutImageResource.h"
#include "core/layout/PointerEventsHitRules.h"
#include "core/layout/svg/LayoutSVGResourceContainer.h"
#include "core/layout/svg/SVGLayoutSupport.h"
#include "core/layout/svg/SVGResources.h"
#include "core/layout/svg/SVGResourcesCache.h"
#include "core/paint/SVGImagePainter.h"
#include "core/svg/SVGImageElement.h"
#include "platform/LengthFunctions.h"
#include "third_party/skia/include/core/SkPicture.h"

namespace blink {

LayoutSVGImage::LayoutSVGImage(SVGImageElement* impl)
    : LayoutSVGModelObject(impl)
    , m_needsBoundariesUpdate(true)
    , m_needsTransformUpdate(true)
    , m_imageResource(LayoutImageResource::create())
{
    m_imageResource->initialize(this);
}

LayoutSVGImage::~LayoutSVGImage()
{
}

void LayoutSVGImage::destroy()
{
    ImageQualityController::remove(this);
    m_imageResource->shutdown();
    LayoutSVGModelObject::destroy();
}

FloatSize LayoutSVGImage::computeImageViewportSize(ImageResource& cachedImage) const
{
    if (toSVGImageElement(element())->preserveAspectRatio()->currentValue()->align() != SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE)
        return m_objectBoundingBox.size();

    // Images with preserveAspectRatio=none should force non-uniform
    // scaling. This can be achieved by setting the image's container size to
    // its viewport size (i.e. if a viewBox is available - use that - else use intrinsic size.)
    // See: http://www.w3.org/TR/SVG/single-page.html, 7.8 The 'preserveAspectRatio' attribute.
    Length intrinsicWidth;
    Length intrinsicHeight;
    FloatSize intrinsicRatio;
    cachedImage.computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
    return intrinsicRatio;
}

static bool containerSizeIsSetForRenderer(ImageResource& cachedImage, const LayoutObject* renderer)
{
    const Image* image = cachedImage.image();
    // If a container size has been specified for this renderer, then
    // imageForRenderer() will return the SVGImageForContainer while image()
    // will return the underlying SVGImage.
    return !image->isSVGImage() || image != cachedImage.imageForRenderer(renderer);
}

bool LayoutSVGImage::updateImageViewport()
{
    SVGImageElement* image = toSVGImageElement(element());
    FloatRect oldBoundaries = m_objectBoundingBox;

    SVGLengthContext lengthContext(image);
    m_objectBoundingBox = FloatRect(image->x()->currentValue()->value(lengthContext), image->y()->currentValue()->value(lengthContext), image->width()->currentValue()->value(lengthContext), image->height()->currentValue()->value(lengthContext));
    bool boundsChanged = oldBoundaries != m_objectBoundingBox;

    bool updatedViewport = false;
    ImageResource* cachedImage = m_imageResource->cachedImage();
    if (cachedImage && cachedImage->usesImageContainerSize()) {
        FloatSize imageViewportSize = computeImageViewportSize(*cachedImage);
        if (LayoutSize(imageViewportSize) != m_imageResource->imageSize(style()->effectiveZoom())
            || !containerSizeIsSetForRenderer(*cachedImage, this)) {
            m_imageResource->setContainerSizeForRenderer(roundedIntSize(imageViewportSize));
            updatedViewport = true;
        }
    }

    m_needsBoundariesUpdate |= boundsChanged;
    return updatedViewport || boundsChanged;
}

void LayoutSVGImage::layout()
{
    ASSERT(needsLayout());

    updateImageViewport();

    bool transformOrBoundariesUpdate = m_needsTransformUpdate || m_needsBoundariesUpdate;
    if (m_needsTransformUpdate) {
        m_localTransform = toSVGImageElement(element())->calculateAnimatedLocalTransform();
        m_needsTransformUpdate = false;
    }

    if (m_needsBoundariesUpdate) {
        m_bufferedForeground.clear();

        m_paintInvalidationBoundingBox = m_objectBoundingBox;
        SVGLayoutSupport::intersectPaintInvalidationRectWithResources(this, m_paintInvalidationBoundingBox);

        m_needsBoundariesUpdate = false;
    }

    // Invalidate all resources of this client if our layout changed.
    if (everHadLayout() && selfNeedsLayout())
        SVGResourcesCache::clientLayoutChanged(this);

    // If our bounds changed, notify the parents.
    if (transformOrBoundariesUpdate)
        LayoutSVGModelObject::setNeedsBoundariesUpdate();

    clearNeedsLayout();
}

void LayoutSVGImage::paint(const PaintInfo& paintInfo, const LayoutPoint&)
{
    SVGImagePainter(*this).paint(paintInfo);
}

bool LayoutSVGImage::nodeAtFloatPoint(const HitTestRequest& request, HitTestResult& result, const FloatPoint& pointInParent, HitTestAction hitTestAction)
{
    // We only draw in the forground phase, so we only hit-test then.
    if (hitTestAction != HitTestForeground)
        return false;

    PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_IMAGE_HITTESTING, request, style()->pointerEvents());
    bool isVisible = (style()->visibility() == VISIBLE);
    if (isVisible || !hitRules.requireVisible) {
        FloatPoint localPoint;
        if (!SVGLayoutSupport::transformToUserSpaceAndCheckClipping(this, localToParentTransform(), pointInParent, localPoint))
            return false;

        if (hitRules.canHitFill || hitRules.canHitBoundingBox) {
            if (m_objectBoundingBox.contains(localPoint)) {
                updateHitTestResult(result, roundedLayoutPoint(localPoint));
                return true;
            }
        }
    }

    return false;
}

void LayoutSVGImage::imageChanged(WrappedImagePtr, const IntRect*)
{
    // The image resource defaults to nullImage until the resource arrives.
    // This empty image may be cached by SVG resources which must be invalidated.
    if (SVGResources* resources = SVGResourcesCache::cachedResourcesForLayoutObject(this))
        resources->removeClientFromCache(this);

    // Eventually notify parent resources, that we've changed.
    LayoutSVGResourceContainer::markForLayoutAndParentResourceInvalidation(this, false);

    // Update the SVGImageCache sizeAndScales entry in case image loading finished after layout.
    // (https://bugs.webkit.org/show_bug.cgi?id=99489)
    m_objectBoundingBox = FloatRect();
    updateImageViewport();

    m_bufferedForeground.clear();

    setShouldDoFullPaintInvalidation();
}

void LayoutSVGImage::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint&) const
{
    // this is called from paint() after the localTransform has already been applied
    LayoutRect contentRect = LayoutRect(paintInvalidationRectInLocalCoordinates());
    if (!contentRect.isEmpty())
        rects.append(contentRect);
}

} // namespace blink


text:
package mp.consumer.com.cfc.facade.converter.impl;

import mp.producer.com.cfp.data.TradeMessageData;
import mp.producer.com.cfp.data.TradeMessageEntity;
import mp.producer.com.cfp.facade.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class TradeMessageEntityConverter implements Converter<TradeMessageEntity, TradeMessageData>
{
	@Override
	public TradeMessageData convert(TradeMessageEntity tradeMessageEntity)
	{

		return convert(tradeMessageEntity, new TradeMessageData());
	}

	@Override
	public TradeMessageData convert(TradeMessageEntity tradeMessageEntity, TradeMessageData tradeMessageData)
	{
		tradeMessageData.setUserId(tradeMessageEntity.getUserId());
		tradeMessageData.setAmountBuy(tradeMessageEntity.getAmountBuy());
		tradeMessageData.setCurrencyFrom(tradeMessageEntity.getCurrencyFrom());
		tradeMessageData.setCurrencyTo(tradeMessageEntity.getCurrencyTo());
		tradeMessageData.setRate(tradeMessageEntity.getRate());
		tradeMessageData.setAmountSell(tradeMessageEntity.getAmountSell());
		tradeMessageData.setTimePlaced(tradeMessageEntity.getTimePlaced());
		tradeMessageData.setOriginatingCountry(tradeMessageEntity.getOriginatingCountry());
		return tradeMessageData;
	}
}


text:
// Copyright (C) 2008-2016 Alexander Vdovin
// This file is part of the "Technology in Abstract".

#include "stdafx.h"
#include "tia\psf\RandomWin.h"

#include <time.h>
#include <stdlib.h>

namespace tia
{
	namespace psf
	{
		RandomWin::RandomWin()
		{

		}

		RandomWin::~RandomWin()
		{

		}

		float RandomWin::GetRandomFloat(float lowBound, float highBound)
		{
			if (lowBound >= highBound) return lowBound;
			float f = (rand() % 10000) * 0.0001f;
			return (f * (highBound - lowBound)) + lowBound;
		}

		int RandomWin::GetRandomInt(int alMin, int alMax)
		{
			/*if( lowBound >= highBound )	return lowBound;
			float f = (rand() % 10000) * 0.0001f;
			return (int)(f*(highBound - lowBound))+lowBound; */
			return (rand() % (alMax - alMin + 1)) + alMin;
		}

		void RandomWin::Randomize(int alSeed)
		{
			if (alSeed == -1) srand((unsigned)time(0));
			else srand(alSeed);
		}
	}
}


text:
package configv3_test

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	. "code.cloudfoundry.org/cli/utils/configv3"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"
)

var _ = Describe("Config", func() {
	var homeDir string

	BeforeEach(func() {
		homeDir = setup()
	})

	AfterEach(func() {
		teardown(homeDir)
	})

	Context("when there isn't a config set", func() {
		var (
			oldLang  string
			oldLCAll string
		)

		BeforeEach(func() {
			oldLang = os.Getenv("LANG")
			oldLCAll = os.Getenv("LC_ALL")
			os.Unsetenv("LANG")
			os.Unsetenv("LC_ALL")
		})

		It("returns a default config", func() {
			defer os.Setenv("LANG", oldLang)
			defer os.Setenv("LC_ALL", oldLCAll)

			config, err := LoadConfig()
			Expect(err).ToNot(HaveOccurred())

			Expect(config).ToNot(BeNil())
			Expect(config.Target()).To(Equal(DefaultTarget))
			Expect(config.SkipSSLValidation()).To(BeFalse())
			Expect(config.ColorEnabled()).To(Equal(ColorEnabled))
			Expect(config.PluginHome()).To(Equal(filepath.Join(homeDir, ".cf", "plugins")))
			Expect(config.StagingTimeout()).To(Equal(DefaultStagingTimeout))
			Expect(config.StartupTimeout()).To(Equal(DefaultStartupTimeout))
			Expect(config.Locale()).To(BeEmpty())
			Expect(config.PluginRepos()).To(Equal([]PluginRepos{{
				Name: "CF-Community",
				URL:  "https://plugins.cloudfoundry.org",
			}}))
			Expect(config.Experimental()).To(BeFalse())

			pluginConfig := config.Plugins()
			Expect(pluginConfig).To(BeEmpty())
		})
	})

	Describe("getter functions", func() {
		Describe("Target", func() {
			var config *Config

			BeforeEach(func() {
				rawConfig := `{ "Target":"https://api.foo.com" }`
				setConfig(homeDir, rawConfig)

				var err error
				config, err = LoadConfig()
				Expect(err).ToNot(HaveOccurred())
				Expect(config).ToNot(BeNil())
			})

			It("returns fields directly from config", func() {
				Expect(config.Target()).To(Equal("https://api.foo.com"))
			})
		})

		Describe("SkipSSLValidation", func() {
			var config *Config

			BeforeEach(func() {
				rawConfig := `{ "SSLDisabled":true }`
				setConfig(homeDir, rawConfig)

				var err error
				config, err = LoadConfig()
				Expect(err).ToNot(HaveOccurred())
				Expect(config).ToNot(BeNil())
			})

			It("returns fields directly from config", func() {
				Expect(config.SkipSSLValidation()).To(BeTrue())
			})
		})
		Describe("AccessToken", func() {
			var config *Config

			BeforeEach(func() {
				rawConfig := `{ "AccessToken":"some-token" }`
				setConfig(homeDir, rawConfig)

				var err error
				config, err = LoadConfig()
				Expect(err).ToNot(HaveOccurred())
				Expect(config).ToNot(BeNil())
			})

			It("returns fields directly from config", func() {
				Expect(config.AccessToken()).To(Equal("some-token"))
			})
		})

		Describe("RefreshToken", func() {
			var config *Config

			BeforeEach(func() {
				rawConfig := `{ "RefreshToken":"some-token" }`
				setConfig(homeDir, rawConfig)

				var err error
				config, err = LoadConfig()
				Expect(err).ToNot(HaveOccurred())
				Expect(config).ToNot(BeNil())
			})

			It("returns fields directly from config", func() {
				Expect(config.RefreshToken()).To(Equal("some-token"))
			})
		})

		DescribeTable("Experimental",
			func(envVal string, expected bool) {
				rawConfig := fmt.Sprintf(`{}`)
				setConfig(homeDir, rawConfig)

				defer os.Unsetenv("EXPERIMENTAL")
				if envVal == "" {
					os.Unsetenv("EXPERIMENTAL")
				} else {
					os.Setenv("EXPERIMENTAL", envVal)
				}

				config, err := LoadConfig()
				Expect(err).ToNot(HaveOccurred())
				Expect(config).ToNot(BeNil())

				Expect(config.Experimental()).To(Equal(expected))
			},

			Entry("uses default value of false if environment value is not set", "", false),
			Entry("uses environment value if a valid environment value is set", "true", true),
			Entry("uses default value of false if an invalid environment value is set", "something-invalid", false),
		)

		Describe("BinaryName", func() {
			It("returns the name used to invoke", func() {
				config, err := LoadConfig()
				Expect(err).ToNot(HaveOccurred())
				Expect(config).ToNot(BeNil())

				// Ginkgo will uses a config file as the first test argument, so that
				// will be considered the binary name
				Expect(config.BinaryName()).To(MatchRegexp("configv3\\.test$"))
			})
		})

		Context("when there are environment variables", func() {
			var (
				originalCFStagingTimeout string
				originalCFStartupTimeout string
				originalHTTPSProxy       string

				config *Config
			)

			BeforeEach(func() {
				originalCFStagingTimeout = os.Getenv("CF_STAGING_TIMEOUT")
				originalCFStartupTimeout = os.Getenv("CF_STARTUP_TIMEOUT")
				originalHTTPSProxy = os.Getenv("https_proxy")
				os.Setenv("CF_STAGING_TIMEOUT", "8675")
				os.Setenv("CF_STARTUP_TIMEOUT", "309")
				os.Setenv("https_proxy", "proxy.com")

				var err error
				config, err = LoadConfig()
				Expect(err).ToNot(HaveOccurred())
				Expect(config).ToNot(BeNil())
			})

			AfterEach(func() {
				os.Setenv("CF_STAGING_TIMEOUT", originalCFStagingTimeout)
				os.Setenv("CF_STARTUP_TIMEOUT", originalCFStartupTimeout)
				os.Setenv("https_proxy", originalHTTPSProxy)
			})

			It("overrides specific config values", func() {
				Expect(config.StagingTimeout()).To(Equal(time.Duration(8675) * time.Minute))
				Expect(config.StartupTimeout()).To(Equal(time.Duration(309) * time.Minute))
				Expect(config.HTTPSProxy()).To(Equal("proxy.com"))
			})
		})

		Describe("APIVersion", func() {
			It("returns the api version", func() {
				config := Config{
					ConfigFile: CFConfig{
						APIVersion: "2.59.0",
					},
				}

				Expect(config.APIVersion()).To(Equal("2.59.0"))
			})
		})

		Describe("TargetedOrganization", func() {
			It("returns the organization", func() {
				organization := Organization{
					GUID: "some-guid",
					Name: "some-org",
				}
				config := Config{
					ConfigFile: CFConfig{
						TargetedOrganization: organization,
					},
				}

				Expect(config.TargetedOrganization()).To(Equal(organization))
			})
		})

		Describe("TargetedSpace", func() {
			It("returns the space", func() {
				space := Space{
					GUID: "some-guid",
					Name: "some-space",
				}
				config := Config{
					ConfigFile: CFConfig{
						TargetedSpace: space,
					},
				}

				Expect(config.TargetedSpace()).To(Equal(space))
			})
		})
	})

	Describe("Write Config", func() {
		var config *Config
		BeforeEach(func() {
			config = &Config{
				ConfigFile: CFConfig{
					ConfigVersion: 3,
					Target:        "foo.com",
					ColorEnabled:  "true",
				},
				ENV: EnvOverride{
					CFColor: "false",
				},
			}
		})

		It("writes ConfigFile to homeDir/.cf/config.json", func() {
			err := WriteConfig(config)
			Expect(err).ToNot(HaveOccurred())

			file, err := ioutil.ReadFile(filepath.Join(homeDir, ".cf", "config.json"))
			Expect(err).ToNot(HaveOccurred())

			var writtenCFConfig CFConfig
			err = json.Unmarshal(file, &writtenCFConfig)
			Expect(err).ToNot(HaveOccurred())

			Expect(writtenCFConfig.ConfigVersion).To(Equal(config.ConfigFile.ConfigVersion))
			Expect(writtenCFConfig.Target).To(Equal(config.ConfigFile.Target))
			Expect(writtenCFConfig.ColorEnabled).To(Equal(config.ConfigFile.ColorEnabled))
		})
	})

	Describe("setter functions", func() {
		Describe("SetTargetInformation", func() {
			It("sets the api target and other related endpoints", func() {
				config := Config{
					ConfigFile: CFConfig{
						TargetedOrganization: Organization{
							GUID: "this-is-a-guid",
							Name: "jo bobo jim boo",
						},
						TargetedSpace: Space{
							GUID:     "this-is-a-guid",
							Name:     "jo bobo jim boo",
							AllowSSH: true,
						},
					},
				}
				config.SetTargetInformation(
					"https://api.foo.com",
					"2.59.31",
					"https://login.foo.com",
					"wws://loggregator.foo.com:443",
					"wws://doppler.foo.com:443",
					"https://uaa.foo.com",
					"https://api.foo.com/routing",
					true,
				)

				Expect(config.ConfigFile.Target).To(Equal("https://api.foo.com"))
				Expect(config.ConfigFile.APIVersion).To(Equal("2.59.31"))
				Expect(config.ConfigFile.AuthorizationEndpoint).To(Equal("https://login.foo.com"))
				Expect(config.ConfigFile.LoggregatorEndpoint).To(Equal("wws://loggregator.foo.com:443"))
				Expect(config.ConfigFile.DopplerEndpoint).To(Equal("wws://doppler.foo.com:443"))
				Expect(config.ConfigFile.UAAEndpoint).To(Equal("https://uaa.foo.com"))
				Expect(config.ConfigFile.RoutingEndpoint).To(Equal("https://api.foo.com/routing"))
				Expect(config.ConfigFile.SkipSSLValidation).To(BeTrue())

				Expect(config.ConfigFile.TargetedOrganization.GUID).To(BeEmpty())
				Expect(config.ConfigFile.TargetedOrganization.Name).To(BeEmpty())
				Expect(config.ConfigFile.TargetedSpace.GUID).To(BeEmpty())
				Expect(config.ConfigFile.TargetedSpace.Name).To(BeEmpty())
				Expect(config.ConfigFile.TargetedSpace.AllowSSH).To(BeFalse())
			})
		})

		Describe("SetTokenInformation", func() {
			It("sets the authentication token information", func() {
				var config Config
				config.SetTokenInformation("I am the access token", "I am the refresh token", "I am the SSH OAuth client")

				Expect(config.ConfigFile.AccessToken).To(Equal("I am the access token"))
				Expect(config.ConfigFile.RefreshToken).To(Equal("I am the refresh token"))
				Expect(config.ConfigFile.SSHOAuthClient).To(Equal("I am the SSH OAuth client"))
			})
		})

		Describe("SetOrganizationInformation", func() {
			It("sets the organization GUID and name", func() {
				config := Config{}
				config.SetOrganizationInformation("guid-value-1", "my-org-name")

				Expect(config.ConfigFile.TargetedOrganization.GUID).To(Equal("guid-value-1"))
				Expect(config.ConfigFile.TargetedOrganization.Name).To(Equal("my-org-name"))
			})
		})

		Describe("SetSpaceInformation", func() {
			It("sets the organization GUID and name", func() {
				config := Config{}
				config.SetSpaceInformation("guid-value-1", "my-org-name", true)

				Expect(config.ConfigFile.TargetedSpace.GUID).To(Equal("guid-value-1"))
				Expect(config.ConfigFile.TargetedSpace.Name).To(Equal("my-org-name"))
				Expect(config.ConfigFile.TargetedSpace.AllowSSH).To(BeTrue())
			})
		})
	})
})


text:
import {MetaUtils} from "../metadata/utils";
import {Decorators} from '../constants/decorators';
import {DecoratorType} from '../enums/decorator-type';
import {JsonIgnore} from '../enums/jsonignore-enum';
import { OptimisticLockType } from "../enums/optimisticlock-type";

export function OptimisticLocking(params?: JsonIgnore): any {
    params = params || <any>{};
    return function (target: Object, propertyKey: string) {
        let type = params && params["type"];
        switch(type){
            case OptimisticLockType.VERSION:
             MetaUtils.addMetaData(target,
              {
                decorator: Decorators.OPTIMISTICLOCK,
                decoratorType: DecoratorType.PROPERTY,
                params: params,
                propertyKey: propertyKey
             });
            break;
        }
    };
}


text:
""" Custom Nose-Hoover NVT thermostat based on ASE.

This code was originally written by Jonathan Mailoa based on these notes:

    https://www2.ph.ed.ac.uk/~dmarendu/MVP/MVP03.pdf

It was then adapted by Simon Batzner to be used within ASE. Parts of the overall outline of the class are also based on the Langevin class in ASE.
"""

import numpy as np

from ase.md.md import MolecularDynamics
from ase.md.velocitydistribution import Stationary, ZeroRotation
from ase import units

class NoseHoover(MolecularDynamics):
    """Nose-Hoover (constant N, V, T) molecular dynamics.

    Usage: NoseHoover(atoms, dt, temperature)

    atoms
        The list of atoms.

    timestep
        The time step.

    temperature
        Target temperature of the MD run in [K * units.kB]

    nvt_q
        Q in the Nose-Hoover equations

    Example Usage:

        nvt_dyn = NoseHoover(
            atoms=atoms,
            timestep=0.5 * units.fs,
            temperature=300. * units.kB,
            nvt_q=334.
        )

    """

    def __init__(
        self,
        atoms,
        timestep,
        temperature,
        nvt_q,
        trajectory=None,
        logfile=None,
        loginterval=1,
        append_trajectory=False,
    ):
        # set angular and com momentum to zero, necessary for nose-hoover dynamics.
        ZeroRotation(atoms)
        Stationary(atoms)

        # thermostat parameters
        self.temp = temperature / units.kB
        self.nvt_q = nvt_q
        self.dt = timestep
        self.dtdt = np.power(self.dt, 2)
        self.nvt_bath = 0.0

        self.natoms = len(atoms)

        MolecularDynamics.__init__(
            self,
            atoms,
            timestep,
            trajectory,
            logfile,
            loginterval,
            append_trajectory=append_trajectory,
        )

    def step(self):
        """Perform a MD step."""
        masses = self.atoms.get_masses()

        modified_acc = (
            self.atoms.get_forces() / masses[:, np.newaxis]
            - self.nvt_bath * self.atoms.get_velocities()
        )
        pos_fullstep = (
            self.atoms.get_positions()
            + self.dt * self.atoms.get_velocities()
            + 0.5 * self.dtdt * modified_acc
        )
        vel_halfstep = self.atoms.get_velocities() + 0.5 * self.dt * modified_acc

        self.atoms.set_positions(pos_fullstep)

        e_kin_diff = 0.5 * (
            np.sum(masses * np.sum(self.atoms.get_velocities() ** 2, axis=1))
            - (3 * self.natoms + 1) * units.kB * self.temp
        )

        nvt_bath_halfstep = self.nvt_bath + 0.5 * self.dt * e_kin_diff / self.nvt_q
        e_kin_diff_halfstep = 0.5 * (
            np.sum(masses * np.sum(vel_halfstep ** 2, axis=1))
            - (3 * self.natoms + 1) * units.kB * self.temp
        )
        self.nvt_bath = (
            nvt_bath_halfstep + 0.5 * self.dt * e_kin_diff_halfstep / self.nvt_q
        )
        self.atoms.set_velocities(
            (
                vel_halfstep
                + 0.5 * self.dt * (self.atoms.get_forces() / masses[:, np.newaxis])
            )
            / (1 + 0.5 * self.dt * self.nvt_bath)
        )


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>{pagetitle}</title>
        <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <link rel="stylesheet" type="text/css" href="/assets/css/default.css"/>
		<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
		<link rel="stylesheet" type="text/css" media="all" href="css/text.css" />
		<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
		<link rel="stylesheet" type="text/css" media="all" href="css/lightbox.css" />

			Simple Image Gallery

Home

Gallery

About

			{content}

			Copyright © 2014,  Me.


text:
#include <aws/clouddirectory/model/PutSchemaFromJsonResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::CloudDirectory::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

PutSchemaFromJsonResult::PutSchemaFromJsonResult()
{
}

PutSchemaFromJsonResult::PutSchemaFromJsonResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

PutSchemaFromJsonResult& PutSchemaFromJsonResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("Arn"))
  {
    m_arn = jsonValue.GetString("Arn");

  }

  return *this;
}


text:
package org.apache.tools.ant.taskdefs;

import org.apache.tools.ant.taskdefs.email.EmailTask;

/**
 * A task to send SMTP email.
 * This task can send mail using either plain
 * text, UU encoding or Mime format mail depending on what is available.
 * Attachments may be sent using nested FileSet
 * elements.
 *
 * @since Ant 1.2
 *
 * @ant.task name="mail" category="network"
 */
public class SendEmail extends EmailTask {
    /**
     * Sets the mailport parameter of this build task.
     * @param value mail port name.
     *
     * @deprecated since 1.5.x.
     *             Use {@link #setMailport(int)} instead.
     */
    public void setMailport(Integer value) {
        setMailport(value.intValue());
    }
}


text: from mattermark.mattermark import mattermark


text:
<?php

namespace ema\engine;

use ema\exceptions\FatalError;
use ema\exceptions\LoginIncorrect;
use ema\exceptions\NotLoggedIn;
use ema\exceptions\SessionExpired;
use Exception;
use RuntimeException;

class UserAuth
{

    /**
     * Should Auth mechanism check expire filed
     */
    const CHECK_EXPIRE = true;

    const RESTRICT_TOR_ACCESS = true;

    /**
     * Write CSRF token to cookie to prevent CSRF attacks
     */
    const USE_CSRF_TOKEN = true;

    /**
     * If false CSRF token will be always valid
     */
    const CHECK_CSRF_TOKEN = true;

    /**
     * User id
     * @var string
     */
    public $id;

    /**
     * User name
     * @var string
     */
    public $name;

    /**
     * User ip
     * @var string
     */
    public $ip;

    public $expires;

    /**
     * Indicates is there user authorized
     * @var bool
     */
    private $authorized = false;

    /**
     * Indicates why user was logged out. Filled by constructor.
     * @var int
     */
    public $logoutReason = 0;

    private $group;

    protected $sessionAuthData = array();

    protected static $expectedFields = array('group', 'name', 'lastUserActivity', 'ip', 'id', 'expires', 'memberid', 'secret');

    /**
     * @var \medoo Db connection instance
     */
    protected $db;

    /**
     * Session lifetime in seconds
     * @var int deffault value = 300
     */
    const sessionTTL = 14400;

    const USERS_TABLE = 'users';

    /**
     * Function set session options, starting session, checking session timeout and trying to get user info from session
     *
     * If user is authorized function will fill object properties.
     * @throws \ema\exceptions\FatalError
     * @throws \ema\exceptions\SessionExpired
     * @throws \Exception
     */
    public function __construct()
    {
        session_cache_limiter(false);
        $returned = ini_get('session.use_only_cookies');
        if (is_bool($returned) == true || ($returned === "" || $returned === "0")) {
            $complete = ini_set('session.use_only_cookies', '1');

            if ($complete === false) {
                throw new FatalError("Error. Cannot set session parameter by function 'ini_set'.");
            }
        }
        $returned = ini_get("session.cookie_lifetime");
        if ($returned !== 0) {
            $complete = ini_set("session.cookie_lifetime", 0);
            if ($complete === false) {
                throw new FatalError("Error. Cannot set session parameter by function 'ini_set'.");
            }
        }
        unset($complete);

        $this->db = $GLOBALS['EMA']['DB']['connection'];

        $globalData = $this->getFromGlobal();

        if ($globalData && self::checkSessionConsistency($globalData)) {
            $this->sessionAuthData = $globalData;
            $this->fillObject();

            return;
        }

        $response = session_id();
        if (empty($response)) {
            session_start();
        }

        if (empty($_SESSION['EMA']['UserAuth'])) {
            return;
        } else {
            if (self::checkSessionConsistency($_SESSION['EMA']['UserAuth'])) {
                $this->sessionAuthData = $_SESSION['EMA']['UserAuth'];
            } else {
                return;
            }
        }

        $logoutTime = $this->sessionAuthData['lastUserActivity'] + self::sessionTTL;

        if ($logoutTime <= time()) {
            $this->destroySession();
            throw new SessionExpired('Session expired');
        }

        if (EMA_AUTH_CHECK_IP && $this->sessionAuthData['ip'] !== $_SERVER['REMOTE_ADDR']) {
            $this->destroySession();
            throw new SessionExpired('Your IP has benn changed');
        }

        if (self::CHECK_EXPIRE && $this->sessionAuthData['expires'] > 0 && time() > $this->sessionAuthData['expires']) {
            throw new SessionExpired('Your account has been expired');
        }

        $_SESSION['EMA']['UserAuth']['lastUserActivity'] = $this->sessionAuthData['lastUserActivity'] = time();

        $this->fillObject();
        $this->writeToGlobal();
        session_write_close();

    }

    /**
     * Check if user currently log in and update $_SESSION['lastUserActivity'] time.
     * This function generates error if user are not loged in.
     *
     * It used inside functions to check if user are logged in.
     *
     * If you just need to check up if user logged in, use "UserLogIn Simple" function.
     * @param bool $isUserActivity Set false if you do not want to update $_SESSION['lastUserActivity']
     * @return bool True if user are logged in.
     * @throws \ema\exceptions\NotLoggedIn
     */
    public function isUserLoggedIn($isUserActivity = true)
    {
        if ($isUserActivity === true) {
            if ($this->authorized === true) {
                $this->sessionAuthData['lastUserActivity'] = time();
                $this->writeToSession();
            }
        }
        if ($this->authorized === true) {
            return true;
        } else {
            throw new NotLoggedIn('Access denied: You need to log in to use this function');
        }
    }

    /**
     * This function just return $authorized property of an object, without errors or any other activity
     * It used for simple check: if user logged in or not.
     * @return bool True if user are logged in. False otherwise.
     */
    public function isUserLoggedInSimple()
    {
        return $this->authorized;
    }

    /**
     * Try to login user with name and password
     * @param string $userName User name
     * @param string $userPasswd User password
     * @param bool $checkOnly Set true if you just need to check up username and password without login
     * @return bool True if user was logged in. False otherwise.
     * @throws Exception
     */
    public function userLogin($userName = "", $userPasswd = "", $checkOnly = false, $writeToSession = true)
    {
        if ($this->authorized === true && $checkOnly === false) {
            return true;
        }
        if (is_string($userName) === false || is_string($userPasswd) === false) {
            throw new FatalError('Arguments are not a string');
        }
        if (is_bool($checkOnly) === false) {
            throw new FatalError('Arguments are not a string');
        }

        if (self::RESTRICT_TOR_ACCESS && $this->isTor()) {
            throw new LoginIncorrect('Its not allowed to login from Tor network');
        }
        $userData = $this->getUser($userName);

        if (count($userData) === 0) {
            throw new LoginIncorrect('User name or password incorrect', 6030);
        }

        $userPasswordHash = $this->createPassHash($userPasswd, $userData['salt']);

        if ($userPasswordHash !== $userData['password']) {
            throw new LoginIncorrect('User name or password incorrect', 6030);
        }

        if (self::CHECK_EXPIRE && $userData['expires'] > 0 && time() > $userData['expires']) {
            throw new LoginIncorrect('Your account has been expired');
        }

        if ($checkOnly === true) {
            return true;
        }

        $this->destroySession();
        $returned = session_start();
        if ($returned === false) {
            throw new FatalError("Cannot start session");
        }

        $this->authorized = true;

        $this->sessionAuthData['id'] = $userData['id'];
        $this->sessionAuthData['ip'] = $_SERVER['REMOTE_ADDR'];
        $this->sessionAuthData['name'] = $userName;
        $this->sessionAuthData['memberid'] = $userData['memberid'];

        $this->sessionAuthData['group'] = (int)$userData['group'];
        $this->sessionAuthData['lastUserActivity'] = time();
        $this->sessionAuthData['expires'] = $userData['expires'];
        $this->sessionAuthData['secret'] = $this->getCsrfSecret();

        if (self::USE_CSRF_TOKEN) {
            $this->writeCsrfCookie($this->sessionAuthData['secret']);
        }

        foreach ($this->sessionAuthData as $key => $value) {
            $this->$key = $value;
        }

        if ($writeToSession) {
            $this->writeToSession();
        }
    }

    /**
     * @return array
     */
    public function getSessionAuthData()
    {
        $return = $this->sessionAuthData;
        unset($return['secret'], $return['ip']);
        $return['ttl'] = self::sessionTTL;
        return $return;
    }

    /**
     * @param $token
     * @return bool
     * @throws FatalError
     */
    public function checkCsrfToken($token)
    {
        if (!self::CHECK_CSRF_TOKEN) {
            return true;
        }

        if (!$this->isUserLoggedInSimple()) {
            return true;
        }

        if (empty($token) || !is_string($token)) {
            return false;
        }

        $result = explode('-', $token);
        $tokenValid = false;

        if (is_array($result) && count($result) === 2) {
            list($hash, $salt) = $result;
            $validToken = $this->getCsrfToken($this->sessionAuthData['secret'], $salt);

            if ($validToken === $token) {
                return true;
            }
        }

        return $tokenValid;
    }

    /**
     * Retrieves is logged user have admin rights
     * @return bool True if user have admin rights or false otherwise
     */
    public function isAdmin()
    {
        if ($this->authorized === false) {
            return false;
        }
        if ($this->getGroup() === 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Try to log out current user
     * @return bool Function stop script in case of errors or returb true
     */
    public function logout()
    {
        $sesid = session_id();
            session_start();

        $this->destroySession();
        return true;
    }

    /**
     * @return mixed
     */
    public function getGroup()
    {
        return $this->group;
    }

    /**
     * Destroy current session. Causes user to log out.
     *
     * Function stop script in case of errors.
     * @throws Exception
     */
    protected function destroySession()
    {
        if (session_id() !== "") {
            /*$returned = setcookie(session_name(), session_id(), time() - 60 * 60 * 24);
            if ($returned === false) {
                throw new FatalError("Error when try to set cookie");
            }*/
            session_unset();

            if (self::USE_CSRF_TOKEN) {
                $this->removeCsrfCookie();
            }

            $returned = session_destroy();
            if ($returned === false) {
                throw new FatalError("Error. Cannot destroy session");
            }
        }
    }

    /**
     * Generates hash and salt from string
     *
     * WARNING! Each time you run this function it will generate different pairs of hash/salt, even for equal strings.
     *
     * Also, function check password for validaty, used regexp:
     *            /^[a-zA-Z0-9\_\-\*\$\^\#\!\@\%\&\(\)]{6,18}$/
     * @param string $password User password
     * @return array|bool Return false in case of errors or array with hashes.
     * @throws Exception
     */
    protected function generatePasswordHashAndSalt($password)
    {
        if (isset($password) === false or is_string($password) === false) {
            throw new Exception("Invalid arguments");
        }
        $password = trim($password);
        /*$returned = preg_match("/^[a-zA-Z0-9\\_\\-\\*\$\\^\\#\\!\\@\\%\\&\\(\\)]{6,128}$/", $password);
        if ($returned === 0) {
            throw new RuntimeException("Password incorrect");
        }*/
        $arr['salt'] = base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM));
        $arr['password'] = crypt($password, "$6$" . $arr['salt'] . "$");
        $arr['password'] = $this->createPassHash($password, $arr['salt']);
        return $arr;
    }

    protected function writeToSession()
    {
        $this->writeToGlobal();
        $_SESSION['EMA']['UserAuth'] = $this->sessionAuthData;
        session_write_close();
    }

    protected function isTor()
    {
        $ReverseIPOctets = function ($inputip) {
            $ipoc = explode(".",$inputip);
            return $ipoc[3].".".$ipoc[2].".".$ipoc[1].".".$ipoc[0];
        };

        $IsTorExitPoint = function () use (&$ReverseIPOctets) {
            if (gethostbyname($ReverseIPOctets($_SERVER['REMOTE_ADDR']) . "." . $_SERVER['SERVER_PORT'] . "."
                    . $ReverseIPOctets($_SERVER['SERVER_ADDR']) . ".ip-port.exitlist.torproject.org")=="127.0.0.2") {
                return true;
            } else {
                return false;
            }
        };
        return $IsTorExitPoint();
    }

    /**
     * Generates random CSRF secret
     * @return string
     */
    protected function getCsrfSecret()
    {
        return base64_encode(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
    }

    /**
     * Generates CSRF token
     * @param $secret
     * @param string $salt
     * @return string
     * @throws FatalError
     */
    protected function getCsrfToken($secret, $salt = '')
    {
        if (!is_string($secret) || empty($secret)) {
            throw new FatalError('Secret invalid');
        }

        if (empty($salt)) {
            $salt = base64_encode(mcrypt_create_iv(5, MCRYPT_DEV_URANDOM));
        }

        return md5($salt . '-' . $secret) . '-' . $salt;

    }

    /**
     * Sets CSRF cookie
     * @param $secret
     * @throws FatalError
     */
    protected function writeCsrfCookie($secret)
    {
        $token = $this->getCsrfToken($secret);
        $result = setcookie('X-EMA-CSRFToken', $token, 0, '/');
        if ($result === false) {
            throw  new FatalError('Cannot set CSRF cookie');
        }
    }

    protected function removeCsrfCookie()
    {
        setcookie('X-EMA-CSRFToken', null, -1, '/');
    }

    /**
     * Checks if all fields present in session
     * @param array $userAuthArray
     * @return bool
     */
    private static function checkSessionConsistency(array $userAuthArray)
    {
        foreach (self::$expectedFields as $value) {
            if (!array_key_exists($value, $userAuthArray)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Generates Hash for password and salt
     * @param $password
     * @param $salt
     * @return string
     */
    private function createPassHash($password, $salt)
    {
        return crypt($password, "$6$" . $salt . "$");
    }

    private function getUser($username)
    {
        $userData = array();
        $re = "/^[\\w\\-\\$]{3,64}$/";

        if(preg_match($re, $username) === 1){
            $result = $this->db->select(self::USERS_TABLE, '*', array('AND' => array('name' => $username, 'active' => 1)));
            if(! empty($result) && count($result) > 0) {
                $userData = end($result);
            }
        }

        return $userData;
    }

    private function fillObject()
    {
        foreach ($this->sessionAuthData as $key => $value) {
            $this->$key = $value;
        }

        $this->authorized = true;
    }

    private function getFromGlobal()
    {
        $authData = false;
        if (defined('EMA_AUTH')) {
            $authData = @unserialize(EMA_AUTH);
        }

        return $authData;
    }

    private function writeToGlobal()
    {
        if (!defined('EMA_AUTH')) {
            define('EMA_AUTH', serialize($this->sessionAuthData));
        }
    }

}


text:
const markdown11ty = require('../markdown');

/**
 *
 * @param {string} entry - markdown to be render as HTML.
 * @return {string} HTML code from Markdown format.
 */
function markdown(entry) {
  if (!entry) {
    return '';
  }
  return markdown11ty.render(entry);
}

module.exports = (eleventy) => {
  eleventy.addFilter('markdown', markdown);
};


text:
package net.sf.esfinge.metadata.validate;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;

import net.sf.esfinge.metadata.AnnotationPropertyValidator;
import net.sf.esfinge.metadata.AnnotationValidationException;
import net.sf.esfinge.metadata.annotation.validator.MaxValue;

public class SiteValidoAnnotationValidator implements AnnotationPropertyValidator{
	private int maxValue;
	private MaxValue mv;

	@Override
	public void initialize(Annotation self) {
		mv = (MaxValue) self;
		maxValue = mv.value();
	}

	@Override
	public void validate(Annotation annotationOnElement,
			AnnotatedElement annotatedWithMainAnnotation,
			Method annotatedWithValidation, Object annotationPropertyValue)
			throws AnnotationValidationException {

		Integer value = (Integer) annotationPropertyValue;
		if(maxValue < value){
			throw new AnnotationValidationException("The attribute "+ annotatedWithValidation.getName() +" of @" +annotationOnElement.annotationType().getName() + " has a value("+value+"), which is greather than the @MaxValue("+maxValue+")");
		}

	}
}


text:
package org.arquillian.cube.impl.util;

import java.util.Arrays;
import java.util.Collections;

import java.io.Serializable;
import java.util.Date;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;

/**
 * This class represents a notion of timespan. Note that the time units goes from milliseconds to year.
 * It does not go below milliseconds because we rarely use this kind of precision especially since the
 * java vm does not support it very well. Note that above hour, the timespan is approximate. This
 * object is immutable and thread safe.
 *
 * @author ypujante@linkedin.com
 */
public class Timespan implements Serializable {
    private static final long serialVersionUID = 1L;

    public enum TimeUnit {
        MILLISECOND(1L, ""),
        SECOND(1000L * MILLISECOND.getMillisecondsCount(), "s"),
        MINUTE(60L * SECOND.getMillisecondsCount(), "m"),
        HOUR(60L * MINUTE.getMillisecondsCount(), "h"),
        // note that the values below are approximations, and should not be used to compute exact
        // values!
        DAY(24L * HOUR.getMillisecondsCount(), "d"),
        WEEK(7L * DAY.getMillisecondsCount(), "w"),
        MONTH(30L * DAY.getMillisecondsCount(), "M"),
        YEAR(365L * DAY.getMillisecondsCount(), "y");

        private final long _millisecondsCount;
        private final String _displayChar;

        private TimeUnit(long millisecondsCount, String displayChar) {
            _millisecondsCount = millisecondsCount;
            _displayChar = displayChar;
        }

        public long getMillisecondsCount() {
            return _millisecondsCount;
        }

        public String getDisplayChar() {
            return _displayChar;
        }
    }

    public final static Timespan ZERO_YEARS = new Timespan(0, TimeUnit.YEAR);
    public final static Timespan ZERO_MONTHS = new Timespan(0, TimeUnit.MONTH);
    public final static Timespan ZERO_WEEKS = new Timespan(0, TimeUnit.WEEK);
    public final static Timespan ZERO_DAYS = new Timespan(0, TimeUnit.DAY);
    public final static Timespan ZERO_HOURS = new Timespan(0, TimeUnit.HOUR);
    public final static Timespan ZERO_MINUTES = new Timespan(0, TimeUnit.MINUTE);
    public final static Timespan ZERO_SECONDS = new Timespan(0, TimeUnit.SECOND);
    public final static Timespan ZERO_MILLISECONDS = new Timespan(0, TimeUnit.MILLISECOND);

    public final static Timespan ONE_SECOND = new Timespan(1, TimeUnit.SECOND);
    public final static Timespan ONE_MINUTE = new Timespan(1, TimeUnit.MINUTE);

    private final static EnumMap<TimeUnit, Timespan> ZERO_TIMESPANS =
        new EnumMap<>(TimeUnit.class);

    private final static TimeUnit[] TIME_UNIT_ORDER;

    static {
        final List<TimeUnit> timeUnits = Arrays.asList(TimeUnit.values());
        Collections.reverse(timeUnits);

        TIME_UNIT_ORDER = (TimeUnit[]) timeUnits.toArray();
    }

    static {
        ZERO_TIMESPANS.put(TimeUnit.YEAR, ZERO_YEARS);
        ZERO_TIMESPANS.put(TimeUnit.MONTH, ZERO_MONTHS);
        ZERO_TIMESPANS.put(TimeUnit.WEEK, ZERO_WEEKS);
        ZERO_TIMESPANS.put(TimeUnit.DAY, ZERO_DAYS);
        ZERO_TIMESPANS.put(TimeUnit.HOUR, ZERO_HOURS);
        ZERO_TIMESPANS.put(TimeUnit.MINUTE, ZERO_MINUTES);
        ZERO_TIMESPANS.put(TimeUnit.SECOND, ZERO_SECONDS);
        ZERO_TIMESPANS.put(TimeUnit.MILLISECOND, ZERO_MILLISECONDS);
    }

    private final static EnumSet<TimeUnit> CANONICAL_TIME_UNITS =
        EnumSet.range(TimeUnit.MILLISECOND, TimeUnit.YEAR);

    private final long _duration;
    private final TimeUnit _timeUnit;

    /**
     * Constructor
     *
     * @param durationInMilliseconds
     *     the duration in milliseconds
     */
    public Timespan(long durationInMilliseconds) {
        this(durationInMilliseconds, TimeUnit.MILLISECOND);
    }

    /**
     * Constructor
     */
    public Timespan(long duration, TimeUnit timeUnit) {
        _duration = duration;
        _timeUnit = timeUnit;
    }

    /**
     * @return the time unit of this timespan
     */
    public TimeUnit getTimeUnit() {
        return _timeUnit;
    }

    /**
     * @return the duration of this timespan
     */
    public long getDuration() {
        return _duration;
    }

    /**
     * Adds another timespan to this timespan and return a brand new one. Note that the unit is
     * preserved if other has the same unit as 'this'.
     *
     * @param other
     *     the timespan to add
     *
     * @return a brand new timespan.
     */
    public Timespan add(Timespan other) {
        if (getTimeUnit() == other.getTimeUnit()) {
            return new Timespan(getDuration() + other.getDuration(), getTimeUnit());
        }

        return new Timespan(getDurationInMilliseconds() + other.getDurationInMilliseconds(),
            TimeUnit.MILLISECOND);
    }

    /**
     * Creates and returns a new timespan whose duration is {@code this}
     * timespan's duration minus the {@code other} timespan's duration.
     *

     * The time unit is preserved if {@code other} has the same unit
     * as {@code this}.
     *

     * Negative timespans are not supported, so if the {@code other}
     * timespan duration is greater than {@code this} timespan duration,
     * a timespan of zero is returned (i.e., a negative timespan is never
     * returned).
     *
     * @param other
     *     the timespan to subtract from this one
     *
     * @return a new timespan representing {@code this - other}
     */
    public Timespan substractWithZeroFloor(Timespan other) {
        if (getTimeUnit() == other.getTimeUnit()) {
            long delta = Math.max(0, getDuration() - other.getDuration());
            return new Timespan(delta, getTimeUnit());
        }

        long delta = Math.max(0, getDurationInMilliseconds() - other.getDurationInMilliseconds());

        return new Timespan(delta, TimeUnit.MILLISECOND);
    }

    /**
     * @return the duration of this timespan in milliseconds
     */
    public long getDurationInMilliseconds() {
        // 100% equivalent to getDuration(TimeUnit.MILLISECOND) but faster!
        return getDuration() * getTimeUnit().getMillisecondsCount();
    }

    /**
     * @param timeUnit
     *     the unit of time you want this timespan ass
     *
     * @return the duration of this timespan expressed in the time unit provided. Note that all
     * units below timeUnit will be truncated! (ex: 3h20m45s will return 3 if timeUnit=HOUR).
     */
    public long getDuration(TimeUnit timeUnit) {
        return truncate(timeUnit).getDuration();
    }

    /**
     * @return the duration of this timespan expressed in seconds. If milliseconds are present,
     * they will be truncated!
     */
    public long getDurationInSeconds() {
        return getDuration(TimeUnit.SECOND);
    }

    /**
     * @return the duration of this timespan expressed in minutes. If s/ms are present,
     * they will be truncated!
     */
    public long getDurationInMinutes() {
        return getDuration(TimeUnit.MINUTE);
    }

    /**
     * @return the duration of this timespan expressed in hours. If m/s/ms are present,
     * they will be truncated!
     */
    public long getDurationInHours() {
        return getDuration(TimeUnit.HOUR);
    }

    /**
     * @return a (potentially new) version of this timestamp where the unit is
     * {@link TimeUnit#MILLISECOND}.
     */
    public Timespan toMillisecondsTimespan() {
        if (getTimeUnit() == TimeUnit.MILLISECOND) {
            return this;
        }

        return new Timespan(getDurationInMilliseconds(), TimeUnit.MILLISECOND);
    }

    /**
     * Truncates this timespan to the given time unit. Example: if this is 1h20m5s then
     * truncate(TimeUnit.HOUR) will return 1h,
     * truncate(TimeUnit.MINUTE) will return 1h20m and
     * truncate(TimeUnit.SECOND) will return 1h20m5s
     *
     * @param timeUnit
     *     the unit you want the timespan in
     *
     * @return this timespan if time unit matches otherwise a new one with the given unit
     */
    public Timespan truncate(TimeUnit timeUnit) {
        if (getTimeUnit() == timeUnit) {
            return this;
        }

        return truncateDurationToUnit(getDurationInMilliseconds(), timeUnit);
    }

    /**
     * There are many ways to represent the same timespan: 3h, 180m... this call return the unique
     * way to express it such that ms is < 1000, s is < 60, m is < 60, h is < 24,
     * d is < 7.
     *
     * @return this timespan as a canonical representation: an entry for w/dh/m/s/ms is returned
     *
     * @see #getAsTimespans(EnumSet)
     */
    public EnumMap<TimeUnit, Timespan> getCanonicalTimespans() {
        return getAsTimespans(CANONICAL_TIME_UNITS);
    }

    /**
     * @return a string representing this timespan (ex: 3h2m23s). Note that if a duration is missing,
     * it is not part of the string (the string would be 3h23s and not 3h0m23s).
     *
     * @see #getCanonicalTimespans()
     */
    public String getCanonicalString() {
        return getAsString(CANONICAL_TIME_UNITS);
    }

    /**
     * Decomposes this timespan as a map for each unit provided. Example: if this timespan represents
     * 63s and you provide m/s/ms then you will get 3 timespans in the map: one of 1mn, one for 3s
     * and one for 0ms.
     *
     * @param timeUnits
     *     the time units you want to be part of the decomposition.
     *
     * @return a map containing an entry for each time unit provided. All others are null.
     */
    public EnumMap<TimeUnit, Timespan> getAsTimespans(EnumSet<TimeUnit> timeUnits) {
        EnumMap<TimeUnit, Timespan> res = new EnumMap<TimeUnit, Timespan>(TimeUnit.class);

        long durationInMillis = getDurationInMilliseconds();

        for (TimeUnit timeUnit : TIME_UNIT_ORDER) {
            if (timeUnits.contains(timeUnit)) {
                Timespan timespan = truncateDurationToUnit(durationInMillis, timeUnit);
                res.put(timeUnit, timespan);
                durationInMillis -= timespan.getDurationInMilliseconds();
            }
        }

        return res;
    }

    /**
     * Filters this timespan with only the unit provided. It computes the canonical representation
     * and keeps only the units that are present in the filter. Example: if this timespan represents
     * 3d2h25m10s and filter is d/h/m then result is 3d2h25m.
     *
     * @param timeUnits
     *     the time units you want to keep in the filtering.
     *
     * @return the timespan after the filtering
     */
    public Timespan filter(EnumSet<TimeUnit> timeUnits) {
        Timespan res = null;

        EnumMap<TimeUnit, Timespan> canonicalTimespans = getCanonicalTimespans();

        for (TimeUnit timeUnit : TIME_UNIT_ORDER) {
            if (timeUnits.contains(timeUnit)) {
                Timespan timespan = canonicalTimespans.get(timeUnit);
                if (timespan != null && timespan.getDuration() > 0) {
                    if (res == null) {
                        res = timespan;
                    } else {
                        res = res.add(timespan);
                    }
                }
            }
        }

        // in case there is no match we return with smallest timeunit provided
        if (res == null) {
            res = ZERO_TIMESPANS.get(timeUnits.iterator().next());
        }

        return res;
    }

    /**
     * Returns a string representing this timespan expressed with the units provided.
     *
     * @param timeUnits
     *     the timeunits you want in the decomposition
     *
     * @return a string representation using the units.
     *
     * @see #getAsTimespans(EnumSet)
     */
    public String getAsString(EnumSet<TimeUnit> timeUnits) {
        StringBuilder sb = new StringBuilder();

        EnumMap<TimeUnit, Timespan> canonicalTimespans = getAsTimespans(timeUnits);
        for (TimeUnit timeUnit : TIME_UNIT_ORDER) {
            if (canonicalTimespans.containsKey(timeUnit)) {
                long duration = canonicalTimespans.get(timeUnit).getDuration();
                if (duration > 0) {
                    sb.append(duration).append(timeUnit.getDisplayChar());
                }
            }
        }

        if (sb.length() == 0) {
            sb.append(0);
            if (timeUnits.contains(getTimeUnit())) {
                sb.append(getTimeUnit().getDisplayChar());
            }
        }

        return sb.toString();
    }

    /**
     * 2 timespans can be different (1h and 3600s) while representing the same duration expressed
     * in milliseconds... This method tests for this.
     *
     * @param timespan
     *     the other timespan to compare with
     *
     * @return true if this timespan and the provided one represent the same
     * duration of time.
     */
    public boolean equalsDurationInMilliseconds(Timespan timespan) {
        // shortcut when time unit are the same
        if (timespan.getTimeUnit() == getTimeUnit()) {
            return timespan.getDuration() == getDuration();
        } else {
            return getDurationInMilliseconds() == timespan.getDurationInMilliseconds();
        }
    }

    /**
     * @param baseMilliseconds
     *     the starting point to compute the future time
     *
     * @return the absolute time in milliseconds (since jan 01 1970) represented
     * {@code baseMilliseconds} + this timespan
     */
    public long futureTimeMillis(long baseMilliseconds) {
        return baseMilliseconds + getDurationInMilliseconds();
    }

    /**
     * @param baseMillis
     *     the starting point
     *
     * @return baseMillis - this timespan
     */
    public long pastTimeMillis(long baseMillis) {
        return baseMillis - getDurationInMilliseconds();
    }

    /**
     * @param baseDate
     *     base date to offset from
     *
     * @return return the date which is baseDate + value of this timespan
     */
    public Date futureDate(Date baseDate) {
        return new Date(baseDate.getTime() + getDurationInMilliseconds());
    }

    /**
     * @param baseDate
     *     base date to offset from
     *
     * @return return the date which is baseDate - value of this timespan
     */
    public Date pastDate(Date baseDate) {
        return new Date(pastTimeMillis(baseDate.getTime()));
    }

    /**
     * Expresses the provided duration in the unit provided. Note that the timespan returned
     * represent only the truncated version of the duration: if duration is 1002ms and timeunit
     * is seconds, then the timespan returned is 1 second... leaving behind 2ms.
     *
     * @return the timespan
     */
    private static Timespan truncateDurationToUnit(long durationInMillis, TimeUnit timeUnit) {
        Timespan res;

        if (durationInMillis >= timeUnit.getMillisecondsCount()) {
            res = new Timespan(durationInMillis / timeUnit.getMillisecondsCount(),
                timeUnit);
        } else {
            res = ZERO_TIMESPANS.get(timeUnit);
        }

        return res;
    }

    /**
     * @return a string representation of the object.
     */
    @Override
    public String toString() {
        return getCanonicalString();
    }

    /**
     * Creates a timespan from a list of other timespans.
     *
     * @return a timespan representing the sum of all the timespans provided
     */
    public static Timespan create(Timespan... timespans) {
        if (timespans == null) {
            return null;
        }

        if (timespans.length == 0) {
            return ZERO_MILLISECONDS;
        }

        Timespan res = timespans[0];

        for (int i = 1; i < timespans.length; i++) {
            Timespan timespan = timespans[i];
            res = res.add(timespan);
        }

        return res;
    }

    /**
     * Synonym.
     *
     * @see #parseTimespan(String)
     */
    public static Timespan parse(String timespan) {
        return parseTimespan(timespan);
    }

    /**
     * Synonym.
     *
     * @see #parseTimespan(String)
     */
    public static Timespan valueOf(String timespan) {
        return parseTimespan(timespan);
    }

    /**
     * Convenient call when providing milliseconds
     *
     * @return the timespan
     */
    public static Timespan milliseconds(long milliseconds) {
        return new Timespan(milliseconds);
    }

    /**
     * Convenient call when providing seconds
     *
     * @return the timespan
     */
    public static Timespan seconds(long seconds) {
        return new Timespan(seconds, TimeUnit.SECOND);
    }

    /**
     * Convenient call when providing minutes
     *
     * @return the timespan
     */
    public static Timespan minutes(long minutes) {
        return new Timespan(minutes, TimeUnit.MINUTE);
    }

    /**
     * Parses the provided string as a timespan. It should follow the pattern returned by
     * {@link #getCanonicalString()}. Example: 10m30s
     *
     * @return the timespan to parse
     *
     * @throws IllegalArgumentException
     *     if the string is not valid
     */
    public static Timespan parseTimespan(String timespan) {
        if (timespan == null) {
            return null;
        }

        // easiest way to be compliant with docker-compose format
        timespan = timespan.replace("ms", "");

        int len = timespan.length();
        if (len == 0) {
            return ZERO_MILLISECONDS;
        }

        int count = 0;
        int timeUnitOrderIdx = 0;
        int timeUnitOrderLen = TIME_UNIT_ORDER.length;
        Timespan[] timespans = new Timespan[timeUnitOrderLen];

        int startDigitsIdx = 0;
        boolean expectingDigits = true;

        for (int i = 0; i < len; i++) {
            char c = timespan.charAt(i);
            if (isDigit(c)) {
                expectingDigits = false;
                continue;
            }

            if (expectingDigits) {
                throw new IllegalArgumentException("found " + c + " was expecting a digit");
            }

            for (; timeUnitOrderIdx < timeUnitOrderLen; timeUnitOrderIdx++) {
                TimeUnit timeUnit = TIME_UNIT_ORDER[timeUnitOrderIdx];
                String displayChar = timeUnit.getDisplayChar();
                if (displayChar.length() == 0) {
                    throw new IllegalArgumentException("found nothing was expecting: " + c);
                }
                if (c == displayChar.charAt(0)) {
                    try {
                        long duration = Long.parseLong(timespan.substring(startDigitsIdx, i));
                        timespans[timeUnitOrderIdx++] = new Timespan(duration, timeUnit);
                        startDigitsIdx = i + 1;
                        expectingDigits = true;
                        count++;
                        break;
                    } catch (NumberFormatException e) {
                        throw new IllegalArgumentException(e);
                    }
                }
            }
        }

        if (startDigitsIdx < len) {
            try {
                long duration = Long.parseLong(timespan.substring(startDigitsIdx, len));
                timespans[timeUnitOrderLen - 1] = new Timespan(duration, TimeUnit.MILLISECOND);
                count++;
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(e);
            }
        }

        Timespan[] ts = new Timespan[count];
        for (int i = 0, idx = 0; i < timespans.length; i++) {
            Timespan t = timespans[i];
            if (t != null) {
                ts[idx++] = t;
            }
        }
        return create(ts);
    }

    private static boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }

    /**
     * Shortcut for creating a timespan and then retrieving the value in milliseconds.
     *
     * @param timespan
     *     the timespan as a string
     *
     * @return the value in milliseconds
     */
    public static long toMilliseconds(String timespan) {
        return parseTimespan(timespan).getDurationInMilliseconds();
    }
}


text:
package no.kantega.publishing.admin.model;

/**
 * Indicates if the items on the clipboard are sent to the clipboard by a clip-action or a copy-action.
 */
public enum ClipboardStatus {
    CLIPPED, COPIED
}


text:
<BroadcastMonitor>
  <updated>2015-08-03T14:10:14</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-03T14:09:10</startTime>
    <itemId>1000080509:0</itemId>
    <titleId>216138701</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** OPENER ZMOR</titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode>833</CategoryCode>
    <CategoryName>BEDJES</CategoryName>
    <itemDuration>214</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-03T14:12:45</startTime>
    <itemId>1000080509:1240922</itemId>
    <titleId>216032098</titleId>
    <itemCode>2024037</itemCode>
    <itemReference>2024037</itemReference>
    <titleName>Cold Shoulder</titleName>
    <artistName>Adele</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>190</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
/**
 *
 */
package org.socraticgrid.hl7.services.uc.functional;

import static org.junit.Assert.*;

import org.junit.Ignore;
import org.junit.Test;
import org.socraticgrid.hl7.services.uc.functional.UCSProperties.PROPS;

/**
 * @author steven
 * @created Jan 22, 2014

 */
public class UCSProperties_test {

	@Ignore
	@Test
	public void test() {
		//tests reading the junit property in ucs.properties
		String junitProp = UCSProperties.getProperty(PROPS.JUNIT);
		assertEquals("test-property", junitProp);
	}

}