text:
var StatsModel = {};

(function (self) {
  // starts future.get with given ajaxOptions and arranges invocation
  // of 'body' with value or if future is cancelled invocation of body
  // with 'cancelledValue'.
  //
  // NOTE: this is not normal future as normal futures deliver values
  // to cell, but this one 'delivers' values to given function 'body'.
  function getCPS(ajaxOptions, cancelledValue, body) {
    // this wrapper calls 'body' instead of delivering value to it's
    // cell
    var futureWrapper = future.wrap(function (ignoredDataCallback, startGet) {
      return startGet(body);
    });
    var async = future.get(ajaxOptions, undefined, undefined, futureWrapper);
    async.cancel = (function (realCancel) {
      return function () {
        if (realCancel) {
          realCancel.call(this);
        }
        body(cancelledValue);
      }
    })(async.cancel);
    // we need any cell here to satisfy our not yet perfect API
    async.start(new Cell());
    return async;
  }

  function createSamplesFuture(opts, bufferDepth) {
    var cancelMark = {};
    var mark404 = {};

    function doGet(data, body) {
      if (mainAsync.cancelled) {
        return body(cancelMark);
      }

      function onCancel() {
        if (async) {
          async.cancel();
        }
      }
      function unbind() {
        $(mainAsync).unbind('cancelled', onCancel);
      }
      $(mainAsync).bind('cancelled', onCancel);

      var async;
      return async = getCPS({url: '/_uistats', data: data, missingValue: mark404}, cancelMark, function (value, status, xhr) {
        unbind();
        if (value !== cancelMark && value !== mark404) {
          var date = xhr.getResponseHeader('date');
          value.serverDate = parseHTTPDate(date).valueOf();
          value.clientDate = (new Date()).valueOf();
        }
        body(value, status, xhr);
      });
    }

    var dataCallback;

    var mainAsync = future(function (_dataCallback) {
      dataCallback = _dataCallback;
      loop();
    });
    mainAsync.cancel = function () {
      $(this).trigger("cancelled");
    };

    var extraOpts = {};
    var prevValue;

    return mainAsync;

    function loop(deliverValue) {
      doGet(_.extend({}, opts, extraOpts), onLoopData);
    }

    function onLoopData(value) {
      if (value === mark404) {
        return;
      }
      if (prevValue) {
        value = maybeApplyDelta(prevValue, value);
      }
      if (!dataCallback.continuing(value)) {
        return;
      }
      prevValue = value;
      if (value.lastTStamp) {
        extraOpts = {haveTStamp: JSON.stringify(value.lastTStamp)};
      }
      if (!('nextReqAfter' in value)) {
        BUG();
      }
      setTimeout(loop, value.nextReqAfter);
    }

    function restoreOpsBlock(prevSamples, samples, keepCount) {
      var prevTS = prevSamples.timestamp;
      if (samples.timestamp && samples.timestamp.length == 0) {
        // server was unable to return any data for this "kind" of
        // stats
        if (prevSamples && prevSamples.timestamp && prevSamples.timestamp.length > 0) {
          return prevSamples;
        }
        return samples;
      }
      if (prevTS == undefined ||
          prevTS.length == 0 ||
          prevTS[prevTS.length-1] != samples.timestamp[0]) {
        return samples;
      }
      var newSamples = {};
      for (var keyName in samples) {
        var ps = prevSamples[keyName];
        if (!ps) {
          ps = [];
          ps.length = keepCount;
        }
        newSamples[keyName] = ps.concat(samples[keyName].slice(1)).slice(-keepCount);
      }
      return newSamples;
    }

    function maybeApplyDelta(prevValue, value) {
      var stats = value.stats;
      var prevStats = prevValue.stats || {};
      for (var kind in stats) {
        var newSamples = restoreOpsBlock(prevStats[kind],
                                         stats[kind],
                                         value.samplesCount + bufferDepth);
        stats[kind] = newSamples;
      }
      return value;
    }
  }

  var statsBucketURL = self.statsBucketURL = new StringHashFragmentCell("statsBucket");
  var statsHostname = self.statsHostname = new StringHashFragmentCell("statsHostname");
  var statsStatName = self.statsStatName = new StringHashFragmentCell("statsStatName");

  self.selectedGraphNameCell = new StringHashFragmentCell("graph");

  self.configurationExtra = new Cell();

  self.smallGraphSelectionCellCell = Cell.compute(function (v) {
    return v.need(self.displayingSpecificStatsCell) ? self.statsHostname : self.selectedGraphNameCell;
  });

  // contains bucket details of statsBucketURL bucket (or default if there are no such bucket)
  var statsBucketDetails = self.statsBucketDetails = Cell.compute(function (v) {
    var uri = v(statsBucketURL);
    var buckets = v.need(DAL.cells.bucketsListCell);
    var rv;
    if (uri !== undefined) {
      rv = _.detect(buckets, function (info) {return info.uri === uri});
    } else {
      rv = _.detect(buckets, function (info) {return info.name === "default"}) || buckets[0];
    }
    return rv;
  }).name("statsBucketDetails");

  var statsOptionsCell = self.statsOptionsCell = (new Cell()).name("statsOptionsCell");
  statsOptionsCell.setValue({});
  _.extend(statsOptionsCell, {
    update: function (options) {
      this.modifyValue(_.bind($.extend, $, {}), options);
    },
    equality: _.isEqual
  });

  var samplesBufferDepthRAW = new StringHashFragmentCell("statsBufferDepth");
  self.samplesBufferDepth = Cell.computeEager(function (v) {
    return v(samplesBufferDepthRAW) || 1;
  });

  var zoomLevel;
  (function () {
    var slider = $("#js_date_slider").slider({
      orientation: "vertical",
      range: "min",
      min: 1,
      max: 6,
      value: 6,
      step: 1,
      slide: function(event, ui) {
        var dateSwitchers = $("#js_date_slider_container .js_click");
        dateSwitchers.eq(dateSwitchers.length - ui.value).trigger('click');
      }
    });

    zoomLevel = (new LinkSwitchCell('zoom', {
      firstItemIsDefault: true
    })).name("zoomLevel");

    _.each('minute hour day week month year'.split(' '), function (name) {
      zoomLevel.addItem('js_zoom_' + name, name);
    });

    zoomLevel.finalizeBuilding();

    zoomLevel.subscribeValue(function (zoomLevel) {
      var z = $('#js_zoom_' + zoomLevel);
      slider.slider('value', 6 - z.index());
      self.statsOptionsCell.update({
        zoom: zoomLevel
      });
    });
  })();

  self.rawStatsCell = Cell.compute(function (v) {
    if (v.need(DAL.cells.mode) != "analytics") {
      return;
    }
    var options = v.need(statsOptionsCell);
    var node;
    var bucket = v.need(statsBucketDetails).name;
    var data = _.extend({bucket: bucket}, options);
    var statName = v(statsStatName);
    if (statName) {
      data.statName = statName;
    } else if ((node = v(statsHostname))) {
      // we don't send node it we're dealing with "specific stats" and
      // we're careful to depend on statsHostname cell _only_ we're
      // willing to send node.
      data.node = node;
    }
    var bufferDepth = v.need(self.samplesBufferDepth);
    return createSamplesFuture(data, bufferDepth);
  });

  self.displayingSpecificStatsCell = Cell.compute(function (v) {
    return !!(v.need(self.rawStatsCell).specificStatName);
  });

  self.directoryURLCell = Cell.compute(function (v) {
    return v.need(self.rawStatsCell).directory.url;
  });
  self.directoryURLCell.equality = function (a, b) {return a === b;};

  self.directoryValueCell = Cell.compute(function (v) {
    return v.need(self.rawStatsCell).directory.value;
  });
  self.directoryValueCell.equality = _.isEqual;

  self.directoryCell = Cell.compute(function (v) {
    var url = v.need(self.directoryURLCell);
    if (url) {
      return future.get({url: url});
    }
    return v.need(self.directoryValueCell);
  });

  self.specificStatTitleCell = Cell.compute(function (v) {
    return v.need(self.rawStatsCell).directory.origTitle;
  });

  self.infosCell = Cell.needing(self.directoryCell).compute(function (v, statDesc) {
    statDesc = JSON.parse(JSON.stringify(statDesc)); // this makes deep copy of statDesc

    var infos = [];
    infos.byName = {};

    var statItems = [];
    var blockIDs = [];

    var hadServerResources = false;
    if (statDesc.blocks[0].serverResources) {
      // We want it last so that default stat name (which is first
      // statItems entry) is not from ServerResourcesBlock
      hadServerResources = true;
      statDesc.blocks = statDesc.blocks.slice(1).concat([statDesc.blocks[0]]);
    }
    _.each(statDesc.blocks, function (aBlock) {
      var blockName = aBlock.blockName;
      aBlock.id = _.uniqueId("GB");
      blockIDs.push(aBlock.id);
      var stats = aBlock.stats;
      statItems = statItems.concat(stats);
      _.each(stats, function (statInfo) {
        statInfo.id = _.uniqueId("G");
        statInfo.blockId = aBlock.id;
      });
    });
    // and now make ServerResourcesBlock first for rendering
    if (hadServerResources) {
      statDesc.blocks.unshift(statDesc.blocks.pop());
    }
    _.each(statItems, function (item) {
      infos.push(item);
      infos.byName[item.name] = item;
    });
    infos.blockIDs = blockIDs;

    var infosByTitle = _.groupBy(infos, "title");

    _.each(infos, function (statInfo) {
      if (statInfo.missing || statInfo.bigTitle) {
        return;
      }
      var title = statInfo.title;
      var homonyms = infosByTitle[title];
      if (homonyms.length == 1) {
        return;
      }
      var sameBlock = _.any(homonyms, function (otherInfo) {
        return otherInfo !== statInfo && otherInfo.blockId === statInfo.blockId;
      });
      var blockInfo = _.detect(statDesc.blocks, function (blockCand) {
        return blockCand.id === statInfo.blockId;
      });
      if (!blockInfo) {
        BUG();
      }
      if (sameBlock && blockInfo.columns) {
        var idx = _.indexOf(blockInfo.stats, statInfo);
        if (idx < 0) {
          BUG();
        }
        statInfo.bigTitle = blockInfo.columns[idx % 4] + ' ' + statInfo.title;
      } else {
        statInfo.bigTitle = (blockInfo.bigTitlePrefix || blockInfo.blockName) + ' ' + statInfo.title;
      }
    });

    return {statDesc: statDesc, infos: infos};
  });

  self.statsDescInfoCell = Cell.needing(self.infosCell).compute(function (v, infos) {
    return infos.statDesc;
  }).name("statsDescInfoCell");

  self.graphsConfigurationCell = Cell.compute(function (v) {
    var selectedGraphName = v(v.need(self.smallGraphSelectionCellCell));
    var stats = v.need(self.rawStatsCell);
    var selected;

    var infos = v.need(self.infosCell).infos;
    if (selectedGraphName && (selectedGraphName in infos.byName)) {
      selected = infos.byName[selectedGraphName];
    } else {
      selected = infos[0];
    }

    var auxTS = {};

    var samples = _.clone(stats.stats[stats.mainStatsBlock]);
    _.each(stats.stats, function (subSamples, subName) {
      if (subName === stats.mainStatsBlock) {
        return;
      }
      var timestamps = subSamples.timestamp;
      for (var k in subSamples) {
        if (k == "timestamp") {
          continue;
        }
        samples[k] = subSamples[k];
        auxTS[k] = timestamps;
      }
    });

    if (!samples[selected.name]) {
      selected = _.detect(infos, function (info) {return samples[info.name];}) || selected;
    }

    return {
      interval: stats.interval,
      zoomLevel: v.need(zoomLevel),
      selected: selected,
      samples: samples,
      timestamp: samples.timestamp,
      auxTimestamps: auxTS,
      serverDate: stats.serverDate,
      clientDate: stats.clientDate,
      infos: infos,
      extra: v(self.configurationExtra)
    };
  });

  self.statsNodesCell = Cell.compute(function (v) {
    return v.need(DAL.cells.serversCell).active;
  });

  self.hotKeysCell = Cell.computeEager(function (v) {
    if (!v(self.statsBucketDetails)) {
      // this deals with "no buckets at all" case for us
      return [];
    }
    return v.need(self.rawStatsCell).hot_keys || [];
  });
  self.hotKeysCell.equality = _.isEqual;

  Cell.autonameCells(self);
})(StatsModel);

