text:
'use strict';

describe('dateParser', function () {

  var $compile, scope, $dateParser, parser;

  var lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur non velit nulla. Suspendisse sit amet tempus diam. Sed at ultricies neque. Suspendisse id felis a sem placerat ornare. Donec auctor, purus at molestie tempor, arcu enim molestie lacus, ac imperdiet massa urna eu massa. Praesent velit tellus, scelerisque a fermentum ut, ornare in diam. Phasellus egestas molestie feugiat. Vivamus sit amet viverra metus.';

  beforeEach(module('mgcrea.ngStrap.helpers.dateParser'));

  beforeEach(inject(function (_$rootScope_, _$compile_, _$dateParser_) {
    scope = _$rootScope_;
    $compile = _$compile_;
    $dateParser = _$dateParser_;
  }));

  function generateTestCases(tests) {
    tests.forEach(function(test) {
      it('should report isValid(' + test.val + ')=' + test.expect + ' (' + test.reason + ')', function() {
        expect(parser.isValid(test.val)).toBe(test.expect);
      });
    });
  }

  // Tests
  describe('isValid', function () {
    describe('date format is "y" (single digit year -- extremely permissive)', function() {
      describe('strict=true', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'y', strict: true});
        });
        generateTestCases([
          {val:'-1', expect:true, reason:'negative single digit, no prefix'},
          {val:'-01', expect:false, reason:'negative single digit, prefixed'},
          {val:'0', expect:true, reason:'single digit, no prefix'},
          {val:'00', expect:false, reason:'double digit, prefixed'},
          {val:'199', expect:true, reason:'multi digit, no prefix'},
          {val:'0199', expect:false, reason:'multi digit, prefixed'},
          {val:'2099', expect:true, reason:'many digit, no prefix'},
          {val:'002099', expect:false, reason:'many digit, multiple prefixed'},
          {val:'10000', expect:false, reason:'only support 4-digit years'},
        ]);
      });
      describe('strict=false', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'y', strict: false});
        });
        generateTestCases([
          {val:'-1', expect:true, reason:'negative single digit, no prefix'},
          {val:'-01', expect:true, reason:'negative single digit, prefixed'},
          {val:'0', expect:true, reason:'single digit, no prefix'},
          {val:'00', expect:true, reason:'double digit, prefixed'},
          {val:'199', expect:true, reason:'multi digit, no prefix'},
          {val:'0199', expect:true, reason:'multi digit, prefixed'},
          {val:'2099', expect:true, reason:'many digit, no prefix'},
          {val:'002099', expect:true, reason:'many digit, multiple prefixed'},
          {val:'10000', expect:false, reason:'only support 4-digit years'},
        ]);
      });
    });

    describe('date format is "M" (single digit month)', function() {
      describe('strict=true', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'M', strict: true});
        });
        generateTestCases([
          {val:'0', expect:false, reason:'invalid date'},
          {val:'00', expect:false, reason:'invalid date'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:false, reason:'double digit, prefixed'},
          {val:'12', expect:true, reason:'double digit, no prefix'},
          {val:'13', expect:false, reason:'invalid date'}
        ]);
      });
      describe('strict=false', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'M', strict: false});
        });
        generateTestCases([
          {val:'0', expect:false, reason:'invalid date'},
          {val:'00', expect:false, reason:'invalid date'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:true, reason:'double digit, prefixed'},
          {val:'12', expect:true, reason:'double digit, no prefix'},
          {val:'13', expect:false, reason:'invalid date'}
        ]);
      });
    });

    describe('date format is "d" (single digit date)', function() {
      describe('strict=true', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'd', strict: true});
        });
        generateTestCases([
          {val:'0', expect:false, reason:'invalid date'},
          {val:'00', expect:false, reason:'invalid date'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:false, reason:'double digit, prefixed'},
          {val:'31', expect:true, reason:'double digit, no prefix'},
          {val:'32', expect:false, reason:'invalid date'}
        ]);
      });
      describe('strict=false', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'd', strict: false});
        });
        generateTestCases([
          {val:'0', expect:false, reason:'invalid date'},
          {val:'00', expect:false, reason:'invalid date'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:true, reason:'double digit, prefixed'},
          {val:'31', expect:true, reason:'double digit, no prefix'},
          {val:'32', expect:false, reason:'invalid date'}
        ]);
      });
    });

    describe('date format is "dd" (two-digit date)', function() {
      beforeEach(function() {
        parser = $dateParser({format: 'dd', strict: true});
      });
      generateTestCases([
        {val:'0', expect:false, reason:'invalid date'},
        {val:'00', expect:false, reason:'invalid date'},
        {val:'1', expect:false, reason:'single digit, no prefix'},
        {val:'01', expect:true, reason:'double digit, prefixed'},
        {val:'31', expect:true, reason:'double digit, no prefix'},
        {val:'32', expect:false, reason:'invalid date'}
      ]);
    });

    describe('date format is "h" (single digit hour, 12-hour clock)', function() {
      describe('strict=true', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'h', strict: true});
        });
        generateTestCases([
          {val:'0', expect:false, reason:'invalid in 12-hour clock'},
          {val:'00', expect:false, reason:'invalid in 12-hour clock'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:false, reason:'double digit, prefixed'},
          {val:'12', expect:true, reason:'double digit, no prefix'},
          {val:'13', expect:false, reason:'double digit, invalid hour'}
        ]);
      });
      describe('strict=false', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'h', strict: false});
        });
        generateTestCases([
          {val:'0', expect:false, reason:'invalid in 12-hour clock'},
          {val:'00', expect:false, reason:'invalid in 12-hour clock'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:true, reason:'double digit, prefixed'},
          {val:'12', expect:true, reason:'double digit, no prefix'},
          {val:'13', expect:false, reason:'double digit, invalid hour'}
        ]);
      });
    });

    describe('date format is "H" (single digit hour, 24-hour clock)', function() {
      describe('strict=true', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'H', strict: true});
        });
        generateTestCases([
          {val:'0', expect:true, reason:'single digit, no prefix'},
          {val:'00', expect:false, reason:'double digit, prefixed'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:false, reason:'double digit, prefixed'},
          {val:'23', expect:true, reason:'double digit, no prefix'},
          {val:'24', expect:false, reason:'double digit, invalid hour'}
        ]);
      });
      describe('strict=false', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'H', strict: false});
        });
        generateTestCases([
          {val:'0', expect:true, reason:'single digit'},
          {val:'00', expect:true, reason:'double digit, prefixed'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:true, reason:'double digit, prefixed'},
          {val:'23', expect:true, reason:'double digit, no prefix'},
          {val:'24', expect:false, reason:'double digit, invalid hour'}
        ]);
      });
    });

    describe('date format is "m" (single digit minute)', function() {
      describe('strict=true', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'm', strict: true});
        });
        generateTestCases([
          {val:'0', expect:true, reason:'single digit, no prefix'},
          {val:'00', expect:false, reason:'double digit, prefixed'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:false, reason:'double digit, prefixed'},
          {val:'59', expect:true, reason:'double digit, no prefix'},
          {val:'60', expect:false, reason:'double digit, too many minutes'}
        ]);
      });
      describe('strict=false', function() {
        beforeEach(function() {
          parser = $dateParser({format: 'm', strict: false});
        });
        generateTestCases([
          {val:'0', expect:true, reason:'single digit, no prefix'},
          {val:'00', expect:true, reason:'double digit, prefixed'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:true, reason:'double digit, prefixed'},
          {val:'59', expect:true, reason:'double digit, no prefix'},
          {val:'60', expect:false, reason:'double digit, too many minutes'}
        ]);
      });
    });

    describe('date format is "s" (single digit second)', function() {
      describe('strict=true', function() {
        beforeEach(function() {
          parser = $dateParser({format: 's', strict: true});
        });
        generateTestCases([
          {val:'0', expect:true, reason:'single digit, no prefix'},
          {val:'00', expect:false, reason:'double digit, prefixed'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:false, reason:'double digit, prefixed'},
          {val:'59', expect:true, reason:'double digit, no prefix'},
          {val:'60', expect:false, reason:'double digit, too many seconds'}
        ]);
      });
      describe('strict=false', function() {
        beforeEach(function() {
          parser = $dateParser({format: 's', strict: false});
        });
        generateTestCases([
          {val:'0', expect:true, reason:'single digit, no prefix'},
          {val:'00', expect:true, reason:'double digit, prefixed'},
          {val:'1', expect:true, reason:'single digit, no prefix'},
          {val:'01', expect:true, reason:'double digit, prefixed'},
          {val:'59', expect:true, reason:'double digit, no prefix'},
          {val:'60', expect:false, reason:'double digit, too many seconds'}
        ]);
      });
    });
  });
});


