text:
/**
 * Given a field name, this will return its field info.
 * @param {String} field_name
 * @return {Object}
 */
function drupalgap_field_info_field(field_name) {
  try {
    return drupalgap.field_info_fields[field_name];
  }
  catch (error) { console.log('drupalgap_field_info_field - ' + error); }
}

/**
 * Returns info on all fields.
 * @return {Object}
 */
function drupalgap_field_info_fields() {
  try {
    return drupalgap.field_info_fields;
  }
  catch (error) { console.log('drupalgap_field_info_fields - ' + error); }
}

/**
 * Given an entity type, field name, and bundle name this will return a JSON
 * object with data for the specified field name.
 * @param {String} entity_type
 * @param {String} field_name
 * @param {String} bundle_name
 * @return {Object}
 */
function drupalgap_field_info_instance(entity_type, field_name, bundle_name) {
  try {
    var instances = drupalgap_field_info_instances(entity_type, bundle_name);
    if (!instances) {
      var msg = 'WARNING: drupalgap_field_info_instance - instance was null ' +
      'for entity (' + entity_type + ') bundle (' + bundle_name + ') using ' +
      'field (' + field_name + ')';
      console.log(msg);
      return null;
    }
    if (!instances[field_name]) {
      var msg = 'WARNING: drupalgap_field_info_instance - ' +
        '"' + field_name + '" does not exist for entity (' + entity_type + ')' +
        ' bundle (' + bundle_name + ')';
      console.log(msg);
      return null;
    }
    return instances[field_name];
  }
  catch (error) { console.log('drupalgap_field_info_instance - ' + error); }
}

/**
 * Given an entity type and/or a bundle name, this returns the field info
 * instances for the entity or the bundle.
 * @param {String} entity_type
 * @param {String} bundle_name
 * @return {Object}
 */
function drupalgap_field_info_instances(entity_type, bundle_name) {
  try {
    var field_info_instances;
    // If there is no bundle, pull the fields out of the wrapper.
    // @TODO there appears to be a special case with commerce_products, in that
    // they aren't wrapped like normal entities (see the else statement when a
    // bundle name isn't present). Or do we have a bug here, and we shouldn't
    // be expecting the wrapper in the first place?
    if (!bundle_name) {
      if (entity_type == 'commerce_product') {
        field_info_instances =
          drupalgap.field_info_instances[entity_type];
      }
      else {
        field_info_instances =
          drupalgap.field_info_instances[entity_type][entity_type];
      }
    }
    else {
      if (typeof drupalgap.field_info_instances[entity_type] !== 'undefined') {
        field_info_instances =
          drupalgap.field_info_instances[entity_type][bundle_name];
      }
    }
    return field_info_instances;
  }
  catch (error) { console.log('drupalgap_field_info_instances - ' + error); }
}

/**
 * Given an entity type, bundle, form and entity, this will add the
 * entity's fields to the given form.
 * @param {String} entity_type
 * @param {String} bundle
 * @param {Object} form
 * @param {Object} entity
 */
function drupalgap_field_info_instances_add_to_form(entity_type, bundle,
  form, entity) {
  try {
    // Grab the field info instances for this entity type and bundle.
    var fields = drupalgap_field_info_instances(entity_type, bundle);
    // If there is no bundle, pull the fields out of the wrapper.
    //if (!bundle) { fields = fields[entity_type]; }
    // Use the default language, unless the entity has one specified.
    var language = language_default();
    if (entity && entity.language) { language = entity.language; }
    // Iterate over each field in the entity and add it to the form. If there is
    // a value present in the entity, then set the field's form element default
    // value equal to the field value.
    if (fields) {
      for (var name in fields) {
        if (!fields.hasOwnProperty(name)) { continue; }
        var field = fields[name];
        // The user registration form is a special case, in that we only want
        // to place fields that are set to display on the user registration
        // form. Skip any fields not set to display.
        if (form.id == 'user_register_form' &&
          !field.settings.user_register_form) {
          continue;
        }
        var field_info = drupalgap_field_info_field(name);
        if (field_info) {
          form.elements[name] = {
            type: field_info.type,
            title: field.label,
            required: field.required,
            description: field.description
          };
          if (!form.elements[name][language]) {
            form.elements[name][language] = {};
          }
          var default_value = field.default_value;
          var delta = 0;
          var cardinality = parseInt(field_info.cardinality);
          if (cardinality == -1) {
            cardinality = 1; // we'll just add one element for now, until we
                             // figure out how to handle the 'add another
                             // item' feature.
          }
          if (entity && entity[name] && entity[name].length != 0 && entity[name][language]) {
            for (var delta = 0; delta < cardinality; delta++) {
              // @TODO - is this where we need to use the idea of the
              // value_callback property present in Drupal's FAPI? That way
              // each element knows how to map the entity data to its element
              // value property.
              if (
                entity[name][language][delta] &&
                typeof entity[name][language][delta].value !== 'undefined'
              ) { default_value = entity[name][language][delta].value; }
              // If the default_value is null, set it to an empty string.
              if (default_value == null) { default_value = ''; }
              // @todo - It appears not all fields have a language code to use
              // here, for example taxonomy term reference fields don't!
              form.elements[name][language][delta] = {
                value: default_value
              };
              // Place the field item onto the element.
              if (entity[name][language][delta]) {
                form.elements[name][language][delta].item =
                  entity[name][language][delta];
              }
            }
          }

          // Give module's a chance to alter their own element during the form
          // build, that way element properties will be saved to local storage
          // and then available during hook_field_widget_form() and the form
          // submission process.
          var fn = field.widget.module + '_field_info_instance_add_to_form';
          if (drupalgap_function_exists(fn)) {
            window[fn](entity_type, bundle, form, entity, form.elements[name]);
          }

        }
      }
    }
  }
  catch (error) {
    console.log('drupalgap_field_info_instances_add_to_form - ' + error);
  }
}

/**
 * Given a field name, this will return the key that should be used when
 * setting its value on an entity. If the field name is not a field, it returns
 * false.
 * @param {String} field_name
 * @return {String}
 */
function drupalgap_field_key(field_name) {
  try {
    // Determine the key to use for the value. By default, most fields
    // use 'value' as the key.
    var key = false;
    var field_info = drupalgap_field_info_field(field_name);
    if (field_info) {
      key = 'value';
      // Images use fid as the key.
      if (field_info.module == 'image' && field_info.type == 'image') {
        key = 'fid';
      }
      else if (
        field_info.module == 'taxonomy' &&
        field_info.type == 'taxonomy_term_reference'
      ) { key = 'tid'; }
    }
    return key;
  }
  catch (error) { console.log('drupalgap_field_key - ' + error); }
}

/**
 * Implements hook_field_formatter_view().
 * @param {String} entity_type
 * @param {Object} entity
 * @param {Object} field
 * @param {Object} instance
 * @param {String} langcode
 * @param {Object} items
 * @param {*} display
 * @return {Object}
 */
function list_field_formatter_view(entity_type, entity, field, instance,
  langcode, items, display) {
  try {
    var element = {};
    if (!empty(items)) {
      for (var delta in items) {
          if (!items.hasOwnProperty(delta)) { continue; }
          var item = items[delta];
          var markup = '';
          // list_default or list_key
          if (display.type == 'list_default') {
            markup = instance.settings.allowed_values[item.value];
            // Single on/off checkboxes need an empty space as their markup so
            // just the label gets rendered.
            if (
              instance.type == 'list_boolean' &&
              field.widget.type == 'options_onoff'
            ) { markup = ' '; }
          }
          else { markup = item.value; }
          element[delta] = { markup: markup };
      }
    }
    return element;
  }
  catch (error) { console.log('list_field_formatter_view - ' + error); }
}

/**
 * Implements hook_assemble_form_state_into_field().
 * @param {Object} entity_type
 * @param {String} bundle
 * @param {String} form_state_value
 * @param {Object} field
 * @param {Object} instance
 * @param {String} langcode
 * @param {Number} delta
 * @param {Object} field_key
 *
 * @return {*}
 */
function list_assemble_form_state_into_field(entity_type, bundle,
  form_state_value, field, instance, langcode, delta, field_key) {
  try {
    var result = form_state_value;
    switch (field.type) {
      case 'list_boolean':
        // For single on/off checkboxes, if the checkbox is unchecked, then we
        // send a null value on the language code. We know the checkbox is
        // unchecked if the form_state_value is equal to the first allowed value
        // on the field.
        if (instance.widget.type == 'options_onoff') {
          var index = 0;
          var on = true;
          for (var value in field.settings.allowed_values) {
              if (!field.settings.allowed_values.hasOwnProperty(value)) { continue; }
              var label = field.settings.allowed_values[value];
              if (form_state_value == value && index == 0) {
                on = false;
                break;
              }
              index++;
          }
          if (!on) {
            field_key.use_delta = false;
            field_key.use_wrapper = false;
            result = null;
          }
        }
        else {
          console.log(
            'WARNING: list_assemble_form_state_into_field - unknown widget (' +
              field.type +
            ') on list_boolean'
          );
        }
        break;
      case 'list_text':
        // For radio buttons on the user entity form, field values must be
        // "flattened", i.e. this field_foo: { und: [ { value: 123 }]}, should
        // be turned into field_foo: { und: 123 }
        if (
          entity_type == 'user' &&
          instance.widget.type == 'options_buttons'
        ) {
          field_key.use_delta = false;
          field_key.use_wrapper = false;
        }
        break;
      default:
        console.log(
          'WARNING: list_assemble_form_state_into_field - unknown type (' +
            field.type +
          ')'
        );
        break;
    }
    return result;
  }
  catch (error) {
    console.log('list_assemble_form_state_into_field - ' + error);
  }
}

/**
 * Implements hook_views_exposed_filter().
 * @param {Object} form
 * @param {Object} form_state
 * @param {Object} element
 * @param {Object} filter
 * @param {Object} field
 */
function list_views_exposed_filter(form, form_state, element, filter, field) {
  try {
    //dpm('list_views_exposed_filter');
    //dpm(arguments);
    var widget = filter.options.group_info.widget;
    if (widget == 'select') {
      // Set the element value if we have one in the filter.
      if (!empty(filter.value)) { element.value = filter.value[0]; }
      // Set the options, then depending on whether or not it is required, set
      // the default value accordingly.
      element.options = filter.value_options;
      if (!element.required) {
        element.options['All'] = '- ' + t('Any') + ' -';
        if (typeof element.value === 'undefined') { element.value = 'All'; }
      }
    }
    else {
      dpm(
        'WARNING: list_views_exposed_filter - unsupported widget (' +
          widget +
        ')'
      );
    }
  }
  catch (error) { console.log('list_views_exposed_filter - ' + error); }
}

/**
 * Implements hook_field_formatter_view().
 * @param {String} entity_type
 * @param {Object} entity
 * @param {Object} field
 * @param {Object} instance
 * @param {String} langcode
 * @param {Object} items
 * @param {*} display
 * @return {Object}
 */
