text:
"""Tests for python-mcollective base connector."""
import pytest
import six

from pymco import connector
from pymco import exc
from pymco.test.utils import mock

def test_connector_is_abstract():
    """Tests Connector is an abstract class."""
    with pytest.raises(TypeError):
        connector.Connector()

class ConnectorFake(connector.Connector):
    def get_target(self):
        pass

    def get_reply_target(self):
        pass

@pytest.fixture
def fake_connector(config, conn_mock):
    return ConnectorFake(config=config, connection=conn_mock)

def test_set_listeners(config, conn_mock):
    listener = mock.Mock()
    with mock.patch.dict(ConnectorFake.listeners, {'tracker': listener}):
        connector = ConnectorFake(config=config, connection=conn_mock)

    conn_mock.set_listener.assert_called_once_with('tracker',
                                                   listener.return_value)
    listener.assert_called_once_with(connector=connector, config=config)

@mock.patch('pymco.config.Config.get_security')
def test_connector_security(get_security, fake_connector):
    assert fake_connector.security == get_security.return_value
    get_security.assert_called_once_with()

@mock.patch('pymco.config.Config.get_security')
def test_connector_security__caches_security(get_security, fake_connector):
    security = mock.Mock()
    fake_connector._security = security
    assert fake_connector.security == security
    assert get_security.called is False

@mock.patch('pymco.connector.Connector.get_current_host_and_port')
def test_connect(host_and_port, fake_connector, conn_mock, config):
    conn_mock.connected = False
    host_and_port.return_value = ('localhost', 6163)
    assert fake_connector.connect() is fake_connector
    conn_mock.connect.assert_called_once_with(
        username=config['plugin.activemq.pool.1.user'],
        passcode=config['plugin.activemq.pool.1.password'],
        wait=None,
    )
    conn_mock.start.assert_called_once_with()
    host_and_port.assert_called_once_with()

def test_connect_already_connected(fake_connector, conn_mock):
    conn_mock.connected = True
    assert fake_connector.connect() is fake_connector
    assert 0 == conn_mock.connect.call_count
    assert 0 == conn_mock.start.call_count

def test_disconnect(fake_connector, conn_mock):
    conn_mock.is_connected.return_value = True
    assert fake_connector.disconnect() is fake_connector
    conn_mock.disconnect.assert_called_once_with()

def test_disconnect_not_connected(fake_connector, conn_mock):
    conn_mock.is_connected.return_value = False
    assert fake_connector.disconnect() is fake_connector
    assert 0 == conn_mock.disconnect.call_count

def test_get_current_host_and_port(fake_connector, conn_mock):
    conn_mock.get_listener.return_value.get_host.return_value = 'localhost'
    conn_mock.get_listener.return_value.get_port.return_value = 61613

    assert fake_connector.get_current_host_and_port() == ('localhost', 61613)

    conn_mock.get_listener.assert_called_once_with('tracker')
    conn_mock.get_listener.return_value.get_host.assert_called_once_with()
    conn_mock.get_listener.return_value.get_port.assert_called_once_with()

@mock.patch('pymco.connector.Connector.security')
def test_send(security, fake_connector, conn_mock):
    assert fake_connector.send('foo', 'destination') is fake_connector
    conn_mock.send.assert_called_with(body=security.encode('foo'),
                                      destination='destination')

def test_subcscribe(fake_connector, conn_mock):
    assert fake_connector.subscribe('destination', id='some-id') is fake_connector
    conn_mock.subscribe.assert_called_once_with('destination', id='some-id')

@mock.patch.object(six.moves.builtins, 'next')
@mock.patch('pymco.connector.Connector.id_generator')
def test_subscribe_no_id(id_generator, next, fake_connector, conn_mock):
    next.return_value = 1
    assert fake_connector.subscribe('destination') is fake_connector
    conn_mock.subscribe.assert_called_once_with('destination', id=1)
    next.assert_called_once_with(id_generator)

def test_set_ssl(config, conn_mock):
    calls = [
        mock.call(for_hosts=(('localhost', 6163),),
                  cert_file='tests/fixtures/activemq_cert.pem',
                  key_file='tests/fixtures/activemq_private.pem',
                  ca_certs='tests/fixtures/ca.pem'),
        mock.call(for_hosts=(('localhost', 6164),),
                  cert_file='tests/fixtures/activemq_cert.pem',
                  key_file='tests/fixtures/activemq_private.pem',
                  ca_certs='tests/fixtures/ca.pem'),
    ]
    ConnectorFake(config, conn_mock)
    assert conn_mock.transport.set_ssl.call_args_list == calls

