text:
require 'date'
require_relative 'has_applications_view_model'

module AdminUI
  class ApplicationsViewModel < AdminUI::HasApplicationsViewModel
    def do_items
      applications = @cc.applications
      droplets     = @cc.droplets
      packages     = @cc.packages

      # applications, droplets and packages have to exist. Other record types are optional
      return result unless applications['connected'] &&
                           droplets['connected'] &&
                           packages['connected']

      application_annotations  = @cc.application_annotations
      application_labels       = @cc.application_labels
      buildpack_lifecycle_data = @cc.buildpack_lifecycle_data
      containers               = @doppler.containers
      events                   = @cc.events
      organizations            = @cc.organizations
      processes                = @cc.processes
      route_mappings           = @cc.route_mappings
      service_bindings         = @cc.service_bindings
      spaces                   = @cc.spaces
      stacks                   = @cc.stacks
      tasks                    = @cc.tasks

      events_connected           = events['connected']
      processes_connected        = processes['connected']
      route_mappings_connected   = route_mappings['connected']
      service_bindings_connected = service_bindings['connected']
      tasks_connected            = tasks['connected']

      buildpack_lifecycle_data_hash = buildpack_lifecycle_data['items'].to_h { |item| [item[:app_guid], item] }
      droplet_hash                  = droplets['items'].to_h { |item| [item[:guid], item] }
      organization_hash             = organizations['items'].to_h { |item| [item[:id], item] }
      package_hash                  = packages['items'].to_h { |item| [item[:guid], item] }
      process_app_hash              = processes['items'].to_h { |item| [item[:app_guid], item] }
      space_hash                    = spaces['items'].to_h { |item| [item[:guid], item] }
      stack_hash                    = stacks['items'].to_h { |item| [item[:name], item] }

      latest_droplets = latest_app_guid_hash(droplets['items'])
      latest_packages = latest_app_guid_hash(packages['items'])

      application_annotations_hash = {}
      application_annotations['items'].each do |application_annotation|
        return result unless @running

        Thread.pass

        application_guid = application_annotation[:resource_guid]
        application_annotations_array = application_annotations_hash[application_guid]
        if application_annotations_array.nil?
          application_annotations_array = []
          application_annotations_hash[application_guid] = application_annotations_array
        end

        # Need rfc3339 dates
        wrapper =
          {
            annotation:         application_annotation,
            created_at_rfc3339: application_annotation[:created_at].to_datetime.rfc3339,
            updated_at_rfc3339: application_annotation[:updated_at].nil? ? nil : application_annotation[:updated_at].to_datetime.rfc3339
          }

        application_annotations_array.push(wrapper)
      end

      application_labels_hash = {}
      application_labels['items'].each do |application_label|
        return result unless @running

        Thread.pass

        application_guid = application_label[:resource_guid]
        application_labels_array = application_labels_hash[application_guid]
        if application_labels_array.nil?
          application_labels_array = []
          application_labels_hash[application_guid] = application_labels_array
        end

        # Need rfc3339 dates
        wrapper =
          {
            label:              application_label,
            created_at_rfc3339: application_label[:created_at].to_datetime.rfc3339,
            updated_at_rfc3339: application_label[:updated_at].nil? ? nil : application_label[:updated_at].to_datetime.rfc3339
          }

        application_labels_array.push(wrapper)
      end

      event_counters = {}
      events['items'].each do |event|
        return result unless @running

        Thread.pass

        if event[:actee_type] == 'app'
          actee = event[:actee]
          event_counters[actee] = 0 if event_counters[actee].nil?
          event_counters[actee] += 1
        elsif event[:actor_type] == 'app'
          actor = event[:actor]
          event_counters[actor] = 0 if event_counters[actor].nil?
          event_counters[actor] += 1
        end
      end

      route_mapping_counters = {}
      route_mappings['items'].each do |route_mapping|
        return result unless @running

        Thread.pass

        app_guid = route_mapping[:app_guid]
        route_mapping_counters[app_guid] = 0 if route_mapping_counters[app_guid].nil?
        route_mapping_counters[app_guid] += 1
      end

      service_binding_counters = {}
      service_bindings['items'].each do |service_binding|
        return result unless @running

        Thread.pass

        app_guid = service_binding[:app_guid]
        service_binding_counters[app_guid] = 0 if service_binding_counters[app_guid].nil?
        service_binding_counters[app_guid] += 1
      end

      application_usage_counters_hash = {}
      containers['items'].each_value do |container|
        return result unless @running

        Thread.pass

        application_guid = container[:application_id]
        application_usage_counters = application_usage_counters_hash[application_guid]
        if application_usage_counters.nil?
          application_usage_counters =
            {
              'used_memory' => 0,
              'used_disk'   => 0,
              'used_cpu'    => 0
            }
          application_usage_counters_hash[application_guid] = application_usage_counters
        end

        application_usage_counters['used_memory'] += container[:memory_bytes]
        application_usage_counters['used_disk'] += container[:disk_bytes]
        application_usage_counters['used_cpu'] += container[:cpu_percentage]
      end

      task_counters = {}
      tasks['items'].each do |task|
        return result unless @running

        Thread.pass

        app_guid = task[:app_guid]
        task_counters[app_guid] = 0 if task_counters[app_guid].nil?
        task_counters[app_guid] += 1
      end

      items = []
      hash  = {}

      applications['items'].each do |application|
        return result unless @running

        Thread.pass

        guid                     = application[:guid]
        process                  = process_app_hash[guid]
        current_droplet_guid     = application[:droplet_guid]
        current_droplet          = current_droplet_guid.nil? ? nil : droplet_hash[current_droplet_guid]
        current_package_guid     = current_droplet.nil? ? nil : current_droplet[:package_guid]
        current_package          = current_package_guid.nil? ? nil : package_hash[current_package_guid]
        latest_droplet           = latest_droplets[guid]
        latest_package           = latest_packages[guid]
        space                    = space_hash[application[:space_guid]]
        organization             = space.nil? ? nil : organization_hash[space[:organization_id]]
        buildpack_lifecycle_data = buildpack_lifecycle_data_hash[guid]
        stack_name               = buildpack_lifecycle_data.nil? ? nil : buildpack_lifecycle_data[:stack]
        stack                    = stack_name.nil? ? nil : stack_hash[stack_name]

        droplet = current_droplet
        droplet = latest_droplet if droplet.nil?

        package = current_package
        package = latest_package if package.nil?

        application_annotation_array = application_annotations_hash[guid] || []
        application_label_array      = application_labels_hash[guid] || []
        application_usage_counters   = application_usage_counters_hash[guid]
        event_counter                = event_counters[guid]
        route_mapping_counter        = route_mapping_counters[guid]
        service_binding_counter      = service_binding_counters[guid]
        task_counter                 = task_counters[guid]

        row = []

        row.push(guid)
        row.push(application[:name])
        row.push(guid)

        row.push(application[:desired_state])

        if process
          row.push(process[:state])
        else
          row.push(nil)
        end

        row.push(package_state(current_droplet, latest_droplet, latest_package))

        if droplet
          row.push(droplet[:error_id])
        else
          row.push(nil)
        end

        row.push(application[:created_at].to_datetime.rfc3339)

        if application[:updated_at]
          row.push(application[:updated_at].to_datetime.rfc3339)
        else
          row.push(nil)
        end

        if process
          row.push(process[:diego])
        else
          row.push(nil)
        end

        # enable_ssh moved from process to application in cf-release 273
        if application[:enable_ssh].nil?
          if process
            row.push(process[:enable_ssh])
          else
            row.push(nil)
          end
        else
          row.push(application[:enable_ssh])
        end

        row.push(application[:revisions_enabled])

        if package
          row.push(!package[:docker_image].nil?)
        else
          row.push(false)
        end

        row.push(stack_name)

        if droplet
          row.push(droplet[:buildpack_receipt_buildpack])
          row.push(droplet[:buildpack_receipt_buildpack_guid])
        else
          row.push(nil, nil)
        end

        if event_counter
          row.push(event_counter)
        elsif events_connected
          row.push(0)
        else
          row.push(nil)
        end

        if process
          row.push(process[:instances])
        elsif processes_connected
          row.push(0)
        else
          row.push(nil)
        end

        if route_mapping_counter
          row.push(route_mapping_counter)
        elsif route_mappings_connected
          row.push(0)
        else
          row.push(nil)
        end

        if service_binding_counter
          row.push(service_binding_counter)
        elsif service_bindings_connected
          row.push(0)
        else
          row.push(nil)
        end

        if task_counter
          row.push(task_counter)
        elsif tasks_connected
          row.push(0)
        else
          row.push(nil)
        end

        if application_usage_counters
          row.push(Utils.convert_bytes_to_megabytes(application_usage_counters['used_memory']))
          row.push(Utils.convert_bytes_to_megabytes(application_usage_counters['used_disk']))
          row.push(application_usage_counters['used_cpu'])
        else
          row.push(nil, nil, nil)
        end

        if process
          row.push(process[:memory])
          row.push(process[:disk_quota])
        else
          row.push(nil, nil)
        end

        if organization && space
          row.push("#{organization[:name]}/#{space[:name]}")
        else
          row.push(nil)
        end

        items.push(row)

        hash[guid] =
          {
            'annotations'              => application_annotation_array,
            'application'              => application,
            'buildpack_lifecycle_data' => buildpack_lifecycle_data,
            'current_droplet'          => current_droplet,
            'current_package'          => current_package,
            'labels'                   => application_label_array,
            'latest_droplet'           => latest_droplet,
            'latest_package'           => latest_package,
            'organization'             => organization,
            'process'                  => process,
            'space'                    => space,
            'stack'                    => stack
          }
      end

      result(true, items, hash, (1..26).to_a, (1..15).to_a << 26)
    end
  end
end


