text:
// ==========================================================================
//                            DG.DataLayerModel
//
//  Author:   William Finzer
//
//  Copyright ©2014 Concord Consortium
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

sc_require('alpha/destroyable');
sc_require('components/graph/utilities/plot_utilities');

/** @class  DG.DataLayerModel - The model for a for use in a display situation such as a graph or map.

 @extends SC.Object
 */
DG.DataLayerModel = SC.Object.extend( DG.Destroyable,
  /** @scope DG.DataLayerModel.prototype */
  {
    autoDestroyProperties: [ 'legend' ],

    /**
     * @property {number} May be used to access controller for calls to createComponentStorage and
     * restoreComponentStorage for purposes of undo/redo
     */
    componentID: null,

    /**
     @property { DG.LegendModel }
     */
    legend: null,

    /**
     @property { DG.GraphDataConfiguration }
     */
    dataConfiguration: null,

    /**
     * @property {String}
     */
    defaultTitle: function() {
      return this.getPath('dataConfiguration.defaultTitle');
    }.property(),

    defaultTitleChanged: function() {
      this.notifyPropertyChange('defaultTitle');
    }.observes('*dataConfiguration.defaultTitle'),

    /**
      @property { DG.CollectionClient }
    */
    collectionClient: null,
    collectionClientBinding: '*dataConfiguration.collectionClient',

    /**
      The plot model needs access to the cases controller that is stored in my dataConfiguration's
        collection client.
      @property { SC.ArrayController }
    */
    casesController: null,
    casesControllerBinding: '*dataConfiguration.collectionClient.casesController',

    /**
     * @property {Array} of DG.Case
     */
    cases: function() {
      return this.getPath('dataConfiguration.cases');
    }.property(),

    casesDidChange: function() {
      this.notifyPropertyChange('cases');
    }.observes('*dataConfiguration.cases'),

    /**
      @property { SC.SelectionSet }
    */
    selection: function() {
      return this.getPath('dataConfiguration.selection');
    }.property(),

    selectionDidChange: function() {
      this.notifyPropertyChange('selection');
    }.observes('*dataConfiguration.selection'),

    /**
     Work around current notification bug whereby we get notified that number of cases has
     changed even when it hasn't.
     @property {Number}
     */
    _oldNumberOfCases: 0,

    /**
     * Point color default can be changed by user.
     * @property {String} representing a color
     */
    pointColor: DG.PlotUtilities.kDefaultPointColor,

    /**
     * This function is passed as an accessor to certain plots and axes
     * @return {*}
     */
    getPointColor: function() {
      return this.get('pointColor');
    },

    /**
     * Stroke color default can be changed by user.
     * @property {String} representing a color
     */
    _strokeColor: null,
    /**
     * @property{Number} between 0 and 1
     */
    _strokeTransparency: null,

    strokeColor: function( iKey, iValue) {
      var tLegendAttribute = this.hasLegendVar() &&
            this.getPath('dataConfiguration.legendAttributeDescription.attribute'),
          tLegendColorMap = tLegendAttribute && tLegendAttribute.get('categoryMap');
      if( iValue !== undefined) {
        this._strokeColor = iValue;
        if(tLegendColorMap)
            tLegendColorMap['stroke-color'] = iValue;
      }
      var tLegendStrokeColor = DG.ColorUtilities.getStrokeColorFromColorMap( tLegendColorMap),
          tResult = tLegendStrokeColor || this._strokeColor ||
              (tLegendAttribute ? DG.PlotUtilities.kDefaultStrokeColorWithLegend :
                  DG.PlotUtilities.kDefaultStrokeColor);
      return tResult;
    }.property(),

    strokeTransparency: function( iKey, iValue) {
      var tLegendAttribute = this.hasLegendVar() &&
            this.getPath('dataConfiguration.legendAttributeDescription.attribute'),
          tLegendColorMap = tLegendAttribute && tLegendAttribute.get('categoryMap');
      if( iValue !== undefined) {
        this._strokeTransparency = iValue;
        if(tLegendColorMap)
          tLegendColorMap['stroke-transparency'] = iValue;
      }
      var tLegendStrokeTransparency = tLegendColorMap ? tLegendColorMap['stroke-transparency'] : null,
          tResult;
      if (!SC.none(tLegendStrokeTransparency))
        tResult = tLegendStrokeTransparency;
      else if (!SC.none(this._strokeTransparency))
        tResult = this._strokeTransparency;
      else
        tResult = tLegendAttribute ? DG.PlotUtilities.kDefaultStrokeOpacityWithLegend :
            DG.PlotUtilities.kDefaultStrokeOpacity;
      return tResult;
    }.property(),

    /**
     * If true, then the stroke color/transparency will be the same as that used to fill the element
     * @property {Boolean}
     */
    strokeSameAsFill: false,

    hasLegendVar: function() {
      return !SC.none( this.getPath('dataConfiguration.legendAttributeDescription.attributeID'));
    },

    /**
     * Point size is computed at the view level and then multiplied by this number. Default is 1.
     * @property {Number} between 0 and 2
     */
    pointSizeMultiplier: 1,

    /**
     * Needed for MapPointLayer that relies on this accessor in call to PlotLayer::CalcPointRadius
     * @returns {Number}
     */
    getPointSizeMultiplier: function() {
      return this.get('pointSizeMultiplier');
    },

    /**
     * Point size is computed at the view level and then multiplied by this number. Default is 1.
     * @property {Number} between 0 and 2
     */
    transparency: DG.PlotUtilities.kDefaultPointOpacity,

    /**
     Prepare dependencies.
     */
    init: function() {
      sc_super();

     },

    destroy: function() {
      if( this.get('dataContext'))
         this.get('dataContext').removeObserver('changeCount', this, 'handleDataContextNotification');
      sc_super();
      // Special case in which we have to destroy a property _after_ rest of destroy has happened in order to
      // allow all observers of dataConfiguration to get removed.
      this.destroyProperty('dataConfiguration');
    },

    /**
     * This is called when the dataContext has changed. We prepare to accept a new dataContext and be
     * reconfigured with new axes, plots, and legends.
     */
    reset: function() {
      this.init();
    },

    /**
     * Subclasses will append if necessary.
     * These appear in the valuePane of the inspector
     * @property {[SC.Control]}
     */
    lastValueControls: function() {
      return [];
    }.property(),

   /**
     * Subclasses will append if necessary.
     * These appear in the configurationPane of the inspector
     * @property {[SC.Control]}
     */
    lastConfigurationControls: function() {
      return [];
    }.property(),

    /**
     * Default is true. Subclasses will override as desired.
     * @returns {boolean}
     */
    wantsInspector: function() {
      return true;
    },

    /**
      The data context for the graph. Set by caller after construction initially and
      reset for graphs restored from document to point to the restored data context.
      @property   {DG.DataContext}
     */
    dataContext: function( iKey, iValue) {
      var tContext = this.getPath('dataConfiguration.dataContext');
      if( iValue) {
        if( iValue !== tContext) {
          if( tContext){
            tContext.removeObserver('changeCount', this, 'handleDataContextNotification');
          }
          this.setPath('dataConfiguration.dataContext', iValue);
          iValue.addObserver('changeCount', this, 'handleDataContextNotification');
        }
        return this;
      }
      else if( tContext && !tContext.hasObserverFor('changeCount', this)) {
        tContext.addObserver('changeCount', this, 'handleDataContextNotification');
      }
      return this.getPath('dataConfiguration.dataContext');
    }.property(),  // Todo: Figure out if this can be cacheable

    _dataContextDidChange: function() {
      this.notifyPropertyChange('dataContext');
    }.observes('*dataConfiguration.dataContext'),

    /**
      Called when the 'dataContext' property is changed.
     */
    dataContextDidChange: function() {
      var tContext = this.get('dataConfiguration.dataContext');
      if( tContext && !tContext.hasObserverFor('changeCount'))
        tContext.addObserver('changeCount', this, 'handleDataContextNotification');
    }.observes('dataContext'),

    childmostCollectionTitle: function() {
      return this.getPath('dataConfiguration.childmostCollection.title');
    }.property(),

    /**
      Delete the currently selected cases.
      Passes the request on to the data context to do the heavy lifting.
     */
    deleteSelectedCases: function() {
      var tContext = this.get('dataContext'),
          tSelectedCases = this.get('selection'),
          tChange;
      if( tContext) {
        tChange = {
          operation: 'selectCases',
          select: false,
          cases: tSelectedCases
        };
        tContext.applyChange( tChange);
        tChange = {
          operation: 'deleteCases',
          cases: tSelectedCases
        };
        tContext.applyChange( tChange);
      }
    },

    /**
      Delete the currently unselected cases.
      Passes the request on to the data context to do the heavy lifting.
     */
    deleteUnselectedCases: function(){
      var tCases = this.getPath('dataConfiguration.cases');
      var tUnselected = DG.ArrayUtils.subtract( tCases, this.get('selection'),
                                                            function( iCase) {
                                                              return iCase.get('id');
                                                            });
      var tChange = {
            operation: 'deleteCases',
            cases: DG.copy(tUnselected)
          };
      this.get('dataContext').applyChange( tChange);
    },

    /**
      Select/deselect all of the points in all the plots.
      @param  {Boolean}   iSelect -- True to select all points, false to deselect all.
                                      Defaults to true (select all) if undefined/null.
     */
    selectAll: function( iSelect) {
      var tSelect = SC.none( iSelect) ? true : !!iSelect,
          tCases = tSelect ? this.get('cases') : null,  // null means all cases, even hidden ones
          tContext = this.get('dataContext'),
          tChange = {
            operation: 'selectCases',
            collection: this.get('collectionClient'),
            cases: tCases,
            select: tSelect
          };
      if (tContext) {
        tContext.applyChange( tChange);
      }
      DG.logUser( iSelect ? "selectAll" : "deselectAll");
    },

    /**
     * Utility function for use by subclasses.
     * @param iStorage
     * @param iCollLinkName
     * @param iAttrLinkName
     * @returns {*}
     */
    instantiateAttributeRefFromStorage: function( iStorage, iCollLinkName, iAttrLinkName) {
      var kNullResult = { collection: null, attributes: [] },
          tDataContext = this.getPath('dataConfiguration.dataContext');
      if( SC.empty( iCollLinkName) || SC.empty( iAttrLinkName) || !iStorage || !iStorage._links_)
        return kNullResult;

      var collLink = iStorage._links_[ iCollLinkName],
          coll = collLink && collLink.id && tDataContext.getCollectionByID( collLink.id),
          attrs = [],
          tLinkCount = DG.ArchiveUtils.getLinkCount( iStorage, iAttrLinkName ),
          tIndex;
      if( !coll)
        return kNullResult;

      for( tIndex = 0; tIndex < tLinkCount; tIndex++) {
        var tAttr = coll.getAttributeByID( DG.ArchiveUtils.getLinkID( iStorage, iAttrLinkName, tIndex));
        if( tAttr)
          attrs.push(tAttr);
      }
      return { collection: coll, attributes: attrs };
    },

    /**
     * Use the properties of the given object to restore my hidden cases.
     * Subclasses can override but should call sc_super.
     * @param iStorage {Object}
     */
    restoreStorage: function( iStorage) {
      // CODAP builds prior to 0289 stored hidden cases not as links, but as simple case IDs.
      // More recent builds store links, which we now convert on restore.
      var tHiddenCasesLinks = iStorage._links_ && iStorage._links_.hiddenCases;
      if( SC.isArray( tHiddenCasesLinks)) {
        var tLinkCount = DG.ArchiveUtils.getLinkCount( iStorage, 'hiddenCases'),
            tIndex;
        iStorage.hiddenCases = [];
        for( tIndex = 0; tIndex < tLinkCount; tIndex++) {
          iStorage.hiddenCases.push( DG.ArchiveUtils.getLinkID( iStorage, 'hiddenCases', tIndex));
        }
      }
      this.get('dataConfiguration').restoreHiddenCases( iStorage.hiddenCases);
      this.setPath('dataConfiguration.displayOnlySelected', iStorage.displayOnlySelected);

      if( !SC.none( iStorage.pointColor))
        this.set('pointColor', iStorage.pointColor);
      if( !SC.none( iStorage.strokeColor))
        this.set('strokeColor', iStorage.strokeColor);
      if( !SC.none( iStorage.pointSizeMultiplier))
        this.set('pointSizeMultiplier', iStorage.pointSizeMultiplier);
      if( !SC.none( iStorage.transparency))
        this.set('transparency', iStorage.transparency);
      if( !SC.none( iStorage.strokeTransparency))
        this.set('strokeTransparency', iStorage.strokeTransparency);
      if( !SC.none( iStorage.strokeSameAsFill))
        this.set('strokeSameAsFill', iStorage.strokeSameAsFill);
    },

    handleOneDataContextChange: function( iNotifier, iChange) {
      var tOperation = iChange && iChange.operation;

      switch( tOperation) {
        case 'deleteAttributes':
          iChange.attrs.forEach(function (iAttr) {
            iAttr = iAttr.attribute || iAttr; // We get here with two forms. Cover both.
            ['x', 'y', 'legend', 'y2', 'area'].forEach(function (iKey) {
              var tDescKey = iKey + 'AttributeDescription',
                  tAxisKey = iKey + 'Axis',
                  tAttrs = this.getPath('dataConfiguration.' + tDescKey + '.attributes');
              if(tAttrs) {
                tAttrs.forEach(function (iPlottedAttr, iIndex) {
                  if (iPlottedAttr === iAttr) {
                    if (iKey === 'legend')
                      this.removeLegendAttribute();
                    else
                      this.removeAttribute(tDescKey, tAxisKey, iIndex);
                  }
                }.bind(this));
              }
            }.bind(this));
          }.bind( this));
          break;
        case 'deleteCollection':
          this.dataContextOrCollectionWasDeleted(iChange.collection); // jshint ignore:line
          // fallthrough deliberate
        case 'updateAttributes':
          this.handleUpdateAttributes( iChange);
          break;
        case 'createCollection':
          this.notifyPropertyChange('caseOrder');
          break;
        case 'deleteDataContext':
          this.reset();
          this.dataContextOrCollectionWasDeleted();
          break;
        default:
          // Nothing to do
      }
      // Give the legend a chance
      var tLegend = this.get('legend');
      if( tLegend)
          tLegend.handleOneDataContextChange( iNotifier, iChange);
    },

    dataContextOrCollectionWasDeleted: function ( iCollection) {
      DG.log('dataContextWasDeleted');
      ['x', 'y', 'legend', 'y2', 'area'].forEach(function (iKey) {
        var tDescKey = iKey + 'AttributeDescription',
            tAxisKey = iKey + 'Axis',
            tCollectionClient = this.getPath('dataConfiguration.'
                + tDescKey + '.collectionClient'),
            tAttrs = this.getPath('dataConfiguration.' + tDescKey + '.attributes');
        if (tCollectionClient && tAttrs) {
          if (!iCollection || tCollectionClient === iCollection) {
            tAttrs.forEach(function (iPlottedAttr, iIndex) {
              if (iKey === 'legend')
                this.removeLegendAttribute();
              else
                this.removeAttribute(tDescKey, tAxisKey, iIndex);
            }.bind(this));
          }
        }
      }.bind(this));
      var tConfig = this.get('dataConfiguration');
      if(tConfig)
        tConfig.synchHiddenCases();
    },

    /**
     * Subclasses will override
     * @param iChange {Object}
     */
    handleUpdateAttributes: function( iChange) {
    },

    /**
      Returns an array of indices corresponding to the indices
      of the cases affected by the specified change.
     */
    buildIndices: function( iChange) {
      var srcCases = this.getPath('dataConfiguration.cases');
      if( (iChange.operation === 'updateCases') &&
          srcCases && !SC.none( iChange.cases) &&
          !this.getPath('dataConfiguration.hasAggregates')) {
        var updatedCasesByID = {},
            indices = SC.IndexSet.create();
        // Build a map of IDs for affected cases
        iChange.cases.forEach( function( iCase) {
                                updatedCasesByID[ iCase.get('id')] = iCase;
                               });
        // Loop through source cases to determine indices for the affected cases
        srcCases.forEach( function( iCase, iIndex) {
                            var caseID = iCase.get('id');
                            if( updatedCasesByID[ caseID])
                              indices.add( iIndex);
                          });
        return indices;
      }
      return SC.IndexSet.create( 0, this.getPath('dataConfiguration.cases.length'));
    },

    /**
      Responder for notifications from the DataContext.
     */
    handleDataContextNotification: function( iNotifier) {
      var newChanges = iNotifier.get('newChanges' ),
          tNumChanges = newChanges.length,
          i;
      for( i = 0; i < tNumChanges; i++) {
        this.handleOneDataContextChange( iNotifier, newChanges[ i]);
      }
    },

    getModelPointStyleAccessors: function() {
      var this_ = this;
      return {
        getPointColor: this_.getPointColor.bind(this_),
        getStrokeColor: function() {
          return this_.get('strokeSameAsFill') ?  this_.get('pointColor') : this_.get('strokeColor');
        },
        getPointSizeMultiplier: function() {
          return this_.get('pointSizeMultiplier');
        },
        getTransparency: function() {
          return this_.get('transparency');
        },
        getStrokeTransparency: function() {
          return this_.get('strokeSameAsFill') ?  this_.get('transparency') : this_.get('strokeTransparency');
        },
        getStrokeSameAsFill: function() {
          return this_.get('strokeSameAsFill');
        }
      };
    },

    /** create a menu item that removes the attribute on the given axis/legend */
    createRemoveAttributeMenuItem: function( iAxisOrLegendView, iXYorLegend, isForSubmenu, iAttrIndex ) {
      iAttrIndex = iAttrIndex || 0;
      var tDescKey = iXYorLegend + 'AttributeDescription',
          tAxisKey = iXYorLegend + 'Axis', // not used by removeLegendAttribute()
          tAttributes = this.getPath( 'dataConfiguration.' + tDescKey + '.attributes'),
          tAttribute = (SC.isArray( tAttributes) && iAttrIndex < tAttributes.length) ?
              tAttributes[ iAttrIndex] : DG.Analysis.kNullAttribute,
          tName = (tAttribute === DG.Analysis.kNullAttribute) ? '' : tAttribute.get( 'name'),
          tResourceName = isForSubmenu ? 'attribute_' : 'removeAttribute_',
          tTitle = ('DG.DataDisplayMenu.' + tResourceName + iXYorLegend).loc( tName ),
          tAction;
      switch( iXYorLegend) {
        case 'x':
        case 'y':
        case 'y2':
          tAction = this.removeAttribute;
          break;
        case 'legend':
          tAction = this.removeLegendAttribute;
          break;
        case 'top':
        case 'right':
          tAction = this.removeSplitAttribute;
          break;
      }
      return {
        title: tTitle,
        target: this,
        itemAction: tAction,
        isEnabled: (tAttribute !== DG.Analysis.kNullAttribute),
        log: "attributeRemoved: { attribute: %@, axis: %@ }".fmt(tName, iXYorLegend),
        args: [ tDescKey, tAxisKey, iAttrIndex ] };
    },

    /** create a menu item that changes the attribute type on the given axis/legend */
    createChangeAttributeTypeMenuItem: function( iAxisView, iXYorLegend ) {
      var tDescKey = iXYorLegend + 'AttributeDescription',
          tAxisKey = iXYorLegend + 'Axis',
          tDescription = this.getPath( 'dataConfiguration.' + tDescKey),
          tAttribute = tDescription && tDescription.get( 'attribute'),
          tAttributeName = tAttribute && (tAttribute !== -1) ? tAttribute.get('name') : '',
          tIsNumeric = tDescription && tDescription.get( 'isNumeric'),
          tTitle =( tIsNumeric ? 'DG.DataDisplayMenu.treatAsCategorical' : 'DG.DataDisplayMenu.treatAsNumeric').loc();
      return {
        title: tTitle,
        target: this,
        itemAction: this.changeAttributeType, // call with args, toggling 'numeric' setting
        isEnabled: (tAttribute !== DG.Analysis.kNullAttribute),
        log: "plotAxisAttributeChangeType: { axis: %@, attribute: %@, numeric: %@ }".fmt( tAxisKey, tAttributeName, !tIsNumeric),
        args: [ tDescKey, tAxisKey, !tIsNumeric ] };
    },

    /** Submenu items for hiding selected or unselected cases, or showing all cases */
    createHideShowSelectionMenuItems: function() {
      var tSelection = this.getPath('dataConfiguration.selection' ).toArray(),
          tSomethingIsSelected = tSelection && tSelection.get('length') !== 0,
          tCases = this.getPath('dataConfiguration.cases' ),
          tSomethingIsUnselected = tSelection && tCases && (tSelection.get('length') < tCases.get('length')),
          tSomethingHidden = this.getPath('dataConfiguration.hiddenCases' ).length > 0,
          tHideSelectedNumber = (tSelection && tSelection.length > 1) ? 'Plural' : 'Sing',
          tHideUnselectedNumber = (tSelection && tCases &&
              (tCases.get('length') - tSelection.length > 1)) ? 'Plural' : 'Sing',
          tDisplayingOnlySelected = this.getPath('dataConfiguration.displayOnlySelected'),
          self = this;

      function hideSelectedCases() {
        DG.UndoHistory.execute(DG.Command.create({
          name: 'graph.display.hideSelectedCases',
          undoString: 'DG.Undo.hideSelectedCases',
          redoString: 'DG.Redo.hideSelectedCases',
          log: "Hide %@ selected cases".fmt(tSelection.length),
          executeNotification: {
            action: 'notify',
            resource: 'component',
            values: {
              operation: 'hideSelected',
              type: '',
              numberHidden: tSelection.length
            }
          },
          execute: function() {
            this._undoData = tSelection;
            self.get('dataConfiguration' ).hideCases( tSelection );
          },
          undo: function() {
            self.get('dataConfiguration' ).showCases( this._undoData );
          },
          redo: function() {
            self.get('dataConfiguration' ).hideCases( this._undoData );
          }
        }));
      }

      function hideUnselectedCases() {
        var tUnselected = DG.ArrayUtils.subtract( tCases, tSelection,
            function( iCase) {
              return iCase.get('id');
            });
        DG.UndoHistory.execute(DG.Command.create({
          name: 'graph.display.hideUnselectedCases',
          undoString: 'DG.Undo.hideUnselectedCases',
          redoString: 'DG.Redo.hideUnselectedCases',
          log: "Hide unselected cases",
          executeNotification: {
            action: 'notify',
            resource: 'component',
            values: {
              operation: 'hideUnselected',
              type: '',
              numberHidden: tUnselected.length
            }
          },
          execute: function() {
            this._undoData = tUnselected;

            this.log = "Hide %@ unselected cases".fmt(tUnselected.length);
            self.get('dataConfiguration' ).hideCases( tUnselected );
          },
          undo: function() {
            self.get('dataConfiguration' ).showCases( this._undoData );
          },
          redo: function() {
            self.get('dataConfiguration' ).hideCases( this._undoData );
          }
        }));
      }

      function showAllCases() {
        DG.UndoHistory.execute(DG.Command.create({
          name: 'graph.display.showAllCases',
          undoString: 'DG.Undo.showAllCases',
          redoString: 'DG.Redo.showAllCases',
          log: "Show all cases",
          execute: function() {
            self.setPath('dataConfiguration.displayOnlySelected', false );
            this._undoData = self.getPath('dataConfiguration.hiddenCases');
            self.get('dataConfiguration' ).showAllCases();
          },
          undo: function() {
            self.get('dataConfiguration' ).hideCases( this._undoData );
          }
        }));
      }

      function displayOnlySelected() {
        DG.UndoHistory.execute(DG.Command.create({
          name: 'graph.display.displayOnlySelected',
          undoString: 'DG.Undo.displayOnlySelected',
          redoString: 'DG.Redo.displayOnlySelected',
          log: "Display only selected cases",
          execute: function() {
            self.setPath('dataConfiguration.displayOnlySelected', true );
          },
        }));
      }

      return [
        // Note that these 'built' string keys will have to be specially handled by any
        // minifier we use
        { title: ('DG.DataDisplayMenu.hideSelected' + tHideSelectedNumber), isEnabled: tSomethingIsSelected,
          target: this, action: hideSelectedCases },
        { title: ('DG.DataDisplayMenu.hideUnselected' + tHideUnselectedNumber), isEnabled: tSomethingIsUnselected,
          target: this, action: hideUnselectedCases },
        { title: 'DG.DataDisplayMenu.showAll', isEnabled: tSomethingHidden || tDisplayingOnlySelected,
          target: this, action: showAllCases },
        { title: 'DG.DataDisplayMenu.displayOnlySelected', isEnabled: !tDisplayingOnlySelected,
          target: this, action: displayOnlySelected }
      ];
    },

    /**
     * Removing the attribute is just changing with null arguments
     */
    removeLegendAttribute: function() {
      this.changeAttributeForLegend( null, null);
    },

    /**
     * Subclasses will override
     */
    removeSplitAttribute: function() {
    },

    /**
     * Change the attribute type (EAttributeType) on the axis described by the given key,
     * to treat a Numeric attribute as Categorical.
     * @param{String} iDescKey - key to the desired attribute description (x...|y...|legendAttributeDescription)
     * @param{String} iAxisKey - key to the axis whose attribute is to be removed (x...|yAxis)
     * @param{Boolean} true if we want to treat the attribute as numeric (else categorical).
     */
    changeAttributeType: function( iDescKey, iAxisKey, iTreatAsNumeric ) {
      var tDataConfiguration = this.get('dataConfiguration');

      // We're handling a case specific to graphs here for convenience
      if( !iTreatAsNumeric && this.getY2Plot && this.getY2Plot()) {
        this.removeAttribute('y2AttributeDescription', 'y2Axis', 0);
      }

      this.set('aboutToChangeConfiguration', true ); // signals dependents to prepare

      tDataConfiguration.setAttributeType( iDescKey, iTreatAsNumeric );

      this.invalidate( null, true /* also invalidate plot caches */);
      this.set('aboutToChangeConfiguration', false ); // reset for next time
    },

    /**
     Sets the attribute for the legend.
     @param  {DG.DataContext}      iDataContext -- The data context for this graph
     @param  {Object}              iAttrRefs -- The attribute to set for the axis
     {DG.CollectionClient} iAttrRefs.collection -- The collection that contains the attribute
     {DG.Attribute}        iAttrRefs.attribute -- Array of attributes to set for the legend
     */
    changeAttributeForLegend: function( iDataContext, iAttrRefs) {

      function newAttributeCollectionIsDescendant() {

        function isDescendantOf(iColl1, iColl2) {
          // Is iColl1 a descendant of iColl2
          var tChildren = iColl2 && iColl2.get('children'),
              found = false;
          while (!found && tChildren) {
            var tChild = tChildren.length >= 0 && tChildren[0];
            if (tChild === iColl1)
              found = true;
            else tChildren = tChild && tChild.get('children');
          }
          return found;
        }

        if( !iAttrRefs)
          return false; // Since we didn't get an attribute, its collection is not a descendant

        // iAttrRefs.collection is actually a CollectionClient
        var tNewCollection = iAttrRefs.collection.get('collection'),
            tXCollection = dataConfiguration.getPath('xAttributeDescription.collectionClient.collection'),
            tYCollection = dataConfiguration.getPath('yAttributeDescription.collectionClient.collection'),
            tPolygonCollection = dataConfiguration.getPath('polygonAttributeDescription.collectionClient.collection'),
            tChildMost;
        if(tPolygonCollection)
          tChildMost = tPolygonCollection;
        else if( tXCollection && tYCollection){
          tChildMost = isDescendantOf(tXCollection, tYCollection) ? tXCollection : tYCollection;
        }
        else {
          tChildMost = tXCollection || tYCollection;
        }
        return isDescendantOf(tNewCollection, tChildMost);
      }

      var dataConfiguration = this.get('dataConfiguration');

      if( newAttributeCollectionIsDescendant())
        return; // Because legend attribute has to be at same level as or higher than existing data attributes

      this.set('aboutToChangeConfiguration', true ); // signals dependents to prepare

      if( iDataContext)
        dataConfiguration.set('dataContext', iDataContext);
      dataConfiguration.setAttributeAndCollectionClient('legendAttributeDescription', iAttrRefs);
      this.invalidate();
      this.set('aboutToChangeConfiguration', false ); // reset for next time
    },

    /**
     @private
     */
    dataRangeDidChange: function( iSource, iKey, iObject, iIndices) {
      this.invalidate();
    },

    /**
     *
     * @param iChange
     * @param iInvalidateDisplayCaches {Boolean}
     */
    invalidate: function( iChange, iInvalidateDisplayCaches) {
      this.get( 'dataConfiguration' ).invalidateCaches( null, iChange);
    }

  } );


