text:
//_objective.c

#include <Python.h>
#include <numpy/arrayobject.h>
#include "objective.h"

static char module_docstring[] = "This module provides an interface for calculating objectives using C.";
static char obj_func_lin_reg_docstring[] = "Calculate objective function for linear regression.";
static char obj_func_ar_ls_docstring[] = "Calculate objective function (ls) for auto-regressive.";
static char obj_func_ar_cml_docstring[] = "Calculate objective function (cml) for auto-regressive.";

static PyObject *objective_obj_func_lin_reg(PyObject *self, PyObject *args);
static PyObject *objective_obj_func_ar_ls(PyObject *self, PyObject *args);
static PyObject *objective_obj_func_ar_cml(PyObject *self, PyObject *args);

static PyMethodDef module_methods[] = {
    {"obj_func_lin_reg", objective_obj_func_lin_reg, METH_VARARGS, obj_func_lin_reg_docstring},
    {"obj_func_ar_ls", objective_obj_func_ar_ls, METH_VARARGS, obj_func_ar_ls_docstring},
    {"obj_func_ar_cml", objective_obj_func_ar_cml, METH_VARARGS, obj_func_ar_cml_docstring},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC PyInit__objective(void)
{
    PyObject *module;
    static struct PyModuleDef moduledef = {
        PyModuleDef_HEAD_INIT,
        "_objective",
        module_docstring,
        -1,
        module_methods,
        NULL,
        NULL,
        NULL,
        NULL
    };
    module = PyModule_Create(&moduledef);
    if (!module) return NULL;

    /* Load `numpy` functionality. */
    import_array();

    return module;
}

static PyObject *objective_obj_func_lin_reg(PyObject *self, PyObject *args)
{
    int i, n_coef, dim2;
    PyObject *p_obj, *xx_obj, *yy_obj;

    /* Parse the input tuple */
    if (!PyArg_ParseTuple(args, "OOOii", &p_obj, &xx_obj, &yy_obj, &n_coef, &dim2))
        return NULL;

    /* Interpret the input objects as numpy arrays. */
    PyObject *p_array = PyArray_FROM_OTF(p_obj, NPY_DOUBLE, NPY_IN_ARRAY);
    PyObject *xx_array = PyArray_FROM_OTF(xx_obj, NPY_DOUBLE, NPY_IN_ARRAY);
    PyObject *yy_array = PyArray_FROM_OTF(yy_obj, NPY_DOUBLE, NPY_IN_ARRAY);

    /* If that didn't work, throw an exception. */
    if (p_array == NULL || xx_array == NULL || yy_array == NULL ) {
        Py_XDECREF(p_array);
        Py_XDECREF(xx_array);
        Py_XDECREF(yy_array);
        return NULL;
    }

    /* How many data points are there? */
    int np = (int)PyArray_DIM(p_array, 0);
    int nx = (int)PyArray_DIM(xx_array, 0);
    int ny = (int)PyArray_DIM(yy_array, 0);
    int ng = n_coef*dim2;

    /* Get pointers to the data as C-types. */
    double *p = (double*)PyArray_DATA(p_array);
    double *xx = (double*)PyArray_DATA(xx_array);
    double *yy = (double*)PyArray_DATA(yy_array);
    double *g;

    g=(double*)malloc(ng*sizeof(double));

    /* Call the external C function to compute the chi-squared. */
    double error = obj_func_lin_reg(p, np, xx, nx, yy, ny, n_coef, dim2, g, ng);

    /* Clean up. */
    Py_DECREF(p_array);
    Py_DECREF(xx_array);
    Py_DECREF(yy_array);

    /* Build the output tuple */

    PyObject *grad = PyList_New(ng);
    for(i=0;i<ng;i++) PyList_SET_ITEM(grad, i, Py_BuildValue("d", g[i]));

    PyObject *ret = PyTuple_New(2);
    PyTuple_SET_ITEM(ret, 0, Py_BuildValue("d", error));
    PyTuple_SET_ITEM(ret, 1, Py_BuildValue("O", grad));
    //PyObject *ret = Py_BuildValue("d", error);
    free(g);
    return ret;
}

static PyObject *objective_obj_func_ar_ls(PyObject *self, PyObject *args)
{
    int i, n_coef, dim2, intercept;
    PyObject *p_obj, *ofns_obj;

    /* Parse the input tuple */
    if (!PyArg_ParseTuple(args, "OOiii", &p_obj, &ofns_obj, &n_coef, &dim2, &intercept))
        return NULL;

    /* Interpret the input objects as numpy arrays. */
    PyObject *p_array = PyArray_FROM_OTF(p_obj, NPY_DOUBLE, NPY_IN_ARRAY);
    PyObject *ofns_array = PyArray_FROM_OTF(ofns_obj, NPY_DOUBLE, NPY_IN_ARRAY);

    /* If that didn't work, throw an exception. */
    if (p_array == NULL || ofns_array == NULL ) {
        Py_XDECREF(p_array);
        Py_XDECREF(ofns_array);
        return NULL;
    }

    /* How many data points are there? */
    int np = (int)PyArray_DIM(p_array, 0);
    int nc = (int)PyArray_DIM(ofns_array, 0);
    int ng = n_coef*dim2;

    /* Get pointers to the data as C-types. */
    double *p = (double*)PyArray_DATA(p_array);
    double *ofns = (double*)PyArray_DATA(ofns_array);
    double *g;

    g=(double*)malloc(ng*sizeof(double));

    /* Call the external C function to compute the chi-squared. */
    double error = obj_func_ar_ls(p, np, ofns, nc, n_coef, dim2, intercept, g, ng);

    /* Clean up. */
    Py_DECREF(p_array);
    Py_DECREF(ofns_array);

    /* Build the output tuple */
    PyObject *grad = PyList_New(ng);
    for(i=0;i<ng;i++) PyList_SET_ITEM(grad, i, Py_BuildValue("d", g[i]));

    PyObject *ret = PyTuple_New(2);
    PyTuple_SET_ITEM(ret, 0, Py_BuildValue("d", error));
    PyTuple_SET_ITEM(ret, 1, Py_BuildValue("O", grad));
    //PyObject *ret = Py_BuildValue("d", error);
    free(g);
    return ret;
}

static PyObject *objective_obj_func_ar_cml(PyObject *self, PyObject *args)
{
    int i, n_coef, dim2, intercept;
    PyObject *p_obj, *ofns_obj;

    /* Parse the input tuple */
    if (!PyArg_ParseTuple(args, "OOiii", &p_obj, &ofns_obj, &n_coef, &dim2, &intercept))
        return NULL;

    /* Interpret the input objects as numpy arrays. */
    PyObject *p_array = PyArray_FROM_OTF(p_obj, NPY_DOUBLE, NPY_IN_ARRAY);
    PyObject *ofns_array = PyArray_FROM_OTF(ofns_obj, NPY_DOUBLE, NPY_IN_ARRAY);

    /* If that didn't work, throw an exception. */
    if (p_array == NULL || ofns_array == NULL ) {
        Py_XDECREF(p_array);
        Py_XDECREF(ofns_array);
        return NULL;
    }

    /* How many data points are there? */
    int np = (int)PyArray_DIM(p_array, 0);
    int nc = (int)PyArray_DIM(ofns_array, 0);
    int ng = (n_coef+1)*dim2;

    /* Get pointers to the data as C-types. */
    double *p = (double*)PyArray_DATA(p_array);
    double *ofns = (double*)PyArray_DATA(ofns_array);
    double *g;

    g=(double*)malloc(ng*sizeof(double));

    /* Call the external C function to compute the chi-squared. */
    double error = obj_func_ar_cml(p, np, ofns, nc, n_coef, dim2, intercept, g, ng);

    /* Clean up. */
    Py_DECREF(p_array);
    Py_DECREF(ofns_array);

    /* Build the output tuple */
    PyObject *grad = PyList_New(ng);
    for(i=0;i<ng;i++) PyList_SET_ITEM(grad, i, Py_BuildValue("d", g[i]));

    PyObject *ret = PyTuple_New(2);
    PyTuple_SET_ITEM(ret, 0, Py_BuildValue("d", error));
    PyTuple_SET_ITEM(ret, 1, Py_BuildValue("O", grad));
    //PyObject *ret = Py_BuildValue("d", error);
    free(g);
    return ret;
}


text:
class OpCodeInjectedFaultParams;

class OpCodeInjectedFault : public O3CPUInjectedFault
{

public:

  typedef OpCodeInjectedFaultParams Params;

  const Params *params() const
  {
    return reinterpret_cast<const Params *>(_params);
  }

  OpCodeInjectedFault(Params *params);
  OpCodeInjectedFault(OpCodeInjectedFault &source);
	OpCodeInjectedFault(Params *p, std::ifstream &os);
  ~OpCodeInjectedFault();

  const std::string name() const;
  virtual const char *description() const;

  void dump() const;

  virtual void init();
  virtual void startup();

  TheISA::MachInst process(TheISA::MachInst inst);
  OpCodeInjectedFault* copyme(InjectedFaultQueue& myq){
    DPRINTF(FaultInjection,"copy me OpCodeInjectedFault\n");
    return (new OpCodeInjectedFault(*this) ); }

  void check4reschedule();

	virtual void store(std::ofstream &os);

};

#endif // __OPCODE_INJECTED_FAULT_HH__

redpajama_set_name: RedPajamaGithub


text:
#include "glm/gtc/matrix_transform.hpp"

#include <Common/Extern.h>
#include <Common/Utility.h>

#include <Patronus/PhysicalWorld.h>
#include <Patronus/Camera.h>

#include <Lumos/Instance.h>
#include <Lumos/Program.h>

using namespace Daylight::Lumos;

Instance::Instance( Daylight::Patronus::Mesh * meshPtr, const ModelAsset & asset)
    :_meshPtr(meshPtr)
    , _asset(asset)
    , _rigidBody( nullptr )
    , _pickingColor(0.0f, 0.0f, 0.0f)
{

}

//Instance::~Instance(){
//    //if (_rigidBody) delete _rigidBody;
//}

void Instance::setRidgidBody( Daylight::Patronus::PhysicalWorld * world, btRigidBody * const &  arg )
{
    if(_rigidBody){
        world->getWorld()->removeRigidBody(_rigidBody);
        delete _rigidBody->getMotionState();
        delete _rigidBody;
    }
    arg->setUserPointer(this);
    _rigidBody = arg;
}

void Instance::loadAttribsAndUniform() const {

    GLuint attribId;
    if (gProgram->hasAttribute("vert")){
        attribId = gProgram->getAttrib("vert");
        glBindBuffer(GL_ARRAY_BUFFER, _asset.VBO_VERT);

        Utils::logOpenGLError();
        glEnableVertexAttribArray(attribId);
        Utils::logOpenGLError();
        glVertexAttribPointer(attribId, 3, GL_FLOAT, GL_FALSE, 0, 0);
        Utils::logOpenGLError();
    }
    if (gProgram->hasAttribute("vertNormal")){
        attribId = gProgram->getAttrib("vertNormal");
        glBindBuffer(GL_ARRAY_BUFFER, _asset.VBO_NORMAL);
        glEnableVertexAttribArray(attribId);
        glVertexAttribPointer(attribId, 3, GL_FLOAT, GL_FALSE, 0, 0);
        Utils::logOpenGLError();
    }
    if (gProgram->hasAttribute("vertTexCoord")){
        attribId = gProgram->getAttrib("vertTexCoord");
        glBindBuffer(GL_ARRAY_BUFFER, _asset.VBO_TEXCOORD);
        glEnableVertexAttribArray(attribId);
        glVertexAttribPointer(attribId, 2, GL_FLOAT, GL_FALSE, 0, 0);
        Utils::logOpenGLError();
    }

    // load uniform
    if( gProgram->hasUniform("inverseModel") )
        gProgram->setUniform( "inverseModel" , getInverseModelMatrix() );
    Utils::logOpenGLError();

    if( gProgram->hasUniform("model") )
        gProgram->setUniform("model", getModelMatrix() );

    if( gProgram->hasUniform("pickingColor") )
        gProgram->setUniform("pickingColor", getPickingColor() );

    Utils::logOpenGLError();
}

void Instance::renderMesh( Material * materialInUse ) const{

    for (const MaterialPack & mp: _asset.materials ){
        if (materialInUse != mp.material ){

            Utils::logOpenGLError();
            mp.material->loadUniforms();
            Utils::logOpenGLError();
            materialInUse = mp.material;
        }
        loadAttribsAndUniform();
        Utils::logOpenGLError();
        glDrawArrays(_asset.drawType, mp.drawStart, mp.drawCnt);
        Utils::logOpenGLError();
    }

}

void Instance::renderBoundngBox( const Daylight::IO::PerspectiveView & view ) const{

    // Cube 1x1x1, centered on origin
    GLfloat vertices[] = {
        -0.5, -0.5, -0.5,
         0.5, -0.5, -0.5,
         0.5,  0.5, -0.5,
        -0.5,  0.5, -0.5,
        -0.5, -0.5,  0.5,
         0.5, -0.5,  0.5,
         0.5,  0.5,  0.5,
        -0.5,  0.5,  0.5,
    };
    GLuint vbo_vertices;
    glGenBuffers(1, &vbo_vertices);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    GLushort elements[] = {
        0, 1, 2, 3,
        4, 5, 6, 7,
        0, 4, 1, 5, 2, 6, 3, 7
    };
    GLuint ibo_elements;
    glGenBuffers(1, &ibo_elements);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_elements);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glm::vec3 min = _meshPtr->getMinPos();
    glm::vec3 max = _meshPtr->getMaxPos();

    glm::vec3 size = glm::vec3(max.x-min.x, max.y-min.y, max.z-min.z);
    glm::vec3 center = glm::vec3((min.x+max.x)/2, (min.y+max.y)/2, (min.z+max.z)/2);
    glm::mat4 transform =  glm::translate(glm::mat4(1), center)* glm::scale(glm::mat4(1), size);

    gProgram->setUniform("ModelViewProjectionMatrix",
                         view.getCamInUse()->getProjectionMatrix(static_cast<float>(view.getWidth())/static_cast<float>(view.getHeight()) )*
                         view.getCamInUse()->getPerspectiveMatrix()*
                         getModelMatrix()*
                         transform);

    //glm::mat4 m = _meshPtr->getModelMatrix() * transform;
    //glUniformMatrix4fv(uniform_m, 1, GL_FALSE, glm::value_ptr(m));

    glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices);
    glEnableVertexAttribArray(gProgram->getAttrib("vert"));
    glVertexAttribPointer(
    gProgram->getAttrib("vert"),  // attribute
        3,                  // number of elements per vertex, here (x,y,z,w)
        GL_FLOAT,           // the type of each element
        GL_FALSE,           // take our values as-is
        0,                  // no extra data between each position
        0                   // offset of first element
    );

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_elements);
    glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0);
    glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, (GLvoid*)(4*sizeof(GLushort)));
    glDrawElements(GL_LINES, 8, GL_UNSIGNED_SHORT, (GLvoid*)(8*sizeof(GLushort)));
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    //glDisableVertexAttribArray(attribute_v_coord);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glDeleteBuffers(1, &vbo_vertices);
    glDeleteBuffers(1, &ibo_elements);

}


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

