text:
<!doctype html>

    <meta charset="utf-8">

    <title>Version Control Systems</title>

    <meta name="description"
          content="My presentation about version control systems for databases university course">
    <meta name="author" content="Oleksandr Kovalchuk">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style"
          content="black-translucent">

    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

    <link rel="stylesheet" href="css/reveal.css">
    <link rel="stylesheet" href="css/custom.css">
    <link rel="stylesheet" href="css/theme/black.css" id="theme">

    <link rel="stylesheet" href="lib/css/zenburn.css">

VCS

Three letters that can change your life

Why do I talk about this?

Meet main characters

This is a story with a few characters. Let meet them!

Cthulhu The Cute

Twilight The Gentoo Pony

Shadow The Gamer

Once upon a time in R'lyeh Programming University...

Shadow played games the whole semester. At the end of the
                    semester he had to do a lot of tasks but he did not know
                    how.

So he asked Twilight for help

And then the terrible thing happened

Cute Cthulhu's wise words:

So why do I talk about this?

Because...

Sharing source code as attachments in social networks is like
                    using stone instruments nowadays

Because...

Version control systems simplify software development

Especially when several people work on the
                    same code together

Because...

It is vital to programmer to know how to use version control
                    systems

Boring part

What is Version Control System?

“
                    Version control is a system that records changes to a
                    file or set of files over time so that you can recall
                    specific versions later.”

                “
                    Version control, also known as revision control or
                    source control, is the management of changes to
                    documents, computer programs, large web sites, and other
                    collections of information.” — Wikipedia

Goals of VCS

Allow
                        developers to work simultaneously.

Do not
                        overwrite each other's changes.

                        Maintain history of every version of everything.

VCS classification

Centralized version control systems (CVCS)

Distributed version control systems (DVCS)

Centralized VCS

There is a single “central” copy of your project
                    somewhere, and programmers commit their changes to this
                    central copy.

CVCS Workflow

Pull down any changes other people have made from the
                        central server.

Make your changes, and make sure they work properly.

Commit your changes to the central server, so other
                        programmers can see them.

Distributed VCS

Do not necessarily rely on a central server
                    to store all the versions of a project's files.

Every developer clones a copy of a
                    repository and has the full history of the project on their
                    own hard drive

Advantages over CVCS

Faster

Nobody sees unfinished work

Less dependent on Internet

Performing actions other than
                            pushing and pulling changesets is extremely fast
                            because the tool only needs to access the hard
                            drive, not a remote server.

                            Committing new changesets can be
                            done locally
                            without anyone else seeing them. Once you have a
                            group of changesets ready, you can push all of them
                            at once.

                            Everything but pushing and pulling can
                            be done without an internet connection. So you can
                            work on a plane, and you won't be forced to commit
                            several bugfixes as one big changeset.

