text:
package au.edu.labshare.rigclient.action.detect;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import au.edu.uts.eng.remotelabs.rigclient.rig.IActivityDetectorAction;
import au.edu.uts.eng.remotelabs.rigclient.util.ILogger;
import au.edu.uts.eng.remotelabs.rigclient.util.LoggerFactory;

/**
 * This class checks for activity for a rig that uses Remote Desktop for access.  If a user has
 * a session active on the Remote Desktop machine, the rig is considered to be in use. If there is
 * no active session, the rig is considered to be unused.
 *

 * An active session is determined using the qwinsta command.  Any session with a
 * STATE = "Active" is considered valid for determining a rig is in use.
 *

 * This command is only valid for Windows systems
 *

 */
public class RDPActivityDetectorAction implements IActivityDetectorAction
{
    /** String to indicate a session is "Active" from qwinsta output */
    public static final String ACTIVE_STATE = "Active";

    /** Default command for querying session in Windows */
    public static final String DEFAULT_COMMAND = "qwinsta";

    /** Default user group for remote desktop access. */
    private String failureReason;

    /** Logger. */
    protected ILogger logger;

    public RDPActivityDetectorAction()
    {
        this.logger = LoggerFactory.getLoggerInstance();

        /* Windows notification only valid for windows and not for Vista */
        if (System.getProperty("os.name").startsWith("Windows"))
        {
            this.logger.debug("Preparing to detect RDP activity.");
        }
        else
        {
            this.logger.error("Unable to instantiate the Remote Desktop Activity Detector Action ("
                    + this.getClass().getName() + ") becuase the detected platform is not Windows. Detected platform is '"
                    + System.getProperty("os.name") + "'.");
            throw new IllegalStateException("RDP Activity Detector Action is only valid for a WINDOWS platforms not "
                    + System.getProperty("os.name") + '.');
        }
    }

    @Override
    public boolean detectActivity()
    {
        boolean isActive = false;
        try{
            ProcessBuilder builder = new ProcessBuilder(RDPActivityDetectorAction.DEFAULT_COMMAND);
            Process proc = builder.start();

            if (proc.waitFor() != 0)
            {
                this.failureReason = "RDP Activity Detector Action failed";
                this.logger.warn("The RDP Activity Detector Action has failed with the following error: "
                        + proc.exitValue() + ". Activity Detection cannot be determined.");
                return false;
            }

            InputStream is = proc.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = null;

            while (br.ready() && (line = br.readLine()) != null)
            {
                if (line.contains(RDPActivityDetectorAction.ACTIVE_STATE))
                {
                    isActive = true;
                    this.logger.debug("The RDP Activity Detector Action has found an active session");
                }
            }
            br.close();
            return isActive;
        }
        catch (Exception e)
        {
            this.failureReason = "RDP Activity Detector could not check status";
            this.logger.error("The RDP Activity Detector failed with exception " + e.getMessage() + ", and type "
                    + e.getClass().getName() + '.');
            return isActive;
        }
    }

    @Override
    public String getActionType()
    {
        return "RDP Activity Detector Action";
    }

    @Override
    public String getFailureReason()
    {
        return this.failureReason;
    }

}


text:
package org.apache.hadoop.fs;

import java.io.IOException;

/** Thrown for checksum errors. */
public class ChecksumException extends IOException {
  public ChecksumException(String description) {
    super(description);
  }
}

redpajama_set_name: RedPajamaGithub


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

namespace Aubergine.Tests.Accounts.SoftwareToTest.Model
{
    public class User
    {
        public string Name { get; set; }
        public string Password { get; set; }
    }
}


text:
<html>
<head>
  <title>smalltitle</title>
  <meta property="description" content="small description" />
</head>

<body>
<p>
This is a piece of small content.
</p>
</body>
</html>


text:
#define	JEMALLOC_TCACHE_C_
#include "jemalloc/internal/jemalloc_internal.h"

/******************************************************************************/
/* Data. */

bool	opt_tcache = true;
ssize_t	opt_lg_tcache_max = LG_TCACHE_MAXCLASS_DEFAULT;

tcache_bin_info_t	*tcache_bin_info;
static unsigned		stack_nelms; /* Total stack elms per tcache. */

unsigned		nhbins;
size_t			tcache_maxclass;

tcaches_t		*tcaches;

/* Index of first element within tcaches that has never been used. */
static unsigned		tcaches_past;

/* Head of singly linked list tracking available tcaches elements. */
static tcaches_t	*tcaches_avail;

/******************************************************************************/

size_t
tcache_salloc(tsdn_t *tsdn, const void *ptr)
{

	return (arena_salloc(tsdn, ptr, false));
}

void
tcache_event_hard(tsd_t *tsd, tcache_t *tcache)
{
	szind_t binind = tcache->next_gc_bin;
	tcache_bin_t *tbin = &tcache->tbins[binind];
	tcache_bin_info_t *tbin_info = &tcache_bin_info[binind];

	if (tbin->low_water > 0) {
		/*
		 * Flush (ceiling) 3/4 of the objects below the low water mark.
		 */
		if (binind < NBINS) {
			tcache_bin_flush_small(tsd, tcache, tbin, binind,
			    tbin->ncached - tbin->low_water + (tbin->low_water
			    >> 2));
		} else {
			tcache_bin_flush_large(tsd, tbin, binind, tbin->ncached
			    - tbin->low_water + (tbin->low_water >> 2), tcache);
		}
		/*
		 * Reduce fill count by 2X.  Limit lg_fill_div such that the
		 * fill count is always at least 1.
		 */
		if ((tbin_info->ncached_max >> (tbin->lg_fill_div+1)) >= 1)
			tbin->lg_fill_div++;
	} else if (tbin->low_water < 0) {
		/*
		 * Increase fill count by 2X.  Make sure lg_fill_div stays
		 * greater than 0.
		 */
		if (tbin->lg_fill_div > 1)
			tbin->lg_fill_div--;
	}
	tbin->low_water = tbin->ncached;

	tcache->next_gc_bin++;
	if (tcache->next_gc_bin == nhbins)
		tcache->next_gc_bin = 0;
}

void *
tcache_alloc_small_hard(tsdn_t *tsdn, arena_t *arena, tcache_t *tcache,
    tcache_bin_t *tbin, szind_t binind, bool *tcache_success)
{
	void *ret;

	arena_tcache_fill_small(tsdn, arena, tbin, binind, config_prof ?
	    tcache->prof_accumbytes : 0);
	if (config_prof)
		tcache->prof_accumbytes = 0;
	ret = tcache_alloc_easy(tbin, tcache_success);

	return (ret);
}

void
tcache_bin_flush_small(tsd_t *tsd, tcache_t *tcache, tcache_bin_t *tbin,
    szind_t binind, unsigned rem)
{
	arena_t *arena;
	void *ptr;
	unsigned i, nflush, ndeferred;
	bool merged_stats = false;

	assert(binind < NBINS);
	assert(rem <= tbin->ncached);

	arena = arena_choose(tsd, NULL);
	assert(arena != NULL);
	for (nflush = tbin->ncached - rem; nflush > 0; nflush = ndeferred) {
		/* Lock the arena bin associated with the first object. */
		arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(
		    *(tbin->avail - 1));
		arena_t *bin_arena = extent_node_arena_get(&chunk->node);
		arena_bin_t *bin = &bin_arena->bins[binind];

		if (config_prof && bin_arena == arena) {
			if (arena_prof_accum(tsd_tsdn(tsd), arena,
			    tcache->prof_accumbytes))
				prof_idump(tsd_tsdn(tsd));
			tcache->prof_accumbytes = 0;
		}

		malloc_mutex_lock(tsd_tsdn(tsd), &bin->lock);
		if (config_stats && bin_arena == arena) {
			assert(!merged_stats);
			merged_stats = true;
			bin->stats.nflushes++;
			bin->stats.nrequests += tbin->tstats.nrequests;
			tbin->tstats.nrequests = 0;
		}
		ndeferred = 0;
		for (i = 0; i < nflush; i++) {
			ptr = *(tbin->avail - 1 - i);
			assert(ptr != NULL);
			chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
			if (extent_node_arena_get(&chunk->node) == bin_arena) {
				size_t pageind = ((uintptr_t)ptr -
				    (uintptr_t)chunk) >> LG_PAGE;
				arena_chunk_map_bits_t *bitselm =
				    arena_bitselm_get_mutable(chunk, pageind);
				arena_dalloc_bin_junked_locked(tsd_tsdn(tsd),
				    bin_arena, chunk, ptr, bitselm);
			} else {
				/*
				 * This object was allocated via a different
				 * arena bin than the one that is currently
				 * locked.  Stash the object, so that it can be
				 * handled in a future pass.
				 */
				*(tbin->avail - 1 - ndeferred) = ptr;
				ndeferred++;
			}
		}
		malloc_mutex_unlock(tsd_tsdn(tsd), &bin->lock);
		arena_decay_ticks(tsd_tsdn(tsd), bin_arena, nflush - ndeferred);
	}
	if (config_stats && !merged_stats) {
		/*
		 * The flush loop didn't happen to flush to this thread's
		 * arena, so the stats didn't get merged.  Manually do so now.
		 */
		arena_bin_t *bin = &arena->bins[binind];
		malloc_mutex_lock(tsd_tsdn(tsd), &bin->lock);
		bin->stats.nflushes++;
		bin->stats.nrequests += tbin->tstats.nrequests;
		tbin->tstats.nrequests = 0;
		malloc_mutex_unlock(tsd_tsdn(tsd), &bin->lock);
	}

	memmove(tbin->avail - rem, tbin->avail - tbin->ncached, rem *
	    sizeof(void *));
	tbin->ncached = rem;
	if ((int)tbin->ncached < tbin->low_water)
		tbin->low_water = tbin->ncached;
}

void
tcache_bin_flush_large(tsd_t *tsd, tcache_bin_t *tbin, szind_t binind,
    unsigned rem, tcache_t *tcache)
{
	arena_t *arena;
	void *ptr;
	unsigned i, nflush, ndeferred;
	bool merged_stats = false;

	assert(binind < nhbins);
	assert(rem <= tbin->ncached);

	arena = arena_choose(tsd, NULL);
	assert(arena != NULL);
	for (nflush = tbin->ncached - rem; nflush > 0; nflush = ndeferred) {
		/* Lock the arena associated with the first object. */
		arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(
		    *(tbin->avail - 1));
		arena_t *locked_arena = extent_node_arena_get(&chunk->node);
		UNUSED bool idump;

		if (config_prof)
			idump = false;
		malloc_mutex_lock(tsd_tsdn(tsd), &locked_arena->lock);
		if ((config_prof || config_stats) && locked_arena == arena) {
			if (config_prof) {
				idump = arena_prof_accum_locked(arena,
				    tcache->prof_accumbytes);
				tcache->prof_accumbytes = 0;
			}
			if (config_stats) {
				merged_stats = true;
				arena->stats.nrequests_large +=
				    tbin->tstats.nrequests;
				arena->stats.lstats[binind - NBINS].nrequests +=
				    tbin->tstats.nrequests;
				tbin->tstats.nrequests = 0;
			}
		}
		ndeferred = 0;
		for (i = 0; i < nflush; i++) {
			ptr = *(tbin->avail - 1 - i);
			assert(ptr != NULL);
			chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
			if (extent_node_arena_get(&chunk->node) ==
			    locked_arena) {
				arena_dalloc_large_junked_locked(tsd_tsdn(tsd),
				    locked_arena, chunk, ptr);
			} else {
				/*
				 * This object was allocated via a different
				 * arena than the one that is currently locked.
				 * Stash the object, so that it can be handled
				 * in a future pass.
				 */
				*(tbin->avail - 1 - ndeferred) = ptr;
				ndeferred++;
			}
		}
		malloc_mutex_unlock(tsd_tsdn(tsd), &locked_arena->lock);
		if (config_prof && idump)
			prof_idump(tsd_tsdn(tsd));
		arena_decay_ticks(tsd_tsdn(tsd), locked_arena, nflush -
		    ndeferred);
	}
	if (config_stats && !merged_stats) {
		/*
		 * The flush loop didn't happen to flush to this thread's
		 * arena, so the stats didn't get merged.  Manually do so now.
		 */
		malloc_mutex_lock(tsd_tsdn(tsd), &arena->lock);
		arena->stats.nrequests_large += tbin->tstats.nrequests;
		arena->stats.lstats[binind - NBINS].nrequests +=
		    tbin->tstats.nrequests;
		tbin->tstats.nrequests = 0;
		malloc_mutex_unlock(tsd_tsdn(tsd), &arena->lock);
	}

	memmove(tbin->avail - rem, tbin->avail - tbin->ncached, rem *
	    sizeof(void *));
	tbin->ncached = rem;
	if ((int)tbin->ncached < tbin->low_water)
		tbin->low_water = tbin->ncached;
}