from commitsan.checks import checker
from commitsan.git import git_diff_check

@checker
def check_diff(repo, commit):
    bad_lines = git_diff_check(repo, commit)
    if bad_lines:
        single = (bad_lines == 1)
        yield ('error', 'diff',
               ('{} line{plural} introduce{singular} whitespace errors'
                .format(bad_lines,
                        plural='s'*(not single), singular='s'*single)))


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class PerfEntityMetric extends PerfEntityMetricBase {
  public PerfSampleInfo[] sampleInfo;
  public PerfMetricSeries[] value;

  public PerfSampleInfo[] getSampleInfo() {
    return this.sampleInfo;
  }

  public PerfMetricSeries[] getValue() {
    return this.value;
  }

  public void setSampleInfo(PerfSampleInfo[] sampleInfo) {
    this.sampleInfo=sampleInfo;
  }

  public void setValue(PerfMetricSeries[] value) {
    this.value=value;
  }
}


text:
<?php
/***********************************************************************/
/* ATutor															   */
/***********************************************************************/
/* Copyright (c) 2002-2010                                             */
/* Inclusive Design Institute	                                       */
/* http://atutor.ca													   */
/*																	   */
/* This program is free software. You can redistribute it and/or	   */
/* modify it under the terms of the GNU General Public License		   */
/* as published by the Free Software Foundation.					   */
/***********************************************************************/
// $Id: profile_picture.php 10142 2010-08-17 19:17:26Z hwong $

define('AT_INCLUDE_PATH', '../../../include/');
$_user_location	= 'users';
require (AT_INCLUDE_PATH.'vitals.inc.php');
require ('save_profile_picture.php');

if (in_array('mods/_standard/photos/index.php', $_modules)){
	require(AT_PA_INCLUDE.'profile_album.inc.php');
} else {
	require(AT_INCLUDE_PATH.'../mods/_standard/profile_pictures/html/profile_picture.inc.php');
}
?>


text:
from __future__ import print_function

import argparse
import copy
import os
import sys
import time

import six

from cinderclient import exceptions
from cinderclient import utils
from cinderclient.openstack.common import strutils
from cinderclient.v2 import availability_zones

def _poll_for_status(poll_fn, obj_id, action, final_ok_states,
                     poll_period=5, show_progress=True):
    """Block while action is performed, periodically printing progress."""
    def print_progress(progress):
        if show_progress:
            msg = ('\rInstance %(action)s... %(progress)s%% complete'
                   % dict(action=action, progress=progress))
        else:
            msg = '\rInstance %(action)s...' % dict(action=action)

        sys.stdout.write(msg)
        sys.stdout.flush()

    print()
    while True:
        obj = poll_fn(obj_id)
        status = obj.status.lower()
        progress = getattr(obj, 'progress', None) or 0
        if status in final_ok_states:
            print_progress(100)
            print("\nFinished")
            break
        elif status == "error":
            print("\nError %(action)s instance" % {'action': action})
            break
        else:
            print_progress(progress)
            time.sleep(poll_period)

def _find_volume_snapshot(cs, snapshot):
    """Get a volume snapshot by name or ID."""
    return utils.find_resource(cs.volume_snapshots, snapshot)

def _find_backup(cs, backup):
    """Get a backup by name or ID."""
    return utils.find_resource(cs.backups, backup)

def _find_transfer(cs, transfer):
    """Get a transfer by name or ID."""
    return utils.find_resource(cs.transfers, transfer)

def _find_qos_specs(cs, qos_specs):
    """Get a qos specs by ID."""
    return utils.find_resource(cs.qos_specs, qos_specs)

def _print_volume_snapshot(snapshot):
    utils.print_dict(snapshot._info)

def _print_volume_image(image):
    utils.print_dict(image[1]['os-volume_upload_image'])

def _translate_keys(collection, convert):
    for item in collection:
        keys = item.__dict__
        for from_key, to_key in convert:
            if from_key in keys and to_key not in keys:
                setattr(item, to_key, item._info[from_key])

def _translate_volume_keys(collection):
    convert = [('volumeType', 'volume_type')]
    _translate_keys(collection, convert)

def _translate_volume_snapshot_keys(collection):
    convert = [('volumeId', 'volume_id')]
    _translate_keys(collection, convert)

def _translate_availability_zone_keys(collection):
    convert = [('zoneName', 'name'), ('zoneState', 'status')]
    _translate_keys(collection, convert)

def _extract_metadata(args):
    metadata = {}
    for metadatum in args.metadata:
        # unset doesn't require a val, so we have the if/else
        if '=' in metadatum:
            (key, value) = metadatum.split('=', 1)
        else:
            key = metadatum
            value = None

        metadata[key] = value
    return metadata

@utils.arg('--all-tenants',
           dest='all_tenants',
           metavar='<0|1>',
           nargs='?',
           type=int,
           const=1,
           default=0,
           help='Display information from all tenants (Admin only).')
@utils.arg('--all_tenants',
           nargs='?',
           type=int,
           const=1,
           help=argparse.SUPPRESS)
@utils.arg('--name',
           metavar='<name>',
           default=None,
           help='Filter results by name')
@utils.arg('--display-name',
           help=argparse.SUPPRESS)
@utils.arg('--status',
           metavar='<status>',
           default=None,
           help='Filter results by status')
@utils.arg('--metadata',
           type=str,
           nargs='*',
           metavar='<key=value>',
           help='Filter results by metadata',
           default=None)
@utils.service_type('volumev2')
def do_list(cs, args):
    """List all the volumes."""
    # NOTE(thingee): Backwards-compatibility with v1 args
    if args.display_name is not None:
        args.name = args.display_name

    all_tenants = int(os.environ.get("ALL_TENANTS", args.all_tenants))
    search_opts = {
        'all_tenants': all_tenants,
        'name': args.name,
        'status': args.status,
        'metadata': _extract_metadata(args) if args.metadata else None,
    }
    volumes = cs.volumes.list(search_opts=search_opts)
    _translate_volume_keys(volumes)

    # Create a list of servers to which the volume is attached
    for vol in volumes:
        servers = [s.get('server_id') for s in vol.attachments]
        setattr(vol, 'attached_to', ','.join(map(str, servers)))

    utils.print_list(volumes, ['ID', 'Status', 'Name',
                     'Size', 'Volume Type', 'Bootable', 'Attached to'])

@utils.arg('volume',
           metavar='<volume>',
           help='Name or ID of the volume.')
@utils.service_type('volumev2')
def do_show(cs, args):
    """Show details about a volume."""
    info = dict()
    volume = utils.find_volume(cs, args.volume)
    info.update(volume._info)

    info.pop('links', None)
    utils.print_dict(info)

@utils.arg('size',
           metavar='<size>',
           type=int,
           help='Size of volume in GB')
@utils.arg('--snapshot-id',
           metavar='<snapshot-id>',
           default=None,
           help='Create volume from snapshot id (Optional, Default=None)')
@utils.arg('--snapshot_id',
           help=argparse.SUPPRESS)
@utils.arg('--source-volid',
           metavar='<source-volid>',
           default=None,
           help='Create volume from volume id (Optional, Default=None)')
@utils.arg('--source_volid',
           help=argparse.SUPPRESS)
@utils.arg('--image-id',
           metavar='<image-id>',
           default=None,
           help='Create volume from image id (Optional, Default=None)')
@utils.arg('--image_id',
           help=argparse.SUPPRESS)
@utils.arg('--name',
           metavar='<name>',
           default=None,
           help='Volume name (Optional, Default=None)')
@utils.arg('--display-name',
           help=argparse.SUPPRESS)
@utils.arg('--display_name',
           help=argparse.SUPPRESS)
@utils.arg('--description',
           metavar='<description>',
           default=None,
           help='Volume description (Optional, Default=None)')
