text:
require 'spec_helper'

describe Nightfury::Metric::CountTimeSeries do
  describe "#get_padded_range" do
    it "should fill the missing data points with zero" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      start_time = Time.new(2013,1,1,0,0,0)
      end_time = start_time + 120
      missing_time = start_time + 60

      count_series.set(1, start_time)
      count_series.set(2, end_time)
      count_series.get_padded_range(start_time, end_time)[missing_time.to_i.to_s].should == "0"
    end
  end

  describe "Incr" do
    it "should increment the count at the step time of the given timestamp" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      time_now = Time.now
      #Add a data point
      count_series.set(2, time_now)

      count_series.incr(2, time_now)

      count_series.get.values.first.should == "4"
    end

    it "should increment the count at the step time of the current time by default" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      time_now = Time.now
      #Add a data point
      count_series.set(2, time_now)

      Timecop.freeze(time_now) do
        count_series.incr(2)
      end
      Timecop.return

      count_series.get.values.first.should == "4"
    end

    it "should increment the count by 1 by default" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      time_now = Time.now
      #Add a data point
      count_series.set(2, time_now)

      Timecop.freeze(time_now) do
        count_series.incr
      end
      Timecop.return

      count_series.get.values.first.should == "3"
    end

    it "should set the count to the step when there is no data point at the step time" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      time_now = Time.now
      count_series.incr(1, time_now)
      count_series.get(time_now).values.first.should == "1"
    end

    it "should increment the right step bucket" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      first_step_bucket = Time.now
      second_step_bucket = Time.now + 61

      count_series.set(5, first_step_bucket)
      count_series.set(6, second_step_bucket)

      count_series.incr(1, first_step_bucket)
      count_series.incr(1, second_step_bucket)

      count_series.get(first_step_bucket).values.first.should == "6"
      count_series.get(second_step_bucket).values.first.should == "7"
    end
  end

  describe "Decr" do
    it "should decrement the count at the step time of the given timestamp" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:counter)
      time_now = Time.now

      #Add a data point
      count_series.set(2, time_now)

      count_series.decr(2, time_now)

      count_series.get.values.first.should == "0"
    end

    it "should decrement the count at the step time of the current time by default" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      time_now = Time.now
      #Add a data point
      count_series.set(2, time_now)

      Timecop.freeze(time_now) do
        count_series.decr(2)
      end
      Timecop.return

      count_series.get.values.first.should == "0"
    end

    it "should decrement the count by 1 by default" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      time_now = Time.now
      #Add a data point
      count_series.set(2, time_now)

      Timecop.freeze(time_now) do
        count_series.decr
      end
      Timecop.return

      count_series.get.values.first.should == "1"
    end

    it "should set the count to the step when there is no data point at the step time" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      time_now = Time.now
      count_series.decr(1, time_now)
      count_series.get(time_now).values.first.should == "-1"
    end

    it "should decrement the right step bucket" do
      count_series = Nightfury::Metric::CountTimeSeries.new(:count)
      first_step_bucket = Time.now
      second_step_bucket = Time.now + 61

      count_series.set(5, first_step_bucket)
      count_series.set(6, second_step_bucket)

      count_series.decr(1, first_step_bucket)
      count_series.decr(1, second_step_bucket)

      count_series.get(first_step_bucket).values.first.should == "4"
      count_series.get(second_step_bucket).values.first.should == "5"
    end
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Trichomanes minutum Blume

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
export default {
  Network: require('./network').default,
  Source: require('./source').default,
  Target: require('./target').default
}


text:
using System;
using System.Linq;
using System.Data.Linq;
using System.Data.Entity;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CNSirindar.Models
{
    [Table("TblDependencias")]
    public class Dependencia : TableDbConventions
    {
        public Dependencia()
        {
            this.Deportistas = new HashSet<Deportista>();
            this.Entrenadores = new HashSet<Entrenador>();
        }

        public virtual int DependenciaId { get; set; }

        [Required]
        [MaxLength(50)]
        public virtual string Nombre { get; set; }

        [Required]
        [MaxLength(10)]
        public virtual string Clave { get; set; }

        public virtual ICollection<Deportista> Deportistas { get; set; }
        public virtual ICollection<Entrenador> Entrenadores { get; set; }

        public static Dependencia Read(int id)
        {
            var entity = new Dependencia();
            using (var db = new SirindarDbContext())
            {
                try
                {
                    db.ClasificacionesDeportes.Find(id);
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return entity;
        }

        public static bool Create(Dependencia entity)
        {
            using (var db = new SirindarDbContext())
            {
                try
                {
                    db.Entry(entity).State = EntityState.Added;
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return true;
        }

        public static bool Update(Dependencia entity)
        {
            using (var db = new SirindarDbContext())
            {
                try
                {
                    db.Entry(entity).State = EntityState.Modified;
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return true;
        }

        public static bool Delete(int id)
        {
            using (var db = new SirindarDbContext())
            {
                try
                {
                    var entity = db.Dependencias.Find(id);
                    entity.EsActivo = false;
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return true;
        }

        public static IList<Dependencia> List()
        {
            var list = new List<Dependencia>();
            using (var db = new SirindarDbContext())
            {
                list = db.Dependencias.ToList();
            }
            return list;
        }
    }
}


text:
package com.googlecode.japi.checker.tests.serializable;

import java.io.Serializable;

public class InvalidTypeInNewUID implements Serializable {

    private static final int serialVersionUID = 123;

}


text:
file(REMOVE_RECURSE
  "CMakeFiles/geo_alignedbox_14.dir/geo_alignedbox.cpp.o"
  "geo_alignedbox_14.pdb"
  "geo_alignedbox_14"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/geo_alignedbox_14.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
using System;
using ServiceStack.Text;

namespace StatelessAuthentication.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            new AppHost().Init().Start("http://*:8088/");
            "ServiceStack SelfHost listening at http://localhost:8088 ".Print();

            Console.ReadLine();
        }
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;

/* @var $this yii\web\View */
/* @var $model app\models\ItemsParteSalida */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'idParte')->textInput() ?>

    <?= $form->field($model, 'idInsumo')->dropDownList(ArrayHelper::map(app\models\Insumos::find()->all(),'idInsumo','Descripcion'),['prompt'=>('- Elija un Insumo -')])->label('Seleccione un Insumo:') ?>

    <?= $form->field($model, 'Cantidad')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
{% if dev %}
<script>
  (function() {
    let ws = new WebSocket(`ws://${location.host}/ws`);
    ws.onopen = function (event) {
      console.log('WebSocket connected');
    };
    ws.onmessage = function (event) {
      if (event.data == 'reload') {
        location.reload(true);
      }
    };
  })();
</script>
{% endif %}


text:
// Load configuration
var cfg = require('../config');

exports.Setup = function (test) {
  test.expect(0);

  var conn = cfg.mysql_libmysqlclient.createConnectionSync(cfg.host, cfg.user, cfg.password, cfg.database);

  conn.querySync("DROP TABLE IF EXISTS " + cfg.test_table + ";");
  conn.querySync("CREATE TABLE " + cfg.test_table + " (number INT(8) NOT NULL) ENGINE=MEMORY;");

  conn.closeSync();

  test.done();
};

exports.New = function (test) {
  test.expect(1);

  test.doesNotThrow(function () {
    (new cfg.mysql_libmysqlclient.MysqlConnectionHighlevel());
  });

  test.done();
};

exports.ConnectWithCallback = function (test) {
  test.expect(2);

  var conn = cfg.mysql_libmysqlclient.createConnectionHighlevelSync();

  conn.connect(cfg.host, cfg.user, cfg.password, cfg.database, function (err) {
    test.ok(err === null, "Error object is not present");

    test.ok(arguments.length <= 1, "Only error arguments is possible.");

    test.done();
  });
};

exports.ConnectWithQueryInCallback = function (test) {
  test.expect(1);

  var conn = cfg.mysql_libmysqlclient.createConnectionHighlevelSync();

  conn.connect(cfg.host, cfg.user, cfg.password, cfg.database, function () {
    conn.query("SELECT 1;", function (err, res) {
      if (err) {
        throw err;
      }

      test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

      test.done();
    });
  });
};

exports.ConnectWithoutCallbackAndThenQueryWithCallback = function (test) {
  test.expect(1);

  var conn = cfg.mysql_libmysqlclient.createConnectionHighlevelSync();

  conn.connect(cfg.host, cfg.user, cfg.password, cfg.database);

  conn.query("SELECT 1;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    test.done();
  });
};

exports.ConnectWithoutCallbackAndThenTwoQueriesWithCallbacks = function (test) {
  test.expect(2);

  var conn = cfg.mysql_libmysqlclient.createConnectionHighlevelSync();

  conn.connect(cfg.host, cfg.user, cfg.password, cfg.database);

  conn.query("SELECT 1;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);
  });

  conn.query("SELECT 2;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    test.done();
  });
};

exports.QueryParallel = function (test) {
  test.expect(4);

  var
    conn = cfg.mysql_libmysqlclient.createConnectionHighlevelSync(cfg.host, cfg.user, cfg.password, cfg.database),
    i = 0;

  conn.query("SELECT 1;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 4) {
      test.done();
    }
  });

  conn.query("SELECT 2;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 4) {
      test.done();
    }
  });

  conn.query("SELECT 3;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 4) {
      test.done();
    }
  });

  conn.query("SELECT 4;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 4) {
      test.done();
    }
  });
};

exports.QueryParallelWithSetQueryType = function (test) {
  test.expect(6);

  var
    conn = cfg.mysql_libmysqlclient.createConnectionHighlevelSync(cfg.host, cfg.user, cfg.password, cfg.database),
    i = 0;

  conn.query("SELECT 1;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 6) {
      test.done();
    }
  });

  conn.setQueryTypeSync('query');

  conn.query("SELECT 2;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 6) {
      test.done();
    }
  });

  conn.setQueryTypeSync('querySend');

  conn.query("SELECT 3;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 6) {
      test.done();
    }
  });

  conn.setQueryTypeSync('query');

  conn.query("SELECT 4;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 6) {
      test.done();
    }
  });

  conn.setQueryTypeSync('querySend');

  conn.query("SELECT 5;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 6) {
      test.done();
    }
  });

  conn.setQueryTypeSync('query');

  conn.query("SELECT 6;", function (err, res) {
    if (err) {
      throw err;
    }

    test.ok(res instanceof cfg.mysql_bindings.MysqlResult);

    i++;

    if (i == 6) {
      test.done();
    }
  });
};


text:
if(typeof exports === 'object') {
	var assert = require("assert");
	var alasql = require('..');
} else {
	__dirname = '.';
};

describe('Test 299 Parser Test', function() {

  it('1. CREATE DATABASE',function(done){
    alasql('CREATE DATABASE test299;USE test299');
    done();
  });

  it('2.Tests',function(done){
    var res = alasql(' AUTO_INCREMENT');
    console.log(res);
//      console.log(2,res);
    done();
  });

  it('99. DROP DATABASE',function(done){
    alasql('DROP DATABASE test299');
    done();
  });
});


