text:
package com.baidu.palo.qe;

import com.baidu.palo.common.InternalException;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "org.apache.log4j.*"})
@PrepareForTest({HelpModule.class, HelpObjectLoader.class})
public class HelpModuleTest {
    private List<HelpCategory> categories;
    private List<HelpTopic> topics;

    // Category
    //  Admin
    //      - Show
    //      - Select
    // Topic
    //      - SHOW TABLES
    //      - SELECT TIME
    @Before
    public void setUp() {
        categories = Lists.newArrayList();
        topics = Lists.newArrayList();

        HelpCategory category = new HelpCategory();
        Map<String, String> map = Maps.newHashMap();
        map.put("parent", "Admin");
        Map.Entry<String, Map<String, String>> entry = Maps.immutableEntry("Show", map);
        category.loadFrom(entry);
        categories.add(category);

        category = new HelpCategory();
        map = Maps.newHashMap();
        map.put("parent", "Admin");
        entry = Maps.immutableEntry("Select", map);
        category.loadFrom(entry);
        categories.add(category);

        category = new HelpCategory();
        map = Maps.newHashMap();
        entry = Maps.immutableEntry("Admin", map);
        category.loadFrom(entry);
        categories.add(category);

        // Topic
        HelpTopic topic = new HelpTopic();
        map = Maps.newHashMap();
        map.put("keyword", "SHOW, TABLES");
        map.put("category", "Show");
        entry = Maps.immutableEntry("SHOW TABLES", map);
        topic.loadFrom(entry);
        topics.add(topic);

        topic = new HelpTopic();
        map = Maps.newHashMap();
        map.put("keyword", "SELECT");
        map.put("category", "Select");
        entry = Maps.immutableEntry("SELECT TIME", map);
        topic.loadFrom(entry);
        topics.add(topic);

        // emtpy
        topic = new HelpTopic();
        map = Maps.newHashMap();
        entry = Maps.immutableEntry("empty", map);
        topic.loadFrom(entry);
        topics.add(topic);
    }

    @Test
    public void testNormal() throws IOException, InternalException {
        // Mock
        // HelpObjectLoader categoryLoader = EasyMock.createMock(HelpObjectLoader.class);
        // EasyMock.expect(categoryLoader.loadAll(EasyMock.isA(String.class))).andReturn(categories).anyTimes();
        // EasyMock.replay(categoryLoader);
        // HelpObjectLoader topicLoader = EasyMock.createMock(HelpObjectLoader.class);
        // EasyMock.expect(topicLoader.loadAll(EasyMock.isA(String.class))).andReturn(topics).anyTimes();
        // EasyMock.replay(topicLoader);
        // PowerMock.mockStatic(HelpObjectLoader.class);
        // EasyMock.expect(HelpObjectLoader.createCategoryLoader()).andReturn(categoryLoader).anyTimes();
        // EasyMock.expect(HelpObjectLoader.createTopicLoader()).andReturn(topicLoader).anyTimes();
        // PowerMock.replay(HelpObjectLoader.class);

        HelpModule module = new HelpModule();
        URL help = getClass().getClassLoader().getResource("data/help");
        module.setUp(help.getPath());

        HelpTopic topic = module.getTopic("SELECT TIME");
        Assert.assertNotNull(topic);

        topic = module.getTopic("select time");
        Assert.assertNotNull(topic);

        // Must ordered by alpha.
        List<String> categories = module.listCategoryByCategory("Admin");
        Assert.assertEquals(2, categories.size());
        Assert.assertTrue(Arrays.equals(categories.toArray(), Lists.newArrayList("Select", "Show").toArray()));
        // topics
        List<String> topics = module.listTopicByKeyword("SHOW");
        Assert.assertEquals(1, topics.size());
        Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray()));

        topics = module.listTopicByKeyword("SELECT");
        Assert.assertEquals(1, topics.size());
        Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray()));

        topics = module.listTopicByCategory("selEct");
        Assert.assertEquals(1, topics.size());
        Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray()));

        topics = module.listTopicByCategory("show");
        Assert.assertEquals(1, topics.size());
        Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray()));

        Assert.assertTrue(Arrays.equals(module.listCategoryByName("ADMIN").toArray(),
                Lists.newArrayList("Admin").toArray()));
    }

    @Test
    public void testLoadFromZip() throws IOException, InternalException {
        HelpModule module = new HelpModule();
        URL help = getClass().getClassLoader().getResource("test-help-resource.zip");
        module.setUpByZip(help.getPath());

        HelpTopic topic = module.getTopic("SELECT TIME");
        Assert.assertNotNull(topic);

        topic = module.getTopic("select time");
        Assert.assertNotNull(topic);

        // Must ordered by alpha.
        List<String> categories = module.listCategoryByCategory("Admin");
        Assert.assertEquals(2, categories.size());
        Assert.assertTrue(Arrays.equals(categories.toArray(), Lists.newArrayList("Select", "Show").toArray()));
        // topics
        List<String> topics = module.listTopicByKeyword("SHOW");
        Assert.assertEquals(1, topics.size());
        Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray()));

        topics = module.listTopicByKeyword("SELECT");
        Assert.assertEquals(1, topics.size());
        Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray()));

        topics = module.listTopicByCategory("selEct");
        Assert.assertEquals(1, topics.size());
        Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray()));

        topics = module.listTopicByCategory("show");
        Assert.assertEquals(1, topics.size());
        Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray()));

        Assert.assertTrue(Arrays.equals(module.listCategoryByName("ADMIN").toArray(),
                Lists.newArrayList("Admin").toArray()));
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Tile : MonoBehaviour
{
    public int x, y;
    public int gold, food, production, tourism, faith, science, culture;
    public List<Tile> neighbours = new List<Tile>();
    public enum tiletype { plain, forest, jungle, desert, shore, ocean, mountain, hill, swamp, tundra };
}

redpajama_set_name: RedPajamaGithub


text:
package httpexpect

import (
	"reflect"
)

// Object provides methods to inspect attached map[string]interface{} object
// (Go representation of JSON object).
type Object struct {
	chain chain
	value map[string]interface{}
}

// NewObject returns a new Object given a reporter used to report failures
// and value to be inspected.
//
// Both reporter and value should not be nil. If value is nil, failure is
// reported.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
func NewObject(reporter Reporter, value map[string]interface{}) *Object {
	chain := makeChain(reporter)
	if value == nil {
		chain.fail("expected non-nil map value")
	} else {
		value, _ = canonMap(&chain, value)
	}
	return &Object{chain, value}
}

// Raw returns underlying value attached to Object.
// This is the value originally passed to NewObject, converted to canonical form.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  assert.Equal(t, map[string]interface{}{"foo": 123.0}, object.Raw())
func (o *Object) Raw() map[string]interface{} {
	return o.value
}

// Path is similar to Value.Path.
func (o *Object) Path(path string) *Value {
	return getPath(&o.chain, o.value, path)
}

// Schema is similar to Value.Schema.
func (o *Object) Schema(schema interface{}) *Object {
	checkSchema(&o.chain, o.value, schema)
	return o
}

// Keys returns a new Array object that may be used to inspect objects keys.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123, "bar": 456})
//  object.Keys().ContainsOnly("foo", "bar")
func (o *Object) Keys() *Array {
	keys := []interface{}{}
	for k := range o.value {
		keys = append(keys, k)
	}
	return &Array{o.chain, keys}
}

// Values returns a new Array object that may be used to inspect objects values.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123, "bar": 456})
//  object.Values().ContainsOnly(123, 456)
func (o *Object) Values() *Array {
	values := []interface{}{}
	for _, v := range o.value {
		values = append(values, v)
	}
	return &Array{o.chain, values}
}

// Value returns a new Value object that may be used to inspect single value
// for given key.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  object.Value("foo").Number().Equal(123)
func (o *Object) Value(key string) *Value {
	value, ok := o.value[key]
	if !ok {
		o.chain.fail("\nexpected object containing key '%s', but got:\n%s",
			key, dumpValue(o.value))
		return &Value{o.chain, nil}
	}
	return &Value{o.chain, value}
}

// Empty succeedes if object is empty.
//
// Example:
//  object := NewObject(t, map[string]interface{}{})
//  object.Empty()
func (o *Object) Empty() *Object {
	return o.Equal(map[string]interface{}{})
}

// NotEmpty succeedes if object is non-empty.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  object.NotEmpty()
func (o *Object) NotEmpty() *Object {
	return o.NotEqual(map[string]interface{}{})
}

// Equal succeedes if object is equal to another object.
// Before comparison, both objects are converted to canonical form.
//
// value should map[string]interface{} or struct.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  object.Equal(map[string]interface{}{"foo": 123})
func (o *Object) Equal(value interface{}) *Object {
	expected, ok := canonMap(&o.chain, value)
	if !ok {
		return o
	}
	if !reflect.DeepEqual(expected, o.value) {
		o.chain.fail("\nexpected object equal to:\n%s\n\nbut got:\n%s\n\ndiff:\n%s",
			dumpValue(expected),
			dumpValue(o.value),
			diffValues(expected, o.value))
	}
	return o
}

// NotEqual succeedes if object is not equal to another object.
// Before comparison, both objects are converted to canonical form.
//
// value should map[string]interface{} or struct.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  object.Equal(map[string]interface{}{"bar": 123})
func (o *Object) NotEqual(v interface{}) *Object {
	expected, ok := canonMap(&o.chain, v)
	if !ok {
		return o
	}
	if reflect.DeepEqual(expected, o.value) {
		o.chain.fail("\nexpected object not equal to:\n%s",
			dumpValue(expected))
	}
	return o
}