@utils.arg('--display-description',
           help=argparse.SUPPRESS)
@utils.arg('--display_description',
           help=argparse.SUPPRESS)
@utils.arg('--volume-type',
           metavar='<volume-type>',
           default=None,
           help='Volume type (Optional, Default=None)')
@utils.arg('--volume_type',
           help=argparse.SUPPRESS)
@utils.arg('--availability-zone',
           metavar='<availability-zone>',
           default=None,
           help='Availability zone for volume (Optional, Default=None)')
@utils.arg('--availability_zone',
           help=argparse.SUPPRESS)
@utils.arg('--metadata',
           type=str,
           nargs='*',
           metavar='<key=value>',
           help='Metadata key=value pairs (Optional, Default=None)',
           default=None)
@utils.arg('--hint',
           metavar='<key=value>',
           dest='scheduler_hints',
           action='append',
           default=[],
           help='Scheduler hint like in nova')
@utils.service_type('volumev2')
def do_create(cs, args):
    """Add a new volume."""
    # NOTE(thingee): Backwards-compatibility with v1 args
    if args.display_name is not None:
        args.name = args.display_name

    if args.display_description is not None:
        args.description = args.display_description

    volume_metadata = None
    if args.metadata is not None:
        volume_metadata = _extract_metadata(args)

    #NOTE(N.S.): take this piece from novaclient
    hints = {}
    if args.scheduler_hints:
        for hint in args.scheduler_hints:
            key, _sep, value = hint.partition('=')
            # NOTE(vish): multiple copies of the same hint will
            #             result in a list of values
            if key in hints:
                if isinstance(hints[key], six.string_types):
                    hints[key] = [hints[key]]
                hints[key] += [value]
            else:
                hints[key] = value
    #NOTE(N.S.): end of the taken piece

    volume = cs.volumes.create(args.size,
                               args.snapshot_id,
                               args.source_volid,
                               args.name,
                               args.description,
                               args.volume_type,
                               availability_zone=args.availability_zone,
                               imageRef=args.image_id,
                               metadata=volume_metadata,
                               scheduler_hints=hints)

    info = dict()
    volume = cs.volumes.get(volume.id)
    info.update(volume._info)

    info.pop('links', None)
    utils.print_dict(info)

@utils.arg('volume',
           metavar='<volume>', nargs='+',
           help='Name or ID of the volume(s) to delete.')
@utils.service_type('volumev2')
def do_delete(cs, args):
    """Remove a volume(s)."""
    failure_count = 0
    for volume in args.volume:
        try:
            utils.find_volume(cs, volume).delete()
        except Exception as e:
            failure_count += 1
            print("Delete for volume %s failed: %s" % (volume, e))
    if failure_count == len(args.volume):
        raise exceptions.CommandError("Unable to delete any of the specified "
                                      "volumes.")

@utils.arg('volume',
           metavar='<volume>', nargs='+',
           help='Name or ID of the volume(s) to delete.')
@utils.service_type('volumev2')
def do_force_delete(cs, args):
    """Attempt forced removal of volume(s), regardless of the state(s)."""
    failure_count = 0
    for volume in args.volume:
        try:
            utils.find_volume(cs, volume).force_delete()
        except Exception as e:
            failure_count += 1
            print("Delete for volume %s failed: %s" % (volume, e))
    if failure_count == len(args.volume):
        raise exceptions.CommandError("Unable to force delete any of the "
                                      "specified volumes.")

@utils.arg('volume', metavar='<volume>', nargs='+',
           help='Name or ID of the volume to modify.')
@utils.arg('--state', metavar='<state>', default='available',
           help=('Indicate which state to assign the volume. Options include '
                 'available, error, creating, deleting, error_deleting. If no '
                 'state is provided, available will be used.'))
@utils.service_type('volumev2')
def do_reset_state(cs, args):
    """Explicitly update the state of a volume."""
    failure_count = 0

    single = (len(args.volume) == 1)

    for volume in args.volume:
        try:
            utils.find_volume(cs, volume).reset_state(args.state)
        except Exception as e:
            failure_count += 1
            msg = "Reset state for volume %s failed: %s" % (volume, e)
            if not single:
                print(msg)

    if failure_count == len(args.volume):
        if not single:
            msg = "Unable to reset the state for any of the specified volumes."
        raise exceptions.CommandError(msg)

@utils.arg('volume',
           metavar='<volume>',
           help='Name or ID of the volume to rename.')
@utils.arg('name',
           nargs='?',
           metavar='<name>',
           help='New name for the volume.')
@utils.arg('--description', metavar='<description>',
           help='Optional volume description. (Default=None)',
           default=None)
@utils.arg('--display-description',
           help=argparse.SUPPRESS)
@utils.arg('--display_description',
           help=argparse.SUPPRESS)
@utils.service_type('volumev2')
def do_rename(cs, args):
    """Rename a volume."""
    kwargs = {}

    if args.name is not None:
        kwargs['name'] = args.name
    if args.display_description is not None:
        kwargs['description'] = args.display_description
    elif args.description is not None:
        kwargs['description'] = args.description

    if not any(kwargs):
        msg = 'Must supply either name or description.'
        raise exceptions.ClientException(code=1, message=msg)

    utils.find_volume(cs, args.volume).update(**kwargs)

@utils.arg('volume',
           metavar='<volume>',
           help='Name or ID of the volume to update metadata on.')
@utils.arg('action',
           metavar='<action>',
           choices=['set', 'unset'],
           help="Actions: 'set' or 'unset'")
@utils.arg('metadata',
           metavar='<key=value>',
           nargs='+',
           default=[],
           help='Metadata to set/unset (only key is necessary on unset)')
@utils.service_type('volumev2')
def do_metadata(cs, args):
    """Set or Delete metadata on a volume."""
    volume = utils.find_volume(cs, args.volume)
    metadata = _extract_metadata(args)

    if args.action == 'set':
        cs.volumes.set_metadata(volume, metadata)
    elif args.action == 'unset':
        # NOTE(zul): Make sure py2/py3 sorting is the same
        cs.volumes.delete_metadata(volume, sorted(metadata.keys(),
                                   reverse=True))

@utils.arg('--all-tenants',
           dest='all_tenants',
           metavar='<0|1>',
           nargs='?',
           type=int,
           const=1,
           default=0,
           help='Display information from all tenants (Admin only).')
@utils.arg('--all_tenants',
           nargs='?',
           type=int,
           const=1,
           help=argparse.SUPPRESS)
@utils.arg('--name',
           metavar='<name>',
           default=None,
           help='Filter results by name')
@utils.arg('--display-name',
           help=argparse.SUPPRESS)
@utils.arg('--display_name',
           help=argparse.SUPPRESS)
@utils.arg('--status',
           metavar='<status>',
           default=None,
           help='Filter results by status')
@utils.arg('--volume-id',
           metavar='<volume-id>',
           default=None,
           help='Filter results by volume-id')
@utils.arg('--volume_id',
           help=argparse.SUPPRESS)
@utils.service_type('volumev2')
def do_snapshot_list(cs, args):
    """List all the snapshots."""
    all_tenants = int(os.environ.get("ALL_TENANTS", args.all_tenants))

    if args.display_name is not None:
        args.name = args.display_name

    search_opts = {
        'all_tenants': all_tenants,
        'display_name': args.name,
        'status': args.status,
        'volume_id': args.volume_id,
    }

    snapshots = cs.volume_snapshots.list(search_opts=search_opts)
    _translate_volume_snapshot_keys(snapshots)
    utils.print_list(snapshots,
                     ['ID', 'Volume ID', 'Status', 'Name', 'Size'])

@utils.arg('snapshot',
           metavar='<snapshot>',
           help='Name or ID of the snapshot.')
@utils.service_type('volumev2')
def do_snapshot_show(cs, args):
    """Show details about a snapshot."""
    snapshot = _find_volume_snapshot(cs, args.snapshot)
    _print_volume_snapshot(snapshot)

@utils.arg('volume',
           metavar='<volume>',
           help='Name or ID of the volume to snapshot')
@utils.arg('--force',
           metavar='<True|False>',
           help='Optional flag to indicate whether '
           'to snapshot a volume even if it\'s '
           'attached to an instance. (Default=False)',
           default=False)
@utils.arg('--name',
           metavar='<name>',
           default=None,
           help='Optional snapshot name. (Default=None)')
@utils.arg('--display-name',
           help=argparse.SUPPRESS)
@utils.arg('--display_name',
           help=argparse.SUPPRESS)
@utils.arg('--description',
           metavar='<description>',
           default=None,
           help='Optional snapshot description. (Default=None)')
@utils.arg('--display-description',
           help=argparse.SUPPRESS)
@utils.arg('--display_description',
           help=argparse.SUPPRESS)
@utils.service_type('volumev2')
def do_snapshot_create(cs, args):
    """Add a new snapshot."""
    if args.display_name is not None:
        args.name = args.display_name

    if args.display_description is not None:
        args.description = args.display_description

    volume = utils.find_volume(cs, args.volume)
    snapshot = cs.volume_snapshots.create(volume.id,
                                          args.force,
                                          args.name,
                                          args.description)
    _print_volume_snapshot(snapshot)

@utils.arg('snapshot',
           metavar='<snapshot>', nargs='+',
           help='Name or ID of the snapshot(s) to delete.')
@utils.service_type('volumev2')
def do_snapshot_delete(cs, args):
    """Remove one or more snapshots."""
    failure_count = 0
    for snapshot in args.snapshot:
        try:
            _find_volume_snapshot(cs, snapshot).delete()
        except Exception as e:
            failure_count += 1
            print("Delete for snapshot %s failed: %s" % (snapshot, e))
    if failure_count == len(args.snapshot):
        raise exceptions.CommandError("Unable to delete any of the specified "
                                      "snapshots.")

@utils.arg('snapshot', metavar='<snapshot>',
           help='Name or ID of the snapshot.')
@utils.arg('name', nargs='?', metavar='<name>',
           help='New name for the snapshot.')
@utils.arg('--description', metavar='<description>',
           help='Optional snapshot description. (Default=None)',
           default=None)
@utils.arg('--display-description',
           help=argparse.SUPPRESS)
@utils.arg('--display_description',
           help=argparse.SUPPRESS)
@utils.service_type('volumev2')
def do_snapshot_rename(cs, args):
    """Rename a snapshot."""
    kwargs = {}

    if args.name is not None:
        kwargs['name'] = args.name

    if args.description is not None:
        kwargs['description'] = args.description
    elif args.display_description is not None:
        kwargs['description'] = args.display_description

    if not any(kwargs):
        msg = 'Must supply either name or description.'
        raise exceptions.ClientException(code=1, message=msg)

    _find_volume_snapshot(cs, args.snapshot).update(**kwargs)

@utils.arg('snapshot', metavar='<snapshot>', nargs='+',
           help='Name or ID of the snapshot to modify.')
@utils.arg('--state', metavar='<state>',
           default='available',
           help=('Indicate which state to assign the snapshot. '
                 'Options include available, error, creating, '
                 'deleting, error_deleting. If no state is provided, '
                 'available will be used.'))
@utils.service_type('volumev2')
def do_snapshot_reset_state(cs, args):
    """Explicitly update the state of a snapshot."""
    failure_count = 0

    single = (len(args.snapshot) == 1)

    for snapshot in args.snapshot:
        try:
            _find_volume_snapshot(cs, snapshot).reset_state(args.state)
        except Exception as e:
            failure_count += 1
            msg = "Reset state for snapshot %s failed: %s" % (snapshot, e)
            if not single:
                print(msg)

    if failure_count == len(args.snapshot):
        if not single:
            msg = ("Unable to reset the state for any of the the specified "
                   "snapshots.")
        raise exceptions.CommandError(msg)