static void
tcache_arena_associate(tsdn_t *tsdn, tcache_t *tcache, arena_t *arena)
{

	if (config_stats) {
		/* Link into list of extant tcaches. */
		malloc_mutex_lock(tsdn, &arena->lock);
		ql_elm_new(tcache, link);
		ql_tail_insert(&arena->tcache_ql, tcache, link);
		malloc_mutex_unlock(tsdn, &arena->lock);
	}
}

static void
tcache_arena_dissociate(tsdn_t *tsdn, tcache_t *tcache, arena_t *arena)
{

	if (config_stats) {
		/* Unlink from list of extant tcaches. */
		malloc_mutex_lock(tsdn, &arena->lock);
		if (config_debug) {
			bool in_ql = false;
			tcache_t *iter;
			ql_foreach(iter, &arena->tcache_ql, link) {
				if (iter == tcache) {
					in_ql = true;
					break;
				}
			}
			assert(in_ql);
		}
		ql_remove(&arena->tcache_ql, tcache, link);
		tcache_stats_merge(tsdn, tcache, arena);
		malloc_mutex_unlock(tsdn, &arena->lock);
	}
}

void
tcache_arena_reassociate(tsdn_t *tsdn, tcache_t *tcache, arena_t *oldarena,
    arena_t *newarena)
{

	tcache_arena_dissociate(tsdn, tcache, oldarena);
	tcache_arena_associate(tsdn, tcache, newarena);
}

tcache_t *
tcache_get_hard(tsd_t *tsd)
{
	arena_t *arena;

	if (!tcache_enabled_get()) {
		if (tsd_nominal(tsd))
			tcache_enabled_set(false); /* Memoize. */
		return (NULL);
	}
	arena = arena_choose(tsd, NULL);
	if (unlikely(arena == NULL))
		return (NULL);
	return (tcache_create(tsd_tsdn(tsd), arena));
}

tcache_t *
tcache_create(tsdn_t *tsdn, arena_t *arena)
{
	tcache_t *tcache;
	size_t size, stack_offset;
	unsigned i;

	size = offsetof(tcache_t, tbins) + (sizeof(tcache_bin_t) * nhbins);
	/* Naturally align the pointer stacks. */
	size = PTR_CEILING(size);
	stack_offset = size;
	size += stack_nelms * sizeof(void *);
	/* Avoid false cacheline sharing. */
	size = sa2u(size, CACHELINE);

	tcache = ipallocztm(tsdn, size, CACHELINE, true, NULL, true,
	    arena_get(TSDN_NULL, 0, true));
	if (tcache == NULL)
		return (NULL);

	tcache_arena_associate(tsdn, tcache, arena);

	ticker_init(&tcache->gc_ticker, TCACHE_GC_INCR);

	assert((TCACHE_NSLOTS_SMALL_MAX & 1U) == 0);
	for (i = 0; i < nhbins; i++) {
		tcache->tbins[i].lg_fill_div = 1;
		stack_offset += tcache_bin_info[i].ncached_max * sizeof(void *);
		/*
		 * avail points past the available space.  Allocations will
		 * access the slots toward higher addresses (for the benefit of
		 * prefetch).
		 */
		tcache->tbins[i].avail = (void **)((uintptr_t)tcache +
		    (uintptr_t)stack_offset);
	}

	return (tcache);
}

static void
tcache_destroy(tsd_t *tsd, tcache_t *tcache)
{
	arena_t *arena;
	unsigned i;

	arena = arena_choose(tsd, NULL);
	tcache_arena_dissociate(tsd_tsdn(tsd), tcache, arena);

	for (i = 0; i < NBINS; i++) {
		tcache_bin_t *tbin = &tcache->tbins[i];
		tcache_bin_flush_small(tsd, tcache, tbin, i, 0);

		if (config_stats && tbin->tstats.nrequests != 0) {
			arena_bin_t *bin = &arena->bins[i];
			malloc_mutex_lock(tsd_tsdn(tsd), &bin->lock);
			bin->stats.nrequests += tbin->tstats.nrequests;
			malloc_mutex_unlock(tsd_tsdn(tsd), &bin->lock);
		}
	}

	for (; i < nhbins; i++) {
		tcache_bin_t *tbin = &tcache->tbins[i];
		tcache_bin_flush_large(tsd, tbin, i, 0, tcache);

		if (config_stats && tbin->tstats.nrequests != 0) {
			malloc_mutex_lock(tsd_tsdn(tsd), &arena->lock);
			arena->stats.nrequests_large += tbin->tstats.nrequests;
			arena->stats.lstats[i - NBINS].nrequests +=
			    tbin->tstats.nrequests;
			malloc_mutex_unlock(tsd_tsdn(tsd), &arena->lock);
		}
	}

	if (config_prof && tcache->prof_accumbytes > 0 &&
	    arena_prof_accum(tsd_tsdn(tsd), arena, tcache->prof_accumbytes))
		prof_idump(tsd_tsdn(tsd));

	idalloctm(tsd_tsdn(tsd), tcache, NULL, true, true);
}

void
tcache_cleanup(tsd_t *tsd)
{
	tcache_t *tcache;

	if (!config_tcache)
		return;

	if ((tcache = tsd_tcache_get(tsd)) != NULL) {
		tcache_destroy(tsd, tcache);
		tsd_tcache_set(tsd, NULL);
	}
}

void
tcache_enabled_cleanup(tsd_t *tsd)
{

	/* Do nothing. */
}

void
tcache_stats_merge(tsdn_t *tsdn, tcache_t *tcache, arena_t *arena)
{
	unsigned i;

	cassert(config_stats);

	malloc_mutex_assert_owner(tsdn, &arena->lock);

	/* Merge and reset tcache stats. */
	for (i = 0; i < NBINS; i++) {
		arena_bin_t *bin = &arena->bins[i];
		tcache_bin_t *tbin = &tcache->tbins[i];
		malloc_mutex_lock(tsdn, &bin->lock);
		bin->stats.nrequests += tbin->tstats.nrequests;
		malloc_mutex_unlock(tsdn, &bin->lock);
		tbin->tstats.nrequests = 0;
	}

	for (; i < nhbins; i++) {
		malloc_large_stats_t *lstats = &arena->stats.lstats[i - NBINS];
		tcache_bin_t *tbin = &tcache->tbins[i];
		arena->stats.nrequests_large += tbin->tstats.nrequests;
		lstats->nrequests += tbin->tstats.nrequests;
		tbin->tstats.nrequests = 0;
	}
}

bool
tcaches_create(tsd_t *tsd, unsigned *r_ind)
{
	arena_t *arena;
	tcache_t *tcache;
	tcaches_t *elm;

	if (tcaches == NULL) {
		tcaches = base_alloc(tsd_tsdn(tsd), sizeof(tcache_t *) *
		    (MALLOCX_TCACHE_MAX+1));
		if (tcaches == NULL)
			return (true);
	}

	if (tcaches_avail == NULL && tcaches_past > MALLOCX_TCACHE_MAX)
		return (true);
	arena = arena_ichoose(tsd, NULL);
	if (unlikely(arena == NULL))
		return (true);
	tcache = tcache_create(tsd_tsdn(tsd), arena);
	if (tcache == NULL)
		return (true);

	if (tcaches_avail != NULL) {
		elm = tcaches_avail;
		tcaches_avail = tcaches_avail->next;
		elm->tcache = tcache;
		*r_ind = (unsigned)(elm - tcaches);
	} else {
		elm = &tcaches[tcaches_past];
		elm->tcache = tcache;
		*r_ind = tcaches_past;
		tcaches_past++;
	}

	return (false);
}

static void
tcaches_elm_flush(tsd_t *tsd, tcaches_t *elm)
{

	if (elm->tcache == NULL)
		return;
	tcache_destroy(tsd, elm->tcache);
	elm->tcache = NULL;
}

void
tcaches_flush(tsd_t *tsd, unsigned ind)
{

	tcaches_elm_flush(tsd, &tcaches[ind]);
}

void
tcaches_destroy(tsd_t *tsd, unsigned ind)
{
	tcaches_t *elm = &tcaches[ind];
	tcaches_elm_flush(tsd, elm);
	elm->next = tcaches_avail;
	tcaches_avail = elm;
}

bool
tcache_boot(tsdn_t *tsdn)
{
	unsigned i;

	/*
	 * If necessary, clamp opt_lg_tcache_max, now that large_maxclass is
	 * known.
	 */
	if (opt_lg_tcache_max < 0 || (ZU(1) << opt_lg_tcache_max) < SMALL_MAXCLASS)
		tcache_maxclass = SMALL_MAXCLASS;
	else if ((ZU(1) << opt_lg_tcache_max) > large_maxclass)
		tcache_maxclass = large_maxclass;
	else
		tcache_maxclass = (ZU(1) << opt_lg_tcache_max);

	nhbins = size2index(tcache_maxclass) + 1;

	/* Initialize tcache_bin_info. */
	tcache_bin_info = (tcache_bin_info_t *)base_alloc(tsdn, nhbins *
	    sizeof(tcache_bin_info_t));
	if (tcache_bin_info == NULL)
		return (true);
	stack_nelms = 0;
	for (i = 0; i < NBINS; i++) {
		if ((arena_bin_info[i].nregs << 1) <= TCACHE_NSLOTS_SMALL_MIN) {
			tcache_bin_info[i].ncached_max =
			    TCACHE_NSLOTS_SMALL_MIN;
		} else if ((arena_bin_info[i].nregs << 1) <=
		    TCACHE_NSLOTS_SMALL_MAX) {
			tcache_bin_info[i].ncached_max =
			    (arena_bin_info[i].nregs << 1);
		} else {
			tcache_bin_info[i].ncached_max =
			    TCACHE_NSLOTS_SMALL_MAX;
		}
		stack_nelms += tcache_bin_info[i].ncached_max;
	}
	for (; i < nhbins; i++) {
		tcache_bin_info[i].ncached_max = TCACHE_NSLOTS_LARGE;
		stack_nelms += tcache_bin_info[i].ncached_max;
	}

	return (false);
}


text:
'use strict';

var http = require('http');

var options = {
  hostname: '127.0.0.1',
  port: 1337,
  // 134.102.218.16=coap.me
  path: 'coap://134.102.218.16/query?foo=quas&bar=wex&baz=exort',
  method: 'GET',
  // Headers correspond to properties of an object passed to
  // `h5.coap.Message.fromObject()` and can optionally be prefixed
  // with `Coap-`.
  headers: {
    'Coap-Type': 'NON',
    'Accept': 'text/plain;charset=utf-8'
  }
};

var req = http.request(options, function(res)
{
  console.log('Status : %d', res.statusCode);
  console.log('Headers: %s', JSON.stringify(res.headers, null, 2));
  console.log('Payload:');

  res.on('data', function(chunk)
  {
    process.stdout.write(chunk);
  });
});