text:
import minima from './_sass/main.scss';
import headerCSS from './_sass/header.scss';
import blogCSS from './_sass/blog.scss';
import contentCSS from './_sass/content.scss';
import footerCSS from './_sass/footer.scss';
import reposCSS from './_sass/repos.scss';
import servicesCSS from './_sass/services.scss';

redpajama_set_name: RedPajamaGithub


text:
DEFINE_int32(num_operations, 10*1000, "Number of operations to perform");
DEFINE_int32(num_threads, 2, "Number of worker threads");

namespace kudu {

// Test some basic operations
TEST(Striped64Test, TestBasic) {
  LongAdder adder;
  ASSERT_EQ(adder.Value(), 0);
  adder.IncrementBy(100);
  ASSERT_EQ(adder.Value(), 100);
  adder.Increment();
  ASSERT_EQ(adder.Value(), 101);
  adder.Decrement();
  ASSERT_EQ(adder.Value(), 100);
  adder.IncrementBy(-200);
  ASSERT_EQ(adder.Value(), -100);
  adder.Reset();
  ASSERT_EQ(adder.Value(), 0);
}

template <class Adder>
class MultiThreadTest {
 public:
  typedef std::vector<scoped_refptr<Thread> > thread_vec_t;

  MultiThreadTest(int64_t num_operations, int64_t num_threads)
   :  num_operations_(num_operations),
      num_threads_(num_threads) {
  }