@mock.patch('pymco.listener.SingleResponseListener',
            **{'return_value.responses.__len__.return_value': 1})
class TestReceive:
    def patch_connection(self, fake_connector):
        return mock.patch.multiple(fake_connector,
                                   connect=mock.DEFAULT,
                                   subscribe=mock.DEFAULT,
                                   disconnect=mock.DEFAULT)

    def test_receive__sets_single_response_listener(self,
                                                    listener,
                                                    fake_connector,
                                                    conn_mock):
        fake_connector.receive(5)
        assert mock.call('response_listener', listener.return_value
                         ) in conn_mock.set_listener.call_args_list

    def test_receive__sets_the_right_timeout(self,
                                             listener,
                                             fake_connector,
                                             conn_mock):
        fake_connector.receive(5)
        listener.assert_called_once_with(timeout=5,
                                         config=fake_connector.config)

    def test_receive__raises_timeout_error_if_no_message(self,
                                                         listener,
                                                         fake_connector,
                                                         conn_mock):
        listener.return_value.responses.__len__.return_value = 0
        with self.patch_connection(fake_connector):
            with pytest.raises(exc.TimeoutError):
                fake_connector.receive(5)

@mock.patch('pymco.config.Config.get_conn_params')
@mock.patch('stomp.connect.StompConnection11')
def test_default_connection(conn_mock, get_conn_params, config):
    get_conn_params.return_value = {}
    connector = ConnectorFake(config=config)
    assert connector.connection is conn_mock.return_value
    conn_mock.assert_called_once_with(**{})

@mock.patch('pymco.config.Config.get_conn_params')
@mock.patch('stomp.connect.StompConnection11')
def test_default_connection__rabbitmq(conn_mock, get_conn_params, config):
    config.config['connector'] = 'rabbitmq'
    config.config['plugin.rabbitmq.vhost'] = 'mcollective'
    config.config['plugin.rabbitmq.pool.size'] = 1
    config.config['plugin.rabbitmq.pool.1.host'] = 'localhost'
    config.config['plugin.rabbitmq.pool.1.port'] = 61612
    config.config['plugin.rabbitmq.pool.1.user'] = 'mcollective'
    config.config['plugin.rabbitmq.pool.1.password'] = 'marionette'
    get_conn_params.return_value = {}
    connector = ConnectorFake(config=config)
    assert connector.connection is conn_mock.return_value
    conn_mock.assert_called_once_with(**{'vhost': 'mcollective'})

def test_use_b64__disabled(config, fake_connector):
    assert fake_connector.use_b64 is False

def test_use_b64__enabled(config, fake_connector):
    for value in ('1', 'y', 'true'):
        config.config['plugin.activemq.base64'] = value
        assert fake_connector.use_b64 is True

def test_use_b64__non_activmeq(config, fake_connector):
    config.config['plugin.activemq.base64'] = 'true'
    config.config['connector'] = 'rabbitmq'
    assert fake_connector.use_b64 is False


text:
<?php
return [
    '@class' => 'Grav\\Common\\File\\CompiledYamlFile',
    'filename' => '/home/ubuntu/workspace/user/plugins/gravstrap/gravstrap.yaml',
    'modified' => 1508073478,
    'data' => [
        'enabled' => true
    ]
];

redpajama_set_name: RedPajamaGithub


