text:
android2po
==========

Convert Android string resources to gettext .po files, and import them
right back.

The goal is to remove as many syntax elements required by the Android
string resource files when exporting, to present the text to translators
in as easy a format as possible; and correctly writing everything back
to Android on import while keeping the generated XML files easily
readable as well (i.e. no unnecessary escaping).

Requirements
------------

The following Python modules are required, but will mostly be
auto-installed. See ``Installation`` below.

babel >= 1.0dev (only the dev version has support for contexts)
    http://babel.edgewall.org/

lxml
    http://codespeak.net/lxml/

argparse
    http://argparse.googlecode.com/

Since the .po files this script generates use contexts (``msgctx``),
that's what you're gettext software will have to support as well.

Installation
------------

To install the current release, you can simply do:

    $ easy_install android2po

That's it!

If you want to install the current development version of
``android2po`` instead, get the source code, then run:

    $ python setup.py install

``setup.py`` should automatically install all the dependencies.
Alternatively, you can also use pip if you prefer:

    $ pip install -r requirements.pip

Note: The development version of Babel is required, which isn't
straighforward to install, so both the ``setup.py`` file and the
``requirements.pip`` file link to a custom distribution I made for
android2po. If you prefer to install the babel SVN version
yourself, you need to follow the instructions on this page:

    http://babel.edgewall.org/wiki/SubversionCheckout

Usage
~~~~~

The basic idea is that:

* ``values/strings.xml`` holds the reference strings in their
  original language (the gettext ``msgid`` fields).

* The gettext .po files generated and updated by this script contain
  the reference version of the translations.

* The ``values-XX/strings.xml`` files are fully generated based on
  your ``.po`` files, and should not be modified manually.

In addition to your authoritative strings.xml file, you will usually
also want to keep your .po files in source control; The generated
language-specific ``strings.xml`` files then contain no additional
information, and do not need to be source controlled, though you are
free to if you like.

The environment
~~~~~~~~~~~~~~~

To be able to run, the script necessarily needs to know about two
filesystem locations: The directory where your Android resources are
located, and the directory where the gettext .po files should be stored:

    $ a2po --android myproject/res --gettext myproject/locale COMMAND

However, to simplify usage, the program will automatically try to
detect the location of these folders, as follows:

* It will search the directory hierarchy, starting with the your working
  directory, for a ``AndroidManifest.xml`` or ``.android2po`` file.
* As soon as it finds either of those files, it will stop, and consider
  the it's location the **project directory**.
* Unless explicitly overriden by you, it will place the .po files in
  a subdirectory ``./locale`` of that project directory.
* Only if a ``AndroidManifest.xml`` file is in the project directory
  will it assume that the Android resources are located in a subfolder
  named ``./res``.
* If a ``.android2po`` file is in the project directory, it automatically
  will be loaded as a configuration file. See the section below on the
  format of the configuration file, and possible values.
* The script automatically processes all the languages it can find. It
  will normally look at the existing .po files to determine the list of
  languages, with the exception of the ``init`` command, in which case
  the list of languages inside the Android resource directory will be
  used.

Initial setup
~~~~~~~~~~~~~

When switching to ``android2po``, you will first want to create an
initial export of your current translations.

    $ a2po init

This will ignore any languages for which a ``.po`` file already exists.

For testing purposes, you may want to immediately import the generated
files back in, to compare with what you originally had, and make sure
the script was able to process your files correctly.
At this point, make sure you have a backup, since your language-specific
``strings.xml`` files are going to be replaced (you are using source
control, right?!)::

    $ a2po import
    $ git diff --ignore-all-space res/values-XX/strings.xml

In the example above, ``git`` is used for source control. ``git``
provides a nice option to show a diff while ignoring whitespace
changes, which will make it much easier to spot problems with the
import. If you use a different tool, see if there is a comparable
feature.

Hopefully, your translated XML files at this point hold the same
information as before. The whitespace will probably have changed,
comments will have been removed, and some strings may have changed
visually (i.e. use different escaping). However, their *meaning*
should not have changed. If it has, please report a bug.

Updating
~~~~~~~~

After hacking on your code for a while, you have changed some
strings (in your authoritative ``values/strings.xml`` file), and now
you need to pass those on to your translators through your .po files.

Simply do:

    $ a2po export

This will update your ``.po files`` with your changes.

Importing
~~~~~~~~~

Your translators have come back to you with their changes, and you
want to include them in the next build. Simply do:

    $ a2po import

This will fully regenerate your language-specific ``strings.xml``
based on the gettext ``.po`` files.

You can do this step manually, or add it to your build process.

Adding a new language
~~~~~~~~~~~~~~~~~~~~~

As noted above, ``android2po`` will automatically process all the
languages it can find, based on the .po files that exist. To add a
new language, simply run

    $ a2po init {LANGUAGE CODES}

For example:

    $ a2po init de fr

This will create both new .po and strings.xml files for German and French.

You are also free to simply create the appropriate ``strings.xml`` files
yourself, and let

    $ a2po init

initialize their proper .po counterparts (in case of the ``init`` command,
the languages found in the Android resource directory will be processed).

Configuration file
~~~~~~~~~~~~~~~~~~

A configuration file can be used to avoid manually specifying all the
required options. The format of the file is simply a list of command
line option, each specified on a line of it's own. For example::

    --no-template
    # Paths - don't specify --android, default location is used.
    --gettext ../locale

As you can see, comments are supported by using ``#``, and the mechanism
to automatically try to detect the directories for .po files and Android
``strings.xml`` files is still in place if you don't specify locations
explicitly.

The configuration file may be specified by using the ``--config`` option.
Alternatively, if a ``.android2po`` file is found in the project directory,
it will be used.

See ``--help`` for a list of possible configuration options. There's also
an example configuration file in ``example.config`` that you can have a
look at, or use as a template for your own.

Notes
-----

Initially based on:
    http://code.google.com/p/openintents/source/browse/tools/Androidxml2po/androidxml2po.bash

Links of interest:
~~~~~~~~~~~~~~~~~~

http://www.gnu.org/software/hello/manual/gettext/PO-Files.html
    GNU PO file format docs.

http://docs.oasis-open.org/xliff/v1.2/xliff-profile-po/xliff-profile-po-1.2.html
    Explains the gettext format according to how xliff interprets it.

http://www.artfulbits.com/Android/aiLocalizer.aspx
    App to localize Android xml string files directly. They seems to be
    involved with the Ukrainian translation of Android itself.

http://groups.google.com/group/android-platform/browse_thread/thread/a2626195205e8543
    Notes that Google internally manages Android translations in their
    own system.

    There is a converter from and to XLIFF in ``frameworks/base/tools/localize``,
    which might be what they are using. It looks pretty decent too. Why
    isn't this promoted more?

https://launchpad.net/intltool
    Converts to and from .po und "can be extended to support other types
    of XML" - sounds like something we could've used? It's Perl though,
    ugh.


text:
using content::BrowserThread;

namespace chromeos {
namespace imageburner {

namespace {

// Name for hwid in machine statistics.
const char kHwidStatistic[] = "hardware_class";

const char kConfigFileUrl[] =
    "https://dl.google.com/dl/edgedl/chromeos/recovery/recovery.conf";
const char kTempImageFolderName[] = "chromeos_image";

const int64 kBytesImageDownloadProgressReportInterval = 10240;

BurnManager* g_burn_manager = NULL;

// Cretes a directory and calls |callback| with the result on UI thread.
void CreateDirectory(const base::FilePath& path,
                     base::Callback<void(bool success)> callback) {
  const bool success = file_util::CreateDirectory(path);
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                          base::Bind(callback, success));
}

}  // namespace

const char kName[] = "name";
const char kHwid[] = "hwid";
const char kFileName[] = "file";
const char kUrl[] = "url";

////////////////////////////////////////////////////////////////////////////////
//
// ConfigFile
//
////////////////////////////////////////////////////////////////////////////////
ConfigFile::ConfigFile() {
}

ConfigFile::ConfigFile(const std::string& file_content) {
  reset(file_content);
}

ConfigFile::~ConfigFile() {
}

void ConfigFile::reset(const std::string& file_content) {
  clear();

  std::vector<std::string> lines;
  Tokenize(file_content, "\n", &lines);

  std::vector<std::string> key_value_pair;
  for (size_t i = 0; i < lines.size(); ++i) {
    if (lines[i].empty())
      continue;

    key_value_pair.clear();
    Tokenize(lines[i], "=", &key_value_pair);
    // Skip lines that don't contain key-value pair and lines without a key.
    if (key_value_pair.size() != 2 || key_value_pair[0].empty())
      continue;

    ProcessLine(key_value_pair);
  }

  // Make sure last block has at least one hwid associated with it.
  DeleteLastBlockIfHasNoHwid();
}

void ConfigFile::clear() {
  config_struct_.clear();
}

const std::string& ConfigFile::GetProperty(
    const std::string& property_name,
    const std::string& hwid) const {
  // We search for block that has desired hwid property, and if we find it, we
  // return its property_name property.
  for (BlockList::const_iterator block_it = config_struct_.begin();
       block_it != config_struct_.end();
       ++block_it) {
    if (block_it->hwids.find(hwid) != block_it->hwids.end()) {
      PropertyMap::const_iterator property =
          block_it->properties.find(property_name);
      if (property != block_it->properties.end()) {
        return property->second;
      } else {
        return EmptyString();
      }
    }
  }

  return EmptyString();
}

// Check if last block has a hwid associated with it, and erase it if it
// doesn't,
void ConfigFile::DeleteLastBlockIfHasNoHwid() {
  if (!config_struct_.empty() && config_struct_.back().hwids.empty()) {
    config_struct_.pop_back();
  }
}

void ConfigFile::ProcessLine(const std::vector<std::string>& line) {
  // If line contains name key, new image block is starting, so we have to add
  // new entry to our data structure.
  if (line[0] == kName) {
    // If there was no hardware class defined for previous block, we can
    // disregard is since we won't be abble to access any of its properties
    // anyway. This should not happen, but let's be defensive.
    DeleteLastBlockIfHasNoHwid();
    config_struct_.resize(config_struct_.size() + 1);
  }

  // If we still haven't added any blocks to data struct, we disregard this
  // line. Again, this should never happen.
  if (config_struct_.empty())
    return;

  ConfigFileBlock& last_block = config_struct_.back();

  if (line[0] == kHwid) {
    // Check if line contains hwid property. If so, add it to set of hwids
    // associated with current block.
    last_block.hwids.insert(line[1]);
  } else {
    // Add new block property.
    last_block.properties.insert(std::make_pair(line[0], line[1]));
  }
}

ConfigFile::ConfigFileBlock::ConfigFileBlock() {
}

ConfigFile::ConfigFileBlock::~ConfigFileBlock() {
}

////////////////////////////////////////////////////////////////////////////////
//
// StateMachine
//
////////////////////////////////////////////////////////////////////////////////
StateMachine::StateMachine()
    : download_started_(false),
      download_finished_(false),
      state_(INITIAL) {
}

StateMachine::~StateMachine() {
}

void StateMachine::OnError(int error_message_id) {
  if (state_ == INITIAL)
    return;
  if (!download_finished_)
    download_started_ = false;

  state_ = INITIAL;
  FOR_EACH_OBSERVER(Observer, observers_, OnError(error_message_id));
}

void StateMachine::OnSuccess() {
  if (state_ == INITIAL)
    return;
  state_ = INITIAL;
  OnStateChanged();
}

void StateMachine::OnCancelation() {
  // We use state CANCELLED only to let observers know that they have to
  // process cancelation. We don't actually change the state.
  FOR_EACH_OBSERVER(Observer, observers_, OnBurnStateChanged(CANCELLED));
}

////////////////////////////////////////////////////////////////////////////////
//
// BurnManager
//
////////////////////////////////////////////////////////////////////////////////

BurnManager::BurnManager()
    : weak_ptr_factory_(this),
      config_file_url_(kConfigFileUrl),
      config_file_fetched_(false),
      state_machine_(new StateMachine()),
      bytes_image_download_progress_last_reported_(0) {
  CrosLibrary::Get()->GetBurnLibrary()->AddObserver(this);
}

BurnManager::~BurnManager() {
  if (!image_dir_.empty()) {
    file_util::Delete(image_dir_, true);
  }
  CrosLibrary::Get()->GetBurnLibrary()->RemoveObserver(this);
}

// static
void BurnManager::Initialize() {
  if (g_burn_manager) {
    LOG(WARNING) << "BurnManager was already initialized";
    return;
  }
  g_burn_manager = new BurnManager();
  VLOG(1) << "BurnManager initialized";
}

// static
void BurnManager::Shutdown() {
  if (!g_burn_manager) {
    LOG(WARNING) << "BurnManager::Shutdown() called with NULL manager";
    return;
  }
  delete g_burn_manager;
  g_burn_manager = NULL;
  VLOG(1) << "BurnManager Shutdown completed";
}

// static
BurnManager* BurnManager::GetInstance() {
  return g_burn_manager;
}

void BurnManager::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void BurnManager::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void BurnManager::CreateImageDir() {
  if (image_dir_.empty()) {
    CHECK(PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &image_dir_));
    image_dir_ = image_dir_.Append(kTempImageFolderName);
    BrowserThread::PostBlockingPoolTask(
        FROM_HERE,
        base::Bind(CreateDirectory,
                   image_dir_,
                   base::Bind(&BurnManager::OnImageDirCreated,
                              weak_ptr_factory_.GetWeakPtr())));
  } else {
    const bool success = true;
    OnImageDirCreated(success);
  }
}

