text:
package net

// TODO(rsc):
//	support for raw ethernet sockets

import "os"

// Addr represents a network end point address.
type Addr interface {
	Network() string // name of the network
	String() string  // string form of address
}

// Conn is a generic stream-oriented network connection.
type Conn interface {
	// Read reads data from the connection.
	// Read can be made to time out and return a net.Error with Timeout() == true
	// after a fixed time limit; see SetTimeout and SetReadTimeout.
	Read(b []byte) (n int, err os.Error)

	// Write writes data to the connection.
	// Write can be made to time out and return a net.Error with Timeout() == true
	// after a fixed time limit; see SetTimeout and SetWriteTimeout.
	Write(b []byte) (n int, err os.Error)

	// Close closes the connection.
	Close() os.Error

	// LocalAddr returns the local network address.
	LocalAddr() Addr

	// RemoteAddr returns the remote network address.
	RemoteAddr() Addr

	// SetTimeout sets the read and write deadlines associated
	// with the connection.
	SetTimeout(nsec int64) os.Error

	// SetReadTimeout sets the time (in nanoseconds) that
	// Read will wait for data before returning an error with Timeout() == true.
	// Setting nsec == 0 (the default) disables the deadline.
	SetReadTimeout(nsec int64) os.Error

	// SetWriteTimeout sets the time (in nanoseconds) that
	// Write will wait to send its data before returning an error with Timeout() == true.
	// Setting nsec == 0 (the default) disables the deadline.
	// Even if write times out, it may return n > 0, indicating that
	// some of the data was successfully written.
	SetWriteTimeout(nsec int64) os.Error
}

// An Error represents a network error.
type Error interface {
	os.Error
	Timeout() bool   // Is the error a timeout?
	Temporary() bool // Is the error temporary?
}

// PacketConn is a generic packet-oriented network connection.
type PacketConn interface {
	// ReadFrom reads a packet from the connection,
	// copying the payload into b.  It returns the number of
	// bytes copied into b and the return address that
	// was on the packet.
	// ReadFrom can be made to time out and return
	// an error with Timeout() == true after a fixed time limit;
	// see SetTimeout and SetReadTimeout.
	ReadFrom(b []byte) (n int, addr Addr, err os.Error)

	// WriteTo writes a packet with payload b to addr.
	// WriteTo can be made to time out and return
	// an error with Timeout() == true after a fixed time limit;
	// see SetTimeout and SetWriteTimeout.
	// On packet-oriented connections, write timeouts are rare.
	WriteTo(b []byte, addr Addr) (n int, err os.Error)

	// Close closes the connection.
	Close() os.Error

	// LocalAddr returns the local network address.
	LocalAddr() Addr

	// SetTimeout sets the read and write deadlines associated
	// with the connection.
	SetTimeout(nsec int64) os.Error

	// SetReadTimeout sets the time (in nanoseconds) that
	// Read will wait for data before returning an error with Timeout() == true.
	// Setting nsec == 0 (the default) disables the deadline.
	SetReadTimeout(nsec int64) os.Error

	// SetWriteTimeout sets the time (in nanoseconds) that
	// Write will wait to send its data before returning an error with Timeout() == true.
	// Setting nsec == 0 (the default) disables the deadline.
	// Even if write times out, it may return n > 0, indicating that
	// some of the data was successfully written.
	SetWriteTimeout(nsec int64) os.Error
}

// A Listener is a generic network listener for stream-oriented protocols.
type Listener interface {
	// Accept waits for and returns the next connection to the listener.
	Accept() (c Conn, err os.Error)

	// Close closes the listener.
	Close() os.Error

	// Addr returns the listener's network address.
	Addr() Addr
}

var errMissingAddress = os.ErrorString("missing address")

type OpError struct {
	Op    string
	Net   string
	Addr  Addr
	Error os.Error
}

func (e *OpError) String() string {
	if e == nil {
		return "<nil>"
	}
	s := e.Op
	if e.Net != "" {
		s += " " + e.Net
	}
	if e.Addr != nil {
		s += " " + e.Addr.String()
	}
	s += ": " + e.Error.String()
	return s
}

type temporary interface {
	Temporary() bool
}

func (e *OpError) Temporary() bool {
	t, ok := e.Error.(temporary)
	return ok && t.Temporary()
}

type timeout interface {
	Timeout() bool
}

func (e *OpError) Timeout() bool {
	t, ok := e.Error.(timeout)
	return ok && t.Timeout()
}

type AddrError struct {
	Error string
	Addr  string
}

func (e *AddrError) String() string {
	if e == nil {
		return "<nil>"
	}
	s := e.Error
	if e.Addr != "" {
		s += " " + e.Addr
	}
	return s
}

func (e *AddrError) Temporary() bool {
	return false
}

func (e *AddrError) Timeout() bool {
	return false
}

type UnknownNetworkError string

func (e UnknownNetworkError) String() string  { return "unknown network " + string(e) }
func (e UnknownNetworkError) Temporary() bool { return false }
func (e UnknownNetworkError) Timeout() bool   { return false }


text:
package main

import (
	"os"
	"text/template"

	"github.com/kubernetes-incubator/cri-o/server"
	"github.com/urfave/cli"
)

var commentedConfigTemplate = template.Must(template.New("config").Parse(`
# The "ocid" table contains all of the server options.
[ocid]

# root is a path to the "root directory". OCID stores all of its data,
# including container images, in this directory.
root = "{{ .Root }}"

# run is a path to the "run directory". OCID stores all of its state
# in this directory.
runroot = "{{ .RunRoot }}"

# storage_driver select which storage driver is used to manage storage
# of images and containers.
storage_driver = "{{ .Storage }}"

# storage_option is used to pass an option to the storage driver.
storage_option = [
{{ range $opt := .StorageOptions }}{{ printf "\t%q,\n" $opt }}{{ end }}]

# The "ocid.api" table contains settings for the kubelet/gRPC
# interface (which is also used by ocic).
[ocid.api]

# listen is the path to the AF_LOCAL socket on which ocid will listen.
listen = "{{ .Listen }}"

# The "ocid.runtime" table contains settings pertaining to the OCI
# runtime used and options for how to set up and manage the OCI runtime.
[ocid.runtime]

# runtime is a path to the OCI runtime which ocid will be using.
runtime = "{{ .Runtime }}"

# conmon is the path to conmon binary, used for managing the runtime.
conmon = "{{ .Conmon }}"

# conmon_env is the environment variable list for conmon process,
# used for passing necessary environment variable to conmon or runtime.
conmon_env = [
{{ range $env := .ConmonEnv }}{{ printf "\t%q,\n" $env }}{{ end }}]

# selinux indicates whether or not SELinux will be used for pod
# separation on the host. If you enable this flag, SELinux must be running
# on the host.
selinux = {{ .SELinux }}

# seccomp_profile is the seccomp json profile path which is used as the
# default for the runtime.
seccomp_profile = "{{ .SeccompProfile }}"

# apparmor_profile is the apparmor profile name which is used as the
# default for the runtime.
apparmor_profile = "{{ .ApparmorProfile }}"

# cgroup_manager is the cgroup management implementation to be used
# for the runtime.
cgroup_manager = "{{ .CgroupManager }}"

# The "ocid.image" table contains settings pertaining to the
# management of OCI images.
[ocid.image]

# default_transport is the prefix we try prepending to an image name if the
# image name as we receive it can't be parsed as a valid source reference
default_transport = "{{ .DefaultTransport }}"

# pause_image is the image which we use to instantiate infra containers.
pause_image = "{{ .PauseImage }}"

# pause_command is the command to run in a pause_image to have a container just
# sit there.  If the image contains the necessary information, this value need
# not be specified.
pause_command = "{{ .PauseCommand }}"

# signature_policy is the name of the file which decides what sort of policy we
# use when deciding whether or not to trust an image that we've pulled.
# Outside of testing situations, it is strongly advised that this be left
# unspecified so that the default system-wide policy will be used.
signature_policy = "{{ .SignaturePolicyPath }}"

# The "ocid.network" table contains settings pertaining to the
# management of CNI plugins.
[ocid.network]

# network_dir is is where CNI network configuration
# files are stored.
network_dir = "{{ .NetworkDir }}"

# plugin_dir is is where CNI plugin binaries are stored.
plugin_dir = "{{ .PluginDir }}"
`))

// TODO: Currently ImageDir isn't really used, so we haven't added it to this
//       template. Add it once the storage code has been merged.

var configCommand = cli.Command{
	Name:  "config",
	Usage: "generate ocid configuration files",
	Flags: []cli.Flag{
		cli.BoolFlag{
			Name:  "default",
			Usage: "output the default configuration",
		},
	},
	Action: func(c *cli.Context) error {
		// At this point, app.Before has already parsed the user's chosen
		// config file. So no need to handle that here.
		config := c.App.Metadata["config"].(*server.Config)
		if c.Bool("default") {
			config = server.DefaultConfig()
		}

		// Output the commented config.
		return commentedConfigTemplate.ExecuteTemplate(os.Stdout, "config", config)
	},
}

redpajama_set_name: RedPajamaGithub


text:
import numpy
import six

from chainer import cuda
from chainer import function
from chainer.utils import type_check

class TreeParser(object):

    def __init__(self):
        self.next_id = 0

    def size(self):
        return self.next_id

    def get_paths(self):
        return self.paths

    def get_codes(self):
        return self.codes

    def parse(self, tree):
        self.next_id = 0
        self.path = []
        self.code = []
        self.paths = {}
        self.codes = {}
        self._parse(tree)

        assert(len(self.path) == 0)
        assert(len(self.code) == 0)
        assert(len(self.paths) == len(self.codes))

    def _parse(self, node):
        if isinstance(node, tuple):
            # internal node
            if len(node) != 2:
                raise ValueError(
                    'All internal nodes must have two child nodes')
            left, right = node
            self.path.append(self.next_id)
            self.next_id += 1
            self.code.append(1.0)
            self._parse(left)

            self.code[-1] = -1.0
            self._parse(right)

            self.path.pop()
            self.code.pop()

        else:
            # leaf node
            self.paths[node] = numpy.array(self.path).astype(numpy.int32)
            self.codes[node] = numpy.array(self.code).astype(numpy.float32)