Version Control Systems

                    About 46 VCS exist now
                    (https://goo.gl/imTGhs)

The most popular VCS

Subversion

Git

Mercurial

Interesting part

Hello, git!

Initialize an empty repository

                git init

Add files

                git add

Commit changes

                git commit

What is your status?

                git status

Local history

                git log

Branches
git branch

Switch working tree
git
                checkout

Get it together
git merge

Put one onto another
git
                rebase

Working in team

Remotes
git remote add <name> <address>

Send commits to remote
git push <remote>
                <branch>

Update from remote

                git fetch <remote>

                git pull <remote>

What to read next?

Git

Git documentation

Atlassian tutorials about git

Git in 15 minutes

Git tree planting

What to do if you messed your Git repository

Mercurial

Mercurial official website

Great Mercurial tutorial

Comparison of Git and Mercurial

Working qwith bookmarks

Presentation by
                Oleksandr Kovalchuk

The end

Any questions?


text:
/**
 * @file load_impl.hpp
 * @author Ryan Curtin
 *
 * Implementation of templatized load() function defined in load.hpp.
 *
 * This file is part of mlpack 2.0.1.
 *
 * mlpack is free software; you may redstribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef __MLPACK_CORE_DATA_LOAD_IMPL_HPP
#define __MLPACK_CORE_DATA_LOAD_IMPL_HPP

// In case it hasn't already been included.
#include "load.hpp"
#include "extension.hpp"

#include <algorithm>
#include <mlpack/core/util/timers.hpp>

#include <boost/serialization/serialization.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>

#include "serialization_shim.hpp"

#include "load_arff.hpp"

namespace mlpack {
namespace data {

template<typename eT>
bool inline inplace_transpose(arma::Mat<eT>& X)
{
  try
  {
    X = arma::trans(X);
    return false;
  }
  catch (std::bad_alloc& exception)
  {
#if (ARMA_VERSION_MAJOR >= 4) || \
    ((ARMA_VERSION_MAJOR == 3) && (ARMA_VERSION_MINOR >= 930))
    arma::inplace_trans(X, "lowmem");
    return true;
#else
    Log::Fatal << "data::Load(): inplace_trans() is only available on Armadillo"
        << " 3.930 or higher. Ran out of memory to transpose matrix."
        << std::endl;
    return false;
#endif
  }
}

template<typename eT>
bool Load(const std::string& filename,
          arma::Mat<eT>& matrix,
          const bool fatal,
          const bool transpose)
{
  Timer::Start("loading_data");

  // Get the extension.
  std::string extension = Extension(filename);

  // Catch nonexistent files by opening the stream ourselves.
  std::fstream stream;
#ifdef  _WIN32 // Always open in binary mode on Windows.
  stream.open(filename.c_str(), std::fstream::in | std::fstream::binary);
#else
  stream.open(filename.c_str(), std::fstream::in);
#endif
  if (!stream.is_open())
  {
    Timer::Stop("loading_data");
    if (fatal)
      Log::Fatal << "Cannot open file '" << filename << "'. " << std::endl;
    else
      Log::Warn << "Cannot open file '" << filename << "'; load failed."
          << std::endl;

    return false;
  }

  bool unknownType = false;
  arma::file_type loadType;
  std::string stringType;

  if (extension == "csv" || extension == "tsv")
  {
    loadType = arma::diskio::guess_file_type(stream);
    if (loadType == arma::csv_ascii)
    {
      if (extension == "tsv")
        Log::Warn << "'" << filename << "' is comma-separated, not "
            "tab-separated!" << std::endl;
      stringType = "CSV data";
    }
    else if (loadType == arma::raw_ascii) // .csv file can be tsv.
    {
      if (extension == "csv")
      {
        // We should issue a warning, but we don't want to issue the warning if
        // there is only one column in the CSV (since there will be no commas
        // anyway, and it will be detected as arma::raw_ascii).
        const std::streampos pos = stream.tellg();
        std::string line;
        std::getline(stream, line, '\n');
        boost::trim(line);

        // Reset stream position.
        stream.seekg(pos);

        // If there are no spaces or whitespace in the line, then we shouldn't
        // print the warning.
        if ((line.find(' ') != std::string::npos) ||
            (line.find('\t') != std::string::npos))
        {
          Log::Warn << "'" << filename << "' is not a standard csv file."
              << std::endl;
        }
      }
      stringType = "raw ASCII formatted data";
    }
    else
    {
      unknownType = true;
      loadType = arma::raw_binary; // Won't be used; prevent a warning.
      stringType = "";
    }
  }
  else if (extension == "txt")
  {
    // This could be raw ASCII or Armadillo ASCII (ASCII with size header).
    // We'll let Armadillo do its guessing (although we have to check if it is
    // arma_ascii ourselves) and see what we come up with.

    // This is taken from load_auto_detect() in diskio_meat.hpp
    const std::string ARMA_MAT_TXT = "ARMA_MAT_TXT";
    char* rawHeader = new char[ARMA_MAT_TXT.length() + 1];
    std::streampos pos = stream.tellg();

    stream.read(rawHeader, std::streamsize(ARMA_MAT_TXT.length()));
    rawHeader[ARMA_MAT_TXT.length()] = '\0';
    stream.clear();
    stream.seekg(pos); // Reset stream position after peeking.

    if (std::string(rawHeader) == ARMA_MAT_TXT)
    {
      loadType = arma::arma_ascii;
      stringType = "Armadillo ASCII formatted data";
    }
    else // It's not arma_ascii.  Now we let Armadillo guess.
    {
      loadType = arma::diskio::guess_file_type(stream);

      if (loadType == arma::raw_ascii) // Raw ASCII (space-separated).
        stringType = "raw ASCII formatted data";
      else if (loadType == arma::csv_ascii) // CSV can be .txt too.
        stringType = "CSV data";
      else // Unknown .txt... we will throw an error.
        unknownType = true;
    }

    delete[] rawHeader;
  }
  else if (extension == "bin")
  {
    // This could be raw binary or Armadillo binary (binary with header).  We
    // will check to see if it is Armadillo binary.
    const std::string ARMA_MAT_BIN = "ARMA_MAT_BIN";
    char *rawHeader = new char[ARMA_MAT_BIN.length() + 1];

    std::streampos pos = stream.tellg();

    stream.read(rawHeader, std::streamsize(ARMA_MAT_BIN.length()));
    rawHeader[ARMA_MAT_BIN.length()] = '\0';
    stream.clear();
    stream.seekg(pos); // Reset stream position after peeking.

    if (std::string(rawHeader) == ARMA_MAT_BIN)
    {
      stringType = "Armadillo binary formatted data";
      loadType = arma::arma_binary;
    }
    else // We can only assume it's raw binary.
    {
      stringType = "raw binary formatted data";
      loadType = arma::raw_binary;
    }

    delete[] rawHeader;
  }
  else if (extension == "pgm")
  {
    loadType = arma::pgm_binary;
    stringType = "PGM data";
  }
  else if (extension == "h5" || extension == "hdf5" || extension == "hdf" ||
           extension == "he5")
  {
#ifdef ARMA_USE_HDF5
    loadType = arma::hdf5_binary;
    stringType = "HDF5 data";
  #if ARMA_VERSION_MAJOR == 4 && \
      (ARMA_VERSION_MINOR >= 300 && ARMA_VERSION_MINOR <= 400)
    Timer::Stop("loading_data");
    if (fatal)
      Log::Fatal << "Attempted to load '" << filename << "' as HDF5 data, but "
          << "Armadillo 4.300.0 through Armadillo 4.400.1 are known to have "
          << "bugs and one of these versions is in use.  Load failed."
          << std::endl;
    else
      Log::Warn << "Attempted to load '" << filename << "' as HDF5 data, but "
          << "Armadillo 4.300.0 through Armadillo 4.400.1 are known to have "
          << "bugs and one of these versions is in use.  Load failed."
          << std::endl;

    return false;
  #endif
#else
    Timer::Stop("loading_data");
    if (fatal)
      Log::Fatal << "Attempted to load '" << filename << "' as HDF5 data, but "
          << "Armadillo was compiled without HDF5 support.  Load failed."
          << std::endl;
    else
      Log::Warn << "Attempted to load '" << filename << "' as HDF5 data, but "
          << "Armadillo was compiled without HDF5 support.  Load failed."
          << std::endl;

    return false;
#endif
  }
  else // Unknown extension...
  {
    unknownType = true;
    loadType = arma::raw_binary; // Won't be used; prevent a warning.
    stringType = "";
  }

  // Provide error if we don't know the type.
  if (unknownType)
  {
    Timer::Stop("loading_data");
    if (fatal)
      Log::Fatal << "Unable to detect type of '" << filename << "'; "
          << "incorrect extension?" << std::endl;
    else
      Log::Warn << "Unable to detect type of '" << filename << "'; load failed."
          << " Incorrect extension?" << std::endl;

    return false;
  }

  // Try to load the file; but if it's raw_binary, it could be a problem.
  if (loadType == arma::raw_binary)
    Log::Warn << "Loading '" << filename << "' as " << stringType << "; "
        << "but this may not be the actual filetype!" << std::endl;
  else
    Log::Info << "Loading '" << filename << "' as " << stringType << ".  "
        << std::flush;

  const bool success = matrix.load(stream, loadType);

  if (!success)
  {
    Log::Info << std::endl;
    Timer::Stop("loading_data");
    if (fatal)
      Log::Fatal << "Loading from '" << filename << "' failed." << std::endl;
    else
      Log::Warn << "Loading from '" << filename << "' failed." << std::endl;

    return false;
  }
  else
    Log::Info << "Size is " << (transpose ? matrix.n_cols : matrix.n_rows)
        << " x " << (transpose ? matrix.n_rows : matrix.n_cols) << ".\n";

  // Now transpose the matrix, if necessary.
  if (transpose)
  {
    inplace_transpose(matrix);
  }

  Timer::Stop("loading_data");

  // Finally, return the success indicator.
  return success;
}

// Load with mappings.  Unfortunately we have to implement this ourselves.
template<typename eT>
bool Load(const std::string& filename,
          arma::Mat<eT>& matrix,
          DatasetInfo& info,
          const bool fatal,
          const bool transpose)
{
  // Get the extension and load as necessary.
  Timer::Start("loading_data");

  // Get the extension.
  std::string extension = Extension(filename);

  // Catch nonexistent files by opening the stream ourselves.
  std::fstream stream;
  stream.open(filename.c_str(), std::fstream::in);

  if (!stream.is_open())
  {
    Timer::Stop("loading_data");
    if (fatal)
      Log::Fatal << "Cannot open file '" << filename << "'. " << std::endl;
    else
      Log::Warn << "Cannot open file '" << filename << "'; load failed."
          << std::endl;

    return false;
  }

  if (extension == "csv" || extension == "tsv" || extension == "txt")
  {
    // True if we're looking for commas; if false, we're looking for spaces.
    bool commas = (extension == "csv");

    std::string type;
    if (extension == "csv")
      type = "CSV data";
    else
      type = "raw ASCII-formatted data";

    Log::Info << "Loading '" << filename << "' as " << type << ".  "
        << std::flush;
    std::string separators;
    if (commas)
      separators = ",";
    else
      separators = " \t";

    // We'll load this as CSV (or CSV with spaces or tabs) according to
    // RFC4180.  So the first thing to do is determine the size of the matrix.
    std::string buffer;
    size_t cols = 0;

    std::getline(stream, buffer, '\n');
    // Count commas and whitespace in the line, ignoring anything inside
    // quotes.
    typedef boost::tokenizer<boost::escaped_list_separator<char>> Tokenizer;
    boost::escaped_list_separator<char> sep("\\", separators, "\"");
    Tokenizer tok(buffer, sep);
    for (Tokenizer::iterator i = tok.begin(); i != tok.end(); ++i)
      ++cols;

    // Now count the number of lines in the file.  We've already counted the
    // first one.
    size_t rows = 1;
    while (!stream.eof() && !stream.bad() && !stream.fail())
    {
      std::getline(stream, buffer, '\n');
      if (!stream.fail())
        ++rows;
    }

    // Now we have the size.  So resize our matrix.
    if (transpose)
    {
      matrix.set_size(cols, rows);
      info = DatasetInfo(cols);
    }
    else
    {
      matrix.set_size(rows, cols);
      info = DatasetInfo(rows);
    }

    stream.close();
    stream.open(filename, std::fstream::in);

    // Extract line by line.
    std::stringstream token;
    size_t row = 0;
    while (!stream.bad() && !stream.fail() && !stream.eof())
    {
      std::getline(stream, buffer, '\n');

      // Look at each token.  Unfortunately we have to do this character by
      // character, because things may be escaped in quotes.
      Tokenizer lineTok(buffer, sep);
      size_t col = 0;
      for (Tokenizer::iterator it = lineTok.begin(); it != lineTok.end(); ++it)
      {
        // Attempt to extract as type eT.  If that fails, we'll assume it's a
        // string and map it (which may involve retroactively mapping everything
        // we've seen so far).
        token.clear();
        token.str(*it);

        eT val = eT(0);
        token >> val;

        if (token.fail())
        {
          // Conversion failed; but it may be a NaN or inf.  Armadillo has
          // convenient functions to check.
          if (!arma::diskio::convert_naninf(val, token.str()))
          {
            // We need to perform a mapping.
            const size_t dim = (transpose) ? col : row;
            if (info.Type(dim) == Datatype::numeric)
            {
              // We must map everything we have seen up to this point and change
              // the values in the matrix.
              if (transpose)
              {
                // Whatever we've seen so far has successfully mapped to an eT.
                // So we need to print it back to a string.  We'll use
                // Armadillo's functionality for that.
                for (size_t i = 0; i < row; ++i)
                {
                  std::stringstream sstr;
                  arma::arma_ostream::print_elem(sstr, matrix.at(i, col),
                      false);
                  eT newVal = info.MapString(sstr.str(), col);
                  matrix.at(i, col) = newVal;
                }
              }
              else
              {
                for (size_t i = 0; i < col; ++i)
                {
                  std::stringstream sstr;
                  arma::arma_ostream::print_elem(sstr, matrix.at(row, i),
                      false);
                  eT newVal = info.MapString(sstr.str(), row);
                  matrix.at(row, i) = newVal;
                }
              }
            }

            // Strip whitespace from either side of the string.
            std::string trimmedToken(token.str());
            boost::trim(trimmedToken);
            val = info.MapString(trimmedToken, dim);
          }
        }

        if (transpose)
          matrix(col, row) = val;
        else
          matrix(row, col) = val;

        ++col;
      }

      ++row;
    }
  }
  else if (extension == "arff")
  {
    Log::Info << "Loading '" << filename << "' as ARFF dataset.  "
        << std::flush;
    try
    {
      LoadARFF(filename, matrix, info);

      // We transpose by default.  So, un-transpose if necessary...
      if (!transpose)
        inplace_transpose(matrix);
    }
    catch (std::exception& e)
    {
      if (fatal)
        Log::Fatal << e.what() << std::endl;
      else
        Log::Warn << e.what() << std::endl;
    }
  }
  else
  {
    // The type is unknown.
    Timer::Stop("loading_data");
    if (fatal)
      Log::Fatal << "Unable to detect type of '" << filename << "'; "
          << "incorrect extension?" << std::endl;
    else
      Log::Warn << "Unable to detect type of '" << filename << "'; load failed."
          << " Incorrect extension?" << std::endl;

    return false;
  }

  Log::Info << "Size is " << (transpose ? matrix.n_cols : matrix.n_rows)
      << " x " << (transpose ? matrix.n_rows : matrix.n_cols) << ".\n";

  Timer::Stop("loading_data");

  return true;
}

// Load a model from file.
template<typename T>
bool Load(const std::string& filename,
          const std::string& name,
          T& t,
          const bool fatal,
          format f)
{
  if (f == format::autodetect)
  {
    std::string extension = Extension(filename);

    if (extension == "xml")
      f = format::xml;
    else if (extension == "bin")
      f = format::binary;
    else if (extension == "txt")
      f = format::text;
    else
    {
      if (fatal)
        Log::Fatal << "Unable to detect type of '" << filename << "'; incorrect"
            << " extension?" << std::endl;
      else
        Log::Warn << "Unable to detect type of '" << filename << "'; load "
            << "failed.  Incorrect extension?" << std::endl;

      return false;
    }
  }

  // Now load the given format.
  std::ifstream ifs;
#ifdef _WIN32 // Open non-text in binary mode on Windows.
  if (f == format::binary)
    ifs.open(filename, std::ifstream::in | std::ifstream::binary);
  else
    ifs.open(filename, std::ifstream::in);
#else
  ifs.open(filename, std::ifstream::in);
#endif

  if (!ifs.is_open())
  {
    if (fatal)
      Log::Fatal << "Unable to open file '" << filename << "' to load object '"
          << name << "'." << std::endl;
    else
      Log::Warn << "Unable to open file '" << filename << "' to load object '"
          << name << "'." << std::endl;

    return false;
  }

  try
  {
    if (f == format::xml)
    {
      boost::archive::xml_iarchive ar(ifs);
      ar >> CreateNVP(t, name);
    }
    else if (f == format::text)
    {
      boost::archive::text_iarchive ar(ifs);
      ar >> CreateNVP(t, name);
    }
    else if (f == format::binary)
    {
      boost::archive::binary_iarchive ar(ifs);
      ar >> CreateNVP(t, name);
    }

    return true;
  }
  catch (boost::archive::archive_exception& e)
  {
    if (fatal)
      Log::Fatal << e.what() << std::endl;
    else
      Log::Warn << e.what() << std::endl;

    return false;
  }
}

} // namespace data
} // namespace mlpack

#endif

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using com.celigo.net.ServiceManager.SuiteTalk;
#if CLR_2_0
using Celigo.Linq;
#else
using System.Linq;
#endif

namespace Celigo.ServiceManager.Utility.Search
{
    /// <summary>
    /// A dictionary of Custom Fields indexed by the Internal IDs of the fields.
    /// </summary>
    public partial class SearchColumnCustomFieldDictionary : IDictionary<string, SearchColumnCustomField>
    {
        private readonly SearchColumnCustomField[] _customFields;
        private readonly Dictionary<string, SearchColumnCustomField> _dictionary;
        private bool _requiresInit;

        /// <summary>
        /// Initializes a new instance of the <see cref="SearchColumnCustomFieldDictionary"/> class.
        /// </summary>
        public SearchColumnCustomFieldDictionary() : this(null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SearchColumnCustomFieldDictionary"/> class.
        /// </summary>
        /// <param name="customFields">The custom fields.</param>
        public SearchColumnCustomFieldDictionary(SearchColumnCustomField[] customFields)
        {
            _customFields = customFields;
            if (null != customFields)
            {
                _dictionary = new Dictionary<string, SearchColumnCustomField>(customFields.Length);
                _requiresInit = true;
            }
            else
            {
                _dictionary = new Dictionary<string, SearchColumnCustomField>();
                _requiresInit = false;
            }
        }

        private void Initialize()
        {
            if (_requiresInit)
                lock (_dictionary)
                    if (_requiresInit)
                    {
                        for (int i = _customFields.Length - 1; i >= 0; i--)
                            if (_customFields[i] != null)
                            {
                                _dictionary[_customFields[i].GetInternalId()] = _customFields[i];
                            }
                        _requiresInit = false;
                    }
        }

        /// <summary>
        /// Returns an array of Custom Fields contained in the dictionary.
        /// </summary>
        /// <returns>An array of Custom Fields</returns>
        public SearchColumnCustomField[] ToArray()
        {
            if (_requiresInit)
                return _customFields;
            else
            {
#if CLR_2_0
                return Extensions.ToArray(_dictionary);
#else
                return _dictionary.Values.ToArray();
#endif
            }
        }

        /// <summary>
        /// Gets the field with the given Id.
        /// </summary>
        /// <typeparam name="T">The Type of the custom field.</typeparam>
        /// <param name="fieldId">The field id.</param>
        /// <returns></returns>
        public T GetCustomField<T>(string fieldId) where T: SearchColumnCustomField
        {
            return this[fieldId] as T;
        }

        /// <summary>
        /// Adds the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public void Add(string key, SearchColumnCustomField value)
        {
            _dictionary[key] = value;
        }

        /// <summary>
        /// Determines whether the specified key contains key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>
        /// 	<c>true</c> if the specified key contains key; otherwise, <c>false</c>.
        /// </returns>
        public bool ContainsKey(string key)
        {
            if (_requiresInit)
                Initialize();
            return _dictionary.ContainsKey(key);
        }

        /// <summary>
        /// Gets the keys.
        /// </summary>
        /// <value>The keys.</value>
        public ICollection<string> Keys
        {
            get
            {
                if (_requiresInit)
                    Initialize();
                return _dictionary.Keys;
            }
        }

        /// <summary>
        /// Removes the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            if (_requiresInit)
                Initialize();
            return _dictionary.Remove(key);
        }

        /// <summary>
        /// Tries the get value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public bool TryGetValue(string key, out SearchColumnCustomField value)
        {
            if (_requiresInit)
                Initialize();
            return _dictionary.TryGetValue(key, out value);
        }

        /// <summary>
        /// Gets the values.
        /// </summary>
        /// <value>The values.</value>
        public ICollection<SearchColumnCustomField> Values
        {
            get
            {
                if (_requiresInit)
                    Initialize();
                return _dictionary.Values;
            }
        }

        /// <summary>
        /// Gets or sets the <see cref="com.celigo.net.ServiceManager.SuiteTalk.SearchColumnCustomField"/> with the specified key.
        /// </summary>
        /// <value></value>
        public SearchColumnCustomField this[string key]
        {
            get
            {
                if (_requiresInit)
                    Initialize();
                return _dictionary[key];
            }
            set
            {
                if (_requiresInit)
                    Initialize();
                _dictionary[key] = value;
            }
        }

        /// <summary>
        /// Adds the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        public void Add(KeyValuePair<string, SearchColumnCustomField> item)
        {
            if (_requiresInit)
                Initialize();
            _dictionary.Add(item.Key, item.Value);
        }

        /// <summary>
        /// Clears this instance.
        /// </summary>
        public void Clear()
        {
            _dictionary.Clear();
        }

        /// <summary>
        /// Determines whether [contains] [the specified item].
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns>
        /// 	<c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
        /// </returns>
        public bool Contains(KeyValuePair<string, SearchColumnCustomField> item)
        {
            if (_requiresInit)
                Initialize();
            return _dictionary.ContainsKey(item.Key);
        }

        /// <summary>
        /// Copies to.
        /// </summary>
        /// <param name="array">The array.</param>
        /// <param name="arrayIndex">Index of the array.</param>
        public void CopyTo(KeyValuePair<string, SearchColumnCustomField>[] array, int arrayIndex)
        {
            if (_requiresInit)
                Initialize();

            var itr = _dictionary.GetEnumerator();
            for (int i = arrayIndex; i < array.Length; i++)
            {
                itr.MoveNext();
                array[i] = itr.Current;
            }
        }

        /// <summary>
        /// Gets the count.
        /// </summary>
        /// <value>The count.</value>
        public int Count
        {
            get
            {
                if (_requiresInit)
                    return _customFields.Length;
                else
                    return _dictionary.Count;
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is read only.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is read only; otherwise, <c>false</c>.
        /// </value>
        public bool IsReadOnly
        {
            get { return false; }
        }

        /// <summary>
        /// Removes the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public bool Remove(KeyValuePair<string, SearchColumnCustomField> item)
        {
            if (_requiresInit)
                Initialize();
            return _dictionary.Remove(item.Key);
        }

        /// <summary>
        /// Gets the enumerator.
        /// </summary>
        /// <returns></returns>
        public IEnumerator<KeyValuePair<string, SearchColumnCustomField>> GetEnumerator()
        {
            if (_requiresInit)
                Initialize();
            return _dictionary.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles(): iterable
    {
        return [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Umpirsky\I18nRoutingBundle\UmpirskyI18nRoutingBundle(),
        ];
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
package com.github.amlewis.graphy.core;

import org.junit.Test;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import static org.junit.Assert.*;

/**
 * Created by amlewis on 7/16/15.
 */
public class ValueNodeTest {
  @Test
  public void setValueBeforeSink() throws ExecutionException, InterruptedException {
    final ValueNode<Integer> valueNode = new ValueNode<Integer>();
    valueNode.setValue(5);
    assertEquals(5, Graphy.sinkFirstResult(valueNode).intValue());
  }

  @Test
  public void setValueAfterSink() throws ExecutionException, InterruptedException {
    final ValueNode<Integer> valueNode = new ValueNode<Integer>();
    final Future<Integer> sinkFuture = Graphy.sinkFirstResultFuture(valueNode);
    valueNode.setValue(5);
    assertEquals(5, sinkFuture.get().intValue());
  }

  @Test
  public void valueNodeUpdatesShouldBeOrdered() {
    final int NUM_SETS = 1000;
    final ValueNode<Integer> valueNode = new ValueNode<Integer>();
    BlockingDeque<NodeResult<Integer>> sink = Graphy.sinkToBlockingDeque(valueNode, NUM_SETS);

    for (int i = 1; i <= NUM_SETS; ++i) {
      valueNode.setValue(i);
    }

    for (int i=0; i<10; ++i) {
      if (sink.peekLast() == null || sink.peekLast().getResult() == null || sink.peekLast().getResult().intValue() != NUM_SETS) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      } else {
        break;
      }
    }

    if (sink.peekLast().getResult() == null || sink.peekLast().getResult().intValue() != NUM_SETS) {
      fail("Final value of NUM_SETS is not last message in Queue after 1 second!");
    }

    Integer prev = null;
    for (NodeResult<Integer> result : sink) {
      assertNotNull("NodeResult must not be null!", result);
      assertNotNull("NodeResult.getResult must not be null!", result.getResult());
      Integer current = result.getResult();
      if (prev != null) {
        assertTrue("Previous Result should be less than the Current!", prev.intValue() < current.intValue());
      }
      prev = current;
    }
  }

  @Test
  public void valueExceptionBackAndForthTest() throws InterruptedException {
    final ValueNode<Integer> valueNode = new ValueNode<Integer>();
    BlockingDeque<NodeResult<Integer>> sink = Graphy.sinkToBlockingDeque(valueNode, 1);

    valueNode.setValue(5);
    assertEquals(5, sink.take().getResult().intValue());

    Exception exception1 = new Exception();
    valueNode.setValue(exception1);
    assertEquals(exception1, sink.take().getException());

    valueNode.setValue(6);
    assertEquals(6, sink.take().getResult().intValue());

    Exception exception2 = new Exception();
    valueNode.setValue(exception2);
    assertEquals(exception2, sink.take().getException());
  }
}