void BurnManager::OnImageDirCreated(bool success) {
  FOR_EACH_OBSERVER(Observer, observers_, OnImageDirCreated(success));
}

const base::FilePath& BurnManager::GetImageDir() {
  return image_dir_;
}

void BurnManager::FetchConfigFile() {
  if (config_file_fetched_) {
    FOR_EACH_OBSERVER(
        Observer, observers_,
        OnConfigFileFetched(true, image_file_name_, image_download_url_));
    return;
  }

  if (config_fetcher_.get())
    return;

  config_fetcher_.reset(net::URLFetcher::Create(
      config_file_url_, net::URLFetcher::GET, this));
  config_fetcher_->SetRequestContext(
      g_browser_process->system_request_context());
  config_fetcher_->Start();
}

void BurnManager::FetchImage(const GURL& image_url,
                             const base::FilePath& file_path) {
  tick_image_download_start_ = base::TimeTicks::Now();
  bytes_image_download_progress_last_reported_ = 0;
  image_fetcher_.reset(net::URLFetcher::Create(image_url,
                                               net::URLFetcher::GET,
                                               this));
  image_fetcher_->SetRequestContext(
      g_browser_process->system_request_context());
  image_fetcher_->SaveResponseToFileAtPath(
      file_path,
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
  image_fetcher_->Start();
}

void BurnManager::CancelImageFetch() {
  image_fetcher_.reset();
}

void BurnManager::DoBurn(const base::FilePath& source_path,
                         const std::string& image_name) {
  CrosLibrary::Get()->GetBurnLibrary()->DoBurn(
      source_path, image_name, target_file_path(), target_device_path());
}

void BurnManager::CancelBurnImage() {
  CrosLibrary::Get()->GetBurnLibrary()->CancelBurnImage();
}

void BurnManager::OnURLFetchComplete(const net::URLFetcher* source) {
  const bool success =
      source->GetStatus().status() == net::URLRequestStatus::SUCCESS;
  if (source == config_fetcher_.get()) {
    std::string data;
    if (success)
      config_fetcher_->GetResponseAsString(&data);
    config_fetcher_.reset();
    ConfigFileFetched(success, data);
  } else if (source == image_fetcher_.get()) {
    FOR_EACH_OBSERVER(Observer, observers_, OnImageFileFetched(success));
  }
}

void BurnManager::OnURLFetchDownloadProgress(const net::URLFetcher* source,
                                             int64 current,
                                             int64 total) {
  if (source == image_fetcher_.get()) {
    if (current >= bytes_image_download_progress_last_reported_ +
        kBytesImageDownloadProgressReportInterval) {
      bytes_image_download_progress_last_reported_ = current;
      base::TimeDelta estimated_remaining_time;
      if (current > 0) {
        // Extrapolate from the elapsed time.
        const base::TimeDelta elapsed_time =
            base::TimeTicks::Now() - tick_image_download_start_;
        estimated_remaining_time = elapsed_time * (total - current) / current;
      }
      FOR_EACH_OBSERVER(
          Observer, observers_,
          OnImageFileFetchDownloadProgressUpdated(
              current, total, estimated_remaining_time));
    }
  }
}

void BurnManager::BurnProgressUpdated(BurnLibrary* object,
                                      BurnEvent evt,
                                      const ImageBurnStatus& status) {
  // At the moment, this is just a proxy of BurnLibrary callback to observers.
  FOR_EACH_OBSERVER(
      Observer, observers_, OnBurnProgressUpdated(evt, status));
}

void BurnManager::ConfigFileFetched(bool fetched, const std::string& content) {
  if (config_file_fetched_)
    return;

  // Get image file name and image download URL.
  std::string hwid;
  if (fetched && system::StatisticsProvider::GetInstance()->
      GetMachineStatistic(kHwidStatistic, &hwid)) {
    ConfigFile config_file(content);
    image_file_name_ = config_file.GetProperty(kFileName, hwid);
    image_download_url_ = GURL(config_file.GetProperty(kUrl, hwid));
  }

  // Error check.
  if (fetched && !image_file_name_.empty() && !image_download_url_.is_empty()) {
    config_file_fetched_ = true;
  } else {
    fetched = false;
    image_file_name_.clear();
    image_download_url_ = GURL();
  }

  FOR_EACH_OBSERVER(
      Observer, observers_,
      OnConfigFileFetched(fetched, image_file_name_, image_download_url_));
}

}  // namespace imageburner
}  // namespace chromeos

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>File Extensions</title>
    <meta charset="utf-8"/>
    <link type="text/css" rel="stylesheet" href="styles.css"/>

File Extensions

.jpg — 'JPEG' file — digital image such as a photograph

.pdf — portable document format (Adobe Acrobat file)

.txt — a plain text file (no fancy formatting)


text:
package net.springconfig.java.service;

import net.springconfig.java.dao.UserDao;
import net.springconfig.java.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author karpenko_rs
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public User getById(long id) {
        return null;
    }

    @Override
    public User getByLogin(String login) {
        return userDao.find(1);
    }

    @Override
    public void saveUser(User user) {
        userDao.saveOrUpdate(user);
    }

    @Override
    public void delete(User user) {
        userDao.delete(user);
    }

}


text:
#include <assert.h>
#include <stdio.h>      /* for fflush(), printf(), puts(), ... */
#include <string.h>     /* for strchr() */

#include "cmdopt.h" /* for target_name -should this be moved? */
#include "exec.h" /* for get_signame */

#include "display.h"
#include "target.h"   /* for target_status */

#include <time.h>      /* for CLK_TCK, CLOCKS_PER_SEC */

#ifndef _WIN32
#  include <unistd.h>   /* for _SC_CLK_TCK, sysconf() */
#endif

#if defined (_SC_CLK_TCK)

/* dynamically determine the number of clock ticks per second */
static const float TICKS_PER_SEC = float (sysconf (_SC_CLK_TCK));

#elif defined CLOCKS_PER_SEC

/* use the POSIX (and MSVC 6.0) CLOCKS_PER_SEC constant */
static const float TICKS_PER_SEC = CLOCKS_PER_SEC;

#elif defined CLK_TCK

/* use CLK_TCK if it's defined (e.g., pre-MSVC 6.0) */
static const float TICKS_PER_SEC = CLK_TCK;

#else

/* if all else fails, assume the standard 1 million ticks per second */
static const float TICKS_PER_SEC = 1000000UL;

#endif

/**
   ProcessStatus enum lookup table for 'short' (6 character) strings.
*/
static const char* const
short_st_name [ST_LAST] = {
    "OK", /*ST_OK*/
    "COMP", /*ST_COMPILE*/
    "LINK", /*ST_LINK*/
    "EXIST", /*ST_EXIST*/
    "XPERM", /*ST_EXECUTE_FLAG*/
    "EXEC", /*ST_EXECUTE*/
    "NOUT", /*ST_NO_OUTPUT*/
    "OUTPUT", /*ST_NO_REF*/
    "BREF", /*ST_BAD_REF*/
    "DIFF", /*ST_BAD_OUTPUT*/
    "FORMAT", /*ST_FORMAT*/
    "OFLOW", /*ST_OVERFLOW*/
    "ERROR", /*ST_SYSTEM_ERROR*/
    "KILLED", /*ST_KILLED*/
    "NKILL" /*ST_NOT_KILLED*/
};

/**
   ProcessStatus enum lookup table for descriptive strings.
*/
static const char* const
verbose_st_name [ST_LAST] = {
    "OK", /*ST_OK*/
    "Program failed to compile.", /*ST_COMPILE*/
    "Program failed to link.", /*ST_LINK*/
    "Program executable not found.", /*ST_EXIST*/
    "Program not executable.", /*ST_EXECUTE_FLAG*/
    "Program failed to execute.", /*ST_EXECUTE*/
    "Program generated no output.", /*ST_NO_OUTPUT*/
    "Program reference output missing.", /*ST_NO_REF*/
    "Bad reference.", /*ST_BAD_REF*/
    "Program produced unexpected output.", /*ST_BAD_OUTPUT*/
    "Program produced output in unexpected format.", /*ST_FORMAT*/
    "Arithmetic overflow.", /*ST_OVERFLOW*/
    "System error occurred.", /*ST_SYSTEM_ERROR*/
    "Process killed after a timeout.", /*ST_KILLED*/
    "Failed to kill process after a timeout." /*ST_NOT_KILLED*/
};