// ContainsKey succeedes if object contains given key.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  object.ContainsKey("foo")
func (o *Object) ContainsKey(key string) *Object {
	if !o.containsKey(key) {
		o.chain.fail("\nexpected object containing key '%s', but got:\n%s",
			key, dumpValue(o.value))
	}
	return o
}

// NotContainsKey succeedes if object doesn't contain given key.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  object.NotContainsKey("bar")
func (o *Object) NotContainsKey(key string) *Object {
	if o.containsKey(key) {
		o.chain.fail(
			"\nexpected object not containing key '%s', but got:\n%s", key,
			dumpValue(o.value))
	}
	return o
}

// ContainsMap succeedes if object contains given sub-object.
// Before comparison, both objects are converted to canonical form.
//
// value should map[string]interface{} or struct.
//
// Example:
//  object := NewObject(t, map[string]interface{}{
//      "foo": 123,
//      "bar": []interface{}{"x", "y"},
//      "bar": map[string]interface{}{
//          "a": true,
//          "b": false,
//      },
//  })
//
//  object.ContainsMap(map[string]interface{}{  // success
//      "foo": 123,
//      "bar": map[string]interface{}{
//          "a": true,
//      },
//  })
//
//  object.ContainsMap(map[string]interface{}{  // failure
//      "foo": 123,
//      "qux": 456,
//  })
//
//  object.ContainsMap(map[string]interface{}{  // failure, slices should match exactly
//      "bar": []interface{}{"x"},
//  })
func (o *Object) ContainsMap(value interface{}) *Object {
	if !o.containsMap(value) {
		o.chain.fail("\nexpected object containing sub-object:\n%s\n\nbut got:\n%s",
			dumpValue(value), dumpValue(o.value))
	}
	return o
}

// NotContainsMap succeedes if object doesn't contain given sub-object exactly.
// Before comparison, both objects are converted to canonical form.
//
// value should map[string]interface{} or struct.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123, "bar": 456})
//  object.NotContainsMap(map[string]interface{}{"foo": 123, "bar": "no-no-no"})
func (o *Object) NotContainsMap(value interface{}) *Object {
	if o.containsMap(value) {
		o.chain.fail("\nexpected object not containing sub-object:\n%s\n\nbut got:\n%s",
			dumpValue(value), dumpValue(o.value))
	}
	return o
}

// ValueEqual succeedes if object's value for given key is equal to given value.
// Before comparison, both values are converted to canonical form.
//
// value should map[string]interface{} or struct.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  object.ValueEqual("foo", 123)
func (o *Object) ValueEqual(key string, value interface{}) *Object {
	if !o.containsKey(key) {
		o.chain.fail("\nexpected object containing key '%s', but got:\n%s",
			key, dumpValue(o.value))
		return o
	}
	expected, ok := canonValue(&o.chain, value)
	if !ok {
		return o
	}
	if !reflect.DeepEqual(expected, o.value[key]) {
		o.chain.fail(
			"\nexpected value for key '%s' equal to:\n%s\n\nbut got:\n%s\n\ndiff:\n%s",
			key,
			dumpValue(expected),
			dumpValue(o.value[key]),
			diffValues(expected, o.value[key]))
	}
	return o
}

// ValueNotEqual succeedes if object's value for given key is not equal to given value.
// Before comparison, both values are converted to canonical form.
//
// value should map[string]interface{} or struct.
//
// If object doesn't contain any value for given key, failure is reported.
//
// Example:
//  object := NewObject(t, map[string]interface{}{"foo": 123})
//  object.ValueNotEqual("foo", "bad value")  // success
//  object.ValueNotEqual("bar", "bad value")  // failure! (key is missing)
func (o *Object) ValueNotEqual(key string, value interface{}) *Object {
	if !o.containsKey(key) {
		o.chain.fail("\nexpected object containing key '%s', but got:\n%s",
			key, dumpValue(o.value))
		return o
	}
	expected, ok := canonValue(&o.chain, value)
	if !ok {
		return o
	}
	if reflect.DeepEqual(expected, o.value[key]) {
		o.chain.fail("\nexpected value for key '%s' not equal to:\n%s",
			key, dumpValue(expected))
	}
	return o
}

func (o *Object) containsKey(key string) bool {
	for k := range o.value {
		if k == key {
			return true
		}
	}
	return false
}

func (o *Object) containsMap(sm interface{}) bool {
	submap, ok := canonMap(&o.chain, sm)
	if !ok {
		return false
	}
	return checkContainsMap(o.value, submap)
}

func checkContainsMap(outer, inner map[string]interface{}) bool {
	for k, iv := range inner {
		ov, ok := outer[k]
		if !ok {
			return false
		}
		if ovm, ok := ov.(map[string]interface{}); ok {
			if ivm, ok := iv.(map[string]interface{}); ok {
				if !checkContainsMap(ovm, ivm) {
					return false
				}
				continue
			}
		}
		if !reflect.DeepEqual(ov, iv) {
			return false
		}
	}
	return true
}


text:
package controller;

import model.ApplicationMsg;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import wtf.socket.controller.WTFSocketController;
import wtf.socket.exception.WTFSocketException;
import wtf.socket.exception.fatal.WTFSocketInvalidSourceException;
import wtf.socket.protocol.WTFSocketMsg;
import wtf.socket.routing.item.WTFSocketRoutingItem;
import wtf.socket.routing.item.WTFSocketRoutingTmpItem;

import java.util.List;

/**
 * 注册功能
 */
@Controller
public class RegisterController implements WTFSocketController {

    @Override
    public boolean isResponse(WTFSocketMsg msg) {
        ApplicationMsg body = msg.getBody(ApplicationMsg.class);
        return body.getCmd() != null &&
                body.getCmd() == 64;
    }

    @Override
    public boolean work(WTFSocketRoutingItem item, WTFSocketMsg msg, List<WTFSocketMsg> responses) throws WTFSocketException{

        final ApplicationMsg body = msg.getBody(ApplicationMsg.class);

        if (!(item instanceof WTFSocketRoutingTmpItem)) {
            throw new WTFSocketInvalidSourceException("[" + msg.getFrom() + "] has registered" );
        }

        item.setAddress(msg.getFrom());
        item.setAccept(msg.getVersion());

        if (body.hasParams())
            item.setDeviceType(body.firstParam().getString("deviceType"));

        if (StringUtils.startsWith(msg.getFrom(), "Debug_")) {
            ((WTFSocketRoutingTmpItem) item).shiftToDebug();
        }else {
            item.setCover(false);
            ((WTFSocketRoutingTmpItem) item).shiftToFormal();
        }

        final WTFSocketMsg response = msg.makeResponse();
        response.setBody(ApplicationMsg.success());
        responses.add(response);

        return true;
    }
}


text:
'''
motion.py: part of mriqc package

'''
import numpy as np
import pylab as plt
import seaborn as sns
from mriqc.misc import plot_vline
from matplotlib.figure import Figure
from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas
from matplotlib.gridspec import GridSpec

def calc_frame_dispalcement(realignment_parameters_file):
    lines = open(realignment_parameters_file, 'r').readlines()
    rows = [[float(x) for x in line.split()] for line in lines]
    cols = np.array([list(col) for col in zip(*rows)])

    translations = np.transpose(np.abs(np.diff(cols[0:3, :])))
    rotations = np.transpose(np.abs(np.diff(cols[3:6, :])))

    FD_power = np.sum(translations, axis = 1) + (50*3.141/180)*np.sum(rotations, axis =1)

    #FD is zero for the first time point
    FD_power = np.insert(FD_power, 0, 0)

    return FD_power

def get_mean_frame_displacement_disttribution(realignment_parameters_files):
    mean_FDs = []
    max_FDs = []
    for realignment_parameters_file in realignment_parameters_files:
        FD_power = calc_frame_dispalcement(realignment_parameters_file)
        mean_FDs.append(FD_power.mean())
        max_FDs.append(FD_power.max())

    return mean_FDs, max_FDs

def plot_frame_displacement(realignment_parameters_file, mean_FD_distribution=None, figsize=(11.7,8.3)):

    FD_power = calc_frame_dispalcement(realignment_parameters_file)

    fig = Figure(figsize=figsize)
    FigureCanvas(fig)

    if mean_FD_distribution:
        grid = GridSpec(2, 4)
    else:
        grid = GridSpec(1, 4)

    ax = fig.add_subplot(grid[0,:-1])
    ax.plot(FD_power)
    ax.set_xlim((0, len(FD_power)))
    ax.set_ylabel("Frame Displacement [mm]")
    ax.set_xlabel("Frame number")
    ylim = ax.get_ylim()

    ax = fig.add_subplot(grid[0,-1])
    sns.distplot(FD_power, vertical=True, ax=ax)
    ax.set_ylim(ylim)

    if mean_FD_distribution:
        ax = fig.add_subplot(grid[1,:])
        sns.distplot(mean_FD_distribution, ax=ax)
        ax.set_xlabel("Mean Frame Dispalcement (over all subjects) [mm]")
        MeanFD = FD_power.mean()
        label = "MeanFD = %g"%MeanFD
        plot_vline(MeanFD, label, ax=ax)

    return fig


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Page Not Found - GEC MIJ Nigeria</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

        GEC-MIJ Services
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              About

              Services

                Projects

                Key Projects
                Ongoing Projects
                Union Bank Projects

              Contact

404
        Page Not Found

          Home

404

404

The page you're looking for could not be found. Here are some helpful links to get you back on track:

            Home

            About

            Services

            Portfolio

                1 Column Portfolio

                2 Column Portfolio

                3 Column Portfolio

                4 Column Portfolio

            Contact

