text:
require 'test_helper'

module Kblog
  class ArticlesHelperTest < ActionView::TestCase
  end
end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'
require 'omniauth-mailchimp'

describe OmniAuth::Strategies::Mailchimp do
  before :each do
    @request = double('Request')
    @request.stub(:params) { {} }
  end

  subject do
    OmniAuth::Strategies::Mailchimp.new(nil, @options || {}).tap do |strategy|
      strategy.stub(:request) { @request }
    end
  end

  it_should_behave_like 'an oauth2 strategy'

	describe '#client' do
    it 'has correct Mailchimp api site' do
      subject.options.client_options.site.should eq('https://login.mailchimp.com')
    end

    it 'has correct access token path' do
      subject.options.client_options.token_url.should eq('/oauth2/token')
    end

    it 'has correct authorize url' do
      subject.options.client_options.authorize_url.should eq('/oauth2/authorize')
    end
  end

	describe '#callback_path' do
    it 'should have the correct callback path' do
      subject.callback_path.should eq('/auth/mailchimp/callback')
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Packets;
using QuantConnect.Securities;

namespace QuantConnect.Lean.Engine.DataFeeds
{
    /// <summary>
    /// Datafeed interface for creating custom datafeed sources.
    /// </summary>
    [InheritedExport(typeof(IDataFeed))]
    public interface IDataFeed : IEnumerable<TimeSlice>
    {
        /// <summary>
        /// Gets all of the current subscriptions this data feed is processing
        /// </summary>
        IEnumerable<Subscription> Subscriptions
        {
            get;
        }

        /// <summary>
        /// Public flag indicator that the thread is still busy.
        /// </summary>
        bool IsActive
        {
            get;
        }

        /// <summary>
        /// Initializes the data feed for the specified job and algorithm
        /// </summary>
        void Initialize(IAlgorithm algorithm, AlgorithmNodePacket job, IResultHandler resultHandler, IMapFileProvider mapFileProvider, IFactorFileProvider factorFileProvider);

        /// <summary>
        /// Adds a new subscription to provide data for the specified security.
        /// </summary>
        /// <param name="universe">The universe the subscription is to be added to</param>
        /// <param name="security">The security to add a subscription for</param>
        /// <param name="config">The subscription config to be added</param>
        /// <param name="utcStartTime">The start time of the subscription</param>
        /// <param name="utcEndTime">The end time of the subscription</param>
        /// <returns>True if the subscription was created and added successfully, false otherwise</returns>
        bool AddSubscription(Universe universe, Security security, SubscriptionDataConfig config, DateTime utcStartTime, DateTime utcEndTime);

        /// <summary>
        /// Removes the subscription from the data feed, if it exists
        /// </summary>
        /// <param name="configuration">The configuration of the subscription to remove</param>
        /// <returns>True if the subscription was successfully removed, false otherwise</returns>
        bool RemoveSubscription(SubscriptionDataConfig configuration);

        /// <summary>
        /// Primary entry point.
        /// </summary>
        void Run();

        /// <summary>
        /// External controller calls to signal a terminate of the thread.
        /// </summary>
        void Exit();
    }
}


text:
layout: post
title: Time Backup Stili RSync Backup
date: '2013-10-28T00:43:00.001+02:00'
author: Onur Atçı
tags:
- Linux
- kabuk scriptleri
- MacOsx
modified_time: '2013-10-28T00:43:12.907+02:00'
blogger_id: tag:blogger.com,1999:blog-7631058678726023805.post-6445076665051545138
blogger_orig_url: http://onuratci.blogspot.com/2013/10/time-backup-stili-rsync-backup.html
---

MacOs ile kullanabildiğimiz Time Backup yazılımının sağladığı incremental backup özelliğini rsync ile tüm platformlarda uygulayabilmek için github üzerinde bir proje başlatılmış.
Kullanımı gayet kolay ve yedekler alınırken eski yedeklere hard-link ile bağlanıyor. Böylece yedekler çok az yer kaplamış oluyor. Scriptin kurulumu ve kullanımı da çok kolay.

Ayrıntılı bilgi için: github rsync time backup


text:
"""Get details for an image."""
# :license: MIT, see LICENSE for more details.

import click

import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
from SoftLayer.CLI import image as image_mod
from SoftLayer import utils

