text:
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// This UI is only opened from the Extension Manager when the app is upgraded.

"use strict";

const PREF_UPDATE_EXTENSIONS_ENABLED            = "extensions.update.enabled";
const PREF_XPINSTALL_ENABLED                    = "xpinstall.enabled";

// timeout (in milliseconds) to wait for response to the metadata ping
const METADATA_TIMEOUT    = 30000;

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", "resource://gre/modules/AddonManager.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AddonManagerPrivate", "resource://gre/modules/AddonManager.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Services", "resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AddonRepository", "resource://gre/modules/addons/AddonRepository.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task", "resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Promise", "resource://gre/modules/Promise.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Log", "resource://gre/modules/Log.jsm");
var logger = null;

var gUpdateWizard = {
  // When synchronizing app compatibility info this contains all installed
  // add-ons. When checking for compatible versions this contains only
  // incompatible add-ons.
  addons: [],
  // Contains a Set of IDs for add-on that were disabled by the application update.
  affectedAddonIDs: null,
  // The add-ons that we found updates available for
  addonsToUpdate: [],
  shouldSuggestAutoChecking: false,
  shouldAutoCheck: false,
  xpinstallEnabled: true,
  xpinstallLocked: false,
  // cached AddonInstall entries for add-ons we might want to update,
  // keyed by add-on ID
  addonInstalls: new Map(),
  shuttingDown: false,
  // Count the add-ons disabled by this update, enabled/disabled by
  // metadata checks, and upgraded.
  disabled: 0,
  metadataEnabled: 0,
  metadataDisabled: 0,
  upgraded: 0,
  upgradeFailed: 0,
  upgradeDeclined: 0,

  init: function gUpdateWizard_init()
  {
    logger = Log.repository.getLogger("addons.update-dialog");
    // XXX could we pass the addons themselves rather than the IDs?
    this.affectedAddonIDs = new Set(window.arguments[0]);

    try {
      this.shouldSuggestAutoChecking =
        !Services.prefs.getBoolPref(PREF_UPDATE_EXTENSIONS_ENABLED);
    }
    catch (e) {
    }

    try {
      this.xpinstallEnabled = Services.prefs.getBoolPref(PREF_XPINSTALL_ENABLED);
      this.xpinstallLocked = Services.prefs.prefIsLocked(PREF_XPINSTALL_ENABLED);
    }
    catch (e) {
    }

    if (Services.io.offline)
      document.documentElement.currentPage = document.getElementById("offline");
    else
      document.documentElement.currentPage = document.getElementById("versioninfo");
  },

  onWizardFinish: function gUpdateWizard_onWizardFinish ()
  {
    if (this.shouldSuggestAutoChecking)
      Services.prefs.setBoolPref(PREF_UPDATE_EXTENSIONS_ENABLED, this.shouldAutoCheck);
  },

  _setUpButton: function gUpdateWizard_setUpButton(aButtonID, aButtonKey, aDisabled)
  {
    var strings = document.getElementById("updateStrings");
    var button = document.documentElement.getButton(aButtonID);
    if (aButtonKey) {
      button.label = strings.getString(aButtonKey);
      try {
        button.setAttribute("accesskey", strings.getString(aButtonKey + "Accesskey"));
      }
      catch (e) {
      }
    }
    button.disabled = aDisabled;
  },

  setButtonLabels: function gUpdateWizard_setButtonLabels(aBackButton, aBackButtonIsDisabled,
                             aNextButton, aNextButtonIsDisabled,
                             aCancelButton, aCancelButtonIsDisabled)
  {
    this._setUpButton("back", aBackButton, aBackButtonIsDisabled);
    this._setUpButton("next", aNextButton, aNextButtonIsDisabled);
    this._setUpButton("cancel", aCancelButton, aCancelButtonIsDisabled);
  },

  /////////////////////////////////////////////////////////////////////////////
  // Update Errors
  errorItems: [],

  checkForErrors: function gUpdateWizard_checkForErrors(aElementIDToShow)
  {
    if (this.errorItems.length > 0)
      document.getElementById(aElementIDToShow).hidden = false;
  },

  onWizardClose: function gUpdateWizard_onWizardClose(aEvent)
  {
    return this.onWizardCancel();
  },

  onWizardCancel: function gUpdateWizard_onWizardCancel()
  {
    gUpdateWizard.shuttingDown = true;
    // Allow add-ons to continue downloading and installing
    // in the background, though some may require a later restart
    // Pages that are waiting for user input go into the background
    // on cancel
    if (gMismatchPage.waiting) {
      logger.info("Dialog closed in mismatch page");
      if (gUpdateWizard.addonInstalls.size > 0) {
        gInstallingPage.startInstalls([i for ([, i] of gUpdateWizard.addonInstalls)]);
      }
      return true;
    }

    // Pages that do asynchronous things will just keep running and check
    // gUpdateWizard.shuttingDown to trigger background behaviour
    if (!gInstallingPage.installing) {
      logger.info("Dialog closed while waiting for updated compatibility information");
    }
    else {
      logger.info("Dialog closed while downloading and installing updates");
    }
    return true;
  }
};

var gOfflinePage = {
  onPageAdvanced: function gOfflinePage_onPageAdvanced()
  {
    Services.io.offline = false;
    return true;
  },

  toggleOffline: function gOfflinePage_toggleOffline()
  {
    var nextbtn = document.documentElement.getButton("next");
    nextbtn.disabled = !nextbtn.disabled;
  }
}

// Addon listener to count addons enabled/disabled by metadata checks
var listener = {
  onDisabled: function listener_onDisabled(aAddon) {
    gUpdateWizard.affectedAddonIDs.add(aAddon.id);
    gUpdateWizard.metadataDisabled++;
  },
  onEnabled: function listener_onEnabled(aAddon) {
    gUpdateWizard.affectedAddonIDs.delete(aAddon.id);
    gUpdateWizard.metadataEnabled++;
  }
};

var gVersionInfoPage = {
  _completeCount: 0,
  _totalCount: 0,
  _versionInfoDone: false,
  onPageShow: Task.async(function* gVersionInfoPage_onPageShow() {
    gUpdateWizard.setButtonLabels(null, true,
                                  "nextButtonText", true,
                                  "cancelButtonText", false);

    gUpdateWizard.disabled = gUpdateWizard.affectedAddonIDs.size;

    // Ensure compatibility overrides are up to date before checking for
    // individual addon updates.
    AddonManager.addAddonListener(listener);
    if (AddonRepository.isMetadataStale()) {
      // Do the metadata ping, listening for any newly enabled/disabled add-ons.
      yield AddonRepository.repopulateCache(METADATA_TIMEOUT);
      if (gUpdateWizard.shuttingDown) {
        logger.debug("repopulateCache completed after dialog closed");
      }
    }
    // Fetch the add-ons that are still affected by this update,
    // excluding the hotfix add-on.
    let idlist = [id for (id of gUpdateWizard.affectedAddonIDs)
                     if (id != AddonManager.hotfixID)];
    if (idlist.length < 1) {
      gVersionInfoPage.onAllUpdatesFinished();
      return;
    }

    logger.debug("Fetching affected addons " + idlist.toSource());
    let fetchedAddons = yield new Promise((resolve, reject) =>
      AddonManager.getAddonsByIDs(idlist, resolve));
    // We shouldn't get nulls here, but let's be paranoid...
    gUpdateWizard.addons = [a for (a of fetchedAddons) if (a)];
    if (gUpdateWizard.addons.length < 1) {
      gVersionInfoPage.onAllUpdatesFinished();
      return;
    }

    gVersionInfoPage._totalCount = gUpdateWizard.addons.length;

    for (let addon of gUpdateWizard.addons) {
      logger.debug("VersionInfo Finding updates for ${id}", addon);
      addon.findUpdates(gVersionInfoPage, AddonManager.UPDATE_WHEN_NEW_APP_INSTALLED);
    }
  }),

  onAllUpdatesFinished: function gVersionInfoPage_onAllUpdatesFinished() {
    AddonManager.removeAddonListener(listener);
    AddonManagerPrivate.recordSimpleMeasure("appUpdate_disabled",
        gUpdateWizard.disabled);
    AddonManagerPrivate.recordSimpleMeasure("appUpdate_metadata_enabled",
        gUpdateWizard.metadataEnabled);
    AddonManagerPrivate.recordSimpleMeasure("appUpdate_metadata_disabled",
        gUpdateWizard.metadataDisabled);
    // Record 0 for these here in case we exit early; values will be replaced
    // later if we actually upgrade any.
    AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgraded", 0);
    AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeFailed", 0);
    AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeDeclined", 0);
    // Filter out any add-ons that are now enabled.
    logger.debug("VersionInfo updates finished: found " +
         [addon.id + ":" + addon.appDisabled for (addon of gUpdateWizard.addons)].toSource());
    let filteredAddons = [];
    for (let a of gUpdateWizard.addons) {
      if (a.appDisabled) {
        logger.debug("Continuing with add-on " + a.id);
        filteredAddons.push(a);
      }
      else if (gUpdateWizard.addonInstalls.has(a.id)) {
        gUpdateWizard.addonInstalls.get(a.id).cancel();
        gUpdateWizard.addonInstalls.delete(a.id);
      }
    }
    gUpdateWizard.addons = filteredAddons;

    if (gUpdateWizard.shuttingDown) {
      // jump directly to updating auto-update add-ons in the background
      if (gUpdateWizard.addonInstalls.size > 0) {
        gInstallingPage.startInstalls([i for ([, i] of gUpdateWizard.addonInstalls)]);
      }
      return;
    }

    if (filteredAddons.length > 0) {
      if (!gUpdateWizard.xpinstallEnabled && gUpdateWizard.xpinstallLocked) {
        document.documentElement.currentPage = document.getElementById("adminDisabled");
        return;
      }
      document.documentElement.currentPage = document.getElementById("mismatch");
    }
    else {
      logger.info("VersionInfo: No updates require further action");
      // VersionInfo compatibility updates resolved all compatibility problems,
      // close this window and continue starting the application...
      //XXX Bug 314754 - We need to use setTimeout to close the window due to
      // the EM using xmlHttpRequest when checking for updates.
      setTimeout(close, 0);
    }
  },

  /////////////////////////////////////////////////////////////////////////////
  // UpdateListener
  onUpdateFinished: function gVersionInfoPage_onUpdateFinished(aAddon, status) {
    ++this._completeCount;

    if (status != AddonManager.UPDATE_STATUS_NO_ERROR) {
      logger.debug("VersionInfo update " + this._completeCount + " of " + this._totalCount +
           " failed for " + aAddon.id + ": " + status);
      gUpdateWizard.errorItems.push(aAddon);
    }
    else {
      logger.debug("VersionInfo update " + this._completeCount + " of " + this._totalCount +
           " finished for " + aAddon.id);
    }

    // If we're not in the background, just make a list of add-ons that have
    // updates available
    if (!gUpdateWizard.shuttingDown) {
      // If we're still in the update check window and the add-on is now active
      // then it won't have been disabled by startup
      if (aAddon.active) {
        AddonManagerPrivate.removeStartupChange(AddonManager.STARTUP_CHANGE_DISABLED, aAddon.id);
        gUpdateWizard.metadataEnabled++;
      }

      // Update the status text and progress bar
      var updateStrings = document.getElementById("updateStrings");
      var statusElt = document.getElementById("versioninfo.status");
      var statusString = updateStrings.getFormattedString("statusPrefix", [aAddon.name]);
      statusElt.setAttribute("value", statusString);

      // Update the status text and progress bar
      var progress = document.getElementById("versioninfo.progress");
      progress.mode = "normal";
      progress.value = Math.ceil((this._completeCount / this._totalCount) * 100);
    }

    if (this._completeCount == this._totalCount)
      this.onAllUpdatesFinished();
  },

  onUpdateAvailable: function gVersionInfoPage_onUpdateAvailable(aAddon, aInstall) {
    logger.debug("VersionInfo got an install for " + aAddon.id + ": " + aAddon.version);
    gUpdateWizard.addonInstalls.set(aAddon.id, aInstall);
  },
};

var gMismatchPage = {
  waiting: false,

  onPageShow: function gMismatchPage_onPageShow()
  {
    gMismatchPage.waiting = true;
    gUpdateWizard.setButtonLabels(null, true,
                                  "mismatchCheckNow", false,
                                  "mismatchDontCheck", false);
    document.documentElement.getButton("next").focus();

    var incompatible = document.getElementById("mismatch.incompatible");
    for (let addon of gUpdateWizard.addons) {
      var listitem = document.createElement("listitem");
      listitem.setAttribute("label", addon.name + " " + addon.version);
      incompatible.appendChild(listitem);
    }
  }
};