req.on('error', function(err)
{
  console.error("[req#error] %s", err.message);
});

req.end();


text:
#ifndef SkOSWindow_Android_DEFINED
#define SkOSWindow_Android_DEFINED

#include "SkWindow.h"

class SkIRect;

class SkOSWindow : public SkWindow {
public:
    SkOSWindow(void*) {}
    ~SkOSWindow() {}

    enum SkBackEndTypes {
        kNone_BackEndType,
        kNativeGL_BackEndType,
    };

    bool attach(SkBackEndTypes /* attachType */, int /* msaaSampleCount */) {
        return true;
    }
    void detach() {}
    void present() {}

    virtual void onPDFSaved(const char title[], const char desc[],
        const char path[]);

protected:
    // overrides from SkWindow
    virtual void onHandleInval(const SkIRect&);
    virtual void onSetTitle(const char title[]);

private:
    typedef SkWindow INHERITED;
};

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<response stat="ok">
  <ltml xmlns="http://www.librarything.com/" version="1.0">
    <item id="113" type="work">
      <author id="21" authorcode="rowlingjk">J.K. Rowling</author>
      <url>http://www.librarything.com/work/113</url>
      <commonknowledge>
        <fieldList>
          <field type="27" name="quotations" displayName="Quotations">
            <versionList>
              <version id="2179387" archived="0" lang="eng">
                <date timestamp="1265358816">Fri, 05 Feb 2010 03:33:36 -0500</date>
                <person id="937705">
                  <name>bergs47</name>
                  <url>http://www.librarything.com/profile/bergs47</url>
                </person>
                <factList>
                  <fact><![CDATA[ Differences of habit and language are nothing at all if our aims are identical and our hearts are open.  ]]></fact>
                  <fact><![CDATA[ If you're holding out for universal popularity, I'm afraid you will be in this cabin for a very long time.  ]]></fact>
                  <fact><![CDATA[ It matters not what someone is born, but what they grow to be.  ]]></fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="4" name="awards" displayName="Awards and honors">
            <versionList>
              <version id="2146839" archived="0" lang="eng">
                <date timestamp="1264724107">Thu, 28 Jan 2010 19:15:07 -0500</date>
                <person id="122621">
                  <name>stephmo</name>
                  <url>http://www.librarything.com/profile/stephmo</url>
                </person>
                <factList>
                  <fact>Hugo (Novel, 2001)</fact>
                  <fact>Scottish Arts Council Book Award (2001)</fact>
                  <fact>Whitaker's (Platinum Book Award, 2001)</fact>
                  <fact>ALA Notable Children's Book (2001)</fact>
                  <fact>Red House Children's Book Award (Older Readers, 2001)</fact>
                  <fact>BBC's Big Read (Best loved novel, 2003, No 05)</fact>
                  <fact>Mythopoeic Fantasy Award (Children's Literature, 2008)</fact>
                  <fact>Bram Stoker Award Nominee (Work For Younger Readers, 2000)</fact>
                  <fact>SF Site Reader's Choice (2000)</fact>
                  <fact>Whitcoulls top 100, 2008 (56)</fact>
                  <fact>ALA Popular Paperbacks for Young Adults (2009.03|Fame and Fortune, 2009)</fact>
                  <fact>1001 Children's Books You Must Read Before You Grow Up (2009.0701|2009, Ages 8↑)</fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="2" name="placesmentioned" displayName="Important places">
            <versionList>
              <version id="2118302" archived="0" lang="eng">
                <date timestamp="1263908705">Tue, 19 Jan 2010 08:45:05 -0500</date>
                <person id="453271">
                  <name>djryan</name>
                  <url>http://www.librarything.com/profile/djryan</url>
                </person>
                <factList>
                  <fact>Hogwarts School of Witchcraft and Wizardry, Scotland, UK</fact>
                  <fact>4 Privet Drive, Little Whinging, Surrey, England, UK</fact>
                  <fact>Surrey, England, UK</fact>
                  <fact>Little Hangleton, England, UK</fact>
                  <fact>The Burrow, Ottery St. Catchpole, Devon, England, UK</fact>
                  <fact>Devon, England, UK</fact>
                  <fact>Scotland, UK</fact>
                  <fact>Forbidden Forest, Scotland, UK</fact>
                  <fact>Hogsmeade, Scotland, UK</fact>
                  <fact>London, England, UK</fact>
                  <fact>Diagon Alley, London, England, UK</fact>
                  <fact>King's Cross Station, London, England, UK</fact>
                  <fact>Platform 9 3/4, King's Cross Station, London, England, UK</fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="34" name="events" displayName="Important events">
            <versionList>
              <version id="2118301" archived="0" lang="eng">
                <date timestamp="1263908690">Tue, 19 Jan 2010 08:44:50 -0500</date>
                <person id="453271">
                  <name>djryan</name>
                  <url>http://www.librarything.com/profile/djryan</url>
                </person>
                <factList>
                  <fact>The Tri-Wizard Tournament </fact>
                  <fact>The return of Lord Voldemort </fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="3" name="characternames" displayName="People/Characters">
            <versionList>
              <version id="2018335" archived="0" lang="eng">
                <date timestamp="1261442966">Mon, 21 Dec 2009 19:49:26 -0500</date>
                <person id="8334">
                  <name>lampbane</name>
                  <url>http://www.librarything.com/profile/lampbane</url>
                </person>
                <factList>
                  <fact>Harry James Potter</fact>
                  <fact>Hermione Jean Granger</fact>
                  <fact>Ronald Bilius "Ron" Weasley</fact>
                  <fact>Ludo Bagman</fact>
                  <fact>Sirius Black</fact>
                  <fact>Cho Chang</fact>
                  <fact>Bartemius Crouch</fact>
                  <fact>Bartemius Crouch Jr.</fact>
                  <fact>Fleur Isabelle Delacour</fact>
                  <fact>Cedric Diggory</fact>
                  <fact>Albus Percival Wulfric Brian Dumbledore (Headmaster)</fact>
                  <fact>Cornelius Oswald Fudge (Minister for Magic, Minister of Magic)</fact>
                  <fact>Rubeus Hagrid (Keeper of Keys and Grounds, gamekeeper)</fact>
                  <fact>Viktor Krum</fact>
                  <fact>Bellatrix Lestrange</fact>
                  <fact>Neville Longbottom</fact>
                  <fact>Minerva McGonagall (Hogwarts Professor, Transfiguration mistress)</fact>
                  <fact>Alastor "Mad-Eye" Moody</fact>
                  <fact>Rita Skeeter</fact>
                  <fact>Severus Snape (Hogwarts Professor, Potions master)</fact>
                  <fact>Sybill Patricia Trelawney (Hogwarts Professor, Divination mistress)</fact>
                  <fact>Lord Voldemort (Tom Riddle | He Who Must Not be Named)</fact>
                  <fact>Fred Weasley</fact>
                  <fact>George Weasley</fact>
                  <fact>Draco Malfoy</fact>
                  <fact>Bill Weasley</fact>
                  <fact>Charlie Weasley</fact>
                  <fact>Percy Ignatius Weasley</fact>
                  <fact>Peter Pettigrew</fact>
                  <fact>Mr Ollivander</fact>
                  <fact>Arthur Weasley</fact>
                  <fact>Colin Creevey</fact>
                  <fact>Crookshanks</fact>
                  <fact>Dean Thomas</fact>
                  <fact>Dobby</fact>
                  <fact>Dudley Dursley</fact>
                  <fact>Filius Flitwick</fact>
                  <fact>Ginevra Molly "Ginny" Weasley</fact>
                  <fact>Gregory Goyle</fact>
                  <fact>Lavender Brown</fact>
                  <fact>Lucius Malfoy</fact>
                  <fact>Narcissa Malfoy</fact>
                  <fact>Oliver Wood</fact>
                  <fact>Padma Patil</fact>
                  <fact>Parvati Patil</fact>
                  <fact>Stan Shunpike</fact>
                  <fact>Vernon Dursley</fact>
                  <fact>Vincent Crabbe</fact>
                  <fact>Aberforth Dumbledore</fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="37" name="movies" displayName="Related movies">
            <versionList>
              <version id="1967795" archived="0" lang="eng">
                <date timestamp="1259692858">Tue, 01 Dec 2009 13:40:58 -0500</date>
                <person id="18138">
                  <name>ablachly</name>
                  <url>http://www.librarything.com/profile/ablachly</url>
                </person>
                <factList>
                  <fact>Harry Potter and the Goblet of Fire (2005 | tt0330373 | Mike Newell)</fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="29" name="blurbers" displayName="Blurbers">
            <versionList>
              <version id="1843103" archived="0" lang="eng">
                <date timestamp="1255372292">Mon, 12 Oct 2009 14:31:32 -0400</date>
                <person id="684944">
                  <name>fig2</name>
                  <url>http://www.librarything.com/profile/fig2</url>
                </person>
                <factList>
                  <fact>Kng, Stephen</fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="36" name="mediareviews" displayName="Media reviews">
            <versionList>
              <version id="1813461" archived="0" lang="eng">
                <date timestamp="1254187863">Mon, 28 Sep 2009 21:31:03 -0400</date>
                <person id="116044">
                  <name>Shortride</name>
                  <url>http://www.librarything.com/profile/Shortride</url>
                </person>
                <factList>
                  <fact>726</fact>
                  <fact>3304</fact>
                  <fact>4047</fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="23" name="series" displayName="Series">
            <versionList>
              <version id="1555830" archived="0" lang="eng">
                <date timestamp="1245622094">Sun, 21 Jun 2009 18:08:14 -0400</date>
                <person id="235285">
                  <name>norabelle414</name>
                  <url>http://www.librarything.com/profile/norabelle414</url>
                </person>
                <factList>
                  <fact>Harry Potter (4)</fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="14" name="description" displayName="Description">
            <versionList>
              <version id="1517216" archived="0" lang="eng">
                <date timestamp="1244500422">Mon, 08 Jun 2009 18:33:42 -0400</date>
                <person id="729852">
                  <name>grattonlibrary</name>
                  <url>http://www.librarything.com/profile/grattonlibrary</url>
                </person>
                <factList>
                  <fact><![CDATA[ This is Cristina's favorite book in the Harry Potter series. In this book Harry conquers various tasks via the triwizard tournament, but is this tournament more than Harry can handle? ]]></fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="30" name="dedication" displayName="Dedication">
            <versionList>
              <version id="1350688" archived="0" lang="eng">
                <date timestamp="1239986353">Fri, 17 Apr 2009 12:39:13 -0400</date>
                <person id="9086">
                  <name>Writer_Librarian</name>
                  <url>http://www.librarything.com/profile/Writer_Librarian</url>
                </person>
                <factList>
                  <fact><![CDATA[ To Peter Rowling,
in memory of Mr. Ridley
and to Susan Sladden,
who helped Harry
out of his cupboard. ]]></fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="25" name="firstwords" displayName="First words">
            <versionList>
              <version id="1254560" archived="0" lang="eng">
                <date timestamp="1237400947">Wed, 18 Mar 2009 14:29:07 -0400</date>
                <person id="182277">
                  <name>pmowrey</name>
                  <url>http://www.librarything.com/profile/pmowrey</url>
                </person>
                <factList>
                  <fact><![CDATA[ The villagers of Little Hangleton still called it 'the Riddle House', even though it had been many years since the Riddle family had lived there. ]]></fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="26" name="lastwords" displayName="Last words">
            <versionList>
              <version id="533298" archived="0" lang="eng">
                <date timestamp="1218680304">Wed, 13 Aug 2008 22:18:24 -0400</date>
                <person id="122621">
                  <name>stephmo</name>
                  <url>http://www.librarything.com/profile/stephmo</url>
                </person>
                <factList>
                  <fact><![CDATA[ As Hagrid had said, what would come, would come...and he would have to meet it when it did. ]]></fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="21" name="canonicaltitle" displayName="Canonical title">
            <versionList>
              <version id="471906" archived="0" lang="eng">
                <date timestamp="1215145823">Fri, 04 Jul 2008 00:30:23 -0400</date>
                <person id="1">
                  <name>timspalding</name>
                  <url>http://www.librarything.com/profile/timspalding</url>
                </person>
                <factList>
                  <fact>Harry Potter and the Goblet of Fire</fact>
                </factList>
              </version>
            </versionList>
          </field>
          <field type="16" name="originalpublicationdate" displayName="Original publication date">
            <versionList>
              <version id="338282" archived="0" lang="eng">
                <date timestamp="1207535844">Sun, 06 Apr 2008 22:37:24 -0400</date>
                <person id="125174">
                  <name>paulhurtley</name>
                  <url>http://www.librarything.com/profile/paulhurtley</url>
                </person>
                <factList>
                  <fact>2000-07-08</fact>
                </factList>
              </version>
            </versionList>
          </field>
        </fieldList>
      </commonknowledge>
    </item>
    <legal>By using this data you agree to the LibraryThing API terms of service.</legal>
  </ltml>
</response>


text:
package main

import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"strings"
)

func (s *State) shell(args ...string) {
	const promptPlaceholder = "<username>"
	const help = `
Shell runs an interactive session for Upspin subcommands.
When running the shell, the leading "upspin" is assumed on each command.
`
	fs := flag.NewFlagSet("shell", flag.ExitOnError)
	promptFlag := fs.String("prompt", promptPlaceholder, "interactive `prompt`")
	verbose := fs.Bool("v", false, "verbose; print to stderr each command before execution")
	s.ParseFlags(fs, args, help, "shell [-v] [-prompt=<prompt_string>]")
	if fs.NArg() != 0 {
		usageAndExit(fs)
	}
	prompt := func() {
		if len(*promptFlag) > 0 {
			fmt.Fprint(os.Stderr, *promptFlag)
		}
	}
	if *promptFlag == promptPlaceholder {
		*promptFlag = string(s.Config.UserName()) + ">"
	}
	s.Interactive = true
	defer func() { s.Interactive = false }()
	scanner := bufio.NewScanner(os.Stdin)
	for prompt(); scanner.Scan(); prompt() {
		s.exec(scanner.Text(), *verbose)
	}
	if scanner.Err() != nil {
		s.Exit(scanner.Err())
	}
}

func (s *State) exec(line string, verbose bool) {
	defer func() {
		err := recover()
		if err != nil {
			if str, ok := err.(string); ok && str == "exit" {
				// OK; this was a subcommand calling exit
			} else {
				panic(err)
			}
		}
	}()
	// TODO: quoting.
	line = strings.TrimSpace(line)
	sharp := strings.IndexByte(line, '#')
	if sharp >= 0 {
		line = line[:sharp]
	}
	words := strings.Fields(line)
	if len(words) == 0 {
		return
	}
	fn := s.getCommand(strings.ToLower(words[0]))
	if fn == nil {
		fmt.Fprintf(os.Stderr, "upspin: no such command %q\n", words[0])
		return
	}
	if verbose {
		fmt.Fprintln(os.Stderr, " + "+strings.Join(words, " "))
	}
	s.Name = words[0]
	fn(s, words[1:]...)
}


text:
package de.linkvt.ontobench.features.annotations.ontology;

import org.semanticweb.owlapi.model.IRI;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class OntologyConstants {

  public static final IRI ONTOVIBE_CORE_IRI = IRI.create("http://ontovibe.visualdataweb.org/");
  public static final IRI ONTOVIBE_MINIMAL_IRI = IRI.create("http://ontovibe.visualdataweb.org/minimal/");

  public String getContributor() {
    return "Vincent Link";
  }

  public String getCreator() {
    return "Ontology Visualization Benchmark Generator";
  }

  public String getDescription() {
    return "Benchmark ontology created with the " + getCreator();
  }

  /**
   * @return the current date in W3C Date Format (http://www.w3.org/TR/NOTE-datetime)
   */
  public String getGenerationDate() {
    return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  }

  public String getTitle() {
    return "Benchmark Ontology";
  }

  public String getVersion() {
    return "1.0";
  }
}


text:
package client

import (
	"archive/tar"
	"bytes"
	"compress/gzip"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"sort"
	"strings"
	"time"

	"github.com/tsuru/tsuru-client/tsuru/formatter"
	"github.com/tsuru/tsuru/cmd"
	"github.com/tsuru/tsuru/cmd/cmdtest"
	tsuruIo "github.com/tsuru/tsuru/io"
	"gopkg.in/check.v1"
)

func (s *S) TestDeployInfo(c *check.C) {
	var cmd AppDeploy
	c.Assert(cmd.Info(), check.NotNil)
}

func (s *S) TestDeployRun(c *check.C) {
	calledTimes := 0
	var buf bytes.Buffer
	ctx := cmd.Context{Stderr: bytes.NewBufferString(""), Stdout: bytes.NewBufferString("")}
	tm := newTarMaker(&ctx)
	err := tm.targz(&buf, false, "testdata", "..")
	c.Assert(err, check.IsNil)
	trans := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "deploy worked\nOK\n", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			calledTimes++
			if req.Body != nil {
				defer req.Body.Close()
			}
			if calledTimes == 1 {
				return req.Method == "GET" && strings.HasSuffix(req.URL.Path, "/apps/secret")
			}
			file, _, transErr := req.FormFile("file")
			c.Assert(transErr, check.IsNil)
			content, transErr := ioutil.ReadAll(file)
			c.Assert(transErr, check.IsNil)
			c.Assert(content, check.DeepEquals, buf.Bytes())
			c.Assert(req.Header.Get("Content-Type"), check.Matches, "multipart/form-data; boundary=.*")
			c.Assert(req.FormValue("origin"), check.Equals, "app-deploy")
			return req.Method == "POST" && strings.HasSuffix(req.URL.Path, "/apps/secret/deploy")
		},
	}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	cmd := AppDeploy{}
	err = cmd.Flags().Parse(true, []string{"testdata", "..", "-a", "secret"})
	c.Assert(err, check.IsNil)
	context.Args = cmd.Flags().Args()

	err = cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(calledTimes, check.Equals, 2)
}