@click.command(cls=SoftLayer.CLI.command.SLCommand, )
@click.argument('identifier')
@environment.pass_env
def cli(env, identifier):
    """Get details for an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')
    image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK)

    children_images = image.get('children')
    total_size = utils.lookup(image, 'firstChild', 'blockDevicesDiskSpaceTotal') or 0

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', image['id']])
    table.add_row(['global_identifier',
                   image.get('globalIdentifier', formatting.blank())])
    table.add_row(['name', image['name'].strip()])
    table.add_row(['status', formatting.FormattedItem(
        utils.lookup(image, 'status', 'keyname'),
        utils.lookup(image, 'status', 'name'),
    )])

    table.add_row([
        'active_transaction',
        formatting.listing(_get_transaction_groups(children_images), separator=','),
    ])
    table.add_row(['account', image.get('accountId', formatting.blank())])
    table.add_row(['visibility',
                   image_mod.PUBLIC_TYPE if image['publicFlag']
                   else image_mod.PRIVATE_TYPE])
    table.add_row(['type',
                   formatting.FormattedItem(
                       utils.lookup(image, 'imageType', 'keyName'),
                       utils.lookup(image, 'imageType', 'name'),
                   )])
    table.add_row(['flex', image.get('flexImageFlag')])
    table.add_row(['note', image.get('note')])
    table.add_row(['created', image.get('createDate')])
    table.add_row(['total_size', formatting.b_to_gb(total_size)])
    table.add_row(['datacenters', _get_datacenter_table(children_images)])

    env.fout(table)

def _get_datacenter_table(children_images):
    """Returns image details as datacenter, size, and transaction within a formatting table.

      :param children_images: A list of images.
      """
    table_datacenter = formatting.Table(['DC', 'size', 'transaction'])
    for child in children_images:
        table_datacenter.add_row([
            utils.lookup(child, 'datacenter', 'name'),
            formatting.b_to_gb(child.get('blockDevicesDiskSpaceTotal', 0)),
            formatting.transaction_status(child.get('transaction'))
        ])

    return table_datacenter

def _get_transaction_groups(children_images):
    """Returns a Set of transaction groups.

      :param children_images: A list of images.
      """
    transactions = set()
    for child in children_images:
        transactions.add(utils.lookup(child, 'transaction', 'transactionGroup', 'name'))

    return transactions


text:
#include "fuse_dfs.h"
#include "fuse_options.h"
#include "fuse_impls.h"
#include "fuse_init.h"

int is_protected(const char *path) {

  dfs_context *dfs = (dfs_context*)fuse_get_context()->private_data;
  assert(dfs != NULL);
  assert(dfs->protectedpaths);

  int i ;
  for (i = 0; dfs->protectedpaths[i]; i++) {
    if (strcmp(path, dfs->protectedpaths[i]) == 0) {
      return 1;
    }
  }
  return 0;
}

static struct fuse_operations dfs_oper = {
  .getattr	= dfs_getattr,
  .access	= dfs_access,
  .readdir	= dfs_readdir,
  .destroy       = dfs_destroy,
  .init         = dfs_init,
  .open	        = dfs_open,
  .read	        = dfs_read,
  .symlink	= dfs_symlink,
  .statfs	= dfs_statfs,
  .mkdir	= dfs_mkdir,
  .rmdir	= dfs_rmdir,
  .rename	= dfs_rename,
  .unlink       = dfs_unlink,
  .release      = dfs_release,
  .create       = dfs_create,
  .write	= dfs_write,
  .flush        = dfs_flush,
  .mknod        = dfs_mknod,
  .utimens      = dfs_utimens,
  .chmod	= dfs_chmod,
  .chown	= dfs_chown,
  .truncate	= dfs_truncate,
};

int main(int argc, char *argv[])
{

  umask(0);

  extern const char *program;
  program = argv[0];
  struct fuse_args args = FUSE_ARGS_INIT(argc, argv);

  /* clear structure that holds our options */
  memset(&options, 0, sizeof(struct options));

  // some defaults
  options.rdbuffer_size = 10*1024*1024;
  options.attribute_timeout = 60;
  options.entry_timeout = 60;

  if (fuse_opt_parse(&args, &options, dfs_opts, dfs_options) == -1)
    /** error parsing options */
    return -1;

  // Some fuse options we set
  if (! options.private) {
    fuse_opt_add_arg(&args, "-oallow_other");
  }

  if (!options.no_permissions) {
    fuse_opt_add_arg(&args, "-odefault_permissions");
  }

  {
    char buf[1024];

    snprintf(buf, sizeof buf, "-oattr_timeout=%d",options.attribute_timeout);
    fuse_opt_add_arg(&args, buf);

    snprintf(buf, sizeof buf, "-oentry_timeout=%d",options.entry_timeout);
    fuse_opt_add_arg(&args, buf);
  }

  if (options.server == NULL || options.port == 0) {
    print_usage(argv[0]);
    exit(0);
  }

  //
  // Check we can connect to hdfs
  //
  if (options.initchecks == 1) {
    hdfsFS temp;
    if ((temp = hdfsConnect(options.server, options.port)) == NULL) {
      const char *cp = getenv("CLASSPATH");
      const char *ld = getenv("LD_LIBRARY_PATH");
      ERROR("FATAL: misconfiguration - cannot connect to HDFS");
      ERROR("LD_LIBRARY_PATH=%s",ld == NULL ? "NULL" : ld);
      ERROR("CLASSPATH=%s",cp == NULL ? "NULL" : cp);
      exit(0);
    }
  }

  int ret = fuse_main(args.argc, args.argv, &dfs_oper, NULL);

  if (ret) printf("\n");

  /** free arguments */
  fuse_opt_free_args(&args);

  return ret;
}


text:
package com.xnx3.j2ee.entity;

import static javax.persistence.GenerationType.IDENTITY;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Friend entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "permission")
public class Permission implements java.io.Serializable {

	private Integer id;
	private String description;
	private String url;
	private Integer parentId;
	private String name;
	private String percode;

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}

	public String getPercode() {
		return percode;
	}
	public void setPercode(String percode) {
		this.percode = percode;
	}

	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public Integer getParentId() {
		return parentId;
	}
	public void setParentId(Integer parentId) {
		this.parentId = parentId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}


text:
package mssql

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"math"
	"net"
	"reflect"
	"strings"
	"time"
)

var driverInstance = &MssqlDriver{processQueryText: true}
var driverInstanceNoProcess = &MssqlDriver{processQueryText: false}

func init() {
	sql.Register("mssql", driverInstance)
	sql.Register("sqlserver", driverInstanceNoProcess)
	createDialer = func(p *connectParams) dialer {
		return tcpDialer{&net.Dialer{Timeout: p.dial_timeout, KeepAlive: p.keepAlive}}
	}
}

// Abstract the dialer for testing and for non-TCP based connections.
type dialer interface {
	Dial(addr string) (net.Conn, error)
}

var createDialer func(p *connectParams) dialer

type tcpDialer struct {
	nd *net.Dialer
}

func (d tcpDialer) Dial(addr string) (net.Conn, error) {
	return d.nd.Dial("tcp", addr)
}

type MssqlDriver struct {
	log optionalLogger

	processQueryText bool
}

func SetLogger(logger Logger) {
	driverInstance.SetLogger(logger)
	driverInstanceNoProcess.SetLogger(logger)
}

func (d *MssqlDriver) SetLogger(logger Logger) {
	d.log = optionalLogger{logger}
}

type MssqlConn struct {
	sess           *tdsSession
	transactionCtx context.Context

	processQueryText bool
	connectionGood   bool

	outs map[string]interface{}
}

func (c *MssqlConn) checkBadConn(err error) error {
	// this is a hack to address Issue #275
	// we set connectionGood flag to false if
	// error indicates that connection is not usable
	// but we return actual error instead of ErrBadConn
	// this will cause connection to stay in a pool
	// but next request to this connection will return ErrBadConn

	// it might be possible to revise this hack after
	// https://github.com/golang/go/issues/20807
	// is implemented
	switch err {
	case nil:
		return nil
	case io.EOF:
		return driver.ErrBadConn
	case driver.ErrBadConn:
		// It is an internal programming error if driver.ErrBadConn
		// is ever passed to this function. driver.ErrBadConn should
		// only ever be returned in response to a *MssqlConn.connectionGood == false
		// check in the external facing API.
		panic("driver.ErrBadConn in checkBadConn. This should not happen.")
	}

	switch err.(type) {
	case net.Error:
		c.connectionGood = false
		return err
	case StreamError:
		c.connectionGood = false
		return err
	default:
		return err
	}
}

func (c *MssqlConn) clearOuts() {
	c.outs = nil
}

func (c *MssqlConn) simpleProcessResp(ctx context.Context) error {
	tokchan := make(chan tokenStruct, 5)
	go processResponse(ctx, c.sess, tokchan, c.outs)
	c.clearOuts()
	for tok := range tokchan {
		switch token := tok.(type) {
		case doneStruct:
			if token.isError() {
				return c.checkBadConn(token.getError())
			}
		case error:
			return c.checkBadConn(token)
		}
	}
	return nil
}

func (c *MssqlConn) Commit() error {
	if !c.connectionGood {
		return driver.ErrBadConn
	}
	if err := c.sendCommitRequest(); err != nil {
		return c.checkBadConn(err)
	}
	return c.simpleProcessResp(c.transactionCtx)
}

func (c *MssqlConn) sendCommitRequest() error {
	headers := []headerStruct{
		{hdrtype: dataStmHdrTransDescr,
			data: transDescrHdr{c.sess.tranid, 1}.pack()},
	}
	if err := sendCommitXact(c.sess.buf, headers, "", 0, 0, ""); err != nil {
		if c.sess.logFlags&logErrors != 0 {
			c.sess.log.Printf("Failed to send CommitXact with %v", err)
		}
		c.connectionGood = false
		return fmt.Errorf("Faild to send CommitXact: %v", err)
	}
	return nil
}

func (c *MssqlConn) Rollback() error {
	if !c.connectionGood {
		return driver.ErrBadConn
	}
	if err := c.sendRollbackRequest(); err != nil {
		return c.checkBadConn(err)
	}
	return c.simpleProcessResp(c.transactionCtx)
}

func (c *MssqlConn) sendRollbackRequest() error {
	headers := []headerStruct{
		{hdrtype: dataStmHdrTransDescr,
			data: transDescrHdr{c.sess.tranid, 1}.pack()},
	}
	if err := sendRollbackXact(c.sess.buf, headers, "", 0, 0, ""); err != nil {
		if c.sess.logFlags&logErrors != 0 {
			c.sess.log.Printf("Failed to send RollbackXact with %v", err)
		}
		c.connectionGood = false
		return fmt.Errorf("Failed to send RollbackXact: %v", err)
	}
	return nil
}

func (c *MssqlConn) Begin() (driver.Tx, error) {
	return c.begin(context.Background(), isolationUseCurrent)
}

func (c *MssqlConn) begin(ctx context.Context, tdsIsolation isoLevel) (tx driver.Tx, err error) {
	if !c.connectionGood {
		return nil, driver.ErrBadConn
	}
	err = c.sendBeginRequest(ctx, tdsIsolation)
	if err != nil {
		return nil, c.checkBadConn(err)
	}
	tx, err = c.processBeginResponse(ctx)
	if err != nil {
		return nil, c.checkBadConn(err)
	}
	return
}

func (c *MssqlConn) sendBeginRequest(ctx context.Context, tdsIsolation isoLevel) error {
	c.transactionCtx = ctx
	headers := []headerStruct{
		{hdrtype: dataStmHdrTransDescr,
			data: transDescrHdr{0, 1}.pack()},
	}
	if err := sendBeginXact(c.sess.buf, headers, tdsIsolation, ""); err != nil {
		if c.sess.logFlags&logErrors != 0 {
			c.sess.log.Printf("Failed to send BeginXact with %v", err)
		}
		c.connectionGood = false
		return fmt.Errorf("Failed to send BiginXant: %v", err)
	}
	return nil
}

func (c *MssqlConn) processBeginResponse(ctx context.Context) (driver.Tx, error) {
	if err := c.simpleProcessResp(ctx); err != nil {
		return nil, err
	}
	// successful BEGINXACT request will return sess.tranid
	// for started transaction
	return c, nil
}

func (d *MssqlDriver) Open(dsn string) (driver.Conn, error) {
	return d.open(dsn)
}

func (d *MssqlDriver) open(dsn string) (*MssqlConn, error) {
	params, err := parseConnectParams(dsn)
	if err != nil {
		return nil, err
	}

	sess, err := connect(d.log, params)
	if err != nil {
		// main server failed, try fail-over partner
		if params.failOverPartner == "" {
			return nil, err
		}

		params.host = params.failOverPartner
		if params.failOverPort != 0 {
			params.port = params.failOverPort
		}

		sess, err = connect(d.log, params)
		if err != nil {
			// fail-over partner also failed, now fail
			return nil, err
		}
	}

	conn := &MssqlConn{
		sess:             sess,
		transactionCtx:   context.Background(),
		processQueryText: d.processQueryText,
		connectionGood:   true,
	}
	conn.sess.log = d.log
	return conn, nil
}

func (c *MssqlConn) Close() error {
	return c.sess.buf.transport.Close()
}

type MssqlStmt struct {
	c          *MssqlConn
	query      string
	paramCount int
	notifSub   *queryNotifSub
}

type queryNotifSub struct {
	msgText string
	options string
	timeout uint32
}

func (c *MssqlConn) Prepare(query string) (driver.Stmt, error) {
	if !c.connectionGood {
		return nil, driver.ErrBadConn
	}
	if len(query) > 10 && strings.EqualFold(query[:10], "INSERTBULK") {
		return c.prepareCopyIn(query)
	}

	return c.prepareContext(context.Background(), query)
}

func (c *MssqlConn) prepareContext(ctx context.Context, query string) (*MssqlStmt, error) {
	paramCount := -1
	if c.processQueryText {
		query, paramCount = parseParams(query)
	}
	return &MssqlStmt{c, query, paramCount, nil}, nil
}

func (s *MssqlStmt) Close() error {
	return nil
}

func (s *MssqlStmt) SetQueryNotification(id, options string, timeout time.Duration) {
	to := uint32(timeout / time.Second)
	if to < 1 {
		to = 1
	}
	s.notifSub = &queryNotifSub{id, options, to}
}

func (s *MssqlStmt) NumInput() int {
	return s.paramCount
}

func (s *MssqlStmt) sendQuery(args []namedValue) (err error) {
	headers := []headerStruct{
		{hdrtype: dataStmHdrTransDescr,
			data: transDescrHdr{s.c.sess.tranid, 1}.pack()},
	}

	if s.notifSub != nil {
		headers = append(headers,
			headerStruct{
				hdrtype: dataStmHdrQueryNotif,
				data: queryNotifHdr{
					s.notifSub.msgText,
					s.notifSub.options,
					s.notifSub.timeout,
				}.pack(),
			})
	}

	// no need to check number of parameters here, it is checked by database/sql
	if s.c.sess.logFlags&logSQL != 0 {
		s.c.sess.log.Println(s.query)
	}
	if s.c.sess.logFlags&logParams != 0 && len(args) > 0 {
		for i := 0; i < len(args); i++ {
			if len(args[i].Name) > 0 {
				s.c.sess.log.Printf("\t@%s\t%v\n", args[i].Name, args[i].Value)
			} else {
				s.c.sess.log.Printf("\t@p%d\t%v\n", i+1, args[i].Value)
			}
		}

	}
	if len(args) == 0 {
		if err = sendSqlBatch72(s.c.sess.buf, s.query, headers); err != nil {
			if s.c.sess.logFlags&logErrors != 0 {
				s.c.sess.log.Printf("Failed to send SqlBatch with %v", err)
			}
			s.c.connectionGood = false
			return fmt.Errorf("failed to send SQL Batch: %v", err)
		}
	} else {
		proc := Sp_ExecuteSql
		var params []Param
		if isProc(s.query) {
			proc.name = s.query
			params, _, err = s.makeRPCParams(args, 0)
		} else {
			var decls []string
			params, decls, err = s.makeRPCParams(args, 2)
			if err != nil {
				return
			}
			params[0] = makeStrParam(s.query)
			params[1] = makeStrParam(strings.Join(decls, ","))
		}
		if err = sendRpc(s.c.sess.buf, headers, proc, 0, params); err != nil {
			if s.c.sess.logFlags&logErrors != 0 {
				s.c.sess.log.Printf("Failed to send Rpc with %v", err)
			}
			s.c.connectionGood = false
			return fmt.Errorf("Failed to send RPC: %v", err)
		}
	}
	return
}

// isProc takes the query text in s and determines if it is a stored proc name
// or SQL text.
func isProc(s string) bool {
	if len(s) == 0 {
		return false
	}
	if s[0] == '[' && s[len(s)-1] == ']' && strings.ContainsAny(s, "\n\r") == false {
		return true
	}
	return !strings.ContainsAny(s, " \t\n\r;")
}

func (s *MssqlStmt) makeRPCParams(args []namedValue, offset int) ([]Param, []string, error) {
	var err error
	params := make([]Param, len(args)+offset)
	decls := make([]string, len(args))
	for i, val := range args {
		params[i+offset], err = s.makeParam(val.Value)
		if err != nil {
			return nil, nil, err
		}
		var name string
		if len(val.Name) > 0 {
			name = "@" + val.Name
		} else {
			name = fmt.Sprintf("@p%d", val.Ordinal)
		}
		params[i+offset].Name = name
		decls[i] = fmt.Sprintf("%s %s", name, makeDecl(params[i+offset].ti))
	}
	return params, decls, nil
}

type namedValue struct {
	Name    string
	Ordinal int
	Value   driver.Value
}

func convertOldArgs(args []driver.Value) []namedValue {
	list := make([]namedValue, len(args))
	for i, v := range args {
		list[i] = namedValue{
			Ordinal: i + 1,
			Value:   v,
		}
	}
	return list
}

func (s *MssqlStmt) Query(args []driver.Value) (driver.Rows, error) {
	return s.queryContext(context.Background(), convertOldArgs(args))
}

func (s *MssqlStmt) queryContext(ctx context.Context, args []namedValue) (rows driver.Rows, err error) {
	if !s.c.connectionGood {
		return nil, driver.ErrBadConn
	}
	if err = s.sendQuery(args); err != nil {
		return nil, s.c.checkBadConn(err)
	}
	return s.processQueryResponse(ctx)
}

func (s *MssqlStmt) processQueryResponse(ctx context.Context) (res driver.Rows, err error) {
	tokchan := make(chan tokenStruct, 5)
	ctx, cancel := context.WithCancel(ctx)
	go processResponse(ctx, s.c.sess, tokchan, s.c.outs)
	s.c.clearOuts()
	// process metadata
	var cols []columnStruct
loop:
	for tok := range tokchan {
		switch token := tok.(type) {
		// By ignoring DONE token we effectively
		// skip empty result-sets.
		// This improves results in queries like that:
		// set nocount on; select 1
		// see TestIgnoreEmptyResults test
		//case doneStruct:
		//break loop
		case []columnStruct:
			cols = token
			break loop
		case doneStruct:
			if token.isError() {
				return nil, s.c.checkBadConn(token.getError())
			}
		case error:
			return nil, s.c.checkBadConn(token)
		}
	}
	res = &MssqlRows{stmt: s, tokchan: tokchan, cols: cols, cancel: cancel}
	return
}

func (s *MssqlStmt) Exec(args []driver.Value) (driver.Result, error) {
	return s.exec(context.Background(), convertOldArgs(args))
}

func (s *MssqlStmt) exec(ctx context.Context, args []namedValue) (res driver.Result, err error) {
	if !s.c.connectionGood {
		return nil, driver.ErrBadConn
	}
	if err = s.sendQuery(args); err != nil {
		return nil, s.c.checkBadConn(err)
	}
	if res, err = s.processExec(ctx); err != nil {
		return nil, s.c.checkBadConn(err)
	}
	return
}

func (s *MssqlStmt) processExec(ctx context.Context) (res driver.Result, err error) {
	tokchan := make(chan tokenStruct, 5)
	go processResponse(ctx, s.c.sess, tokchan, s.c.outs)
	s.c.clearOuts()
	var rowCount int64
	for token := range tokchan {
		switch token := token.(type) {
		case doneInProcStruct:
			if token.Status&doneCount != 0 {
				rowCount += int64(token.RowCount)
			}
		case doneStruct:
			if token.Status&doneCount != 0 {
				rowCount += int64(token.RowCount)
			}
			if token.isError() {
				return nil, token.getError()
			}
		case error:
			return nil, token
		}
	}
	return &MssqlResult{s.c, rowCount}, nil
}

type MssqlRows struct {
	stmt    *MssqlStmt
	cols    []columnStruct
	tokchan chan tokenStruct

	nextCols []columnStruct

	cancel func()
}

func (rc *MssqlRows) Close() error {
	rc.cancel()
	for _ = range rc.tokchan {
	}
	rc.tokchan = nil
	return nil
}

func (rc *MssqlRows) Columns() (res []string) {
	res = make([]string, len(rc.cols))
	for i, col := range rc.cols {
		res[i] = col.ColName
	}
	return
}

func (rc *MssqlRows) Next(dest []driver.Value) error {
	if !rc.stmt.c.connectionGood {
		return driver.ErrBadConn
	}
	if rc.nextCols != nil {
		return io.EOF
	}
	for tok := range rc.tokchan {
		switch tokdata := tok.(type) {
		case []columnStruct:
			rc.nextCols = tokdata
			return io.EOF
		case []interface{}:
			for i := range dest {
				dest[i] = tokdata[i]
			}
			return nil
		case doneStruct:
			if tokdata.isError() {
				return rc.stmt.c.checkBadConn(tokdata.getError())
			}
		case error:
			return rc.stmt.c.checkBadConn(tokdata)
		}
	}
	return io.EOF
}

func (rc *MssqlRows) HasNextResultSet() bool {
	return rc.nextCols != nil
}

func (rc *MssqlRows) NextResultSet() error {
	rc.cols = rc.nextCols
	rc.nextCols = nil
	if rc.cols == nil {
		return io.EOF
	}
	return nil
}

// It should return
// the value type that can be used to scan types into. For example, the database
// column type "bigint" this should return "reflect.TypeOf(int64(0))".
func (r *MssqlRows) ColumnTypeScanType(index int) reflect.Type {
	return makeGoLangScanType(r.cols[index].ti)
}

// RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the
// database system type name without the length. Type names should be uppercase.
// Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT",
// "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML",
// "TIMESTAMP".
func (r *MssqlRows) ColumnTypeDatabaseTypeName(index int) string {
	return makeGoLangTypeName(r.cols[index].ti)
}

// RowsColumnTypeLength may be implemented by Rows. It should return the length
// of the column type if the column is a variable length type. If the column is
// not a variable length type ok should return false.
// If length is not limited other than system limits, it should return math.MaxInt64.
// The following are examples of returned values for various types:
//   TEXT          (math.MaxInt64, true)
//   varchar(10)   (10, true)
//   nvarchar(10)  (10, true)
//   decimal       (0, false)
//   int           (0, false)
//   bytea(30)     (30, true)
func (r *MssqlRows) ColumnTypeLength(index int) (int64, bool) {
	return makeGoLangTypeLength(r.cols[index].ti)
}

// It should return
// the precision and scale for decimal types. If not applicable, ok should be false.
// The following are examples of returned values for various types:
//   decimal(38, 4)    (38, 4, true)
//   int               (0, 0, false)
//   decimal           (math.MaxInt64, math.MaxInt64, true)
func (r *MssqlRows) ColumnTypePrecisionScale(index int) (int64, int64, bool) {
	return makeGoLangTypePrecisionScale(r.cols[index].ti)
}

// The nullable value should
// be true if it is known the column may be null, or false if the column is known
// to be not nullable.
// If the column nullability is unknown, ok should be false.
func (r *MssqlRows) ColumnTypeNullable(index int) (nullable, ok bool) {
	nullable = r.cols[index].Flags&colFlagNullable != 0
	ok = true
	return
}

func makeStrParam(val string) (res Param) {
	res.ti.TypeId = typeNVarChar
	res.buffer = str2ucs2(val)
	res.ti.Size = len(res.buffer)
	return
}

func (s *MssqlStmt) makeParam(val driver.Value) (res Param, err error) {
	if val == nil {
		res.ti.TypeId = typeNull
		res.buffer = nil
		res.ti.Size = 0
		return
	}
	switch val := val.(type) {
	case int64:
		res.ti.TypeId = typeIntN
		res.buffer = make([]byte, 8)
		res.ti.Size = 8
		binary.LittleEndian.PutUint64(res.buffer, uint64(val))
	case float64:
		res.ti.TypeId = typeFltN
		res.ti.Size = 8
		res.buffer = make([]byte, 8)
		binary.LittleEndian.PutUint64(res.buffer, math.Float64bits(val))
	case []byte:
		res.ti.TypeId = typeBigVarBin
		res.ti.Size = len(val)
		res.buffer = val
	case string:
		res = makeStrParam(val)
	case bool:
		res.ti.TypeId = typeBitN
		res.ti.Size = 1
		res.buffer = make([]byte, 1)
		if val {
			res.buffer[0] = 1
		}
	case time.Time:
		if s.c.sess.loginAck.TDSVersion >= verTDS73 {
			res.ti.TypeId = typeDateTimeOffsetN
			res.ti.Scale = 7
			res.ti.Size = 10
			buf := make([]byte, 10)
			res.buffer = buf
			days, ns := dateTime2(val)
			ns /= 100
			buf[0] = byte(ns)
			buf[1] = byte(ns >> 8)
			buf[2] = byte(ns >> 16)
			buf[3] = byte(ns >> 24)
			buf[4] = byte(ns >> 32)
			buf[5] = byte(days)
			buf[6] = byte(days >> 8)
			buf[7] = byte(days >> 16)
			_, offset := val.Zone()
			offset /= 60
			buf[8] = byte(offset)
			buf[9] = byte(offset >> 8)
		} else {
			res.ti.TypeId = typeDateTimeN
			res.ti.Size = 8
			res.buffer = make([]byte, 8)
			ref := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
			dur := val.Sub(ref)
			days := dur / (24 * time.Hour)
			tm := (300 * (dur % (24 * time.Hour))) / time.Second
			binary.LittleEndian.PutUint32(res.buffer[0:4], uint32(days))
			binary.LittleEndian.PutUint32(res.buffer[4:8], uint32(tm))
		}
	default:
		return s.makeParamExtra(val)
	}
	return
}

type MssqlResult struct {
	c            *MssqlConn
	rowsAffected int64
}

func (r *MssqlResult) RowsAffected() (int64, error) {
	return r.rowsAffected, nil
}

func (r *MssqlResult) LastInsertId() (int64, error) {
	s, err := r.c.Prepare("select cast(@@identity as bigint)")
	if err != nil {
		return 0, err
	}
	defer s.Close()
	rows, err := s.Query(nil)
	if err != nil {
		return 0, err
	}
	defer rows.Close()
	dest := make([]driver.Value, 1)
	err = rows.Next(dest)
	if err != nil {
		return 0, err
	}
	if dest[0] == nil {
		return -1, errors.New("There is no generated identity value")
	}
	lastInsertId := dest[0].(int64)
	return lastInsertId, nil
}


text:
/**
 * \file xdrop_aliigner.cpp: contains implementation of XdropAligner
 */

#include "dozeu_interface.hpp"

// Configure dozeu:
// We want the full length bonus included
#ifndef DZ_FULL_LENGTH_BONUS
#define DZ_FULL_LENGTH_BONUS
#endif
// We want the non-quality adjusted versions of functions
#ifdef DZ_QUAL_ADJ
#undef DZ_QUAL_ADJ
#endif
// We require these particular values for this enum because we index arrays with it.
enum { MISMATCH = 1, MATCH = 2, INS = 3, DEL = 4 };
// Set dozeu's CIGAR codes to match our enum
#ifndef DZ_CIGAR_OP
#define DZ_CIGAR_OP 0x04030201
#endif

// To turn on debugging:
//#define DEBUG
//#define DZ_PRINT_VECTOR

#include <dozeu/dozeu.h>

using namespace vg;

XdropAligner::XdropAligner(const XdropAligner& other)
{
    *this = other;
}

XdropAligner& XdropAligner::operator=(const XdropAligner& other)
{
	if (this != &other) {

        if (dz) {
            dz_destroy(dz);
        }
        dz = dz_init(other.dz->matrix,
                     *((const uint16_t*) &other.dz->giv),
                     *((const uint16_t*) &other.dz->gev));
    }

	return *this;
}

XdropAligner::XdropAligner(XdropAligner&& other)
{
    *this = other;
}

XdropAligner& XdropAligner::operator=(XdropAligner&& other)
{
	if (this != &other) {
        if (dz) {
            dz_destroy(dz);
        }
        dz = other.dz;
        other.dz = nullptr;
    }

	return *this;
}

XdropAligner::XdropAligner(const int8_t* _score_matrix, int8_t _gap_open, int8_t _gap_extension)
{
    // xdrop aligner uses the parameterization where both gap open and gap extend
    // are added when opening a gap
    assert(_gap_open - _gap_extension >= 0);
    assert(_gap_extension > 0);
    dz = dz_init(_score_matrix, _gap_open - _gap_extension, _gap_extension);
}

XdropAligner::~XdropAligner(void)
{
    dz_destroy(dz);
}

dz_query_s* XdropAligner::pack_query_forward(const char* seq, const uint8_t* qual,
                                             int8_t full_length_bonus, size_t len) {
    return dz_pack_query_forward(dz, seq, full_length_bonus, len);
}

dz_query_s* XdropAligner::pack_query_reverse(const char* seq, const uint8_t* qual,
                                             int8_t full_length_bonus, size_t len) {
    return dz_pack_query_reverse(dz, seq, full_length_bonus, len);
}

const dz_forefront_s* XdropAligner::scan(const dz_query_s* query, const dz_forefront_s** forefronts,
                                         size_t n_forefronts, const char* ref, int32_t rlen,
                                         uint32_t rid, uint16_t xt) {
    return dz_scan(dz, query, forefronts, n_forefronts, ref, rlen, rid, xt);
}

const dz_forefront_s* XdropAligner::extend(const dz_query_s* query, const dz_forefront_s** forefronts,
                                           size_t n_forefronts, const char* ref, int32_t rlen,
                                           uint32_t rid, uint16_t xt) {
    return dz_extend(dz, query, forefronts, n_forefronts, ref, rlen, rid, xt);
}

dz_alignment_s* XdropAligner::trace(const dz_forefront_s* forefront) {
    return dz_trace(dz, forefront);
}

void XdropAligner::flush() {
    dz_flush(dz);
}

/**
 * end of xdrop_aligner.cpp
 */


text:
import unittest
from unittest import TestCase
import os
import driveami
import driveami.tests.resources as resources

import logging
logging.basicConfig(level=logging.DEBUG)

import pickle

# @unittest.skip
class TestGrouping(TestCase):
    def setUp(self):
        env_extras = resources.setup_testdata_symlink()
        self.reduce = driveami.Reduce(ami_rootdir=resources.ami_rootdir,
                                      ami_version=driveami.AmiVersion.legacy,
                                      additional_env_variables=env_extras)
        with open(resources.file_info_dump) as f:
            file_info_data = pickle.load(f)
        self.reduce.files = file_info_data

    def test_grouping_by_target_id(self):
        groups = self.reduce.group_obs_by_target_id()
        #Regression test, assuming fixed data dump
        self.assertEqual(len(groups), 178)

    def test_grouping_by_pointing(self):
        id_groups = self.reduce.group_obs_by_target_id()
        pointing_groups = self.reduce.group_target_ids_by_pointing(id_groups)
        #Regression test, assuming fixed data dump
        self.assertEqual(len(pointing_groups.keys()),130)


text:
import { connect } from  'react-redux'
import EventList from '../../components/events/list'
import {
  filterEventsStartTime,
  filterEventsEndTime,
  changeFilterType,
  changeFilterTerm,
  addNewFilter,
  removeFilter,
  clearFilters } from '../../actions/events'

export default connect(
  (state) => (
    {
      filterStartTime:            state.events.filterStartTime,
      filterEndTime:              state.events.filterEndTime,
      filterType:                 state.events.filterType,
      filterTerm:                 state.events.filterTerm,
      activeFilters:              state.events.activeFilters,
      attributeValues:            state.events.attributeValues,
      isFetchingAttributeValues:  state.events.isFetchingAttributeValues,
      offset:                     state.events.offset,
      limit:                      state.events.limit,
      total:                      state.events.total,
      error:                      state.events.error
    }
  ),
  (dispatch) =>(
    {
      handleStartTimeChange:  (filterStartTime)         => dispatch(filterEventsStartTime(filterStartTime)),
      handleEndTimeChange:    (filterEndTime)           => dispatch(filterEventsEndTime(filterEndTime)),
      handleFilterTypeChange: (filterType)              => dispatch(changeFilterType(filterType)),
      handleFilterTermChange: (filterTerm, withFetch)   => dispatch(changeFilterTerm(filterTerm, withFetch)),
      handleClearFilters:     ()                        => dispatch(clearFilters()),
      addNewFilter:           ()                        => dispatch(addNewFilter()),
      handleRemoveFilter:     (filterType)              => dispatch(removeFilter(filterType))

    }
  )
)(EventList)


text:
Mailboxer.setup do |config|

  #Configures if you applications uses or no the email sending for Notifications and Messages
  config.uses_emails = true

  #Configures the default from for the email sent for Messages and Notifications of Mailboxer
  config.default_from = "no-reply@mailboxer.com"

  #Configures the methods needed by mailboxer
  config.email_method = :mailboxer_email
  config.name_method = :name
  config.notify_method = :notify

  #Configures if you use or not a search engine and wich one are you using
  #Supported enignes: [:solr,:sphinx]
  config.search_enabled = false
  config.search_engine = :solr

  #Configures maximum length of the message subject and body
  config.subject_max_length = 255
  config.body_max_length = 32000
end


text:
layout: post
title: "There Are No Sides to Every Issue"
excerpt: "National"
categories: national
comments: false
share: true
---

![](http://www.jonathanmeres.com/wp-content/uploads/2014/07/the-big-issue-logo.jpg)

One common thing I hear every single year of a presidential election is that no one is sticking to the issues. 'The politicians aren't talking about the issues', or 'the media is not airing what is important', or my favorite 'I just want to hear the issues and have someone lay out a plan for the future'.

**GARBAGE!!!**

This is NOT what the hoi polloi want.

People have many ways to access the daily news and delve into the issues they find the most meaningful. Hell, with the internet, you can easily research articles from credible sources about issues such as what is going in in Syria, our economic situation, job growth, global warming, foreign and domestic trade, race relations, etc. But this is not what the majority of people are interested in.

If it was, then we would have a completely different social and political climate. People would have interesting and thoughtful takes on the US economy, people would think deeper about ISIS and their international place in the world, and hell, people would know the faces of our politicians?

Do you know who Tim Kaine is? Do you know who Mike Pence is? Maybe YOU do, but over 50% of Americans cannot pick them out of a lineup of one.

Need proof people don't care about issues? Look at Trump. The man has offered 1 semi-detailed plan for taxes and that is it. No more. Nothing on the battle against terrorism, nothing about trade deals (just that he is against them), nothing about education reform, not even anything about job growth (yes, his view on privatizing infrastructure development is fuzzy at best). On the other hand, Clinton has fleshed out multiple plans to attack problems of today; from domestic to international policy. You may not agree with them all, but I bet you agree with some of them. And at least they were thought out in an adult manner. But guess what? It doesn't matter. Well, at least to over 40% of Americans it doesn't.

People want and like rhetoric. They like to hear from someone who expresses themselves with the same feeling about issues as they do. There is no thought to any of this, just a visceral reaction that people gravitate to.

Granted, this is not everyone. I for one am not like that at all. And I bet you are not as well. You are obviously much smarter than most because you are reading this right now. But most people are not that educated on the complexity and depth of the real issues. Most like a distilled version of an issue and construct a reality about the cause and solution based on their emotional reaction to it.

So to those undecideds out there that are complaining about the lack of tackling the issues, what are you doing on your end to educate yourself?


text:
package gqt_test

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"code.cloudfoundry.org/garden"
	"code.cloudfoundry.org/guardian/gqt/runner"
	"code.cloudfoundry.org/guardian/imageplugin"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	digest "github.com/opencontainers/go-digest"
	imagespec "github.com/opencontainers/image-spec/specs-go/v1"
	specs "github.com/opencontainers/runtime-spec/specs-go"
)

var _ = Describe("Image Plugin", func() {
	var (
		tmpDir                            string
		client                            *runner.RunningGarden
		containerDestructionShouldSucceed bool
	)

	BeforeEach(func() {
		config = resetImagePluginConfig()
		containerDestructionShouldSucceed = true
		var err error
		tmpDir, err = ioutil.TempDir("", "")
		Expect(err).NotTo(HaveOccurred())
		Expect(os.Chmod(tmpDir, 0777)).To(Succeed())
	})

	JustBeforeEach(func() {
		client = runner.Start(config)
	})

	AfterEach(func() {
		err := client.DestroyAndStop()
		if containerDestructionShouldSucceed {
			Expect(err).NotTo(HaveOccurred())
		} else {
			Expect(err).NotTo(BeAssignableToTypeOf(runner.ErrGardenStop{}))
		}
		Expect(os.RemoveAll(tmpDir)).To(Succeed())
	})

	Context("when only an unprivileged image plugin is provided", func() {
		BeforeEach(func() {
			config.ImagePluginBin = binaries.ImagePlugin
			config.ImagePluginExtraArgs = []string{
				"\"--rootfs-path\"",
				tmpDir,
				"\"--args-path\"",
				filepath.Join(tmpDir, "args"),
			}
		})

		Context("and an unprivileged container is successfully created", func() {
			var (
				containerSpec garden.ContainerSpec
				container     garden.Container
				handle        string
				tmpMountDir   string
			)

			BeforeEach(func() {
				var err error
				tmpMountDir, err = ioutil.TempDir("", "")
				Expect(err).NotTo(HaveOccurred())

				containerSpec = garden.ContainerSpec{
					BindMounts: []garden.BindMount{
						garden.BindMount{
							SrcPath: tmpMountDir,
							DstPath: "/user-provided-bind-mount",
							Mode:    garden.BindMountModeRO,
						},
					},
				}
				config.ImagePluginExtraArgs = append(
					config.ImagePluginExtraArgs,
					"\"--create-whoami-path\"",
					filepath.Join(tmpDir, "create-whoami"),
				)
			})

			JustBeforeEach(func() {
				var err error
				container, err = client.Create(containerSpec)
				Expect(err).NotTo(HaveOccurred())
				handle = container.Handle()
			})

			AfterEach(func() {
				Expect(os.RemoveAll(tmpMountDir)).To(Succeed())
			})

			It("executes the plugin, passing the correct args", func() {
				pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
				Expect(err).ToNot(HaveOccurred())

				pluginArgs := strings.Split(string(pluginArgsBytes), " ")
				Expect(pluginArgs).To(Equal([]string{
					binaries.ImagePlugin,
					"--rootfs-path", tmpDir,
					"--args-path", filepath.Join(tmpDir, "args"),
					"--create-whoami-path", filepath.Join(tmpDir, "create-whoami"),
					"create",
					defaultTestRootFS,
					handle,
				}))
			})

			It("executes the plugin as root", func() {
				whoamiBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "create-whoami"))
				Expect(err).NotTo(HaveOccurred())

				Expect(string(whoamiBytes)).To(ContainSubstring("0 - 0"))
			})

			Context("when there are env vars", func() {
				BeforeEach(func() {
					env := []string{
						"MY_VAR=set",
						"MY_SECOND_VAR=also_set",
					}
					envJson, err := json.Marshal(env)
					Expect(err).NotTo(HaveOccurred())

					config.ImagePluginExtraArgs = append(
						config.ImagePluginExtraArgs,
						"\"--env-json\"",
						string(envJson),
					)

					rootfs := createRootfs(func(string) {}, 0755)
					Expect(copyFile(filepath.Join(rootfs, "bin", "env"),
						filepath.Join(tmpDir, "env"))).To(Succeed())
				})

				It("loads the image plugin env variables", func() {
					buffer := gbytes.NewBuffer()
					process, err := container.Run(garden.ProcessSpec{
						Path: "/env",
						Dir:  "/",
					}, garden.ProcessIO{Stdout: buffer, Stderr: buffer})
					Expect(err).NotTo(HaveOccurred())
					exitCode, err := process.Wait()
					Expect(err).NotTo(HaveOccurred())
					Expect(exitCode).To(BeZero())

					Eventually(buffer).Should(gbytes.Say("MY_VAR=set"))
					Eventually(buffer).Should(gbytes.Say("MY_SECOND_VAR=also_set"))
				})
			})

			Context("when there are mounts", func() {
				var mountedDir string
				fileName := "mnted-file"
				fileContent := "mnted-file-content"

				BeforeEach(func() {
					var err error
					mountedDir, err = ioutil.TempDir("", "bind-mount")
					Expect(err).NotTo(HaveOccurred())
					Expect(os.Chmod(mountedDir, 0777)).To(Succeed())
					Expect(ioutil.WriteFile(filepath.Join(mountedDir, fileName), []byte(fileContent), 0644)).To(Succeed())

					mounts := []specs.Mount{
						{
							Type:        "bind",
							Options:     []string{"bind"},
							Source:      mountedDir,
							Destination: "/image-plugin-bind-mount",
						},
					}
					mountsJson, err := json.Marshal(mounts)
					Expect(err).NotTo(HaveOccurred())

					config.ImagePluginExtraArgs = append(
						config.ImagePluginExtraArgs,
						"\"--mounts-json\"",
						string(mountsJson),
					)

					rootfs := createRootfs(func(string) {}, 0755)
					Expect(copyFile(filepath.Join(rootfs, "bin", "cat"),
						filepath.Join(tmpDir, "cat"))).To(Succeed())
				})

				AfterEach(func() {
					Expect(os.RemoveAll(mountedDir)).To(Succeed())
				})

				It("mounts the directories from the image plugin response", func() {
					var stdout bytes.Buffer
					process, err := container.Run(garden.ProcessSpec{
						Path: "/cat",
						Args: []string{filepath.Join("/image-plugin-bind-mount", fileName)},
					}, garden.ProcessIO{
						Stdout: io.MultiWriter(&stdout, GinkgoWriter),
						Stderr: GinkgoWriter,
					})
					Expect(err).NotTo(HaveOccurred())
					Expect(process.Wait()).To(Equal(0))
					Expect(stdout.String()).To(Equal(fileContent))
				})

				It("ensures that the mounts from the image plugin response are first in config.json", func() {
					config, err := ioutil.ReadFile(filepath.Join(client.DepotDir, container.Handle(), "config.json"))
					Expect(err).NotTo(HaveOccurred())

					var spec specs.Spec
					Expect(json.Unmarshal(config, &spec)).To(Succeed())

					Expect(spec.Mounts[0].Destination).To(Equal("/image-plugin-bind-mount"))
				})
			})

			It("adds any returned Windows config to the container bundle", func() {
				var spec specs.Spec
				unmarshalJSONFromFile(filepath.Join(client.DepotDir, container.Handle(), "config.json"), &spec)
				Expect(spec.Windows.LayerFolders).To(Equal([]string{"layer", "folders"}))
			})

			Context("when rootfs is not specified", func() {
				BeforeEach(func() {
					containerSpec.RootFSPath = ""
				})

				It("uses the default rootfs", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginArgsBytes)).To(ContainSubstring(defaultTestRootFS))
				})
			})

			Context("when passing a tagged docker image as the RootFSPath", func() {
				BeforeEach(func() {
					containerSpec.RootFSPath = "docker:///busybox#1.26.1"
				})

				It("replaces the # with :", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginArgsBytes)).To(ContainSubstring("docker:///busybox:1.26.1"))
				})
			})

			Context("when passing an Image URI", func() {
				BeforeEach(func() {
					containerSpec.Image = garden.ImageRef{URI: "/some/fake/rootfs"}
				})

				It("executes the plugin, passing the Image URI", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginArgsBytes)).To(ContainSubstring("/some/fake/rootfs"))
				})
			})

			Context("when passing a preloaded+layer image URI", func() {
				// This must be a real file, as it has stat() called on it to get the
				// mtime.
				// Using a temporary directory causes flakiness.
				var (
					ociImagePath string
					rootFSPath   = "/bin/sh"
				)

				BeforeEach(func() {
					containerSpec.Image = garden.ImageRef{URI: fmt.Sprintf(
						"preloaded+layer://%s?layer=https://droplets.com/droplet.tgz&layer_path=/untar/here&layer_digest=some-digest",
						rootFSPath,
					)}
				})

				JustBeforeEach(func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					ociImagePath = filepath.Join(client.DepotDir, container.Handle(), "image")
					ociImageURI := fmt.Sprintf("oci://%s", ociImagePath)
					Expect(string(pluginArgsBytes)).To(ContainSubstring(ociImageURI))
				})

				It("executes the plugin, creating the expected OCI image", func() {
					By("correctly writing index.json")
					var imageIndex imagespec.Index
					unmarshalJSONFromFile(filepath.Join(ociImagePath, "index.json"), &imageIndex)
					Expect(imageIndex.SchemaVersion).To(Equal(imageplugin.ImageSpecSchemaVersion))
					Expect(imageIndex.Manifests).To(HaveLen(1))
					Expect(imageIndex.Manifests[0].MediaType).To(Equal("application/vnd.oci.image.manifest.v1+json"))

					manifestDigest := imageIndex.Manifests[0].Digest.String()
					Expect(manifestDigest).To(HavePrefix("sha256:"))
					manifestDigest = strings.TrimLeft(manifestDigest, "sha256:")
					manifestPath := filepath.Join(ociImagePath, "blobs", "sha256", manifestDigest)

					By("correctly writing blobs/sha256/{manifest_sha}")
					var imageManifest imagespec.Manifest
					unmarshalJSONFromFile(manifestPath, &imageManifest)
					Expect(imageManifest.SchemaVersion).To(Equal(imageplugin.ImageSpecSchemaVersion))

					Expect(imageManifest.Layers).To(Equal([]imagespec.Descriptor{
						{
							MediaType: "application/vnd.oci.image.layer.v1.tar",
							Digest:    digest.Digest("sha256:" + shaOf(fmt.Sprintf("%s-%d", rootFSPath, lastModifiedTime(rootFSPath)))),
						},
						{
							MediaType:   "application/vnd.oci.image.layer.v1.tar+gzip",
							URLs:        []string{"https://droplets.com/droplet.tgz"},
							Annotations: map[string]string{imageplugin.ImageSpecBaseDirectoryAnnotationKey: "/untar/here"},
							Digest:      digest.Digest("sha256:some-digest"),
						},
					}))

					By("correctly writing blobs/sha256/{config_sha}")
					Expect(imageManifest.Config.MediaType).To(Equal("application/vnd.oci.image.config.v1+json"))
					configDigest := imageManifest.Config.Digest.String()
					Expect(configDigest).To(HavePrefix("sha256:"))
					configDigest = strings.Split(configDigest, ":")[1]
					configPath := filepath.Join(ociImagePath, "blobs", "sha256", configDigest)

					var imageConfig imagespec.Image
					unmarshalJSONFromFile(configPath, &imageConfig)
					Expect(imageConfig.RootFS.DiffIDs).To(Equal([]digest.Digest{
						digest.Digest("sha256:" + shaOf(fmt.Sprintf("%s-%d", rootFSPath, lastModifiedTime(rootFSPath)))),
						digest.Digest("sha256:some-digest")},
					))

					By("creating a symlink to the rootfs layer's tarball")
					linkBasename := shaOf(fmt.Sprintf("%s-%d", rootFSPath, lastModifiedTime(rootFSPath)))
					rootFSLinkPath := filepath.Join(ociImagePath, "blobs", "sha256", linkBasename)
					Expect(readlink(rootFSLinkPath)).To(Equal(rootFSPath))
				})
			})

			Context("when specifying a quota", func() {
				BeforeEach(func() {
					containerSpec.Limits.Disk.ByteHard = 100000
				})

				It("calls the image plugin setting the quota", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginArgsBytes)).To(ContainSubstring("--disk-limit-size-bytes 100000"))
				})

				Context("when the quota is total", func() {
					BeforeEach(func() {
						containerSpec.Limits.Disk.Scope = garden.DiskLimitScopeTotal
					})

					It("calls the image plugin without the exclusive flag", func() {
						pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
						Expect(err).ToNot(HaveOccurred())

						Expect(string(pluginArgsBytes)).NotTo(ContainSubstring("--exclude-image-from-quota"))
					})
				})

				Context("when the quota is exclusive", func() {
					BeforeEach(func() {
						containerSpec.Limits.Disk.Scope = garden.DiskLimitScopeExclusive
					})

					It("calls the image plugin setting the exclusive flag", func() {
						pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
						Expect(err).ToNot(HaveOccurred())

						Expect(string(pluginArgsBytes)).To(ContainSubstring("--exclude-image-from-quota"))
					})
				})

				Context("when the plugin logs to stderr", func() {
					BeforeEach(func() {
						config.ImagePluginExtraArgs = append(
							config.ImagePluginExtraArgs,
							"\"--create-log-content\"",
							"CREATE-FAKE-LOG-LINE",
						)
					})

					It("relogs the plugin's stderr to the garden logs", func() {
						Eventually(client).Should(gbytes.Say("CREATE-FAKE-LOG-LINE"))
					})
				})
			})

			Context("and a pea is run on that container", func() {
				var process garden.Process

				BeforeEach(func() {
					rootfs := createRootfs(func(string) {}, 0755)
					Expect(copyFile(filepath.Join(rootfs, "bin", "env"),
						filepath.Join(tmpDir, "env"))).To(Succeed())
				})

				JustBeforeEach(func() {
					var err error
					process, err = container.Run(garden.ProcessSpec{
						Path:  "/env",
						Dir:   "/",
						Image: garden.ImageRef{URI: "docker:///busybox"},
					}, garden.ProcessIO{})
					Expect(err).NotTo(HaveOccurred())
				})

				It("executes the plugin, destroying the image when the process exits", func() {
					exitCode, err := process.Wait()
					Expect(exitCode).To(BeZero())
					Expect(err).NotTo(HaveOccurred())

					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					pluginArgs := strings.Split(string(pluginArgsBytes), " ")
					Expect(pluginArgs).To(Equal([]string{
						binaries.ImagePlugin,
						"--rootfs-path", tmpDir,
						"--args-path", filepath.Join(tmpDir, "args"),
						"--create-whoami-path", filepath.Join(tmpDir, "create-whoami"),
						"delete",
						process.ID(),
					}))
				})
			})

			Context("and metrics are collected on that container", func() {
				var metrics garden.Metrics

				BeforeEach(func() {
					config.ImagePluginExtraArgs = append(
						config.ImagePluginExtraArgs,
						"\"--metrics-whoami-path\"",
						filepath.Join(tmpDir, "metrics-whoami"),
						"\"--metrics-output\"",
						`{"disk_usage": {"total_bytes_used": 1000, "exclusive_bytes_used": 2000}}`,
					)
				})

				JustBeforeEach(func() {
					var err error
					metrics, err = container.Metrics()
					Expect(err).NotTo(HaveOccurred())
				})

				It("executes the plugin, passing the correct args", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					pluginArgs := strings.Split(string(pluginArgsBytes), " ")
					Expect(pluginArgs).To(Equal([]string{
						binaries.ImagePlugin,
						"--rootfs-path", tmpDir,
						"--args-path", filepath.Join(tmpDir, "args"),
						"--create-whoami-path", filepath.Join(tmpDir, "create-whoami"),
						"--metrics-whoami-path", filepath.Join(tmpDir, "metrics-whoami"),
						"--metrics-output",
						"{\"disk_usage\":",
						"{\"total_bytes_used\":",
						"1000,",
						"\"exclusive_bytes_used\":",
						"2000}}",
						"stats",
						handle,
					}))
				})

				It("executes the plugin as root", func() {
					whoamiBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "metrics-whoami"))
					Expect(err).NotTo(HaveOccurred())

					Expect(string(whoamiBytes)).To(ContainSubstring("0 - 0"))
				})

				It("returns the plugin stdout as disk stats", func() {
					Expect(metrics.DiskStat.TotalBytesUsed).To(BeEquivalentTo(1000))
					Expect(metrics.DiskStat.ExclusiveBytesUsed).To(BeEquivalentTo(2000))
				})

				Context("when the plugin logs to stderr", func() {
					BeforeEach(func() {
						config.ImagePluginExtraArgs = append(
							config.ImagePluginExtraArgs,
							"\"--metrics-log-content\"",
							"METRICS-FAKE-LOG-LINE",
						)
					})

					It("relogs the plugin's stderr to the garden logs", func() {
						Eventually(client).Should(gbytes.Say("METRICS-FAKE-LOG-LINE"))
					})
				})
			})

			Context("but the plugin returns nonsense stats", func() {
				BeforeEach(func() {
					config.ImagePluginExtraArgs = append(
						config.ImagePluginExtraArgs,
						"\"--metrics-output\"",
						"NONSENSE_JSON",
					)
				})

				It("returns a sensible error containing the json", func() {
					_, err := container.Metrics()
					Expect(err).To(MatchError(ContainSubstring("parsing stats: NONSENSE_JSON")))
				})
			})

			Context("but the plugin fails when collecting metrics", func() {
				BeforeEach(func() {
					config.ImagePluginExtraArgs = append(
						config.ImagePluginExtraArgs,
						"\"--fail-on\"",
						"metrics",
					)
				})

				It("returns the plugin's stdout in a useful error", func() {
					_, err := container.Metrics()
					Expect(err).To(MatchError(ContainSubstring("running image plugin metrics: metrics failed")))
				})
			})

			Context("and that container is destroyed", func() {
				BeforeEach(func() {
					config.ImagePluginExtraArgs = append(
						config.ImagePluginExtraArgs,
						"\"--destroy-whoami-path\"",
						filepath.Join(tmpDir, "destroy-whoami"),
					)
				})

				JustBeforeEach(func() {
					Expect(client.Destroy(container.Handle())).Should(Succeed())
				})

				It("executes the plugin, passing the correct args", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					pluginArgs := strings.Split(string(pluginArgsBytes), " ")
					Expect(pluginArgs).To(Equal([]string{
						binaries.ImagePlugin,
						"--rootfs-path", tmpDir,
						"--args-path", filepath.Join(tmpDir, "args"),
						"--create-whoami-path", filepath.Join(tmpDir, "create-whoami"),
						"--destroy-whoami-path", filepath.Join(tmpDir, "destroy-whoami"),
						"delete",
						handle,
					}))
				})

				It("executes the plugin as root", func() {
					whoamiBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "destroy-whoami"))
					Expect(err).NotTo(HaveOccurred())

					Expect(string(whoamiBytes)).To(ContainSubstring("0 - 0"))
				})

				Context("when the plugin logs to stderr", func() {
					BeforeEach(func() {
						config.ImagePluginExtraArgs = append(
							config.ImagePluginExtraArgs,
							"\"--destroy-log-content\"",
							"DESTROY-FAKE-LOG-LINE",
						)
					})

					It("relogs the plugin's stderr to the garden logs", func() {
						Eventually(client).Should(gbytes.Say("DESTROY-FAKE-LOG-LINE"))
					})
				})
			})

			Context("but the plugin fails on destruction", func() {
				BeforeEach(func() {
					containerDestructionShouldSucceed = false
					config.ImagePluginExtraArgs = append(
						config.ImagePluginExtraArgs,
						"\"--fail-on\"",
						"destroy",
					)
				})

				AfterEach(func() {
					// No need to client.DestroyAndStop() because the container is never
					// created BUT it's important to stop the server as otherwise the
					// connection hangs around and in some cases can be used by other
					// tests :-|
					Expect(client.Stop()).To(Succeed())
				})

				It("returns the plugin's stdout in a useful error", func() {
					err := client.Destroy(container.Handle())
					Expect(err).To(MatchError(ContainSubstring("running image plugin destroy: destroy failed")))
				})
			})
		})

		Context("but the plugin fails on creation", func() {
			BeforeEach(func() {
				config.ImagePluginExtraArgs = append(
					config.ImagePluginExtraArgs,
					"\"--fail-on\"",
					"create",
				)
			})

			It("returns the plugin's stdout in a useful error", func() {
				_, err := client.Create(garden.ContainerSpec{})
				Expect(err).To(MatchError(ContainSubstring("running image plugin create: create failed")))
			})
		})

		Context("but we attempt to create a privileged container", func() {
			It("returns an informative error", func() {
				_, err := client.Create(garden.ContainerSpec{Privileged: true})
				Expect(err).To(MatchError(ContainSubstring("no privileged_image_plugin provided")))
			})
		})
	})

	Context("when only a privileged image plugin is provided", func() {
		BeforeEach(func() {
			config.PrivilegedImagePluginBin = binaries.ImagePlugin
			config.PrivilegedImagePluginExtraArgs = []string{
				"\"--rootfs-path\"",
				tmpDir,
				"\"--args-path\"",
				filepath.Join(tmpDir, "args"),
			}
		})

		Context("and a container is created", func() {
			var (
				containerSpec garden.ContainerSpec
				container     garden.Container
				handle        string
			)

			BeforeEach(func() {
				containerSpec = garden.ContainerSpec{Privileged: true}

				config.PrivilegedImagePluginExtraArgs = append(
					config.PrivilegedImagePluginExtraArgs,
					"\"--create-whoami-path\"",
					filepath.Join(tmpDir, "create-whoami"),
				)
			})

			JustBeforeEach(func() {
				var err error
				container, err = client.Create(containerSpec)
				Expect(err).NotTo(HaveOccurred())
				handle = container.Handle()
			})

			It("executes the plugin, passing the correct args", func() {
				pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
				Expect(err).ToNot(HaveOccurred())

				pluginArgs := strings.Split(string(pluginArgsBytes), " ")
				Expect(pluginArgs).To(Equal([]string{
					binaries.ImagePlugin,
					"--rootfs-path", tmpDir,
					"--args-path", filepath.Join(tmpDir, "args"),
					"--create-whoami-path", filepath.Join(tmpDir, "create-whoami"),
					"create",
					defaultTestRootFS,
					handle,
				}))
			})

			It("executes the plugin as root", func() {
				whoamiBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "create-whoami"))
				Expect(err).NotTo(HaveOccurred())

				Expect(string(whoamiBytes)).To(ContainSubstring("0 - 0"))
			})

			Context("when there are env vars", func() {
				BeforeEach(func() {
					env := []string{
						"MY_VAR=set",
						"MY_SECOND_VAR=also_set",
					}
					envJson, err := json.Marshal(env)
					Expect(err).NotTo(HaveOccurred())

					config.PrivilegedImagePluginExtraArgs = append(
						config.PrivilegedImagePluginExtraArgs,
						"\"--env-json\"",
						string(envJson),
					)
					rootfs := createRootfs(func(string) {}, 0755)
					Expect(copyFile(filepath.Join(rootfs, "bin", "env"),
						filepath.Join(tmpDir, "env"))).To(Succeed())
				})

				It("loads the image.json env variables", func() {
					buffer := gbytes.NewBuffer()
					process, err := container.Run(garden.ProcessSpec{
						Path: "/env",
						Dir:  "/",
					}, garden.ProcessIO{Stdout: buffer, Stderr: buffer})
					Expect(err).NotTo(HaveOccurred())
					exitCode, err := process.Wait()
					Expect(err).NotTo(HaveOccurred())
					Expect(exitCode).To(BeZero())

					Eventually(buffer).Should(gbytes.Say("MY_VAR=set"))
					Eventually(buffer).Should(gbytes.Say("MY_SECOND_VAR=also_set"))
				})
			})

			Context("when rootfs is not specified", func() {
				BeforeEach(func() {
					containerSpec.RootFSPath = ""
				})

				It("uses the default rootfs", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginArgsBytes)).To(ContainSubstring(defaultTestRootFS))
				})
			})

			Context("when passing a tagged docker image as the RootFSPath", func() {
				BeforeEach(func() {
					containerSpec.RootFSPath = "docker:///busybox#1.26.1"
				})

				It("replaces the # with :", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginArgsBytes)).To(ContainSubstring("docker:///busybox:1.26.1"))
				})
			})

			Context("when passing an Image URI", func() {
				BeforeEach(func() {
					containerSpec.Image = garden.ImageRef{URI: "/some/fake/rootfs"}
				})

				It("executes the plugin, passing the Image URI", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginArgsBytes)).To(ContainSubstring("/some/fake/rootfs"))
				})
			})

			Context("when specifying a quota", func() {
				BeforeEach(func() {
					containerSpec.Limits.Disk.ByteHard = 100000
				})

				It("calls the image plugin setting the quota", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginArgsBytes)).To(ContainSubstring("--disk-limit-size-bytes 100000"))
				})

				Context("when the quota is total", func() {
					BeforeEach(func() {
						containerSpec.Limits.Disk.Scope = garden.DiskLimitScopeTotal
					})

					It("calls the image plugin without the exclusive flag", func() {
						pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
						Expect(err).ToNot(HaveOccurred())

						Expect(string(pluginArgsBytes)).NotTo(ContainSubstring("--exclude-image-from-quota"))
					})
				})

				Context("when the quota is exclusive", func() {
					BeforeEach(func() {
						containerSpec.Limits.Disk.Scope = garden.DiskLimitScopeExclusive
					})

					It("calls the image plugin setting the exclusive flag", func() {
						pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
						Expect(err).ToNot(HaveOccurred())

						Expect(string(pluginArgsBytes)).To(ContainSubstring("--exclude-image-from-quota"))
					})
				})
			})

			Context("and metrics are collected on that container", func() {
				BeforeEach(func() {
					config.PrivilegedImagePluginExtraArgs = append(
						config.PrivilegedImagePluginExtraArgs,
						"\"--metrics-whoami-path\"",
						filepath.Join(tmpDir, "metrics-whoami"),
						"\"--metrics-output\"",
						`{"disk_usage": {"total_bytes_used": 1000, "exclusive_bytes_used": 2000}}`,
					)
				})

				JustBeforeEach(func() {
					_, err := container.Metrics()
					Expect(err).NotTo(HaveOccurred())
				})

				It("executes the plugin, passing the correct args", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					pluginArgs := strings.Split(string(pluginArgsBytes), " ")
					Expect(pluginArgs).To(Equal([]string{
						binaries.ImagePlugin,
						"--rootfs-path", tmpDir,
						"--args-path", filepath.Join(tmpDir, "args"),
						"--create-whoami-path", filepath.Join(tmpDir, "create-whoami"),
						"--metrics-whoami-path", filepath.Join(tmpDir, "metrics-whoami"),
						"--metrics-output",
						"{\"disk_usage\":",
						"{\"total_bytes_used\":",
						"1000,",
						"\"exclusive_bytes_used\":",
						"2000}}",
						"stats",
						handle,
					}))
				})

				It("executes the plugin as root", func() {
					whoamiBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "metrics-whoami"))
					Expect(err).NotTo(HaveOccurred())

					Expect(string(whoamiBytes)).To(ContainSubstring("0 - 0"))
				})

				Context("when the plugin logs to stderr", func() {
					BeforeEach(func() {
						config.PrivilegedImagePluginExtraArgs = append(
							config.PrivilegedImagePluginExtraArgs,
							"\"--metrics-log-content\"",
							"METRICS-FAKE-LOG-LINE",
						)
					})

					It("relogs the plugin's stderr to the garden logs", func() {
						Eventually(client).Should(gbytes.Say("METRICS-FAKE-LOG-LINE"))
					})
				})
			})

			Context("but the plugin fails when collecting metrics", func() {
				BeforeEach(func() {
					config.PrivilegedImagePluginExtraArgs = append(
						config.PrivilegedImagePluginExtraArgs,
						"\"--fail-on\"",
						"metrics",
					)
				})

				It("returns the plugin's stdout in a useful error", func() {
					_, err := container.Metrics()
					Expect(err).To(MatchError(ContainSubstring("running image plugin metrics: metrics failed")))
				})
			})

			Context("and that container is destroyed", func() {
				BeforeEach(func() {
					config.PrivilegedImagePluginExtraArgs = append(
						config.PrivilegedImagePluginExtraArgs,
						"\"--destroy-whoami-path\"",
						filepath.Join(tmpDir, "destroy-whoami"),
					)
				})

				JustBeforeEach(func() {
					Expect(client.Destroy(container.Handle())).Should(Succeed())
				})

				It("executes the plugin, passing the correct args", func() {
					pluginArgsBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
					Expect(err).ToNot(HaveOccurred())

					pluginArgs := strings.Split(string(pluginArgsBytes), " ")
					Expect(pluginArgs).To(Equal([]string{
						binaries.ImagePlugin,
						"--rootfs-path", tmpDir,
						"--args-path", filepath.Join(tmpDir, "args"),
						"--create-whoami-path", filepath.Join(tmpDir, "create-whoami"),
						"--destroy-whoami-path", filepath.Join(tmpDir, "destroy-whoami"),
						"delete",
						handle,
					}))
				})

				It("executes the plugin as root", func() {
					whoamiBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "destroy-whoami"))
					Expect(err).NotTo(HaveOccurred())

					Expect(string(whoamiBytes)).To(ContainSubstring("0 - 0"))
				})

				Context("when the plugin logs to stderr", func() {
					BeforeEach(func() {
						config.PrivilegedImagePluginExtraArgs = append(
							config.PrivilegedImagePluginExtraArgs,
							"\"--destroy-log-content\"",
							"DESTROY-FAKE-LOG-LINE",
						)
					})

					It("relogs the plugin's stderr to the garden logs", func() {
						Eventually(client).Should(gbytes.Say("DESTROY-FAKE-LOG-LINE"))
					})
				})
			})

			Context("but the plugin fails on destruction", func() {
				BeforeEach(func() {
					containerDestructionShouldSucceed = false
					config.PrivilegedImagePluginExtraArgs = append(
						config.PrivilegedImagePluginExtraArgs,
						"\"--fail-on\"",
						"destroy",
					)
				})

				It("returns the plugin's stdout in a useful error", func() {
					err := client.Destroy(container.Handle())
					Expect(err).To(MatchError(ContainSubstring("running image plugin destroy: destroy failed")))
				})
			})
		})

		Context("but the plugin fails on creation", func() {
			BeforeEach(func() {
				config.PrivilegedImagePluginExtraArgs = append(
					config.PrivilegedImagePluginExtraArgs,
					"\"--fail-on\"",
					"create",
				)
			})

			It("returns the plugin's stdout in a useful error", func() {
				_, err := client.Create(garden.ContainerSpec{Privileged: true})
				Expect(err).To(MatchError(ContainSubstring("running image plugin create: create failed")))
			})
		})

		Context("but we attempt to create an unprivileged container", func() {
			It("returns an informative error", func() {
				_, err := client.Create(garden.ContainerSpec{Privileged: false})
				Expect(err).To(MatchError(ContainSubstring("no image_plugin provided")))
			})
		})
	})

	Context("when both image_plugin and privileged_image_plugin are provided", func() {
		BeforeEach(func() {
			config.ImagePluginBin = binaries.ImagePlugin
			config.PrivilegedImagePluginBin = binaries.PrivilegedImagePlugin
			config.ImagePluginExtraArgs = append(
				config.ImagePluginExtraArgs,
				"\"--rootfs-path\"",
				tmpDir,
				"\"--create-bin-location-path\"",
				filepath.Join(tmpDir, "create-bin-location"),
				"\"--destroy-bin-location-path\"",
				filepath.Join(tmpDir, "destroy-bin-location"),
				"\"--metrics-bin-location-path\"",
				filepath.Join(tmpDir, "metrics-bin-location"),
			)
			config.PrivilegedImagePluginExtraArgs = append(
				config.PrivilegedImagePluginExtraArgs,
				"\"--rootfs-path\"",
				tmpDir,
				"\"--create-bin-location-path\"",
				filepath.Join(tmpDir, "create-bin-location"),
				"\"--destroy-bin-location-path\"",
				filepath.Join(tmpDir, "destroy-bin-location"),
				"\"--metrics-bin-location-path\"",
				filepath.Join(tmpDir, "metrics-bin-location"),
			)
		})

		Context("when an unprivileged container is created", func() {
			var container garden.Container

			JustBeforeEach(func() {
				var err error
				container, err = client.Create(garden.ContainerSpec{})
				Expect(err).NotTo(HaveOccurred())
			})

			It("calls only the unprivileged plugin", func() {
				pluginLocationBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "create-bin-location"))
				Expect(err).ToNot(HaveOccurred())

				Expect(string(pluginLocationBytes)).To(Equal(binaries.ImagePlugin))
			})

			Context("and metrics are collected on that container", func() {
				JustBeforeEach(func() {
					_, err := container.Metrics()
					Expect(err).NotTo(HaveOccurred())
				})

				It("calls only the unprivileged plugin", func() {
					pluginLocationBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "metrics-bin-location"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginLocationBytes)).To(Equal(binaries.ImagePlugin))
				})
			})

			Context("and that container is destroyed", func() {
				JustBeforeEach(func() {
					Expect(client.Destroy(container.Handle())).To(Succeed())
				})

				It("calls the unprivileged plugin", func() {
					pluginLocationBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "destroy-bin-location"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginLocationBytes)).To(ContainSubstring(binaries.ImagePlugin))
				})
			})
		})

		Context("when a privileged container is created", func() {
			var container garden.Container

			BeforeEach(func() {
				config.ImagePluginExtraArgs = append(
					config.ImagePluginExtraArgs,
					"\"--fail-on\"",
					"metrics",
				)
			})

			JustBeforeEach(func() {
				var err error
				container, err = client.Create(garden.ContainerSpec{Privileged: true})
				Expect(err).NotTo(HaveOccurred())
			})

			It("calls only the privileged plugin", func() {
				pluginLocationBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "create-bin-location"))
				Expect(err).ToNot(HaveOccurred())

				Expect(string(pluginLocationBytes)).To(Equal(binaries.PrivilegedImagePlugin))
			})

			Context("and metrics are collected on that container", func() {
				JustBeforeEach(func() {
					_, err := container.Metrics()
					Expect(err).NotTo(HaveOccurred())
				})

				It("tries to call both image plugins", func() {
					pluginLocationBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "metrics-bin-location"))
					Expect(err).ToNot(HaveOccurred())
					Expect(string(pluginLocationBytes)).To(ContainSubstring(binaries.ImagePlugin))
					Expect(string(pluginLocationBytes)).To(ContainSubstring(binaries.PrivilegedImagePlugin))
				})
			})

			Context("and that container is destroyed", func() {
				JustBeforeEach(func() {
					Expect(client.Destroy(container.Handle())).To(Succeed())
				})

				It("calls the privileged plugin", func() {
					pluginLocationBytes, err := ioutil.ReadFile(filepath.Join(tmpDir, "destroy-bin-location"))
					Expect(err).ToNot(HaveOccurred())

					Expect(string(pluginLocationBytes)).To(ContainSubstring(binaries.PrivilegedImagePlugin))
				})
			})
		})
	})

	Context("when images are located in a private registry", func() {
		var imageSpec garden.ImageRef

		BeforeEach(func() {
			config.LogLevel = "debug"
			config.ImagePluginBin = binaries.ImagePlugin
			config.ImagePluginExtraArgs = append(
				config.ImagePluginExtraArgs,
				"\"--rootfs-path\"",
				tmpDir,
				"\"--args-path\"",
				filepath.Join(tmpDir, "args"),
			)

			imageSpec = garden.ImageRef{
				URI:      "",
				Username: "imagepluginuser",
				Password: "secretpassword",
			}
		})

		It("calls the image plugin with username and password", func() {
			_, err := client.Create(garden.ContainerSpec{
				Image: imageSpec,
			})
			Expect(err).NotTo(HaveOccurred())

			args, err := ioutil.ReadFile(filepath.Join(tmpDir, "args"))
			Expect(err).NotTo(HaveOccurred())
			Expect(string(args)).To(ContainSubstring("imagepluginuser"))
			Expect(string(args)).To(ContainSubstring("secretpassword"))
		})

		It("does not log username and password", func() {
			_, err := client.Create(garden.ContainerSpec{
				Image: imageSpec,
			})
			Expect(err).NotTo(HaveOccurred())

			log := string(client.Buffer().Contents())
			Expect(log).NotTo(ContainSubstring("imagepluginuser"))
			Expect(log).NotTo(ContainSubstring("secretpassword"))
		})
	})
})

func shaOf(s string) string {
	shaBytes := sha256.Sum256([]byte(s))
	return hex.EncodeToString(shaBytes[:])
}

func lastModifiedTime(pathname string) int64 {
	info, err := os.Stat(pathname)
	Expect(err).NotTo(HaveOccurred())
	return info.ModTime().UnixNano()
}

func unmarshalJSONFromFile(pathname string, into interface{}) {
	contents, err := ioutil.ReadFile(pathname)
	Expect(err).NotTo(HaveOccurred())
	Expect(json.Unmarshal(contents, into)).To(Succeed())
}

func readlink(name string) string {
	destination, err := os.Readlink(name)
	Expect(err).NotTo(HaveOccurred())
	return destination
}


text:
package com.intellij.tasks;

import java.lang.ref.Reference;
import java.util.ResourceBundle;

import javax.annotation.Nonnull;

import org.apache.commons.httpclient.HttpStatus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.PropertyKey;
import com.intellij.CommonBundle;
import com.intellij.reference.SoftReference;

/**
 * Contains common and repository specific messages for "Tasks and Contexts" subsystem.
 * Initialization logic follows the same pattern as most of the other bundles in project.
 *
 * @author Mikhail Golubev
 */
public class TaskBundle
{

	private static Reference<ResourceBundle> ourBundle;
	@NonNls
	private static final String BUNDLE = "com.intellij.tasks.TaskBundle";

	private TaskBundle()
	{
		// empty
	}

	public static String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... params)
	{
		return CommonBundle.message(getBundle(), key, params);
	}

	@Nonnull
	public static String messageForStatusCode(int statusCode)
	{
		if(statusCode == HttpStatus.SC_UNAUTHORIZED)
		{
			return message("failure.login");
		}
		else if(statusCode == HttpStatus.SC_FORBIDDEN)
		{
			return message("failure.permissions");
		}
		return message("failure.http.error", statusCode, HttpStatus.getStatusText(statusCode));
	}

	private static ResourceBundle getBundle()
	{
		ResourceBundle bundle = SoftReference.dereference(ourBundle);
		if(bundle == null)
		{
			bundle = ResourceBundle.getBundle(BUNDLE);
			ourBundle = new SoftReference<ResourceBundle>(bundle);
		}
		return bundle;
	}
}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-22.js
 * @description Array.prototype.every - element to be retrieved is inherited accessor property without a get function on an Array
 */

function testcase() {

        var accessed = false;

        function callbackfn(val, idx, obj) {
            accessed = true;
            return typeof val === "undefined";
        }

        try {
            Object.defineProperty(Array.prototype, "0", {
                set: function () { },
                configurable: true
            });

            return [, ].every(callbackfn) && accessed;
        } finally {
            delete Array.prototype[0];
        }

    }
runTestCase(testcase);


text:
The `event-group-by` processor, groups values under the same event message based on a list of tag names.

This processor is intended to be used together with a output with cached gNMI notifications, like `prometheus` output with `gnmi-cache: true`.

### Configuration

```yaml
processors:
  # processor name
  sample-processor:
    # processor type
    event-group-by:
      # list of strings defining the tags to group by the values under
      # a single event
      tags: []
      # a boolean, if true only the values from events of the same name
      # are grouped together according to the list of tags
      by-name:
      # boolean
      debug: false
```

### Examples

#### group by a single tag

```yaml
processors:
  group-by-source:
    event-group-by:
      tags:
        - source
```

=== "Event format before"
    ```json
    [
        {
            "name": "sub2",
            "timestamp": 1615284691523204299,
            "tags": {
                "neighbor_peer-address": "2002::1:1:1:1",
                "network-instance_name": "default",
                "source": "leaf1:57400",
                "subscription-name": "sub2"
            },
            "values": {
                "bgp_neighbor_sent_messages_queue_depth": 0,
                "bgp_neighbor_sent_messages_total_messages": "423",
                "bgp_neighbor_sent_messages_total_non_updates": "415",
                "bgp_neighbor_sent_messages_total_updates": "8"
            }
        },
        {
            "name": "sub2",
            "timestamp": 1615284691523204299,
            "tags": {
                "neighbor_peer-address": "2002::1:1:1:1",
                "network-instance_name": "default",
                "source": "leaf1:57400",
                "subscription-name": "sub2"
            },
            "values": {
                "bgp_neighbor_received_messages_malformed_updates": "0",
                "bgp_neighbor_received_messages_queue_depth": 0,
                "bgp_neighbor_received_messages_total_messages": "424",
                "bgp_neighbor_received_messages_total_non_updates": "418",
                "bgp_neighbor_received_messages_total_updates": "6"
            }
        }
    ]
    ```
=== "Event format after"
    ```json
    [
        {
            "name": "sub2",
            "timestamp": 1615284691523204299,
            "tags": {
                "neighbor_peer-address": "2002::1:1:1:1",
                "network-instance_name": "default",
                "source": "leaf1:57400",
                "subscription-name": "sub2"
            },
            "values": {
                "bgp_neighbor_sent_messages_queue_depth": 0,
                "bgp_neighbor_sent_messages_total_messages": "423",
                "bgp_neighbor_sent_messages_total_non_updates": "415",
                "bgp_neighbor_sent_messages_total_updates": "8",
                "bgp_neighbor_received_messages_malformed_updates": "0",
                "bgp_neighbor_received_messages_queue_depth": 0,
                "bgp_neighbor_received_messages_total_messages": "424",
                "bgp_neighbor_received_messages_total_non_updates": "418",
                "bgp_neighbor_received_messages_total_updates": "6"
            }
        }
    ]
    ```

#### group by multiple tags

```yaml
processors:
  group-by-queue-id:
    event-group-by:
      tags:
        - source
        - interface_name
        - multicast-queue_queue-id
```

=== "Event Format Before"
    ```json
    [
      {
        "name": "sub1",
        "timestamp": 1627997491187771616,
        "tags": {
          "interface_name": "ethernet-1/1",
          "multicast-queue_queue-id": "5",
          "source": "clab-ndk-srl1:57400",
          "subscription-name": "sub1",
      },
        "values": {
          "/interface/qos/output/multicast-queue/queue-depth/maximum-burst-size": "0"
        }
      },
      {
        "name": "sub1",
        "timestamp": 1627997491187771616,
        "tags": {
          "interface_name": "ethernet-1/1",
          "multicast-queue_queue-id": "5",
          "source": "clab-ndk-srl1:57400",
          "subscription-name": "sub1",
        },
        "values": {
          "/interface/qos/output/multicast-queue/scheduling/peak-rate-bps": "0"
        }
      }
    ]
    ```
=== "Event Format After"
    ```json
    [
      {
        "name": "sub1",
        "timestamp": 1627997491187771616,
        "tags": {
          "interface_name": "ethernet-1/1",
          "multicast-queue_queue-id": "5",
          "source": "clab-ndk-srl1:57400",
          "subscription-name": "sub1",
      },
        "values": {
          "/interface/qos/output/multicast-queue/queue-depth/maximum-burst-size": "0",
          "/interface/qos/output/multicast-queue/scheduling/peak-rate-bps": "0"
        }
      }
    ]
    ```


text:
<?php
    //header + menu
    $layoutPath = 'webroot.themes.'.Yii::app()->theme->name.'.views.layouts.';
    $this->renderPartial('../app/info/terla/infocommon',
            array( "title"=> "FAQ : Foire aux questions", "layoutPath" => $layoutPath ));
?>

	    Hello FAQ

<?php $this->renderPartial($layoutPath.'footer',  array( "subdomain"=>"info" ) ); ?>


text:
package org.jbb.frontend.impl.faq;

import com.google.common.collect.Lists;

import org.jbb.frontend.api.faq.Faq;
import org.jbb.frontend.impl.faq.model.FaqCategoryEntity;
import org.jbb.frontend.impl.faq.model.FaqEntryEntity;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
class FaqDomainTranslator {

    ValidatedFaq toEntity(Faq faq) {
        List<Faq.Category> faqCategories = faq.getCategories();
        int categoryCount = faqCategories.size();

        List<FaqCategoryEntity> result = Lists.newArrayList();
        for (int i = 1; i <= categoryCount; i++) {
            FaqCategoryEntity category = toCategoryEntity(faqCategories.get(i - 1), i);
            result.add(category);
        }
        return ValidatedFaq.builder().categories(result).build();
    }

    Faq.Category toModel(FaqCategoryEntity entity) {
        return Faq.Category.builder()
                .name(entity.getName())
                .questions(entity.getEntries().stream()
                        .map(this::toModel)
                        .collect(Collectors.toList())
                )
                .build();
    }

    private Faq.Entry toModel(FaqEntryEntity entity) {
        return Faq.Entry.builder()
                .question(entity.getQuestion())
                .answer(entity.getAnswer())
                .build();
    }

    FaqCategoryEntity toCategoryEntity(Faq.Category faqCategory, int position) {
        FaqCategoryEntity category = FaqCategoryEntity.builder()
                .position(position)
                .name(faqCategory.getName())
                .build();

        category.setEntries(createEntryEntities(faqCategory.getQuestions(), category));

        return category;
    }

    private List<FaqEntryEntity> createEntryEntities(List<Faq.Entry> questions,
                                                     FaqCategoryEntity category) {

        int questionCount = questions.size();
        List<FaqEntryEntity> entries = Lists.newArrayList();
        for (int i = 1; i <= questionCount; i++) {
            entries.add(FaqEntryEntity.builder()
                    .position(i)
                    .category(category)
                    .question(questions.get(i - 1).getQuestion())
                    .answer(questions.get(i - 1).getAnswer()).build()
            );
        }
        return entries;
    }
}


text:
Mutest::Meta::Example.add :regexp_alternation_meta do
  source '/\A(foo|bar|baz)\z/'

  singleton_mutations
  regexp_mutations

  mutation '/\A(foo|bar)\z/'
  mutation '/\A(foo|baz)\z/'
  mutation '/\A(bar|baz)\z/'
  mutation '/\A(?:foo|bar|baz)\z/'
end


text:
namespace Distribox.Network
{
    using System;
    using System.Runtime.CompilerServices;

    /// <summary>
    /// Abstract message of Anti-Entropy Protocol.
    /// </summary>
    public abstract class ProtocolMessage
    {
        // FIXME: Use a factory and make this class abstract
        // FIXME: I set all of these public for JSON serialize

        /// <summary>
        /// Initializes a new instance of the <see cref="Distribox.Network.ProtocolMessage"/> class.
        /// </summary>
        /// <param name="listeningPort">Listening port.</param>
        protected ProtocolMessage(int listeningPort)
        {
            this.ListeningPort = listeningPort;
        }

        /// <summary>
        /// Message type.
        /// </summary>
        [assembly: InternalsVisibleTo("Distribox.Test")]
        public enum MessageType
        {
            /// <summary>
            /// The invitation request.
            /// </summary>
            InvitationRequest,

            /// <summary>
            /// The invitation ACK.
            /// </summary>
            InvitationAck,

            /// <summary>
            /// The sync request.
            /// </summary>
            SyncRequest,

            /// <summary>
            /// The sync ACK.
            /// </summary>
            SyncAck,

            /// <summary>
            /// The peer list message.
            /// </summary>
            PeerListMessage,

            /// <summary>
            /// The version list message.
            /// </summary>
            VersionListMessage,

            /// <summary>
            /// The patch request.
            /// </summary>
            PatchRequest,

            /// <summary>
            /// The file response.
            /// </summary>
            FileResponse
        }

        /// <summary>
        /// Gets or sets the listening port.
        /// </summary>
        /// <value>The listening port.</value>
        public int ListeningPort { get; set; }

        /// <summary>
        /// Gets or sets the type.
        /// </summary>
        /// <value>The type.</value>
        public MessageType Type { get; set; }

        /// <summary>
        /// Accept the specified visitor and peer.
        /// </summary>
        /// <param name='visitor'>
        /// The Visitor.
        /// </param>
        /// <param name='peer'>
        /// The Peer.
        /// </param>
        public abstract void Accept(AntiEntropyProtocol visitor, Peer peer);
    }
}


text:
Deeplator is a Python library and application enabling translation via the DeepL translator available at [deepl.com](https://www.deepl.com/translator).

In August 2017, DeepL released the DeepL translator.
With unprecedented translation quality, the DeepL translator sets a new standard in neural machine translation.
Check out [deepl.com](https://www.deepl.com/press.html) to get more information.

Currently, the supported languages include English, German, French, Spanish, Italian, Dutch and Polish.

If you're coding in PHP instead, [DeepLy](https://github.com/chriskonnertz/DeepLy) might be the right choice.

## Application Usage
Using the application is straight forward.
Basically, you just need to launch `deeplator.py`.

The `-l LANG` argument specifies the source and output languages.
If omitted, the application will ask for the languages interactively.
`LANG` is the translation code in the format `AA-BB` where `AA` ist the source language code and `BB` is the output language code.
See the table below for all language codes.
For example, if you were to translate from English to German, the argument should be `-l EN-DE`.
You can also tell DeepL to automatically detect the language of the source text by supplying `AUTO` as the source language (e.g. `-l AUTO-DE`).

|Language   |Code|
|:----------|:--:|
|German     |DE  |
|English    |EN  |
|Spanish    |ES  |
|French     |FR  |
|Italian    |IT  |
|Dutch      |NL  |
|Polish     |PL  |
|Portuguese |PT  |
|Russian    |RU  |

You can tell Deeplator to read input from a file using the `-f PATH` argument.
When ommitted, Deeplator will read input from `stdin` instead.
Remember to exit the multiline input with `Ctrl+D`.

## Library Usage
The Deeplator library was written for Python 3.

### Single Sentence
```python
from deeplator import Translator

t = Translator("EN", "DE")
sentence = "Hello world."
translation = t.translate_sentence(sentence)
print(translation)
```

### Multiple Sentences
In case it is unknown if the input string consists of multiple sentences, use the `translate_sentences` method.
It will split the passed argument into sentences first and translate each sentence by its own.
```python
from deeplator import Translator

t = Translator("EN", "DE")
paragraph = "Hello world. DeepL is awesome."
translations = t.translate_sentences(paragraph)
print(translations)
```


text:
bool locked_container_focus = false;
bool locked_view_focus = false;

// switches parent focus to c. will switch it accordingly
// TODO: Everything needs a handle, so we can set front/back position properly
static void update_focus(swayc_t *c) {
	// Handle if focus switches
	swayc_t *parent = c->parent;
	if (parent->focused != c) {
		switch (c->type) {
		case C_ROOT: return;
		case C_OUTPUT:
			wlc_output_focus(c->handle);
			break;
		// switching workspaces
		case C_WORKSPACE:
			if (parent->focused) {
				swayc_t *ws = parent->focused;
				// hide visibility of old workspace
				uint32_t mask = 1;
				container_map(ws, set_view_visibility, &mask);
				// set visibility of new workspace
				mask = 2;
				container_map(c, set_view_visibility, &mask);
				wlc_output_set_mask(parent->handle, 2);
				destroy_workspace(ws);
			}
			active_workspace = c;
			break;
		default:
		case C_VIEW:
		case C_CONTAINER:
			// TODO whatever to do when container changes
			// for example, stacked and tabbing change stuff.
			break;
		}
	}
	c->parent->focused = c;
}

bool move_focus(enum movement_direction direction) {
	if (locked_container_focus) {
		return false;
	}
	swayc_t *current = get_focused_container(&root_container);
	swayc_t *parent = current->parent;

	if (direction == MOVE_PARENT) {
		if (parent->type == C_OUTPUT) {
			sway_log(L_DEBUG, "Focus cannot move to parent");
			return false;
		} else {
			sway_log(L_DEBUG, "Moving focus from %p:%ld to %p:%ld",
				current, current->handle, parent, parent->handle);
			set_focused_container(parent);
			return true;
		}
	}

	while (true) {
		sway_log(L_DEBUG, "Moving focus away from %p", current);

		// Test if we can even make a difference here
		bool can_move = false;
		int diff = 0;
		if (direction == MOVE_LEFT || direction == MOVE_RIGHT) {
			if (parent->layout == L_HORIZ || parent->type == C_ROOT) {
				can_move = true;
				diff = direction == MOVE_LEFT ? -1 : 1;
			}
		} else {
			if (parent->layout == L_VERT) {
				can_move = true;
				diff = direction == MOVE_UP ? -1 : 1;
			}
		}
		sway_log(L_DEBUG, "Can move? %s", can_move ? "yes" : "no");
		if (can_move) {
			int i;
			for (i = 0; i < parent->children->length; ++i) {
				swayc_t *child = parent->children->items[i];
				if (child == current) {
					break;
				}
			}
			int desired = i + diff;
			sway_log(L_DEBUG, "Moving from %d to %d", i, desired);
			if (desired < 0 || desired >= parent->children->length) {
				can_move = false;
			} else {
				swayc_t *newview = parent->children->items[desired];
				set_focused_container(get_focused_view(newview));
				return true;
			}
		}
		if (!can_move) {
			sway_log(L_DEBUG, "Can't move at current level, moving up tree");
			current = parent;
			parent = parent->parent;
			if (!parent) {
				// Nothing we can do
				return false;
			}
		}
	}
}

swayc_t *get_focused_container(swayc_t *parent) {
	while (parent && !parent->is_focused) {
		parent = parent->focused;
	}
	// just incase
	if (parent == NULL) {
		sway_log(L_DEBUG, "get_focused_container unable to find container");
		return active_workspace;
	}
	return parent;
}

void set_focused_container(swayc_t *c) {
	if (locked_container_focus || !c) {
		return;
	}
	sway_log(L_DEBUG, "Setting focus to %p:%ld", c, c->handle);
	if (c->type != C_ROOT && c->type != C_OUTPUT) {
		c->is_focused = true;
	}
	swayc_t *prev_view = get_focused_view(&root_container);
	swayc_t *p = c;
	while (p != &root_container) {
		update_focus(p);
		p = p->parent;
		p->is_focused = false;
	}
	if (!locked_view_focus) {
		p = get_focused_view(c);
		// Set focus to p
		if (p && !(wlc_view_get_type(p->handle) & WLC_BIT_POPUP)) {
			if (prev_view) {
				wlc_view_set_state(prev_view->handle, WLC_BIT_ACTIVATED, false);
			}
			wlc_view_focus(p->handle);
			wlc_view_set_state(p->handle, WLC_BIT_ACTIVATED, true);
		}
	}
}

void set_focused_container_for(swayc_t *a, swayc_t *c) {
	if (locked_container_focus || !c) {
		return;
	}
	swayc_t *find = c;
	//Ensure that a is an ancestor of c
	while (find != a && (find = find->parent)) {
		if (find == &root_container) {
			return;
		}
	}

	sway_log(L_DEBUG, "Setting focus for %p:%ld to %p:%ld",
		a, a->handle, c, c->handle);

	c->is_focused = true;
	swayc_t *p = c;
	while (p != a) {
		update_focus(p);
		p = p->parent;
		p->is_focused = false;
	}
	if (!locked_view_focus) {
		p = get_focused_view(c);
		// Set focus to p
		if (p) {
			wlc_view_focus(p->handle);
			wlc_view_set_state(p->handle, WLC_BIT_ACTIVATED, true);
		}
	}
}

swayc_t *get_focused_view(swayc_t *parent) {
	while (parent && parent->type != C_VIEW) {
		parent = parent->focused;
	}
	return parent;
}


text:
require "rails_helper"

describe VolunteerOpsController, :type => :routing do
  describe "routing" do
    before :each do
      allow(Feature).to receive(:active?).with(:volunteer_ops).and_return(true)
    end

    it "routes to #index" do
      expect(get("/volunteer_ops")).to route_to("volunteer_ops#index")
    end

    it "routes to #new" do
      expect(get("/organisations/2/volunteer_ops/new")).to route_to("volunteer_ops#new", organisation_id: "2")
    end

    it "routes to #show" do
      expect(get("/volunteer_ops/1")).to route_to("volunteer_ops#show", :id => "1")
    end

    it "routes to #edit" do
      expect(get("/volunteer_ops/1/edit")).to route_to("volunteer_ops#edit", :id => "1")
    end

    it "routes to #create" do
      expect(post("/organisations/2/volunteer_ops")).to route_to("volunteer_ops#create", organisation_id: "2")
    end

    it "routes to #update" do
      expect(put("/volunteer_ops/1")).to route_to("volunteer_ops#update", :id => "1")
    end

    it "routes to #destroy" do
      expect(delete("/volunteer_ops/1")).to route_to("volunteer_ops#destroy", :id => "1")
    end
  end
end


text:
<?xml version="1.0" ?>

<package-spec xmlns="urn:jboss:galleon:package:1.0" name="product.conf">
</package-spec>


text:
mvn clean verify
mvn release:prepare -DskipTests
mvn release:perform -DskipTests


text:
export default function append(s: string, toPrepend: string): string {
  return `${ s }${ toPrepend }`;
}


text:
class CtorTag { }

CtorTag `Hello world!`;

//// [taggedTemplateWithConstructableTag01.js]
var CtorTag = (function () {
    function CtorTag() {
    }
    return CtorTag;
}());
(_a = ["Hello world!"], _a.raw = ["Hello world!"], CtorTag(_a));
var _a;


text:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#2F6"
    android:src="@drawable/ic_launcher" >

</ImageView>