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

/**
 * Default success callback for ajax-requests in this module
 * @type {Function}
 */
var defaultSuccessCallback = function(data, ajaxOptions, params) {
  App.router.get('userSettingsController').dataLoading('show_bg').done(function(initValue) {
    params.query && params.query.set('status', 'SUCCESS');
    if (initValue) {
      App.router.get('backgroundOperationsController').showPopup();
    }
  });
};
/**
 * Default error callback for ajax-requests in this module
 * @param {Object} xhr
 * @param {String} textStatus
 * @param {String} error
 * @param {Object} opt
 * @param {Object} params
 * @type {Function}
 */
var defaultErrorCallback = function(xhr, textStatus, error, opt, params) {
  params.query && params.query.set('status', 'FAIL');
  App.ajax.defaultErrorHandler(xhr, opt.url, 'POST', xhr.status);
};

/**
 * Contains helpful utilities for handling batch and scheduled requests.
 */
module.exports = {

  /**
   * Some services have components which have a need for rolling restarts. This
   * method returns the name of the host-component which supports rolling
   * restarts for a service.
   * @param {String} serviceName
   */
  getRollingRestartComponentName: function(serviceName) {
    var rollingRestartComponents = {
      HDFS: 'DATANODE',
      YARN: 'NODEMANAGER',
      HBASE: 'HBASE_REGIONSERVER',
      STORM: 'SUPERVISOR'
    };
    return rollingRestartComponents[serviceName] ? rollingRestartComponents[serviceName] : null;
  },

  /**
   * Facade-function for restarting host components of specific service
   * @param {String} serviceDisplayName for which service hostComponents should be restarted
   * @param {String} serviceName for which service hostComponents should be restarted
   * @param {bool} staleConfigsOnly restart only hostComponents with staleConfig true
   * @param {Object} query
   * @param {bool} runMmOperation
   */
  restartAllServiceHostComponents: function(serviceDisplayName, serviceName, staleConfigsOnly, query, runMmOperation) {
    var self = this;
    var context = staleConfigsOnly ?
      Em.I18n.t('rollingrestart.context.allWithStaleConfigsForSelectedService').format(serviceDisplayName) :
      Em.I18n.t('rollingrestart.context.allForSelectedService').format(serviceDisplayName);

    if (runMmOperation) {
      this.turnOnOffPassiveRequest('ON', Em.I18n.t('passiveState.turnOnFor').format(serviceName), serviceName);
    }
    this.getComponentsFromServer({
      services: [serviceName],
      staleConfigs: staleConfigsOnly ? staleConfigsOnly : null,
      passiveState: 'OFF',
      displayParams: ['host_components/HostRoles/component_name']
    }, function (data) {
      var hostComponents = [];
      data.items.forEach(function (host) {
        host.host_components.forEach(function (hostComponent) {
          hostComponents.push(Em.Object.create({
            componentName: hostComponent.HostRoles.component_name,
            hostName: host.Hosts.host_name
          }))
        });
      });
      self.restartHostComponents(hostComponents, context, "SERVICE", query);
    });
  },

  /**
   * construct URL from parameters for request in getComponentsFromServer()
   * @param {object} options
   * @return {{fields: string, params: string}}
   */
  constructComponentsCallUrl: function (options) {
    var multipleValueParams = {
        'services': 'host_components/HostRoles/service_name.in(<entity-names>)',
        'hosts': 'Hosts/host_name.in(<entity-names>)',
        'components': 'host_components/HostRoles/component_name.in(<entity-names>)'
      },
      singleValueParams = {
        staleConfigs: 'host_components/HostRoles/stale_configs=',
        passiveState: 'Hosts/maintenance_state=',
        workStatus: 'host_components/HostRoles/state='
      },
      displayParams = options.displayParams || [],
      urlParams = '',
      addAmpersand = false;

    for (var i in multipleValueParams) {
      var arrayParams = options[i];
      if (Array.isArray(arrayParams) && arrayParams.length > 0) {
        if (addAmpersand) {
          urlParams += '&';
          addAmpersand = false;
        }
        urlParams += multipleValueParams[i].replace('<entity-names>', arrayParams.join(','));
        addAmpersand = true;
      }
    }

    for (var j in singleValueParams) {
      var param = options[j];
      if (!Em.isNone(param)) {
        urlParams += (addAmpersand) ? '&' : '';
        urlParams += singleValueParams[j] + param.toString();
        addAmpersand = true;
      }
    }
    var params = urlParams,
      fields = '';
    displayParams.forEach(function (displayParam, index, array) {
      if (index === 0) {
        fields += (addAmpersand) ? '&' : '';
        fields += 'fields=';
      }
      fields += displayParam;
      fields += (array.length === (index + 1)) ? '' : ",";
    });
    fields += '&minimal_response=true';

    return {fields: fields.substring(1, fields.length), params: params};
  },

  /**
   * make GET call to server in order to obtain host-components
   * which correspond to filter params from options
   * @param options
   * @param callback
   */
  getComponentsFromServer: function (options, callback) {
    var request_parameters = this.constructComponentsCallUrl(options);
    return App.ajax.send({
      name: 'host.host_components.filtered',
      sender: this,
      data: {
        parameters: request_parameters.params,
        fields: request_parameters.fields,
        callback: callback
      },
      success: 'getComponentsFromServerSuccessCallback'
    });
  },

  /**
   * pass request outcome to callback()
   * @param data
   * @param opt
   * @param params
   */
  getComponentsFromServerSuccessCallback: function (data, opt, params) {
    params.callback(data);
  },

  /**
   * Restart list of host components
   * @param {Ember.Enumerable} hostComponentsList list of host components should be restarted
   * @param {String} context message to show in BG popup
   * @param {String} level - operation level, can be ("CLUSTER", "SERVICE", "HOST", "HOSTCOMPONENT")
   * @param {String} query
   */
  restartHostComponents: function (hostComponentsList, context, level, query) {
    context = context || Em.I18n.t('rollingrestart.context.default');
    /**
     * Format: {
     *  'DATANODE': ['host1', 'host2'],
     *  'NAMENODE': ['host1', 'host3']
     *  ...
     * }
     */
    var componentToHostsMap = {};
    var hosts = [];
    hostComponentsList.forEach(function(hc) {
      var hostName = hc.get('hostName');
      var componentName = hc.get('componentName');
      if (!componentToHostsMap[componentName]) {
        componentToHostsMap[componentName] = [];
      }
      componentToHostsMap[componentName].push(hostName);
      hosts.push(hostName);
    });
    var resource_filters = [];
    for (var componentName in componentToHostsMap) {
      if (componentToHostsMap.hasOwnProperty(componentName)) {
        resource_filters.push({
          service_name: App.StackServiceComponent.find(componentName).get('serviceName'),
          component_name: componentName,
          hosts: componentToHostsMap[componentName].join(",")
        });
      }
    }
    if (hostComponentsList.length > 0) {
      var serviceComponentName = hostComponentsList[0].get("componentName");
      var serviceName = App.StackServiceComponent.find(serviceComponentName).get('serviceName');
      var operation_level = this.getOperationLevelObject(level, serviceName,
        serviceComponentName);
    }

    if (resource_filters.length) {
      App.ajax.send({
        name: 'restart.hostComponents',
        sender: {
          successCallback: defaultSuccessCallback,
          errorCallback: defaultErrorCallback
        },
        data: {
          context: context,
          resource_filters: resource_filters,
          query: query,
          operation_level: operation_level
        },
        success: 'successCallback',
        error: 'errorCallback',
        showLoadingPopup: true
      });
    }
  },

  /**
   * @param {String} level - operation level name, can be ("CLUSTER", "SERVICE", "HOST", "HOSTCOMPONENT")
   * @param {String} serviceName
   * @param {String} componentName
   * @returns {Object} {{level: *, cluster_name: *}} - operation level object
   * @method getOperationLevelObject - create operation level object to be included into ajax query
   */
  getOperationLevelObject: function(level, serviceName, componentName) {
    var operationLevel = {
      "level": level,
      "cluster_name": App.get("clusterName")
    };
    if (level === "SERVICE") {
      operationLevel["service_name"] = serviceName;
    }
    else {
      if (level !== "HOST") {
        operationLevel["service_name"] = serviceName;
        operationLevel["hostcomponent_name"] = componentName;
      }
    }
    return operationLevel;
  },

  turnOnOffPassiveRequest: function(state, message, serviceName, callback) {
    return App.ajax.send({
      'name': 'common.service.passive',
      'sender': {
        'successCallback': callback || defaultSuccessCallback,
        'errorCallback': defaultErrorCallback
      },
      'data': {
        'requestInfo': message,
        'serviceName': serviceName,
        'passive_state': state
      },
      'success': 'successCallback'
    });
  },

  /**
   * Makes a REST call to the server requesting the rolling restart of the
   * provided host components.
   * @param {Array} restartHostComponents list of host components should be restarted
   * @param {Number} batchSize size of each batch
   * @param {Number} intervalTimeSeconds delay between two batches
   * @param {Number} tolerateSize task failure tolerance
   * @param {callback} [successCallback]
   * @param {callback} [errorCallback]
   */
  _doPostBatchRollingRestartRequest: function(restartHostComponents, batchSize, intervalTimeSeconds, tolerateSize, successCallback, errorCallback) {
    successCallback = successCallback || defaultSuccessCallback;
    errorCallback = errorCallback || defaultErrorCallback;

    if (!restartHostComponents.length) {
      return;
    }
    return App.ajax.send({
      name: 'common.batch.request_schedules',
      sender: {
        successCallback: successCallback,
        errorCallback: errorCallback
      },
      data: {
        intervalTimeSeconds: intervalTimeSeconds,
        tolerateSize: tolerateSize,
        batches: this.getBatchesForRollingRestartRequest(restartHostComponents, batchSize)
      },
      success: 'successCallback',
      error: 'errorCallback',
      showLoadingPopup: true
    });
  },

  /**
   * Create list of batches for rolling restart request
   * @param {Array} restartHostComponents list host components should be restarted
   * @param {Number} batchSize size of each batch
   * @returns {Array} list of batches
   */
  getBatchesForRollingRestartRequest: function(restartHostComponents, batchSize) {
    var hostIndex = 0,
        batches = [],
        batchCount = Math.ceil(restartHostComponents.length / batchSize),
        sampleHostComponent = restartHostComponents.objectAt(0),
        componentName = sampleHostComponent.get('componentName'),
        serviceName = sampleHostComponent.get('serviceName');

    for ( var count = 0; count < batchCount; count++) {
      var hostNames = [];
      for ( var hc = 0; hc < batchSize && hostIndex < restartHostComponents.length; hc++) {
        hostNames.push(restartHostComponents.objectAt(hostIndex++).get('hostName'));
      }
      if (hostNames.length) {
        batches.push({
          "order_id" : count + 1,
          "type" : "POST",
          "uri" : App.apiPrefix + "/clusters/" + App.get('clusterName') + "/requests",
          "RequestBodyInfo" : {
            "RequestInfo" : {
              "context" : "_PARSE_.ROLLING-RESTART." + componentName + "." + (count + 1) + "." + batchCount,
              "command" : "RESTART"
            },
            "Requests/resource_filters": [{
              "service_name" : serviceName,
              "component_name" : componentName,
              "hosts" : hostNames.join(",")
            }]
          }
        });
      }
    }
    return batches;
  },

  /**
   * Launches dialog to handle rolling restarts of host components.
   *
   * Rolling restart is supported only for components listed in getRollingRestartComponentName
   * @see getRollingRestartComponentName
   * @param {String} hostComponentName
   *           Type of host-component to restart across cluster
   *          (ex: DATANODE)
   * @param {bool} staleConfigsOnly
   *           Pre-select host-components which have stale
   *          configurations
   */
  launchHostComponentRollingRestart: function(hostComponentName, serviceName, isMaintenanceModeOn, staleConfigsOnly, skipMaintenance) {
    if (App.get('components.rollinRestartAllowed').contains(hostComponentName)) {
      return this.showRollingRestartPopup(hostComponentName, serviceName, isMaintenanceModeOn, staleConfigsOnly, null, skipMaintenance);
    }
    return this.showWarningRollingRestartPopup(hostComponentName);
  },

  /**
   * Show popup with rolling restart dialog
   * @param {String} hostComponentName name of the host components that should be restarted
   * @param {String} serviceName
   * @param {boolean} isMaintenanceModeOn
   * @param {bool} staleConfigsOnly restart only components with staleConfigs = true
   * @param {App.hostComponent[]} [hostComponents] list of hostComponents that should be restarted
   * @param {boolean} [skipMaintenance]
   * Using this parameter will reset hostComponentName
   */
  showRollingRestartPopup: function(hostComponentName, serviceName, isMaintenanceModeOn, staleConfigsOnly, hostComponents, skipMaintenance) {
    hostComponents = hostComponents || [];
    var componentDisplayName = App.format.role(hostComponentName, false);
    var self = this;
    if (!componentDisplayName) {
      componentDisplayName = hostComponentName;
    }
    var title = Em.I18n.t('rollingrestart.dialog.title').format(componentDisplayName);
    var viewExtend = {
      turnOnMmMsg: Em.I18n.t('passiveState.turnOnFor').format(serviceName),
      turnOnMm: false,
      staleConfigsOnly : staleConfigsOnly,
      hostComponentName : hostComponentName,
      skipMaintenance: skipMaintenance,
      serviceName: serviceName,
      isServiceInMM: isMaintenanceModeOn,
      didInsertElement: function () {
        var view = this;

        this.set('parentView.innerView', this);
        if (hostComponents.length) {
          view.initialize();
          return;
        }

        self.getComponentsFromServer({
          components: [hostComponentName],
          displayParams: ['host_components/HostRoles/stale_configs', 'Hosts/maintenance_state', 'host_components/HostRoles/maintenance_state'],
          staleConfigs: staleConfigsOnly ? staleConfigsOnly : null
        }, function (data) {
          var wrappedHostComponents = [];
          data.items.forEach(function (host) {
            host.host_components.forEach(function(hostComponent) {
              wrappedHostComponents.push(Em.Object.create({
                componentName: hostComponent.HostRoles.component_name,
                serviceName: App.StackServiceComponent.find(hostComponent.HostRoles.component_name).get('serviceName'),
                hostName: host.Hosts.host_name,
                staleConfigs: hostComponent.HostRoles.stale_configs,
                hostPassiveState: host.Hosts.maintenance_state,
                passiveState: hostComponent.HostRoles.maintenance_state
              }));
            });
          });
          view.set('allHostComponents', wrappedHostComponents);
          view.initialize();
        });
      }
    };
    if (hostComponents.length) {
      viewExtend.allHostComponents = hostComponents;
    }

    App.ModalPopup.show({
      header : title,
      hostComponentName : hostComponentName,
      serviceName: serviceName,
      isServiceInMM: isMaintenanceModeOn,
      staleConfigsOnly : staleConfigsOnly,
      skipMaintenance: skipMaintenance,
      innerView : null,
      bodyClass : App.RollingRestartView.extend(viewExtend),
      classNames : [ 'rolling-restart-popup' ],
      primary : Em.I18n.t('rollingrestart.dialog.primary'),
      onPrimary : function() {
        var dialog = this;
        var restartComponents = this.get('innerView.restartHostComponents');
        var batchSize = this.get('innerView.batchSize');
        var waitTime = this.get('innerView.interBatchWaitTimeSeconds');
        var tolerateSize = this.get('innerView.tolerateSize');
        if (this.get('innerView.turnOnMm')) {
          self.turnOnOffPassiveRequest('ON', Em.I18n.t('passiveState.turnOnFor').format(serviceName), serviceName.toUpperCase());
        }
        self._doPostBatchRollingRestartRequest(restartComponents, batchSize, waitTime, tolerateSize, function(data, ajaxOptions, params) {
          dialog.hide();
          defaultSuccessCallback(data, ajaxOptions, params);
        });
      },
      updateButtons : function() {
        var errors = this.get('innerView.errors');
        this.set('disablePrimary', (errors != null && errors.length > 0))
      }.observes('innerView.errors')
    });
  },

  /**
   * Show warning popup about not supported host components
   * @param {String} hostComponentName
   */
  showWarningRollingRestartPopup: function(hostComponentName) {
    var componentDisplayName = App.format.role(hostComponentName, false) || hostComponentName;
    var title = Em.I18n.t('rollingrestart.dialog.title').format(componentDisplayName);
    var msg = Em.I18n.t('rollingrestart.notsupported.hostComponent').format(componentDisplayName);

    return App.ModalPopup.show({
      header : title,
      secondary : false,
      msg : msg,
      bodyClass : Em.View.extend({
        template : Em.Handlebars.compile('
{{msg}}
')
      })
    });
  },

  /**
   * Warn user that alerts will be updated in few minutes
   * @param {String} passiveState
   */
  infoPassiveState: function(passiveState) {
    var enabled = passiveState == 'OFF' ? 'enabled' : 'suppressed';
    App.ModalPopup.show({
      header: Em.I18n.t('common.information'),
      secondary: null,
      bodyClass: Em.View.extend({
        template: Em.Handlebars.compile('
{{view.message}}
'),
        message: Em.I18n.t('hostPopup.warning.alertsTimeOut').format(passiveState.toLowerCase(), enabled)
      })
    });
  },

  /**
   * Retrieves the latest information about a specific request schedule
   * identified by 'requestScheduleId'
   *
   * @param {Number} requestScheduleId ID of the request schedule to get
   * @param {Function} successCallback Called with request_schedule data from server. An
   *          empty object returned for invalid ID.
   * @param {Function} errorCallback Optional error callback. Default behavior is to
   *          popup default error dialog.
   */
  getRequestSchedule: function(requestScheduleId, successCallback, errorCallback) {
    if (requestScheduleId != null && !isNaN(requestScheduleId) && requestScheduleId > -1) {
      errorCallback = errorCallback || defaultErrorCallback;
      App.ajax.send({
        name : 'request_schedule.get',
        sender : {
          successCallbackFunction: successCallback,
          errorCallbackFunction: errorCallback
        },
        data : {
          request_schedule_id : requestScheduleId
        },
        success : 'successCallbackFunction',
        error : 'errorCallbackFunction'
      });
    } else {
      successCallback({});
    }
  },

  /**
   * Attempts to abort a specific request schedule identified by 'requestScheduleId'
   *
   * @param {Number} requestScheduleId ID of the request schedule to get
   * @param {Function} successCallback Called when request schedule successfully aborted
   * @param {Function} errorCallback Optional error callback. Default behavior is to
   *          popup default error dialog.
   */
  doAbortRequestSchedule: function(requestScheduleId, successCallback, errorCallback) {
    if (requestScheduleId != null && !isNaN(requestScheduleId) && requestScheduleId > -1) {
      errorCallback = errorCallback || defaultErrorCallback;
      App.ajax.send({
        name : 'common.delete.request_schedule',
        sender : {
          successCallbackFunction: successCallback,
          errorCallbackFunction: errorCallback
        },
        data : {
          request_schedule_id : requestScheduleId
        },
        success : 'successCallbackFunction',
        error : 'errorCallbackFunction'
      });
    } else {
      successCallback({});
    }
  }
};


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.browserservices;

import android.os.SystemClock;

import androidx.annotation.IntDef;

import org.chromium.base.metrics.RecordHistogram;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Class to contain metrics recording constants and behaviour for Browser Services.
 */
public class BrowserServicesMetrics {
    @IntDef({VerificationResult.ONLINE_SUCCESS, VerificationResult.ONLINE_FAILURE,
            VerificationResult.OFFLINE_SUCCESS, VerificationResult.OFFLINE_FAILURE,
            VerificationResult.HTTPS_FAILURE, VerificationResult.REQUEST_FAILURE,
            VerificationResult.CACHED_SUCCESS})
    @Retention(RetentionPolicy.SOURCE)
    public @interface VerificationResult {
        // Don't reuse values or reorder values. If you add something new, change NUM_ENTRIES as
        // well.
        int ONLINE_SUCCESS = 0;
        int ONLINE_FAILURE = 1;
        int OFFLINE_SUCCESS = 2;
        int OFFLINE_FAILURE = 3;
        int HTTPS_FAILURE = 4;
        int REQUEST_FAILURE = 5;
        int CACHED_SUCCESS = 6;
        int NUM_ENTRIES = 7;
    }

    /**
     * Records the verification result for Trusted Web Activity verification.
     */
    public static void recordVerificationResult(@VerificationResult int result) {
        RecordHistogram.recordEnumeratedHistogram(
                "BrowserServices.VerificationResult", result, VerificationResult.NUM_ENTRIES);
    }

    public static void recordVerificationTime(long duration, boolean online) {
        if (online) {
            RecordHistogram.recordTimesHistogram(
                    "BrowserServices.VerificationTime.Online", duration);
        } else {
            RecordHistogram.recordTimesHistogram(
                    "BrowserServices.VerificationTime.Offline", duration);
        }
    }

    /**
     * Returns a {@link TimingMetric} that records the amount of time spent querying the Android
     * system for ResolveInfos that will deal with a given URL when launching from a background
     * service.
     */
    public static TimingMetric getServiceTabResolveInfoTimingContext() {
        return new TimingMetric("BrowserServices.ServiceTabResolveInfoQuery");
    }

    /**
     * Returns a {@link TimingMetric} that records the amount of time spent opening the
     * {@link ClientAppDataRegister}.
     */
    public static TimingMetric getClientAppDataLoadTimingContext() {
        return new TimingMetric("BrowserServices.ClientAppDataLoad");
    }

    /**
     * Returns a {@link TimingMetric} that records the amount of time taken to check if a package
     * handles a Browsable intent.
     */
    public static TimingMetric getBrowsableIntentResolutionTimingContext() {
        return new TimingMetric("BrowserServices.BrowsableIntentCheck");
    }

    /**
     * A class to be used with a try-with-resources to record the elapsed time within the try block.
     */
    public static class TimingMetric implements AutoCloseable {
        private final String mMetric;
        private final long mStart;

        private static long now() {
            return SystemClock.uptimeMillis();
        }

        private TimingMetric(String metric) {
            mMetric = metric;
            mStart = now();
        }

        @Override
        public void close() {
            RecordHistogram.recordMediumTimesHistogram(mMetric, now() - mStart);
        }
    }

    // Don't let anyone instantiate.
    private BrowserServicesMetrics() {}
}

redpajama_set_name: RedPajamaGithub


text:
package org.hisp.dhis.webapi.controller.event;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.Grid;
import org.hisp.dhis.common.OrganisationUnitSelectionMode;
import org.hisp.dhis.common.Pager;
import org.hisp.dhis.common.cache.CacheStrategy;
import org.hisp.dhis.commons.util.StreamUtils;
import org.hisp.dhis.commons.util.TextUtils;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstanceService;
import org.hisp.dhis.dxf2.importsummary.ImportStatus;
import org.hisp.dhis.dxf2.importsummary.ImportSummaries;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.dxf2.webmessage.WebMessageException;
import org.hisp.dhis.event.EventStatus;
import org.hisp.dhis.fieldfilter.FieldFilterService;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.node.NodeUtils;
import org.hisp.dhis.node.types.CollectionNode;
import org.hisp.dhis.node.types.RootNode;
import org.hisp.dhis.program.ProgramStatus;
import org.hisp.dhis.render.RenderService;
import org.hisp.dhis.schema.descriptors.TrackedEntityInstanceSchemaDescriptor;
import org.hisp.dhis.system.grid.GridUtils;
import org.hisp.dhis.trackedentity.TrackedEntityInstanceQueryParams;
import org.hisp.dhis.webapi.controller.exception.NotFoundException;
import org.hisp.dhis.webapi.mvc.annotation.ApiVersion;
import org.hisp.dhis.webapi.service.ContextService;
import org.hisp.dhis.webapi.service.WebMessageService;
import org.hisp.dhis.webapi.utils.ContextUtils;
import org.hisp.dhis.webapi.utils.WebMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 *

 *

 *         The following statements are added not to cause api break.
 *         They need to be remove say in 2.26 or so once users are aware of the changes.
 *         programEnrollmentStartDate= ObjectUtils.firstNonNull( programEnrollmentStartDate, programStartDate );
 *         programEnrollmentEndDate= ObjectUtils.firstNonNull( programEnrollmentEndDate, programEndDate );
 */
@Controller
@RequestMapping( value = TrackedEntityInstanceSchemaDescriptor.API_ENDPOINT )
@PreAuthorize( "hasAnyRole('ALL', 'F_TRACKED_ENTITY_INSTANCE_SEARCH')" )
@ApiVersion( { ApiVersion.Version.DEFAULT, ApiVersion.Version.ALL } )
public class TrackedEntityInstanceController
{
    @Autowired
    private TrackedEntityInstanceService trackedEntityInstanceService;

    @Autowired
    private org.hisp.dhis.trackedentity.TrackedEntityInstanceService instanceService;

    @Autowired
    private ContextUtils contextUtils;

    @Autowired
    private FieldFilterService fieldFilterService;

    @Autowired
    private ContextService contextService;

    @Autowired
    private WebMessageService webMessageService;

    @Autowired
    private RenderService renderService;

    // -------------------------------------------------------------------------
    // READ
    // -------------------------------------------------------------------------

    @RequestMapping( value = "", method = RequestMethod.GET )
    public @ResponseBody RootNode getTrackedEntityInstances(
        @RequestParam( required = false ) String query,
        @RequestParam( required = false ) Set<String> attribute,
        @RequestParam( required = false ) Set<String> filter,
        @RequestParam( required = false ) String ou,
        @RequestParam( required = false ) OrganisationUnitSelectionMode ouMode,
        @RequestParam( required = false ) String program,
        @RequestParam( required = false ) ProgramStatus programStatus,
        @RequestParam( required = false ) Boolean followUp,
        @RequestParam( required = false ) Date programStartDate,
        @RequestParam( required = false ) Date programEnrollmentStartDate,
        @RequestParam( required = false ) Date programEndDate,
        @RequestParam( required = false ) Date programEnrollmentEndDate,
        @RequestParam( required = false ) Date programIncidentStartDate,
        @RequestParam( required = false ) Date programIncidentEndDate,
        @RequestParam( required = false ) String trackedEntity,
        @RequestParam( required = false ) EventStatus eventStatus,
        @RequestParam( required = false ) Date eventStartDate,
        @RequestParam( required = false ) Date eventEndDate,
        @RequestParam( required = false ) boolean skipMeta,
        @RequestParam( required = false ) Integer page,
        @RequestParam( required = false ) Integer pageSize,
        @RequestParam( required = false ) boolean totalPages,
        @RequestParam( required = false ) boolean skipPaging ) throws Exception
    {
        programEnrollmentStartDate = ObjectUtils.firstNonNull( programEnrollmentStartDate, programStartDate );
        programEnrollmentEndDate = ObjectUtils.firstNonNull( programEnrollmentEndDate, programEndDate );
        List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) );

        if ( fields.isEmpty() )
        {
            fields.add( ":all" );
        }

        Set<String> orgUnits = TextUtils.splitToArray( ou, TextUtils.SEMICOLON );

        TrackedEntityInstanceQueryParams params = instanceService.getFromUrl( query, attribute, filter, orgUnits, ouMode,
            program, programStatus, followUp, programEnrollmentStartDate, programEnrollmentEndDate, programIncidentStartDate, programIncidentEndDate, trackedEntity,
            eventStatus, eventStartDate, eventEndDate, skipMeta, page, pageSize, totalPages, skipPaging );

        List<TrackedEntityInstance> trackedEntityInstances = trackedEntityInstanceService.getTrackedEntityInstances( params );

        RootNode rootNode = NodeUtils.createMetadata();

        if ( params.isPaging() && params.isTotalPages() )
        {
            int count = trackedEntityInstanceService.getTrackedEntityInstanceCount( params );
            Pager pager = new Pager( params.getPageWithDefault(), count, params.getPageSizeWithDefault() );
            rootNode.addChild( NodeUtils.createPager( pager ) );
        }

        rootNode.addChild( fieldFilterService.filter( TrackedEntityInstance.class, trackedEntityInstances, fields ) );

        return rootNode;
    }

    @RequestMapping( value = "/query", method = RequestMethod.GET, produces = { ContextUtils.CONTENT_TYPE_JSON, ContextUtils.CONTENT_TYPE_JAVASCRIPT } )
    public @ResponseBody Grid queryTrackedEntityInstancesJson(
        @RequestParam( required = false ) String query,
        @RequestParam( required = false ) Set<String> attribute,
        @RequestParam( required = false ) Set<String> filter,
        @RequestParam( required = false ) String ou,
        @RequestParam( required = false ) OrganisationUnitSelectionMode ouMode,
        @RequestParam( required = false ) String program,
        @RequestParam( required = false ) ProgramStatus programStatus,
        @RequestParam( required = false ) Boolean followUp,
        @RequestParam( required = false ) Date programStartDate,
        @RequestParam( required = false ) Date programEnrollmentStartDate,
        @RequestParam( required = false ) Date programEndDate,
        @RequestParam( required = false ) Date programEnrollmentEndDate,
        @RequestParam( required = false ) Date programIncidentStartDate,
        @RequestParam( required = false ) Date programIncidentEndDate,
        @RequestParam( required = false ) String trackedEntity,
        @RequestParam( required = false ) EventStatus eventStatus,
        @RequestParam( required = false ) Date eventStartDate,
        @RequestParam( required = false ) Date eventEndDate,
        @RequestParam( required = false ) boolean skipMeta,
        @RequestParam( required = false ) Integer page,
        @RequestParam( required = false ) Integer pageSize,
        @RequestParam( required = false ) boolean totalPages,
        @RequestParam( required = false ) boolean skipPaging,
        Model model,
        HttpServletResponse response ) throws Exception
    {
        programEnrollmentStartDate = ObjectUtils.firstNonNull( programEnrollmentStartDate, programStartDate );
        programEnrollmentEndDate = ObjectUtils.firstNonNull( programEnrollmentEndDate, programEndDate );
        Set<String> orgUnits = TextUtils.splitToArray( ou, TextUtils.SEMICOLON );
        TrackedEntityInstanceQueryParams params = instanceService.getFromUrl( query, attribute, filter, orgUnits, ouMode,
            program, programStatus, followUp, programEnrollmentStartDate, programEnrollmentEndDate, programIncidentStartDate, programIncidentEndDate, trackedEntity,
            eventStatus, eventStartDate, eventEndDate, skipMeta, page, pageSize, totalPages, skipPaging );

        contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_JSON, CacheStrategy.NO_CACHE );
        return instanceService.getTrackedEntityInstancesGrid( params );
    }

    @RequestMapping( value = "/query", method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_XML )
    public void queryTrackedEntityInstancesXml(
        @RequestParam( required = false ) String query,
        @RequestParam( required = false ) Set<String> attribute,
        @RequestParam( required = false ) Set<String> filter,
        @RequestParam( required = false ) String ou,
        @RequestParam( required = false ) OrganisationUnitSelectionMode ouMode,
        @RequestParam( required = false ) String program,
        @RequestParam( required = false ) ProgramStatus programStatus,
        @RequestParam( required = false ) Boolean followUp,
        @RequestParam( required = false ) Date programStartDate,
        @RequestParam( required = false ) Date programEnrollmentStartDate,
        @RequestParam( required = false ) Date programEndDate,
        @RequestParam( required = false ) Date programEnrollmentEndDate,
        @RequestParam( required = false ) Date programIncidentStartDate,
        @RequestParam( required = false ) Date programIncidentEndDate,
        @RequestParam( required = false ) String trackedEntity,
        @RequestParam( required = false ) EventStatus eventStatus,
        @RequestParam( required = false ) Date eventStartDate,
        @RequestParam( required = false ) Date eventEndDate,
        @RequestParam( required = false ) boolean skipMeta,
        @RequestParam( required = false ) Integer page,
        @RequestParam( required = false ) Integer pageSize,
        @RequestParam( required = false ) boolean totalPages,
        @RequestParam( required = false ) boolean skipPaging,
        HttpServletResponse response ) throws Exception
    {
        programEnrollmentStartDate = ObjectUtils.firstNonNull( programEnrollmentStartDate, programStartDate );
        programEnrollmentEndDate = ObjectUtils.firstNonNull( programEnrollmentEndDate, programEndDate );
        Set<String> orgUnits = TextUtils.splitToArray( ou, TextUtils.SEMICOLON );
        TrackedEntityInstanceQueryParams params = instanceService.getFromUrl( query, attribute, filter, orgUnits, ouMode,
            program, programStatus, followUp, programEnrollmentStartDate, programEnrollmentEndDate, programIncidentStartDate, programIncidentEndDate, trackedEntity,
            eventStatus, eventStartDate, eventEndDate, skipMeta, page, pageSize, totalPages, skipPaging );

        contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_XML, CacheStrategy.NO_CACHE );
        Grid grid = instanceService.getTrackedEntityInstancesGrid( params );
        GridUtils.toXml( grid, response.getOutputStream() );
    }

    @RequestMapping( value = "/query", method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_EXCEL )
    public void queryTrackedEntityInstancesXls(
        @RequestParam( required = false ) String query,
        @RequestParam( required = false ) Set<String> attribute,
        @RequestParam( required = false ) Set<String> filter,
        @RequestParam( required = false ) String ou,
        @RequestParam( required = false ) OrganisationUnitSelectionMode ouMode,
        @RequestParam( required = false ) String program,
        @RequestParam( required = false ) ProgramStatus programStatus,
        @RequestParam( required = false ) Boolean followUp,
        @RequestParam( required = false ) Date programStartDate,
        @RequestParam( required = false ) Date programEnrollmentStartDate,
        @RequestParam( required = false ) Date programEndDate,
        @RequestParam( required = false ) Date programEnrollmentEndDate,
        @RequestParam( required = false ) Date programIncidentStartDate,
        @RequestParam( required = false ) Date programIncidentEndDate,
        @RequestParam( required = false ) String trackedEntity,
        @RequestParam( required = false ) EventStatus eventStatus,
        @RequestParam( required = false ) Date eventStartDate,
        @RequestParam( required = false ) Date eventEndDate,
        @RequestParam( required = false ) boolean skipMeta,
        @RequestParam( required = false ) Integer page,
        @RequestParam( required = false ) Integer pageSize,
        @RequestParam( required = false ) boolean totalPages,
        @RequestParam( required = false ) boolean skipPaging,
        HttpServletResponse response ) throws Exception
    {
        programEnrollmentStartDate = ObjectUtils.firstNonNull( programEnrollmentStartDate, programStartDate );
        programEnrollmentEndDate = ObjectUtils.firstNonNull( programEnrollmentEndDate, programEndDate );
        Set<String> orgUnits = TextUtils.splitToArray( ou, TextUtils.SEMICOLON );
        TrackedEntityInstanceQueryParams params = instanceService.getFromUrl( query, attribute, filter, orgUnits, ouMode,
            program, programStatus, followUp, programEnrollmentStartDate, programEnrollmentEndDate, programIncidentStartDate, programIncidentEndDate, trackedEntity,
            eventStatus, eventStartDate, eventEndDate, skipMeta, page, pageSize, totalPages, skipPaging );

        contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_EXCEL, CacheStrategy.NO_CACHE );
        Grid grid = instanceService.getTrackedEntityInstancesGrid( params );
        GridUtils.toXls( grid, response.getOutputStream() );
    }

    @RequestMapping( value = "/query", method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_CSV )
    public void queryTrackedEntityInstancesCsv(
        @RequestParam( required = false ) String query,
        @RequestParam( required = false ) Set<String> attribute,
        @RequestParam( required = false ) Set<String> filter,
        @RequestParam( required = false ) String ou,
        @RequestParam( required = false ) OrganisationUnitSelectionMode ouMode,
        @RequestParam( required = false ) String program,
        @RequestParam( required = false ) ProgramStatus programStatus,
        @RequestParam( required = false ) Boolean followUp,
        @RequestParam( required = false ) Date programStartDate,
        @RequestParam( required = false ) Date programEnrollmentStartDate,
        @RequestParam( required = false ) Date programEndDate,
        @RequestParam( required = false ) Date programEnrollmentEndDate,
        @RequestParam( required = false ) Date programIncidentStartDate,
        @RequestParam( required = false ) Date programIncidentEndDate,
        @RequestParam( required = false ) String trackedEntity,
        @RequestParam( required = false ) EventStatus eventStatus,
        @RequestParam( required = false ) Date eventStartDate,
        @RequestParam( required = false ) Date eventEndDate,
        @RequestParam( required = false ) boolean skipMeta,
        @RequestParam( required = false ) Integer page,
        @RequestParam( required = false ) Integer pageSize,
        @RequestParam( required = false ) boolean totalPages,
        @RequestParam( required = false ) boolean skipPaging,
        HttpServletResponse response ) throws Exception
    {
        programEnrollmentStartDate = ObjectUtils.firstNonNull( programEnrollmentStartDate, programStartDate );
        programEnrollmentEndDate = ObjectUtils.firstNonNull( programEnrollmentEndDate, programEndDate );
        Set<String> orgUnits = TextUtils.splitToArray( ou, TextUtils.SEMICOLON );
        TrackedEntityInstanceQueryParams params = instanceService.getFromUrl( query, attribute, filter, orgUnits, ouMode,
            program, programStatus, followUp, programEnrollmentStartDate, programEnrollmentEndDate, programIncidentStartDate, programIncidentEndDate, trackedEntity,
            eventStatus, eventStartDate, eventEndDate, skipMeta, page, pageSize, totalPages, skipPaging );

        contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_CSV, CacheStrategy.NO_CACHE );
        Grid grid = instanceService.getTrackedEntityInstancesGrid( params );
        GridUtils.toCsv( grid, response.getWriter() );
    }

    @RequestMapping( value = "/{id}", method = RequestMethod.GET )
    @PreAuthorize( "hasRole('ALL') or hasRole('F_TRACKED_ENTITY_INSTANCE_SEARCH')" )
    public @ResponseBody RootNode getTrackedEntityInstanceById( @PathVariable( "id" ) String pvId )
        throws NotFoundException
    {
        List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) );

        if ( fields.isEmpty() )
        {
            fields.add( ":all" );
        }

        CollectionNode collectionNode = fieldFilterService.filter( TrackedEntityInstance.class, Lists.newArrayList( getTrackedEntityInstance( pvId ) ), fields );

        RootNode rootNode = new RootNode( collectionNode.getChildren().get( 0 ) );
        rootNode.setDefaultNamespace( DxfNamespaces.DXF_2_0 );
        rootNode.setNamespace( DxfNamespaces.DXF_2_0 );

        return rootNode;
    }

    // -------------------------------------------------------------------------
    // CREATE
    // -------------------------------------------------------------------------

    @RequestMapping( value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_XML_VALUE )
    @PreAuthorize( "hasRole('ALL') or hasRole('F_TRACKED_ENTITY_INSTANCE_ADD')" )
    public void postTrackedEntityInstanceXml( @RequestParam( defaultValue = "CREATE" ) ImportStrategy strategy,
        ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException
    {
        importOptions.setStrategy( strategy );
        InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() );
        ImportSummaries importSummaries = trackedEntityInstanceService.addTrackedEntityInstanceXml( inputStream, importOptions );
        response.setContentType( MediaType.APPLICATION_XML_VALUE );

        if ( importSummaries.getImportSummaries().size() > 1 )
        {
            response.setStatus( HttpServletResponse.SC_CREATED );
            renderService.toXml( response.getOutputStream(), importSummaries );
        }
        else
        {
            response.setStatus( HttpServletResponse.SC_CREATED );
            ImportSummary importSummary;

            if ( !importSummaries.getImportSummaries().isEmpty() )
            {
                importSummary = importSummaries.getImportSummaries().get( 0 );

                if ( !importSummary.getStatus().equals( ImportStatus.ERROR ) )
                {
                    response.setHeader( "Location", getResourcePath( request, importSummary ) );
                }
            }
            else
            {
                importSummary = new ImportSummary( ImportStatus.SUCCESS, "Empty list of tracked entity instances given." );
                importSummary.setImportCount( null );
            }

            webMessageService.send( WebMessageUtils.importSummaries( importSummaries ), response, request );
        }
    }

    @RequestMapping( value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE )
    @PreAuthorize( "hasRole('ALL') or hasRole('F_TRACKED_ENTITY_INSTANCE_ADD')" )
    public void postTrackedEntityInstanceJson( @RequestParam( defaultValue = "CREATE" ) ImportStrategy strategy,
        ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response ) throws IOException
    {
        importOptions.setStrategy( strategy );
        InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() );
        ImportSummaries importSummaries = trackedEntityInstanceService.addTrackedEntityInstanceJson( inputStream, importOptions );
        response.setContentType( MediaType.APPLICATION_JSON_VALUE );

        if ( importSummaries.getImportSummaries().size() > 1 )
        {
            response.setStatus( HttpServletResponse.SC_CREATED );
            renderService.toJson( response.getOutputStream(), importSummaries );
        }
        else
        {
            response.setStatus( HttpServletResponse.SC_CREATED );
            ImportSummary importSummary;

            if ( !importSummaries.getImportSummaries().isEmpty() )
            {
                importSummary = importSummaries.getImportSummaries().get( 0 );

                if ( !importSummary.getStatus().equals( ImportStatus.ERROR ) )
                {
                    response.setHeader( "Location", getResourcePath( request, importSummary ) );
                }
            }
            else
            {
                importSummary = new ImportSummary( ImportStatus.SUCCESS, "Empty list of tracked entity instances given." );
                importSummary.setImportCount( null );
            }

            webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request );
        }
    }

    // -------------------------------------------------------------------------
    // UPDATE
    // -------------------------------------------------------------------------

    @RequestMapping( value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_XML_VALUE )
    @PreAuthorize( "hasRole('ALL') or hasRole('F_TRACKED_ENTITY_INSTANCE_ADD')" )
    public void updateTrackedEntityInstanceXml( @PathVariable String id, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response )
        throws IOException
    {
        InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() );
        ImportSummary importSummary = trackedEntityInstanceService.updateTrackedEntityInstanceXml( id, inputStream, importOptions );
        webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request );
    }

    @RequestMapping( value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE )
    @PreAuthorize( "hasRole('ALL') or hasRole('F_TRACKED_ENTITY_INSTANCE_ADD')" )
    public void updateTrackedEntityInstanceJson( @PathVariable String id, ImportOptions importOptions, HttpServletRequest request, HttpServletResponse response )
        throws IOException
    {
        InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() );
        ImportSummary importSummary = trackedEntityInstanceService.updateTrackedEntityInstanceJson( id, inputStream, importOptions );
        webMessageService.send( WebMessageUtils.importSummary( importSummary ), response, request );
    }

    // -------------------------------------------------------------------------
    // DELETE
    // -------------------------------------------------------------------------

    @RequestMapping( value = "/{id}", method = RequestMethod.DELETE )
    @PreAuthorize( "hasRole('ALL') or hasRole('F_TRACKED_ENTITY_INSTANCE_ADD')" )
    @ResponseStatus( HttpStatus.NO_CONTENT )
    public void deleteTrackedEntityInstance( @PathVariable String id ) throws WebMessageException
    {
        if ( !instanceService.trackedEntityInstanceExists( id ) )
        {
            throw new WebMessageException( WebMessageUtils.notFound( "Tracked entity instance not found for ID " + id ) );
        }

        trackedEntityInstanceService.deleteTrackedEntityInstance( id );
    }

    // -------------------------------------------------------------------------
    // HELPERS
    // -------------------------------------------------------------------------

    private TrackedEntityInstance getTrackedEntityInstance( String id )
        throws NotFoundException
    {
        TrackedEntityInstance trackedEntityInstance = trackedEntityInstanceService.getTrackedEntityInstance( id );

        if ( trackedEntityInstance == null )
        {
            throw new NotFoundException( "TrackedEntityInstance", id );
        }
        return trackedEntityInstance;
    }

    private String getResourcePath( HttpServletRequest request, ImportSummary importSummary )
    {
        return ContextUtils.getContextPath( request ) + "/api/" + "trackedEntityInstances" + "/" + importSummary.getReference();
    }
}