function number_field_formatter_view(entity_type, entity, field, instance,
  langcode, items, display) {
  try {
    var element = {};
    // If items is a string, convert it into a single item JSON object.
    if (typeof items === 'string') {
      items = {0: {value: items}};
    }
    if (!empty(items)) {
      var prefix = '';
      if (!empty(field.settings.prefix)) { prefix = field.settings.prefix; }
      var suffix = '';
      if (!empty(field.settings.suffix)) { suffix = field.settings.suffix; }
      for (var delta in items) {
          if (!items.hasOwnProperty(delta)) { continue; }
          var item = items[delta];
          element[delta] = {
            markup: prefix + item.value + suffix
          };
      }
    }
    return element;
  }
  catch (error) { console.log('number_field_formatter_view - ' + error); }
}

/**
 * Implements hook_field_widget_form().
 * @param {Object} form
 * @param {Object} form_state
 * @param {Object} field
 * @param {Object} instance
 * @param {String} langcode
 * @param {Object} items
 * @param {Number} delta
 * @param {Object} element
 */
function number_field_widget_form(form, form_state, field, instance, langcode,
  items, delta, element) {
  try {
    switch (element.type) {
      case 'number_integer':
      case 'number_float':
      case 'number_decimal':
      case 'range':
        // Change the form element into a number, unless we're using a range
        // slider. Then set its min/max attributes along with the step.
        if (element.type != 'range') { items[delta].type = 'number'; }
        if (!empty(instance.settings.max)) {
          items[delta].options.attributes['min'] = instance.settings.min;
        }
        if (!empty(instance.settings.max)) {
          items[delta].options.attributes['max'] = instance.settings.max;
        }
        var step = 1;
        if (element.type == 'number_float') { step = 0.01; }
        if (element.type == 'number_decimal') { step = 0.01; }
        items[delta].options.attributes['step'] = step;
        break;
      default:
        console.log(
          'number_field_widget_form - element type not supported (' +
            element.type +
          ')'
        );
        break;
    }
  }
  catch (error) { console.log('number_field_widget_form - ' + error); }
}

/**
 * Implements hook_field_widget_form().
 * @param {Object} form
 * @param {Object} form_state
 * @param {Object} field
 * @param {Object} instance
 * @param {String} langcode
 * @param {Object} items
 * @param {Number} delta
 * @param {Object} element
 * @return {*}
 */
function options_field_widget_form(form, form_state, field, instance, langcode,
  items, delta, element) {
  try {
    switch (element.type) {
      case 'checkbox':
        // If the checkbox has a default value of 1, check the box.
        if (items[delta].default_value == 1) { items[delta].checked = true; }
        break;
      case 'radios':
        break;
      case 'list_boolean':
        switch (instance.widget.type) {
          case 'options_onoff':
            // Switch an on/off boolean to a checkbox and place its on/off
            // values as attributes. Depending on the allowed values, we may
            // have to iterate over an array, or an object to get the on/off
            // values.
            items[delta].type = 'checkbox';
            var off = null;
            var on = null;
            if ($.isArray(field.settings.allowed_values)) {
              for (var key in field.settings.allowed_values) {
                if (off === null) { off = key; }
                else { on = key; }
              }
            }
            else {
              for (var value in field.settings.allowed_values) {
                  if (!field.settings.allowed_values.hasOwnProperty(value)) { continue; }
                  var label = field.settings.allowed_values[value];
                  if (off === null) { off = value; }
                  else { on = value; }
              }
            }
            items[delta].options.attributes['off'] = off;
            items[delta].options.attributes['on'] = on;
            // If the value equals the on value, then check the box.
            if (
              typeof items[delta] !== 'undefined' && items[delta].value == on
            ) { items[delta].options.attributes['checked'] = 'checked'; }
            break;
          default:
            console.log(
              'WARNING: options_field_widget_form list_boolean with ' +
              'unsupported type (' + instance.widget.type + ')'
            );
            break;
        }
        break;
      case 'select':
      case 'list_text':
      case 'list_float':
      case 'list_integer':
        if (instance) {
          switch (instance.widget.type) {
            case 'options_select':
              items[delta].type = 'select';
              // If the select list is required, add a 'Select' option and set
              // it as the default.  If it is optional, place a "none" option
              // for the user to choose from.
              var text = '- None -';
              if (items[delta].required) {
                text = '- ' + t('Select a value') + ' -';
              }
              items[delta].options[''] = text;
              if (empty(items[delta].value)) { items[delta].value = ''; }
              // If more than one value is allowed, turn it into a multiple
              // select list.
              if (field.cardinality != 1) {
                items[delta].options.attributes['data-native-menu'] = 'false';
                items[delta].options.attributes['multiple'] = 'multiple';
              }
              break;
            case 'options_buttons':
              // If there is one value allowed, we turn this into radio
              // button(s), otherwise they will become checkboxes.
              var type = 'checkboxes';
              if (field.cardinality == 1) { type = 'radios'; }
              items[delta].type = type;
              break;
            default:
              console.log(
                'WARNING: options_field_widget_form - unsupported widget (' +
                instance.widget.type + ')'
              );
              return false;
              break;
          }
          // If there are any allowed values, place them on the options
          // list. Then check for a default value, and set it if necessary.
          if (field && field.settings.allowed_values) {
            for (var key in field.settings.allowed_values) {
                if (!field.settings.allowed_values.hasOwnProperty(key)) { continue; }
                var value = field.settings.allowed_values[key];
                // Don't place values that are objects onto the options
                // (i.e. commerce taxonomy term reference fields).
                if (typeof value === 'object') { continue; }
                // If the value already exists in the options, then someone
                // else has populated the list (e.g. commerce), so don't do
                // any processing.
                if (typeof items[delta].options[key] !== 'undefined') {
                  break;
                }
                // Set the key and value for the option.
                items[delta].options[key] = value;
            }
            if (instance.default_value && instance.default_value[delta] &&
              typeof instance.default_value[delta].value !== 'undefined') {
                items[delta].value = instance.default_value[delta].value;
            }
          }
        }
        break;
      case 'taxonomy_term_reference':
          // Change the item type to a hidden input.
          items[delta].type = 'hidden';
          // What vocabulary are we using?
          var machine_name = field.settings.allowed_values[0].vocabulary;
          var taxonomy_vocabulary =
            taxonomy_vocabulary_machine_name_load(machine_name);

          var widget_type = false;
          if (instance.widget.type == 'options_select') {
            widget_type = 'select';
          }
          else {
            console.log(
              'WARNING: options_field_widget_form() - ' + instance.widget.type +
              ' not yet supported for ' + element.type + ' form elements!'
            );
            return false;
          }
          var widget_id = items[delta].id + '-' + widget_type;
          // If the select list is required, add a 'Select' option and set
          // it as the default.  If it is optional, place a "none" option
          // for the user to choose from.
          var text = '- ' + t('None') + ' -';
          if (items[delta].required) {
            text = '- ' + t('Select a value') + ' -';
          }
          items[delta].children.push({
              type: widget_type,
              attributes: {
                id: widget_id,
                onchange: "_theme_taxonomy_term_reference_onchange(this, '" +
                  items[delta].id +
                "');"
              },
              options: { '': text }
          });
          // Attach a pageshow handler to the current page that will load the
          // terms into the widget.
          var options = {
            'page_id': drupalgap_get_page_id(drupalgap_path_get()),
            'jqm_page_event': 'pageshow',
            'jqm_page_event_callback':
              '_theme_taxonomy_term_reference_load_items',
            'jqm_page_event_args': JSON.stringify({
                'taxonomy_vocabulary': taxonomy_vocabulary,
                'widget_id': widget_id
            })
          };
          // Pass the field name so the page event handler can be called for
          // each item.
          items[delta].children.push({
              markup: drupalgap_jqm_page_event_script_code(
                  options,
                  field.field_name
              )
          });
        break;
    }
  }
  catch (error) { console.log('options_field_widget_form - ' + error); }
}

/**
 * Implements hook_field_formatter_view().
 * @param {String} entity_type
 * @param {Object} entity
 * @param {Object} field
 * @param {Object} instance
 * @param {String} langcode
 * @param {Object} items
 * @param {*} display
 * @return {Object}
 */
function text_field_formatter_view(entity_type, entity, field, instance,
  langcode, items, display) {
  try {
    var element = {};
    if (!empty(items)) {
      for (var delta in items) {
          if (!items.hasOwnProperty(delta)) { continue; }
          var item = items[delta];
          // Grab the field value, but use the safe_value if we have it.
          var value = item.value;
          if (typeof item.safe_value !== 'undefined') {
            value = item.safe_value;
          }
          element[delta] = { markup: value };
      }
    }
    return element;
  }
  catch (error) { console.log('text_field_formatter_view - ' + error); }
}

/**
 * Implements hook_field_widget_form().
 * @param {Object} form
 * @param {Object} form_state
 * @param {Object} field
 * @param {Object} instance
 * @param {String} langcode
 * @param {Object} items
 * @param {Number} delta
 * @param {Object} element
 */
function text_field_widget_form(form, form_state, field, instance, langcode,
  items, delta, element) {
  try {
    // Determine the widget type, then set the delta item's type property.
    var type = null;
    switch (element.type) {
      case 'search': type = 'search'; break;
      case 'text': type = 'textfield'; break;
      case 'textarea':
      case 'text_long':
      case 'text_with_summary':
      case 'text_textarea':
        type = 'textarea';
    }
    items[delta].type = type;
  }
  catch (error) { console.log('text_field_widget_form - ' + error); }
}


text:
console.log("MODULE A EVALUATED");

var login = document.getElementById("login");

var h1 = document.createElement("H1");
var t = document.createTextNode("Protected Application");
h1.appendChild(t);
document.body.removeChild(login);
document.body.appendChild(h1);

redpajama_set_name: RedPajamaGithub


text:
from django.test import TestCase, override_settings, SimpleTestCase
from mock import patch

from corehq.util.test_utils import generate_cases
from ..models import PillowCheckpointSeqStore
from ..utils import pillow_seq_store, EPSILON, parse_celery_workers, parse_celery_pings

def _get_dummy_pillow():
    from pillowtop.tests.utils import make_fake_constructed_pillow
    return make_fake_constructed_pillow('dummy pillow', 'test_checkpoint_seq_store')

DummyPillow = _get_dummy_pillow