def _print_volume_type_list(vtypes):
    utils.print_list(vtypes, ['ID', 'Name'])

def _print_type_and_extra_specs_list(vtypes):
    formatters = {'extra_specs': _print_type_extra_specs}
    utils.print_list(vtypes, ['ID', 'Name', 'extra_specs'], formatters)

@utils.service_type('volumev2')
def do_type_list(cs, args):
    """Print a list of available 'volume types'."""
    vtypes = cs.volume_types.list()
    _print_volume_type_list(vtypes)

@utils.service_type('volumev2')
def do_extra_specs_list(cs, args):
    """Print a list of current 'volume types and extra specs' (Admin Only)."""
    vtypes = cs.volume_types.list()
    _print_type_and_extra_specs_list(vtypes)

@utils.arg('name',
           metavar='<name>',
           help="Name of the new volume type")
@utils.service_type('volumev2')
def do_type_create(cs, args):
    """Create a new volume type."""
    vtype = cs.volume_types.create(args.name)
    _print_volume_type_list([vtype])

@utils.arg('id',
           metavar='<id>',
           help="Name or ID of the volume type to delete")
@utils.service_type('volumev2')
def do_type_delete(cs, args):
    """Delete a specific volume type."""
    volume_type = _find_volume_type(cs, args.id)
    cs.volume_types.delete(volume_type)

@utils.arg('vtype',
           metavar='<vtype>',
           help="Name or ID of the volume type")
@utils.arg('action',
           metavar='<action>',
           choices=['set', 'unset'],
           help="Actions: 'set' or 'unset'")
@utils.arg('metadata',
           metavar='<key=value>',
           nargs='+',
           default=[],
           help='Extra_specs to set/unset (only key is necessary on unset)')
@utils.service_type('volumev2')
def do_type_key(cs, args):
    """Set or unset extra_spec for a volume type."""
    vtype = _find_volume_type(cs, args.vtype)
    keypair = _extract_metadata(args)

    if args.action == 'set':
        vtype.set_keys(keypair)
    elif args.action == 'unset':
        vtype.unset_keys(list(keypair))

@utils.service_type('volumev2')
def do_endpoints(cs, args):
    """Discover endpoints that get returned from the authenticate services."""
    catalog = cs.client.service_catalog.catalog
    for e in catalog['serviceCatalog']:
        utils.print_dict(e['endpoints'][0], e['name'])

@utils.service_type('volumev2')
def do_credentials(cs, args):
    """Show user credentials returned from auth."""
    catalog = cs.client.service_catalog.catalog
    utils.print_dict(catalog['user'], "User Credentials")
    utils.print_dict(catalog['token'], "Token")

_quota_resources = ['volumes', 'snapshots', 'gigabytes']
_quota_infos = ['Type', 'In_use', 'Reserved', 'Limit']

def _quota_show(quotas):
    quota_dict = {}
    for resource in quotas._info:
        good_name = False
        for name in _quota_resources:
            if resource.startswith(name):
                good_name = True
        if not good_name:
            continue
        quota_dict[resource] = getattr(quotas, resource, None)
    utils.print_dict(quota_dict)

def _quota_usage_show(quotas):
    quota_list = []
    for resource in quotas._info.keys():
        good_name = False
        for name in _quota_resources:
            if resource.startswith(name):
                good_name = True
        if not good_name:
            continue
        quota_info = getattr(quotas, resource, None)
        quota_info['Type'] = resource
        quota_info = dict((k.capitalize(), v) for k, v in quota_info.items())
        quota_list.append(quota_info)
    utils.print_list(quota_list, _quota_infos)

def _quota_update(manager, identifier, args):
    updates = {}
    for resource in _quota_resources:
        val = getattr(args, resource, None)
        if val is not None:
            if args.volume_type:
                resource = resource + '_%s' % args.volume_type
            updates[resource] = val

    if updates:
        manager.update(identifier, **updates)

@utils.arg('tenant',
           metavar='<tenant_id>',
           help='UUID of tenant to list the quotas for.')
@utils.service_type('volumev2')
def do_quota_show(cs, args):
    """List the quotas for a tenant."""

    _quota_show(cs.quotas.get(args.tenant))

@utils.arg('tenant', metavar='<tenant_id>',
           help='UUID of tenant to list the quota usage for.')
@utils.service_type('volumev2')
def do_quota_usage(cs, args):
    """List the quota usage for a tenant."""

    _quota_usage_show(cs.quotas.get(args.tenant, usage=True))

@utils.arg('tenant',
           metavar='<tenant_id>',
           help='UUID of tenant to list the default quotas for.')
@utils.service_type('volumev2')
def do_quota_defaults(cs, args):
    """List the default quotas for a tenant."""

    _quota_show(cs.quotas.defaults(args.tenant))

@utils.arg('tenant',
           metavar='<tenant_id>',
           help='UUID of tenant to set the quotas for.')
@utils.arg('--volumes',
           metavar='<volumes>',
           type=int, default=None,
           help='New value for the "volumes" quota.')
@utils.arg('--snapshots',
           metavar='<snapshots>',
           type=int, default=None,
           help='New value for the "snapshots" quota.')
@utils.arg('--gigabytes',
           metavar='<gigabytes>',
           type=int, default=None,
           help='New value for the "gigabytes" quota.')
@utils.arg('--volume-type',
           metavar='<volume_type_name>',
           default=None,
           help='Volume type (Optional, Default=None)')
@utils.service_type('volumev2')
def do_quota_update(cs, args):
    """Update the quotas for a tenant."""

    _quota_update(cs.quotas, args.tenant, args)

@utils.arg('tenant', metavar='<tenant_id>',
           help='UUID of tenant to delete the quotas for.')
@utils.service_type('volume')
def do_quota_delete(cs, args):
    """Delete the quotas for a tenant."""

    cs.quotas.delete(args.tenant)

@utils.arg('class_name',
           metavar='<class>',
           help='Name of quota class to list the quotas for.')
@utils.service_type('volumev2')
def do_quota_class_show(cs, args):
    """List the quotas for a quota class."""

    _quota_show(cs.quota_classes.get(args.class_name))

@utils.arg('class-name',
           metavar='<class-name>',
           help='Name of quota class to set the quotas for.')
@utils.arg('--volumes',
           metavar='<volumes>',
           type=int, default=None,
           help='New value for the "volumes" quota.')
@utils.arg('--snapshots',
           metavar='<snapshots>',
           type=int, default=None,
           help='New value for the "snapshots" quota.')
@utils.arg('--gigabytes',
           metavar='<gigabytes>',
           type=int, default=None,
           help='New value for the "gigabytes" quota.')
@utils.arg('--volume-type',
           metavar='<volume_type_name>',
           default=None,
           help='Volume type (Optional, Default=None)')
@utils.service_type('volumev2')
def do_quota_class_update(cs, args):
    """Update the quotas for a quota class."""

    _quota_update(cs.quota_classes, args.class_name, args)

@utils.service_type('volumev2')
def do_absolute_limits(cs, args):
    """Print a list of absolute limits for a user"""
    limits = cs.limits.get().absolute
    columns = ['Name', 'Value']
    utils.print_list(limits, columns)

@utils.service_type('volumev2')
def do_rate_limits(cs, args):
    """Print a list of rate limits for a user"""
    limits = cs.limits.get().rate
    columns = ['Verb', 'URI', 'Value', 'Remain', 'Unit', 'Next_Available']
    utils.print_list(limits, columns)

def _print_type_extra_specs(vol_type):
    try:
        return vol_type.get_keys()
    except exceptions.NotFound:
        return "N/A"

def _find_volume_type(cs, vtype):
    """Get a volume type by name or ID."""
    return utils.find_resource(cs.volume_types, vtype)

@utils.arg('volume',
           metavar='<volume>',
           help='Name or ID of the volume to snapshot')
@utils.arg('--force',
           metavar='<True|False>',
           help='Optional flag to indicate whether '
           'to upload a volume even if it\'s '
           'attached to an instance. (Default=False)',
           default=False)
@utils.arg('--container-format',
           metavar='<container-format>',
           help='Optional type for container format '
           '(Default=bare)',
           default='bare')
@utils.arg('--container_format',
           help=argparse.SUPPRESS)
@utils.arg('--disk-format',
           metavar='<disk-format>',
           help='Optional type for disk format '
           '(Default=raw)',
           default='raw')
@utils.arg('--disk_format',
           help=argparse.SUPPRESS)
@utils.arg('image_name',
           metavar='<image-name>',
           help='Name for created image')
@utils.arg('--image_name',
           help=argparse.SUPPRESS)
@utils.service_type('volumev2')
def do_upload_to_image(cs, args):
    """Upload volume to image service as image."""
    volume = utils.find_volume(cs, args.volume)
    _print_volume_image(volume.upload_to_image(args.force,
                                               args.image_name,
                                               args.container_format,
                                               args.disk_format))

@utils.arg('volume', metavar='<volume>', help='ID of the volume to migrate')
@utils.arg('host', metavar='<host>', help='Destination host')
@utils.arg('--force-host-copy', metavar='<True|False>',
           choices=['True', 'False'], required=False,
           help='Optional flag to force the use of the generic '
           'host-based migration mechanism, bypassing driver '
           'optimizations (Default=False).',
           default=False)
@utils.service_type('volumev2')
def do_migrate(cs, args):
    """Migrate the volume to the new host."""
    volume = utils.find_volume(cs, args.volume)
    volume.migrate_volume(args.host, args.force_host_copy)

@utils.arg('volume', metavar='<volume>',
           help='Name or ID of the volume to retype')
@utils.arg('new_type', metavar='<volume-type>', help='New volume type')
@utils.arg('--migration-policy', metavar='<never|on-demand>', required=False,
           choices=['never', 'on-demand'], default='never',
           help='Policy on migrating the volume during the retype.')
@utils.service_type('volumev2')
def do_retype(cs, args):
    """Change the volume's type."""
    volume = utils.find_volume(cs, args.volume)
    volume.retype(args.new_type, args.migration_policy)

@utils.arg('volume', metavar='<volume>',
           help='Name or ID of the volume to backup.')
@utils.arg('--container', metavar='<container>',
           help='Optional backup container name. (Default=None)',
           default=None)
@utils.arg('--display-name',
           help=argparse.SUPPRESS)
@utils.arg('--name', metavar='<name>',
           help='Optional backup name. (Default=None)',
           default=None)
@utils.arg('--display-description',
           help=argparse.SUPPRESS)
@utils.arg('--description',
           metavar='<description>',
           default=None,
           help='Options backup description (Default=None)')
@utils.service_type('volumev2')
def do_backup_create(cs, args):
    """Creates a backup."""
    if args.display_name is not None:
        args.name = args.display_name

    if args.display_description is not None:
        args.description = args.display_description

    volume = utils.find_volume(cs, args.volume)
    backup = cs.backups.create(volume.id,
                               args.container,
                               args.name,
                               args.description)

    info = {"volume_id": volume.id}
    info.update(backup._info)

    if 'links' in info:
        info.pop('links')

    utils.print_dict(info)

@utils.arg('backup', metavar='<backup>', help='Name or ID of the backup.')
@utils.service_type('volumev2')
def do_backup_show(cs, args):
    """Show details about a backup."""
    backup = _find_backup(cs, args.backup)
    info = dict()
    info.update(backup._info)

    info.pop('links', None)
    utils.print_dict(info)