text:
package opennebula

import (
	"encoding/xml"
	"fmt"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
	"log"
	"strings"
	"time"
)

type UserVm struct {
	Id          string       `xml:"ID"`
	Name        string       `xml:"NAME"`
	Uid         int          `xml:"UID"`
	Gid         int          `xml:"GID"`
	Uname       string       `xml:"UNAME"`
	Gname       string       `xml:"GNAME"`
	Permissions *Permissions `xml:"PERMISSIONS"`
	State       int          `xml:"STATE"`
	LcmState    int          `xml:"LCM_STATE"`
	VmTemplate  *VmTemplate  `xml:"TEMPLATE"`
}

type UserVms struct {
	UserVm []*UserVm `xml:"VM"`
}

type VmTemplate struct {
	Context *Context `xml:"CONTEXT"`
}

type Context struct {
	IP string `xml:"ETH0_IP"`
}

func resourceVm() *schema.Resource {
	return &schema.Resource{
		Create: resourceVmCreate,
		Read:   resourceVmRead,
		Exists: resourceVmExists,
		Update: resourceVmUpdate,
		Delete: resourceVmDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "Name of the VM. If empty, defaults to 'templatename-<vmid>'",
			},
			"instance": {
				Type:        schema.TypeString,
				Computed:    true,
				Description: "Final name of the VM instance",
			},
			"template_id": {
				Type:        schema.TypeInt,
				Required:    true,
				Description: "Id of the VM template to use. Either 'template_name' or 'template_id' is required",
			},
			"permissions": {
				Type:        schema.TypeString,
				Required:    true,
				Description: "Permissions for the template (in Unix format, owner-group-other, use-manage-admin)",
				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
					value := v.(string)

					if len(value) != 3 {
						errors = append(errors, fmt.Errorf("%q has specify 3 permission sets: owner-group-other", k))
					}

					all := true
					for _, c := range strings.Split(value, "") {
						if c < "0" || c > "7" {
							all = false
						}
					}
					if !all {
						errors = append(errors, fmt.Errorf("Each character in %q should specify a Unix-like permission set with a number from 0 to 7", k))
					}

					return
				},
			},

			"uid": {
				Type:        schema.TypeInt,
				Computed:    true,
				Description: "ID of the user that will own the VM",
			},
			"gid": {
				Type:        schema.TypeInt,
				Computed:    true,
				Description: "ID of the group that will own the VM",
			},
			"uname": {
				Type:        schema.TypeString,
				Computed:    true,
				Description: "Name of the user that will own the VM",
			},
			"gname": {
				Type:        schema.TypeString,
				Computed:    true,
				Description: "Name of the group that will own the VM",
			},
			"ip": {
				Type:        schema.TypeString,
				Computed:    true,
				Description: "IP address that is assigned to the VM",
			},
			"state": {
				Type:        schema.TypeInt,
				Computed:    true,
				Description: "Current state of the VM",
			},
			"lcmstate": {
				Type:        schema.TypeInt,
				Computed:    true,
				Description: "Current LCM state of the VM",
			},
		},
	}
}

func resourceVmCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*Client)

	resp, err := client.Call(
		"one.template.instantiate",
		d.Get("template_id"),
		d.Get("name"),
		false,
		"",
		false,
	)
	if err != nil {
		return err
	}

	d.SetId(resp)

	_, err = waitForVmState(d, meta, "running")
	if err != nil {
		return fmt.Errorf(
			"Error waiting for virtual machine (%s) to be in state RUNNING: %s", d.Id(), err)
	}

	if _, err = changePermissions(intId(d.Id()), permission(d.Get("permissions").(string)), client, "one.vm.chmod"); err != nil {
		return err
	}

	return resourceVmRead(d, meta)
}

func resourceVmRead(d *schema.ResourceData, meta interface{}) error {
	var vm *UserVm
	var vms *UserVms

	client := meta.(*Client)
	found := false
	name := d.Get("name").(string)
	if name == "" {
		name = d.Get("instance").(string)
	}

	// Try to find the vm by ID, if specified
	if d.Id() != "" {
		resp, err := client.Call("one.vm.info", intId(d.Id()))
		if err == nil {
			found = true
			if err = xml.Unmarshal([]byte(resp), &vm); err != nil {
				return err
			}
		} else {
			log.Printf("Could not find VM by ID %s", d.Id())
		}
	}

	// Otherwise, try to find the vm by (user, name) as the de facto compound primary key
	if d.Id() == "" || !found {
		resp, err := client.Call("one.vmpool.info", -3, -1, -1)
		if err != nil {
			return err
		}

		if err = xml.Unmarshal([]byte(resp), &vms); err != nil {
			return err
		}

		for _, v := range vms.UserVm {
			if v.Name == name {
				vm = v
				found = true
				break
			}
		}

		if !found || vm == nil {
			d.SetId("")
			log.Printf("Could not find vm with name %s for user %s", name, client.Username)
			return nil
		}
	}

	d.SetId(vm.Id)
	d.Set("instance", vm.Name)
	d.Set("uid", vm.Uid)
	d.Set("gid", vm.Gid)
	d.Set("uname", vm.Uname)
	d.Set("gname", vm.Gname)
	d.Set("state", vm.State)
	d.Set("lcmstate", vm.LcmState)
	d.Set("ip", vm.VmTemplate.Context.IP)
	d.Set("permissions", permissionString(vm.Permissions))

	return nil
}