  void IncrementerThread(const int64_t num) {
    for (int i = 0; i < num; i++) {
      adder_.Increment();
    }
  }

  void DecrementerThread(const int64_t num) {
    for (int i = 0; i < num; i++) {
      adder_.Decrement();
    }
  }

  void Run() {
    // Increment
    for (int i = 0; i < num_threads_; i++) {
      scoped_refptr<Thread> ref;
      Thread::Create("Striped64", "Incrementer", &MultiThreadTest::IncrementerThread, this,
                     num_operations_, &ref);
      threads_.push_back(ref);
    }
    for (const scoped_refptr<Thread> &t : threads_) {
      t->Join();
    }
    ASSERT_EQ(num_threads_*num_operations_, adder_.Value());
    threads_.clear();

    // Decrement back to zero
    for (int i = 0; i < num_threads_; i++) {
      scoped_refptr<Thread> ref;
      Thread::Create("Striped64", "Decrementer", &MultiThreadTest::DecrementerThread, this,
                     num_operations_, &ref);
      threads_.push_back(ref);
    }
    for (const scoped_refptr<Thread> &t : threads_) {
      t->Join();
    }
    ASSERT_EQ(0, adder_.Value());
  }

  Adder adder_;

  int64_t num_operations_;
  // This is rounded down to the nearest even number
  int32_t num_threads_;
  thread_vec_t threads_;
};

// Test adder implemented by a single AtomicInt for comparison
class BasicAdder {
 public:
  BasicAdder() : value_(0) {}
  void IncrementBy(int64_t x) { value_.IncrementBy(x); }
  inline void Increment() { IncrementBy(1); }
  inline void Decrement() { IncrementBy(-1); }
  int64_t Value() { return value_.Load(); }
 private:
  AtomicInt<int64_t> value_;
};

void RunMultiTest(int64_t num_operations, int64_t num_threads) {
  MonoTime start = MonoTime::Now();
  MultiThreadTest<BasicAdder> basicTest(num_operations, num_threads);
  basicTest.Run();
  MonoTime end1 = MonoTime::Now();
  MultiThreadTest<LongAdder> test(num_operations, num_threads);
  test.Run();
  MonoTime end2 = MonoTime::Now();
  MonoDelta basic = end1 - start;
  MonoDelta striped = end2 - end1;
  LOG(INFO) << "Basic counter took   " << basic.ToMilliseconds() << "ms.";
  LOG(INFO) << "Striped counter took " << striped.ToMilliseconds() << "ms.";
}

// Compare a single-thread workload. Demonstrates the overhead of LongAdder over AtomicInt.
TEST(Striped64Test, TestSingleIncrDecr) {
  OverrideFlagForSlowTests(
      "num_operations",
      strings::Substitute("$0", (FLAGS_num_operations * 100)));
  RunMultiTest(FLAGS_num_operations, 1);
}

// Compare a multi-threaded workload. LongAdder should show improvements here.
TEST(Striped64Test, TestMultiIncrDecr) {
  OverrideFlagForSlowTests(
      "num_operations",
      strings::Substitute("$0", (FLAGS_num_operations * 100)));
  OverrideFlagForSlowTests(
      "num_threads",
      strings::Substitute("$0", (FLAGS_num_threads * 4)));
  RunMultiTest(FLAGS_num_operations, FLAGS_num_threads);
}

TEST(Striped64Test, TestSize) {
  ASSERT_EQ(16, sizeof(LongAdder));
}

}  // namespace kudu


text:
<?php

namespace PHPixie\BundleFramework;

abstract class Builder extends \PHPixie\Framework\Builder
{
    /**
     * Framework configuration
     * @return Configuration
     */
    public function configuration()
    {
        return $this->instance('configuration');
    }

    /**
     * Bundle registry
     * @return Bundles
     */
    public function bundles()
    {
        return $this->instance('bundles');
    }

    /**
     * Assets
     * @return Assets
     */
    public function assets()
    {
        return parent::assets();
    }

    /**
     * Framework components
     * @return Components
     */
    public function components()
    {
        return parent::components();
    }

    /**
     * Framework components
     * @return Components
     */
    protected function buildComponents()
    {
        return new Components($this);
    }

    /**
     * @return Assets
     */
    protected function buildAssets()
    {
        return new Assets(
            $this->components(),
            $this->getRootDirectory()
        );
    }

    /**
     * @return Configuration
     */
    protected function buildConfiguration()
    {
        return new Configuration($this);
    }

    /**
     * Build project bundles registry
     * @return Bundles
     */
    abstract protected function buildBundles();

    /**
     * Project root directory
     * @return string
     */
    abstract protected function getRootDirectory();
}


text:
// Copyright (c) 2012 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.