text:
using System;
using Caliburn.Micro;
using Cortex.Core.Model;

namespace Cortex.Studio.Elements
{
    public abstract class EditorViewModel : PropertyChangedBase, IDisposable
    {
        public abstract string Name { get; }
        public INode Element { get; }

        protected EditorViewModel(INode element)
        {
            Element = element;
            foreach (var pin in element.Inputs)
            {
               // pin.AfterPinProcessed += AfterInputPinProcessed;
            }
        }

        public virtual void AfterInputPinProcessed(IInputPin input, object o) { }

        public virtual void Apply() { }
        public void Dispose()
        {
            if (Element != null)
            {
                foreach (var pin in Element.Inputs)
                {
                    //pin.AfterPinProcessed -= AfterInputPinProcessed;
                }
            }
        }
    }
}


text:
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: t -*-

/// @file	GCS_MAVLink.cpp

/*
This provides some support code and variables for MAVLink enabled sketches

This firmware is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
*/

#include <AP_HAL.h>
#include <AP_Common.h>
#include <GCS_MAVLink.h>

#ifdef MAVLINK_SEPARATE_HELPERS
#include "include/mavlink/v1.0/mavlink_helpers.h"
#endif

AP_HAL::BetterStream	*mavlink_comm_0_port;
AP_HAL::BetterStream	*mavlink_comm_1_port;

mavlink_system_t mavlink_system = {7,1,0,0};

uint8_t mavlink_check_target(uint8_t sysid, uint8_t compid)
{
    if (sysid != mavlink_system.sysid)
        return 1;
    // Currently we are not checking for correct compid since APM is not passing mavlink info to any subsystem
    // If it is addressed to our system ID we assume it is for us
    return 0; // no error
}

// return a MAVLink variable type given a AP_Param type
uint8_t mav_var_type(enum ap_var_type t)
{
    if (t == AP_PARAM_INT8) {
	    return MAVLINK_TYPE_INT8_T;
    }
    if (t == AP_PARAM_INT16) {
	    return MAVLINK_TYPE_INT16_T;
    }
    if (t == AP_PARAM_INT32) {
	    return MAVLINK_TYPE_INT32_T;
    }
    // treat any others as float
    return MAVLINK_TYPE_FLOAT;
}

/*
  send a buffer out a MAVLink channel
 */
void comm_send_buffer(mavlink_channel_t chan, const uint8_t *buf, uint8_t len)
{
    switch(chan) {
	case MAVLINK_COMM_0:
		mavlink_comm_0_port->write(buf, len);
		break;
	case MAVLINK_COMM_1:
		mavlink_comm_1_port->write(buf, len);
		break;
	default:
		break;
	}
}


text:
/**
 * DO NOT EDIT
 *
 * This file was automatically generated by
 *   https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
 *
 * To modify these typings, edit the source file(s):
 *   paper-button.html
 */

// tslint:disable:variable-name Describing an API that's defined elsewhere.

/// <reference path="../polymer/types/polymer.d.ts" />
/// <reference path="../iron-flex-layout/iron-flex-layout.d.ts" />
/// <reference path="../paper-behaviors/paper-button-behavior.d.ts" />
/// <reference path="../paper-styles/element-styles/paper-material-styles.d.ts" />

/**
 * Material design: [Buttons](https://www.google.com/design/spec/components/buttons.html)
 *
 * `paper-button` is a button. When the user touches the button, a ripple effect emanates
 * from the point of contact. It may be flat or raised. A raised button is styled with a
 * shadow.
 *
 * Example:
 *
 *     <paper-button>Flat button</paper-button>
 *     <paper-button raised>Raised button</paper-button>
 *     <paper-button noink>No ripple effect</paper-button>
 *     <paper-button toggles>Toggle-able button</paper-button>
 *
 * A button that has `toggles` true will remain `active` after being clicked (and
 * will have an `active` attribute set). For more information, see the `Polymer.IronButtonState`
 * behavior.
 *
 * You may use custom DOM in the button body to create a variety of buttons. For example, to
 * create a button with an icon and some text:
 *
 *     <paper-button>
 *       <iron-icon icon="favorite"></iron-icon>
 *       custom button content
 *     </paper-button>
 *
 * To use `paper-button` as a link, wrap it in an anchor tag. Since `paper-button` will already
 * receive focus, you may want to prevent the anchor tag from receiving focus as well by setting
 * its tabindex to -1.
 *
 *     <a href="https://www.polymer-project.org/" tabindex="-1">
 *       <paper-button raised>Polymer Project</paper-button>
 *     </a>
 *
 * ### Styling
 *
 * Style the button with CSS as you would a normal DOM element.
 *
 *     paper-button.fancy {
 *       background: green;
 *       color: yellow;
 *     }
 *
 *     paper-button.fancy:hover {
 *       background: lime;
 *     }
 *
 *     paper-button[disabled],
 *     paper-button[toggles][active] {
 *       background: red;
 *     }
 *
 * By default, the ripple is the same color as the foreground at 25% opacity. You may
 * customize the color using the `--paper-button-ink-color` custom property.
 *
 * The following custom properties and mixins are also available for styling:
 *
 * Custom property | Description | Default
 * ----------------|-------------|----------
 * `--paper-button-ink-color` | Background color of the ripple | `Based on the button's color`
 * `--paper-button` | Mixin applied to the button | `{}`
 * `--paper-button-disabled` | Mixin applied to the disabled button. Note that you can also use the `paper-button[disabled]` selector | `{}`
 * `--paper-button-flat-keyboard-focus` | Mixin applied to a flat button after it's been focused using the keyboard | `{}`
 * `--paper-button-raised-keyboard-focus` | Mixin applied to a raised button after it's been focused using the keyboard | `{}`
 */
interface PaperButtonElement extends Polymer.PaperButtonBehavior, Polymer.LegacyElementMixin, HTMLElement {

  /**
   * If true, the button should be styled with a shadow.
   */
  raised: boolean|null|undefined;
  _calculateElevation(): void;
}