func resourceVmExists(d *schema.ResourceData, meta interface{}) (bool, error) {
	err := resourceVmRead(d, meta)
	// a terminated VM is in state 6 (DONE)
	if err != nil || d.Id() == "" || d.Get("state").(int) == 6 {
		return false, err
	}

	return true, nil
}

func resourceVmUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*Client)

	if d.HasChange("permissions") {
		resp, err := changePermissions(intId(d.Id()), permission(d.Get("permissions").(string)), client, "one.vm.chmod")
		if err != nil {
			return err
		}
		log.Printf("[INFO] Successfully updated VM %s\n", resp)
	} else {
		log.Printf("[INFO] Sorry, only 'permissions' updates are supported at the moment.")
	}

	return nil
}

func resourceVmDelete(d *schema.ResourceData, meta interface{}) error {
	err := resourceVmRead(d, meta)
	if err != nil || d.Id() == "" {
		return err
	}

	client := meta.(*Client)
	resp, err := client.Call("one.vm.action", "terminate-hard", intId(d.Id()))
	if err != nil {
		return err
	}

	_, err = waitForVmState(d, meta, "done")
	if err != nil {
		return fmt.Errorf(
			"Error waiting for virtual machine (%s) to be in state DONE: %s", d.Id(), err)
	}

	log.Printf("[INFO] Successfully terminated VM %s\n", resp)
	return nil
}

