text:
Rumble in the Jungle- Boxing Game

                             This was the first project I did at GA. It is an 8-Bit, turn-based boxing match game. There is a power bar which is constantly moving that dictates how powerful each punch is according to the timing of the user's strike.  The game was built with jQuery, animation sprites and CSS animations to create a retro, user friendly game.

Link:

                                     Click here

Date:
                                     April 2016

                             <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Babel

Babel is a social network that connects users who are looking to learn or teach a language. The app uses the CRUD principles, and was my first project using Ruby on Rails. I learnt the potential and power of Rails, and how to use relational databases effectively, as well as how to create a responsive app that was also attractive to look at.

Link:
                                 Click here

Date:
                                 May 2016

                         <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Transcribe

Transcribe was the final project I did at GA. It is an app that records speech, then turns it into text for the user to use as they wish. The initial idea was inspired by a friend who is about to start university, and was worried about making notes. Transcribe uses Angular, a powerful tool which I really enjoyed using. It also makes use of IBM's Watson Developer Cloud, and passport to provide authentication.

Link:

                                 Click here

Date:

         June 2016

                         <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

LineUp

LineUp is a map for a user to find gigs local to their chosen area. The gigs are created by other users, and users can scan for other gigs using a map. LineUp also used the Google Maps API, as well as AJAX and Node.

Link:
                                 Click here

Date:
                                 May 2014

                         <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text: export { SentryBrowser, ISentryBrowserOptions } from './lib/SentryBrowser';

redpajama_set_name: RedPajamaGithub


text:
import { Injectable } from '@angular/core';

@Injectable()
export class MovieService {
  movies: string[];

  getAllMovies() {
    this.movies = ['Rio', 'Rio2', 'Deadpool'];
    return this.movies;
  }

}


text:
require 'sitehub/cookie'
require 'sitehub/constants'
class SiteHub
  # TODO: - change in to object and remove .reek exclusions for UtilityFunction
  module CookieRewriting
    ENDING_WITH_NEWLINE = /#{NEW_LINE}$/

    def rewrite_cookies(headers, substitute_domain:)
      cookies_hash = cookies_string_as_hash(headers[Constants::HttpHeaderKeys::SET_COOKIE])

      cookies_hash.values.each do |cookie|
        domain_attribute = cookie.find(:domain) || next
        update_domain(domain_attribute, substitute_domain)
      end
      headers[Constants::HttpHeaderKeys::SET_COOKIE] = cookies_hash_to_string(cookies_hash)
    end

    def update_domain(domain_attribute, substitute_domain)
      substitute = substitute_domain.dup
      if domain_attribute.value.start_with?(FULL_STOP)
        domain_attribute.update(substitute.prepend(FULL_STOP))
      else
        domain_attribute.update(substitute)
      end
    end

    def cookies_hash_to_string(cookies_hash)
      cookies_hash.values.inject(EMPTY_STRING.dup) do |cookie_string, cookie|
        cookie_string << "#{cookie}#{NEW_LINE}"
      end.sub(ENDING_WITH_NEWLINE, EMPTY_STRING)
    end

    def cookies_string_as_hash(cookie_string)
      cookie_string.lines.each_with_object({}) do |cookie_line, cookies|
        cookie = SiteHub::Cookie.new(cookie_line)
        cookies[cookie.name] = cookie
      end
    end
  end
end


text:
REG_FIDDLE(Color_Type_Alpha_8, 256, 64, false, 0) {
void draw(SkCanvas* canvas) {
    canvas->scale(16, 16);
    SkBitmap bitmap;
    SkImageInfo imageInfo = SkImageInfo::Make(2, 2, kAlpha_8_SkColorType, kOpaque_SkAlphaType);
    bitmap.allocPixels(imageInfo);
    SkCanvas offscreen(bitmap);
    offscreen.clear(SK_ColorGREEN);
    SkPaint orangePaint;
    orangePaint.setARGB(0xFF, 0xFF, 0xA5, 0x00);
    canvas->drawBitmap(bitmap, 0, 0, &orangePaint);
    uint8_t alpha8[] = { 0xFF, 0xBB, 0x77, 0x33 };
    SkPixmap alphaPixmap(imageInfo, &alpha8, imageInfo.minRowBytes());
    if (bitmap.writePixels(alphaPixmap, 0, 0)) {
        canvas->drawBitmap(bitmap, 2, 2, &orangePaint);
    }
}
}  // END FIDDLE