var maybeReloadAppDueToLeak = (function () {
  var counter = 300;

  return function () {
    if (!window.G_vmlCanvasManager)
      return;

    if (!--counter)
      reloadPage();
  };
})();

;(function (global) {

  var queuedUpdates = [];

  function flushQueuedUpdate() {
    var i = queuedUpdates.length;
    while (--i >= 0) {
      queuedUpdates[i]();
    }
    queuedUpdates.length = 0;
  }

  var shadowSize = 3;

  if (window.G_vmlCanvasManager) {
    shadowSize = 0;
  }

  function renderSmallGraph(jq, options) {
    function reqOpt(name) {
      var rv = options[name];
      if (rv === undefined)
        throw new Error("missing option: " + name);
      return rv;
    }
    var data = reqOpt('data');
    var now = reqOpt('now');
    var plotSeries = buildPlotSeries(data,
                                     reqOpt('timestamp'),
                                     reqOpt('breakInterval'),
                                     reqOpt('timeOffset')).plotSeries;

    var lastY = data[data.length-1];
    var maxString = isNaN(lastY) ? 'N/A' : ViewHelpers.formatQuantity(lastY, options.isBytes ? 1024 : 1000);
    queuedUpdates.push(function () {
      jq.find('#js_small_graph_value').text(maxString);
    });
    if (queuedUpdates.length == 1) {
      setTimeout(flushQueuedUpdate, 0);
    }

    var color = reqOpt('isSelected') ? '#e2f1f9' : '#d95e28';

    var yaxis = {min:0, ticks:0, autoscaleMargin: 0.04}

    if (options.maxY)
      yaxis.max = options.maxY;

    $.plot(jq.find('#js_small_graph_block'),
           _.map(plotSeries, function (plotData) {
             return {color: color,
                     shadowSize: shadowSize,
                     data: plotData};
           }),
           {xaxis: {ticks:0,
                    autoscaleMargin: 0.04,
                    min: now - reqOpt('zoomMillis'),
                    max: now},
            yaxis: yaxis,
            grid: {show:false}});
  }

  global.renderSmallGraph = renderSmallGraph;
})(this);

var GraphsWidget = mkClass({
  initialize: function (largeGraphJQ, smallGraphsContainerJQ, descCell, configurationCell, isBucketAvailableCell) {
    this.largeGraphJQ = largeGraphJQ;
    this.smallGraphsContainerJQ = smallGraphsContainerJQ;

    this.drawnDesc = this.drawnConfiguration = {};
    Cell.subscribeMultipleValues($m(this, 'renderAll'), descCell, configurationCell, isBucketAvailableCell);
  },
  // renderAll (and subscribeMultipleValues) exist to strictly order renderStatsBlock w.r.t. updateGraphs
  renderAll: function (desc, configuration, isBucketAvailable) {
    if (this.drawnDesc !== desc) {
      this.renderStatsBlock(desc);
      this.drawnDesc = desc;
    }
    if (this.drawnConfiguration !== configuration) {
      this.updateGraphs(configuration);
      this.drawnConfiguration = configuration;
    }

    if (!isBucketAvailable) {
      this.unrenderNothing();
      this.largeGraphJQ.html('');
      this.smallGraphsContainerJQ.html('');
      $('#js_analytics .js_current-graph-name').text('');
      $('#js_analytics .js_current-graph-desc').text('');
    }
  },
  unrenderNothing: function () {
    if (this.spinners) {
      _.each(this.spinners, function (s) {s.remove()});
      this.spinners = null;
    }
  },
  renderNothing: function () {
    if (this.spinners) {
      return;
    }
    this.spinners = [
      overlayWithSpinner(this.largeGraphJQ, undefined, undefined, 1)
    ];
    this.smallGraphsContainerJQ.find('#js_small_graph_value').text('?')
  },
  renderStatsBlock: function (descValue) {
    if (!descValue) {
      this.smallGraphsContainerJQ.html('');
      this.renderNothing();
      return;
    }
    this.unrenderNothing();
    renderTemplate('js_new_stats_block', descValue, this.smallGraphsContainerJQ[0]);
    $(this).trigger('menelaus.graphs-widget.rendered-stats-block');
  },
  zoomToSeconds: {
    minute: 60,
    hour: 3600,
    day: 86400,
    week: 691200,
    month: 2678400,
    year: 31622400
  },
  forceNextRendering: function () {
    this.lastCompletedTimestamp = undefined;
  },
  updateGraphs: function (configuration) {
    var self = this;

    if (!configuration) {
      self.lastCompletedTimestamp = undefined;
      return self.renderNothing();
    }

    self.unrenderNothing();

    var nowTStamp = (new Date()).valueOf();
    if (self.lastCompletedTimestamp && nowTStamp - self.lastCompletedTimestamp < 200) {
      // skip this sample as we're too slow
      return;
    }

    var stats = configuration.samples;

    var timeOffset = configuration.clientDate - configuration.serverDate;

    var zoomMillis = (self.zoomToSeconds[configuration.zoomLevel] || 60) * 1000;
    var selected = configuration.selected;
    var now = (new Date()).valueOf();
    if (configuration.interval < 2000) {
      now -= StatsModel.samplesBufferDepth.value * 1000;
    }

    maybeReloadAppDueToLeak();

    var auxTS = configuration.auxTimestamps || {};

    plotStatGraph(self.largeGraphJQ, stats[selected.name], auxTS[selected.name] || configuration.timestamp, {
      color: '#1d88ad',
      verticalMargin: 1.02,
      fixedTimeWidth: zoomMillis,
      timeOffset: timeOffset,
      lastSampleTime: now,
      breakInterval: configuration.interval * 2.5,
      maxY: configuration.infos.byName[selected.name].maxY,
      isBytes: configuration.selected.isBytes
    });

    try {
      var visibleBlockIDs = {};
      _.each($(_.map(configuration.infos.blockIDs, $i)).filter(":has(.js_stats:visible)"), function (e) {
        visibleBlockIDs[e.id] = e;
      });
    } catch (e) {
      debugger
      throw e;
    }

    _.each(configuration.infos, function (statInfo) {
      if (!visibleBlockIDs[statInfo.blockId]) {
        return;
      }
      var statName = statInfo.name;
      var graphContainer = $($i(statInfo.id));
      if (graphContainer.length == 0) {
        return;
      }
      renderSmallGraph(graphContainer, {
        data: stats[statName] || [],
        breakInterval: configuration.interval * 2.5,
        timeOffset: timeOffset,
        now: now,
        zoomMillis: zoomMillis,
        isSelected: selected.name == statName,
        timestamp: auxTS[statName] || configuration.timestamp,
        maxY: configuration.infos.byName[statName].maxY,
        isBytes: statInfo.isBytes
      });
    });

    self.lastCompletedTimestamp = (new Date()).valueOf();

    $(self).trigger('menelaus.graphs-widget.rendered-graphs');
  }
});

var AnalyticsSection = {
  onKeyStats: function (hotKeys) {
    renderTemplate('js_top_keys', _.map(hotKeys, function (e) {
      return $.extend({}, e, {total: 0 + e.gets + e.misses});
    }));
  },
  init: function () {
    var self = this;

    StatsModel.hotKeysCell.subscribeValue($m(self, 'onKeyStats'));
    prepareTemplateForCell('js_top_keys', StatsModel.hotKeysCell);
    StatsModel.displayingSpecificStatsCell.subscribeValue(function (displayingSpecificStats) {
      $('#js_top_keys_block').toggle(!displayingSpecificStats);
    });

    $('#js_analytics .js_block-expander').live('click', function () {
      // this forces configuration refresh and graphs redraw
      self.widget.forceNextRendering();
      StatsModel.configurationExtra.setValue({});
    });

    IOCenter.staleness.subscribeValue(function (stale) {
      $('#js_stats-period-container')[stale ? 'hide' : 'show']();
      $('#js_analytics .js_staleness-notice')[stale ? 'show' : 'hide']();
    });

    (function () {
      var cell = Cell.compute(function (v) {
        var mode = v.need(DAL.cells.mode);
        if (mode != 'analytics') {
          return;
        }

        var allBuckets = v.need(DAL.cells.bucketsListCell);
        var selectedBucket = v(StatsModel.statsBucketDetails);
        return {list: _.map(allBuckets, function (info) {return [info.uri, info.name]}),
                selected: selectedBucket && selectedBucket.uri};
      });
      $('#js_analytics_buckets_select').bindListCell(cell, {
        onChange: function (e, newValue) {
          StatsModel.statsBucketURL.setValue(newValue);
        }
      });
    })();

    (function () {
      var cell = Cell.compute(function (v) {
        var mode = v.need(DAL.cells.mode);
        if (mode != 'analytics') {
          return;
        }

        var allNodes = v(StatsModel.statsNodesCell);
        var statsHostname = v(StatsModel.statsHostname);

        var list;
        if (allNodes) {
          list = _.map(allNodes, function (srv) {
            var name = ViewHelpers.maybeStripPort(srv.hostname, allNodes);
            return [srv.hostname, name];
          });
          // natural sort by full hostname (which includes port number)
          list.sort(mkComparatorByProp(0, naturalSort));
          list.unshift(['', 'All Server Nodes (' + allNodes.length + ')' ]);
        }

        return {list: list, selected: statsHostname};
      });
      $('#js_analytics_servers_select').bindListCell(cell, {
        onChange: function (e, newValue) {
          StatsModel.statsHostname.setValue(newValue || undefined);
        }
      });
    })();

    self.widget = new GraphsWidget(
      $('#js_analytics_main_graph'),
      $('#js_stats_container'),
      StatsModel.statsDescInfoCell,
      StatsModel.graphsConfigurationCell,
      DAL.cells.isBucketsAvailableCell);

    Cell.needing(StatsModel.graphsConfigurationCell).compute(function (v, configuration) {
      return configuration.timestamp.length == 0;
    }).subscribeValue(function (missingSamples) {
      $('#js_stats-period-container').toggleClass('dynamic_missing-samples', !!missingSamples);
    });
    Cell.needing(StatsModel.graphsConfigurationCell).compute(function (v, configuration) {
      var zoomMillis = GraphsWidget.prototype.zoomToSeconds[configuration.zoomLevel] * 1000;
      return Math.ceil(Math.min(zoomMillis, configuration.serverDate - configuration.timestamp[0]) / 1000);
    }).subscribeValue(function (visibleSeconds) {
      $('#js_stats_visible_period').text(isNaN(visibleSeconds) ? '?' : formatUptime(visibleSeconds));
    });

    (function () {
      var selectionCell;
      StatsModel.smallGraphSelectionCellCell.subscribeValue(function (cell) {
        selectionCell = cell;
      });

      $(".js_analytics-small-graph").live("click", function (e) {
        // don't intercept right arrow clicks
        if ($(e.target).is(".js_right-arrow, .js_right-arrow *")) {
          return;
        }
        e.preventDefault();
        var graphParam = this.getAttribute('data-graph');
        if (!graphParam) {
          debugger
          throw new Error("shouldn't happen");
        }
        if (!selectionCell) {
          return;
        }
        selectionCell.setValue(graphParam);
        self.widget.forceNextRendering();
      });
    })();

    (function () {
      function handler() {
        var val = effectiveSelected.value;
        val = val && val.name;
        $('.js_analytics-small-graph.dynamic_selected').removeClass('dynamic_selected');
        if (!val) {
          return;
        }
        $(_.filter($('.js_analytics-small-graph[data-graph]'), function (el) {
          return String(el.getAttribute('data-graph')) === val;
        })).addClass('dynamic_selected');
      }
      var effectiveSelected = Cell.compute(function (v) {return v.need(StatsModel.graphsConfigurationCell).selected});
      effectiveSelected.subscribeValue(handler);
      $(self.widget).bind('menelaus.graphs-widget.rendered-stats-block', handler);
    })();

    $(self.widget).bind('menelaus.graphs-widget.rendered-graphs', function () {
      var graph = StatsModel.graphsConfigurationCell.value.selected;
      $('#js_analytics .js_current-graph-name').text(graph.bigTitle || graph.title);
      $('#js_analytics .js_current-graph-desc').text(graph.desc);
    });

    $(self.widget).bind('menelaus.graphs-widget.rendered-stats-block', function () {
      $('#js_stats_container').hide();
      _.each($('.js_analytics-small-graph:not(.dynamic_dim)'), function (e) {
        e = $(e);
        var graphParam = e.attr('data-graph');
        if (!graphParam) {
          debugger
          throw new Error("shouldn't happen");
        }
        var ul = e.find('.js_right-arrow .js_inner').need(1);

        var params = {sec: 'analytics', statsBucket: StatsModel.statsBucketDetails.value.uri};
        var aInner;

        if (!StatsModel.displayingSpecificStatsCell.value) {
          params.statsStatName = graphParam;
          aInner = "show by server";
        } else {
          params.graph = StatsModel.statsStatName.value;
          params.statsHostname = graphParam.slice(1);
          aInner = "show this server";
        }

        ul[0].appendChild(jst.analyticsRightArrow(aInner, params));
      });
      $('#js_stats_container').show();
    });

    StatsModel.displayingSpecificStatsCell.subscribeValue(function (displayingSpecificStats) {
      displayingSpecificStats = !!displayingSpecificStats;
      $('#js_analytics .js_when-normal-stats').toggle(!displayingSpecificStats);
      $('#js_analytics .js_when-specific-stats').toggle(displayingSpecificStats);
    });

    StatsModel.specificStatTitleCell.subscribeValue(function (val) {
      var text = val || '?';
      $('.js_specific-stat-description').text(text);
    });
  },
  onLeave: function () {
    setHashFragmentParam("zoom", undefined);
    StatsModel.statsHostname.setValue(undefined);
    StatsModel.statsBucketURL.setValue(undefined);
    StatsModel.selectedGraphNameCell.setValue(undefined);
    StatsModel.statsStatName.setValue(undefined);
  },
  onEnter: function () {
  }
};