var gUpdatePage = {
  _totalCount: 0,
  _completeCount: 0,
  onPageShow: function gUpdatePage_onPageShow()
  {
    gMismatchPage.waiting = false;
    gUpdateWizard.setButtonLabels(null, true,
                                  "nextButtonText", true,
                                  "cancelButtonText", false);
    document.documentElement.getButton("next").focus();

    gUpdateWizard.errorItems = [];

    this._totalCount = gUpdateWizard.addons.length;
    for (let addon of gUpdateWizard.addons) {
      logger.debug("UpdatePage requesting update for " + addon.id);
      // Redundant call to find updates again here when we already got them
      // in the VersionInfo page: https://bugzilla.mozilla.org/show_bug.cgi?id=960597
      addon.findUpdates(this, AddonManager.UPDATE_WHEN_NEW_APP_INSTALLED);
    }
  },

  onAllUpdatesFinished: function gUpdatePage_onAllUpdatesFinished() {
    if (gUpdateWizard.shuttingDown)
      return;

    var nextPage = document.getElementById("noupdates");
    if (gUpdateWizard.addonsToUpdate.length > 0)
      nextPage = document.getElementById("found");
    document.documentElement.currentPage = nextPage;
  },

  /////////////////////////////////////////////////////////////////////////////
  // UpdateListener
  onUpdateAvailable: function gUpdatePage_onUpdateAvailable(aAddon, aInstall) {
    logger.debug("UpdatePage got an update for " + aAddon.id + ": " + aAddon.version);
    gUpdateWizard.addonsToUpdate.push(aInstall);
  },

  onUpdateFinished: function gUpdatePage_onUpdateFinished(aAddon, status) {
    if (status != AddonManager.UPDATE_STATUS_NO_ERROR)
      gUpdateWizard.errorItems.push(aAddon);

    ++this._completeCount;

    if (!gUpdateWizard.shuttingDown) {
      // Update the status text and progress bar
      var updateStrings = document.getElementById("updateStrings");
      var statusElt = document.getElementById("checking.status");
      var statusString = updateStrings.getFormattedString("statusPrefix", [aAddon.name]);
      statusElt.setAttribute("value", statusString);

      var progress = document.getElementById("checking.progress");
      progress.value = Math.ceil((this._completeCount / this._totalCount) * 100);
    }

    if (this._completeCount == this._totalCount)
      this.onAllUpdatesFinished()
  },
};

var gFoundPage = {
  onPageShow: function gFoundPage_onPageShow()
  {
    gUpdateWizard.setButtonLabels(null, true,
                                  "installButtonText", false,
                                  null, false);

    var foundUpdates = document.getElementById("found.updates");
    var itemCount = gUpdateWizard.addonsToUpdate.length;
    for (let install of gUpdateWizard.addonsToUpdate) {
      let listItem = foundUpdates.appendItem(install.name + " " + install.version);
      listItem.setAttribute("type", "checkbox");
      listItem.setAttribute("checked", "true");
      listItem.install = install;
    }

    if (!gUpdateWizard.xpinstallEnabled) {
      document.getElementById("xpinstallDisabledAlert").hidden = false;
      document.getElementById("enableXPInstall").focus();
      document.documentElement.getButton("next").disabled = true;
    }
    else {
      document.documentElement.getButton("next").focus();
      document.documentElement.getButton("next").disabled = false;
    }
  },

  toggleXPInstallEnable: function gFoundPage_toggleXPInstallEnable(aEvent)
  {
    var enabled = aEvent.target.checked;
    gUpdateWizard.xpinstallEnabled = enabled;
    var pref = Components.classes["@mozilla.org/preferences-service;1"]
                         .getService(Components.interfaces.nsIPrefBranch);
    pref.setBoolPref(PREF_XPINSTALL_ENABLED, enabled);
    this.updateNextButton();
  },

  updateNextButton: function gFoundPage_updateNextButton()
  {
    if (!gUpdateWizard.xpinstallEnabled) {
      document.documentElement.getButton("next").disabled = true;
      return;
    }

    var oneChecked = false;
    var foundUpdates = document.getElementById("found.updates");
    var updates = foundUpdates.getElementsByTagName("listitem");
    for (let update of updates) {
      if (!update.checked)
        continue;
      oneChecked = true;
      break;
    }

    gUpdateWizard.setButtonLabels(null, true,
                                  "installButtonText", true,
                                  null, false);
    document.getElementById("found").setAttribute("next", "installing");
    document.documentElement.getButton("next").disabled = !oneChecked;
  }
};

var gInstallingPage = {
  _installs         : [],
  _errors           : [],
  _strings          : null,
  _currentInstall   : -1,
  _installing       : false,

  // Initialize fields we need for installing and tracking progress,
  // and start iterating through the installations
  startInstalls: function gInstallingPage_startInstalls(aInstallList) {
    if (!gUpdateWizard.xpinstallEnabled) {
      return;
    }

    logger.debug("Start installs for "
                 + [i.existingAddon.id for (i of aInstallList)].toSource());
    this._errors = [];
    this._installs = aInstallList;
    this._installing = true;
    this.startNextInstall();
  },

  onPageShow: function gInstallingPage_onPageShow()
  {
    gUpdateWizard.setButtonLabels(null, true,
                                  "nextButtonText", true,
                                  null, true);

    var foundUpdates = document.getElementById("found.updates");
    var updates = foundUpdates.getElementsByTagName("listitem");
    let toInstall = [];
    for (let update of updates) {
      if (!update.checked) {
        logger.info("User chose to cancel update of " + update.label);
        gUpdateWizard.upgradeDeclined++;
        update.install.cancel();
        continue;
      }
      toInstall.push(update.install);
    }
    this._strings = document.getElementById("updateStrings");

    this.startInstalls(toInstall);
  },

  startNextInstall: function gInstallingPage_startNextInstall() {
    if (this._currentInstall >= 0) {
      this._installs[this._currentInstall].removeListener(this);
    }

    this._currentInstall++;

    if (this._installs.length == this._currentInstall) {
      Services.obs.notifyObservers(null, "TEST:all-updates-done", null);
      AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgraded",
          gUpdateWizard.upgraded);
      AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeFailed",
          gUpdateWizard.upgradeFailed);
      AddonManagerPrivate.recordSimpleMeasure("appUpdate_upgradeDeclined",
          gUpdateWizard.upgradeDeclined);
      this._installing = false;
      if (gUpdateWizard.shuttingDown) {
        return;
      }
      var nextPage = this._errors.length > 0 ? "installerrors" : "finished";
      document.getElementById("installing").setAttribute("next", nextPage);
      document.documentElement.advance();
      return;
    }

    let install = this._installs[this._currentInstall];

    if (gUpdateWizard.shuttingDown && !AddonManager.shouldAutoUpdate(install.existingAddon)) {
      logger.debug("Don't update " + install.existingAddon.id + " in background");
      gUpdateWizard.upgradeDeclined++;
      install.cancel();
      this.startNextInstall();
      return;
    }
    install.addListener(this);
    install.install();
  },

  /////////////////////////////////////////////////////////////////////////////
  // InstallListener
  onDownloadStarted: function gInstallingPage_onDownloadStarted(aInstall) {
    if (gUpdateWizard.shuttingDown) {
      return;
    }
    var strings = document.getElementById("updateStrings");
    var label = strings.getFormattedString("downloadingPrefix", [aInstall.name]);
    var actionItem = document.getElementById("actionItem");
    actionItem.value = label;
  },

  onDownloadProgress: function gInstallingPage_onDownloadProgress(aInstall) {
    if (gUpdateWizard.shuttingDown) {
      return;
    }
    var downloadProgress = document.getElementById("downloadProgress");
    downloadProgress.value = Math.ceil(100 * aInstall.progress / aInstall.maxProgress);
  },

  onDownloadEnded: function gInstallingPage_onDownloadEnded(aInstall) {
  },

  onDownloadFailed: function gInstallingPage_onDownloadFailed(aInstall) {
    this._errors.push(aInstall);

    gUpdateWizard.upgradeFailed++;
    this.startNextInstall();
  },

  onInstallStarted: function gInstallingPage_onInstallStarted(aInstall) {
    if (gUpdateWizard.shuttingDown) {
      return;
    }
    var strings = document.getElementById("updateStrings");
    var label = strings.getFormattedString("installingPrefix", [aInstall.name]);
    var actionItem = document.getElementById("actionItem");
    actionItem.value = label;
  },

  onInstallEnded: function gInstallingPage_onInstallEnded(aInstall, aAddon) {
    if (!gUpdateWizard.shuttingDown) {
      // Remember that this add-on was updated during startup
      AddonManagerPrivate.addStartupChange(AddonManager.STARTUP_CHANGE_CHANGED,
                                           aAddon.id);
    }

    gUpdateWizard.upgraded++;
    this.startNextInstall();
  },

  onInstallFailed: function gInstallingPage_onInstallFailed(aInstall) {
    this._errors.push(aInstall);

    gUpdateWizard.upgradeFailed++;
    this.startNextInstall();
  }
};

var gInstallErrorsPage = {
  onPageShow: function gInstallErrorsPage_onPageShow()
  {
    gUpdateWizard.setButtonLabels(null, true, null, true, null, true);
    document.documentElement.getButton("finish").focus();
  },
};

// Displayed when there are incompatible add-ons and the xpinstall.enabled
// pref is false and locked.
var gAdminDisabledPage = {
  onPageShow: function gAdminDisabledPage_onPageShow()
  {
    gUpdateWizard.setButtonLabels(null, true, null, true,
                                  "cancelButtonText", true);
    document.documentElement.getButton("finish").focus();
  }
};

// Displayed when selected add-on updates have been installed without error.
// There can still be add-ons that are not compatible and don't have an update.
var gFinishedPage = {
  onPageShow: function gFinishedPage_onPageShow()
  {
    gUpdateWizard.setButtonLabels(null, true, null, true, null, true);
    document.documentElement.getButton("finish").focus();

    if (gUpdateWizard.shouldSuggestAutoChecking) {
      document.getElementById("finishedCheckDisabled").hidden = false;
      gUpdateWizard.shouldAutoCheck = true;
    }
    else
      document.getElementById("finishedCheckEnabled").hidden = false;

    document.documentElement.getButton("finish").focus();
  }
};

// Displayed when there are incompatible add-ons and there are no available
// updates.
var gNoUpdatesPage = {
  onPageShow: function gNoUpdatesPage_onPageLoad(aEvent)
  {
    gUpdateWizard.setButtonLabels(null, true, null, true, null, true);
    if (gUpdateWizard.shouldSuggestAutoChecking) {
      document.getElementById("noupdatesCheckDisabled").hidden = false;
      gUpdateWizard.shouldAutoCheck = true;
    }
    else
      document.getElementById("noupdatesCheckEnabled").hidden = false;

    gUpdateWizard.checkForErrors("updateCheckErrorNotFound");
    document.documentElement.getButton("finish").focus();
  }
};


text:
@interface PKTHTTPClientTests : XCTestCase

@property (nonatomic, strong) PKTHTTPClient *testClient;

@end

@implementation PKTHTTPClientTests

- (void)setUp {
  [super setUp];
  self.testClient = [PKTHTTPClient new];
}

- (void)tearDown {
  self.testClient = nil;
  [Expecta setAsynchronousTestTimeout:1];
  [super tearDown];
}

#pragma mark - Tests

- (void)testInit {
  PKTHTTPClient *client = [PKTHTTPClient new];
  expect([client.baseURL absoluteString]).to.equal(@"https://api.podio.com");
}

- (void)testPerformSuccessfulRequest {
  NSString *path = @"/user/status";
  PKTRequest *request = [PKTRequest GETRequestWithPath:path parameters:@{@"param1": @"someValue", @"param2": @"someOtherValue"}];

  [PKTHTTPStubs stubResponseForPath:path statusCode:200];

  __block BOOL completed = NO;
  NSURLSessionTask *task = [self.testClient taskForRequest:request progress:nil completion:^(PKTResponse *result, NSError *error) {
    if (!error) {
      completed = YES;
    }
  }];

  [task resume];

  expect(task).notTo.beNil();
  expect(completed).will.beTruthy();
}

- (void)testPerformUnsuccessfulRequest {
  NSString *path = @"/user/status";
  PKTRequest *request = [PKTRequest GETRequestWithPath:path parameters:@{@"param1": @"someValue", @"param2": @"someOtherValue"}];

  [PKTHTTPStubs stubResponseForPath:path statusCode:500];

  __block BOOL errorOccured = NO;
  NSURLSessionTask *task = [self.testClient taskForRequest:request progress:nil completion:^(PKTResponse *result, NSError *error) {
    if (error) {
      errorOccured = YES;
    }
  }];

  [task resume];

  expect(errorOccured).will.beTruthy();
}