interface HTMLElementTagNameMap {
  "paper-button": PaperButtonElement;
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
const utf8_1 = require("../util/utf8");
class Utf8Builder extends base_1.FlatListBuilder {
    writeValue(value, index = this.length) {
        return super.writeValue(utf8_1.encodeUtf8(value), index);
    }
}
exports.Utf8Builder = Utf8Builder;

//# sourceMappingURL=utf8.js.map


text:
/*
 *   This file is part of SGEA - Sistema de Gestão de Eventos Acadêmicos - TADS IFNMG Campus Januária.
 *
 *   SGEA is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   SGEA is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with SGEA.  If not, see <http://www.gnu.org/licenses/>.
 */
package br.edu.ifnmg.GerenciamentoEventos.Apresentacao.Converters;

import br.edu.ifnmg.DomainModel.MensagemPerfil;
import br.edu.ifnmg.DomainModel.Perfil;
import br.edu.ifnmg.DomainModel.Services.MensagemPerfilRepositorio;
import br.edu.ifnmg.GerenciamentoEventos.Aplicacao.GenericConverter;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.inject.Singleton;

/**
 *
 * @author petronio
 */
@Named(value = "mensagemPerfilConverter")
@Singleton
public class MensagemPerfilConverter
        extends GenericConverter<MensagemPerfil, MensagemPerfilRepositorio>
        implements Serializable {

    @EJB
    MensagemPerfilRepositorio dao;

    @PostConstruct
    public void init() {
        setRepositorio(dao);
    }

     public List<MensagemPerfil> autoCompletePerfil(String query) {
        MensagemPerfil i = new MensagemPerfil();
        i.setNome(query);
        return dao.Buscar(i);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="app.akexorcist.bluetoothspp" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Main"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SimpleActivity"
            android:label="@string/app_name" />
        <activity
            android:name=".ListenerActivity"
            android:label="@string/title_activity_listener" >
        </activity>
        <activity
            android:name=".AutoConnectActivity"
            android:label="@string/title_activity_auto_connect" >
        </activity>
        <activity
            android:name=".DeviceListActivity"
            android:label="@string/title_activity_device_list" >
        </activity>
        <activity
            android:name=".TerminalActivity"
            android:label="@string/title_activity_terminal" >
        </activity>
        <activity
            android:name=".GraphActivity"
            android:label="@string/title_activity_graph" >
        </activity>
    </application>

</manifest>


text:
package resources

import (
	"context"
	"errors"
	"fmt"
	"path/filepath"
	"runtime"
	"testing"

	"github.com/tektoncd/operator/pkg/reconciler/common"

	mfc "github.com/manifestival/client-go-client"
	mf "github.com/manifestival/manifestival"

	"knative.dev/pkg/test/logging"

	"github.com/tektoncd/operator/test/utils"
	"k8s.io/apimachinery/pkg/util/wait"

	"github.com/tektoncd/operator/pkg/apis/operator/v1alpha1"
	addonv1alpha1 "github.com/tektoncd/operator/pkg/client/clientset/versioned/typed/operator/v1alpha1"
	"github.com/tektoncd/operator/pkg/reconciler/openshift/tektonaddon"
	apierrs "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// EnsureTektonAddonExists creates a TektonAddon with the name names.TektonAddon, if it does not exist.
func EnsureTektonAddonExists(clients addonv1alpha1.TektonAddonInterface, names utils.ResourceNames) (*v1alpha1.TektonAddon, error) {
	// If this function is called by the upgrade tests, we only create the custom resource, if it does not exist.
	ks, err := clients.Get(context.TODO(), names.TektonAddon, metav1.GetOptions{})
	if apierrs.IsNotFound(err) {
		ks := &v1alpha1.TektonAddon{
			ObjectMeta: metav1.ObjectMeta{
				Name: names.TektonAddon,
			},
			Spec: v1alpha1.TektonAddonSpec{
				CommonSpec: v1alpha1.CommonSpec{
					TargetNamespace: names.TargetNamespace,
				},
			},
		}
		return clients.Create(context.TODO(), ks, metav1.CreateOptions{})
	}
	return ks, err
}

// WaitForTektonAddonState polls the status of the TektonAddon called name
// from client every `interval` until `inState` returns `true` indicating it
// is done, returns an error or timeout.
func WaitForTektonAddonState(clients addonv1alpha1.TektonAddonInterface, name string,
	inState func(s *v1alpha1.TektonAddon, err error) (bool, error)) (*v1alpha1.TektonAddon, error) {
	span := logging.GetEmitableSpan(context.Background(), fmt.Sprintf("WaitForTektonAddonState/%s/%s", name, "TektonAddonIsReady"))
	defer span.End()

	var lastState *v1alpha1.TektonAddon
	waitErr := wait.PollImmediate(utils.Interval, utils.Timeout, func() (bool, error) {
		lastState, err := clients.Get(context.TODO(), name, metav1.GetOptions{})
		return inState(lastState, err)
	})

	if waitErr != nil {
		return lastState, fmt.Errorf("tektonaddon %s is not in desired state, got: %+v: %w", name, lastState, waitErr)
	}
	return lastState, nil
}

// IsTektonAddonReady will check the status conditions of the TektonAddon and return true if the TektonAddon is ready.
func IsTektonAddonReady(s *v1alpha1.TektonAddon, err error) (bool, error) {
	return s.Status.IsReady(), err
}

// AssertTektonAddonCRReadyStatus verifies if the TektonAddon reaches the READY status.
func AssertTektonAddonCRReadyStatus(t *testing.T, clients *utils.Clients, names utils.ResourceNames) {
	if _, err := WaitForTektonAddonState(clients.TektonAddon(), names.TektonAddon,
		IsTektonAddonReady); err != nil {
		t.Fatalf("TektonAddonCR %q failed to get to the READY status: %v", names.TektonAddon, err)
	}
}

// AssertTektonInstallerSets verifies if the TektonInstallerSets are created.
func AssertTektonInstallerSets(t *testing.T, clients *utils.Clients) {
	assertInstallerSets(t, clients, tektonaddon.CommunityClusterTaskInstallerSet)
	assertInstallerSets(t, clients, tektonaddon.ClusterTaskInstallerSet)
	assertInstallerSets(t, clients, tektonaddon.VersionedClusterTaskInstallerSet)
	assertInstallerSets(t, clients, tektonaddon.PipelinesTemplateInstallerSet)
	assertInstallerSets(t, clients, tektonaddon.TriggersResourcesInstallerSet)
	assertInstallerSets(t, clients, tektonaddon.ConsoleCLIInstallerSet)
	assertInstallerSets(t, clients, tektonaddon.MiscellaneousResourcesInstallerSet)
}

func assertInstallerSets(t *testing.T, clients *utils.Clients, component string) {
	ls := metav1.LabelSelector{
		MatchLabels: map[string]string{
			v1alpha1.InstallerSetType: component,
		},
	}
	labelSelector, err := common.LabelSelector(ls)
	if err != nil {
		t.Fatal(err)
	}
	installerSets, err := clients.TektonInstallerSet().List(context.TODO(), metav1.ListOptions{
		LabelSelector: labelSelector,
	})
	if err != nil {
		t.Fatalf("failed to get TektonInstallerSet for %s : %v", component, err)
	}
	if len(installerSets.Items) > 1 {
		t.Fatalf("multiple installer sets for %s TektonInstallerSet", component)
	}
}

// TektonAddonCRDelete deletes tha TektonAddon to see if all resources will be deleted
func TektonAddonCRDelete(t *testing.T, clients *utils.Clients, crNames utils.ResourceNames) {
	if err := clients.TektonAddon().Delete(context.TODO(), crNames.TektonAddon, metav1.DeleteOptions{}); err != nil {
		t.Fatalf("TektonAddon %q failed to delete: %v", crNames.TektonAddon, err)
	}
	err := wait.PollImmediate(utils.Interval, utils.Timeout, func() (bool, error) {
		_, err := clients.TektonAddon().Get(context.TODO(), crNames.TektonAddon, metav1.GetOptions{})
		if apierrs.IsNotFound(err) {
			return true, nil
		}
		return false, err
	})
	if err != nil {
		t.Fatal("Timed out waiting on TektonAddon to delete", err)
	}
	_, b, _, _ := runtime.Caller(0)
	m, err := mfc.NewManifest(filepath.Join((filepath.Dir(b)+"/.."), "manifests/"), clients.Config)
	if err != nil {
		t.Fatal("Failed to load manifest", err)
	}
	if err := verifyNoTektonAddonCR(clients); err != nil {
		t.Fatal(err)
	}

	// verify all but the CRD's and the Namespace are gone
	for _, u := range m.Filter(mf.NoCRDs, mf.Not(mf.ByKind("Namespace"))).Resources() {
		if _, err := m.Client.Get(&u); !apierrs.IsNotFound(err) {
			t.Fatalf("The %s %s failed to be deleted: %v", u.GetKind(), u.GetName(), err)
		}
	}
	// verify all the CRD's remain
	for _, u := range m.Filter(mf.CRDs).Resources() {
		if _, err := m.Client.Get(&u); apierrs.IsNotFound(err) {
			t.Fatalf("The %s CRD was deleted", u.GetName())
		}
	}
}

func verifyNoTektonAddonCR(clients *utils.Clients) error {
	addons, err := clients.TektonAddonAll().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		return err
	}
	if len(addons.Items) > 0 {
		return errors.New("Unable to verify cluster-scoped resources are deleted if any TektonAddon exists")
	}
	return nil
}


text:
import os
from socket import timeout as socket_timeout
import unittest

from django.core.urlresolvers import reverse
from django import http

from glanceclient.common import exceptions as glance_exec

from mox3.mox import IsA
import six

from horizon import exceptions
from horizon import messages

from openstack_dashboard import api
from openstack_dashboard.dashboards.project.images import utils
from openstack_dashboard.test import helpers as test

INDEX_TEMPLATE = 'horizon/common/_data_table_view.html'
INDEX_URL = reverse('horizon:project:images:index')
CREATE_URL = reverse('horizon:project:images:images:create')

class ImagesAndSnapshotsTests(test.TestCase):
    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_index(self):
        images = self.images.list()
        api.glance.image_list_detailed(IsA(http.HttpRequest),
                                       marker=None, paginate=True,
                                       sort_dir='asc', sort_key='name',
                                       reversed_order=False) \
            .AndReturn([images, False, False])
        self.mox.ReplayAll()

        res = self.client.get(INDEX_URL)
        self.assertTemplateUsed(res, INDEX_TEMPLATE)
        self.assertContains(res, 'help_text="Deleted images'
                                 ' are not recoverable."')
        self.assertIn('images_table', res.context)
        images_table = res.context['images_table']
        images = images_table.data

        self.assertEqual(len(images), 9)
        row_actions = images_table.get_row_actions(images[0])
        self.assertEqual(len(row_actions), 5)
        row_actions = images_table.get_row_actions(images[1])
        self.assertEqual(len(row_actions), 3)
        self.assertNotIn('delete_image',
                         [a.name for a in row_actions])
        row_actions = images_table.get_row_actions(images[2])
        self.assertEqual(len(row_actions), 4)

    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_index_no_images(self):
        api.glance.image_list_detailed(IsA(http.HttpRequest),
                                       marker=None, paginate=True,
                                       sort_dir='asc', sort_key='name',
                                       reversed_order=False) \
            .AndReturn([(), False, False])
        self.mox.ReplayAll()

        res = self.client.get(INDEX_URL)
        self.assertTemplateUsed(res, INDEX_TEMPLATE)
        self.assertContains(res, 'No items to display')

    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_index_error(self):
        api.glance.image_list_detailed(IsA(http.HttpRequest),
                                       marker=None, paginate=True,
                                       sort_dir='asc', sort_key='name',
                                       reversed_order=False) \
            .AndRaise(self.exceptions.glance)
        self.mox.ReplayAll()

        res = self.client.get(INDEX_URL)
        self.assertTemplateUsed(res, INDEX_TEMPLATE)

    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_snapshot_actions(self):
        snapshots = self.snapshots.list()
        api.glance.image_list_detailed(IsA(http.HttpRequest),
                                       marker=None, paginate=True,
                                       sort_dir='asc', sort_key='name',
                                       reversed_order=False) \
            .AndReturn([snapshots, False, False])
        self.mox.ReplayAll()

        res = self.client.get(INDEX_URL)
        self.assertTemplateUsed(res, INDEX_TEMPLATE)
        self.assertIn('images_table', res.context)
        snaps = res.context['images_table']
        self.assertEqual(len(snaps.get_rows()), 3)

        row_actions = snaps.get_row_actions(snaps.data[0])

        # first instance - status active, owned
        self.assertEqual(len(row_actions), 5)
        self.assertEqual(row_actions[0].verbose_name, u"Launch")
        self.assertEqual(row_actions[1].verbose_name, u"Create Volume")
        self.assertEqual(row_actions[2].verbose_name, u"Edit Image")
        self.assertEqual(row_actions[3].verbose_name, u"Update Metadata")
        self.assertEqual(row_actions[4].verbose_name, u"Delete Image")

        row_actions = snaps.get_row_actions(snaps.data[1])

        # second instance - status active, not owned
        self.assertEqual(len(row_actions), 2)
        self.assertEqual(row_actions[0].verbose_name, u"Launch")
        self.assertEqual(row_actions[1].verbose_name, u"Create Volume")

        row_actions = snaps.get_row_actions(snaps.data[2])
        # third instance - status queued, only delete is available
        self.assertEqual(len(row_actions), 1)
        self.assertEqual(six.text_type(row_actions[0].verbose_name),
                         u"Delete Image")
        self.assertEqual(str(row_actions[0]), "<DeleteImage: delete>")

class ImagesAndSnapshotsUtilsTests(test.TestCase):

    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_list_image(self):
        public_images = [image for image in self.images.list()
                         if image.status == 'active' and image.is_public]
        private_images = [image for image in self.images.list()
                          if (image.status == 'active' and
                              not image.is_public)]
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'is_public': True, 'status': 'active'}) \
            .AndReturn([public_images, False, False])
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'property-owner_id': self.tenant.id,
                     'status': 'active'}) \
            .AndReturn([private_images, False, False])

        self.mox.ReplayAll()

        ret = utils.get_available_images(self.request, self.tenant.id)

        expected_images = [image for image in self.images.list()
                           if (image.status == 'active' and
                               image.container_format not in ('ami', 'aki'))]
        self.assertEqual(len(expected_images), len(ret))

    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_list_image_using_cache(self):
        public_images = [image for image in self.images.list()
                         if image.status == 'active' and image.is_public]
        private_images = [image for image in self.images.list()
                          if (image.status == 'active' and
                              not image.is_public)]
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'is_public': True, 'status': 'active'}) \
            .AndReturn([public_images, False, False])
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'property-owner_id': self.tenant.id,
                     'status': 'active'}) \
            .AndReturn([private_images, False, False])
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'property-owner_id': 'other-tenant',
                     'status': 'active'}) \
            .AndReturn([private_images, False, False])

        self.mox.ReplayAll()

        expected_images = [image for image in self.images.list()
                           if (image.status == 'active' and
                               image.container_format not in ('ari', 'aki'))]

        images_cache = {}
        ret = utils.get_available_images(self.request, self.tenant.id,
                                         images_cache)
        self.assertEqual(len(expected_images), len(ret))
        self.assertEqual(
            len(public_images),
            len(images_cache['public_images']))
        self.assertEqual(1, len(images_cache['images_by_project']))
        self.assertEqual(
            len(private_images),
            len(images_cache['images_by_project'][self.tenant.id]))

        ret = utils.get_available_images(self.request, self.tenant.id,
                                         images_cache)
        self.assertEqual(len(expected_images), len(ret))

        # image list for other-tenant
        ret = utils.get_available_images(self.request, 'other-tenant',
                                         images_cache)
        self.assertEqual(len(expected_images), len(ret))
        self.assertEqual(
            len(public_images),
            len(images_cache['public_images']))
        self.assertEqual(2, len(images_cache['images_by_project']))
        self.assertEqual(
            len(private_images),
            len(images_cache['images_by_project']['other-tenant']))

    @test.create_stubs({api.glance: ('image_list_detailed',),
                        exceptions: ('handle',)})
    def test_list_image_error_public_image_list(self):
        public_images = [image for image in self.images.list()
                         if image.status == 'active' and image.is_public]
        private_images = [image for image in self.images.list()
                          if (image.status == 'active' and
                              not image.is_public)]
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'is_public': True, 'status': 'active'}) \
            .AndRaise(self.exceptions.glance)
        exceptions.handle(IsA(http.HttpRequest),
                          "Unable to retrieve public images.")
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'property-owner_id': self.tenant.id,
                     'status': 'active'}) \
            .AndReturn([private_images, False, False])
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'is_public': True, 'status': 'active'}) \
            .AndReturn([public_images, False, False])

        self.mox.ReplayAll()

        images_cache = {}
        ret = utils.get_available_images(self.request, self.tenant.id,
                                         images_cache)

        expected_images = [image for image in private_images
                           if image.container_format not in ('ami', 'aki')]
        self.assertEqual(len(expected_images), len(ret))
        self.assertNotIn('public_images', images_cache)
        self.assertEqual(1, len(images_cache['images_by_project']))
        self.assertEqual(
            len(private_images),
            len(images_cache['images_by_project'][self.tenant.id]))

        ret = utils.get_available_images(self.request, self.tenant.id,
                                         images_cache)

        expected_images = [image for image in self.images.list()
                           if image.container_format not in ('ami', 'aki')]
        self.assertEqual(len(expected_images), len(ret))
        self.assertEqual(
            len(public_images),
            len(images_cache['public_images']))
        self.assertEqual(1, len(images_cache['images_by_project']))
        self.assertEqual(
            len(private_images),
            len(images_cache['images_by_project'][self.tenant.id]))

    @test.create_stubs({api.glance: ('image_list_detailed',),
                        messages: ('error',)})
    def test_list_image_communication_error_public_image_list(self):
        public_images = [image for image in self.images.list()
                         if image.status == 'active' and image.is_public]
        private_images = [image for image in self.images.list()
                          if (image.status == 'active' and
                              not image.is_public)]
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'is_public': True, 'status': 'active'}) \
            .AndRaise(glance_exec.CommunicationError)
        # Make sure the exception is handled with the correct
        # error message. If the exception cannot be handled,
        # the error message will be different.
        messages.error(IsA(http.HttpRequest),
                       "Unable to retrieve public images.")
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'property-owner_id': self.tenant.id,
                     'status': 'active'}) \
            .AndReturn([private_images, False, False])
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'is_public': True, 'status': 'active'}) \
            .AndReturn([public_images, False, False])

        self.mox.ReplayAll()

        images_cache = {}
        ret = utils.get_available_images(self.request, self.tenant.id,
                                         images_cache)

        expected_images = [image for image in private_images
                           if image.container_format not in ('ami', 'aki')]
        self.assertEqual(len(expected_images), len(ret))
        self.assertNotIn('public_images', images_cache)
        self.assertEqual(1, len(images_cache['images_by_project']))
        self.assertEqual(
            len(private_images),
            len(images_cache['images_by_project'][self.tenant.id]))

        ret = utils.get_available_images(self.request, self.tenant.id,
                                         images_cache)

        expected_images = [image for image in self.images.list()
                           if image.container_format not in ('ami', 'aki')]
        self.assertEqual(len(expected_images), len(ret))
        self.assertEqual(
            len(public_images),
            len(images_cache['public_images']))
        self.assertEqual(1, len(images_cache['images_by_project']))
        self.assertEqual(
            len(private_images),
            len(images_cache['images_by_project'][self.tenant.id]))

    @test.create_stubs({api.glance: ('image_list_detailed',),
                        exceptions: ('handle',)})
    def test_list_image_error_private_image_list(self):
        public_images = [image for image in self.images.list()
                         if image.status == 'active' and image.is_public]
        private_images = [image for image in self.images.list()
                          if (image.status == 'active' and
                              not image.is_public)]
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'is_public': True, 'status': 'active'}) \
            .AndReturn([public_images, False, False])
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'property-owner_id': self.tenant.id,
                     'status': 'active'}) \
            .AndRaise(self.exceptions.glance)
        exceptions.handle(IsA(http.HttpRequest),
                          "Unable to retrieve images for the current project.")
        api.glance.image_list_detailed(
            IsA(http.HttpRequest),
            filters={'property-owner_id': self.tenant.id,
                     'status': 'active'}) \
            .AndReturn([private_images, False, False])

        self.mox.ReplayAll()

        images_cache = {}
        ret = utils.get_available_images(self.request, self.tenant.id,
                                         images_cache)

        expected_images = [image for image in public_images
                           if image.container_format not in ('ami', 'aki')]
        self.assertEqual(len(expected_images), len(ret))
        self.assertEqual(
            len(public_images),
            len(images_cache['public_images']))
        self.assertFalse(len(images_cache['images_by_project']))

        ret = utils.get_available_images(self.request, self.tenant.id,
                                         images_cache)

        expected_images = [image for image in self.images.list()
                           if image.container_format not in ('ami', 'aki')]
        self.assertEqual(len(expected_images), len(ret))
        self.assertEqual(
            len(public_images),
            len(images_cache['public_images']))
        self.assertEqual(1, len(images_cache['images_by_project']))
        self.assertEqual(
            len(private_images),
            len(images_cache['images_by_project'][self.tenant.id]))