text:
class CalypearDiagramComponent {
  constructor(componentData,diagramComponentData = {}) {
    if (componentData != null) {
      if (componentData.id) {
        this.id = componentData.id;
      }

      /**
        TODO: copy these properties over more efficiently.
      **/
      this.name = componentData.name;
      this.description = componentData.description;
      this.docUrl = componentData.docUrl;
      this.alternativeNames = componentData.alternativeNames;

      if (componentData.type) {
        this.type = {};
        if (componentData.type.id) {
          this.type.id = componentData.type.id;
        }
        if (componentData.type.name) {
          this.type.name = componentData.type.name;
        }
      }

      this.relationships = componentData.relationships;
      //Set the Source/Target fields
      this.relationships.forEach(function(relationship) {
        relationship.source = relationship.from;
        relationship.target = relationship.to;
      });

    }

    if (diagramComponentData.includedInDiagram) {
      this.includedInDiagram = diagramComponentData.includedInDiagram;
    } else {
      this.includedInDiagram = false;
    }

    /**
      Set defaults for display
    */
    this.display = {
      //<=0: Automatic (Diagam specifics will determine this)
      //>0: Use the specific size
      width: 0,
      //-1 = Automatic/Use defaults
      //>-1 - Use the specified angle
      //0 = 3 O'Clock position and proceeds clockwise
      rotation: 0
    }

    if (diagramComponentData.display) {
      this.display.width = diagramComponentData.display.width;
      this.displau.rotation = diagramComponentData.display.rotation;
    }

    //Currently this effectively unpins the component
    //Waiting here until we are supplied with further Diagram Specifics for the component
    this.pinAt(componentData.fixedX, componentData.fixedY);
  }

  pinAtPosition(){
    this.pinAt(this.x, this.y);
  }

  /*
    Hold only sets the fixed position,
    This generally is to allow nodes to be stopped from exiting to view box
    while the simulation is running - without actually pinning them.
    Rather than simply ignoring X/Y movement which would cause the simulation
    issues.
  */
  holdAt(x,y){
    this.fx = x;
    this.fy = y;
  }

  pinAt(x,y){
    this.fx = x;
    this.fy = y;

    if (x || y) {
      this.pinned = true;
    } else {
      this.pinned = false;
    }
    return this;
  }

  pinRelease(){
    this.pinAt(null,null);
    return this;
  }

  isPinned(){
    //No longer relies on the Fx/Fy positions as they are set by the dragging
    //logic hence may or may not be set.
    return this.pinned;
  }

  included(includedInDiagram = true) {
    this.includedInDiagram = includedInDiagram
    return this;
  }

  isIncludedInDiagram() {
    return this.includedInDiagram;
  }

  getForwardRelationships() {
    return this.relationships.filter(function(relationship){
      return relationship.inverse == false
    });
  }

  getRelationships() {
    return this.relationships;
  }

  getRelatedComponentIds(forwardOnly = false, limitType = null){
    var forwardIds = this.relationships.map(function(relationship){
      return relationship.to;
    });
    if (!forwardOnly) {
      forwardIds.concat(this.relationships.map(function(relationship){
        return relationship.from;
      }));
    }
    return forwardIds;
  }

  getDiagramSaveObject(){
    var componentToSave = {
      component: this.id,
    }
    if (this.isPinned()) {
      componentToSave.fixedX = this.fx;
      componentToSave.fixedY = this.fy;
    }
    return componentToSave;
  }
}

class CalypearDiagram  {
  constructor() {
    this.diagramComponents = new Array();
    this.diagramName = 'Untitled';
  }

  name(name){
    if (name) {
      this.diagramName = name;
      return this;
    } else {
      return this.diagramName;
    }
  }

  nodeById(nodeId) {
    return this.diagramComponents.find(function(component){
      return component.id == nodeId;
    })
  }

  nodes() {
    return this.diagramComponents;
  }

  edges() {
    var edges = [];
    var componentIds = [];
    //Pull out the relationships for all the diagram components
    /**
      Note: The deep copy is to prevent the issue with removing items
      creating weird edges that don't connect to things
      Probably a much more effecient way to do this but will solve tht later
      TODO: Do this better
    */
    this.diagramComponents.forEach(function(component) {
      edges = edges.concat(component.getRelationships().map(function(relationship){
        return JSON.parse(JSON.stringify(relationship))
      }));
      // edges = edges.concat(component.getRelationships());
      componentIds.push(component.id);
    });
    //Filter out relationships to unknown objects
    edges = edges.filter(function(relationship,index,relationsArray) {
      return (componentIds.includes(relationship.to) && (componentIds.includes(relationship.from)));
    });
    //Filter out inverse Relationships when a forward relationship exists
    edges = edges.filter(function(relationship,index,relationsArray) {
      return (relationship.inverse == false);
    });
    return edges;
  }

  getDiagramComponentIds(){
    return this.diagramComponents.map((component) => {
      return component.id;
    });
  }

  /*
    Will run the expand function on each component connected to the supplied
    component id, Flourishing null will be interpreted as ALL components

    Returns a promise for consistency
  */
  flourishAll(iterations = 1, refreshOnSuccess = true) {
    var  componentIdsToFlourish = this.getDiagramComponentIds();

    //Recursive flourish - warning - dangerous
    return this.retrieveAndAddRelatedComponents(componentIdsToFlourish).then(() => {
      if (iterations > 1) {
        //Recursion
        return diagram.flourishAll(iterations-1,refreshOnSuccess);
      } else {
        //Caller is expecting a Promise -
        return Promise.resolve("Retrieved");
      }
    },{diagram: this});
  }

  /*
    Removes all components that do not have atleast X links to other components
    Note: A forward and inverse link between objects count as 2,
          An object with a link to itself counts as linked
  */
  removeOrphanComponents(minimumLinks = 1, refreshOnSuccess = true) {
    //Get a list of all component id's in the diagram
    var diagramComponentIds = this.diagramComponents.reduce((accumulator,component) => {
      accumulator.push(component.id);
      return accumulator;
    },[])
    //Find the components that aren't linked to anything above
    var componentsToRemove = this.diagramComponents.reduce((accumulator, component) => {
      var thisComponentLinks = component.getRelationships().filter((relationship) => {
        return (diagramComponentIds.includes(relationship.to) && diagramComponentIds.includes(relationship.from));
      });
      if (thisComponentLinks < minimumLinks) {
        accumulator.push(component.id);
      }
      return accumulator;
    },[]);

    this.removeComponents(componentsToRemove,refreshOnSuccess);
  }

  removeComponents(componentIds, refreshOnSuccess = true) {
    //Force componentIds to be an array so we can process consistently
    if (!(componentIds instanceof Array)) {
      componentIds = [componentIds];
    }
    //Get a map of the element ids from the components Array
    var elementsToRemove = [] ;

    this.diagramComponents.forEach(function(element, index){
      if (componentIds.includes(element.id)) {
        elementsToRemove.push(index);
      }
    })

    //sort the elements to remove and reverse it so we work back from the end
    //of the array
    //otherwise deleting will alter the indexes
    elementsToRemove.sort().reverse();
    elementsToRemove.forEach(function(elemToRemove){
      this.diagramComponents.splice(elemToRemove,1);
    },this);

    if (refreshOnSuccess) {
      this.updateDiagram();
    }

  }

  retrieveAndAddComponents(componentIds, autoIncludeComponents = false, refreshOnSuccess = true){
    var queryParams =  {
      componentId: componentIds,
      detailed: true,
    }
    var url = '/archcomponents';
    var current = this;
    var returnPromise = new Promise(function(resolve, reject){
      $.ajax({
        dataType: "json",
        method: "GET",
        url: url,
        data: $.param(queryParams,true),
        context: {
          diagram: current,
          autoInclude: autoIncludeComponents
        },
        success: function(responseData) {
          var existingComponentIds = this.diagram.diagramComponents.map(function(ac){
            return ac.id;
          });
          if (responseData.archComponents) {
            responseData.archComponents.forEach(function(newComponent){
              //Check if the component already exists if so - ignore it
              //TODO: Delete and replace (in case relationships have changed on the server)
              if (!existingComponentIds.includes(newComponent.id)){
                var componentDiagramData = {
                  includedInDiagram: autoIncludeComponents
                }
                diagram.diagramComponents.push(new CalypearDiagramComponent(newComponent,componentDiagramData));
              }
            });
            resolve("Components Loaded");
          } else {
            reject("No component received");
          }
          if (refreshOnSuccess) {
            this.diagram.updateDiagram();
          }

        }
      });
    },this);
    return returnPromise;
  }

  retrieveAndAddRelatedComponents(componentIds, autoIncludeComponents = false, refreshOnSuccess = true) {
    //This could be done quicker and faster using a D3 nest but trying not to introduce depednancies here
    //Function accepts a single component or an array
    if (!(componentIds instanceof Array)) {
      componentIds = [componentIds];
    }
    //Get the components
    var componetsToExpand = [];
    componentIds.forEach((componentId) => {
      var thisComponent = this.nodeById(componentId);
      if (thisComponent) {
        componetsToExpand.push(thisComponent);
      }
    })
    //Get an array of related components
    var relatedComponentIds = componetsToExpand.reduce((accumulator,component) =>{

      return accumulator.concat(component.getRelatedComponentIds());
    },[]);
    //Remove duplicates here
    var relatedComponentIds = relatedComponentIds.filter((element, index, relatedComponentArray) => {
      return relatedComponentArray.indexOf(element) == index;
    });

    if (relatedComponentIds) {
      return this.retrieveAndAddComponents(relatedComponentIds,autoIncludeComponents,refreshOnSuccess);
    } else {
      return Promise.reject("Component not loaded");
    }

  }

  updateDiagram(){
    refresh(this.nodes(), this.edges());
  }

  getDiagramSaveObject(){
    var returnObj = {
      components: [],
      name: this.diagramName,
      id: this.id
    };
    this.diagramComponents.forEach(function(diagramComponent) {
      if (diagramComponent.includedInDiagram) {
        returnObj.components.push(diagramComponent.getDiagramSaveObject());
      }

    });

    return returnObj;
  }

  saveDiagramToServer(){
    var saveObject = {
      diagram: this.getDiagramSaveObject()
    }
    //If the ID is known then we will update a diagram rather than create
    var url = "/diagram"
    if (saveObject.diagram.id) {
      url = url + '/' + saveObject.diagram.id;
    }

    return new Promise((resolve,reject) => {
      $.ajax({
        method: "POST",
        dataType : "json",
        contentType: "application/json; charset=utf-8",
        //processData: false,
        data: JSON.stringify(saveObject),
        url: url,
        context: {diagram: this},
        success: function(responseData) {
          //Set the ID so we can update the saved diagram
          diagram.id = responseData.diagram[0].id;
          resolve(diagram);
        },
        error: function(){
          reject("Error saving diagram");
        }
      });
    },this)

  }