class BinaryHierarchicalSoftmax(function.Function):

    """Implementation of hierarchical softmax (HSM).

    In natural language applications, vocabulary size is too large to use
    softmax loss.
    Instead, the hierarchical softmax uses product of sigmoid functions.
    It costs only :math:`O(\log(n))` time where :math:`n` is the vocabulary
    size in average.

    At first a user need to prepare a binary tree whose each leaf is
    corresponding to a word in a vocabulary.
    When a word :math:`x` is given, exactly one path from the root of the tree
    to the leaf of the word exists.
    Let :math:`\mbox{path}(x) = ((e_1, b_1), \dots, (e_m, b_m))` be the path of
    :math:`x`, where :math:`e_i` is an index of :math:`i`-th internal node, and
    :math:`b_i \in \{-1, 1\}` indicates direction to move at :math:`i`-th
    internal node (-1 is left, and 1 is right).
    Then, the probability of :math:`x` is given as below:

    .. math::

       P(x) &= \prod_{(e_i, b_i) \in \mbox{path}(x)}P(b_i | e_i)  \\\\
            &= \prod_{(e_i, b_i) \in \mbox{path}(x)}\sigma(b_i x^\\top
               w_{e_i}),

    where :math:`\sigma(\\cdot)` is a sigmoid function, and :math:`w` is a
    weight matrix.

    This function costs :math:`O(\log(n))` time as an average length of paths
    is :math:`O(\log(n))`, and :math:`O(n)` memory as the number of internal
    nodes equals :math:`n - 1`.

    Args:
        in_size (int): Dimension of input vectors.
        tree: A binary tree made with tuples like `((1, 2), 3)`.

    See: Hierarchical Probabilistic Neural Network Language Model [Morin+,
    AISTAT2005].

    """

    parameter_names = ('W',)
    gradient_names = ('gW',)

    def __init__(self, in_size, tree):
        parser = TreeParser()
        parser.parse(tree)
        self.paths = parser.get_paths()
        self.codes = parser.get_codes()

        self.W = numpy.random.uniform(
            -1, 1, (parser.size(), in_size)).astype(numpy.float32)
        self.gW = numpy.zeros(self.W.shape, numpy.float32)

    def check_type_forward(self, in_types):
        type_check.expect(in_types.size() == 2)
        x_type, t_type = in_types

        type_check.expect(
            x_type.dtype == numpy.float32,
            x_type.ndim == 2,
            t_type.dtype == numpy.int32,
            t_type.ndim == 1,
            x_type.shape[0] == t_type.shape[0]
        )

    def forward_cpu(self, args):
        x, t = args

        loss = numpy.float32(0.0)
        for ix, it in six.moves.zip(x, t):
            loss += self._forward_cpu_one(ix, it)
        return numpy.array(loss),

    def _forward_cpu_one(self, x, t):
        assert t in self.paths

        w = self.W[self.paths[t]]
        wxy = w.dot(x) * self.codes[t]
        loss = numpy.logaddexp(0.0, -wxy)  # == log(1 + exp(-wxy))
        return numpy.sum(loss)

    def backward_cpu(self, args, loss):
        x, t = args
        gloss, = loss
        gx = numpy.empty_like(x)
        for i, (ix, it) in enumerate(six.moves.zip(x, t)):
            gx[i] = self._backward_cpu_one(ix, it, gloss)
        return gx, None

    def _backward_cpu_one(self, x, t, gloss):
        path = self.paths[t]
        w = self.W[path]
        wxy = w.dot(x) * self.codes[t]
        g = -gloss * self.codes[t] / (1.0 + numpy.exp(wxy))
        gx = g.dot(w)
        gw = g.reshape((g.shape[0], 1)).dot(x.reshape(1, x.shape[0]))
        self.gW[path] += gw
        return gx

    def to_gpu(self, device=None):
        function.Function.to_gpu(self, device)

        n_vocab = max(self.paths.keys()) + 1
        paths = cuda.to_gpu(numpy.concatenate(
            [self.paths[i] for i in range(n_vocab) if i in self.paths]))
        codes = cuda.to_gpu(numpy.concatenate(
            [self.codes[i] for i in range(n_vocab) if i in self.codes]))

        begins = numpy.empty((n_vocab + 1,), dtype=numpy.int32)
        begins[0] = 0
        for i in range(0, n_vocab):
            length = len(self.paths[i]) if i in self.paths else 0
            begins[i + 1] = begins[i] + length

        self.paths = paths
        self.codes = codes
        self.begins = cuda.to_gpu(begins)

    def forward_gpu(self, inputs):
        x, t = inputs

        max_length = cuda.reduce(
            'int* t, int* begins', 'begins[t[i] + 1] - begins[t[i]]',
            'max(a,b)', '0', 'binary_hierarchical_softmax_max_length',
            numpy.int32
        )(t, self.begins)
        max_length = cuda.to_cpu(max_length)[()]

        length = max_length * x.shape[0]
        ls = cuda.empty((length,), dtype=numpy.float32)
        n_in = x.shape[1]
        wxy = cuda.empty((length,), dtype=numpy.float32)
        cuda.elementwise(
            '''float* ls, float* wxy, const float* x, const float* w,
            const int* ts, const int* paths, const float* codes,
            const int* begins, int c, int max_length''',
            '''
            int ind = i / max_length;
            int offset = i - ind * max_length;
            int t = ts[ind];

            int begin = begins[t];
            int length = begins[t + 1] - begins[t];

            if (offset < length) {
              int p = begin + offset;
              int node = paths[p];

              x = &x[ind * c];

              float wx = 0;
              for (int j = 0; j < c; ++j) {
                wx += w[node * c + j] * x[j];
              }
              wxy[i] = wx * codes[p];
              ls[i] = log(1 + exp(-wxy[i]));
            } else {
              ls[i] = 0;
            }
            ''',
            'binary_hierarchical_softmax_forward'
        )(ls, wxy, x, self.W, t, self.paths, self.codes, self.begins,
          n_in, max_length)
        self.max_length = max_length
        self.wxy = wxy
        return cuda.gpuarray.sum(ls),

    def backward_gpu(self, inputs, loss):
        x, t = inputs
        gloss, = loss

        n_in = x.shape[1]
        gx = cuda.zeros_like(x)
        cuda.elementwise(
            '''const float* wxy, float* gx, float* gw, const float* x,
            const float* w, const int* ts, const int* paths,
            const float* codes, const int* begins,
            const float* gloss, int c, int max_length''',
            '''
            int ind = i / max_length;
            int offset = i - ind * max_length;
            int t = ts[ind];

            int begin = begins[t];
            int length = begins[t + 1] - begins[t];

            if (offset < length) {
              int p = begin + offset;
              int node = paths[p];
              float code = codes[p];
              gx = &gx[ind * c];
              x = &x[ind * c];

              float g = -*gloss * code / (1.0 + exp(wxy[i]));
              for (int j = 0; j < c; ++j) {
                atomicAdd(gx + j, g * w[node * c + j]);
                atomicAdd(gw + node * c + j, g * x[j]);
              }
            }
            ''',
            'binary_hierarchical_softmax_bwd'
        )(self.wxy, gx, self.gW, x, self.W, t, self.paths, self.codes,
          self.begins, gloss, n_in, self.max_length)
        return gx, None

def create_huffman_tree(word_counts):
    """Make a huffman tree from a dictionary containing word counts.

    This method creates a binary huffman tree, that is required for
    :class:`BinaryHierarchicalSoftmax`.
    For example, ``{0: 8, 1: 5, 2: 6, 3: 4}`` is converted to
    ``((3, 1), (2, 0))``.

    Args:
        word_counts (``dict`` of ``int`` key and ``int`` or ``float`` values.):
            Dictionary representing counts of words.

    Returns:
        Binary huffman tree with tuples and keys of ``word_coutns``.

    """
    if len(word_counts) == 0:
        raise ValueError('Empty vocabulary')

    q = six.moves.queue.PriorityQueue()
    # Add unique id to each entry so that we can compare two entries with same
    # counts.
    # Note that itreitems randomly order the entries.
    for uid, (w, c) in enumerate(six.iteritems(word_counts)):
        q.put((c, uid, w))

    while q.qsize() >= 2:
        (count1, id1, word1) = q.get()
        (count2, id2, word2) = q.get()
        count = count1 + count2
        tree = (word1, word2)
        q.put((count, min(id1, id2), tree))

    return q.get()[2]


text:
package org.curso.angular.service.impl;

import java.util.Collection;

import org.curso.angular.entity.Operadora;
import org.curso.angular.repository.OperadoraRepository;
import org.curso.angular.service.OperadoraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OperadoraServiceImpl implements OperadoraService {

	@Autowired
	private OperadoraRepository repository;

	public Operadora findById(Long id) {
		return repository.findOne(id);
	}

	public Operadora findByNome(String nome) {
		return repository.findByNome(nome);
	}

	public Operadora findByCodigo(Long codigo){
		return repository.findByCodigo(codigo);
	}

	public Collection<Operadora> findAll() {
		return (Collection<Operadora>) repository.findAll();
	}

	public Operadora create(Operadora operadora) {
		return repository.save(operadora);
	}

	public Operadora update(Operadora operadora) {
		return repository.save(operadora);
	}

	public void delete(Operadora operadora) {
		repository.delete(operadora);

	}

}


text:
#ifndef __ASM_CRIME_H__
#define __ASM_CRIME_H__

/*
 * Address map
 */
#define CRIME_BASE	0x14000000	/* physical */

struct sgi_crime {
	volatile unsigned long id;
#define CRIME_ID_MASK			0xff
#define CRIME_ID_IDBITS			0xf0
#define CRIME_ID_IDVALUE		0xa0
#define CRIME_ID_REV			0x0f
#define CRIME_REV_PETTY			0x00
#define CRIME_REV_11			0x11
#define CRIME_REV_13			0x13
#define CRIME_REV_14			0x14