- (void)testTimeoutRequest {
  NSString *path = @"/user/status";
  PKTRequest *request = [PKTRequest GETRequestWithPath:path parameters:@{@"param1": @"someValue", @"param2": @"someOtherValue"}];

  [Expecta setAsynchronousTestTimeout:5];
  [PKTHTTPStubs stubResponseForPath:path requestTime:2 responseTime:0];

  __block BOOL completed = NO;
  NSURLSessionTask *task = [self.testClient taskForRequest:request progress:nil completion:^(PKTResponse *result, NSError *error) {
    completed = YES;
  }];

  [task resume];

  expect(completed).will.beFalsy();
}

- (void)testCancelRequest {
  NSString *path = @"/user/status";
  PKTRequest *request = [PKTRequest GETRequestWithPath:path parameters:@{@"param1": @"someValue", @"param2": @"someOtherValue"}];

  [Expecta setAsynchronousTestTimeout:5];
  [PKTHTTPStubs stubResponseForPath:path requestTime:5 responseTime:0];

  __block BOOL cancelled = NO;
  NSURLSessionTask *task = [self.testClient taskForRequest:request progress:nil completion:^(PKTResponse *result, NSError *error) {
    if (error.code == NSURLErrorCancelled) {
      cancelled = YES;
    }
  }];

  [task resume];

  expect(task).notTo.beNil();

  [task cancel];

  expect(cancelled).will.beTruthy();
}

- (void)testSuspendRequest {
  NSString *path = @"/user/status";
  PKTRequest *request = [PKTRequest GETRequestWithPath:path parameters:@{@"param1": @"someValue", @"param2": @"someOtherValue"}];

  [Expecta setAsynchronousTestTimeout:5];
  [PKTHTTPStubs stubResponseForPath:path requestTime:5 responseTime:0];

  __block BOOL completed = NO;
  NSURLSessionTask *task = [self.testClient taskForRequest:request progress:nil completion:^(PKTResponse *result, NSError *error) {
    completed = YES;
  }];

  [task resume];
  expect(task).notTo.beNil();

  [task suspend];
  expect(completed).will.beFalsy();
}

- (void)testResumeRequest {
  NSString *path = @"/user/status";
  PKTRequest *request = [PKTRequest GETRequestWithPath:path parameters:@{@"param1": @"someValue", @"param2": @"someOtherValue"}];

  [Expecta setAsynchronousTestTimeout:5];
  [PKTHTTPStubs stubResponseForPath:path requestTime:2 responseTime:0];

  __block BOOL completed = NO;
  NSURLSessionTask *task = [self.testClient taskForRequest:request progress:nil completion:^(PKTResponse *result, NSError *error) {
    completed = YES;
  }];

  [task resume];
  expect(task).notTo.beNil();

  [task suspend];
  expect(completed).will.beFalsy();

  wait(1);

  [task resume];
  expect(completed).will.beTruthy();
}

- (void)testReturnsServerError {
  NSString *path = @"/some/path";
  PKTRequest *request = [PKTRequest GETRequestWithPath:path parameters:nil];

  [PKTHTTPStubs stubResponseForPath:path block:^(PKTHTTPStubber *stubber) {
    stubber.statusCode = 400;
    stubber.responseObject = @{
      @"error" : @"invalid_grant",
      @"error_description" : @"The username is not valid",
      @"error_detail" : @"user.invalid.username",
      @"error_parameters" : @{},
      @"error_propagate" : @1
      };
  }];

  __block BOOL completed = NO;
  __block NSError *serverError = nil;
  NSURLSessionTask *task = [self.testClient taskForRequest:request progress:nil completion:^(PKTResponse *result, NSError *error) {
    completed = YES;
    serverError = error;
  }];

  [task resume];
  expect(completed).will.beTruthy();
  expect(serverError.domain).to.equal(PodioServerErrorDomain);
  expect(serverError.code).to.equal(400);
}

- (void)testDownloadRequestIsDownloadTask {
  PKTRequest *request = [PKTRequest GETRequestWithURL:[NSURL URLWithString:@"https://files.podio.com/111111"] parameters:nil];
  request.fileData = [PKTRequestFileData fileDataWithFilePath:@"/tmp/file.pdf" name:nil fileName:nil];

  id task = [self.testClient taskForRequest:request progress:nil completion:nil];
  expect(task).to.beKindOf([NSURLSessionDownloadTask class]);
}

- (void)testSetUserAgent {
  NSString *userAgent = @"Some user agent";
  self.testClient.userAgent = userAgent;
  expect([self.testClient.requestSerializer valueForHTTPHeader:PKTRequestSerializerHTTPHeaderKeyUserAgent]).to.equal(userAgent);
  expect(self.testClient.userAgent).to.equal(userAgent);

  userAgent = @"Some other user agent";
  [self.testClient.requestSerializer setUserAgentHeader:userAgent];
  expect(self.testClient.userAgent).to.equal(userAgent);
}

@end

redpajama_set_name: RedPajamaGithub


text:
export const input = {
  type: {
    type: String,
    default: 'date'
  },
  min: {
    type: String,
    default: ''
  },
  max: {
    type: String,
    default: ''
  },
  format: String,
  noClear: Boolean,
  clearLabel: {
    type: String,
    default: 'Clear'
  },
  okLabel: {
    type: String,
    default: 'Set'
  },
  cancelLabel: {
    type: String,
    default: 'Cancel'
  },
  defaultSelection: String,
  label: String,
  placeholder: String,
  staticLabel: String,
  readonly: Boolean,
  disable: Boolean
}

export const inline = {
  value: {
    type: String,
    required: true
  },
  type: {
    type: String,
    default: 'date',
    validator (value) {
      return ['date', 'time', 'datetime'].includes(value)
    }
  },
  min: {
    type: String,
    default: ''
  },
  max: {
    type: String,
    default: ''
  },
  readonly: Boolean,
  disable: Boolean
}


text:
name             "postgresql"
maintainer        "Opscode, Inc."
maintainer_email  "cookbooks@opscode.com"
license           "Apache 2.0"
description       "Installs and configures postgresql for clients or servers"
long_description  IO.read(File.join(File.dirname(__FILE__), 'README.md'))

version           "1.0.3"
recipe            "postgresql", "Includes postgresql::client"
recipe            "postgresql::apt_postgresql_ppa ", "Includes ubuntu sources for PostgreSQL 9.1"
recipe            "postgresql::client", "Installs postgresql client package(s)"
recipe            "postgresql::server", "Installs postgresql server packages, templates"
recipe            "postgresql::server_redhat", "Installs postgresql server packages, redhat family style"
recipe            "postgresql::server_debian", "Installs postgresql server packages, debian family style"
recipe            "postgresql::setup", "Create users/databases from data bags"

%w{ ubuntu debian fedora suse }.each do |os|
  supports os
end

%w{redhat centos scientific}.each do |el|
  supports el, ">= 6.0"
end

depends "apt"
depends "openssl"


text:
#ifndef SRC_TRACED_PROBES_FTRACE_DISCOVER_VENDOR_TRACEPOINTS_H_
#define SRC_TRACED_PROBES_FTRACE_DISCOVER_VENDOR_TRACEPOINTS_H_

#include <map>
#include <string>
#include <vector>

#include "src/traced/probes/ftrace/atrace_hal_wrapper.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "src/traced/probes/ftrace/proto_translation_table.h"

namespace perfetto {
namespace vendor_tracepoints {

// Exposed for testing.
std::vector<GroupAndName> DiscoverTracepoints(AtraceHalWrapper* hal,
                                              FtraceProcfs* ftrace,
                                              const std::string& category);

// Returns a map from vendor category to events we should enable
std::map<std::string, std::vector<GroupAndName>> DiscoverVendorTracepoints(
    AtraceHalWrapper* hal,
    FtraceProcfs* ftrace);

}  // namespace vendor_tracepoints
}  // namespace perfetto

#endif  // SRC_TRACED_PROBES_FTRACE_DISCOVER_VENDOR_TRACEPOINTS_H_


text:
module Spree
  class SelfDeliveryPoint < ActiveRecord::Base

    belongs_to :country
    belongs_to :state

    acts_as_list
    scope :ordered, order("#{SelfDeliveryPoint.table_name}.position ASC")

    validates :country, :city, :address1, :presence => true
    validate :state_or_state_name

    attr_accessible :country_id, :show_country, :state_id, :state_name, :show_state, :city, :address1, :hours, :description, :cost

    def full_address
      addr = []
      addr << country.try(:name) if show_country
      addr << (state.try(:name).presence || state_name) if show_state
      addr << address1
      addr.compact.join(', ')
    end

    private

    def state_or_state_name
      return unless country.present?
      if country.states.exists?
        self.state_name = nil
        errors.add(:state, :invalid) if state.blank? || state.country_id != country.id
      else
        self.state_id = nil
        errors.add(:state, :invalid) if state_name.blank?
      end
    end
  end
end


text:
title: Logic and Philosophy
author: Yogesh Bailwal
layout: post
permalink: /logic-and-philosophy/
blogger_blog:
  - www.philosophyinlife.info
blogger_permalink:
  - /2008/12/logic-and-philosophy.html
ks_metadata:
  - 'a:7:{s:4:"lang";s:2:"en";s:8:"keywords";s:0:"";s:19:"keywords_autoupdate";s:1:"0";s:11:"description";s:0:"";s:22:"description_autoupdate";s:1:"0";s:5:"title";s:0:"";s:6:"robots";s:12:"index,follow";}'
wpsd_autopost:
  - 1
wpr-options:
  - YToxOntpOjE7YToxMDp7czozOiJuaWQiO3M6MToiMSI7czo3OiJzdWJqZWN0IjtzOjA6IiI7czo4OiJ0ZXh0Ym9keSI7czowOiIiO3M6ODoiaHRtbGJvZHkiO3M6MDoiIjtzOjc6ImRpc2FibGUiO2k6MDtzOjE1OiJub2N1c3RvbWl6YXRpb24iO2k6MTtzOjEyOiJub3Bvc3RzZXJpZXMiO2k6MTtzOjEwOiJodG1sZW5hYmxlIjtpOjE7czoxMjoiYXR0YWNoaW1hZ2VzIjtpOjE7czoyMToic2tpcGFjdGl2ZXN1YnNjcmliZXJzIjtpOjA7fX0=
categories:
  - Life
  - Philosophy
  - Positive Thinking
tags:
  - blog philosophy
  - logic and philosophy
  - logic philosophy
  - logical philosophy
  - moral philosophy
  - philosophy happiness
  - philosophy in life
  - soul of philosophy
---

  Logic and Philosophy are two sides of a coin, philosophy is a logical reasoning of ethical behavior or we can say logically interpreted moral values create a philosophy. Philosophy exists because it is based on the firm ground of logic. Philosophy is appreciated because it teaches moral values logically in a form which is easily grasped by most of us.

  What is a logical philosophy? What is the importance of philosophy and its logical answers?

  A life based on a logical philosophy is far more better than a life with no philosophy or logic. Philosophy tries to answer, common questions that often come to our mind. These questions can be very disturbing and need to be immediately answered. If these questions remain unanswered then our overall efficiency in life will decrease to some extent, our energy level will decrease, our charm for life will head downward. Answer to all such questions that exist in our mind, these questions have no real meaning and are practically of no real value but these questions play very important role in society, they have role in family, in health and wellness of a person.

  All this questions are answered by philosophy, a logical reasoning for our behavior. Philosophy is not a indigestible hard fact, something which is like concrete, hard and unaccommodating. Philosophy is soft easily digestible, logical answer to our most common question. More information on theoretical aspect of Philosophy of Logic can be read at wiki.

  Can philosophy exist without logic?

  Contd…in….next…post of this philosophy blog with title ‘Can philosophy exist without logic?‘


text:
ActiveRecord::NamedScope::Scope.class_eval do
  private
  def load_found(*args)
    @found = find(:all, :eager => true)
  end
end


text:
import Application from './electron/application';