text:
'use strict';

const RSVP = require('rsvp');

const app = require('../app');

const {
  getFileDir,
  isScratchPaper
} = require('../utils');

const {
  checkLoading,
  setPath
} = require('./helpers');

const get = require('./ajax/get');

const loadDataAndCode = (dir) => {
  return RSVP.hash({
    data: get(`${dir}data.js`),
    code: get(`${dir}code.js`)
  });
};

const loadFileAndUpdateContent = (dir) => {
  app.getEditor().clearContent();

  return loadDataAndCode(dir).then((content) => {
    app.updateCachedFile(dir, content);
    app.getEditor().setContent(content);
  });
};

const cachedContentExists = (cachedFile) => {
  return cachedFile &&
    cachedFile.data !== undefined &&
    cachedFile.code !== undefined;
};

module.exports = (category, algorithm, file, explanation) => {
  return new RSVP.Promise((resolve, reject) => {
    if (checkLoading()) {
      reject();
    } else {
      if (isScratchPaper(category)) {
        setPath(category, app.getLoadedScratch());
      } else {
        setPath(category, algorithm, file);
      }
      $('#explanation').html(explanation);

      let dir = getFileDir(category, algorithm, file);
      app.setLastFileUsed(dir);
      const cachedFile = app.getCachedFile(dir);

      if (cachedContentExists(cachedFile)) {
        app.getEditor().setContent(cachedFile);
        resolve();
      } else {
        loadFileAndUpdateContent(dir).then(resolve, reject);
      }
    }
  });
};


text:
MyTokenWallet is a high security fork of MyEtherWallet! Let me call it
the paranoid version of MyEtherWallet.

## What is the benefit of MyTokenWallet vs MyEtherWallet?

* We have added many
  [security features](../Security_and_Privacy_tests_and_results.md) to
  our servers! (You are welcome to hack them)
* more than [40 new features](../New_Features_on_MyTokenWallet.md)
* more privacy by the features above
* more security by the techniques above
* security warnings from time to time
* pure offline mode
* prevent copy and past when online!
* we research every day for your security and try to hack our self to
  find the holes!
* and many other things more. Read the docs [DOCS-TOC](DOCS-TOC.md)

***

## What is the goal of MyTokenWallet against MyEtherWallet?