	volatile unsigned long control;
#define CRIME_CONTROL_MASK		0x3fff
#define CRIME_CONTROL_TRITON_SYSADC	0x2000
#define CRIME_CONTROL_CRIME_SYSADC	0x1000
#define CRIME_CONTROL_HARD_RESET	0x0800
#define CRIME_CONTROL_SOFT_RESET	0x0400
#define CRIME_CONTROL_DOG_ENA		0x0200
#define CRIME_CONTROL_ENDIANESS		0x0100
#define CRIME_CONTROL_ENDIAN_BIG	0x0100
#define CRIME_CONTROL_ENDIAN_LITTLE	0x0000
#define CRIME_CONTROL_CQUEUE_HWM	0x000f
#define CRIME_CONTROL_CQUEUE_SHFT	0
#define CRIME_CONTROL_WBUF_HWM		0x00f0
#define CRIME_CONTROL_WBUF_SHFT		8

	volatile unsigned long istat;
	volatile unsigned long imask;
	volatile unsigned long soft_int;
	volatile unsigned long hard_int;
#define MACE_VID_IN1_INT		BIT(0)
#define MACE_VID_IN2_INT		BIT(1)
#define MACE_VID_OUT_INT		BIT(2)
#define MACE_ETHERNET_INT		BIT(3)
#define MACE_SUPERIO_INT		BIT(4)
#define MACE_MISC_INT			BIT(5)
#define MACE_AUDIO_INT			BIT(6)
#define MACE_PCI_BRIDGE_INT		BIT(7)
#define MACEPCI_SCSI0_INT		BIT(8)
#define MACEPCI_SCSI1_INT		BIT(9)
#define MACEPCI_SLOT0_INT		BIT(10)
#define MACEPCI_SLOT1_INT		BIT(11)
#define MACEPCI_SLOT2_INT		BIT(12)
#define MACEPCI_SHARED0_INT		BIT(13)
#define MACEPCI_SHARED1_INT		BIT(14)
#define MACEPCI_SHARED2_INT		BIT(15)
#define CRIME_GBE0_INT			BIT(16)
#define CRIME_GBE1_INT			BIT(17)
#define CRIME_GBE2_INT			BIT(18)
#define CRIME_GBE3_INT			BIT(19)
#define CRIME_CPUERR_INT		BIT(20)
#define CRIME_MEMERR_INT		BIT(21)
#define CRIME_RE_EMPTY_E_INT		BIT(22)
#define CRIME_RE_FULL_E_INT		BIT(23)
#define CRIME_RE_IDLE_E_INT		BIT(24)
#define CRIME_RE_EMPTY_L_INT		BIT(25)
#define CRIME_RE_FULL_L_INT		BIT(26)
#define CRIME_RE_IDLE_L_INT    		BIT(27)
#define CRIME_SOFT0_INT			BIT(28)
#define CRIME_SOFT1_INT			BIT(29)
#define CRIME_SOFT2_INT			BIT(30)
#define CRIME_SYSCORERR_INT		CRIME_SOFT2_INT
#define CRIME_VICE_INT			BIT(31)
/* Masks for deciding who handles the interrupt */
#define CRIME_MACE_INT_MASK		0x8f
#define CRIME_MACEISA_INT_MASK		0x70
#define CRIME_MACEPCI_INT_MASK		0xff00
#define CRIME_CRIME_INT_MASK		0xffff0000

	volatile unsigned long watchdog;
#define CRIME_DOG_POWER_ON_RESET	0x00010000
#define CRIME_DOG_WARM_RESET		0x00080000
#define CRIME_DOG_TIMEOUT		(CRIME_DOG_POWER_ON_RESET|CRIME_DOG_WARM_RESET)
#define CRIME_DOG_VALUE			0x00007fff

	volatile unsigned long timer;
#define CRIME_MASTER_FREQ		66666500	/* Crime upcounter frequency */
#define CRIME_NS_PER_TICK		15		/* for delay_calibrate */

	volatile unsigned long cpu_error_addr;
#define CRIME_CPU_ERROR_ADDR_MASK	0x3ffffffff

	volatile unsigned long cpu_error_stat;
#define CRIME_CPU_ERROR_MASK		0x7		/* cpu error stat is 3 bits */
#define CRIME_CPU_ERROR_CPU_ILL_ADDR	0x4
#define CRIME_CPU_ERROR_VICE_WRT_PRTY	0x2
#define CRIME_CPU_ERROR_CPU_WRT_PRTY	0x1

	unsigned long _pad0[54];

	volatile unsigned long mc_ctrl;
	volatile unsigned long bank_ctrl[8];
#define CRIME_MEM_BANK_CONTROL_MASK		0x11f	/* 9 bits 7:5 reserved */
#define CRIME_MEM_BANK_CONTROL_ADDR		0x01f
#define CRIME_MEM_BANK_CONTROL_SDRAM_SIZE	0x100
#define CRIME_MAXBANKS				8

	volatile unsigned long mem_ref_counter;
#define CRIME_MEM_REF_COUNTER_MASK	0x3ff		/* 10bit */

	volatile unsigned long mem_error_stat;
#define CRIME_MEM_ERROR_STAT_MASK       0x0ff7ffff	/* 28-bit register */
#define CRIME_MEM_ERROR_MACE_ID		0x0000007f
#define CRIME_MEM_ERROR_MACE_ACCESS	0x00000080
#define CRIME_MEM_ERROR_RE_ID		0x00007f00
#define CRIME_MEM_ERROR_RE_ACCESS	0x00008000
#define CRIME_MEM_ERROR_GBE_ACCESS	0x00010000
#define CRIME_MEM_ERROR_VICE_ACCESS	0x00020000
#define CRIME_MEM_ERROR_CPU_ACCESS	0x00040000
#define CRIME_MEM_ERROR_RESERVED	0x00080000
#define CRIME_MEM_ERROR_SOFT_ERR	0x00100000
#define CRIME_MEM_ERROR_HARD_ERR	0x00200000
#define CRIME_MEM_ERROR_MULTIPLE	0x00400000
#define CRIME_MEM_ERROR_ECC		0x01800000
#define CRIME_MEM_ERROR_MEM_ECC_RD	0x00800000
#define CRIME_MEM_ERROR_MEM_ECC_RMW	0x01000000
#define CRIME_MEM_ERROR_INV		0x0e000000
#define CRIME_MEM_ERROR_INV_MEM_ADDR_RD	0x02000000
#define CRIME_MEM_ERROR_INV_MEM_ADDR_WR	0x04000000
#define CRIME_MEM_ERROR_INV_MEM_ADDR_RMW 0x08000000

	volatile unsigned long mem_error_addr;
#define CRIME_MEM_ERROR_ADDR_MASK	0x3fffffff

	volatile unsigned long mem_ecc_syn;
#define CRIME_MEM_ERROR_ECC_SYN_MASK	0xffffffff

	volatile unsigned long mem_ecc_chk;
#define CRIME_MEM_ERROR_ECC_CHK_MASK	0xffffffff

	volatile unsigned long mem_ecc_repl;
#define CRIME_MEM_ERROR_ECC_REPL_MASK	0xffffffff
};

extern struct sgi_crime __iomem *crime;

#define CRIME_HI_MEM_BASE	0x40000000	/* this is where whole 1G of RAM is mapped */

#endif /* __ASM_CRIME_H__ */


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six

if six.PY2:
    from .tempfile import TemporaryDirectory
    from .contextlib import ExitStack
else:
    from tempfile import TemporaryDirectory
    from contextlib import ExitStack


text:
<?php namespace Tests\Feature;

use App\Factory\PhotoFactory;
use App\Http\Livewire\Acp\PhotoEditForm;
use App\Http\Livewire\Acp\PhotoUploadForm;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;

class AcpPhotosTest extends TestCase
{
    use BeAdmin;
    use DatabaseTransactions;

    public function testCreate()
    {
        $this->get('acp/photos/create')
            ->assertOk()
            ->assertSeeLivewire(PhotoUploadForm::class);
    }

    public function testEdit()
    {
        $photo = PhotoFactory::new()->withTrip()->create();

        $this->get("acp/photos/{$photo->id}/edit")
            ->assertOk();
    }

    public function testIndex()
    {
        PhotoFactory::new()->withTrip()->create();

        $this->get('acp/photos')
            ->assertOk();
    }

    public function testShow()
    {
        $photo = PhotoFactory::new()->withTrip()->create();

        $this->get("acp/photos/{$photo->id}")
            ->assertOk();
    }

    public function testUpdate()
    {
        $photo = PhotoFactory::new()->withTag()->withTrip()->create();

        \Livewire::test(PhotoEditForm::class, ['photo' => $photo])
            ->set('tags', [])
            ->call('submit')
            ->assertHasNoErrors()
            ->assertRedirect('/acp/photos');

        $photo->refresh();

        $this->assertCount(0, $photo->tags);
    }
}


text:
<!DOCTYPE html>

    <title>Test 0084</title>

      Cryptography Users

          Alice

        1977


text:
package net.lshift.diffa.agent.itest.config

import net.lshift.diffa.agent.itest.support.TestConstants._
import org.junit.Test
import net.lshift.diffa.kernel.frontend.{PairDef, EndpointDef}
import net.lshift.diffa.agent.client.ConfigurationRestClient
import org.apache.http.impl.client.{BasicAuthCache, DefaultHttpClient}
import org.apache.http.client.methods.HttpGet
import org.junit.Assert._
import org.apache.http.auth.{AuthScope, UsernamePasswordCredentials}
import org.apache.http.HttpHost
import org.apache.http.impl.auth.BasicScheme
import org.apache.http.protocol.BasicHttpContext
import org.apache.http.client.protocol.ClientContext
import net.lshift.diffa.agent.itest.IsolatedDomainTest

class EtagTest extends IsolatedDomainTest {

  val configClient = new ConfigurationRestClient(agentURL, isolatedDomain)

  @Test
  def configChangeShouldUpgradeEtag {

    val up = EndpointDef(name = "some-upstream-endpoint")
    val down = EndpointDef(name = "some-downstream-endpoint")
    val pair = PairDef(key = "some-pair", upstreamName = up.name, downstreamName = down.name)

    val oldTag = getAggregatesEtag

    configClient.declareEndpoint(up)
    configClient.declareEndpoint(down)
    configClient.declarePair(pair)

    val newTag = getAggregatesEtag

    assertNotSame("Old etag was %s, new etag was %s".format(oldTag,newTag), oldTag, newTag)

  }