new Application();


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Jarvis.Framework.Shared.Helpers
{
    public static class FastReflectionHelper
    {
        /// <summary>
        /// http://rogeralsing.com/2008/02/28/linq-expressions-creating-objects/
        /// </summary>
        /// <param name="ctor"></param>
        /// <returns></returns>
        public static ObjectActivator GetActivator(ConstructorInfo ctor)
        {
            ParameterInfo[] paramsInfo = ctor.GetParameters();

            //create a single param of type object[]
            ParameterExpression param =
                Expression.Parameter(typeof(object[]), "args");

            Expression[] argsExp =
                new Expression[paramsInfo.Length];

            //pick each arg from the params array
            //and create a typed expression of them
            for (int i = 0; i < paramsInfo.Length; i++)
            {
                Expression index = Expression.Constant(i);
                Type paramType = paramsInfo[i].ParameterType;

                Expression paramAccessorExp =
                    Expression.ArrayIndex(param, index);

                Expression paramCastExp =
                    Expression.Convert(paramAccessorExp, paramType);

                argsExp[i] = paramCastExp;
            }

            //make a NewExpression that calls the
            //ctor with the args we just created
            NewExpression newExp = Expression.New(ctor, argsExp);

            //create a lambda with the New
            //Expression as body and our param object[] as arg
            LambdaExpression lambda =
                Expression.Lambda(typeof(ObjectActivator), newExp, param);

            //compile it
            ObjectActivator compiled = (ObjectActivator)lambda.Compile();
            return compiled;
        }

        public delegate object ObjectActivator(params object[] args);
    }
}


text:
<?php
namespace Lucid\Task;

class Generate extends Task implements TaskInterface
{
    public static $trigger = 'generate';

    public function __construct()
    {
        $this->parameters[] = new \Lucid\Task\Parameter('name', 'unlabeled', false, null);
        $this->parameters[] = new \Lucid\Task\Parameter('table', 'unlabeled', false, null);
        $this->parameters[] = new \Lucid\Task\Parameter('no-model', 'flag', true, false);
        $this->parameters[] = new \Lucid\Task\Parameter('no-view', 'flag', true, false);
        $this->parameters[] = new \Lucid\Task\Parameter('no-controller', 'flag', true, false);
        $this->parameters[] = new \Lucid\Task\Parameter('no-helper', 'flag', true, false);
        $this->parameters[] = new \Lucid\Task\Parameter('no-ruleset', 'flag', true, false);
        $this->parameters[] = new \Lucid\Task\Parameter('no-test', 'flag', true, false);
        $this->parameters[] = new \Lucid\Task\Parameter('no-dictionary', 'flag', true, false);
    }

    public function run()
    {
        include(getcwd().'/bootstrap.php');

        if (preg_match('#^\p{Lu}#u', $this->config['name']) === 0){
            echo("Error: parameter name must be camel-case. At a minimum, it must start with a capital letter.\n");
            \Lucid\Task\Container::run('usage', [static::$trigger]);
            exit();
        }
        $this->config['meta'] = new \Lucid\Library\Metabase\Metabase(\ORM::get_db());

        if (is_null($this->config['table']) === true) {
            $this->config['table'] = $this->config['name'];
        }
        $this->config['columns'] = $this->config['meta']->getColumns($this->config['table']);

        $this->config['keys'] = [
            'name'=>$this->config['name'],
            'table'=>$this->config['table'],
            'id_type'=>$this->config['columns'][0]['type'],
    	    'id'=>$this->config['columns'][0]['name'],
    		'first_string_col'=>null,
            'title'=>$this->config['name'],
        ];

        foreach($this->config['columns'] as $column) {
    		if ($column['type'] == 'string' && is_null($this->config['keys']['first_string_col']) === true) {
    			$this->config['keys']['first_string_col'] = $column['name'];
    		}
    	}

        # we always run all *BuildKeys methods in case a later *BuildFile function relies on a key built by
        # a component not selected for building
        $this->modelBuildKeys();
        $this->viewBuildKeys();
        $this->controllerBuildKeys();
        $this->helperBuildKeys();
        $this->rulesetBuildKeys();
        $this->testBuildKeys();
        $this->dictionaryBuildKeys();

        if ($this->config['no-model'] === false) {
            echo("Building Model...\n");
            $this->modelBuildFiles();
        }
        if ($this->config['no-view'] === false) {
            echo("Building View...\n");
            $this->viewBuildFiles();
        }
        if ($this->config['no-controller'] === false) {
            echo("Building Controller...\n");
            $this->controllerBuildFiles();
        }
        if ($this->config['no-helper'] === false) {
            echo("Building Helper...\n");
            $this->helperBuildFiles();
        }
        if ($this->config['no-ruleset'] === false) {
            echo("Building Ruleset...\n");
            $this->rulesetBuildFiles();
        }
        if ($this->config['no-test'] === false) {
            echo("Building Test...\n");
            $this->testBuildFiles();
        }
        if ($this->config['no-dictionary'] === false) {
            echo("Building Dictionary...\n");
            $this->dictionaryBuildFiles();
        }
        echo("Complete.\n");
    }

    protected function buildFromTemplate($templateName, $outputName) {

    	$source = file_get_contents(getcwd().'/vendor/dev-lucid/lucid/tasks/GenerateTemplates/'.$templateName.'.php');
    	foreach ($this->config['keys'] as $key=>$value) {
    		$source = str_replace('{{'.$key.'}}', $value, $source);
    	}
    	file_put_contents($outputName, $source);
    }

    protected function findTableForKey($table, $key)
    {
    	$tables = $this->config['meta']->getTables(false);

        for ($i=0; $i<count($tables); $i++) {
            $tableCols = $this->config['meta']->getColumns($tables[$i]);
            if ($tableCols[0]['name'] == $key) {
                $return = [
                    $tables[$i],
                    $tableCols[0]['name'],
                ];

                for ($j = 1; $j<count($tableCols); $j++) {
                    if ($tableCols[$j]['type'] == 'string'){
                        $return[] = $tableCols[$j]['name'];
                        return $return;
                    }
                }
                echo('Could not find a label column in table '.$tables[$i].'. Build script looks for the first column that is of a string type (varchar, char, text, etc).');
                return [false, false, false];
            }
        }

        echo('Could not find a table to use as a source for '.$key.' select.');
        return [false, false, false];
    }

    public function modelBuildKeys()
    {
    }

    public function modelBuildFiles()
    {
        $this->buildFromTemplate('model', getcwd().'/app/model/'.$this->config['name'].'.php');
    }

    public function viewBuildKeys()
    {
        # build form form_fields
        $this->config['keys']['select_options'] = '';
        $this->config['keys']['form_fields'] = '';
        $this->config['keys']['table_cols'] = '';
        $this->config['keys']['search_cols'] = '';

        # build the columns for the form
        foreach($this->config['columns'] as $column) {
            if ($column['index'] > 0) {
                switch ($column['type']) {
                    case 'string':
                    case 'int':
                    case 'float':
                        if (strpos(strrev($column['name']), 'di_') === 0) {
                            #echo ("trying to find options for ".$column['name']."\n");
                            # this is likely a foreign key for another table. make it a select list instead of a text field
                            $source = '[]';
                            list($keyTable, $idColumn, $labelColumn) = $this->findTableForKey($this->config['table'], $column['name']);

                            $modelName = null;
                            # so here's the annoying thing: all mvchr class names are camel-case, but when we look up
                            # tables using Metabase lib for keys, we get the actual db table name, which by convention
                            # is lowercase. So, we need to try to find a camel-cased-named model file. Arggh!
                            $existingModels = glob(getcwd().'/app/model/*.php');
                            foreach ($existingModels as $existingModel) {
                                $finalName = basename($existingModel);
                                if (strtolower($finalName) == $keyTable.'.php') {
                                    $modelName = substr($finalName, 0, strlen($keyTable));
                                }
                            }
                            if (is_null($modelName) === true) {
                                echo("Note: Tried to generate a select option list for field ".$column['name'].", but could not find a model for database table $keyTable. You may have to generate that model and rerun this task.\n\n");
                                $keyTable = false;
                            }

                            if ($keyTable !== false) {
                                $source = '$'.$column['name'].'_options';
                                $this->config['keys']['select_options'] .= '        $'.$column['name'].'_options = lucid::$app->factory()->model(\''.$modelName.'\')';
                                $this->config['keys']['select_options'] .= "\n            ->select('$idColumn', 'value')";
                                $this->config['keys']['select_options'] .= "\n            ->select('$labelColumn', 'label')";
                                $this->config['keys']['select_options'] .= "\n            ->order_by_asc('$labelColumn')";
                                $this->config['keys']['select_options'] .= "\n            ->find_array();";
                                $this->config['keys']['select_options'] .= "\n        $".$column['name'].'_options = array_merge([0, \'\'], $'.$column['name']."_options);\n\n";
                            }

                            $this->config['keys']['form_fields'] .= '            html::formGroup(lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$column['name'].'\'), html::select(\''.$column['name'].'\', $data->'.$column['name'].', '.$source.')),'."\n";
                        } else {
                            if ($column['type'] == 'string' && is_null($this->config['keys']['first_string_col']) === true) {
                                $this->config['keys']['first_string_col'] = $column['name'];
                            }
                            $this->config['keys']['form_fields'] .= '            html::formGroup(lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$column['name'].'\'), html::input(\'text\', \''.$column['name'].'\', $data->'.$column['name'].')),'."\n";
                        }

                        break;
                    case 'bool':
                        $this->config['keys']['form_fields'] .= '            html::formGroup(lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$column['name'].'\'), html::input(\'checkbox\', \''.$column['name'].'\', $data->'.$column['name'].')),'."\n";
                        break;
                    case 'timestamp':
                        $this->config['keys']['form_fields'] .= '            html::formGroup(lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$column['name'].'\'), html::input(\'date\', \''.$column['name'].'\', (new \DateTime($data->'.$column['name'].'))->format(\'Y-m-d H:i\'))),'."\n";
                        break;
                    default:
                        echo("no logic for rendering type ". $column['type']."\n");
                        break;
                }
            }
        }

        # build the list of table columns
        foreach($this->config['columns'] as $column) {
            if ($column['index'] > 0) {
                $this->config['keys']['table_cols'] .= '        $table->add(html::dataColumn(lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$column['name'].'\'), \''.$column['name'].'\', \''. ceil(90 / (count($this->config['columns']) - 1)) .'%\', true));'."\n";
            }
        }

        # find all columns that should be part of the search
        foreach($this->config['columns'] as $column) {
            if ($column['index'] > 0 && $column['type'] == 'string') {
                $this->config['keys']['search_cols'] .= "'".$column['name']."',";
            }
        }
    }

    public function viewBuildFiles()
    {
        $this->buildFromTemplate('view', getcwd().'/app/view/'.$this->config['name'].'.php');
    }

    public function controllerBuildKeys()
    {
        $this->config['keys']['save_parameters'] = '';
        $this->config['keys']['save_actions'] = '';
        $this->config['keys']['phpdoc_save_parameters'] = '';
        $this->config['keys']['primary_key_col_type'] = $this->config['columns'][0]['type'];

        foreach($this->config['columns'] as $column) {
            $type = ($column['type'] == 'timestamp')?'\DateTime':$column['type'];
            $this->config['keys']['save_parameters'] .= $type.' $'.$column['name'].', ';

            $this->config['keys']['phpdoc_save_parameters'] .= "      * @param ".$type.' $'.$column['name']."\n";

            if($column['name'] != $this->config['columns'][0]['name']){
                $this->config['keys']['save_actions'] .= "\t\t$"."data->".$column['name']." = $".$column['name'];
                if($column['type'] == 'timestamp') {
                    $this->config['keys']['save_actions'] .= '->format(\DateTime::ISO8601)';
                }
                $this->config['keys']['save_actions'] .= ";\n";
            }
        }
    }

    public function controllerBuildFiles()
    {
        $this->buildFromTemplate('controller', getcwd().'/app/controller/'.$this->config['name'].'.php');
    }

    public function helperBuildKeys()
    {
    }

    public function helperBuildFiles()
    {
        $this->buildFromTemplate('helper',  getcwd().'/app/helper/'.$this->config['name'].'.php');
    }