text:
import asciiTable

class table_T_S_I_V_(asciiTable.asciiTable):
	pass

redpajama_set_name: RedPajamaGithub


text:
var React = require('react');
var merge = require('react/lib/merge');
var ActiveState = require('../mixins/ActiveState');
var Navigation = require('../mixins/Navigation');

function isLeftClickEvent(event) {
  return event.button === 0;
}

function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}

/**
 * <Link> components are used to create an <a> element that links to a route.
 * When that route is active, the link gets an "active" class name (or the
 * value of its `activeClassName` prop).
 *
 * For example, assuming you have the following route:
 *
 *   <Route name="showPost" path="/posts/:postID" handler={Post}/>
 *
 * You could use the following component to link to that route:
 *
 *   <Link to="showPost" params={{ postID: "123" }} />
 *
 * In addition to params, links may pass along query string parameters
 * using the `query` prop.
 *
 *   <Link to="showPost" params={{ postID: "123" }} query={{ show:true }}/>
 */
var Link = React.createClass({

  displayName: 'Link',

  mixins: [ ActiveState, Navigation ],

  propTypes: {
    activeClassName: React.PropTypes.string.isRequired,
    to: React.PropTypes.string.isRequired,
    params: React.PropTypes.object,
    query: React.PropTypes.object,
    onClick: React.PropTypes.func
  },

  getDefaultProps: function () {
    return {
      activeClassName: 'active'
    };
  },

  handleClick: function (event) {
    var allowTransition = true;
    var clickResult;

    if (this.props.onClick)
      clickResult = this.props.onClick(event);

    if (isModifiedEvent(event) || !isLeftClickEvent(event))
      return;

    if (clickResult === false || event.defaultPrevented === true)
      allowTransition = false;

    event.preventDefault();

    if (allowTransition)
      this.transitionTo(this.props.to, this.props.params, this.props.query);
  },

  /**
   * Returns the value of the "href" attribute to use on the DOM element.
   */
  getHref: function () {
    return this.makeHref(this.props.to, this.props.params, this.props.query);
  },

  /**
   * Returns the value of the "class" attribute to use on the DOM element, which contains
   * the value of the activeClassName property when this <Link> is active.
   */
  getClassName: function () {
    var className = this.props.className || '';

    if (this.isActive(this.props.to, this.props.params, this.props.query))
      className += ' ' + this.props.activeClassName;

    return className;
  },

  render: function () {
    var props = merge(this.props, {
      href: this.getHref(),
      className: this.getClassName(),
      onClick: this.handleClick
    });

    return React.DOM.a(props, this.props.children);
  }

});

module.exports = Link;


text:
require('./vendor');
require('./index');
require('angular-mocks');

var testsContext = require.context('.', true, /Spec$/);
testsContext.keys().forEach(testsContext);


text:
package com.lchli.angithub;

import android.app.Application;

import com.apkfuns.logutils.LogUtils;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.shell.MainReactPackage;
import com.lchli.angithub.common.appEnv.AppEnvironmentFactory;
import com.lchli.angithub.common.utils.ContextProvider;
import com.lchli.angithub.common.utils.LogExt;
import com.lchli.angithub.common.utils.UniversalLog;

import java.util.Arrays;
import java.util.List;

/**
 * Created by lchli on 2016/10/29.
 */

public class GithubApp extends Application implements ReactApplication {

  @Override
  public void onCreate() {
    super.onCreate();
    ContextProvider.initContext(this);
    UniversalLog.LOG_FLAG= AppEnvironmentFactory.ins().logFlag();
    UniversalLog.get().setLogExt(new LogImpl());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());

    registerReactInstanceEventListener();
    //

  }

  private static class LogImpl implements LogExt {
    @Override
    public void e(String tag, String msg) {
      LogUtils.e(tag,msg);
    }

    @Override
    public void e(String tag, String msg, Throwable tr) {
      LogUtils.e(tag,msg);
    }

    @Override
    public void e(String msg) {
      LogUtils.e(msg);
    }

  }

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
              new MainReactPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  private void registerReactInstanceEventListener() {
    mReactNativeHost.getReactInstanceManager().addReactInstanceEventListener(mReactInstanceEventListener);
  }
  private void unRegisterReactInstanceEventListener() {
    mReactNativeHost.getReactInstanceManager().removeReactInstanceEventListener(mReactInstanceEventListener);
  }
  private final ReactInstanceManager.ReactInstanceEventListener mReactInstanceEventListener = new ReactInstanceManager.ReactInstanceEventListener() {
    @Override
    public void onReactContextInitialized(ReactContext context) {
      mReactContext = context;
    }
  };

  private ReactContext mReactContext;

  public ReactContext getReactContext() {
    return mReactContext;
  }
}


text:
SALE

NEW

White Blouse Armani

Scroll to product details, material & care and sizing

$124.00

                     Add to cart
                     Add to wishlist

Product details

White lace top, woven, has a round neck, short sleeves, has knitted lining attached

Material & care

Polyester

Machine wash

Size & Fit

Regular fit

The model (height 5'8" and chest 33") is wearing a size S

Define style this season with Armani's new range of trendy tops, crafted with intricate details. Create a chic statement look by teaming this lace number with skinny jeans and pumps.

Show it to your friends


text:
/*
 * module dependencies
 */
var fs = require('fs');

function parseRangeHeader(req) {
  var info = {};
  console.log(req.headers);
  if(req.headers && req.headers['content-range']) {
    var ranges = req.headers['content-range'].match(/bytes\s(\*|\d+)-?(\d+)?\/(\d+)/i);
    if(ranges && ranges[1] && ranges[3] && !ranges[2]) {
      info.type = "info";
      info.size = Number(ranges[3]);
      info.stop = Number(ranges[3]);
    } else if(ranges && ranges[1] && ranges[2] && ranges[3]) {
      info.type = "data";
      info.start = Number(ranges[1]);
      info.stop = Number(ranges[2]);
      info.size = Number(ranges[3]);
    } else {
      return null;
    }
  } else {
    return null;
  }
  return info;
}

var UploadRequest = module.exports = function(req, res, next, options) {
  req.pause();
  this.req = req;
  this.res = res;
  this.options = options;
  this.next = next;
  this.range = parseRangeHeader(req);
  this.mongodb = options.mongodb;
  this.mongo = options.mongo;
  this.requestSize = Number(req.headers['content-length']);
  if(!this.range) {
    this.range = {"start":0,"stop":this.requestSize-1,size:this.requestSize};
  }
  this.received = 0;
  this.directory = options.directory || "/tmp";
  console.log(this.directory);
  this.fname = "";
  var m;
  if (m = (req.headers['content-disposition'] || req.headers['x-content-disposition']).match(/name="([^"]+)"/i)) {
    this.name = m[1];
  }
  if (m = (req.headers['content-disposition'] || req.headers['x-content-disposition']).match(/filename="([^"]+)"/i)) {
    this.fname = m[1];
  }
  this.id = req.headers['etag'] + this.fname;
  console.log("New upload request, range start:",this.range.start,"stop:",this.range.stop,"size:",this.range.size,"chunk:",this.requestSize);
};

UploadRequest.prototype.execute = function() {
  var self = this, stream, outputStream;
  stream = this.req;
  console.log("Creating write stream to ",this.directory+'/'+this.id);
  outputStream = this.writeStream = fs.createWriteStream(this.directory+'/'+this.id);
  stream.on('data', function(d) {
    var drain = outputStream.write(d);
    if(!drain) {
      stream.pause();
    }
  });

  outputStream.on('drain', function() {
    stream.resume();
  });
  outputStream.on('close', function() {
    self.received = outputStream.bytesWritten;
    self.respond();
  });

  stream.on('end', function() {
    outputStream.end();
  });
  stream.resume();
};

UploadRequest.prototype.getFileInfo = function(callback) {
  fs.stat(this.directory+'/'+this.id, function(err, stats) {
    return callback(err, stats);
  });
}

UploadRequest.prototype.respond = function() {
  var self = this;
  if(this.received >= this.range.size) {
    console.log("We received the whole file");
    this.req.files = this.req.files || {};
    var file = this.req.files[this.name] = {};
    this.getFileInfo(function(err, stats) {
      if(err) {
        return this.next(err);
      }
      file.size = stats.size;
      file.path = self.directory + '/' + self.id;
      file.name = self.id;
      file._writeStream = self.writeStream;
      console.log("File completed: ",file);
      return self.next();
    });
  } else if(this.received == this.requestSize && this.received < this.range.size) {
    this.res.set('Range','0-'+(this.range.start+this.received));
    this.res.writeHead(308, 'Resume incomplete');
    this.res.end();
  }
};