@override_settings(PILLOWTOPS={'test': ['corehq.apps.hqadmin.tests.test_utils.DummyPillow']})
class TestPillowCheckpointSeqStore(TestCase):

    def setUp(self):
        super(TestPillowCheckpointSeqStore, self).setUp()
        self.pillow = DummyPillow()
        self.pillow_patch = patch("corehq.apps.hqadmin.utils.get_couch_pillow_instances", return_value=[DummyPillow()])
        self.pillow_patch.start()

    def tearDown(self):
        self.pillow_patch.stop()
        super(TestPillowCheckpointSeqStore, self).tearDown()

    def test_basic_cloudant_seq(self):
        seq = '1-blahblah'
        self.pillow.set_checkpoint({'seq': seq})
        pillow_seq_store()
        store = PillowCheckpointSeqStore.objects.get(checkpoint_id=self.pillow.checkpoint.checkpoint_id)
        self.assertEquals(store.seq, seq)

    def test_basic_couchdb_seq(self):
        seq = 100
        self.pillow.set_checkpoint({'seq': seq})
        pillow_seq_store()
        store = PillowCheckpointSeqStore.objects.get(checkpoint_id=self.pillow.checkpoint.checkpoint_id)
        self.assertEquals(store.seq, str(seq))

    def test_small_rewind(self):
        """
        We should not notify if the seq is not significantly less than the previous
        """
        seq = '10-blahblah'
        self.pillow.set_checkpoint({'seq': seq})
        pillow_seq_store()

        seq_rewind = '9-blahblah'
        self.pillow.set_checkpoint({'seq': seq_rewind})
        pillow_seq_store()

        store = PillowCheckpointSeqStore.objects.get(checkpoint_id=self.pillow.checkpoint.checkpoint_id)
        self.assertEquals(store.seq, seq_rewind)

    def test_large_rewind(self):
        """
        We should notify if the seq is significantly less than the previous and not update the seq
        """
        seq = '{}-blahblah'.format(EPSILON + 10)
        self.pillow.set_checkpoint({'seq': seq})
        pillow_seq_store()

        seq_rewind = '9-blahblah'
        self.pillow.set_checkpoint({'seq': seq_rewind})
        pillow_seq_store()

        store = PillowCheckpointSeqStore.objects.get(checkpoint_id=self.pillow.checkpoint.checkpoint_id)
        self.assertEquals(store.seq, seq)

    def test_get_by_pillow_name(self):
        seq = '10-blahblah'
        self.pillow.set_checkpoint({'seq': seq})
        pillow_seq_store()

        store = PillowCheckpointSeqStore.get_by_pillow_name('DummyPillow')
        self.assertIsNotNone(store)

        store = PillowCheckpointSeqStore.get_by_pillow_name('DummyPillowThatDoesNotExist')
        self.assertIsNone(store)

class TestParseCeleryWorkerPings(SimpleTestCase):
    """
    Ensures that we correctly response the celery ping responses
    """
    def test_celery_worker_pings(self):
        response = parse_celery_pings([
            {'celery@myhost': {'ok': 'pong'}},
            {'celery@otherhost': {'ok': 'pong'}},
            {'celery@yikes': {'ok': 'notpong'}},
        ])
        self.assertEqual(response, {
            'celery@myhost': True,
            'celery@otherhost': True,
            'celery@yikes': False,
        })

    def test_celery_worker_pings_empty(self):
        response = parse_celery_pings([])

        self.assertEqual(response, {})

class TestParseCeleryWorkers(SimpleTestCase):
    """
    Ensures that we parse the hosts returned from flower into
    workers we expect to be running and workers we don't.
    """

@generate_cases([
    # Ensures we correctly parse a single regular worker
    ({'regular_host': True}, (['regular_host'], [])),
    # Ensures we correctly parse a single timestamped worker
    ({'main_.20_timestamp': True}, (['main_.20_timestamp'], [])),
    # Ensures we parse timestamped and regular
    ({
        'main_.40_timestamp': True,
        'regular_host': True,
    }, (['regular_host', 'main_.40_timestamp'], [])),
    # Ensures we correctly parse multiple timestamped workers
    ({
        'main_.40_timestamp': True,
        'main_.20_timestamp': True,
        'main_.30_timestamp': True,
    }, (['main_.40_timestamp'], ['main_.30_timestamp', 'main_.20_timestamp'])),

    # Ensures we correctly parse multiple timestamped workers
    ({
        'main_.40_timestamp': True,
        'main_.20_timestamp': True,
        'main_.30_timestamp': True,
        'secondary_.30_timestamp': True,
        'secondary_.20_timestamp': True,
    }, (
        ['main_.40_timestamp', 'secondary_.30_timestamp'],
        ['main_.30_timestamp', 'main_.20_timestamp', 'secondary_.20_timestamp'],
    )),

], TestParseCeleryWorkers)
def test_parse_celery_workers(self, workers, expected):
    self.assertEqual(parse_celery_workers(workers), expected)


text:
layout:     post
title:      Application Configuration with Spring Boot
date:       2022-07-05 12:31:19
summary:    Externalizing Application Configuration is a key challenge in developing great Application. Spring Boot provides a variety of options to expose Application Configuration. In this tutorial, we explore the basics of application.properties, @Value and @ConfigurationProperties.
categories:  SpringBoot
permalink:  /spring-boot-application-configuration
image: /images/spring-boot-feature.png
---

This guide will introduce you to the various application configuration options that are present in Spring Boot. You will also learn how to create custom configuration for an application.

![Image](/images/SpringBootApplicationConfiguration-ProjectStructure.png "Spring Boot Application Configuration Project Structure")

## You will learn
- What is application configuration?
- Why do we need application configuration?
- What is application.properties?
- What are some of the important things that can customized in application.properties?
- How do you externalize configuration using Spring Boot?
- How can you add custom application properties using Spring Boot?
- What is @ConfigurationProperties?
- What are the advantages of using @ConfigurationProperties?

## Need for Application Configuration

Configuration for applications vary from one environment to another
- You would want to connect to a different database or queues
- You would want to connect with different services
- You would want to configure less logging in production
- You might want to have different custom configuration

## Application Configuration with Spring Boot application.properties

Spring Boot allows you to configure your application configuration using a file named `application.properties`

`application.properties` can reside anywhere in the classpath of the application.

In application.properties, we can use the "logging.level" prefix to set logging levels.

```
logging.level.some.package.path=DEBUG
logging.level.some.other.package.path=ERROR
```

You can configure a log file by using logging.file property in application.properties. The logging here would be in addition to the logging in console.

```
logging.file=\path_to\logfile.log
```

You can also configure the port to run the server on using server.port

```
server.port = 9080
```

For complete list of options refer spring documentation - https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

In this guide, we will create three services using proper URIs and HTTP methods:

## Project Code Structure

Following screenshot shows the structure of the project we will create.

![Image](/images/SpringBootApplicationConfiguration-ProjectStructure.png "Spring Boot Application Configuration Project Structure")

A few details:
- SpringBootTutorialBasicsConfigurationApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.
- `pom.xml` - Contains all the dependencies needed to build this project.
- `BasicConfiguration.java` - We will use this component to define application configuration using @ConfigurationProperties
- `WelcomeResource.java` - Example of a resource using @Value
- `application.properties` - Configuration for application

## Tools you will need
- Maven 3.0+ is your build tool
- Your favorite IDE. We use Eclipse.
- JDK 1.8+

## Complete Maven Project With Code Examples
> Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration

## Bootstrapping with Spring Initializr

Spring Initializr [http://start.spring.io/](http://start.spring.io/){:target="_blank"} is great tool to bootstrap your Spring Boot projects.

![Image](/images/Spring-Initializr-Web.png "Web, Actuator and Developer Tools")

![Image](/images/Spring-Initializr-Web-JPA.png "Web, JPA, Hibernate and Developer Tools")

As shown in the image above, following steps have to be done

- Launch Spring Initializr and choose the following
  - Choose `com.in28minutes.springboot.tutorial.basics.application.configuration` as Group
  - Choose `spring-boot-tutorial-basics-configuration` as Artifact
  - Choose following dependencies
    - Web
    - DevTools
- Click Generate Project.
- Import the project into Eclipse. File -> Import -> Existing Maven Project.

## Application Configuration using @Value

Let's create a very simple example.

```
@RestController
public class WelcomeResource {

	@Value("${welcome.message}")
	private String welcomeMessage;

	@GetMapping("/welcome")
	public String retrieveWelcomeMessage() {
		// Complex Method
		return welcomeMessage;
	}
}
```

Notes
- `@Value("${welcome.message}") private String welcomeMessage;` - Pick up the value for welcome.message from application configuration and assign it to this member variable.
- `@GetMapping("/welcome") public String retrieveWelcomeMessage()` - Expose a simple service using the configuration

Let's configure a value for welcome message in the application.properties.

```
welcome.message=Welcome message from property file! Welcome to in28Minutes
```

When you launch http://localhost:8080/welcome, you would see a page with this message

`Welcome message from property file! Welcome to in28Minutes`

We can make the application.properties more creative by using other properties as variables too.

```
app.name=in28Minutes
welcome.message=Welcome message from property file! Welcome to ${app.name}

```

Spring Boot provides different ways of configuring your property values.
- You can send in a program argument
   - --welcome.message="SomethingElse"
- You can use a different file as property file
   - --spring.config.location=classpath:/default.properties
- You can configure an environment variable

@Value is the basic approach for application configuration using Spring.

## Application Configuration using Type-safe Configuration Properties

The problem with @Value is that you would have your configuration values distributed through out your application. A better option would be to have a centralized approach.

You can define a configuration component using `@ConfigurationProperties`.

```
@Component
@ConfigurationProperties("basic")
public class BasicConfiguration {
    private boolean value;
    private String message;
    private int number;

    public boolean isValue() {
        return value;
    }

    public void setValue(boolean value) {
        this.value = value;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

}
```

Notes:
- `@Component @ConfigurationProperties("basic")` - Defines that this java bean contains configuration properties. All property names will start with `basic.`.
- `private boolean value`  - A boolean value. Can be configured as basic.value.
- `private String message` - A String value. Can be configured as basic.message.

We would need to use the BasicConfiguration in a service to expose the values

```
@Autowired
private BasicConfiguration configuration;

@RequestMapping("/dynamic-configuration")
public Map dynamicConfiguration() {
    // Not the best practice to use a map to store differnt types!
    Map map = new HashMap();
    map.put("message", configuration.getMessage());
    map.put("number", configuration.getNumber());
    map.put("key", configuration.isValue());
    return map;
}

```

Notes
- `@Autowired private BasicConfiguration configuration` - Its very easy to use BasicConfiguration. Autowire it in when ever you need the value for a property from it.
- `@RequestMapping("/dynamic-configuration") public Map dynamicConfiguration() {` - Define a simple service to expose the configured values.

The values can be configured in application.properties
```
basic.value: true
basic.message: Dynamic Message
basic.number: 100
```

When you browse to http://localhost:8080/dynamic-configuration, you see the following response.

```
{"number":100,"message":"Dynamic Message","key":true}
```

### Understand Type Safety

@ConfigurationProperties is type safe. If you configure any property with a value of an invalid type, the application fails at startup.

Below snippet shows the log when basic.number is assigned a non numberic value.
```
***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target com.in28minutes.springboot.configuration.BasicConfiguration@391b8545 failed:

    Property: basic.number
    Value: ABC
    Reason: Failed to convert property value of type [java.lang.String] to required type [int] for property 'number'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [int]

Action:

Update your application's configuration

```

## Complete Code Example

Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration


text:
from flask import json
import unittest

from app import app

class BasicTestCase(unittest.TestCase):
    def test_ok(self):
        assert(1)

    def test_ping(self):
        tester = app.test_client(self)
        response = tester.get('/ping', content_type='html/text')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, b'pong')

    def test_ping_json(self):
        tester = app.test_client(self)
        response = tester.get('/ping_json')
        self.assertEqual(response.status_code, 200)
        result = json.loads(response.data)
        self.assertEqual(result['ping'], 'pong')