Copyright © Your Website 2017


text:
import '/resources/polymer/@polymer/polymer/lib/elements/dom-module.js';
import '/resources/polymer/@polymer/paper-styles/color.js';

const styleElement = document.createElement('dom-module');
styleElement.innerHTML = `
    <template>
        <style>
            tg-accordion {
                margin-bottom: 20px;
                --tg-accordion-selected-heading-background-color: var(--paper-light-blue-700);
                --tg-accordion-selected-heading-color: white;
                --tg-accordion-selected-label-color: white;
            }
            paper-radio-button {
                margin: 10px;
                --paper-radio-button-checked-color: var(--paper-light-blue-700);
                --paper-radio-button-checked-ink-color: var(--paper-light-blue-700);
                font-family: 'Roboto', 'Noto', sans-serif;
            }
            paper-radio-button {
                --calculated-paper-radio-button-ink-size: 36px;
            }
        </style>
    </template>
`;
styleElement.register('tg-accordion-with-radio-buttons-styles');


text: package upper_snake;


text:
package org.apache.servicemix.jbi.deployer.task;

import org.apache.servicemix.jbi.deployer.AdminCommandsService;
import org.apache.tools.ant.BuildException;

/**
 * Start a Component
 *
 * @version $Revision$
 */
public class StartComponentTask extends JbiTask {

    private String name;

    /**
     * @return Returns the component name.
     */
    public String getName() {
        return name;
    }

    /**
     * @param name The componentName to set.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * execute the task
     *
     * @throws BuildException
     */
    public void doExecute(AdminCommandsService acs) throws Exception {
        if (name == null) {
            throw new BuildException("null componentName");
        }
        acs.startComponent(name);
    }

}


text:
package util

import (
	"io"
)

// A Wrapper provides hard line wrapping and output limits to an io.Writer.
type Wrapper struct {
	w     io.Writer
	n     int
	width int
	limit int
}

// NewWrapper returns a Wrapper that causes wraps lines at width bytes and
// limits the number of bytes written to the provided limit.
func NewWrapper(w io.Writer, width, limit int) *Wrapper {
	return &Wrapper{
		w:     w,
		width: width,
		limit: limit,
	}
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// Write writes the lesser of len(p) or the Writer's limit bytes from p to
// the underlying data stream. It returns the number of bytes written from
// p (0 <= n <= len(p)) and any error encountered that caused the write to
// stop early, except the Writer's own limit.
func (w *Wrapper) Write(p []byte) (n int, err error) {
	if w.limit >= 0 {
		if w.n >= w.limit {
			return 0, nil
		}
		p = p[:min(w.limit-w.n, len(p))]
	}
	if w.width <= 0 {
		return w.w.Write(p)
	}
	var _n int
	for len(p) > 0 {
		if w.n != 0 && w.n%w.width == 0 {
			_n, err = w.w.Write([]byte{'\n'})
			n += _n
			if err != nil {
				return
			}
		}
		_n, err = w.w.Write(p[:min(w.width-w.n%w.width, len(p))])
		n += _n
		w.n += _n
		if err != nil {
			return
		}
		p = p[_n:]
	}
	return n, err
}


text:
package com.quiz.php.core;

import android.content.Context;
import android.util.DisplayMetrics;

/**
 * Created by fabricio on 3/31/14.
 */
public class Util {

    public static int dpToPx (Context context, int dp) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
}


text:
import { defineMessages } from 'react-intl';

export default defineMessages({
  title: {
    id: 'chenya.components.Banner.title',
    defaultMessage: '國產新型風機將問世',
  },
  subtitle: {
    id: 'chenya.components.Banner.subtitle',
    defaultMessage: '台灣之光',
  },
  more: {
    id: 'chenya.components.Banner.more',
    defaultMessage: '了解更多',
  },
});


text:
<spacer size="32"></spacer>

<wrapper class="no-padding-h">
	<container>
		<row>
			<columns class="show-for-large" large="6" small="12">

			</columns>
			<columns class="full-width-image" large="6" small="12">

			</columns>
		</row>
	</container>
</wrapper>


text:
namespace Ocelot.DependencyInjection
{
    using Configuration.File;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Configuration.Memory;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text.RegularExpressions;

    public static class ConfigurationBuilderExtensions
    {
        [Obsolete("Please set BaseUrl in ocelot.json GlobalConfiguration.BaseUrl")]
        public static IConfigurationBuilder AddOcelotBaseUrl(this IConfigurationBuilder builder, string baseUrl)
        {
            var memorySource = new MemoryConfigurationSource
            {
                InitialData = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("BaseUrl", baseUrl)
                }
            };

            builder.Add(memorySource);

            return builder;
        }

        public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, IWebHostEnvironment env)
        {
            return builder.AddOcelot(".", env);
        }

        public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, string folder, IWebHostEnvironment env)
        {
            const string primaryConfigFile = "ocelot.json";

            const string globalConfigFile = "ocelot.global.json";

            const string subConfigPattern = @"^ocelot\.(.*?)\.json$";

            string excludeConfigName = env?.EnvironmentName != null ? $"ocelot.{env.EnvironmentName}.json" : string.Empty;

            var reg = new Regex(subConfigPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);

            var files = new DirectoryInfo(folder)
                .EnumerateFiles()
                .Where(fi => reg.IsMatch(fi.Name) && (fi.Name != excludeConfigName))
                .ToList();

            var fileConfiguration = new FileConfiguration();

            foreach (var file in files)
            {
                if (files.Count > 1 && file.Name.Equals(primaryConfigFile, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                var lines = File.ReadAllText(file.FullName);

                var config = JsonConvert.DeserializeObject<FileConfiguration>(lines);

                if (file.Name.Equals(globalConfigFile, StringComparison.OrdinalIgnoreCase))
                {
                    fileConfiguration.GlobalConfiguration = config.GlobalConfiguration;
                }

                fileConfiguration.Aggregates.AddRange(config.Aggregates);
                fileConfiguration.ReRoutes.AddRange(config.ReRoutes);
            }

            var json = JsonConvert.SerializeObject(fileConfiguration);

            File.WriteAllText(primaryConfigFile, json);

            builder.AddJsonFile(primaryConfigFile, false, false);

            return builder;
        }
    }
}


text:
import React, { PropTypes } from 'react'
import * as I from 'immutable'
import Select from 'react-select'
import Styles from './styles.scss'

const noop = () => {}

const Searchbar = ({
  suggestions,
  onUpdate = noop,
  onSearch = noop,
  isSearching = false,
  query,
}) => {
  return (
    <div className={Styles.searchbar}>
      <Select
        value={query}
        isLoading={isSearching}
        onChange={({ value }) => onSearch(value)}
        options={suggestions.map(createOption).toJS()}
        onInputChange={onUpdate}/>
    </div>
  )
}

function createOption(suggestion) {
  return {
    value: suggestion,
    label: suggestion,
  }
}

Searchbar.propTypes = {
  suggestions: PropTypes.instanceOf(I.List).isRequired,
  onUpdate: PropTypes.func,
  onSearch: PropTypes.func,
  isSearching: PropTypes.bool,
  query: PropTypes.string.isRequired,
}

export default Searchbar


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

namespace XingZen.Core
{
    public class TransactionManager
    {
        private IAccountRepository _accountRepository;
        private ITransactionRepository _transactionRepository;

        public TransactionManager(IAccountRepository accountRepository, ITransactionRepository transactionRepository)
        {
            _accountRepository = accountRepository;
            _transactionRepository = transactionRepository;
        }

        public void Transfer(Guid sourceAccountId, Guid targetAccountId, decimal amount)
        {

        }

        public void Deposit(Guid accountId, decimal amount)
        {

        }
    }
}


text:
INSTANCE_NAME=$1
POSTGRES_ROLE=primary

source scripts/aws/config.sh

echo "Creating Postgres instance $INSTANCE_NAME..."
INSTANCE_ID=$(aws ec2 run-instances \
  --image-id $AMI_IMAGE_ID \
  --instance-type t2.micro \
  --key-name $KEY_NAME \
  --security-group-ids $SG_DEFAULT $SG_SSH_ACCESS $SG_POSTGRES \
  --user-data file://$(pwd)/scripts/aws/postgres/remote_provision.sh \
  --output text \
  --query 'Instances[*].InstanceId')
echo "Created instance $INSTANCE_ID..."

echo "Waiting for instance to be 'pending'..."
scripts/aws/base/wait_for_instance_state.sh $INSTANCE_ID pending

echo "Creating $INSTANCE_NAME name tag..."
TAG_RESPONSE=$(aws ec2 create-tags --resources $INSTANCE_ID --tags Key=Name,Value=$INSTANCE_NAME)

echo "Creating PostgresRole=$POSTGRES_ROLE tag..."
TAG_RESPONSE=$(aws ec2 create-tags --resources $INSTANCE_ID --tags Key=PostgresRole,Value=$POSTGRES_ROLE)

echo "Waiting for instance to be 'running'..."
scripts/aws/base/wait_for_instance_state.sh $INSTANCE_ID running

echo "Adding DNS entry for $INSTANCE_NAME.$DOMAIN_NAME..."
scripts/aws/base/create_dns_record.sh $INSTANCE_ID $INSTANCE_NAME.$DOMAIN_NAME

echo "Checking availability zone of instance..."
AVAILABILITY_ZONE=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID --output text --query 'Reservations[*].Instances[*].Placement.AvailabilityZone')
echo "Found: $AVAILABILITY_ZONE"