text:
using System.Web.Http;

namespace NHS111.Domain.DOS.Api
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}


text:
#pragma once

#include <thrust/detail/config.h>
#include <thrust/copy.h>

namespace grapple
{

template<typename InputIterator, typename OutputIterator>
OutputIterator copy(grapple_system &exec,
                    InputIterator first,
                    InputIterator last,
                    OutputIterator result)
{
    using thrust::system::detail::generic::select_system;

    typedef typename thrust::iterator_system<InputIterator>::type System1;
    typedef typename thrust::iterator_system<OutputIterator>::type System2;

    System1 system1;
    System2 system2;

    exec.start(THRUST_COPY);
    OutputIterator ret = thrust::copy(exec.policy(select_system(system1,system2)), first, last, result);
    exec.stop();

    return ret;
}

template<typename InputIterator, typename Size, typename OutputIterator>
OutputIterator copy_n(grapple_system &exec,
                      InputIterator first,
                      Size n,
                      OutputIterator result)
{
    using thrust::system::detail::generic::select_system;

    typedef typename thrust::iterator_system<InputIterator>::type System1;
    typedef typename thrust::iterator_system<OutputIterator>::type System2;

    System1 system1;
    System2 system2;

    exec.start(THRUST_COPY_N);
    OutputIterator ret = thrust::copy_n(exec.policy(select_system(first,result)), first, n, result);
    exec.stop();

    return ret;
}

template<typename InputIterator, typename OutputIterator, typename Predicate>
OutputIterator copy_if(grapple_system &exec,
                       InputIterator first,
                       InputIterator last,
                       OutputIterator result,
                       Predicate pred)
{
    exec.start(THRUST_COPY_IF);
    OutputIterator ret = thrust::copy_if(exec.policy(get_system(first,result)), first, last, result, pred);
    exec.stop();

    return ret;
}

template<typename InputIterator1, typename InputIterator2, typename OutputIterator, typename Predicate>
OutputIterator copy_if(grapple_system &exec,
                       InputIterator1 first,
                       InputIterator1 last,
                       InputIterator2 stencil,
                       OutputIterator result,
                       Predicate pred)
{
    exec.start(THRUST_COPY_IF);
    OutputIterator ret = thrust::copy_if(exec.policy(get_system(first,stencil,result)), first, last, stencil, result, pred);
    exec.stop();

    return ret;
}

}


text:
<?php

namespace App\Modules\Diag\Providers;

use App;
use Illuminate\Support\ServiceProvider;
use Lang;
use View;

class ModuleServiceProvider extends ServiceProvider
{

    public function register()
    {
        App::register('App\Modules\Diag\Providers\RouteServiceProvider');

        Lang::addNamespace('diag', realpath(__DIR__.'/../Resources/Lang'));

        View::addNamespace('diag', realpath(__DIR__.'/../Resources/Views'));
    }
}


text:
sX,sY = guiGetScreenSize()

Infobox = {
["Window"] = false,
["Label"] = {},
["Image"] = {},
}

Infobox["Window"] = new(CDxWindow, "Information", 310, 137, true, false, "Center|Top")
Infobox["Image"][1] = new(CDxImage, 5, 5, 95, 95, "res/images/infobox/info.png",tocolor(255,255,255,255), Infobox["Window"])
Infobox["Label"][1] = new(CDxLabel, "", 105, 0, 190, 110, tocolor(255,255,255,255), 1.2, "default", "center", "center", Infobox["Window"])

Infobox["Window"]:add(Infobox["Image"][1])
Infobox["Window"]:add(Infobox["Label"][1])

Infobox["Window"]:setReadOnly(true)

function destroyInfoBox()
	Infobox["Window"]:hide()
end

function showInfoBox(action, text, iTime, sSound)
	Infobox["Window"]:hide()
	Infobox["Image"][1]:loadImage("res/images/infobox/"..action..".png")

    local sound = "res/sounds/hud/info_"..action..".ogg";

	if(sSound) then
		sound = "res/sounds/hud/info_"..sSound..".ogg";
	end

    if not(fileExists(sound)) then
        sound = nil;
    end

	if(toboolean(config:getConfig("use_old_plop_sound"))) then
		sound = "res/sounds/poke.ogg";
	end
	-- Text --

	text = string.gsub(text, "\\ae", "ä")
	text = string.gsub(text, "\\ue", "ü")
	text = string.gsub(text, "\\oe", "ö")

	outputConsole(action..": "..text)

	Infobox["Label"][1]:setText(text)
	if (not (isTimer(Infobox["Timer"])) ) then
		Infobox["Window"]:show(sound)
		Infobox["Timer"] = setTimer(destroyInfoBox, iTime or 5000, 1)
	else
		killTimer(Infobox["Timer"])
		Infobox["Window"]:show(sound)
		Infobox["Timer"] = setTimer(destroyInfoBox, iTime or 5000, 1)
	end
end
addEvent("infoBoxShow", true)
addEventHandler("infoBoxShow", getLocalPlayer(), showInfoBox)


text:
layout: page_v2
title: AdUnit - iOS
description: AdUnit - iOS
top_nav_section: prebid-mobile
nav_section: prebid-mobile
sidebarType: 2
---

# AdUnit: NSObject
{: .notoc}

The AdUnit class is the superclass of the [BannerAdUnit](/prebid-mobile/pbm-api/ios/pbm-banneradunit-ios.html) and [InterstitialAdUnit](/prebid-mobile/pbm-api/ios/pbm-bannerinterstitialadunit-ios.html) classes.

- TOC
 {:toc}

---

## Object

### AdUnit

Create a new Banner Ad Unit or Interstitial Ad Unit with a Prebid Server configuration ID and a banner size if applicable.

**Parameters**

`configId`:  String containing the Prebid Server configuration ID. Note: this is a Prebid Server [impression-level stored request ID](/prebid-server/features/pbs-storedreqs.html).

`size:`: CGSize conatining width and height of the AdUnit.

**Properties**

`prebidConfigId`: String containing the Prebid Server configuration ID.

`adSizes`: An Array of CGSizes to be used for AdUnit sizes.

#### pbAdSlot

PB Ad Slot is an identifier tied to the placement the ad will be delivered in. The use case for PB Ad Slot is to pass to exchange an ID they can use to tie to reporting systems or use for data science driven model building to match with impressions sourced from alternate integrations. A common ID to pass is the ad server slot name.

`adUnit.ortb2Imp.ext.data.pbadslot = "/1111111/homepage/med-rect-2"`

---

## Methods

### fetchDemand

Trigger a call to Prebid Server to retrieve demand for this Prebid Mobile ad unit.

#### Mopub or GAM

By default, Prebid SDK uses inflection to determine the publisher ad server, one of Mopub or Google Ad Manager (GAM), to convert Prebid's targeting keys (PBS bid keys, host and cache key) to trigger targeted line items. To render ads in ad servers other than Mopub or GAM, use the next section's 3rd party ad server support feature.

**Parameters**

`adObject`: adServer object to which the Prebid keys need to be attached.

`completion`: Closure which receives one argument, the enum `ResultCode`. There is no return value.

#### 3rd Party Ad Server

The default ad servers for Prebid's Mobile SDK are MoPub and GAM. The SDK can be expanded to include support for 3rd party ad servers through the fetchDemand function. This function returns the Prebid Server bidder key/values (targeting keys), which can then be passed to the ad server of choice.

In this mode, the publisher will be responsible for the following actions:
* Call fetchDemand with extended targetingDict callback
* Retrieve targeting keys from extended fetchDemand function
* Convert targeting keys into the format for your ad server
* Pass converted keys to your ad server
* Render ad with Prebid Universal Creative or custom renderer

**Function callbacks**