text:
[//000000001]: # (doctools::toc::parse \- Documentation tools)
[//000000002]: # (Generated from file 'toc\_parse\.man' by tcllib/doctools with format 'markdown')
[//000000003]: # (Copyright © 2009 Andreas Kupries <andreas\_kupries@users\.sourceforge\.net>)
[//000000004]: # (doctools::toc::parse\(n\) 1 tcllib "Documentation tools")

 [ Main Table Of Contents | Table Of Contents | Keyword Index | Categories | Modules | Applications ]

# NAME

doctools::toc::parse \- Parsing text in doctoc format

# Table Of Contents

  - [Table Of Contents](#toc)

  - [Synopsis](#synopsis)

  - [Description](#section1)

  - [API](#section2)

  - [Parse errors](#section3)

  - [\[doctoc\] notation of tables of contents](#section4)

  - [ToC serialization format](#section5)

  - [Bugs, Ideas, Feedback](#section6)

  - [Keywords](#keywords)

  - [Category](#category)

  - [Copyright](#copyright)

# SYNOPSIS

package require doctools::toc::parse ?0\.1?
package require Tcl 8\.4
package require doctools::toc::structure
package require doctools::msgcat
package require doctools::tcl::parse
package require fileutil
package require logger
package require snit
package require struct::list
package require struct::stack

[__::doctools::toc::parse__ __text__ *text*](#1)
[__::doctools::toc::parse__ __file__ *path*](#2)
[__::doctools::toc::parse__ __includes__](#3)
[__::doctools::toc::parse__ __include add__ *path*](#4)
[__::doctools::toc::parse__ __include remove__ *path*](#5)
[__::doctools::toc::parse__ __include clear__](#6)
[__::doctools::toc::parse__ __vars__](#7)
[__::doctools::toc::parse__ __var set__ *name* *value*](#8)
[__::doctools::toc::parse__ __var unset__ *name*](#9)
[__::doctools::toc::parse__ __var clear__ ?*pattern*?](#10)

# DESCRIPTION

This package provides commands to parse text written in the
*[doctoc](\.\./\.\./\.\./\.\./index\.md\#doctoc)* markup language and convert it
into the canonical serialization of the table of contents encoded in the text\.
See the section [ToC serialization format](#section5) for specification of
their format\.

This is an internal package of doctools, for use by the higher level packages
handling *[doctoc](\.\./\.\./\.\./\.\./index\.md\#doctoc)* documents\.

# API

  - __::doctools::toc::parse__ __text__ *text*

    The command takes the string contained in *text* and parses it under the
    assumption that it contains a document written using the
    *[doctoc](\.\./\.\./\.\./\.\./index\.md\#doctoc)* markup language\. An error is
    thrown if this assumption is found to be false\. The format of these errors
    is described in section [Parse errors](#section3)\.

    When successful the command returns the canonical serialization of the table
    of contents which was encoded in the text\. See the section [ToC
    serialization format](#section5) for specification of that format\.

  - __::doctools::toc::parse__ __file__ *path*

    The same as __text__, except that the text to parse is read from the
    file specified by *path*\.

  - __::doctools::toc::parse__ __includes__

    This method returns the current list of search paths used when looking for
    include files\.

  - __::doctools::toc::parse__ __include add__ *path*

    This method adds the *path* to the list of paths searched when looking for
    an include file\. The call is ignored if the path is already in the list of
    paths\. The method returns the empty string as its result\.

  - __::doctools::toc::parse__ __include remove__ *path*

    This method removes the *path* from the list of paths searched when
    looking for an include file\. The call is ignored if the path is not
    contained in the list of paths\. The method returns the empty string as its
    result\.

  - __::doctools::toc::parse__ __include clear__

    This method clears the list of search paths for include files\.

  - __::doctools::toc::parse__ __vars__

    This method returns a dictionary containing the current set of predefined
    variables known to the __vset__ markup command during processing\.

  - __::doctools::toc::parse__ __var set__ *name* *value*

    This method adds the variable *name* to the set of predefined variables
    known to the __vset__ markup command during processing, and gives it the
    specified *value*\. The method returns the empty string as its result\.

  - __::doctools::toc::parse__ __var unset__ *name*

    This method removes the variable *name* from the set of predefined
    variables known to the __vset__ markup command during processing\. The
    method returns the empty string as its result\.

  - __::doctools::toc::parse__ __var clear__ ?*pattern*?

    This method removes all variables matching the *pattern* from the set of
    predefined variables known to the __vset__ markup command during
    processing\. The method returns the empty string as its result\.

    The pattern matching is done with __string match__, and the default
    pattern used when none is specified, is __\*__\.

# Parse errors

The format of the parse error messages thrown when encountering violations of
the *[doctoc](\.\./\.\./\.\./\.\./index\.md\#doctoc)* markup syntax is human
readable and not intended for processing by machines\. As such it is not
documented\.

*However*, the errorCode attached to the message is machine\-readable and has
the following format:

  1. The error code will be a list, each element describing a single error found
     in the input\. The list has at least one element, possibly more\.

  1. Each error element will be a list containing six strings describing an
     error in detail\. The strings will be

       1) The path of the file the error occurred in\. This may be empty\.

       1) The range of the token the error was found at\. This range is a
          two\-element list containing the offset of the first and last character
          in the range, counted from the beginning of the input \(file\)\. Offsets
          are counted from zero\.

       1) The line the first character after the error is on\. Lines are counted
          from one\.

       1) The column the first character after the error is at\. Columns are
          counted from zero\.

       1) The message code of the error\. This value can be used as argument to
          __msgcat::mc__ to obtain a localized error message, assuming that
          the application had a suitable call of __doctools::msgcat::init__
          to initialize the necessary message catalogs \(See package
          __[doctools::msgcat](\.\./doctools2base/tcllib\_msgcat\.md)__\)\.

       1) A list of details for the error, like the markup command involved\. In
          the case of message code __doctoc/include/syntax__ this value is
          the set of errors found in the included file, using the format
          described here\.

# \[doctoc\] notation of tables of contents

The doctoc format for tables of contents, also called the *doctoc markup
language*, is too large to be covered in single section\. The interested reader
should start with the document

  1. *[doctoc language introduction](\.\./doctools/doctoc\_lang\_intro\.md)*

and then proceed from there to the formal specifications, i\.e\. the documents

  1. *[doctoc language syntax](\.\./doctools/doctoc\_lang\_syntax\.md)* and

  1. *[doctoc language command
     reference](\.\./doctools/doctoc\_lang\_cmdref\.md)*\.

to get a thorough understanding of the language\.

# ToC serialization format

Here we specify the format used by the doctools v2 packages to serialize tables
of contents as immutable values for transport, comparison, etc\.

We distinguish between *regular* and *canonical* serializations\. While a
table of contents may have more than one regular serialization only exactly one
of them will be *canonical*\.

  - regular serialization

      1. The serialization of any table of contents is a nested Tcl dictionary\.

      1. This dictionary holds a single key, __doctools::toc__, and its
         value\. This value holds the contents of the table of contents\.

      1. The contents of the table of contents are a Tcl dictionary holding the
         title of the table of contents, a label, and its elements\. The relevant
         keys and their values are

           * __title__

             The value is a string containing the title of the table of
             contents\.

           * __label__

             The value is a string containing a label for the table of contents\.

           * __items__

             The value is a Tcl list holding the elements of the table, in the
             order they are to be shown\.

             Each element is a Tcl list holding the type of the item, and its
             description, in this order\. An alternative description would be
             that it is a Tcl dictionary holding a single key, the item type,
             mapped to the item description\.

             The two legal item types and their descriptions are

               + __reference__

                 This item describes a single entry in the table of contents,
                 referencing a single document\. To this end its value is a Tcl
                 dictionary containing an id for the referenced document, a
                 label, and a longer textual description which can be associated
                 with the entry\. The relevant keys and their values are

                   - __id__

                     The value is a string containing the id of the document
                     associated with the entry\.

                   - __label__

                     The value is a string containing a label for this entry\.
                     This string also identifies the entry, and no two entries
                     \(references and divisions\) in the containing list are
                     allowed to have the same label\.

                   - __desc__

                     The value is a string containing a longer description for
                     this entry\.

               + __division__

                 This item describes a group of entries in the table of
                 contents, inducing a hierarchy of entries\. To this end its
                 value is a Tcl dictionary containing a label for the group, an
                 optional id to a document for the whole group, and the list of
                 entries in the group\. The relevant keys and their values are

                   - __id__

                     The value is a string containing the id of the document
                     associated with the whole group\. This key is optional\.

                   - __label__

                     The value is a string containing a label for the group\.
                     This string also identifies the entry, and no two entries
                     \(references and divisions\) in the containing list are
                     allowed to have the same label\.

                   - __items__

                     The value is a Tcl list holding the elements of the group,
                     in the order they are to be shown\. This list has the same
                     structure as the value for the keyword __items__ used
                     to describe the whole table of contents, see above\. This
                     closes the recusrive definition of the structure, with
                     divisions holding the same type of elements as the whole
                     table of contents, including other divisions\.

  - canonical serialization

    The canonical serialization of a table of contents has the format as
    specified in the previous item, and then additionally satisfies the
    constraints below, which make it unique among all the possible
    serializations of this table of contents\.

      1. The keys found in all the nested Tcl dictionaries are sorted in
         ascending dictionary order, as generated by Tcl's builtin command
         __lsort \-increasing \-dict__\.

# Bugs, Ideas, Feedback

This document, and the package it describes, will undoubtedly contain bugs and
other problems\. Please report such in the category *doctools* of the [Tcllib
Trackers](http://core\.tcl\.tk/tcllib/reportlist)\. Please also report any ideas
for enhancements you may have for either package and/or documentation\.

When proposing code changes, please provide *unified diffs*, i\.e the output of
__diff \-u__\.

Note further that *attachments* are strongly preferred over inlined patches\.
Attachments can be made by going to the __Edit__ form of the ticket
immediately after its creation, and then using the left\-most button in the
secondary navigation bar\.

# KEYWORDS

[doctoc](\.\./\.\./\.\./\.\./index\.md\#doctoc),
[doctools](\.\./\.\./\.\./\.\./index\.md\#doctools),
[lexer](\.\./\.\./\.\./\.\./index\.md\#lexer),
[parser](\.\./\.\./\.\./\.\./index\.md\#parser)

# CATEGORY

Documentation tools

# COPYRIGHT

Copyright © 2009 Andreas Kupries <andreas\_kupries@users\.sourceforge\.net>


text:
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import classNames from 'classnames'
import Button from '../Button'
import ButtonGroup from '../ButtonGroup'
import Textarea from '../Form/Textarea'
import { getWindowSize, getAttributeForCurrentSize } from '../../utils/size'
import style from './style.less'
import colors from '../../foundation/colors.less'

export default class Text extends Component {
   static propTypes = {
      children: PropTypes.node,
      className: PropTypes.string,
      color: PropTypes.string,
      editable: PropTypes.bool,
      editorCancelButtonText: PropTypes.string,
      editorDoneButtonText: PropTypes.string,
      editorState: PropTypes.oneOf(['ready', 'pending']),
      editorOnCancel: PropTypes.func,
      editorOnDone: PropTypes.func,
      editorShowEditButton: PropTypes.bool,
      editorValue: PropTypes.string,
      editing: PropTypes.bool,
      fontFamily: PropTypes.string,
      letterSpacing: PropTypes.string,
      size: PropTypes.string,
      style: PropTypes.object,
      uppercase: PropTypes.bool,
      weight: PropTypes.string
   }

   static defaultProps = {
      editable: false,
      editorCancelButtonText: 'Cancel',
      editorDoneButtonText: 'Done',
      editorState: 'ready',
      editorShowEditButton: false,
      editing: false,
      size: '3',
      weight: 'normal'
   }

   static contextTypes = {
      OIOStyles: PropTypes.object
   }

   constructor(props) {
      super(props)

      this.state = {
         editing: props.editing,
         editorValue: props.editorValue,
         size: getWindowSize()
      }
   }

   // =====================================================
   // Lifecycle
   // =====================================================

   componentDidMount() {
      window.addEventListener('resize', this.windowSizeUpdated, false)
   }

   componentWillReceiveProps(nextProps) {
      const stateChangeRequired = ['editable', 'editing', 'editorState', 'editorValue'].some(prop => (
         typeof nextProps[prop] !== 'undefined' && this.state[prop] !== nextProps[prop]
      ))

      if (stateChangeRequired) {
         this.setState({
            editable: nextProps.editable,
            editing: nextProps.editing,
            editorState: nextProps.editorState,
            editorValue: nextProps.editorValue
         })
      }
   }

   componentDidUpdate() {
      // this.editor is a ref generated by the editable portion,
      // when the componentDidUpdate, auto-size the textarea
      if (this.editor) {
         const textarea = this.editor.parentNode.getElementsByTagName('textarea')[0]
         this.adjustTextareaHeight(textarea)
      }
   }

   componentWillUnmount() {
      window.removeEventListener('resize', this.windowSizeUpdated)
   }

   // =====================================================
   // Utils
   // =====================================================

   adjustTextareaHeight(textarea) {
      if (textarea) {
         // Set to auto first to "reset" to avoid browser jank
         textarea.style.height = 'auto'
         textarea.style.height = `${textarea.scrollHeight + 5}px`
      }
   }

   // =====================================================
   // Event Handlers
   // =====================================================

   handleChange = (event) => {
      this.adjustTextareaHeight(event.target)

      let value = event.target.value

      // Remove line-breaks from textarea value
      value = value.replace(/\n/g, '')

      this.setState({ editorValue: value })
   }

   handleEditCancel = () => {
      if (this.props.editorOnCancel) this.props.editorOnCancel(this.state.editorValue)

      this.setState({ editorValue: this.props.editorValue })
   }

   handleEditClick = (event) => {
      this.setState({
         editorValue: this.props.editorValue,
         editing: true
      })
   }

   handleEditDone = () => {
      if (this.props.editorOnDone) this.props.editorOnDone(this.state.editorValue)
   }

   windowSizeUpdated = () => {
      const windowSize = getWindowSize()
      this.setState({ size: windowSize })
   }

   // =====================================================
   // Edit Action Buttons JSX (Editable Text Only)
   // =====================================================

   editButtonsReady() {
      return (
         <ButtonGroup align="right">
            <Button
               onClick={this.handleEditCancel}
               name={this.props.editorCancelButtonText}
               size="tiny"
               color="#CCC"
            />
            <Button
               onClick={this.handleEditDone}
               name={this.props.editorDoneButtonText}
               size="tiny"
            />
         </ButtonGroup>
      )
   }

   editButtonsPending() {
      return (
         <ButtonGroup align="right">
            <Button
               onClick={this.handleEditDone}
               name="Done"
               size="tiny"
               mode="loading"
            />
         </ButtonGroup>
      )
   }

   // =====================================================
   // Render
   // =====================================================

   render() {
      const fontSize = getAttributeForCurrentSize(this.state.size, this.props.size)
      const textStyle = {
         ...this.props.style,
         ...this.context.OIOStyles.fontSizes[fontSize]
      }

      if (this.props.fontFamily) {
         textStyle.fontFamily = this.props.fontFamily
      }

      if (this.props.letterSpacing) {
         textStyle.letterSpacing = this.props.letterSpacing
      }

      const textClasses = [
         style[this.props.weight],
         colors[this.props.color],
         this.props.className
      ]

      if (this.props.uppercase) {
         textClasses.push(style.uppercase)
      }

      const editing = this.props.editable && this.state.editing
      const editorValue = this.props.editable && this.props.editorValue

      const showEditButton = (
         !this.state.editing &&
         this.props.editable &&
         this.props.editorShowEditButton
      )

      const editActionButtons = this.props.editorState === 'ready'
         ? this.editButtonsReady()
         : this.editButtonsPending()

      let content = {this.props.children || editorValue}
      if (editing) {
         content = (

 { this.editor = editor }}>
               <Textarea
                  className={style.editTextarea}
                  onChange={this.handleChange}
                  value={this.state.editorValue}
                  placeholder="Add text..."
                  disabled={this.state.editorState === 'pending'}
               />
               {editActionButtons}

         )
      }

      return (

            {showEditButton && (
               <Button
                  onClick={this.handleEditClick}
                  className={style.editButton}
                  icon="ion-edit"
                  size="tiny"
               />
            )}
            {content}

      )
   }
}


text:
class Image < ActiveRecord::Base
  require 'open-uri'

  # OpenURI::Buffer::StringMax = 10240
  OpenURI::Buffer::StringMax = 0

  belongs_to :gallery

  after_save :create_dimensioned
  after_destroy :delete_image

  validate :check_format

  def file= (f)
    self.original_filename = f.original_filename
    @file = f
  end

  def file
    return @file
  end

  def self.unaltered_file
    return 'original'
  end

  def check_format
    errors.add_on_empty 'name'

    if !(self.file.kind_of? ActionDispatch::Http::UploadedFile)
      errors.add :base, 'No file selected.'
      return
    end

    meta = `#{IMAGE_MAGICK_PATH}/identify -format %m,%w,%h #{self.file.path} 2>&1`
    meta_strs = meta.split(',')

    self.width = meta_strs[1].to_i
    self.height = meta_strs[2].to_i

    if !meta_strs || !(meta_strs[0] == 'JPEG' || meta_strs[0] == 'PNG') || self.height <= 0 || self.width <= 0
      errors.add :base, 'Data contains errors or is not a supported format.'
    end
  end

  def create_dimensioned
    gallery = Gallery.find(self.gallery_id)
    temp_path = self.file.path
    base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}"
    FileUtils.mkdir_p(base_path)

    # keep original copy
    original_path = "#{base_path}/#{Image.unaltered_file}.jpg"
    FileUtils.cp(temp_path, original_path)

    dims = gallery.dimensions

    dims.each do |dim|
      self.create_with_dimension(dim)
    end
  end

  def delete_image
    base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}"
    FileUtils.remove_entry_secure(base_path)
  end

  def create_with_dimension(dimension)
    gallery = Gallery.find(self.gallery_id)

    base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}"
    dim_name = dimension.name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase
    dest_path = "#{base_path}/#{dim_name}.jpg"

    src_path = "#{base_path}/#{Image.unaltered_file}.jpg"

    FileUtils.cp(src_path, dest_path)

    base_command = "#{IMAGE_MAGICK_PATH}/convert \"#{dest_path}\""

    if dimension.crop?
      if dimension.resize?
        if dimension.aspect
          aspect_ratio = dimension.aspect
        elsif dimension.height && dimension.width
          aspect_ratio = (dimension.width.to_f / dimension.height.to_f)
        end

        crop_width = (self.height * aspect_ratio).round
        crop_height = (self.width * (1/aspect_ratio)).round
      else
        if dimension.aspect
          crop_width = (self.height * dimension.aspect).round
          crop_height = (self.width * (1/dimension.aspect)).round
        else
          if dimension.width && !dimension.height
            crop_width = dimension.width
            crop_height = self.height
          elsif !dimension.width && dimension.height
            crop_width = self.width
            crop_height = dimension.height
          elsif dimension.width && dimension.height
            crop_width = dimension.width
            crop_height = dimension.height
          end
        end
      end

      y_offset = 0
      x_offset = 0

      if self.height > crop_height
        y_offset = ((self.height - crop_height)/2).round
      elsif self.width > crop_width
        x_offset = ((self.width - crop_width)/2).round
      end

      `#{base_command} -crop #{crop_width}x#{crop_height}+#{x_offset}+#{y_offset} "#{dest_path}"`
    end

    if dimension.resize?
      if dimension.width && !dimension.height
        `#{base_command} -resize #{dimension.width} -quality 100 "#{dest_path}"`
      elsif !dimension.width && dimension.height
        `#{base_command} -resize x#{dimension.height} -quality 100 "#{dest_path}"`
      elsif dimension.width && dimension.height
        `#{base_command} -resize #{dimension.width}x#{dimension.height}> -quality 100 "#{dest_path}"`
      end
    end
  end

  def destroy_with_dimension(dimension)
    gallery = Gallery.find(self.gallery_id)

    base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}"
    dim_name = dimension.name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase
    dest_path = "#{base_path}/#{dim_name}.jpg"

    FileUtils.rm(dest_path)
  end

  def rename_with_dimension(old, new)
    gallery = Gallery.find(self.gallery_id)

    base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}"
    old_name = old.name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase
    new_name = new.name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase
    old_path = "#{base_path}/#{old_name}.jpg"
    new_path = "#{base_path}/#{new_name}.jpg"

    FileUtils.mv(old_path, new_path)
  end

  def tag(dim_name = Image.unaltered_file, options = {})
    gallery = Gallery.find(self.gallery_id)

    image_path = self.src(dim_name, gallery)
    return "<img src=\"#{image_path}\" alt=\"#{self.name}\" />"
  end

  def src(dim_name = Image.unaltered_file, gallery = nil)
    if !gallery
      gallery = Gallery.find(self.gallery_id)
    end

    if (dim_name.downcase <=> Image.unaltered_file) == 0
      image_name = Image.unaltered_file
    else
      image_name = dim_name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase
    end
    return "#{Gallery.relative_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}/#{image_name}.jpg"
  end

  def holder(gallery = nil)
    if !gallery
      gallery = Gallery.find(self.gallery_id)
    end

    return gallery.holder_type.pluralize.downcase
  end
end


text:
dreynaud
emjburns
marchello2000
robzienert