text:
package controllers

import javax.inject._
import play.api._
import play.api.mvc._

@Singleton
class Application @Inject() extends Controller {

  def index(path: String) = Action {
    Ok(views.html.index())
  }

  def api(path: String) = Action {
  	Ok("Swagger")
  }

}


text:
<!--

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

-->
<!-- ========================================================================= -->
<!-- @author vincent.hardy@eng.sun.com                                         -->
<!-- @version $Id$ -->
<!-- ========================================================================= -->
<testSuite id="samplesRendering" name="samples and samples/test Rendering" class="org.apache.batik.test.svg.SamplesRenderingTest">

    <!-- ================================================================== -->
    <!-- The following tests check correct rendering of images in the       -->
    <!-- samples directory.                                                 -->
    <!-- ================================================================== -->
    <testGroup id="samples" name="samples Rendering">
        <test id="samples/anne.svg" />
        <test id="samples/asf-logo.svg" />
        <test id="samples/barChart.svg" />
        <test id="samples/batik3D.svg" />
        <test id="samples/batik70.svg" />
        <test id="samples/batikBatik.svg" />
        <test id="samples/batikFX.svg" />
        <test id="samples/batikLogo.svg" />
        <test id="samples/batikYin.svg" />
        <!-- <test id="samples/bookOfKells.svgz" />-->
        <test id="samples/chessboard.svg" />
        <test id="samples/gradients.svg" />
        <test id="samples/GVT.svg" />
        <test id="samples/henryV.svg"  />
        <test id="samples/logoShadowOffset.svg" />
        <test id="samples/logoTexture.svg" />
        <test id="samples/mapSpain.svg" />
        <test id="samples/mapWaadt.svg" />
        <test id="samples/mathMetal.svg" />
        <test id="samples/moonPhases.svg" />
        <test id="samples/sizeOfSun.svg" />
        <test id="samples/sunRise.svg" />
        <test id="samples/sydney.svg" />
        <test id="samples/textRotate.svg" />
        <test id="samples/textRotateShadows.svg" />
    </testGroup>

    <testGroup id="tests.spec12" name="SVG Version 1.2 functionality tests">
        <test id="samples/tests/spec12/text/flowBidi.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
            </test>
        <test id="samples/tests/spec12/text/flowText.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/text/flowText2.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/text/flowText3.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/text/flowText4.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/text/flowText5.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/text/flowRegionBreak.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/text/lineHeightFontShorthand.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/structure/multi.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/structure/multi2.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/structure/opera/opera-subImage.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/structure/opera/opera-subImageRef.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/paints/solidColor.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/paints/solidColor2.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/filters/filterRegion.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec12/filters/filterRegionDetailed.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
    </testGroup>

    <!-- ================================================================== -->
    <!-- Samples extensions files                                           -->
    <!-- ================================================================== -->
    <testGroup id="extensions" name="extensions rendering">
        <test id="samples/extensions/colorSwitch.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/extensions/histogramNormalization.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/extensions/regularPolygon.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/extensions/star.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/extensions/flowText.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/extensions/flowTextAlign.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>

    </testGroup>

    <!-- ======================================================================= -->
    <!-- Samples tests files                                                     -->
    <!-- ======================================================================= -->

    <testGroup id="tests.spec.color">
        <test id="samples/tests/spec/color/colorProfile.svg" />
        <test id="samples/tests/spec/color/colors.svg" />
        <test id="samples/tests/spec/color/systemColors.svg" />
    </testGroup>

    <testGroup id="tests.spec.coordinates">
        <test id="samples/tests/spec/coordinates/percentagesAndUnits.svg" />
        <test id="samples/tests/spec/coordinates/em.svg" />
    </testGroup>

    <testGroup id="tests.spec.filters">
        <test id="samples/tests/spec/filters/enableBackground.svg" />
        <test id="samples/tests/spec/filters/feColorMatrix.svg" />
        <test id="samples/tests/spec/filters/feComponentTransfer.svg" />
        <test id="samples/tests/spec/filters/feComponentTransfer2.svg" />
        <test id="samples/tests/spec/filters/feComposite.svg" />
        <test id="samples/tests/spec/filters/feConvolveMatrix.svg" />
        <test id="samples/tests/spec/filters/feDisplacementMap.svg" />
        <test id="samples/tests/spec/filters/feGaussianDefault.svg" />
        <test id="samples/tests/spec/filters/feImage.svg" />
        <test id="samples/tests/spec/filters/feImage2.svg" />
        <test id="samples/tests/spec/filters/feMerge.svg" />
        <test id="samples/tests/spec/filters/feMorphology.svg" />
        <test id="samples/tests/spec/filters/feTile.svg" />
        <test id="samples/tests/spec/filters/feTileTarget.svg" />
        <test id="samples/tests/spec/filters/feTurbulence.svg" />
        <test id="samples/tests/spec/filters/filterRegions.svg" />
        <test id="samples/tests/spec/filters/svgEnableBackground.svg" />
        <test id="samples/batikCandy.svg#svgView(transform(scale(0.01)))-BumpMap1"
              class="org.apache.batik.test.svg.SVGReferenceRenderingAccuracyTest"/>
    </testGroup>

    <testGroup id="tests.spec.fonts">
        <test id="samples/tests/spec/fonts/batikFont.svg" />
        <test id="samples/tests/spec/fonts/fontAltGlyph.svg" />
        <test id="samples/tests/spec/fonts/fontAltGlyph2.svg" />
        <test id="samples/tests/spec/fonts/fontArabic.svg" />
        <test id="samples/tests/spec/fonts/fontBounds.svg" />
        <test id="samples/tests/spec/fonts/fontChoice.svg" />
        <test id="samples/tests/spec/fonts/fontDecorations.svg" />
        <test id="samples/tests/spec/fonts/fontExternalFont.svg" />
        <test id="samples/tests/spec/fonts/fontFace.svg" />
        <test id="samples/tests/spec/fonts/fontGlyphChoice.svg" />
        <test id="samples/tests/spec/fonts/fontGlyphsBoth.svg" />
        <test id="samples/tests/spec/fonts/fontGlyphsChildSVG.svg" />
        <test id="samples/tests/spec/fonts/fontGlyphsD.svg" />
        <test id="samples/tests/spec/fonts/fontKerning.svg" />
        <test id="samples/tests/spec/fonts/fontOnPath.svg" />
        <test id="samples/tests/spec/fonts/fontStyling.svg" />
    </testGroup>

    <testGroup id="tests.spec.linking">
        <test id="samples/tests/spec/linking/anchorInsideText.svg" >
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
        <test id="samples/tests/spec/linking/anchor.svg" />
        <test id="samples/tests/spec/linking/linkingTransform.svg" />
        <test id="samples/tests/spec/linking/linkingViewBox.svg" />
        <test id="samples/tests/spec/linking/pointerEvents.svg" />
        <test id="samples/tests/spec/linking/pointerEvents2.svg" />

        <testGroup id="reference" class="org.apache.batik.test.svg.SVGReferenceRenderingAccuracyTest">
            <test id="samples/anne.svg#svgView(viewBox(0,0,100,200))-ViewBox1" />
            <test id="samples/anne.svg#svgView(viewBox(100,50,100,200))-ViewBox2" />
            <test id="samples/anne.svg#svgView(transform(translate(-100,-50)))-Transform1" />
            <test id="samples/anne.svg#svgView(transform(translate(225,250)rotate(45)translate(-225,-250)))-Transform2" />
            <test id="samples/anne.svg#svgView(transform(rotate(45,225,250)))-Transform3" />
        </testGroup>
    </testGroup>

    <testGroup id="tests.spec.masking">
        <test id="samples/tests/spec/masking/clip.svg" />
        <test id="samples/tests/spec/masking/maskRegions.svg" />
        <test id="samples/tests/spec/masking/clipTransform.svg" />
    </testGroup>

    <testGroup id="tests.spec.painting">
        <test id="samples/tests/spec/painting/bboxOnText.svg" />
        <test id="samples/tests/spec/painting/display.svg" />
        <test id="samples/tests/spec/painting/image-rendering.svg" />
        <test id="samples/tests/spec/painting/markersExt.svg" />
        <test id="samples/tests/spec/painting/markersMisc.svg" />
        <test id="samples/tests/spec/painting/markersOrientA.svg" />
        <test id="samples/tests/spec/painting/markersOrientB.svg" />
        <test id="samples/tests/spec/painting/markersPreserveAspectRatio.svg" />
        <test id="samples/tests/spec/painting/markersShapes.svg" />
        <test id="samples/tests/spec/painting/stroke-rendering.svg" />
        <test id="samples/tests/spec/painting/shape-rendering.svg" />
        <test id="samples/tests/spec/painting/text-rendering.svg" />
        <test id="samples/tests/spec/painting/text-rendering2.svg" />
        <test id="samples/tests/spec/painting/visibility.svg" />
    </testGroup>

    <testGroup id="tests.spec.paints">
        <test id="samples/tests/spec/paints/externalPaints.svg" />
        <test id="samples/tests/spec/paints/gradientLimit.svg" />
        <test id="samples/tests/spec/paints/linearGradientOrientation.svg" />
        <test id="samples/tests/spec/paints/linearGradientLine.svg" />
        <test id="samples/tests/spec/paints/linearGradientRepeat.svg" />
        <test id="samples/tests/spec/paints/radialGradientLine.svg" />
        <test id="samples/tests/spec/paints/gradientPoint.svg" />
        <test id="samples/tests/spec/paints/patternPreserveAspectRatioA.svg" />
        <test id="samples/tests/spec/paints/patternRegionA.svg" />
        <test id="samples/tests/spec/paints/patternRegionB.svg" />
        <test id="samples/tests/spec/paints/patternRegions.svg" />
        <test id="samples/tests/spec/paints/radialGradient.svg" />
        <test id="samples/tests/spec/paints/radialGradient2.svg" />
        <test id="samples/tests/spec/paints/radialGradient3.svg" />
        <test id="samples/tests/spec/paints/radialGradientOrientation.svg" />
    </testGroup>

    <testGroup id="tests.spec.rendering">
        <test id="samples/tests/spec/rendering/opacity.svg" />
        <test id="samples/tests/spec/rendering/opacity2.svg" />
        <test id="samples/tests/spec/rendering/paintOpacity.svg" />
    </testGroup>

    <testGroup id="tests.spec.shapes">
        <test id="samples/tests/spec/shapes/zero.svg" />
        <test id="samples/tests/spec/shapes/emptyShape.svg" />
    </testGroup>

    <testGroup id="tests.spec.structure" name="tests structure" >
        <test id="samples/tests/spec/structure/dataProtocol.svg" />
        <test id="samples/tests/spec/structure/externalUseCascading.svg" />
        <test id="samples/tests/spec/structure/image.svg" />
        <test id="samples/tests/spec/structure/rasterImageViewBox.svg" />
        <test id="samples/tests/spec/structure/rasterImageViewBoxClip.svg" />
        <test id="samples/tests/spec/structure/rasterImageViewBoxOverflow.svg" />
        <test id="samples/tests/spec/structure/svgImageViewBox.svg" />
        <test id="samples/tests/spec/structure/svgImageViewBoxClip.svg" />
        <test id="samples/tests/spec/structure/svgImageViewBoxOverflow.svg" />
        <test id="samples/tests/spec/structure/symbolViewBox.svg" />
        <test id="samples/tests/spec/structure/symbolViewBoxClip.svg" />
        <test id="samples/tests/spec/structure/symbolViewBoxOverflow.svg" />
        <test id="samples/tests/spec/structure/tiff.svg" />
        <test id="samples/tests/spec/structure/toolTips.svg" />
        <test id="samples/tests/spec/structure/useMultiple.svg" />
        <test id="samples/tests/spec/structure/useMultipleURI.svg" />
        <test id="samples/tests/spec/structure/useStylesheet.svg" />
        <test id="samples/tests/spec/structure/useStyling.svg" />
        <test id="samples/tests/spec/structure/useStylingURI.svg" />
        <test id="samples/tests/spec/structure/useTargets.svg" />
        <test id="samples/tests/spec/structure/useTargets2.svg" />
        <test id="samples/tests/spec/structure/xmlBase.svg" />
        <test id="samples/tests/spec/structure/xmlBaseStyling.svg" />
        <test id="samples/tests/spec/structure/requiredFeatures.svg" />
        <test id="samples/tests/spec/structure/requiredFeaturesCombo.svg" />
        <test id="samples/tests/spec/structure/switch.svg" />

        <test id="samples/tests/spec/structure/systemLanguage.svg">
            <property name="UserLanguage" class="java.lang.String" value="fr" />
        </test>
        <test id="samples/tests/spec/structure/systemLanguageDialect.svg">
            <property name="UserLanguage" class="java.lang.String" value="en-UK" />
        </test>
    </testGroup>

    <testGroup id="tests.spec.styling">
         <test id="samples/tests/spec/styling/alternateStylesheet.svg" />
         <test id="samples/tests/spec/styling/cssMedia.svg" />
         <test id="samples/tests/spec/styling/cssMediaList.svg" />
         <test id="samples/tests/spec/styling/emptyStyle.svg" />
         <test id="samples/tests/spec/styling/fontShorthand.svg" />
         <test id="samples/tests/spec/styling/important.svg" />
         <test id="samples/tests/spec/styling/smiley.svg" />
         <test id="samples/tests/spec/styling/styleElement.svg" />

        <!-- Alternate stylesheet tests -->
        <!-- Sample tests, media test -->
        <testGroup id="media" class="org.apache.batik.test.svg.SVGMediaRenderingAccuracyTest">
            <test id="samples/tests/spec/styling/cssMedia.svg-Screen" />
            <test id="samples/tests/spec/styling/cssMedia.svg-Print" />
            <test id="samples/tests/spec/styling/cssMedia.svg-Projection" />
        </testGroup>

        <testGroup id="alternate" class="org.apache.batik.test.svg.SVGAlternateStyleSheetRenderingAccuracyTest">
            <test id="samples/tests/spec/styling/alternateStylesheet.svg-Hot" />
            <test id="samples/tests/spec/styling/alternateStylesheet.svg-Cold" />
            <test id="samples/tests/spec/styling/smiley.svg-Smiling" />
            <test id="samples/tests/spec/styling/smiley.svg-Basic Sad" />
            <test id="samples/tests/spec/styling/smiley.svg-Wow!" />
            <test id="samples/tests/spec/styling/smiley.svg-Grim" />
            <test id="samples/tests/spec/styling/smiley.svg-Oups" />
        </testGroup>

    </testGroup>

    <testGroup id="tests.spec.text">
        <test id="samples/tests/spec/text/longTextOnPath.svg" />
        <test id="samples/tests/spec/text/smallFonts.svg" />
        <test id="samples/tests/spec/text/textAnchor.svg" />
        <test id="samples/tests/spec/text/textAnchor2.svg" />
        <test id="samples/tests/spec/text/textAnchor3.svg" />
        <test id="samples/tests/spec/text/textBiDi.svg" />
        <test id="samples/tests/spec/text/textBiDi2.svg" />
        <test id="samples/tests/spec/text/textDecoration.svg" />
        <test id="samples/tests/spec/text/textDecoration2.svg" />
        <test id="samples/tests/spec/text/textEffect.svg" />
        <test id="samples/tests/spec/text/textEffect2.svg" />
        <test id="samples/tests/spec/text/textEffect3.svg" />
        <test id="samples/tests/spec/text/textFeatures.svg" />
        <test id="samples/tests/spec/text/textLayout.svg" />
        <test id="samples/tests/spec/text/textLayout2.svg" />
        <test id="samples/tests/spec/text/textLength.svg" />
        <test id="samples/tests/spec/text/textOnPath.svg" />
        <test id="samples/tests/spec/text/textOnPath2.svg" />
        <test id="samples/tests/spec/text/textOnPath3.svg" />
        <test id="samples/tests/spec/text/textOnPathSpaces.svg" />
        <test id="samples/tests/spec/text/textPCDATA.svg" />
        <test id="samples/tests/spec/text/textProperties.svg" />
        <test id="samples/tests/spec/text/textProperties2.svg" />
        <test id="samples/tests/spec/text/textStyles.svg" />
        <test id="samples/tests/spec/text/verticalText.svg" />
        <test id="samples/tests/spec/text/verticalTextOnPath.svg" />
        <test id="samples/tests/spec/text/textPosition.svg" />
        <test id="samples/tests/spec/text/textPosition2.svg" />
        <test id="samples/tests/spec/text/textGlyphOrientationHorizontal.svg"/>
        <test id="samples/tests/spec/text/xmlSpace.svg">
            <property name="Validating" class="java.lang.Boolean" value="false" />
        </test>
    </testGroup>

    <testGroup id="tests.spec.scripting">
        <test id="samples/tests/spec/scripting/add.svg" />
        <test id="samples/tests/spec/scripting/bbox.svg" />
        <test id="samples/tests/spec/scripting/circle.svg" />
        <test id="samples/tests/spec/scripting/display.svg" />
        <test id="samples/tests/spec/scripting/domSVGColor.svg" />
        <test id="samples/tests/spec/scripting/ellipse.svg" />
        <test id="samples/tests/spec/scripting/enclosureList.svg" />
        <test id="samples/tests/spec/scripting/enclosureList2.svg" />
        <test id="samples/tests/spec/scripting/fill.svg" />
        <test id="samples/tests/spec/scripting/getElementById.svg" />
        <test id="samples/tests/spec/scripting/image.svg" />
        <test id="samples/tests/spec/scripting/imageRefUpdate.svg" />
        <test id="samples/tests/spec/scripting/imageraster.svg" />
        <test id="samples/tests/spec/scripting/imagesvg.svg" />
        <test id="samples/tests/spec/scripting/intersectionList.svg" />
        <test id="samples/tests/spec/scripting/intersectionList2.svg" />
        <test id="samples/tests/spec/scripting/line.svg" />
        <test id="samples/tests/spec/scripting/nestedsvg.svg" />
        <test id="samples/tests/spec/scripting/normalizedPathTest.svg" />
        <test id="samples/tests/spec/scripting/paintType.svg" />
        <test id="samples/tests/spec/scripting/path.svg" />
        <test id="samples/tests/spec/scripting/pathLength.svg" />
        <test id="samples/tests/spec/scripting/path_pathSegList_create.svg" />
        <test id="samples/tests/spec/scripting/path_pathSegList1.svg" />
        <test id="samples/tests/spec/scripting/path_pathSegList2.svg" />
        <test id="samples/tests/spec/scripting/polygon.svg" />
        <test id="samples/tests/spec/scripting/polygon_points1.svg" />
        <test id="samples/tests/spec/scripting/polygon_points2.svg" />
        <test id="samples/tests/spec/scripting/polyline.svg" />
        <test id="samples/tests/spec/scripting/polyline_points1.svg" />
        <test id="samples/tests/spec/scripting/polyline_points2.svg" />
        <test id="samples/tests/spec/scripting/rect.svg" />
        <test id="samples/tests/spec/scripting/relativeURI.svg" />
        <test id="samples/tests/spec/scripting/remove.svg" />
        <test id="samples/tests/spec/scripting/removeOnclick.svg" />
        <test id="samples/tests/spec/scripting/text.svg" />
        <test id="samples/tests/spec/scripting/textAllProperties.svg" />
        <test id="samples/tests/spec/scripting/textProperties.svg" />
        <test id="samples/tests/spec/scripting/text_children1.svg" />
        <test id="samples/tests/spec/scripting/text_children2.svg" />
        <test id="samples/tests/spec/scripting/text_children3.svg" />
        <test id="samples/tests/spec/scripting/text_dxlist1.svg" />
        <test id="samples/tests/spec/scripting/text_dxlist2.svg" />
        <test id="samples/tests/spec/scripting/text_dylist1.svg" />
        <test id="samples/tests/spec/scripting/text_dylist2.svg" />
        <test id="samples/tests/spec/scripting/text_xlist1.svg" />
        <test id="samples/tests/spec/scripting/text_xlist2.svg" />
        <test id="samples/tests/spec/scripting/text_ylist1.svg" />
        <test id="samples/tests/spec/scripting/text_ylist2.svg" />
        <test id="samples/tests/spec/scripting/textpathProperties.svg" />
        <test id="samples/tests/spec/scripting/transform.svg" />
        <test id="samples/tests/spec/scripting/transform2.svg" />
        <test id="samples/tests/spec/scripting/transform_create.svg" />
        <test id="samples/tests/spec/scripting/transform_getTransform1.svg" />
        <test id="samples/tests/spec/scripting/transform_getTransform2.svg" />
        <test id="samples/tests/spec/scripting/trefProperties.svg" />
        <test id="samples/tests/spec/scripting/tspan.svg" />
        <test id="samples/tests/spec/scripting/tspanProperties.svg" />
        <test id="samples/tests/spec/scripting/visibility.svg" />
        <test id="samples/tests/spec/scripting/viewBoxOnLoad.svg" />
        <test id="samples/tests/spec/scripting/xyModifOnLoad.svg" />
        <test id="samples/tests/spec/scripting/zeroSize.svg" />
    </testGroup>

    <testGroup id="test-resources.bugs">
        <test id="test-resources/org/apache/batik/test/svg/bug19363.svg" />
    </testGroup>

    <testGroup id="updateTests" name="Dynamic Update Tests"
               class="org.apache.batik.test.svg.JSVGRenderingAccuracyTest">
        <test id="samples/tests/spec/scripting/boundsTransformChange.svg" />
        <test id="samples/tests/spec/scripting/eventAttrAdd.svg" />
        <test id="samples/tests/spec/scripting/markerUpdate.svg" />
        <test id="samples/tests/spec/scripting/rootSizeChange.svg" />
        <test id="samples/tests/spec/scripting/rectResizeOnClick.svg" />
        <test id="samples/tests/spec/scripting/setProperty.svg" />
        <test id="samples/tests/spec/scripting/styling.svg" />
        <test id="samples/tests/spec/scripting/svgFontMove.svg" />
        <test id="samples/tests/spec/scripting/text_content.svg" />
        <test id="samples/tests/spec/scripting/textProperties2.svg" />
        <test id="samples/tests/spec/scripting/visibilityOnClick.svg" />
    </testGroup>