type slowReader struct {
	io.ReadCloser
	Latency time.Duration
}

func (s *slowReader) Read(p []byte) (n int, err error) {
	time.Sleep(s.Latency)
	return s.ReadCloser.Read(p)
}

func (s *slowReader) Close() error {
	return s.ReadCloser.Close()
}

func (s *S) TestDeployRunCancel(c *check.C) {
	calledTimes := 0
	var buf bytes.Buffer
	ctx := cmd.Context{Stderr: bytes.NewBufferString(""), Stdout: bytes.NewBufferString("")}
	tm := newTarMaker(&ctx)
	err := tm.targz(&buf, false, "testdata", "..")
	c.Assert(err, check.IsNil)
	deploy := make(chan struct{}, 1)
	trans := cmdtest.MultiConditionalTransport{
		ConditionalTransports: []cmdtest.ConditionalTransport{
			{
				Transport: cmdtest.Transport{Status: http.StatusOK},
				CondFunc: func(req *http.Request) bool {
					calledTimes++
					c.Assert(req.Method, check.Equals, "GET")
					c.Assert(req.URL.Path, check.Equals, "/1.0/apps/secret")
					return true
				},
			},
			{
				Transport: &cmdtest.BodyTransport{
					Status:  http.StatusOK,
					Headers: map[string][]string{"X-Tsuru-Eventid": {"5aec54d93195b20001194951"}},
					Body:    &slowReader{ReadCloser: ioutil.NopCloser(bytes.NewBufferString("deploy worked\nOK\n")), Latency: time.Second * 5},
				},
				CondFunc: func(req *http.Request) bool {
					deploy <- struct{}{}
					calledTimes++
					if req.Body != nil {
						defer req.Body.Close()
					}
					file, _, transErr := req.FormFile("file")
					c.Assert(transErr, check.IsNil)
					content, transErr := ioutil.ReadAll(file)
					c.Assert(transErr, check.IsNil)
					c.Assert(content, check.DeepEquals, buf.Bytes())
					c.Assert(req.Header.Get("Content-Type"), check.Matches, "multipart/form-data; boundary=.*")
					c.Assert(req.FormValue("origin"), check.Equals, "app-deploy")
					return req.Method == "POST" && strings.HasSuffix(req.URL.Path, "/apps/secret/deploy")
				},
			},
			{
				Transport: cmdtest.Transport{Status: http.StatusOK},
				CondFunc: func(req *http.Request) bool {
					calledTimes++
					c.Assert(req.Method, check.Equals, "POST")
					c.Assert(req.URL.Path, check.Equals, "/1.1/events/5aec54d93195b20001194951/cancel")
					return true
				},
			},
		},
	}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Stdin:  bytes.NewReader([]byte("y")),
		Args:   []string{"testdata", "..", "-a", "secret"},
	}
	cmd := AppDeploy{}

	err = cmd.Flags().Parse(true, context.Args)
	c.Assert(err, check.IsNil)
	context.Args = cmd.Flags().Args()

	go func() {
		err = cmd.Run(&context, client)
		c.Assert(err, check.IsNil)
	}()
	<-deploy
	err = cmd.Cancel(context, client)
	c.Assert(err, check.IsNil)
	c.Assert(calledTimes, check.Equals, 3)
}

func (s *S) TestDeployImage(c *check.C) {
	calledTimes := 0
	trans := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "deploy worked\nOK\n", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			calledTimes++
			if req.Body != nil {
				defer req.Body.Close()
			}
			if calledTimes == 1 {
				return req.Method == "GET" && strings.HasSuffix(req.URL.Path, "/apps/secret")
			}
			image := req.FormValue("image")
			c.Assert(image, check.Equals, "registr.com/image-to-deploy")
			c.Assert(req.Header.Get("Content-Type"), check.Equals, "application/x-www-form-urlencoded")
			c.Assert(req.FormValue("origin"), check.Equals, "image")
			return req.Method == "POST" && strings.HasSuffix(req.URL.Path, "/apps/secret/deploy")
		},
	}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	cmd := AppDeploy{}
	err := cmd.Flags().Parse(true, []string{"-a", "secret", "-i", "registr.com/image-to-deploy"})
	c.Assert(err, check.IsNil)
	context.Args = cmd.Flags().Args()
	err = cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(calledTimes, check.Equals, 2)
}

func (s *S) TestDeployRunWithMessage(c *check.C) {
	calledTimes := 0
	var buf bytes.Buffer
	ctx := cmd.Context{Stderr: bytes.NewBufferString(""), Stdout: bytes.NewBufferString("")}
	tm := newTarMaker(&ctx)
	err := tm.targz(&buf, false, "testdata", "..")
	c.Assert(err, check.IsNil)
	trans := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "deploy worked\nOK\n", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			calledTimes++
			if req.Body != nil {
				defer req.Body.Close()
			}
			if calledTimes == 1 {
				return req.Method == "GET" && strings.HasSuffix(req.URL.Path, "/apps/secret")
			}
			file, _, transErr := req.FormFile("file")
			c.Assert(transErr, check.IsNil)
			content, transErr := ioutil.ReadAll(file)
			c.Assert(transErr, check.IsNil)
			c.Assert(content, check.DeepEquals, buf.Bytes())
			c.Assert(req.Header.Get("Content-Type"), check.Matches, "multipart/form-data; boundary=.*")
			c.Assert(req.FormValue("origin"), check.Equals, "app-deploy")
			c.Assert(req.FormValue("message"), check.Equals, "my awesome deploy")
			return req.Method == "POST" && strings.HasSuffix(req.URL.Path, "/apps/secret/deploy")
		},
	}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"testdata", ".."},
	}
	cmd := AppDeploy{}
	err = cmd.Flags().Parse(true, []string{"-a", "secret", "-m", "my awesome deploy"})
	c.Assert(err, check.IsNil)
	err = cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(calledTimes, check.Equals, 2)
}