text:
var App = require('app');

App.DashboardWidgetView = Em.View.extend({

  /**
   * @type {string}
   * @default null
   */
  title: null,
  templateName: null, // each has specific template

  /**
   * Setup model for widget by `model_type`. Usually `model_type` is a lowercase service name,
   * for example `hdfs`, `yarn`, etc. You need to set `model_type` in extended object View, for example
   * look App.DataNodeUpView.
   * @type {object} - model that set up in App.MainDashboardView.setWidgetsDataModel()
   */
  model : function () {
    if (!this.get('model_type')) return {};
    return this.get('parentView').get(this.get('model_type') + '_model');
  }.property(),

  /**
   * id 1-10 used to identify
   * @type {number}
   * @default null
   */
  id: null,

  /**
   * html id bind to view-class: widget-(1)
   * used by re-sort
   * @type {string}
   */
  viewID: Em.computed.format('widget-{0}', 'id'),

  attributeBindings: ['viewID'],

  /**
   * widget content pieChart/ text/ progress bar/links/ metrics. etc
   * @type {Array}
   * @default null
   */
  content: null,

  /**
   * more info details
   * @type {Array}
   */
  hiddenInfo: [],

  /**
   * @type {string}
   */
  hiddenInfoClass: "hidden-info-two-line",

  /**
   * @type {number}
   * @default null
   */
  thresh1: null,

  /**
   * @type {number}
   * @default null
   */
  thresh2: null,

  /**
   * @type {Boolean}
   * @default false
   */
  isDataLoadedBinding: 'App.router.clusterController.isServiceContentFullyLoaded',

  /**
   * @type {Em.Object}
   * @class
   */
  widgetConfig: Ember.Object.extend({
    thresh1: '',
    thresh2: '',
    hintInfo: Em.computed.i18nFormat('dashboard.widgets.hintInfo.common', 'maxValue'),
    isThresh1Error: false,
    isThresh2Error: false,
    errorMessage1: "",
    errorMessage2: "",
    maxValue: 0,
    observeThresh1Value: function () {
      var thresh1 = this.get('thresh1');
      var thresh2 = this.get('thresh2');
      var maxValue = this.get('maxValue');

      if (thresh1.trim() !== "") {
        if (isNaN(thresh1) || thresh1 > maxValue || thresh1 < 0) {
          this.set('isThresh1Error', true);
          this.set('errorMessage1', Em.I18n.t('dashboard.widgets.error.invalid').format(maxValue));
        } else if (this.get('isThresh2Error') === false && parseFloat(thresh2) <= parseFloat(thresh1)) {
          this.set('isThresh1Error', true);
          this.set('errorMessage1', Em.I18n.t('dashboard.widgets.error.smaller'));
        } else {
          this.set('isThresh1Error', false);
          this.set('errorMessage1', '');
        }
      } else {
        this.set('isThresh1Error', true);
        this.set('errorMessage1', Em.I18n.t('admin.users.editError.requiredField'));
      }
      this.updateSlider();
    }.observes('thresh1', 'maxValue'),
    observeThresh2Value: function () {
      var thresh2 = this.get('thresh2');
      var maxValue = this.get('maxValue');

      if (thresh2.trim() !== "") {
        if (isNaN(thresh2) || thresh2 > maxValue || thresh2 < 0) {
          this.set('isThresh2Error', true);
          this.set('errorMessage2', Em.I18n.t('dashboard.widgets.error.invalid').format(maxValue));
        } else {
          this.set('isThresh2Error', false);
          this.set('errorMessage2', '');
        }
      } else {
        this.set('isThresh2Error', true);
        this.set('errorMessage2', Em.I18n.t('admin.users.editError.requiredField'));
      }
      this.updateSlider();
    }.observes('thresh2', 'maxValue'),
    updateSlider: function () {
      var thresh1 = this.get('thresh1');
      var thresh2 = this.get('thresh2');
      // update the slider handles and color
      if (this.get('isThresh1Error') === false && this.get('isThresh2Error') === false) {
        $("#slider-range")
          .slider('values', 0, parseFloat(thresh1))
          .slider('values', 1, parseFloat(thresh2));
      }
    }
  }),

  didInsertElement: function () {
    App.tooltip(this.$("[rel='ZoomInTooltip']"), {
      placement: 'left',
      template: '

'
    });
  },

  willDestroyElement : function() {
    $("[rel='ZoomInTooltip']").tooltip('destroy');
  },
  /**
   * delete widget
   * @param {object} event
   */
  deleteWidget: function () {
    var parent = this.get('parentView');
    var self = this;

    if (App.get('testMode')) {
      //update view on dashboard
      var objClass = parent.widgetsMapper(this.get('id'));
      parent.get('visibleWidgets').removeObject(objClass);
      parent.get('hiddenWidgets').pushObject(Em.Object.create({displayName: this.get('title'), id: this.get('id'), checked: false}));
    } else {
      //reconstruct new persist value then post in persist
      parent.getUserPref(parent.get('persistKey')).complete(function () {
        self.deleteWidgetComplete.apply(self);
      });
    }
  },

  /**
   * delete widget complete callback
   */
  deleteWidgetComplete: function () {
    var parent = this.get('parentView');
    var oldValue = parent.get('currentPrefObject');
    var deletedId = this.get('id');
    var newValue = Em.Object.create({
      dashboardVersion: oldValue.dashboardVersion,
      visible: oldValue.visible.slice(0).without(deletedId),
      hidden: oldValue.hidden,
      threshold: oldValue.threshold
    });
    newValue.hidden.push([deletedId, this.get('title')]);
    parent.postUserPref(parent.get('persistKey'), newValue);
    parent.translateToReal(newValue);
  },

  /**
   * edit widget
   * @param {object} event
   */
  editWidget: function (event) {
    var configObj = this.get('widgetConfig').create({
      thresh1: this.get('thresh1') + '',
      thresh2: this.get('thresh2') + '',
      maxValue: parseFloat(this.get('maxValue'))
    });
    this.showEditDialog(configObj)
  },

  /**
   *  show edit dialog
   * @param {Em.Object} configObj
   * @returns {App.ModalPopup}
   */
  showEditDialog: function (configObj) {
    var self = this;
    var maxValue = this.get('maxValue');

    return App.ModalPopup.show({
      header: Em.I18n.t('dashboard.widgets.popupHeader'),
      classNames: ['sixty-percent-width-modal-edit-widget'],
      bodyClass: Ember.View.extend({
        templateName: require('templates/main/dashboard/edit_widget_popup'),
        configPropertyObj: configObj
      }),
      primary: Em.I18n.t('common.apply'),
      onPrimary: function () {
        configObj.observeThresh1Value();
        configObj.observeThresh2Value();
        if (!configObj.isThresh1Error && !configObj.isThresh2Error) {
          self.set('thresh1', parseFloat(configObj.get('thresh1')));
          self.set('thresh2', parseFloat(configObj.get('thresh2')));

          if (!App.get('testMode')) {
            // save to persist
            var parent = self.get('parentView');
            parent.getUserPref(parent.get('persistKey')).complete(function () {
              var oldValue = parent.get('currentPrefObject');
              oldValue.threshold[parseInt(self.get('id'), 10)] = [configObj.get('thresh1'), configObj.get('thresh2')];
              parent.postUserPref(parent.get('persistKey'), oldValue);
            });
          }

          this.hide();
        }
      },

      didInsertElement: function () {
        this._super();
        var browserVersion = self.getInternetExplorerVersion();
        var handlers = [configObj.get('thresh1'), configObj.get('thresh2')];
        var colors = [App.healthStatusGreen, App.healthStatusOrange, App.healthStatusRed]; //color green, orange ,red

        if (browserVersion === -1 || browserVersion > 9) {
          configObj.set('isIE9', false);
          configObj.set('isGreenOrangeRed', true);
          $("#slider-range").slider({
            range: true,
            min: 0,
            max: maxValue,
            values: handlers,
            create: function () {
              updateColors(handlers);
            },
            slide: function (event, ui) {
              updateColors(ui.values);
              configObj.set('thresh1', ui.values[0] + '');
              configObj.set('thresh2', ui.values[1] + '');
            },
            change: function (event, ui) {
              updateColors(ui.values);
            }
          });

          function updateColors(handlers) {
            var colorstops = colors[0] + ", "; // start with the first color
            for (var i = 0; i < handlers.length; i++) {
              colorstops += colors[i] + " " + handlers[i] * 100 / maxValue + "%,";
              colorstops += colors[i + 1] + " " + handlers[i] * 100 / maxValue + "%,";
            }
            colorstops += colors[colors.length - 1];
            var sliderElement = $('#slider-range');
            var css1 = '-webkit-linear-gradient(left,' + colorstops + ')'; // chrome & safari
            sliderElement.css('background-image', css1);
            var css2 = '-ms-linear-gradient(left,' + colorstops + ')'; // IE 10+
            sliderElement.css('background-image', css2);
            //$('#slider-range').css('filter', 'progid:DXImageTransform.Microsoft.gradient( startColorStr= ' + colors[0] + ', endColorStr= ' + colors[2] +',  GradientType=1 )' ); // IE 10-
            var css3 = '-moz-linear-gradient(left,' + colorstops + ')'; // Firefox
            sliderElement.css('background-image', css3);

            sliderElement.find('.ui-widget-header').css({'background-color': '#FF8E00', 'background-image': 'none'}); // change the  original ranger color
          }
        } else {
          configObj.set('isIE9', true);
          configObj.set('isGreenOrangeRed', true);
        }
      }
    });
  },

  /**
   * @returns {number}
   */
  getInternetExplorerVersion: function () {
    var rv = -1; //return -1 for other browsers
    if (navigator.appName === 'Microsoft Internet Explorer') {
      var ua = navigator.userAgent;
      var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (re.exec(ua) != null) {
        rv = parseFloat(RegExp.$1); // IE version 1-10
      }
    }
    return rv;
  },

  /**
   * for widgets has hidden info(hover info),
   * calculate the hover content top number
   * based on how long the hiddenInfo is
   * @returns {string}
   */
  hoverContentTopClass: function () {
    var lineNum = this.get('hiddenInfo.length');
    if (lineNum === 2) {
      return "content-hidden-two-line";
    }
    if (lineNum === 3) {
      return "content-hidden-three-line";
    }
    if (lineNum === 4) {
      return "content-hidden-four-line";
    }
    if (lineNum === 5) {
      return "content-hidden-five-line";
    }
    if (lineNum === 6) {
      return "content-hidden-six-line";
    }
    return '';
  }.property('hiddenInfo.length')

});