echo "Creating a new EBS volume for data..."
VOLUME_ID=$(aws ec2 create-volume \
  --size 100 \
  --region us-west-2 \
  --availability-zone $AVAILABILITY_ZONE \
  --volume-type gp2 \
  --output text \
  --query 'VolumeId')
echo "Created volume $VOLUME_ID."

echo "Creating $INSTANCE_NAME-volume name tag for volume..."
TAG_RESPONSE=$(aws ec2 create-tags --resources $VOLUME_ID --tags Key=Name,Value=$INSTANCE_NAME-volume)

echo "Waiting for volume to be 'available'..."
scripts/aws/base/wait_for_volume_state.sh $VOLUME_ID available

echo "Attaching EBS volume $VOLUME_ID to instance $INSTANCE_ID..."
ATTACH_VOLUME_RESPONSE=$(aws ec2 attach-volume \
  --volume-id $VOLUME_ID \
  --instance-id $INSTANCE_ID \
  --device /dev/sdf)

echo "Waiting for volume to be 'in-use'..."
scripts/aws/base/wait_for_volume_state.sh $VOLUME_ID in-use

echo "Done creating Postgres instance."
echo $INSTANCE_ID


text:
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace KinderChat
{
	class AvatarAdapter : BaseAdapter
	{

		Activity context;
		readonly ProfileViewModel viewModel;
		public AvatarAdapter(Activity context, ProfileViewModel viewModel)
		{
			this.context = context;
			this.viewModel = viewModel;
			viewModel.Avatars.CollectionChanged += (sender, e) => context.RunOnUiThread (NotifyDataSetChanged);

		}

		public override Java.Lang.Object GetItem(int position)
		{
			return position;
		}

		public override long GetItemId(int position)
		{
			return position;
		}

		public override View GetView(int position, View convertView, ViewGroup parent)
		{
			var view = convertView;
			AvatarAdapterViewHolder holder = null;

			if (view != null)
				holder = view.Tag as AvatarAdapterViewHolder;

			if (holder == null)
			{
				holder = new AvatarAdapterViewHolder();
				var inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast<LayoutInflater>();
				//replace with your item and your holder items
				//comment back in
				view = inflater.Inflate(Resource.Layout.item_avatar, parent, false);
				holder.Photo = view.FindViewById<ImageView>(Resource.Id.photo);
				view.Tag = holder;
			}

			var avatar = viewModel.Avatars [position];

			Koush.UrlImageViewHelper.SetUrlDrawable (holder.Photo, avatar.ImageUrl, Resource.Drawable.ic_launcher);

			return view;
		}

		public override int Count
		{
			get
			{
				return viewModel.Avatars.Count;
			}
		}

	}

	class AvatarAdapterViewHolder : Java.Lang.Object
	{
		public ImageView Photo { get; set; }
	}
}


text:
package com.nuke.scheme.core;

/**
 * Base environment. Cannot have a parent and will contain all system functions.
 */
public class CoreEnvironment extends Environment {
   public CoreEnvironment() {
      super(null);

      Language.addDefaultVariables(this);
   }
}


text:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSubstitutesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return  void
     */
    public function up()
    {
        Schema::create('substitutes', function (Blueprint $table)
        {
            $table->increments('id');

            $table->string('path');
            $table->string('extension');
            $table->string('mimetype');
            $table->bigInteger('size')->unsigned();

            $table->integer('media_id')->unsigned()->nullable();

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return  void
     */
    public function down()
    {
        Schema::drop('substitutes');
    }

}


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

#include "platform/menus/menuBar.h"
#include "platform/menus/popupMenu.h"
#include "gui/core/guiCanvas.h"
#include "windowManager/platformWindowMgr.h"
#include "core/util/safeDelete.h"

#include "windowManager/sdl/sdlWindow.h"
#include "gui/editor/guiMenuBar.h"

#include "platformSDL/menus/PlatformSDLPopupMenuData.h"

#include "platformSDL/menus/guiPlatformGenericMenuBar.h"

#ifdef TORQUE_SDL

//-----------------------------------------------------------------------------
// Platform Data
//-----------------------------------------------------------------------------

// class PlatformMenuBarData
// {
//
// };

Map<GuiMenuBar::Menu*, PopupMenu*> PlatformPopupMenuData::mMenuMap;

IMPLEMENT_CONOBJECT(GuiPlatformGenericMenuBar);

//-----------------------------------------------------------------------------
// MenuBar Methods
//-----------------------------------------------------------------------------

void MenuBar::createPlatformPopupMenuData()
{
   mData = NULL;
}

void MenuBar::deletePlatformPopupMenuData()
{
//    SAFE_DELETE(mData);
}

//-----------------------------------------------------------------------------

GuiPlatformGenericMenuBar* _FindMenuBarCtrl()
{
   GuiControl* control;
   Sim::findObject("PlatformGenericMenubar", control);
   AssertFatal(control, "");
   if( !control )
      return NULL;

   GuiPlatformGenericMenuBar* menuBar;
   menuBar = dynamic_cast<GuiPlatformGenericMenuBar*>( control->findObjectByInternalName(  StringTable->insert("menubar"), true) );
   AssertFatal(menuBar, "");
   return menuBar;
}

void MenuBar::updateMenuBar(PopupMenu *popupMenu /* = NULL */)
{
   //if(! isAttachedToCanvas())
   //   return;

   if(!popupMenu)
      return;

   GuiPlatformGenericMenuBar* menuBarGui = _FindMenuBarCtrl();
   popupMenu->mData->mMenuBar = this;

   String menuTitle = popupMenu->getBarTitle();

   //Next, find out if we're still in the list of entries
   SimSet::iterator itr = find(begin(), end(), popupMenu);

   GuiMenuBar::Menu* menuGui = menuBarGui->findMenu(menuTitle);
   if (!menuGui)
   {
      //This is our first time setting this particular menu up, so we'll OK it.
      if (itr == end())
         menuBarGui->attachToMenuBar(popupMenu->mData->mMenuGui);
      else
         menuBarGui->attachToMenuBar(popupMenu->mData->mMenuGui, itr - begin());
   }
   else
   {
      //Not our first time through, so we're really updating it.

      //So, first, remove it from the menubar
      menuBarGui->removeFromMenuBar(menuGui);

      //Next, find out if we're still in the list of entries
      SimSet::iterator itr = find(begin(), end(), popupMenu);

      //if we're no longer in the list, we're pretty much done here
      if (itr == end())
         return;

      //We're still here, so this is a valid menu for our current bar configuration, so add us back in.
      menuBarGui->attachToMenuBar(menuGui, itr - begin());
   }
}

//-----------------------------------------------------------------------------

void MenuBar::attachToCanvas(GuiCanvas *owner, S32 pos)
{
   if(owner == NULL || isAttachedToCanvas())
      return;

   // This is set for popup menus in the onAttachToMenuBar() callback
   mCanvas = owner;

   PlatformWindowSDL *pWindow = dynamic_cast<PlatformWindowSDL*>(owner->getPlatformWindow());
   if(pWindow == NULL)
      return;

   // Setup the native menu bar
   GuiMenuBar *hWindowMenu = static_cast<GuiMenuBar*>( pWindow->getMenuHandle() );
	if( hWindowMenu == NULL && !Journal::IsPlaying() )
      hWindowMenu = _FindMenuBarCtrl();

   if(hWindowMenu)
   {
      pWindow->setMenuHandle( hWindowMenu );
      GuiControl *base = hWindowMenu->getParent();

      while( base->getParent() )
      {
         base = base->getParent();
      }

      mCanvas->setMenuBar( base );
   }

   for (S32 i = 0; i < size(); ++i)
   {
      PopupMenu *mnu = dynamic_cast<PopupMenu *>(at(i));
      if (mnu == NULL)
      {
         Con::warnf("MenuBar::attachToMenuBar - Non-PopupMenu object in set");
         continue;
      }

      if (mnu->isAttachedToMenuBar())
         mnu->removeFromMenuBar();

      mnu->attachToMenuBar(owner, pos + i);
   }

}

void MenuBar::removeFromCanvas()
{
   if (mCanvas == NULL || !isAttachedToCanvas())
      return;

   //_FindMenuBarCtrl()->clearMenus();

   // Add the items
   for (S32 i = 0; i < size(); ++i)
   {
      PopupMenu *mnu = dynamic_cast<PopupMenu *>(at(i));
      if (mnu == NULL)
      {
         Con::warnf("MenuBar::removeFromMenuBar - Non-PopupMenu object in set");
         continue;
      }

      mnu->removeFromMenuBar();
   }

   mCanvas->setMenuBar(NULL);

   mCanvas = NULL;
}

#endif


text:
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ HttpRequest, Uri }
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.util.ByteString
import cats.instances.future._
import cats.syntax.functor._
import com.bot4s.telegram.api.declarative.Commands
import com.bot4s.telegram.future.Polling
import com.bot4s.telegram.methods._

import scala.concurrent.Future
import scala.util.{ Failure, Success }

/**
 * This bot receives voice recordings and outputs the file size.
 */
class VoiceFileBot(token: String) extends AkkaExampleBot(token) with Polling with Commands[Future] {

  onMessage { implicit msg =>
    using(_.voice) { voice =>
      request(GetFile(voice.fileId))
        .andThen({
          case Success(file) =>
            file.filePath match {

              case Some(filePath) =>
                // See https://core.telegram.org/bots/api#getfile
                val url = s"https://api.telegram.org/file/bot${token}/${filePath}"

                for {
                  res <- Http().singleRequest(HttpRequest(uri = Uri(url)))
                  if res.status.isSuccess()
                  bytes <- Unmarshal(res).to[ByteString]
                  _     <- reply(s"File with ${bytes.size} bytes received.")
                } yield ()
              case None =>
                reply("No file_path was returned")
            }

          case Failure(e) =>
            logger.error("Exception: " + e) // poor's man logging
        })
        .void
    }
  }
}


text:
#ifndef LIEF_PE_HEADER_CPP_C_API_
#define LIEF_PE_HEADER_CPP_C_API_

#include "LIEF/PE/Binary.h"
#include "LIEF/PE/Binary.hpp"

#include "LIEF/PE/Header.h"
#include "LIEF/PE/Header.hpp"

namespace LIEF {
namespace PE {

void init_c_header(Pe_Binary_t* c_binary, Binary* binary);

}
}

#endif


text:
<?php
namespace MES\APP\FrontendBundle\Service\Upload;

class UploadFileNamer
{
    protected $baseDirectory;

    public function __construct($baseDirectory)
    {
        $this->baseDirectory = $baseDirectory;
    }

    public function getAbsolutePath($key, $type)
    {
        return $this->baseDirectory . $type . '/' . $this->getRelativePath($key, $type);
    }

    public function getRelativePath($key)
    {
        $url = '';

        for ($i = 1, $c = min(3, strlen($key)); $i < $c; $i ++) {
            $url .= substr($key, 0, $i) . '/';
        }

        return sprintf('%s', $url . $key);
    }

    public function getWebUrl($key, $type)
    {
        return '/uploads/' . $type . '/' . $this->getRelativePath($key, $type);
    }
}


text:
""" Tests for create_volume TaskFlow """

import ddt
import mock

from castellan.tests.unit.key_manager import mock_key_manager
from oslo_utils import imageutils

from cinder import context
from cinder import exception
from cinder import test
from cinder.tests.unit.consistencygroup import fake_consistencygroup
from cinder.tests.unit import fake_constants as fakes
from cinder.tests.unit import fake_snapshot
from cinder.tests.unit import fake_volume
from cinder.tests.unit.image import fake as fake_image
from cinder.tests.unit import utils
from cinder.tests.unit.volume.flows import fake_volume_api
from cinder.volume.flows.api import create_volume
from cinder.volume.flows.manager import create_volume as create_volume_manager

@ddt.ddt
class CreateVolumeFlowTestCase(test.TestCase):

    def time_inc(self):
        self.counter += 1
        return self.counter

    def setUp(self):
        super(CreateVolumeFlowTestCase, self).setUp()
        self.ctxt = context.get_admin_context()

        # Ensure that time.time() always returns more than the last time it was
        # called to avoid div by zero errors.
        self.counter = float(0)

    @mock.patch('cinder.objects.Volume.get_by_id')
    @mock.patch('cinder.volume.utils.extract_host')
    @mock.patch('time.time')
    @mock.patch('cinder.objects.ConsistencyGroup.get_by_id')
    def test_cast_create_volume(self, consistencygroup_get_by_id, mock_time,
                                mock_extract_host, volume_get_by_id):
        mock_time.side_effect = self.time_inc
        volume = fake_volume.fake_volume_obj(self.ctxt)
        volume_get_by_id.return_value = volume
        props = {}
        cg_obj = (fake_consistencygroup.
                  fake_consistencyobject_obj(self.ctxt, consistencygroup_id=1,
                                             host='host@backend#pool'))
        consistencygroup_get_by_id.return_value = cg_obj
        spec = {'volume_id': None,
                'volume': None,
                'source_volid': None,
                'snapshot_id': None,
                'image_id': None,
                'source_replicaid': None,
                'consistencygroup_id': None,
                'cgsnapshot_id': None,
                'group_id': None, }

        # Fake objects assert specs
        task = create_volume.VolumeCastTask(
            fake_volume_api.FakeSchedulerRpcAPI(spec, self),
            fake_volume_api.FakeVolumeAPI(spec, self),
            fake_volume_api.FakeDb())

        task._cast_create_volume(self.ctxt, spec, props)

        spec = {'volume_id': volume.id,
                'volume': volume,
                'source_volid': 2,
                'snapshot_id': 3,
                'image_id': 4,
                'source_replicaid': 5,
                'consistencygroup_id': 5,
                'cgsnapshot_id': None,
                'group_id': None, }

        # Fake objects assert specs
        task = create_volume.VolumeCastTask(
            fake_volume_api.FakeSchedulerRpcAPI(spec, self),
            fake_volume_api.FakeVolumeAPI(spec, self),
            fake_volume_api.FakeDb())

        task._cast_create_volume(self.ctxt, spec, props)
        consistencygroup_get_by_id.assert_called_once_with(self.ctxt, 5)
        mock_extract_host.assert_called_once_with('host@backend#pool')

    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_encryption_key_id')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    def test_extract_volume_request_from_image_encrypted(
            self,
            fake_get_qos,
            fake_get_encryption_key,
            fake_get_volume_type_id,
            fake_is_encrypted):

        fake_image_service = fake_image.FakeImageService()
        image_id = 1
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = True
        fake_get_volume_type_id.return_value = fakes.VOLUME_TYPE_ID
        task.execute(self.ctxt,
                     size=1,
                     snapshot=None,
                     image_id=image_id,
                     source_volume=None,
                     availability_zone='nova',
                     volume_type=None,
                     metadata=None,
                     key_manager=fake_key_manager,
                     source_replica=None,
                     consistencygroup=None,
                     cgsnapshot=None,
                     group=None)
        fake_get_encryption_key.assert_called_once_with(
            fake_key_manager, self.ctxt, fakes.VOLUME_TYPE_ID, None, None)

    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    def test_extract_volume_request_from_image(
            self,
            fake_get_type_id,
            fake_get_qos,
            fake_is_encrypted):

        fake_image_service = fake_image.FakeImageService()
        image_id = 2
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()
        volume_type = 'type1'

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = False
        fake_get_type_id.return_value = 1
        fake_get_qos.return_value = {'qos_specs': None}
        result = task.execute(self.ctxt,
                              size=1,
                              snapshot=None,
                              image_id=image_id,
                              source_volume=None,
                              availability_zone='nova',
                              volume_type=volume_type,
                              metadata=None,
                              key_manager=fake_key_manager,
                              source_replica=None,
                              consistencygroup=None,
                              cgsnapshot=None,
                              group=None)
        expected_result = {'size': 1,
                           'snapshot_id': None,
                           'source_volid': None,
                           'availability_zone': 'nova',
                           'volume_type': volume_type,
                           'volume_type_id': 1,
                           'encryption_key_id': None,
                           'qos_specs': None,
                           'source_replicaid': None,
                           'consistencygroup_id': None,
                           'cgsnapshot_id': None,
                           'group_id': None, }
        self.assertEqual(expected_result, result)

    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    def test_extract_availability_zone_without_fallback(
            self,
            fake_get_type_id,
            fake_get_qos,
            fake_is_encrypted):
        fake_image_service = fake_image.FakeImageService()
        image_id = 3
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()
        volume_type = 'type1'

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = False
        fake_get_type_id.return_value = 1
        fake_get_qos.return_value = {'qos_specs': None}
        self.assertRaises(exception.InvalidInput,
                          task.execute,
                          self.ctxt,
                          size=1,
                          snapshot=None,
                          image_id=image_id,
                          source_volume=None,
                          availability_zone='notnova',
                          volume_type=volume_type,
                          metadata=None,
                          key_manager=fake_key_manager,
                          source_replica=None,
                          consistencygroup=None,
                          cgsnapshot=None,
                          group=None)

    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    def test_extract_availability_zone_with_fallback(
            self,
            fake_get_type_id,
            fake_get_qos,
            fake_is_encrypted):

        self.override_config('allow_availability_zone_fallback', True)

        fake_image_service = fake_image.FakeImageService()
        image_id = 4
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()
        volume_type = 'type1'

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = False
        fake_get_type_id.return_value = 1
        fake_get_qos.return_value = {'qos_specs': None}
        result = task.execute(self.ctxt,
                              size=1,
                              snapshot=None,
                              image_id=image_id,
                              source_volume=None,
                              availability_zone='does_not_exist',
                              volume_type=volume_type,
                              metadata=None,
                              key_manager=fake_key_manager,
                              source_replica=None,
                              consistencygroup=None,
                              cgsnapshot=None,
                              group=None)
        expected_result = {'size': 1,
                           'snapshot_id': None,
                           'source_volid': None,
                           'availability_zone': 'nova',
                           'volume_type': volume_type,
                           'volume_type_id': 1,
                           'encryption_key_id': None,
                           'qos_specs': None,
                           'source_replicaid': None,
                           'consistencygroup_id': None,
                           'cgsnapshot_id': None,
                           'group_id': None, }
        self.assertEqual(expected_result, result)

    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    def test_extract_volume_request_from_image_with_qos_specs(
            self,
            fake_get_type_id,
            fake_get_qos,
            fake_is_encrypted):

        fake_image_service = fake_image.FakeImageService()
        image_id = 5
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()
        volume_type = 'type1'

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = False
        fake_get_type_id.return_value = 1
        fake_qos_spec = {'specs': {'fake_key': 'fake'}}
        fake_get_qos.return_value = {'qos_specs': fake_qos_spec}
        result = task.execute(self.ctxt,
                              size=1,
                              snapshot=None,
                              image_id=image_id,
                              source_volume=None,
                              availability_zone='nova',
                              volume_type=volume_type,
                              metadata=None,
                              key_manager=fake_key_manager,
                              source_replica=None,
                              consistencygroup=None,
                              cgsnapshot=None,
                              group=None)
        expected_result = {'size': 1,
                           'snapshot_id': None,
                           'source_volid': None,
                           'availability_zone': 'nova',
                           'volume_type': volume_type,
                           'volume_type_id': 1,
                           'encryption_key_id': None,
                           'qos_specs': {'fake_key': 'fake'},
                           'source_replicaid': None,
                           'consistencygroup_id': None,
                           'cgsnapshot_id': None,
                           'group_id': None, }
        self.assertEqual(expected_result, result)

    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    @mock.patch('cinder.volume.volume_types.get_default_volume_type')
    @mock.patch('cinder.volume.volume_types.get_volume_type_by_name')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    def test_extract_image_volume_type_from_image(
            self,
            fake_get_type_id,
            fake_get_vol_type,
            fake_get_def_vol_type,
            fake_get_qos,
            fake_is_encrypted):

        image_volume_type = 'type_from_image'
        fake_image_service = fake_image.FakeImageService()
        image_id = 6
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        image_meta['properties'] = {}
        image_meta['properties']['cinder_img_volume_type'] = image_volume_type
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = False
        fake_get_type_id.return_value = 1
        fake_get_vol_type.return_value = image_volume_type
        fake_get_def_vol_type.return_value = 'fake_vol_type'
        fake_get_qos.return_value = {'qos_specs': None}
        result = task.execute(self.ctxt,
                              size=1,
                              snapshot=None,
                              image_id=image_id,
                              source_volume=None,
                              availability_zone='nova',
                              volume_type=None,
                              metadata=None,
                              key_manager=fake_key_manager,
                              source_replica=None,
                              consistencygroup=None,
                              cgsnapshot=None,
                              group=None)
        expected_result = {'size': 1,
                           'snapshot_id': None,
                           'source_volid': None,
                           'availability_zone': 'nova',
                           'volume_type': image_volume_type,
                           'volume_type_id': 1,
                           'encryption_key_id': None,
                           'qos_specs': None,
                           'source_replicaid': None,
                           'consistencygroup_id': None,
                           'cgsnapshot_id': None,
                           'group_id': None, }
        self.assertEqual(expected_result, result)

    @mock.patch('cinder.db.volume_type_get_by_name')
    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    @mock.patch('cinder.volume.volume_types.get_default_volume_type')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    def test_extract_image_volume_type_from_image_invalid_type(
            self,
            fake_get_type_id,
            fake_get_def_vol_type,
            fake_get_qos,
            fake_is_encrypted,
            fake_db_get_vol_type):

        image_volume_type = 'invalid'
        fake_image_service = fake_image.FakeImageService()
        image_id = 7
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        image_meta['properties'] = {}
        image_meta['properties']['cinder_img_volume_type'] = image_volume_type
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = False
        fake_get_type_id.return_value = 1
        fake_get_def_vol_type.return_value = 'fake_vol_type'
        fake_db_get_vol_type.side_effect = (
            exception.VolumeTypeNotFoundByName(volume_type_name='invalid'))
        fake_get_qos.return_value = {'qos_specs': None}
        result = task.execute(self.ctxt,
                              size=1,
                              snapshot=None,
                              image_id=image_id,
                              source_volume=None,
                              availability_zone='nova',
                              volume_type=None,
                              metadata=None,
                              key_manager=fake_key_manager,
                              source_replica=None,
                              consistencygroup=None,
                              cgsnapshot=None,
                              group=None)
        expected_result = {'size': 1,
                           'snapshot_id': None,
                           'source_volid': None,
                           'availability_zone': 'nova',
                           'volume_type': 'fake_vol_type',
                           'volume_type_id': 1,
                           'encryption_key_id': None,
                           'qos_specs': None,
                           'source_replicaid': None,
                           'consistencygroup_id': None,
                           'cgsnapshot_id': None,
                           'group_id': None, }
        self.assertEqual(expected_result, result)

    @mock.patch('cinder.db.volume_type_get_by_name')
    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    @mock.patch('cinder.volume.volume_types.get_default_volume_type')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    @ddt.data((8, None), (9, {'cinder_img_volume_type': None}))
    @ddt.unpack
    def test_extract_image_volume_type_from_image_properties_error(
            self,
            image_id,
            fake_img_properties,
            fake_get_type_id,
            fake_get_def_vol_type,
            fake_get_qos,
            fake_is_encrypted,
            fake_db_get_vol_type):

        fake_image_service = fake_image.FakeImageService()
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        image_meta['properties'] = fake_img_properties
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = False
        fake_get_type_id.return_value = 1
        fake_get_def_vol_type.return_value = 'fake_vol_type'
        fake_get_qos.return_value = {'qos_specs': None}
        result = task.execute(self.ctxt,
                              size=1,
                              snapshot=None,
                              image_id=image_id,
                              source_volume=None,
                              availability_zone='nova',
                              volume_type=None,
                              metadata=None,
                              key_manager=fake_key_manager,
                              source_replica=None,
                              consistencygroup=None,
                              cgsnapshot=None,
                              group=None)
        expected_result = {'size': 1,
                           'snapshot_id': None,
                           'source_volid': None,
                           'availability_zone': 'nova',
                           'volume_type': 'fake_vol_type',
                           'volume_type_id': 1,
                           'encryption_key_id': None,
                           'qos_specs': None,
                           'source_replicaid': None,
                           'consistencygroup_id': None,
                           'cgsnapshot_id': None,
                           'group_id': None, }
        self.assertEqual(expected_result, result)

    @mock.patch('cinder.db.volume_type_get_by_name')
    @mock.patch('cinder.volume.volume_types.is_encrypted')
    @mock.patch('cinder.volume.volume_types.get_volume_type_qos_specs')
    @mock.patch('cinder.volume.volume_types.get_default_volume_type')
    @mock.patch('cinder.volume.flows.api.create_volume.'
                'ExtractVolumeRequestTask.'
                '_get_volume_type_id')
    def test_extract_image_volume_type_from_image_invalid_input(
            self,
            fake_get_type_id,
            fake_get_def_vol_type,
            fake_get_qos,
            fake_is_encrypted,
            fake_db_get_vol_type):

        fake_image_service = fake_image.FakeImageService()
        image_id = 10
        image_meta = {}
        image_meta['id'] = image_id
        image_meta['status'] = 'inactive'
        fake_image_service.create(self.ctxt, image_meta)
        fake_key_manager = mock_key_manager.MockKeyManager()

        task = create_volume.ExtractVolumeRequestTask(
            fake_image_service,
            {'nova'})

        fake_is_encrypted.return_value = False
        fake_get_type_id.return_value = 1
        fake_get_def_vol_type.return_value = 'fake_vol_type'
        fake_get_qos.return_value = {'qos_specs': None}

        self.assertRaises(exception.InvalidInput,
                          task.execute,
                          self.ctxt,
                          size=1,
                          snapshot=None,
                          image_id=image_id,
                          source_volume=None,
                          availability_zone='nova',
                          volume_type=None,
                          metadata=None,
                          key_manager=fake_key_manager,
                          source_replica=None,
                          consistencygroup=None,
                          cgsnapshot=None,
                          group=None)