func (s *S) TestDeployAuthNotOK(c *check.C) {
	calledTimes := 0
	trans := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "Forbidden", Status: http.StatusForbidden},
		CondFunc: func(req *http.Request) bool {
			calledTimes++
			return req.Method == "GET" && strings.HasSuffix(req.URL.Path, "/apps/secret")
		},
	}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"testdata", "..", "-a", "secret"},
	}
	command := AppDeploy{}
	err := command.Flags().Parse(true, context.Args)
	c.Assert(err, check.IsNil)
	context.Args = command.Flags().Args()
	err = command.Run(&context, client)
	c.Assert(err, check.ErrorMatches, "Forbidden")
	c.Assert(calledTimes, check.Equals, 1)
}

func (s *S) TestDeployRunNotOK(c *check.C) {
	trans := cmdtest.Transport{Message: "deploy worked\n", Status: http.StatusOK}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"testdata", "..", "-a", "secret"},
	}
	command := AppDeploy{}
	err := command.Flags().Parse(true, context.Args)
	c.Assert(err, check.IsNil)
	context.Args = command.Flags().Args()
	err = command.Run(&context, client)
	c.Assert(err, check.Equals, cmd.ErrAbortCommand)
}

func (s *S) TestDeployRunFileNotFound(c *check.C) {
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"/tmp/something/that/doesn't/really/exist/im/sure", "-a", "secret"},
	}
	trans := cmdtest.Transport{Message: "OK\n", Status: http.StatusOK}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	command := AppDeploy{}
	err := command.Flags().Parse(true, context.Args)
	c.Assert(err, check.IsNil)
	context.Args = command.Flags().Args()
	err = command.Run(&context, client)
	c.Assert(err, check.NotNil)
}

func (s *S) TestDeployRunWithoutArgsAndImage(c *check.C) {
	var stdout, stderr bytes.Buffer
	ctx := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"-a", "secret"},
	}
	trans := cmdtest.Transport{Message: "OK\n", Status: http.StatusOK}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	command := AppDeploy{}
	err := command.Flags().Parse(true, ctx.Args)
	c.Assert(err, check.IsNil)
	ctx.Args = command.Flags().Args()
	err = command.Run(&ctx, client)
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Equals, "You should provide at least one file or a docker image to deploy.\n")
}

func (s *S) TestDeployRunWithArgsAndImage(c *check.C) {
	var stdout, stderr bytes.Buffer
	ctx := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"testdata", "..", "-a", "secret"},
	}
	trans := cmdtest.Transport{Message: "OK\n", Status: http.StatusOK}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	command := AppDeploy{}
	command.Flags().Parse(true, []string{"-i", "registr.com/image-to-deploy"})
	err := command.Run(&ctx, client)
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Equals, "You can't deploy files and docker image at the same time.\n")
}

func (s *S) TestDeployRunRequestFailure(c *check.C) {
	trans := cmdtest.Transport{Message: "app not found\n", Status: http.StatusNotFound}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"testdata", "..", "-a", "secret"},
	}
	command := AppDeploy{}
	err := command.Flags().Parse(true, context.Args)
	c.Assert(err, check.IsNil)
	context.Args = command.Flags().Args()
	err = command.Run(&context, client)
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Equals, "app not found\n")
}

func (s *S) TestTargzSymlink(c *check.C) {
	if runtime.GOOS == "windows" {
		c.Skip("no symlink support on windows")
	}
	var buf, outBuf bytes.Buffer
	ctx := cmd.Context{Stderr: &buf, Stdout: &outBuf}
	var gzipBuf, tarBuf bytes.Buffer
	tm := newTarMaker(&ctx)
	err := tm.targz(&gzipBuf, false, "testdata-symlink", "..")
	c.Assert(err, check.IsNil)
	gzipReader, err := gzip.NewReader(&gzipBuf)
	c.Assert(err, check.IsNil)
	_, err = io.Copy(&tarBuf, gzipReader)
	c.Assert(err, check.IsNil)
	tarReader := tar.NewReader(&tarBuf)
	var headers [][]string
	for header, err := tarReader.Next(); err == nil; header, err = tarReader.Next() {
		if header.Linkname != "" {
			headers = append(headers, []string{header.Name, header.Linkname})
		}
	}
	expected := [][]string{{"testdata-symlink/link", "test"}}
	c.Assert(headers, check.DeepEquals, expected)
}

func (s *S) TestTargzFailure(c *check.C) {
	var stderr, stdout bytes.Buffer
	ctx := cmd.Context{Stderr: &stderr, Stdout: &stdout}
	var buf bytes.Buffer
	tm := newTarMaker(&ctx)
	err := tm.targz(&buf, false, "/tmp/something/that/definitely/doesn't/exist/right", "testdata")
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Matches, ".*(no such file or directory|cannot find the path specified).*")
}

func (s *S) TestDeployListInfo(c *check.C) {
	var cmd AppDeployList
	c.Assert(cmd.Info(), check.NotNil)
}

func (s *S) TestAppDeployList(c *check.C) {
	var stdout, stderr bytes.Buffer
	result := `
[
  {
    "ID": "54c92d91a46ec0e78501d86b",
    "App": "test",
    "Timestamp": "2015-01-27T18:42:25.725Z",
    "Duration": 18709653486,
    "Commit": "54c92d91a46ec0e78501d86b54c92d91a46ec0e78501d86b",
    "Error": "",
    "Image": "tsuru/app-test:v3",
    "User": "admin@example.com",
    "Origin": "git",
    "CanRollback": true
  },
  {
    "ID": "54c922d0a46ec0e78501d84e",
    "App": "test",
    "Timestamp": "2015-01-28T18:56:32.583Z",
    "Duration": 18781564759,
    "Commit": "",
    "Error": "",
    "Image": "tsuru/app-test:v2",
    "User": "admin@example.com",
    "Origin": "app-deploy",
    "CanRollback": true
  },
  {
    "ID": "54c918a7a46ec0e78501d831",
    "App": "test",
    "Timestamp": "2015-01-28T19:13:11.498Z",
    "Duration": 26064205176,
    "Commit": "",
    "Error": "my-error",
    "Image": "tsuru/app-test:v1",
    "User": "",
    "Origin": "rollback",
    "CanRollback": false
  }
]
`
	timestamps := []string{
		"2015-01-27T18:42:25.725Z",
		"2015-01-28T18:56:32.583Z",
		"2015-01-28T19:13:11.498Z",
	}
	var formatted []string
	for _, t := range timestamps {
		parsed, _ := time.Parse(time.RFC3339, t)
		formatted = append(formatted, formatter.Local(parsed).Format(time.RFC822))
	}
	red := "\x1b[0;31;10m"
	reset := "\x1b[0m"
	expected := `+-----------------------+---------------+-------------------+-----------------------------+----------+
| Image (Rollback)      | Origin        | User              | Date (Duration)             | Error    |
+-----------------------+---------------+-------------------+-----------------------------+----------+
| ` + red + `tsuru/app-test:v1` + reset + `     | ` + red + `rollback` + reset + `      |                   | ` + red + formatted[2] + ` (00:26)` + reset + ` | ` + red + `my-error` + reset + ` |
+-----------------------+---------------+-------------------+-----------------------------+----------+
| tsuru/app-test:v2 (*) | app-deploy    | admin@example.com | ` + formatted[1] + ` (00:18) |          |
+-----------------------+---------------+-------------------+-----------------------------+----------+
| tsuru/app-test:v3 (*) | git (54c92d9) | admin@example.com | ` + formatted[0] + ` (00:18) |          |
+-----------------------+---------------+-------------------+-----------------------------+----------+
`
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	client := cmd.NewClient(&http.Client{Transport: &cmdtest.Transport{Message: result, Status: http.StatusOK}}, nil, manager)
	command := AppDeployList{}
	err := command.Flags().Parse(true, []string{"--app", "test"})
	c.Assert(err, check.IsNil)
	context.Args = command.Flags().Args()
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, expected)
}

func (s *S) TestDeployRunAppWithouDeploy(c *check.C) {
	trans := cmdtest.Transport{Message: "", Status: http.StatusNoContent}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	command := AppDeployList{}
	command.Flags().Parse(true, []string{"-a", "secret"})
	err := command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, "App secret has no deploy.\n")
}

func (s *S) TestAppDeployRollbackInfo(c *check.C) {
	c.Assert((&AppDeployRollback{}).Info(), check.NotNil)
}

func (s *S) TestAppDeployRollback(c *check.C) {
	var (
		called         bool
		stdout, stderr bytes.Buffer
	)
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"my-image"},
	}
	expectedOut := "-- deployed --"
	msg := tsuruIo.SimpleJsonMessage{Message: expectedOut}
	result, err := json.Marshal(msg)
	c.Assert(err, check.IsNil)
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			method := req.Method == "POST"
			path := strings.HasSuffix(req.URL.Path, "/apps/arrakis/deploy/rollback")
			image := req.FormValue("image") == "my-image"
			rollback := req.FormValue("origin") == "rollback"
			return method && path && image && rollback
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	command := AppDeployRollback{}
	command.Flags().Parse(true, []string{"--app", "arrakis", "-y"})
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(called, check.Equals, true)
	c.Assert(stdout.String(), check.Equals, expectedOut)
}

func (s *S) TestAppDeployRollbackUpdateInfo(c *check.C) {
	c.Assert((&AppDeployRollbackUpdate{}).Info(), check.NotNil)
}

func (s *S) TestAppDeployRollbackUpdate(c *check.C) {
	var (
		called         bool
		stdout, stderr bytes.Buffer
	)
	context := cmd.Context{Stdout: &stdout, Stderr: &stderr}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			method := req.Method == http.MethodPut
			path := strings.HasSuffix(req.URL.Path, "/apps/zilean/deploy/rollback/update")
			image := req.FormValue("image") == "caitlyn"
			enable := req.FormValue("disable") == "true"
			reason := req.FormValue("reason") == "DEMACIA"
			rollback := req.FormValue("origin") == "rollback"
			return method && path && image && rollback && reason && enable
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	command := AppDeployRollbackUpdate{}
	command.Flags().Parse(true, []string{"--app", "zilean", "-i", "caitlyn", "-r", "DEMACIA", "-d"})
	err := command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(called, check.Equals, true)
	c.Assert(stdout.String(), check.Equals, "")
}

func (s *S) TestAppDeployRollbackUpdateDisabling(c *check.C) {
	var (
		called         bool
		stdout, stderr bytes.Buffer
	)
	context := cmd.Context{Stdout: &stdout, Stderr: &stderr}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			method := req.Method == http.MethodPut
			path := strings.HasSuffix(req.URL.Path, "/apps/xayah/deploy/rollback/update")
			image := req.FormValue("image") == "rakan"
			enable := req.FormValue("disable") == "false"
			reason := req.FormValue("reason") == "vastayan"
			rollback := req.FormValue("origin") == "rollback"
			return method && path && image && rollback && reason && enable
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	command := AppDeployRollbackUpdate{}
	command.Flags().Parse(true, []string{"--app", "xayah", "-i", "rakan", "-r", "vastayan"})
	err := command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(called, check.Equals, true)
	c.Assert(stdout.String(), check.Equals, "")
}

func (s *S) TestAppDeployRebuildInfo(c *check.C) {
	c.Assert((&AppDeployRebuild{}).Info(), check.NotNil)
}

func (s *S) TestAppDeployRebuild(c *check.C) {
	var (
		called         bool
		stdout, stderr bytes.Buffer
	)
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	expectedOut := "---- rebuild ----"
	msg := tsuruIo.SimpleJsonMessage{Message: expectedOut}
	result, err := json.Marshal(msg)
	c.Assert(err, check.IsNil)
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			method := req.Method == "POST"
			path := strings.HasSuffix(req.URL.Path, "/apps/myapp/deploy/rebuild")
			rebuild := req.FormValue("origin") == "rebuild"
			return method && path && rebuild
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	command := AppDeployRebuild{}
	command.Flags().Parse(true, []string{"--app", "myapp"})
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(called, check.Equals, true)
	c.Assert(stdout.String(), check.Equals, expectedOut)
}