App.DashboardWidgetView.reopenClass({
  class: 'span2p4'
});

redpajama_set_name: RedPajamaGithub


text:
CREATE TABLE ao_locks_table (a INT, b INT) WITH (appendonly=true) distributed by (a);
INSERT INTO ao_locks_table SELECT i as a, i as b FROM generate_series(1, 100) AS i;

create or replace view locktest_master as
select coalesce(
  case when relname like 'pg_toast%index' then 'toast index'
       when relname like 'pg_toast%' then 'toast table'
       when relname like 'pg_aoseg%' then 'aoseg table'
       when relname like 'pg_aovisimap%index' then 'aovisimap index'
       when relname like 'pg_aovisimap%' then 'aovisimap table'
       else relname end, 'dropped table'),
  mode,
  locktype,
  'master'::text as node
from pg_locks l
left outer join pg_class c on l.relation = c.oid,
pg_database d
where relation is not null
and l.database = d.oid
and (relname <> 'gp_fault_strategy' and relname != 'locktest_master' or relname is NULL)
and d.datname = current_database()
and l.gp_segment_id = -1
group by l.gp_segment_id, relation, relname, locktype, mode
order by 1, 3, 2;

create or replace view locktest_segments_dist as
select relname,
  mode,
  locktype,
  l.gp_segment_id as node,
  relation