@ddt.ddt
class CreateVolumeFlowManagerTestCase(test.TestCase):

    def setUp(self):
        super(CreateVolumeFlowManagerTestCase, self).setUp()
        self.ctxt = context.get_admin_context()

    @mock.patch('cinder.volume.flows.manager.create_volume.'
                'CreateVolumeFromSpecTask.'
                '_handle_bootable_volume_glance_meta')
    @mock.patch('cinder.objects.Volume.get_by_id')
    @mock.patch('cinder.objects.Snapshot.get_by_id')
    def test_create_from_snapshot(self, snapshot_get_by_id, volume_get_by_id,
                                  handle_bootable):
        fake_db = mock.MagicMock()
        fake_driver = mock.MagicMock()
        fake_volume_manager = mock.MagicMock()
        fake_manager = create_volume_manager.CreateVolumeFromSpecTask(
            fake_volume_manager, fake_db, fake_driver)
        volume_db = {'bootable': True}
        volume_obj = fake_volume.fake_volume_obj(self.ctxt, **volume_db)
        snapshot_obj = fake_snapshot.fake_snapshot_obj(self.ctxt)
        snapshot_get_by_id.return_value = snapshot_obj
        volume_get_by_id.return_value = volume_obj

        fake_manager._create_from_snapshot(self.ctxt, volume_obj,
                                           snapshot_obj.id)
        fake_driver.create_volume_from_snapshot.assert_called_once_with(
            volume_obj, snapshot_obj)
        handle_bootable.assert_called_once_with(self.ctxt, volume_obj,
                                                snapshot_id=snapshot_obj.id)

    @mock.patch('cinder.objects.Snapshot.get_by_id')
    def test_create_from_snapshot_update_failure(self, snapshot_get_by_id):
        fake_db = mock.MagicMock()
        fake_driver = mock.MagicMock()
        fake_volume_manager = mock.MagicMock()
        fake_manager = create_volume_manager.CreateVolumeFromSpecTask(
            fake_volume_manager, fake_db, fake_driver)
        volume = fake_volume.fake_db_volume()
        snapshot_obj = fake_snapshot.fake_snapshot_obj(self.ctxt)
        snapshot_get_by_id.return_value = snapshot_obj
        fake_db.volume_get.side_effect = exception.CinderException

        self.assertRaises(exception.MetadataUpdateFailure,
                          fake_manager._create_from_snapshot, self.ctxt,
                          volume, snapshot_obj.id)
        fake_driver.create_volume_from_snapshot.assert_called_once_with(
            volume, snapshot_obj)

    @mock.patch('cinder.volume.flows.manager.create_volume.'
                'CreateVolumeFromSpecTask.'
                '_handle_bootable_volume_glance_meta')
    @mock.patch('cinder.image.image_utils.TemporaryImages.fetch')
    @mock.patch('cinder.image.image_utils.qemu_img_info')
    @mock.patch('cinder.image.image_utils.check_virtual_size')
    def test_create_encrypted_volume_from_image(self,
                                                mock_check_size,
                                                mock_qemu_img,
                                                mock_fetch_img,
                                                mock_handle_bootable):
        fake_db = mock.MagicMock()
        fake_driver = mock.MagicMock()
        fake_volume_manager = mock.MagicMock()
        fake_manager = create_volume_manager.CreateVolumeFromSpecTask(
            fake_volume_manager, fake_db, fake_driver)
        volume = fake_volume.fake_volume_obj(
            self.ctxt,
            encryption_key_id=fakes.ENCRYPTION_KEY_ID)

        fake_image_service = fake_image.FakeImageService()
        image_meta = {}
        image_id = fakes.IMAGE_ID
        image_meta['id'] = image_id
        image_meta['status'] = 'active'
        image_meta['size'] = 1
        image_location = 'abc'

        fake_db.volume_update.return_value = volume
        fake_manager._create_from_image(self.ctxt, volume,
                                        image_location, image_id,
                                        image_meta, fake_image_service)

        fake_driver.create_volume.assert_called_once_with(volume)
        fake_driver.copy_image_to_encrypted_volume.assert_called_once_with(
            self.ctxt, volume, fake_image_service, image_id)
        mock_handle_bootable.assert_called_once_with(self.ctxt, volume,
                                                     image_id=image_id,
                                                     image_meta=image_meta)

    @ddt.data(True, False)
    def test__copy_image_to_volume(self, is_encrypted):
        fake_db = mock.MagicMock()
        fake_driver = mock.MagicMock()
        fake_volume_manager = mock.MagicMock()
        fake_manager = create_volume_manager.CreateVolumeFromSpecTask(
            fake_volume_manager, fake_db, fake_driver)
        key = fakes.ENCRYPTION_KEY_ID if is_encrypted else None
        volume = fake_volume.fake_volume_obj(
            self.ctxt,
            encryption_key_id=key)

        fake_image_service = fake_image.FakeImageService()
        image_id = fakes.IMAGE_ID
        image_location = 'abc'

        fake_manager._copy_image_to_volume(self.ctxt, volume, image_id,
                                           image_location, fake_image_service)
        if is_encrypted:
            fake_driver.copy_image_to_encrypted_volume.assert_called_once_with(
                self.ctxt, volume, fake_image_service, image_id)
        else:
            fake_driver.copy_image_to_volume.assert_called_once_with(
                self.ctxt, volume, fake_image_service, image_id)