| No. | MyEtherWallet                      | MyTokenWallet                                      |
|:----|:-----------------------------------|:---------------------------------------------------|
| 1   | Adding every day new tokens        | researching every day to protect our users         |
| 2   | collecting money to add new tokens | pray that no one is copy and past his private keys |

## What are the next security steps for MyTokenWallet?

| No. | Date / since | goLive         | ToDo                                              | Done            |
|:----|:-------------|:---------------|:--------------------------------------------------|:----------------|
| 1   | 2017-July    | 2017-December  | Convert MyTokenWallet into an trusted offline app | [ ] in progress |
| 2   | 2017-July    | 2017-August    | App for Apple OSX                                 | [ ] in progress |
| 3   | 2017-July    | 2017-November  | App for Mircosoft Windows                         | [ ] in progress |
| 4   | 2017-July    | 2017-September | App for Ubuntu, Debian and other Linux OS's       | [ ] in progress |
| 5   | 2017-June    | 2018 Q1        | Java-Card for creating new wallets like Nitrokey  | [ ] in progress |

***
[back to TOC](DOCS-TOC.md)


text:
class Scheduler {
  public:
    Scheduler();			// Initialize list of ready threads
    ~Scheduler();			// De-allocate ready list

    void ReadyToRun(Thread* thread);	// Thread can be dispatched.
    Thread* FindNextToRun();		// Dequeue first thread on the ready
					// list, if any, and return thread.
    void Run(Thread* nextThread);	// Cause nextThread to start running
    void Print();			// Print contents of ready list

    void Move(Thread* t, int p);

  private:
    List<Thread*>* readyList[MAX_PRIORITY];  		// queue of threads that are ready to run,
					// but not running
};

#endif // SCHEDULER_H


text:
require 'spec_helper'

module WysiwygDocs
  describe DocsController do

    describe "GET 'index'" do
      it "returns http success" do
        get 'index'
        response.should be_success
      end
    end

  end
end


text:
import django.core.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('sponsors', '0079_index_to_force_singleton'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='sponsorshipcurrentyear',
            options={'verbose_name': 'Active Year', 'verbose_name_plural': 'Active Year'},
        ),
        migrations.AlterField(
            model_name='sponsorshipcurrentyear',
            name='year',
            field=models.PositiveIntegerField(help_text='Every new sponsorship application will be considered as an application from to the active year.', validators=[django.core.validators.MinValueValidator(limit_value=2022, message='The min year value is 2022.'), django.core.validators.MaxValueValidator(limit_value=2050, message='The max year value is 2050.')]),
        ),
    ]


text:
package server

type database struct {
	Name   string
	Tables []*table // This might not be a good idea. A linked-list might be better.
}

func (db *database) CreateTable(name string, numCols int) *table {
	tbl := &table{name, numCols, make([]*column, numCols), 0}
	db.Tables = append(db.Tables, tbl)

	return tbl
}

func (db *database) Table(name string) *table {
	for _, t := range db.Tables {
		if t.Name == name {
			return t
		}
	}

	// Unable to find table.
	return nil
}

func CreateDatabase(name string) *database {
	return &database{name, make([]*table, 0)}
}


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

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:showIn="@layout/appwidget">

    <TextView
        android:id="@+id/title"
        android:text="@string/app_name"
        style="@style/TextAppearance.AppCompat.Subhead"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAllCaps="true"
        android:padding="@dimen/padding"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/subtitle"
        android:layout_toStartOf="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="RtlSymmetry"
        tools:targetApi="ice_cream_sandwich"/>

    <TextView
        android:id="@id/subtitle"
        android:text="@string/loading_text"
        tools:text="Last updated"
        style="@style/TextAppearance.AppCompat.Caption"
        android:gravity="center_vertical"
        android:layout_alignTop="@id/title"
        android:layout_alignBottom="@id/title"
        android:layout_toLeftOf="@+id/button_refresh"
        android:layout_toStartOf="@+id/button_refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="RtlSymmetry"/>

    <ImageButton
        android:id="@id/button_refresh"
        android:contentDescription="@string/refresh"
        android:layout_alignTop="@id/title"
        android:layout_alignBottom="@id/subtitle"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:scaleType="center"
        android:src="@drawable/ic_refresh_white_24dp"
        style="@style/Widget.AppCompat.Button.Borderless"
        app:tint="?android:attr/colorForeground"
        android:minWidth="0dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <ImageView
        android:id="@id/divider"
        android:background="?android:attr/listDivider"
        android:layout_below="@id/subtitle"
        android:layout_width="match_parent"
        android:layout_height="@dimen/divider"
        tools:ignore="ContentDescription"/>

    <ListView
        android:id="@android:id/list"
        android:layout_below="@id/divider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@id/empty"
        style="@style/TextAppearance.AppCompat.Headline"
        android:padding="@dimen/padding"
        android:text="@string/loading_text"
        android:layout_below="@id/subtitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</merge>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Set maximum parallel threads</title>

eio_set_max_idle

eio_set_max_poll_reqs

Eio Functions

PHP Manual

eio_set_max_parallel

(PECL eio >= 0.0.1dev)

eio_set_max_parallel — Set maximum parallel threads

Description

   void eio_set_max_parallel
    ( int $nthreads
   )

Parameters

nthreads

     Number of parallel threads

Return Values

  No value is returned.

See Also

eio_set_min_parallel

eio_set_max_idle

eio_set_max_poll_reqs

Eio Functions

PHP Manual


text:
@implementation ATCAnimatedTransitioningSquish

-(void)animateTransitionWithContext:(id<UIViewControllerContextTransitioning>)transitionContext
                 fromViewController:(UIViewController *)fromViewController
                   toViewController:(UIViewController *)toViewController
                           fromView:(UIView *)fromView
                             toView:(UIView *)toView {

    if ( self.isDismissal ) {
        [self animateDismissalWithContext:transitionContext fromViewController:fromViewController fromView:fromView toView:toView];
    } else {
        [self animatePresentationWithContext:transitionContext fromViewController:fromViewController fromView:fromView toView:toView];
    }

}

-(void)animateDismissalWithContext:(id<UIViewControllerContextTransitioning>)context
                fromViewController:(UIViewController *)fromViewController
                          fromView:(UIView *)fromView toView:(UIView *)toView {

    UIView *container = [context containerView];
    NSTimeInterval duration = [self transitionDuration:context];

    // Set up initial state
    [container addSubview:toView];
    fromView.hidden = YES;

    CGRect initialFrame = [context initialFrameForViewController:fromViewController];
    toView.frame = initialFrame;
    toView.alpha = 0.2f;
    CGAffineTransform transform = fromView.transform;
    CGRect originalFromViewFrame = fromView.frame;
    BOOL isSideways = NO;
    if ( !self.isPush ) {
        if ( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight ) {
            fromView.transform = CGAffineTransformIdentity;
            fromView.frame = CGRectMake(0, 0, originalFromViewFrame.size.height, originalFromViewFrame.size.width);

            isSideways = YES;
        }
    }

    UIView *snapshot = [fromView resizableSnapshotViewFromRect:fromView.frame  afterScreenUpdates:NO withCapInsets:UIEdgeInsetsZero];

    if ( isSideways ) {
        snapshot.frame = CGRectMake(0, 0, originalFromViewFrame.size.height, originalFromViewFrame.size.width);
        snapshot.layer.position = CGPointMake(CGRectGetMidX(originalFromViewFrame), CGRectGetMidY(originalFromViewFrame));
    }

    snapshot.transform = transform;
    [container addSubview:snapshot];

    [UIView animateKeyframesWithDuration:duration delay:0.0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{

        [UIView addKeyframeWithRelativeStartTime:0.0f relativeDuration:0.6f animations:^{
            toView.alpha = 0.6f;

            CGRect snapshotFrame = snapshot.frame;
            if ( isSideways ) {

                snapshotFrame.origin.y = CGRectGetMidY(initialFrame) - 5.0f;
                snapshotFrame.size.height = 10.0f;
                snapshot.frame = snapshotFrame;

            } else {

                snapshotFrame.origin.x = CGRectGetMidX(initialFrame) - 5.0f;
                snapshotFrame.size.width = 10.0f;
                snapshot.frame = snapshotFrame;

            }
        }];
        [UIView addKeyframeWithRelativeStartTime:0.6f relativeDuration:0.4f animations:^{
            CGRect snapshotFrame = snapshot.frame;

            if ( isSideways ) {
                snapshotFrame.origin.x = CGRectGetWidth(initialFrame);
                snapshotFrame.size.height = 5.0f;
                snapshot.frame = snapshotFrame;

            } else {
                snapshotFrame.origin.y = CGRectGetHeight(initialFrame);
                snapshotFrame.size.width = 5.0f;
                snapshot.frame = snapshotFrame;

            }

            toView.alpha = 1.0f;
        }];
    } completion:^(BOOL finished) {
        [fromView removeFromSuperview];
        [snapshot removeFromSuperview];
        [context completeTransition:![context transitionWasCancelled]];

    }];

}

-(void)animatePresentationWithContext:(id<UIViewControllerContextTransitioning>)context fromViewController:(UIViewController *)fromViewController fromView:(UIView *)fromView toView:(UIView *)toView {

    UIView *container = [context containerView];
    NSTimeInterval duration = [self transitionDuration:context];

    [container addSubview:toView];

    CGRect initialFrame = [context initialFrameForViewController:fromViewController];
    UIView *blackView = [[UIView alloc] initWithFrame:initialFrame];
    blackView.backgroundColor = [UIColor blackColor];
    UIView *snapshot = [toView resizableSnapshotViewFromRect:toView.frame  afterScreenUpdates:YES withCapInsets:UIEdgeInsetsZero];
    [container addSubview:snapshot];
    [container insertSubview:blackView belowSubview:fromView];
    [container sendSubviewToBack:toView];

    CGRect snapshotFrame = initialFrame;
    snapshotFrame.origin.y = CGRectGetHeight(initialFrame);
    snapshotFrame.origin.x = CGRectGetMidX(initialFrame);
    snapshotFrame.size.width = 10.0f;

    snapshot.frame = snapshotFrame;

    [UIView animateKeyframesWithDuration:duration delay:0.0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{

        [UIView addKeyframeWithRelativeStartTime:0.0f relativeDuration:0.6f animations:^{
            fromView.alpha = 0.7f;
            CGRect snapshotFrame = snapshot.frame;
            snapshotFrame.origin.y = 0.0f;
            snapshot.frame = snapshotFrame;
        }];
        [UIView addKeyframeWithRelativeStartTime:0.6f relativeDuration:0.3f animations:^{
            CGRect snapshotFrame = snapshot.frame;
            snapshotFrame.origin.x = 0.0f;
            snapshotFrame.size.width = CGRectGetWidth(initialFrame);
            snapshot.frame = snapshotFrame;
            fromView.alpha = 0.0f;

        }];
    } completion:^(BOOL finished) {
        [fromView removeFromSuperview];
        [snapshot removeFromSuperview];
        [blackView removeFromSuperview];
        toView.alpha = 1.0f;
        [context completeTransition:![context transitionWasCancelled]];

    }];

}