  loadDiagramFromObject(diagramObject){
    this.name(diagramObject.name);
    this.id = diagramObject.id;
    this.diagramComponents = [];
    var componentIds = diagramObject.components.map(function(diagramComponent){
      return diagramComponent.component;
    });
    //TODO: Need to account for Fixed Position Components?
    //Retrieve the components from the server (this ensures we get all the data we want consistently)
    this.retrieveAndAddComponents(componentIds,true,true).then(() => {
    //   this.components
      diagramObject.components.forEach((requestedComponent) => {
        if ((requestedComponent.fixedX) || (requestedComponent.fixedY)) {
          var activeComponent = this.nodeById(requestedComponent.component);
          if (activeComponent) {
            activeComponent.pinAt(requestedComponent.fixedX,requestedComponent.fixedY);
          }
        }
      });
    },this);
  }

  retrieveDiagramFromServer(diagramId){
    var url = "/diagram/"+diagramId;
    return new Promise((resolve, reject) => {
      $.ajax({
        method: "GET",
        dataType : "json",
        contentType: "application/json; charset=utf-8",
        //processData: false,
        url : url,
        context: {diagram: this},
        success: function(responseData) {
          //Pick out the Diagram from the responseData
          if (responseData.diagram.length > 0)  {
            diagram.loadDiagramFromObject(responseData.diagram[0]);
          }
          resolve(this);
        },
        error: function(){
          reject("Error loading Diagram");
        }
      });
    },this);

  }