class CreateVolumeFlowManagerGlanceCinderBackendCase(test.TestCase):

    def setUp(self):
        super(CreateVolumeFlowManagerGlanceCinderBackendCase, self).setUp()
        self.ctxt = context.get_admin_context()

    @mock.patch('cinder.image.image_utils.TemporaryImages.fetch')
    @mock.patch('cinder.volume.flows.manager.create_volume.'
                'CreateVolumeFromSpecTask.'
                '_handle_bootable_volume_glance_meta')
    @mock.patch('cinder.image.image_utils.qemu_img_info')
    def test_create_from_image_volume(self, mock_qemu_info, handle_bootable,
                                      mock_fetch_img, format='raw', owner=None,
                                      location=True):
        self.flags(allowed_direct_url_schemes=['cinder'])
        mock_fetch_img.return_value = mock.MagicMock(
            spec=utils.get_file_spec())
        fake_db = mock.MagicMock()
        fake_driver = mock.MagicMock()
        fake_manager = create_volume_manager.CreateVolumeFromSpecTask(
            mock.MagicMock(), fake_db, fake_driver)
        fake_image_service = mock.MagicMock()
        volume = fake_volume.fake_volume_obj(self.ctxt)
        image_volume = fake_volume.fake_volume_obj(self.ctxt,
                                                   volume_metadata={})
        image_id = fakes.IMAGE_ID
        image_info = imageutils.QemuImgInfo()
        image_info.virtual_size = '1073741824'
        mock_qemu_info.return_value = image_info

        url = 'cinder://%s' % image_volume['id']
        image_location = None
        if location:
            image_location = (url, [{'url': url, 'metadata': {}}])
        image_meta = {'id': image_id,
                      'container_format': 'bare',
                      'disk_format': format,
                      'owner': owner or self.ctxt.project_id,
                      'virtual_size': None}

        fake_driver.clone_image.return_value = (None, False)
        fake_db.volume_get_all_by_host.return_value = [image_volume]

        fake_manager._create_from_image(self.ctxt,
                                        volume,
                                        image_location,
                                        image_id,
                                        image_meta,
                                        fake_image_service)
        if format is 'raw' and not owner and location:
            fake_driver.create_cloned_volume.assert_called_once_with(
                volume, image_volume)
            handle_bootable.assert_called_once_with(self.ctxt, volume,
                                                    image_id=image_id,
                                                    image_meta=image_meta)
        else:
            self.assertFalse(fake_driver.create_cloned_volume.called)

    def test_create_from_image_volume_in_qcow2_format(self):
        self.test_create_from_image_volume(format='qcow2')

    def test_create_from_image_volume_of_other_owner(self):
        self.test_create_from_image_volume(owner='fake-owner')

    def test_create_from_image_volume_without_location(self):
        self.test_create_from_image_volume(location=False)

@mock.patch('cinder.image.image_utils.TemporaryImages.fetch')
@mock.patch('cinder.volume.flows.manager.create_volume.'
            'CreateVolumeFromSpecTask.'
            '_handle_bootable_volume_glance_meta')
@mock.patch('cinder.volume.flows.manager.create_volume.'
            'CreateVolumeFromSpecTask.'
            '_create_from_source_volume')
@mock.patch('cinder.volume.flows.manager.create_volume.'
            'CreateVolumeFromSpecTask.'
            '_create_from_image_download')