#ifndef MEDIA_FILTERS_GPU_VIDEO_DECODER_H_
#define MEDIA_FILTERS_GPU_VIDEO_DECODER_H_

#include <stddef.h>
#include <stdint.h>

#include <list>
#include <map>
#include <set>
#include <utility>
#include <vector>

#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "media/base/pipeline_status.h"
#include "media/base/video_decoder.h"
#include "media/video/video_decode_accelerator.h"

template <class T> class scoped_refptr;

namespace base {
class SharedMemory;
class SingleThreadTaskRunner;
}

namespace gpu {
struct SyncToken;
}

namespace media {

class DecoderBuffer;
class GpuVideoAcceleratorFactories;
class MediaLog;

// GPU-accelerated video decoder implementation.  Relies on
// AcceleratedVideoDecoderMsg_Decode and friends.  Can be created on any thread
// but must be accessed and destroyed on GpuVideoAcceleratorFactories's
// GetMessageLoop().
class MEDIA_EXPORT GpuVideoDecoder
    : public VideoDecoder,
      public VideoDecodeAccelerator::Client {
 public:
  explicit GpuVideoDecoder(GpuVideoAcceleratorFactories* factories);

  // VideoDecoder implementation.
  std::string GetDisplayName() const override;
  void Initialize(const VideoDecoderConfig& config,
                  bool low_delay,
                  const SetCdmReadyCB& set_cdm_ready_cb,
                  const InitCB& init_cb,
                  const OutputCB& output_cb) override;
  void Decode(const scoped_refptr<DecoderBuffer>& buffer,
              const DecodeCB& decode_cb) override;
  void Reset(const base::Closure& closure) override;
  bool NeedsBitstreamConversion() const override;
  bool CanReadWithoutStalling() const override;
  int GetMaxDecodeRequests() const override;

  // VideoDecodeAccelerator::Client implementation.
  void NotifyCdmAttached(bool success) override;
  void ProvidePictureBuffers(uint32_t count,
                             const gfx::Size& size,
                             uint32_t texture_target) override;
  void DismissPictureBuffer(int32_t id) override;
  void PictureReady(const media::Picture& picture) override;
  void NotifyEndOfBitstreamBuffer(int32_t id) override;
  void NotifyFlushDone() override;
  void NotifyResetDone() override;
  void NotifyError(media::VideoDecodeAccelerator::Error error) override;

  static const char kDecoderName[];

 protected:
  ~GpuVideoDecoder() override;

 private:
  enum State {
    kNormal,
    kDrainingDecoder,
    kDecoderDrained,
    kError
  };

  // A shared memory segment and its allocated size.
  struct SHMBuffer {
    SHMBuffer(scoped_ptr<base::SharedMemory> m, size_t s);
    ~SHMBuffer();
    scoped_ptr<base::SharedMemory> shm;
    size_t size;
  };

  // A SHMBuffer and the DecoderBuffer its data came from.
  struct PendingDecoderBuffer {
    PendingDecoderBuffer(SHMBuffer* s,
                        const scoped_refptr<DecoderBuffer>& b,
                        const DecodeCB& done_cb);
    ~PendingDecoderBuffer();
    SHMBuffer* shm_buffer;
    scoped_refptr<DecoderBuffer> buffer;
    DecodeCB done_cb;
  };

  typedef std::map<int32_t, PictureBuffer> PictureBufferMap;

  // Callback to set CDM. |cdm_attached_cb| is called when the decryptor in the
  // CDM has been completely attached to the pipeline.
  void SetCdm(CdmContext* cdm_context, const CdmAttachedCB& cdm_attached_cb);

  void DeliverFrame(const scoped_refptr<VideoFrame>& frame);

  // Static method is to allow it to run even after GVD is deleted.
  static void ReleaseMailbox(base::WeakPtr<GpuVideoDecoder> decoder,
                             media::GpuVideoAcceleratorFactories* factories,
                             int64_t picture_buffer_id,
                             uint32_t texture_id,
                             const gpu::SyncToken& release_sync_token);
  // Indicate the picture buffer can be reused by the decoder.
  void ReusePictureBuffer(int64_t picture_buffer_id);

  void RecordBufferData(
      const BitstreamBuffer& bitstream_buffer, const DecoderBuffer& buffer);
  void GetBufferData(int32_t id,
                     base::TimeDelta* timetamp,
                     gfx::Rect* visible_rect,
                     gfx::Size* natural_size);

  void DestroyVDA();

  // Request a shared-memory segment of at least |min_size| bytes.  Will
  // allocate as necessary.
  scoped_ptr<SHMBuffer> GetSHM(size_t min_size);

  // Return a shared-memory segment to the available pool.
  void PutSHM(scoped_ptr<SHMBuffer> shm_buffer);

  // Destroy all PictureBuffers in |buffers|, and delete their textures.
  void DestroyPictureBuffers(PictureBufferMap* buffers);

  // Returns true if the video decoder with |capabilities| can support
  // |profile| and |coded_size|.
  bool IsProfileSupported(
      const VideoDecodeAccelerator::Capabilities& capabilities,
      VideoCodecProfile profile,
      const gfx::Size& coded_size);

  // Assert the contract that this class is operated on the right thread.
  void DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent() const;

  bool needs_bitstream_conversion_;

  GpuVideoAcceleratorFactories* factories_;

  // Populated during Initialize() (on success) and unchanged until an error
  // occurs.
  scoped_ptr<VideoDecodeAccelerator> vda_;

  InitCB init_cb_;
  OutputCB output_cb_;

  DecodeCB eos_decode_cb_;

  // Not null only during reset.
  base::Closure pending_reset_cb_;

  State state_;

  VideoDecoderConfig config_;

  // Callback to request/cancel CDM ready notification.
  SetCdmReadyCB set_cdm_ready_cb_;
  CdmAttachedCB cdm_attached_cb_;

  // Shared-memory buffer pool.  Since allocating SHM segments requires a
  // round-trip to the browser process, we keep allocation out of the
  // steady-state of the decoder.
  std::vector<SHMBuffer*> available_shm_segments_;

  std::map<int32_t, PendingDecoderBuffer> bitstream_buffers_in_decoder_;
  PictureBufferMap assigned_picture_buffers_;
  // PictureBuffers given to us by VDA via PictureReady, which we sent forward
  // as VideoFrames to be rendered via decode_cb_, and which will be returned
  // to us via ReusePictureBuffer.
  typedef std::map<int32_t /* picture_buffer_id */, uint32_t /* texture_id */>
      PictureBufferTextureMap;
  PictureBufferTextureMap picture_buffers_at_display_;

  // The texture target used for decoded pictures.
  uint32_t decoder_texture_target_;

  struct BufferData {
    BufferData(int32_t bbid,
               base::TimeDelta ts,
               const gfx::Rect& visible_rect,
               const gfx::Size& natural_size);
    ~BufferData();
    int32_t bitstream_buffer_id;
    base::TimeDelta timestamp;
    gfx::Rect visible_rect;
    gfx::Size natural_size;
  };
  std::list<BufferData> input_buffer_data_;

  // picture_buffer_id and the frame wrapping the corresponding Picture, for
  // frames that have been decoded but haven't been requested by a Decode() yet.
  int32_t next_picture_buffer_id_;
  int32_t next_bitstream_buffer_id_;

  // Set during ProvidePictureBuffers(), used for checking and implementing
  // HasAvailableOutputFrames().
  int available_pictures_;

  // If true, the client cannot expect the VDA to produce any new decoded
  // frames, until it returns all PictureBuffers it may be holding back to the
  // VDA. In other words, the VDA may require all PictureBuffers to be able to
  // proceed with decoding the next frame.
  bool needs_all_picture_buffers_to_decode_;

  // Bound to factories_->GetMessageLoop().
  // NOTE: Weak pointers must be invalidated before all other member variables.
  base::WeakPtrFactory<GpuVideoDecoder> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(GpuVideoDecoder);
};

}  // namespace media

#endif  // MEDIA_FILTERS_GPU_VIDEO_DECODER_H_


text:
package auctionCapability.planschemes;

import oo2apl.agent.AgentContextInterface;
import oo2apl.agent.PlanToAgentInterface;
import oo2apl.agent.Trigger;
import auctionCapability.BuyerContext;
import auctionCapability.triggers.AuctionAnnouncement;
import auctionCapability.triggers.ParticipantResponse;
import oo2apl.plan.builtin.FunctionalPlanSchemeInterface;
import oo2apl.plan.builtin.SubPlanInterface;
/**
 * This plan scheme handles for participants of an auction the announcement of the auction.
 *
 * @author Bas Testerink
 *
 */
public final class HandleAuctionAnnouncement implements FunctionalPlanSchemeInterface {
	public SubPlanInterface getPlan(final Trigger trigger, final AgentContextInterface contextInterface) {
		if(trigger instanceof AuctionAnnouncement<?>){
			AuctionAnnouncement<?> announcement = (AuctionAnnouncement<?>) trigger;
			return (PlanToAgentInterface planInterface) -> {
				// Get the context for decision making
				BuyerContext context = planInterface.getContext(BuyerContext.class);

				// Get the (initial) bid
				ParticipantResponse participantResponse = context.registerAuction(announcement, planInterface.getAgentID());

				// Send the bid
				planInterface.sendMessage(announcement.getAuctioneer(), participantResponse);
			};
		}
		return SubPlanInterface.UNINSTANTIATED;
	}
}