/**
   Prints an argv array, quoting elelemnts containing spaces.
*/
static int
print_argv (const char* const argv[], int newline)
{
    assert (0 != argv);

    const char* const* parg = argv;

    int nchars = 0;

    for (parg = argv; *parg; ++parg) {

        const char *fmt = "%s ";

        if (strchr (*parg, ' '))
            fmt = "\"%s\" ";

        nchars += printf (fmt, *parg);
    }

    if (newline)
        puts ("");

    return nchars;
}

/**
   Generates output header, designed for text output and console viewing.
*/
static void
print_header_plain (const char* const argv[])
{
    (void)&argv;

    puts ("NAME                                     STATUS WARN ASSERTS "
          "FAILED PERCNT    USER     SYS    REAL");
}

/**
   Generates output header in verbose mode.
*/
static void
print_header_verbose (const char* const argv[])
{
    print_argv (argv, 1 /* append newline */);
}

/**
   Generates target name listing, designed for text output and console viewing.
*/
static void
print_target_plain (const struct target_opts *defaults)
{
    const char* const target_name = get_target ();

    assert (0 == defaults->verbose);

    printf ("%-40.40s ", target_name);

    /* flush to prevent killing a signal from not displaying the text */
    fflush (stdout);
}

/**
   Generates target name listing, designed for text output and console viewing.
*/
static void
print_target_verbose (const struct target_opts *defaults)
{
    assert (defaults->verbose);

    printf ("%s ", "Executing \"");
    print_argv (defaults->argv, 0 /* no newline */);

    /* print stdin, stdout, and stderr redirections */
    if (defaults->infname && *defaults->infname)
        printf (" <%s", defaults->infname);

    if (defaults->outfname && *defaults->outfname)
        printf (" >%s 2>&1", defaults->outfname);

    puts ("\"");

    /* flush to prevent killing a signal from not displaying the text */
    fflush (stdout);
}

/**
   Generates target result listing, designed for text output and console
   viewing.
*/
static void print_status_plain (const struct target_status* status)
{
    unsigned valid_timing;
    assert (0 != status);
    assert (ST_OK <= status->status && ST_LAST > status->status);

    valid_timing =    status->usr_time != (clock_t)-1
                   && status->sys_time != (clock_t)-1
                   && ST_NOT_KILLED != status->status;

    if (status->status) /* if status is set, print it */
        printf ("%6s", short_st_name [status->status]);
    else if (status->signaled) /* if exit signal is non-zero, print it */
        printf ("%6s", get_signame (status->exit));
    else if (status->exit) /* if exit code is non-zero, print it */
        printf ("%6d", status->exit);
    else
        printf ("     0");

    printf (" %4u", status->c_warn + status->l_warn + status->t_warn);

    /* Print assetions, if any registered */
    if (   (unsigned)-1 != status->assert
        && 0 == status->status
        && 0 == status->exit) {
        if (status->assert) {
            const int percnt = int (  100.0
                                    * (status->assert - status->failed)
                                    / status->assert);
            printf (" %7u %6u %5d%%", status->assert, status->failed, percnt);
        }
        else {
            printf ("       0 %6u   100%%", status->failed);
        }
    }
    else if (valid_timing || status->wall_time != (clock_t)-1)
        printf ("                      ");

    /* Print timings, if available */
    if (valid_timing)
        printf (" %7.3f %7.3f", (float)status->usr_time / TICKS_PER_SEC,
                (float)status->sys_time / TICKS_PER_SEC);
    else if (status->wall_time != (clock_t)-1)
        printf ("                ");

    if (status->wall_time != (clock_t)-1)
        printf (" %7.3f\n", (float)status->wall_time / TICKS_PER_SEC);
    else
        puts ("");
}

/**
   Generates verbose target result listing.
*/
static void
print_status_verbose (const struct target_status* status)
{
    unsigned valid_timing;

    assert (0 != status);
    assert (ST_OK <= status->status && ST_LAST > status->status);

    valid_timing =    status->usr_time != (clock_t)-1
                   && status->sys_time != (clock_t)-1
                   && ST_NOT_KILLED != status->status;

    if (status->status) /* if status is set, print it */
        printf ("  Status: %s\n", verbose_st_name [status->status]);
    else if (status->signaled) /* if exit signal is non-zero, print it */
        printf ("  Process signalled:    %s\n", get_signame (status->exit));
    else {
        printf ("  Exit status:          %6d%s\n"
                "  Compiler warnings:    %6u\n"
                "  Linker warnings:      %6u\n"
                "  Runtime warnings:     %6u\n",
                status->exit, 0 == status->exit ? " (success)" : "",
                status->c_warn,
                status->l_warn,
                status->t_warn);

        /* Print assetions, if any registered */
        if ((unsigned)-1 != status->assert && status->assert) {
            printf ("  Failed assertions:    %6u\n"
                    "  Total assertions:     %6u\n",
                    status->failed, status->assert);
        }
    }

    /* Print timings, if available */
    if (valid_timing) {
        const float wall = (float)status->wall_time / TICKS_PER_SEC;
        const float user = (float)status->usr_time  / TICKS_PER_SEC;
        const float sys  = (float)status->sys_time  / TICKS_PER_SEC;

        printf ("  Times:\n"
                "    Real               %7.3fs\n"
                "    User               %7.3fs\n"
                "    Sys                %7.3fs\n",
                wall, user, sys);
    }

    puts ("");
}

/**
   Placholder output footer function, unneeded for text output and console
   viewing.
*/
static void
print_footer_plain (int count, const struct target_status *summary)
{
    /* compute cumulative times for all targets */
    const float wall = (float)summary->wall_time / TICKS_PER_SEC;
    const float user = (float)summary->usr_time  / TICKS_PER_SEC;
    const float sys  = (float)summary->sys_time  / TICKS_PER_SEC;

    printf ("PROGRAM SUMMARY:\n"
            "  Programs:             %9d\n"
            "  Non-zero exit status: %9d\n"
            "  Signalled:            %9d\n"
            "  Compiler warnings:    %9u\n"
            "  Linker warnings:      %9u\n"
            "  Runtime warnings:     %9u\n",
            count,
            summary->exit,
            summary->signaled,
            summary->c_warn,
            summary->l_warn,
            summary->t_warn);

    if ((unsigned)-1 != summary->assert) {
        /* print assertion counters only when they're valid */
        printf ("  Assertions:           %9u\n"
                "  Failed assertions:    %9u\n",
                summary->assert,
                summary->failed);
    }

    printf (            "  Cumulative times:\n"
            "    Real                      %7.3fs\n"
            "    User                      %7.3fs\n"
            "    Sys                       %7.3fs\n",
            wall,
            user,
            sys);
}

static void
print_footer_verbose (int count, const struct target_status *summary)
{
    print_footer_plain (count, summary);
}

/**
   Sets the output functions referenced.
*/
void set_output_format (enum OutputFmt format)
{
    if (FMT_VERBOSE == format) {
        print_header = print_header_verbose;
        print_target = print_target_verbose;
        print_status = print_status_verbose;
        print_footer = print_footer_verbose;
    }
    else {
        /* only two formats implemented */
        assert (FMT_PLAIN == format);

        print_header = print_header_plain;
        print_target = print_target_plain;
        print_status = print_status_plain;
        print_footer = print_footer_plain;
    }
}

void (*print_header) (const char* const[]) = print_header_plain;
void (*print_target) (const struct target_opts*) = print_target_plain;
void (*print_status) (const struct target_status*) = print_status_plain;
void (*print_footer) (int, const struct target_status*) = print_footer_plain;


text:
using System;
using System.Runtime.InteropServices;

namespace NowPlayingLib.Interop
{
    /// <summary>
    /// Gives an embedded object information about resources provided by its container such as the location and extent of its display site, its moniker, and its user interface.
    /// </summary>
    [ComImport]
    [ComVisible(true)]
    [Guid("00000118-0000-0000-C000-000000000046")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IOleClientSite
    {
        /// <summary>
        /// Saves the embedded object associated with the client site.
        /// </summary>
        void SaveObject();

        /// <summary>
        /// <para>Retrieves a moniker for the object's client site.</para>
        /// <para>An object can force the assignment of its own or its container's moniker by specifying a value for dwAssign.</para>
        /// </summary>
        [return: MarshalAs(UnmanagedType.Interface)]
        object GetMoniker(uint dwAssign, uint dwWhichMoniker);

        /// <summary>
        /// Retrieves a pointer to the object's container.
        /// </summary>
        [return: MarshalAs(UnmanagedType.Interface)]
        object GetContainer();

        /// <summary>
        /// Asks a container to display its object to the user.
        /// </summary>
        void ShowObject();

        /// <summary>
        /// Notifies a container when an embedded object's window is about to become visible or invisible.
        /// </summary>
        void OnShowWindow(bool fShow);

        /// <summary>
        /// Asks a container to resize the display site for embedded objects.
        /// </summary>
        void RequestNewObjectLayout();
    }
}


text:
using System;
using System.Buffers;
using MQTTnet.Adapter;
using MQTTnet.Exceptions;
using MQTTnet.Packets;
using MQTTnet.Serializer;

namespace MQTTnet.AspNetCore
{
    public static class ReaderExtensions
    {
        public static bool TryDeserialize(this IMqttPacketSerializer serializer, in ReadOnlySequence<byte> input, out MqttBasePacket packet, out SequencePosition consumed, out SequencePosition observed)
        {
            packet = null;
            consumed = input.Start;
            observed = input.End;
            var copy = input;
            if (copy.Length < 2)
            {
                return false;
            }

            var fixedheader = copy.First.Span[0];
            if (!TryReadBodyLength(ref copy, out var bodyLength))
            {
                return false;
            }

            if (copy.Length < bodyLength)
            {
                return false;
            }

            var bodySlice = copy.Slice(0, bodyLength);
            var buffer = bodySlice.GetArray();
            packet = serializer.Deserialize(new ReceivedMqttPacket(fixedheader, new MqttPacketBodyReader(buffer, 0, buffer.Length)));
            consumed = bodySlice.End;
            observed = bodySlice.End;
            return true;
        }