func (s *S) TestDeployRunTarGeneration(c *check.C) {
	var foundFiles []string
	trans := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "deploy worked\nOK\n", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			if req.Method == "GET" {
				return true
			}
			defer req.Body.Close()
			file, _, transErr := req.FormFile("file")
			c.Assert(transErr, check.IsNil)
			gzReader, transErr := gzip.NewReader(file)
			c.Assert(transErr, check.IsNil)
			tarReader := tar.NewReader(gzReader)
			foundFiles = nil
			for {
				header, transErr := tarReader.Next()
				if transErr == io.EOF {
					break
				}
				c.Assert(transErr, check.IsNil)
				foundFiles = append(foundFiles, header.Name)
			}
			return true
		},
	}
	client := cmd.NewClient(&http.Client{Transport: &trans}, nil, manager)
	tests := []struct {
		files          []string
		ignored        []string
		deployArgs     []string
		flags          []string
		expected       []string
		expectedStderr string
		absPath        bool
	}{
		{
			files:      []string{"f1", "f2", "d1/f3", "d1/d2/f4"},
			deployArgs: []string{"."},
			expected:   []string{"f1", "f2", "d1", "d1/f3", "d1/d2", "d1/d2/f4"},
			flags:      []string{"-a", "secret"},
		},
		{
			files:      []string{"testdata/deploy/file1.txt", "testdata/deploy2/file2.txt"},
			deployArgs: []string{"testdata/deploy/file1.txt", "testdata/deploy2/file2.txt"},
			expected:   []string{"testdata/deploy/file1.txt", "testdata/deploy2/file2.txt"},
			flags:      []string{"-a", "secret"},
		},
		{
			files:      []string{"testdata/deploy/file1.txt", "testdata/deploy2/file2.txt"},
			deployArgs: []string{"testdata/deploy/file1.txt", "testdata/deploy2/file2.txt"},
			flags:      []string{"-a", "secret", "-f"},
			expected:   []string{"file1.txt", "file2.txt"},
		},
		{
			files:      []string{"testdata/deploy/file1.txt", "testdata/deploy/file2.txt", "testdata/deploy2/file3.txt", "testdata/deploy2/directory/file4.txt"},
			deployArgs: []string{"testdata/deploy", "testdata/deploy2"},
			flags:      []string{"-a", "secret"},
			expected:   []string{"testdata/deploy", "testdata/deploy2", "testdata/deploy/file1.txt", "testdata/deploy/file2.txt", "testdata/deploy2/file3.txt", "testdata/deploy2/directory", "testdata/deploy2/directory/file4.txt"},
		},
		{
			files:      []string{"testdata/deploy/file1.txt", "testdata/deploy/file2.txt", "testdata/deploy2/file3.txt", "testdata/deploy2/directory/file4.txt"},
			deployArgs: []string{"testdata/deploy", "testdata/deploy2"},
			flags:      []string{"-a", "secret", "-f"},
			expected:   []string{"file1.txt", "file2.txt", "file3.txt", "directory", "directory/file4.txt"},
		},
		{
			files:          []string{"testdata/deploy/file1.txt", "testdata/deploy/file2.txt", "testdata/deploy/directory/file.txt"},
			deployArgs:     []string{"testdata/deploy", ".."},
			flags:          []string{"-a", "secret"},
			expected:       []string{"testdata/deploy", "testdata/deploy/file1.txt", "testdata/deploy/file2.txt", "testdata/deploy/directory", "testdata/deploy/directory/file.txt"},
			expectedStderr: `Warning: skipping "\.\."`,
		},
		{
			files:      []string{"testdata/deploy/file1.txt", "testdata/deploy/file2.txt", "testdata/deploy/directory/file.txt"},
			deployArgs: []string{"testdata/deploy"},
			flags:      []string{"-a", "secret"},
			expected:   []string{"file1.txt", "file2.txt", "directory", "directory/file.txt"},
		},
		{
			files:      []string{"testdata/deploy2/file1.txt", "testdata/deploy2/file2.txt", "testdata/deploy2/directory/file.txt", "testdata/deploy2/directory/dir2/file.txt"},
			ignored:    []string{"*.txt"},
			flags:      []string{"-a", "secret"},
			deployArgs: []string{"testdata/deploy2"},
			expected:   []string{"directory", "directory/dir2"},
		},
		{
			files:      []string{"testdata/deploy/file1.txt", "testdata/deploy/file2.txt", "testdata/deploy2/file3.txt", "testdata/deploy2/directory/file4.txt"},
			deployArgs: []string{"testdata/deploy", "testdata/deploy2"},
			ignored:    []string{"*.txt"},
			flags:      []string{"-a", "secret"},
			expected:   []string{"testdata/deploy", "testdata/deploy2", "testdata/deploy2/directory"},
		},
		{
			files:      []string{"testdata/deploy/file1.txt", "testdata/deploy/file2.txt", "testdata/deploy2/file3.txt", "testdata/deploy2/directory/file4.txt"},
			deployArgs: []string{"testdata/deploy", "testdata/deploy2"},
			ignored:    []string{"*.txt"},
			flags:      []string{"-a", "secret", "-f"},
			expected:   []string{"directory"},
		},
		{
			files:      []string{"testdata/deploy2/file1.txt", "testdata/deploy2/file2.txt", "testdata/deploy2/directory/file.txt", "testdata/deploy2/directory/dir2/file.txt"},
			ignored:    []string{"*.txt"},
			deployArgs: []string{"testdata/deploy2"},
			flags:      []string{"-a", "secret"},
			expected:   []string{"directory", "directory/dir2"},
			absPath:    true,
		},
		{
			files:      []string{"file1.txt", "file2.txt", "directory/file.txt", "directory/dir2/file.txt"},
			ignored:    []string{"*.txt"},
			deployArgs: []string{"."},
			flags:      []string{"-a", "secret"},
			expected:   []string{".tsuruignore", "directory", "directory/dir2"},
		},
		{
			files:      []string{"testdata/deploy2/file1.txt", "testdata/deploy2/file2.txt", "testdata/deploy2/directory/file.txt", "testdata/deploy2/directory/dir2/file.txt"},
			ignored:    []string{"directory"},
			deployArgs: []string{"testdata/deploy2"},
			flags:      []string{"-a", "secret"},
			expected:   []string{"file1.txt", "file2.txt"},
		},
		{
			files:      []string{"testdata/deploy2/file1.txt", "testdata/deploy2/file2.txt", "testdata/deploy2/directory/file.txt", "testdata/deploy2/directory/dir2/file.txt"},
			ignored:    []string{"*/dir2"},
			deployArgs: []string{"testdata/deploy2"},
			flags:      []string{"-a", "secret"},
			expected:   []string{"directory", "directory/file.txt", "file1.txt", "file2.txt"},
		},
		{
			files:      []string{"testdata/deploy2/file1.txt", "testdata/deploy2/file2.txt", "testdata/deploy2/directory/file.txt", "testdata/deploy2/directory/dir2/file.txt"},
			ignored:    []string{"directory/dir2/*"},
			deployArgs: []string{"testdata/deploy2"},
			flags:      []string{"-a", "secret"},
			expected:   []string{"directory", "directory/dir2", "directory/file.txt", "file1.txt", "file2.txt"},
		},
	}
	origDir, err := os.Getwd()
	c.Assert(err, check.IsNil)
	defer os.Chdir(origDir)
	for i, tt := range tests {
		comment := check.Commentf("test %d", i)

		tmpDir, err := ioutil.TempDir("", "integration")
		c.Assert(err, check.IsNil)
		defer os.RemoveAll(tmpDir)
		err = os.Chdir(tmpDir)
		c.Assert(err, check.IsNil)
		for _, f := range tt.files {
			err = os.MkdirAll(path.Dir(f), 0700)
			c.Assert(err, check.IsNil)
			err = ioutil.WriteFile(f, []byte{}, 0600)
			c.Assert(err, check.IsNil)
		}
		if len(tt.ignored) > 0 {
			err = ioutil.WriteFile(".tsuruignore", []byte(strings.Join(tt.ignored, "\n")), 0600)
			c.Assert(err, check.IsNil)
		}

		var stdout, stderr bytes.Buffer
		if tt.absPath {
			for i, f := range tt.deployArgs {
				tt.deployArgs[i], err = filepath.Abs(f)
				c.Assert(err, check.IsNil)
			}
		}
		context := cmd.Context{
			Stdout: &stdout,
			Stderr: &stderr,
			Args:   tt.deployArgs,
		}
		cmd := AppDeploy{}
		err = cmd.Flags().Parse(true, append([]string{"-a", "secret"}, tt.flags...))
		c.Assert(err, check.IsNil)
		err = cmd.Run(&context, client)
		c.Assert(err, check.IsNil, comment)
		sort.Strings(foundFiles)
		sort.Strings(tt.expected)
		c.Assert(foundFiles, check.DeepEquals, tt.expected, comment)
		c.Assert(stderr.String(), check.Matches, tt.expectedStderr, comment)
	}
}


text:
     Feedback

# endif


text:
require 'spec_helper'

module Rubocop
  module Cop
    module Style
      describe Documentation do
        subject(:documentation) { Documentation.new }

        it 'registers an offence for non-empty class' do
          inspect_source(documentation,
                         ['class My_Class',
                          '  TEST = 20',
                          'end'
                         ])
          expect(documentation.offences.size).to eq(1)
        end

        it 'registers an offence for non-namespace' do
          inspect_source(documentation,
                         ['module My_Class',
                          '  TEST = 20',
                          'end'
                         ])
          expect(documentation.offences.size).to eq(1)
        end

        it 'registers an offence for empty module without documentation' do
          # Because why would you have an empty module? It requires some
          # explanation.
          inspect_source(documentation,
                         ['module Test',
                          'end'
                         ])
          expect(documentation.offences.size).to eq(1)
        end

        it 'accepts non-empty class with documentation' do
          inspect_source(documentation,
                         ['# class comment',
                          'class My_Class',
                          '  TEST = 20',
                          'end'
                         ])
          expect(documentation.offences).to be_empty
        end

        it 'accepts non-empty module with documentation' do
          inspect_source(documentation,
                         ['# class comment',
                          'module My_Class',
                          '  TEST = 20',
                          'end'
                         ])
          expect(documentation.offences).to be_empty
        end

        it 'accepts empty class without documentation' do
          inspect_source(documentation,
                         ['class My_Class',
                          'end'
                         ])
          expect(documentation.offences).to be_empty
        end

        it 'accepts namespace module without documentation' do
          inspect_source(documentation,
                         ['module Test',
                          '  class A; end',
                          '  class B; end',
                          'end'
                         ])
          expect(documentation.offences).to be_empty
        end
      end
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>MNE-CPP: D:/Users/Christoph/GitHub/mne-cpp/applications/mne_x/plugins/brainmonitor Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

MNE-CPP
    beta 1.0

Main Page

Related Pages

Modules

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

applications

mne_x

plugins

brainmonitor

brainmonitor Directory Reference

Files

file  	ui_brainmonitorabout.h [code]

file  	ui_brainmonitorrun.h [code]

file  	ui_brainmonitorsetup.h [code]

<address class="footer">
Generated on Fri Mar 27 2015 22:54:46 for MNE-CPP by

 1.8.9.1
</address>


text:
@implementation DropboxRemoveFolderMemberArg (DictionarySerializer)

- (NSDictionary *)dictionaryFromParams
{
    return @{ @"shared_folder_id": self.sharedFolderID,
              @"member": [self.member dictionaryFromParams],
              @"leave_a_copy": @(self.leaveACopy) };
}