* `ResultCode`: enum [result codes](https://docs.prebid.org/prebid-mobile/pbm-api/ios/pbm-api-result-codes-ios.html)
* `targetingDict`: [Prebid Server Response targeting keys](https://docs.prebid.org/prebid-server/endpoints/openrtb2/pbs-endpoint-auction.html#targeting)

```
func fetchDemand(completion: @escaping(_ result: ResultCode, _ kvResultDict: [String : String]?) -> Void)
```

Examples:

Swift
```swift
func loadBanner() {

    //adUnit is BannerAdUnit type
    adUnit.fetchDemand { [weak self] (resultCode: ResultCode, targetingDict: [String : String]?) in

        self?.adServerRequest.customTargeting = targetingDict
        self?.adServerBanner.load(self?.adServerRequest)
    }
}

func loadRewardedVideo() {
    let adUnit = RewardedVideoAdUnit(configId: "1001-1")
    adUnit.fetchDemand { [weak self] (resultCode: ResultCode, targetingDict: [String : String]?) in

        //Publisher should provide support for converting keys into format of 3rd party ad server and loading ads
        let keywords = convertDictToAdServerKeywords(dict: targetingDict)
        AdServerLoadAds.loadAd(withAdUnitID: "46d2ebb3ccd340b38580b5d3581c6434", keywords: keywords)
    }
}
```

Objective-C
```objective-C
-(void) loadAdServerBanner {

    //adUnit is BannerAdUnit Type
    [self.adUnit fetchDemandWithCompletion:^(enum ResultCode resultCode, NSDictionary<NSString *,NSString *> * _Nullable targetingDict) {

        [self.request setCustomTargeting:targetingDict];
        [self.adServerView loadRequest:self.request];
    }];
}

-(void) loadAdServerRewardedVideo {

    //adUnit is RewardedVideoAdUnit Type
    [adUnit fetchDemandWithCompletion:^(enum ResultCode resultCode, NSDictionary<NSString *,NSString *> * _Nullable targetingDict) {

        NSString *keywords = [Utils.shared convertDictToMoPubKeywordsWithDict:targetingDict];
        [adServerRewardedVideo loadRewardedVideoAdWithAdUnitID:@"46d2ebb3ccd340b38580b5d3581c6434" keywords:keywords ];

    }];
}
```

### addUserKeyword

Obtains the user keyword and value for targeting of a Prebid Mobile ad unit. If the key already exists the value will be appended to the `customKeywords` property. No duplicates will be added.

**Parameters**

`key`: A String to be used to check if an existing value exists in the `customKeywords` property.

`value`: A String to be appended to the `customKeywords` property.

### removeUserKeyword
Remove a key and all its associated values from `customKeywords` of a given Prebid Mobile ad unit.

**Parameters**

`forKey`: A string containing the key to remove from `customKeywords`.

### clearUserKeywords
Remove all keys and all values from a given Prebid Mobile ad unit.

### setAutoRefreshMillis
If set on a given Prebid Mobile ad unit, the `fetchDemand` function will be called every `periodMillis` until `stopAutoRefresh` is called. Each call to `fetchDemand` will invoke the `onComplete` function. This refresh only pertains to Prebid Mobile and not to any ad server refresh processes. It is suggested that the adServes refresh be turned off.

### startAutoRefresh

Starts the auto-refresh behavior for a given Prebid Mobile ad unit.

### stopAutoRefresh
Halts the auto-refresh behavior for a given Prebid Mobile ad unit. If no auto-refresh behavior has been set, `stopAutoRefresh` will be ignored.

### addContextKeyword
Ad Unit context keywords object is a free form list of comma separated keywords about the app as defined in app.keyword in OpenRTB 2.5. The `addContextKeyword` function adds a single keyword to the ad unit.

```
func addContextKeyword(_ newElement: String)
```

### addContextKeywords
Ad Unit context keywords object is a free form list of comma separated keywords about the app as defined in app.keyword in OpenRTB 2.5. The `addContextKeywords` function adds a multiple keyword to the ad unit.

```
func addContextKeywords(_ newElements: Set<String>)
```

### removeContextKeyword

```
func removeContextKeyword(_ element: String)
```

### clearContextKeywords

```
func clearContextKeywords()
```

### App Content

The `ContentObject` alows you to provide more details about content whithin the app. All proeprties provided to the `ContentObject` will be sent in the `app.content` field of the bid request.

```
func setAppContent(_ appContent: ContentObject)
```

```
func getAppContent() -> ContentObject?
```

```
func clearAppContent()
```

### App Content Data

Using the following methods you can add `app.content.data` objects to the bid requests.

```
func addAppContentData(_ dataObjects: [ContentDataObject])
```

```
func removeAppContentData(_ dataObject: ContentDataObject)
```

```
func clearAppContentData()
```

### User Data

Using the following methods you can add `user.data` objects to the bid requests.

```
func getUserData() -> [PBMORTBContentData]?
```
```
func addUserData(_ userDataObjects: [PBMORTBContentData])
```

```
func removeUserData(_ userDataObject: PBMORTBContentData)
```

```
func clearUserData()
```

### Data Object

The Data object is free form data (also known as First Party Data) supplied by the publisher to provide additional targeting of the user or inventory context, used primarily for striking PMP (Private MarketPlace) deals with Advertisers. Data supplied in the data parameters are typically not sent to DSPs whereas information sent in non-data objects (i.e. `setYearOfBirth`, `setGender`, etc.) will be. Access to FPD can be limited to a supplied set of Prebid bidders via an access control list.

Data is broken up into two different data types:
* User
  * Global in scope only
* Inventory (context)
  * Global scope
  * Ad Unit grain

The first party inventory context below will apply to the specic ad unit the data object is applied to. For global user or inventory context level first party data, refer to [first party data section of the Targeting](/prebid-mobile/pbm-api/ios/pbm-targeting-ios.html#first-party-data) page.

#### addContextData
```
func addContextData(key: String, value: String)
```

**Parameters**
`key`: string containing the key for the specific data object
`value`: String containing the value for the supplied key

#### updateContextData
```
func updateContextData(key: String, value: Set<String>)
```

**Parameters**
`key`: string containing the key for the specific data object
`value`: String containing the value for the supplied key

#### removeContextData
```
func removeContextData(forKey: String)
```

**Parameters**
`key`: string containing the key for the specific data object
`value`: String containing the value for the supplied key

#### clearContextData
```
func clearContextData()
```

## Examples

**fetchDemand**

**Swift**

 func loadDFPBanner(bannerUnit : AdUnit){

     let bannerUnit = BannerAdUnit(configId: "6ace8c7d-88c0-4623-8117-75bc3f0a2e45", size: CGSize(width: 300, height: 250))
     bannerUnit.ortb2Imp.ext.data.pbadslot = "/1111111/homepage/med-rect-2"`

    let dfpBanner = DFPBannerView(adSize: kGADAdSizeMediumRectangle)
    dfpBanner.adUnitID = "/19968336/PriceCheck_300x250"
    dfpBanner.rootViewController = self

    bannerView.addSubview(dfpBanner)
    request.testDevices = [ kGADSimulatorID ]

    // Do any additional setup after loading the view, typically from a nib.
    bannerUnit.fetchDemand(adObject: self.request) { (ResultCode) in
        print("Google Ad Manager banner bids fetch successfull")
        dfpBanner.load(self.request)
    }
}

**Objective-C**

```
-(void) loadDFPBanner {

    self.bannerUnit = [[BannerAdUnit alloc] initWithConfigId:@"6ace8c7d-88c0-4623-8117-75bc3f0a2e45" size:CGSizeMake(300, 250)];
    [self.bannerUnit setAutoRefreshMillisWithTime:35000];
    self.dfpView = [[DFPBannerView alloc] initWithAdSize:kGADAdSizeMediumRectangle];
    self.dfpView.rootViewController = self;
    self.dfpView.adUnitID = @"/19968336/PrebidMobileValidator_Banner_All_Sizes";
    self.dfpView.delegate = self;
    [self.bannerView addSubview:self.dfpView];
    self.dfpView.backgroundColor = [UIColor redColor];
    self.request = [[DFPRequest alloc] init];
    self.request.testDevices = @[kDFPSimulatorID];

    [self.bannerUnit fetchDemandWithAdObject:self.request completion:^(enum ResultCode result) {
        NSLog(@"Prebid demand result %ld", (long)result);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dfpView loadRequest:self.request];
        });
    }];
}
```
---
**addKeyword**

```
bannerUnit.addKeyword(key:"Sample", value:"Value to add")
```

**removeUserKeyword**

```
bannerUnit.removeUserKeyword(forKey:"sample")
```

**clearUserKeywords**

```
bannerUnit.clearUserKeywords()
```

**setAutoRefreshMillis**

```
bannerUnit.setAutoRefreshMillis(time:Double)
```
**stopAutoRefresh**

```
bannerUnit.stopAutoRefresh()
```

**addContextKeyword**
```
bannerAdUnit.addContextKeyword("adunitContextKeywordValue1")
bannerAdUnit.addContextKeyword("adunitContextKeywordValue2")
bannerAdUnit.addContextKeyword("adunitContextKeywordValue3")
```

**addContextData**
```
bannerAdUnit.addContextData(key: "adunitContextDataKey1", value: "adunitContextDataValue1")
```

## Related Topics

- [Prebid Mobile API - iOS]({{site.baseurl}}/prebid-mobile/pbm-api/ios/pbm-api-ios.html)
- [Banner Ad Unit](/prebid-mobile/pbm-api/ios/pbm-banneradunit-ios.html)
- [Interstitial Ad Unit]({{site.baseurl}}/prebid-mobile/pbm-api/ios/pbm-bannerinterstitialadunit-ios.html)
- [Result Codes]({{site.baseurl}}/prebid-mobile/pbm-api/ios/pbm-api-result-codes-ios.html)
- [Targeting Parameters]({{site.baseurl}}/prebid-mobile/pbm-api/ios/pbm-targeting-ios.html)
- [Prebid Mobile Object]({{site.baseurl}}/prebid-mobile/pbm-api/ios/prebidmobile-object-ios.html)
- [Prebid Mobile API - Android]({{site.baseurl}}/prebid-mobile/pbm-api/android/pbm-api-android.html)


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'econth-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.css']
})
export class ReportsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
package org.jupyter.server.kernels;

public interface KernelCodegenInfo {
    /**
     * Supplies the string representing the symbols to start a single line comment in the language of the kernel.
     * @return A string representing the beginning of a single line comment
     */
    String getLanguageComment();

    /**
     * The name of the kernel to define in the notebook json. This should be
     * the value used to define the kernel.json for your kernel.
     * @return The name of the kernel
     */
    String getName();

    /**
     * The display name of the kernel within the Jupyter Notebook
     * @return A display name of the kernel
     */
    String getDisplayName();

    /**
     * The language of the code executed within the kernel
     * @return The language of the code executed within the kernel
     */
    String getLanguage();

}


text:
using MahApps.Metro.Controls;
using System.Windows;
using System.Windows.Input;

namespace TweetGazer.Behaviors
{
    public static class ReadMoreBehavior
    {
        [AttachedPropertyBrowsableForType(typeof(ProgressRing))]
        public static ICommand GetCommand(DependencyObject element)
        {
            if (element == null)
            {
                return null;
            }

            return element.GetValue(CommandProperty) as ICommand;
        }

        [AttachedPropertyBrowsableForType(typeof(ProgressRing))]
        public static void SetCommand(DependencyObject element, ICommand value)
        {
            if (element == null)
            {
                return;
            }

            element.SetValue(CommandProperty, value);
        }

        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(ReadMoreBehavior), new PropertyMetadata(Command_Changed));

        private static void Command_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var element = sender as ProgressRing;
            var command = e.NewValue as ICommand;
            if (element == null || command == null)
            {
                return;
            }

            element.Loaded += (s, eventArgs) =>
            {
                element.IsActive = true;
                command.Execute(GetCommandParameter(element));
            };
        }

        [AttachedPropertyBrowsableForType(typeof(ProgressRing))]
        public static object GetCommandParameter(DependencyObject element)
        {
            if (element == null)
            {
                return null;
            }

            return element.GetValue(CommandParameterProperty) as object;
        }

        [AttachedPropertyBrowsableForType(typeof(ProgressRing))]
        public static void SetCommandParameter(DependencyObject element, object value)
        {
            if (element == null)
            {
                return;
            }

            element.SetValue(CommandParameterProperty, value);
        }

        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(ReadMoreBehavior), new PropertyMetadata(null));
    }
}


text:
<?php
class carro{
	public function listar(){
		$dato=array("table"=>"cl_carro");
		include_once("helpers.php");
		$helper=new Helpers();
		return $helper->select( $dato );
	}
	public function listarCarrosDisponibles(){
		$data["table"]="cl_carro as c";
		$data["condicion"]=" where c.id not in ( select id_cl_carro from cl_ruta )";
		//select * from cl_carro as c  where c.id not in ( select id_cl_carro from cl_ruta )
		include_once("helpers.php");
		$helper=new Helpers();
		return $helper->select( $data );
	}
	public function editar($data){
		$pre=array("table"=>"cl_carro","condicion"=>" where id=".$data["id"]);
		include_once("helpers.php");
		$helper=new Helpers();
		return $helper->select( $pre )->fetch();
	}
	public function insert($data){
		$data["table"]="cl_carro";
		//id	placa_delantera	placa_lateral	modelo	marca	ubicacion
		$data["values"]=" '$data[u_placa_delantera]' , '$data[u_placa_lateral]', '$data[u_modelo]', '$data[u_marca]', '$data[u_ubicacion]' ";
		include_once("helpers.php");
		$helper=new Helpers();
		return $helper->insert( $data );
	}
	public function update($data){
		$data["table"]="cl_carro";
		$data["condicion"]=" where id=".$data['u_id'];
		$data["set"]=" marca='$data[u_marca]' , modelo='$data[u_modelo]', placa_delantera='$data[u_placa_delantera]', placa_lateral='$data[u_placa_lateral]' ";
		include_once("helpers.php");
		$helper=new Helpers();
		return $helper->update( $data );
	}
	public function eliminar($data){
		$data["table"]="cl_carro";
		$data["condicion"]=" where id=".$data['id'];
		$dato=array("table"=>"cl_carro");
		include_once("helpers.php");
		$helper=new Helpers();
		return $helper->delete( $data );
	}

}
?>


text:
<!DOCTYPE html>
<script src="../../resources/js-test.js"></script>
<body>
<script>
description('EventTarget.addEventListener and EventTarget.removeEventLister should throw on invalid arguments.');

function listener(event)
{
}

debug('Signature:')
debug('void addEventListener(DOMString type, EventListener listener, optional boolean useCapture)');
// FIXME: should throw on missing arguments: http://crbug.com/353484
// shouldThrow('document.addEventListener()');
// shouldThrow('document.addEventListener("foo")');
var AddEventListenerNoArguments = 656;
shouldBeFalse('internals.isUseCounted(document, AddEventListenerNoArguments)');
shouldBe('document.addEventListener()', 'undefined');
shouldBeTrue('internals.isUseCounted(document, AddEventListenerNoArguments)');
var AddEventListenerOneArgument = 657;
shouldBeFalse('internals.isUseCounted(document, AddEventListenerOneArgument)');
shouldBe('document.addEventListener("foo")', 'undefined');
shouldBeTrue('internals.isUseCounted(document, AddEventListenerOneArgument)');
shouldNotThrow('document.addEventListener("foo", listener)');
shouldNotThrow('document.addEventListener("", listener)');
shouldNotThrow('document.addEventListener("", function(){})');
shouldNotThrow('document.addEventListener("bar", listener, false)');
shouldNotThrow('document.addEventListener("bar", listener, true)');
// null
shouldBe('document.addEventListener(null)', 'undefined');
shouldNotThrow('document.addEventListener(null, listener)'); // converted to "null"
// FIXME: throw on |null|: http://crbug.com/249598
// shouldThrow('document.addEventListener("foo", null)');
shouldBe('document.addEventListener("foo", null)', 'undefined');
shouldNotThrow('document.addEventListener("zork", listener, null)');
// undefined
// FIXME: behavior of undefined for mandatory arguments is unclear, but
// probably should throw
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=23532
shouldBe('document.addEventListener(undefined)', 'undefined');
// shouldThrow('document.addEventListener(undefined, listener)');
// shouldThrow('document.addEventListener("foo", undefined)');
shouldBe('document.addEventListener(undefined, listener)', 'undefined');
shouldBe('document.addEventListener("foo", undefined)', 'undefined');
shouldNotThrow('document.addEventListener("zork", listener, undefined)');

debug('');
debug('Signature:');
debug('void removeEventListener(DOMString type, EventListener listener, optional boolean useCapture)');
// FIXME: should throw on missing arguments: http://crbug.com/353484
// shouldThrow('document.removeEventListener()');
// shouldThrow('document.removeEventListener("foo")');
var RemoveEventListenerNoArguments = 658;
shouldBeFalse('internals.isUseCounted(document, RemoveEventListenerNoArguments)');
shouldBe('document.removeEventListener()', 'undefined');
shouldBeTrue('internals.isUseCounted(document, RemoveEventListenerNoArguments)');
var RemoveEventListenerOneArgument = 659;
shouldBeFalse('internals.isUseCounted(document, RemoveEventListenerOneArgument)');
shouldBe('document.removeEventListener("foo")', 'undefined');
shouldBeTrue('internals.isUseCounted(document, RemoveEventListenerOneArgument)');
shouldNotThrow('document.removeEventListener("foo", listener)');
shouldNotThrow('document.removeEventListener("foo", listener, true)');
shouldNotThrow('document.removeEventListener("bar", listener, false)');
shouldNotThrow('document.removeEventListener("bar", listener, false)');
shouldNotThrow('document.removeEventListener("bar", listener, true)');
// null
shouldBe('document.removeEventListener(null)', 'undefined');
shouldNotThrow('document.removeEventListener(null, listener)'); // converted to "null"
// FIXME: throw on |null|: http://crbug.com/249598
// shouldThrow('document.removeEventListener("foo", null)');
shouldBe('document.removeEventListener("foo", null)', 'undefined');
shouldNotThrow('document.removeEventListener("zork", listener, null)');
// undefined
// FIXME: behavior of undefined for mandatory arguments is unclear, but
// probably should throw
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=23532
shouldBe('document.removeEventListener(undefined)', 'undefined');
// shouldthrow('document.removeeventlistener("foo", undefined)');
// shouldthrow('document.removeeventlistener(undefined, listener)');
shouldBe('document.removeEventListener(undefined, listener)', 'undefined');
shouldBe('document.removeEventListener("foo", undefined)', 'undefined');
shouldNotThrow('document.removeEventListener("zork", listener, undefined)');
</script>


text:
Imports Grasshopper.Kernel

Public Class Sandbox_Topology_Info
    Inherits GH_AssemblyInfo

    Public Overrides ReadOnly Property AssemblyName() As String
        Get
            Return "Sandbox Topology"
        End Get
    End Property

    Public Overrides ReadOnly Property License As Grasshopper.Kernel.GH_LibraryLicense
        Get
            Return GH_LibraryLicense.opensource
        End Get
    End Property
    Public Overrides ReadOnly Property Description As String
        Get
            Return "Tools for experiments in computational architecture"
        End Get
    End Property
    Public Overrides ReadOnly Property Version As String
        Get
            Return "1.0.0.0"
        End Get
    End Property
    Public Overrides ReadOnly Property Name As String
        Get
            Return "Sandbox Topology"
        End Get
    End Property
    Public Overrides ReadOnly Property AuthorContact As String
        Get
            Return "tobias.schwinn@gmail.com"
        End Get
    End Property
    Public Overrides ReadOnly Property AuthorName As String
        Get
            Return "Tobias Schwinn"
        End Get
    End Property

    'Override here any more methods you see fit.
    'Start typing Public Overrides..., select a property and push Enter.

End Class


text:
'use strict';
/* eslint-env node */

const concat = require('broccoli-concat');

module.exports = function(tree, options) {
  let { outputFile, hasBootstrap } = options;

  if (typeof hasBootstrap !== 'boolean') {
    hasBootstrap = true;
  }

  let footerFiles = [];

  if (hasBootstrap) {
    footerFiles = ['bootstrap']
  }

  return concat(tree, {
    header: '(function() {',
    outputFile: outputFile,
    headerFiles: ['license.js', 'loader.js'],
    footerFiles: footerFiles,
    inputFiles: ['**/*'],
    annotation: outputFile,
    footer: '}());'
  });
}


text:
import connectInfiniteHits from 'instantsearch.js/es/connectors/infinite-hits/connectInfiniteHits';

import { useConnector } from '../hooks/useConnector';

import type { AdditionalWidgetProperties } from '../hooks/useConnector';
import type { BaseHit } from 'instantsearch.js';
import type {
  InfiniteHitsConnectorParams,
  InfiniteHitsWidgetDescription,
  InfiniteHitsConnector,
} from 'instantsearch.js/es/connectors/infinite-hits/connectInfiniteHits';

export type UseInfiniteHitsProps<THit extends BaseHit = BaseHit> =
  InfiniteHitsConnectorParams<THit>;

export function useInfiniteHits<THit extends BaseHit = BaseHit>(
  props?: UseInfiniteHitsProps<THit>,
  additionalWidgetProperties?: AdditionalWidgetProperties
) {
  return useConnector<
    InfiniteHitsConnectorParams<THit>,
    InfiniteHitsWidgetDescription<THit>
  >(
    connectInfiniteHits as InfiniteHitsConnector<THit>,
    props,
    additionalWidgetProperties
  );
}


text:
def get_pip_version(executable)
  if Facter::Util::Resolution.which(executable) # rubocop:disable Style/GuardClause
    results = Facter::Util::Resolution.exec("#{executable} --version 2>&1").match(%r{^pip (\d+\.\d+\.?\d*).*$})
    results[1] if results
  end
end

Facter.add('pip_version') do
  setcode do
    get_pip_version 'pip'
  end
end

Facter.add('pip2_version') do
  setcode do
    get_pip_version 'pip2'
  end
end

Facter.add('pip3_version') do
  setcode do
    get_pip_version 'pip3'
  end
end


text:
class UpdatesController < ApplicationController
  before_action :set_update, only: [:edit, :update, :destroy]
  before_action :set_deal, only: [:new, :create, :edit, :update, :destroy]

  # GET /updates/new
  def new
    @update = Update.new
    authorize @deal, :owner?
  end

  # GET /updates/1/edit
  def edit
    authorize @deal, :owner?
  end

  # POST /updates
  # POST /updates.json
  def create
    @update = Update.new(update_params)
    @update.deal_id = @deal.id
    respond_to do |format|
      authorize @deal, :owner?
      if @update.save
        format.html { redirect_to @deal, notice: 'Update was successfully created.' }
        format.json { render :show, status: :created, location: @update }
      else
        format.html { render :new }
        format.json { render json: @update.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /updates/1
  # PATCH/PUT /updates/1.json
  def update
    respond_to do |format|
      authorize @deal, :owner?
      if @update.update(update_params)
        format.html { redirect_to @deal, notice: 'Update was successfully updated.' }
        format.json { render :show, status: :ok, location: @update }
      else
        format.html { render :edit }
        format.json { render json: @update.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /updates/1
  # DELETE /updates/1.json
  def destroy
    authorize @deal, :owner?
    @update.destroy
    respond_to do |format|
      format.html { redirect_to :back, notice: 'Update was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_update
      @update = Update.find(params[:id])
    end

    def set_deal
      @deal = Deal.find(params[:deal_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def update_params
      params.require(:update).permit(:content)
    end
end


text:
<?xml version="1.0" encoding="UTF-8" ?>

<dt-example table-type="html-details" table-class="display nowrap" order="2">

<css lib="datatables responsive" />
<js lib="jquery datatables responsive">
<![CDATA[

$(document).ready(function() {
	$('#example').DataTable( {
		responsive: {
			details: {
				type: 'column'
			}
		},
		columnDefs: [ {
			className: 'control',
			orderable: false,
			targets:   0
		} ],
		order: [ 1, 'asc' ]
	} );
} );

]]>
</js>

<title lib="Responsive">Column controlled child rows</title>

<info><![CDATA[

Responsive has two built in methods for displaying the controlling element of the child rows; `inline` which is the default option and shows the control in the first column, and `column` which set a _control column_ as the control. The control column is shown only when there is some other column hidden, and is dedicated only to the show / hide control for the rows.

This example shows the `r-init responsive.details.type` option set to `column` to activate the control column. Note that by default the first column is used as the control, so additionally in the initialisation the `dt-init order` and `dt-init columns.orderable` options are used to disable sorting on this column.

]]></info>

</dt-example>


text:
module ReceiptBank
  module Models
    class Receipt < ReceiptBank::Models::BaseModel
      attr_accessor :local_image_file_path

      def self.inbox(user)
        options = { sessionid: user.session[:session_id] }
        process_results user.client_connection,
                        user.client_connection.query_post_api("#{BASE_URI}inbox", options),
                        'receipts'
      end

      def self.upload_receipt(user, image_file_path)
        options = { sessionid: user.session[:session_id] }
        user.client_connection.query_post_file(build_url(:upload_new_receipt_image),
                                               options,
                                               :photo, image_file_path)
      end

      def self.build_url(resource_action)
        return "#{BASE_URI}postReceipt" if resource_action == :upload_new_receipt_image
        return "#{BASE_URI}update_receipt_data" if resource_action == :update_receipt_data
        super
      end

      def get_image
        options = { sessionid: session[:session_id], id: id }
        client_connection.query_post_api("#{BASE_URI}image", options)
      end

      def publish
        options = { sessionid: session[:session_id], id: id }
        client_connection.query_post_api("#{BASE_URI}publish_receipt", options)
      end

      def save
        return save_new_image if !has_attribute?('id') && local_image_file_path && !local_image_file_path.empty?
        options = { data: build_changed_data.to_json, id: id }.merge(build_session_data)
        response = client_connection.query_post_api(self.class.build_url(:update_receipt_data), options)
        set_all_attributes(response[self.class.resource_name].first, true) if response['size'] > 0
        self
      end

      def save_new_image
        response = self.class.upload_receipt(client_connection.current_user,
                                             local_image_file_path)

        set_attribute('id', response['receiptid'], true)
        self
      end
    end
  end
end


text: DELETE [dbo].[DocmahDocumentationPages] WHERE [Id] NOT IN (@pageIds)


text:
title: Hilbert's New Hotel
localeTitle: Новый отель Гильберта
---
## Задача 359: Новый отель Гильберта

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-359-hilberts-new-hotel/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
package robocode.control.events;

/**
 * A BattleResumedEvent is sent to {@link IBattleListener#onBattleResumed(BattleResumedEvent)
 * onBattleResumed()} when a battle has been resumed (after having been paused).
 *
 * @see IBattleListener
 * @see BattlePausedEvent
 *
 * @author Pavel Savara (original)
 * @author Flemming N. Larsen (contributor)
 *
 * @since 1.6.2
 */
public class BattleResumedEvent extends BattleEvent {

	/**
	 * Called by the game to create a new BattleResumedEvent.
	 * Please don't use this constructor as it might change.
	 */
	public BattleResumedEvent() {
		super();
	}
}


text:
import * as _ from 'lodash';
import * as glob from 'glob';

/**
  * Get files by glob patterns
  */
export function getGlobbedPaths(globPatterns: string | string[], excludes: string | string[]): string[] {
  // URL paths regex
  let urlRegex = new RegExp('^(?:[a-z]+:)?//', 'i');

  // The output array
  let output: string[] = [];

  // If glob pattern is array then we use each pattern in a recursive way, otherwise we use glob
  if (_.isArray(globPatterns)) {
    globPatterns.forEach((globPattern) => {
      output = _.union(output, getGlobbedPaths(globPattern, excludes));
    });
  } else if (_.isString(globPatterns)) {
    if (urlRegex.test(globPatterns)) {
      output.push(globPatterns);
    } else {
      let files = glob.sync(globPatterns);
      if (excludes) {
        files = files.map((file: any) => {
          if (_.isArray(excludes)) {
            excludes.forEach((item) => {
              file = file.replace(item, '');
            });
          } else {
            file = file.replace(excludes, '');
          }
          return file;
        });
      }
      output = _.union(output, files);
    }
  }

  return output;
};

/**
  * Wrapper lodash.union to return a string[] to pass to a gulp.src.
  * To avoid error: cannot assign {}[] to string[].
  */
export function assetsUnion(...args: any[]): string[] {
  return <string[]>_.union(...args);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <link href="http://fonts.googleapis.com/css?family=Droid+Sans+Mono" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="design/index.css">

    <title>Players at the Database</title>

Back to Home

Players stored at the Database

          Spieler

        <input type="button"  value="Alle anzeigen" onclick="holeDaten();">
        <input type="button"  value="Favoriten anzeigen" onclick="holeFavoriten();">


text:
from __future__ import print_function
import logging

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
        '%(levelname)-8s %(name)-12s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

# from faker import Factory
# from pprint import pprint
# fake = Factory.create('en_US')
# exdict = dict(((fake.name(), (fake.city(), fake.zipcode())) for i in range(20)))
# pprint(exdict)

exdict = {
    'Alyssa Boyd': ('Brownmouth', '09044'),
    'Amy Martin': ('Mikechester', '33477'),
    'Angela Mcdonald': ('North Gwendolynberg', '29053'),
    'Bradley Santos': ('Andrewsmouth', '72513'),
    'Brittany Manning': ('South Danielmouth', '44482'),
    'Candice Huber': ('New Kimberly', '11698'),
    'Cheyenne Thornton': ('New Anthony', '88618'),
    'Dr. Kelli Sharp MD': ('North Rhondashire', '71761'),
    'Evan Osborne': ('Andrewsside', '14378'),
    'Gary Hernandez': ('Burnshaven', '62267'),
    'George Elliott': ('Calebton', '55053'),
    'Hannah Williams': ('North Stacy', '50983'),
    'James Taylor': ('Gallegoshaven', '95677'),
    'John White': ('Hansenhaven', '44559'),
    'Monique Mccoy': ('Katherinemouth', '42023'),
    'Randy Campos': ('South Scotthaven', '47692'),
    'Rebecca Wolfe': ('Torresburgh', '37979'),
    'Ronald Parks': ('Turnerland', '96367'),
    'Russell Schroeder': ('Smithfurt', '39696'),
    'Trevor Kelly': ('South Jenniferport', '73366'),
}

from dynmen.rofi import Rofi
menu = Rofi(lines=5, hide_scrollbar=True)
menu.prompt = "Name of person: "
menu.case_insensitive = True
out = menu(exdict)
print('Output from rofi:', out)

from dynmen.dmenu import DMenu
menu = DMenu()
menu.font = 'Satisfy-20'
menu.nf = '#6FC3DF'
menu.nb = '#0C141F'
menu.sf = '#FFE64D'
menu.sb = '#0C141F'
menu.lines = 20
menu.prompt = "Name of person: "
menu.case_insensitive = True
out = menu(exdict)
print('Output from dmenu:', out)


text:
#ifndef __AtomicScalar_H__
#define __AtomicScalar_H__

#include <signal.h>
#include "OgrePrerequisites.h"
#include "OgreException.h"
#include "OgrePlatformInformation.h"

#if (((OGRE_COMPILER == OGRE_COMPILER_GNUC) && (OGRE_COMP_VER >= 412)) || (OGRE_COMPILER == OGRE_COMPILER_CLANG)) && OGRE_THREAD_SUPPORT

// Atomics are not yet supported for the unsigned long long int(ResourceHandle) type as of Clang 5.0. So only GCC for now.
#if ((OGRE_COMPILER == OGRE_COMPILER_GNUC) && (OGRE_COMP_VER >= 473))
    #define BUILTIN_FETCH_ADD(var, add) __atomic_fetch_add (var, add, __ATOMIC_SEQ_CST);
    #define BUILTIN_ADD_FETCH(var, add) __atomic_add_fetch (var, add, __ATOMIC_SEQ_CST);
    #define BUILTIN_SUB_FETCH(var, sub) __atomic_sub_fetch (var, sub, __ATOMIC_SEQ_CST);
#else
    #define BUILTIN_FETCH_ADD(var, add) __sync_fetch_and_add (var, add);
    #define BUILTIN_ADD_FETCH(var, add) __sync_add_and_fetch (var, add);
    #define BUILTIN_SUB_FETCH(var, sub) __sync_sub_and_fetch (var, sub);
#endif

namespace Ogre {

	/** \addtogroup Core
	*  @{
	*/
	/** \addtogroup General
	*  @{
	*/
    template<class T> class AtomicScalar
    {

        public:

        AtomicScalar (const T &initial)
            : mField(initial)
        {   }

        AtomicScalar (const AtomicScalar<T> &cousin)
            : mField(cousin.mField)
        {   }

        AtomicScalar ()
        {   }

        void operator= (const AtomicScalar<T> &cousin)
        {
            mField = cousin.mField;
        }

        T get (void) const
        {
            return mField;
        }

        void set (const T &v)
        {
            mField = v;
        }

        bool cas (const T &old, const T &nu)
        {
            return __sync_bool_compare_and_swap (&mField, old, nu);
        }

        T operator++ (void)
        {
            return BUILTIN_ADD_FETCH (&mField, 1);
        }

        T operator-- (void)
        {
            return BUILTIN_ADD_FETCH (&mField, -1);
        }

        T operator++ (int)
        {
            return BUILTIN_FETCH_ADD (&mField, 1);
        }

        T operator-- (int)
        {
            return BUILTIN_FETCH_ADD (&mField, -1);
        }

		T operator+=(const T &add)
		{
			return BUILTIN_ADD_FETCH (&mField, add);
		}

		T operator-=(const T &sub)
		{
			return BUILTIN_SUB_FETCH (&mField, sub);
		}

        // Need special alignment for atomic functions on ARM CPU's
#if OGRE_CPU == OGRE_CPU_ARM
#   if OGRE_COMPILER == OGRE_COMPILER_MSVC
        __declspec(align(16)) volatile T mField;
#   elif (OGRE_COMPILER == OGRE_COMPILER_GNUC) || (OGRE_COMPILER == OGRE_COMPILER_CLANG)
        volatile T mField __attribute__((__aligned__(16)));
#   endif
#else
        volatile T mField;
#endif

    };
	/** @} */
	/** @} */

}

 #elif OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER >= 1400 && OGRE_THREAD_SUPPORT

#ifndef WIN32_LEAN_AND_MEAN
#  define WIN32_LEAN_AND_MEAN
#endif
#if !defined(NOMINMAX) && defined(_MSC_VER)
#	define NOMINMAX // required to stop windows.h messing up std::min
#endif
#include <windows.h>
#include <intrin.h>
#include "Threading/OgreThreadHeaders.h"

// Save warnings state
#   pragma warning (push)
#   pragma warning (disable : 4244)

namespace Ogre {

    // a hack so we can support windows xp.
#define NEED_TO_INIT_INTERLOCKEDCOMPAREEXCHANGE64WRAPPER
    struct _OgreExport InterlockedCompareExchange64Wrapper
    {
        InterlockedCompareExchange64Wrapper();

        typedef
            LONGLONG
            (WINAPI *func_InterlockedCompareExchange64)(
            __inout LONGLONG volatile *Destination,
            __in    LONGLONG Exchange,
            __in    LONGLONG Comperand) ;

        static func_InterlockedCompareExchange64 Ogre_InterlockedCompareExchange64;

        static FORCEINLINE
            LONGLONG
            Ogre_InterlockedIncrement64 (
            __inout LONGLONG volatile *Addend
            )
        {
            LONGLONG Old;

            do {
                Old = *Addend;
            } while (Ogre_InterlockedCompareExchange64(Addend,
                Old + 1,
                Old) != Old);

            return Old + 1;
        }

        static FORCEINLINE
            LONGLONG
            Ogre_InterlockedDecrement64 (
            __inout LONGLONG volatile *Addend
            )
        {
            LONGLONG Old;

            do {
                Old = *Addend;
            } while (Ogre_InterlockedCompareExchange64(Addend,
                Old - 1,
                Old) != Old);

            return Old - 1;
        }

    };

    /** \addtogroup Core
	*  @{
	*/
	/** \addtogroup General
	*  @{
	*/
    template<class T> class AtomicScalar
    {

        public:

        AtomicScalar (const T &initial)
            : mField(initial)
        {   }

        AtomicScalar (const AtomicScalar<T> &cousin)
            : mField(cousin.mField)
        {   }

        AtomicScalar ()
        {   }

        void operator= (const AtomicScalar<T> &cousin)
        {
            mField = cousin.mField;
        }

        T get (void) const
        {
            return mField;
        }

        void set (const T &v)
        {
            mField = v;
        }

        bool cas (const T &old, const T &nu)
        {
            if (sizeof(T)==2) {
                return _InterlockedCompareExchange16((SHORT*)&mField, static_cast<SHORT>(nu), static_cast<SHORT>(old)) == static_cast<SHORT>(old);
            }
			else if (sizeof(T)==4)
			{
                return _InterlockedCompareExchange((LONG*)&mField, static_cast<LONG>(nu), static_cast<LONG>(old)) == static_cast<LONG>(old);
			}
			else if (sizeof(T)==8 && InterlockedCompareExchange64Wrapper::Ogre_InterlockedCompareExchange64 != NULL) {
                return InterlockedCompareExchange64Wrapper::Ogre_InterlockedCompareExchange64((LONGLONG*)&mField, static_cast<LONGLONG>(nu), static_cast<LONGLONG>(old)) == static_cast<LONGLONG>(old);
            }
			else {
                OGRE_LOCK_AUTO_MUTEX;
                if (mField != old) return false;
                mField = nu;
                return true;
            }
        }

        T operator++ (void)
        {
            if (sizeof(T)==2) {
                return _InterlockedIncrement16((SHORT*)&mField);
            } else if (sizeof(T)==4) {
                return InterlockedIncrement((LONG*)&mField);
            } else if (sizeof(T)==8 && InterlockedCompareExchange64Wrapper::Ogre_InterlockedCompareExchange64 != NULL) {
                return InterlockedCompareExchange64Wrapper::Ogre_InterlockedIncrement64((LONGLONG*)&mField);
            } else {
                OGRE_LOCK_AUTO_MUTEX;
                return ++mField;
            }
        }

        T operator-- (void)
        {
            if (sizeof(T)==2) {
                return _InterlockedDecrement16((SHORT*)&mField);
            } else if (sizeof(T)==4) {
                return InterlockedDecrement((LONG*)&mField);
            } else if (sizeof(T)==8 && InterlockedCompareExchange64Wrapper::Ogre_InterlockedCompareExchange64 != NULL) {
                return InterlockedCompareExchange64Wrapper::Ogre_InterlockedDecrement64((LONGLONG*)&mField);
            } else {
                OGRE_LOCK_AUTO_MUTEX;
                return --mField;
            }
        }

        T operator++ (int)
        {
            if (sizeof(T)==2) {
                return _InterlockedIncrement16((SHORT*)&mField)-1;
            } else if (sizeof(T)==4) {
                return InterlockedIncrement((LONG*)&mField)-1;
            } else if (sizeof(T)==8 && InterlockedCompareExchange64Wrapper::Ogre_InterlockedCompareExchange64 != NULL) {
                return InterlockedCompareExchange64Wrapper::Ogre_InterlockedIncrement64((LONGLONG*)&mField)-1;
            } else {
                OGRE_LOCK_AUTO_MUTEX;
                return mField++;
            }
        }

        T operator-- (int)
        {
            if (sizeof(T)==2) {
                return _InterlockedDecrement16((SHORT*)&mField)+1;
            } else if (sizeof(T)==4) {
                return InterlockedDecrement((LONG*)&mField)+1;
            } else if (sizeof(T)==8 && InterlockedCompareExchange64Wrapper::Ogre_InterlockedCompareExchange64 != NULL) {
                return InterlockedCompareExchange64Wrapper::Ogre_InterlockedDecrement64((LONGLONG*)&mField)+1;
            } else {
                OGRE_LOCK_AUTO_MUTEX;
                return mField--;
            }
        }

		T operator+=(const T &add)
		{
            if ((sizeof(T)==2) || (sizeof(T)==4) || (sizeof(T)==8 && InterlockedCompareExchange64Wrapper::Ogre_InterlockedCompareExchange64 != NULL)) {
                //The function InterlockedExchangeAdd is not available for 64 and 16 bit version
                //We will use the cas operation instead.
                T newVal;
                do {
                    //Create a value of the current field plus the added value
                    newVal = mField + add;
                    //Replace the current field value with the new value. Ensure that the value
                    //of the field hasn't changed in the mean time by comparing it to the new value
                    //minus the added value.
                } while (!cas(newVal - add, newVal)); //repeat until successful
                return newVal;
            }
            else
            {
                OGRE_LOCK_AUTO_MUTEX;
                mField += add;
                return mField;
            }
		}

		T operator-=(const T &sub)
		{
            if ((sizeof(T)==2) || (sizeof(T)==4) || (sizeof(T)==8 && InterlockedCompareExchange64Wrapper::Ogre_InterlockedCompareExchange64 != NULL)) {
                //The function InterlockedExchangeAdd is not available for 64 and 16 bit version
                //We will use the cas operation instead.
                T newVal;
                do {
                    //Create a value of the current field plus the added value
                    newVal = mField - sub;
                    //Replace the current field value with the new value. Ensure that the value
                    //of the field hasn't changed in the mean time by comparing it to the new value
                    //minus the added value.
                } while (!cas(newVal + sub, newVal)); //repeat until successful
                return newVal;
            }
            else
            {
                OGRE_LOCK_AUTO_MUTEX;
                mField -= sub;
                return mField;
            }
		}

        protected:

        OGRE_AUTO_MUTEX;

        volatile T mField;

    };
	/** @} */
	/** @} */

}

#   pragma warning (pop)

#else

#include "Threading/OgreThreadHeaders.h"

namespace Ogre {

	/** \addtogroup Core
	*  @{
	*/
	/** \addtogroup General
	*  @{
	*/
    template <class T> class AtomicScalar {

        public:

        AtomicScalar (const T &initial)
            : mField(initial)
        {   }

        AtomicScalar (const AtomicScalar<T> &cousin)
            : mField(cousin.mField)
        {   }

        AtomicScalar ()
        {   }

        void operator= (const AtomicScalar<T> &cousin)
        {
            mField = cousin.mField;
        }

        T get (void) const
        {
            // no lock required here
            // since get will not interfere with set or cas
            // we may get a stale value, but this is ok
            return mField;
        }

        void set (const T &v)
        {
            mField = v;
        }

        bool cas (const T &old, const T &nu)
        {
            OGRE_LOCK_AUTO_MUTEX;
            if (mField != old) return false;
            mField = nu;
            return true;
        }

        T operator++ (void)
        {
            OGRE_LOCK_AUTO_MUTEX;
            return ++mField;
        }

        T operator-- (void)
        {
            OGRE_LOCK_AUTO_MUTEX;
            return --mField;
        }

        T operator++ (int)
        {
            OGRE_LOCK_AUTO_MUTEX;
            return mField++;
        }

        T operator-- (int)
        {
            OGRE_LOCK_AUTO_MUTEX;
            return mField--;
        }

		T operator+=(const T &add)
		{
            OGRE_LOCK_AUTO_MUTEX;
			mField += add;
			return mField;
		}

		T operator-=(const T &sub)
		{
            OGRE_LOCK_AUTO_MUTEX;
			mField -= sub;
			return mField;
		}

        protected:

        OGRE_AUTO_MUTEX;

        volatile T mField;

    };
	/** @} */
	/** @} */

}

#endif

#endif


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

/*----------------------------------------------------------------
    Copyright (C) 2017 Senparc

    文件名:GetMenuResult.cs
    文件功能描述:获取菜单返回的Json结果

    创建标识:Senparc - 20150211

    修改标识:Senparc - 20150303
    修改描述:整理接口
----------------------------------------------------------------*/

using System.Collections.Generic;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP.Entities.Menu;

namespace Senparc.Weixin.MP.Entities
{
    /// <summary>
    /// GetMenu返回的Json结果
    /// </summary>
    public class GetMenuResult : WxJsonResult
    {
        //TODO:这里如果有更加复杂的情况,可以换成ButtonGroupBase类型,并提供泛型
        public ButtonGroupBase menu { get; set; }

        /// <summary>
        /// 有个性化菜单时显示。最新的在最前。
        /// </summary>
        public List<ConditionalButtonGroup> conditionalmenu { get; set; }

        public GetMenuResult(ButtonGroupBase buttonGroupBase)
        {
            menu = buttonGroupBase;
        }
    }
}


text:
DELIMITER $$

DROP PROCEDURE IF EXISTS exec_single $$
CREATE PROCEDURE exec_single(IN execute_query TEXT CHARSET utf8)
MODIFIES SQL DATA
SQL SECURITY INVOKER
COMMENT ''

_proc_body: begin
  set @_execute_query := trim_wspace(execute_query);
  if CHAR_LENGTH(@_execute_query) = 0 then
    -- An empty statement
    -- This can happen as result of splitting by semicolon ';'
    leave _proc_body;
  end if;

  set @common_schema_rowcount := NULL;

  if @common_schema_dryrun IS TRUE then
    SELECT @_execute_query AS 'exec_single: @common_schema_dryrun';
  else
    if @common_schema_verbose IS TRUE then
	  SELECT @_execute_query AS 'exec_single: @common_schema_verbose';
    end if;

    PREPARE st FROM @_execute_query;
    EXECUTE st;
    set @common_schema_rowcount := ROW_COUNT(), @common_schema_found_rows := FOUND_ROWS();
    DEALLOCATE PREPARE st;
  end if;
end $$

DELIMITER ;


text:
namespace Nancy.Security
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading;
    using FluentAssertions;
    using Owin;
    using Annotations;
    using Xunit;

    [UsedImplicitly]
    public class NancyModuleExtensionsTests
    {
        public class Given_a_module_that_requires_owin_authentication
        {
            private readonly TestModule _testModule;

            public Given_a_module_that_requires_owin_authentication()
            {
                _testModule = new TestModule();
                _testModule.RequiresMSOwinAuthentication();
            }

            [Fact]
            public void With_no_authentication_manager_then_should_get_unauthorized()
            {
                var context = new NancyContext();

                Response response = _testModule.InvokeBeforePipeLine(context);

                response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
            }

            [Fact]
            public void With_authentication_manager_but_no_user_then_should_get_unauthorized()
            {
                var context = new NancyContext();
                context.Items.Add(NancyMiddleware.RequestEnvironmentKey, new Dictionary<string, object>());

                Response response = _testModule.InvokeBeforePipeLine(context);

                response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
            }

            [Fact]
            public void With_authentication_manager_and_a_user_then_should_get_null()
            {
                var context = new NancyContext();
                context.Items.Add(NancyMiddleware.RequestEnvironmentKey, new Dictionary<string, object> { { "server.User", new ClaimsPrincipal() } });

                Response response = _testModule.InvokeBeforePipeLine(context);

                response.Should().BeNull();
            }

            private class TestModule : NancyModule
            {}
        }

        public class Given_a_module_that_requires_security_claims
        {
            private readonly TestModule _testModule;
            private readonly NancyContext _context;
            private readonly Dictionary<string, object> _environment;
            private const string ServerUserKey = "server.User";

            public Given_a_module_that_requires_security_claims()
            {
                _testModule = new TestModule();
                _testModule.RequiresSecurityClaims(claims => claims.Any(
                        claim => claim.Type == ClaimTypes.Country
                        && claim.Value.Equals("IE", StringComparison.Ordinal)));
                _context = new NancyContext();
                _environment = new Dictionary<string, object>();
                _context.Items.Add(NancyMiddleware.RequestEnvironmentKey, _environment);
            }

            [Fact]
            public void When_unauthenticated_should_get_unauthorized()
            {
                _environment[ServerUserKey] = null;

                Response response = _testModule.InvokeBeforePipeLine(_context);

                response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
            }

            [Fact]
            public void When_authenticated_and_claims_not_valid_should_get_Forbidden()
            {
                _environment[ServerUserKey] = new ClaimsPrincipal(new ClaimsIdentity(new Claim[0], "Custom"));

                Response response = _testModule.InvokeBeforePipeLine(_context);

                response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
            }

            [Fact]
            public void With_authentication_manager_and_a_user_then_should_get_null()
            {
                _environment[ServerUserKey] = new ClaimsPrincipal(
                    new ClaimsIdentity(
                        new [] { new Claim(ClaimTypes.Country, "IE") }));

                Response response = _testModule.InvokeBeforePipeLine(_context);

                response.Should().BeNull();
            }

            private class TestModule : NancyModule
            { }
        }
    }

    internal static class NancyModuleExtensions
    {
        internal static Response InvokeBeforePipeLine(this NancyModule module, NancyContext context)
        {
            return module
                    .Before
                    .PipelineItems
                    .Select(pipelineItem => pipelineItem.Delegate(context, CancellationToken.None).Result)
                    .FirstOrDefault(res => res != null);
        }
    }
}


text:
package cn.com.warlock.wisp.core.exception;

public class WispInjectorInitException extends WispException {

    private static final long serialVersionUID = 1L;

    public WispInjectorInitException() {
    }

    public WispInjectorInitException(String message) {
        super(message);
    }

    public WispInjectorInitException(String message, Throwable cause) {
        super(message, cause);
    }

    public WispInjectorInitException(Throwable cause) {
        super(cause);
    }
}