        private static byte[] GetArray(this in ReadOnlySequence<byte> input)
        {
            if (input.IsSingleSegment)
            {
                return input.First.Span.ToArray();
            }

            // Should be rare
            return input.ToArray();
        }

        private static bool TryReadBodyLength(ref ReadOnlySequence<byte> input, out int result)
        {
            // Alorithm taken from https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html.
            var multiplier = 1;
            var value = 0;
            byte encodedByte;
            var index = 1;
            result = 0;

            var temp = input.Slice(0, Math.Min(5, input.Length)).GetArray();

            do
            {
                if (index == temp.Length)
                {
                    return false;
                }
                encodedByte = temp[index];
                index++;

                value += (byte)(encodedByte & 127) * multiplier;
                if (multiplier > 128 * 128 * 128)
                {
                    throw new MqttProtocolViolationException($"Remaining length is invalid (Data={string.Join(",", temp.AsSpan(1, index).ToArray())}).");
                }

                multiplier *= 128;
            } while ((encodedByte & 128) != 0);

            input = input.Slice(index);

            result = value;
            return true;
        }
    }
}


text:
//
//  VROTorusKnot.hpp
//  ViroRenderer
//
//  Created by Raj Advani on 1/11/16.
//  Copyright © 2016 Viro Media. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining
//  a copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be included
//  in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef VROTorusKnot_h
#define VROTorusKnot_h

#include "VROGeometry.h"
#include <vector>
#include <memory>

class VROTorusKnot : public VROGeometry {

public:

    static std::shared_ptr<VROTorusKnot> createTorusKnot(float p, float q, float tubeRadius,
                                                         int segments, int slices);
    virtual ~VROTorusKnot();

private:

    VROTorusKnot(std::vector<std::shared_ptr<VROGeometrySource>> sources,
                 std::vector<std::shared_ptr<VROGeometryElement>> elements) :
        VROGeometry(sources, elements)
    {}

};

#endif /* VROTorusKnot_h */


text: void* input_alsa(void* data);


text:
<?php

namespace app\facades\adminuser;

/**
 * @author: Prachi
 * @date: 17-March-2016
 * @description: LookupFacade interacts with models for all lookup related activities
 */

use Yii;
use app\facades\common\CommonFacade;
use app\web\util\Codes\Codes;
use app\models\Lookups;
use app\web\util\Codes\LookupCodes;

class LookupFacade {

    public $messages;           //stores an instance of the messages XML file.

    public function __construct() {
        $this->messages = CommonFacade::getMessages();
    }

    public function listLookup(){
            $CODES = new Codes();
            $lookupModel = new Lookups();

            $connection = Yii::$app->getDb();

           if(Yii::$app->user->identity->user_type==LookupCodes::L_USER_TYPE_DEVELOPERS){
            $query="SELECT c.id,c.value,t.value AS lookup_type,IFNULL(l.value,'-') AS parent,IF(c.is_seed_data='0','user managed','system managed') AS seed_data_type,ls.value AS status,c.status as status_id"
                    . " FROM cc_lookups AS c"
                    . " LEFT JOIN cc_lookups AS l ON c.parent_id=l.id"
                    . " LEFT JOIN cc_lookups AS ls ON c.status=ls.id"
                    . " LEFT JOIN cc_lookup_types AS t ON c.type=t.id"
                    . " WHERE c.is_delete='1' AND c.type = 45 OR c.type = 46 OR c.type = 50" ;
           }else{
                $query="SELECT c.id,c.value,t.value AS lookup_type,IFNULL(l.value,'-') AS parent,IF(c.is_seed_data='0','user managed','system managed') AS seed_data_type,ls.value AS status,c.status as status_id"
                    . " FROM cc_lookups AS c"
                    . " LEFT JOIN cc_lookups AS l ON c.parent_id=l.id"
                    . " LEFT JOIN cc_lookups AS ls ON c.status=ls.id"
                    . " LEFT JOIN cc_lookup_types AS t ON c.type=t.id"
                    . " WHERE c.is_delete='1' AND c.is_seed_data='0' AND t.type_of_lookup_type='0' AND c.type = 45 OR c.type = 46 OR c.type = 50" ;
           }

            $command = $connection->createCommand($query);
            $data = $command->queryAll();
            if (!empty($data)) {
                $MSG ="";
                $CODE = $CODES::SUCCESS;
                $data = array('STATUS' => 'success', 'SUBDATA' => $data);
                return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
            } else {
                $MSG = $this->messages->M121;
                $CODE = $CODES::VALIDATION_ERROR;
                $data = array('STATUS' => 'error', 'SUBDATA' => array());
                return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
            }

    }

    public function add_modify($request,$image=array()){

          $CODES = new Codes();
          $commonFacade= new CommonFacade();
          $model= new Lookups();
          $path=$save_path="";
          if(!empty($image)){
           // store the source file name
            $ext = end((explode(".", $image->name)));

            // generate a unique file name
            $avatar = Yii::$app->security->generateRandomString().".{$ext}";

            // the path to save file, you can set an uploadPath
            $path = Yii::$app->params['UPLOAD_PATH'].'lookup/' . $avatar;
            $save_path="lookup/".$avatar;
          }

          $currentTime=$commonFacade->getCurrentDateTime();
          if($request['id']!=""){ //edit
              if($save_path!=""){
                 $request['image_path']=$save_path;
              }else{unset($request['image_path']);}
              $model = Lookups::find()->where(['id'=>$request['id']])->one();

              if($model->is_seed_data==1 && Yii::$app->user->identity->user_type!=LookupCodes::L_USER_TYPE_DEVELOPERS){
                  $MSG=$this->messages->M122;
                  $MSG=  str_replace('{1}','update', $MSG);
                  $MSG=  str_replace('{2}','lookup', $MSG);
                  $CODE=$CODES::ERROR;
                  $data = array('STATUS' => 'error', 'SUBDATA' => array());
                  return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
              }

               if($save_path!=""){
                if(file_exists(Yii::$app->params['UPLOAD_PATH'].$model->image_path) && $model->image_path!=""){
                 unlink(Yii::$app->params['UPLOAD_PATH'].$model->image_path);
                 Yii::$app->params['UPLOAD_PATH'].$model->image_path;
                }
               }
              $response="updated";
          }else{    //add
              $auto_id=self::setIdentity($request['type']);
              $request['id']=$auto_id;
              $request['created_by']=Yii::$app->admin->adminId;
              $request['created_on']=$currentTime;
              $request['is_delete']='1';
              $request['image_path']=$save_path;
              $model->id= $request['id'];
              $response="added";
          }
              $request['modified_by'] =  Yii::$app->admin->adminId;
              $request['modified_on'] = $currentTime;
              $model->setAttributes($request);
          if($model->validate()){  //To Validate Model
                try{

                    if ($model->save()) {
                         if($path!=""){$res=$image->saveAs($path);}
                        $MSG=$this->messages->M113; //To get Message
                        $MSG= str_replace("{1}","Lookup", $MSG);
                        $MSG= str_replace("{2}",$response, $MSG);
                        $CODE=$CODES::SUCCESS;
                        $data = array('STATUS' => 'success', 'SUBDATA' => array());
                        return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);

                    } else {
                        $MSG=$this->messages->M102;
                        $CODE=$CODES::DB_TECH_ERROR;
                        Yii::error($model->getErrors());
                        $data = array('STATUS' => 'error', 'SUBDATA' => array());
                        return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
                    }
                }//EOF try
                catch (\yii\base\Exception $e){
                    $MSG=$this->messages->M103;
                    $CODE=$CODES::EXCEPTION_ERROR;
                    Yii::error($e->getMessage());
                    // use $e->getMessage() to write error in log file.
                    $data = array('STATUS' => 'error', 'SUBDATA' => array());
                    return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
                }//EOF catch

        } else {
            $error = array_values($model->firstErrors);
            $MSG="";
            if(!empty($error)){$MSG=$error[0];}
            $CODE=$CODES::VALIDATION_ERROR;
            $data = array('STATUS' => 'error', 'SUBDATA' => array());
            return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
        }

    }

    public function viewType($id){
            $CODES = new Codes();
            $connection = Yii::$app->getDb();
            $query="SELECT c.id,c.value,c.description,c.info1,c.info2,c.image_path,t.value AS lookup_type,IFNULL(l.value,'-') AS parent,IF(c.is_seed_data='0','user managed','system managed') AS seed_data_type,ls.value AS status,c.short_code"
                    . " FROM cc_lookups AS c"
                    . " LEFT JOIN cc_lookups AS l ON c.parent_id=l.id"
                    . " LEFT JOIN cc_lookups AS ls ON c.status=ls.id"
                    . " LEFT JOIN cc_lookup_types AS t ON c.type=t.id"
                    . " WHERE c.id='".$id."'";
            $command = $connection->createCommand($query);
            $data = $command->queryAll();
            if (!empty($data)) {
                $MSG ="";
                $CODE = $CODES::SUCCESS;
                $data = array('STATUS' => 'success', 'SUBDATA' => $data);
                return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
            } else {
                $MSG = $this->messages->M121;
                $CODE = $CODES::VALIDATION_ERROR;
                $data = array('STATUS' => 'error', 'SUBDATA' => array());
                return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
            }

    }