@utils.service_type('volumev2')
def do_backup_list(cs, args):
    """List all the backups."""
    backups = cs.backups.list()
    columns = ['ID', 'Volume ID', 'Status', 'Name', 'Size', 'Object Count',
               'Container']
    utils.print_list(backups, columns)

@utils.arg('backup', metavar='<backup>',
           help='Name or ID of the backup to delete.')
@utils.service_type('volumev2')
def do_backup_delete(cs, args):
    """Remove a backup."""
    backup = _find_backup(cs, args.backup)
    backup.delete()

@utils.arg('backup', metavar='<backup>',
           help='ID of the backup to restore.')
@utils.arg('--volume-id', metavar='<volume>',
           help=argparse.SUPPRESS,
           default=None)
@utils.arg('--volume', metavar='<volume>',
           help='Optional ID(or name) of the volume to restore to.',
           default=None)
@utils.service_type('volumev2')
def do_backup_restore(cs, args):
    """Restore a backup."""
    vol = args.volume or args.volume_id
    if vol:
        volume_id = utils.find_volume(cs, vol).id
    else:
        volume_id = None
    cs.restores.restore(args.backup, volume_id)

@utils.arg('backup', metavar='<backup>',
           help='ID of the backup to export.')
@utils.service_type('volumev2')
def do_backup_export(cs, args):
    """Export backup metadata record."""
    info = cs.backups.export_record(args.backup)
    utils.print_dict(info)

@utils.arg('backup_service', metavar='<backup_service>',
           help='Backup service to use for importing the backup.')
@utils.arg('backup_url', metavar='<backup_url>',
           help='Backup URL for importing the backup metadata.')
@utils.service_type('volumev2')
def do_backup_import(cs, args):
    """Import backup metadata record."""
    info = cs.backups.import_record(args.backup_service, args.backup_url)
    info.pop('links', None)

    utils.print_dict(info)

@utils.arg('volume', metavar='<volume>',
           help='Name or ID of the volume to transfer.')
@utils.arg('--name',
           metavar='<name>',
           default=None,
           help='Optional transfer name. (Default=None)')
@utils.arg('--display-name',
           help=argparse.SUPPRESS)
@utils.service_type('volumev2')
def do_transfer_create(cs, args):
    """Creates a volume transfer."""
    if args.display_name is not None:
        args.name = args.display_name

    volume = utils.find_volume(cs, args.volume)
    transfer = cs.transfers.create(volume.id,
                                   args.name)
    info = dict()
    info.update(transfer._info)

    info.pop('links', None)
    utils.print_dict(info)

@utils.arg('transfer', metavar='<transfer>',
           help='Name or ID of the transfer to delete.')
@utils.service_type('volumev2')
def do_transfer_delete(cs, args):
    """Undo a transfer."""
    transfer = _find_transfer(cs, args.transfer)
    transfer.delete()

@utils.arg('transfer', metavar='<transfer>',
           help='ID of the transfer to accept.')
@utils.arg('auth_key', metavar='<auth_key>',
           help='Auth key of the transfer to accept.')
@utils.service_type('volumev2')
def do_transfer_accept(cs, args):
    """Accepts a volume transfer."""
    transfer = cs.transfers.accept(args.transfer, args.auth_key)
    info = dict()
    info.update(transfer._info)

    info.pop('links', None)
    utils.print_dict(info)

@utils.service_type('volumev2')
def do_transfer_list(cs, args):
    """List all the transfers."""
    transfers = cs.transfers.list()
    columns = ['ID', 'Volume ID', 'Name']
    utils.print_list(transfers, columns)

@utils.arg('transfer', metavar='<transfer>',
           help='Name or ID of the transfer to accept.')
@utils.service_type('volumev2')
def do_transfer_show(cs, args):
    """Show details about a transfer."""
    transfer = _find_transfer(cs, args.transfer)
    info = dict()
    info.update(transfer._info)

    info.pop('links', None)
    utils.print_dict(info)

@utils.arg('volume', metavar='<volume>',
           help='Name or ID of the volume to extend.')
@utils.arg('new_size',
           metavar='<new_size>',
           type=int,
           help='New size of volume in GB')
@utils.service_type('volumev2')
def do_extend(cs, args):
    """Attempt to extend the size of an existing volume."""
    volume = utils.find_volume(cs, args.volume)
    cs.volumes.extend(volume, args.new_size)

@utils.arg('--host', metavar='<hostname>', default=None,
           help='Name of host.')
@utils.arg('--binary', metavar='<binary>', default=None,
           help='Service binary.')
@utils.service_type('volumev2')
def do_service_list(cs, args):
    """List all the services. Filter by host & service binary."""
    result = cs.services.list(host=args.host, binary=args.binary)
    columns = ["Binary", "Host", "Zone", "Status", "State", "Updated_at"]
    # NOTE(jay-lau-513): we check if the response has disabled_reason
    # so as not to add the column when the extended ext is not enabled.
    if result and hasattr(result[0], 'disabled_reason'):
        columns.append("Disabled Reason")
    utils.print_list(result, columns)

@utils.arg('host', metavar='<hostname>', help='Name of host.')
@utils.arg('binary', metavar='<binary>', help='Service binary.')
@utils.service_type('volumev2')
def do_service_enable(cs, args):
    """Enable the service."""
    result = cs.services.enable(args.host, args.binary)
    columns = ["Host", "Binary", "Status"]
    utils.print_list([result], columns)

@utils.arg('host', metavar='<hostname>', help='Name of host.')
@utils.arg('binary', metavar='<binary>', help='Service binary.')
@utils.arg('--reason', metavar='<reason>',
           help='Reason for disabling service.')
@utils.service_type('volumev2')
def do_service_disable(cs, args):
    """Disable the service."""
    columns = ["Host", "Binary", "Status"]
    if args.reason:
        columns.append('Disabled Reason')
        result = cs.services.disable_log_reason(args.host, args.binary,
                                                args.reason)
    else:
        result = cs.services.disable(args.host, args.binary)
    utils.print_list([result], columns)

def _treeizeAvailabilityZone(zone):
    """Build a tree view for availability zones."""
    AvailabilityZone = availability_zones.AvailabilityZone

    az = AvailabilityZone(zone.manager,
                          copy.deepcopy(zone._info), zone._loaded)
    result = []

    # Zone tree view item
    az.zoneName = zone.zoneName
    az.zoneState = ('available'
                    if zone.zoneState['available'] else 'not available')
    az._info['zoneName'] = az.zoneName
    az._info['zoneState'] = az.zoneState
    result.append(az)

    if getattr(zone, "hosts", None) and zone.hosts is not None:
        for (host, services) in zone.hosts.items():
            # Host tree view item
            az = AvailabilityZone(zone.manager,
                                  copy.deepcopy(zone._info), zone._loaded)
            az.zoneName = '|- %s' % host
            az.zoneState = ''
            az._info['zoneName'] = az.zoneName
            az._info['zoneState'] = az.zoneState
            result.append(az)

            for (svc, state) in services.items():
                # Service tree view item
                az = AvailabilityZone(zone.manager,
                                      copy.deepcopy(zone._info), zone._loaded)
                az.zoneName = '| |- %s' % svc
                az.zoneState = '%s %s %s' % (
                               'enabled' if state['active'] else 'disabled',
                               ':-)' if state['available'] else 'XXX',
                               state['updated_at'])
                az._info['zoneName'] = az.zoneName
                az._info['zoneState'] = az.zoneState
                result.append(az)
    return result

@utils.service_type('volumev2')
def do_availability_zone_list(cs, _args):
    """List all the availability zones."""
    try:
        availability_zones = cs.availability_zones.list()
    except exceptions.Forbidden as e:  # policy doesn't allow probably
        try:
            availability_zones = cs.availability_zones.list(detailed=False)
        except Exception:
            raise e

    result = []
    for zone in availability_zones:
        result += _treeizeAvailabilityZone(zone)
    _translate_availability_zone_keys(result)
    utils.print_list(result, ['Name', 'Status'])

def _print_volume_encryption_type_list(encryption_types):
    """
    Display a tabularized list of volume encryption types.

    :param encryption_types: a list of :class: VolumeEncryptionType instances
    """
    utils.print_list(encryption_types, ['Volume Type ID', 'Provider',
                                        'Cipher', 'Key Size',
                                        'Control Location'])

@utils.service_type('volumev2')
def do_encryption_type_list(cs, args):
    """List encryption type information for all volume types (Admin Only)."""
    result = cs.volume_encryption_types.list()
    utils.print_list(result, ['Volume Type ID', 'Provider', 'Cipher',
                              'Key Size', 'Control Location'])

@utils.arg('volume_type',
           metavar='<volume_type>',
           type=str,
           help="Name or ID of the volume type")
@utils.service_type('volumev2')
def do_encryption_type_show(cs, args):
    """Show the encryption type information for a volume type (Admin Only)."""
    volume_type = _find_volume_type(cs, args.volume_type)

    result = cs.volume_encryption_types.get(volume_type)

    # Display result or an empty table if no result
    if hasattr(result, 'volume_type_id'):
        _print_volume_encryption_type_list([result])
    else:
        _print_volume_encryption_type_list([])

@utils.arg('volume_type',
           metavar='<volume_type>',
           type=str,
           help="Name or ID of the volume type")
@utils.arg('provider',
           metavar='<provider>',
           type=str,
           help="Class providing encryption support (e.g. LuksEncryptor)")
@utils.arg('--cipher',
           metavar='<cipher>',
           type=str,
           required=False,
           default=None,
           help="Encryption algorithm/mode to use (e.g., aes-xts-plain64) "
           "(Optional, Default=None)")
@utils.arg('--key_size',
           metavar='<key_size>',
           type=int,
           required=False,
           default=None,
           help="Size of the encryption key, in bits (e.g., 128, 256) "
           "(Optional, Default=None)")
@utils.arg('--control_location',
           metavar='<control_location>',
           choices=['front-end', 'back-end'],
           type=str,
           required=False,
           default='front-end',
           help="Notional service where encryption is performed (e.g., "
           "front-end=Nova) Values: 'front-end', 'back-end' "
           "(Default='front-end')")
@utils.service_type('volumev2')
def do_encryption_type_create(cs, args):
    """Create a new encryption type for a volume type (Admin Only)."""
    volume_type = _find_volume_type(cs, args.volume_type)

    body = {}
    body['provider'] = args.provider
    body['cipher'] = args.cipher
    body['key_size'] = args.key_size
    body['control_location'] = args.control_location

    result = cs.volume_encryption_types.create(volume_type, body)
    _print_volume_encryption_type_list([result])

@utils.arg('volume_type',
           metavar='<volume_type>',
           type=str,
           help="Name or ID of the volume type")
@utils.service_type('volumev2')
def do_encryption_type_delete(cs, args):
    """Delete the encryption type for a volume type (Admin Only)."""
    volume_type = _find_volume_type(cs, args.volume_type)
    cs.volume_encryption_types.delete(volume_type)

def _print_qos_specs(qos_specs):
    utils.print_dict(qos_specs._info)

def _print_qos_specs_list(q_specs):
    utils.print_list(q_specs, ['ID', 'Name', 'Consumer', 'specs'])

def _print_qos_specs_and_associations_list(q_specs):
    utils.print_list(q_specs, ['ID', 'Name', 'Consumer', 'specs'])

def _print_associations_list(associations):
    utils.print_list(associations, ['Association_Type', 'Name', 'ID'])