    public function rulesetBuildKeys()
    {
        $this->config['keys']['rules'] = '';
        for ($i=1; $i<count($this->config['columns']); $i++) {
            $this->config['keys']['rules'] .= "\n\t\t".'$this->addRule(';
            if (strpos(strrev($this->config['columns'][$i]['name']), 'di_') === 0) {
                $this->config['keys']['rules'] .= '[\'type\'=>\'anyValue\', \'label\'=>lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$this->config['columns'][$i]['name'].'\'), \'field\'=>\''.$this->config['columns'][$i]['name'].'\', ]';
            } elseif ($this->config['columns'][$i]['type'] == 'string') {
                $this->config['keys']['rules'] .= '[\'type\'=>\'lengthRange\', \'label\'=>lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$this->config['columns'][$i]['name'].'\'), \'field\'=>\''.$this->config['columns'][$i]['name'].'\', \'min\'=>\'2\', \'max\'=>\'255\', ]';
            } elseif ($this->config['columns'][$i]['type'] == 'bool') {
                $this->config['keys']['rules'] .= '[\'type\'=>\'checked\', \'label\'=>lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$this->config['columns'][$i]['name'].'\'), \'field\'=>\''.$this->config['columns'][$i]['name'].'\', ]';
            } elseif ($this->config['columns'][$i]['type'] == 'int') {
                $this->config['keys']['rules'] .= '[\'type\'=>\'integerValue\', \'label\'=>lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$this->config['columns'][$i]['name'].'\'), \'field\'=>\''.$this->config['columns'][$i]['name'].'\', ]';
            } elseif ($this->config['columns'][$i]['type'] == 'float') {
                $this->config['keys']['rules'] .= '[\'type\'=>\'floatValue\', \'label\'=>lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$this->config['columns'][$i]['name'].'\'), \'field\'=>\''.$this->config['columns'][$i]['name'].'\', ]';
            } elseif ($this->config['columns'][$i]['type'] == 'timestamp') {
                $this->config['keys']['rules'] .= '[\'type\'=>\'validDate\', \'label\'=>lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$this->config['columns'][$i]['name'].'\'), \'field\'=>\''.$this->config['columns'][$i]['name'].'\', ]';
            } else {
                $this->config['keys']['rules'] .= '[\'type\'=>\'anyValue\', \'label\'=>lucid::$app->i18n()->translate(\'model:'.$this->config['table'].':'.$this->config['columns'][$i]['name'].'\'), \'field\'=>\''.$this->config['columns'][$i]['name'].'\', ]';
            }
            $this->config['keys']['rules'] .= ');';
        }
    }

    public function rulesetBuildFiles()
    {
        $this->buildFromTemplate('ruleset', getcwd().'/app/ruleset/'.$this->config['name'].'.php');
    }

    public function dictionaryBuildKeys()
    {
    }

    public function dictionaryBuildFiles()
    {
        $modelDictPath = getcwd().'/app/dictionary/en__models.json';
        if (file_exists($modelDictPath)){
            $dictionaryKeys = json_decode(file_get_contents($modelDictPath), true);
        } else {
            $dictionaryKeys = [];
        }

        if (isset($dictionaryKeys['model:'.$this->config['table']]) === false) {
            $dictionaryKeys['model:'.$this->config['table']] = ucwords($this->config['table']);
        }

        foreach ($this->config['columns'] as $column) {
            if (isset($dictionaryKeys['model:'.$this->config['table'].':'.$column['name']]) === false) {
                $dictionaryKeys['model:'.$this->config['table'].':'.$column['name']] = ucwords(str_replace('_', ' ', $column['name']));
            }
        }

        ksort($dictionaryKeys);

        file_put_contents($modelDictPath, json_encode($dictionaryKeys, JSON_PRETTY_PRINT));

        $navigationDictPath = getcwd().'/app/dictionary/en__navigation.json';
        if (file_exists($modelDictPath)){
            $dictionaryKeys = json_decode(file_get_contents($navigationDictPath), true);
        } else {
            $dictionaryKeys = [];
        }

        if (isset($dictionaryKeys['navigation:'.$this->config['table'].'.view.table']) === false) {
            $dictionaryKeys['navigation:'.$this->config['table'].'.view.table'] = ucwords(str_replace('_', ' ', $this->config['table']));
        }

        ksort($dictionaryKeys);

        file_put_contents($navigationDictPath, json_encode($dictionaryKeys, JSON_PRETTY_PRINT));
    }

    public function testBuildKeys()
    {
    }

    public function testBuildFiles()
    {
        $this->buildFromTemplate('test', getcwd().'/tests/'.$this->config['name'].'_Test.php');
    }
}
Container::addTask(new Generate());


text:
require 'spec_helper'

describe ScoringClass do
  describe "scoring_helpers" do
    Competition.scoring_classes.each do |scoring_class|
      let(:competition) { FactoryBot.build(:competition, scoring_class: scoring_class) }
      it "has valid scoring_helper for #{scoring_class}" do
        scoring_helper = described_class.for(scoring_class, competition)[:helper]
        expect(scoring_helper).not_to be_nil
      end
    end
  end
end


text:
@class XEFormRowObject, XEFormViewController;

@interface XEFormController : NSObject<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *formTableView;
@property (nonatomic, strong) XEFormController *parentFormController;
@property (nonatomic, weak) XEFormViewController *formViewController;
@property (nonatomic, strong) XEFormObject *form;

@property (nonatomic, strong) NSMutableDictionary *cellHeightCache;
@property (nonatomic, strong) NSMutableDictionary *controllerClassesForRowTypes;
@property (nonatomic, strong) NSMutableDictionary *controllerClassesForRowClasses;
@property (nonatomic, assign) UIEdgeInsets originalTableContentInset;

- (void)performAction:(SEL)selector withSender:(id)sender;
- (UIViewController *)tableViewController;

@end


text:
package org.apache.geode.internal.cache.execute;

import static org.apache.geode.cache.RegionShortcut.PARTITION;
import static org.apache.geode.distributed.ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER;
import static org.apache.geode.test.dunit.Host.getHost;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.Collection;
import java.util.Properties;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.CacheTestCase;
import org.apache.geode.test.junit.categories.FunctionServiceTest;

/**
 * TRAC #40714: Registering a function on a Java client changes the behavior when executing an
 * instance of the function
 *
 * On a Java client if a function is registered with id="f1":
 *
 *

 * FunctionService.registerFunction(new FunctionAdapter() {
 *   private final Integer state = 1;
 *
 *   public String getId() {
 *     return "f1";
 *   }
 *
 *   public void execute(FunctionContext fc) {}
 * });
 *

 *
 * But execute a particular instance of a function e.g.:
 *
 *

 * FunctionService.onRegion(r).execute(new FunctionAdapter() {
 *   private final Integer state = 2;
 *
 *   public String getId() {
 *     return "f1";
 *   }
 *
 *   public void execute(FunctionContext fc) {}
 * });
 *

 *
 * The execution code does not serialize (nor execute) the instance which was given. The problems
 * are:
 *

 *
 *
Confusing behavior, the programmer intended an instance (and its state) to be serialized and
 * executed.

 *
 *
Assumes that a function with the same Id is registered on the server which is not necessarily
 * the case.

 *
 *

 *
 *

 * Extracted from {@link PRFunctionExecutionDUnitTest}.
 */
@Category({FunctionServiceTest.class})
public class ExecuteFunctionInstanceRegressionTest extends CacheTestCase {

  private String regionName;

  private VM datastore0;
  private VM datastore1;
  private VM datastore2;
  private VM datastore3;

  @Before
  public void setUp() {
    datastore0 = getHost(0).getVM(0);
    datastore1 = getHost(0).getVM(1);
    datastore2 = getHost(0).getVM(2);
    datastore3 = getHost(0).getVM(3);

    regionName = getUniqueName();

    getCache();
  }

  @Override
  public Properties getDistributedSystemProperties() {
    Properties config = new Properties();
    config.put(SERIALIZABLE_OBJECT_FILTER,
        "org.apache.geode.test.junit.rules.**;org.apache.geode.internal.cache.execute.**;org.apache.geode.internal.cache.functions.**;org.apache.geode.test.dunit.**");
    return config;
  }

  @Test
  public void providedFunctionInstanceShouldBeUsed() throws Exception {
    datastore0.invoke(() -> createPartitionedRegion());
    datastore1.invoke(() -> createPartitionedRegion());
    datastore2.invoke(() -> createPartitionedRegion());
    datastore3.invoke(() -> createPartitionedRegion());

    datastore0.invoke(() -> FunctionService.registerFunction(new BooleanFunction(false)));
    datastore1.invoke(() -> FunctionService.registerFunction(new BooleanFunction(false)));
    datastore2.invoke(() -> FunctionService.registerFunction(new BooleanFunction(false)));
    datastore3.invoke(() -> FunctionService.registerFunction(new BooleanFunction(false)));

    datastore3.invoke(() -> {
      PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionName);
      createAllBuckets(pr);

      ResultCollector<Boolean, Collection<Boolean>> rc =
          executeFunctionWithId(pr, BooleanFunction.class.getName());
      validateResults(rc, false);
    });

    datastore3.invoke(() -> {
      PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(regionName);
      ResultCollector<Boolean, Collection<Boolean>> rc =
          executeFunctionWithInstance(pr, new BooleanFunction(true));

      validateResults(rc, true);
    });
  }

  private void createPartitionedRegion() {
    PartitionAttributesFactory paf = new PartitionAttributesFactory();
    paf.setLocalMaxMemory(10);
    paf.setRedundantCopies(0);
    paf.setTotalNumBuckets(17);

    RegionFactory<Integer, Integer> regionFactory = getCache().createRegionFactory(PARTITION);
    regionFactory.setPartitionAttributes(paf.create());

    regionFactory.create(regionName);
  }

  private void createAllBuckets(final PartitionedRegion pr) {
    for (int bucketId = 0; bucketId < pr.getTotalNumberOfBuckets(); bucketId++) {
      pr.put(bucketId, bucketId);
    }

    for (int bucketId = 0; bucketId < pr.getTotalNumberOfBuckets(); bucketId++) {
      assertThat(pr.getBucketKeys(bucketId)).hasSize(1);
    }
  }

  private ResultCollector<Boolean, Collection<Boolean>> executeFunctionWithInstance(
      final Region region, final BooleanFunction function) {
    Execution<Void, Boolean, Collection<Boolean>> dataSet = FunctionService.onRegion(region);
    ResultCollector<Boolean, Collection<Boolean>> resultCollector = dataSet.execute(function);
    return resultCollector;
  }

  private ResultCollector executeFunctionWithId(final Region region, final String functionId) {
    Execution<Void, Boolean, Collection<Boolean>> dataSet = FunctionService.onRegion(region);
    ResultCollector<Boolean, Collection<Boolean>> resultCollector = dataSet.execute(functionId);
    return resultCollector;
  }

  private void validateResults(final ResultCollector<Boolean, Collection<Boolean>> resultCollector,
      final boolean expectedResult) {
    Collection<Boolean> results = resultCollector.getResult();
    assertThat(results).hasSize(4).containsExactly(expectedResult, expectedResult, expectedResult,
        expectedResult);
  }
}


text:
/**
 *
 */
package info.guardianproject.geebox.browser;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.ipaulpro.afilechooser.FileChooserActivity;
import com.ipaulpro.afilechooser.VFS;

import java.io.File;

import info.guardianproject.geebox.GeeVFS;
import info.guardianproject.geebox.Geebox;

/**
 * Copyright (C) 2013 Lior Saar. All rights reserved.
 *
 * @author liorsaar
 *
 */
public class FileBrowser extends FileChooserActivity {
    protected static final int REQUEST_CODE_FOLDER_BROWSER = 6661;
    protected static final int REQUEST_CODE_FILE_BROWSER = 6662;
    protected static final int REQUEST_CODE_FOLDER_BROWSER_MOVE = 6663;
    private String mStoreRootPath;

	public static void startActivityForResult(Activity aActivity, int aRequestCode, String aBasePath ) {
		Intent intent = new Intent(aActivity, FileBrowser.class);
		intent.setAction( ACTION_FILE_BROWSER );
        intent.putExtra( EXTRA_BASE_PATH, aBasePath);
		aActivity.startActivityForResult(intent, aRequestCode);
	}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if( getIntent().getStringExtra(EXTRA_BASE_PATH) != null ) {
            mBasePath = getIntent().getStringExtra(EXTRA_BASE_PATH);
        } else {
            mBasePath = File.separator; // root
        }
        mStoreRootPath = Geebox.Config.getStoreRootPath();
        super.onCreate(savedInstanceState);
    }

    @Override
    public VFS getVFS() {
        return new GeeVFS(mStoreRootPath);
    }
}


text:
/**
 * Created by casanova on 1/22/16.
 */