    public function delete($id){
        $CODES = new Codes();
        $commonFacade= new CommonFacade();
        $model = Lookups::find()->where(['id'=>$id])->one();
        if($model->is_seed_data==1 && Yii::$app->user->identity->user_type!=LookupCodes::L_USER_TYPE_DEVELOPERS){
                  $MSG=$this->messages->M122;
                  $MSG=  str_replace('{1}','delete', $MSG);
                  $MSG=  str_replace('{2}','lookup', $MSG);
                  $CODE=$CODES::ERROR;
                  $data = array('STATUS' => 'error', 'SUBDATA' => array());
                  return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
        }

        $value=$model->value;
        $model->is_delete=0;
        /*if($model->validate(false)){  //To Validate Model
                try{
                    */
                    if ($model->save(false)) {
                        $MSG=$this->messages->M113; //To get Message
                        $MSG= str_replace("{1}",$value, $MSG);
                        $MSG= str_replace("{2}","deleted", $MSG);
                        $CODE=$CODES::SUCCESS;
                        $data = array('STATUS' => 'success', 'SUBDATA' => array());
                        return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);

                    } else {
                        $MSG=$this->messages->M102;
                        $CODE=$CODES::DB_TECH_ERROR;
                        Yii::error($model->getErrors());
                        $data = array('STATUS' => 'error', 'SUBDATA' => array());
                        return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
                    }
                /*}//EOF try
                catch (Exception $e){
                    $MSG=$this->messages->M103;
                    $CODE=$CODES::EXCEPTION_ERROR;
                    // use $e->getMessage() to write error in log file.
                    $data = array('STATUS' => 'error', 'SUBDATA' => array());
                    return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
                }//EOF catch
                 *

        } else {
            $error = array_values($model->firstErrors);
            $MSG="";
            if(!empty($error)){$MSG=$error[0];}
            $CODE=$CODES::VALIDATION_ERROR;
            $data = array('STATUS' => 'error', 'SUBDATA' => array());
            return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $data);
        } */
    }

    public function changeStatus($id,$status){
        $CODES = new Codes;
        $commonFacade= new CommonFacade();
        $currentTime=$commonFacade->getCurrentDateTime();
        if($id != ''){
            $model = Lookups::find()->where(['id'=>$id])->one();
            if($model){
                if($model->is_seed_data==1 && Yii::$app->user->identity->user_type!=LookupCodes::L_USER_TYPE_DEVELOPERS){
                  $MSG=$this->messages->M122;
                  $MSG=  str_replace('{1}','change status of', $MSG);
                  $MSG=  str_replace('{2}','lookup', $MSG);
                  $CODE=$CODES::ERROR;
                  return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $status);
                }

                $model->status = $status;
                $model->modified_by = Yii::$app->admin->adminId;
                $model->modified_on = $currentTime;

                if($model->save(false)){
                    $MSG = $this->messages->M119;
                    $CODE = $CODES::SUCCESS;
                    $DATA = $model->status0->value;
                    return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' =>$DATA);
                } else {
                    $MSG = $this->messages->M103;
                    $CODE = $CODES::ERROR;
                    return array('CODE' => $CODE, 'MESSAGE' => $MSG, 'DATA' => $status);
                }
            }

        }
    }

    public function setIdentity($lookupTypeId){
        $count=Lookups::find()->where(['type'=>$lookupTypeId])->count();
        if($count>0){
            $max_id=Lookups::find()->select('id')->where(['type'=>$lookupTypeId])->max('id');
            $auto_id=$max_id+1;
            return $auto_id;
        }else{
            $startRange=(($lookupTypeId*50000)+50000);
            $endRange=$startRange+50000;
            $auto_id=$startRange+1;
            return $auto_id;
        }
        return false;
    }

}


text:
CREATE OR REPLACE FUNCTION ti.getelementportionbyname(_portion character varying)
 RETURNS TABLE(portionid integer, portion character varying)
 LANGUAGE sql
AS $function$
SELECT portionid, portion
FROM ndb.elementportions
WHERE portion ILIKE $1
$function$


text:
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type
     ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logFile.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>

            <!-- keep 1 days' worth of history -->
            <maxHistory>5</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info" additivity="false">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>

    <logger name="application" level="info" additivity="false">
    <appender-ref ref="STDOUT"/>
    <appender-ref ref="FILE"/>
</logger>

<logger name="play" level="INFO" additivity="false">
    <appender-ref ref="STDOUT"/>
    <appender-ref ref="FILE"/>
</logger>

</configuration>


text:
module.exports = {
  assertSimilar: function (type, val1, val2, errorMessage, depth) {
    depth = depth || 0;
    this.assertDefined(type, depth + 1);
    type = type.replace("?", "");
    if (val2 === null) {
      this.assertNull(val1, errorMessage, depth + 1);
    } else if (type === "float" || type === "double") {
      this.assertEqualWithTolerance(val1, val2, 0.000001, errorMessage, depth + 1);
    } else if (type === "decimal128" || type === "objectId" || type === "uuid") {
      this.assertEqual(val1.toString(), val2.toString(), errorMessage, depth + 1);
    } else if (type === "data") {
      this.assertArraysEqual(new Uint8Array(val1), val2, errorMessage, depth + 1);
    } else if (type === "date") {
      this.assertEqual(val1 && val1.getTime(), val2.getTime(), errorMessage, depth + 1);
    } else if (type === "object") {
      var keys = val1.keys !== undefined ? val1.keys() : Object.keys(val1);

      for (const key of keys) {
        const message = errorMessage ? `${errorMessage}: ${key}` : key;
        this.assertEqual(val1[key], val2[key], message, depth + 1);
      }
    } else if (type === "list") {
      this.assertArraysEqual(val1, val2, errorMessage, depth + 1);
    } else {
      this.assertEqual(val1, val2, errorMessage, depth + 1);
    }
  },

  assertEqual: function (val1, val2, errorMessage, depth) {
    if (val1 !== val2) {
      let message = `'${val1}' does not equal expected value '${val2}'`;
      if (errorMessage) {
        message = `${errorMessage} - ${message}`;
      }
      throw new TestFailureError(message, depth);
    }
  },

  assertNotEqual: function (val1, val2, errorMessage, depth) {
    if (val1 === val2) {
      let message = `'${val1}' equals '${val2}'`;
      if (errorMessage) {
        message = `${errorMessage} - ${message}`;
      }
      throw new TestFailureError(message, depth);
    }
  },

  assertEqualWithTolerance: function (val1, val2, tolerance, errorMessage, depth) {
    if (val1 < val2 - tolerance || val1 > val2 + tolerance) {
      let message = `'${val1}' does not equal '${val2}' with tolerance '${tolerance}'`;
      if (errorMessage) {
        message = `${errorMessage} - ${message}`;
      }
      throw new TestFailureError(message, depth);
    }
  },

  assertArray: function (value, length, errorMessage, depth) {
    if (!Array.isArray(value)) {
      throw new TestFailureError(errorMessage || `Value ${value} is not an array`, depth);
    }
  },

  assertArrayLength: function (value, length, errorMessage, depth) {
    this.assertArray(value, 1 + depth || 0);
    if (value.length !== length) {
      throw new TestFailureError(errorMessage || `Value ${value} is not an array of length ${length}`, depth);
    }
  },

  assertArraysEqual: function (val1, val2, errorMessage, depth) {
    this.assertDefined(val1, `val1 should be non-null but is ${val1}`, 1 + (depth || 0));
    this.assertDefined(val2, `val2 should be non-null but is ${val2}`, 1 + (depth || 0));
    const len1 = val1.length;
    const len2 = val2.length;

    if (len1 !== len2) {
      let message = `Arrays (${val1}) and (${val2}) have different lengths (${len1} != ${len2})`;
      if (errorMessage) {
        message = `${errorMessage} - ${message}`;
      }
      throw new TestFailureError(message, depth);
    }

    let compare;
    if (val1.type === "data") {
      compare = (i, a, b) =>
        a === b || this.assertArraysEqual(new Uint8Array(a), b, `Data elements at index ${i}`, 1) || true;
    } else if (val1.type === "date") {
      compare = (i, a, b) => (a && a.getTime()) === (b && b.getTime());
    } else if (val1.type === "float" || val1.type === "double") {
      compare = (i, a, b) => a >= b - 0.000001 && a <= b + 0.000001;
    } else if (val1.type === "object") {
      compare = (i, a, b) => {
        var keys = a.keys !== undefined ? a.keys() : Object.keys(a);
        return keys.every((key) => a[key] === b[key]);
      };
    } else if (val1.type === "decimal128" || val1.type === "objectId" || val1.type === "uuid") {
      compare = (i, a, b) => (a && a.toString()) === (b && b.toString());
    } else {
      compare = (i, a, b) => a === b;
    }

    for (let i = 0; i < len1; i++) {
      if (!compare(i, val1[i], val2[i])) {
        let message = `Array contents not equal at index ${i} (${val1[i]} != ${val2[i]})`;
        if (errorMessage) {
          message = `${errorMessage} - ${message}`;
        }
        throw new TestFailureError(message, depth);
      }
    }
  },

  assertThrows: function (func, errorMessage, depth) {
    try {
      func();
    } catch (e) {
      return e;
    }
    throw new TestFailureError(errorMessage || `Expected exception not thrown from ${func}`, depth);
  },

  assertThrowsAsync: async function (func, errorMessage, depth) {
    try {
      await func();
    } catch (e) {
      return e;
    }
    throw new TestFailureError(errorMessage || `Expected exception not thrown from ${func}`, depth);
  },

  assertThrowsException: function (func, expectedException) {
    let caught = false;
    try {
      func();
    } catch (e) {
      caught = true;
      if (e.name !== expectedException.name) {
        throw new TestFailureError(
          `Expected a ${expectedException.name} exception but caught a ${e.name} instead. Message was: ${e.message}`,
        );
      }
      if (e.message != expectedException.message) {
        throw new TestFailureError(`Expected exception "${expectedException}" not thrown - instead caught: "${e}"`);
      }
    }

    if (!caught) {
      throw new TestFailureError("Expected exception not thrown");
    }
  },

  assertThrowsContaining: function (func, expectedMessage, depth) {
    let caught = false;
    try {
      func();
    } catch (e) {
      caught = true;
      if (!e.message.includes(expectedMessage) && !e.name.includes(expectedMessage)) {
        throw new TestFailureError(
          `Expected exception "${expectedMessage}" not thrown - instead caught: "${e}"`,
          depth,
        );
      }
    }

    if (!caught) {
      throw new TestFailureError(`Expected exception "${expectedMessage}" not thrown`, depth);
    }
  },

  assertThrowsAsyncContaining: async function (func, expectedMessage, depth) {
    let caught = false;
    try {
      await func();
    } catch (e) {
      caught = true;
      if (!e.message.includes(expectedMessage)) {
        throw new TestFailureError(
          `Expected exception "${expectedMessage}" not thrown - instead caught: "${e}"`,
          depth,
        );
      }
    }

    if (!caught) {
      throw new TestFailureError(`Expected exception "${expectedMessage}" not thrown`, depth);
    }
  },

  assertTrue: function (condition, errorMessage, depth) {
    if (!condition) {
      throw new TestFailureError(errorMessage || `Condition ${condition} expected to be true`, depth);
    }
  },

  assertFalse: function (condition, errorMessage, depth) {
    if (condition) {
      throw new TestFailureError(errorMessage || `Condition ${condition} expected to be false`, depth);
    }
  },

  assertInstanceOf: function (object, type, errorMessage, depth) {
    if (!(object instanceof type)) {
      throw new TestFailureError(errorMessage || `Object ${object} expected to be of type ${type}`, depth);
    }
  },

  assertType: function (value, type, depth) {
    try {
      this.assertEqual(typeof value, type, "", 1 + depth || 0);
    } catch (e) {
      throw new Error(`Value ${value} expected to be of type ${type}`);
    }
  },

  assertDefined: function (value, errorMessage, depth) {
    if (value === undefined || value === null) {
      throw new TestFailureError(errorMessage || `Value ${value} expected to be non-null`, depth);
    }
  },

  assertUndefined: function (value, errorMessage, depth) {
    if (value !== undefined) {
      throw new TestFailureError(errorMessage || `Value ${value} expected to be undefined`, depth);
    }
  },

  assertNull: function (value, errorMessage, depth) {
    if (value !== null) {
      throw new TestFailureError(errorMessage || `Value ${value} expected to be null`, depth);
    }
  },

  assertNotNull: function (value, errorMessage, depth) {
    if (value === null) {
      throw new TestFailureError(errorMessage || `Value ${value} expected to be not null`, depth);
    }
  },

  isNode: function () {
    // eslint-disable-next-line no-undef
    return typeof process == "object" && Object.prototype.toString.call(process) == "[object process]";
  },

  isNode6: function () {
    // eslint-disable-next-line no-undef
    return this.isNode() && process.version.indexOf("v6.") == 0;
  },
};