-(void)handlePanGesture:(UIPanGestureRecognizer *)recognizer inViewController:(UIViewController *)controller {

}

@end


text:
package de.tudarmstadt.ukp.dkpro.lab.task.impl;

import de.tudarmstadt.ukp.dkpro.lab.Lab;
import de.tudarmstadt.ukp.dkpro.lab.engine.ExecutionException;
import de.tudarmstadt.ukp.dkpro.lab.engine.TaskContext;
import de.tudarmstadt.ukp.dkpro.lab.engine.TaskExecutionEngine;
import de.tudarmstadt.ukp.dkpro.lab.engine.impl.DefaultTaskExecutionService;
import de.tudarmstadt.ukp.dkpro.lab.engine.impl.MultiThreadBatchTaskEngine;
import de.tudarmstadt.ukp.dkpro.lab.storage.impl.PropertiesAdapter;
import de.tudarmstadt.ukp.dkpro.lab.task.*;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;

import java.io.File;
import java.util.Map;
import java.util.Properties;

public class MultiThreadBatchTaskTest
{
    private Class<? extends TaskExecutionEngine> oldEngine;

    @Before
    public void setup()
    {
        File path = new File("target/repository/" + getClass().getSimpleName() + "/"
                + name.getMethodName());
        System.setProperty("DKPRO_HOME", path.getAbsolutePath());
        FileUtils.deleteQuietly(path);

        // Configure Lab to use MultiThreadBatchTaskEngine
        Lab lab = Lab.getInstance();
        oldEngine = ((DefaultTaskExecutionService) lab.getTaskExecutionService())
                .getEngine(BatchTask.class);
        ((DefaultTaskExecutionService) lab.getTaskExecutionService()).registerEngine(
                BatchTask.class, MultiThreadBatchTaskEngine.class);
        lab.setProperty(MultiThreadBatchTaskEngine.PROP_THREADS, "10");
    }

    @After
    public void teardown()
    {
        // Restore Lab to using default BatchTask engine
        Lab lab = Lab.getInstance();
        oldEngine = ((DefaultTaskExecutionService) lab.getTaskExecutionService())
                .getEngine(BatchTask.class);
        ((DefaultTaskExecutionService) lab.getTaskExecutionService()).registerEngine(
                BatchTask.class, oldEngine);
    }

    @Test(expected = ExecutionException.class)
    public void importTest()
            throws Exception
    {
        Task producer = new ExecutableTaskBase()
        {
            @Override
            public void execute(TaskContext aContext)
                    throws Exception
            {
                System.out.println("Running producer");

                Properties data = new Properties();
                data.setProperty("key", "value");

                aContext.storeBinary("DATA", new PropertiesAdapter(data));
            }
        };

        Task consumer = new ExecutableTaskBase()
        {
            @Override
            public void execute(TaskContext aContext)
                    throws Exception
            {
                System.out.println("Running consumer");

                Properties data = new Properties();
                aContext.retrieveBinary("DATA", new PropertiesAdapter(data));
                Assert.assertEquals(data.getProperty("key"), "value");
            }
        };

        consumer.addImport(producer, "DATA1", "DATA");

        DefaultBatchTask batch = new DefaultBatchTask();
        //                BatchTask batch = new BatchTask();
        batch.addTask(producer);
        batch.addTask(consumer);

        Lab.getInstance().run(batch);
    }

    @Test
    public void testNested()
            throws Exception
    {
        Dimension innerDim = Dimension.create("inner", "1", "2", "3");
        ParameterSpace innerPSpace = new ParameterSpace(innerDim);
        //        BatchTask innerTask = new BatchTask()
        DefaultBatchTask innerTask = new DefaultBatchTask()
        {
            @Override
            public void setConfiguration(Map<String, Object> aConfig)
            {
                super.setConfiguration(aConfig);
                System.out.printf("A %10d %s %s%n", this.hashCode(), getType(), aConfig);
            }
        };
        innerTask.setParameterSpace(innerPSpace);
        innerTask.addTask(new ConfigDumperTask1());

        Dimension outerDim = Dimension.create("outer", "1", "2", "3");
        ParameterSpace outerPSpace = new ParameterSpace(outerDim);
        //        BatchTask outerTask = new BatchTask()
        DefaultBatchTask outerTask = new DefaultBatchTask()
        {
            @Override
            public void setConfiguration(Map<String, Object> aConfig)
            {
                super.setConfiguration(aConfig);
                System.out.printf("B %10d %s %s%n", this.hashCode(), getType(), aConfig);
            }
        };
        outerTask.setParameterSpace(outerPSpace);
        outerTask.addTask(innerTask);
        outerTask.addTask(new ConfigDumperTask2());

        Lab.getInstance().run(outerTask);
    }

    @Test
    public void testNested2()
            throws Exception
    {
        //        BatchTask innerTask = new BatchTask()
        DefaultBatchTask innerTask = new DefaultBatchTask()
        {
            @Discriminator
            private Integer outer;

            @Override
            public ParameterSpace getParameterSpace()
            {
                // Dynamically configure parameter space of nested batch task
                Integer[] values = new Integer[outer];
                for (int i = 0; i < outer; i++) {
                    values[i] = i;
                }
                Dimension<Integer> innerDim = Dimension.create("inner", values);
                ParameterSpace innerPSpace = new ParameterSpace(innerDim);

                return innerPSpace;
            }

            @Override
            public void setConfiguration(Map<String, Object> aConfig)
            {
                super.setConfiguration(aConfig);
                System.out.printf("A %10d %s %s%n", this.hashCode(), getType(), aConfig);
            }
        };
        innerTask.addTask(new ConfigDumperTask1());

        Dimension<Integer> outerDim = Dimension.create("outer", 1, 2, 3);
        ParameterSpace outerPSpace = new ParameterSpace(outerDim);
        DefaultBatchTask outerTask = new DefaultBatchTask()
        {
            @Override
            public void setConfiguration(Map<String, Object> aConfig)
            {
                super.setConfiguration(aConfig);
                System.out.printf("B %10d %s %s%n", this.hashCode(), getType(), aConfig);
            }
        };
        outerTask.setParameterSpace(outerPSpace);
        outerTask.addTask(innerTask);
        outerTask.addTask(new ConfigDumperTask2());

        Lab.getInstance().run(outerTask);
    }

    @Test(expected = ExecutionException.class)
    public void testUnresolvable()
            throws Exception
    {
        Dimension<String> dim = Dimension.create("param", "1", "2", "3");

        ParameterSpace pSpace = new ParameterSpace(dim);

        Task task1 = new ExecutableTaskBase()
        {
            @Discriminator
            private String param;

            @Override
            public void execute(TaskContext aContext)
                    throws Exception
            {
                // Nothing to do
            }
        };

        Task task2 = new ExecutableTaskBase()
        {
            @Discriminator
            private String param;

            @Override
            public void execute(TaskContext aContext)
                    throws Exception
            {
                // Nothing to do
            }
        };

        task2.addImport(task1, "DUMMY");
        task1.addImport(task2, "DUMMY");

        DefaultBatchTask batchTask = new DefaultBatchTask();
        batchTask.setParameterSpace(pSpace);
        batchTask.addTask(task1);
        batchTask.addTask(task2);

        Lab.getInstance().run(batchTask);
    }

    public static class ConfigDumperTask1
            extends ExecutableTaskBase
            implements ConfigurationAware
    {
        @Discriminator
        private String inner;

        private Map<String, Object> config;

        @Override
        public void execute(TaskContext aContext)
                throws Exception
        {
            System.out.printf("C %10d %s %s%n", this.hashCode(), getType(), config);
        }

        @Override
        public void setConfiguration(Map<String, Object> aConfig)
        {
            config = aConfig;
        }
    }

    public static class ConfigDumperTask2
            extends ExecutableTaskBase
            implements ConfigurationAware
    {
        @Discriminator
        private String outer;

        private Map<String, Object> config;

        @Override
        public void execute(TaskContext aContext)
                throws Exception
        {
            System.out.printf("D %10d %s %s%n", this.hashCode(), getType(), config);
        }

        @Override
        public void setConfiguration(Map<String, Object> aConfig)
        {
            config = aConfig;
        }
    }

    @Rule
    public TestName name = new TestName();

    @Before
    public void printSeparator()
    {
        System.out.println("\n=== " + name.getMethodName() + " =====================");
    }
}


text:
local socket = require("socket")
client = socket.connect("google.com", 80)
client:send("GET /robots.txt HTTP/1.0\r\n\r\n")
while true do
	s, status, partial = client:receive(1024)
	print(s or partial)
	if status == "closed" then
		break
	end
end
client:close()


text:
package com.devicehive.messages.handler;

import com.google.gson.JsonElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.FutureTask;

public class RestHandlerCreator implements HandlerCreator {

    private static final Logger logger = LoggerFactory.getLogger(RestHandlerCreator.class);

    private final FutureTask<Void> futureTask;

    public RestHandlerCreator() {
        futureTask = new FutureTask<Void>(DUMMY_TASK, null);
    }

    public FutureTask<Void> getFutureTask() {
        return futureTask;
    }

    @Override
    public Runnable getHandler(final JsonElement message) {
        logger.debug("REST subscription notified");
        return futureTask;
    }

    private static final Runnable DUMMY_TASK = new Runnable() {
        @Override
        public void run() {
        }
    };
}


text:
#ifndef __TO_STR_H__
#define __TO_STR_H__

#include <glib.h>

#include "wsutil/nstime.h"
#include "time_fmt.h"
#include <epan/packet_info.h>
#include "ws_symbol_export.h"
#include "wmem/wmem.h"

#define GUID_STR_LEN 37
#define MAX_IP_STR_LEN 16
#define MAX_IP6_STR_LEN 40
#define MAX_ADDR_STR_LEN 256
#define VINES_ADDR_LEN	6
#define EUI64_STR_LEN 24

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/*
 * These are utility functions which convert various types to strings,
 * but for which no more specific module applies.
 */

struct     e_in6_addr;