// On server startup, if the database is empty, create some initial data.
if (Meteor.isServer) {

  console.log("SERVER-SIDE: ROOT_URL = ", process.env.ROOT_URL);

  Meteor.startup(function () {
    try {
      initialize_upload_server();
      print_collection_info();
      remove_orphan_entries();
      remove_dangling_files();
      reset_globals();
    } catch (e) {
      throw(e);
    }
    console.log("Server running at: ", Meteor.absoluteUrl());

  });

  function initialize_upload_server() {

    var upload_root = process.env.UPLOAD_DIR;
    if (upload_root == undefined) {
      throw new Meteor.Error("UPLOAD_DIR environment variable must be defined");
    }
    //var upload_root = process.env.PWD + '/.uploads/';

    UploadServer.init({
      tmpDir: upload_root+'/tmp',
      uploadDir: upload_root,
      uploadUrl: "/upload",  // Seems to work with a custom ROOT_URL (see Client startup) - with some hacking
      checkCreateDirectories: true,
      getDirectory: function(fileInfo, formData) {
        //console.log("Server-side getDirectory: fileInfo = ", fileInfo);
        //console.log("Server-side getDirectory: formData = ", formData);

        if (formData && formData.directoryName != null) {
          return formData.directoryName;
        }
        return "";
      },
      getFileName: function(fileInfo, formData) {
        //console.log("Server-side getFileName: fileInfo = ", fileInfo);
        //console.log("Server-side getFileName: formData = ", formData);
        if (formData && formData.prefix != null) {
          return formData.prefix + '_' + fileInfo.name;
        }
        return fileInfo.name;
      },
      finished: function(fileInfo, formData) {
        //console.log("Server-side FINISH: fileInfo = ", fileInfo);
        //console.log("Server-side FINISH: formData = ", formData);
        //if (formData && formData._id != null) {
        //  Items.update({_id: formData._id}, { $push: { uploads: fileInfo }});
        //}
      }
    });

    // Make the images sub-directory
    console.log("Creating Directory "+upload_root+"/images/ ...");
    var Future=Npm.require("fibers/future");
    var exec=Npm.require("child_process").exec;
    var future = new Future();
    var dir = process.env.PWD;
    var command = "mkdir -p "+ upload_root + "/images/";
    exec(command, {cwd: dir}, function (error, stdout, stderr) {
      if (error) {
        console.log(error);
        throw new Meteor.Error(500, command + " failed");
      }
      future.return(stdout.toString());
    });
    future.wait();

  }

  function reset_globals() {

    // some_global  (could come in handy)
    Globals.remove({name: "some_global"});
    Globals.insert({name: "some_global", value: ""});

  }

  function remove_orphan_entries() {
    var cursor = DivelogEntries.find();
    cursor.forEach(function(doc) {
      if ((!("diver" in doc)) ||
        (Divers.find({diver: doc.diver}).count() == 0))
      {
        console.log("REMOVING AN ORPHAN ENTRY!!");
        DivelogEntries.remove({_id: doc._id});
      }

      if (("start_pressure" in doc) ||
        ("end_pressure" in doc) ||
        ("expanded" in doc)) {
        console.log("REMOVING AN ENTRY THAT USES A DEPRECATED FIELD!!");
        DivelogEntries.remove({_id: doc._id});
      }
    });

  }

  function remove_dangling_files() {
    var cursor = UploadedImages.find();

    var referencedFiles = build_list_referenced_files();

    cursor.forEach(function(doc) {
      if (referencedFiles.indexOf(doc._id) == -1) {
        var filepath = doc.fileinfo.path;

        // Removing UpoadedImages document
        UploadedImages.remove({_id: doc._id});
        console.log("REMOVING uploaded file ", filepath, ", which was not referenced");
        try {
          // Remove file (not that this may remove nothing if
          // there are other inconsistencies, which is fine
          Meteor.methods.removeFile(filepath);
          // Remove document
        } catch (e) {
          console.log("   Actual file had been already removed...");
          // do nothing
        }
      }

    });

    function build_list_referenced_files() {
      var list = [];
      var cursor = Certifications.find();
      cursor.forEach(function(doc) {
        if (doc.filekey) {
          list.push(doc.filekey);
        }
      });
      return list;
    }
  }

  function print_collection_info() {

    console.log("*****************************************");
    console.log("Number of Registered Users:", Meteor.users.find().count());

    console.log("Number of Divers: ", Divers.find().count());
    var cursor = Divers.find();
    var divers = cursor.fetch();
    for (var i = 0; i < divers.length; i++) {
      console.log("Diver username / name: ",
        Meteor.users.findOne({_id: divers[i].diver}).username, " / ",
        divers[i].name);
      console.log("    - Number of entries: ", DivelogEntries.find({diver: divers[i].diver}).count());
      console.log("    - Number of certifications: ", Certifications.find({diver: divers[i].diver}).count());
    }
    console.log("*****************************************");
  }

}


text:
namespace Likja.ImgurNet.Models
{
    public class GalleryImage
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public long DateTime { get; set; }
        public string Type { get; set; }
        public bool Animated { get; set; }
        public long Width { get; set; }
        public long Height { get; set; }
        public long Size { get; set; }
        public long Views { get; set; }
        public long Bandwidth { get; set; }
        public string DeleteHash { get; set; }
        public string Link { get; set; }
        public string Gifv { get; set; }
        public string Mp4 { get; set; }
        public string Webm { get; set; }
        public bool Looping { get; set; }
        public bool? Favorite { get; set; }
        public bool? Nsfw { get; set; }
        public string Section { get; set; }
        public string AccountUrl { get; set; }
        public long AccountId { get; set; }
        public long Ups { get; set; }
        public long Downs { get; set; }
        public long Score { get; set; }
        public bool IsAlbum { get; set; }
    }
}


text:
set -ex

# Print basic testing info
pip --version

# Building universal wheel package
python setup.py sdist bdist_wheel --universal

# Building Python source package
python setup.py build sdist


text:
using System.Globalization;
using Xunit;

namespace System.Numerics.Tests
{
    public partial class parseTest
    {
        [Theory]
        [InlineData("123456789", 0, 9, "123456789")]
        [InlineData("123456789", 0, 1, "1")]
        [InlineData("123456789", 1, 3, "234")]
        [InlineData("123456789", 8, 1, "9")]
        [InlineData("123456789abc", 8, 1, "9")]
        [InlineData("1\03456789", 0, 1, "1")]
        [InlineData("1\03456789", 0, 2, "1")]
        [InlineData("123456789\0", 0, 10, "123456789")]
        public void Parse_Subspan_Success(string input, int offset, int length, string expected)
        {
            Eval(BigInteger.Parse(input.AsSpan(offset, length)), expected);
            Assert.True(BigInteger.TryParse(input.AsSpan(offset, length), out BigInteger test));
            Eval(test, expected);
        }

        [Fact]
        public void Parse_EmptySubspan_Fails()
        {
            Assert.False(BigInteger.TryParse("12345".AsSpan(0, 0), out BigInteger result));
            Assert.Equal(0, result);
        }

        static partial void VerifyParseSpanToString(string num1, NumberStyles ns, bool failureNotExpected, string expected)
        {
            if (failureNotExpected)
            {
                Eval(BigInteger.Parse(num1.AsSpan(), ns), expected);

                Assert.True(BigInteger.TryParse(num1.AsSpan(), ns, provider: null, out BigInteger test));
                Eval(test, expected);

                if (ns == NumberStyles.Integer)
                {
                    Assert.True(BigInteger.TryParse(num1.AsSpan(), out test));
                    Eval(test, expected);
                }
            }
            else
            {
                Assert.Throws<FormatException>(() => { BigInteger.Parse(num1.AsSpan(), ns); });

                Assert.False(BigInteger.TryParse(num1.AsSpan(), ns, provider: null, out BigInteger test));

                if (ns == NumberStyles.Integer)
                {
                    Assert.False(BigInteger.TryParse(num1.AsSpan(), out test));
                }
            }
        }

        static partial void VerifySimpleFormatParseSpan(string num1, NumberFormatInfo nfi, BigInteger expected, bool failureExpected)
        {
            if (!failureExpected)
            {
                Assert.Equal(expected, BigInteger.Parse(num1.AsSpan(), provider: nfi));
                Assert.True(BigInteger.TryParse(num1.AsSpan(), NumberStyles.Any, nfi, out BigInteger test));
                Assert.Equal(expected, test);
            }
            else
            {
                Assert.Throws<FormatException>(() => { BigInteger.Parse(num1.AsSpan(), provider: nfi); });
                Assert.False(BigInteger.TryParse(num1.AsSpan(), NumberStyles.Any, nfi, out BigInteger test), string.Format("Expected TryParse to fail on {0}", num1));
            }
        }

        static partial void VerifyFormatParseSpan(string num1, NumberStyles ns, NumberFormatInfo nfi, BigInteger expected, bool failureExpected)
        {
            if (!failureExpected)
            {
                Assert.Equal(expected, BigInteger.Parse(num1.AsSpan(), ns, nfi));
                Assert.True(BigInteger.TryParse(num1.AsSpan(), NumberStyles.Any, nfi, out BigInteger test));
                Assert.Equal(expected, test);
            }
            else
            {
                Assert.Throws<FormatException>(() => { BigInteger.Parse(num1.AsSpan(), ns, nfi); });
                Assert.False(BigInteger.TryParse(num1.AsSpan(), ns, nfi, out BigInteger test), string.Format("Expected TryParse to fail on {0}", num1));
            }
        }
    }
}


text:
class AddPiConsentAtToUsers < ActiveRecord::Migration
  def change
    add_column :users, :pi_consent_at, :datetime
  end
end


text:
INSERT INTO SAKAI_REALM_FUNCTION (FUNCTION_NAME) VALUES ('calendar.revise.any');
INSERT INTO SAKAI_REALM_FUNCTION (FUNCTION_NAME) VALUES ('calendar.revise.own');
INSERT INTO SAKAI_REALM_FUNCTION (FUNCTION_NAME) VALUES ('calendar.delete.any');
INSERT INTO SAKAI_REALM_FUNCTION (FUNCTION_NAME) VALUES ('calendar.delete.own');
INSERT INTO SAKAI_REALM_FUNCTION (FUNCTION_NAME) VALUES ('content.revise.any');
INSERT INTO SAKAI_REALM_FUNCTION (FUNCTION_NAME) VALUES ('content.revise.own');
INSERT INTO SAKAI_REALM_FUNCTION (FUNCTION_NAME) VALUES ('content.delete.any');
INSERT INTO SAKAI_REALM_FUNCTION (FUNCTION_NAME) VALUES ('content.delete.own');

--
-- Convert and expand calendar permissions:
--    calendar.revise becomes calendar.revise.own | calendar.revise.any | calendar.delete.own | calendar.delete.any
--
-- Note: mapping revise permission to delete is based on the original (misguided) permissions
--

INSERT INTO SAKAI_REALM_RL_FN (REALM_KEY, ROLE_KEY, FUNCTION_KEY)
   SELECT SAKAI_REALM_RL_FN.REALM_KEY, SAKAI_REALM_RL_FN.ROLE_KEY, F.FUNCTION_KEY
   FROM SAKAI_REALM_ROLE, SAKAI_REALM_FUNCTION,SAKAI_REALM_RL_FN,SAKAI_REALM, SAKAI_REALM_FUNCTION F
   WHERE SAKAI_REALM_FUNCTION.FUNCTION_NAME = 'calendar.revise'
     AND SAKAI_REALM.REALM_KEY = SAKAI_REALM_RL_FN.REALM_KEY
     AND SAKAI_REALM_ROLE.ROLE_KEY = SAKAI_REALM_RL_FN.ROLE_KEY
     AND SAKAI_REALM_FUNCTION.FUNCTION_KEY = SAKAI_REALM_RL_FN.FUNCTION_KEY
     AND F.FUNCTION_NAME='calendar.revise.any';

INSERT INTO SAKAI_REALM_RL_FN (REALM_KEY, ROLE_KEY, FUNCTION_KEY)
   SELECT SAKAI_REALM_RL_FN.REALM_KEY, SAKAI_REALM_RL_FN.ROLE_KEY, F.FUNCTION_KEY
   FROM SAKAI_REALM_ROLE, SAKAI_REALM_FUNCTION,SAKAI_REALM_RL_FN,SAKAI_REALM, SAKAI_REALM_FUNCTION F
   WHERE SAKAI_REALM_FUNCTION.FUNCTION_NAME = 'calendar.revise'
     AND SAKAI_REALM.REALM_KEY = SAKAI_REALM_RL_FN.REALM_KEY
     AND SAKAI_REALM_ROLE.ROLE_KEY = SAKAI_REALM_RL_FN.ROLE_KEY
     AND SAKAI_REALM_FUNCTION.FUNCTION_KEY = SAKAI_REALM_RL_FN.FUNCTION_KEY
     AND F.FUNCTION_NAME='calendar.revise.own';

INSERT INTO SAKAI_REALM_RL_FN (REALM_KEY, ROLE_KEY, FUNCTION_KEY)
   SELECT SAKAI_REALM_RL_FN.REALM_KEY, SAKAI_REALM_RL_FN.ROLE_KEY, F.FUNCTION_KEY
   FROM SAKAI_REALM_ROLE, SAKAI_REALM_FUNCTION,SAKAI_REALM_RL_FN,SAKAI_REALM, SAKAI_REALM_FUNCTION F
   WHERE SAKAI_REALM_FUNCTION.FUNCTION_NAME = 'calendar.revise'
     AND SAKAI_REALM.REALM_KEY = SAKAI_REALM_RL_FN.REALM_KEY
     AND SAKAI_REALM_ROLE.ROLE_KEY = SAKAI_REALM_RL_FN.ROLE_KEY
     AND SAKAI_REALM_FUNCTION.FUNCTION_KEY = SAKAI_REALM_RL_FN.FUNCTION_KEY
     AND F.FUNCTION_NAME='calendar.delete.any';