@utils.arg('name',
           metavar='<name>',
           help="Name of the new QoS specs")
@utils.arg('metadata',
           metavar='<key=value>',
           nargs='+',
           default=[],
           help='Specifications for QoS')
@utils.service_type('volumev2')
def do_qos_create(cs, args):
    """Create a new qos specs."""
    keypair = None
    if args.metadata is not None:
        keypair = _extract_metadata(args)
    qos_specs = cs.qos_specs.create(args.name, keypair)
    _print_qos_specs(qos_specs)

@utils.service_type('volumev2')
def do_qos_list(cs, args):
    """Get full list of qos specs."""
    qos_specs = cs.qos_specs.list()
    _print_qos_specs_list(qos_specs)

@utils.arg('qos_specs', metavar='<qos_specs>',
           help='ID of the qos_specs to show.')
@utils.service_type('volumev2')
def do_qos_show(cs, args):
    """Get a specific qos specs."""
    qos_specs = _find_qos_specs(cs, args.qos_specs)
    _print_qos_specs(qos_specs)

@utils.arg('qos_specs', metavar='<qos_specs>',
           help='ID of the qos_specs to delete.')
@utils.arg('--force',
           metavar='<True|False>',
           default=False,
           help='Optional flag that indicates whether to delete '
                'specified qos specs even if it is in-use.')
@utils.service_type('volumev2')
def do_qos_delete(cs, args):
    """Delete a specific qos specs."""
    force = strutils.bool_from_string(args.force)
    qos_specs = _find_qos_specs(cs, args.qos_specs)
    cs.qos_specs.delete(qos_specs, force)

@utils.arg('qos_specs', metavar='<qos_specs>',
           help='ID of qos_specs.')
@utils.arg('vol_type_id', metavar='<volume_type_id>',
           help='ID of volume type to be associated with.')
@utils.service_type('volumev2')
def do_qos_associate(cs, args):
    """Associate qos specs with specific volume type."""
    cs.qos_specs.associate(args.qos_specs, args.vol_type_id)

@utils.arg('qos_specs', metavar='<qos_specs>',
           help='ID of qos_specs.')
@utils.arg('vol_type_id', metavar='<volume_type_id>',
           help='ID of volume type to be associated with.')
@utils.service_type('volumev2')
def do_qos_disassociate(cs, args):
    """Disassociate qos specs from specific volume type."""
    cs.qos_specs.disassociate(args.qos_specs, args.vol_type_id)

@utils.arg('qos_specs', metavar='<qos_specs>',
           help='ID of qos_specs to be operate on.')
@utils.service_type('volumev2')
def do_qos_disassociate_all(cs, args):
    """Disassociate qos specs from all of its associations."""
    cs.qos_specs.disassociate_all(args.qos_specs)

@utils.arg('qos_specs', metavar='<qos_specs>',
           help='ID of qos specs')
@utils.arg('action',
           metavar='<action>',
           choices=['set', 'unset'],
           help="Actions: 'set' or 'unset'")
@utils.arg('metadata', metavar='key=value',
           nargs='+',
           default=[],
           help='QoS specs to set/unset (only key is necessary on unset)')
@utils.service_type('volumev2')
def do_qos_key(cs, args):
    """Set or unset specifications for a qos spec."""
    keypair = _extract_metadata(args)

    if args.action == 'set':
        cs.qos_specs.set_keys(args.qos_specs, keypair)
    elif args.action == 'unset':
        cs.qos_specs.unset_keys(args.qos_specs, list(keypair))

@utils.arg('qos_specs', metavar='<qos_specs>',
           help='ID of the qos_specs.')
@utils.service_type('volumev2')
def do_qos_get_association(cs, args):
    """Get all associations of specific qos specs."""
    associations = cs.qos_specs.get_associations(args.qos_specs)
    _print_associations_list(associations)

@utils.arg('snapshot',
           metavar='<snapshot>',
           help='ID of the snapshot to update metadata on.')
@utils.arg('action',
           metavar='<action>',
           choices=['set', 'unset'],
           help="Actions: 'set' or 'unset'")
@utils.arg('metadata',
           metavar='<key=value>',
           nargs='+',
           default=[],
           help='Metadata to set/unset (only key is necessary on unset)')
@utils.service_type('volumev2')
def do_snapshot_metadata(cs, args):
    """Set or Delete metadata of a snapshot."""
    snapshot = _find_volume_snapshot(cs, args.snapshot)
    metadata = _extract_metadata(args)

    if args.action == 'set':
        metadata = snapshot.set_metadata(metadata)
        utils.print_dict(metadata._info)
    elif args.action == 'unset':
        snapshot.delete_metadata(list(metadata.keys()))

@utils.arg('snapshot', metavar='<snapshot>',
           help='ID of snapshot')
@utils.service_type('volumev2')
def do_snapshot_metadata_show(cs, args):
    """Show metadata of given snapshot."""
    snapshot = _find_volume_snapshot(cs, args.snapshot)
    utils.print_dict(snapshot._info['metadata'], 'Metadata-property')

@utils.arg('volume', metavar='<volume>',
           help='ID of volume')
@utils.service_type('volumev2')
def do_metadata_show(cs, args):
    """Show metadata of given volume."""
    volume = utils.find_volume(cs, args.volume)
    utils.print_dict(volume._info['metadata'], 'Metadata-property')

@utils.arg('volume',
           metavar='<volume>',
           help='ID of the volume to update metadata on.')
@utils.arg('metadata',
           metavar='<key=value>',
           nargs='+',
           default=[],
           help='Metadata entry/entries to update.')
@utils.service_type('volumev2')
def do_metadata_update_all(cs, args):
    """Update all metadata of a volume."""
    volume = utils.find_volume(cs, args.volume)
    metadata = _extract_metadata(args)
    metadata = volume.update_all_metadata(metadata)
    utils.print_dict(metadata)

@utils.arg('snapshot',
           metavar='<snapshot>',
           help='ID of the snapshot to update metadata on.')
@utils.arg('metadata',
           metavar='<key=value>',
           nargs='+',
           default=[],
           help='Metadata entry/entries to update')
@utils.service_type('volumev2')
def do_snapshot_metadata_update_all(cs, args):
    """Update all metadata of a snapshot."""
    snapshot = _find_volume_snapshot(cs, args.snapshot)
    metadata = _extract_metadata(args)
    metadata = snapshot.update_all_metadata(metadata)
    utils.print_dict(metadata)

@utils.arg('volume', metavar='<volume>', help='ID of the volume to update.')
@utils.arg('read_only',
           metavar='<True|true|False|false>',
           choices=['True', 'true', 'False', 'false'],
           help='Flag to indicate whether to update volume to '
           'read-only access mode.')
@utils.service_type('volumev2')
def do_readonly_mode_update(cs, args):
    """Update volume read-only access mode flag."""
    volume = utils.find_volume(cs, args.volume)
    cs.volumes.update_readonly_flag(volume,
                                    strutils.bool_from_string(args.read_only))


text:
module Milwaukee
  VERSION = "1.0.3"
end


text:
package com.orientechnologies.orient.core.storage.impl.local.paginated.wal;

import java.nio.ByteBuffer;

/**
 * @author Andrey Lomakin (a.lomakin-at-orientdb.com) <a
 *     href="mailto:lomakin.andrey@gmail.com">Andrey Lomakin</a>
 * @since 12/12/14
 */
public class ONonTxOperationPerformedWALRecord extends OAbstractWALRecord {
  @Override
  public int toStream(byte[] content, int offset) {
    return offset;
  }

  @Override
  public void toStream(final ByteBuffer buffer) {}

  @Override
  public int fromStream(byte[] content, int offset) {
    return offset;
  }

  @Override
  public int serializedSize() {
    return 0;
  }

  @Override
  public int getId() {
    return WALRecordTypes.NON_TX_OPERATION_PERFORMED_WAL_RECORD;
  }
}


text:
package pe.org.reclamos.entidad;

import java.io.Serializable;
import javax.persistence.*;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import java.util.Date;

/**
 * The persistent class for the solicitud database table.
 *
 */
@Entity
@Table(name="solicitud")
public class Solicitud implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int idSolicitud;

    @Temporal( TemporalType.TIMESTAMP)
	@Column(name="created_at")
	private Date createdAt;

	private String descripcion;

	private int estado;

    @Temporal( TemporalType.TIMESTAMP)
	private Date fecSolicitud;

    @Temporal( TemporalType.TIMESTAMP)
	@Column(name="updated_at")
	private Date updatedAt;

	//bi-directional many-to-one association to Cliente
    @ManyToOne
	@JoinColumn(name="idCliente")
	private Cliente cliente;

    public Solicitud() {
    }

	public int getIdSolicitud() {
		return this.idSolicitud;
	}

	public void setIdSolicitud(int idSolicitud) {
		this.idSolicitud = idSolicitud;
	}

	public Date getCreatedAt() {
		return this.createdAt;
	}

	public void setCreatedAt(Date createdAt) {
		this.createdAt = createdAt;
	}

	public String getDescripcion() {
		return this.descripcion;
	}

	public void setDescripcion(String descripcion) {
		this.descripcion = descripcion;
	}

	public int getEstado() {
		return this.estado;
	}

	public void setEstado(int estado) {
		this.estado = estado;
	}

	public Date getFecSolicitud() {
		return this.fecSolicitud;
	}

	public void setFecSolicitud(Date fecSolicitud) {
		this.fecSolicitud = fecSolicitud;
	}

	public Date getUpdatedAt() {
		return this.updatedAt;
	}

	public void setUpdatedAt(Date updatedAt) {
		this.updatedAt = updatedAt;
	}

	public Cliente getCliente() {
		return this.cliente;
	}

	public void setCliente(Cliente cliente) {
		this.cliente = cliente;
	}

	 @Override
     public String toString() {
          return ReflectionToStringBuilder.toString(this,ToStringStyle.SIMPLE_STYLE);
     }

}


text:
@implementation NSPathCell

-initWithCoder: (NSCoder *) coder {
	self = [super initWithCoder: coder];
	if (self) {
		if (![coder allowsKeyedCoding]) {
			[NSException raise:NSInvalidArgumentException format:@"%@ can not initWithCoder:%@",isa,[coder class]];
		}

		[self setPlaceholderString: [coder decodeObjectForKey: @"NSPlaceholderString"]];
		[self setBackgroundColor: [coder decodeObjectForKey: @"NSBackgroundColor"]];
		[self setPathComponentCells: [coder decodeObjectForKey: @"NSPathComponentCells"]];
		[self setPathStyle: [coder decodeIntForKey: @"NSPathStyle"]];
		_delegate=[coder decodeObjectForKey: @"NSDelegate"];
		[self setAllowedTypes: [coder decodeObjectForKey: @"NSAllowedTypes"]];
	}

	return self;
}

- (void) dealloc {
   [_URL release];
   [_pathComponentCells release];
   [_backgroundColor release];
   [_allowedTypes release];
   [_placeholder release];
   [super dealloc];
}

- (void)mouseEntered:(NSEvent *)event withFrame:(NSRect)frame inView:(NSView *)view {
	NSUnimplementedMethod();
}

- (void)mouseExited:(NSEvent *)event withFrame:(NSRect)frame inView:(NSView *)view {
	NSUnimplementedMethod();
}

- (NSArray *)allowedTypes {
	return _allowedTypes;
}

- (void)setAllowedTypes:(NSArray *)value {
   value=[value copy];
   [_allowedTypes release];
   _allowedTypes=value;
}

-(NSPathStyle)pathStyle {
   return _pathStyle;
}