from pg_locks l
left outer join pg_class c on l.relation = c.oid,
pg_database d
where relation is not null
and l.database = d.oid
and (relname <> 'gp_fault_strategy' and relname != 'locktest_segments_dist' or relname is NULL)
and d.datname = current_database()
and l.gp_segment_id > -1
group by l.gp_segment_id, relation, relname, locktype, mode;

create or replace view locktest_segments as
SELECT coalesce(
  case when relname like 'pg_toast%index' then 'toast index'
       when relname like 'pg_toast%' then 'toast table'
       when relname like 'pg_aoseg%' then 'aoseg table'
       when relname like 'pg_aovisimap%index' then 'aovisimap index'
       when relname like 'pg_aovisimap%' then 'aovisimap table'
       else relname end, 'dropped table'),
  mode,
  locktype,
  case when count(*) = 1 then '1 segment'
       else 'n segments' end as node
  FROM gp_dist_random('locktest_segments_dist')
  group by relname, relation, mode, locktype;

-- Actual test begins
BEGIN;
INSERT INTO ao_locks_table VALUES (200, 200);
SELECT * FROM locktest_master where coalesce = 'ao_locks_table' or
 coalesce like 'aovisimap%' or coalesce like 'aoseg%';
SELECT * FROM locktest_segments where coalesce = 'ao_locks_table' or
 coalesce like 'aovisimap%' or coalesce like 'aoseg%';