  private def getAggregatesEtag = {
    val targetHost = new HttpHost(agentHost, agentPort, "http")
    val httpClient = new DefaultHttpClient

    httpClient.getCredentialsProvider().setCredentials(
      new AuthScope(agentHost, agentPort),
      new UsernamePasswordCredentials(agentUsername, agentPassword))

    val httpResponse = httpClient.execute(
      new HttpGet(agentURL + "/spaces/%s/diffs/aggregates".format(isolatedDomain)),
      basicAuthContext(targetHost))

    assertNotSame("Should not have got a 404", 404, httpResponse.getStatusLine.getStatusCode)

    val etag = httpResponse.getLastHeader("ETag")
    httpResponse.getAllHeaders foreach { header =>
      println("Header [%s]".format(header))
    }
    httpClient.getConnectionManager.shutdown()
    etag.getValue
  }

  private def basicAuthContext(targetHost: HttpHost): BasicHttpContext = {
    val authCache = new BasicAuthCache
    val basicAuth = new BasicScheme
    authCache.put(targetHost, basicAuth)

    val context = new BasicHttpContext
    context.setAttribute(ClientContext.AUTH_CACHE, authCache)
    context
  }
}


text:
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/

define(function(require){
	var $ = require('jquery');
	var html = require('text!test/markup/datepicker-markup.html');
	/* FOR DEV TESTING - uncomment to test against index.html */
	//html = require('text!index.html!strip');

	require('bootstrap');
	require('fuelux/datepicker');

	module('Fuel UX Datepicker');

	test("should be defined on jquery object", function () {
		ok($().datepicker, 'datepicker method is defined');
	});

	test("should return element", function () {
		var $datepicker = $(html);
		ok($datepicker.datepicker()===$datepicker, 'datepicker should be initialized');
	});

	test('should initialize with current date and restrict past dates by default', function(){
		var today = new Date();
		var todaysDate = (today.getDate()<10) ? '0' + today.getDate() : today.getDate();
		var todaysMonth = ((today.getMonth()+1)<10) ? '0' + (today.getMonth()+1) : (today.getMonth()+1);
		today = todaysMonth + '/' + todaysDate + '/' + today.getFullYear();

		var $datepicker = $(html).datepicker();
		var pickerDate = $datepicker.datepicker('getFormattedDate');
		equal(pickerDate, today, 'w/ markup - initialized with todays date');

		var pastRestrictionCheck = $datepicker.find('.restricted').length > 0;
		equal(pastRestrictionCheck, true, 'restricted past dates are default');
	});

	test('should initialize with date other than now', function(){
		var $datepicker = $(html);
		var futureDate = new Date(new Date().getTime() + 604800000).getTime();	// 7 days in the future
		var pickerDate;

		$datepicker.datepicker({ date: futureDate });
		pickerDate = $datepicker.datepicker('getDate');

		equal(pickerDate.getTime(), futureDate, 'markup datepicker initialized with different date than now');
	});

	test('should initialize with null date', function(){
		var $datepicker = $(html).datepicker({ date: null });
		var initializedDate = $datepicker.datepicker('getDate').toString();
		var inputValue = $datepicker.find('input[type="text"]').val();

		equal((initializedDate==='Invalid Date' || initializedDate==='NaN'), true, 'datepicker was initialized with null value');
		equal(inputValue, '', 'datepicker does not have value in input field');
	});

	test('should return date using getDate method', function(){
		var $datepicker = $(html).datepicker({ date: new Date(1987, 2, 31) });
		var date = $datepicker.datepicker('getDate');
		var dateFormatted = $datepicker.datepicker('getFormattedDate');

		equal(date instanceof Date, true, 'returned a valid date object');
		equal((date.getDate()===31 && date.getMonth()===2 && date.getFullYear()===1987), true, 'returned correct date');
		equal(dateFormatted, '03/31/1987', 'returned correct formatted date');
	});

	test('should set new date using setDate method', function(){
		var $datepicker = $(html).datepicker();
		var newDate = new Date(1987, 2, 31);
		var datepickerDate;

		$datepicker.datepicker('setDate', newDate);
		datepickerDate = $datepicker.datepicker('getDate');

		equal(datepickerDate.getTime(), newDate.getTime(), 'setDate method works');
	});

	test('should enable/disable datepicker', function(){
		var $datepicker = $(html).datepicker();
		var $datepickerInput = $datepicker.find('input');

		var defaultState = !!$datepicker.find('button').prop('disabled') && !!$datepickerInput.prop('disabled');
		equal(defaultState, false, 'datepicker is enabled');

		$datepicker.datepicker('disable');
		var disabledState = !!$datepicker.find('button').prop('disabled') && !!$datepickerInput.prop('disabled');
		equal(disabledState, true, 'datepicker is disabled');

		$datepicker.datepicker('enable');
		var enabledState = !!$datepicker.find('button').prop('disabled') && !!$datepickerInput.prop('disabled');
		equal(enabledState, false, 'datepicker is enabled again');
	});

	test('should not restrict past dates when allowPastDates option set to true', function(){
		var $datepicker = $(html);
		var $pastDate;

		$datepicker.datepicker({ allowPastDates: true });
		$pastDate = $datepicker.find('.past:first');

		equal($pastDate.hasClass('restricted'), false, 'past dates are not restricted as expected');
	});

	test('should fire changed event when new date is input', function(){
		var called = 0;
		var $datepicker = $(html).datepicker();
		var $datepickerInput = $datepicker.find('input');
		var date = new Date(NaN);
		var event = false;

		$datepicker.on('changed.fu.datepicker', function(e, dt){
			called++;
			date = dt;
			event = e;
		});

		$datepickerInput.val('03/31/1987');
		$datepickerInput.trigger('blur');

		equal(called, 1, 'Event was triggered as expected');
		equal(typeof event, 'object', 'Appropriate event object passed back as argument');
		equal((date.getDate()===31 && date.getMonth()===2 && date.getFullYear()===1987), true, 'Appropriate date object passed back as argument');
	});

	test('should not use moment.js if not available', function(){
		var $datepicker = $(html).datepicker();
		var momentBoolean = $datepicker.datepicker('checkForMomentJS');

		equal(momentBoolean, false, 'not utilizing moment.js because it is not available');
	});

	test('should not be able to use features that require moment.js when it is not available', function(){
		var $datepicker = $(html).datepicker();
		var momentBoolean = $datepicker.datepicker('checkForMomentJS');
		var defaultErrorReturned = 'moment.js is not available so you cannot use this function';
		var errors = {};

		try{
			$datepicker.datepicker('getCulture');
		}catch(e){
			errors.getCulture = e;
		}

		try{
			$datepicker.datepicker('setCulture', 'de');
		}catch(e){
			errors.setCulture = e;
		}

		try{
			$datepicker.datepicker('getFormat');
		}catch(e){
			errors.getFormat = e;
		}

		try{
			$datepicker.datepicker('setFormat', 'l');
		}catch(e){
			errors.setFormat = e;
		}

		equal(momentBoolean, false, 'not utilizing moment.js because it is not available');
		equal(errors.getCulture, defaultErrorReturned, 'getCulture is not available for use');
		equal(errors.setCulture, defaultErrorReturned, 'setCulture is not available for use');
		equal(errors.getFormat, defaultErrorReturned, 'getFormat is not available for use');
		equal(errors.setFormat, defaultErrorReturned, 'setFormat is not available for use');
	});

	test('should restrict navigation and selection of dates within other years if option sameYearOnly is set to true', function() {
		var $datepicker = $(html).datepicker({
			date: new Date(1987, 2, 31),
			sameYearOnly: true
		});
		var $datepickerInput = $datepicker.find('input');
		var $header = $datepicker.find('.datepicker-calendar-header');
		var $titleButton = $header.find('.title');
		var $titleYear = $titleButton.find('span.year');
		var dateString;

		$datepicker.datepicker('setDate', '12/01/1987');
		$header.find('.next').trigger('click');
		equal($titleYear.text(), '1987', 'user can\'t next click outside current year');

		$datepicker.datepicker('setDate', '01/01/1987');
		$header.find('.prev').trigger('click');
		equal($titleYear.text(), '1987', 'user can\'t prev click outside current year');

		$titleButton.trigger('click');
		equal($datepicker.find('.datepicker-wheels-year').hasClass('hidden'), true, 'years wheel hidden');

		$datepickerInput.val('03/31/1988');
		$datepickerInput.trigger('blur');
		dateString = $datepicker.datepicker('getDate').toString();
		equal((dateString==='Invalid Date' || dateString==='NaN'), true, 'user can\t input date outside current year');
	});

	test('should restrict days if restricted option is set', function(){
		var $datepicker = $(html).datepicker({
			allowPastDates: true,
			date: new Date(1987, 2, 5),
			restricted: [{ from: new Date(1987, 2, 1), to: new Date(1987, 2, 4) }, { from: new Date(1987, 2, 28), to: new Date(1987, 3, 1) }]
		});
		var dates = ['1', '2', '3', '4', '28', '29', '30', '31', '1'];
		var i=0;
		var month = '2';

		$datepicker.find('.restricted').each(function(){
			var $item = $(this);
			if(i>7) {
				month = '3';
			}
			equal(($item.attr('data-date')===dates[i] && $item.attr('data-month')===month && $item.attr('data-year')==='1987'), true,
				'correct date restricted as expected');
			i++;
		});

		equal(dates.length===i, true, 'correct number of dates restricted');
	});

	test('should destroy control', function (){
		var $datepicker = $(html).datepicker();

		equal(typeof($datepicker.datepicker('destroy')), 'string', 'returns string (markup)');
		equal($datepicker.parent().length, false, 'control has been removed from DOM');
	});
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/icon_area_size"
    android:layout_height="@dimen/icon_area_size"
    android:layout_gravity="center"
    android:gravity="center">

    <ImageView
        android:id="@+id/icon"
        android:src="@drawable/ic_drink_generic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</LinearLayout>


text:
import tempfile
import os

#test
from testrunner.testhelp import context
from conary_test import recipes
from conary_test import rephelp

#conary
from conary.build import use
from conary.deps import deps
from conary.lib import log
from conary.local import database
from conary.versions import Label, VersionFromString

class DepTest(rephelp.RepositoryHelper):
    def getFlavor(self):
        if use.Arch.x86:
            return {'flavor': 'is: x86'}
        elif use.Arch.x86_64:
            return {'flavor': 'is: x86_64'}
        else:
            raise NotImplementedError, 'edit test for this arch'

    def testDependencies(self):
        self.resetRepository()
        self.resetRoot()
        (built, d) = self.buildRecipe(recipes.libhelloRecipe, "Libhello")
        version = built[0][1]
        # XXX need more keepExisting tests
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:user", version,
                                       tagScript = '/dev/null',
                                       keepExisting=True)
        assert(str == '1 additional trove is needed:\n'
                      '    libhello:runtime=0-1-1 is required by:\n'
                      '       libhello:user=0-1-1\n')

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:user", version,
                                       tagScript = '/dev/null')
        assert(str == "1 additional trove is needed:\n"
                      "    libhello:runtime=0-1-1 is required by:\n"
                      "       libhello:user=0-1-1\n")
        self.cfg.fullVersions = self.cfg.fullFlavors = True

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:user", version,
                                       tagScript = '/dev/null')

        self.assertEqual(str,
                 "1 additional trove is needed:\n"
                 "    libhello:runtime=/localhost@rpl:linux/0-1-1[%(is)s]"
                 " is required by:\n"
                 "       libhello:user=/localhost@rpl:linux/0-1-1[%(is)s]\n"
            % self.buildIs)
        self.cfg.fullVersions = self.cfg.fullFlavors = False
        self.cfg.showLabels = True
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:user", version,
                                       tagScript = '/dev/null')
        assert(str ==
                 "1 additional trove is needed:\n"
                 "    libhello:runtime=localhost@rpl:linux/0-1-1"
                 " is required by:\n"
                 "       libhello:user=localhost@rpl:linux/0-1-1\n")

        self.cfg.showLabels = False

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:runtime", version,
                                       tagScript = '/dev/null')
        assert(not str)
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:user", version,
                                       tagScript = '/dev/null')
        assert(not str)

        self.resetRoot()
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello", version,
                                       tagScript = '/dev/null')
        self.assertEquals(str, '')

        self.resetRoot()
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:user", version,
                                       tagScript = '/dev/null',
                                       resolve = True)
        assert(str == "Including extra troves to resolve dependencies:\n"
                      "    libhello:runtime=0-1-1\n")

        self.resetRoot()

        self.cfg.fullFlavors = self.cfg.fullVersions = True
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:user", version,
                                       tagScript = '/dev/null',
                                       resolve = True)
        assert(str == "Including extra troves to resolve dependencies:\n"
                      "    libhello:runtime=/localhost@rpl:linux/0-1-1[%(flavor)s]\n" %self.getFlavor())
        self.cfg.fullFlavors = self.cfg.fullVersions = False
        self.resetRoot()

        # add an extra bogus value at the front of the installLabelPath
        # this ensures that conary searches the whole installLabelPath
        oldPath = self.cfg.installLabelPath[:]
        self.cfg.installLabelPath.insert(0, Label('localhost@foo:bar'))

        # :script needs :user, which needs :runtime -- this makes sure
        # multilevel (well, 2 level) dependency resolution works
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:script", version,
                                       tagScript = '/dev/null',
                                       resolve = True)
        assert(str == "Including extra troves to resolve dependencies:\n"
                      "    libhello:runtime=0-1-1 libhello:user=0-1-1\n")

        self.cfg.installLabelPath = oldPath

        (rc, str) = self.captureOutput(self.erasePkg,
                                       self.rootDir,
                                       "libhello:user")
        self.assertEquals(str, """\
The following dependencies would not be met after this update:

  libhello:script=0-1-1 (Already installed) requires:
    file: /sbin/user
  which is provided by:
    libhello:user=0-1-1 (Would be erased)
""")

        self.cfg.showLabels = self.cfg.fullFlavors = True
        (rc, str) = self.captureOutput(self.erasePkg,
                                       self.rootDir,
                                       "libhello:user")
        assert(str == """\
The following dependencies would not be met after this update:

  libhello:script=localhost@rpl:linux/0-1-1[%(flavor)s] (Already installed) requires:
    file: /sbin/user
  which is provided by:
    libhello:user=localhost@rpl:linux/0-1-1[%(flavor)s] (Would be erased)
""" % self.getFlavor())
        self.cfg.showLabels = self.cfg.fullFlavors = False

        (rc, str) = self.captureOutput(self.erasePkg,
                                       self.rootDir,
                                       "libhello:user",
                                       depCheck = False)
        assert(not str)

        # test erase breaking a dependency w/ flags (since getting the flags
        # set has caused problems before)
        self.resetRoot()

        self.updatePkg(self.rootDir, "libhello:runtime", version,
                       tagScript = '/dev/null')
        self.updatePkg(self.rootDir, "libhello:user", version,
                       tagScript = '/dev/null')

        (rc, str) = self.captureOutput(self.erasePkg,
                                       self.rootDir,
                                       "libhello:runtime",
                                       depCheck = True)
        if use.Arch.x86:
            assert(str == """\
The following dependencies would not be met after this update:

  libhello:user=0-1-1 (Already installed) requires:
    soname: ELF32/libhello.so.0(SysV x86)
  which is provided by:
    libhello:runtime=0-1-1 (Would be erased)
""")
        elif use.Arch.x86_64:
            assert(str == """\
The following dependencies would not be met after this update:

  libhello:user=0-1-1 (Already installed) requires:
    soname: ELF64/libhello.so.0(SysV x86_64)
  which is provided by:
    libhello:runtime=0-1-1 (Would be erased)
""")
        else:
            raise NotImplementedError, 'modify test for this arch'

    def testUpdateTwoProvideSameDependencies(self):
        # CNY-2459 - moving from one trove providing foo:lib(1) to two
        # caused some mismatches in the dep resolution code
        self.addComponent('foo:lib[is:x86]', provides='trove:foo:lib')
        self.addComponent('foo:lib[is:x86_64]', provides='trove:foo:lib(1)',
                          filePrimer=1)
        self.addComponent('bar:lib', requires='trove:foo:lib(1)', filePrimer=2)
        self.updatePkg(['foo:lib[is:x86]', 'foo:lib[is:x86_64]', 'bar:lib'])
        self.addComponent('foo:lib=2[is:x86]', provides='trove:foo:lib(1)')
        self.addComponent('foo:lib=2[is:x86_64]', filePrimer=1,
                            provides='trove:foo:lib(1)')
        self.checkUpdate('foo:lib', ['foo:lib=1.0[is:x86_64]--2[is:x86_64]',
                                     'foo:lib=1.0[is:x86]--2[is:x86]'])

    def testNoVersionSonameDependencies(self):
        # just need to do one test to make sure the dependency shows up;
        # all the other functionality should be adequately tested in
        # testDependencies
        self.resetRepository()
        self.resetRoot()
        (built, d) = self.buildRecipe(recipes.libhelloRecipeNoVersion, "Libhello")
        version = built[0][1]
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "libhello:user", version,
                                       tagScript = '/dev/null',
                                       resolve = True)
        assert(str == "Including extra troves to resolve dependencies:\n"
                      "    libhello:runtime=0-1-1\n")

    def testFileDependency(self):
        self.resetRepository()
        self.resetRoot()

        (built, d) = self.buildRecipe(recipes.bashUserRecipe, "BashUser")
        version = built[0][1]

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "bashuser", version,
                                       tagScript = '/dev/null')
        assert(str == "The following dependencies could not be resolved:\n"
                      "    bashuser:runtime=0-1-1:\n"
                      "\tfile: /bin/bash\n")

        (built, d) = self.buildRecipe(recipes.bashRecipe, "Bash")
        version = built[0][1]

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "bashuser", tagScript = '/dev/null')
        assert(str == '1 additional trove is needed:\n'
                      '    bash:runtime=0-1-1 is required by:\n'
                      '       bashuser:runtime=0-1-1\n')

    def testTroveDependency(self):
        self.resetRepository()
        self.resetRoot()

        (built, d) = self.buildRecipe(recipes.bashTroveUserRecipe,
                                      "BashTroveUser")
        version = built[0][1]

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "bashtroveuser", version,
                                       tagScript = '/dev/null')
        assert(str == "The following dependencies could not be resolved:\n"
                      "    bashtroveuser:lib=0-1-1:\n"
                      "\ttrove: bash:runtime\n")

        (built, d) = self.buildRecipe(recipes.bashRecipe, "Bash")
        version = built[0][1]

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "bashtroveuser", tagScript = '/dev/null')
        assert(str == "1 additional trove is needed:\n"
                      "    bash:runtime=0-1-1 is required by:\n"
                      "       bashtroveuser:lib=0-1-1\n")

    def testUnresolvedDependencies(self):
        self.resetRepository()
        self.resetRoot()

        (built, d) = self.buildRecipe(recipes.testUnresolved, 'Unresolved')
        version = built[0][1]
        (rc, s) = self.captureOutput(self.updatePkg, self.rootDir,
                                       'testcase:runtime', version,
                                       tagScript = '/dev/null')
        s = s.split('\n')
        expected = ['The following dependencies could not be resolved:',
                    '    testcase:runtime=1.0-1-1:',
                    '\ttrove: bar:foo',
                    '']
        assert(s == expected)

    def testBreakOnUpdate(self):
        # create a package which provides a file, then update that package to
        # a version which does not provide that library while installing a
        # package which requires that file. it should cause a dep failure.
        self.resetRepository()
        self.resetRoot()

        (built, d) = self.buildRecipe(recipes.bashRecipe, "Bash")
        bashVersion = built[0][1]
        (built, d) = self.buildRecipe(recipes.bashMissingRecipe, "Bash")
        noBashVersion = built[0][1]

        (built, d) = self.buildRecipe(recipes.bashUserRecipe, "BashUser")
        userVersion = built[0][1]

        repos = self.openRepository()
        # this changeset updates bash to a trove which removed /bin/bash
        # and installs bashuser, which requies /bin/bash
        cs = repos.createChangeSet([("bash",
                                     (VersionFromString(bashVersion), deps.parseFlavor('ssl')),
                                     (VersionFromString(noBashVersion), deps.parseFlavor('ssl')),
                                    0),
                                    ("bashuser", (None, None),
                                     (VersionFromString(userVersion),
                                      deps.Flavor()),
                                    0)
                                  ])

        (fd, fileName) = tempfile.mkstemp()
        os.close(fd)
        cs.writeToFile(fileName)

        try:
            self.updatePkg(self.rootDir, 'bash', version = bashVersion)
            (rc, s) = self.captureOutput(self.updatePkg, self.rootDir, fileName)
        finally:
            os.unlink(fileName)
        expectedStr = """\
The following dependencies would not be met after this update:

  bashuser:runtime=0-1-1 (Would be newly installed) requires:
    file: /bin/bash
  which is provided by:
    bash:runtime=0-1-1 (Would be updated to 1-1-1)
"""
        self.assertEquals(s, expectedStr)

        # since /bin/bash is still installed, this should work fine
        self.updatePkg(self.rootDir, 'bashuser', version = bashVersion)

    def testNotBrokenOnUpdate(self):
        # create trove a and trove b, a file in trove b requires a:runtime
        # install both trove a and b.  build a new version of a.  update
        # to new version of a.
        self.resetRepository()
        self.resetRoot()

        (built, d) = self.buildRecipe(recipes.testTroveDepA, "A")
        aVersion = built[0][1]
        (built, d) = self.buildRecipe(recipes.testTroveDepB, "B")
        bVersion = built[0][1]

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "a", version=aVersion,
                                       tagScript = '/dev/null')
        assert(str == "")
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       "b", version=bVersion,
                                       tagScript = '/dev/null')
        assert(str == "")

        # build a new version of a to do an update
        (built, d) = self.buildRecipe(recipes.testTroveDepA, "A")
        aNewVersion = built[0][1]

        # since a:runtime is still provided, this should work fine
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       'a', version = aNewVersion)
        assert(str == "")

    def testNoSuggestionsSatisfyFlavor(self):
        # test that when none of the suggestion's flavors satisfy
        # the flavor, nothing is installed.
        self.resetRepository()
        self.resetRoot()

        # make sure that bash gets the ssl flavor
        self.overrideBuildFlavor('~ssl')
        (built, d) = self.buildRecipe(recipes.bashRecipe, 'Bash')
        (built, d) = self.buildRecipe(recipes.bashTroveUserRecipe,
                                      'BashTroveUser')
        userVersion = built[0][1]

        # require ssl to be off in all the flavors in self.cfg.flavor
        for flavor in self.cfg.flavor:
            flavor.union(deps.parseFlavor('use: !ssl'),
                          mergeType = deps.DEP_MERGE_TYPE_OVERRIDE)
        (rc, s) = self.captureOutput(self.updatePkg, self.rootDir,
                                       'bashtroveuser', userVersion,
                                       tagScript = '/dev/null',
                                       resolve = True)
        assert(s == 'The following dependencies could not be resolved:\n'
                    '    bashtroveuser:lib=0-1-1:\n'
                    '\ttrove: bash:runtime\n')

    # XXX test an update with --resolve where two troves are available
    # -- one that scores -1, one that scores False

    def testMultipleVersionsOfTroveNeeded(self):
        # this test builds two versions of foo:lib: 1.0-1-1, and
        # 2.0-1-1.  1.0-1-1 gets installed.  then we attempt to
        # install bar:runtime which requires foo:lib=1.0-1-1 and
        # baz:runtime which requires foo:lib=2.0-1-1.  the depsolver
        # should suggest foo:lib 2.0-1-1 to solve baz:runtime's dep.
        # but if you use --resolve, bar:runtime's dependency is broken.

        # IDEALY, the depsolver would tell you to install both versions
        # of foo:lib, but it has no idea if that will actually work, since
        # the files cannot overlap.

        self.resetRepository()
        self.resetRoot()

        (built, d) = self.buildRecipe(recipes.depsMultiVersionTest1, 'Foo')
        v1,f1 = built[0][1:3]
        (built, d) = self.buildRecipe(recipes.depsMultiVersionTest2, 'Foo')
        v2,f2 = built[0][1:3]

        (built, d) = self.buildRecipe(recipes.depsMultiVersionUser1, 'Bar')
        user1, flavor1 = built[0][1:3]

        (built, d) = self.buildRecipe(recipes.depsMultiVersionUser2, 'Baz')
        user2, flavor2 = built[0][1:3]

        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       'foo:lib', version=v1,
                                       tagScript = '/dev/null')
        assert(str == "")

        self.logFilter.add()
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       [ 'bar=%s' %user1, 'baz=%s' %user2 ],
                                       tagScript = '/dev/null')
        self.logFilter.clear()

        assert(str == "1 additional trove is needed:\n"
                      "    foo:lib=2.0-1-1 is required by:\n"
                      "       baz:runtime=1.0-1-1\n")

        # now attempt to resolve.  this will attempt to update foo:lib
        # to a version that does not have what bar:runtime needs
        self.logFilter.add()
        self.cfg.keepRequired = True
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       [ 'bar=%s' %user1, 'baz=%s' %user2 ],
                                       tagScript = '/dev/null',
                                       resolve = True)
        self.logFilter.clear()
        assert(str == 'Including extra troves to resolve dependencies:\n'
                      '    foo:lib=2.0-1-1\n')

    def testGroupDeps(self):
        self.addQuickTestComponent('test:runtime', '1.0-1-1')
        self.buildRecipe(recipes.dependencyGroup, 'DependencyGroup')
        (rc, str) = self.captureOutput(self.updatePkg, self.rootDir,
                                       'group-test')
        assert(str == 'The following dependencies could not be resolved:\n'
                      '    group-test=1.0-1-1:\n'
                      '\ttrove: other\n')

    def testCrossFlavorDeps(self):
        provideRec = recipes.bashRecipe + '        if Arch.x86:pass'
        userRec = recipes.bashUserRecipe + '        if Arch.x86:pass'

        # build provides (foo) as x86
        self.overrideBuildFlavor('is:x86')
        (built, d) = self.buildRecipe(provideRec, 'Bash')
        v1,f1 = built[0][1:3]

        # build requires (bar) as x86
        (built, d) = self.buildRecipe(userRec, 'BashUser')
        user1, flavor1 = built[0][1:3]

        # set flavor to be x86_64
        x86Flavor = deps.overrideFlavor(self.cfg.flavor[0],
                                        deps.parseFlavor('is:x86'))
        x86_64Flavor = deps.overrideFlavor(self.cfg.flavor[0],
                                           deps.parseFlavor('is:x86_64'))
        self.cfg.flavor = [x86_64Flavor]

        # install w/ x86 flavor request
        rc, str = self.captureOutput(self.updatePkg,
                            self.rootDir, 'bashuser:runtime', user1,
                           tagScript = '/dev/null',
                           resolve = True,
                           flavor='is:x86')
        # XXX ideally, the x86 flavor of the trove we are installing should
        # override the install flavor path here, and find the right trove
        assert(str == 'The following dependencies could not be resolved:\n'
                      '    bashuser:runtime=0-1-1:\n'
                      '\tfile: /bin/bash\n')

        # flavorPath is now x86_64, x86
        self.cfg.flavor =  [ x86_64Flavor, x86Flavor ]
        rc, str = self.captureOutput(self.updatePkg,
                           self.rootDir, 'bashuser:runtime', user1,
                           tagScript = '/dev/null',
                           resolve = True,
                           justDatabase = True,
                           flavor='')
        assert(str == 'Including extra troves to resolve dependencies:\n'
                      '    bash:runtime=0-1-1\n')
        # these erases spew output because of the justDatabase flags used
        # during the install. squelch.
        self.captureOutput(self.erasePkg, self.rootDir, 'bashuser:runtime',
                           justDatabase=True)
        self.captureOutput(self.erasePkg, self.rootDir, 'bash:runtime',
                           justDatabase=True)
        self.cfg.buildFlavor = x86_64Flavor

        (built, d) = self.buildRecipe(provideRec, 'Bash')
        v1,f2 = built[0][1:3]
        rc, str = self.captureOutput(self.updatePkg,
                           self.rootDir, 'bashuser:runtime', user1,
                           tagScript = '/dev/null',
                           resolve = True,
                           justDatabase = True,
                           flavor='')
        assert(str == 'Including extra troves to resolve dependencies:\n'
                      '    bash:runtime=0-1-1\n')
        db = database.Database(self.rootDir, self.cfg.dbPath)
        # make sure that we installed the x86_64 one -- the first one that
        # matches on our flavor path
        bashTroves = db.findTrove(None, ('bash:runtime', None, None))
        assert(len(bashTroves) == 1)
        assert(bashTroves[0][2].freeze() == '1#x86_64|5#use:ssl')

    def testGetTrovesWithProvides(self):
        v = '/localhost@rpl:linux/1.0-1-1'
        f = ''
        db = database.Database(self.rootDir, self.cfg.dbPath)
        prov1 = deps.parseDep('trove: test1:runtime')
        prov2 = deps.parseDep('trove: test2:runtime')
        self.addQuickDbTestPkg(db, 'test1', v,f, provides=prov1)
        self.addQuickDbTestPkg(db, 'test2', v,f, provides=prov2)
        self.addQuickDbTestPkg(db, 'test1-foo', v,f, provides=prov1)
        provMap = db.getTrovesWithProvides([prov1, prov2])
        assert(sorted(x[0] for x in provMap[prov1]) == ['test1','test1-foo'])
        assert([x[0] for x in provMap[prov2]] == ['test2'])

    def testResolveUsingLatest(self):
        myDep = deps.parseDep('trove: test:runtime')
        self.addQuickTestComponent('prov:runtime', '1.0-1-1', '!builddocs',
                                   provides=myDep)
        self.addQuickTestComponent('prov:runtime', '2.0-1-1', '~!builddocs',
                                   provides=myDep)
        self.addQuickTestComponent('req:runtime', '2.0-1-1', '~!builddocs',
                                   requires=myDep)
        oldFlavor = self.cfg.flavor
        try:
            self.cfg.flavor = [ deps.parseFlavor('!builddocs') ]
            rc, msg = self.captureOutput(self.updatePkg,
                                         self.cfg.root, 'req:runtime')
            assert(msg == "1 additional trove is needed:\n"
                          "    prov:runtime=2.0-1-1 is required by:\n"
                          "       req:runtime=2.0-1-1\n")
        finally:
            self.cfg.flavor = oldFlavor

    def testMultDepsResolvedByOneTrove(self):
        # test multiple dependencies resolved by the same trove - make sure
        # there's no duplicate information given
        myDep = deps.parseDep('trove: test:runtime trove: test:foo')
        self.addQuickTestComponent('prov:runtime', '2.0-1-1', '~!builddocs',
                                   provides=myDep)
        self.addQuickTestComponent('req:runtime', '2.0-1-1', '~!builddocs',
                                   requires=myDep)
        rc, msg = self.captureOutput(self.updatePkg,
                                         self.cfg.root, 'req:runtime')
        assert(msg == "1 additional trove is needed:\n"
                      "    prov:runtime=2.0-1-1 is required by:\n"
                      "       req:runtime=2.0-1-1\n")

    def testUpdateWithCapabilityDeps(self):
        myDep = deps.parseDep('trove: test:python(1.0)')

        self.addComponent('test:python', '1.0-1-1', provides=myDep,
                          filePrimer=1)
        self.addComponent('test:runtime', '1.0-1-1', requires=myDep,
                          filePrimer=2)
        self.addCollection('test', '1.0-1-1', ['test:python', 'test:runtime'])
        self.updatePkg(self.rootDir, 'test')

        self.addComponent('test:python', '1.0-2-1', provides=myDep,
                          filePrimer=1)
        self.addComponent('test:runtime', '1.0-2-1', requires=myDep,
                          filePrimer=2)
        self.addCollection('test', '1.0-2-1', ['test:python', 'test:runtime'])

        self.updatePkg(self.rootDir, 'test')

    def testGroupResolution(self):
        self.addComponent('test:runtime', '1.0')
        self.addComponent('test:runtime', '2.0')
        trv = self.addCollection('group-dist', '1.0', ['test:runtime'])

        self.addComponent('foo:runtime', '1.0', requires='trove: test:runtime')

        self.checkUpdate('foo:runtime', ['test:runtime=2.0',
                                         'foo:runtime=1.0'], resolve=True)

        self.checkUpdate('foo:runtime', ['test:runtime=1.0',
                                         'foo:runtime=1.0'], resolve=True,
                         resolveGroupList=[('group-dist', None, None)])

    def testGroupResolutionFails(self):
        self.addComponent('test:runtime', '1.0',
                          provides='trove:test:runtime(1.0)')
        self.addCollection('test', '1.0', [':runtime'])
        self.addComponent('test:runtime', '2.0',
                          provides='trove:test:runtime(2.0)')
        self.addCollection('test', '2.0', [':runtime'])
        trv = self.addCollection('group-dist', '1.0', ['test'])

        self.addComponent('foo:runtime', '1.0',
                          requires='trove: test:runtime(2.0)')

        self.checkUpdate('foo:runtime', ['test:runtime=2.0',
                                         'test=2.0',
                                         'foo:runtime=1.0'], resolve=True)

        try:
            self.checkUpdate('foo:runtime', ['test:runtime=2.0',
                                             'test=2.0',
                                             'foo:runtime=1.0'], resolve=True,
                             resolveGroupList=[('group-dist', None, None)])
        except Exception, err:
            pass
        else:
            assert 0, 'This test should fail because test 2.0 is not in the group'

    def testDepResolutionResultFormat(self):
        # test result formats in case dep resolution fails
        repos = self.openRepository()
        test1r = self.addComponent('test:runtime', '1.0')
        test1 = self.addCollection('test', '1.0', [':runtime'])
        test2r = self.addComponent('test:runtime', '2.0')
        test2 = self.addCollection('test', '2.0', [':runtime'])
        grp1 = self.addCollection('group-dist', '1.0', [('test', '1.0')])
        grp2 = self.addCollection('group-dist', '2.0', [('test', '2.0')])

        # test a match
        dep = deps.parseDep('trove:test:runtime')
        sugg = repos.resolveDependenciesByGroups([grp1], [ dep ])
        self.assertEqual(sugg[dep], [[test1r.getNameVersionFlavor()]])
        sugg = repos.resolveDependenciesByGroups([grp2], [ dep ])
        self.assertEqual(sugg[dep], [[test2r.getNameVersionFlavor()]])

        # test misses
        dep = deps.parseDep('trove:foo:runtime')
        sugg = repos.resolveDependenciesByGroups([grp1], [ dep ])
        self.assertEqual(sugg[dep], [ [] ])
        dep = deps.parseDep('trove:foo:runtime trove:bar:runtime')
        sugg = repos.resolveDependenciesByGroups([grp1], [ dep ])
        self.assertEqual(sugg[dep], [ [], [] ])

        # test hits and misses
        dep = deps.parseDep('trove:foo:runtime trove:test:runtime')
        sugg = repos.resolveDependenciesByGroups([grp1], [ dep ])
        self.assertEqual(sugg[dep], [ [], [test1r.getNameVersionFlavor()] ])
        dep = deps.parseDep('trove:foo:runtime trove:test:runtime trove:bar:runtime')
        sugg = repos.resolveDependenciesByGroups([grp2], [ dep ])
        self.assertEqual(sugg[dep], [ [], [], [test2r.getNameVersionFlavor()] ])

        # test a more complex case
        dep1 = deps.parseDep('trove:test:runtime')
        dep2 = deps.parseDep('trove:foo:runtime')
        dep3 = deps.parseDep('trove:foo:runtime trove:test:runtime')
        sugg = repos.resolveDependenciesByGroups([grp1, grp2], [ dep1, dep2, dep3 ])
        # tehse should return the latest deps from grp2
        self.assertEqual(sugg[dep1], [[test2r.getNameVersionFlavor()]])
        self.assertEqual(sugg[dep2], [ [] ])
        self.assertEqual(sugg[dep3], [ [], [test2r.getNameVersionFlavor()] ])
    def testDepResolutionResultFormat2(self):
        #CNY-2254
        self.addComponent('foo:python', '1', provides='python: foo(2.4)')
        self.addComponent('conary-policy:lib', '1')
        repos = self.openRepository()
        depSet = deps.parseDep('trove: conary-policy:lib python: foo')
        results = repos.resolveDependencies(self.cfg.buildLabel, [depSet])
        for idx, (depClass, dep) in enumerate(depSet.iterDeps(sort=True)):
            sol, = results[depSet][idx]
            solName = sol[0]
            if dep.name == 'conary-policy:lib':
                self.assertEquals(solName, 'conary-policy:lib')
            else:
                self.assertEquals(solName, 'foo:python')

    def testGroupResolutionAcrossRepos(self):
        self.openRepository()
        repos = self.openRepository(1)
        self.addComponent('test:runtime', '1.0', '!ssl')
        self.addComponent('test:runtime', '2.0', '!ssl')
        self.addComponent('test:runtime', '/localhost1@rpl:foobar/1.0', 'ssl')
        self.addComponent('test:runtime', '/localhost1@rpl:foobar/2.0', 'ssl')

        trv = self.addCollection('group-dist', '1.0',
                    [('test:runtime', '1.0', '!ssl'),
                     ('test:runtime', '/localhost1@rpl:foobar/1.0', 'ssl')])

        sugg = repos.resolveDependenciesByGroups([trv],
                                      [deps.parseDep('trove:test:runtime')])
        troves = sugg[deps.parseDep('trove:test:runtime')][0]
        troveVers = set((x[1].getHost(), x[1].trailingRevision().getVersion())
                        for x in troves)
        assert(troveVers == set([('localhost', '1.0'), ('localhost1', '1.0')]))
        # this doesn't match anything.  Make sure there's a spot in the suggestion list.
        sugg = repos.resolveDependenciesByGroups([trv],
                                      [deps.parseDep('trove:foo:runtime trove:bar:runtime')])
        resultList,  = sugg.values()
        self.assertEqual(resultList, [[], []])

    def testResolveAgainstTipFirst(self):
        self.addComponent('foo:run', '1', filePrimer=0,
                            requires='trove:bar:run(1.0)')
        self.addComponent('bar:run', '1-1-1', provides='trove:bar:run(1.0)',
                          filePrimer=1)
        self.addComponent('bar:run', '1-1-2', provides='trove:bar:run',
                          filePrimer=1)
        branchBar = self.addComponent('bar:run', ':branch/1',
                                      provides='trove:bar:run(1.0)',
                                      filePrimer=1)
        self.cfg.installLabelPath.append(Label('localhost@rpl:branch'))
        self.checkUpdate('foo:run', ['foo:run', 'bar:run=:branch'],
                         resolve=True)
        # make the thing on :branch that provides the dep not be on tip either
        branchBar = self.addComponent('bar:run', ':branch/1-1-2',
                                      filePrimer=1)
        self.checkUpdate('foo:run', ['foo:run', 'bar:run=:linux'],
                         resolve=True)
        # now check when they're both on tip
        self.addComponent('bar:run', '1-1-3', provides='trove:bar:run(1.0)',
                          filePrimer=1)
        branchBar = self.addComponent('bar:run', ':branch/3',
                                      provides='trove:bar:run(1.0)',
                                      filePrimer=1)
        self.checkUpdate('foo:run', ['foo:run', 'bar:run=:linux'],
                         resolve=True)

    @context('resolvelog')
    def testResolutionLogging(self):
        myDep= ('soname: ELF32/a.so(x86)'
                ' soname: ELF32/b.so(x86)'
                ' soname: ELF32/c.so(x86)'
                ' soname: ELF32/d.so(x86)'
                ' soname: ELF32/e.so(x86)'
                ' soname: ELF32/f.so(x86)')
        log.setVerbosity(log.DEBUG)
        self.addComponent('prov:runtime', '1.0', provides=myDep, filePrimer=1)
        self.addComponent('req:runtime', '1.0', requires=myDep, filePrimer=2)

        self.logFilter.add()
        self.checkUpdate(['req:runtime'], ['req:runtime', 'prov:runtime'],
                         resolve=True)
        self.logFilter.remove()
        self.logFilter.compare('''\
+ Resolved:
    req:runtime=localhost@rpl:linux/1.0-1-1[]
    Required:  soname: ELF32/a.so(x86)
               soname: ELF32/b.so(x86)
               soname: ELF32/c.so(x86)
               soname: ELF32/d.so(x86)
               soname: ELF32/e.so(x86)
               ...
    Adding: prov:runtime=localhost@rpl:linux/1.0-1-1[]''')

    @context('resolvelog')
    def testResolutionKeepExistingLogging(self):
        self.addComponent('keepprov:runtime', '1.0',
                           provides='trove:keepreq(1.0)',
                          filePrimer=3)
        self.addComponent('keepprov:runtime', '2.0',
                          provides='trove:keepreq(2.0)',
                          filePrimer=4)
        self.addComponent('keepreq1:runtime', '1.0',
                          requires='trove:keepreq(1.0)',
                          filePrimer=5)
        self.addComponent('keepreq2:runtime', '1.0',
                          requires='trove:keepreq(2.0)',
                          filePrimer=6)
        self.updatePkg(['keepprov:runtime=1.0', 'keepreq1:runtime'])
        log.setVerbosity(log.DEBUG)
        self.logFilter.add()
        self.checkUpdate('keepreq2:runtime',
                         ['keepreq2:runtime', 'keepprov:runtime=--2.0'],
                        resolve=True, keepRequired=True)

        self.logFilter.compare([
'''+ Resolved:
    keepreq2:runtime=localhost@rpl:linux/1.0-1-1[]
    Required:  trove: keepreq(2.0)
    Adding: keepprov:runtime=localhost@rpl:linux/2.0-1-1[]''',
'''+ Update breaks dependencies!''',
'''+ Broken dependency: (dep needed by the system but being removed):
   keepreq1:runtime=1.0-1-1
   Requires:
     trove: keepreq(1.0)
   Provided by removed or updated packages: keepprov:runtime''',
'''+ Attempting to update the following packages in order to remove their dependency on something being erased:
   keepreq1''',
'''+ Resolved (installing side-by-side)
    keepreq1:runtime=1.0-1-1[]    Required: trove: keepreq(1.0)    Keeping: keepprov:runtime=1.0-1-1[]''',
'warning: keeping keepprov:runtime - required by at least keepreq1:runtime'])

    @context('resolvelog')
    def testResolutionKeepExistingLogging2(self):
        self.addComponent('keepprov:lib', '1.0',
                           provides='trove:keepreq(1.0)',
                          filePrimer=3)
        self.addCollection('keepprov', '1.0', [':lib'])

        self.addComponent('keepprov:data', '2.0', filePrimer=4)
        # they conflict!
        self.addCollection('keepprov', '2.0', [':data'])
        self.addComponent('keepreq:runtime', '1.0',
                          requires='trove:keepreq(1.0)',
                          filePrimer=5)
        self.updatePkg(['keepprov=1.0', 'keepreq:runtime'])
        log.setVerbosity(log.DEBUG)
        self.logFilter.add()
        self.checkUpdate('keepprov', ['keepprov=--2.0',
                                      'keepprov:data=--2.0'], keepRequired=True)
        self.logFilter.compare([
'''+ Update breaks dependencies!''',
'''+ Broken dependency: (dep needed by the system but being removed):
   keepreq:runtime=1.0-1-1
   Requires:
     trove: keepreq(1.0)
   Provided by removed or updated packages: keepprov:lib''',
'''+ Resolved (undoing erasure)
    keepreq:runtime=1.0-1-1[]    Required: trove: keepreq(1.0)    Keeping: keepprov:lib=1.0-1-1[]''',
'''warning: keeping keepprov:lib - required by at least keepreq:runtime'''
])

    @context('resolvelog')
    def testResolutionUpdateExistingLogging(self):
        self.addComponent('foo:runtime', '1.0',
                          provides='trove:foo(1.0)',
                          filePrimer=7)
        self.addComponent('foo-build:runtime', '1.0',
                          requires='trove:foo(1.0)',
                          filePrimer=8)
        self.addComponent('foo:runtime', '2.0',
                        provides='trove:foo(2.0)',
                        filePrimer=9)
        self.addComponent('foo-build:runtime', '2.0',
                          requires='trove:foo(2.0)',
                          filePrimer=10)
        self.addCollection('foo-build', '2.0', [':runtime'])
        self.updatePkg(['foo:runtime=1.0', 'foo-build:runtime=1.0'])
        log.setVerbosity(log.DEBUG)
        self.logFilter.add()
        self.checkUpdate('foo:runtime',
                         ['foo:runtime=1.0--2.0', 'foo-build=2.0',
                          'foo-build:runtime=1.0--2.0'])
        self.logFilter.compare([
'''+ Update breaks dependencies!''',
'''+ Broken dependency: (dep needed by the system but being removed):
   foo-build:runtime=1.0-1-1
   Requires:
     trove: foo(1.0)
   Provided by removed or updated packages: foo:runtime''',
'''+ Attempting to update the following packages in order to remove their dependency on something being erased:
   foo-build''',
'''+ updated 2 troves:
   foo-build:runtime=localhost@rpl:linux/2.0-1-1[]
   foo-build=localhost@rpl:linux/2.0-1-1[]'''])

    def testKeepRequiredWithOverlappingFiles(self):
        # Test that keepRequired will function when an old trove overlaps with
        # a new trove providing that the old trove had the overlapping files
        # removed previously.
        prov1 = deps.parseDep('file: /lib/libfoo.so.1')
        prov2 = deps.parseDep('file: /lib/libfoo.so.2')
        self.addComponent('foo:lib=1.0', provides = prov1,
                          fileContents = [ ('/lib/libfoo.so.1', '1'),
                                           ('/etc/conflict', 'contents') ] )
        self.addComponent('foo:lib=2.0', provides = prov2,
                          fileContents = [ ('/lib/libfoo.so.2', '2'),
                                           ('/etc/conflict', 'contents') ] )
        self.addComponent('bar:runtime=1.0', requires = prov1,
                          fileContents = [ ('/bin/bar1', '1') ] )
        self.addComponent('bar:runtime=2.0', requires = prov2,
                          fileContents = [ ('/bin/bar2', '2') ] )

        self.updatePkg([ 'foo:lib=1.0', 'bar:runtime=1.0'])

        (rc, str) = self.captureOutput(self.updatePkg, 'bar:runtime=2.0',
                                       resolve = True, keepExisting = True,
                                       keepRequired = True)
        expectedStr = """\
The following dependencies would not be met after this update:

  bar:runtime=1.0-1-1 (Already installed) requires:
    file: /lib/libfoo.so.1
  which is provided by:
    foo:lib=1.0-1-1 (Would be updated to 2.0-1-1)
"""
        assert(str == expectedStr)

        self.removeFile(self.rootDir, '/etc/conflict')

        (rc, str) = self.captureOutput(self.updatePkg, 'bar:runtime=2.0',
                                       resolve = True, keepExisting = True,
                                       keepRequired = True)
        assert(str ==
            'Including extra troves to resolve dependencies:\n'
            '    foo:lib=2.0-1-1\n'
            'warning: keeping foo:lib - required by at least bar:runtime\n')