func waitForVmState(d *schema.ResourceData, meta interface{}, state string) (interface{}, error) {
	var vm *UserVm
	client := meta.(*Client)

	log.Printf("Waiting for VM (%s) to be in state Done", d.Id())

	stateConf := &resource.StateChangeConf{
		Pending: []string{"anythingelse"},
		Target:  []string{state},
		Refresh: func() (interface{}, string, error) {
			log.Println("Refreshing VM state...")
			if d.Id() != "" {
				resp, err := client.Call("one.vm.info", intId(d.Id()))
				if err == nil {
					if err = xml.Unmarshal([]byte(resp), &vm); err != nil {
						return nil, "", fmt.Errorf("Couldn't fetch VM state: %s", err)
					}
				} else {
					return nil, "", fmt.Errorf("Could not find VM by ID %s", d.Id())
				}
			}
			log.Printf("VM is currently in state %v and in LCM state %v", vm.State, vm.LcmState)
			if vm.State == 3 && vm.LcmState == 3 {
				return vm, "running", nil
			} else if vm.State == 6 {
				return vm, "done", nil
			} else {
				return nil, "anythingelse", nil
			}
		},
		Timeout:    10 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	return stateConf.WaitForState()
}


text:
ACCEPTED

#### According to
GRIN Taxonomy for Plants

#### Published in
Bot. Mag. (Tokyo) 31:98. 1917

#### Original name
null

### Remarks
null


text:
'use strict';

const _ = require('lodash');
const fs = require('fs-extra');
const Promise = require('bluebird');

const Collector = require('../../../lib/collector');
const DataCollector = require('../../../lib/collector/data-collector');

describe('collector/index', () => {
    const sandbox = sinon.sandbox.create();

    const mkToolCollector_ = (opts) => {
        return _.defaults(opts || {}, {
            configureTestResult: (data) => {
                delete data.err;
                return data;
            },
            getSkipReason: sandbox.stub()
        });
    };

    const mkCollector_ = (toolCollectorOpts, opts) => {
        const toolCollector = mkToolCollector_(toolCollectorOpts);
        const config = _.defaults(opts || {}, {
            path: '/default/path'
        });

        return Collector.create(toolCollector, config);
    };

    afterEach(() => sandbox.restore());

    describe('create', () => {
        beforeEach(() => sandbox.stub(DataCollector, 'create'));

        it('should has static factory creation method', () => {
            assert.instanceOf(Collector.create(), Collector);
        });

        it('should create instance of DataCollector inside the Collector creation', () => {
            Collector.create();

            assert.calledOnce(DataCollector.create);
        });
    });

    describe('collect the results of the passed tests', () => {
        const saveReport_ = (collector) => {
            return collector.saveFile()
                .then(() => fs.outputJsonAsync.firstCall.args[1]);
        };

        beforeEach(() => {
            sandbox.stub(fs, 'outputJsonAsync').returns(Promise.resolve());
        });

        it('should add succesfully passed test', () => {
            const data = {fullName: 'some name', browserId: 'bro'};
            const collector = mkCollector_();

            collector.addSuccess(data);

            return saveReport_(collector).then((result) => {
                assert.deepEqual(result, {
                    'some name.bro': {
                        fullName: 'some name',
                        browserId: 'bro',
                        status: 'success'
                    }});
            });
        });

        it('should add failed test', () => {
            const testError = new Promise.OperationalError('test');
            const data = {fullName: 'some name', browserId: 'bro', err: testError};
            const collector = mkCollector_();

            collector.addFail(data);

            return saveReport_(collector).then((result) => {
                assert.deepEqual(result, {'some name.bro': {
                    fullName: 'some name',
                    browserId: 'bro',
                    status: 'fail',
                    errorReason: {message: testError.message, stack: testError.stack},
                    retries: [{message: testError.message, stack: testError.stack}]
                }});
            });
        });

        it('should add skipped test', () => {
            const data = {fullName: 'some name', browserId: 'bro'};
            const collector = mkCollector_({
                getSkipReason: sandbox.stub().returns('some-reason')
            });

            collector.addSkipped(data);

            return saveReport_(collector).then((result) => {
                assert.deepEqual(result, {'some name.bro': {
                    fullName: 'some name',
                    browserId: 'bro',
                    status: 'skipped',
                    skipReason: 'some-reason'
                }});
            });
        });

        it('should add failed test if the retry fails', () => {
            const testError = new Promise.OperationalError('test');
            const data = {fullName: 'some name', browserId: 'bro', err: testError};
            const collector = mkCollector_();

            collector.addRetry(data);

            return saveReport_(collector).then((result) => {
                assert.deepEqual(result, {'some name.bro': {
                    fullName: 'some name',
                    browserId: 'bro',
                    status: 'fail',
                    errorReason: {message: testError.message, stack: testError.stack},
                    retries: [{message: testError.message, stack: testError.stack}]
                }});
            });
        });

        it('should add errored test with reason from "message"', () => {
            const data = {fullName: 'some name', browserId: 'bro', message: 'err-msg'};
            const collector = mkCollector_();

            collector.addError(data);

            return saveReport_(collector)
                .then((result) => assert.deepPropertyVal(result['some name.bro'], 'errorReason.message', 'err-msg'));
        });

        it('should add errored test with reason from "stack"', () => {
            const data = {fullName: 'some name', browserId: 'bro', message: 'err-msg', stack: 'stack-msg'};
            const collector = mkCollector_();

            collector.addError(data);

            return saveReport_(collector)
                .then((result) => assert.deepPropertyVal(result['some name.bro'], 'errorReason.stack', 'stack-msg'));
        });
    });

    describe('saveFile', () => {
        beforeEach(() => sandbox.stub(fs, 'outputJsonAsync'));

        it('should save json file on file system for given file path', () => {
            fs.outputJsonAsync.returns(Promise.resolve());

            const collector = mkCollector_({}, {path: '/some-folder/file.json'});

            return collector.saveFile()
                .then(() => assert.calledWith(fs.outputJsonAsync, '/some-folder/file.json'));
        });

        it('should show an error if error occurred on saving file', () => {
            fs.outputJsonAsync.returns(Promise.reject('some-error'));
            sandbox.stub(console, 'error');

            const collector = mkCollector_({});

            return collector.saveFile()
                .then(() => assert.calledWith(console.error, 'some-error'));
        });
    });
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

	<title><?php echo $title; ?></title>
	<link href='http://fonts.googleapis.com/css?family=Roboto:300italic,400italic,300,400,500,700,900' rel='stylesheet' type='text/css'/>
	<?php echo Asset::css('theme-default/bootstrap.css'); ?>
	<?php echo Asset::css('theme-default/materialadmin.css'); ?>
	<?php echo Asset::css('theme-default/font-awesome.min.css'); ?>
	<?php echo Asset::css('theme-default/material-design-iconic-font.min.css'); ?>
	<?php echo Asset::css('jquery.datetimepicker.css') ?>
   	<?php echo Asset::css('plugins.css'); ?>
	<?php echo Asset::css('bootstrap.min.css'); ?>

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">
	<?php echo Asset::css('bootstrap.css'); ?>

	<?php echo Asset::js(array(
		'http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js',
		'bootstrap.js',
		'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js',
		'jquery.datetimepicker.full.js'
	)); ?>

	<?php if ($current_user): ?>

                        	<?php echo Html::anchor('admin', 'CheckKoBayadKo') ?>

                    <form class="navbar-search" role="search">

                            <input type="text" class="form-control" name="headerSearch" placeholder="Enter your keyword">

                        <button type="submit" class="btn btn-icon-toggle ink-reaction"></button>
                    </form>

                    	<?php echo Asset::img('default_icon.png') ?>
                     	<?php echo " " . $current_user->username?>

 <?php echo Html::anchor('admin/logout', ' Logout') ?>

    <?php //$this->load->view($v); ?>

					<?php
						$files = new GlobIterator(APPPATH.'classes/controller/admin/*.php');

						foreach($files as $file)
						{
							$section_segment = $file->getBasename('.php');

							//START SUPER ADMIN -->
							if($current_user->role == 10):
									$section_title = Inflector::humanize($section_segment);
									?>
									<li class="<?php echo Uri::segment(2) == $section_segment ? 'active' : '' ?>">

										<?php echo Html::anchor('admin/'.$section_segment, '

 '.$section_title) . ''?>

							<?php endif ?>

							<?php
							//START VPAAS -->
							if($current_user->role == 7):
								if ($section_segment == "vpaas"):
									$section_title = Inflector::humanize($section_segment);
									?>
									<li class="<?php echo Uri::segment(2) == $section_segment ? 'active' : '' ?>">
										<?php echo Html::anchor('admin/'.$section_segment, '

 '. $section_title). ''?>

								<?php endif ?>
							<?php endif ?>

							<?php
							//START ADMIN -->
							if($current_user->role == 6):
								if ($section_segment == "admins"):
									$section_title = Inflector::humanize($section_segment);
									?>
									<li class="<?php echo Uri::segment(2) == $section_segment ? 'active' : '' ?>">

									<?php echo Html::anchor('admin/'.$section_segment, $section_title)?>

								<?php endif ?>
							<?php endif ?>

							<?php
							//START PRINCIPAL -->
							if($current_user->role == 5):
								if ($section_segment == "principals"):
									$section_title = Inflector::humanize($section_segment);
									?>
									<li class="<?php echo Uri::segment(2) == $section_segment ? 'active' : '' ?>">
										<?php echo Html::anchor('admin/'.$section_segment, $section_title)?>

								<?php endif ?>
							<?php endif ?>

							<?php
							//START CASHIERS -->
							if($current_user->role == 4):
								if ($section_segment == "cashiers"):
									$section_title = Inflector::humanize($section_segment);
									?>
									<li class="<?php echo Uri::segment(2) == $section_segment ? 'active' : '' ?>">
										<?php echo Html::anchor('admin/'.$section_segment, $section_title)?>

								<?php endif ?>
							<?php endif ?>

							<?php
							//START DEAN / PROGRAM -->
							if($current_user->role == 1 || $current_user->role == 2):
								if ($section_segment == "deans" ):
									$section_title = Inflector::humanize($section_segment);
									?>
									<li class="<?php echo Uri::segment(2) == $section_segment ? 'active' : '' ?>">
										<?php echo Html::anchor('admin/'.$section_segment, $section_title)?>

								<?php endif ?>
							<?php endif ?>

							<?php
							//START ACCOUNTANT
							if($current_user->role == 3):
								if ($section_segment == "accountants" || $section_segment == "users" || $section_segment == "students" ):
									$section_title = Inflector::humanize($section_segment);
									?>
									<li class="<?php echo Uri::segment(2) == $section_segment ? 'active' : '' ?>">
										<?php echo Html::anchor('admin/'.$section_segment, $section_title)?>

								<?php endif ?>
							<?php endif ?>

							<?php
						}
					?>

	<?php endif; ?>

<?php if (Session::get_flash('success')): ?>

					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

					<?php echo implode('

', (array) Session::get_flash('success')); ?>

<?php endif; ?>
<?php if (Session::get_flash('error')): ?>

					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

					<?php echo implode('

', (array) Session::get_flash('error')); ?>

<?php endif; ?>

				<?php echo $content; ?>

Copyright © CheckKoBayadKo 2016

<?php echo Asset::js(array(
		'libs/jquery/jquery-1.11.2.min.js',
		'libs/jquery/jquery-migrate-1.2.1.min.js',
		'libs/bootstrap/bootstrap.min.js',
		'libs/spin.js/spin.min.js',
		'libs/autosize/jquery.autosize.min.js',
		'libs/nanoscroller/jquery.nanoscroller.min.js',
		'core/source/App.js',
		'core/source/AppNavigation.js',
		'core/source/AppOffcanvas.js',
		'libs/autosize/jquery.autosize.min.js',
		'core/source/AppCard.js',
		'core/source/AppForm.js',
		'core/source/AppNavSearch.js',
		'core/source/AppVendor.js',
		'core/demo/Demo.js',
	)); ?>


text:
package de.tr7zw.changeme.nbtapi;

import java.util.Map;

import org.bukkit.persistence.PersistentDataContainer;

import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;

public class NBTPersistentDataContainer extends NBTCompound {

    private final PersistentDataContainer container;

    public NBTPersistentDataContainer(PersistentDataContainer container) {
        super(null, null);
        this.container = container;
    }

    @Override
    public Object getCompound() {
        return ReflectionMethod.CRAFT_PERSISTENT_DATA_CONTAINER_TO_TAG.run(container);
    }

    @Override
    protected void setCompound(Object compound) {
        @SuppressWarnings("unchecked")
        Map<Object, Object> map = (Map<Object, Object>) ReflectionMethod.CRAFT_PERSISTENT_DATA_CONTAINER_GET_MAP
                .run(container);
        map.clear();
        ReflectionMethod.CRAFT_PERSISTENT_DATA_CONTAINER_PUT_ALL.run(container, compound);
    }

}


text:
package do

import "github.com/digitalocean/godo"

// Tag is a wrapper for godo.Tag
type Tag struct {
	*godo.Tag
}

// Tags is a slice of Tag.
type Tags []Tag

// TagsService is an interface for interacting with DigitalOcean's tags api.
type TagsService interface {
	List() (Tags, error)
	Get(string) (*Tag, error)
	Create(*godo.TagCreateRequest) (*Tag, error)
	Update(string, *godo.TagUpdateRequest) error
	Delete(string) error
	TagResources(string, *godo.TagResourcesRequest) error
	UntagResources(string, *godo.UntagResourcesRequest) error
}

type tagsService struct {
	client *godo.Client
}

var _ TagsService = (*tagsService)(nil)

// NewTagsService builds a TagsService instance.
func NewTagsService(godoClient *godo.Client) TagsService {
	return &tagsService{
		client: godoClient,
	}
}

func (ts *tagsService) List() (Tags, error) {
	f := func(opt *godo.ListOptions) ([]interface{}, *godo.Response, error) {
		list, resp, err := ts.client.Tags.List(opt)
		if err != nil {
			return nil, nil, err
		}

		si := make([]interface{}, len(list))
		for i := range list {
			si[i] = list[i]
		}

		return si, resp, err
	}

	si, err := PaginateResp(f)
	if err != nil {
		return nil, err
	}

	list := make(Tags, len(si))
	for i := range si {
		a := si[i].(godo.Tag)
		list[i] = Tag{Tag: &a}
	}

	return list, nil
}

func (ts *tagsService) Get(name string) (*Tag, error) {
	t, _, err := ts.client.Tags.Get(name)
	if err != nil {
		return nil, err
	}

	return &Tag{Tag: t}, nil
}

func (ts *tagsService) Create(tcr *godo.TagCreateRequest) (*Tag, error) {
	t, _, err := ts.client.Tags.Create(tcr)
	if err != nil {
		return nil, err
	}

	return &Tag{Tag: t}, nil
}

func (ts *tagsService) Update(name string, tur *godo.TagUpdateRequest) error {
	_, err := ts.client.Tags.Update(name, tur)
	return err
}

func (ts *tagsService) Delete(name string) error {
	_, err := ts.client.Tags.Delete(name)
	return err
}

func (ts *tagsService) TagResources(name string, trr *godo.TagResourcesRequest) error {
	_, err := ts.client.Tags.TagResources(name, trr)
	return err
}

func (ts *tagsService) UntagResources(name string, urr *godo.UntagResourcesRequest) error {
	_, err := ts.client.Tags.UntagResources(name, urr)
	return err
}


text:
import BasePartnersModule from './basePartners'
import BasePartnersController from './basePartners.controller';
import BasePartnersComponent from './basePartners.component';
import BasePartnersTemplate from './basePartners.html';

describe('BasePartners', () => {
  let $rootScope, makeController;

  beforeEach(window.module(BasePartnersModule));
  beforeEach(inject((_$rootScope_) => {
    $rootScope = _$rootScope_;
    makeController = () => {
      return new BasePartnersController();
    };
  }));

  describe('Module', () => {
    // top-level specs: i.e., routes, injection, naming
  });

  describe('Controller', () => {
    // controller specs
    it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller
      let controller = makeController();
      expect(controller).to.have.property('name');
    });
  });

  describe('Template', () => {
    // template specs
    // tip: use regex to ensure correct bindings are used e.g., {{  }}
    it('has name in template [REMOVE]', () => {
      expect(BasePartnersTemplate).to.match(/{{\s?\$ctrl\.name\s?}}/g);
    });
  });

  describe('Component', () => {
      // component/directive specs
      let component = BasePartnersComponent;

      it('includes the intended template',() => {
        expect(component.template).to.equal(BasePartnersTemplate);
      });

      it('invokes the right controller', () => {
        expect(component.controller).to.equal(BasePartnersController);
      });
  });
});


text:
package org.ehcache.sample;

import org.slf4j.Logger;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.spi.CachingProvider;
import java.util.concurrent.TimeUnit;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Created by fabien.sanglier on 10/6/16.
 */
public class CreateExtendedJCache extends BaseJCacheTester {
  private static final Logger LOGGER = getLogger(CreateExtendedJCache.class);

  public static void main(String[] args) throws Exception {
    // pass in the number of object you want to generate, default is 100
    int numberOfObjects = Integer.parseInt(args.length == 0 ? "5000" : args[0]);
    int numberOfIteration = Integer.parseInt(args.length == 0 ? "5" : args[1]);
    int sleepTimeMillisBetweenIterations = Integer.parseInt(args.length == 0 ? "1000" : args[2]);

    new CreateExtendedJCache().run(numberOfIteration, numberOfObjects, sleepTimeMillisBetweenIterations);

    LOGGER.info("Exiting");
  }

  public void run(int numberOfIteration, int numberOfObjectPerIteration, int sleepTimeMillisBetweenIterations) throws Exception {
    LOGGER.info("Extended JCache testing BEGIN - Creating extended JCache programmatically using ehcache templates.");

    //finds ehcache provider automatically if it is in the classpath
    CachingProvider cachingProvider = Caching.getCachingProvider();

    // If there are multiple providers in your classpath, use the fully qualified name to retrieve the Ehcache caching provider.
    //CachingProvider cachingProvider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");

    // This time, load the cache manager from the XML to extend JSR107 by using the cache-templates created
    String xmlClassPath = System.getProperty("jsr107.config.classpath", "ehcache-jsr107-extendedWithTemplates.xml");

    try (CacheManager cacheManager = cachingProvider.getCacheManager(
      Thread.currentThread().getContextClassLoader().getResource(xmlClassPath).toURI(),
      Thread.currentThread().getContextClassLoader())) {

      LOGGER.info("----------------------------------------------------------------");
      String cacheName = "myJCache";

      //this new cache should use the default maxEntriesOnHeapCache template defined in the config
      LOGGER.info("Cache testing with new cache name {} - " +
        "The new cache should use the default 'maxEntriesOnHeapCache' template defined in the config.", cacheName);
      Cache<Long, String> myJCache = cacheManager.createCache(
        cacheName,
        new MutableConfiguration<Long, String>()
          .setTypes(Long.class, String.class)
          .setStoreByValue(false)
          .setStatisticsEnabled(true)
          .setExpiryPolicyFactory(FactoryBuilder.factoryOf(new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, 5)))));

      simpleGetsAndPutsCacheTest(myJCache, numberOfIteration, numberOfObjectPerIteration, sleepTimeMillisBetweenIterations, new KeyValueGenerator<Long, String>() {
        @Override
        public Long getKey(Number k) {
          return new Long(k.longValue());
        }

        @Override
        public String getValue(Number v) {
          return String.format("Da One %s!!", v.toString());
        }
      });

      LOGGER.info("----------------------------------------------------------------");
      cacheName = "byRefCache";

      //this new cache should use the default byRefCache template defined in the config
      LOGGER.info("Cache testing with cache name {} - " +
        "The new cache should use the jsr107 default matched by name '{}' defined in the config.", cacheName, cacheName);

      LOGGER.info("Cache testing with cache name {} - ", cacheName);

      //this new cache should use the default maxEntriesOnHeapCache template defined in the config
      Cache<Long, String> myJCache2 = cacheManager.createCache(
        cacheName,
        new MutableConfiguration<Long, String>()
          .setTypes(Long.class, String.class)
          .setStoreByValue(false)
          .setStatisticsEnabled(true)
          .setExpiryPolicyFactory(FactoryBuilder.factoryOf(new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, 5)))));

      simpleGetsAndPutsCacheTest(myJCache, numberOfIteration, numberOfObjectPerIteration, sleepTimeMillisBetweenIterations, new KeyValueGenerator<Long, String>() {
        @Override
        public Long getKey(Number k) {
          return new Long(k.longValue());
        }

        @Override
        public String getValue(Number v) {
          return String.format("Da One %s!!", v.toString());
        }
      });

      LOGGER.info("----------------------------------------------------------------");
      cacheName = "byValueTemplate";

      //this new cache should use the default byRefCache template defined in the config
      LOGGER.info("Cache testing with cache name {} - " +
        "The new cache should use the jsr107 default matched by name '{}' defined in the config.", cacheName, cacheName);

      //this new cache should use the default maxEntriesOnHeapCache template defined in the config
      Cache<Long, String> myJCache3 = cacheManager.createCache(
        cacheName,
        new MutableConfiguration<Long, String>()
          .setTypes(Long.class, String.class)
          .setStoreByValue(false)
          .setStatisticsEnabled(true)
          .setExpiryPolicyFactory(FactoryBuilder.factoryOf(new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, 5)))));

      simpleGetsAndPutsCacheTest(myJCache, numberOfIteration, numberOfObjectPerIteration, sleepTimeMillisBetweenIterations, new KeyValueGenerator<Long, String>() {
        @Override
        public Long getKey(Number k) {
          return new Long(k.longValue());
        }

        @Override
        public String getValue(Number v) {
          return String.format("Da One %s!!", v.toString());
        }
      });
    }
    LOGGER.info("Extended JCache testing DONE - Creating extended JCache programmatically using ehcache templates.");
  }
}