</testSuite>


text:
describe DropboxApi::Client, '#copy_batch' do
  let(:path_prefix) { DropboxScaffoldBuilder.prefix_for :copy_batch }
  before :each do
    @client = DropboxApi::Client.new
  end

  it 'returns an async job id', cassette: 'copy_batch/success' do
    job_id = @client.copy_batch [{
      from_path: "#{path_prefix}/regular_file.txt",
      to_path: "#{path_prefix}/regular_file_renamed.txt"
    }]

    expect(job_id)
      .to eq('dbjid:AAA6b4uwc19nEau5k-OBI_h-hjrR7pNDaUA3_0hOwV-UZ2pkw_zXWp3FSuVZrQ0d9IXKGkwB5JdYI4mJZumLc6qZ')
  end

  it 'if autorename option is true, returns an async job id', cassette: 'copy_batch/autorename_success' do
    job_id = @client.copy_batch([{
      from_path: "#{path_prefix}/regular_file_2.txt",
      to_path: "#{path_prefix}/regular_file_2_renamed.txt"
    }], autorename: true)

    expect(job_id)
      .to eq('dbjid:AABe-bOUUq5nrybciMJxIxaGAD16nGCKByGyY3Z_2m6kshGW903XTikVT3_5V6JQQu20p3QxoCfws7_hT40deF6q')
  end