text:
'use strict';
import Vue from 'vue'
import {
    Menu,
    Submenu,
    MenuItem,
    Table,
    TableColumn,
    Tabs,
    TabPane,
    Progress,
    Popover,
    Tooltip
} from 'element-ui'
import Vue2Filters from 'vue2-filters'
import Notifications from 'vue-notification'
export default class Config {
    constructor(option) {
        var defaults = {
            app_mode: "normal",
            base_url: '/',
            ajax_url: "http://localhost:9090/api",
            ajax_timeout: 15000,
            ajax_after_delay: 1,
            init_view: "dashboard-view",
            dash_interval: 10,
            status_interval: 5
        };
        Chart.defaults.global.layout.padding.top = 10;
        Chart.defaults.global.legend.position = "bottom";
        Chart.defaults.global.legend.labels.boxWidth = 10;
        Chart.defaults.global.legend.labels.fontSize = 11;
        Chart.defaults.global.tooltips.intersect = false;
        Chart.defaults.global.responsive = true;
        Chart.defaults.global.maintainAspectRatio = true;
        // Chart.defaults.global.layout.padding.top = 10;
        //  = {
        //     responsive: true,
        //     maintainAspectRatio: false,
        //     legend: {
        //         position: "bottom"
        //     },
        //     layout: {
        //         padding: {
        //             top: 10
        //         }
        //     }
        // };
        log.setDefaultLevel("debug");
        log.warn("DEBUG MODE");
        //log.disableAll()`
        this.setting = _.extend(defaults, option);
        this.configVue();
        this.configAjax();
        this.configRoute();
        this.configAlert();
    }
    // registerComponents(Vue) {
    //     for (let component in components) {
    //         let definition = components[component];
    //         Vue.component(component, definition);
    //     }
    // }
    // registerDirectives(Vue) {
    //     for (let directive in directives) {
    //         let definition = directives[directive];
    //         Vue.directive(directive, definition);
    //     }
    // }
    configVue() {
        Vue.use(Vue2Filters);
        Vue.use(Notifications);
        /* element-ui */
        Vue.use(Menu);
        Vue.use(Submenu);
        Vue.use(MenuItem);
        Vue.use(Table);
        Vue.use(TableColumn);
        Vue.use(Tabs);
        Vue.use(TabPane);
        Vue.use(Progress);
        Vue.use(Popover);
        Vue.use(Tooltip);
        //Vue.prototype.$http = Axios
        //Vue.config.devtools = false;
        //Vue.config.silent = true;
        // component //
        Vue.component('n-loading', require('element/component/core/NLoading.vue'));
        Vue.component('n-view', require('element/component/core/NView.vue'));
        Vue.component('n-panel', require('element/component/core/NPanel.vue'));
        Vue.component('n-popup', require('element/component/core/NPopup.vue'));
        Vue.component('n-input', require('element/component/core/NInput.vue'));
        Vue.component('n-check', require('element/component/core/NCheck.vue'));
        Vue.component('n-radio', require('element/component/core/NRadio.vue'));
        Vue.component('n-toggle', require('element/component/core/NToggle.vue'));
        Vue.component('n-rating', require('element/component/core/NRating.vue'));
        Vue.component('n-select', require('element/component/core/NSelect.vue'));
        Vue.component('n-date', require('element/component/core/NDate.vue'));
        Vue.component('n-tree', require('element/component/core/NTree.vue'));
        Vue.component('n-map', require('element/component/core/NMap.vue'));
        Vue.component('n-upload', require('element/component/core/NUpload.vue'));
        Vue.component('n-progress', require('element/component/core/NProgress.vue'));
        Vue.component('n-date-box', require('element/component/core/NDateBox.vue'));
        Vue.component('n-paging-box', require('element/component/core/NPagingBox.vue'));
        Vue.component('n-data-table', require('element/component/core/NDataTable.vue'));
        Vue.component('n-data-table-panel', require('element/component/core/NDataTablePanel.vue'));
        Vue.component('search-box', require('element/component/SearchBox.vue'));
        Vue.component('config-box', require('element/component/ConfigBox.vue'));
        Vue.component('policy-box', require('element/component/PolicyBox.vue'));
        // renderer //
        Vue.component('button-render', require('element/component/render/ButtonRender.vue'));
        Vue.component('indicator-render', require('element/component/render/IndicatorRender.vue'));
        Vue.component('color-render', require('element/component/render/ColorRender.vue'));
        Vue.component('icon-render', require('element/component/render/IconRender.vue'));
        Vue.component('label-render', require('element/component/render/LabelRender.vue'));
        Vue.component('server-render', require('element/component/render/ServerRender.vue'));
        Vue.component('detail-render', require('element/component/render/DetailRender.vue'));
        Vue.config.warnHandler = function (err, vm, info) {
            if(info.indexOf("Avoid mutating") == -1) {}
        }
        // Vue.config.errorHandler = function(err, vm, info) {
        //     if(info.indexOf("created hook") == -1) {
        //         log.error(err);
        //     }
        // }
        // Vue.material.registerTheme({
        //     default: {
        //         primary: '#106cc8'
        //     }
        // })
    }
    // configValidate() {
    //     var myTest = {
    //         expects = [
    //             'startsWith',
    //             'endsWith'
    //         ],
    //         message = '{title} must start with {startswith} and end with {endsWith}.
    //         validate = function (value, pars) {
    //             return value.startsWith(pars.startsWith) && value.endsWith(pars.endsWith);
    //         }
    //     };
    //     approve.addTest(myTest, 'myTest');
    // }
    configAjax() {
        var me = this;
        axios.defaults.baseURL = this.setting.ajax_url;
        axios.defaults.timeout = this.setting.ajax_timeout;
        // 저장된 쿠키값 가지고 전송
        axios.defaults.withCredentials = true;
        //axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
        axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
        // axios.defaults.paramsSerializer = function(params) {
        //     log.warn("paramsSerializer");
        //     if(params instanceof FormData) {
        //         return params;
        //     }
        //     params = qs.stringify(params, {
        //         // parseArrays: true
        //         // arrayFormat: 'brackets'
        //     });
        //     return params;
        // };
        // axios.defaults.transformRequest = [function(params) {
        //     log.warn("transformRequest");
        //     if(params instanceof FormData) {
        //         return params;
        //     }
        //     params = qs.stringify(params, {
        //         // parseArrays: true
        //         // arrayFormat: 'brackets'
        //     });
        //     return params;
        // }];
        axios.interceptors.request.use(function (config) {
            log.warn("start : " + config.url);
            if(config.data) {
                log.warn(config.data);
            }
            var dash_skip = me.getIsDashSkip(config.url);
            // 상태바 데이터 업데이트 경우에는 SKIP
            var url = String(config.url);
            if(url.indexOf("getStatus") != -1 || url.indexOf("getPolicyProcess") != -1 || dash_skip) {} else {
                app.store.busy = true;
                me.beforeAjax();
            }
            return config;
        }, function (error) {
            return Promise.reject(error);
        });
        axios.interceptors.response.use(function (response) {
            var dash_skip = me.getIsDashSkip(response.config.url);
            log.warn("end : " + response.config.url);
            var url = String(response.config.url);
            if(url.indexOf("getStatus") != -1 || url.indexOf("getPolicyProcess") != -1 || dash_skip) {} else {
                app.store.busy = false;
                me.afterAjax();
            }
            return response;
        }, function (error) {
            log.warn("error : " + error);
            app.store.busy = false;
            me.afterAjax(0);
            return me.handleAjaxError(error);
        });
    }
    getIsDashSkip(url) {
        var dash_skip = false;
        if(app.view.current_view_id == "dashboard-view" && url.indexOf("getDashboardData") != -1) {
            if(app.view.current_view.isFirst == false) {
                dash_skip = true;
            }
        }
        return dash_skip;
    }
    beforeAjax() {
        log.warn("show loading");
        //Pace.start();
        app.$loading.show();
    }
    afterAjax($delay) {
        log.warn("hide loading");
        //Pace.stop();
        var delay = $delay || this.setting.ajax_after_delay;
        delay = delay * 1000;
        _.delay(() => {
            app.$loading.hide();
        }, delay);
    }
    handleAjaxError(error) {
        if(error.response && error.response.status == 401) {
            app.alert("에러", "세션이 종료되었습니다.");
            _.delay(() => {
                location.reload(true);
            }, 3000);
        } else {
            if(error.message.indexOf("Network Error") != -1 || error.message.indexOf("409") != -1) {
                app.alert("에러", "서버에 접속할 수 없습니다.<br>" + error.message);
            } else {
                app.alert("에러", error.message);
            }
        }
        return Promise.reject(error);
    }
    configRoute() {
        if(window.location.port === '') { // if production
            page.base(this.setting.base_url.replace(/\/$/, ''));
        } else {
            page.base(this.setting.base_url);
        }
        page(this.setting.base_url, () => {});
        page('*', (url) => {
            //e.preventDefault();
            var path = _.replace(url.path, "/", "");
            page.redirect("/");
            try {
                var view = app.view.createView(path);
                app.$content.appendChild(view.$el);
            } catch(ex) {
                page.redirect("/");
            }
            // app.alert("에러", "잘못된 경로입니다.");
            // TweenLite.delayedCall(0.5, function() {
            //     page.redirect(app.base_url);
            // });
        });
        // add #! before urls
        page({
            hashbang: true
        });
        // function loadData(ctx, next) {
        // 	var id = ctx.params.id
        // 	$.getJSON('/user/' + id + '.json', function(user) {
        // 		ctx.user = user;
        // 		next();
        // 	});
        // }
    }
    configAlert() {
        alertify.dialog('alert').set({
            label: '확인',
            transition: 'fade',
            title: "에러",
            movable: false,
            closable: true,
            modal: true
        });
        alertify.dialog('confirm').set({
            labels: {
                ok: '확인',
                cancel: '취소'
            },
            transition: 'fade',
            title: "에러",
            movable: false,
            closable: true,
            modal: true
        });
    }
}


text:
/**
 * @file
 *   This file implements the PAN ID Query Client.
 */

#include "panid_query_client.hpp"

#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/instance.hpp"
#include "common/locator-getters.hpp"
#include "common/logging.hpp"
#include "meshcop/meshcop.hpp"
#include "meshcop/meshcop_tlvs.hpp"
#include "thread/thread_netif.hpp"
#include "thread/uri_paths.hpp"

#if OPENTHREAD_CONFIG_COMMISSIONER_ENABLE && OPENTHREAD_FTD

namespace ot {

PanIdQueryClient::PanIdQueryClient(Instance &aInstance)
    : InstanceLocator(aInstance)
    , mCallback(nullptr)
    , mContext(nullptr)
    , mPanIdQuery(UriPath::kPanIdConflict, &PanIdQueryClient::HandleConflict, this)
{
    Get<Tmf::TmfAgent>().AddResource(mPanIdQuery);
}

otError PanIdQueryClient::SendQuery(uint16_t                            aPanId,
                                    uint32_t                            aChannelMask,
                                    const Ip6::Address &                aAddress,
                                    otCommissionerPanIdConflictCallback aCallback,
                                    void *                              aContext)
{
    otError                 error = OT_ERROR_NONE;
    MeshCoP::ChannelMaskTlv channelMask;
    Ip6::MessageInfo        messageInfo;
    Coap::Message *         message = nullptr;

    VerifyOrExit(Get<MeshCoP::Commissioner>().IsActive(), error = OT_ERROR_INVALID_STATE);
    VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get<Tmf::TmfAgent>())) != nullptr, error = OT_ERROR_NO_BUFS);

    SuccessOrExit(error = message->InitAsPost(aAddress, UriPath::kPanIdQuery));
    SuccessOrExit(error = message->SetPayloadMarker());

    SuccessOrExit(
        error = Tlv::Append<MeshCoP::CommissionerSessionIdTlv>(*message, Get<MeshCoP::Commissioner>().GetSessionId()));

    channelMask.Init();
    channelMask.SetChannelMask(aChannelMask);
    SuccessOrExit(error = channelMask.AppendTo(*message));

    SuccessOrExit(error = Tlv::Append<MeshCoP::PanIdTlv>(*message, aPanId));

    messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16());
    messageInfo.SetPeerAddr(aAddress);
    messageInfo.SetPeerPort(Tmf::kUdpPort);
    SuccessOrExit(error = Get<Tmf::TmfAgent>().SendMessage(*message, messageInfo));

    otLogInfoMeshCoP("sent panid query");

    mCallback = aCallback;
    mContext  = aContext;

exit:
    FreeMessageOnError(message, error);
    return error;
}

void PanIdQueryClient::HandleConflict(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
{
    static_cast<PanIdQueryClient *>(aContext)->HandleConflict(*static_cast<Coap::Message *>(aMessage),
                                                              *static_cast<const Ip6::MessageInfo *>(aMessageInfo));
}

void PanIdQueryClient::HandleConflict(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    uint16_t         panId;
    Ip6::MessageInfo responseInfo(aMessageInfo);
    uint32_t         mask;

    VerifyOrExit(aMessage.IsConfirmablePostRequest());

    otLogInfoMeshCoP("received panid conflict");

    SuccessOrExit(Tlv::Find<MeshCoP::PanIdTlv>(aMessage, panId));

    VerifyOrExit((mask = MeshCoP::ChannelMaskTlv::GetChannelMask(aMessage)) != 0);

    if (mCallback != nullptr)
    {
        mCallback(panId, mask, mContext);
    }

    SuccessOrExit(Get<Tmf::TmfAgent>().SendEmptyAck(aMessage, responseInfo));

    otLogInfoMeshCoP("sent panid query conflict response");

exit:
    return;
}

} // namespace ot

#endif //  OPENTHREAD_CONFIG_COMMISSIONER_ENABLE && OPENTHREAD_FTD


text:
namespace YAF.Pages {

    public partial class error {

        /// <summary>
        /// errormsg control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableCell errormsg;
    }
}


text:
require 'spec_helper'
require 'fluent_helpers/themes/inspinia'