text:
package org.apache.drill.exec.store.cassandra.schema;

import org.apache.calcite.DataContext;
import org.apache.calcite.adapter.cassandra.CassandraSchema;
import org.apache.calcite.linq4j.tree.Expression;
import org.apache.calcite.linq4j.tree.Expressions;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaFactory;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.util.BuiltInMethod;
import org.apache.drill.exec.store.AbstractSchema;
import org.apache.drill.exec.store.StoragePlugin;
import org.apache.drill.exec.store.cassandra.CassandraStorageConfig;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CassandraRootDrillSchema extends AbstractSchema {
  private final Map<String, Schema> schemas = new ConcurrentHashMap<>();

  private final StoragePlugin plugin;
  private final SchemaFactory schemaFactory;
  private final SchemaPlus parent;
  private final String parentName;
  private final Map<String, Object> configMap;

  public CassandraRootDrillSchema(String name, StoragePlugin plugin, SchemaFactory schemaFactory,
      SchemaPlus parent, String parentName, Map<String, Object> configMap) {
    super(Collections.emptyList(), name);
    this.plugin = plugin;
    this.schemaFactory = schemaFactory;
    this.parent = parent;
    this.parentName = parentName;
    this.configMap = configMap;
  }

  @Override
  public String getTypeName() {
    return CassandraStorageConfig.NAME;
  }

  @Override
  public Schema getSubSchema(String name) {
    return schemas.computeIfAbsent(name, this::createSubSchema);
  }

  private Schema createSubSchema(String schemaName) {
    Map<String, Object> configs = new HashMap<>(configMap);
    configs.put("keyspace", schemaName);

    SchemaPlus parentSchema = parent.getSubSchema(parentName);
    Schema schema = new CassandraDrillSchema(schemaName, plugin,
        (CassandraSchema) schemaFactory.create(parentSchema, schemaName, configs));
    parentSchema.add(schemaName, schema);
    return schema;
  }

  @Override
  public Expression getExpression(SchemaPlus parentSchema, String name) {
    return Expressions.call(
        DataContext.ROOT,
        BuiltInMethod.DATA_CONTEXT_GET_ROOT_SCHEMA.method);
  }
}