WS_DLL_PUBLIC gchar* address_to_str(wmem_allocator_t *scope, const address *addr);
WS_DLL_PUBLIC gchar* ep_address_to_str(const address *);
WS_DLL_PUBLIC void     address_to_str_buf(const address *addr, gchar *buf, int buf_len);
WS_DLL_PUBLIC const gchar*	ether_to_str(const guint8 *);
WS_DLL_PUBLIC const gchar*	tvb_ether_to_str(tvbuff_t *tvb, const gint offset);
extern const gchar*   ax25_to_str(const guint8 *);
extern gchar*   get_ax25_name(const guint8 *);
WS_DLL_PUBLIC const gchar*	ip_to_str(const guint8 *);
WS_DLL_PUBLIC const gchar*	tvb_ip_to_str(tvbuff_t *tvb, const gint offset);
void	ip_to_str_buf(const guint8 *ad, gchar *buf, const int buf_len);
extern const gchar*	fc_to_str(const guint8 *);
extern gchar*	fcwwn_to_str (const guint8 *);
WS_DLL_PUBLIC const gchar*	tvb_fc_to_str(tvbuff_t *tvb, const gint offset);
WS_DLL_PUBLIC gchar*	tvb_fcwwn_to_str (tvbuff_t *tvb, const gint offset);
WS_DLL_PUBLIC const gchar*	ip6_to_str(const struct e_in6_addr *);
WS_DLL_PUBLIC const gchar*      ip6_guint8_to_str(const guint8 *ad);

WS_DLL_PUBLIC const gchar*	tvb_ip6_to_str(tvbuff_t *tvb, const gint offset);
void	ip6_to_str_buf(const struct e_in6_addr *, gchar *);
extern gchar*	ipx_addr_to_str(const guint32, const guint8 *);
extern gchar*	ipxnet_to_string(const guint8 *ad);
extern gchar*	tvb_ipxnet_to_string(tvbuff_t *tvb, const gint offset);
extern gchar*	ipxnet_to_str_punct(const guint32 ad, const char punct);
extern gchar*	tvb_vines_addr_to_str(tvbuff_t *tvb, const gint offset);
WS_DLL_PUBLIC gchar*	eui64_to_str(const guint64 ad);
WS_DLL_PUBLIC gchar*	tvb_eui64_to_str(tvbuff_t *tvb, const gint offset, const guint encoding);
WS_DLL_PUBLIC gchar*	time_secs_to_ep_str(const gint32 time_val);
gchar*	time_secs_to_ep_str_unsigned(const guint32);
WS_DLL_PUBLIC gchar*	time_msecs_to_ep_str(gint32 time_val);
WS_DLL_PUBLIC gchar*	abs_time_to_ep_str(const nstime_t*, const absolute_time_display_e fmt,
    gboolean show_zone);
WS_DLL_PUBLIC gchar*	abs_time_secs_to_ep_str(const time_t, const absolute_time_display_e fmt,
    gboolean show_zone);
WS_DLL_PUBLIC void	display_signed_time(gchar *, int, const gint32, gint32, const to_str_time_res_t);
WS_DLL_PUBLIC void	display_epoch_time(gchar *, int, const time_t,  gint32, const to_str_time_res_t);

extern void	guint32_to_str_buf(guint32 u, gchar *buf, int buf_len);

WS_DLL_PUBLIC gchar*	rel_time_to_ep_str(const nstime_t*);
WS_DLL_PUBLIC gchar*	rel_time_to_secs_ep_str(const nstime_t*);
WS_DLL_PUBLIC gchar*	guid_to_ep_str(const e_guid_t*);
gchar*	guid_to_str_buf(const e_guid_t*, gchar*, int);

WS_DLL_PUBLIC char *decode_bits_in_field(const guint bit_offset, const gint no_of_bits, const guint64 value);

WS_DLL_PUBLIC char	*other_decode_bitfield_value(char *buf, const guint32 val, const guint32 mask,
    const int width);
WS_DLL_PUBLIC char	*decode_bitfield_value(char *buf, const guint32 val, const guint32 mask,
    const int width);
WS_DLL_PUBLIC const char *decode_numeric_bitfield(const guint32 val, const guint32 mask, const int width,
    const char *fmt) G_GNUC_PRINTF(4, 0);

WS_DLL_PUBLIC const gchar* port_type_to_str (port_type type);

/** Turn an array of bytes into a string showing the bytes in hex.
 *
 * @param bd A pointer to the byte array
 * @param bd_len The length of the byte array
 * @return A pointer to the formatted string
 *
 * @see bytes_to_ep_str_punct()
 */
WS_DLL_PUBLIC gchar *bytes_to_ep_str(const guint8 *bd, int bd_len);

/** Turn an array of bytes into a string showing the bytes in hex,
 *  separated by a punctuation character.
 *
 * @param bd A pointer to the byte array
 * @param bd_len The length of the byte array
 * @param punct The punctuation character
 * @return A pointer to the formatted string
 *
 * @see bytes_to_ep_str()
 */
WS_DLL_PUBLIC gchar *bytes_to_ep_str_punct(const guint8 *bd, int bd_len, gchar punct);

/* Deprecated, use bytestring_to_str instead */
WS_DLL_PUBLIC const gchar *bytestring_to_ep_str(const guint8 *, const guint32, const char punct);

WS_DLL_PUBLIC const gchar *bytestring_to_str(wmem_allocator_t *scope, const guint8 *ad, const guint32 len, const char punct);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __TO_STR_H__  */


text:
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.application.arraydesign;

import gov.nih.nci.caarray.dao.ArrayDao;
import gov.nih.nci.caarray.dao.SearchDao;
import gov.nih.nci.caarray.domain.array.ArrayDesign;
import gov.nih.nci.caarray.domain.file.CaArrayFile;
import gov.nih.nci.caarray.domain.file.FileStatus;
import gov.nih.nci.caarray.platforms.spi.DesignFileHandler;
import gov.nih.nci.caarray.platforms.spi.PlatformFileReadException;
import gov.nih.nci.caarray.validation.FileValidationResult;
import gov.nih.nci.caarray.validation.InvalidNumberOfArgsException;
import gov.nih.nci.caarray.validation.ValidationMessage.Type;
import gov.nih.nci.caarray.validation.ValidationResult;

import java.util.HashSet;
import java.util.Set;

import com.google.inject.Inject;

/**
 * Helper class for performing various array design operations. Services as a facade for platform-specific
 * functionality.
 *
 * @author dkokotov
 */
@SuppressWarnings({ "PMD.CyclomaticComplexity" })
final class ArrayDesignPlatformFacade {
    private final Set<DesignFileHandler> handlers;
    private final ArrayDao arrayDao;
    private final SearchDao searchDao;

    /**
     * @param handlers
     */
    @Inject
    ArrayDesignPlatformFacade(ArrayDao arrayDao, SearchDao searchDao, Set<DesignFileHandler> handlers) {
        this.handlers = new HashSet<DesignFileHandler>(handlers);
        this.arrayDao = arrayDao;
        this.searchDao = searchDao;
    }

    private DesignFileHandler getHandler(Set<CaArrayFile> designFiles) throws PlatformFileReadException {
        for (final DesignFileHandler handler : this.handlers) {
            try {
                if (handler.openFiles(designFiles)) {
                    return handler;
                }
            } catch (final PlatformFileReadException e) {
                handler.closeFiles();
                throw e;
            }
        }
        throw new InvalidNumberOfArgsException(InvalidNumberOfArgsException.UNSUPPORTED_ARRAY_DESIGN);
    }

    @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity", "PMD.ExcessiveMethodLength" })
    ValidationResult validateDesignFiles(Set<CaArrayFile> designFiles) {
        final ValidationResult result = new ValidationResult();
        for (final CaArrayFile designFile : designFiles) {
            final FileValidationResult fileResult = new FileValidationResult();
            if (designFile.getType() == null) {
                designFile.setValidationResult(fileResult);
                fileResult.addMessage(Type.ERROR,
                        "Array design file type was unrecognized, please select a file format");
                result.addFile(designFile.getName(), fileResult);
            } else if (!designFile.getFileType().isArrayDesign()) {
                designFile.setValidationResult(fileResult);
                fileResult.addMessage(Type.ERROR, "File type " + designFile.getFileType().getName()
                        + " is not an array design type.");
                result.addFile(designFile.getName(), fileResult);
            }

        }

        FileStatus validatedStatus = FileStatus.VALIDATED;
        if (result.isValid()) {
            DesignFileHandler handler = null;
            try {
                handler = getHandler(designFiles);
                if (!handler.parsesData()) {
                    validatedStatus = FileStatus.VALIDATED_NOT_PARSED;
                }
                handler.validate(result);
            } catch (final PlatformFileReadException e) {
                final CaArrayFile firstDesignFile = designFiles.iterator().next();
                FileValidationResult fileResult = firstDesignFile.getValidationResult();
                if (fileResult == null) {
                    fileResult = new FileValidationResult();
                    firstDesignFile.setValidationResult(fileResult);
                }
                fileResult.addMessage(Type.ERROR, "Unable to read file");
                result.addFile(firstDesignFile.getName(), fileResult);
            } finally {
                if (handler != null) {
                    handler.closeFiles();
                }
            }
        }

        final FileStatus status = result.isValid() ? validatedStatus : FileStatus.VALIDATION_ERRORS;
        for (final CaArrayFile designFile : designFiles) {
            designFile.setFileStatus(status);
            this.arrayDao.save(designFile);
        }
        this.arrayDao.flushSession();

        return result;
    }

    @SuppressWarnings("PMD.AvoidReassigningParameters")
    void importDesignDetails(ArrayDesign arrayDesign) {
        DesignFileHandler handler = null;
        try {
            handler = getHandler(arrayDesign.getDesignFiles());
            handler.createDesignDetails(arrayDesign);
        } catch (final PlatformFileReadException e) {
            throw new IllegalStateException("Error importing design", e);
        } finally {
            if (handler != null) {
                handler.closeFiles();
            }
        }

        // the handler cleared the session, so we need to merge before we update the status
        // See hibernate bug http://opensource.atlassian.com/projects/hibernate/browse/HHH-511
        // When we upgrade to hibernate 3.2.4+, we can remove the call to merge.
        //commenting out as part of merging 2.4.1.x to trunk. Step 3.
        /*
        arrayDesign = (ArrayDesign) this.arrayDao.mergeObject(arrayDesign);
        arrayDesign.getDesignFileSet().updateStatus(
                arrayDesign.getDesignFiles().iterator().next().getFileType().isParsed() ? FileStatus.IMPORTED
                        : FileStatus.IMPORTED_NOT_PARSED);
         */
        arrayDesign = searchDao.retrieve(ArrayDesign.class, arrayDesign.getId());
        arrayDesign.getDesignFileSet().updateStatus(
                handler.parsesData() ? FileStatus.IMPORTED : FileStatus.IMPORTED_NOT_PARSED);
        this.arrayDao.save(arrayDesign);
    }