describe FluentHelpers::Themes::Inspinia::Panel do
  include FluentHelpers::Helpers

  let(:template) { TemplateStub.new }
  let(:panel) { FluentHelpers::Themes::Inspinia::Panel.new(template) }

  example 'A complete example' do
    html = panel.named('foo') do
      template.concat 'bar'
    end.to_s

    expect(html).to have_tag('div.panel.panel-default') do
      with_tag 'div.panel-heading', text: 'foo'
      with_tag 'div.panel-body', text: 'bar'
    end
  end

  example 'With different styles' do
    styles = %w[default info warning danger success primary]

    styles.each do |style|
      html = panel.__send__(style).named('foo') do
        template.concat 'bar'
      end.to_s

      expect(html).to have_tag("div.panel.panel-#{style}")
    end
  end

  example 'Without heading' do
    html = panel.default do
      template.concat 'bar'
    end.to_s

    expect(html).to have_tag('div.panel.panel-default') do
      without_tag 'div.panel-heading'
      with_tag 'div.panel-body', text: 'bar'
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Gribble.Extensions
{
    public static class DictionaryExtensions
    {
        public static string AddWithUniquelyNamedKey<TValue>(
            this IDictionary<string, TValue> dictionary, TValue value)
        {
            var name = "K" + Unique.Next();
            dictionary.Add(name, value);
            return name;
        }

        public static void AddRange<TKey, TValue>(
            this IDictionary<TKey, TValue> source,
            IEnumerable<KeyValuePair<TKey, TValue>> items)
        {
            items.ToList().ForEach(x => source.Add(x.Key, x.Value));
        }

        public static TValue AddItem<TKey, TValue>(
            this IDictionary<TKey, TValue> source,
            TKey key, TValue value)
        {
            source.Add(key, value);
            return value;
        }

        public static bool ContainsKey<TKey, TValue>(this IDictionary<TKey, TValue> source,
            TKey key, Func<TKey, TKey> mapKey)
        {
            return source.Keys.Any(x => mapKey(x)?.Equals(key) ?? false);
        }

        public static TValue Map<TKey, TValue>(this IDictionary<TKey, TValue> source,
            TKey key, Func<TKey, TKey> mapKey)
        {
            var realKey = source.Keys.FirstOrDefault(x => mapKey(x)?.Equals(key) ?? false);
            if (realKey == null)
                throw new NullReferenceException($"Key '{key}' mapping not found.");
            return source[realKey];
        }

        public static Dictionary<TKey, TValue> ToDistinctDictionary<T, TKey, TValue>(
            this IEnumerable<T> source, Func<T, TKey> keySelector,
            Func<T, TValue> valueSelector,
            IEqualityComparer<TKey> equalityComparer = null)
        {
            var dictionary = equalityComparer != null
                ? new Dictionary<TKey, TValue>(equalityComparer)
                : new Dictionary<TKey, TValue>();
            source.ForEach(x => dictionary[keySelector(x)] = valueSelector(x));
            return dictionary;
        }
    }
}


text:
from xml.dom import minidom

from social.backends.oauth import BaseOAuth2

class NaverOAuth2(BaseOAuth2):
    """Naver OAuth authentication backend"""
    name = 'naver'
    AUTHORIZATION_URL = 'https://nid.naver.com/oauth2.0/authorize'
    ACCESS_TOKEN_URL = 'https://nid.naver.com/oauth2.0/token'
    ACCESS_TOKEN_METHOD = 'POST'
    EXTRA_DATA = [
        ('id', 'id'),
    ]

    def get_user_id(self, details, response):
        return response.get('id')

    def get_user_details(self, response):
        """Return user details from Naver account"""
        return {
            'username': response.get('username'),
            'email': response.get('email'),
            'fullname': response.get('username'),
        }

    def user_data(self, access_token, *args, **kwargs):
        """Loads user data from service"""
        response = self.request(
            'https://openapi.naver.com/v1/nid/getUserProfile.xml',
            headers={
                'Authorization': 'Bearer {0}'.format(access_token),
                'Content_Type': 'text/xml'
            }
        )

        dom = minidom.parseString(response.text.encode('utf-8').strip())

        return {
            'id': self._dom_value(dom, 'id'),
            'email': self._dom_value(dom, 'email'),
            'username': self._dom_value(dom, 'name'),
            'nickname': self._dom_value(dom, 'nickname'),
            'gender': self._dom_value(dom, 'gender'),
            'age': self._dom_value(dom, 'age'),
            'birthday': self._dom_value(dom, 'birthday'),
            'profile_image': self._dom_value(dom, 'profile_image')
        }

    def auth_headers(self):
        client_id, client_secret = self.get_key_and_secret()
        return {
            'grant_type': 'authorization_code',
            'code': self.data.get('code'),
            'client_id': client_id,
            'client_secret': client_secret,
        }

    def _dom_value(self, dom, key):
        return dom.getElementsByTagName(key)[0].childNodes[0].data


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Taschenbestimmb. f. Pilze 2, Erysiphaceen (1926)

#### Original name
Sphaerotheca macularis f. veronicae-virginicae Jacz.

### Remarks
null


text:
require_relative '../../acceptance_helper'

describe FeatureFlag do
  describe '#create' do
    it 'should create feature flag' do
      feature_flag = FactoryGirl.build(:feature_flag)

      expect {
        post superadmin_feature_flags_url, { feature_flag: feature_flag }.to_json, default_headers

        response.status.should == 204
      }.to change(FeatureFlag, :count).by(1)
    end
  end

  describe '#update' do
    it 'should update feature flag name' do
      feature_flag      = FactoryGirl.build(:feature_flag)
      test_feature_flag = FactoryGirl.build(:feature_flag)

      test_feature_flag.id   = feature_flag.id
      test_feature_flag.name = "test_new_name"
      test_feature_flag.save

      old_name = feature_flag.name

      expect {
        put superadmin_feature_flag_url(feature_flag.id), { feature_flag: test_feature_flag }.to_json, default_headers

        feature_flag.reload
      }.to change(feature_flag, :name).from(old_name).to(test_feature_flag.name)
    end
  end

  describe '#destroy' do

    it 'should destroy feature flag' do
      feature_flag = FactoryGirl.create(:feature_flag)

      expect {
        delete superadmin_feature_flag_url(feature_flag.id), { feature_flag: feature_flag }.to_json, default_headers
      }.to change(FeatureFlag, :count).by(-1)
    end

    it 'should destroy feature flag user relations' do
      feature_flag = FactoryGirl.create(:feature_flag)
      user         = FactoryGirl.create(:user)

      feature_flag_user = FactoryGirl.create(:feature_flags_user, feature_flag_id: feature_flag.id, user_id: user.id)

      expect {
        delete superadmin_feature_flag_url(feature_flag.id), { feature_flag: feature_flag }.to_json, default_headers
      }.to change(FeatureFlagsUser, :count).by(-1)
    end
  end

  private

  def default_headers(user = Cartodb.config[:superadmin]["username"], password = Cartodb.config[:superadmin]["password"])
    {
      'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user, password),
      'HTTP_ACCEPT' => "application/json",
      'CONTENT_TYPE'  => 'application/json'
    }
  end
end


text:
/**
 * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v25.1.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { RefSelector } from '../../../widgets/componentAnnotations';
import { SimpleFilter, ConditionPosition } from '../simpleFilter';
import { makeNull } from '../../../utils/generic';
import { setDisplayed } from '../../../utils/dom';
import { forEach } from '../../../utils/array';
var TextFilter = /** @class */ (function (_super) {
    __extends(TextFilter, _super);
    function TextFilter() {
        return _super.call(this, 'textFilter') || this;
    }
    TextFilter.trimInput = function (value) {
        var trimmedInput = value && value.trim();
        // trim the input, unless it is all whitespace (this is consistent with Excel behaviour)
        return trimmedInput === '' ? value : trimmedInput;
    };
    TextFilter.prototype.getDefaultDebounceMs = function () {
        return 500;
    };
    TextFilter.prototype.getCleanValue = function (inputField) {
        var value = makeNull(inputField.getValue());
        return this.textFilterParams.trimInput ? TextFilter.trimInput(value) : value;
    };
    TextFilter.prototype.addValueChangedListeners = function () {
        var _this = this;
        var listener = function () { return _this.onUiChanged(); };
        this.eValue1.onValueChange(listener);
        this.eValue2.onValueChange(listener);
    };
    TextFilter.prototype.setParams = function (params) {
        _super.prototype.setParams.call(this, params);
        this.textFilterParams = params;
        this.comparator = this.textFilterParams.textCustomComparator || TextFilter.DEFAULT_COMPARATOR;
        this.formatter = this.textFilterParams.textFormatter ||
            (this.textFilterParams.caseSensitive ? TextFilter.DEFAULT_FORMATTER : TextFilter.DEFAULT_LOWERCASE_FORMATTER);
        this.addValueChangedListeners();
    };
    TextFilter.prototype.setConditionIntoUi = function (model, position) {
        var positionOne = position === ConditionPosition.One;
        var eValue = positionOne ? this.eValue1 : this.eValue2;
        eValue.setValue(model ? model.filter : null);
    };
    TextFilter.prototype.createCondition = function (position) {
        var positionOne = position === ConditionPosition.One;
        var type = positionOne ? this.getCondition1Type() : this.getCondition2Type();
        var eValue = positionOne ? this.eValue1 : this.eValue2;
        var value = this.getCleanValue(eValue);
        eValue.setValue(value, true); // ensure clean value is visible
        var model = {
            filterType: this.getFilterType(),
            type: type
        };
        if (!this.doesFilterHaveHiddenInput(type)) {
            model.filter = value;
        }
        return model;
    };
    TextFilter.prototype.getFilterType = function () {
        return 'text';
    };
    TextFilter.prototype.areSimpleModelsEqual = function (aSimple, bSimple) {
        return aSimple.filter === bSimple.filter && aSimple.type === bSimple.type;
    };
    TextFilter.prototype.resetUiToDefaults = function (silent) {
        var _this = this;
        return _super.prototype.resetUiToDefaults.call(this, silent).then(function () {
            _this.forEachInput(function (field) { return field.setValue(null, silent); });
            _this.resetPlaceholder();
        });
    };
    TextFilter.prototype.resetPlaceholder = function () {
        var globalTranslate = this.gridOptionsWrapper.getLocaleTextFunc();
        var placeholder = this.translate('filterOoo');
        this.forEachInput(function (field) {
            field.setInputPlaceholder(placeholder);
            field.setInputAriaLabel(globalTranslate('ariaFilterValue', 'Filter Value'));
        });
    };
    TextFilter.prototype.forEachInput = function (action) {
        forEach([this.eValue1, this.eValue2], action);
    };
    TextFilter.prototype.setValueFromFloatingFilter = function (value) {
        this.eValue1.setValue(value);
        this.eValue2.setValue(null);
    };
    TextFilter.prototype.getDefaultFilterOptions = function () {
        return TextFilter.DEFAULT_FILTER_OPTIONS;
    };
    TextFilter.prototype.createValueTemplate = function (position) {
        var pos = position === ConditionPosition.One ? '1' : '2';
        return /* html */ "\n            <div class=\"ag-filter-body\" ref=\"eCondition" + pos + "Body\" role=\"presentation\">\n                <ag-input-text-field class=\"ag-filter-filter\" ref=\"eValue" + pos + "\"></ag-input-text-field>\n            </div>";
    };
    TextFilter.prototype.updateUiVisibility = function () {
        _super.prototype.updateUiVisibility.call(this);
        setDisplayed(this.eCondition1Body, this.showValueFrom(this.getCondition1Type()));
        setDisplayed(this.eCondition2Body, this.isCondition2Enabled() && this.showValueFrom(this.getCondition2Type()));
    };
    TextFilter.prototype.afterGuiAttached = function (params) {
        _super.prototype.afterGuiAttached.call(this, params);
        this.resetPlaceholder();
        if (!params || !params.suppressFocus) {
            this.eValue1.getInputElement().focus();
        }
    };
    TextFilter.prototype.isConditionUiComplete = function (position) {
        var positionOne = position === ConditionPosition.One;
        var option = positionOne ? this.getCondition1Type() : this.getCondition2Type();
        if (option === SimpleFilter.EMPTY) {
            return false;
        }
        if (this.doesFilterHaveHiddenInput(option)) {
            return true;
        }
        return this.getCleanValue(positionOne ? this.eValue1 : this.eValue2) != null;
    };
    TextFilter.prototype.individualConditionPasses = function (params, filterModel) {
        var filterText = filterModel.filter;
        var filterOption = filterModel.type;
        var cellValue = this.textFilterParams.valueGetter(params.node);
        var cellValueFormatted = this.formatter(cellValue);
        var customFilterOption = this.optionsFactory.getCustomOption(filterOption);
        if (customFilterOption) {
            // only execute the custom filter if a value exists or a value isn't required, i.e. input is hidden
            if (filterText != null || customFilterOption.hideFilterInput) {
                return customFilterOption.test(filterText, cellValueFormatted);
            }
        }
        if (cellValue == null) {
            return filterOption === SimpleFilter.NOT_EQUAL || filterOption === SimpleFilter.NOT_CONTAINS;
        }
        var filterTextFormatted = this.formatter(filterText);
        return this.comparator(filterOption, cellValueFormatted, filterTextFormatted);
    };
    TextFilter.DEFAULT_FILTER_OPTIONS = [
        SimpleFilter.CONTAINS,
        SimpleFilter.NOT_CONTAINS,
        SimpleFilter.EQUALS,
        SimpleFilter.NOT_EQUAL,
        SimpleFilter.STARTS_WITH,
        SimpleFilter.ENDS_WITH
    ];
    TextFilter.DEFAULT_FORMATTER = function (from) { return from; };
    TextFilter.DEFAULT_LOWERCASE_FORMATTER = function (from) { return from == null ? null : from.toString().toLowerCase(); };
    TextFilter.DEFAULT_COMPARATOR = function (filter, value, filterText) {
        switch (filter) {
            case TextFilter.CONTAINS:
                return value.indexOf(filterText) >= 0;
            case TextFilter.NOT_CONTAINS:
                return value.indexOf(filterText) < 0;
            case TextFilter.EQUALS:
                return value === filterText;
            case TextFilter.NOT_EQUAL:
                return value != filterText;
            case TextFilter.STARTS_WITH:
                return value.indexOf(filterText) === 0;
            case TextFilter.ENDS_WITH:
                var index = value.lastIndexOf(filterText);
                return index >= 0 && index === (value.length - filterText.length);
            default:
                // should never happen
                console.warn('invalid filter type ' + filter);
                return false;
        }
    };
    __decorate([
        RefSelector('eValue1')
    ], TextFilter.prototype, "eValue1", void 0);
    __decorate([
        RefSelector('eValue2')
    ], TextFilter.prototype, "eValue2", void 0);
    return TextFilter;
}(SimpleFilter));
export { TextFilter };