INSERT INTO SAKAI_REALM_RL_FN (REALM_KEY, ROLE_KEY, FUNCTION_KEY)
   SELECT SAKAI_REALM_RL_FN.REALM_KEY, SAKAI_REALM_RL_FN.ROLE_KEY, F.FUNCTION_KEY
   FROM SAKAI_REALM_ROLE, SAKAI_REALM_FUNCTION,SAKAI_REALM_RL_FN,SAKAI_REALM, SAKAI_REALM_FUNCTION F
   WHERE SAKAI_REALM_FUNCTION.FUNCTION_NAME = 'calendar.revise'
     AND SAKAI_REALM.REALM_KEY = SAKAI_REALM_RL_FN.REALM_KEY
     AND SAKAI_REALM_ROLE.ROLE_KEY = SAKAI_REALM_RL_FN.ROLE_KEY
     AND SAKAI_REALM_FUNCTION.FUNCTION_KEY = SAKAI_REALM_RL_FN.FUNCTION_KEY
     AND F.FUNCTION_NAME='calendar.delete.own';

--
-- Convert and expand content permissions:
--    content.revise becomes content.revise.own | content.revise.any
--    content.delete becomes content.delete.own | content.delete.any
--

INSERT INTO SAKAI_REALM_RL_FN (REALM_KEY, ROLE_KEY, FUNCTION_KEY)
   SELECT SAKAI_REALM_RL_FN.REALM_KEY, SAKAI_REALM_RL_FN.ROLE_KEY, F.FUNCTION_KEY
   FROM SAKAI_REALM_ROLE, SAKAI_REALM_FUNCTION,SAKAI_REALM_RL_FN,SAKAI_REALM, SAKAI_REALM_FUNCTION F
   WHERE SAKAI_REALM_FUNCTION.FUNCTION_NAME = 'content.revise'
     AND SAKAI_REALM.REALM_KEY = SAKAI_REALM_RL_FN.REALM_KEY
     AND SAKAI_REALM_ROLE.ROLE_KEY = SAKAI_REALM_RL_FN.ROLE_KEY
     AND SAKAI_REALM_FUNCTION.FUNCTION_KEY = SAKAI_REALM_RL_FN.FUNCTION_KEY
     AND F.FUNCTION_NAME='content.revise.any';

INSERT INTO SAKAI_REALM_RL_FN (REALM_KEY, ROLE_KEY, FUNCTION_KEY)
   SELECT SAKAI_REALM_RL_FN.REALM_KEY, SAKAI_REALM_RL_FN.ROLE_KEY, F.FUNCTION_KEY
   FROM SAKAI_REALM_ROLE, SAKAI_REALM_FUNCTION,SAKAI_REALM_RL_FN,SAKAI_REALM, SAKAI_REALM_FUNCTION F
   WHERE SAKAI_REALM_FUNCTION.FUNCTION_NAME = 'content.revise'
     AND SAKAI_REALM.REALM_KEY = SAKAI_REALM_RL_FN.REALM_KEY
     AND SAKAI_REALM_ROLE.ROLE_KEY = SAKAI_REALM_RL_FN.ROLE_KEY
     AND SAKAI_REALM_FUNCTION.FUNCTION_KEY = SAKAI_REALM_RL_FN.FUNCTION_KEY
     AND F.FUNCTION_NAME='content.revise.own';

INSERT INTO SAKAI_REALM_RL_FN (REALM_KEY, ROLE_KEY, FUNCTION_KEY)
   SELECT SAKAI_REALM_RL_FN.REALM_KEY, SAKAI_REALM_RL_FN.ROLE_KEY, F.FUNCTION_KEY
   FROM SAKAI_REALM_ROLE, SAKAI_REALM_FUNCTION,SAKAI_REALM_RL_FN,SAKAI_REALM, SAKAI_REALM_FUNCTION F
   WHERE SAKAI_REALM_FUNCTION.FUNCTION_NAME = 'content.delete'
     AND SAKAI_REALM.REALM_KEY = SAKAI_REALM_RL_FN.REALM_KEY
     AND SAKAI_REALM_ROLE.ROLE_KEY = SAKAI_REALM_RL_FN.ROLE_KEY
     AND SAKAI_REALM_FUNCTION.FUNCTION_KEY = SAKAI_REALM_RL_FN.FUNCTION_KEY
     AND F.FUNCTION_NAME='content.delete.any';

INSERT INTO SAKAI_REALM_RL_FN (REALM_KEY, ROLE_KEY, FUNCTION_KEY)
   SELECT SAKAI_REALM_RL_FN.REALM_KEY, SAKAI_REALM_RL_FN.ROLE_KEY, F.FUNCTION_KEY
   FROM SAKAI_REALM_ROLE, SAKAI_REALM_FUNCTION,SAKAI_REALM_RL_FN,SAKAI_REALM, SAKAI_REALM_FUNCTION F
   WHERE SAKAI_REALM_FUNCTION.FUNCTION_NAME = 'content.delete'
     AND SAKAI_REALM.REALM_KEY = SAKAI_REALM_RL_FN.REALM_KEY
     AND SAKAI_REALM_ROLE.ROLE_KEY = SAKAI_REALM_RL_FN.ROLE_KEY
     AND SAKAI_REALM_FUNCTION.FUNCTION_KEY = SAKAI_REALM_RL_FN.FUNCTION_KEY
     AND F.FUNCTION_NAME='content.delete.own';

--
-- Delete old functions
--

DELETE FROM SAKAI_REALM_RL_FN WHERE FUNCTION_KEY IN (SELECT FUNCTION_KEY FROM SAKAI_REALM_FUNCTION WHERE FUNCTION_NAME IN ('calendar.revise','calendar.delete','content.revise','content.delete'));

set foreign_key_checks=0;
DELETE FROM SAKAI_REALM_FUNCTION WHERE FUNCTION_NAME IN ('calendar.revise','calendar.delete','content.revise','content.delete');
set foreign_key_checks=1;

-- --------------------------------------------------------------------------------------------------------------------------------------

-- --------------------------------------------------------------------------------------------------------------------------------------
-- OSP

UPDATE osp_guidance SET securityViewFunction='osp.wizard.operate' WHERE
securityViewFunction='osp.wizard.view';

alter table osp_style add column style_hash varchar(255);

-- --------------------------------------------------------------------------------------------------------------------------------------

-- --------------------------------------------------------------------------------------------------------------------------------------
-- SAK-6468 - CM

-- Drop the previously generated tables (these were not used in previous versions of Sakai)

alter table CM_COURSE_SET_CANON_ASSOC_T drop foreign key FKBFCBD9AE47C5DD8C;
alter table CM_COURSE_SET_CANON_ASSOC_T drop foreign key FKBFCBD9AEA12CE4B7;
alter table CM_COURSE_SET_OFFERING_ASSOC_T drop foreign key FK5B9A5CFDF6B32479;
alter table CM_COURSE_SET_OFFERING_ASSOC_T drop foreign key FK5B9A5CFDA12CE4B7;
alter table CM_ENROLLMENT_SET_T drop foreign key FK99479DD1F6B32479;
alter table CM_ENROLLMENT_T drop foreign key FK7A7F878E5E7CD717;
alter table CM_MEMBERSHIP_T drop foreign key FK9FBBBFE0C04582D9;
alter table CM_MEMBER_CONTAINER_T drop foreign key FKD96A9BC6506E999F;
alter table CM_MEMBER_CONTAINER_T drop foreign key FKD96A9BC65E7CD717;
alter table CM_MEMBER_CONTAINER_T drop foreign key FKD96A9BC6F6B32479;
alter table CM_MEMBER_CONTAINER_T drop foreign key FKD96A9BC610198CE7;
alter table CM_MEMBER_CONTAINER_T drop foreign key FKD96A9BC6CE101BF7;
alter table CM_MEMBER_CONTAINER_T drop foreign key FKD96A9BC6988DCAA7;
alter table CM_MEMBER_CONTAINER_T drop foreign key FKD96A9BC6A5FB6F8D;
alter table CM_MEMBER_CONTAINER_T drop foreign key FKD96A9BC6BDA3036C;
alter table CM_OFFICIAL_INSTRUCTORS_T drop foreign key FK470F8ACCDB9C5A23;

drop table if exists CM_ACADEMIC_SESSION_T;
drop table if exists CM_COURSE_SET_CANON_ASSOC_T;
drop table if exists CM_COURSE_SET_OFFERING_ASSOC_T;
drop table if exists CM_CROSS_LISTING_T;
drop table if exists CM_ENROLLMENT_SET_T;
drop table if exists CM_ENROLLMENT_T;

drop table if exists CM_MEMBERSHIP_T;
drop table if exists CM_MEMBER_CONTAINER_T;
drop table if exists CM_OFFICIAL_INSTRUCTORS_T;

-- Create the new CM tables