text:
"""Import a TF v1-style SavedModel when executing eagerly."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools

from tensorflow.python.eager import context
from tensorflow.python.eager import lift_to_graph
from tensorflow.python.eager import wrap_function
from tensorflow.python.framework import composite_tensor
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.saved_model import function_deserialization
from tensorflow.python.saved_model import loader_impl
from tensorflow.python.saved_model import signature_serialization
from tensorflow.python.saved_model.experimental.pywrap_libexport import metrics
from tensorflow.python.training import monitored_session
from tensorflow.python.training import saver as tf_saver
from tensorflow.python.training.tracking import tracking
from tensorflow.python.util import nest

# API label for SavedModel metrics.
_LOAD_V1_V2_LABEL = "load_v1_in_v2"

class _Initializer(tracking.CapturableResource):
  """Represents an initialization operation restored from a SavedModel.

  Without this object re-export of imported 1.x SavedModels would omit the
  original SavedModel's initialization procedure.

  Created when `tf.saved_model.load` loads a TF 1.x-style SavedModel with an
  initialization op. This object holds a function that runs the
  initialization. It does not require any manual user intervention;
  `tf.saved_model.save` will see this object and automatically add it to the
  exported SavedModel, and `tf.saved_model.load` runs the initialization
  function automatically.
  """

  def __init__(self, init_fn, asset_paths):
    super(_Initializer, self).__init__()
    self._asset_paths = asset_paths
    self._init_fn = init_fn

  def _create_resource(self):
    return array_ops.placeholder(
        dtype=dtypes.resource, shape=[], name="unused_resource")

  def _initialize(self):
    return self._init_fn(*[path.asset_path for path in self._asset_paths])

class _EagerSavedModelLoader(loader_impl.SavedModelLoader):
  """Loads a SavedModel without using Sessions."""

  def get_meta_graph_def_from_tags(self, tags):
    """Override to support implicit one-MetaGraph loading with tags=None."""
    if tags is None:
      if len(self._saved_model.meta_graphs) != 1:
        tag_sets = [mg.meta_info_def.tags
                    for mg in self._saved_model.meta_graphs]
        raise ValueError(
            ("Importing a SavedModel with tf.saved_model.load requires a "
             "'tags=' argument if there is more than one MetaGraph. Got "
             "'tags=None', but there are {} MetaGraphs in the SavedModel with "
             "tag sets {}. Pass a 'tags=' argument to load this SavedModel.")
            .format(len(self._saved_model.meta_graphs), tag_sets))
      return self._saved_model.meta_graphs[0]
    return super(_EagerSavedModelLoader, self).get_meta_graph_def_from_tags(
        tags)

  def load_graph(self, returns, meta_graph_def):
    """Called from wrap_function to import `meta_graph_def`."""
    # pylint: disable=protected-access
    saver, _ = tf_saver._import_meta_graph_with_return_elements(
        meta_graph_def)
    # pylint: enable=protected-access
    returns[0] = saver

  def _extract_saver_restore(self, wrapped, saver):
    if saver is None:
      return None
    saver_def = saver.saver_def
    filename_tensor = wrapped.graph.as_graph_element(
        saver_def.filename_tensor_name)
    # We both feed and fetch filename_tensor so we have an operation to use to
    # feed into variable initializers (only relevant for v1 graph building).
    return wrapped.prune(
        feeds=[filename_tensor],
        fetches=[filename_tensor,
                 wrapped.graph.as_graph_element(saver_def.restore_op_name)])

  def restore_variables(self, wrapped, restore_from_saver):
    """Restores variables from the checkpoint."""
    if restore_from_saver is not None:
      initializer, _ = restore_from_saver(
          constant_op.constant(self._variables_path))
      if not ops.executing_eagerly_outside_functions():
        # Add the initialization operation to the "saved_model_initializers"
        # collection in case we don't have any lifted variables to attach it to.
        ops.add_to_collection("saved_model_initializers", initializer)
        one_unlifted = False

        for variable in wrapped.graph.get_collection_ref(
            ops.GraphKeys.GLOBAL_VARIABLES):
          if variable.graph is wrapped.graph:
            one_unlifted = True
          # pylint: disable=protected-access
          variable._initializer_op = initializer
          # pylint: enable=protected-access
        if one_unlifted:
          logging.warning(
              "Some variables could not be lifted out of a loaded function. "
              "Please run "
              "`sess.run(tf.get_collection(\"saved_model_initializers\"))`to "
              "restore these variables.")

  def _extract_signatures(self, wrapped, meta_graph_def):
    """Creates ConcreteFunctions for signatures in `meta_graph_def`."""
    signature_functions = {}
    for signature_key, signature_def in meta_graph_def.signature_def.items():
      if signature_def.inputs:
        input_items = sorted(
            signature_def.inputs.items(), key=lambda item: item[1].name)
        original_input_names, input_specs = zip(*input_items)
      else:
        original_input_names = []
        input_specs = []
      # TODO(allenl): Support optional arguments
      feeds = [
          wrap_function._get_element_from_tensor_info(input_spec, wrapped.graph)  # pylint: disable=protected-access
          for input_spec in input_specs
      ]
      input_names = []
      input_tensors = []
      for original_input_name, feed in zip(original_input_names, feeds):
        if isinstance(feed, sparse_tensor.SparseTensor):
          # We have to give explicit name for SparseTensor arguments, because
          # these are not present in the TensorInfo.
          indices_name = "%s_indices" % original_input_name
          values_name = "%s_values" % original_input_name
          dense_shape_name = "%s_dense_shape" % original_input_name
          input_names.extend([indices_name, values_name, dense_shape_name])
          input_tensors.extend([feed.indices, feed.values, feed.dense_shape])
        elif isinstance(feed, composite_tensor.CompositeTensor):
          component_tensors = nest.flatten(feed, expand_composites=True)
          input_names.extend("%s_component_%d" % (original_input_name, n)
                             for n in range(len(component_tensors)))
          input_tensors.extend(component_tensors)
        else:
          input_names.append(original_input_name)
          input_tensors.append(feed)
      fetches = {name: out for name, out in signature_def.outputs.items()}
      try:
        signature_fn = wrapped.prune(feeds=feeds, fetches=fetches)
      except lift_to_graph.UnliftableError as ex:
        # Mutate the exception to add a bit more detail.
        args = ex.args
        if not args:
          message = ""
        else:
          message = args[0]
        message = (
            ("A SavedModel signature needs an input for each placeholder the "
             "signature's outputs use. An output for signature '{}' depends on "
             "a placeholder which is not an input (i.e. the placeholder is not "
             "fed a value).\n\n").format(signature_key)
            + message)
        ex.args = (message,) + args[1:]
        raise
      # pylint: disable=protected-access
      signature_fn._arg_keywords = input_names
      signature_fn._func_graph.structured_input_signature = (
          (),
          func_graph.convert_structure_to_signature(
              dict(zip(input_names, input_tensors))))

      if len(input_names) == 1:
        # Allowing positional arguments does not create any ambiguity if there's
        # only one.
        signature_fn._num_positional_args = 1
      else:
        signature_fn._num_positional_args = 0
      # pylint: enable=protected-access
      signature_functions[signature_key] = signature_fn
    return signature_functions

  def load(self, tags):
    """Creates an object from the MetaGraph identified by `tags`."""
    meta_graph_def = self.get_meta_graph_def_from_tags(tags)
    load_shared_name_suffix = "_load_{}".format(ops.uid())
    functions = function_deserialization.load_function_def_library(
        meta_graph_def.graph_def.library,
        load_shared_name_suffix=load_shared_name_suffix)
    # Replace existing functions in the MetaGraphDef with renamed functions so
    # we don't have duplicates or name collisions.
    meta_graph_def.graph_def.library.Clear()
    for function in functions.values():
      meta_graph_def.graph_def.library.function.add().CopyFrom(
          function.function_def)
    # We've renamed functions and shared names. We need the same operation on
    # the GraphDef itself for consistency.
    for node_def in meta_graph_def.graph_def.node:
      function_deserialization.fix_node_def(node_def, functions,
                                            load_shared_name_suffix)

    load_graph_returns = [None]
    wrapped = wrap_function.wrap_function(
        functools.partial(self.load_graph, load_graph_returns, meta_graph_def),
        signature=[])
    saver, = load_graph_returns
    restore_from_saver = self._extract_saver_restore(wrapped, saver)
    self.restore_variables(wrapped, restore_from_saver)
    with wrapped.graph.as_default():
      init_op = loader_impl.get_init_op(
          meta_graph_def) or monitored_session.Scaffold.default_local_init_op()
      # Add a dummy Tensor we know we can fetch to add control dependencies to.
      init_anchor = constant_op.constant(0., name="dummy_fetch")

    root = tracking.AutoTrackable()
    if restore_from_saver is not None:
      root.restore = (
          lambda path: restore_from_saver(constant_op.constant(path)))
    asset_feed_tensors = []
    asset_paths = []
    for tensor_name, value in loader_impl.get_asset_tensors(
        self._export_dir, meta_graph_def).items():
      asset_feed_tensors.append(wrapped.graph.as_graph_element(tensor_name))
      asset_paths.append(tracking.Asset(value))
    init_fn = wrapped.prune(
        feeds=asset_feed_tensors,
        fetches=[init_anchor, wrapped.graph.as_graph_element(init_op)])
    initializer = _Initializer(init_fn, asset_paths)
    # pylint: disable=protected-access
    local_init_op, _ = initializer._initialize()
    # pylint: enable=protected-access
    with ops.init_scope():
      if not context.executing_eagerly():
        ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, local_init_op)
        for variable in wrapped.graph.get_collection_ref(
            ops.GraphKeys.LOCAL_VARIABLES):
          # pylint: disable=protected-access
          variable._initializer_op = local_init_op
          # pylint: enable=protected-access
    root.initializer = initializer
    root.asset_paths = asset_paths
    signature_functions = self._extract_signatures(wrapped, meta_graph_def)

    root.signatures = signature_serialization.create_signature_map(
        signature_functions)
    root.variables = list(wrapped.graph.variables)
    root.tensorflow_version = (
        meta_graph_def.meta_info_def.tensorflow_version)
    root.tensorflow_git_version = (
        meta_graph_def.meta_info_def.tensorflow_git_version)
    root.graph = wrapped.graph
    root.prune = wrapped.prune
    return root

def load(export_dir, tags):
  """Load a v1-style SavedModel as an object."""
  metrics.IncrementReadApi(_LOAD_V1_V2_LABEL, write_version="1")
  loader = _EagerSavedModelLoader(export_dir)
  return loader.load(tags=tags)


text:
$ = jQuery;
var smile_panel_id = '';
jQuery(document).ready( function() {
	jQuery(document).on('smile_panel_loaded',function(e,smile_panel,id){
		var smile_panel = jQuery(".customize").data('style');
		smile_panel_id = smile_panel;
		function Border (options) {

			this.htmlElement = options['htmlElement'] || jQuery('#accordion-'+ smile_panel_id +' #border-radius-panel');
			this.htmlCode = jQuery('#accordion-'+ smile_panel_id +' #border-code');
			this.br_all = ( typeof options['br_all'] !== 'undefined' ? options['br_all'] : 10 );
			this.br_tl = ( typeof options['br_tl'] !== 'undefined' ? options['br_tl'] : 10 );
			this.br_tr = ( typeof options['br_tr'] !== 'undefined' ? options['br_tr'] : 10 );
			this.br_bl = ( typeof options['br_bl'] !== 'undefined' ? options['br_bl'] : 10 );
			this.br_br = ( typeof options['br_br'] !== 'undefined' ? options['br_br'] : 10 );
			this.style = options['style'] || 'none';
			this.color = options['color'] ||'#000000';
			this.br_type = options['br_type'] || 0;
			this.bw_type = options['bw_type'] || 0;
			this.bw_all = ( typeof options['bw_all'] !== 'undefined' ? options['bw_all'] : 10 );
			this.bw_t = ( typeof options['bw_t'] !== 'undefined' ? options['bw_t'] : 10 );
			this.bw_l = ( typeof options['bw_l'] !== 'undefined' ? options['bw_l'] : 10 );
			this.bw_r = ( typeof options['bw_r'] !== 'undefined' ? options['bw_r'] : 10 );
			this.bw_b = ( typeof options['bw_b'] !== 'undefined' ? options['bw_b'] : 10 );
			return this;
		}

		Border.prototype.refresh = function () {
			var inputCode = 'br_type:'+this.br_type+'|';
			inputCode += 'br_all:'+this.br_all+'|';
			inputCode += 'br_tl:'+this.br_tl+'|';
			inputCode += 'br_tr:'+this.br_tr+'|';
			inputCode += 'br_br:'+this.br_br+'|';
			inputCode += 'br_bl:'+this.br_bl+'|';
			inputCode += 'style:'+this.style+'|';
			inputCode += 'color:'+this.color+'|';
			inputCode += 'bw_type:'+this.bw_type+'|';
			inputCode += 'bw_all:'+this.bw_all+'|';
			inputCode += 'bw_t:'+this.bw_t+'|';
			inputCode += 'bw_l:'+this.bw_l+'|';
			inputCode += 'bw_r:'+this.bw_r+'|';
			inputCode += 'bw_b:'+this.bw_b;

			this.htmlCode.html(inputCode);

			//this.htmlCode.trigger('change');
		}

		Border.prototype.setAllCorners = function (border) {
			this.br_all = border;
			this.br_tl = border;
			this.br_tr = border;
			this.br_bl = border;
			this.br_br = border;
		}

		Border.prototype.setAllSides = function (width) {
			this.bw_all = width;
			this.bw_t = width;
			this.bw_l = width;
			this.bw_r = width;
			this.bw_b = width;
		}

		function _getAllValuesFromPanelBorder() {
			var options 		= {};
			options['br_all'] 	= parseFloat(jQuery("#accordion-"+ smile_panel_id +" #all-corners").val());
			options['br_tl'] 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #top-left').val());
			options['br_tr'] 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #top-right').val());
			options['br_bl'] 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #bottom-left').val());
			options['br_br'] 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #bottom-right').val());
			options['style'] 	= jQuery('#accordion-'+ smile_panel_id +' #select-border :selected').val();
			options['color'] 	= jQuery('#accordion-'+ smile_panel_id +' #br-color').val();
			options['br_type'] 	= jQuery('#accordion-'+ smile_panel_id +' #smile_adv_border_opt').val();
			options['bw_all'] 	= parseFloat(jQuery("#accordion-"+ smile_panel_id +" #width-allsides").val());
			options['bw_t'] 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #width-top').val());
			options['bw_l'] 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #width-left').val());
			options['bw_r'] 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #width-right').val());
			options['bw_b'] 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #width-bottom').val());
			options['bw_type'] 	= jQuery('#accordion-'+ smile_panel_id +' #smile_adv_borderwidth_opt').val();
			return options;
		}

		function _getFromFieldBorder(value, min, max, elem) {
			var val = parseFloat(value);
			if (isNaN(val) || val < min) {
				val = 0;
			} else if (val > max) {
				val = max;
			}

			if (elem)
				elem.val(val);

			return val;
		}

		var opts = _getAllValuesFromPanelBorder();
		var border = new Border(opts);
		// border.refresh();

		/* Border Type */
		jQuery('#accordion-'+ smile_panel +' #smile_adv_border_opt').on('change', function () {

			var all_radius		= parseFloat(jQuery("#accordion-"+ smile_panel_id +" #all-corners").val());
			var top_left	 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #top-left').val());
			var top_right	 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #top-right').val());
			var bottom_left	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #bottom-left').val());
			var bottom_right 	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #bottom-right').val());

			var val = jQuery(this).val();
			if( val == 0 ) {
				jQuery(".border-container.param-advanced-block").slideUp();
				jQuery(".border-container.param-basic-block").slideDown();
				partial_refresh_border('border-radius', all_radius);
			} else {
				jQuery(".border-container.param-basic-block").slideUp();
				jQuery(".border-container.param-advanced-block").slideDown();

				partial_refresh_border('border-top-left-radius', top_left );
				partial_refresh_border('border-top-right-radius', top_right );
				partial_refresh_border('border-bottom-left-radius', bottom_left );
				partial_refresh_border('border-bottom-right-radius', bottom_right );
			}

			// border.br_type = val;
			// border.refresh();
		});

		/* Border Width - Switch ( basic / advanced ) */
		jQuery('#accordion-'+ smile_panel +' #smile_adv_borderwidth_opt').on('change', function () {

			var all_widths	= parseFloat(jQuery("#accordion-"+ smile_panel_id +" #width-allsides").val());
			var top		= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #width-top').val());
			var left		= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #width-left').val());
			var right		= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #width-right').val());
			var bottom	= parseFloat(jQuery('#accordion-'+ smile_panel_id +' #width-bottom').val());

			var val = jQuery(this).val();
			if( val == 0 ) {
				jQuery(".borderwidth-container.param-advanced-block").slideUp();
				jQuery(".borderwidth-container.param-basic-block").slideDown();
				partial_refresh_border('border-width', all_widths);
			} else {
				jQuery(".borderwidth-container.param-basic-block").slideUp();
				jQuery(".borderwidth-container.param-advanced-block").slideDown();

				partial_refresh_border('border-top-width', top);
				partial_refresh_border('border-left-width', left);
				partial_refresh_border('border-right-width', right);
				partial_refresh_border('border-bottom-width', bottom);
			}
			// border.bw_type = val;
			// border.refresh();
		});

		/* Border Style */
		jQuery('#accordion-'+ smile_panel +' #select-border').on('change', function () {
			var val = jQuery(this).val();

			//	Partial refresh - Apply to [border-style]
			partial_refresh_border('border-style', val);

			if( val == 'none' ) {
				jQuery(".borderwidth-block").closest(".setting-block").slideUp();
				jQuery(".bordercolor-block").closest(".setting-block").slideUp();
			} else {
				jQuery(".borderwidth-block").closest(".setting-block").slideDown();
				jQuery(".bordercolor-block").closest(".setting-block").slideDown();
			}
			// border.style = val;
			// border.refresh();
		});

		/* Border Radius - Slider */
		jQuery('#accordion-'+ smile_panel +' #slider-all-corners').slider({

			value: jQuery('#accordion-'+ smile_panel +' #all-corners').val(),
			min: 0,
			max: 500,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500);
				//  Partial Refresh - Apply [border-radius]
				partial_refresh_border( 'border-radius', val );

				// border.setAllCorners(val);

				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');

				jQuery('#accordion-'+ smile_panel +' #all-corners').val(val);
				jQuery('#accordion-'+ smile_panel +' #top-left').val(val);
				jQuery('#accordion-'+ smile_panel +' #top-right').val(val);
				jQuery('#accordion-'+ smile_panel +' #bottom-left').val(val);
				jQuery('#accordion-'+ smile_panel +' #bottom-right').val(val);

				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-top-left').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-top-right').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-bottom-left').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-bottom-right').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);

				// border.refresh();
			},
			stop: function( event, ui ) {
				border.refresh();
			},
			create: function( event, ui ){
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});
		jQuery('#accordion-'+ smile_panel +' #slider-top-left').slider({
			value: jQuery('#accordion-'+ smile_panel +' #top-left').val(),
			min: 0,
			max: 500,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500, jQuery('#accordion-'+ smile_panel +' #top-left'));

				//	Partial refresh - Apply to [border-top-left-radius]
				partial_refresh_border('border-top-left-radius', val);

				// border.br_tl = val;
				// border.refresh();

				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			},
			create: function( event, ui ){
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});
		jQuery('#accordion-'+ smile_panel +' #slider-top-right').slider({
			value: jQuery('#accordion-'+ smile_panel +' #top-right').val(),
			min: 0,
			max: 500,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500, jQuery('#accordion-'+ smile_panel +' #top-right').val(val));
				// border.br_tr = val;
				// border.refresh();

				// Partial refresh - Apply to [border-top-right-radius]
				partial_refresh_border('border-top-right-radius', val);

				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			},
			create: function( event, ui ){
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});
		jQuery('#accordion-'+ smile_panel +' #slider-bottom-left').slider({
			value: jQuery('#accordion-'+ smile_panel +' #bottom-left').val(),
			min: 0,
			max: 500,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500, jQuery('#accordion-'+ smile_panel +' #bottom-left'));
				// border.br_bl = val;
				// border.refresh();

				// Partial refresh - Apply to [border-bottom-left-radius]
				partial_refresh_border('border-bottom-left-radius', val);

				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			},
			create: function( event, ui ){
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});
		jQuery('#accordion-'+ smile_panel +' #slider-bottom-right').slider({
			value: jQuery('#accordion-'+ smile_panel +' #bottom-right').val(),
			min: 0,
			max: 500,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500, jQuery('#accordion-'+ smile_panel +' #bottom-right'));
				// border.br_br = val;
				// border.refresh();

				// Partial refresh - Apply to [border-bottom-right-radius]
				partial_refresh_border('border-bottom-right-radius', val);

				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);

			},
			create: function( event, ui ){
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});

		/* Border Radius - Input */
		jQuery('#accordion-'+ smile_panel +' #all-corners').on('keyup change', function() {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #all-corners'));

			// border.setAllCorners(val);
			// border.refresh();

			//	Partial refresh - Apply [border-radius]
			partial_refresh_border('border-radius', val );

			jQuery('#accordion-'+ smile_panel +' #slider-all-corners').slider('value', val);
			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-all-corners').find('.ui-slider-handle').css('left');

			jQuery('#accordion-'+ smile_panel +' #slider-all-corners').find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #top-left').val(val);
			jQuery('#accordion-'+ smile_panel +' #top-right').val(val);
			jQuery('#accordion-'+ smile_panel +' #bottom-left').val(val);
			jQuery('#accordion-'+ smile_panel +' #bottom-right').val(val);
			jQuery('#accordion-'+ smile_panel +' #slider-top-left').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #slider-top-right').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #slider-bottom-left').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #slider-bottom-right').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
		});
		jQuery('#top-left').on('keyup change', function() {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #top-left'));
			// border.br_tl = val;
			// border.refresh();

			//	Partial refresh - Apply [border-top-left-radius]
			partial_refresh_border('border-top-left-radius', val );

			jQuery('#accordion-'+ smile_panel +' #slider-top-left').slider('value', val);
			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-top-left').find('.ui-slider-handle').css('left');
			jQuery('#accordion-'+ smile_panel +' #slider-top-left').find('.range-quantity').css('width',leftMarginToSlider);
		});
		jQuery('#accordion-'+ smile_panel +' #top-right').on('keyup change', function () {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #top-right'));
			// border.br_tr = val;
			// border.refresh();

			//	Partial refresh - Apply [border-top-right-radius]
			partial_refresh_border('border-top-right-radius', val );

			jQuery('#accordion-'+ smile_panel +' #slider-top-right').slider('value', val);
			 var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-top-right').find('.ui-slider-handle').css('left');
			jQuery('#accordion-'+ smile_panel +' #slider-top-right').find('.range-quantity').css('width',leftMarginToSlider);
		});
		jQuery('#accordion-'+ smile_panel +' #bottom-left').on('keyup change', function() {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #bottom-left'));
			// border.br_bl = val;
			// border.refresh();

			//	Partial refresh - Apply [border-bottom-left-radius]
			partial_refresh_border('border-bottom-left-radius', val );

			jQuery('#accordion-'+ smile_panel +' #slider-bottom-left').slider('value', val);
			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-bottom-left').find('.ui-slider-handle').css('left');
			jQuery('#accordion-'+ smile_panel +' #slider-bottom-left').find('.range-quantity').css('width',leftMarginToSlider);
		});
		jQuery('#accordion-'+ smile_panel +' #bottom-right').on('keyup change', function() {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #bottom-right'));
			// border.br_br = val;
			// border.refresh();

			//	Partial refresh - Apply [border-bottom-right-radius]
			partial_refresh_border('border-bottom-right-radius', val );

			jQuery('#accordion-'+ smile_panel +' #slider-bottom-right').slider('value', val);
			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-bottom-right').find('.ui-slider-handle').css('left');
			jQuery('#accordion-'+ smile_panel +' #slider-bottom-right').find('.range-quantity').css('width',leftMarginToSlider);
		});

		/* Color (Border and background) */
		jQuery('#accordion-'+ smile_panel +' #br-color').on('change', function () {
			var v = jQuery(this).val();
			// border.color = jQuery(this).val();
			// border.refresh();
			jQuery('#accordion-'+ smile_panel +' #br-color-button').css('background-color', '#' + v );

			//  Partial Refresh - Apply [border-color]
			partial_refresh_border( 'border-color', v );
		});
		// jQuery('#accordion-'+ smile_panel +' #br-background-color').on('change', function () {
		// 	// border.borderBackground = jQuery(this).val();
		// 	// border.refresh();
		// 	jQuery('#accordion-'+ smile_panel +' #br-background-color-button').css('background-color', '#' + jQuery(this).val());
		// });

		/* Border Width - Slider */
		jQuery('#accordion-'+ smile_panel +' #slider-width-allsides').slider({
			value: jQuery('#accordion-'+ smile_panel +' #width-allsides').val(),
			min: 0,
			max: 50,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500);

				//  Partial Refresh - Apply [border-color]
				partial_refresh_border( 'border-width', val );

				// border.setAllSides(val);

				jQuery('#accordion-'+ smile_panel +' #width-allsides').val(val);
				jQuery('#accordion-'+ smile_panel +' #width-top').val(val);
				jQuery('#accordion-'+ smile_panel +' #width-left').val(val);
				jQuery('#accordion-'+ smile_panel +' #width-right').val(val);
				jQuery('#accordion-'+ smile_panel +' #width-bottom').val(val);

				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-width-allsides').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-width-top').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-width-left').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-width-right').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
				jQuery('#accordion-'+ smile_panel +' #slider-width-bottom').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);

				// border.refresh();

			},
			stop: function( event, ui ) {
				border.refresh();
			},
			create: function( event, ui ) {
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});
		jQuery('#accordion-'+ smile_panel +' #slider-width-top').slider({
			value: jQuery('#accordion-'+ smile_panel +' #width-top').val(),
			min: 0,
			max: 50,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500, jQuery('#accordion-'+ smile_panel +' #width-top'));
				// border.bw_t = val;
				// border.refresh();

				//  Partial Refresh - Apply [border-top-width]
				partial_refresh_border( 'border-top-width', val );

				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			},
			create: function( event, ui ){
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});
		jQuery('#accordion-'+ smile_panel +' #slider-width-left').slider({
			value: jQuery('#accordion-'+ smile_panel +' #width-left').val(),
			min: 0,
			max: 50,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500, jQuery('#accordion-'+ smile_panel +' #width-left'));
				// border.bw_l = val;
				// border.refresh();

				//  Partial Refresh - Apply [border-left-width]
				partial_refresh_border( 'border-left-width', val );

				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			},
			create: function( event, ui ){
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});
		jQuery('#accordion-'+ smile_panel +' #slider-width-right').slider({
			value: jQuery('#accordion-'+ smile_panel +' #width-right').val(),
			min: 0,
			max: 50,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500, jQuery('#accordion-'+ smile_panel +' #width-right'));

				//  Partial Refresh - Apply [border-right-width]
				partial_refresh_border( 'border-right-width', val );

				// border.bw_r = val;
				// border.refresh();
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			},
			create: function( event, ui ) {
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});
		jQuery('#accordion-'+ smile_panel +' #slider-width-bottom').slider({
			value: jQuery('#accordion-'+ smile_panel +' #width-bottom').val(),
			min: 0,
			max: 50,
			step: 1,
			slide: function(event, ui) {
				var val = _getFromFieldBorder(ui.value, 0, 500, jQuery('#accordion-'+ smile_panel +' #width-bottom'));

				//  Partial Refresh - Apply [border-bottom-width]
				partial_refresh_border( 'border-bottom-width', val );

				// border.bw_b = val;
				// border.refresh();
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			},
			create: function( event, ui ) {
				var leftMarginToSlider = jQuery( this ).find('.ui-slider-handle').css('left');
				jQuery( this ).find('.range-quantity').css('width',leftMarginToSlider);
			}
		});

		/* Border Width - Input */
		jQuery('#accordion-'+ smile_panel +' #width-allsides').on('keyup change', function() {

			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #all-sides'));
			// border.setAllSides(val);
			// border.refresh();

			//  Partial Refresh - Apply [border-width]
			partial_refresh_border( 'border-width', val );

			jQuery('#accordion-'+ smile_panel +' #slider-width-allsides').slider('value', val);
			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-width-allsides').find('.ui-slider-handle').css('left');

			jQuery('#accordion-'+ smile_panel +' #slider-width-allsides').find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #width-top').val(val);
			jQuery('#accordion-'+ smile_panel +' #width-left').val(val);
			jQuery('#accordion-'+ smile_panel +' #width-right').val(val);
			jQuery('#accordion-'+ smile_panel +' #width-bottom').val(val);

			jQuery('#accordion-'+ smile_panel +' #slider-width-allsides').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #slider-width-top').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #slider-width-left').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #slider-width-right').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
			jQuery('#accordion-'+ smile_panel +' #slider-width-bottom').slider('value', val).find('.range-quantity').css('width',leftMarginToSlider);
		});
		jQuery('#width-top').on('keyup change', function() {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #width-top'));
			// border.bw_t = val;
			// border.refresh();

			//  Partial Refresh - Apply [border-top-width]
			partial_refresh_border( 'border-top-width', val );

			jQuery('#accordion-'+ smile_panel +' #slider-width-top').slider('value', val);

			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-width-top').find('.ui-slider-handle').css('left');
			jQuery('#accordion-'+ smile_panel +' #slider-width-top').find('.range-quantity').css('width',leftMarginToSlider);
		});
		jQuery('#accordion-'+ smile_panel +' #width-left').on('keyup change', function () {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #width-left'));
			// border.bw_l = val;
			// border.refresh();

			//  Partial Refresh - Apply [border-left-width]
			partial_refresh_border( 'border-left-width', val );

			jQuery('#accordion-'+ smile_panel +' #slider-width-left').slider('value', val);

			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-width-left').find('.ui-slider-handle').css('left');
			jQuery('#accordion-'+ smile_panel +' #slider-width-left').find('.range-quantity').css('width',leftMarginToSlider);
		});
		jQuery('#accordion-'+ smile_panel +' #width-right').on('keyup change', function() {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #width-right'));
			// border.bw_r = val;
			// border.refresh();

			//  Partial Refresh - Apply [border-right-width]
			partial_refresh_border( 'border-right-width', val );

			jQuery('#accordion-'+ smile_panel +' #slider-width-right').slider('value', val);

			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-width-right').find('.ui-slider-handle').css('left');
			jQuery('#accordion-'+ smile_panel +' #slider-width-right').find('.range-quantity').css('width',leftMarginToSlider);
		});
		jQuery('#accordion-'+ smile_panel +' #width-bottom').on('keyup change', function() {
			var val = _getFromFieldBorder(jQuery(this).val(), 0, 500, jQuery('#accordion-'+ smile_panel +' #width-bottom'));
			// border.bw_b = val;
			// border.refresh();

			//  Partial Refresh - Apply [border-bottom-width]
			partial_refresh_border( 'border-bottom-width', val );

			jQuery('#accordion-'+ smile_panel +' #slider-width-bottom').slider('value', val);

			var leftMarginToSlider = jQuery('#accordion-'+ smile_panel +' #slider-width-bottom').find('.ui-slider-handle').css('left');
			jQuery('#accordion-'+ smile_panel +' #slider-width-bottom').find('.range-quantity').css('width',leftMarginToSlider);
		});

		//	Generate CSS
		var a = jQuery('#accordion-'+ smile_panel_id +' #border-code');
		var css_preview = a.attr('data-css-preview') || '';
		var selector    = a.attr('data-css-selector') || '';
		var unit        = a.attr('data-unit') || 'px';
		function partial_refresh_border( property, value ) {
			//  apply css by - inline
			if( css_preview != 1 || null == css_preview || 'undefined' == css_preview ) {
				jQuery("#smile_design_iframe").contents().find( selector ).css( property , value );
			}
			a.trigger("change");

			//  apply css by - after css generation
			jQuery(document).trigger('updated', [css_preview, selector, property, value, unit]);
	    	}

	    	//	Generate - Border hidden value with ConCat
	 	var smile_panel = jQuery(".customize").data('style');
		jQuery('#button-save-'+smile_panel+' > span').trigger('click');
		jQuery('#button-save-'+smile_panel).click(function(event) {

			var opts = _getAllValuesFromPanelBorder();
			var border = new Border(opts);
			border.refresh();
		});
	});
});


text:
import os

from django.db.models import ImageField
from django.core.files.base import ContentFile
from django.db.models import signals

from Compat.thumbnail.utils import rescale

class ThumbField(ImageField):

    def __init__(self, source, size, *args, **kwargs):
        kwargs['blank'] = True
        super(ThumbField, self).__init__(*args, **kwargs)
        self.source = source
        self.size = size

    def contribute_to_class(self, cls, name):
        self._field_name = name
        super(ThumbField, self).contribute_to_class(cls, name)
        signals.pre_save.connect(self.force_rethumb, sender=cls, weak=False)

    def generate_thumb_name(self, original):
        filename = os.path.split(original)[-1].split('.')
        if len(filename) > 1:
            filename[-2] = filename[-2] + '.' + self._field_name
        else:
            filename.append('.'+self._field_name)
        return '.'.join(filename)

    def force_rethumb(self, instance, *args, **kwargs):
        source = getattr(instance, self.source, None)
        try:
            old_instance = instance._default_manager.get(pk=instance.pk)
            old_source = getattr(old_instance, self.source)
        except:
            old_source = None

        try:
            src_empty = source.path
        except ValueError, e:
            src_empty = None

        try:
            if old_source is not None:
                old_empty = old_source.path
            else:
                old_empty = None
        except ValueError, e:
            old_empty = None

        if src_empty is None:
            return

        if old_empty is None or getattr(source, 'path') != getattr(old_source, 'path'):
            thumb = getattr(instance, self._field_name, )
            import Image as pil
            import os
            try:
                img = pil.open(source.path, )
            except IOError:
#                pub_date = getattr(instance, 'pub_date', None, )
#                if pub_date:
#                    filename = source.name.split('/')[-1]
#                    source.name = 'photos/news/%s/%s' % (pub_date.strftime('%Y/%m/%d'), filename, )
                import os
                source.save(os.path.basename(source.path, ), source, save=False, )
                img = pil.open(source.path, )
                if old_source:
                    import os
                    os.system("rm " + old_source.path, )
            finally:
                filename = self.generate_thumb_name(source.path, )
                try:
                    raw = rescale(img, self.size[0], self.size[1])
                except UnboundLocalError:
                    import os
                    source.save(os.path.basename(source.path, ), source, save=False, )
                    img = pil.open(source.path, )
                    raw = rescale(img, self.size[0], self.size[1])
                thumb.save(name=filename, content=ContentFile(raw), save=False, )
                if old_source:
                    old_thumb = getattr(old_instance, self._field_name, )
                    import os
#                    old_thumb_path = old_thumb.path
                    os.system('rm ' + old_thumb.path, )
#                command = 'rm ' + 'photos/news/%s/' % add_date.strftime('%Y/%m/%d') + self.generate_thumb_name(old_source.path, )
#                raise Exception("Message")


text:
maintainer       "Andrew Crump"
maintainer_email "andrew@kotirisoftware.com"
license          "Apache 2.0"
description      "Acceptance tests for mysql"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "0.1.0"

depends          "database"
depends          "mysql"
depends          "yum"


text:
from elasticsearch import Elasticsearch
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.ioff()
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.dates import AutoDateLocator, AutoDateFormatter
import numpy as np
from scipy import stats
import datetime as dt
import math
import json
import pprint

with open("config", "r+") as txt:
    contents = list(map(str.rstrip, txt))

esCon = Elasticsearch([{
    'host': contents[4], 'port': contents[5]
}], timeout=30)

pp = pprint.PrettyPrinter(indent=4)

def utcDate(time):
    return dt.datetime.fromtimestamp(time, dt.timezone.utc)

def utcStamp(time):
    return (dt.datetime.strptime(time,'%Y-%m-%dT%X')).replace(tzinfo=dt.timezone.utc).timestamp()

scrollPreserve="3m"
startDate = "2016-07-17T00:00:00"
endDate = "2016-07-25T00:00:00"
utcStart = utcStamp(startDate)
utcEnd = utcStamp(endDate)
oneDay = np.multiply(24,np.multiply(60,60))

loc = {}
loc["Workflow"] = np.array([])

def esConAgg(field):
    queryBody={"aggs": {
                 "dev": {
                   "terms": {"field":field}
                 }
               }
              }
    scannerCon = esCon.search(index="net-health",
                              body=queryBody,
                              search_type="query_then_fetch",
                              scroll=scrollPreserve)
    scrollIdCon = scannerCon['aggregations']['dev']
    conTotalRec = scrollIdCon['buckets']
    arrRet = np.array([])

    if conTotalRec == 0:
        return None
    else:
        for hit in conTotalRec:
            arrRet = np.append(arrRet, hit['key'])
        return arrRet

def esConQuery(src, dest):
    queryBody={"query" :
                {"bool": {
                  "must": [
                    {"match" :
                      {"src" : src}
                    },
                    {"match" :
                      {"dest" : dest}
                    },
                    {"range" : {
                       "beginDate" : {
                         "gt" : int(utcStart),
                         "lt" : int((utcStart + oneDay))
                       }
                     }
                    }
                  ]
                 }
                }, "sort": {"beginDate": {"order": "desc"}}
              }
    scannerCon = esCon.search(index="net-health",
                              body=queryBody,
                              search_type="scan",
                              scroll=scrollPreserve)
    scrollIdCon = scannerCon['_scroll_id']
    conTotalRec = scannerCon["hits"]["total"]
    arrRet = {}

    if conTotalRec == 0:
        return None
    else:
        while conTotalRec > 0:
            responseCon = esCon.scroll(scroll_id=scrollIdCon,
                                       scroll=scrollPreserve)
            for hit in responseCon["hits"]["hits"]:
                if not str(hit["_source"]["Workflow"]) in arrRet:
                    loc["Workflow"] = np.append(loc["Workflow"],
                                                str(hit["_source"]["Workflow"]))
                    arrRet[str(hit["_source"]["Workflow"])] = np.reshape(np.array([hit["_source"]["meanKEvents"],
                                                                   hit["_source"]["meanCpuEff"],
                                                                   hit["_source"]["meanWallClockHr"]]), (1,3))
                else:
                    arrRet[str(hit["_source"]["Workflow"])] = np.vstack((arrRet[str(hit["_source"]["Workflow"])],
                                                         np.array([hit["_source"]["meanKEvents"],
                                                                   hit["_source"]["meanCpuEff"],
                                                                   hit["_source"]["meanWallClockHr"]])))
            conTotalRec -= len(responseCon['hits']['hits'])
        return arrRet

#print(esConAgg("src"))
#print(esConAgg("dest"))
def main(utcStart):
    with PdfPages('PDFOut/CMS_Lumosity.pdf') as pc:
        d = pc.infodict()
        d['Title'] = 'CMS Scatter Plots'
        d['Author'] = u'Jerrod T. Dixon\xe4nen'
        d['Subject'] = 'Plot of network affects on grid jobs'
        d['Keywords'] = 'PdfPages matplotlib CMS grid'
        d['CreationDate'] = dt.datetime.today()
        d['ModDate'] = dt.datetime.today()
        with open("WorkOut/Lumosity.out", "w") as ww:
            while utcStart <= utcEnd:
                srcSites = esConAgg("src")
                destSites = esConAgg("dest")
                workDate = utcDate(utcStart)
                for ping in srcSites:
                    for pong in destSites:
                        qResults = esConQuery(ping, pong)
                        if not type(qResults) == type(None):
                            ww.write(str(workDate.strftime('%d-%B-%Y') + "\n\n"))
                            for hit in qResults:
                                diskUsage = qResults[str(hit)]
                                figsT, axsT = plt.subplots(1, sharex=True)
                                axsT.scatter(diskUsage[:,0],diskUsage[:,1])
                                axsT.set_ylabel("meanWallClockHr")
                                axsT.set_xlabel(str("meanKEvents (" + hit + ")"))
                                axsT.set_title(str(ping + " to " + pong + " on " + workDate.strftime('%d-%B-%Y')))
                                pc.savefig(figsT)
                                plt.close(figsT)
                                print("diskUsage[:,0]")
                                print(diskUsage[:,0])
                                print("diskUsage[:,1]")
                                print(diskUsage[:,1])
                                ww.write(str("Workflow: " + hit + "\n"))
                                ww.write(str("Work site: " + ping + "\n"))
                                ww.write(str("Data site: " + pong + "\n"))
                                cslope, cintercept, cr_value, cp_value, cstd_err = stats.linregress(diskUsage[:,0],diskUsage[:,1])
                                ww.write(str("X: CpuEff  Y: InputGB\n"))
                                ww.write(str("c_Slope: " + str(cslope) + "\n"))
                                ww.write(str("c_Intercept: " + str(cintercept) + "\n"))
                                ww.write(str("c_R Value: " + str(cr_value) + "\n"))
                                ww.write(str("c_P Value: " + str(cp_value) + "\n"))
                                ww.write(str("c_std err: " + str(cstd_err) + "\n"))
                                ww.write(str("\n\n"))

                utcStart = utcStart + oneDay

    #axC[1].scatter(destRes[:,0],destRes[:,1])
    #axC[1].set_ylabel("meanCpuEff")

# Run Main code
print("start")
main(utcStart)
print("finish")


text:
.. HdlParse documentation master file, created by
   sphinx-quickstart on Sun Oct 15 14:19:42 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

========
Hdlparse
========

Hdlparse is a simple package implementing a rudimentary parser for VHDL and Verilog. It is not capable of fully parsing the entire language. Rather, it is meant to extract enough key information from a source file to create generated documentation.

This library is used by the `Symbolator <https://github.com/kevinpt/symbolator>`_ diagram generator.

For VHDL this library can extract component, subprogram, type, subtype, and constant declarations from a package. For Verilog it can extract module declarations (both 1995 and 2001 syntax).

Requirements
------------

Hdlparse requires either Python 2.7 or Python 3.x and no additional libraries.

The installation script depends on setuptools. The source is written in
Python 2.7 syntax but will convert cleanly to Python 3 when the installer
passes it through ``2to3``.

Licensing
---------

Opbasm and the included VHDL source is licensed for free commercial and non-commercial use under the terms of the MIT license.

Download
--------

You can access the Hdlparse Git repository from `Github
<https://github.com/kevinpt/hdlparse>`_. You can install direct from PyPI with the ``pip``
command if you have it available.

Installation
------------

Hdlparse is a Python library. You must have Python installed first to use it. Most modern Linux distributions and OS/X have it available by default. There are a number of options available for Windows. If you don't already have a favorite, I recommend getting one of the `"full-stack" Python distros <http://www.scipy.org/install.html>`_ that are geared toward scientific computing such as Anaconda or Python(x,y).

You need to have the Python setuptools installed first. If your OS has a package manager, it may be preferable to install setuptools through that tool. Otherwise you can use Pip:

.. code-block:: sh

  > pip install setuptools

The easiest way to install Hdlparse is from `PyPI <https://pypi.python.org/pypi/hdlparse>`_.

.. code-block:: sh

  > pip install --upgrade hdlparse

This will download and install the latest release, upgrading if you already have it installed. If you don't have ``pip`` you may have the ``easy_install`` command available which can be used to install ``pip`` on your system:

.. code-block:: sh

  > easy_install pip

You can also use ``pip`` to get the latest development code from Github:

.. code-block:: sh

  > pip install --upgrade https://github.com/kevinpt/hdlparse/tarball/master

If you manually downloaded a source package or created a clone with Git you can install with the following command run from the base Hdlparse directory:

.. code-block:: sh

  > python setup.py install

On Linux systems you may need to install with root privileges using the *sudo* command.

After a successful install the Hdlparse library will be available.

Using Hdlparse
--------------

The Hdlparse library has two main modules :py:mod:`~hdlparse.vhdl_parser` and :py:mod:`~hdlparse.verilog_parser`. You import one or both of them as needed.

.. code-block:: python

  import hdlparse.vhdl_parser as vhdl
  import hdlparse.verilog_parser as vlog

Within each module are extractor classes :py:class:`~hdlparse.vhdl_parser.VhdlExtractor` and :py:class:`~hdlparse.verilog_parser.VerilogExtractor` that are the central mechanisms for using Hdlparse.

.. code-block:: python

  vhdl_ex = vhdl.VhdlExtractor()
  vlog_ex = vlog.VerilogExtractor()

VHDL
~~~~

The VHDL parser can extract a variety of different objects from sourec code. It can be used to access package definitions and component declarations,type and subtype definitions, functions, and procedures found within a package. It will not process entity declarations or nested subprograms and types.

Extraction proceeds as follows:

.. code-block:: python

  with io.open(fname, 'rt', encoding='latin-1') as fh:
    code = fh.read()
  vhdl_objs = vhdl_ex.extract_objects_from_source(code)

  vhdl_objs = vhdl_ex.extract_objects(fname)

These will extract a list of all supported object types. The result is a list of objects subclassed from :py:class:`~hdlparse.vhdl_parser.VhdlObject`. You can pass an optional subclass of ``VhdlObject`` to filter the results for just that type. Repeated calls are more efficient when using :py:meth:`~hdlparse.vhdl_parser.VhdlExtractor.extract_objects` which maintains a cache of all previously parsed objects in the extractor.

.. code-block:: vhdl

  package example is
    component demo is
      generic (
        GENERIC1: boolean := false;
        GENERIC2: integer := 100
      );
      port (
        a, b : in std_ulogic := '1';
        c, d : out std_ulogic_vector(7 downto 0);
        e, f : inout unsigned(7 downto 0)
      );
    end component;
  end package;

Each port and generic is an instance of :py:class:`~hdlparse.vhdl_parser.VhdlParameter` containing the name, mode (input, output, inout), and type.

.. code-block:: python

  import hdlparse.vhdl_parser as vhdl
  from hdlparse.vhdl_parser import VhdlComponent

  vhdl_ex = vhdl.VhdlExtractor()
  vhdl_comps = vhdl_ex.extract_objects('example.vhdl', VhdlComponent)

  for c in vhdl_comps:
    print('Component "{}":'.format(c.name))

    print('  Generics:')
    for p in c.generics:
      print('\t{:20}{:8} {}'.format(p.name, p.mode, p.data_type))

    print('  Ports:')
    for p in c.ports:
      print('\t{:20}{:8} {}'.format(p.name, p.mode, p.data_type ))

When run against the example code produces the following:

.. code-block: console

  Component "demo":
    Generics:
	  GENERIC1            in       boolean
	  GENERIC2            in       integer
    Ports:
	  a                   in       std_ulogic
	  b                   in       std_ulogic
	  c                   out      std_ulogic_vector(7 downto 0)
	  d                   out      std_ulogic_vector(7 downto 0)
	  e                   inout    unsigned(7 downto 0)
	  f                   inout    unsigned(7 downto 0)

VHDL arrays
~~~~~~~~~~~

It can be useful to know which data types are an array. The :py:class:`~hdlparse.vhdl_parser.VhdlExtractor` class will keep track of all visited array type definitions it sees. The :py:meth:`~hdlparse.vhdl_parser.VhdlExtractor.is_array` method lets you query the internal list to check if a type is for an array. All IEEE standard array types are supported by default. Any subtypes derived from an array type will also be considered as arrays.

.. code-block:: python

  import hdlparse.vhdl_parser as vhdl

  vhdl_ex = vhdl.VhdlExtractor()

  code = '''
  package foobar is
    type custom_array is array(integer range <>) of boolean;
    subtype custom_subtype is custom_array(1 to 10);
  end package;
  '''
  vhdl_comps = vhdl_ex.extract_objects(code)

  # These all return true:
  print(vhdl_ex.is_array('unsigned'))
  print(vhdl_ex.is_array('custom_array'))
  print(vhdl_ex.is_array('custom_subtype'))

Parsed array data can be saved to a file with :py:meth:`~hdlparse.vhdl_parser.VhdlExtractor.save_array_types` and restored with :py:meth:`~hdlparse.vhdl_parser.VhdlExtractor.load_array_types`. This lets you parse one set of files for type definitions and use the saved info for parsing other code at a different time.

Verilog
~~~~~~~

The Verilog parser is only able to extract module definitions with a port and optional parameter list. Verilog modules are extracted using the :py:meth:`~hdlparse.verilog_parser.VerilogExtractor.extract_objects` and :py:meth:`~hdlparse.verilog_parser.VerilogExtractor.extract_objects_from_source` methods. The latter is used when you have the code in a string. The former when you want to read the Veirlog source from a file. When parsing a file, a cache of objects is maintained so you can repeatedly call :py:meth:`~hdlparse.verilog_parser.VerilogExtractor.extract_objects` without reparsing the file.

.. code-block:: python

  with open(fname, 'rt') as fh:
    code = fh.read()
  vlog_mods = vlog_ex.extract_objects_from_source(code)

  vlog_mods = vlog_ex.extract_objects(fname)

The result is a list of extracted :py:class:`~hdlparse.verilog_parser.VerilogModule` objects. Each instance of this class has ``name``, ``generics``, and ``ports`` attributes. The ``name`` attribute is the name of the module. The ``generics`` attribute is a list of extracted parameters and ``ports`` is a list of the ports on the module.

.. code-block:: verilog

  module newstyle // This is a new style module def
  #(parameter real foo = 8, bar=1, baz=2,
  parameter signed [7:0] zip = 100)
  (
    input x, x2, inout y, y2_long_output,
    output wire [4:1] z, z2
  );
  endmodule

Each port and generic is an instance of :py:class:`~hdlparse.verilog_parser.VerilogParameter` containing the name, mode (input, output, inout), and type.

.. code-block:: python

  import hdlparse.verilog_parser as vlog

  vlog_ex = vlog.VerilogExtractor()
  vlog_mods = vlog_ex.extract_objects_from_source('example.v')

  for m in vlog_mods:
    print('Module "{}":'.format(m.name))

    print('  Parameters:')
    for p in m.generics:
      print('\t{:20}{:8}{}'.format(p.name, p.mode, p.data_type))

    print('  Ports:')
    for p in m.ports:
      print('\t{:20}{:8}{}'.format(p.name, p.mode, p.data_type))

When run against the example code produces the following:

.. code-block:: console

  Module "newstyle":
    Parameters:
	  foo                 in      real
	  bar                 in      real
	  baz                 in      real
	  zip                 in      signed [7:0]
    Ports:
	  x                   input
	  x2                  input
	  y                   inout
	  y2_long_output      inout
	  z                   output  wire [4:1]
	  z2                  output  wire [4:1]

.. toctree::
   :hidden:
   :maxdepth: 2

   apidoc/modules

Indices and tables
------------------

* :ref:`genindex`
* :ref:`search`


text:
<!doctype html>

<meta charset="utf-8">
<title>US States Choropleth</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<link href="../dist/d3-geomap.css" rel="stylesheet">

US States Venture Capital 1$ / 1000$ GDP


text:
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
 * Copyright 2008-2013 Pelican Mapping
 * http://osgearth.org
 *
 * osgEarth 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 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */
#include "LevelDBCache"
#include "LevelDBCacheBin"
#include <osgEarth/URI>
#include <osgEarth/ThreadingUtils>
#include <osgDB/Registry>
#include <osgDB/ReaderWriter>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>

#include <sys/stat.h>
#ifndef _WIN32
#   include <unistd.h>
#endif

#define LC "[LevelDBCache] "

#define OSGEARTH_ENV_CACHE_MAX_SIZE_MB "OSGEARTH_CACHE_MAX_SIZE_MB"

#define LEVELDB_CACHE_VERSION 1

using namespace osgEarth;
using namespace osgEarth::Drivers::LevelDBCache;

LevelDBCacheImpl::LevelDBCacheImpl( const CacheOptions& options ) :
osgEarth::Cache( options ),
_options       ( options ),
_active        ( true )
{
    if ( _options.rootPath().isSet() )
    {
        _rootPath = URI( *_options.rootPath(), options.referrer() ).full();
    }
    else
    {
        // read the root path from ENV is necessary:
        const char* cachePath = ::getenv(OSGEARTH_ENV_CACHE_PATH);
        if ( cachePath )
        {
            _rootPath = cachePath;
            OE_INFO << LC << "Cache location set from environment: \""
                << cachePath << "\"" << std::endl;
        }
    }

    const char* maxsize = ::getenv(OSGEARTH_ENV_CACHE_MAX_SIZE_MB);
    if ( maxsize )
    {
        unsigned mb = as<unsigned>(std::string(maxsize), 0u);
        if ( mb > 0 )
        {
            _options.maxSizeMB() = mb;

            OE_INFO << LC << "Set max cache size from environment: "
                << (_options.maxSizeMB().value()) << " MB"
                << std::endl;
        }
        else
        {
            OE_WARN << LC
                << "Env var \"" OSGEARTH_ENV_CACHE_MAX_SIZE_MB "\" set to an invalid value"
                << std::endl;
        }
    }

    _tracker = new Tracker(_options, _rootPath);

    if ( !_rootPath.empty() )
    {
        init();
    }
    else
    {
        _active = false;
        OE_WARN << LC << "Illegal: no root path set for cache!" << std::endl;
    }
}

LevelDBCacheImpl::~LevelDBCacheImpl()
{
    if ( _db )
    {
        delete _db;
        _db = 0L;
    }
}

void
LevelDBCacheImpl::init()
{
    // ensure there's a folder for the cache.
    if ( !osgDB::fileExists(_rootPath) )
    {
        if (osgDB::makeDirectory(_rootPath) == false)
        {
            OE_WARN << LC << "Oh no, failed to create root cache folder \"" << _rootPath << "\""
                << std::endl;
            return;
        }
    }

    open();

    // Do an initial size check.
    if ( _db )
    {
        _tracker->calcSize();
    }

    if ( _active )
    {
        OE_INFO << LC << "Opened DB at " << _rootPath << std::endl;
    }
}

void
LevelDBCacheImpl::open()
{
    leveldb::Options options;
    options.create_if_missing = true;
    options.block_size        = _options.blockSize().value();

    leveldb::Status status;

    status = leveldb::DB::Open(options, _rootPath, &_db);
    if ( status.ok() )
        return;

    OE_WARN << LC << "Database problem...attempting to repair..." << std::endl;
    status = leveldb::RepairDB(_rootPath, options);
    if ( status.ok() )
    {
        status = leveldb::DB::Open(options, _rootPath, &_db);
        if ( status.ok() )
        {
            OE_WARN << LC << "...repair complete!" << std::endl;
            return;
        }
    }

    OE_WARN << LC << "Failed to open or create cache bin at " << _rootPath << std::endl;
    if ( _db )
    {
        delete _db;
        _db = 0L;
        _active = false;
    }
}

CacheBin*
LevelDBCacheImpl::addBin( const std::string& name )
{
    return _db ?
        _bins.getOrCreate(name, new LevelDBCacheBin(name, _db, _tracker.get())) :
        0L;
}

CacheBin*
LevelDBCacheImpl::getOrCreateDefaultBin()
{
    if ( !_db )
        return 0L;

    static Threading::Mutex s_defaultBinMutex;
    if ( !_defaultBin.valid() )
    {
        Threading::ScopedMutexLock lock( s_defaultBinMutex );
        if ( !_defaultBin.valid() ) // double-check
        {
            _defaultBin = new LevelDBCacheBin("_default", _db, _tracker.get());
        }
    }
    return _defaultBin.get();
}

off_t
LevelDBCacheImpl::getApproximateSize() const
{
    return _tracker->calcSize();
}

bool
LevelDBCacheImpl::compact()
{
    if ( !_db )
        return false;

    _db->CompactRange(0L, 0L);

    return true;
}

bool
LevelDBCacheImpl::clear()
{
    if ( !_db )
        return false;

    // No WriteBatch because it doesn't seem to allow compaction to occur
    // -- need to figure out why someday.

    leveldb::Iterator* it = _db->NewIterator(leveldb::ReadOptions());
    for(it->SeekToFirst(); it->Valid(); it->Next())
    {
        _db->Delete(leveldb::WriteOptions(), it->key());
    }

    return true;
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.IO
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Semantics
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Semantics

    Public Class SpeculationAnalyzerTests
        Inherits SpeculationAnalyzerTestsBase

        <Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")>
        Public Sub SpeculationAnalyzerExtensionMethodExplicitInvocation()
            Test(<Code>
Module Oombr
    <System.Runtime.CompilerServices.Extension>
    Public Sub Vain(arg As Integer)
    End Sub

    Sub Main()
        Call [|5.Vain()|]
    End Sub
End Module
            </Code>.Value, "Vain(5)", False)
        End Sub

        Protected Overrides Function Parse(text As String) As SyntaxTree
            Return SyntaxFactory.ParseSyntaxTree(text)
        End Function

        Protected Overrides Function IsExpressionNode(node As SyntaxNode) As Boolean
            Return TypeOf node Is ExpressionSyntax
        End Function

        Protected Overrides Function CreateCompilation(tree As SyntaxTree) As Compilation
            Return VisualBasicCompilation.Create(
                CompilationName,
                {DirectCast(tree, VisualBasicSyntaxTree)},
                References,
                TestOptions.ReleaseDll.WithSpecificDiagnosticOptions({KeyValuePairUtil.Create("BC0219", ReportDiagnostic.Suppress)}))
        End Function

        Protected Overrides Function CompilationSucceeded(compilation As Compilation, temporaryStream As Stream) As Boolean
            Dim langCompilation = DirectCast(compilation, VisualBasicCompilation)
            Return Not langCompilation.GetDiagnostics().Any() AndAlso Not langCompilation.Emit(temporaryStream).Diagnostics.Any()
        End Function

        Protected Overrides Function ReplacementChangesSemantics(initialNode As SyntaxNode, replacementNode As SyntaxNode, initialModel As SemanticModel) As Boolean
            Return New SpeculationAnalyzer(DirectCast(initialNode, ExpressionSyntax), DirectCast(replacementNode, ExpressionSyntax), initialModel, CancellationToken.None).ReplacementChangesSemantics()
        End Function
    End Class
End Namespace


text:
import { Class, SugarElement } from '@ephox/sugar';

import * as Behaviour from 'ephox/alloy/api/behaviour/Behaviour';
import { Toggling } from 'ephox/alloy/api/behaviour/Toggling';
import * as Attachment from 'ephox/alloy/api/system/Attachment';
import * as Gui from 'ephox/alloy/api/system/Gui';
import { Button } from 'ephox/alloy/api/ui/Button';
import * as HtmlDisplay from 'ephox/alloy/demo/HtmlDisplay';
import * as DomModification from 'ephox/alloy/dom/DomModification';

/* eslint-disable no-console */

export default (): void => {
  const gui = Gui.create();
  const body = SugarElement.fromDom(document.body);
  Class.add(gui.element, 'gui-root-demo-container');
  Attachment.attachSystem(body, gui);

  const redBehaviour = Behaviour.create({
    fields: [ ],
    name: 'red.behaviour',
    active: {
      exhibit: () => {
        return DomModification.nu({
          classes: [ 'cat' ],
          attributes: {

          },
          styles: {
            color: 'red'
          }
        });
      }
    }
  });

  const catBehaviour = Behaviour.create({
    fields: [ ],
    name: 'cat.behaviour',
    active: {
      exhibit: () => {
        return DomModification.nu({
          classes: [ 'cat' ],
          attributes: {
            'data-cat': 'cat'
          },
          styles: {
            background: 'blue'
          }
        });
      }
    }
  });

  HtmlDisplay.section(
    gui,
    'This button is a button tag with an image',
    Button.sketch({
      dom: {
        tag: 'button',
        styles: {
          'background-color': 'black',
          'background-image': 'url(http://yamaha/textbox/icons/Transforms13.png)',
          'width': '20px',
          'height': '20px'
        }
      },
      action: () => {
        console.log('*** Image ButtonDemo click ***');
      }
    })
  );

  const button2 = HtmlDisplay.section(
    gui,
    'This toggle button is a span tag with an font',
    Button.sketch({
      dom: {
        tag: 'button',
        classes: [ 'demo-alloy-bold' ],
        styles: {
          border: '1px solid #ccc',
          display: 'inline-block'
        }
      },
      action: () => {
        console.log('*** Font ButtonDemo click ***');
      },
      buttonBehaviours: Behaviour.derive([
        Toggling.config({
          toggleClass: 'demo-selected',
          aria: {
            mode: 'pressed'
          }
        })
      ])
    })
  );

  Toggling.on(button2);

  HtmlDisplay.section(
    gui,
    'This text button has two custom behaviours. One adds (among other things) "data-cat" and ' +
    'background blue, and the other adds color red',
    Button.sketch({
      dom: {
        tag: 'span',
        innerHtml: 'Button.with.Text'
      },
      action: () => {
        console.log('*** ButtonDemo click ***');
      },

      buttonBehaviours: Behaviour.derive([
        catBehaviour.config({ }),
        redBehaviour.config({ })
      ])
    })
  );
};