@mock.patch('cinder.context.get_internal_tenant_context')
class CreateVolumeFlowManagerImageCacheTestCase(test.TestCase):

    def setUp(self):
        super(CreateVolumeFlowManagerImageCacheTestCase, self).setUp()
        self.ctxt = context.get_admin_context()
        self.mock_db = mock.MagicMock()
        self.mock_driver = mock.MagicMock()
        self.mock_cache = mock.MagicMock()
        self.mock_image_service = mock.MagicMock()
        self.mock_volume_manager = mock.MagicMock()

        self.internal_context = self.ctxt
        self.internal_context.user_id = 'abc123'
        self.internal_context.project_id = 'def456'

    def test_create_from_image_clone_image_and_skip_cache(
            self, mock_get_internal_context, mock_create_from_img_dl,
            mock_create_from_src, mock_handle_bootable, mock_fetch_img):
        self.mock_driver.clone_image.return_value = (None, True)
        volume = fake_volume.fake_volume_obj(self.ctxt)

        image_location = 'someImageLocationStr'
        image_id = fakes.IMAGE_ID
        image_meta = {'virtual_size': '1073741824'}

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache
        )

        manager._create_from_image(self.ctxt,
                                   volume,
                                   image_location,
                                   image_id,
                                   image_meta,
                                   self.mock_image_service)

        # Make sure clone_image is always called even if the cache is enabled
        self.assertTrue(self.mock_driver.clone_image.called)

        # Create from source shouldn't happen if clone_image succeeds
        self.assertFalse(mock_create_from_src.called)

        # The image download should not happen if clone_image succeeds
        self.assertFalse(mock_create_from_img_dl.called)

        mock_handle_bootable.assert_called_once_with(
            self.ctxt,
            volume,
            image_id=image_id,
            image_meta=image_meta
        )

    @mock.patch('cinder.image.image_utils.qemu_img_info')
    def test_create_from_image_cannot_use_cache(
            self, mock_qemu_info, mock_get_internal_context,
            mock_create_from_img_dl, mock_create_from_src,
            mock_handle_bootable, mock_fetch_img):
        mock_get_internal_context.return_value = None
        self.mock_driver.clone_image.return_value = (None, False)
        volume = fake_volume.fake_volume_obj(self.ctxt)
        image_info = imageutils.QemuImgInfo()
        image_info.virtual_size = '1073741824'
        mock_qemu_info.return_value = image_info

        image_location = 'someImageLocationStr'
        image_id = fakes.IMAGE_ID
        image_meta = {'virtual_size': '1073741824'}

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache
        )

        manager._create_from_image(self.ctxt,
                                   volume,
                                   image_location,
                                   image_id,
                                   image_meta,
                                   self.mock_image_service)

        # Make sure clone_image is always called
        self.assertTrue(self.mock_driver.clone_image.called)

        # Create from source shouldn't happen if cache cannot be used.
        self.assertFalse(mock_create_from_src.called)

        # The image download should happen if clone fails and we can't use the
        # image-volume cache.
        mock_create_from_img_dl.assert_called_once_with(
            self.ctxt,
            volume,
            image_location,
            image_id,
            self.mock_image_service
        )

        # This should not attempt to use a minimal size volume
        self.assertFalse(self.mock_db.volume_update.called)

        # Make sure we didn't try and create a cache entry
        self.assertFalse(self.mock_cache.ensure_space.called)
        self.assertFalse(self.mock_cache.create_cache_entry.called)

        mock_handle_bootable.assert_called_once_with(
            self.ctxt,
            volume,
            image_id=image_id,
            image_meta=image_meta
        )

    def test_create_from_image_bigger_size(
            self, mock_get_internal_context,
            mock_create_from_img_dl, mock_create_from_src,
            mock_handle_bootable, mock_fetch_img):
        volume = fake_volume.fake_volume_obj(self.ctxt)

        image_location = 'someImageLocationStr'
        image_id = fakes.IMAGE_ID
        image_meta = {'virtual_size': '2147483648'}

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache
        )

        self.assertRaises(
            exception.ImageUnacceptable,
            manager._create_from_image,
            self.ctxt,
            volume,
            image_location,
            image_id,
            image_meta,
            self.mock_image_service)

    def test_create_from_image_cache_hit(
            self, mock_get_internal_context, mock_create_from_img_dl,
            mock_create_from_src, mock_handle_bootable, mock_fetch_img):
        self.mock_driver.clone_image.return_value = (None, False)
        image_volume_id = '70a599e0-31e7-49b7-b260-868f441e862b'
        self.mock_cache.get_entry.return_value = {
            'volume_id': image_volume_id
        }

        volume = fake_volume.fake_volume_obj(self.ctxt)

        image_location = 'someImageLocationStr'
        image_id = fakes.IMAGE_ID
        image_meta = {'virtual_size': None}

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache
        )

        manager._create_from_image(self.ctxt,
                                   volume,
                                   image_location,
                                   image_id,
                                   image_meta,
                                   self.mock_image_service)

        # Make sure clone_image is always called even if the cache is enabled
        self.assertTrue(self.mock_driver.clone_image.called)

        # For a cache hit it should only clone from the image-volume
        mock_create_from_src.assert_called_once_with(self.ctxt,
                                                     volume,
                                                     image_volume_id)

        # The image download should not happen when we get a cache hit
        self.assertFalse(mock_create_from_img_dl.called)

        mock_handle_bootable.assert_called_once_with(
            self.ctxt,
            volume,
            image_id=image_id,
            image_meta=image_meta
        )

    @mock.patch('cinder.db.volume_update')
    @mock.patch('cinder.objects.Volume.get_by_id')
    @mock.patch('cinder.image.image_utils.qemu_img_info')
    def test_create_from_image_cache_miss(
            self, mock_qemu_info, mock_volume_get, mock_volume_update,
            mock_get_internal_context, mock_create_from_img_dl,
            mock_create_from_src, mock_handle_bootable, mock_fetch_img):
        mock_get_internal_context.return_value = self.ctxt
        mock_fetch_img.return_value = mock.MagicMock(
            spec=utils.get_file_spec())
        image_info = imageutils.QemuImgInfo()
        image_info.virtual_size = '2147483648'
        mock_qemu_info.return_value = image_info
        self.mock_driver.clone_image.return_value = (None, False)
        self.mock_cache.get_entry.return_value = None

        volume = fake_volume.fake_volume_obj(self.ctxt, size=10,
                                             host='foo@bar#pool')
        mock_volume_get.return_value = volume

        image_location = 'someImageLocationStr'
        image_id = fakes.IMAGE_ID
        image_meta = mock.MagicMock()

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache
        )

        manager._create_from_image(self.ctxt,
                                   volume,
                                   image_location,
                                   image_id,
                                   image_meta,
                                   self.mock_image_service)

        # Make sure clone_image is always called
        self.assertTrue(self.mock_driver.clone_image.called)

        # The image download should happen if clone fails and
        # we get a cache miss
        mock_create_from_img_dl.assert_called_once_with(
            self.ctxt,
            mock.ANY,
            image_location,
            image_id,
            self.mock_image_service
        )

        # The volume size should be reduced to virtual_size and then put back
        mock_volume_update.assert_any_call(self.ctxt, volume.id, {'size': 2})
        mock_volume_update.assert_any_call(self.ctxt, volume.id, {'size': 10})

        # Make sure created a new cache entry
        (self.mock_volume_manager.
            _create_image_cache_volume_entry.assert_called_once_with(
                self.ctxt, volume, image_id, image_meta))

        mock_handle_bootable.assert_called_once_with(
            self.ctxt,
            volume,
            image_id=image_id,
            image_meta=image_meta
        )

    @mock.patch('cinder.db.volume_update')
    @mock.patch('cinder.objects.Volume.get_by_id')
    @mock.patch('cinder.image.image_utils.qemu_img_info')
    def test_create_from_image_cache_miss_error_downloading(
            self, mock_qemu_info, mock_volume_get, mock_volume_update,
            mock_get_internal_context,
            mock_create_from_img_dl, mock_create_from_src,
            mock_handle_bootable, mock_fetch_img):
        mock_fetch_img.return_value = mock.MagicMock()
        image_info = imageutils.QemuImgInfo()
        image_info.virtual_size = '2147483648'
        mock_qemu_info.return_value = image_info
        self.mock_driver.clone_image.return_value = (None, False)
        self.mock_cache.get_entry.return_value = None

        volume = fake_volume.fake_volume_obj(self.ctxt, size=10,
                                             host='foo@bar#pool')
        mock_volume_get.return_value = volume

        mock_create_from_img_dl.side_effect = exception.CinderException()

        image_location = 'someImageLocationStr'
        image_id = fakes.IMAGE_ID
        image_meta = mock.MagicMock()

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache
        )

        self.assertRaises(
            exception.CinderException,
            manager._create_from_image,
            self.ctxt,
            volume,
            image_location,
            image_id,
            image_meta,
            self.mock_image_service
        )

        # Make sure clone_image is always called
        self.assertTrue(self.mock_driver.clone_image.called)

        # The image download should happen if clone fails and
        # we get a cache miss
        mock_create_from_img_dl.assert_called_once_with(
            self.ctxt,
            mock.ANY,
            image_location,
            image_id,
            self.mock_image_service
        )

        # The volume size should be reduced to virtual_size and then put back,
        # especially if there is an exception while creating the volume.
        self.assertEqual(2, mock_volume_update.call_count)
        mock_volume_update.assert_any_call(self.ctxt, volume.id, {'size': 2})
        mock_volume_update.assert_any_call(self.ctxt, volume.id, {'size': 10})

        # Make sure we didn't try and create a cache entry
        self.assertFalse(self.mock_cache.ensure_space.called)
        self.assertFalse(self.mock_cache.create_cache_entry.called)

    @mock.patch('cinder.image.image_utils.qemu_img_info')
    def test_create_from_image_no_internal_context(
            self, mock_qemu_info, mock_get_internal_context,
            mock_create_from_img_dl, mock_create_from_src,
            mock_handle_bootable, mock_fetch_img):
        self.mock_driver.clone_image.return_value = (None, False)
        mock_get_internal_context.return_value = None
        volume = fake_volume.fake_volume_obj(self.ctxt)
        image_info = imageutils.QemuImgInfo()
        image_info.virtual_size = '1073741824'
        mock_qemu_info.return_value = image_info

        image_location = 'someImageLocationStr'
        image_id = fakes.IMAGE_ID
        image_meta = {'virtual_size': '1073741824'}

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache
        )

        manager._create_from_image(self.ctxt,
                                   volume,
                                   image_location,
                                   image_id,
                                   image_meta,
                                   self.mock_image_service)

        # Make sure clone_image is always called
        self.assertTrue(self.mock_driver.clone_image.called)

        # Create from source shouldn't happen if cache cannot be used.
        self.assertFalse(mock_create_from_src.called)

        # The image download should happen if clone fails and we can't use the
        # image-volume cache due to not having an internal context available.
        mock_create_from_img_dl.assert_called_once_with(
            self.ctxt,
            volume,
            image_location,
            image_id,
            self.mock_image_service
        )

        # This should not attempt to use a minimal size volume
        self.assertFalse(self.mock_db.volume_update.called)

        # Make sure we didn't try and create a cache entry
        self.assertFalse(self.mock_cache.ensure_space.called)
        self.assertFalse(self.mock_cache.create_cache_entry.called)

        mock_handle_bootable.assert_called_once_with(
            self.ctxt,
            volume,
            image_id=image_id,
            image_meta=image_meta
        )

    @mock.patch('cinder.image.image_utils.qemu_img_info')
    def test_create_from_image_cache_miss_error_size_invalid(
            self, mock_qemu_info, mock_get_internal_context,
            mock_create_from_img_dl, mock_create_from_src,
            mock_handle_bootable, mock_fetch_img):
        mock_fetch_img.return_value = mock.MagicMock()
        image_info = imageutils.QemuImgInfo()
        image_info.virtual_size = '2147483648'
        mock_qemu_info.return_value = image_info
        self.mock_driver.clone_image.return_value = (None, False)
        self.mock_cache.get_entry.return_value = None

        volume = fake_volume.fake_volume_obj(self.ctxt, size=1,
                                             host='foo@bar#pool')
        image_volume = fake_volume.fake_db_volume(size=2)
        self.mock_db.volume_create.return_value = image_volume

        image_location = 'someImageLocationStr'
        image_id = fakes.IMAGE_ID
        image_meta = mock.MagicMock()

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache
        )

        self.assertRaises(
            exception.ImageUnacceptable,
            manager._create_from_image,
            self.ctxt,
            volume,
            image_location,
            image_id,
            image_meta,
            self.mock_image_service
        )

        # The volume size should NOT be changed when in this case
        self.assertFalse(self.mock_db.volume_update.called)

        # Make sure we didn't try and create a cache entry
        self.assertFalse(self.mock_cache.ensure_space.called)
        self.assertFalse(self.mock_cache.create_cache_entry.called)