text:
"""flatty - marshaller/unmarshaller for light-schema python objects"""
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__author__ = "Christian Haintz"
__contact__ = "christian.haintz@orangelabs.at"
__homepage__ = "http://packages.python.org/flatty"
__docformat__ = "restructuredtext"

from flatty import *
try:
    import mongo
except ImportError:
    pass
try:
    import couch
except ImportError:
    pass


text:
#ifndef jscompat_h___
#define jscompat_h___
/*
 * Compatibility glue for various NSPR versions.  We must always define int8,
 * int16, jsword, and so on to minimize differences with js/ref, no matter what
 * the NSPR typedef names may be.
 */
#include "jstypes.h"
#include "jslong.h"

typedef JSIntn intN;
typedef JSUintn uintN;
typedef JSUword jsuword;
typedef JSWord jsword;
typedef float float32;
#endif /* jscompat_h___ */


text:
Initial version of Onedata Helm Charts

~~~
make clean install-onedata
~~~


text:
package synchronization

import (
	"os"
	"testing"

	"github.com/mutagen-io/mutagen/pkg/encoding"
	"github.com/mutagen-io/mutagen/pkg/filesystem/behavior"
	"github.com/mutagen-io/mutagen/pkg/synchronization"
	"github.com/mutagen-io/mutagen/pkg/synchronization/core"
)

const (
	testYAMLConfiguration = `
mode: "two-way-resolved"
maxEntryCount: 500
maxStagingFileSize: "1000 GB"
probeMode: "assume"
scanMode: "accelerated"
stageMode: "neighboring"

symlink:
  mode: "portable"

watch:
  mode: "force-poll"
  pollingInterval: 5

ignore:
  paths:
    - "ignore/this/**"
    - "!ignore/this/that"
  vcs: true

permissions:
  defaultFileMode: 644
  defaultDirectoryMode: 0755
  defaultOwner: "george"
  defaultGroup: "presidents"
`
)

// expectedConfiguration is the configuration that's expected based on the
// human-readable configuration given above.
var expectedConfiguration = &synchronization.Configuration{
	SynchronizationMode: core.SynchronizationMode_SynchronizationModeTwoWayResolved,
	MaximumEntryCount:   500,
	// TODO: This will mis-match.
	MaximumStagingFileSize: 1000000000000,
	ProbeMode:              behavior.ProbeMode_ProbeModeAssume,
	ScanMode:               synchronization.ScanMode_ScanModeAccelerated,
	StageMode:              synchronization.StageMode_StageModeNeighboring,
	SymbolicLinkMode:       core.SymbolicLinkMode_SymbolicLinkModePortable,
	WatchMode:              synchronization.WatchMode_WatchModeForcePoll,
	WatchPollingInterval:   5,
	Ignores: []string{
		"ignore/this/**",
		"!ignore/this/that",
	},
	IgnoreVCSMode:        core.IgnoreVCSMode_IgnoreVCSModeIgnore,
	DefaultFileMode:      0644,
	DefaultDirectoryMode: 0755,
	DefaultOwner:         "george",
	DefaultGroup:         "presidents",
}

// TestLoadConfiguration tests loading a YAML-based session configuration.
func TestLoadConfiguration(t *testing.T) {
	// Write a valid configuration to a temporary file and defer its cleanup.
	file, err := os.CreateTemp("", "mutagen_configuration")
	if err != nil {
		t.Fatal("unable to create temporary file:", err)
	} else if _, err = file.Write([]byte(testYAMLConfiguration)); err != nil {
		t.Fatal("unable to write data to temporary file:", err)
	} else if err = file.Close(); err != nil {
		t.Fatal("unable to close temporary file:", err)
	}
	defer os.Remove(file.Name())

	// Attempt to load.
	yamlConfiguration := &Configuration{}
	if err := encoding.LoadAndUnmarshalYAML(file.Name(), yamlConfiguration); err != nil {
		t.Error("configuration loading failed:", err)
	}

	// Compute the Protocol Buffers session representation.
	configuration := yamlConfiguration.Configuration()

	// Ensure that the resulting configuration is valid.
	if err := configuration.EnsureValid(false); err != nil {
		t.Error("derived configuration invalid:", err)
	}

	// Verify that the configuration matches what's expected.
	if configuration.SynchronizationMode != expectedConfiguration.SynchronizationMode {
		t.Error("synchronization mode mismatch:", configuration.SynchronizationMode, "!=", expectedConfiguration.SynchronizationMode)
	}
	if configuration.MaximumEntryCount != expectedConfiguration.MaximumEntryCount {
		t.Error("maximum entry count mismatch:", configuration.MaximumEntryCount, "!=", expectedConfiguration.MaximumEntryCount)
	}
	if configuration.MaximumStagingFileSize != expectedConfiguration.MaximumStagingFileSize {
		t.Error("maximum staging file size mismatch:", configuration.MaximumStagingFileSize, "!=", expectedConfiguration.MaximumStagingFileSize)
	}
	if configuration.ProbeMode != expectedConfiguration.ProbeMode {
		t.Error("probe mode mismatch:", configuration.ProbeMode, "!=", expectedConfiguration.ProbeMode)
	}
	if configuration.ScanMode != expectedConfiguration.ScanMode {
		t.Error("scan mode mismatch:", configuration.ScanMode, "!=", expectedConfiguration.ScanMode)
	}
	if configuration.StageMode != expectedConfiguration.StageMode {
		t.Error("stage mode mismatch:", configuration.StageMode, "!=", expectedConfiguration.StageMode)
	}
	if configuration.SymbolicLinkMode != expectedConfiguration.SymbolicLinkMode {
		t.Error("symbolic link mode mismatch:", configuration.SymbolicLinkMode, "!=", expectedConfiguration.SymbolicLinkMode)
	}
	if configuration.WatchMode != expectedConfiguration.WatchMode {
		t.Error("watch mode mismatch:", configuration.WatchMode, "!=", expectedConfiguration.WatchMode)
	}
	if configuration.WatchPollingInterval != expectedConfiguration.WatchPollingInterval {
		t.Error("watch polling interval mismatch:", configuration.WatchPollingInterval, "!=", expectedConfiguration.WatchPollingInterval)
	}
	if len(configuration.Ignores) != len(expectedConfiguration.Ignores) {
		t.Error("ignore count mismatch:", len(configuration.Ignores), "!=", len(expectedConfiguration.Ignores))
	} else {
		for i, ignore := range configuration.Ignores {
			if ignore != expectedConfiguration.Ignores[i] {
				t.Error("ignore mismatch:", ignore, "!=", expectedConfiguration.Ignores[i], "at index", i)
			}
		}
	}
	if configuration.IgnoreVCSMode != expectedConfiguration.IgnoreVCSMode {
		t.Error("ignore VCS mode mismatch:", configuration.IgnoreVCSMode, "!=", expectedConfiguration.IgnoreVCSMode)
	}
	if configuration.DefaultFileMode != expectedConfiguration.DefaultFileMode {
		t.Errorf("default file mode mismatch: %o != %o", configuration.DefaultFileMode, expectedConfiguration.DefaultFileMode)
	}
	if configuration.DefaultDirectoryMode != expectedConfiguration.DefaultDirectoryMode {
		t.Errorf("default directory mode mismatch: %o != %o", configuration.DefaultDirectoryMode, expectedConfiguration.DefaultDirectoryMode)
	}
	if configuration.DefaultOwner != expectedConfiguration.DefaultOwner {
		t.Error("default owner mismatch:", configuration.DefaultOwner, "!=", expectedConfiguration.DefaultOwner)
	}
	if configuration.DefaultGroup != expectedConfiguration.DefaultGroup {
		t.Error("default owner mismatch:", configuration.DefaultGroup, "!=", expectedConfiguration.DefaultGroup)
	}
}

// TODO: Expand tests, including testing for invalid configurations.


text:
/*
 * This file is part of Beads. See http://www.beadsproject.net for all information.
 */
package net.beadsproject.beads.ugens;

import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.UGen;

/**
 * A very simple {@link UGen} that generates one click and then kills itself.
 *
 * @beads.category synth
 * @author ollie
 */
public class Clicker extends UGen {

	private boolean done;
	private float strength;

	/**
	 * Instantiates a new Clicker.
	 *
	 * @param context
	 *            the AudioContext.
	 * @param strength the volume of the click (max = 1).
	 */
	public Clicker(AudioContext context, float strength) {
		super(context, 0, 1);
		this.strength = Math.min(1f, Math.abs(strength));
		done = false;
	}