text:
module Aperture

  # = Overview
  # The PhotoSet object that contains a series of Photo objects in a hash. This object is used
  # by the Library, Album and Project objects cotain photos. This object also contains methods
  # to look up interest statistics across the set.
  #
  # = Statistic gathering methods
  # * photo_count - number of photos in set
  # * version_count - number of versions across all photos in set
  # * camera_model_count_hash - count of how many times each camera used in the set
  # * lens_model_count_hash - count of how many times each lens used in the set
  #
  # *Note* This object can be directly treated like an array using each or any method from
  # the Enumerable module. These will access the the values, the Photo objects, contained
  # within the hash.
  class PhotoSet
    include Enumerable
    attr_accessor :photos

    # Creates a new PhotoSet, can be passed an array of Photo objects
    def initialize(photos = {})
      @photos = photos
    end

    # Adds a Photo to the hash PhotoSet uses to track Photo's using the photo's UUID. This UUID
    # matches up to the masterUuid found in Version#attributes
    def <<(photo)
      @photos[ photo.master_attributes['uuid'] ] = photo
    end

    # Iterates over the hash's values, ie the photos, the PhotoSet is tracking
    def each &blk
      @photos.values.each &blk
    end

    # This method passes any unknown method calls onto the hash of photos, allowing you to
    # treat the PhotoSet object as the Hash of photos it holds.
    def method_missing(sym, *args, &block)
      @photos.send(sym, *args, &block) if @photos.respond_to?(sym)
    end

    # Returns the number of photos tracked by the PhotoSet
    def photo_count
      return size
    end

    # Returns the number of versions across all the photos tracked by the PhotoSet
    def version_count
      return inject(0) {|sum, photo| sum += photo.versions.size}
    end

    # Returns a hash in the following format
    # * The keys are the camera model for the photo parsed from the EXIF information
    # * The value is the number of times that camera model shows up across all the photos in
    #   the set
    def camera_model_count_hash
      hash = Hash.new(0)
      self.each do |photo|
        model = photo.version(1).attributes['exifProperties']['Model']
        hash[model] += 1
      end

      return hash
    end

    # Returns a hash in the following format
    # * The keys are the lens model for the photo parsed from the EXIF information
    # * The value is the number of times that lens model shows up across all the photos in
    #   the set
    def lens_model_count_hash
      hash = Hash.new(0)
      self.each do |photo|
        model = photo.version(1).attributes['exifProperties']['LensModel']
        hash[model] += 1
      end

      return hash
    end

    # Returns a new PhotoSet where the photos match the passed keyword
    def find_by_keyword(keyword)
      versions = map {|p| p.versions }.flatten
      matching = versions.select {|v| v.attributes['keywords'] && v.attributes['keywords'].include?(keyword) }
      return PhotoSet.new(matching.map{|v| v.photo}.uniq)
    end

    # def find_photos_by_rating

  end
end