function TestFailureError(message, depth) {
  let error;
  try {
    throw new Error(message);
  } catch (e) {
    error = e;
  }

  depth = 2 + (depth || 0);

  // This regular expression will match stack trace lines provided by JavaScriptCore.
  // Example: someMethod@file:///path/to/file.js:10:24
  const regex = /^(?:.*?@)?([^[(].+?):(\d+)(?::(\d+))?\s*$/;

  // Remove the top two stack frames and use information from the third, if possible.
  const stack = error.stack && error.stack.split("\n");
  const match = stack[depth] && stack[depth].match(regex);
  if (match) {
    this.sourceURL = match[1];
    this.line = +match[2];
    this.column = +match[3];
    this.stack = stack.slice(depth).join("\n");
  }

  this.__proto__ = error;
}


text:
from django import forms

class MessagesGetForm(forms.Form):
    since = forms.DateTimeField(required=False)


text:
import type {
    GenericDescriptor as ESGenericDescriptor,
    AccessorDescriptor as ESAccessorDescriptor,
    DataDescriptor as ESDataDescriptor,
    PropertyDescriptor as ESPropertyDescriptor,
} from './index';

interface ES5 {
    readonly 'Abstract Equality Comparison': typeof import('./5/AbstractEqualityComparison');
    readonly 'Abstract Relational Comparison': typeof import('./5/AbstractRelationalComparison');
    readonly 'Strict Equality Comparison': typeof import('./5/StrictEqualityComparison');
    readonly CheckObjectCoercible: typeof import('./5/CheckObjectCoercible');
    readonly DateFromTime: typeof import('./5/DateFromTime');
    readonly Day: typeof import('./5/Day');
    readonly DayFromYear: typeof import('./5/DayFromYear');
    readonly DaysInYear: typeof import('./5/DaysInYear');
    readonly DayWithinYear: typeof import('./5/DayWithinYear');
    readonly FromPropertyDescriptor: typeof import('./5/FromPropertyDescriptor');
    readonly HourFromTime: typeof import('./5/HourFromTime');
    readonly InLeapYear: typeof import('./5/InLeapYear');
    readonly IsAccessorDescriptor: typeof import('./5/IsAccessorDescriptor');
    readonly IsCallable: typeof import('./5/IsCallable');
    readonly IsDataDescriptor: typeof import('./5/IsDataDescriptor');
    readonly IsGenericDescriptor: typeof import('./5/IsGenericDescriptor');
    readonly IsPropertyDescriptor: typeof import('./5/IsPropertyDescriptor');
    readonly MakeDate: typeof import('./5/MakeDate');
    readonly MakeDay: typeof import('./5/MakeDay');
    readonly MakeTime: typeof import('./5/MakeTime');
    readonly MinFromTime: typeof import('./5/MinFromTime');
    readonly modulo: typeof import('./5/modulo');
    readonly MonthFromTime: typeof import('./5/MonthFromTime');
    readonly msFromTime: typeof import('./5/msFromTime');
    readonly SameValue: typeof import('./5/SameValue');
    readonly SecFromTime: typeof import('./5/SecFromTime');
    readonly TimeClip: typeof import('./5/TimeClip');
    readonly TimeFromYear: typeof import('./5/TimeFromYear');
    readonly TimeWithinDay: typeof import('./5/TimeWithinDay');
    readonly ToBoolean: typeof import('./5/ToBoolean');
    readonly ToInt32: typeof import('./5/ToInt32');
    readonly ToInteger: typeof import('./5/ToInteger');
    readonly ToNumber: typeof import('./5/ToNumber');
    readonly ToObject: typeof import('./5/ToObject');
    readonly ToPrimitive: typeof import('./5/ToPrimitive');
    readonly ToPropertyDescriptor: typeof import('./5/ToPropertyDescriptor');
    readonly ToString: typeof import('./5/ToString');
    readonly ToUint16: typeof import('./5/ToUint16');
    readonly ToUint32: typeof import('./5/ToUint32');
    readonly Type: typeof import('./5/Type');
    readonly WeekDay: typeof import('./5/WeekDay');
    readonly YearFromTime: typeof import('./5/YearFromTime');
}

declare namespace ES5 {
    type GenericDescriptor = ESGenericDescriptor;
    type AccessorDescriptor<T = unknown> = ESAccessorDescriptor<T>;
    type DataDescriptor<T = unknown> = ESDataDescriptor<T>;
    type PropertyDescriptor<T = unknown> = ESPropertyDescriptor<T>;
}

declare const ES5: ES5;
export = ES5;


text:
package br.com.lealweb.aventuradoconhecimento;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.Target;
import com.github.amlcurran.showcaseview.targets.ViewTarget;

import java.util.List;

import github.chenupt.multiplemodel.viewpager.ModelPagerAdapter;
import github.chenupt.multiplemodel.viewpager.PagerModelManager;
import github.chenupt.springindicator.SpringIndicator;

/**
 * Created by leonardoleal on 02/09/16.
 */
public abstract class DefaultActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,
                    ClickableScrollerViewPager.OnItemClickListener,
                    View.OnClickListener {

    protected  DrawerLayout drawer;
    private boolean playTutorial;

    protected abstract List<String> getTitles();
    protected abstract List<Integer> getBgRes();

    final String TUTORIAL_KEY = "tutorial";
    private ShowcaseView showcaseView;
    private ViewTarget target1;
    private ViewTarget target2;
    private ViewTarget target3;
    private int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setupScreenParameters();
        setupElements();

        playTutorial();
    }

    private void setupScreenParameters() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().setBackgroundDrawableResource(R.drawable.main_background);
    }

    private void setupElements() {
        setContentView(R.layout.activity_main);
        scrollableView();
        menu();
        floatingButton();
    }

    private void scrollableView() {
        ClickableScrollerViewPager viewPager = (ClickableScrollerViewPager) findViewById(R.id.view_pager);
        SpringIndicator springIndicator = (SpringIndicator) findViewById(R.id.indicator);

        PagerModelManager manager = new PagerModelManager();
        manager.addCommonFragment(GuideFragment.class, getBgRes(), getTitles());
        ModelPagerAdapter adapter = new ModelPagerAdapter(getSupportFragmentManager(), manager);
        viewPager.setAdapter(adapter);
        viewPager.fixScrollSpeed();

        springIndicator.setViewPager(viewPager);

        viewPager.setOnItemClickListener(this);
    }

    private void menu() {
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    private void floatingButton() {
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toogleMenu();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    private void toogleMenu() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            drawer.openDrawer(GravityCompat.START);
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_about) {
            Intent intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.nav_help) {
            setTutorialOn();
            playTutorial();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void playTutorial() {
        if (isTutorialOn()) {
            count = 0;

            target1 = new ViewTarget(R.id.fab, this);
            target2 = new ViewTarget(R.id.indicator, this);
            target3 = new ViewTarget(R.id.view_pager, this);

            showcaseView = new ShowcaseView.Builder(this)
                    .setTarget(Target.NONE)
                    .setContentTitle(getResources().getString(R.string.tutorial_intro))
                    .setShowcaseDrawer(new CustomShowcaseView(getResources()))
                    .setStyle(R.style.CustomShowcaseTheme)
                    .setOnClickListener(this)
                    .blockAllTouches()
                    .build();

            showcaseView.setButtonText(getResources().getString(R.string.next));
        }
    }

    @Override
    public void onClick(View v) {
        switch (count) {
            case 0:
                showcaseView.setTarget(target1);
                showcaseView.setContentTitle(getResources().getString(R.string.tutorial_step_1));
                showcaseView.setContentText(getResources().getString(R.string.tutorial_step_1_description));
                break;
            case 1:
                showcaseView.setTarget(target2);
                showcaseView.setContentTitle(getResources().getString(R.string.tutorial_step_2));
                showcaseView.setContentText(getResources().getString(R.string.tutorial_step_2_description));
                break;
            case 2:
                showcaseView.setTarget(target3);
                showcaseView.setContentTitle(getResources().getString(R.string.tutorial_step_3));
                showcaseView.setContentText(getResources().getString(R.string.tutorial_step_3_description));
                showcaseView.setButtonText(getResources().getString(R.string.understood));
                break;
            case 3:
                setTutorialOff();
                showcaseView.hide();
                break;
        }
        count++;
    }

    private void setTutorialOff() {
        getAppPreferences()
                .edit()
                .putBoolean(TUTORIAL_KEY, false)
                .commit();
    }

    private void setTutorialOn() {
        getAppPreferences()
                .edit()
                .putBoolean(TUTORIAL_KEY, true)
                .commit();
    }

    private SharedPreferences getAppPreferences() {
        return getSharedPreferences(getResources().getString(R.string.app_name), MODE_PRIVATE);
    }

    private boolean isTutorialOn() {
        return getAppPreferences().getBoolean(TUTORIAL_KEY, true);
    }
}


text:
[CmdletBinding(PositionalBinding = $false)]
param()

Set-StrictMode -Version 2
$ErrorActionPreference = 'Stop'

. $PSScriptRoot\Test-Template.ps1

Test-Template "mvc" "mvc -au Individual" "Microsoft.DotNet.Web.ProjectTemplates.7.0.7.0.0-dev.nupkg" $false


text:
Wouldn't it be great to put all your PDFs into a single directory and then quickly make a report out of them for easy presentation? Well now you can with noteTeX! Create a directory and move all your PDF files to this directory before either calling an instance of `noteTeX`:
```
noteTeX(directory="./",outputfilename="Analysis_Update.tex",captions=[],filestoignoreList=[],keepBuildFiles=False)
```
or simply running within the folder:
```
python /address/to/noteTeX/noteTeX.py
```

## Setting Captions

By default noteTeX simply takes the filename to be the caption for the attached PDF, however the user can specify captions as an argument. The ID for each element at definition is an integer starting from 0 assigned to each file when the files are ordered alphabetically. You can view the elements as a table after running the script by:
```
report = noteTeX()
report.printElements()
```

## TeX Files

noteTeX can import existing LaTeX files, however note that these should not have any preamble, i.e. no`\begin{document}`, `\end{document}` or `usepackage{}` statements etc as they are imported using the `\import{file}` command.

## Prerequisites
For noteTeX to work you require `latexmk` to be installed on your machine. `tabulate` is used to produce the table of elements contained, these are printed using the `printElements()` function.


text:
package nl.tno.idsa.framework.behavior.likelihoods;

import nl.tno.idsa.framework.semantics_base.enumerations.IRuntimeEnumElement;
import nl.tno.idsa.framework.semantics_base.enumerations.RuntimeEnum;
import nl.tno.idsa.framework.world.Day;

import java.util.Collection;

/**
 * Days of the week form the basis for our activity likelihood definitions.
 */
public abstract class DayOfWeek extends ActivityLikelihoodMap implements IRuntimeEnumElement, Cloneable {

    public DayOfWeek() {
        super();
        makeActivities();
    }

    /**
     * Returns the day of the week for the day given.
     */
    public static DayOfWeek getDayOfWeek(Day day) {
        Collection<DayOfWeek> dayOfWeeks = RuntimeEnum.getInstance(DayOfWeek.class).listOptions();
        for (DayOfWeek dayOfWeek : dayOfWeeks) {
            if (dayOfWeek.getPrototypeDay().getDayOfWeek() == day.getDayOfWeek()) {
                return dayOfWeek;
            }
        }
        return null;
    }

    /**
     * Get an example day (e.g. March 2nd 2016 for a Wednesday). This prevents incompatibilities
     * with Calendar implementations, as we can be sure a Wednesday is a Wednesday, instead of relying on e.g. a
     * numeric system where Monday is a 0, or a 2, or whatever.
     */
    public abstract Day getPrototypeDay();

    /**
     * Construct the lists of activities and their likelihoods.
     */
    protected abstract void makeActivities();
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * @internal
 */
var DefaultNotificationSettings = /** @class */ (function () {
    function DefaultNotificationSettings() {
        this.startingZIndex = 1000;
        this.rejectOnCancel = false;
        this.ignoreTransitions = false;
    }
    return DefaultNotificationSettings;
}());
exports.DefaultNotificationSettings = DefaultNotificationSettings;


text:
package org.apache.hadoop.hive.ql.udf.generic;

import java.util.ArrayList;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

/**
 * GenericUDFArray.
 *
 */
@Description(name = "array",
    value = "_FUNC_(n0, n1...) - Creates an array with the given elements ")
public class GenericUDFArray extends GenericUDF {
  private transient Converter[] converters;
  private transient ArrayList<Object> ret = new ArrayList<Object>();

  @Override
  public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {

    GenericUDFUtils.ReturnObjectInspectorResolver returnOIResolver;

    returnOIResolver = new GenericUDFUtils.ReturnObjectInspectorResolver(true);

    for (int i = 0; i < arguments.length; i++) {
      if (!returnOIResolver.update(arguments[i])) {
        throw new UDFArgumentTypeException(i, "Argument type \""
            + arguments[i].getTypeName()
            + "\" is different from preceding arguments. "
            + "Previous type was \"" + arguments[i - 1].getTypeName() + "\"");
      }
    }

    converters = new Converter[arguments.length];

    ObjectInspector returnOI =
        returnOIResolver.get(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
    for (int i = 0; i < arguments.length; i++) {
      converters[i] = ObjectInspectorConverters.getConverter(arguments[i],
          returnOI);
    }

    return ObjectInspectorFactory.getStandardListObjectInspector(returnOI);
  }

  @Override
  public Object evaluate(DeferredObject[] arguments) throws HiveException {
    ret.clear();
    for (int i = 0; i < arguments.length; i++) {
      ret.add(converters[i].convert(arguments[i].get()));
    }
    return ret;

  }

  @Override
  public String getDisplayString(String[] children) {
    return getStandardDisplayString("array", children, ",");
  }
}


text:
use crate::codec::FrontendMessage;
use crate::connection::RequestMessages;
use crate::copy_out::CopyOutStream;
use crate::query::RowStream;
#[cfg(feature = "runtime")]
use crate::tls::MakeTlsConnect;
use crate::tls::TlsConnect;
use crate::types::{BorrowToSql, ToSql, Type};
#[cfg(feature = "runtime")]
use crate::Socket;
use crate::{
    bind, query, slice_iter, CancelToken, Client, CopyInSink, Error, Portal, Row,
    SimpleQueryMessage, Statement, ToStatement,
};
use bytes::Buf;
use futures_util::TryStreamExt;
use postgres_protocol::message::frontend;
use tokio::io::{AsyncRead, AsyncWrite};

/// A representation of a PostgreSQL database transaction.
///
/// Transactions will implicitly roll back when dropped. Use the `commit` method to commit the changes made in the
/// transaction. Transactions can be nested, with inner transactions implemented via safepoints.
pub struct Transaction<'a> {
    client: &'a mut Client,
    savepoint: Option<Savepoint>,
    done: bool,
}

/// A representation of a PostgreSQL database savepoint.
struct Savepoint {
    name: String,
    depth: u32,
}

impl<'a> Drop for Transaction<'a> {
    fn drop(&mut self) {
        if self.done {
            return;
        }

        let query = if let Some(sp) = self.savepoint.as_ref() {
            format!("ROLLBACK TO {}", sp.name)
        } else {
            "ROLLBACK".to_string()
        };
        let buf = self.client.inner().with_buf(|buf| {
            frontend::query(&query, buf).unwrap();
            buf.split().freeze()
        });
        let _ = self
            .client
            .inner()
            .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
    }
}

impl<'a> Transaction<'a> {
    pub(crate) fn new(client: &'a mut Client) -> Transaction<'a> {
        Transaction {
            client,
            savepoint: None,
            done: false,
        }
    }

    /// Consumes the transaction, committing all changes made within it.
    pub async fn commit(mut self) -> Result<(), Error> {
        self.done = true;
        let query = if let Some(sp) = self.savepoint.as_ref() {
            format!("RELEASE {}", sp.name)
        } else {
            "COMMIT".to_string()
        };
        self.client.batch_execute(&query).await
    }

    /// Rolls the transaction back, discarding all changes made within it.
    ///
    /// This is equivalent to `Transaction`'s `Drop` implementation, but provides any error encountered to the caller.
    pub async fn rollback(mut self) -> Result<(), Error> {
        self.done = true;
        let query = if let Some(sp) = self.savepoint.as_ref() {
            format!("ROLLBACK TO {}", sp.name)
        } else {
            "ROLLBACK".to_string()
        };
        self.client.batch_execute(&query).await
    }

    /// Like `Client::prepare`.
    pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
        self.client.prepare(query).await
    }

    /// Like `Client::prepare_typed`.
    pub async fn prepare_typed(
        &self,
        query: &str,
        parameter_types: &[Type],
    ) -> Result<Statement, Error> {
        self.client.prepare_typed(query, parameter_types).await
    }

    /// Like `Client::query`.
    pub async fn query<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> Result<Vec<Row>, Error>
    where
        T: ?Sized + ToStatement,
    {
        self.client.query(statement, params).await
    }

    /// Like `Client::query_one`.
    pub async fn query_one<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> Result<Row, Error>
    where
        T: ?Sized + ToStatement,
    {
        self.client.query_one(statement, params).await
    }

    /// Like `Client::query_opt`.
    pub async fn query_opt<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> Result<Option<Row>, Error>
    where
        T: ?Sized + ToStatement,
    {
        self.client.query_opt(statement, params).await
    }

    /// Like `Client::query_raw`.
    pub async fn query_raw<T, P, I>(&self, statement: &T, params: I) -> Result<RowStream, Error>
    where
        T: ?Sized + ToStatement,
        P: BorrowToSql,
        I: IntoIterator<Item = P>,
        I::IntoIter: ExactSizeIterator,
    {
        self.client.query_raw(statement, params).await
    }

    /// Like `Client::execute`.
    pub async fn execute<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> Result<u64, Error>
    where
        T: ?Sized + ToStatement,
    {
        self.client.execute(statement, params).await
    }

    /// Like `Client::execute_iter`.
    pub async fn execute_raw<P, I, T>(&self, statement: &T, params: I) -> Result<u64, Error>
    where
        T: ?Sized + ToStatement,
        P: BorrowToSql,
        I: IntoIterator<Item = P>,
        I::IntoIter: ExactSizeIterator,
    {
        self.client.execute_raw(statement, params).await
    }

    /// Binds a statement to a set of parameters, creating a `Portal` which can be incrementally queried.
    ///
    /// Portals only last for the duration of the transaction in which they are created, and can only be used on the
    /// connection that created them.
    ///
    /// # Panics
    ///
    /// Panics if the number of parameters provided does not match the number expected.
    pub async fn bind<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> Result<Portal, Error>
    where
        T: ?Sized + ToStatement,
    {
        self.bind_raw(statement, slice_iter(params)).await
    }

    /// A maximally flexible version of [`bind`].
    ///
    /// [`bind`]: #method.bind
    pub async fn bind_raw<P, T, I>(&self, statement: &T, params: I) -> Result<Portal, Error>
    where
        T: ?Sized + ToStatement,
        P: BorrowToSql,
        I: IntoIterator<Item = P>,
        I::IntoIter: ExactSizeIterator,
    {
        let statement = statement.__convert().into_statement(self.client).await?;
        bind::bind(self.client.inner(), statement, params).await
    }

    /// Continues execution of a portal, returning a stream of the resulting rows.
    ///
    /// Unlike `query`, portals can be incrementally evaluated by limiting the number of rows returned in each call to
    /// `query_portal`. If the requested number is negative or 0, all rows will be returned.
    pub async fn query_portal(&self, portal: &Portal, max_rows: i32) -> Result<Vec<Row>, Error> {
        self.query_portal_raw(portal, max_rows)
            .await?
            .try_collect()
            .await
    }

    /// The maximally flexible version of [`query_portal`].
    ///
    /// [`query_portal`]: #method.query_portal
    pub async fn query_portal_raw(
        &self,
        portal: &Portal,
        max_rows: i32,
    ) -> Result<RowStream, Error> {
        query::query_portal(self.client.inner(), portal, max_rows).await
    }

    /// Like `Client::copy_in`.
    pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
    where
        T: ?Sized + ToStatement,
        U: Buf + 'static + Send,
    {
        self.client.copy_in(statement).await
    }

    /// Like `Client::copy_out`.
    pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
    where
        T: ?Sized + ToStatement,
    {
        self.client.copy_out(statement).await
    }

    /// Like `Client::simple_query`.
    pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
        self.client.simple_query(query).await
    }

    /// Like `Client::batch_execute`.
    pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
        self.client.batch_execute(query).await
    }

    /// Like `Client::cancel_token`.
    pub fn cancel_token(&self) -> CancelToken {
        self.client.cancel_token()
    }

    /// Like `Client::cancel_query`.
    #[cfg(feature = "runtime")]
    #[deprecated(since = "0.6.0", note = "use Transaction::cancel_token() instead")]
    pub async fn cancel_query<T>(&self, tls: T) -> Result<(), Error>
    where
        T: MakeTlsConnect<Socket>,
    {
        #[allow(deprecated)]
        self.client.cancel_query(tls).await
    }

    /// Like `Client::cancel_query_raw`.
    #[deprecated(since = "0.6.0", note = "use Transaction::cancel_token() instead")]
    pub async fn cancel_query_raw<S, T>(&self, stream: S, tls: T) -> Result<(), Error>
    where
        S: AsyncRead + AsyncWrite + Unpin,
        T: TlsConnect<S>,
    {
        #[allow(deprecated)]
        self.client.cancel_query_raw(stream, tls).await
    }

    /// Like `Client::transaction`, but creates a nested transaction via a savepoint.
    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
        self._savepoint(None).await
    }

    /// Like `Client::transaction`, but creates a nested transaction via a savepoint with the specified name.
    pub async fn savepoint<I>(&mut self, name: I) -> Result<Transaction<'_>, Error>
    where
        I: Into<String>,
    {
        self._savepoint(Some(name.into())).await
    }

    async fn _savepoint(&mut self, name: Option<String>) -> Result<Transaction<'_>, Error> {
        let depth = self.savepoint.as_ref().map_or(0, |sp| sp.depth) + 1;
        let name = name.unwrap_or_else(|| format!("sp_{}", depth));
        let query = format!("SAVEPOINT {}", name);
        self.batch_execute(&query).await?;

        Ok(Transaction {
            client: self.client,
            savepoint: Some(Savepoint { name, depth }),
            done: false,
        })
    }

    /// Returns a reference to the underlying `Client`.
    pub fn client(&self) -> &Client {
        self.client
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Alert = mongoose.model('Alert'),
	_ = require('lodash');

/**
 * Create a Alert
 */
exports.create = function(req, res) {
	var alert = new Alert(req.body);
	alert.user = req.user;

	alert.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(alert);
		}
	});
};