	/* (non-Javadoc)
	 * @see com.olliebown.beads.core.UGen#calculateBuffer()
	 */
	@Override
	public void calculateBuffer() {
		if(done) kill();
		else {
			bufOut[0][0] = strength;
			done = true;
		}
	}

}


text:
No features have been deprecated in this version of Chrome.
Chrome Platform Status provides a
<a href='https://chromestatus.com/features#browsers.chrome.status:"Deprecated"'>
  list of deprecated features
</a>
from previous versions of Chrome.


text:
@interface SpecialsInfoViewController : BaseViewController

@property (nonatomic) Event* eventObj;

@end


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Quantity
 *
 * @ORM\Table(name="quantity")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\QuantityRepository")
 */
class Quantity
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var int
     *
     * @ORM\Column(name="quantity", type="integer", nullable=true)
     */
    private $quantity;

    /**
     * @var int
     *
     * @ORM\Column(name="minimalquantity", type="integer", nullable=true)
     */
    private $minimalquantity=1;

    /**
     * Préférences de disponibilité
     * 1- Refuser les commandes
     * 2- Accepter les commandes
     * 3- Utiliser le comportement par défaut (Refuser les commandes)
     * @var int
     *
     * @ORM\Column(name="outofstock", type="integer", nullable=true)
     */
    private $outofstock;
    /**
     * Libellé si en stock
     *
     * @var string
     *
     * @ORM\Column(name="availablenow", type="string", nullable=true)
     */
    private $availablenow;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="availabledate", type="datetimetz", nullable=true)
     */
    private $availabledate;

    /**
     * Si rupture de stock (et précommande autorisée)
     *
     * @var string
     *
     * @ORM\Column(name="availablelater", type="string", length=255, nullable=true)
     */
    private $availablelater;

    /**
     * Quantity constructor.
     * @param \DateTime $availabledate
     */
    public function __construct()
    {
        $this->availabledate = new \DateTime('now');
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set quantity
     *
     * @param integer $quantity
     *
     * @return Quantity
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;

        return $this;
    }

    /**
     * Get quantity
     *
     * @return int
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * Set minimalquantity
     *
     * @param integer $minimalquantity
     *
     * @return Quantity
     */
    public function setMinimalquantity($minimalquantity)
    {
        $this->minimalquantity = $minimalquantity;

        return $this;
    }

    /**
     * Get minimalquantity
     *
     * @return int
     */
    public function getMinimalquantity()
    {
        return $this->minimalquantity;
    }

    /**
     * Set outofstock
     *
     * @param integer $outofstock
     *
     * @return Quantity
     */
    public function setOutofstock($outofstock)
    {
        $this->outofstock = $outofstock;

        return $this;
    }

    /**
     * Get outofstock
     *
     * @return int
     */
    public function getOutofstock()
    {
        return $this->outofstock;
    }

    /**
     * Set availabledate
     *
     * @param \DateTime $availabledate
     *
     * @return Quantity
     */
    public function setAvailabledate($availabledate)
    {
        $this->availabledate = $availabledate;

        return $this;
    }

    /**
     * Get availabledate
     *
     * @return \DateTime
     */
    public function getAvailabledate()
    {
        return $this->availabledate;
    }

    /**
     * Set availablelater
     *
     * @param string $availablelater
     *
     * @return Quantity
     */
    public function setAvailablelater($availablelater)
    {
        $this->availablelater = $availablelater;

        return $this;
    }

    /**
     * Get availablelater
     *
     * @return string
     */
    public function getAvailablelater()
    {
        return $this->availablelater;
    }

    /**
     * Set availablenow
     *
     * @param string $availablenow
     *
     * @return Quantity
     */
    public function setAvailablenow($availablenow)
    {
        $this->availablenow = $availablenow;

        return $this;
    }

    /**
     * Get availablenow
     *
     * @return string
     */
    public function getAvailablenow()
    {
        return $this->availablenow;
    }
}


text:
package com.opengamma.strata.basics.currency;

/**
 * A provider of FX rates.
 *

 * This provides the ability to obtain an FX rate. The interface does not mandate when the
 * rate applies, however it typically represents the current rate.
 *

 * One possible implementation is {@link FxMatrix}.
 *

 * Implementations do not have to be immutable, but calls to the methods must be thread-safe.
 */
public interface FxRateProvider {

  /**
   * Gets the FX rate for the specified currency pair.
   *

   * The rate returned is the rate from the base currency to the counter currency
   * as defined by this formula: {@code (1 * baseCurrency = fxRate * counterCurrency)}.
   *
   * @param baseCurrency  the base currency, to convert from
   * @param counterCurrency  the counter currency, to convert to
   * @return the FX rate for the currency pair
   * @throws RuntimeException if no FX rate could be found
   */
  public abstract double fxRate(Currency baseCurrency, Currency counterCurrency);

  /**
   * Gets the FX rate for the specified currency pair.
   *

   * The rate returned is the rate from the base currency to the counter currency
   * as defined by this formula: {@code (1 * baseCurrency = fxRate * counterCurrency)}.
   *
   * @param currencyPair  the ordered currency pair defining the rate required
   * @return the FX rate for the currency pair
   * @throws RuntimeException if no FX rate could be found
   */
  public default double fxRate(CurrencyPair currencyPair) {
    return fxRate(currencyPair.getBase(), currencyPair.getCounter());
  }

}


text:
namespace content {

// Parameters used when showing an HTML5 notification.
struct CONTENT_EXPORT ShowDesktopNotificationHostMsgParams {
  ShowDesktopNotificationHostMsgParams();
  ~ShowDesktopNotificationHostMsgParams();

  // URL which is the origin that created this notification.
  GURL origin;

  // True if this is HTML
  bool is_html;

  // URL which contains the HTML contents (if is_html is true), otherwise empty.
  GURL contents_url;

  // Contents of the notification if is_html is false.
  GURL icon_url;
  string16 title;
  string16 body;

  // Directionality of the notification.
  WebKit::WebTextDirection direction;

  // ReplaceID if this notification should replace an existing one; may be
  // empty if no replacement is called for.
  string16 replace_id;

  // Notification ID for sending events back for this notification.
  int notification_id;
};

}  // namespace content

#endif  // CONTENT_PUBLIC_COMMON_SHOW_DESKTOP_NOTIFICATION_PARAMS_H_


text:
package com.example.administrator.chinaweather.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Administrator on 2015/9/2.
 */
public class ChinaWeatherOpenHelper extends SQLiteOpenHelper {
    public final static  String CREATE_PROVINCE="create table province(id integer primary key autoincrement," +
            "province_name text,province_code text)";
    public final  static String CREATE_CITY="create table city(id integer primary " +
            "key autoincrement,city_name text, city_code text, province_id text)";
    public final static String CREATE_COUNTY="create table county(id integer primary key" +
            " autoincrement,county_name text,county_code text,city_id integer)";

    public ChinaWeatherOpenHelper(Context context,String name,SQLiteDatabase.CursorFactory factory
    ,int version){
        super(context, name, factory, version);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_PROVINCE);
        db.execSQL(CREATE_CITY);
        db.execSQL(CREATE_COUNTY);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Index extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        if($this->session->userdata('manager_logged_in') != TRUE)
        {
            redirect('manager-admin/login');
        }
    }

    public function index()
    {
        $this->load->view('manager-admin/include/header');
        $this->load->view('manager-admin/index');
        $this->load->view('manager-admin/include/footer');
    }
}


text:
export CATALINA_HOME=/root/apache-tomcat-8.5.9

resultFile=$CATALINA_HOME/startresults.txt
tail -n 1 $resultFile > ./result.txt

while read line
do
      if [ "$line" == "Tomcat started." ];
        then
          echo "ok"
        else
         echo "not ok!"
      fi
done < ./result.txt


text:
using System;
using System.Collections.Generic;

namespace Colyseus.Schema
{
	class ColyseusCustomType
	{
		protected static ColyseusCustomType instance = new ColyseusCustomType();
		protected Dictionary<string, System.Type> types = new Dictionary<string, System.Type>();
		//{
		//		["array"] = ArraySchema
		//};

		public static ColyseusCustomType GetInstance()
		{
			return instance;
		}

		public void Add(string id, System.Type type)
		{
			if (!types.ContainsKey(id))
			{
				types.Add(id, type);
			}
		}

		public System.Type Get(string id)
		{
			System.Type type;
			types.TryGetValue(id, out type);
			return type;
		}
	}
}


text:
require 'spec_helper'

describe MessagesController do

  describe 'POST #create' do

    it 'saves the received message in the db' do
      expect{
        post :create, message: attributes_for(:message)
        }.to change(Message, :count).by(1)
    end
  end
end


text:
/*
 *
 */
package net.community.chest.util;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 *
Copyright as per GPLv2

 *
Wraps an {@link Iterable} or {@link Iterator} instance into an {@link Enumeration}

 * @param <V> Type of parameter being enumerated
 * @author Lyor G.
 * @since Nov 14, 2010 1:55:03 PM
 */
public class IterableEnumeration<V> implements Enumeration<V> {
    private Iterator<V>    _iterator;
    public Iterator<V> getIterator ()
    {
        return _iterator;
    }

    public void setIterator (Iterator<V> iterator)
    {
        _iterator = iterator;
    }

    public IterableEnumeration (Iterator<V> iterator)
    {
        _iterator = iterator;
    }

    public IterableEnumeration (Iterable<V> iterable)
    {
        this((iterable == null) ? null : iterable.iterator());
    }

    public IterableEnumeration ()
    {
        this((Iterator<V>) null);
    }
    /*
     * @see java.util.Enumeration#hasMoreElements()
     */
    @Override
    public boolean hasMoreElements ()
    {
        final Iterator<?>    iter=getIterator();
        if ((iter != null) && iter.hasNext())
            return true;

        return false;
    }
    /*
     * @see java.util.Enumeration#nextElement()
     */
    @Override
    public V nextElement ()
    {
        final Iterator<? extends V>    iter=getIterator();
        if (iter == null)
            throw new NoSuchElementException("No iterator");

        return iter.next();
    }
}


text:
Overview
==================
This project pairs down the OpenStack Shaker project to only execute "spot" tests. These tests do not require a "callback" to a controller.
They are similar to executing a ping test but provide more reporting, testing and configuration options.

Executing
===================
create a shaker.cfg (Shaker docs have more details)

Sample:
  [DEFAULT]
  # results will be stored at this path, so it should be externally accessible from the container
  report = /share/results/report.html
  output = /share/results/output.json

  # this field can also be a path in the /share directory to run a test not provided in Shaker by default
  scenario = spot/ping

  # the contianer will overwrite SPOT_IP with the ip from the heat stack
  # time is an override to what's in the test definition and is set in seconds
  matrix ={host: SPOT_IP, time: 20}

  # OpenStack auth vars
  os_region_name =
  os_project_name =

make sure shaker.cfg is accessible to the container's /share directory

docker run -ti -v $PWD:/share simple-shaker


text:
#import <CoreGraphics/CoreGraphics.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

#ifdef __cplusplus
extern "C" {
#endif

// Get window and screen dimensions
typedef struct {
  struct {
    CGFloat width, height, scale, fontScale;
  } window, screen;
} ABI43_0_0RCTDimensions;
extern __attribute__((visibility("default"))) ABI43_0_0RCTDimensions ABI43_0_0RCTGetDimensions(CGFloat fontScale);

// Get font size multiplier for font base size (Large) by content size category
extern __attribute__((visibility("default"))) CGFloat ABI43_0_0RCTGetMultiplierForContentSizeCategory(
    UIContentSizeCategory category);

#ifdef __cplusplus
}
#endif

NS_ASSUME_NONNULL_END


text:
package io.machinecode.chainlink.spi.jsl;

/**
 * @author Brent Douglas
 * @since 1.0
 */
public interface Element {

}