-(void)setPathStyle:(NSPathStyle)style {
   _pathStyle = style;
   [[self controlView] setNeedsDisplay: YES];
}

- objectValue {
	return [self URL];
}

- (void)setObjectValue:(id <NSCopying>)valueX {
   id value=(id)valueX;

   if([(id)value isKindOfClass: [NSURL class]])
    [self setURL:(id)value];
   else if([(id)value isKindOfClass: [NSString class]])
    [self setURL:[NSURL fileURLWithPath:(id)value]];

   [NSException raise:NSInvalidArgumentException format:@"-[%@ %s] only accepts URL's and strings, class=%@",isa,_cmd,[(id)value class]];
}

-(NSAttributedString *)placeholderAttributedString {
	return _placeholder;
}

-(void)setPlaceholderAttributedString:(NSAttributedString *)value {
   value=[value copy];
   [_placeholder release];
   _placeholder=value;
}

-(NSString *)placeholderString {
	return [_placeholder string];
}

-(void)setPlaceholderString:(NSString *)string {
   [self setPlaceholderAttributedString: [[[NSAttributedString alloc] initWithString: string] autorelease]];
}

-(NSColor *)backgroundColor {
	return _backgroundColor;
}

-(void)setBackgroundColor:(NSColor *)color {
   color=[color copy];
   [_backgroundColor release];
   _backgroundColor=color;
}

+(Class)pathComponentCellClass {
	return [NSPathComponentCell class];
}

-(NSRect)rectOfPathComponentCell:(NSPathComponentCell *)cell withFrame:(NSRect)frame inView:(NSView *)view {
   NSRect rect=frame;

   for(NSPathComponentCell *check in _pathComponentCells){
    rect.size.width = [check cellSize].width;

    if(cell==check)
     return rect;

    switch([self pathStyle]){
     case NSPathStyleStandard:
      rect.origin.x += rect.size.width;
      break;

     case NSPathStyleNavigationBar:
      // Navigation style components butt up against each other
      rect.origin.x+=rect.size.width;
      break;

     case NSPathStylePopUp:
      break;
    }

   }

   return NSZeroRect;
}

-(NSPathComponentCell *)pathComponentCellAtPoint:(NSPoint)point withFrame:(NSRect)frame inView:(NSView *)view {

   for (NSPathComponentCell *cell in _pathComponentCells) {
    NSRect checkFrame=[self rectOfPathComponentCell: cell withFrame: frame inView: view];

    if(NSMouseInRect(point,checkFrame,[view isFlipped] ))
     return cell;
   }

   return nil;
}

-(BOOL)trackMouse:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView untilMouseUp:(BOOL)untilMouseUp {

    do {
     NSPoint point=[controlView convertPoint:[event locationInWindow] fromView:nil];

     [_clickPathComponentCell release];
     _clickPathComponentCell=[[self pathComponentCellAtPoint:point withFrame:cellFrame inView:controlView] retain];

     [controlView setNeedsDisplay:YES];

     event=[[controlView window] nextEventMatchingMask:NSLeftMouseUpMask|NSLeftMouseDraggedMask];

    } while ([event type] != NSLeftMouseUp);

    return (_clickPathComponentCell!=nil);
}

- (NSPathComponentCell *)clickedPathComponentCell {
   return _clickPathComponentCell;
}

-(NSArray *)pathComponentCells {
	return _pathComponentCells;
}

- (void)setPathComponentCells:(NSArray *)cells {
   cells=[cells retain];
   [_pathComponentCells release];
   _pathComponentCells=cells;

   [_clickPathComponentCell release];
   _clickPathComponentCell=nil;

   [[self controlView] setNeedsDisplay: YES];
}

- (SEL)doubleAction {
	return _doubleAction;
}

- (void)setDoubleAction:(SEL)action {
	_doubleAction = action;
}

-(NSURL *)URL {
	return _URL;
}