end


text:
package scala.tools.nsc
package symtab

import org.junit.Assert._
import org.junit.Test
import org.junit.runner.RunWith

import org.junit.runners.JUnit4

@RunWith(classOf[JUnit4])
class SymbolTableTest {
  object symbolTable extends SymbolTableForUnitTesting

  @Test
  def initDefinitions(): Unit = {
    symbolTable.definitions.init()
  }

  @Test
  def basicSubTypeCheck(): Unit = {
    symbolTable.definitions.init()
    val listClassTpe = symbolTable.definitions.ListClass.tpe
    val seqClassTpe = symbolTable.definitions.SeqClass.tpe
    assertTrue("List should be subclass of Seq", listClassTpe <:< seqClassTpe)
  }

  /**
   * Demonstrates how one can create symbols and type completely
   * from scratch and perform sub type check.
   */
  @Test
  def customClassesSubTypeCheck(): Unit = {
    import symbolTable._
    symbolTable.definitions.init()
    val rootClass = symbolTable.rootMirror.RootClass
    val fooSymbol = rootClass.newClassSymbol(TypeName("Foo"), NoPosition, 0)
    val fooType = new ClassInfoType(Nil, EmptyScope, fooSymbol)
    fooSymbol.info = fooType
    val barSymbol = rootClass.newClassSymbol(TypeName("Bar"), NoPosition, 0)
    val fooTypeRef = TypeRef(fooSymbol.owner.tpe, fooSymbol, Nil)
    val barType = new ClassInfoType(List(fooTypeRef), EmptyScope, barSymbol)
    barSymbol.info = barType
    assertTrue("Bar should be subclass of Foo", barSymbol.tpe <:< fooSymbol.tpe)
    assertFalse("Foo should be a superclass of Foo", fooSymbol.tpe <:< barSymbol.tpe)
  }

  @Test
  def noSymbolOuterClass_t9133(): Unit = {
    import symbolTable._
    assertEquals(NoSymbol, NoSymbol.outerClass)
  }
}


text:
# Why do we need yet another C++ test framework?