@end


text:
{% if messages and not page.children.count %}

{% for message in messages %}

{{ message }}

    {% endfor %}

{% endif %}
{% include "admin/cms/page/menu_item.html" %}


text:
#ifndef WebSelectElement_h
#define WebSelectElement_h

#include "WebFormControlElement.h"
#include "WebOptionElement.h"
#include "platform/WebVector.h"

#if WEBKIT_IMPLEMENTATION
namespace WebCore { class HTMLSelectElement; }
#endif

namespace WebKit {

// Provides readonly access to some properties of a DOM select element node.
class WebSelectElement : public WebFormControlElement {
public:
    WebSelectElement() : WebFormControlElement() { }
    WebSelectElement(const WebSelectElement& element) : WebFormControlElement(element) { }

    WebSelectElement& operator=(const WebSelectElement& element)
    {
        WebFormControlElement::assign(element);
        return *this;
    }
    void assign(const WebSelectElement& element) { WebFormControlElement::assign(element); }

    WEBKIT_EXPORT void setValue(const WebString&);
    WEBKIT_EXPORT WebString value() const;
    WEBKIT_EXPORT WebVector<WebElement> listItems() const;

#if WEBKIT_IMPLEMENTATION
    WebSelectElement(const WTF::PassRefPtr<WebCore::HTMLSelectElement>&);
    WebSelectElement& operator=(const WTF::PassRefPtr<WebCore::HTMLSelectElement>&);
    operator WTF::PassRefPtr<WebCore::HTMLSelectElement>() const;
#endif
};

} // namespace WebKit

#endif


text:
DECLARE_EFFECT("Gain", Plugin_Gain)
DECLARE_EFFECT("SOFA Spatializer", Plugin_SofaSpatializer)
#endif


text:
<?php
/******************************************************
 # backendinittime.action.php
 # Authors:		Rick Hofstede <r.j.hofstede@utwente.nl>
 #              Luuk Hendriks
 # University of Twente, The Netherlands
 #
 # LICENSE TERMS: 3-clause BSD license (outlined in license.html)
 *****************************************************/

    require_once("../../config.php");
    header("content-type: application/json");
    require_once("/var/www/nfsen/conf.php");
    require_once("/var/www/nfsen/nfsenutil.php");

    if (!function_exists('ReportLog')) {
        function ReportLog() {
            // dummy function to avoid PHP errors
        }
    }

    $db = new PDO($config['profiling-database.dsn']);
    $data = array();

    $query = "
        SELECT      p.time AS time,
                    p.target_count_scan AS target_count_scan,
                    p.target_count_bruteforce AS target_count_bruteforce,
                    p.target_count_compromise AS target_count_compromise
        FROM        profile p
        ORDER BY    time DESC
        LIMIT       5000
    ";

    $stmnt = $db->prepare($query);
    $stmnt->execute();

    $result = $stmnt->fetchAll(PDO::FETCH_ASSOC);
    unset($stmnt);

    // Convert all timestamps to UNIX timestamps
    foreach ($result as &$row) {
        $row['target_count_scan'] = intval($row['target_count_scan']);
        $row['target_count_bruteforce'] = intval($row['target_count_bruteforce']);
        $row['target_count_compromise'] = intval($row['target_count_compromise']);

        // Convert to UNIX timestamps
        $row['time'] = strtotime($row['time']);

        // flot expects millisecond timestamps
        $row['time'] *= 1000;
    }

    $old_result = $result;
    $result = array('scan' => array(), 'bruteforce' => array(), 'compromise' => array());

    // Find maxima and minima
    $target_min = -1; $target_max = -1;
    $time_min = -1; $time_max = -1;
    foreach ($old_result as $row) {
        if ($time_min == -1 || $row['time'] < $time_min) {
            $time_min = $row['time'];
        }
        if ($time_max == -1 || $row['time'] > $time_max) {
            $time_max = $row['time'];
        }

        if ($target_min == -1 || min($row['target_count_scan'], $row['target_count_bruteforce'], $row['target_count_compromise']) < $target_min) {
            $target_min = min($row['target_count_scan'], $row['target_count_bruteforce'], $row['target_count_compromise']);
        }
        if ($target_max == -1 || max($row['target_count_scan'], $row['target_count_bruteforce'], $row['target_count_compromise']) > $target_max) {
            $target_max = max($row['target_count_scan'], $row['target_count_bruteforce'], $row['target_count_compromise']);
        }

        array_push($result['scan'], array($row['time'], $row['target_count_scan']));
        array_push($result['bruteforce'], array($row['time'], $row['target_count_bruteforce']));
        array_push($result['compromise'], array($row['time'], $row['target_count_compromise']));
    }

    $data['target'] = array('target_min' => $target_min, 'target_max' => $target_max, 'time_min' => $time_min, 'time_max' => $time_max);
    $data['target']['data'] = $result;

    $query = "
        SELECT      p.time AS time,
                    p.flow_records AS flow_records,
                    p.run_time AS run_time
        FROM        profile p
        ORDER BY    time DESC
        LIMIT       5000
    ";

    $stmnt = $db->prepare($query);
    $stmnt->execute();

    $result = $stmnt->fetchAll(PDO::FETCH_ASSOC);
    unset($stmnt);

    // Convert all timestamps to UNIX timestamps
    foreach ($result as &$row) {
        $row['flow_records'] = intval($row['flow_records']);
        $row['run_time'] = intval($row['run_time']);

        // Convert to UNIX timestamps
        $row['time'] = strtotime($row['time']);

        // flot expects millisecond timestamps
        $row['time'] *= 1000;
    }

    $old_result = $result;
    $result = array('flow_records' => array(), 'run_time' => array());

    // Find maxima and minima
    $flow_records_min = -1; $flow_records_max = -1;
    $time_min = -1; $time_max = -1;
    foreach ($old_result as $row) {
        if ($time_min == -1 || $row['time'] < $time_min) {
            $time_min = $row['time'];
        }
        if ($time_max == -1 || $row['time'] > $time_max) {
            $time_max = $row['time'];
        }

        if ($flow_records_min == -1 || $row['flow_records'] < $flow_records_min) {
            $flow_records_min = $row['flow_records'];
        }
        if ($flow_records_max == -1 || $row['flow_records'] > $flow_records_max) {
            $flow_records_max = $row['flow_records'];
        }

        array_push($result['flow_records'], array($row['time'], $row['flow_records']));
        array_push($result['run_time'], array($row['time'], $row['run_time']));
    }

    $data['performance'] = array('flow_records_min' => $flow_records_min, 'flow_records_max' => $flow_records_max, 'time_min' => $time_min, 'time_max' => $time_max);
    $data['performance']['data'] = $result;

    echo json_encode($data);
    die();
?>


text:
package io.dstream.tez.io;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;

import org.apache.commons.io.output.ByteArrayOutputStream;

/**
 *
 */
@SuppressWarnings("unchecked")
public abstract class TypeAwareWritable<T> implements NewWritable<T> {

	protected T value;

	private byte valueType = NULL;

	private final ValueEncoder valueEncoder = new ValueEncoder();

	/**
	 *
	 */
	@Override
	public void setValue(T value) {
		this.value = value;
		this.determineValueType(value);
		this.valueType = this.valueEncoder.valueType;
	}

	/**
	 *
	 */
	@Override
	public T getValue() {
		return this.value;
	}

	/**
	 *
	 */
	@Override
	public int hashCode() {
		int hashCode = 0;
		if (this.value != null){
			hashCode = this.value.hashCode();
		}
		return hashCode;
	}