-(void)setURL:(NSURL *)url {
   url=[url copy];
   [_URL release];
   _URL=url;

   NSMutableArray *cells=[NSMutableArray array];

   if (url!=nil) {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSWorkspace *ws = [NSWorkspace sharedWorkspace];
    BOOL      isFileURL = [url isFileURL];
    NSString *host = [url host];
    NSString *path = [url path];
    NSString *scheme = [url scheme];
    Class pcClass = [[self class] pathComponentCellClass];

    NSArray         *pathComponents = [path pathComponents];
    NSMutableString *currentPath = [NSMutableString string];

    for (NSString *path in pathComponents) {
     [currentPath appendString: @"/"];
     [currentPath appendString: path];

     NSURL    *currentURL = [[[NSURL alloc] initWithScheme: scheme host: host path: currentPath] autorelease];
     NSString *title;
     NSImage  *image;

     if (isFileURL) {
      title = [fm displayNameAtPath: currentPath];
      image = [ws iconForFile: currentPath];
     }
     else {
      title=[path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      image=nil;
     }

     NSPathComponentCell *cell = [[[pcClass alloc] initTextCell: nil] autorelease];
     [cell setURL: currentURL];
     [cell setImage: image];
     [cell setStringValue: title];

     [cells addObject: cell];
    }
   }

   [self setPathComponentCells: cells];
}

-delegate {
   return _delegate;
}

-(void)setDelegate:(id)delegate {
   _delegate = delegate;
}

-(void)drawWithFrame:(NSRect)frame inView:(NSView *)view {
	[_backgroundColor set];
	[NSBezierPath fillRect: frame];

// Draw them last to first to get the proper overlapping arrows drawing

    NSInteger count=[_pathComponentCells count];

    while(--count>=0){
     NSPathComponentCell *cell=[_pathComponentCells objectAtIndex:count];
     NSRect cellFrame = [self rectOfPathComponentCell: cell withFrame: frame inView: view];
     [cell drawWithFrame: cellFrame inView: view];
	}
}

@end


text:
package ua.projects.javatests.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ua.projects.javatests.addressbook.model.ContactData;
import ua.projects.javatests.addressbook.model.GroupData;
import ua.projects.javatests.addressbook.model.Groups;

import java.io.File;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class ContactInGroupTests extends TestBase{

    @BeforeMethod
    public void ensureContactPreconditions() {
        if (app.db().contacts().size() == 0) {
            File photo = new File("src/test/resources/batman.jpg");
            app.contact().create(new ContactData().withFirstName("Anton").withLastName("Tarasovich").withNickname("Hammer").withWorkPlace("MGID")
                    .withAddress("Kiev, Dovzhenko str. 3, app. 21").withHomePhone("111-11-11").withMobilePhone("222-22-22").withWorkPhone("333-33-33")
                    .withFirstEmail("anton.tarasovich@mgid.com").withSecondEmail("vasya111@mail.ru").withThirdEmail("petya72@meta.ua").withPhoto(photo));
        }
    }

    @BeforeMethod
    public void ensureGroupPreconditions() {
        if (app.db().groups().size() == 0) {
            app.goTo().groupPage();
            app.group().create(new GroupData().withName("test1"));
        }
    }

    @Test(priority = 1)
    public void testInsertContactInGroup() {
        app.goTo().goToHomePage();
        if  (app.db().contacts().size() == 0) {
            File photo = new File("src/test/resources/batman.jpg");
            Groups groups = app.db().groups();
            ContactData newContact = new ContactData().withFirstName("Anton").withLastName("Tarasovich").withNickname("Hammer").withWorkPlace("MGID")
                    .withAddress("Kiev, Dovzhenko str. 3, app. 21").withHomePhone("111-11-11").withMobilePhone("222-22-22").withWorkPhone("333-33-33")
                    .withFirstEmail("anton.tarasovich@mgid.com").withSecondEmail("vasya111@mail.ru").withThirdEmail("petya72@meta.ua").withPhoto(photo)
                    .inGroup(groups.iterator().next());
            app.goTo().goToHomePage();
            app.contact().create(newContact);
        }
        ContactData contact = app.db().contacts().iterator().next();
        int contactId = contact.getId();
        Groups before = app.db().contactInGroup(contactId);
        app.contact().selectContactById(contactId);
        if (contactIsInAllGroups(contact)) {
            GroupData group = app.contact().createNewGroupForContact();
            app.contact().selectContactById(contactId);
            app.contact().addSelectedContactToGroup(group.getName());
        }
        GroupData group = app.db().groups().iterator().next();
        app.contact().addSelectedContactToGroup(group.getName());
        Groups after = app.db().contactInGroup(contactId);
        assertThat(after, equalTo(before.withAdded(group)));
    }

    @Test(priority = 2)
    public void testDeleteContactFromGroup() {
        app.goTo().goToHomePage();
        GroupData group = app.db().groupWithContact();
        String groupName = group.getName();
        app.group().selectGroupWithContact(groupName);
        int contactId = app.contact().getContactId();
        Groups before = app.db().contactInGroup(contactId);
        app.group().removeFromGroup();
        Groups after = app.db().contactInGroup(contactId);
        app.goTo().goToHomePage();
        app.group().selectAllGroups();
        assertThat(after, equalTo(before.withoutAdded(group)));
    }

    public boolean contactIsInAllGroups(ContactData contact) {
        Groups groups = app.db().groups();
        Groups contactGroups = contact.getGroups();
        return groups.equals(contactGroups);
    }

    @Test
    public String groupWithContact() {
        String name = "";
        Groups groups = app.db().groups();
        for (GroupData group : groups) {
            if (group.getContacts().size() > 0) {
                name = group.getName();
                break;
            }
        }
        System.out.println(name);
        return name;
    }

}


text:
require_relative 'messages'

module PerformLater
  module Logging

    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def logger
        PerformLater.logger
      end
    end

    def logger
      self.class.logger
    end
  end
end


text:
#ifndef QPID_STORE_MSCLFS_MESSAGELOG_H
#define QPID_STORE_MSCLFS_MESSAGELOG_H

#include <boost/intrusive_ptr.hpp>
#include <qpid/broker/PersistableMessage.h>
#include <qpid/broker/RecoveryManager.h>
#include <qpid/sys/IntegerTypes.h>
#include <qpid/store/StorageProvider.h>

#include "Log.h"

namespace qpid {
namespace store {
namespace ms_clfs {

/**
 * @class MessageLog
 *
 * Represents a CLFS-housed message log.
 */
class MessageLog : public Log {

protected:
    // Message log needs to have a no-op first record written in the log
    // to ensure that no real message gets an ID 0.
    virtual void initialize();

public:
    // Inherited and reimplemented from Log. Figure the minimum marshalling
    // buffer size needed for the records this class writes.
    virtual uint32_t marshallingBufferSize();

    // Add the specified message to the log; Return the persistence Id.
    uint64_t add(const boost::intrusive_ptr<qpid::broker::PersistableMessage>& msg);

    // Write a Delete entry for messageId. If newFirstId is not 0, it is now
    // the earliest valid message in the log, so move the tail up to it.
    void deleteMessage(uint64_t messageId, uint64_t newFirstId);

    // Load part or all of a message's content from previously stored
    // log record(s).
    void loadContent(uint64_t messageId,
                     std::string& data,
                     uint64_t offset,
                     uint32_t length);

    // Enqueue and dequeue operations track messages' transit across
    // queues; each operation may be associated with a transaction. If
    // the transactionId is 0 the operation is not associated with a
    // transaction.
    void recordEnqueue (uint64_t messageId,
                        uint64_t queueId,
                        uint64_t transactionId);
    void recordDequeue (uint64_t messageId,
                        uint64_t queueId,
                        uint64_t transactionId);

    // Recover the messages and their queueing records from the log.
    // @param recoverer  Recovery manager used to recreate broker objects from
    //                   encoded framing buffers recovered from the log.
    // @param messageMap This method fills in the map of id -> ptr of
    //                   recovered messages.
    // @param messageOps This method fills in the map of msg id ->
    //                   vector of operations involving the message that were
    //                   recovered from the log. It is the caller's
    //                   responsibility to sort the operations out and
    //                   ascertain which operations should be acted on. The
    //                   order of operations in the vector is as they were
    //                   read in order from the log.
    typedef enum { RECOVERED_ENQUEUE = 1, RECOVERED_DEQUEUE } RecoveredOpType;
    struct RecoveredMsgOp {
        RecoveredOpType op;
        uint64_t queueId;
        uint64_t txnId;

        RecoveredMsgOp(RecoveredOpType o, const uint64_t& q, const uint64_t& t)
            : op(o), queueId(q), txnId(t) {}
    };
    void recover(qpid::broker::RecoveryManager& recoverer,
                 qpid::store::MessageMap& messageMap,
                 std::map<uint64_t, std::vector<RecoveredMsgOp> >& messageOps);
};

}}}  // namespace qpid::store::ms_clfs

#endif /* QPID_STORE_MSCLFS_MESSAGELOG_H */


text:
namespace SpielGut.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Organization
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Organization()
        {
            this.Clubs = new HashSet<Club>();
        }

        public System.Guid ID { get; set; }
        public Nullable<System.DateTime> ValidTo { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Street { get; set; }
        public int ZipCode { get; set; }
        public string City { get; set; }
        public System.Guid FK_OrganizationManagement { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Club> Clubs { get; set; }
        public virtual OrganizationManagement OrganizationManagement { get; set; }
    }
}


text: Write overview of core services and service docs TOC here.


text:
Prerequisites
=============
To compile and run QFS you need to have the following software packages
installed in your development system.

| RHEL/CentOS      | Debian/Ubuntu        | OS X    | Cygwin             | Notes                                                                                |
|------------------|----------------------|---------|--------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
| `gcc-g++`        | `gcc`                |         | `gcc-g++`          |                                                                                |
| `make`           | `make`               |         | `make`             |                                                                                |
| `git`            | `git`                |         | `git`              | version 1.7.10 or higher                                                                                |
| `cmake`          | `cmake`              | `cmake` | `cmake`            | version 2.8.4 or higher                                                                                |
| `maven`          | `maven2`             | `maven` |                    | version 3.0.3 or higher                                                                                |
| `boost-devel`    | `libboost-regex-dev` | `boost` | `libboost-devel`   | version 1.3.4 or higher (for mac, may need to install boost with `'-no_single'` option if only the `/opt/local/lib/*-mt.dylib` are installed) |
| `krb5-devel`     | `libkrb5-dev`        |         | `libkrb5-devel`    |                                                                                |
| `openssl-devel`  | `libssl-dev`         |         | `openssl-devel`    |                                                                                |
| `python-devel`   | `python-dev`         |         |                    | for python bindings                                                                                |
| `fuse-devel`     | `libfuse-dev`        |         |                    | for FUSE bindings                                                                                |
| `java-openjdk`   | `default-jdk`        |         |                    | for java access                                                                                |
| `java-devel`     |                      |         |                    | for java access                                                                                |
| `libuuid-devel`  |                      |         |                    |                                                                                |
|                  |                      | `Xcode` |                    |                                                                                |
|                  |                      |         | `bzip2`            |                                                                                |
|                  |                      |         | `autoconf`         |                                                                                |
|                  |                      |         | `automake`         |                                                                                |
|                  |                      |         | `libstdc++6-devel` |                                                                                |

Repository Organization
=======================
```
    QFS top-level directory
    │
    ├──── benchmarks
    │     └──── mstress                (Benchmark comparing meta operations)
    │
    ├──── build                        (Build output directory)
    │
    ├──── examples
    │     ├──── cc                     (C++ client example)
    │     ├──── java                   (Java client example)
    │     ├──── python                 (Experimental python client example)
    │     └──── sampleservers          (Scripts to bring up local QFS for testing)
    │
    ├──── contrib                      (Contributions including sample deployment packages)
    │
    ├──── conf                         (Sample configs for release packaging)
    │
    ├──── scripts                      (Admin and init scripts)
    │
    ├──── webui                        (metaserver web UI monitor)
    │
    └──── src
          │
          ├──── cc
          │     ├──── access           (Java/Python glue code)
          │     ├──── chunk            (chunk server code)
          │     ├──── common           (common declarations)
          │     ├──── devtools         (miscellaneous developer utilities & tools)
          │     ├──── emulator         (QFS offline layout emulator)
          │     ├──── fuse             (FUSE module for Linux and MacOS)
          │     ├──── kfsio            (I/O library used by QFS)
          │     ├──── libclient        (client library code)
          │     ├──── meta             (metaserver code)
          │     ├──── qcdio            (low level io and threading library)
          │     ├──── qcrs             (Reed-Solomon encoder and decoder)
          │     ├──── tests            (QFS tests)
          │     └──── tools            (QFS user/admin tools)
          │
          ├──── java
          │     ├──── qfs-access       (Java wrappers to call QFS-JNI code)
          │     └──── hadoop-qfs       (Apache Hadoop QFS plugin)
          │
          ├──── python                 (Experimental python client code)
          └──── test-scripts           (Scripts to test QFS servers and components)
```

Compiling The Source
====================
The top-level Makefile automatically compiles QFS and generates the server
binaries, client tools and client libraries. This section has information that
gives you greater control over the compile process. This section also provides
information to a developer who wants to write a QFS client application to access
files in QFS. The mode of execution of a QFS client application is as follows:

1. The application interacts with the QFS client library. The application can be
   written in C++, Java, or Python (python QFS adapter is in experimental
   stage).
1. The QFS client library, in turn, interfaces with the metaserver and/or chunk
   server(s).
1. If data is replicated, whenever there is a failure in a chunk server, the
   client library will fail-over to another chunk server that has the data; this
   fail-over is transparent to the application.

Compiling the C++ Code
------------------
Compiling the C++ code produces the metaserver, chunkserver, client, and admin
tool binaries. It also produces the C++ client library. We use **`cmake`** to
build the C++ code. You can use the top-level Makefile as a wrapper around cmake
to build the project by simply executing `make`.

Once the build is complete, you will find the build artifacts in the
`build/debug` directory.

### Types of Builds
The default build type is a release build. You can execute a debug build by
running `make BUILD_TYPE=debug CMAKE_OPTIONS=`. The build artifacts for this
build will be available in the `build/debug` directory.

Debug binaries are useful when developing QFS since they include debugging
symbols, greatly simplifying debugging. However, for a production deployment,
it is recommended to use release binaries with debugging info enabled (such as,
compile flags of "-O2 -g"). Having binaries with debugging info in production
simplifies debugging should a problem arise in a production environment.

### Verbose Build Output
To build with verbose output, use the environment variable `VERBOSE=true` to
build. For example, use `VERBOSE=true make`.

### `make test` Targets
To run qfs tests, use `make test`. This will ensure that all core functionality
is intact. Note that this test invokes the metaserver and chunk servers locally
and performs various checks, it may take a couple of minutes to complete. If you
are running this from a partition that is nearly full, the test may fail. Please
refer to `maxSpaceUtilizationThreshold` in [[Configuration Reference]].

#### Writing Tests
C++ tests are stored in `src/cc/tests`. QFS uses [Google Test][gt] as its
testing framework. Unit tests which test specific functionality in a function or
library can simply use a bare test, e.g. `TEST(Foo, Bar)`. However, all
integration tests (tests which interact with the metaserver or chunkserver)
should use test fixtures, subclassing the `QFSTest` class. For example, you
could add a new test class like so:

    #include <gtest/gtest.h>
    #include "tests/integtest.h"

    class FooTest : public QFSTest {
    public:
        virtual void SetUp() { ... }
        virtual void TearDown() { ... }
    };

    TEST_F(FooTest, TestBar) {
        ...
    }

Furthermore, you should place tests in the corresponding directory for which
functionality you are testing. For example, if you are testing functionality for
code stored in the `libclient` directory, place the tests in
`src/cc/tests/libclient`. Either a unit or integration test should be added for
each functionality change to QFS. Please see the tests in `src/cc/tests` for
some examples on how QFS has already implemented various tests.

### Developing a C++ client
To develop a c++ client, see the sample code in the
`examples/cc/qfssample_main.cc` file. The QFS client library API is
defined in `src/cc/libclient/KfsClient.h`.

The C++ client should link with libqfs\_client library and other libqfs\_
dependencies. Note that default build will contain libraries built with the
"Debug" option. This library code in this mode is "very chatty". Hence, it is
recommended that you use the libraries built with "Release" option with your
applications.

Compiling Java Side
-------------------
Compile the Java code to get the QFS access jar (which contains the wrapper
calls to native C++ via JNI; this allows Java apps to access files stored in
QFS) and the Apache Hadoop QFS plugin jar. The Apache Hadoop QFS plugin includes
the QFS access classes within, therefore, someone who wants to use QFS with
Hadoop will only need to use one extra jar file.

Apache Maven is used to build Java jars. Use the top-level makefile (`make
java`) to build the java jars.

### Developing a Java Client
For Java applications, we use the JNI interface to get at the C++ QFS client
library code from Java applications. One should refer to the Java client example
at `examples/java/QfsSample.java`. The QFS Java client library API is
defined in
`src/java/qfs-access/src/main/java/com/quantcast/qfs/access/KfsAccess.java`.

The Java compiler should have
`build/java/qfs-access/qfs-access-<version>.jar` in the `CLASSPATH`. In
addition, to execute the client, `build/release/lib` should be in
the `LD_LIBRARY_PATH` (or `DYLD_LIBRARY_PATH`, if it is Mac OS X).
To build,

    $ cd ~/code/qfs/examples/java
    $ qfsjar=`echo ../../build/qfs-access/qfs-access*.jar`
    $ javac -classpath "$qfsjar" QfsSample.java

To execute,

    $ libdir="`cd ../../build/release/lib && pwd`"
    $ export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${libdir}"
    $ qfsjar=`echo ../../build/qfs-access/qfs-access*.jar`
    $ java -Djava.library.path="$libdir" -classpath ".:$qfsjar" QfsSample 127.0.0.1 20000

Compiling Python Side (Experimental)
------------------------------------
Python applications can access QFS by using the python extension module. This
section describes how to build and install the python extension module. To build
the python module, use the command `make python`. The file
`build/build/<distdir>/qfs.so` will be created at the end.

### Developing a Python Client
Python applications use the python QFS extension module, `qfs.so`, to get at the
C++ QFS client library. The example program
`examples/python/qfssample.py` illustrates how to write a Python client for QFS.

Set `PYTHONPATH` accordingly if you are using a `qfs.so` install path different
from the default path, so that the python run-time can detect the `qfs.so`.
Also, ensure that `LD_LIBRARY_PATH` has the path to the QFS libraries. For
example,

    $ export PYTHONPATH=/usr/lib/python2.7/dist-packages:$PYTHONPATH
    $ export LD_LIBRARY_PATH=/usr/lib/python2.7/dist-packages/qfs:$LD_LIBRARY_PATH
    $ python examples/python/qfssample.py

![Quantcast](//pixel.quantserve.com/pixel/p-9fYuixa7g_Hm2.gif?labels=opensource.qfs.wiki)

[gt]: https://github.com/google/googletest