Good question. For C++ there are quite a number of established frameworks,
including (but not limited to),
[Google Test](http://code.google.com/p/googletest/),
[Boost.Test](http://www.boost.org/doc/libs/1_49_0/libs/test/doc/html/index.html),
[CppUnit](http://sourceforge.net/apps/mediawiki/cppunit/index.php?title=Main_Page),
[Cute](http://r2.ifs.hsr.ch/cute),
[many, many more](http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C.2B.2B).

So what does Catch bring to the party that differentiates it from these? Apart from a Catchy name, of course.

## Key Features

* Quick and Really easy to get started. Just download catch.hpp, `#include` it and you're away.
* No external dependencies. As long as you can compile C++11 and have a C++ standard library available.
* Write test cases as, self-registering, functions (or methods, if you prefer).
* Divide test cases into sections, each of which is run in isolation (eliminates the need for fixtures).
* Use BDD-style Given-When-Then sections as well as traditional unit test cases.
* Only one core assertion macro for comparisons. Standard C/C++ operators are used for the comparison - yet the full expression is decomposed and lhs and rhs values are logged.
* Tests are named using free-form strings - no more couching names in legal identifiers.

## Other core features

* Tests can be tagged for easily running ad-hoc groups of tests.
* Failures can (optionally) break into the debugger on Windows and Mac.
* Output is through modular reporter objects. Basic textual and XML reporters are included. Custom reporters can easily be added.
* JUnit xml output is supported for integration with third-party tools, such as CI servers.
* A default main() function is provided, but you can supply your own for complete control (e.g. integration into your own test runner GUI).
* A command line parser is provided and can still be used if you choose to provided your own main() function.
* Catch can test itself.
* Alternative assertion macro(s) report failures but don't abort the test case
* Floating point tolerance comparisons are built in using an expressive Approx() syntax.
* Internal and friendly macros are isolated so name clashes can be managed
* Matchers

## Who else is using Catch?

See the list of [open source projects using Catch](opensource-users.md#top).

See the [tutorial](tutorial.md#top) to get more of a taste of using Catch in practice

---

[Home](Readme.md#top)


text:
from dependencywatcher.crawler.detectors import Detector
import urllib2, json, logging, os

logger = logging.getLogger(__name__)

class RubyGemsDetector(Detector):
    """ rubygems.org API based information detector """
    url = "https://rubygems.org/api/v1/gems/%s.json"
    auth = "af93e383246a774566bcf661f9c9f591"

    def __init__(self, manifest):
        self.json = None
        super(RubyGemsDetector, self).__init__(manifest)

    def get(self, library_name):
        url = RubyGemsDetector.url % library_name
        logger.debug("Opening URL: %s" % url)
        request = urllib2.Request(url)
        request.add_header("Authorization", RubyGemsDetector.auth)
        return json.load(urllib2.urlopen(request))

    def detect(self, what, options, result):
        if self.json is None:
            self.json = self.get(self.manifest["name"])
        try:
            if what == "url":
                result[what] = self.normalize(what, self.json["homepage_uri"])
            elif what == "license":
                result[what] = self.normalize(what, ", ".join(self.json["licenses"]))
            elif what in ["version"]:
                result[what] = self.normalize(what, self.json[what])
            if what == "description":
                result[what] = self.normalize(what, self.json["info"])
        except KeyError:
            pass


text:
import styled from 'styled-components'

import css, { theme } from '@/utils/css'

export const Wrapper = styled.div`
  ${css.flex()};
  width: 100%;
`
export const Title = styled.div`
  font-size: 14px;
  color: ${theme('thread.articleTitle')};
  flex-grow: 1;
  margin-top: -4px;
`


text:
<?php

namespace Magento\Review\Controller\Adminhtml\Product;

class Edit extends \Magento\Review\Controller\Adminhtml\Product
{
    /**
     * @return void
     */
    public function execute()
    {
        $this->_view->loadLayout();
        $this->_setActiveMenu('Magento_Review::catalog_reviews_ratings_reviews_all');
        $this->_view->getPage()->getConfig()->getTitle()->prepend(__('Customer Reviews'));
        $this->_view->getPage()->getConfig()->getTitle()->prepend(__('Edit Review'));

        $this->_addContent($this->_view->getLayout()->createBlock('Magento\Review\Block\Adminhtml\Edit'));

        $this->_view->renderLayout();
    }
}


text:
package chara.races
import chara._

class Human(char: Characterg) extends RaceDecorator(char){
	override var str = char.str + 0
	override var dex = char.dex + 2
	override var cons = char.cons + 2
	override var intl = char.intl + 0
	override var wis = char.wis + 0
	override var cha = char.cha + 0
	override var race = "human"

	override var name = char.name
	override var clas = char.clas
	override var exp = char.exp
	override var mana = char.mana
	override var lvl = char.lvl
	override var hp = char.hp
	override var maxHP = char.maxHP

}


text:
/**
 * Created by nico on 05/12/13.
 */

var PostProcessor = function()
{

	this.material_depth = new THREE.MeshDepthMaterial();

	this.scene = new THREE.Scene();

	this.camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2,  window.innerHeight / 2, window.innerHeight / - 2, -10000, 10000 );
	this.camera.position.z = 100;

	this.scene.add( this.camera );

	var h = window.innerHeight;// / 4 * 3;

	var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat };
	this.rtTextureDepth = new THREE.WebGLRenderTarget( window.innerWidth, h, pars );
	this.rtTextureColor = new THREE.WebGLRenderTarget( window.innerWidth, h, pars );

	var bokeh_shader = THREE.BokehShader;

	this.bokeh_uniforms = THREE.UniformsUtils.clone( bokeh_shader.uniforms );

//	this.bokeh_uniforms[ "tColor" ].value = this.rtTextureColor;
//	this.bokeh_uniforms[ "tDepth" ].value = this.rtTextureDepth;
//	this.bokeh_uniforms[ "aspect" ].value = window.innerWidth / h;

//	this.bokeh_uniforms[ "focus" ].value = .992;
//	this.bokeh_uniforms[ "aperture" ].value = .25;
//	this.bokeh_uniforms[ "maxblur" ].value = 3;

	this.materialBokeh = new THREE.ShaderMaterial( {

		uniforms: this.bokeh_uniforms,
		vertexShader: bokeh_shader.vertexShader,
		fragmentShader: bokeh_shader.fragmentShader

	} );

	this.quad = new THREE.Mesh( new THREE.PlaneGeometry( window.innerWidth, window.innerHeight ), this.materialBokeh );
	this.quad.position.z = - 500;
	this.scene.add( this.quad );

}
var postProcessing = new PostProcessor();


text:
package com.codewalle.tra;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.codewalle.tra.R.id;
import com.codewalle.tra.R.layout;
import com.codewalle.tra.widget.IMERelativeLayout;
import org.androidannotations.api.view.HasViews;
import org.androidannotations.api.view.OnViewChangedListener;
import org.androidannotations.api.view.OnViewChangedNotifier;

public final class LoginActivity_
    extends LoginActivity
    implements HasViews, OnViewChangedListener
{

    private final OnViewChangedNotifier onViewChangedNotifier_ = new OnViewChangedNotifier();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        OnViewChangedNotifier previousNotifier = OnViewChangedNotifier.replaceNotifier(onViewChangedNotifier_);
        init_(savedInstanceState);
        super.onCreate(savedInstanceState);
        OnViewChangedNotifier.replaceNotifier(previousNotifier);
        setContentView(layout.login);
    }

    private void init_(Bundle savedInstanceState) {
        OnViewChangedNotifier.registerOnViewChangedListener(this);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        super.setContentView(view, params);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    public static LoginActivity_.IntentBuilder_ intent(Context context) {
        return new LoginActivity_.IntentBuilder_(context);
    }

    public static LoginActivity_.IntentBuilder_ intent(Fragment supportFragment) {
        return new LoginActivity_.IntentBuilder_(supportFragment);
    }

    @Override
    public void onViewChanged(HasViews hasViews) {
        mSchoolNameView = ((ImageView) hasViews.findViewById(id.login_school_name));
        mPassword = ((EditText) hasViews.findViewById(id.password));
        mUserName = ((EditText) hasViews.findViewById(id.username));
        mRoot = ((IMERelativeLayout) hasViews.findViewById(id.login_root));
        mLoginButton = ((Button) hasViews.findViewById(id.login_button));
        {
            View view = hasViews.findViewById(id.login_button);
            if (view!= null) {
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        LoginActivity_.this.loginButton();
                    }

                }
                );
            }
        }
        setupBackgroud();
        test();
        initListeners();
    }

    public static class IntentBuilder_ {

        private Context context_;
        private final Intent intent_;
        private Fragment fragmentSupport_;

        public IntentBuilder_(Context context) {
            context_ = context;
            intent_ = new Intent(context, LoginActivity_.class);
        }

        public IntentBuilder_(Fragment fragment) {
            fragmentSupport_ = fragment;
            context_ = fragment.getActivity();
            intent_ = new Intent(context_, LoginActivity_.class);
        }

        public Intent get() {
            return intent_;
        }

        public LoginActivity_.IntentBuilder_ flags(int flags) {
            intent_.setFlags(flags);
            return this;
        }

        public void start() {
            context_.startActivity(intent_);
        }

        public void startForResult(int requestCode) {
            if (fragmentSupport_!= null) {
                fragmentSupport_.startActivityForResult(intent_, requestCode);
            } else {
                if (context_ instanceof Activity) {
                    ((Activity) context_).startActivityForResult(intent_, requestCode);
                } else {
                    context_.startActivity(intent_);
                }
            }
        }

    }

}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>gtypes.GRectangle</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Module gtypes ::
        Class GRectangle

[hide private]

[frames] | no frames]

Class GRectangle

source code

This type contains real-valued x, y, width, and height fields. It is
  used to represent the bounding box of a graphical object

        Instance Methods
        [hide private]

          __init__(self,
        x=0.0,
        y=0.0,
        width=0.0,
        height=0.0)

      Initializes a GRectangle object with the specified fields.

            source code

      boolean

          __eq__(self,
        other)

      Defines equality for GRectangles, namely the x, y, height, and width
      values are     identical for the compared objects

            source code

      boolean

          __ne__(self,
        other)

      Defines inequality for GRectangles, negation of equality

            source code

      float

          getX(self)

      Returns the x component of the upper left corner.

            source code

      float

          getY(self)

      Returns the x component of the upper left corner.

            source code

      float

          getWidth(self)

      Returns the width component of the GRectangle.

            source code

      float

          getHeight(self)

      Returns the width component of the GRectangle.

            source code

      boolean

          isEmpty(self)

      Returns if the rectangle is empty.

            source code

      boolean

          contains(self,
        pt=None,
        x=None,
        y=None)

      Returns true if the rectangle contains the given point, which may be
      specified either as a GPoint or distinct coordinates

            source code

      string

          toString(self)

      Converts the GRectangle to a string in the form "(x, y, width, height)"

            source code

        Method Details
        [hide private]

__init__(self,
        x=0.0,
        y=0.0,
        width=0.0,
        height=0.0)

(Constructor)

  	source code

Initializes a GRectangle object with the specified fields. If these
  parameters are not supplied hte default values are set to 0.0

Parameters:

x (float) - x coordinate of upper left corner

y (float) - y coordinate of upper left corner

width (float) - width of rectangle

height (float) - height of rectangle

__eq__(self,
        other)

(Equality operator)

  	source code

Defines equality for GRectangles, namely the x, y, height, and width
  values are     identical for the compared objects

Parameters:

other (GRectangle) - object to be compared

Returns: boolean

__ne__(self,
        other)

  	source code

Defines inequality for GRectangles, negation of equality

Parameters:

other (GRectangle) - object to be compared

Returns: boolean

contains(self,
        pt=None,
        x=None,
        y=None)

  	source code

Returns true if the rectangle contains the given point, which may be
  specified either as a GPoint or distinct coordinates

Parameters:

pt (GPoint) - GPoint to check, will override x and y

x (float) - x coordinate of point to check

y (float) - y coordinate of point to check

Returns: boolean

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Wed May 08 15:27:31 2013

      http://epydoc.sourceforge.net


text:
<?php

namespace RectorPrefix20210615;

if (\class_exists('Tx_Extbase_Error_Result')) {
    return;
}
class Tx_Extbase_Error_Result
{
}
\class_alias('Tx_Extbase_Error_Result', 'Tx_Extbase_Error_Result', \false);


text:
import Orbit from 'orbit/main';
import Cache from 'orbit-common/cache';
import Schema from 'orbit-common/schema';
import { equalOps } from 'tests/test-helper';
import { Promise, on } from 'rsvp';

var schema,
    cache;

///////////////////////////////////////////////////////////////////////////////

module("OC - Cache", {
  setup: function() {
    Orbit.Promise = Promise;
    schema = new Schema({
      models: {
        planet: {
          links: {
            moons: {type: 'hasMany', model: 'moon'}
          }
        },
        moon: {
          links: {
            planet: {type: 'hasOne', model: 'planet'}
          }
        }
      }
    });

  },

  teardown: function() {
    schema = null;
  }
});

test("it exists", function() {
  cache = new Cache(schema);

  ok(cache);
});

test("is sparse by default", function(assert) {
  cache = new Cache(schema);

  assert.equal(cache.sparse, true, 'sparse is true');
  assert.equal(cache.retrieve('planet'), undefined, 'no data is initialized');
});

test("non-sparse caches will initialize data for all models in a schema", function(assert) {
  cache = new Cache(schema, {sparse: false});

  assert.equal(cache.sparse, false, 'sparse is false');
  assert.deepEqual(cache.retrieve('planet'), {}, 'data is initialized');
});

test("#transform sets data and #retrieve retrieves it", function() {
  cache = new Cache(schema);

  var earth = {id: '1', name: 'Earth'};
  cache.transform([{op: 'add', path: 'planet/1', value: earth}]);
  deepEqual(cache.retrieve('planet/1'), earth, 'objects match in value');
  notStrictEqual(cache.retrieve('planet/1'), earth, 'objects don\'t match by reference because a clone has been cached');
});

test("#exists indicates whether a path exists", function() {
  cache = new Cache(schema);

  var earth = {id: '1', name: 'Earth'};
  cache.transform([{op: 'add', path: 'planet/1', value: earth}]);
  equal(cache.exists('planet'), true, 'path exists');
  equal(cache.exists('planet/1'), true, 'path exists');
  equal(cache.exists('planet/1/id'), true, 'path exists');
  equal(cache.exists('planet/1/id/bogus'), false, 'path does not exist');
  equal(cache.exists('this/path/is/bogus'), false, 'path does not exist');
});

test("#hasDeleted by default just returns the inverse of #exists", function() {
  cache = new Cache(schema);

  var earth = {id: '1', name: 'Earth'};
  cache.transform([{op: 'add', path: 'planet/1', value: earth}]);
  equal(cache.hasDeleted('planet'), !cache.exists('planet'), 'path exists');
  equal(cache.hasDeleted('planet/1'), !cache.exists('planet/1'), 'path exists');
  equal(cache.hasDeleted('planet/1/id/bogus'), !cache.exists('planet/1/id/bogus'), false, 'path does not exist');
});

test("#length returns the size of data at a path", function() {
  cache = new Cache(schema);

  equal(cache.length('notthere'), 0, 'returns 0 when an object does not exist at a path');

  cache.transform([{op: 'add', path: 'planet/1', value: {name: 'Earth'}},
                   {op: 'add', path: 'planet/2', value: {name: 'Mars'}}]);

  equal(cache.length('planet'), 2, 'returns count of objects at a path');

  cache.transform([{op: 'add', path: 'planet/1/stuff', value: ['a', 'b', 'c']}]);

  equal(cache.length('planet/1/stuff'), 3, 'returns size of an array at a path');
});

test("#reset clears the cache by default", function() {
  cache = new Cache(schema);

  cache.transform([{op: 'add', path: 'planet/1', value: {name: 'Earth'}}]);
  cache.reset();
  deepEqual(cache.retrieve(), {});
});

test("#reset overrides the cache completely with the value specified", function() {
  cache = new Cache(schema);

  cache.transform([{op: 'add', path: 'planet/1', value: {name: 'Earth'}}]);

  var newData = {planet: {'2': {name: 'Mars'}}};
  cache.reset(newData);
  deepEqual(cache.retrieve(), newData);
});

test("#transform returns an empty array of `operations` when an operation is a noop", function() {
  cache = new Cache(schema);

  cache.transform([{op: 'add', path: 'planet/1', value: {name: 'Earth'}}]);

  deepEqual(cache.transform([{op: 'remove', path: 'planet/2'}]).operations, [], 'operation was a noop');
});

test("#transform tracks refs and clears them from hasOne relationships when a referenced record is removed", function() {
  cache = new Cache(schema);

  var jupiter = {id: 'p1', name: 'Jupiter', __rel: {moons: {}}};
  var io = {id: 'm1', name: 'Io', __rel: {planet: 'p1'}};
  var europa = {id: 'm2', name: 'Europa', __rel: {planet: 'p1'}};

  cache.transform([{op: 'add', path: 'planet/p1', value: jupiter},
                   {op: 'add', path: 'moon/m1', value: io},
                   {op: 'add', path: 'moon/m2', value: europa}]);

  equal(cache.retrieve('moon/m1/__rel/planet'), 'p1', 'Jupiter has been assigned to Io');
  equal(cache.retrieve('moon/m2/__rel/planet'), 'p1', 'Jupiter has been assigned to Europa');

  cache.transform([{op: 'remove', path: 'planet/p1'}]);

  equal(cache.retrieve('planet/p1'), undefined, 'Jupiter is GONE');

  equal(cache.retrieve('moon/m1/__rel/planet'), undefined, 'Jupiter has been cleared from Io');
  equal(cache.retrieve('moon/m2/__rel/planet'), undefined, 'Jupiter has been cleared from Europa');
});

test("#transform tracks refs and clears them from hasMany relationships when a referenced record is removed", function() {
  cache = new Cache(schema);

  var io = {id: 'm1', name: 'Io', __rel: {planet: null}};
  var europa = {id: 'm2', name: 'Europa', __rel: {planet: null}};
  var jupiter = {id: 'p1', name: 'Jupiter', __rel: {moons: {'m1': true, 'm2': true}}};

  cache.transform([{op: 'add', path: 'moon/m1', value: io},
                   {op: 'add', path: 'moon/m2', value: europa},
                   {op: 'add', path: 'planet/p1', value: jupiter}]);

  equal(cache.retrieve('/planet/p1/__rel/moons/m1'), true, 'Jupiter has been assigned to Io');
  equal(cache.retrieve('/planet/p1/__rel/moons/m2'), true, 'Jupiter has been assigned to Europa');

  cache.transform([{op: 'remove', path: '/moon/m1'}]);
  equal(cache.retrieve('/moon/m1'), null, 'Io is GONE');

  cache.transform([{op: 'remove', path: '/moon/m2'}]);
  equal(cache.retrieve('/moon/m2'), null, 'Europa is GONE');

  equal(cache.retrieve('/planet/p1/__rel/moons/m1'), null, 'Io has been cleared from Jupiter');
  equal(cache.retrieve('/planet/p1/__rel/moons/m2'), null, 'Europa has been cleared from Jupiter');
});

test("for a sparse cache, adds link to hasMany if record doesn't exist", function(){
  cache = new Cache(schema);
  var operation = {op: 'add', path: ['planet', 'p1', '__rel', 'moons', 'moon1'], value: true};

  var result = cache.transform([operation]);
  equalOps(result.operations, [operation], "applied transform");
});

test("for a non-sparse cache, does not add link to hasMany if record doesn't exist", function(){
  cache = new Cache(schema, {sparse: false});
  var operation = {op: 'add', path: ['planet', 'p1', '__rel', 'moons', 'moon1'], value: true};

  var result = cache.transform([operation]);
  deepEqual(result.operations, [], "didn't apply transform");
});

test("does not remove link from hasMany if record doesn't exist", function(){
  cache = new Cache(schema);
  var operation = {op: 'remove', path: ['planet', 'p1', '__rel', 'moons', 'moon1'], value: true};

  var result = cache.transform([operation]);
  deepEqual(result.operations, [], "didn't apply transform");
});

test("for a sparse cache, adds (instead of replaces) hasOne if record doesn't exist", function(){
  cache = new Cache(schema);
  var operation = {op: 'replace', path: ['moon', 'moon1', '__rel', 'planet'], value: "p1"};

  var result = cache.transform([operation]);
  equalOps(result.operations, [operation], "applied transform");
});

test("for a non-sparse cache, does not replace hasOne if record doesn't exist", function(){
  cache = new Cache(schema, {sparse: false});
  var operation = {op: 'replace', path: ['moon', 'moon1', '__rel', 'planet'], value: "p1"};

  var result = cache.transform([operation]);
  deepEqual(result.operations, [], "didn't apply transform");
});

test("does not remove hasOne link if record doesn't exist", function(){
  cache = new Cache(schema);
  var operation = {op: 'remove', path: ['moon', 'moon1', '__rel', 'planet'], value: "p1"};

  var result = cache.transform([operation]);
  deepEqual(result.operations, [], "didn't apply transform");
});

test("does not add link to hasMany if link already exists", function(){
  cache = new Cache(schema);
  var jupiter = { id: 'p1', name: "Jupiter", __rel: { moons: { 'm1': true } } };
  cache.transform([{op: 'add', path: ['planet', jupiter.id], value: jupiter }]);

  var operation = {op: 'replace', path: ['planet', jupiter.id, '__rel', 'moons', 'm1'], value: true};

  var result = cache.transform([operation]);
  deepEqual(result.operations, [], "didn't apply transform");
});

test("test does not remove link from hasMany if link doesn't exist", function(){
  cache = new Cache(schema);
  var jupiter = { id: 'p1', name: "Jupiter", __rel: { moons: {} } };
  cache.transform([{op: 'add', path: ['planet', jupiter.id], value: jupiter }]);

  var operation = {op: 'remove', path: ['planet', jupiter.id, '__rel', 'moons', 'm1']};

  var result = cache.transform([operation]);
  deepEqual(result.operations, [], "didn't apply transform");
});

test("does not replace hasOne if link already exists", function(){
  cache = new Cache(schema);
  var europa = { id: 'm1', name: "Europe", __rel: { planet: 'p1' } };
  cache.transform([{op: 'add', path: ['moon', europa.id], value: europa }]);

  var operation = {op: 'replace', path: ['moon', europa.id, '__rel', 'planet'], value: 'p1'};

  var result = cache.transform([operation]);
  deepEqual(result.operations, [], "didn't apply transform");
});

test("does not remove hasOne if link doesn't exist", function(){
  cache = new Cache(schema);
  var europa = { id: 'm1', name: "Europe" };
  cache.transform([{op: 'add', path: ['moon', europa.id], value: europa }]);

  var operation = {op: 'remove', path: ['moon', europa.id, '__rel', 'planet']};

  var result = cache.transform([operation]);
  deepEqual(result.operations, [], "didn't apply transform");
});

test("#transform removing model with a bi-directional hasOne", function() {
  expect(6);

  var hasOneSchema = new Schema({
    models: {
      one: {
        links: {
          two: { type: 'hasOne', model: 'two', inverse: 'one' }
        }
      },
      two: {
        links: {
          one: { type: 'hasOne', model: 'one', inverse: 'two' }
        }
      },
    }
  });
  cache = new Cache(hasOneSchema);
  cache.transform([
    {
      op: 'add', path: 'one/one',
      value: {
        id: 'one',
        __rel: { two: null },
      }
    },
    {
      op: 'add', path: 'two/two',
      value: {
        id: 'two',
        __rel: { one: 'one' },
      }
    }
  ]);
  var one = cache.retrieve(['one', 'one']);
  var two = cache.retrieve(['two', 'two']);
  ok(one, 'one exists');
  ok(two, 'two exists');
  equal(one.__rel.two, 'two', 'one links to two');
  equal(two.__rel.one, 'one', 'two links to one');

  var result = cache.transform([{ op: 'remove', path: 'two/two' }]);
  strictEqual(one.__rel.two, null, 'ones link to two got removed');

  deepEqual(
    result.inverseOperations,
    [
      {
        op: 'add',
        path: ['two', 'two'],
        value: {
          id: 'two',
          __rel: {
            one: 'one'
          }
        }
      },
      {
        op: 'replace',
        path: ['one', 'one', '__rel', 'two'],
        value: 'two'
      }
    ],
    'inverse ops match'
  );
});

test("#transform removes dependent records", function() {
  // By making this schema recursively dependent remove we check that recursive
  // works as well.
  var dependentSchema = new Schema({
    models: {
      planet: {
        links: {
          moons: {type: 'hasMany', model: 'moon', dependent: 'remove'}
        }
      },
      moon: {
        links: {
          planet: {type: 'hasOne', model: 'planet', dependent: 'remove'}
        }
      }
    }
  });
  cache = new Cache(dependentSchema);

  var jupiter = {id: 'p1', name: 'Jupiter', __rel: {moons: {}}};
  var io = {id: 'm1', name: 'Io', __rel: {planet: 'p1'}};
  var europa = {id: 'm2', name: 'Europa', __rel: {planet: 'p1'}};

  cache.transform([
    {op: 'add', path: 'planet/p1', value: jupiter},
    {op: 'add', path: 'moon/m1', value: io},
    {op: 'add', path: 'moon/m2', value: europa},
    {op: 'add', path: 'planet/p1/__rel/moons/m1', value: true },
    {op: 'add', path: 'planet/p1/__rel/moons/m2', value: true }
  ]);

  // Removing the moon should remove the planet should remove the other moon
  var result = cache.transform([{op: 'remove', path: 'moon/m1'}]);

  equal(cache.length('moon'), 0, 'No moons left in store');
  equal(cache.length('planet'), 0, 'No planets left in store');

  deepEqual(
    result.inverseOperations,
    [
      {
        op: 'add',
        path: ['moon', 'm1'],
        value: {
          id: 'm1',
          name: 'Io',
          __rel: {
            planet: 'p1'
          }
        }
      },
      {
        op: 'add',
        path: ['planet', 'p1'],
        value: {
          id: 'p1',
          name: 'Jupiter',
          __rel: {
            moons: {
              'm1': true,
              'm2': true
            }
          }
        },
      },
      {
        op: 'add',
        path: ['moon', 'm2'],
        value: {
          id: 'm2',
          name: 'Europa',
          __rel: {
            planet: 'p1'
          }
        }
      }
    ],
    'inverse ops match'
  );
});

test("#transform does not remove non-dependent records", function() {
  var dependentSchema = new Schema({
    models: {
      planet: {
        links: {
          moons: {type: 'hasMany', model: 'moon'}
        }
      },
      moon: {
        links: {
          planet: {type: 'hasOne', model: 'planet'}
        }
      }
    }
  });
  cache = new Cache(dependentSchema);

  var jupiter = {id: 'p1', name: 'Jupiter', __rel: {moons: {}}};
  var io = {id: 'm1', name: 'Io', __rel: {planet: 'p1'}};
  var europa = {id: 'm2', name: 'Europa', __rel: {planet: 'p1'}};

  cache.transform([
    {op: 'add', path: 'planet/p1', value: jupiter},
    {op: 'add', path: 'moon/m1', value: io},
    {op: 'add', path: 'moon/m2', value: europa},
    {op: 'add', path: 'planet/p1/__rel/moons/m1', value: true },
    {op: 'add', path: 'planet/p1/__rel/moons/m2', value: true }
  ]);

  // Since there are no dependent relationships, no other records will be
  // removed
  var result = cache.transform([{op: 'remove', path: 'moon/m1'}]);
  equal(cache.length('moon'), 1, 'One moon left in store');
  equal(cache.length('planet'), 1, 'One planet left in store');

  deepEqual(
    result.inverseOperations,
    [
      {
        op: 'add',
        path: ['moon', 'm1'],
        value: {
          id: 'm1',
          name: 'Io',
          __rel: {
            planet: 'p1'
          }
        }
      }
    ],
    'inverse ops match'
  );
});


text:
namespace NetsSharp
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class HttpQueryBuilder
    {
        private readonly IList<KeyValuePair<string, string>> _values = new List<KeyValuePair<string, string>>();

        public void Add(string name, string value)
        {
            this._values.Add(new KeyValuePair<string, string>(name, value));
        }

        public void Remove(string name)
        {
            var removable = this._values.Where(kvp => kvp.Key == name);
            foreach (var item in removable)
            {
                this._values.Remove(item);
            }
        }

        public override string ToString()
        {
            return string.Join("&", this._values.OrderBy(kvp => kvp.Key).Select(kvp => string.Format("{0}={1}", kvp.Key, Uri.EscapeDataString(kvp.Value))));
        }
    }
}