COMMIT;

BEGIN;
DELETE FROM ao_locks_table WHERE a = 1;
SELECT * FROM locktest_master where coalesce = 'ao_locks_table' or
 coalesce like 'aovisimap%' or coalesce like 'aoseg%';
SELECT * FROM locktest_segments where coalesce = 'ao_locks_table' or
 coalesce like 'aovisimap%' or coalesce like 'aoseg%';
COMMIT;

BEGIN;
UPDATE ao_locks_table SET b = -1 WHERE a = 2;
SELECT * FROM locktest_master where coalesce = 'ao_locks_table' or
 coalesce like 'aovisimap%' or coalesce like 'aoseg%';
SELECT * FROM locktest_segments where coalesce = 'ao_locks_table' or
 coalesce like 'aovisimap%' or coalesce like 'aoseg%';
COMMIT;


text:
from django import forms
from django.contrib import messages
from django.contrib.auth import authenticate, login

class LoginForm(forms.Form):
    login = forms.CharField(label=u'Логин')
    password = forms.CharField(label=u'Пароль', widget=forms.PasswordInput)

    def execute(self, request):
        cd = self.cleaned_data
        user = authenticate(username=cd['login'], password=cd['password'])
        if user is not None:
            if not user.is_active:
                messages.error(request, u'Пользователь не активен')
            else:
                login(request, user)
        else:
            messages.error(request, u'Пользователь с таким логином и паролем не найден')