  /*
    Pins all components in the diagram
  */
  pinAll(){
    this.diagramComponents.forEach((diagramComponent) => {
      diagramComponent.pinAtPosition();
    });
  }
  /*
    Pin Releases all components in the diagram
  */
  pinReleaseAll(){
    this.diagramComponents.forEach((diagramComponent) => {
      diagramComponent.pinRelease();
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _events = require("events");

var _couchbase = require("couchbase");

var _couchbase2 = _interopRequireDefault(_couchbase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function isKeyNotFound(err) {
  return err.code === 13;
}

var CouchbaseSessionStore = function (_EventEmitter) {
  _inherits(CouchbaseSessionStore, _EventEmitter);

  /**
  * Construct a couchbase session store
  *
  * @param {string}     options.connect           The couchbase connect string
  * @param {string}     options.bucketName        The bucket for session data
  * @param {string}     options.bucketPassword    The bucket password
  */
  function CouchbaseSessionStore(_ref) {
    var connect = _ref.connect;
    var bucketName = _ref.bucketName;
    var _ref$bucketPassword = _ref.bucketPassword;
    var bucketPassword = _ref$bucketPassword === undefined ? null : _ref$bucketPassword;

    _classCallCheck(this, CouchbaseSessionStore);

    var _this = _possibleConstructorReturn(this, (CouchbaseSessionStore.__proto__ || Object.getPrototypeOf(CouchbaseSessionStore)).call(this));

    _this.cluster = new _couchbase2.default.Cluster(connect);

    _this.bucket = _this.cluster.openBucket(bucketName, bucketPassword);
    _this.bucket.on("connect", function () {
      _this.emit("connect", _this);
    });

    _this.bucket.on("error", function (err) {
      _this.emit("error", err);
    });

    return _this;
  }

  /**
  * Gets a session object by id
  *
  * @param {string}     id          The id to look up
  * @returns {Promise}              Promise resolves to the session object
  */

  _createClass(CouchbaseSessionStore, [{
    key: "get",
    value: function get(id) {
      var _this2 = this;

      return new Promise(function (resolve, reject) {
        _this2.bucket.get(id, function (err, doc) {
          if (err) {
            if (isKeyNotFound(err)) {
              resolve(null);
            } else {
              reject(err);
            }
          } else {
            resolve(doc.value);
          }
        });
      });
    }

    /**
    * Sets a session object by id
    *
    * @param {string}     id          The id to look up
    * @param {object}     session     The session object
    * @param {int}        ttl         The time to live, in ms
    * @returns {Promise}              Promise resolves when done
    */

  }, {
    key: "set",
    value: function set(id, session, ttl) {
      var _this3 = this;

      return new Promise(function (resolve, reject) {
        _this3.bucket.upsert(id, session, {
          expiry: ttl / 1000
        }, function (err) {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    }

    /**
    * Destroys a session object by id
    *
    * @param {string}     id          The id to look up
    * @returns {Promise}              Promise resolves when done
    */

  }, {
    key: "destroy",
    value: function destroy(id) {
      var _this4 = this;

      return new Promise(function (resolve, reject) {
        _this4.bucket.remove(id, function (err) {
          if (err) {
            if (isKeyNotFound(err)) {
              resolve();
            } else {
              reject(err);
            }
          } else {
            resolve();
          }
        });
      });
    }
  }]);

  return CouchbaseSessionStore;
}(_events.EventEmitter);

exports.default = CouchbaseSessionStore;


text:
package com.winterwell.bob;

import com.winterwell.utils.Utils;
import com.winterwell.utils.log.KErrorPolicy;
import com.winterwell.utils.log.Log;

public interface IErrorHandler {

	void handle(Throwable ex); // throws Exception;

	public static IErrorHandler IGNORE = err -> {};

	public static IErrorHandler forPolicy(KErrorPolicy policy) {
		switch(policy) {
		case ACCEPT:
		case IGNORE:
			return IGNORE;
		case DIE:
			return err -> {
				Log.e(err);
				System.exit(1);
			};
		case REPORT:
		case RETURN_NULL:
			return Log::e;
		case THROW_EXCEPTION:
			return err -> {
				throw Utils.runtime(err);
			};
		}
		// :(
		throw new IllegalArgumentException("No default handling for "+policy);
	}

}


text:
package org.roi.itlab.cassandra.random_attributes;

import org.apache.commons.math3.random.MersenneTwister;
import org.mongodb.morphia.geo.Point;
import org.roi.itlab.cassandra.Route;
import org.roi.itlab.cassandra.Routing;
import org.roi.itlab.cassandra.person.Person;
import com.graphhopper.util.DistanceCalcEarth;

import java.io.IOException;
import java.time.LocalTime;
import java.util.UUID;

/**
 * Created by Vadim on 02.03.2017.
 */
public class PersonGenerator {
    public static final int SEED = 1;
    private static final double MAX_DISTANCE_OVERRUN = 3;
    private static final double MIN_DISTANCE = 1000;
    private static final double MIN_SKILL = 0.1;

    private RandomGenerator ageGenerator;
    private RandomGenerator workDurationGenerator;
    private RandomGenerator workStartGenerator;
    private RandomGenerator distanceGenerator;
    private LocationGenerator homeGenerator;
    private LocationGenerator workGenerator;
    private NormalGenerator skillGenerator;
    private NormalGenerator rushGenerator;
    private NormalGenerator experienceGenerator;

    private DistanceCalcEarth distanceEarth = new DistanceCalcEarth();

    public PersonGenerator() {
        this(new MersenneTwister(SEED));
    }

    public PersonGenerator(org.apache.commons.math3.random.RandomGenerator rng) {
        ageGenerator = new AgeRandomGenerator(rng);
        workStartGenerator = new WorkStartRandomGenerator(rng);
        workDurationGenerator = new WorkDurationRandomGenerator(rng);
        skillGenerator = new SkillNormalGenerator(rng);
        experienceGenerator = new ExperienceNormalGenerator(rng);
        rushGenerator = new RushFactorNormalGenerator(rng);
        distanceGenerator = new RandomDistanceGenerator(rng);

        try {
            homeGenerator = new HomeLocationGenerator(rng);
            workGenerator = new WorkLocationGenerator(rng);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Person getResult() {
        Person person = new Person();
        person.setId(UUID.randomUUID());

        person.setAge(ageGenerator.getRandomInt());
        person.setWorkStart(LocalTime.of(workStartGenerator.getRandomInt(),0));
        person.setWorkDuration(LocalTime.of(workDurationGenerator.getRandomInt(),0));
        person.setWorkEnd(LocalTime.of((person.getWorkStart().getHour() + person.getWorkDuration().getHour())% 24,0));
        person.setExperience(Math.max(0, experienceGenerator.getRandomDouble(person.getAge())));
        person.setSkill(Math.max(MIN_SKILL, skillGenerator.getRandomDouble(person.getExperience())));
        person.setRushFactor(rushGenerator.getRandomDouble(person.getAge()));
        if (homeGenerator != null && workGenerator != null) {
            int distance = distanceGenerator.getRandomInt();
            Point home = homeGenerator.sample();
            Point work = workGenerator.sample();
            while (true) {
                double actualDistance = distanceEarth.calcDist(home.getLatitude(), home.getLongitude(), work.getLatitude(), work.getLongitude());
                if (actualDistance < distance && actualDistance > MIN_DISTANCE) {
                    try {
                        Route routeToWork = Routing.route(home, work);
                        Route routeFromWork = Routing.route(work, home);
                        if (routeFromWork.getDistance() < actualDistance * MAX_DISTANCE_OVERRUN && routeToWork.getDistance() < actualDistance * MAX_DISTANCE_OVERRUN) {
                            person.setHome(home);
                            person.setWork(work);
                            person.setToHome(routeFromWork);
                            person.setToWork(routeToWork);
                            break;
                        }
                    }
                    catch (Exception e) {

                    }
                }
                home = homeGenerator.sample();
                work = workGenerator.sample();
            }
        }

        return person;
    }
}


text:
{% extends 'layouts/application.html' %} {% block content %}

DEBT RECOVERY SERVICES

        Download PDF

                    We are proud to be one of the only law firms in New Zealand to offer fixed fee debt recovery services. With Evolution Lawyers, you get a registered lawyer to help get your money back without having to worry about what it might cost you.

Summary of our Fixed Fees

For debts owed by individuals:

Formal demand - $250

Summary judgment application - $1,800

Order for summary judgment - $950

Bankruptcy notice - $900

Creditor's application - $1,800

Order for adjudication - $750

For debts owed by companies:

Formal demand - $250

Statutory demand - $350

Liquidation application - $1,800

Order for liquidation - $750

Summary of Disbursements

The following table summarises the common disbursements (including GST) that you may need to pay in addition to our fixed fee:

                                    Disbursement

                                    District Court

                                    High Court

                                    Filing statement of claim and summary judgment application

                                    $450

                                    $1,350

                                    Service fee (approximate) – applies to service of summary judgment application, bankruptcy notice, creditor’s application for adjudication, statutory demand, liquidation application, and any other steps requiring service of documents

                                    $150

                                    $150

                                    Trace fee (approximate) – for debtors whose whereabouts are unknown

                                    $300

                                    $300

                                    Sealing order for summary judgment

                                    $50

                                    $50

                                    Issuing certificate of judgment

                                    $50

                                    N/A

                                    Filing request for issue of bankruptcy notice

                                    N/A

                                    $200

                                    Filing creditor’s application for adjudication

                                    N/A

                                    $500

                                    Sealing order for bankruptcy

                                    N/A

                                    $50

                                    Filing application to put company into liquidation

                                    N/A

                                    $540

                                    Sealing order for liquidation

                                    N/A

                                    $50

Conditions

Our fixed fees are subject to the following conditions, and any further conditions set out in our letter of engagement:

All fees exclude GST and disbursements.

For simple debt claims over $15,000 involving a single creditor and debtor (claims up to $15,000, and $20,000 by agreement, can be heard in the Disputes Tribunal.

Debt to be based on a standard written document or one prepared by a lawyer.

The written document is signed by the debtor.

Debts covered by the Construction Contracts Act 2002 are excluded.

Debts must be due and owing, and undisputed by the debtor.

Fees at each step assume that all prior steps (if any) have been completed.

If any recovery step is defended by the debtor or the debtor engages counsel to act on their behalf, fees will be charged in accordance with our usual hourly rates.

Step One – Formal Demand - $250

                        Whether the debtor is a company or an individual, we recommend starting with a formal, written demand. Our fee includes the following attendances:

Reviewing documents evidencing the debt e.g. loan agreement, correspondence, and account statement.

Preparing a written demand for your review.

Finalising demand and sending to debtor.

If the debtor does not pay the debt by the deadline set out in the formal demand, move to Step Two. Disbursements to this point include our office disbursement of $50.

If the parties wish to settle the debt, our fee for preparing and arranging execution of a settlement agreement is $800.

Debts Owed by Individuals

These steps in the process relate to debts owed by individuals.

Step Two – Summary Judgment Application - $1,800

                                We recommend filing and serving summary judgment proceedings in the District Court (for debts under $200,000) or High Court (for debts $200,000 and over) if the individual does not satisfy the formal demand. Our fee includes:

Preparing statement of claim, summary judgment application, notice of proceeding, list of documents, and affidavit in support.

Arranging swearing of affidavit in support of summary judgment application.

Finalising documents for filing with the relevant Court.

Arranging personal service of documents on the debtor, if possible.

If an order for deemed or substituted service is required, our additional fee is $1,000 for preparing the necessary documents and obtaining the required order.

Preparing, arranging swearing of, and filing affidavit of service.

                                If the debtor does not oppose the summary judgment application, move to Step Three. Disbursements at this stage will include Court filing fees,the service agent's fee, and our office disbursement of $50.

Step Three – Order for Summary Judgment - $950

                                On the date allocated for the first call of the summary judgment application, we recommend seeking an order for summary judgment. Our fee includes:

Preparing a memorandum of indebtedness for the hearing.

Preparing the draft form of order for summary judgment.

Appearing at, or arranging for an agent to appear at, the first call of the summary judgment application

Sealing order for summary judgment

                                Disbursements at this step will include Court filing fees, agency fees (if an agent is required for an out-of-town Court appearance), and our office disbursement of $50.

At this point, we recommend considering sending a copy of the sealed order to the debtor in the form of a further formal demand. This would involve repeating Step One.

If the Court order does not result in repayment, move to Individual Step Four.

Step Four – Bankruptcy Notice - $900

                                We recommend serving a bankruptcy notice if the individual debtor does not pay the debt in accordance with the Court order. Our fee includes:

Preparing and filing certificate of judgment (if required).

Preparing request for issue of a bankruptcy notice and bankruptcy notice.

Filing request and bankruptcy notice with relevant High Court registry.

Arranging service of bankruptcy notice and reporting to you following expiry.

Preparing, arranging swearing of, and filing affidavit of service.

                                Disbursements at this step will include Court filing fees, service fees, and our office disbursement of $50.

                                If the bankruptcy notice expires unremedied, move to Individual Step Five.

Step Five – Creditor's Application - $1,800

                                We recommend applying for an adjudication order against the debtor as the next step. Our fee includes:

Preparing creditor's application for adjudication order, affidavit in support, and summons to debtor.

Arranging swearing of affidavit in support.

Filing documents with the High Court.

Arranging service of documents, and preparing, arranging swearing of, and filing affidavit of service

                                Disbursements at this step will include Court filing fees, service fees, and our office disbursement of $50.

                                If the individual does not oppose the creditor's application, move to Individual Step Six.

Step Six – Order for Adjudication - $750

                                On the date allocated for the first call of the creditor's application, we recommend seeking an order for adjudication. Our fee includes:

Preparing the draft form of order for adjudication.

Appearing at, or arranging for an agent to appear at, the first call of the creditor's application.

Sealing order for adjudication.

                                Disbursements at this step will include Court filing fees, agency fees (if an agent is required for an out-of-town Court appearance), and our office disbursement of $50.

                                At this point, the Official Assignee will be responsible for repaying the individual's debt out of the assets available in his or her estate, to the extent those assets are able to repay the debt. The creditor will submit a proof of debt in the bankruptcy when prompted by the Official Assignee. No further recovery action may be taken against the individual.

Court Filing and Other Fees

The filing fees payable in the District Court are set out here. The High Court's filing fees are set out here.

Disputes Tribunal

We have limited our fixed fee debt recovery services to debts worth more than $15,000 because debts up to that amount, and up to $20,000 if all parties agree, are within the jurisdiction of the Disputes Tribunal. Parties to hearings in the Disputes Tribunal usually represent themselves, as lawyers cannot represent them.

                Disclaimer:  This guide is not, and must not be relied upon as, legal advice.  The guide is a simple summary prepared by Evolution Lawyers for the general benefit of its clients.  Your use or reliance upon this guide for any purpose is entirely at your own risk.

{% endblock %}


text:
export const getServerSideProps = () => {
  return {
    props: {
      hello: 'world',
      random: Math.random(),
    },
  }
}

export default function Page(props) {
  return (
    <>

getServerSideProps page

{JSON.stringify(props)}

    </>
  )
}


text: class CannotPopulateForDateOutsideExistingCycles(Exception): pass


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28856_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">PETROLEU

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">STATEMENT

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">This statement is being sent in order to comply with NDAC 43-02-03-16 (Application for permit to drill and recomplete) which states (in part that) "confirmation that a legal street address has been requested for the well site, and well facility if separate from the well site, and the proposed road access to the
nearest existing public road". On the date noted below a legal street address was requested from the appropriate county office.

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">April 3, 2014 Mountrail County Corey B — Mountrail County Sheriff's Dept.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Pad 1
Helling Trust Federal 5494 41-22 28 Helling Trust Federal 5494 41-22 11T2 Helling Trust Federal 5494 41-22 8T Helling Trust Federal 5494 41—22 14T3
Pad 2
Helling Trust Federal 5494 42-22 38 Helling Trust Federal 5494 42—22 12T2 Helling Trust Federal 5494 42-22 9T Helling Trust Federal 5494 42-22 15T3
Pad 3
Helling Trust Federal 5494 43-22 43 Helling Trust Federal 5494 43-22 13T2 Helling Trust Federal 5494 43—22 10T Helling Trust Federal 5494 43-22 16T3

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Pad 4
Helling Trust Federal 5494 44-22 SB Helling Trust Federal 5494 44—22 GB Helling Trust Federal 5494 44-22/7B

    <p class="styleSans58.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
Lauri M. Stanfield Regulatory Specialist Oasis Petroleum North America, LLC


text:
describe('Karmic Balance', function() {
    integration(function() {
        describe('Karmic Balance', function() {
            beforeEach(function() {
                this.setupTest({
                    phase: 'draw',
                    player1: {
                        hand: ['karmic-balance', 'court-games'],
                        conflictDiscard: ['banzai', 'banzai', 'banzai']
                    },
                    player2: {
                        hand: ['banzai', 'banzai'],
                        conflictDiscard: ['banzai']
                    }
                });
                this.karmicBalance = this.player1.findCardByName('karmic-balance');
            });

            it('should not be able to be played if honor dials are unequal', function() {
                this.player1.clickPrompt('1');
                this.player2.clickPrompt('2');
                expect(this.player1).toHavePrompt('Action Window');
                this.player1.clickCard(this.karmicBalance);
                expect(this.player1).toHavePrompt('Action Window');
            });

            it('should be able to be played if honor dials are equal', function() {
                this.player1.clickPrompt('1');
                this.player2.clickPrompt('1');
                expect(this.player1).toHavePrompt('Action Window');
                this.player1.clickCard(this.karmicBalance);
                expect(this.player2).toHavePrompt('Action Window');
            });

            describe('if it resolves', function() {
                beforeEach(function() {
                    this.chat = spyOn(this.game, 'addMessage');
                    this.player1.clickPrompt('1');
                    this.player2.clickPrompt('1');
                    this.player1.clickCard(this.karmicBalance);
                });

                it('should shuffle both player\'s hand and conflict discard pile into their conflict deck and draw 4 new cards', function() {
                    expect(this.player1.player.hand.size()).toBe(4);
                    expect(this.player1.player.conflictDiscardPile.size()).toBe(0);
                    expect(this.player2.player.hand.size()).toBe(4);
                    expect(this.player2.player.conflictDiscardPile.size()).toBe(0);
                    expect(this.chat).toHaveBeenCalledWith('{0} is shuffling their conflict deck', this.player1.player);
                    expect(this.chat).toHaveBeenCalledWith('{0} is shuffling their conflict deck', this.player2.player);
                });

                it('should only log 1 shuffling chat message per player', function() {
                    let player1Count = this.chat.calls.allArgs().filter(c => {
                        return c[0] === '{0} is shuffling their conflict deck' && c[1] === this.player1.player;
                    }).length;
                    let player2Count = this.chat.calls.allArgs().filter(c => {
                        return c[0] === '{0} is shuffling their conflict deck' && c[1] === this.player2.player;
                    }).length;
                    expect(player1Count).toBe(1);
                    expect(player2Count).toBe(1);
                });

                it('should remove itself from the game', function() {
                    expect(this.karmicBalance.location).toBe('removed from game');
                });
            });

        });
    });
});


text:
alter table cubes add column grouping_column varchar(40);
alter table dimensions add column cube_column_name varchar(40);
alter table dimensions add column dimension_order int;
alter table measures add column cube_column_name varchar(40);


text:
![Reading Light in action!](https://raw.githubusercontent.com/DeadlyBrad42/ArduinoProjects/master/ReadingLight/ReadingLight.gif)

Turns on an LED when the light sensor detects low levels of light.


text:
import unittest
import lgprime

class TestLargePrime(unittest.TestCase):
    def setUp(self):
        self.lgPrime = lgprime.LgPrime()

    def testInitial(self):
        self.lgPrime.setNumber(13195)
        assert self.lgPrime.lgPrimeNum() == (29), "incorrect answer %d" % self.lgPrime.lgPrimeNum()

    def testFinal(self):
        self.lgPrime.setNumber(600851475143)
        assert self.lgPrime.lgPrimeNum() == (6857), "incorrect answer %d" % self.lgPrime.lgPrimeNum()

lgPrimeTestSuite = unittest.TestSuite()

lgPrimeTestSuite.addTest(TestLargePrime("testInitial"))
lgPrimeTestSuite.addTest(TestLargePrime("testFinal"))

runner = unittest.TextTestRunner()
runner.run(lgPrimeTestSuite)


text:
import os
import django

DEBUG = os.environ.get('DEBUG', False)
TEMPLATE_DEBUG = DEBUG
LOG_LEVEL = os.environ.get('DJANGO_LOG_LEVEL', 'INFO')

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DATA_DIR = os.environ.get('OPENSHIFT_DATA_DIR', 'data')
if not os.path.exists(DATA_DIR):
    os.makedirs(DATA_DIR)

LOG_DIR = os.environ.get('OPENSHIFT_LOG_DIR', 'log')
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

PUBLIC_DIR = os.path.join(os.environ.get('OPENSHIFT_REPO_DIR', ''), 'wsgi/static')

if 'OPENSHIFT_POSTGRESQL_DB_HOST' in os.environ:
    DATABASES['default']['NAME'] = os.environ['OPENSHIFT_APP_NAME']
    DATABASES['default']['USER'] = os.environ['OPENSHIFT_POSTGRESQL_DB_USERNAME']
    DATABASES['default']['PASSWORD'] = os.environ['OPENSHIFT_POSTGRESQL_DB_PASSWORD']
    DATABASES['default']['HOST'] = os.environ['OPENSHIFT_POSTGRESQL_DB_HOST']
    DATABASES['default']['PORT'] = os.environ['OPENSHIFT_POSTGRESQL_DB_PORT']
    DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2'

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'

def get_databases(base_dir):
    return {
        'default': {
            'ENGINE': os.environ.get('DJANGO_DB_ENGINE',
                'django.db.backends.sqlite3'),
            'NAME': os.environ.get('DJANGO_DB_NAME',
                os.path.join(base_dir, 'db.sqlite3')),
            'USER': os.environ.get('DJANGO_DB_USER', ''),
        }
    }

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = [
    # Django apps
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # test apps
    'select2_foreign_key',
    'select2_generic_foreign_key',
    'select2_many_to_many',
    'select2_one_to_one',
    'select2_generic_m2m',
    'select2_taggit',
    'select2_tagulous',
    'select2_outside_admin',
    'secure_data',
    'linked_data',

    # unit test app
    'tests',

    # Autocomplete
    'dal',
    # Enable plugins
    'dal_select2',
    'dal_queryset_sequence',

    # Project apps
    'django_extensions',
    'sbo_selenium',
    'genericm2m',
    'taggit',
    'tagulous',
]

if django.VERSION < (1, 10):
    # Doesn't support dj110
    # https://bitbucket.org/tkhyn/django-gm2m/issues/19
    INSTALLED_APPS += ['gm2m', 'select2_gm2m']

INSTALLED_APPS = INSTALLED_APPS + ['django.contrib.admin']

DATABASES = get_databases(BASE_DIR)

ROOT_URLCONF = 'urls'
WSGI_APPLICATION = 'wsgi.application'

SECRET_KEY = '58$1jvc332=lyfk_m^jl6ody$7pbk18nm95==!r$7m5!2dp%l@'
DEBUG = True
ALLOWED_HOSTS = []

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

AUTH_PASSWORD_VALIDATORS = []
DJANGO_LIVE_TEST_SERVER_ADDRESS="localhost:8000-8010,8080,9200-9300"

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

DNS = os.environ.get('OPENSHIFT_APP_DNS', None),
if DNS:
    ALLOWED_HOSTS += DNS

SITE_ID = 1

from socket import gethostname
ALLOWED_HOSTS = [
    gethostname(),
]

STATIC_URL = '/public/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'public', 'static')

if DATA_DIR:
    MEDIA_URL = '/static/media/'
    MEDIA_ROOT = os.path.join(DATA_DIR, 'media')

if PUBLIC_DIR:
    STATIC_URL = '/static/collected/'
    STATIC_ROOT = os.path.join(PUBLIC_DIR, 'collected')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(os.path.join(PROJECT_ROOT, 'templates')),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

SELENIUM_PAGE_LOAD_TIMEOUT = 100
SELENIUM_TIMEOUT = 100


text:
using QuantumType = System.Byte;
#elif Q16
using QuantumType = System.UInt16;
#elif Q16HDRI
using QuantumType = System.Single;
#else
#error Not implemented!
#endif

namespace ImageMagick
{
    /// <summary>
    /// Sets the fill color to be used for drawing filled objects.
    /// </summary>
    public sealed partial class DrawableFillColor : IDrawable, IDrawingWand
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DrawableFillColor"/> class.
        /// </summary>
        /// <param name="color">The color to use.</param>
        public DrawableFillColor(IMagickColor<QuantumType> color)
        {
            Throw.IfNull(nameof(color), color);

            Color = color;
        }

        /// <summary>
        /// Gets or sets the color to use.
        /// </summary>
        public IMagickColor<QuantumType> Color { get; set; }

        /// <summary>
        /// Draws this instance with the drawing wand.
        /// </summary>
        /// <param name="wand">The want to draw on.</param>
        void IDrawingWand.Draw(DrawingWand wand)
            => wand?.FillColor(Color);
    }
}


text:
(function() {
  'use strict';

  describe('[Migration] Services', function() {
    var database = 'test';
    var sqlStorageMigrationService;
    var localStorageService;

    // load the controller's module
    beforeEach(module('sf.sqlStorage',
    function($exceptionHandlerProvider, sqlStorageServiceProvider) {
      $exceptionHandlerProvider.mode('log');
      sqlStorageServiceProvider.addUpdater({
        version: 1.0,
        method: function() { return Promise.resolve(); },
      });
      sqlStorageServiceProvider.addUpdater({
        version: 2.0,
        method: function() { return Promise.resolve(); },
      });
      sqlStorageServiceProvider.addUpdater({
        version: 1.1,
        method: function() { return Promise.resolve(); },
      });
      sqlStorageServiceProvider.addUpdater({
        version: 10,
        method: function() { return Promise.resolve(); },
      });
      sqlStorageServiceProvider.addUpdater({
        version: 20,
        method: function() { return Promise.resolve(); },
      });
    }));

    // Initialize the controller and a mock scope
    beforeEach(inject(function (_sqlStorageMigrationService_, _localStorageService_) {
      sqlStorageMigrationService = _sqlStorageMigrationService_;
      localStorageService = _localStorageService_;
    }));

    describe('Instantiate', function() {
      it('should update available updaters', inject(function($timeout, $q) {
        var version10 = sinon.stub(sqlStorageMigrationService._updateMethods, '1').returns($q.when());
        var version11 = sinon.stub(sqlStorageMigrationService._updateMethods, '1.1').returns($q.when());

        sqlStorageMigrationService.updateManager(database, 1.0);
        $timeout.flush();
        expect(version10.callCount).equal(0);
        expect(version11.callCount).equal(1);

      }));
      it('should update available updaters in the right order', inject(function($timeout, $q) {
        var version1 = sinon.stub(sqlStorageMigrationService._updateMethods, '1').returns($q.when());
        var version11 = sinon.stub(sqlStorageMigrationService._updateMethods, '1.1').returns($q.when());
        var version2 = sinon.stub(sqlStorageMigrationService._updateMethods, '2').returns($q.when());
        var version10 = sinon.stub(sqlStorageMigrationService._updateMethods, '10').returns($q.when());
        var version20 = sinon.stub(sqlStorageMigrationService._updateMethods, '20').returns($q.when());
        var setLocal = sinon.stub(localStorageService, 'set');

        sqlStorageMigrationService.updateManager(database, 1.0);
        $timeout.flush();
        expect(version1.callCount).equal(0);
        expect(version11.callCount).equal(1);
        expect(version2.callCount).equal(1);
        expect(version10.callCount).equal(1);
        expect(version20.callCount).equal(1);

        expect(setLocal.callCount).equal(4);

        expect(setLocal.args[0][1]).equal(1.1);
        expect(setLocal.args[1][1]).equal(2);
        expect(setLocal.args[2][1]).equal(10);
        expect(setLocal.args[3][1]).equal(20);
      }));
      it('should stop on first fail', inject(function($timeout, $q) {
        var version1 = sinon.stub(sqlStorageMigrationService._updateMethods, '1').returns($q.when());
        var version11 = sinon.stub(sqlStorageMigrationService._updateMethods, '1.1').returns($q.when());
        var version2 = sinon.stub(sqlStorageMigrationService._updateMethods, '2').returns($q.when());
        var version10 = sinon.stub(sqlStorageMigrationService._updateMethods, '10').returns($q.reject());
        var version20 = sinon.stub(sqlStorageMigrationService._updateMethods, '20').returns($q.when());
        var setLocal = sinon.stub(localStorageService, 'set');

        sqlStorageMigrationService.updateManager(database, 1.0);
        $timeout.flush();
        expect(version1.callCount).equal(0);
        expect(version11.callCount).equal(1);
        expect(version2.callCount).equal(1);
        expect(version10.callCount).equal(1);
        expect(version20.callCount).equal(0);

        expect(setLocal.callCount).equal(2);

        expect(setLocal.args[0][1]).equal(1.1);
        expect(setLocal.args[1][1]).equal(2);
      }));
    });

  });
}());


text:
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package tabletmanager exports the ActionAgent object. It keeps the local tablet
state, starts / stops all associated services (query service,
update stream, binlog players, ...), and handles tabletmanager RPCs
to update the state.

The agent is responsible for maintaining the tablet record in the
topology server. Only 'vtctl DeleteTablet'
should be run by other processes, everything else should ask
the tablet server to make the change.

Most RPC calls lock the actionMutex, except the easy read-only ones.
RPC calls that change the tablet record will also call updateState.

See rpc_server.go for all cases, and which actions take the actionMutex,
and which run changeCallback.
*/
package tabletmanager

import (
	"encoding/hex"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"sync"
	"time"

	"golang.org/x/net/context"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/history"
	"github.com/youtube/vitess/go/netutil"
	"github.com/youtube/vitess/go/stats"
	"github.com/youtube/vitess/go/vt/binlog"
	"github.com/youtube/vitess/go/vt/binlog/binlogplayer"
	"github.com/youtube/vitess/go/vt/dbconfigs"
	"github.com/youtube/vitess/go/vt/health"
	"github.com/youtube/vitess/go/vt/key"
	"github.com/youtube/vitess/go/vt/mysqlctl"
	"github.com/youtube/vitess/go/vt/tabletserver"
	"github.com/youtube/vitess/go/vt/tabletserver/planbuilder"
	"github.com/youtube/vitess/go/vt/tabletserver/tabletservermock"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topo/topoproto"
	"github.com/youtube/vitess/go/vt/topotools"

	querypb "github.com/youtube/vitess/go/vt/proto/query"
	topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)

// Query rules from keyrange
const keyrangeQueryRules string = "KeyrangeQueryRules"

var (
	tabletHostname = flag.String("tablet_hostname", "", "if not empty, this hostname will be assumed instead of trying to resolve it")
)

// ActionAgent is the main class for the agent.
type ActionAgent struct {
	// The following fields are set during creation
	QueryServiceControl tabletserver.Controller
	UpdateStream        binlog.UpdateStreamControl
	HealthReporter      health.Reporter
	TopoServer          topo.Server
	TabletAlias         *topodatapb.TabletAlias
	MysqlDaemon         mysqlctl.MysqlDaemon
	DBConfigs           dbconfigs.DBConfigs
	SchemaOverrides     []tabletserver.SchemaOverride
	BinlogPlayerMap     *BinlogPlayerMap

	// exportStats is set only for production tablet.
	exportStats bool

	// statsTabletType is set to expose the current tablet type,
	// only used if exportStats is true.
	statsTabletType *stats.String

	// batchCtx is given to the agent by its creator, and should be used for
	// any background tasks spawned by the agent.
	batchCtx context.Context

	// finalizeReparentCtx represents the background finalize step of a
	// TabletExternallyReparented call.
	finalizeReparentCtx context.Context

	// History of the health checks, public so status
	// pages can display it
	History            *history.History
	lastHealthMapCount *stats.Int

	// actionMutex is there to run only one action at a time. If
	// both agent.actionMutex and agent.mutex needs to be taken,
	// take actionMutex first.
	actionMutex sync.Mutex

	// initReplication remembers whether an action has initialized
	// replication.  It is protected by actionMutex.
	initReplication bool

	// mutex protects the following fields, only hold the mutex
	// to update the fields, nothing else.
	mutex            sync.Mutex
	_tablet          *topo.TabletInfo
	_tabletControl   *topodatapb.Shard_TabletControl
	_waitingForMysql bool

	// if the agent is healthy, this is nil. Otherwise it contains
	// the reason we're not healthy.
	_healthy error

	// this is the last time health check ran
	_healthyTime time.Time

	// replication delay the last time we got it
	_replicationDelay time.Duration

	// last time we ran TabletExternallyReparented
	_tabletExternallyReparentedTime time.Time
}

func loadSchemaOverrides(overridesFile string) []tabletserver.SchemaOverride {
	var schemaOverrides []tabletserver.SchemaOverride
	if overridesFile == "" {
		return schemaOverrides
	}
	data, err := ioutil.ReadFile(overridesFile)
	if err != nil {
		log.Warningf("can't read overridesFile %v: %v", overridesFile, err)
		return schemaOverrides
	}
	if err = json.Unmarshal(data, &schemaOverrides); err != nil {
		log.Warningf("can't parse overridesFile %v: %v", overridesFile, err)
		return schemaOverrides
	}
	data, _ = json.MarshalIndent(schemaOverrides, "", "  ")
	log.Infof("schemaOverrides: %s\n", data)
	return schemaOverrides
}

// NewActionAgent creates a new ActionAgent and registers all the
// associated services.
//
// batchCtx is the context that the agent will use for any background tasks
// it spawns.
func NewActionAgent(
	batchCtx context.Context,
	mysqld mysqlctl.MysqlDaemon,
	queryServiceControl tabletserver.Controller,
	tabletAlias *topodatapb.TabletAlias,
	dbcfgs dbconfigs.DBConfigs,
	mycnf *mysqlctl.Mycnf,
	port, gRPCPort int32,
	overridesFile string,
) (agent *ActionAgent, err error) {
	schemaOverrides := loadSchemaOverrides(overridesFile)

	topoServer := topo.GetServer()

	agent = &ActionAgent{
		QueryServiceControl: queryServiceControl,
		HealthReporter:      health.DefaultAggregator,
		batchCtx:            batchCtx,
		TopoServer:          topoServer,
		TabletAlias:         tabletAlias,
		MysqlDaemon:         mysqld,
		DBConfigs:           dbcfgs,
		SchemaOverrides:     schemaOverrides,
		History:             history.New(historyLength),
		lastHealthMapCount:  stats.NewInt("LastHealthMapCount"),
		_healthy:            fmt.Errorf("healthcheck not run yet"),
	}
	agent.registerQueryRuleSources()

	// try to initialize the tablet if we have to
	if err := agent.InitTablet(port, gRPCPort); err != nil {
		return nil, fmt.Errorf("agent.InitTablet failed: %v", err)
	}

	// Publish and set the TargetTabletType. Not a global var
	// since it should never be changed.
	statsTabletType := stats.NewString("TargetTabletType")
	statsTabletType.Set(*targetTabletType)

	// Create the TabletType stats
	agent.exportStats = true
	agent.statsTabletType = stats.NewString("TabletType")

	// Start the binlog player services, not playing at start.
	agent.BinlogPlayerMap = NewBinlogPlayerMap(topoServer, mysqld, func() binlogplayer.VtClient {
		return binlogplayer.NewDbClient(&agent.DBConfigs.Filtered)
	})
	RegisterBinlogPlayerMap(agent.BinlogPlayerMap)

	// try to figure out the mysql port
	mysqlPort := mycnf.MysqlPort
	if mysqlPort == 0 {
		// we don't know the port, try to get it from mysqld
		var err error
		mysqlPort, err = mysqld.GetMysqlPort()
		if err != nil {
			log.Warningf("Cannot get current mysql port, will use 0 for now: %v", err)
		}
	}

	// Start will get the tablet info, and update our state from it
	if err := agent.Start(batchCtx, int32(mysqlPort), port, gRPCPort, true); err != nil {
		return nil, err
	}

	// register the RPC services from the agent
	agent.registerQueryService()

	// two cases then:
	// - restoreFromBackup is set: we restore, then initHealthCheck, all
	//   in the background
	// - restoreFromBackup is not set: we initHealthCheck right away
	if *restoreFromBackup {
		go func() {
			// restoreFromBackup wil just be a regular action
			// (same as if it was triggered remotely)
			if err := agent.RestoreFromBackup(batchCtx); err != nil {
				println(fmt.Sprintf("RestoreFromBackup failed: %v", err))
				log.Fatalf("RestoreFromBackup failed: %v", err)
			}

			// after the restore is done, start health check
			agent.initHealthCheck()
		}()
	} else {
		// synchronously start health check if needed
		agent.initHealthCheck()
	}

	return agent, nil
}

// NewTestActionAgent creates an agent for test purposes. Only a
// subset of features are supported now, but we'll add more over time.
func NewTestActionAgent(batchCtx context.Context, ts topo.Server, tabletAlias *topodatapb.TabletAlias, vtPort, grpcPort int32, mysqlDaemon mysqlctl.MysqlDaemon) *ActionAgent {
	agent := &ActionAgent{
		QueryServiceControl: tabletservermock.NewController(),
		UpdateStream:        binlog.NewUpdateStreamControlMock(),
		HealthReporter:      health.DefaultAggregator,
		batchCtx:            batchCtx,
		TopoServer:          ts,
		TabletAlias:         tabletAlias,
		MysqlDaemon:         mysqlDaemon,
		DBConfigs:           dbconfigs.DBConfigs{},
		SchemaOverrides:     nil,
		BinlogPlayerMap:     nil,
		History:             history.New(historyLength),
		lastHealthMapCount:  new(stats.Int),
		_healthy:            fmt.Errorf("healthcheck not run yet"),
	}
	if err := agent.Start(batchCtx, 0, vtPort, grpcPort, false); err != nil {
		panic(fmt.Errorf("agent.Start(%v) failed: %v", tabletAlias, err))
	}
	return agent
}

// NewComboActionAgent creates an agent tailored specifically to run
// within the vtcombo binary. It cannot be called concurrently,
// as it changes the flags.
func NewComboActionAgent(batchCtx context.Context, ts topo.Server, tabletAlias *topodatapb.TabletAlias, vtPort, grpcPort int32, queryServiceControl tabletserver.Controller, dbcfgs dbconfigs.DBConfigs, mysqlDaemon mysqlctl.MysqlDaemon, keyspace, shard, dbname, tabletType string) *ActionAgent {
	agent := &ActionAgent{
		QueryServiceControl: queryServiceControl,
		UpdateStream:        binlog.NewUpdateStreamControlMock(),
		HealthReporter:      health.DefaultAggregator,
		batchCtx:            batchCtx,
		TopoServer:          ts,
		TabletAlias:         tabletAlias,
		MysqlDaemon:         mysqlDaemon,
		DBConfigs:           dbcfgs,
		SchemaOverrides:     nil,
		BinlogPlayerMap:     nil,
		History:             history.New(historyLength),
		lastHealthMapCount:  new(stats.Int),
		_healthy:            fmt.Errorf("healthcheck not run yet"),
	}
	agent.registerQueryRuleSources()

	// initialize the tablet
	*initDbNameOverride = dbname
	*initKeyspace = keyspace
	*initShard = shard
	*initTabletType = tabletType
	if err := agent.InitTablet(vtPort, grpcPort); err != nil {
		panic(fmt.Errorf("agent.InitTablet failed: %v", err))
	}

	// and start the agent
	if err := agent.Start(batchCtx, 0, vtPort, grpcPort, false); err != nil {
		panic(fmt.Errorf("agent.Start(%v) failed: %v", tabletAlias, err))
	}
	return agent
}

// registerQueryRuleSources registers query rule sources under control of agent
func (agent *ActionAgent) registerQueryRuleSources() {
	agent.QueryServiceControl.RegisterQueryRuleSource(blacklistQueryRules)
}

// updateTabletFromTopo will read the tablet record from the topology,
// save it in the agent's tablet record, and return it.
func (agent *ActionAgent) updateTabletFromTopo(ctx context.Context) (*topo.TabletInfo, error) {
	tablet, err := agent.TopoServer.GetTablet(ctx, agent.TabletAlias)
	if err != nil {
		return nil, err
	}
	agent.mutex.Lock()
	agent._tablet = tablet
	agent.mutex.Unlock()
	return tablet, nil
}

func (agent *ActionAgent) setTablet(tablet *topo.TabletInfo) {
	agent.mutex.Lock()
	agent._tablet = tablet
	agent.mutex.Unlock()
}

// Tablet reads the stored TabletInfo from the agent, protected by mutex.
func (agent *ActionAgent) Tablet() *topo.TabletInfo {
	agent.mutex.Lock()
	tablet := agent._tablet
	agent.mutex.Unlock()
	return tablet
}

// Healthy reads the result of the latest healthcheck, protected by mutex.
// If that status is too old, it means healthcheck hasn't run for a while,
// and is probably stuck, this is not good, we're not healthy.
func (agent *ActionAgent) Healthy() (time.Duration, error) {
	agent.mutex.Lock()
	defer agent.mutex.Unlock()

	healthy := agent._healthy
	if healthy == nil {
		timeSinceLastCheck := time.Since(agent._healthyTime)
		if timeSinceLastCheck > *healthCheckInterval*3 {
			healthy = fmt.Errorf("last health check is too old: %s > %s", timeSinceLastCheck, *healthCheckInterval*3)
		}
	}

	return agent._replicationDelay, healthy
}

// BlacklistedTables reads the list of blacklisted tables from the TabletControl
// record (if any) stored in the agent, protected by mutex.
func (agent *ActionAgent) BlacklistedTables() []string {
	var blacklistedTables []string
	agent.mutex.Lock()
	if agent._tabletControl != nil {
		blacklistedTables = agent._tabletControl.BlacklistedTables
	}
	agent.mutex.Unlock()
	return blacklistedTables
}

// DisableQueryService reads the DisableQueryService field from the TabletControl
// record (if any) stored in the agent, protected by mutex.
func (agent *ActionAgent) DisableQueryService() bool {
	disable := false
	agent.mutex.Lock()
	if agent._tabletControl != nil {
		disable = agent._tabletControl.DisableQueryService
	}
	agent.mutex.Unlock()
	return disable
}

func (agent *ActionAgent) setTabletControl(tc *topodatapb.Shard_TabletControl) {
	agent.mutex.Lock()
	agent._tabletControl = tc
	agent.mutex.Unlock()
}

func (agent *ActionAgent) verifyTopology(ctx context.Context) error {
	tablet := agent.Tablet()
	if tablet == nil {
		return fmt.Errorf("agent._tablet is nil")
	}

	if err := topo.Validate(ctx, agent.TopoServer, agent.TabletAlias); err != nil {
		// Don't stop, it's not serious enough, this is likely transient.
		log.Warningf("tablet validate failed: %v %v", agent.TabletAlias, err)
	}

	return nil
}

func (agent *ActionAgent) verifyServingAddrs(ctx context.Context) error {
	ti := agent.Tablet()
	if !topo.IsRunningQueryService(ti.Type) {
		return nil
	}

	// Check to see our address is registered in the right place.
	return topotools.UpdateTabletEndpoints(ctx, agent.TopoServer, ti.Tablet)
}

// Start validates and updates the topology records for the tablet, and performs
// the initial state change callback to start tablet services.
// If initUpdateStream is set, update stream service will also be registered.
func (agent *ActionAgent) Start(ctx context.Context, mysqlPort, vtPort, gRPCPort int32, initUpdateStream bool) error {
	var err error
	if _, err = agent.updateTabletFromTopo(ctx); err != nil {
		return err
	}

	// find our hostname as fully qualified, and IP
	hostname := *tabletHostname
	if hostname == "" {
		hostname, err = netutil.FullyQualifiedHostname()
		if err != nil {
			return err
		}
	}
	ipAddrs, err := net.LookupHost(hostname)
	if err != nil {
		return err
	}
	ipAddr := ipAddrs[0]

	// Update bind addr for mysql and query service in the tablet node.
	f := func(tablet *topodatapb.Tablet) error {
		tablet.Hostname = hostname
		tablet.Ip = ipAddr
		if tablet.PortMap == nil {
			tablet.PortMap = make(map[string]int32)
		}
		if mysqlPort != 0 {
			// only overwrite mysql port if we know it, otherwise
			// leave it as is.
			tablet.PortMap["mysql"] = mysqlPort
		}
		if vtPort != 0 {
			tablet.PortMap["vt"] = vtPort
		} else {
			delete(tablet.PortMap, "vt")
		}
		delete(tablet.PortMap, "vts")
		if gRPCPort != 0 {
			tablet.PortMap["grpc"] = gRPCPort
		} else {
			delete(tablet.PortMap, "grpc")
		}
		return nil
	}
	if err := agent.TopoServer.UpdateTabletFields(ctx, agent.Tablet().Alias, f); err != nil {
		return err
	}

	// Reread to get the changes we just made
	tablet, err := agent.updateTabletFromTopo(ctx)
	if err != nil {
		return err
	}

	if err = agent.verifyTopology(ctx); err != nil {
		return err
	}

	if err = agent.verifyServingAddrs(ctx); err != nil {
		return err
	}

	// get and fix the dbname if necessary
	if !agent.DBConfigs.IsZero() {
		// Only for real instances
		// Update our DB config to match the info we have in the tablet
		if agent.DBConfigs.App.DbName == "" {
			agent.DBConfigs.App.DbName = topoproto.TabletDbName(tablet.Tablet)
		}
		if agent.DBConfigs.Filtered.DbName == "" {
			agent.DBConfigs.Filtered.DbName = topoproto.TabletDbName(tablet.Tablet)
		}
		agent.DBConfigs.App.Keyspace = tablet.Keyspace
		agent.DBConfigs.App.Shard = tablet.Shard
	}

	// create and register the RPC services from UpdateStream
	// (it needs the dbname, so it has to be delayed up to here,
	// but it has to be before updateState below that may use it)
	if initUpdateStream {
		us := binlog.NewUpdateStream(agent.MysqlDaemon, agent.DBConfigs.App.DbName)
		us.RegisterService()
		agent.UpdateStream = us
	}

	// initialize tablet server
	if err := agent.QueryServiceControl.InitDBConfig(querypb.Target{
		Keyspace:   tablet.Keyspace,
		Shard:      tablet.Shard,
		TabletType: tablet.Type,
	}, agent.DBConfigs, agent.SchemaOverrides, agent.MysqlDaemon); err != nil {
		return fmt.Errorf("failed to InitDBConfig: %v", err)
	}

	// export a few static variables
	if agent.exportStats {
		statsKeyspace := stats.NewString("TabletKeyspace")
		statsShard := stats.NewString("TabletShard")
		statsKeyRangeStart := stats.NewString("TabletKeyRangeStart")
		statsKeyRangeEnd := stats.NewString("TabletKeyRangeEnd")

		statsKeyspace.Set(tablet.Keyspace)
		statsShard.Set(tablet.Shard)
		if key.KeyRangeIsPartial(tablet.KeyRange) {
			statsKeyRangeStart.Set(hex.EncodeToString(tablet.KeyRange.Start))
			statsKeyRangeEnd.Set(hex.EncodeToString(tablet.KeyRange.End))
		}
	}

	// initialize the key range query rule
	if err := agent.initializeKeyRangeRule(ctx, tablet.Keyspace, tablet.KeyRange); err != nil {
		return err
	}

	// update our state
	oldTablet := &topodatapb.Tablet{}
	if err = agent.updateState(ctx, oldTablet, "Start"); err != nil {
		log.Warningf("Initial updateState failed, will need a state change before running properly: %v", err)
	}

	// run a background task to rebuild the SrvKeyspace in our cell/keyspace
	// if it doesn't exist yet
	go agent.maybeRebuildKeyspace(tablet.Alias.Cell, tablet.Keyspace)

	return nil
}

// Stop shutdowns this agent.
func (agent *ActionAgent) Stop() {
	if agent.UpdateStream != nil {
		agent.UpdateStream.Disable()
	}
	if agent.BinlogPlayerMap != nil {
		agent.BinlogPlayerMap.StopAllPlayersAndReset()
	}
	if agent.MysqlDaemon != nil {
		agent.MysqlDaemon.Close()
	}
}

// hookExtraEnv returns the map to pass to local hooks
func (agent *ActionAgent) hookExtraEnv() map[string]string {
	return map[string]string{"TABLET_ALIAS": topoproto.TabletAliasString(agent.TabletAlias)}
}

// checkTabletMysqlPort will check the mysql port for the tablet is good,
// and if not will try to update it. It returns the modified Tablet record,
// if it was changed.
func (agent *ActionAgent) checkTabletMysqlPort(ctx context.Context, tablet *topo.TabletInfo) *topo.TabletInfo {
	mport, err := agent.MysqlDaemon.GetMysqlPort()
	if err != nil {
		log.Warningf("Cannot get current mysql port, not checking it: %v", err)
		return nil
	}

	if mport == tablet.PortMap["mysql"] {
		return nil
	}

	log.Warningf("MySQL port has changed from %v to %v, updating it in tablet record", tablet.PortMap["mysql"], mport)
	if err := agent.TopoServer.UpdateTabletFields(ctx, tablet.Alias, func(t *topodatapb.Tablet) error {
		t.PortMap["mysql"] = mport
		return nil
	}); err != nil {
		log.Warningf("Failed to update tablet record, may use old mysql port")
		return nil
	}

	// update worked, return the new record
	tablet.PortMap["mysql"] = mport
	return tablet
}

// initializeKeyRangeRule will create and set the key range rules
func (agent *ActionAgent) initializeKeyRangeRule(ctx context.Context, keyspace string, keyRange *topodatapb.KeyRange) error {
	// check we have a partial key range
	if !key.KeyRangeIsPartial(keyRange) {
		log.Infof("Tablet covers the full KeyRange, not adding KeyRange query rule")
		return nil
	}

	// read the keyspace to get the sharding column name
	keyspaceInfo, err := agent.TopoServer.GetKeyspace(ctx, keyspace)
	if err != nil {
		return fmt.Errorf("cannot read keyspace %v to get sharding key: %v", keyspace, err)
	}
	if keyspaceInfo.ShardingColumnName == "" {
		return fmt.Errorf("keyspace %v has an empty ShardingColumnName, cannot setup KeyRange rule", keyspace)
	}

	// create the rules
	log.Infof("Restricting to keyrange: %v", key.KeyRangeString(keyRange))
	keyrangeRules := tabletserver.NewQueryRules()
	dmlPlans := []struct {
		planID   planbuilder.PlanType
		onAbsent bool
	}{
		{planbuilder.PlanInsertPK, true},
		{planbuilder.PlanInsertSubquery, true},
		{planbuilder.PlanPassDML, false},
		{planbuilder.PlanDMLPK, false},
		{planbuilder.PlanDMLSubquery, false},
		{planbuilder.PlanUpsertPK, false},
	}
	for _, plan := range dmlPlans {
		qr := tabletserver.NewQueryRule(
			fmt.Sprintf("enforce %v range for %v", keyspaceInfo.ShardingColumnName, plan.planID),
			fmt.Sprintf("%v_not_in_range_%v", keyspaceInfo.ShardingColumnName, plan.planID),
			tabletserver.QRFail,
		)
		qr.AddPlanCond(plan.planID)
		err := qr.AddBindVarCond(keyspaceInfo.ShardingColumnName, plan.onAbsent, true, tabletserver.QRNotIn, keyRange)
		if err != nil {
			return fmt.Errorf("Unable to add key range rule: %v", err)
		}
		keyrangeRules.Add(qr)
	}

	// and load them
	agent.QueryServiceControl.RegisterQueryRuleSource(keyrangeQueryRules)
	if err := agent.QueryServiceControl.SetQueryRules(keyrangeQueryRules, keyrangeRules); err != nil {
		return fmt.Errorf("failed to load query rule set %s: %s", keyrangeQueryRules, err)
	}
	return nil
}


text:
package org.apache.asterix.formats.base;

import java.util.List;

import org.apache.asterix.om.functions.IFunctionDescriptor;
import org.apache.asterix.om.functions.IFunctionDescriptorFactory;
import org.apache.asterix.om.types.ARecordType;
import org.apache.asterix.om.types.IAType;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.common.utils.Triple;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.IAlgebricksConstantValue;
import org.apache.hyracks.algebricks.core.algebra.expressions.IExpressionEvalSizeComputer;
import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
import org.apache.hyracks.algebricks.core.algebra.expressions.ScalarFunctionCallExpression;
import org.apache.hyracks.algebricks.data.IBinaryBooleanInspectorFactory;
import org.apache.hyracks.algebricks.data.IBinaryComparatorFactoryProvider;
import org.apache.hyracks.algebricks.data.IBinaryHashFunctionFactoryProvider;
import org.apache.hyracks.algebricks.data.IBinaryHashFunctionFamilyProvider;
import org.apache.hyracks.algebricks.data.IBinaryIntegerInspectorFactory;
import org.apache.hyracks.algebricks.data.INormalizedKeyComputerFactoryProvider;
import org.apache.hyracks.algebricks.data.IPrinterFactoryProvider;
import org.apache.hyracks.algebricks.data.ISerializerDeserializerProvider;
import org.apache.hyracks.algebricks.data.ITypeTraitProvider;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;
import org.apache.hyracks.api.dataflow.value.INullWriterFactory;
import org.apache.hyracks.api.dataflow.value.IPredicateEvaluatorFactoryProvider;

public interface IDataFormat {
    public void registerRuntimeFunctions(List<IFunctionDescriptorFactory> funcDescriptor) throws AlgebricksException;

    public ISerializerDeserializerProvider getSerdeProvider();

    public IBinaryHashFunctionFactoryProvider getBinaryHashFunctionFactoryProvider();

    public IBinaryComparatorFactoryProvider getBinaryComparatorFactoryProvider();

    public ITypeTraitProvider getTypeTraitProvider();

    public IBinaryBooleanInspectorFactory getBinaryBooleanInspectorFactory();

    public IBinaryIntegerInspectorFactory getBinaryIntegerInspectorFactory();

    // QQQ Refactor: Make this accept an APIFramework.OutputFormat parameter
    public IPrinterFactoryProvider getADMPrinterFactoryProvider();

    public IPrinterFactoryProvider getLosslessJSONPrinterFactoryProvider();

    public IPrinterFactoryProvider getCSVPrinterFactoryProvider();

    public IPrinterFactoryProvider getCleanJSONPrinterFactoryProvider();

    public INullWriterFactory getNullWriterFactory();

    public Triple<IScalarEvaluatorFactory, ScalarFunctionCallExpression, IAType> partitioningEvaluatorFactory(
            ARecordType recType, List<String> fldName) throws AlgebricksException;

    public IScalarEvaluatorFactory getFieldAccessEvaluatorFactory(ARecordType recType, List<String> fldName,
            int recordColumn) throws AlgebricksException;

    public IFunctionDescriptor resolveFunction(ILogicalExpression expr, IVariableTypeEnvironment typeEnvironment)
            throws AlgebricksException;

    public IScalarEvaluatorFactory getConstantEvalFactory(IAlgebricksConstantValue value) throws AlgebricksException;

    public IScalarEvaluatorFactory[] createMBRFactory(ARecordType recType, List<String> fldName, int recordColumn,
            int dimension, List<String> filterFieldName) throws AlgebricksException;

    public IExpressionEvalSizeComputer getExpressionEvalSizeComputer();

    public INormalizedKeyComputerFactoryProvider getNormalizedKeyComputerFactoryProvider();

    public IBinaryHashFunctionFamilyProvider getBinaryHashFunctionFamilyProvider();

    public IPredicateEvaluatorFactoryProvider getPredicateEvaluatorFactoryProvider();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/church-leaders/quorums-of-the-twelve-apostles/19th-century/francis-m-lyman" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/quorums-of-the-twelve-apostles/19th-century/francis-m-lyman</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Francis M. Lyman</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/quorums-of-the-twelve-apostles/19th-century/francis-m-lyman</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/quorums-of-the-twelve-apostles/19th-century/francis-m-lyman</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
package org.osgi.scr.rmi.api;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Collection;

import org.osgi.framework.dto.ServiceReferenceDTO;
import org.osgi.service.component.runtime.dto.serial.ComponentConfigurationDTO;

/**
 * Remote abstraction
 */
public interface IRMIServiceSerializer extends Remote {

  //	Collection<ComponentConfigurationDTO> getComponentConfigurationDTOsRMI(ComponentDescriptionDTO arg0) throws RemoteException;
  //
  //	ComponentDescriptionDTO getComponentDescriptionDTORMI(Bundle arg0, String arg1)  throws RemoteException;
  //
  //	Collection<ComponentDescriptionDTO> getComponentDescriptionDTOsRMI(Bundle[] arg0) throws RemoteException;
  //
  //	Collection<ComponentDescriptionDTO> getAllComponentDescriptionDTORMI() throws RemoteException;

  Collection<ComponentConfigurationDTO> getAllComponentConfigurationDTORMI() throws RemoteException;

  Collection<ServiceReferenceDTO> getAllServiceReferenceDTORMI() throws RemoteException;

}


text:
<?php
namespace common\extensions\logging;
use \CComponent;
use \ILogFilter;
use \CLogger;
use \Yii;

class LogFilter extends CComponent implements ILogFilter
{
    /**
     * @var boolean whether to prefix each log message with the current user session ID.
     * Defaults to false.
     */
    public $prefixSession = false;
    /**
     * @var boolean whether to prefix each log message with the current user
     * {@link CWebUser::name name} and {@link CWebUser::id ID}. Defaults to false.
     */
    public $prefixUser = false;
    /**
     * @var boolean whether to log the current user name and ID. Defaults to true.
     */
    public $logUser = true;
    /**
     * @var array list of the PHP predefined variables that should be logged.
     * Note that a variable must be accessible via $GLOBALS. Otherwise it won't be logged.
     */
    public $logVars = array('_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER');

    /**
     * Filters the given log messages.
     * This is the main method of CLogFilter. It processes the log messages
     * by adding context information, etc.
     * @param array $logs the log messages
     * @return array
     */
    public function filter(&$logs)
    {
        if (!empty($logs)) {
            if (($message = $this->getContext()) !== '') {
               foreach($logs as &$row){
                   $row[0] = $row[0] . json_encode($message);
               }
            }
            $this->format($logs);
        }

        return $logs;
    }

    /**
     * Formats the log messages.
     * The default implementation will prefix each message with session ID
     * if {@link prefixSession} is set true. It may also prefix each message
     * with the current user's name and ID if {@link prefixUser} is true.
     * @param array $logs the log messages
     */
    protected function format(&$logs)
    {
        $prefix = '';
        if ($this->prefixSession && ($id = session_id()) !== '')
            $prefix .= "[$id]";
        if ($this->prefixUser && ($user = Yii::app()->getComponent('user', false)) !== null)
            $prefix .= '[' . $user->getName() . '][' . $user->getId() . ']';
        if ($prefix !== '') {
            foreach ($logs as &$log)
                $log[0] = $prefix . ' ' . $log[0];
        }
    }

    /**
     * Generates the context information to be logged.
     * The default implementation will dump user information, system variables, etc.
     * @return string the context information. If an empty string, it means no context information.
     */
    protected function getContext()
    {
        $context = array();
        if ($this->logUser && ($user = Yii::app()->getComponent('user', false)) !== null){
            $context['user'] = 'User: ' . $user->getName() . ' (ID: ' . $user->getId() . ')';
        }

        $context['uri'] = $GLOBALS['_SERVER']['REQUEST_URI'];

        return  $context;
    }
}