    void importDesign(ArrayDesign arrayDesign) {
        DesignFileHandler handler = null;
        try {
            handler = getHandler(arrayDesign.getDesignFiles());
            handler.load(arrayDesign);
        } catch (final PlatformFileReadException e) {
            throw new IllegalStateException("Error importing design", e);
        } finally {
            if (handler != null) {
                handler.closeFiles();
            }
        }
    }
}


text:
#pragma once
#include <aws/guardduty/GuardDuty_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace GuardDuty
{
namespace Model
{

  /**
   *
Contains details of the highest severity threat detected during scan and
   * number of infected files.

See Also:
   AWS
   * API Reference

   */
  class AWS_GUARDDUTY_API HighestSeverityThreatDetails
  {
  public:
    HighestSeverityThreatDetails();
    HighestSeverityThreatDetails(Aws::Utils::Json::JsonView jsonValue);
    HighestSeverityThreatDetails& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Severity level of the highest severity threat detected.

     */
    inline const Aws::String& GetSeverity() const{ return m_severity; }

    /**
     *
Severity level of the highest severity threat detected.

     */
    inline bool SeverityHasBeenSet() const { return m_severityHasBeenSet; }

    /**
     *
Severity level of the highest severity threat detected.

     */
    inline void SetSeverity(const Aws::String& value) { m_severityHasBeenSet = true; m_severity = value; }

    /**
     *
Severity level of the highest severity threat detected.

     */
    inline void SetSeverity(Aws::String&& value) { m_severityHasBeenSet = true; m_severity = std::move(value); }

    /**
     *
Severity level of the highest severity threat detected.

     */
    inline void SetSeverity(const char* value) { m_severityHasBeenSet = true; m_severity.assign(value); }

    /**
     *
Severity level of the highest severity threat detected.

     */
    inline HighestSeverityThreatDetails& WithSeverity(const Aws::String& value) { SetSeverity(value); return *this;}

    /**
     *
Severity level of the highest severity threat detected.

     */
    inline HighestSeverityThreatDetails& WithSeverity(Aws::String&& value) { SetSeverity(std::move(value)); return *this;}

    /**
     *
Severity level of the highest severity threat detected.

     */
    inline HighestSeverityThreatDetails& WithSeverity(const char* value) { SetSeverity(value); return *this;}

    /**
     *
Threat name of the highest severity threat detected as part of the malware
     * scan.

     */
    inline const Aws::String& GetThreatName() const{ return m_threatName; }

    /**
     *
Threat name of the highest severity threat detected as part of the malware
     * scan.

     */
    inline bool ThreatNameHasBeenSet() const { return m_threatNameHasBeenSet; }

    /**
     *
Threat name of the highest severity threat detected as part of the malware
     * scan.

     */
    inline void SetThreatName(const Aws::String& value) { m_threatNameHasBeenSet = true; m_threatName = value; }

    /**
     *
Threat name of the highest severity threat detected as part of the malware
     * scan.

     */
    inline void SetThreatName(Aws::String&& value) { m_threatNameHasBeenSet = true; m_threatName = std::move(value); }

    /**
     *
Threat name of the highest severity threat detected as part of the malware
     * scan.

     */
    inline void SetThreatName(const char* value) { m_threatNameHasBeenSet = true; m_threatName.assign(value); }

    /**
     *
Threat name of the highest severity threat detected as part of the malware
     * scan.

     */
    inline HighestSeverityThreatDetails& WithThreatName(const Aws::String& value) { SetThreatName(value); return *this;}

    /**
     *
Threat name of the highest severity threat detected as part of the malware
     * scan.

     */
    inline HighestSeverityThreatDetails& WithThreatName(Aws::String&& value) { SetThreatName(std::move(value)); return *this;}

    /**
     *
Threat name of the highest severity threat detected as part of the malware
     * scan.

     */
    inline HighestSeverityThreatDetails& WithThreatName(const char* value) { SetThreatName(value); return *this;}

    /**
     *
Total number of infected files with the highest severity threat detected.

     */
    inline int GetCount() const{ return m_count; }

    /**
     *
Total number of infected files with the highest severity threat detected.

     */
    inline bool CountHasBeenSet() const { return m_countHasBeenSet; }

    /**
     *
Total number of infected files with the highest severity threat detected.

     */
    inline void SetCount(int value) { m_countHasBeenSet = true; m_count = value; }

    /**
     *
Total number of infected files with the highest severity threat detected.

     */
    inline HighestSeverityThreatDetails& WithCount(int value) { SetCount(value); return *this;}

  private:

    Aws::String m_severity;
    bool m_severityHasBeenSet = false;

    Aws::String m_threatName;
    bool m_threatNameHasBeenSet = false;

    int m_count;
    bool m_countHasBeenSet = false;
  };

} // namespace Model
} // namespace GuardDuty
} // namespace Aws


text:
import SimpleMatcher from 'ember-cli-pact/-private/matcher/simple';
import TypeMatcher from 'ember-cli-pact/-private/matcher/type';
import RegexMatcher from 'ember-cli-pact/-private/matcher/regex';
import MultiMatcher from 'ember-cli-pact/-private/matcher/multi';
import SubpathMatcher from 'ember-cli-pact/-private/matcher/subpath';

export function type(options) {
  return new TypeMatcher('type', 2, options);
}

export function regex(regex) {
  return new RegexMatcher('regex', 2, regex);
}

export function equality() {
  return new SimpleMatcher('equality', 3, { match: 'equality' });
}

export function integer() {
  return new SimpleMatcher('integer', 3, { match: 'integer' });
}

export function decimal() {
  return new SimpleMatcher('decimal', 3, { match: 'decimal' });
}

export function allOf(matchers) {
  return new MultiMatcher('allOf', 2, undefined /* implicitly AND */, matchers);
}

export function anyOf(matchers) {
  return new MultiMatcher('anyOf', 2, 'OR', matchers);
}

export function arrayElements(object) {
  return new SubpathMatcher('arrayElements', 2, '[*]', object);
}

export function hashValues(object) {
  return new SubpathMatcher('hashValues', 2, '.*', object);
}


text:
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import java.io.*;

public class Translate {
	public static void main(String[] args) throws Exception {
		ANTLRInputStream input = new ANTLRInputStream(new FileInputStream("Expression.txt"));
		ArrayInitLexer lexer = new ArrayInitLexer(input);

		CommonTokenStream tokens = new CommonTokenStream(lexer);

		ArrayInitParser parser = new ArrayInitParser(tokens);
		ParseTree tree = parser.init();

		//parse tree walker
		ParseTreeWalker walker = new ParseTreeWalker();

		walker.walk(new ShortToUnicodeString(), tree);
		System.out.println();
	}
}


text:
/**
 *
 */

;
(function($, window, document, undefined) {
	var pluginName = "smsTemplateSettingPane";
	var defaults = {
		id : "",
		parent : "",
		entity : "",
		topparent : "",
		currowner : "",
	};

	var TemplateSettingPanel = function(element, options) {
		this.element = element;
		this.options = $.extend({
			id : "",
			parent : "",
			entity : "",
			topparent : "",
			currowner : "",
		}, defaults, options);
		this._defaults = defaults;
		this._name = pluginName;
		this.topparent = options.topparent;
		this.init(options);
	};

	TemplateSettingPanel.prototype.init = function(options) {
		this.entity = options.entity;
		if (this.entity.template != undefined)
			this.oldTempl = this.entity.template;
		else
			this.oldTempl = "";
		var modalframe = document.createElement("DIV");
		this.element.appendChild(modalframe);
		modalframe.style.margin = "2px";
		modalframe.className = "panel panel-default";

		var tpBodyDiv = document.createElement("div");
		modalframe.appendChild(tpBodyDiv);
		tpBodyDiv.className = "panel-body";

		var urlform = document.createElement("form");
		tpBodyDiv.appendChild(urlform);
		urlform.className = "form-horizontal";
		urlform.setAttribute("role", "form");

		var groupDiv = document.createElement("DIV");
		urlform.appendChild(groupDiv);
		groupDiv.className = "form-group";
		var urlLabel = document.createElement("label");
		groupDiv.appendChild(urlLabel);
		urlLabel.setAttribute("for", "urlvalue" + options.id);
		urlLabel.className = "col-sm-2 control-label";
		urlLabel.innerHTML = "短信模板列表";

		var smsSelDiv = document.createElement("DIV");
		smsSelDiv.className = "col-sm-10";
		groupDiv.appendChild(smsSelDiv);
		this.templateList = document.createElement("select");
		smsSelDiv.appendChild(this.templateList);
		this.templateList.className = "form-control";
		this.templateList.id = "stpl" + options.id;
		this.templateList.name = "stpl" + options.id;

		this.addOptions(this.templateList, "-请选择-", "-1", 0);

		this.templateList.addEventListener("change", this, false);

		var groupDiv1 = document.createElement("DIV");
		urlform.appendChild(groupDiv1);
		groupDiv1.className = "form-group";

		var tempDiv = document.createElement("DIV");
		tempDiv.className = "col-sm-12";
		groupDiv1.appendChild(tempDiv);
		this.templateEidtor = document.createElement("textarea");
		tempDiv.appendChild(this.templateEidtor);
		this.templateEidtor.className = "form-control";
		this.templateEidtor.id = "tempeditor" + options.id;
		this.templateEidtor.name = "tempeditor" + options.id;
		this.templateEidtor.setAttribute("rows", "10");

		this.loadingData(this.entity);
	};

	TemplateSettingPanel.prototype.loadingData = function(entity) {
		if (this.options.currowner instanceof WfProcess) {
			this.templateList.disabled = false;
			this.templateEidtor.disabled = false;
		} else {
			this.templateList.disabled = true;
			this.templateEidtor.disabled = true;
		}

		var that = this;
		$("#progressbar").show();
		$.getJSON(service.api(33, entity.owner), {}).complete(function(data) {
			if (data != undefined && data.responseJSON != undefined) {
				that.loadData(entity, data.responseJSON);
			}
			$("#progressbar").hide();
		});
	};

	// entity is EmailSendingTask in wfprocess
	TemplateSettingPanel.prototype.loadData = function(entity, templates) {
		$(this.templateList).find('option').remove();
		this.templates = [];
		this.addOptions(this.templateList, "-请选择-", "-1", 0);
		if (templates != null && templates.length > 0) {
			for (var i = 0; i < templates.length; i++) {
				this.templates[i] = new SMSTemplate();
				this.templates[i].parse(templates[i]);
				this.addOptions(this.templateList, this.templates[i].name,
						this.templates[i].id, i + 1);
			}
			if (entity.templateId != undefined) {
				this.templateList.value = entity.templateId;
			}
		}
		this.templateEidtor.value = entity.template;
	};

	TemplateSettingPanel.prototype.addOptions = function(parent, title, value,
			index) {
		var option = document.createElement("option");
		option.text = title;
		option.value = value;
		parent.options.add(option, index);
	};

	TemplateSettingPanel.prototype.handleEvent = function(e) {
		switch (e.type) {
		case "change":
			this.doChange(e);
			break;
		}
	};

	TemplateSettingPanel.prototype.doChange = function(evt) {
		if (evt.target == this.templateEidtor) {
			var newvalue = $(this.templateEidtor).val();
			if (newvalue != this.oldTempl) {
				map[this.options.currowner.id].stack
						.execute(new PMValueChangedCmd(this.entity, "template",
								newvalue, this.options.currowner));
			}
		} else if (evt.target == this.templateList) {
			if (this.templateList.value != "-1") {
				for (var i = 0; i < this.templates.length; i++) {
					if (this.templates[i].id == this.templateList.value) {
						map[this.options.currowner.id].stack
								.execute(new PMSMSTemplateChangedCmd(
										this.entity, this.templates[i],
										this.options.currowner));
						break;
					}
				}
			}
		}
	};

	$.fn[pluginName] = function(options) {
		return this.each(function() {
			if (!$.data(this, pluginName)) {
				$.data(this, pluginName,
						new TemplateSettingPanel(this, options));
			} else if ($.isFunction(Plugin.prototype[options])) {
				$.data(this, pluginName)[options]();
			}
		});
	};

})(jQuery, window, document);