text:
package org.apache.asterix.transaction.management.opcallbacks;

import org.apache.asterix.common.exceptions.ACIDException;
import org.apache.asterix.common.transactions.AbstractOperationCallback;
import org.apache.asterix.common.transactions.ILockManager;
import org.apache.asterix.common.transactions.ITransactionContext;
import org.apache.asterix.transaction.management.service.transaction.TransactionManagementConstants.LockManagerConstants.LockMode;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;
import org.apache.hyracks.storage.am.common.api.ISearchOperationCallback;

/**
 * Assumes LSM-BTrees as primary indexes. Implements try/locking and unlocking on primary keys.
 */
public class PrimaryIndexInstantSearchOperationCallback extends AbstractOperationCallback implements
        ISearchOperationCallback {

    public PrimaryIndexInstantSearchOperationCallback(int datasetId, int[] entityIdFields, ILockManager lockManager,
            ITransactionContext txnCtx) {
        super(datasetId, entityIdFields, txnCtx, lockManager);
    }

    @Override
    public boolean proceed(ITupleReference tuple) throws HyracksDataException {
        int pkHash = computePrimaryKeyHashValue(tuple, primaryKeyFields);
        try {
            return lockManager.instantTryLock(datasetId, pkHash, LockMode.S, txnCtx);
        } catch (ACIDException e) {
            throw new HyracksDataException(e);
        }
    }

    @Override
    public void reconcile(ITupleReference tuple) throws HyracksDataException {
        int pkHash = computePrimaryKeyHashValue(tuple, primaryKeyFields);
        try {
            lockManager.lock(datasetId, pkHash, LockMode.S, txnCtx);
        } catch (ACIDException e) {
            throw new HyracksDataException(e);
        }
    }

    @Override
    public void cancel(ITupleReference tuple) throws HyracksDataException {
        //no op
    }

    @Override
    public void complete(ITupleReference tuple) throws HyracksDataException {
        int pkHash = computePrimaryKeyHashValue(tuple, primaryKeyFields);
        try {
            lockManager.unlock(datasetId, pkHash, LockMode.S, txnCtx);
        } catch (ACIDException e) {
            throw new HyracksDataException(e);
        }
    }
}