	/**
	 *
	 */
	@Override
	public void write(DataOutput out) throws IOException {
		out.writeByte(this.valueType);
		if (this.valueType != NULL){
			try {
				out.write(this.valueEncoder.valueBytes);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 *
	 */
	@Override
	public void readFields(DataInput in) throws IOException {
		this.valueType = in.readByte();
		switch (this.valueType) {
		case INTEGER:
			this.value = (T) Integer.valueOf(in.readInt());
			break;
		case LONG:
			this.value = (T) Long.valueOf(in.readLong());
			break;
		case NULL:
			this.value = null;
			break;
		case OBJECT:
			try {
				ObjectInputStream ois = new ObjectInputStream((DataInputStream) in);
				T value = (T) ois.readObject();
				this.value = value;
			} catch (Exception e) {
				throw new IllegalStateException(
						"Failed to deserialize value", e);
			}
			break;
		default:
			throw new IllegalStateException(
					"Unsupported or unrecognized value type: "
							+ this.valueType);
		}
	}

	/**
	 *
	 */
	@Override
	public String toString(){
		if (this.value == null){
			return null;
		} else {
			return this.value.toString();
		}
	}

	/**
	 * NOTE: The below code is temporary and both conversion and ser/deser will be exposed through externally
	 * configurable framework!
	 *
	 * @param value
	 * @return
	 */
	private void determineValueType(Object value){
		if (value instanceof Integer){
			this.valueEncoder.valueType = INTEGER;
			this.valueEncoder.valueBytes = ByteBuffer.allocate(4).putInt((Integer)value).array();
		}
		else if (value instanceof Long) {
			this.valueEncoder.valueType = LONG;
			this.valueEncoder.valueBytes = ByteBuffer.allocate(8).putLong((Long)value).array();
		}
		else if (value == null){
			this.valueEncoder.valueType = NULL;
		}
		else {
			ObjectOutputStream oos = null;
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				oos = new ObjectOutputStream(bos);
				oos.writeObject(value);
				this.valueEncoder.valueType = OBJECT;
				this.valueEncoder.valueBytes = bos.toByteArray();
			} catch (Exception e) {
				throw new IllegalStateException("Failed to serialize value: " + value, e);
			} finally {
				try {
					if (oos != null){
						oos.close();
					}
				} catch (Exception e2) {/*ignore*/}
			}
		}
	}

	private final static byte INTEGER = -128;
	private final static byte STRING = -127;
	private final static byte LONG = -126;
	private final static byte OBJECT = -125;
	private final static byte NULL = -124;

	/**
	 */
	private class ValueEncoder {
		private byte valueType;
		private byte[] valueBytes;
	}
}


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

<title>Uses of Class org.springframework.orm.jpa.EntityManagerHolder (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.springframework.orm.jpa.EntityManagerHolder

Packages that use EntityManagerHolder

Package
Description

org.springframework.orm.hibernate5

Package providing integration of
 Hibernate 5.x
 with Spring concepts.

Uses of EntityManagerHolder in org.springframework.orm.hibernate5

Subclasses of EntityManagerHolder in org.springframework.orm.hibernate5

Modifier and Type
Class and Description

class
SessionHolder

Resource holder wrapping a Hibernate Session (plus an optional Transaction).

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
"""
Unit system for physical quantities; include definition of constants.
"""

from __future__ import division
import numbers

from sympy import sympify, Expr, Number, Pow, Mul, latex
#from sympy.core.decorators import _sympifyit, call_highest_priority
from .dimensions import Dimension, DimensionSystem
#from operator import __truediv__
from sympy.core.compatibility import reduce

class Unit(Expr):
    """
    Class for the units.

    A unit is defined by two things:

    - a dimension;
    - a factor.

    The factor represents the position of the unit with respect to the
    canonical unit of this dimension. For example if we choose the gram to be
    the canonical dimension for the mass, then by definition its factor is 1;
    on the other hand the factor defined here for kilogram is 1000, even when
    it is a base unit. The explanation is that here we do not have defined any
    system that we could use as a reference: here the canonical unit is the
    only scale, and thus the only available origin.

    Additionnaly one can add a prefix and an abbreviation. The only utility of
    the former is to provide a shorthand for some units, but it is never used
    among computations; it appears only when defining and printing units. The
    same remark applies to the abbreviation.

    All operations (pow, mul, etc.) are defined as the corresponding ones
    acting on the factor (a number) and the dimension.
    """

    is_positive = True    # make sqrt(m**2) --> m
    is_commutative = True
    is_number = False
    _op_priority = 10.0

    def __new__(cls, dim, abbrev="", factor=1, prefix=None, **assumptions):
        """
        Create a new unit instance.

        ``dim`` can be a Dimension or Unit object. The latter allows to
        construct derived units and constants. Note that the argument prefix
        is ignored if ``dim`` is a Unit instance and already has a prefix.
        """

        factor = sympify(factor)

        obj_abbrev = abbrev
        obj_factor = factor
        obj_dim = dim
        obj_prefix = prefix

        if isinstance(dim, Unit):
            obj_factor = factor * dim.factor
            obj_dim = dim.dim
            if not abbrev:
                obj_abbrev = dim.abbrev
            #TODO: find a better handling when dim has already a prefix
            if dim.prefix is None and prefix is not None:
                obj_prefix = prefix
            else:
                obj_prefix = None
        else:
            if not isinstance(dim, Dimension):
                raise TypeError("'dim' object should be Unit or Dimension "
                                "instance; found %s" % type(dim))

        # compute the total factor - including the prefix - to pass to Expr
        if obj_prefix is not None:
            arg_factor = obj_prefix.factor * obj_factor
        else:
            arg_factor = obj_factor

        # we can not define obj at the beginning and define its attributes
        # in the previous conditions because one needs to compute the total
        # factor and pass it in args
        obj = Expr.__new__(cls, arg_factor, obj_dim, **assumptions)

        obj._abbrev = obj_abbrev
        obj._factor = obj_factor
        obj.dim = obj_dim
        obj.prefix = obj_prefix

        return obj

    @property
    def factor(self):
        """
        Overall magnitude of the unit.
        """

        if self.prefix is not None:
            return self.prefix.factor * self._factor
        else:
            return self._factor

    @property
    def abbrev(self):
        """
        Symbol representing the unit name.

        Prepend the abbreviation with the prefix symbol if it is defines.
        """

        if self._abbrev == "":
            #return ""
            return self.abbrev_dim
        if self.prefix is not None:
            return self.prefix.abbrev + self._abbrev
        else:
            return self._abbrev

    @property
    def abbrev_dim(self):
        """
        Abbreviation which use only intrinsinc properties of the unit.
        """

        return '(%g %s)' % (self.factor, self.dim)

    def __str__(self):
        if self.abbrev != "":

            factor = 1.0 #self.factor
            if self._abbrev == 'g':
                factor = 1.0
            elif self.prefix:
                factor = factor/self.prefix.factor

            if factor != 1.0:
                #return '{:g}'.format(float(self.factor)) + self.abbrev
                return latex(factor)+self.abbrev.replace('mu','µ')
            else:
                return self.abbrev.replace('mu','µ')
        else:
            return self.abbrev_dim

    def __repr__(self):
        #return self.abbrev_dim
        return self.abbrev #.replace('mu','µ')

    def add(self, other):
        if not isinstance(other, Unit):
            raise TypeError("Only unit can be added; '%s' is not valid"
                            % type(other))
        else:
            if self.is_compatible(other):
                return Unit(self.dim, factor=self.factor + other.factor)
            else:
                raise ValueError("Only dimension which are equal can be "
                                 "added; '%s' and '%s' are different"
                                 % (self, other))

    def sub(self, other):

        if not isinstance(other, Unit):
            raise TypeError("Only unit can be added; '%s' is not valid"
                            % type(other))
        else:
            if self.is_compatible(other):
                return Unit(self.dim, factor=self.factor - other.factor)
            else:
                raise ValueError("Only dimension which are equal can be "
                                 "subtracted; '%s' and '%s' are different"
                                 % (self, other))

#     @_sympifyit('other', NotImplemented)
#     @call_highest_priority('__rpow__')
#     def __pow__(self, other):
#         return self.pow(other)

    def pow(self, other):

        other = sympify(other)
        #TODO: check consistency when having rational, float...
        if isinstance(other, (numbers.Real, Number)):
            if other == 0:
                return sympify(1)
            elif other == 1:
                return self
            else:
                factor = (self.factor**other).evalf()
                dim = self.dim.pow(other)
                abbrev = '' #latex(Pow(self.dim, other).evalf())
                if dim.is_dimensionless:
                    return factor
                else:
                    return Unit(dim, factor=factor, abbrev=abbrev)
        else:
            return Pow(self, other)

#     @_sympifyit('other', NotImplemented)
#     @call_highest_priority('__rmul__')
#     def __mul__(self, other):
#         return self.mul(other)

    def mul(self, other):
        other = sympify(other)

        if other == 1:
            return self
        elif isinstance(other, Unit):
            factor = self.factor * other.factor
            dim = self.dim.mul(other.dim)
            if dim.is_dimensionless:
                return factor
            else:
                arg = Mul(self,other)
                abbrev = latex(arg)
                unit = Unit(dim, factor=factor, abbrev=abbrev)
                #unit.args = [arg,]
                return unit
        #TODO: what to do when other is a number? return a unit or a quantity?
        #      or nothing special?
        #elif isinstance(other, Number):
        #    return Quantity(other, self)
        #elif other.is_number:
        #    factor = self.factor * other
        #    return Unit(self.dim, factor=factor)
        else:
            return Mul(self, other)

#     @_sympifyit('other', NotImplemented)
#     @call_highest_priority('__rdiv__')
#     def __div__(self, other):
#         return self.div(other)
#
#     __truediv__ = __div__

    def div(self, other):

        other = sympify(other)

        if other == 1:
            return self
        elif isinstance(other, Unit):
            factor = self.factor / other.factor
            abbrev = '' #latex(Mul(self, Pow(other, -1)))
            dim = self.dim.div(other.dim)
            if dim.is_dimensionless:
                return factor
            else:
                return Unit(dim, factor=factor, abbrev=abbrev)
        #TODO same remark as in __mul__
        #elif isinstance(other, Number):
        #    return Quantity(1/other, unit)
        #elif other.is_number:
            #factor = self.factor / other
            #return Unit(self.dimension, factor=factor, system=system)
        else:
            return Mul(self, Pow(other, -1))

#     @_sympifyit('other', NotImplemented)
#     @call_highest_priority('__div__')
#     def __rdiv__(self, other):
#         return self.rdiv(other)
#
#     __rtruediv__ = __rdiv__

    def rdiv(self, other):

        return self.pow(-1).mul(other)

    def is_compatible(self, other):
        """
        Test if argument is a unit and has the same dimension as self.

        This function is used to verify that some operations can be done.
        """

        if isinstance(other, Unit):
            if self.dim == other.dim:
                return True

        return False

    @property
    def as_quantity(self):
        """
        Convert the unit to a quantity.

        The quantity unit is given by the unit of factor 1 and with identical
        dimension.

            >>> from sympy.physics.unitsystems.dimensions import Dimension
            >>> from sympy.physics.unitsystems.units import Unit
            >>> length = Dimension(length=1)
            >>> u = Unit(length, factor=10)
            >>> q = u.as_quantity
            >>> q.factor
            10
            >>> q.unit == Unit(length)
            True
        """

        from .quantities import Quantity
        #return Quantity(self.factor, Unit(self.dim, abbrev=self.abbrev))
        return Quantity(1.0, self, abbrev=self.abbrev)

class Constant(Unit):
    """
    Physical constant.

    In our framework a constant is considered as a unit, to which humans givesa
    special sense, because we believe that they give us a special information
    on nature; but it is just a demonstration of our ignorance.
    """

    #TODO: to begin nothing more is needed, but we prepare a dedicated class
    #      for further developments

    def __str__(self):
        if self.abbrev != "":
            return self.abbrev
        else:
            return self.abbrev_dim

class UnitSystem(object):
    """
    UnitSystem represents a coherent set of units.

    A unit system is basically a dimension system with notions of scales. Many
    of the methods are defined in the same way.

    It is much better if all base units have a symbol.
    """

    def __init__(self, base, units=(), name="", descr=""):
        self.name = name
        self.descr = descr

        # construct the associated dimension system
        self._system = DimensionSystem([u.dim for u in base],
                                       [u.dim for u in units])

        if self.is_consistent is False:
            raise ValueError("The system with basis '%s' is not consistent"
                             % str(self._base_units))

        self._units = tuple(set(base) | set(units))

        # create a dict linkin
        # this is possible since we have already verified that the base units
        # form a coherent system
        base_dict = dict((u.dim, u) for u in base)
        # order the base units in the same order than the dimensions in the
        # associated system, in order to ensure that we get always the same
        self._base_units = tuple(base_dict[d] for d in self._system._base_dims)

    def __str__(self):
        """
        Return the name of the system.

        If it does not exist, then it makes a list of symbols (or names) of
        the base dimensions.
        """

        if self.name != "":
            return self.name
        else:
            return "(%s)" % ", ".join(str(d) for d in self._base_units)

    def __repr__(self):
        return '<UnitSystem: %s>' % repr(self._base_units)

    def __getitem__(self, key):
        """
        Shortcut to the get_unit method, using key access.
        """

        u = self.get_unit(key)

        #TODO: really want to raise an error?
        if u is None:
            raise KeyError(key)

        return u

    def __call__(self, other):
        """
        Display the argument in the current system units (or dimensions).

        The argument can be a dimension (call print_dim_base of the system),
        a unit (call print_unit_base) or a quantity
        """
        from sympy.physics.unitsystems import Quantity

        if isinstance(other, Dimension):
            return self._system(other)
        elif isinstance(other, Unit):
            return self.print_unit_base(other)
        elif isinstance(other, Quantity):
            return "%g %s" % (other.factor, self.print_unit_base(other.unit))
        else:
            raise TypeError("System is callable only with unit, dimension "
                            "or quantity.")

    def get_unit(self, unit):
        """
        Find a specific unit which is part of the system.

        unit can be a string or a dimension object. If no unit is found, then
        return None.
        """

        #TODO: if the argument is a list, return a list of all matching dims

        found_unit = None

        #TODO: use copy instead of direct assignment for found_dim?
        if isinstance(unit, str):
            for u in self._units:
                #TODO: verify not only abbrev
                if unit in (u.abbrev,):
                    found_unit = u
                    break
        elif isinstance(unit, Unit):
            try:
                i = self._units.index(unit)
                found_unit = self._units[i]
            except ValueError:
                pass

        return found_unit

    def extend(self, base, units=(), name="", description=""):
        """
        Extend the current system into a new one.

        Take the base and normal units of the current system to merge
        them to the base and normal units given in argument.
        If not provided, name and description are overriden by empty strings.
        """

        base = self._base_units + tuple(base)
        units = self._units + tuple(units)

        return UnitSystem(base, units, name, description)

    def print_unit_base(self, unit):
        """
        Give the string expression of a unit in term of the basis.

        Units are displayed by decreasing power.
        """

        res = ""

        factor = unit.factor
        vec = self._system.dim_vector(unit.dim)

        for (u, p) in sorted(zip(self._base_units, vec), key=lambda x: x[1],
                             reverse=True):

            factor /= u.factor**p
            if p == 0:
                continue
            elif p == 1:
                res += "%s " % str(u)
            else:
                res += "%s^%d " % (str(u), p)

        return "%g %s" % (factor, res.strip())

    def to_base_units(self, unit):

        factor = unit.factor
        vec = self._system.dim_vector(unit.dim)

        res = []
        for (u, p) in sorted(zip(self._base_units, vec), key=lambda x: x[1],
                             reverse=True):
            factor /= u.factor**p
            if p == 0:
                continue
            elif p == 1:
                res.append(u)
            else:
                res.append(u**p)

        return reduce(Mul,res)

    @property
    def dim(self):
        """
        Give the dimension of the system.

        That is return the number of units forming the basis.
        """

        return self._system.dim

    @property
    def is_consistent(self):
        """
        Check if the underlying dimension system is consistent.
        """

        return self._system.is_consistent