/**
 * Show the current Alert
 */
exports.read = function(req, res) {
	res.jsonp(req.alert);
};

/**
 * Update a Alert
 */
exports.update = function(req, res) {
	var alert = req.alert ;

	alert = _.extend(alert , req.body);

	alert.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(alert);
		}
	});
};

/**
 * Delete an Alert
 */
exports.delete = function(req, res) {
	var alert = req.alert ;

	alert.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(alert);
		}
	});
};

/**
 * List of Alerts
 */
exports.list = function(req, res) { Alert.find().sort('-created').populate('user', 'displayName').exec(function(err, alerts) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(alerts);
		}
	});
};

/**
 * Alert middleware
 */
exports.alertByID = function(req, res, next, id) { Alert.findById(id).populate('user', 'displayName').exec(function(err, alert) {
		if (err) return next(err);
		if (! alert) return next(new Error('Failed to load Alert ' + id));
		req.alert = alert ;
		next();
	});
};

/**
 * Alert authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.alert.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
package org.apache.lucene.analysis;

import java.io.Reader;

/**
 * An analyzer wrapper, that doesn't allow to wrap components or readers.
 * By disallowing it, it means that the thread local resources can be delegated
 * to the delegate analyzer, and not also be allocated on this analyzer.
 * This wrapper class is the base class of all analyzers that just delegate to
 * another analyzer, e.g. per field name.
 *
 *
This solves the problem of per field analyzer wrapper, where it also
 * maintains a thread local per field token stream components, while it can
 * safely delegate those and not also hold these data structures, which can
 * become expensive memory wise.
 *
 *
Please note: This analyzer uses a private {@link Analyzer.ReuseStrategy},
 * which is returned by {@link #getReuseStrategy()}. This strategy is used when
 * delegating. If you wrap this analyzer again and reuse this strategy, no
 * delegation is done and the given fallback is used.
 */