text:
<Alloy>
	<Window class="container">
		<View id="postLandingView">
			<Widget src="navigationBar" id="navBar"/>
			<View id="postLandingViewBody">
				<ScrollView id="scroller">
					<View id="tableView">
						<View id="headerRow" class="autoHeight">
							<ImageView id="placeholderHeaderImage" class="headerImage"/>
						</View>
						<View id="socialMediaButtonsRow" class="autoHeight" autoStyle="true">
							<View id="centeredButtons" class="centeredButtons">
								<Button id="commentingButton" class="socialMediaButtonShown" onClick="comment" autoStyle="true"></Button>
								<Button id="shareTextButton" class="socialMediaButtonShown" onClick="shareText" autoStyle="true"></Button>
								<Button id="sharePhotoButton" class="socialMediaButtonShown" onClick="sharePhoto" autoStyle="true"></Button>
							</View>
						</View>
						<View id="postTitleView">

						</View>
						<WebView id="webView"></WebView>
						<View id="commentsHeading" onClick="comment" class="autoHeight">Add Comment</View>
						<View id="commentsView" class="autoHeight"></View>
						<View id="showMoreComments" class="autoHeight">Show more comments</View>
						<View id="noComments" class="autoHeight">There are no comments for this post</View>
					</View>
				</ScrollView>
				<View id="addNewCommentContainer"></View>
				<ScrollView id="commentsModal">
					<View id="submitCommentFormView">
						<TextField id="insertName" />
						*Optional and won't be shared
						<TextField id="insertEmail" />
						*Optional and won't be shared
						<TextArea id="insertComment"/>
						<View id="buttonView">
							<Button id="submitButton" onClick="clickSubmitComment" />
							<Button id="cancelCommentButton" onClick="clickCancelComment" />
						</View>
					</View>
					<View id="thankYouMessageView" onClick="clickThankYouMessage">

					</View>
					Submit Your Comment
				</ScrollView>
			</View>
		</View>
	</Window>
</Alloy>


text:
"""Tests for external_optimizer."""

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

import numpy as np
import tensorflow as tf

# pylint: disable=g-import-not-at-top,unused-import
try:
  import __builtin__ as builtins
except ImportError:
  import builtins

class MockOptimizerInterface(tf.contrib.opt.ExternalOptimizerInterface):

  NUM_STEP_CALLS = 5
  NUM_LOSS_CALLS = 2

  def _minimize(self, initial_val, loss_grad_func, step_callback,
                optimizer_kwargs, **unused_kwargs):
    """Minimize (x - x0)**2 / 2 with respect to x."""
    for _ in range(self.NUM_LOSS_CALLS):
      loss_grad_func(initial_val)
    for _ in range(self.NUM_STEP_CALLS):
      step_callback(initial_val)

    _, grad = loss_grad_func(initial_val)
    return initial_val - grad