text:
{% extends "layout.html" %}

{% block title %}
    Home
{% endblock %}

{% block main %}

            All Collections
            Fantasy
            Sci-Fi
            Classics
            Fairy Tale
            Young Adult

            <select class="sort-options">
            <option value="" disabled selected>Sort by</option>
            <option value="" >Featured</option>
            <option value="title">Alphabetical</option>
            <option value="date-created">Published</option>
            </select>

          {% for book in books %}

{{ book["remote"]["title"] }}

by {{ book["remote"]["author"]|join('') }}

{{ book["remote"]["description"]|truncate(110) }}

                Details

                Close

{{ book["remote"]["title"] }}

{{ book["remote"]["author"]|join('') }}

{{ book["remote"]["description"]|truncate(400) }}

                  Download {{ book["local"]["type"]|upper() }}
                  More about this book

                  Back

More about this book:

Full description:

{{ book["remote"]["description"] }}

            {% endfor %}

Of Mice and Men

by John Steinbeck • 1937

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tellus nisi, eget pulvinar in, molestie et arcu.

                Details

                Close

Of Mice and Men

by John Steinbeck

1937

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam luctus convallis sem. Nunc sed tristique augue. Aenean at nulla vel lacus volutpat bibendum vitae ut nibh. Aliquam eu metus et purus rutrum malesuada. Aenean in auctor mauris,
                    non vulputate libero. Nullam auctor, purus ut cursus convallis, lectus tellus dignissim lectus, id tempor ipsum leo ut nulla. Vestibulum vitae elit erat.

                  Preview

                  Back