class SeleniumTests(test.SeleniumTestCase):
    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_modal_create_image_from_url(self):
        driver = self.selenium
        images = self.images.list()
        api.glance.image_list_detailed(IsA(http.HttpRequest),
                                       marker=None).AndReturn([images,
                                                               False, False])
        filters = {'disk_format': 'aki'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        filters = {'disk_format': 'ari'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        self.mox.ReplayAll()

        driver.get("%s%s" % (self.live_server_url, INDEX_URL))

        # Open the modal menu
        driver.find_element_by_id("images__action_create").send_keys("\n")
        wait = self.ui.WebDriverWait(self.selenium, 10,
                                     ignored_exceptions=[socket_timeout])
        wait.until(lambda x: driver.find_element_by_id("id_disk_format"))

        srctypes = self.ui.Select(driver.find_element_by_id("id_source_type"))
        srctypes.select_by_value("url")
        copyfrom = driver.find_element_by_id("id_image_url")
        copyfrom.send_keys("http://www.test.com/test.iso")
        formats = self.ui.Select(driver.find_element_by_id("id_disk_format"))
        body = formats.first_selected_option
        self.assertIn("ISO", body.text,
                      "ISO should be selected when the extension is *.iso")

    @unittest.skipIf(os.environ.get('SELENIUM_PHANTOMJS'),
                     "PhantomJS cannot test file upload widgets.")
    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_modal_create_image_from_file(self):
        driver = self.selenium
        images = self.images.list()
        api.glance.image_list_detailed(IsA(http.HttpRequest),
                                       marker=None).AndReturn([images,
                                                               False, False])
        filters = {'disk_format': 'aki'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        filters = {'disk_format': 'ari'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        self.mox.ReplayAll()

        driver.get("%s%s" % (self.live_server_url, INDEX_URL))

        # Open the modal menu
        driver.find_element_by_id("images__action_create").send_keys("\n")
        wait = self.ui.WebDriverWait(driver, 10,
                                     ignored_exceptions=[socket_timeout])
        wait.until(lambda x: driver.find_element_by_id("id_disk_format"))

        srctypes = self.ui.Select(driver.find_element_by_id("id_source_type"))
        srctypes.select_by_value("file")
        driver.find_element_by_id("id_image_file").send_keys("/tmp/test.iso")
        formats = self.ui.Select(driver.find_element_by_id("id_disk_format"))
        body = formats.first_selected_option
        self.assertIn("ISO", body.text,
                      "ISO should be selected when the extension is *.iso")

    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_create_image_from_url(self):
        driver = self.selenium
        filters = {'disk_format': 'aki'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        filters = {'disk_format': 'ari'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        self.mox.ReplayAll()

        driver.get("%s%s" % (self.live_server_url, CREATE_URL))
        wait = self.ui.WebDriverWait(driver, 10,
                                     ignored_exceptions=[socket_timeout])
        wait.until(lambda x: driver.find_element_by_id("id_disk_format"))

        srctypes = self.ui.Select(driver.find_element_by_id("id_source_type"))
        srctypes.select_by_value("url")
        copyfrom = driver.find_element_by_id("id_image_url")
        copyfrom.send_keys("http://www.test.com/test.iso")
        formats = self.ui.Select(driver.find_element_by_id("id_disk_format"))
        body = formats.first_selected_option
        self.assertIn("ISO", body.text,
                      "ISO should be selected when the extension is *.iso")

    @unittest.skipIf(os.environ.get('SELENIUM_PHANTOMJS'),
                     "PhantomJS cannot test file upload widgets.")
    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_create_image_from_file(self):
        driver = self.selenium
        filters = {'disk_format': 'aki'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        filters = {'disk_format': 'ari'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        self.mox.ReplayAll()

        driver.get("%s%s" % (self.live_server_url, CREATE_URL))
        wait = self.ui.WebDriverWait(driver, 10,
                                     ignored_exceptions=[socket_timeout])
        wait.until(lambda x: driver.find_element_by_id("id_disk_format"))

        srctypes = self.ui.Select(driver.find_element_by_id("id_source_type"))
        srctypes.select_by_value("file")
        driver.find_element_by_id("id_image_file").send_keys("/tmp/test.iso")
        formats = self.ui.Select(driver.find_element_by_id("id_disk_format"))
        body = formats.first_selected_option
        self.assertIn("ISO", body.text,
                      "ISO should be selected when the extension is *.iso")


text:
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//+build i386 amd64
package loader

/*
#include <asm/types.h>
#include <linux/const.h>
#include <string.h>
#include <asm/bootparam.h>

// E820 codes.
const int E820Ram = E820_RAM;
const int E820Reserved = E820_RESERVED;
const int E820Acpi = E820_ACPI;

// Our E820 map.
static inline void e820_set_count(
    struct boot_params* boot,
    int count) {

    boot->e820_entries = count;
}
static inline void e820_set_region(
    struct boot_params* boot,
    int index,
    __u64 start,
    __u64 size,
    __u8 type) {

    boot->e820_map[index].addr = start;
    boot->e820_map[index].size = size;
    boot->e820_map[index].type = type;
}
static inline void set_header(
    struct boot_params* boot,
    __u64 initrd_addr,
    __u64 initrd_len,
    __u64 cmdline_addr) {

    boot->hdr.vid_mode = 0xffff;
    boot->hdr.type_of_loader = 0xff;
    boot->hdr.loadflags = 0;
    boot->hdr.setup_move_size = 0;
    boot->hdr.ramdisk_image = initrd_addr;
    boot->hdr.ramdisk_size = initrd_len;
    boot->hdr.heap_end_ptr = 0;
    boot->hdr.cmd_line_ptr = cmdline_addr;
    boot->hdr.setup_data = 0;
}
*/
import "C"

import (
	"novmm/machine"
	"novmm/platform"
	"unsafe"
)

func SetupLinuxBootParams(
	model *machine.Model,
	boot_params_data []byte,
	orig_boot_params_data []byte,
	cmdline_addr platform.Paddr,
	initrd_addr platform.Paddr,
	initrd_len uint64) error {

	// Grab a reference to our boot params struct.
	boot_params := (*C.struct_boot_params)(unsafe.Pointer(&boot_params_data[0]))

	// The setup header.
	// First step is to copy the existing setup_header
	// out of the given kernel image. We copy only the
	// header, and not the rest of the setup page.
	setup_start := 0x01f1
	setup_end := 0x0202 + int(orig_boot_params_data[0x0201])
	if setup_end > platform.PageSize {
		return InvalidSetupHeader
	}
	C.memcpy(
		unsafe.Pointer(&boot_params_data[setup_start]),
		unsafe.Pointer(&orig_boot_params_data[setup_start]),
		C.size_t(setup_end-setup_start))

	// Setup our BIOS memory map.
	// NOTE: We have to do this via C bindings. This is really
	// annoying, but basically because of the unaligned structures
	// in the struct_boot_params, the Go code generated here is
	// actually *incompatible* with the actual C layout.

	// First, the count.
	C.e820_set_count(boot_params, C.int(len(model.MemoryMap)))

	// Then, fill out the region information.
	for index, region := range model.MemoryMap {

		var memtype C.int
		switch region.MemoryType {
		case machine.MemoryTypeUser:
			memtype = C.E820Ram
		case machine.MemoryTypeReserved:
			memtype = C.E820Reserved
		case machine.MemoryTypeSpecial:
			memtype = C.E820Reserved
		case machine.MemoryTypeAcpi:
			memtype = C.E820Acpi
		}

		C.e820_set_region(
			boot_params,
			C.int(index),
			C.__u64(region.Start),
			C.__u64(region.Size),
			C.__u8(memtype))
	}

	// Set necessary setup header bits.
	C.set_header(
		boot_params,
		C.__u64(initrd_addr),
		C.__u64(initrd_len),
		C.__u64(cmdline_addr))

	// All done!
	return nil
}


text:
.. include:: references.txt

.. _astropy-coordinates-high-level:

Using the SkyCoord High-level Class
-----------------------------------

The |SkyCoord| class provides a simple and flexible user interface for
celestial coordinate representation, manipulation, and transformation between
coordinate frames.  This is a high-level class that serves as a wrapper
around the low-level coordinate frame classes like `~astropy.coordinates.ICRS`
and `~astropy.coordinates.FK5` which do most of the heavy lifting.

The key distinctions between |SkyCoord| and the low-level classes
(:doc:`frames`) are as follows:

- The |SkyCoord| object can maintain the union of frame attributes for all
  built-in and user-defined coordinate frames in the
  ``astropy.coordinates.frame_transform_graph``.  Individual frame classes hold
  only the required attributes (e.g. equinox, observation time or observer
  location) for that frame.  This means that a transformation from
  `~astropy.coordinates.FK4` (with equinox and observation time) to
  `~astropy.coordinates.ICRS` (with neither) and back to
  `~astropy.coordinates.FK4` via the low-level classes would not remember the
  original equinox and observation time.  Since the |SkyCoord| object stores
  all attributes, such a round-trip transformation will return to the same
  coordinate object.

- The |SkyCoord| class is more flexible with inputs to accommodate a wide
  variety of user preferences and available data formats.

- The |SkyCoord| class has a number of convenience methods that are useful
  in typical analysis.

- At present, |SkyCoord| objects can use only coordinate frames that have
  transformations defined in the ``astropy.coordinates.frame_transform_graph``
  transform graph object.

Creating SkyCoord objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^

The |SkyCoord| class accepts a wide variety of inputs for initialization.
At a minimum these must provide one or more celestial coordinate values
with unambiguous units.  Typically one also specifies the coordinate
frame, though this is not required.

Common patterns are shown below.  In this description the values in upper
case like ``COORD`` or ``FRAME`` represent inputs which are described in detail
in the `Initialization Syntax`_ section.  Elements in square brackets like
``[unit=UNIT]`` are optional.
::

  SkyCoord(COORD, [FRAME], keyword_args ...)
  SkyCoord(LON, LAT, [frame=FRAME], [unit=UNIT], keyword_args ...)
  SkyCoord([FRAME], <lon_attr>=LON, <lat_attr>=LAT, keyword_args ...)

The examples below illustrate common ways of initializing a |SkyCoord| object.
These all reflect initializing using spherical coordinates, which is the
default for all built-in frames.  In order to understand working with coordinates
using a different representation such as cartesian or cylindrical, see the
section on `Representations`_.  First some imports::

  >>> from astropy.coordinates import SkyCoord  # High-level coordinates
  >>> from astropy.coordinates import ICRS, Galactic, FK4, FK5  # Low-level frames
  >>> from astropy.coordinates import Angle, Latitude, Longitude  # Angles
  >>> import astropy.units as u
  >>> import numpy as np

The coordinate values and frame specification can now be provided using
positional and keyword arguments.  First we show positional arguments for
RA and Dec::

  >>> SkyCoord(10, 20, unit='deg')  # Defaults to ICRS
  <SkyCoord (ICRS): (ra, dec) in deg
      ( 10.,  20.)>

  >>> SkyCoord([1, 2, 3], [-30, 45, 8], frame='icrs', unit='deg')
  <SkyCoord (ICRS): (ra, dec) in deg
      [( 1., -30.), ( 2., 45.), ( 3.,   8.)]>

Notice that the first example above does not explicitly give a frame.  In
this case, the default is taken to be the ICRS system (approximately
correct for "J2000" equatorial coordinates).  It is always better to
explicitly specify the frame when it is known to be ICRS, however, as
anyone reading the code will be better able to understand the intent.

String inputs in common formats are acceptable, and the frame can be supplied
as either a class type like `~astropy.coordinates.FK4`, an instance of a
frame class, a `~astropy.coordinates.SkyCoord` instance (from which the frame
will be extracted), or the lower-case version of a frame name as a string,
e.g. ``"fk4"``::

  >>> coords = ["1:12:43.2 +1:12:43", "1 12 43.2 +1 12 43"]
  >>> sc = SkyCoord(coords, frame=FK4, unit=(u.hourangle, u.deg), obstime="J1992.21")
  >>> sc = SkyCoord(coords, frame=FK4(obstime="J1992.21"), unit=(u.hourangle, u.deg))
  >>> sc = SkyCoord(coords, frame='fk4', unit='hourangle,deg', obstime="J1992.21")

  >>> sc = SkyCoord("1h12m43.2s", "+1d12m43s", frame=Galactic)  # Units from strings
  >>> sc = SkyCoord("1h12m43.2s +1d12m43s", frame=Galactic)  # Units from string
  >>> sc = SkyCoord(l="1h12m43.2s", b="+1d12m43s", frame='galactic')
  >>> sc = SkyCoord("1h12.72m +1d12.71m", frame='galactic')

Note that frame instances with data and `~astropy.coordinates.SkyCoord` instances
can only be passed as frames using the ``frame=`` keyword argument and not as
positional arguments.

For representations that have ``ra`` and ``dec`` attributes one can supply a coordinate
string in a number of other common formats.  Examples include::

  >>> sc = SkyCoord("15h17+89d15")
  >>> sc = SkyCoord("275d11m15.6954s+17d59m59.876s")
  >>> sc = SkyCoord("8 00 -5 00.6", unit=(u.hour, u.deg))
  >>> sc = SkyCoord("J080000.00-050036.00", unit=(u.hour, u.deg))
  >>> sc = SkyCoord("J1874221.31+122328.03", unit=u.deg)

Astropy `~astropy.units.Quantity`-type objects are acceptable and encouraged
as a form of input::

  >>> ra = Longitude([1, 2, 3], unit=u.deg)  # Could also use Angle
  >>> dec = np.array([4.5, 5.2, 6.3]) * u.deg  # Astropy Quantity
  >>> sc = SkyCoord(ra, dec, frame='icrs')
  >>> sc = SkyCoord(ra=ra, dec=dec, frame=ICRS, obstime='2001-01-02T12:34:56')

Finally it is possible to initialize from a low-level coordinate frame object.

  >>> c = FK4(1 * u.deg, 2 * u.deg)
  >>> sc = SkyCoord(c, obstime='J2010.11', equinox='B1965')  # Override defaults

A key subtlety highlighted here is that when low-level objects are created they have
certain default attribute values.  For instance the `~astropy.coordinates.FK4`
frame uses ``equinox='B1950.0`` and ``obstime=equinox`` as defaults.  If
this object is used to initialize a |SkyCoord| it is possible to override
the low-level object attributes that were not explicitly set.  If the
coordinate above were created with
``c = FK4(1 * u.deg, 2 * u.deg, equinox='B1960')`` then creating a |SkyCoord|
with a different ``equinox`` would raise an exception.

Initialization Syntax
"""""""""""""""""""""

For spherical representations, which are the most common and are the default
input format for all built-in frames, the syntax for |SkyCoord| is given
below::

  SkyCoord(COORD, [FRAME | frame=FRAME], [unit=UNIT], keyword_args ...)
  SkyCoord(LON, LAT, [DISTANCE], [FRAME | frame=FRAME], [unit=UNIT], keyword_args ...)
  SkyCoord([FRAME | frame=FRAME], <lon_name>=LON, <lat_name>=LAT, [unit=UNIT],
           keyword_args ...)

In the above description, elements in all capital letters (e.g. ``FRAME``)
describes a user input of that element type.  Elements in square brackets are
optional.  For non-spherical inputs see the `Representations`_ section.

**LON**, **LAT**

Longitude and latitude value can be specified as separate positional arguments.
The following options are available for longitude and latitude:

- Single angle value:

  - |Quantity| object
  - Plain numeric value with ``unit`` keyword specifying the unit
  - Angle string which is formatted for :ref:`angle-creation` of
    |Longitude| or |Latitude| objects

- List or |Quantity| array or numpy array of angle values
- |Angle|, |Longitude|, or |Latitude| object, which can be scalar or
  array-valued

**DISTANCE**

The distance to the object from the frame center can be optionally specified:

- Single distance value:

  - |Quantity| or `~astropy.coordinates.Distance` object
  - Plain numeric value for a dimensionless distance
  - Plain numeric value with ``unit`` keyword specifying the unit

- List or |Quantity| or `~astropy.coordinates.Distance` array or numpy array of
  angle values

**COORD**

This input form uses a single object to supply coordinate data.  For the case
of spherical coordinate frames, the coordinate can include one or more
longitude and latitude pairs in one of the following ways:

- Single coordinate string with a LON and LAT value separated by a space.  The
  respective values can be any string which is formatted for
  :ref:`angle-creation` of |Longitude| or |Latitude| objects, respectively.
- List or numpy array of such coordinate strings
- List of (LON, LAT) tuples, where each LON and LAT are scalars (not arrays)
- ``N x 2`` numpy or |Quantity| array of values where the first column is
  longitude and the second column is latitude, e.g.
  ``[[270, -30], [355, +85]] * u.deg``
- List of (LON, LAT, DISTANCE) tuples
- ``N x 3`` numpy or |Quantity| array of values where columns are
  longitude, latitude, and distance respectively.

The input can also be more generalized objects that are not necessarily
represented in the standard spherical coordinates:

- Coordinate frame object, e.g. ``FK4(1*u.deg, 2*u.deg, obstime='J2012.2')``
- |SkyCoord| object (which just makes a copy of the object)
- `~astropy.coordinates.BaseRepresentation` subclass object like
  `~astropy.coordinates.SphericalRepresentation`,
  `~astropy.coordinates.CylindricalRepresentation`,  or
  `~astropy.coordinates.CartesianRepresentation`.

**FRAME**

This can be a `~astropy.coordinates.BaseCoordinateFrame` frame class, an
instance of such a class, or the corresponding string alias. The frame
classes that are built in to astropy are `~astropy.coordinates.ICRS`,
`~astropy.coordinates.FK5`, `~astropy.coordinates.FK4`,
`~astropy.coordinates.FK4NoETerms`, `~astropy.coordinates.Galactic`, and
`~astropy.coordinates.AltAz`. The string aliases are simply lower-case
versions of the class name.

If the frame is not supplied then you will see a special ``ICRS``
identifier.  This indicates that the frame is unspecified and operations
that require comparing coordinates (even within that object) are not allowed.

**unit=UNIT**

The unit specifier can be one of the following:

- `~astropy.units.Unit` object which is an angular unit that is equivalent to
  ``Unit('radian')``
- Single string with a valid angular unit name
- 2-tuple of `~astropy.units.Unit` objects or string unit names specifying the
  LON and LAT unit respectively, e.g. ``('hourangle', 'degree')``
- Single string with two unit names separated by a comma, e.g. ``'hourangle,degree'``

If only a single unit is provided then it applies to both LON and LAT.

**Other keyword arguments**

In lieu of positional arguments to specify the longitude and latitude, the
frame-specific names can be used as keyword arguments:

*ra*, *dec*: **LON**, **LAT** values, optional
    RA and Dec for frames where these are representation, including [FIXME]
    `~astropy.coordinates.ICRS`, `~astropy.coordinates.FK5`,
    `~astropy.coordinates.FK4`, and `~astropy.coordinates.FK4NoETerms`.

*l*, *b*:  **LON**, **LAT** values, optional
    Galactic ``l`` and ``b`` for the `~astropy.coordinates.Galactic` frame.

The following keywords can be specified for any frame:

*distance*: valid `~astropy.coordinates.Distance` initializer, optional
    Distance from reference from center to source.

*obstime*: valid `~astropy.time.Time` initializer, optional
    Time of observation

*equinox*: valid `~astropy.time.Time` initializer, optional
    Coordinate frame equinox

If custom user-defined frames are included in the transform graph and they
have additional frame attributes, then those attributes can also be
set via corresponding keyword args in the |SkyCoord| initialization.

.. _astropy-coordinates-array-operations:

Array operations
^^^^^^^^^^^^^^^^^

It is possible to store arrays of coordinates in a |SkyCoord| object, and
manipulations done in this way will be orders of magnitude faster than
looping over a list of individual |SkyCoord| objects::

  >>> ra = np.linspace(0, 36000, 1001) * u.deg
  >>> dec = np.linspace(-90, 90, 1001) * u.deg

  >>> sc_list = [SkyCoord(r, d, frame='icrs') for r, d in zip(ra, dec)]  # doctest: +SKIP
  >>> timeit sc_gal_list = [c.galactic for c in sc_list]  # doctest: +SKIP
  1 loops, best of 3: 20.4 s per loop

  >>> sc = SkyCoord(ra, dec, frame='icrs')
  >>> timeit sc_gal = sc.galactic  # doctest: +SKIP
  100 loops, best of 3: 21.8 ms per loop

In addition to vectorized transformations, you can do the usual array slicing,
dicing, and selection, using the same methods and attributes that one uses for
`~numpy.ndarray` instances::

  >>> north_mask = sc.dec > 0
  >>> sc_north = sc[north_mask]
  >>> len(sc_north)
  500
  >>> sc[2:4]  # doctest: +FLOAT_CMP
  <SkyCoord (ICRS): (ra, dec) in deg
      [(  72., -89.64), ( 108., -89.46)]>
  >>> sc[500]  # doctest: +FLOAT_CMP
  <SkyCoord (ICRS): (ra, dec) in deg
      ( 0.,  0.)>
  >>> sc[0:-1:100].reshape(2, 5)  # doctest: +FLOAT_CMP
  <SkyCoord (ICRS): (ra, dec) in deg
      [[( 0., -90.), ( 0., -72.), ( 0., -54.), ( 0., -36.), ( 0., -18.)],
       [( 0.,   0.), ( 0.,  18.), ( 0.,  36.), ( 0.,  54.), ( 0.,  72.)]]>

Note that similarly to the `~numpy.ndarray` methods, all but ``flatten`` try to
use new views of the data, with the data copied only if that it is impossible
(as discussed, e.g., in the documentation for numpy :func:`~numpy.reshape`).

Attributes
^^^^^^^^^^^

The |SkyCoord| object has a number of useful attributes which come in handy.
By digging through these we'll learn a little bit about |SkyCoord| and how it
works.

To begin (if you don't know already) one of the most important tools for
learning about attributes and methods of objects is "TAB-discovery".  From
within IPython you can type an object name, the period, and then the <TAB> key
to see what's available.  This can often be faster than reading the
documentation::

  >>> sc = SkyCoord(1, 2, frame='icrs', unit='deg', obstime='2013-01-02 14:25:36')
  >>> sc.<TAB>  # doctest: +SKIP
  sc.T                                   sc.match_to_catalog_3d
  sc.altaz                               sc.match_to_catalog_sky
  sc.barycentrictrueecliptic             sc.name
  sc.cartesian                           sc.ndim
  sc.cirs                                sc.obsgeoloc
  sc.copy                                sc.obsgeovel
  sc.data                                sc.obstime
  sc.dec                                 sc.obswl
  sc.default_representation              sc.position_angle
  sc.diagonal                            sc.precessedgeocentric
  sc.distance                            sc.pressure
  sc.equinox                             sc.ra
  sc.fk4                                 sc.ravel
  sc.fk4noeterms                         sc.realize_frame
  sc.fk5                                 sc.relative_humidity
  sc.flatten                             sc.represent_as
  sc.frame                               sc.representation
  sc.frame_attributes                    sc.representation_component_names
  sc.frame_specific_representation_info  sc.representation_component_units
  sc.from_name                           sc.representation_info
  sc.from_pixel                          sc.reshape
  sc.galactic                            sc.roll
  sc.galactocentric                      sc.search_around_3d
  sc.galcen_dec                          sc.search_around_sky
  sc.galcen_distance                     sc.separation
  sc.galcen_ra                           sc.separation_3d
  sc.gcrs                                sc.shape
  sc.geocentrictrueecliptic              sc.size
  sc.get_constellation                   sc.skyoffset_frame
  sc.get_frame_attr_names                sc.spherical
  sc.guess_from_table                    sc.spherical_offsets_to
  sc.has_data                            sc.squeeze
  sc.hcrs                                sc.supergalactic
  sc.heliocentrictrueecliptic            sc.swapaxes
  sc.icrs                                sc.take
  sc.info                                sc.temperature
  sc.is_equivalent_frame                 sc.to_pixel
  sc.is_frame_attr_default               sc.to_string
  sc.is_transformable_to                 sc.transform_to
  sc.isscalar                            sc.transpose
  sc.itrs                                sc.z_sun
  sc.location

Here we see a bunch of stuff there but much of it should be recognizable or
easily guessed.  The most obvious may be the longitude and latitude attributes
which are named ``ra`` and ``dec`` for the ``ICRS`` frame::

  >>> sc.ra
  <Longitude 1.0 deg>
  >>> sc.dec
  <Latitude 2.0 deg>

Next notice that all the built-in frame names ``icrs``, ``galactic``, ``fk5``
``fk4``, and ``fk4noeterms`` are there.  Through the magic of Python
properties, accessing these attributes calls the object
`~astropy.coordinates.SkyCoord.transform_to` method appropriately and returns a
new |SkyCoord| object in the requested frame::

  >>> sc_gal = sc.galactic
  >>> sc_gal  # doctest: +FLOAT_CMP
  <SkyCoord (Galactic): (l, b) in deg
      ( 99.63785528, -58.70969293)>

Other attributes you should recognize are ``distance``, ``equinox``,
``obstime``, ``shape``.

Digger deeper
"""""""""""""
*[Casual users can skip this section]*

After transforming to Galactic the longitude and latitude values are now
labeled ``l`` and ``b``, following the normal convention for Galactic
coordinates.  How does the object know what to call its values?  The answer
lies in some less-obvious attributes::

  >>> sc_gal.representation_component_names
  OrderedDict([('l', 'lon'), ('b', 'lat'), ('distance', 'distance')])

  >>> sc_gal.representation_component_units
  OrderedDict([('l', Unit("deg")), ('b', Unit("deg"))])

  >>> sc_gal.representation
  <class 'astropy.coordinates.representation.SphericalRepresentation'>

Together these tell the object that ``l`` and ``b`` are the longitude and
latitude, and that they should both be displayed in units of degrees as
a spherical-type coordinate (and not, e.g. a cartesian coordinate).
Furthermore the frame's ``representation_component_names`` attribute defines
the coordinate keyword arguments that |SkyCoord| will accept.

Another important attribute is ``frame_attr_names``, which defines the
additional attributes that are required to fully define the frame::

  >>> sc_fk4 = SkyCoord(1, 2, frame='fk4', unit='deg')
  >>> sc_fk4.get_frame_attr_names()
  OrderedDict([('equinox', <Time object: scale='tai' format='byear_str' value=B1950.000>), ('obstime', None)])

The key values correspond to the defaults if no explicit value is provide by
the user.  This example shows that the `~astropy.coordinates.FK4` frame has two
attributes ``equinox`` and ``obstime`` that are required to fully define the
frame.

Some trickery is happening here because many of these attributes are
actually owned by the underlying coordinate ``frame`` object which does much of
the real work.  This is the middle layer in the three-tiered system of objects:
representation (spherical, cartesian, etc.), frame (aka low-level frame class),
and |SkyCoord| (aka high-level class; see :ref:`astropy-coordinates-overview`
and :ref:`astropy-coordinates-definitions`)::

  >>> sc.frame
  <ICRS Coordinate: (ra, dec) in deg
      ( 1.,  2.)>

  >>> sc.has_data is sc.frame.has_data
  True

  >>> sc.frame.<TAB>  # doctest: +SKIP
  sc.frame.T                                   sc.frame.ra
  sc.frame.cartesian                           sc.frame.ravel
  sc.frame.copy                                sc.frame.realize_frame
  sc.frame.data                                sc.frame.represent_as
  sc.frame.dec                                 sc.frame.representation
  sc.frame.default_representation              sc.frame.representation_component_names
  sc.frame.diagonal                            sc.frame.representation_component_units
  sc.frame.distance                            sc.frame.representation_info
  sc.frame.flatten                             sc.frame.reshape
  sc.frame.frame_attributes                    sc.frame.separation
  sc.frame.frame_specific_representation_info  sc.frame.separation_3d
  sc.frame.get_frame_attr_names                sc.frame.shape
  sc.frame.has_data                            sc.frame.size
  sc.frame.is_equivalent_frame                 sc.frame.spherical
  sc.frame.is_frame_attr_default               sc.frame.squeeze
  sc.frame.is_transformable_to                 sc.frame.swapaxes
  sc.frame.isscalar                            sc.frame.take
  sc.frame.name                                sc.frame.transform_to
  sc.frame.ndim                                sc.frame.transpose

  >>> sc.frame.name
  'icrs'

The |SkyCoord| object exposes the ``frame`` object attributes as its own. Though
it might seem a tad confusing at first, this a good thing because it makes
|SkyCoord| objects and `~astropy.coordinates.BaseCoordinateFrame` objects
behave very similarly and most routines can accept either one as input without
much bother (duck typing!).

The lowest layer in the stack is the abstract
`~astropy.coordinates.UnitSphericalRepresentation` object:

  >>> sc_gal.frame.data  # doctest: +FLOAT_CMP
  <UnitSphericalRepresentation (lon, lat) in rad
      ( 1.73900863, -1.02467744)>

Transformations
^^^^^^^^^^^^^^^^^

The topic of transformations is covered in detail in the section on
:ref:`astropy-coordinates-transforming`.

For completeness here we will give some simple examples.  Once you've defined
your coordinates and the reference frame, you can transform from that frame to
another frame.  You can do this a few different ways: if you just want the
default version of that frame, you can use attribute-style access (as mentioned
previously).  For more control, you can use the
`~astropy.coordinates.SkyCoord.transform_to` method, which accepts a frame
name, frame class, frame instance, or |SkyCoord|::

  >>> from astropy.coordinates import FK5
  >>> sc = SkyCoord(1, 2, frame='icrs', unit='deg')
  >>> sc.galactic  # doctest: +FLOAT_CMP
  <SkyCoord (Galactic): (l, b) in deg
      ( 99.63785528, -58.70969293)>

  >>> sc.transform_to('fk5')  # Same as sc.fk5 and sc.transform_to(FK5)  # doctest: +FLOAT_CMP
  <SkyCoord (FK5: equinox=J2000.000): (ra, dec) in deg
          ( 1.00000656,  2.00000243)>

  >>> sc.transform_to(FK5(equinox='J1975'))  # Transform to FK5 with a different equinox  # doctest: +FLOAT_CMP
  <SkyCoord (FK5: equinox=J1975.000): (ra, dec) in deg
          ( 0.67967282,  1.86083014)>

Transforming to a |SkyCoord| instance is an easy way of ensuring that two
coordinates are in the exact same reference frame::

  >>> sc2 = SkyCoord(3, 4, frame='fk4', unit='deg', obstime='J1978.123', equinox='B1960.0')
  >>> sc.transform_to(sc2)  # doctest: +FLOAT_CMP
  <SkyCoord (FK4: equinox=B1960.000, obstime=J1978.123): (ra, dec) in deg
      ( 0.48726331,  1.77731617)>

.. _astropy-skycoord-representations:

Representations
^^^^^^^^^^^^^^^^

So far we have been using a spherical coordinate representation in the all the
examples, and this is the default for the built-in frames.  Frequently it is
convenient to initialize or work with a coordinate using a different
representation such as cartesian or cylindrical.  In this section we discuss
how to initialize an object using a different representation and how to
change the representation of an object.  For more information about
representation objects themselves see :ref:`astropy-coordinates-representations`.

Initialization
"""""""""""""""

Most of what you need to know can be inferred from the examples below and
by extrapolating the previous documentation for spherical representations.
Initialization just requires setting the ``representation`` keyword and
supplying the corresponding components for that representation::

    >>> c = SkyCoord(x=1, y=2, z=3, unit='kpc', representation='cartesian')
    >>> c
    <SkyCoord (ICRS): (x, y, z) in kpc
        ( 1.,  2.,  3.)>
    >>> c.x, c.y, c.z
    (<Quantity 1.0 kpc>, <Quantity 2.0 kpc>, <Quantity 3.0 kpc>)

Other variations include::

    >>> SkyCoord(1, 2*u.deg, 3, representation='cylindrical')
    <SkyCoord (ICRS): (rho, phi, z) in (, deg, )
        ( 1.,  2.,  3.)>

    >>> SkyCoord(rho=1*u.km, phi=2*u.deg, z=3*u.m, representation='cylindrical')
    <SkyCoord (ICRS): (rho, phi, z) in (km, deg, m)
        ( 1.,  2.,  3.)>

    >>> SkyCoord(rho=1, phi=2, z=3, unit=(u.km, u.deg, u.m), representation='cylindrical')
    <SkyCoord (ICRS): (rho, phi, z) in (km, deg, m)
        ( 1.,  2.,  3.)>

    >>> SkyCoord(1, 2, 3, unit=(None, u.deg, None), representation='cylindrical')
    <SkyCoord (ICRS): (rho, phi, z) in (, deg, )
        ( 1.,  2.,  3.)>

In general terms, the allowed syntax is as follows::

  SkyCoord(COORD, [FRAME | frame=FRAME], [unit=UNIT], [representation=REPRESENTATION],
           keyword_args ...)
  SkyCoord(COMP1, COMP2, [COMP3], [FRAME | frame=FRAME], [unit=UNIT],
           [representation=REPRESENTATION], keyword_args ...)
  SkyCoord([FRAME | frame=FRAME], <comp1_name>=COMP1, <comp2_name>=COMP2,
           <comp3_name>=COMP3, [representation=REPRESENTATION], [unit=UNIT],
           keyword_args ...)

In this case the ``keyword_args`` now includes the element
``representation=REPRESENTATION``.  In the above description, elements in all
capital letters (e.g. ``FRAME``) describes a user input of that element type.
Elements in square brackets are optional.

**COMP1**, **COMP2**, **COMP3**

Component values can be specified as separate positional arguments or as
keyword arguments.  In this formalism the exact types of allowed input depend
on the details of the representation.  In general the following input forms
are supported:

- Single value:

  - Component class object
  - Plain numeric value with ``unit`` keyword specifying the unit

- List or component class array or numpy array of values

Each representation component has a specified class (the "component class")
which is used to convert generic input data into a pre-defined object
class with a certain unit.  These component classes are expected to be
subclasses of the `~astropy.units.Quantity` class.

**COORD**

This input form uses a single object to supply coordinate data.  The coordinate
can specify one or more coordinate positions as follows:

- List of ``(COMP1, .., COMP<M>)`` tuples, where each component is a scalar (not
  array) and there are ``M`` components in the representation.  Typically
  there are 3 components, but some
  (e.g. `~astropy.coordinates.UnitSphericalRepresentation`)
  can have fewer.
- ``N x M`` numpy or |Quantity| array of values, where ``N`` is the number
  of coordinates and ``M`` is the number of components.

**REPRESENTATION**

The representation can be supplied either as a
`~astropy.coordinates.representation.BaseRepresentation` class (e.g.
`~astropy.coordinates.CartesianRepresentation` or as a string name which is
simply the class name in lower case and without the final ``representation``
(e.g. ``'cartesian'``).

The rest of the inputs for creating a |SkyCoord| object in the general case are
the same as for spherical.

Details
"""""""""

The available set of representations is dynamic and may change depending what
representation classes have been defined.  The built-in representations are:

=====================  =======================================================
  Name                   Class
=====================  =======================================================
``spherical``          `~astropy.coordinates.SphericalRepresentation`
``unitspherical``      `~astropy.coordinates.UnitSphericalRepresentation`
``physicsspherical``   `~astropy.coordinates.PhysicsSphericalRepresentation`
``cartesian``          `~astropy.coordinates.CartesianRepresentation`
``cylindrical``        `~astropy.coordinates.CylindricalRepresentation`
=====================  =======================================================

Each frame knows about all the available representations, but different
frames may use different names for the same components.  A common example
is that the `~astropy.coordinates.Galactic` frame uses ``l`` and ``b``
instead of ``ra`` and ``dec`` for the ``lon`` and ``lat`` components of
the `~astropy.coordinates.SphericalRepresentation`.

For a particular frame, in order to see the full list of representations
and how it names all the components, first make an instance of that frame
without any data, and then print the ``representation_info`` property::

    >>> ICRS().representation_info  # doctest: +SKIP
    {astropy.coordinates.representation.CartesianRepresentation:
      {'names': ('x', 'y', 'z'),
       'units': (None, None, None)},
     astropy.coordinates.representation.SphericalRepresentation:
      {'names': ('ra', 'dec', 'distance'),
       'units': (Unit("deg"), Unit("deg"), None)},
     astropy.coordinates.representation.UnitSphericalRepresentation:
      {'names': ('ra', 'dec'),
       'units': (Unit("deg"), Unit("deg"))},
     astropy.coordinates.representation.PhysicsSphericalRepresentation:
      {'names': ('phi', 'theta', 'r'),
       'units': (Unit("deg"), Unit("deg"), None)},
     astropy.coordinates.representation.CylindricalRepresentation:
      {'names': ('rho', 'phi', 'z'),
       'units': (None, Unit("deg"), None)}
    }

This is a bit messy but it shows that for each representation there is a
``dict`` with two keys:

- ``names``: defines how each component is named in that frame
- ``units``: defines the units of each component when output, where ``None``
  means to not force a particular unit.

For a particular coordinate instance you can use the ``representation``
attribute in conjunction with the ``representation_component_names`` attribute
to figure out what keywords are accepted by a particular class object.  The
former will be the representation class the system is expressed in (e.g.,
spherical for equatorial frames), and the latter will be a dictionary mapping
names for that frame to the component name on the representation class::

    >>> import astropy.units as u
    >>> icrs = ICRS(1*u.deg, 2*u.deg)
    >>> icrs.representation
    <class 'astropy.coordinates.representation.SphericalRepresentation'>
    >>> icrs.representation_component_names
    OrderedDict([('ra', 'lon'), ('dec', 'lat'), ('distance', 'distance')])

Changing representation
""""""""""""""""""""""""""

The representation of the coordinate object can be changed, as shown
below.  This actually does *nothing* to the object internal data which
stores the coordinate values, but it changes the external view of that
data in two ways:

- The object prints itself in accord with the new representation.
- The available attributes change to match those of the new representation
  (e.g. from ``ra, dec, distance`` to ``x, y, z``).

Setting the ``representation`` thus changes a *property* of the object (how it
appears) without changing the intrinsic object itself which represents a point
in 3d space.
::

    >>> c = SkyCoord(x=1, y=2, z=3, unit='kpc', representation='cartesian')
    >>> c
    <SkyCoord (ICRS): (x, y, z) in kpc
        ( 1.,  2.,  3.)>

    >>> c.representation = 'cylindrical'
    >>> c  # doctest: +FLOAT_CMP
    <SkyCoord (ICRS): (rho, phi, z) in (kpc, deg, kpc)
        ( 2.23606798,  63.43494882,  3.)>
    >>> c.phi.to(u.deg)  # doctest: +FLOAT_CMP
    <Angle 63.43494882292201 deg>
    >>> c.x  # doctest: +SKIP
    ...
    AttributeError: 'SkyCoord' object has no attribute 'x'

    >>> c.representation = 'spherical'
    >>> c  # doctest: +FLOAT_CMP
    <SkyCoord (ICRS): (ra, dec, distance) in (deg, deg, kpc)
        ( 63.43494882,  53.3007748,  3.74165739)>

    >>> c.representation = 'unitspherical'
    >>> c  # doctest: +FLOAT_CMP
    <SkyCoord (ICRS): (ra, dec) in deg
        ( 63.43494882,  53.3007748)>

You can also use any representation class to set the representation::

    >>> from astropy.coordinates import CartesianRepresentation
    >>> c.representation = CartesianRepresentation

Note that if all you want is a particular representation without changing the
state of the |SkyCoord| object, you should instead use the
``astropy.coordinates.SkyCoord.represent_as()`` method::

    >>> c.representation = 'spherical'
    >>> cart = c.represent_as(CartesianRepresentation)
    >>> cart
    <CartesianRepresentation (x, y, z) in kpc
        ( 1.,  2.,  3.)>
    >>> c.representation
    <class 'astropy.coordinates.representation.SphericalRepresentation'>

Example 1: Plotting random data in Aitoff projection
====================================================

This is an example how to make a plot in the Aitoff projection using data
in a |SkyCoord| object. Here a randomly generated data set will be used.

First we need to import the required packages. We use
`matplotlib <http://www.matplotlib.org/>`_ here for
plotting and `numpy <http://www.numpy.org/>`_  to get the value of pi and to
generate our random data.

    >>> from astropy import units as u
    >>> from astropy.coordinates import SkyCoord
    >>> import numpy as np

We now generate random data for visualisation. For RA this is done in the range
of 0 and 360 degrees (``ra_random``), for DEC between -90 and +90 degrees
(``dec_random``). Finally, we multiply these values by degrees to get an
`~astropy.units.Quantity` with units of degrees.

    >>> ra_random = np.random.rand(100)*360.0 * u.degree
    >>> dec_random = (np.random.rand(100)*180.0-90.0) * u.degree

As next step, those coordinates are transformed into an astropy.coordinates
|SkyCoord| object.

    >>> c = SkyCoord(ra=ra_random, dec=dec_random, frame='icrs')

Because matplotlib needs the coordinates in radians and between :math:`-\pi`
and :math:`\pi`, not 0 and :math:`2\pi`, we have to convert them.
For this purpose the `astropy.coordinates.Angle` object provides a special method,
which we use here to wrap at 180:

    >>> ra_rad = c.ra.wrap_at(180 * u.deg).radian
    >>> dec_rad = c.dec.radian

As last step we set up the plotting environment with matplotlib using the
Aitoff projection with a specific title, a grid, filled circles as markers with
a markersize of 2 and an alpha value of 0.3. We use a figure with an x-y ratio
that is well suited for such a projection and we move the title upwards from
its usual position to avoid overlap with the axis labels.

.. doctest-skip::

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8,4.2))
    >>> plt.subplot(111, projection="aitoff")
    >>> plt.title("Aitoff projection of our random data")
    >>> plt.grid(True)
    >>> plt.plot(ra_rad, dec_rad, 'o', markersize=2, alpha=0.3)
    >>> plt.subplots_adjust(top=0.95,bottom=0.0)
    >>> plt.show()

.. plot::

    # This is an example how to make a plot in the Aitoff projection using data
    # in a SkyCoord object. Here a randomly generated data set will be used. The
    # final script can be found below.

    # First we need to import the required packages. We use
    # `matplotlib <http://www.matplotlib.org/>`_ here for
    # plotting and `numpy <http://www.numpy.org/>`_  to get the value of pi and to
    # generate our random data.
    from astropy import units as u
    from astropy.coordinates import SkyCoord
    import matplotlib.pyplot as plt
    import numpy as np

    # We now generate random data for visualisation. For RA this is done in the range
    # of 0 and 360 degrees (``ra_random``), for DEC between -90 and +90 degrees
    # (``dec_random``). Finally, we multiply these values by degrees to get an
    # `~astropy.units.Quantity` with units of degrees.
    ra_random = np.random.rand(100)*360.0 * u.degree
    dec_random = (np.random.rand(100)*180.0-90.0) * u.degree

    # As next step, those coordinates are transformed into an astropy.coordinates
    # astropy.coordinates.SkyCoord object.
    c = SkyCoord(ra=ra_random, dec=dec_random, frame='icrs')

    # Because matplotlib needs the coordinates in radians and between :math:`-\pi`
    # and :math:`\pi`, not 0 and :math:`2\pi`, we have to convert them.
    # For this purpose the `astropy.coordinates.Angle` object provides a special method,
    # which we use here to wrap at 180:
    ra_rad = c.ra.wrap_at(180 * u.deg).radian
    dec_rad = c.dec.radian

    # As last step we set up the plotting environment with matplotlib using the
    # Aitoff projection with a specific title, a grid, filled circles as markers with
    # a markersize of 2 and an alpha value of 0.3.
    plt.figure(figsize=(8,4.2))
    plt.subplot(111, projection="aitoff")
    plt.title("Aitoff projection of our random data", y=1.08)
    plt.grid(True)
    plt.plot(ra_rad, dec_rad, 'o', markersize=2, alpha=0.3)
    plt.subplots_adjust(top=0.95, bottom=0.0)
    plt.show()

Example 2: Plotting star positions in bulge and disk
====================================================

This is more realistic example how to make a plot in the Aitoff projection
using data in a |SkyCoord| object.
Here a randomly generated data set (multivariate
normal distribution) for both stars in the bulge and in the disk of a galaxy
will be used. Both types will be plotted with different number counts.

As in the last example, we first import the required packages.

    >>> from astropy import units as u
    >>> from astropy.coordinates import SkyCoord
    >>> import numpy as np

We now generate random data for visualisation using
`numpy.random.multivariate_normal`.

    >>> disk = np.random.multivariate_normal(mean=[0,0,0], cov=np.diag([1,1,0.5]), size=5000)
    >>> bulge = np.random.multivariate_normal(mean=[0,0,0], cov=np.diag([1,1,1]), size=500)
    >>> galaxy = np.concatenate([disk, bulge])

As next step, those coordinates are transformed into an astropy.coordinates
|SkyCoord| object.

    >>> c_gal = SkyCoord(galaxy, representation='cartesian', frame='galactic')
    >>> c_gal_icrs = c_gal.icrs

Again, as in the last example, we need to convert the coordinates in radians
and make sure they are between :math:`-\pi` and :math:`\pi`:

    >>> ra_rad = c_gal_icrs.ra.wrap_at(180 * u.deg).radian
    >>> dec_rad = c_gal_icrs.dec.radian

We use the same plotting setup as in the last example:

.. doctest-skip::

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8,4.2))
    >>> plt.subplot(111, projection="aitoff")
    >>> plt.title("Aitoff projection of our random data")
    >>> plt.grid(True)
    >>> plt.plot(ra_rad, dec_rad, 'o', markersize=2, alpha=0.3)
    >>> plt.subplots_adjust(top=0.95,bottom=0.0)
    >>> plt.show()

.. plot::

    # This is more realistic example how to make a plot in the Aitoff projection
    # using data in a SkyCoord object.
    # Here a randomly generated data set (multivariate normal distribution)
    # for both stars in the bulge and in the disk of a galaxy
    # will be used. Both types will be plotted with different number counts. The
    # final script can be found below.

    # As in the last example, we first import the required packages.
    from astropy import units as u
    from astropy.coordinates import SkyCoord
    import matplotlib.pyplot as plt
    import numpy as np

    # We now generate random data for visualisation with
    # np.random.multivariate_normal.
    disk = np.random.multivariate_normal(mean=[0,0,0], cov=np.diag([1,1,0.5]), size=5000)
    bulge = np.random.multivariate_normal(mean=[0,0,0], cov=np.diag([1,1,1]), size=500)
    galaxy = np.concatenate([disk, bulge])

    # As next step, those coordinates are transformed into an astropy.coordinates
    # astropy.coordinates.SkyCoord object.
    c_gal = SkyCoord(galaxy, representation='cartesian', frame='galactic')
    c_gal_icrs = c_gal.icrs

    # Again, as in the last example, we need to convert the coordinates in radians
    # and make sure they are between :math:`-\pi` and :math:`\pi`:
    ra_rad = c_gal_icrs.ra.wrap_at(180 * u.deg).radian
    dec_rad = c_gal_icrs.dec.radian

    # We use the same plotting setup as in the last example:
    plt.figure(figsize=(8,4.2))
    plt.subplot(111, projection="aitoff")
    plt.title("Aitoff projection of our random data", y=1.08)
    plt.grid(True)
    plt.plot(ra_rad, dec_rad, 'o', markersize=2, alpha=0.3)
    plt.subplots_adjust(top=0.95,bottom=0.0)
    plt.show()

Convenience methods
^^^^^^^^^^^^^^^^^^^^

A number of convenience methods are available, and you are encouraged to read
the available docstrings below:

- `~astropy.coordinates.SkyCoord.match_to_catalog_sky`,
- `~astropy.coordinates.SkyCoord.match_to_catalog_3d`,
- `~astropy.coordinates.SkyCoord.position_angle`,
- `~astropy.coordinates.SkyCoord.separation`,
- `~astropy.coordinates.SkyCoord.separation_3d`

Addition information and examples can be found in the section on
:ref:`astropy-coordinates-separations-matching`.


text:
package openmods.api;

import net.minecraft.item.ItemStack;

public interface ICustomPickItem {
	public ItemStack getPickBlock();
}


text:
(function () {
    "use strict";
    module.exports = function (server) {
        var forecastclient = require('../data/forecastclient');
        /**
         * I could have done something fancy with regular expressions, but decided to keep it simple.
         */
        server.get('/weather/:location/', forecastclient.fetch);
        server.get('/weather/:location/:weekday', forecastclient.fetch);
    };
}());