public abstract class DelegatingAnalyzerWrapper extends AnalyzerWrapper {

  /**
   * Constructor.
   * @param fallbackStrategy is the strategy to use if delegation is not possible
   *  This is to support the common pattern:
   *  {@code new OtherWrapper(thisWrapper.getReuseStrategy())}
   */
  protected DelegatingAnalyzerWrapper(ReuseStrategy fallbackStrategy) {
    super(new DelegatingReuseStrategy(fallbackStrategy));
    // häckidy-hick-hack, because we cannot call super() with a reference to "this":
    ((DelegatingReuseStrategy) getReuseStrategy()).wrapper = this;
  }

  @Override
  protected final TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {
    return super.wrapComponents(fieldName, components);
  }

  @Override
  protected final Reader wrapReader(String fieldName, Reader reader) {
    return super.wrapReader(fieldName, reader);
  }

  private static final class DelegatingReuseStrategy extends ReuseStrategy {
    DelegatingAnalyzerWrapper wrapper;
    private final ReuseStrategy fallbackStrategy;

    DelegatingReuseStrategy(ReuseStrategy fallbackStrategy) {
      this.fallbackStrategy = fallbackStrategy;
    }

    @Override
    public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) {
      if (analyzer == wrapper) {
        final Analyzer wrappedAnalyzer = wrapper.getWrappedAnalyzer(fieldName);
        return wrappedAnalyzer.getReuseStrategy().getReusableComponents(wrappedAnalyzer, fieldName);
      } else {
        return fallbackStrategy.getReusableComponents(analyzer, fieldName);
      }
    }

    @Override
    public void setReusableComponents(Analyzer analyzer, String fieldName,  TokenStreamComponents components) {
      if (analyzer == wrapper) {
        final Analyzer wrappedAnalyzer = wrapper.getWrappedAnalyzer(fieldName);
        wrappedAnalyzer.getReuseStrategy().setReusableComponents(wrappedAnalyzer, fieldName, components);
      } else {
        fallbackStrategy.setReusableComponents(analyzer, fieldName, components);
      }
    }
  };

}


text:
const Firebase = require ("firebase");
const Queue = require ("firebase-queue");
const config = require ("config");
const stripe = require ("stripe") (config.get ("stripe.secret-key"));
const Joi = require('joi');

const rootRef = new Firebase ("https://plentifulshop-demo.firebaseio.com/");
const queueRef = rootRef.child ("purchases/queue");
const customersRef = rootRef.child ("customers");
const permissionsRef = rootRef.child ("permissions");

var queue = null;

// Catch termination signal and shut down queue
process.on('SIGINT', () => {
  console.log('SIGINT');
  if (queue) {
    console.log('Starting queue shutdown');
    queue.shutdown().then( () => {
      console.log('Finished queue shutdown');
    });
  }
  process.exit (0);
});

// Authenticate at Firebase and initialize queue
rootRef.authWithCustomToken (config.get ("firebase.token"))
  .then (
    authData => {
      console.log ("Authenticated with uid: ", authData.uid);
      queue = new Queue (queueRef, processTask);
      console.log ("Waiting for tasks at: ", queueRef.toString ());
    })
  .catch (
    error => {
      console.error ("Firebase authentication error: ", error.message);
      process.exit (1);
    }
  );

// Schema to validate request data
var schema = Joi.object().keys({
  uid:  Joi.string().required(),
  email: Joi.string().email().required(),
  slug: Joi.string().required(),
  price: Joi.number().options({ convert: true }).positive(),
  title: Joi.string().required(),
  operation: Joi.string().required().valid(["newCustomer", "existingCustomer"]),
  tokenOrCustomer: Joi.string().required(),
  feedback: Joi.string().valid("").required()
});

function processTask (rawData, progress, resolveTask, rejectTask) {

  var customer, data;

  Promise.resolve ()
    .then (() => {
      // Validate request data
      const validationResult = Joi.validate (rawData, schema);
      if (validationResult.error) {
        console.error ("invalid request data: ", validationResult.error.details);
        throw new Error ("invalid request");
      }
      data = validationResult.value;
      console.log ("task: ", data);
      return null;
    })
    .then (() => {
      // Check whether given email matches the one stored for the given uid
      return customersRef.child (data.uid).child ("email").once ("value");
    })
    .then (emailSnapshot => {
      const emailFB = emailSnapshot.val ();
      if (emailFB !== data.email) {
        console.error (
          "email address mismatch: request: ", data.email,
          " database: ", emailFB
        );
        throw new Error ("email address mismatch");
      }
      return null;
    })

    .then (() => {
      if (data.operation == "existingCustomer") {
        customer = { id: data.tokenOrCustomer };
        return null;
      }
      else {
        // Create a new Stripe customer from a token representing a card
        return stripe.customers.create ({
          source: data.tokenOrCustomer,
          email: data.email,
          metadata: {uid: data.uid}
        })
        .then (customerLocal => {
          // Read details of customers default card
          customer = customerLocal;
          return stripe.customers.retrieveCard (
            customer.id, customer.default_source);
        })
        .then (card => {
          progress (33);
          console.log ("card: ",
            {id: card.id, brand: card.brand, last4: card.last4});
          // Write customer id into Firebase
          return customersRef.child (data.uid).child ("paymentData")
            .set ({
              stripeId: customer.id,
              cardBrand: card.brand,
              cardLast4: card.last4
            });
        });
      }
    })

    .then (() => {
      // Charge the customer
      return stripe.charges.create ({
        amount: data.price,
        currency: "usd",
        customer: customer.id,
        description: config.get ("strings.chargeDescriptionPrefix")
        + data.title,
        statement_descriptor: (config.get ("strings.statementPrefix")
        + data.slug)
          .slice (0, 22)
      });
    })
    .then (charge => {
      progress (66);
      console.log ("charge: ", {
        uid: data.uid,
        stripeId: customer.id,
        chargeId: charge.id,
        amount: charge.amount,
        currency: charge.currency
      });
      // Grant permission to read the purchased item
      return permissionsRef
        .child (data.uid).child (data.slug).child ("valid")
        .set (true);
    })
    .then (() => {
      console.log ("permission: ",
        {uid: data.uid, slug: data.slug});
      // Mark task as complete; it will be removed from the queue
      resolveTask ();
    })
    .catch (error => {
      // In case of an error we set the key "feedback"
      // Client will remove the task after receiving the feedback.
      var clientMessage = "Payment Gateway Error";
      if (error.type === "StripeCardError") {
        clientMessage = error.message || "Card declined";
        console.log ("stripe card error: ", error.raw);
      } else {
        console.error (error.message);
      }
      rawData.feedback = clientMessage;
      rawData._new_state = "feedback";
      resolveTask (rawData);
    });
}