create table CM_ACADEMIC_SESSION_T (ACADEMIC_SESSION_ID bigint not null auto_increment, VERSION integer not null, LAST_MODIFIED_BY varchar(255), LAST_MODIFIED_DATE datetime, CREATED_BY varchar(255), CREATED_DATE datetime, ENTERPRISE_ID varchar(255) not null unique, TITLE varchar(255) not null, DESCRIPTION varchar(255) not null, START_DATE datetime, END_DATE datetime, primary key (ACADEMIC_SESSION_ID));
create table CM_COURSE_SET_CANON_ASSOC_T (CANON_COURSE bigint not null, COURSE_SET bigint not null, primary key (COURSE_SET, CANON_COURSE));
create table CM_COURSE_SET_OFFERING_ASSOC_T (COURSE_SET bigint not null, COURSE_OFFERING bigint not null, primary key (COURSE_SET, COURSE_OFFERING));
create table CM_CROSS_LISTING_T (CROSS_LISTING_ID bigint not null auto_increment, VERSION integer not null, LAST_MODIFIED_BY varchar(255), LAST_MODIFIED_DATE datetime, CREATED_BY varchar(255), CREATED_DATE datetime, primary key (CROSS_LISTING_ID));
create table CM_ENROLLMENT_SET_T (ENROLLMENT_SET_ID bigint not null auto_increment, VERSION integer not null, LAST_MODIFIED_BY varchar(255), LAST_MODIFIED_DATE datetime, CREATED_BY varchar(255), CREATED_DATE datetime, ENTERPRISE_ID varchar(255) not null unique, TITLE varchar(255) not null, DESCRIPTION varchar(255) not null, CATEGORY varchar(255) not null, DEFAULT_CREDITS varchar(255) not null, COURSE_OFFERING bigint, primary key (ENROLLMENT_SET_ID));
create table CM_ENROLLMENT_T (ENROLLMENT_ID bigint not null auto_increment, VERSION integer not null, LAST_MODIFIED_BY varchar(255), LAST_MODIFIED_DATE datetime, CREATED_BY varchar(255), CREATED_DATE datetime, USER_ID varchar(255) not null, STATUS varchar(255) not null, CREDITS varchar(255) not null, GRADING_SCHEME varchar(255) not null, DROPPED bit, ENROLLMENT_SET bigint, primary key (ENROLLMENT_ID));
create table CM_MEETING_T (MEETING_ID bigint not null auto_increment, LOCATION varchar(255), TIME_OF_DAY varchar(255), NOTES varchar(255), SECTION_ID bigint not null, primary key (MEETING_ID));
create table CM_MEMBERSHIP_T (MEMBER_ID bigint not null auto_increment, VERSION integer not null, USER_ID varchar(255) not null, ROLE varchar(255) not null, MEMBER_CONTAINER_ID bigint, primary key (MEMBER_ID));
create table CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID bigint not null auto_increment, CLASS_DISCR varchar(100) not null, VERSION integer not null, LAST_MODIFIED_BY varchar(255), LAST_MODIFIED_DATE datetime, CREATED_BY varchar(255), CREATED_DATE datetime, ENTERPRISE_ID varchar(100) not null, TITLE varchar(255) not null, DESCRIPTION varchar(255) not null, CATEGORY varchar(255), COURSE_OFFERING bigint, ENROLLMENT_SET bigint, PARENT_SECTION bigint, CROSS_LISTING bigint, PARENT_COURSE_SET bigint, STATUS varchar(255), START_DATE datetime, END_DATE datetime, CANONICAL_COURSE bigint, ACADEMIC_SESSION bigint, EQUIV_CANON_COURSE_ID bigint, EQUIV_COURSE_OFFERING_ID bigint, primary key (MEMBER_CONTAINER_ID), unique (CLASS_DISCR, ENTERPRISE_ID));
create table CM_OFFICIAL_INSTRUCTORS_T (ENROLLMENT_SET_ID bigint not null, INSTRUCTOR_ID varchar(255));
alter table CM_COURSE_SET_CANON_ASSOC_T add index FKBFCBD9AE7F976CD6 (CANON_COURSE), add constraint FKBFCBD9AE7F976CD6 foreign key (CANON_COURSE) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
alter table CM_COURSE_SET_CANON_ASSOC_T add index FKBFCBD9AE2D306E01 (COURSE_SET), add constraint FKBFCBD9AE2D306E01 foreign key (COURSE_SET) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
alter table CM_COURSE_SET_OFFERING_ASSOC_T add index FK5B9A5CFD26827043 (COURSE_OFFERING), add constraint FK5B9A5CFD26827043 foreign key (COURSE_OFFERING) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
alter table CM_COURSE_SET_OFFERING_ASSOC_T add index FK5B9A5CFD2D306E01 (COURSE_SET), add constraint FK5B9A5CFD2D306E01 foreign key (COURSE_SET) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
create index CM_ENR_SET_CO_IDX on CM_ENROLLMENT_SET_T (COURSE_OFFERING);
alter table CM_ENROLLMENT_SET_T add index FK99479DD126827043 (COURSE_OFFERING), add constraint FK99479DD126827043 foreign key (COURSE_OFFERING) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
create index CM_ENR_ENR_SET_IDX on CM_ENROLLMENT_T (ENROLLMENT_SET);
alter table CM_ENROLLMENT_T add index FK7A7F878E456D3EA1 (ENROLLMENT_SET), add constraint FK7A7F878E456D3EA1 foreign key (ENROLLMENT_SET) references CM_ENROLLMENT_SET_T (ENROLLMENT_SET_ID);
alter table CM_MEETING_T add index FKE15DCD9BD0506F16 (SECTION_ID), add constraint FKE15DCD9BD0506F16 foreign key (SECTION_ID) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
alter table CM_MEMBERSHIP_T add index FK9FBBBFE067131463 (MEMBER_CONTAINER_ID), add constraint FK9FBBBFE067131463 foreign key (MEMBER_CONTAINER_ID) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
create index CM_SECTION_PARENT_IDX on CM_MEMBER_CONTAINER_T (PARENT_SECTION);
create index CM_SECTION_ENR_SET_IDX on CM_MEMBER_CONTAINER_T (ENROLLMENT_SET);
create index CM_COURSE_SET_PARENT_IDX on CM_MEMBER_CONTAINER_T (PARENT_COURSE_SET);
create index CM_CO_ACADEMIC_SESS_IDX on CM_MEMBER_CONTAINER_T (ACADEMIC_SESSION);
create index CM_CO_CANON_COURSE_IDX on CM_MEMBER_CONTAINER_T (CANONICAL_COURSE);
create index CM_SECTION_COURSE_IDX on CM_MEMBER_CONTAINER_T (COURSE_OFFERING);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC6661E50E9 (ACADEMIC_SESSION), add constraint FKD96A9BC6661E50E9 foreign key (ACADEMIC_SESSION) references CM_ACADEMIC_SESSION_T (ACADEMIC_SESSION_ID);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC6456D3EA1 (ENROLLMENT_SET), add constraint FKD96A9BC6456D3EA1 foreign key (ENROLLMENT_SET) references CM_ENROLLMENT_SET_T (ENROLLMENT_SET_ID);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC626827043 (COURSE_OFFERING), add constraint FKD96A9BC626827043 foreign key (COURSE_OFFERING) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC63B0306B1 (PARENT_SECTION), add constraint FKD96A9BC63B0306B1 foreign key (PARENT_SECTION) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC64F7C8841 (CROSS_LISTING), add constraint FKD96A9BC64F7C8841 foreign key (CROSS_LISTING) references CM_CROSS_LISTING_T (CROSS_LISTING_ID);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC6D05F59F1 (CANONICAL_COURSE), add constraint FKD96A9BC6D05F59F1 foreign key (CANONICAL_COURSE) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC6D0C1EF35 (EQUIV_COURSE_OFFERING_ID), add constraint FKD96A9BC6D0C1EF35 foreign key (EQUIV_COURSE_OFFERING_ID) references CM_CROSS_LISTING_T (CROSS_LISTING_ID);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC66DFDE2 (EQUIV_CANON_COURSE_ID), add constraint FKD96A9BC66DFDE2 foreign key (EQUIV_CANON_COURSE_ID) references CM_CROSS_LISTING_T (CROSS_LISTING_ID);
alter table CM_MEMBER_CONTAINER_T add index FKD96A9BC649A68CB6 (PARENT_COURSE_SET), add constraint FKD96A9BC649A68CB6 foreign key (PARENT_COURSE_SET) references CM_MEMBER_CONTAINER_T (MEMBER_CONTAINER_ID);
alter table CM_OFFICIAL_INSTRUCTORS_T add index FK470F8ACCC28CC1AD (ENROLLMENT_SET_ID), add constraint FK470F8ACCC28CC1AD foreign key (ENROLLMENT_SET_ID) references CM_ENROLLMENT_SET_T (ENROLLMENT_SET_ID);

-- --------------------------------------------------------------------------------------------------------------------------------------

-- --------------------------------------------------------------------------------------------------------------------------------------
-- SAM (SAK-4396)

SET FOREIGN_KEY_CHECKS = 0;
drop table if exists SAM_ATTACHMENT_T;
drop table if exists SAM_PUBLISHEDATTACHMENT_T;
SET FOREIGN_KEY_CHECKS = 1;
create table SAM_ATTACHMENT_T (ATTACHMENTID bigint not null auto_increment, ATTACHMENTTYPE varchar(255) not null, RESOURCEID varchar(255), FILENAME varchar(255), MIMETYPE varchar(80), FILESIZE integer, DESCRIPTION varchar(4000), LOCATION varchar(4000), ISLINK integer, STATUS integer not null, CREATEDBY varchar(36) not null, CREATEDDATE datetime not null, LASTMODIFIEDBY varchar(36) not null, LASTMODIFIEDDATE datetime not null, ASSESSMENTID bigint, SECTIONID bigint, ITEMID bigint, primary key (ATTACHMENTID));
create table SAM_PUBLISHEDATTACHMENT_T (ATTACHMENTID bigint not null auto_increment, ATTACHMENTTYPE varchar(255) not null, RESOURCEID varchar(255), FILENAME varchar(255), MIMETYPE varchar(80), FILESIZE integer, DESCRIPTION varchar(4000), LOCATION varchar(4000), ISLINK integer, STATUS integer not null, CREATEDBY varchar(36) not null, CREATEDDATE datetime not null, LASTMODIFIEDBY varchar(36) not null, LASTMODIFIEDDATE datetime not null, ASSESSMENTID bigint, SECTIONID bigint, ITEMID bigint, primary key (ATTACHMENTID));
alter table SAM_ATTACHMENT_T add index FK99FA8CB8CAC2365B (ASSESSMENTID), add constraint FK99FA8CB8CAC2365B foreign key (ASSESSMENTID) references SAM_ASSESSMENTBASE_T (ID);
alter table SAM_ATTACHMENT_T add index FK99FA8CB83288DBBD (ITEMID), add constraint FK99FA8CB83288DBBD foreign key (ITEMID) references SAM_ITEM_T (ITEMID);
alter table SAM_ATTACHMENT_T add index FK99FA8CB870CE2BD (SECTIONID), add constraint FK99FA8CB870CE2BD foreign key (SECTIONID) references SAM_SECTION_T (SECTIONID);
alter table SAM_PUBLISHEDATTACHMENT_T add index FK270998869482C945 (ASSESSMENTID), add constraint FK270998869482C945 foreign key (ASSESSMENTID) references SAM_PUBLISHEDASSESSMENT_T (ID);
alter table SAM_PUBLISHEDATTACHMENT_T add index FK2709988631446627 (ITEMID), add constraint FK2709988631446627 foreign key (ITEMID) references SAM_PUBLISHEDITEM_T (ITEMID);
alter table SAM_PUBLISHEDATTACHMENT_T add index FK27099886895D4813 (SECTIONID), add constraint FK27099886895D4813 foreign key (SECTIONID) references SAM_PUBLISHEDSECTION_T (SECTIONID);

-- more SAM

INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN , KEYWORD,
    DESCRIPTION,
    STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY,
    LASTMODIFIEDDATE )
    VALUES (11 , 'stanford.edu' , 'assessment.item' ,'Numeric Response' ,NULL ,1 ,1 ,
    '2005-01-01 12:00:00',1 ,'2005-01-01 12:00:00');

-- more more SAM
INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY)
  VALUES(NULL, 1, 'releaseTo', 'SITE_MEMBERS')
;
INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL,
   ENTRY)
   VALUES(NULL, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment'
    AND TYPEID='142' AND ISTEMPLATE=1),
     'releaseTo', 'SITE_MEMBERS')
;
INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL,
   ENTRY)
   VALUES(NULL, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz'
    AND TYPEID='142' AND ISTEMPLATE=1),
     'releaseTo', 'SITE_MEMBERS')
;
INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL,
   ENTRY)
   VALUES(NULL, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set'
    AND TYPEID='142' AND ISTEMPLATE=1),
     'releaseTo', 'SITE_MEMBERS')
;
INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL,
   ENTRY)
   VALUES(NULL, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey'
    AND TYPEID='142' AND ISTEMPLATE=1),
     'releaseTo', 'SITE_MEMBERS')
;
INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL,
   ENTRY)
   VALUES(NULL, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test'
    AND TYPEID='142' AND ISTEMPLATE=1),
     'releaseTo', 'SITE_MEMBERS')
;
INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL,
   ENTRY)
   VALUES(NULL, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test'
    AND TYPEID='142' AND ISTEMPLATE=1),
     'releaseTo', 'SITE_MEMBERS')
;

-- --------------------------------------------------------------------------------------------------------------------------------------

-- --------------------------------------------------------------------------------------------------------------------------------------
-- syllabus

alter table SAKAI_SYLLABUS_DATA change position position_c integer not null;

-- --------------------------------------------------------------------------------------------------------------------------------------
-- privacy manager
create table SAKAI_PRIVACY_RECORD (id bigint not null auto_increment, lockId integer not null, contextId varchar(255) not null, recordType varchar(255) not null, userId varchar(255) not null, viewable bit not null, primary key (id), unique (contextId, recordType, userId)) default charset=latin1;

-- --------------------------------------------------------------------------------------------------------------------------------------

-- --------------------------------------------------------------------------------------------------------------------------------------
-- events

ALTER TABLE SAKAI_EVENT CHANGE SESSION_ID SESSION_ID VARCHAR (163);

-- --------------------------------------------------------------------------------------------------------------------------------------

-- --------------------------------------------------------------------------------------------------------------------------------------
-- rwiki (SAK-5674)

 UPDATE rwikiobject r , SAKAI_SITE s
     SET r.name = replace(r.name, concat('/site/',lower(s.site_id)), concat('/site/', s.site_id)),
     r.referenced = replace(r.referenced, concat('/site/',lower(s.site_id)), concat('/site/', s.site_id)),
     r.realm = replace(r.realm,  concat('/site/',lower(s.site_id)), concat('/site/', s.site_id))
     WHERE r.name LIKE concat('/site/',concat(s.site_id, '/%'));

 UPDATE rwikihistory r , SAKAI_SITE s
     SET r.name = replace(r.name, concat('/site/',lower(s.site_id)), concat('/site/', s.site_id)),
     r.referenced = replace(r.referenced, concat('/site/',lower(s.site_id)), concat('/site/', s.site_id)),
     r.realm = replace(r.realm,  concat('/site/',lower(s.site_id)), concat('/site/', s.site_id))
     WHERE r.name LIKE concat('/site/',concat(s.site_id, '/%'));

-- --------------------------------------------------------------------------------------------------------------------------------------

-- SAK-6780 added SQL update scripts to add new tables and alter existing tables to support selective release and spreadsheet upload

-- Gradebook table changes between Sakai 2.2.* and 2.3.

-- Add spreadsheet upload support.
create table GB_SPREADSHEET_T (
  ID bigint(20) NOT NULL auto_increment,
  VERSION int(11) NOT NULL,
  CREATOR varchar(255) NOT NULL,
  NAME varchar(255) NOT NULL,
  CONTENT text NOT NULL,
  DATE_CREATED datetime NOT NULL,
  GRADEBOOK_ID bigint(20) NOT NULL,
  PRIMARY KEY  (`ID`)
);

-- Add selective release support

alter table GB_GRADABLE_OBJECT_T add column (RELEASED bit);
update GB_GRADABLE_OBJECT_T set RELEASED=1 where RELEASED is NULL;
-- --------------------------------------------------------------------------------------------------------------------------------------