text:
class pComplex
{
public:
	double real_, imag_;

	// zero constructor
	pComplex()
	{
		real_ = 0;
		imag_ = 0;
	}

	// initialization constructor
	pComplex(double real, double imag)
	{
		real_ = real;
		imag_ = imag;
	}

	 // copy constructor
	pComplex(const pComplex &copy)
	{
		real_ = copy.real_;
		imag_ = copy.imag_;
	}

	const pComplex& operator=(const pComplex &rhs) //assignment
	{
		real_ = rhs.real_;
		imag_ = rhs.imag_;

		return *this;
	}

	const pComplex& operator+=(const pComplex &rhs)
	{
		real_ += rhs.real_;
		imag_ += rhs.imag_;

		return *this;
	}

	const pComplex& operator-=(const pComplex &rhs)
	{
		real_ -= rhs.real_;
		imag_ -= rhs.imag_;

		return *this;
	}

	const pComplex& operator*=(const pComplex &rhs)
	{
		double a = real_;
		double b = imag_;
		double c = rhs.real_;
		double d = rhs.imag_;

		double newR = a * c - b * d;
		double newI = b * c + a * d;

		real_= newR;
		imag_ = newI;

		return *this;
	}

	const pComplex& operator*=(double scale)
	{
		real_ *= scale;
		imag_ *= scale;

		return *this;
	}

	const pComplex& operator/=(double scale)
	{
		real_ /= scale;
		imag_ /= scale;

		return *this;
	}

	bool operator==(const pComplex &rhs) const
	{
		return real_ == rhs.real_ && imag_ == rhs.imag_;
	}

	bool operator!=(const pComplex &rhs) const
	{
		return real_ != rhs.real_ || imag_ != rhs.imag_;
	}

	pComplex operator+(const pComplex &rhs) const
	{
		return pComplex(real_ + rhs.real_, imag_ + rhs.imag_);
	}

	pComplex operator-(const pComplex &rhs) const
	{
		return pComplex(real_ - rhs.real_, imag_ - rhs.imag_);
	}

	pComplex operator+(const double r) const
	{
		return pComplex(real_ + r, imag_);
	}

	pComplex operator-(const double r) const
	{
		return pComplex(real_ - r, imag_);
	}

	pComplex operator-() const
	{
		return pComplex(-real_, -imag_);
	}

	friend pComplex operator*(const pComplex &v, double scale)
	{
		return pComplex(v.real_*scale, v.imag_*scale);
	}

	friend pComplex operator*(const pComplex &u, const pComplex &v)
	{
		double a = u.real_;
		double b = u.imag_;
		double c = v.real_;
		double d = v.imag_;

		return pComplex(a * c - b * d, b * c + a * d);
	}

	friend pComplex operator/(const pComplex &u, const pComplex &v)
	{
		double a = u.real_;
		double b = u.imag_;
		double c = v.real_;
		double d = v.imag_;

		return pComplex(a * c - b * d, b * c + a * d);
	}

	friend pComplex operator*(double scale, const pComplex &v)
	{
		return pComplex(v.real_*scale, v.imag_*scale);
	}

	friend pComplex operator/(const pComplex &v, double scale)
	{
		return pComplex(v.real_/scale, v.imag_/scale);
	}

	double mag() const
	{
		return sqrt(real_*real_ + imag_*imag_);
	}

	double magSquared() const
	{
		return real_*real_ + imag_*imag_;
	}

	double phase() const
	{
		double theta = atan2(imag_, real_);
		if( theta < 0 ) theta += 2 * M_PI;
		return theta;
	}

	const pComplex& normalize()
	{
		double l = mag();
		real_ /= l;
		imag_ /= l;

		return *this;
	}

	friend std::ostream& operator<<(std::ostream& out, const pComplex &v)
	{
		out << "[" << v.real_ << ", " << v.imag_ << "]";
		return out;
	}
};


text:
<resources>
    <string name="app_name">BuildVariants</string>
</resources>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Imagination
{
	public static class Singleton<T> where T : class
	{
		private static volatile T _Instance;
		private static object _Lock = new object();

		static Singleton()
		{
			lock (_Lock)
			{
                Type type = typeof(T);
				try
				{
					ConstructorInfo ci = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null);
					if (ci == null)
					{
#if !SILVERLIGHT
                        ApplicationEventLog.WriteEntry("Flow", string.Format("Invoke Error: GetConstructor returned null for type {0} .", type.Name), System.Diagnostics.EventLogEntryType.Error);
#endif
#if DEBUG
						System.Diagnostics.Debugger.Break();
#endif
					}
					else
					{
						_Instance = (T)ci.Invoke(new object[0]);
                    }
				}
				catch (Exception ex)
				{
#if !SILVERLIGHT
					ApplicationEventLog.WriteEntry("Flow", string.Format("Invoke Error for type: {0}\n{1}", type.Name, ex), System.Diagnostics.EventLogEntryType.Error);
#endif
#if DEBUG
					System.Diagnostics.Debugger.Break();
#endif
				}
			}
		}

		/// <summary>
		/// Returns the only instance of the specified Bll generic type T
		/// </summary>
		public static T Instance
		{
			get { return _Instance; }
		}
	}
}


text:
#import <UIKit/UIActivity.h>

#import "UIStateRestoring-Protocol.h"

@class MFMailComposeViewController, NSString;

@interface UIMailActivity : UIActivity <UIStateRestoring>
{
    _Bool _keyboardVisible;
    _Bool _sourceIsManaged;
    _Bool _hasAnyAccount;
    _Bool _hasFilteredAccount;
    NSString *_autosaveIdentifier;
    MFMailComposeViewController *_mailComposeViewController;
}

+ (long long)activityCategory;
@property(retain, nonatomic) MFMailComposeViewController *mailComposeViewController; // @synthesize mailComposeViewController=_mailComposeViewController;
@property(nonatomic) _Bool hasFilteredAccount; // @synthesize hasFilteredAccount=_hasFilteredAccount;
@property(nonatomic) _Bool hasAnyAccount; // @synthesize hasAnyAccount=_hasAnyAccount;
@property(retain, nonatomic) NSString *autosaveIdentifier; // @synthesize autosaveIdentifier=_autosaveIdentifier;
@property(nonatomic) _Bool sourceIsManaged; // @synthesize sourceIsManaged=_sourceIsManaged;
@property(nonatomic) _Bool keyboardVisible; // @synthesize keyboardVisible=_keyboardVisible;
- (void)decodeRestorableStateWithCoder:(id)arg1;
- (void)encodeRestorableStateWithCoder:(id)arg1;
- (void)_cleanup;
- (void)mailComposeController:(id)arg1 didFinishWithResult:(int)arg2 error:(id)arg3;
- (void)setSubject:(id)arg1;
- (id)activityViewController;
- (void)_setSubject:(id)arg1;
- (void)prepareWithActivityItems:(id)arg1;
- (_Bool)canPerformWithActivityItems:(id)arg1;
- (void)autosaveWithHandler:(id)arg1;
- (_Bool)_restoreDraft;
- (id)_stateRestorationDraftIsAvailable;
- (void)_deleteMailDraftIdentifierRestorationArchive:(id)arg1;
- (void)_saveDraft:(id)arg1;
- (id)_mailDraftRestorationURL;
- (id)activityTitle;
- (id)_activityImage;
- (id)activityType;
- (void)dealloc;
- (id)init;

// Remaining properties
@property(readonly, nonatomic) Class objectRestorationClass;
@property(readonly, nonatomic) id <UIStateRestoring> restorationParent;

@end


text:
layout: default
title: Inclusive Research and Design
permalink: /events/2016/inclusive-research-and-design/
---

{% assign currentEvent = page.title %}

<div class="event-container">
    {% include partial-event-large.html %}
</div>


text:
package com.twitter.finagle.zookeeper

import com.twitter.conversions.time._
import com.twitter.io.TempDirectory.create
import com.twitter.finagle.common.zookeeper.ZooKeeperClient
import com.twitter.zk.ServerCnxnFactory
import java.net.{InetAddress, InetSocketAddress}
import org.apache.zookeeper.server.ZooKeeperServer

class ZkInstance {
  var connectionFactory: ServerCnxnFactory = null
  var zookeeperServer: ZooKeeperServer = null
  var zookeeperClient: ZooKeeperClient = null
  var started = false

  lazy val zookeeperAddress = {
    if (!started) throw new IllegalStateException("can't get address until instance is started")
    new InetSocketAddress(zookeeperServer.getClientPort)
  }

  lazy val zookeeperConnectString =
    zookeeperAddress.getHostName() + ":" + zookeeperAddress.getPort()

  def start() {
    started = true

    zookeeperServer = new ZooKeeperServer(
      create(),
      create(),
      ZooKeeperServer.DEFAULT_TICK_TIME)
    zookeeperServer.setMaxSessionTimeout(100)
    zookeeperServer.setMinSessionTimeout(100)
    connectionFactory = ServerCnxnFactory(InetAddress.getLoopbackAddress)
    connectionFactory.startup(zookeeperServer)
    zookeeperClient = new ZooKeeperClient(10.milliseconds, zookeeperAddress)

    // Disable noise from zookeeper logger
//    java.util.logging.LogManager.getLogManager().reset();
  }

  def stop() {
    connectionFactory.shutdown()
    zookeeperClient.close()
  }
}