Preview

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam luctus convallis sem. Nunc sed tristique augue. Aenean at nulla vel lacus volutpat bibendum vitae ut nibh. Aliquam eu metus et purus rutrum malesuada. Aenean in auctor
                      mauris, non vulputate libero. Nullam auctor, purus ut cursus convallis, lectus tellus dignissim lectus, id tempor ipsum leo ut nulla. Vestibulum vitae elit erat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam luctus convallis sem. Nunc sed tristique augue. Aenean at nulla vel lacus volutpat bibendum vitae ut nibh. Aliquam eu metus et purus rutrum malesuada. Aenean in auctor
                      mauris, non vulputate libero. Nullam auctor, purus ut cursus convallis, lectus tellus dignissim lectus, id tempor ipsum leo ut nulla. Vestibulum vitae elit erat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam luctus convallis sem. Nunc sed tristique augue. Aenean at nulla vel lacus volutpat bibendum vitae ut nibh. Aliquam eu metus et purus rutrum malesuada. Aenean in auctor
                      mauris, non vulputate libero. Nullam auctor, purus ut cursus convallis, lectus tellus dignissim lectus, id tempor ipsum leo ut nulla. Vestibulum vitae elit erat.

Harry Potter and the Deathly Hallows

by J.K. Rowling • 2007

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tellus nisi, eget pulvinar in, molestie et arcu.

                Details

                Close

Harry Potter and the Deathly Hallows

by J.K. Rowling

2007

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam luctus convallis sem. Nunc sed tristique augue. Aenean at nulla vel lacus volutpat bibendum vitae ut nibh. Aliquam eu metus et purus rutrum malesuada. Aenean in auctor mauris,
                    non vulputate libero. Nullam auctor, purus ut cursus convallis, lectus tellus dignissim lectus, id tempor ipsum leo ut nulla. Vestibulum vitae elit erat.

                  Preview

                  Back

Preview

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam luctus convallis sem. Nunc sed tristique augue. Aenean at nulla vel lacus volutpat bibendum vitae ut nibh. Aliquam eu metus et purus rutrum malesuada. Aenean in auctor
                      mauris, non vulputate libero. Nullam auctor, purus ut cursus convallis, lectus tellus dignissim lectus, id tempor ipsum leo ut nulla. Vestibulum vitae elit erat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam luctus convallis sem. Nunc sed tristique augue. Aenean at nulla vel lacus volutpat bibendum vitae ut nibh. Aliquam eu metus et purus rutrum malesuada. Aenean in auctor
                      mauris, non vulputate libero. Nullam auctor, purus ut cursus convallis, lectus tellus dignissim lectus, id tempor ipsum leo ut nulla. Vestibulum vitae elit erat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam luctus convallis sem. Nunc sed tristique augue. Aenean at nulla vel lacus volutpat bibendum vitae ut nibh. Aliquam eu metus et purus rutrum malesuada. Aenean in auctor
                      mauris, non vulputate libero. Nullam auctor, purus ut cursus convallis, lectus tellus dignissim lectus, id tempor ipsum leo ut nulla. Vestibulum vitae elit erat.

{% endblock %}


text:
package jdk.internal.jimage;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BasicImageReader {
    private final String imagePath;
    private final PReader preader;
    private final ByteOrder byteOrder;
    private final ImageHeader header;
    private final int indexSize;
    private final IntBuffer redirectBuffer;
    private final IntBuffer offsetsBuffer;
    private final ByteBuffer locationsBuffer;
    private final ByteBuffer stringsBuffer;
    private final ImageStrings strings;

    protected BasicImageReader(String imagePath, ByteOrder byteOrder) throws IOException {
        this.imagePath = imagePath;
        this.preader = PReader.open(imagePath);
        this.byteOrder = byteOrder;
        this.header = ImageHeader.readFrom(byteOrder, getIntBuffer(0, ImageHeader.getHeaderSize()));
        this.indexSize = header.getIndexSize();
        this.redirectBuffer = getIntBuffer(header.getRedirectOffset(), header.getRedirectSize());
        this.offsetsBuffer = getIntBuffer(header.getOffsetsOffset(), header.getOffsetsSize());
        this.locationsBuffer = getByteBuffer(header.getLocationsOffset(), header.getLocationsSize());
        this.stringsBuffer = getByteBuffer(header.getStringsOffset(), header.getStringsSize());
        this.strings = new ImageStrings(new ImageStream(stringsBuffer));
    }

    protected BasicImageReader(String imagePath) throws IOException {
        this(imagePath, ByteOrder.nativeOrder());
    }

    public static BasicImageReader open(String imagePath) throws IOException {
        return new BasicImageReader(imagePath, ByteOrder.nativeOrder());
    }

    public String imagePath() {
        return imagePath;
    }

    public boolean isOpen() {
        return preader.isOpen();
    }

    public void close() throws IOException {
        preader.close();
    }

    public ImageHeader getHeader() {
        return header;
    }

    public ImageLocation findLocation(String name) {
        return findLocation(new UTF8String(name));
    }

    public ImageLocation findLocation(byte[] name) {
        return findLocation(new UTF8String(name));
    }

    public synchronized ImageLocation findLocation(UTF8String name) {
        int count = header.getLocationCount();
        int hash = name.hashCode() % count;
        int redirect = getRedirect(hash);

        if (redirect == 0) {
            return null;
        }

        int index;

        if (redirect < 0) {
            // If no collision.
            index = -redirect - 1;
        } else {
            // If collision, recompute hash code.
            index = name.hashCode(redirect) % count;
        }

        int offset = getOffset(index);

        if (offset == 0) {
            return null;
        }

        ImageLocation location = getLocation(offset);

        return location.verify(name) ? location : null;
    }

    public String[] getEntryNames() {
        return getEntryNames(true);
    }

    public String[] getEntryNames(boolean sorted) {
        int count = header.getLocationCount();
        List<String> list = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            int offset = getOffset(i);

            if (offset != 0) {
                ImageLocation location = ImageLocation.readFrom(locationsBuffer, offset, strings);
                list.add(location.getFullnameString());
            }
        }

        String[] array = list.toArray(new String[0]);

        if (sorted) {
            Arrays.sort(array);
        }

        return array;
    }

    protected ImageLocation[] getAllLocations(boolean sorted) {
        int count = header.getLocationCount();
        List<ImageLocation> list = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            int offset = getOffset(i);

            if (offset != 0) {
                ImageLocation location = ImageLocation.readFrom(locationsBuffer, offset, strings);
                list.add(location);
            }
        }

        ImageLocation[] array = list.toArray(new ImageLocation[0]);

        if (sorted) {
            Arrays.sort(array, (ImageLocation loc1, ImageLocation loc2) ->
                    loc1.getFullnameString().compareTo(loc2.getFullnameString()));
        }

        return array;
    }

    private IntBuffer getIntBuffer(long offset, long size) throws IOException {
        MappedByteBuffer buffer = preader.channel().map(FileChannel.MapMode.READ_ONLY, offset, size);
        buffer.order(byteOrder);

        return buffer.asIntBuffer();
    }

    private ByteBuffer getByteBuffer(long offset, long size) throws IOException {
        MappedByteBuffer buffer = preader.channel().map(FileChannel.MapMode.READ_ONLY, offset, size);
        // order is not copied into the readonly copy.
        ByteBuffer readOnly = buffer.asReadOnlyBuffer();
        readOnly.order(byteOrder);
        return readOnly;
    }

    private int getRedirect(int index) {
        return redirectBuffer.get(index);
    }

    private int getOffset(int index) {
        return offsetsBuffer.get(index);
    }

    private ImageLocation getLocation(int offset) {
        return ImageLocation.readFrom(locationsBuffer, offset, strings);
    }

    public String getString(int offset) {
        return strings.get(offset).toString();
    }

    public byte[] getResource(ImageLocation loc) throws IOException {
        long compressedSize = loc.getCompressedSize();
        assert compressedSize < Integer.MAX_VALUE;

        if (compressedSize == 0) {
            return preader.read((int)loc.getUncompressedSize(),
                                indexSize + loc.getContentOffset());
        } else {
            byte[] buf = preader.read((int)compressedSize,
                                      indexSize + loc.getContentOffset());
            return ImageFile.Compressor.decompress(buf);
        }
    }

    public byte[] getResource(String name) throws IOException {
        ImageLocation location = findLocation(name);

        return location != null ? getResource(location) : null;
    }

    public List<String> getNames(String name) throws IOException {
        return getNames(getResource(name));
    }

    public List<String> getNames(byte[] bytes) {
        IntBuffer buffer = ByteBuffer.wrap(bytes).asIntBuffer();
        List<String> names = new ArrayList<>();

        while (buffer.hasRemaining()) {
            int offset = buffer.get();
            names.add(getString(offset));
        }

        return names;
    }
}


text:
namespace Ilwis {

class Ifnode : public ASTNode
{
public:
    Ifnode();
    bool evaluate(SymbolTable& symbols, int scope, ExecutionContext *ctx);
    void setCondition(ExpressionNode *expr);
    void addThen(ASTNode *node);
    void addElse(ASTNode *node);

private:
    QSharedPointer<ExpressionNode> _condition;
    std::vector<QSharedPointer<ASTNode>> _then;
    std::vector<QSharedPointer<ASTNode>> _else;

};
}

#endif // IFNODE_H