class TestCase(tf.test.TestCase):

  def assertAllClose(self, array1, array2):
    array1 = np.asarray(array1)
    array2 = np.asarray(array2)
    if not array1.shape:
      array1 = np.array([array1])
    if not array2.shape:
      array2 = np.array([array2])

    super(TestCase, self).assertAllClose(array1, array2, rtol=1e-5, atol=1e-5)

class ExternalOptimizerInterfaceTest(TestCase):

  def test_optimize(self):
    scalar = tf.Variable(tf.random_normal([]), 'scalar')
    vector = tf.Variable(tf.random_normal([2]), 'vector')
    matrix = tf.Variable(tf.random_normal([2, 3]), 'matrix')

    minimum_location = tf.constant(np.arange(9), dtype=tf.float32)

    loss = tf.reduce_sum(tf.square(vector - minimum_location[:2])) / 2.
    loss += tf.reduce_sum(tf.square(scalar - minimum_location[2])) / 2.
    loss += tf.reduce_sum(tf.square(
        matrix - tf.reshape(minimum_location[3:], [2, 3]))) / 2.

    optimizer = MockOptimizerInterface(loss)

    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())

      optimizer.minimize(sess)

      self.assertAllClose(np.arange(2), sess.run(vector))
      self.assertAllClose(np.arange(1) + 2, sess.run(scalar))
      self.assertAllClose(np.arange(6).reshape(2, 3) + 3, sess.run(matrix))

  def test_callbacks(self):
    vector_val = np.array([7., -2.], dtype=np.float32)
    vector = tf.Variable(vector_val, 'vector')

    minimum_location_val = np.arange(2)
    minimum_location = tf.constant(minimum_location_val, dtype=tf.float32)

    loss = tf.reduce_sum(tf.square(vector - minimum_location)) / 2.
    loss_val = ((vector_val - minimum_location_val)**2).sum() / 2.

    optimizer = MockOptimizerInterface(loss)

    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())

      initial_vector_val = sess.run(vector)

      extra_fetches = [loss]

      step_callback = tf.test.mock.Mock()
      loss_callback = tf.test.mock.Mock()

      optimizer.minimize(
          sess, fetches=extra_fetches, loss_callback=loss_callback,
          step_callback=step_callback)

      call = tf.test.mock.call(loss_val)
      loss_calls = [call] * MockOptimizerInterface.NUM_LOSS_CALLS
      loss_callback.assert_has_calls(loss_calls)

      args, _ = step_callback.call_args
      self.assertAllClose(initial_vector_val, args[0])

class ScipyOptimizerInterfaceTest(TestCase):

  def test_unconstrained(self):

    def objective(x):
      """Rosenbrock function. (Carl Edward Rasmussen, 2001-07-21).

      f(x) = sum_{i=1:D-1} 100*(x(i+1) - x(i)^2)^2 + (1-x(i))^2

      Args:
        x: a Variable
      Returns:
        f: a tensor (objective value)
      """

      d = tf.size(x)
      s = tf.add(100 * tf.square(
          tf.sub(
              tf.strided_slice(x, [1], [d]),
              tf.square(tf.strided_slice(x, [0], [d - 1])))),
                 tf.square(tf.sub(1.0, tf.strided_slice(x, [0], [d - 1]))))
      return tf.reduce_sum(s)

    dimension = 5
    x = tf.Variable(tf.zeros(dimension))
    optimizer = tf.contrib.opt.ScipyOptimizerInterface(objective(x))

    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())
      optimizer.minimize(sess)

      self.assertAllClose(np.ones(dimension), sess.run(x))

  def test_nonlinear_programming(self):
    vector_initial_value = [7., 7.]
    vector = tf.Variable(vector_initial_value, 'vector')

    # Make norm as small as possible.
    loss = tf.reduce_sum(tf.square(vector))
    # Ensure y = 1.
    equalities = [vector[1] - 1.]
    # Ensure x >= 1. Thus optimum should be at (1, 1).
    inequalities = [vector[0] - 1.]

    optimizer = tf.contrib.opt.ScipyOptimizerInterface(
        loss, equalities=equalities, inequalities=inequalities,
        method='SLSQP')

    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())
      optimizer.minimize(sess)
      self.assertAllClose(np.ones(2), sess.run(vector))

if __name__ == '__main__':
  tf.test.main()