text:
module CukeQ
  class Master
    DEFAULT_BROKER_URI = URI.parse("amqp://cukeq-master:cukeq123@localhost:5672/cukeq")
    DEFAULT_WEBAPP_URI = URI.parse("http://0.0.0.0:9292")

    class << self
      def execute(argv)
        configured_instance(argv).start
      end

      def configured_instance(argv)
        opts = parse(argv)

        raise ArgumentError, "must provide --scm" unless opts[:scm]
        raise ArgumentError, "must provide --report_to" unless opts[:report_to]

        if b = opts[:broker]
          b.user     ||= DEFAULT_BROKER_URI.user
          b.password ||= DEFAULT_BROKER_URI.password
          b.host     ||= DEFAULT_BROKER_URI.host
          b.port     ||= DEFAULT_BROKER_URI.port
          b.path     = b.path.empty? ? DEFAULT_BROKER_URI.path : b.path
        else
          opts[:broker] = DEFAULT_BROKER_URI
        end

        if w = opts[:webapp]
          w.host ||= DEFAULT_WEBAPP_URI.host
          w.port ||= DEFAULT_WEBAPP_URI.port
        else
          opts[:webapp] = DEFAULT_WEBAPP_URI
        end

        new(
          Broker.new(opts[:broker]),
          WebApp.new(opts[:webapp]),
          Scm.new(opts[:scm]),
          Reporter.new(opts[:report_to]),
          ScenarioExploder.new
        )
      end

      def parse(argv)
        options = {}

        argv.extend OptionParser::Arguable
        argv.options do |opts|
          opts.on("-b", "--broker URI (default: #{DEFAULT_BROKER_URI})") do |str|
            options[:broker] = URI.parse(str)
          end

          opts.on("-w", "--webapp URI (default: http://localhost:9292)") do |str|
            options[:webapp] = URI.parse(str)
          end

          opts.on("-s", "--scm SCM-URL") do |url|
            options[:scm] = URI.parse(url)
          end

          opts.on("-r", "--report-to REPORTER-URL") do |url|
            options[:report_to] = URI.parse(url)
          end
        end.parse!

        options
      end
    end # class << self

    attr_reader :broker, :webapp, :scm, :reporter, :exploder

    def initialize(broker, webapp, scm, reporter, exploder)
      @broker   = broker
      @webapp   = webapp
      @scm      = scm
      @reporter = reporter
      @exploder = exploder
    end

    def start
      @scm.update {
        @broker.start {
          subscribe
          start_webapp
        }
      }
    end

    def ping(&blk)
      log self.class, :ping
      @broker.subscribe :pong, &blk
      @broker.publish   :ping, '{}'
    end

    #
    # This is triggered by POSTs to the webapp
    #
    # data:
    #
    # { 'features' => (sent to exploder), 'run_id' => ID }
    #

    def run(data)
      Dir.chdir(@scm.working_copy) do
        @exploder.explode(data['features']) { |units| publish_units(data, units) }
      end
    end

    def publish_units(data, units)
      scm = { :revision => @scm.current_revision, :url => @scm.url }
      run = { :id => data['run_id'], :no_of_units => units.size}

      units.each do |unit|
        @broker.publish(
          :jobs, {
            :run         => run,
            :scm         => scm,
            :unit        => unit,
          }.to_json
        )

        log self.class, :published, unit
      end
    end

    #
    # Called whenever a result is received on the results queue
    #

    def result(message)
      log self.class, :result, message['run']
      @reporter.report message
    end

    def subscribe
      @broker.subscribe :results do |message|
        next unless message
        result(JSON.parse(message))
      end
    end

    def start_webapp
      log self.class, :start_webapp
      @webapp.run method(:run)
    end

  end # Master
end # CukeQ


text:
<?php

declare(strict_types=1);

namespace Tests\Fixtures\AppBundle\Controller;

use Omines\DataTablesBundle\Adapter\Doctrine\Event\ORMAdapterQueryEvent;
use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter;
use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapterEvents;
use Omines\DataTablesBundle\Column\TextColumn;
use Omines\DataTablesBundle\DataTableFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Tests\Fixtures\AppBundle\Entity\Employee;

/**
 * @author Maxime Pinot <contact@maximepinot.com>
 */
class ORMAdapterEventsController extends AbstractController
{
    public const PRE_QUERY_RESULT_CACHE_ID = 'datatable_result_cache';

    public function preQueryAction(Request $request, DataTableFactory $dataTableFactory): Response
    {
        $datatable = $dataTableFactory->create()
            ->add('firstName', TextColumn::class)
            ->add('lastName', TextColumn::class)
            ->add('company', TextColumn::class, ['field' => 'company.name'])
            ->createAdapter(ORMAdapter::class, [
                'entity' => Employee::class,
            ])
            ->addEventListener(ORMAdapterEvents::PRE_QUERY, function (ORMAdapterQueryEvent $event) {
                $event->getQuery()->useResultCache(true, 0, self::PRE_QUERY_RESULT_CACHE_ID);
            });

        return $datatable->handleRequest($request)->getResponse();
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*

  ## Histogram

  ### Parameters
  * auto_int :: Auto calculate data point interval?
  * resolution ::  If auto_int is enables, shoot for this many data points, rounding to
                    sane intervals
  * interval :: Datapoint interval in elasticsearch date math format (eg 1d, 1w, 1y, 5y)
  * fill :: Only applies to line charts. Level of area shading from 0-10
  * linewidth ::  Only applies to line charts. How thick the line should be in pixels
                  While the editor only exposes 0-10, this can be any numeric value.
                  Set to 0 and you'll get something like a scatter plot
  * timezone :: This isn't totally functional yet. Currently only supports browser and utc.
                browser will adjust the x-axis labels to match the timezone of the user's
                browser
  * spyable ::  Dislay the 'eye' icon that show the last elasticsearch query
  * zoomlinks :: Show the zoom links?
  * bars :: Show bars in the chart
  * stack :: Stack multiple queries. This generally a crappy way to represent things.
             You probably should just use a line chart without stacking
  * points :: Should circles at the data points on the chart
  * lines :: Line chart? Sweet.
  * legend :: Show the legend?
  * x-axis :: Show x-axis labels and grid lines
  * y-axis :: Show y-axis labels and grid lines
  * interactive :: Allow drag to select time range

*/
define([
  'angular',
  'app',
  'jquery',
  'underscore',
  'kbn',
  'moment',
  './timeSeries',

  'jquery.flot',
  'jquery.flot.pie',
  'jquery.flot.selection',
  'jquery.flot.time',
  'jquery.flot.stack',
  'jquery.flot.stackpercent'
],
function (angular, app, $, _, kbn, moment, timeSeries) {
  'use strict';

  var DEBUG = true; // DEBUG mode

  var module = angular.module('kibana.panels.histogram', []);
  app.useModule(module);

  module.controller('histogram', function($scope, $q, querySrv, dashboard, filterSrv) {
    $scope.panelMeta = {
      modals : [
        {
          description: "Inspect",
          icon: "icon-info-sign",
          partial: "app/partials/inspector.html",
          show: $scope.panel.spyable
        }
      ],
      editorTabs : [
        {
          title:'Queries',
          src:'app/partials/querySelect.html'
        }
      ],
      status  : "Stable",
      description : "A bucketed time series chart of the current query or queries. Uses the "+
        "Solr facet range. If using time stamped indices this panel will query"+
        " them sequentially to attempt to apply the lighest possible load to your Solr cluster"
    };

    // Set and populate defaults
    var _d = {
      mode        : 'count',
      time_field  : 'event_timestamp',
      queries     : {
        mode        : 'all',
        ids         : [],
        query       : '*:*',
        custom      : ''
      },
      max_rows    : 100000,  // maximum number of rows returned from Solr (also use this for group.limit to simplify UI setting)
      value_field : null,
      group_field : null,
      auto_int    : true,
      resolution  : 100,
      interval    : '5m',
      intervals   : ['auto','1s','1m','5m','10m','30m','1h','3h','12h','1d','1w','1M','1y'],
      fill        : 0,
      linewidth   : 3,
      timezone    : 'browser', // browser, utc or a standard timezone
      spyable     : true,
      zoomlinks   : true,
      bars        : true,
      stack       : true,
      points      : false,
      lines       : false,
      lines_smooth: false, // Enable 'smooth line' mode by removing zero values from the plot.
      legend      : true,
      'x-axis'    : true,
      'y-axis'    : true,
      percentage  : false,
      interactive : true,
      options     : true,
      tooltip     : {
        value_type: 'cumulative',
        query_as_alias: false
      }
    };

    _.defaults($scope.panel,_d);

    $scope.init = function() {
      // Hide view options by default
      $scope.options = false;
      $scope.$on('refresh',function(){
        $scope.get_data();
      });

      $scope.get_data();

    };

    $scope.set_interval = function(interval) {
      if(interval !== 'auto') {
        $scope.panel.auto_int = false;
        $scope.panel.interval = interval;
      } else {
        $scope.panel.auto_int = true;
      }
    };

    $scope.interval_label = function(interval) {
      return $scope.panel.auto_int && interval === $scope.panel.interval ? interval+" (auto)" : interval;
    };

    /**
     * The time range effecting the panel
     * @return {[type]} [description]
     */
    $scope.get_time_range = function () {
      var range = $scope.range = filterSrv.timeRange('min');
      return range;
    };

    $scope.get_interval = function () {
      var interval = $scope.panel.interval,
                      range;
      if ($scope.panel.auto_int) {
        range = $scope.get_time_range();
        if (range) {
          interval = kbn.secondsToHms(
            kbn.calculate_interval(range.from, range.to, $scope.panel.resolution, 0) / 1000
          );
        }
      }
      $scope.panel.interval = interval || '10m';
      return $scope.panel.interval;
    };

    /**
     * Fetch the data for a chunk of a queries results. Multiple segments occur when several indicies
     * need to be consulted (like timestamped logstash indicies)
     *
     * The results of this function are stored on the scope's data property. This property will be an
     * array of objects with the properties info, time_series, and hits. These objects are used in the
     * render_panel function to create the historgram.
     *
     * !!! Solr does not need to fetch the data in chunk because it uses a facet search and retrieve
     * !!! all events from a single query.
     *
     * @param {number} segment   The segment count, (0 based)
     * @param {number} query_id  The id of the query, generated on the first run and passed back when
     *                            this call is made recursively for more segments
     */
    $scope.get_data = function(segment, query_id) {
      if (_.isUndefined(segment)) {
        segment = 0;
      }
      delete $scope.panel.error;

      // Make sure we have everything for the request to complete
      if(dashboard.indices.length === 0) {
        return;
      }
      var _range = $scope.get_time_range();
      var _interval = $scope.get_interval(_range);

      if ($scope.panel.auto_int) {
        $scope.panel.interval = kbn.secondsToHms(
          kbn.calculate_interval(_range.from,_range.to,$scope.panel.resolution,0)/1000);
      }

      $scope.panelMeta.loading = true;

      // Solr
      $scope.sjs.client.server(dashboard.current.solr.server + dashboard.current.solr.core_name);

      if (DEBUG) { console.debug('histogram:\n\tdashboard=',dashboard,'\n\t$scope=',$scope,'\n\t$scope.panel=',$scope.panel,'\n\tquerySrv=',querySrv,'\n\tfilterSrv=',filterSrv); }

      var request = $scope.sjs.Request().indices(dashboard.indices[segment]);
      $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries);

      // Build the query
      _.each($scope.panel.queries.ids, function(id) {
        var query = $scope.sjs.FilteredQuery(
          querySrv.getEjsObj(id),
          filterSrv.getBoolFilter(filterSrv.ids)
        );

        var facet = $scope.sjs.DateHistogramFacet(id);

        if($scope.panel.mode === 'count') {
          facet = facet.field($scope.panel.time_field);
        } else {
          if(_.isNull($scope.panel.value_field)) {
            $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
            return;
          }
          facet = facet.keyField($scope.panel.time_field).valueField($scope.panel.value_field);
        }
        facet = facet.interval(_interval).facetFilter($scope.sjs.QueryFilter(query));

        request = request.facet(facet).size(0);
      });

      // Populate the inspector panel
      $scope.populate_modal(request);

      // Build Solr query
      var fq = '&' + filterSrv.getSolrFq();
      var time_field = filterSrv.getTimeField();
      var start_time = filterSrv.getStartTime();
      var end_time = filterSrv.getEndTime();

      var wt_json = '&wt=json';
      var rows_limit = '&rows=0'; // for histogram, we do not need the actual response doc, so set rows=0
      var facet_gap = $scope.sjs.convertFacetGap($scope.panel.interval);
      var facet = '&facet=true' +
                  '&facet.range=' + time_field +
                  '&facet.range.start=' + start_time + '/DAY' +
                  '&facet.range.end=' + end_time + '%2B1DAY/DAY' +
                  '&facet.range.gap=' + facet_gap;
      var values_mode_query = '';

      // For mode = value
      if($scope.panel.mode === 'values') {
        if (!$scope.panel.value_field) {
            $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
            return;
        }

        values_mode_query = '&fl=' + $scope.panel.time_field + ' ' + $scope.panel.value_field;
        rows_limit = '&rows=' + $scope.panel.max_rows;
        facet = '';

        // if Group By Field is specified
        if ($scope.panel.group_field) {
          values_mode_query += '&group=true&group.field=' + $scope.panel.group_field + '&group.limit=' + $scope.panel.max_rows;
        }
      }

      // Set the panel's query
      $scope.panel.queries.query = querySrv.getQuery(0) + wt_json + rows_limit + fq + facet + values_mode_query;

      // Set the additional custom query
      if ($scope.panel.queries.custom != null) {
        request = request.setQuery($scope.panel.queries.query + $scope.panel.queries.custom);
      } else {
        request = request.setQuery($scope.panel.queries.query);
      }

      var results = request.doSearch();

      // ==========================
      // SOLR - TEST Multiple Queries
      // ==========================
      // var mypromises = [];
      // mypromises.push(results);

      // var temp_q = 'q=' + dashboard.current.services.query.list[1].query + df + wt_json + rows_limit + fq + facet + filter_fq + fl;
      // request = request.setQuery(temp_q);
      // mypromises.push(request.doSearch());

      // if (dashboard.current.services.query.ids.length > 1) {
      //   _.each(dashboard.current.services.query.list, function(v,k) {
      //     if (DEBUG) { console.log('histogram:\n\tv=',v,', k=',k); }
      //     // TODO
      //   });
      //   $q.all(mypromises).then(function(myresults) {
      //     if (DEBUG) { console.log('histogram:\n\tmyresults=',myresults); }
      //     // TODO
      //   });
      // }
      // ========================
      // END SOLR TEST
      // ========================

      // Populate scope when we have results
      results.then(function(results) {
        if (DEBUG) { console.debug('histogram:\n\trequest='+request+'\n\tresults=',results); }

        $scope.panelMeta.loading = false;
        if(segment === 0) {
          $scope.hits = 0;
          $scope.data = [];
          query_id = $scope.query_id = new Date().getTime();
        }

        // Check for error and abort if found
        if(!(_.isUndefined(results.error))) {
          $scope.panel.error = $scope.parse_error(results.error.msg);
          return;
        }

        // Convert facet ids to numbers
        // var facetIds = _.map(_.keys(results.facets),function(k){return parseInt(k, 10);});
        // TODO: change this, Solr do faceting differently
        var facetIds = [0]; // Need to fix this

        // Make sure we're still on the same query/queries
        // TODO: We probably DON'T NEED THIS unless we have to support multiple queries in query module.
        if($scope.query_id === query_id && _.difference(facetIds, $scope.panel.queries.ids).length === 0) {
          var i = 0,
            time_series,
            hits;

          _.each($scope.panel.queries.ids, function(id) {
            // var query_results = results.facets[id];

            if (DEBUG) { console.debug('histogram: i=',i,', segment=',segment,', $scope=',$scope); }

            // we need to initialize the data variable on the first run,
            // and when we are working on the first segment of the data.
            if(_.isUndefined($scope.data[i]) || segment === 0) {
              time_series = new timeSeries.ZeroFilled({
                interval: _interval,
                start_date: _range && _range.from,
                end_date: _range && _range.to,
                fill_style: 'minimal'
              });
              hits = 0;
              if (DEBUG) { console.debug('\tfirst run: i='+i+', time_series=',time_series); }
            } else {
              if (DEBUG) { console.debug('\tNot first run: i='+i+', $scope.data[i].time_series=',$scope.data[i].time_series,', hits='+$scope.data[i].hits); }
              time_series = $scope.data[i].time_series;
              // Bug fix for wrong event count:
              //   Solr don't need to accumulate hits count since it can get total count from facet query.
              //   Therefore, I need to set hits and $scope.hits to zero.
              // hits = $scope.data[i].hits;
              hits = 0;
              $scope.hits = 0;
            }

            // Solr facet counts response is in one big array.
            // So no need to get each segment like Elasticsearch does.
            if ($scope.panel.mode === 'count') {
              // Entries from facet_ranges counts
              var entries = results.facet_counts.facet_ranges[$scope.panel.time_field].counts;
              for (var j = 0; j < entries.length; j++) {
                var entry_time = new Date(entries[j]).getTime(); // convert to millisec
                j++;
                var entry_count = entries[j];
                time_series.addValue(entry_time, entry_count);
                hits += entry_count; // The series level hits counter
                $scope.hits += entry_count; // Entire dataset level hits counter
              };
            } else if ($scope.panel.mode === 'values') {
              if ($scope.panel.group_field) {
                // Group By Field is specified
                var groups = results.grouped[$scope.panel.group_field].groups;

                for (var j=0; j < groups.length; j++) {
                  var docs = groups[j].doclist.docs;
                  var group_time_series = new timeSeries.ZeroFilled({
                    interval: _interval,
                    start_date: _range && _range.from,
                    end_date: _range && _range.to,
                    fill_style: 'minimal'
                  });
                  hits = 0;

                  // loop through each group results
                  for (var k=0; k < docs.length; k++) {
                    var entry_time = new Date(docs[k][$scope.panel.time_field]).getTime(); // convert to millisec
                    var entry_value = docs[k][$scope.panel.value_field];
                    group_time_series.addValue(entry_time, entry_value);
                    hits += 1;
                    $scope.hits += 1;
                  }

                  $scope.data[j] = {
                    // info: querySrv.list[id],
                    // Need to define chart info here according to the results, cannot use querySrv.list[id]
                    info: {
                      alias: groups[j].groupValue,
                      color: querySrv.colors[j],

                    },
                    time_series: group_time_series,
                    hits: hits
                  };
                }
              } else { // Group By Field is not specified
                var entries = results.response.docs;
                for (var j=0; j < entries.length; j++) {
                  var entry_time = new Date(entries[j][$scope.panel.time_field]).getTime(); // convert to millisec
                  var entry_value = entries[j][$scope.panel.value_field];
                  time_series.addValue(entry_time, entry_value);
                  hits += 1;
                  $scope.hits += 1;
                }

                $scope.data[i] = {
                  info: querySrv.list[id],
                  time_series: time_series,
                  hits: hits
                };
              }
            }

            if ($scope.panel.mode !== 'values') {
              $scope.data[i] = {
                info: querySrv.list[id],
                time_series: time_series,
                hits: hits
              };
            }

            i++;
          });

          if (DEBUG) { console.debug('histogram: Before render $scope=',$scope,'$scope.panel=',$scope.panel); }

          // Tell the histogram directive to render.
          $scope.$emit('render');

          // Don't need this for Solr unless we need to support multiple queries.
          // If we still have segments left, get them
          // if(segment < dashboard.indices.length-1) {
          //   $scope.get_data(segment+1,query_id);
          // }
        }
      });
    };

    // function $scope.zoom
    // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
    $scope.zoom = function(factor) {
      var _range = filterSrv.timeRange('min');
      var _timespan = (_range.to.valueOf() - _range.from.valueOf());
      var _center = _range.to.valueOf() - _timespan/2;

      var _to = (_center + (_timespan*factor)/2);
      var _from = (_center - (_timespan*factor)/2);

      // If we're not already looking into the future, don't.
      if(_to > Date.now() && _range.to < Date.now()) {
        var _offset = _to - Date.now();
        _from = _from - _offset;
        _to = Date.now();
      }

      if(factor > 1) {
        filterSrv.removeByType('time');
      }
      filterSrv.set({
        type:'time',
        from:moment.utc(_from),
        to:moment.utc(_to),
        field:$scope.panel.time_field
      });

      dashboard.refresh();

    };

    // I really don't like this function, too much dom manip. Break out into directive?
    $scope.populate_modal = function(request) {
      $scope.inspector = angular.toJson(JSON.parse(request.toString()),true);
    };

    $scope.set_refresh = function (state) {
      $scope.refresh = state;
    };

    $scope.close_edit = function() {
      if($scope.refresh) {
        $scope.get_data();
      }
      $scope.refresh =  false;
      $scope.$emit('render');
    };

    $scope.render = function() {
      $scope.$emit('render');
    };

  });

  module.directive('histogramChart', function(dashboard, filterSrv) {
    return {
      restrict: 'A',
      template: '

',
      link: function(scope, elem) {

        // Receive render events
        scope.$on('render',function(){
          render_panel();
        });

        // Re-render if the window is resized
        angular.element(window).bind('resize', function(){
          render_panel();
        });

        // Function for rendering panel
        function render_panel() {
          // IE doesn't work without this
          elem.css({height:scope.panel.height || scope.row.height});

          // Populate from the query service
          try {
            _.each(scope.data, function(series) {
              series.label = series.info.alias;
              series.color = series.info.color;
            });
          } catch(e) {return;}

          // Set barwidth based on specified interval
          var barwidth = kbn.interval_to_ms(scope.panel.interval);

          var stack = scope.panel.stack ? true : null;

          // Populate element
          try {
            var options = {
              legend: { show: false },
              series: {
                stackpercent: scope.panel.stack ? scope.panel.percentage : false,
                stack: scope.panel.percentage ? null : stack,
                lines:  {
                  show: scope.panel.lines,
                  // Silly, but fixes bug in stacked percentages
                  fill: scope.panel.fill === 0 ? 0.001 : scope.panel.fill/10,
                  lineWidth: scope.panel.linewidth,
                  steps: false
                },
                bars:   {
                  show: scope.panel.bars,
                  fill: 1,
                  barWidth: barwidth/1.8,
                  zero: false,
                  lineWidth: 0
                },
                points: {
                  show: scope.panel.points,
                  fill: 1,
                  fillColor: false,
                  radius: 5
                },
                shadowSize: 1
              },
              yaxis: {
                show: scope.panel['y-axis'],
                min: 0,
                max: scope.panel.percentage && scope.panel.stack ? 100 : null,
              },
              xaxis: {
                timezone: scope.panel.timezone,
                show: scope.panel['x-axis'],
                mode: "time",
                min: _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(),
                max: _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(),
                timeformat: time_format(scope.panel.interval),
                label: "Datetime",
              },
              grid: {
                backgroundColor: null,
                borderWidth: 0,
                hoverable: true,
                color: '#c8c8c8'
              }
            };

            if(scope.panel.interactive) {
              options.selection = { mode: "x", color: '#666' };
            }

            // when rendering stacked bars, we need to ensure each point that has data is zero-filled
            // so that the stacking happens in the proper order
            var required_times = [];
            if (scope.data.length > 1) {
              required_times = Array.prototype.concat.apply([], _.map(scope.data, function (query) {
                return query.time_series.getOrderedTimes();
              }));
              required_times = _.uniq(required_times.sort(function (a, b) {
                // decending numeric sort
                return a-b;
              }), true);
            }

            for (var i = 0; i < scope.data.length; i++) {
              scope.data[i].data = scope.data[i].time_series.getFlotPairs(required_times);
            }

            // ISSUE: SOL-76
            // If 'lines_smooth' is enabled, loop through $scope.data[] and remove zero filled entries.
            // Without zero values, the line chart will appear smooth as SiLK ;-)
            if (scope.panel.lines_smooth) {
              for (var i=0; i < scope.data.length; i++) {
                var new_data = [];
                for (var j=0; j < scope.data[i].data.length; j++) {
                  // if value of the timestamp !== 0, then add it to new_data
                  if (scope.data[i].data[j][1] !== 0) {
                    new_data.push(scope.data[i].data[j]);
                  }
                }
                scope.data[i].data = new_data;
              }
            }

            if (DEBUG) { console.debug('histogram:\n\tflot options = ',options,'\n\tscope.data = ',scope.data); }

            scope.plot = $.plot(elem, scope.data, options);
          } catch(e) {
            // TODO: Need to fix bug => "Invalid dimensions for plot, width = 0, height = 200"
            console.log(e);
          }
        }

        function time_format(interval) {
          var _int = kbn.interval_to_seconds(interval);
          if(_int >= 2628000) {
            return "%m/%y";
          }
          if(_int >= 86400) {
            return "%m/%d/%y";
          }
          if(_int >= 60) {
            return "%H:%M
%m/%d";
          }

          return "%H:%M:%S";
        }

        var $tooltip = $('
');
        elem.bind("plothover", function (event, pos, item) {
          var group, value;
          if (item) {
            if (item.series.info.alias || scope.panel.tooltip.query_as_alias) {
              group = '' +
                '' + ' ' +
                (item.series.info.alias || item.series.info.query)+
              '
';
            } else {
              group = kbn.query_color_dot(item.series.color, 15) + ' ';
            }
            if (scope.panel.stack && scope.panel.tooltip.value_type === 'individual')  {
              value = item.datapoint[1] - item.datapoint[2];
            } else {
              value = item.datapoint[1];
            }
            $tooltip
              .html(
                group + value + " @ " + moment(item.datapoint[0]).format('MM/DD HH:mm:ss')
              )
              .place_tt(pos.pageX, pos.pageY);
          } else {
            $tooltip.detach();
          }
        });

        elem.bind("plotselected", function (event, ranges) {
          filterSrv.set({
            type  : 'time',
            from  : moment.utc(ranges.xaxis.from),
            to    : moment.utc(ranges.xaxis.to),
            field : scope.panel.time_field
          });
          dashboard.refresh();
        });
      }
    };
  });

});


text:
""" Optimizations of built-ins to built-in calls.

"""
import math
import sys

from nuitka.nodes.ParameterSpecs import (
    ParameterSpec,
    TooManyArguments,
    matchCall
)
from nuitka.utils.Utils import python_version

class BuiltinParameterSpec(ParameterSpec):
    def __init__(self, name, arg_names, default_count, list_star_arg = None,
                  dict_star_arg = None):
        ParameterSpec.__init__(
            self,
            name          = name,
            normal_args   = arg_names,
            list_star_arg = list_star_arg,
            dict_star_arg = dict_star_arg,
            default_count = default_count,
            kw_only_args  = ()
        )

        self.builtin = __builtins__[name]

    def __repr__(self):
        return "<BuiltinParameterSpec %s>" % self.name

    def getName(self):
        return self.name

    def isCompileTimeComputable(self, values):
        # By default, we make this dependent on the ability to compute the
        # arguments, which is of course a good start for most cases, so this
        # is for overloads, pylint: disable=R0201

        for value in values:
            if value is not None and not value.isCompileTimeConstant():
                return False
        return True

    def simulateCall(self, given_values):
        # Using star dict call for simulation and catch any exception as really
        # fatal, pylint: disable=W0703

        try:
            given_normal_args = given_values[:len(self.normal_args)]

            if self.list_star_arg:
                given_list_star_args = given_values[len(self.normal_args)]
            else:
                given_list_star_args = None

            if self.dict_star_arg:
                given_dict_star_args = given_values[ -1 ]
            else:
                given_dict_star_args = None

            arg_dict = {}

            for arg_name, given_value in zip(self.normal_args, given_normal_args):
                assert type(given_value) not in (tuple, list), \
                  ("do not like a tuple %s" % (given_value,))

                if given_value is not None:
                    arg_dict[ arg_name ] = given_value.getCompileTimeConstant()

            if given_dict_star_args:
                for given_dict_star_arg in reversed(given_dict_star_args):
                    arg_name = given_dict_star_arg.getKey().getCompileTimeConstant()
                    arg_value = given_dict_star_arg.getValue().getCompileTimeConstant()

                    arg_dict[arg_name] = arg_value

        except Exception as e:
            sys.exit("Fatal problem: %r" % e)

        if given_list_star_args:
            return self.builtin(
                *(value.getCompileTimeConstant() for value in given_list_star_args),
                **arg_dict
            )
        else:
            return self.builtin(**arg_dict)

class BuiltinParameterSpecNoKeywords(BuiltinParameterSpec):

    def allowsKeywords(self):
        return False

    def simulateCall(self, given_values):
        # Using star dict call for simulation and catch any exception as really fatal,
        # pylint: disable=W0703

        try:
            if self.list_star_arg:
                given_list_star_arg = given_values[ len(self.normal_args) ]
            else:
                given_list_star_arg = None

            arg_list = []
            refuse_more = False

            for _arg_name, given_value in zip(self.normal_args, given_values):
                assert type(given_value) not in (tuple, list), ("do not like tuple %s" % (given_value,))

                if given_value is not None:
                    if not refuse_more:
                        arg_list.append(given_value.getCompileTimeConstant())
                    else:
                        assert False
                else:
                    refuse_more = True

            if given_list_star_arg is not None:
                arg_list += [ value.getCompileTimeConstant() for value in given_list_star_arg ]
        except Exception as e:
            print >> sys.stderr, "Fatal error: ",
            import traceback
            traceback.print_exc()
            sys.exit(repr(e))

        return self.builtin(*arg_list)

class BuiltinParameterSpecExceptions(BuiltinParameterSpec):
    def __init__(self, exception_name, default_count):
        # TODO: Parameter default_count makes no sense for exceptions probably.
        BuiltinParameterSpec.__init__(
            self,
            name          = exception_name,
            arg_names     = (),
            default_count = default_count,
            list_star_arg = "args"
        )

    def allowsKeywords(self):
        return False

    def getKeywordRefusalText(self):
        return "exceptions.%s does not take keyword arguments" % self.name

    def getCallableName(self):
        return "exceptions." + self.getName()

def makeBuiltinParameterSpec(exception_name):
    if exception_name == "ImportError" and python_version >= 330:
        # TODO: Create this beast, needs keyword only arguments to be supported,
        # currently user of this function must take care to not have them.
        pass

    return BuiltinParameterSpecExceptions(
        exception_name = exception_name,
        default_count  = 0
    )

builtin_int_spec = BuiltinParameterSpec("int", ('x', "base"), 2)

# These builtins are only available for Python2
if python_version < 300:
    builtin_long_spec = BuiltinParameterSpec(
        "long",
        ('x', "base"),
        2
    )
    builtin_execfile_spec = BuiltinParameterSpecNoKeywords(
        "execfile",
        ("filename", "globals", "locals"),
        2
    )
    builtin_unicode_spec = BuiltinParameterSpec(
        "unicode",
        ("string", "encoding", "errors"),
        3
    )
    builtin_xrange_spec = BuiltinParameterSpec(
        "xrange",
        ("start", "stop", "step"),
        2
    )

builtin_bool_spec = BuiltinParameterSpec("bool", ('x',), 1)
builtin_float_spec = BuiltinParameterSpec("float", ('x',), 1)
builtin_complex_spec = BuiltinParameterSpec("complex", ("real", "imag"), 2)

# This built-in have variable parameters for Python2/3
if python_version < 300:
    builtin_str_spec = BuiltinParameterSpec("str", ("object",), 1)
else:
    builtin_str_spec = BuiltinParameterSpec("str", ("object", "encoding", "errors"), 3)

builtin_len_spec = BuiltinParameterSpecNoKeywords("len", ("object",), 0)
builtin_dict_spec = BuiltinParameterSpec("dict", (), 0, "list_args", "dict_args")
builtin_len_spec = BuiltinParameterSpecNoKeywords("len", ("object",), 0)
builtin_tuple_spec = BuiltinParameterSpec("tuple", ("sequence",), 1)
builtin_list_spec = BuiltinParameterSpec("list", ("sequence",), 1)
builtin_set_spec = BuiltinParameterSpecNoKeywords("set", ("iterable",), 1)

builtin_import_spec = BuiltinParameterSpec("__import__", ("name", "globals", "locals", "fromlist", "level"), 4)
builtin_open_spec = BuiltinParameterSpec("open", ("name", "mode", "buffering"), 3)
builtin_chr_spec = BuiltinParameterSpecNoKeywords("chr", ('i',), 0)
builtin_ord_spec = BuiltinParameterSpecNoKeywords("ord", ('c',), 0)
builtin_bin_spec = BuiltinParameterSpecNoKeywords("bin", ("number",), 0)
builtin_oct_spec = BuiltinParameterSpecNoKeywords("oct", ("number",), 0)
builtin_hex_spec = BuiltinParameterSpecNoKeywords("hex", ("number",), 0)
builtin_id_spec = BuiltinParameterSpecNoKeywords("id", ("object",), 0)
builtin_repr_spec = BuiltinParameterSpecNoKeywords("repr", ("object",), 0)

builtin_dir_spec = BuiltinParameterSpecNoKeywords("dir", ("object",), 1)
builtin_vars_spec = BuiltinParameterSpecNoKeywords("vars", ("object",), 1)

builtin_locals_spec = BuiltinParameterSpecNoKeywords("locals", (), 0)
builtin_globals_spec = BuiltinParameterSpecNoKeywords("globals", (), 0)
builtin_eval_spec = BuiltinParameterSpecNoKeywords("eval", ("source", "globals", "locals"), 2)
if python_version < 300:
    builtin_compile_spec = BuiltinParameterSpec(
        "compile",
        ("source", "filename", "mode", "flags", "dont_inherit"),
        2
    )
else:
    builtin_compile_spec = BuiltinParameterSpec(
        "compile",
        ("source", "filename", "mode", "flags", "dont_inherit", "optimize"),
        3
    )
if python_version >= 300:
    builtin_exec_spec = BuiltinParameterSpecNoKeywords(
        "exec",
        ("source", "globals", "locals"),
        2
    )

# Note: Iter in fact names its first argument if the default applies
# "collection", fixed up in a wrapper.
builtin_iter_spec = BuiltinParameterSpecNoKeywords("iter", ("callable", "sentinel"), 1)
builtin_next_spec = BuiltinParameterSpecNoKeywords("next", ("iterator", "default"), 1)

# Note: type with 1 and type with 3 arguments are too different.
builtin_type1_spec = BuiltinParameterSpecNoKeywords("type", ("object",), 0)
builtin_type3_spec = BuiltinParameterSpecNoKeywords("type", ("name", "bases", "dict"), 0)

builtin_super_spec = BuiltinParameterSpecNoKeywords("super", ("type", "object"), 1 if python_version < 300 else 2)

builtin_hasattr_spec = BuiltinParameterSpecNoKeywords("hasattr", ("object", "name"), 0)
builtin_getattr_spec = BuiltinParameterSpecNoKeywords("getattr", ("object", "name", "default"), 1)
builtin_setattr_spec = BuiltinParameterSpecNoKeywords("setattr", ("object", "name", "value"), 0)

builtin_isinstance_spec = BuiltinParameterSpecNoKeywords("isinstance", ("instance", "classes"), 0)

builtin_bytearray_spec = BuiltinParameterSpecNoKeywords("bytearray", ("iterable_of_ints",), 1)

# Beware: One argument defines stop, not start.
builtin_slice_spec = BuiltinParameterSpecNoKeywords("slice", ("start", "stop", "step"), 2)

builtin_hash_spec = BuiltinParameterSpecNoKeywords("hash", ("object",), 0)

class BuiltinRangeSpec(BuiltinParameterSpecNoKeywords):
    def __init__(self, *args):
        BuiltinParameterSpecNoKeywords.__init__(self, *args)

    def isCompileTimeComputable(self, values):
        # For ranges, we need have many cases that can prevent the ability
        # to pre-compute, pylint: disable=R0911,R0912

        result = BuiltinParameterSpecNoKeywords.isCompileTimeComputable(
            self,
            values = values
        )

        if result:
            arg_count = len(values)

            if arg_count == 1:
                low = values[0]

                # If it's not a number constant, we can compute the exception
                # that will be raised.
                if not low.isNumberConstant():
                    return True

                return low.getConstant() < 256
            elif arg_count == 2:
                low, high = values

                # If it's not a number constant, we can compute the exception
                # that will be raised.
                if not low.isNumberConstant() or not high.isNumberConstant():
                    return True

                return high.getConstant() - low.getConstant() < 256
            elif arg_count == 3:
                low, high, step = values

                if not low.isNumberConstant() or \
                   not high.isNumberConstant() or \
                   not step.isNumberConstant():
                    return True

                low = low.getConstant()
                high = high.getConstant()
                step = step.getConstant()

                # It's going to give a ZeroDivisionError in this case.
                if step == 0:
                    return True

                if low < high:
                    if step < 0:
                        return True
                    else:
                        return math.ceil(float(high - low) / step) < 256
                else:
                    if step > 0:
                        return True
                    else:
                        return math.ceil(float(high - low) / step) < 256
            else:
                assert False
        else:
            return False

builtin_range_spec = BuiltinRangeSpec("range", ("start", "stop", "step"), 2)

def extractBuiltinArgs(node, builtin_spec, builtin_class,
                       empty_special_class = None):
    try:
        kw = node.getCallKw()

        # TODO: Could check for too many / too few, even if they are unknown, we
        # might raise that error, but that need not be optimized immediately.
        if kw is not None:
            if not kw.isMappingWithConstantStringKeys():
                return None

            pairs = kw.getMappingStringKeyPairs()

            if pairs and not builtin_spec.allowsKeywords():
                raise TooManyArguments(
                    TypeError(builtin_spec.getKeywordRefusalText())
                )
        else:
            pairs = ()

        args = node.getCallArgs()

        if args:
            if not args.canPredictIterationValues():
                return None

            positional = args.getIterationValues()
        else:
            positional = ()

        if not positional and not pairs and empty_special_class is not None:
            return empty_special_class(source_ref = node.getSourceReference())

        args_dict = matchCall(
            func_name     = builtin_spec.getName(),
            args          = builtin_spec.getArgumentNames(),
            star_list_arg = builtin_spec.getStarListArgumentName(),
            star_dict_arg = builtin_spec.getStarDictArgumentName(),
            num_defaults  = builtin_spec.getDefaultCount(),
            positional    = positional,
            pairs         = pairs
        )
    except TooManyArguments as e:
        from nuitka.nodes.NodeMakingHelpers import (
            makeRaiseExceptionReplacementExpressionFromInstance,
            wrapExpressionWithSideEffects
        )

        return wrapExpressionWithSideEffects(
            new_node     = makeRaiseExceptionReplacementExpressionFromInstance(
                expression = node,
                exception  = e.getRealException()
            ),
            old_node     = node,
            side_effects = node.extractPreCallSideEffects()
        )

    args_list = []

    for argument_name in builtin_spec.getArgumentNames():
        args_list.append(args_dict[argument_name])

    if builtin_spec.getStarListArgumentName() is not None:
        args_list.append(args_dict[builtin_spec.getStarListArgumentName()])

    if builtin_spec.getStarDictArgumentName() is not None:
        args_list.append(args_dict[builtin_spec.getStarDictArgumentName()])

    # Using list reference for passing the arguments without names,
    result = builtin_class(
        *args_list,
        source_ref = node.getSourceReference()
    )
    result.setCompatibleSourceReference(node.getCompatibleSourceReference())

    return result


text:
using Bjd.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Bjd.Traces
{
    /// <summary>
    /// Write Console Feature
    /// </summary>
    internal class ConsoleTraceListner : System.Diagnostics.TraceListener
    {

        SequentialTaskScheduler sts = new SequentialTaskScheduler();

        public ConsoleTraceListner()
        {

            this.TraceOutputOptions = System.Diagnostics.TraceOptions.DateTime;
            this.IndentSize = 1;
            try
            {
                if (Console.WindowWidth < 200)
                    Console.WindowWidth = 200;
            }
            catch (Exception)
            {
                Console.WriteLine("Not allowed change Console.WindowWidth");
            }

            try
            {
                //Console.WriteLine($"ConsoleTraceListner CodePage={Console.Out.Encoding.CodePage}");
                Define.ChangeOperationSystem += Define_ChangeOperationSystem;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error .ctor ConsoleTraceListner");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

        }

        private void Define_ChangeOperationSystem(object sender, EventArgs e)
        {
            // fix Windows ja-jp to codepage 932
            var lang = System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
            var lang2 = System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;

            if (Define.IsWindows && lang == "ja")
            {
                var enc = System.Text.CodePagesEncodingProvider.Instance;
                var sjis = enc.GetEncoding(932);
                var writer = new System.IO.StreamWriter(Console.OpenStandardOutput(), sjis);
                writer.AutoFlush = true;
                Console.SetOut(writer);
            }
        }

        public override void Write(string message)
        {
            //Console.Write(message);
            var ind = this.NeedIndent;

            var t = new Task(
                () =>
                {
                    if (ind)
                        Console.Write(new string(' ', this.IndentLevel * this.IndentSize));
                    Console.Write(message);
                }, TaskCreationOptions.PreferFairness);
            t.Start(this.sts);

        }
        protected override void WriteIndent()
        {
            //Console.Write(new string(' ', this.IndentLevel * this.IndentSize));
            var t = new Task(
                () =>
                    Console.Write(new string(' ', this.IndentLevel * this.IndentSize)), TaskCreationOptions.PreferFairness);
            t.Start(this.sts);

        }

        public override void WriteLine(string message)
        {

            //Console.WriteLine(message);
            var ind = this.NeedIndent;

            var t = new Task(
                () =>
                {
                    if (ind)
                        Console.Write(new string(' ', this.IndentLevel * this.IndentSize));
                    Console.WriteLine(message);
                }, TaskCreationOptions.PreferFairness);
            t.Start(this.sts);

        }

        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
        {
            if (this.Filter != null)
            {
                if (!this.Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
                    return;
            }

            var ind = this.NeedIndent;
            Action tAct = () =>
            {
                //var sb = new System.Text.StringBuilder();

                if (this.TraceOutputOptions.HasFlag(TraceOptions.DateTime))
                {
                    var date = eventCache.DateTime.ToLocalTime().ToString("HH\\:mm\\:ss\\.fff");
                    //sb.Append($"[{date}]");
                    Console.Write($"[{date}]");
                }
                if (this.TraceOutputOptions.HasFlag(TraceOptions.Timestamp))
                {
                    //var time = TimeSpan.FromTicks(eventCache.Timestamp).ToString("hh\\:mm\\:ss\\.fffff");
                    ////sb.Append($"[{time}]");
                    //Console.Write($"[{time}]");
                    Console.Write($"[{eventCache.Timestamp}]");
                }
                if (this.TraceOutputOptions.HasFlag(TraceOptions.ProcessId))
                {
                    //sb.Append($"[PID:{eventCache.ProcessId}]");
                    Console.Write($"[PID:{eventCache.ProcessId}]");
                }
                if (this.TraceOutputOptions.HasFlag(TraceOptions.ThreadId))
                {
                    //sb.Append($"[{eventCache.ThreadId.PadLeft(3)}]");
                    Console.Write($"[{eventCache.ThreadId.PadLeft(3)}]");
                }

                //sb.Append($"[{eventType.ToString().Remove(4)}][{id}] ");
                //sb.Append($"[{id}] ");
                Console.Write($"[{id}] ");
                if (NeedIndent)
                {
                    //sb.Append(new string(' ', this.IndentLevel * this.IndentSize));
                    Console.Write(new string(' ', this.IndentLevel * this.IndentSize));
                }
                //sb.Append(message);
                Console.WriteLine(message);
                //Console.WriteLine(sb.ToString());
                //base.TraceEvent(eventCache, source, eventType, id, message);
            };
            var t = new Task(tAct, TaskCreationOptions.PreferFairness);
            t.Start(this.sts);

        }

    }

}


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

@Component({
  selector: 'app-comp-2034',
  templateUrl: './comp-2034.component.html',
  styleUrls: ['./comp-2034.component.css']
})
export class Comp2034Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Application.Editions;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;

namespace Abp.MultiTenancy
{
    /// <summary>
    /// Represents a Tenant of the application.
    /// </summary>
    [Table("AbpTenants")]
    public class AbpTenant<TTenant, TUser> : FullAuditedEntity<int, TUser>, IPassivable
        where TUser : AbpUser<TTenant, TUser>
        where TTenant : AbpTenant<TTenant, TUser>
    {
        /// <summary>
        /// "Default".
        /// </summary>
        public const string DefaultTenantName = "Default";

        /// <summary>
        /// "^[a-zA-Z][a-zA-Z0-9_-]{1,}$".
        /// </summary>
        public const string TenancyNameRegex = "^[a-zA-Z][a-zA-Z0-9_-]{1,}$";

        /// <summary>
        /// Max length of the <see cref="TenancyName"/> property.
        /// </summary>
        public const int MaxTenancyNameLength = 64;

        /// <summary>
        /// Max length of the <see cref="Name"/> property.
        /// </summary>
        public const int MaxNameLength = 128;

        /// <summary>
        /// Tenancy name. This property is the UNIQUE name of this Tenant.
        /// It can be used as subdomain name in a web application.
        /// </summary>
        [Required]
        [StringLength(MaxTenancyNameLength)]
        public virtual string TenancyName { get; set; }

        /// <summary>
        /// Current <see cref="Edition"/> of the Tenant.
        /// </summary>
        public virtual Edition Edition { get; set; }
        public virtual int? EditionId { get; set; }

        /// <summary>
        /// Display name of the Tenant.
        /// </summary>
        [Required]
        [StringLength(MaxNameLength)]
        public virtual string Name { get; set; }

        /// <summary>
        /// Is this tenant active?
        /// If as tenant is not active, no user of this tenant can use the application.
        /// </summary>
        public virtual bool IsActive { get; set; }

        /// <summary>
        /// Defined settings for this tenant.
        /// </summary>
        [ForeignKey("TenantId")]
        public virtual ICollection<Setting> Settings { get; set; }

        /// <summary>
        /// Creates a new tenant.
        /// </summary>
        public AbpTenant()
        {
            IsActive = true;
        }

        /// <summary>
        /// Creates a new tenant.
        /// </summary>
        /// <param name="tenancyName">UNIQUE name of this Tenant</param>
        /// <param name="name">Display name of the Tenant</param>
        public AbpTenant(string tenancyName, string name)
            : this()
        {
            TenancyName = tenancyName;
            Name = name;
        }
    }
}


text:
using Moq;
using NUnit.Framework;

using OldBoardGamesNeedLoveToo.Data.Repositories;
using OldBoardGamesNeedLoveToo.Data.UnitOfWork;
using OldBoardGamesNeedLoveToo.Models;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace OldBoardGamesNeedLoveToo.Services.Tests.GamesServiceTests
{
    [TestFixture]
    public class GetAllGamesOfCurrentUser_Should
    {
        [Test]
        public void Throw_WhenIdIsEmpty()
        {
            var gamesRepositoryMock = new Mock<IRepository<Game>>();
            var categoryRepositoryMock = new Mock<IRepository<Category>>();
            var unitOfWorkMock = new Mock<IUnitOfWork>();

            var gamesService = new GamesService(gamesRepositoryMock.Object, categoryRepositoryMock.Object, unitOfWorkMock.Object);

            Assert.Throws<ArgumentException>(() => gamesService.GetAllGamesOfCurrentUser(Guid.Empty));
        }

        [Test]
        public void Invoke_TheRepositoryMethodGetAll_Once()
        {
            var gamesRepositoryMock = new Mock<IRepository<Game>>();
            var categoryRepositoryMock = new Mock<IRepository<Category>>();
            var unitOfWorkMock = new Mock<IUnitOfWork>();
            var id = Guid.Parse("1db6f07d-46f2-4a63-8efd-10306478dd7e");

            var gamesService = new GamesService(gamesRepositoryMock.Object, categoryRepositoryMock.Object, unitOfWorkMock.Object);

            gamesRepositoryMock.Setup(x => x.GetAll(It.IsAny<Expression<Func<Game, bool>>>()));

            gamesService.GetAllGamesOfCurrentUser(id);

            gamesRepositoryMock.Verify(x => x.GetAll(It.IsAny<Expression<Func<Game, bool>>>()), Times.Once);

        }

        [Test]
        public void ReturnResult_WhenInvokingRepositoryMethod_GetAll()
        {
            var gamesRepositoryMock = new Mock<IRepository<Game>>();
            var categoryRepositoryMock = new Mock<IRepository<Category>>();
            var unitOfWorkMock = new Mock<IUnitOfWork>();
            var userId= Guid.Parse("1db6f07d-46f2-4a63-8efd-10306478dd7d");
            var gameId1 = Guid.Parse("1db6f07d-46f2-4a63-8efd-10306478dd7e");
            var gameId2 = Guid.Parse("1db6f07d-46f2-4a63-8efd-10306478dd7c");
            var name1 = "name1";
            var name2 = "name2";
            var gamesService = new GamesService(gamesRepositoryMock.Object, categoryRepositoryMock.Object, unitOfWorkMock.Object);

            var expectedReturnedGames = new List<Game>()
            {
                new Game()
                {
                    Id =gameId1,
                    Name=name1
                },
                new Game()
                {
                    Id =gameId2,
                    Name=name2
                }
            };

            gamesRepositoryMock.Setup(x => x.GetAll(It.IsAny<Expression<Func<Game, bool>>>())).Returns(expectedReturnedGames);

            var actualReturnedGames=gamesService.GetAllGamesOfCurrentUser(userId);
            Assert.AreSame(expectedReturnedGames, actualReturnedGames);

        }

        [Test]
        public void ReturnResultAsTheCorrectType()
        {
            var gamesRepositoryMock = new Mock<IRepository<Game>>();
            var categoryRepositoryMock = new Mock<IRepository<Category>>();
            var unitOfWorkMock = new Mock<IUnitOfWork>();
            var userId = Guid.Parse("1db6f07d-46f2-4a63-8efd-10306478dd7d");
            var gameId1 = Guid.Parse("1db6f07d-46f2-4a63-8efd-10306478dd7e");
            var gameId2 = Guid.Parse("1db6f07d-46f2-4a63-8efd-10306478dd7c");
            var name1 = "name1";
            var name2 = "name2";
            var gamesService = new GamesService(gamesRepositoryMock.Object, categoryRepositoryMock.Object, unitOfWorkMock.Object);

            var expectedReturnedGames = new List<Game>()
            {
                new Game()
                {
                    Id =gameId1,
                    Name=name1
                },
                new Game()
                {
                    Id =gameId2,
                    Name=name2
                }
            };

            gamesRepositoryMock.Setup(x => x.GetAll(It.IsAny<Expression<Func<Game, bool>>>())).Returns(expectedReturnedGames);

            var actualReturnedGames = gamesService.GetAllGamesOfCurrentUser(userId);
            Assert.That(actualReturnedGames, Is.InstanceOf<IEnumerable<Game>>());

        }
    }
}


text:
<test>
  <title>Groups of selectors</title>

The background of this list item should be green

The background of this second list item should be also green

The background of this paragraph should be green.

</test>


text:
package org.jetbrains.plugins.groovy.runner;

import com.intellij.execution.CantRunException;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.runners.ExecutionUtil;
import com.intellij.execution.util.ScriptFileUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.ClasspathEditor;
import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import com.intellij.openapi.vfs.encoding.EncodingProjectManager;
import com.intellij.util.net.HttpConfigurable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.incremental.groovy.GroovycOutputParser;
import org.jetbrains.plugins.groovy.config.GroovyFacetUtil;
import org.jetbrains.plugins.groovy.grape.GrabDependencies;
import org.jetbrains.plugins.groovy.util.LibrariesUtil;

import java.nio.charset.Charset;

public class DefaultGroovyScriptRunner extends GroovyScriptRunner {

  @Override
  public boolean isValidModule(@NotNull Module module) {
    return LibrariesUtil.hasGroovySdk(module);
  }

  @Override
  public boolean ensureRunnerConfigured(@Nullable Module module, RunProfile profile, Executor executor, final Project project) throws ExecutionException {
    if (module == null) {
      throw new ExecutionException("Module is not specified");
    }

    if (LibrariesUtil.getGroovyHomePath(module) == null) {
      ExecutionUtil.handleExecutionError(project, executor.getToolWindowId(), profile, new ExecutionException("Groovy is not configured"));
      ModulesConfigurator.showDialog(module.getProject(), module.getName(), ClasspathEditor.NAME);
      return false;
    }
    return true;
  }

  @Override
  public void configureCommandLine(JavaParameters params, @Nullable Module module, boolean tests, VirtualFile script, GroovyScriptRunConfiguration configuration) throws CantRunException {
    configureGenericGroovyRunner(params, module, "groovy.ui.GroovyMain", false, tests);

    //addClasspathFromRootModel(module, tests, params, true);

    params.getVMParametersList().addParametersString(configuration.getVMParameters());

    addScriptEncodingSettings(params, script, module);

    if (configuration.isDebugEnabled()) {
      params.getProgramParametersList().add("--debug");
    }

    String path = ScriptFileUtil.getLocalFilePath(StringUtil.notNullize(configuration.getScriptPath()));
    params.getProgramParametersList().add(FileUtil.toSystemDependentName(path));
    params.getProgramParametersList().addParametersString(configuration.getScriptParameters());
  }

  public static void configureGenericGroovyRunner(@NotNull JavaParameters params,
                                                  @NotNull Module module,
                                                  @NotNull String mainClass,
                                                  boolean useBundled,
                                                  boolean tests) throws CantRunException {
    final VirtualFile groovyJar = findGroovyJar(module);
    if (useBundled) {
      params.getClassPath().add(GroovyFacetUtil.getBundledGroovyJar());
    }
    else if (groovyJar != null) {
      params.getClassPath().add(groovyJar);
    }

    getClassPathFromRootModel(module, tests, params, true, params.getClassPath());

    setToolsJar(params);

    String groovyHome = useBundled ? FileUtil.toCanonicalPath(GroovyFacetUtil.getBundledGroovyJar().getParentFile().getParent()) : LibrariesUtil.getGroovyHomePath(module);
    String groovyHomeDependentName = groovyHome != null ? FileUtil.toSystemDependentName(groovyHome) : null;

    if (groovyHomeDependentName != null) {
      setGroovyHome(params, groovyHomeDependentName);
    }

    final String confPath = getConfPath(groovyHomeDependentName);
    params.getVMParametersList().add("-Dgroovy.starter.conf=" + confPath);
    params.getVMParametersList().addAll(HttpConfigurable.convertArguments(HttpConfigurable.getJvmPropertiesList(false, null)));

    params.setMainClass("org.codehaus.groovy.tools.GroovyStarter");

    params.getProgramParametersList().add("--conf");
    params.getProgramParametersList().add(confPath);

    params.getProgramParametersList().add("--main");
    params.getProgramParametersList().add(mainClass);

    if (!GrabDependencies.GRAPE_RUNNER.equals(mainClass)) {
      addClasspathFromRootModel(module, tests, params, true);
    }

    if (params.getVMParametersList().getPropertyValue(GroovycOutputParser.GRAPE_ROOT) == null) {
      String sysRoot = System.getProperty(GroovycOutputParser.GRAPE_ROOT);
      if (sysRoot != null) {
        params.getVMParametersList().defineProperty(GroovycOutputParser.GRAPE_ROOT, sysRoot);
      }
    }
  }

  private static void addScriptEncodingSettings(final JavaParameters params, final VirtualFile scriptFile, Module module) {
    Charset charset = EncodingProjectManager.getInstance(module.getProject()).getEncoding(scriptFile, true);
    if (charset == null) {
      charset = EncodingManager.getInstance().getDefaultCharset();
      if (!Comparing.equal(CharsetToolkit.getDefaultSystemCharset(), charset)) {
        params.getProgramParametersList().add("--encoding=" + charset.displayName());
      }
    }
    else {
      params.getProgramParametersList().add("--encoding=" + charset.displayName());
    }
  }

}


text:
		保存

					监听器实例
					Type
					Event
					Fields
					Action


text:
package org.jboss.weld.tests.extensions.lifecycle.processProducerField;

import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.AnnotatedParameter;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.ProcessProducerField;

public class VerifyingExtension implements Extension {

    private AnnotatedParameter<Integer> disposedParameter;

    public void observeProducer(@Observes ProcessProducerField<Integer, Producer> event) {
        this.disposedParameter = event.getAnnotatedDisposedParameter();
    }

    public AnnotatedParameter<Integer> getDisposedParameter() {
        return disposedParameter;
    }
}


text:
#include "radeon_compiler.h"

#include <stdio.h>

#include "radeon_dataflow.h"
#include "radeon_emulate_branches.h"
#include "radeon_emulate_loops.h"
#include "radeon_program_alu.h"
#include "radeon_program_tex.h"
#include "radeon_rename_regs.h"
#include "radeon_remove_constants.h"
#include "r300_fragprog.h"
#include "r300_fragprog_swizzle.h"
#include "r500_fragprog.h"

static void dataflow_outputs_mark_use(void * userdata, void * data,
		void (*callback)(void *, unsigned int, unsigned int))
{
	struct r300_fragment_program_compiler * c = userdata;
	callback(data, c->OutputColor[0], RC_MASK_XYZW);
	callback(data, c->OutputColor[1], RC_MASK_XYZW);
	callback(data, c->OutputColor[2], RC_MASK_XYZW);
	callback(data, c->OutputColor[3], RC_MASK_XYZW);
	callback(data, c->OutputDepth, RC_MASK_W);
}

static void rc_rewrite_depth_out(struct radeon_compiler *cc, void *user)
{
	struct r300_fragment_program_compiler *c = (struct r300_fragment_program_compiler*)cc;
	struct rc_instruction *rci;

	for (rci = c->Base.Program.Instructions.Next; rci != &c->Base.Program.Instructions; rci = rci->Next) {
		struct rc_sub_instruction * inst = &rci->U.I;

		if (inst->DstReg.File != RC_FILE_OUTPUT || inst->DstReg.Index != c->OutputDepth)
			continue;

		if (inst->DstReg.WriteMask & RC_MASK_Z) {
			inst->DstReg.WriteMask = RC_MASK_W;
		} else {
			inst->DstReg.WriteMask = 0;
			continue;
		}

		switch (inst->Opcode) {
			case RC_OPCODE_FRC:
			case RC_OPCODE_MOV:
				inst->SrcReg[0] = lmul_swizzle(RC_SWIZZLE_ZZZZ, inst->SrcReg[0]);
				break;
			case RC_OPCODE_ADD:
			case RC_OPCODE_MAX:
			case RC_OPCODE_MIN:
			case RC_OPCODE_MUL:
				inst->SrcReg[0] = lmul_swizzle(RC_SWIZZLE_ZZZZ, inst->SrcReg[0]);
				inst->SrcReg[1] = lmul_swizzle(RC_SWIZZLE_ZZZZ, inst->SrcReg[1]);
				break;
			case RC_OPCODE_CMP:
			case RC_OPCODE_MAD:
				inst->SrcReg[0] = lmul_swizzle(RC_SWIZZLE_ZZZZ, inst->SrcReg[0]);
				inst->SrcReg[1] = lmul_swizzle(RC_SWIZZLE_ZZZZ, inst->SrcReg[1]);
				inst->SrcReg[2] = lmul_swizzle(RC_SWIZZLE_ZZZZ, inst->SrcReg[2]);
				break;
			default:
				// Scalar instructions needn't be reswizzled
				break;
		}
	}
}

void r3xx_compile_fragment_program(struct r300_fragment_program_compiler* c)
{
	int is_r500 = c->Base.is_r500;
	int kill_consts = c->Base.remove_unused_constants;
	int opt = !c->Base.disable_optimizations;

	/* Lists of instruction transformations. */
	struct radeon_program_transformation rewrite_tex[] = {
		{ &radeonTransformTEX, c },
		{ 0, 0 }
	};

	struct radeon_program_transformation native_rewrite_r500[] = {
		{ &r500_transform_IF, 0 },
		{ &radeonTransformALU, 0 },
		{ &radeonTransformDeriv, 0 },
		{ &radeonTransformTrigScale, 0 },
		{ 0, 0 }
	};

	struct radeon_program_transformation native_rewrite_r300[] = {
		{ &radeonTransformALU, 0 },
		{ &r300_transform_trig_simple, 0 },
		{ 0, 0 }
	};

	/* List of compiler passes. */
	struct radeon_compiler_pass fs_list[] = {
		/* NAME				DUMP PREDICATE	FUNCTION			PARAM */
		{"rewrite depth out",		1, 1,		rc_rewrite_depth_out,		NULL},
		/* This transformation needs to be done before any of the IF
		 * instructions are modified. */
		{"transform KILP",		1, 1,		rc_transform_KILP,		NULL},
		{"unroll loops",		1, is_r500,	rc_unroll_loops,		NULL},
		{"transform loops",		1, !is_r500,	rc_transform_loops,		NULL},
		{"emulate branches",		1, !is_r500,	rc_emulate_branches,		NULL},
		{"transform TEX",		1, 1,		rc_local_transform,		rewrite_tex},
		{"native rewrite",		1, is_r500,	rc_local_transform,		native_rewrite_r500},
		{"native rewrite",		1, !is_r500,	rc_local_transform,		native_rewrite_r300},
		{"deadcode",			1, opt,		rc_dataflow_deadcode,		dataflow_outputs_mark_use},
		{"emulate loops",		1, !is_r500,	rc_emulate_loops,		NULL},
		{"dataflow optimize",		1, opt,		rc_optimize,			NULL},
		{"dataflow swizzles",		1, 1,		rc_dataflow_swizzles,		NULL},
		{"dead constants",		1, kill_consts, rc_remove_unused_constants,	&c->code->constants_remap_table},
		/* This pass makes it easier for the scheduler to group TEX
		 * instructions and reduces the chances of creating too
		 * many texture indirections.*/
		{"register rename",		1, !is_r500,	rc_rename_regs,			NULL},
		{"pair translate",		1, 1,		rc_pair_translate,		NULL},
		{"pair scheduling",		1, 1,		rc_pair_schedule,		NULL},
		{"register allocation",		1, opt,		rc_pair_regalloc,		NULL},
		{"dumb register allocation",	1, !opt,	rc_pair_regalloc_inputs_only,	NULL},
		{"final code validation",	0, 1,		rc_validate_final_shader,	NULL},
		{"machine code generation",	0, is_r500,	r500BuildFragmentProgramHwCode,	NULL},
		{"machine code generation",	0, !is_r500,	r300BuildFragmentProgramHwCode,	NULL},
		{"dump machine code",		0, is_r500  && c->Base.Debug, r500FragmentProgramDump, NULL},
		{"dump machine code",		0, !is_r500 && c->Base.Debug, r300FragmentProgramDump, NULL},
		{NULL, 0, 0, NULL, NULL}
	};

	c->Base.SwizzleCaps = c->Base.is_r500 ? &r500_swizzle_caps : &r300_swizzle_caps;

	rc_run_compiler(&c->Base, fs_list, "Fragment Program");

	rc_constants_copy(&c->code->constants, &c->Base.Program.Constants);
}


text:
1. Queries

2. Mutations

3. Subscriptions

4. Fragments

## Runtime

1. Schema


text:
<show params="value: api, options: {value:'href'}, events: {onclick: select}"></show>

<selected-api params="value: api, selected: selectedApi, config: config"></selected-api>


text:
package org.ebayopensource.turmeric.runtime.common.impl.handlers;

import java.util.List;

import org.ebayopensource.turmeric.runtime.common.exceptions.ServiceException;
import org.ebayopensource.turmeric.runtime.common.pipeline.MessageContext;

import org.ebayopensource.turmeric.common.v1.types.CommonErrorData;

/**
 * Detects the presence of Response Resident Errors in the MessageContext.
 * It should be customized by overriding {@link #getErrorDataList(MessageContext)}
 *
 * @author stecheng
 * @version 1.0
 * @since SOA 2.2
 */
public abstract class ResponseResidentErrorHandler extends BaseHandler {

	@Override
	public void init(InitContext ctx) throws ServiceException
	{
		super.init( ctx );
	}

	/**
	 * Determine if there are RRE's in the response and add them to the MessageContext
	 * @throws ServiceException if there were if there were errors retrieving the ErrorData
	 */
	@Override
	public void invoke(MessageContext ctx) throws ServiceException {
		/* inbound raw mode is not supported*/
		if (ctx.isInboundRawMode())
			return;
		try {
			List<CommonErrorData> errorDataList = getErrorDataList( ctx );
			handleResponseResidentErrors( ctx, errorDataList );
		} catch ( IllegalArgumentException e ) {
			throw new ServiceException( "Unable to retrieve ErrorData: " + e.getMessage() );
		}
	}

	/**
	 * Fetch a List of ErrorData from the response message.
	 *
	 * @param ctx
	 * @return List<ErrorData> from the response message
	 * @throws IllegalArgumentException if an error occurred retrieving the ErrorData
	 */
	protected abstract List<CommonErrorData> getErrorDataList(MessageContext ctx) throws IllegalArgumentException;

	private void handleResponseResidentErrors( MessageContext ctx, List<CommonErrorData> errorDataList ) {
		if ( errorDataList == null ) return;
		for ( CommonErrorData errorData : errorDataList ) {
			ctx.addResponseResidentError( errorData );
		}
	}
}


text:
import os
import sys
import operator
import numpy as np
import itertools as it

from glob import glob
from multiprocessing import Pool

from .config import *

def start_process():
    pass

def do_something(d):
    result = d.run()
    return result

def retrieve_samples(input_path, file_type):

    dir_names = []
    for root, subFolders, files in os.walk(input_path):
        for f in files:
            if f[-len(file_type):] == file_type:
                dir_names += [root]
                break

    dir_names = sorted(dir_names)

    fnames = []
    for dir_name in dir_names:
        dir_fnames = sorted(glob(os.path.join(input_path, dir_name, '*.' + file_type)))
        fnames += dir_fnames

    return fnames

def padwithtens(vector, pad_width, iaxis, kwargs):
    vector[:pad_width[0]] = 10
    vector[-pad_width[1]:] = 10
    return vector

def grouper(n, iterable, fillvalue=None):
    """
    grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    """
    args = [iter(iterable)] * n
    return it.izip_longest(fillvalue=fillvalue, *args)

def mosaic(w, imgs):
    """
    Make a grid from images.
    w    -- number of grid columns
    imgs -- images (must have same size and format)
    """
    imgs = iter(imgs)
    img0 = imgs.next()
    pad = np.zeros_like(img0)
    imgs = it.chain([img0], imgs)
    rows = grouper(w, imgs, pad)
    return np.vstack(map(np.hstack, rows))

def progressbar(name, i, total, barLen = 20):
        percent = float(i) / total

        sys.stdout.write("\r")
        progress = ""
        for i in range(barLen):
            if i < int(barLen * percent):
                progress += "="
            else:
                progress += " "
        sys.stdout.write("%s: [ %s ] %.2f%%" % (name, progress, percent * 100))
        sys.stdout.flush()

class RunInParallel():
    def __init__(self, tasks, n_proc =(cpu_count()-1)):
        self._pool = Pool(initializer=start_process, processes=n_proc)
        self._tasks = tasks

    def run(self):
        pool_outs = self._pool.map_async(do_something, self._tasks)
        self._pool.close()
        self._pool.join()

        try:
            work_done = [out for out in pool_outs.get() if out==True ]
            assert (len(work_done)) == len(self._tasks)
        except Exception:
            sys.stderr.write("ERROR: some objects could not be processed!\n")
            sys.exit(1)

def replace_from_list(string_list, old_str, new_str):
    return map(lambda x: str.replace(x, old_str, new_str), string_list)

def creating_csv(f_results, output_path, test_set, measure):

    f_measure  = [f for f in f_results if((test_set in f) and (measure in f))]

    configs, values = [], []
    for f_m in f_measure:
        configs += [os.path.dirname(os.path.relpath(f_m, output_path))]
        values += [float(open(f_m,'r').readline())]

    configs_orin = configs
    configs = replace_from_list(configs, '/', ',')

    configs = replace_from_list(configs, test_set, '')
    configs = replace_from_list(configs, 'classifiers,', '')

    configs = replace_from_list(configs, '300,', '')

    configs = replace_from_list(configs, 'realization_1', 'R1')
    configs = replace_from_list(configs, 'realization_2', 'R2')
    configs = replace_from_list(configs, 'realization_3', 'R3')

    configs = replace_from_list(configs, 'centerframe', 'C')
    configs = replace_from_list(configs, 'wholeframe', 'W')

    configs = replace_from_list(configs, 'dftenergymag',   'ME')
    configs = replace_from_list(configs, 'dftentropymag',  'MS')
    configs = replace_from_list(configs, 'dftenergyphase', 'PE')
    configs = replace_from_list(configs, 'dftentropyphase','PS')

    configs = replace_from_list(configs, 'kmeans', 'K')
    configs = replace_from_list(configs, 'random', 'R')

    configs = replace_from_list(configs, 'class_based', 'D')
    configs = replace_from_list(configs, 'unified', 'S')

    configs = replace_from_list(configs, 'svm', 'SVM')
    configs = replace_from_list(configs, 'pls', 'PLS')

    configs = replace_from_list(configs, 'energy_phase', 'PE')
    configs = replace_from_list(configs, 'entropy_phase', 'PH')
    configs = replace_from_list(configs, 'energy_mag', 'ME')
    configs = replace_from_list(configs, 'entropy_mag', 'MH')
    configs = replace_from_list(configs, 'mutualinfo_phase', 'PMI')
    configs = replace_from_list(configs, 'mutualinfo_mag', 'MMI')
    configs = replace_from_list(configs, 'correlation_phase', 'PC')
    configs = replace_from_list(configs, 'correlation_mag', 'MC')

    reverse = False if 'hter' in measure else True

    results = sorted(zip(configs, values), key=operator.itemgetter(1), reverse=reverse)

    fname = "{0}/{1}.{2}.csv".format(output_path, test_set, measure)
    f_csv = open(fname, 'w')
    f_csv.write("N,LGF,M,CS,SDD,DS,CP,C,%s\n" % str(measure).upper())
    for r in results:
        f_csv.write("%s%s\n" % (r[0], r[1]))
    f_csv.close()

    print fname, results[:4]

    return sorted(zip(configs_orin, values), key=operator.itemgetter(1), reverse=reverse)


text:
<?php

// ShopShopBundle:Basket:basket.html.twig
return array (
);


text:
import os
from io import BytesIO

import willow
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import FileExtensionValidator
from django.forms.fields import FileField, ImageField
from django.template.defaultfilters import filesizeformat
from django.utils.translation import gettext_lazy as _

ALLOWED_EXTENSIONS = ["gif", "jpg", "jpeg", "png", "webp"]
SUPPORTED_FORMATS_TEXT = _("GIF, JPEG, PNG, WEBP")

class WagtailImageField(ImageField):
    default_validators = [FileExtensionValidator(ALLOWED_EXTENSIONS)]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Get max upload size from settings
        self.max_upload_size = getattr(
            settings, "WAGTAILIMAGES_MAX_UPLOAD_SIZE", 10 * 1024 * 1024
        )
        self.max_image_pixels = getattr(
            settings, "WAGTAILIMAGES_MAX_IMAGE_PIXELS", 128 * 1000000
        )
        max_upload_size_text = filesizeformat(self.max_upload_size)

        # Help text
        if self.max_upload_size is not None:
            self.help_text = _(
                "Supported formats: %(supported_formats)s. Maximum filesize: %(max_upload_size)s."
            ) % {
                "supported_formats": SUPPORTED_FORMATS_TEXT,
                "max_upload_size": max_upload_size_text,
            }
        else:
            self.help_text = _("Supported formats: %(supported_formats)s.") % {
                "supported_formats": SUPPORTED_FORMATS_TEXT,
            }

        # Error messages
        self.error_messages["invalid_image_extension"] = (
            _("Not a supported image format. Supported formats: %s.")
            % SUPPORTED_FORMATS_TEXT
        )

        self.error_messages["invalid_image_known_format"] = _(
            "Not a valid .%s image. The extension does not match the file format (%s)"
        )

        self.error_messages["file_too_large"] = (
            _("This file is too big (%%s). Maximum filesize %s.") % max_upload_size_text
        )

        self.error_messages["file_too_many_pixels"] = (
            _("This file has too many pixels (%%s). Maximum pixels %s.")
            % self.max_image_pixels
        )

        self.error_messages["file_too_large_unknown_size"] = (
            _("This file is too big. Maximum filesize %s.") % max_upload_size_text
        )

    def check_image_file_format(self, f):
        # Check file extension
        extension = os.path.splitext(f.name)[1].lower()[1:]

        if extension not in ALLOWED_EXTENSIONS:
            raise ValidationError(
                self.error_messages["invalid_image_extension"],
                code="invalid_image_extension",
            )

        if extension == "jpg":
            extension = "jpeg"

        # Check that the internal format matches the extension
        # It is possible to upload PSD files if their extension is set to jpg, png or gif. This should catch them out
        if extension != f.image.format_name:
            raise ValidationError(
                self.error_messages["invalid_image_known_format"]
                % (extension, f.image.format_name),
                code="invalid_image_known_format",
            )

    def check_image_file_size(self, f):
        # Upload size checking can be disabled by setting max upload size to None
        if self.max_upload_size is None:
            return

        # Check the filesize
        if f.size > self.max_upload_size:
            raise ValidationError(
                self.error_messages["file_too_large"] % (filesizeformat(f.size),),
                code="file_too_large",
            )

    def check_image_pixel_size(self, f):
        # Upload pixel size checking can be disabled by setting max upload pixel to None
        if self.max_image_pixels is None:
            return

        # Check the pixel size
        width, height = f.image.get_size()
        frames = f.image.get_frame_count()
        num_pixels = width * height * frames

        if num_pixels > self.max_image_pixels:
            raise ValidationError(
                self.error_messages["file_too_many_pixels"] % (num_pixels),
                code="file_too_many_pixels",
            )

    def to_python(self, data):
        """
        Check that the file-upload field data contains a valid image (GIF, JPG,
        PNG, etc. -- whatever Willow supports). Overridden from ImageField to use
        Willow instead of Pillow as the image library in order to enable SVG support.
        """
        f = FileField.to_python(self, data)
        if f is None:
            return None

        # We need to get a file object for Pillow. We might have a path or we might
        # have to read the data into memory.
        if hasattr(data, "temporary_file_path"):
            file = data.temporary_file_path()
        else:
            if hasattr(data, "read"):
                file = BytesIO(data.read())
            else:
                file = BytesIO(data["content"])

        try:
            # Annotate the python representation of the FileField with the image
            # property so subclasses can reuse it for their own validation
            f.image = willow.Image.open(file)
            f.content_type = image_format_name_to_content_type(f.image.format_name)

        except Exception as exc:
            # Willow doesn't recognize it as an image.
            raise ValidationError(
                self.error_messages["invalid_image"],
                code="invalid_image",
            ) from exc

        if hasattr(f, "seek") and callable(f.seek):
            f.seek(0)

        if f is not None:
            self.check_image_file_size(f)
            self.check_image_file_format(f)
            self.check_image_pixel_size(f)

        return f

def image_format_name_to_content_type(image_format_name):
    """
    Convert a Willow image format name to a content type.
    TODO: Replace once https://github.com/wagtail/Willow/pull/102 and
          a new Willow release is out
    """
    if image_format_name == "svg":
        return "image/svg+xml"
    elif image_format_name == "jpeg":
        return "image/jpeg"
    elif image_format_name == "png":
        return "image/png"
    elif image_format_name == "gif":
        return "image/gif"
    elif image_format_name == "bmp":
        return "image/bmp"
    elif image_format_name == "tiff":
        return "image/tiff"
    elif image_format_name == "webp":
        return "image/webp"
    else:
        raise ValueError("Unknown image format name")


text:
import sys
import os
import argparse
from configparser import ConfigParser
from vagrantctl.core.control import Control

def parse_config():
    config_file = os.path.join(os.environ['HOME'], '.vagrantctl')
    try:
        parser = ConfigParser()
        parser.read(config_file)
        base_directory = parser.get('vagrantctl', 'base-directory')
    except:
        base_directory = os.getcwd()

    return os.path.abspath(base_directory)

def parse_options(base_directory):
    parser = argparse.ArgumentParser(description='vagrantctl')
    parser.add_argument('-b', '--base-directory',
                        default=base_directory,
                        help='VM base directory')
    parser.add_argument('-v', '--verbose',
                        action='store_true',
                        help='verbose output')

    subparsers = parser.add_subparsers()

    parser_list = subparsers.add_parser('list')
    parser_list.set_defaults(list=True)

    parser_up = subparsers.add_parser('up')
    parser_up.set_defaults(up=True)
    parser_up.add_argument('VM',
                           help='VM name')

    parser_halt = subparsers.add_parser('halt')
    parser_halt.set_defaults(halt=True)
    parser_halt.add_argument('VM',
                             help='VM name')

    parser_suspend = subparsers.add_parser('suspend')
    parser_suspend.set_defaults(suspend=True)
    parser_suspend.add_argument('VM',
                                help='VM name')

    parser_resume = subparsers.add_parser('resume')
    parser_resume.set_defaults(resume=True)
    parser_resume.add_argument('VM',
                               help='VM name')

    parser_reload = subparsers.add_parser('reload')
    parser_reload.set_defaults(reload=True)
    parser_reload.add_argument('VM',
                               help='VM name')

    parser_status = subparsers.add_parser('status')
    parser_status.set_defaults(status=True)
    parser_status.add_argument('VM',
                               help='VM name')

    parser_ssh_config = subparsers.add_parser('ssh-config')
    parser_ssh_config.set_defaults(ssh_config=True)
    parser_ssh_config.add_argument('VM',
                                   help='VM name')

    parser_config = subparsers.add_parser('config')
    parser_config.set_defaults(config=True)
    parser_config.add_argument('-s', '--show',
                               action='store_true',
                               dest='config_show',
                               help='output Vagrantfile')
    parser_config.add_argument('VM',
                               help='VM name')
    parser_snapshot = subparsers.add_parser('snapshot')
    parser_snapshot.set_defaults(snapshot=True)
    parser_snapshot.add_argument('-l', '--list',
                                 action='store_true',
                                 dest='snapshot_list',
                                 help='list snapshots')
    parser_snapshot.add_argument('-t', '--take',
                                 nargs=1,
                                 metavar='SNAPSHOT_NAME',
                                 dest='snapshot_take',
                                 help='take named snapshot')
    parser_snapshot.add_argument('-d', '--delete',
                                 nargs=1,
                                 metavar='SNAPSHOT_NAME',
                                 dest='snapshot_delete',
                                 help='delete named snapshot')
    parser_snapshot.add_argument('-g', '--go',
                                 nargs=1,
                                 metavar='SNAPSHOT_NAME',
                                 dest='snapshot_go',
                                 help='go to named snapshot')
    parser_snapshot.add_argument('VM',
                                 help='VM name')

    return parser.parse_args()

def build_vm_root(args):
    root = args.base_directory
    if hasattr(args, 'VM'):
        root = os.path.join(root, args.VM)
    return root

def build_control_obj(args, root):
    if hasattr(args, 'verbose') and args.verbose:
        return Control(root=root, quiet_stdout=False, quiet_stderr=False)
    return Control(root=root)

def vm_exists(root):
    return os.path.exists(os.path.join(root, 'Vagrantfile'))

def print_error_exit(msg):
    err = "%s: %s\n" % (os.path.basename(sys.argv[0]), msg)
    sys.stderr.write(err)
    sys.exit(1)

def run(args):
    root = build_vm_root(args)
    vagrantctl = build_control_obj(args, root)
    if hasattr(args, 'VM') and not vm_exists(root):
        print_error_exit("no such VM '%s'" % args.VM)

    if hasattr(args, 'list'):
        for vm in vagrantctl.list():
            print(vm)
    elif hasattr(args, 'up'):
        vagrantctl.up()
    elif hasattr(args, 'halt'):
        vagrantctl.halt()
    elif hasattr(args, 'suspend'):
        vagrantctl.suspend()
    elif hasattr(args, 'resume'):
        vagrantctl.resume()
    elif hasattr(args, 'reload'):
        vagrantctl.reload()
    elif hasattr(args, 'status'):
        for status in vagrantctl.status():
            print(status[1])
    elif hasattr(args, 'ssh_config'):
        try:
            print(vagrantctl.ssh_config())
        except:
            print_error_exit("VM '%s' not up" % args.VM)
    elif hasattr(args, 'snapshot'):
        if args.snapshot_take:
            vagrantctl.snapshot_take(args.snapshot_take.pop())
        elif args.snapshot_delete:
            vagrantctl.snapshot_delete(args.snapshot_delete.pop())
        elif args.snapshot_go:
            vagrantctl.snapshot_go(args.snapshot_go.pop())
        else:
            snapshots = vagrantctl.snapshot_list()
            for snapshot in snapshots[1:]:
                print(snapshot)
    elif hasattr(args, 'config'):
        if args.config_show:
            with open(vagrantctl.config()) as config:
                print(config.read())
        else:
            print(vagrantctl.config())

    sys.exit(0)

def main():
    args = parse_options(parse_config())
    run(args)

if __name__ == '__main__':
    main()


text:
<!DOCTYPE html>

<meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">

<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">

  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">

<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">

  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">

  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">

  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">

  <meta name="keywords" content="Hexo, NexT">

  <link rel="alternate" href="https://notes.iissnan.com/atom.xml" title="kydxone" type="application/atom+xml">

<meta name="description" content="乱写一通,一塌糊涂">
<meta property="og:type" content="website">
<meta property="og:title" content="kydxone">
<meta property="og:url" content="https://kydxone.github.io/tags/算法-shuffle-乱序-洗牌/index.html">
<meta property="og:site_name" content="kydxone">
<meta property="og:description" content="乱写一通,一塌糊涂">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="kydxone">
<meta name="twitter:description" content="乱写一通,一塌糊涂">

  <link rel="canonical" href="https://kydxone.github.io/tags/算法-shuffle-乱序-洗牌/">

  <title>标签: 算法 shuffle 乱序 洗牌 | kydxone</title>

        kydxone

Code is poetry

    <button>

    </button>

            首页

            关于

            标签

            分类

            归档

算法 shuffle 乱序 洗牌标签

                Jekyll 学习心得一

        <time class="post-time" itemprop="dateCreated" datetime="2019-02-23T15:26:47+08:00" content="2019-02-23">
          02-23
        </time>

Horstmann

乱写一通,一塌糊涂

                  6
                  日志

                  3
                  分类

                  5
                  标签

                RSS

                        GitHub

                        E-Mail

                        Weibo

                        Zhihu

                Links

                    KK的博客

© 2019

  Horstmann

由 Hexo 强力驱动

  |

主题 — NexT.Pisces v5.1.4


text:
using UnityEngine;

namespace Assets.Core.NavMesh
{
    public static class NavMeshExtention {

        public static bool HasReachedTarget(this NavMeshAgent agent)
        {
            return agent.remainingDistance < 0.2;
        }
    }
}


text:
@interface Demo3AViewController : UIViewController <GQViewController>

@end


text:
import React from 'react';

export default React.createClass({
  render () {
    return (
      <div className="app-page page-no-match">
        Not Found!
      </div>
    );
  },
});


text:
require 'routing/shared_examples'

describe 'routes for MiqPolicyLogController' do
  let(:controller_name) { 'miq_policy_log' }

  describe '#button' do
    it 'routes with POST' do
      expect(post("/#{controller_name}/button")).to route_to("#{controller_name}#button")
    end
  end

  describe '#fetch_log' do
    it 'routes with GET' do
      expect(get("/#{controller_name}/fetch_log")).to route_to("#{controller_name}#fetch_log")
    end
  end

  describe '#index' do
    it 'routes with GET' do
      expect(get("/#{controller_name}")).to route_to("#{controller_name}#index")
    end
  end
end


text:
package parquet.scrooge;

import parquet.hadoop.thrift.ThriftReadSupport;
import parquet.schema.MessageType;
import parquet.thrift.ThriftSchemaConverter;
import parquet.thrift.projection.FieldProjectionFilter;
import parquet.thrift.struct.ThriftType;

/**
 * Read support for Scrooge
 * @author Tianshuo Deng
 */
public class ScroogeReadSupport extends ThriftReadSupport{

  /**
   * used from hadoop
   * the configuration must contain a "parquet.thrift.read.class" setting
   */
  public ScroogeReadSupport() {
  }

  @Override
  protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) {
    ThriftType.StructType thriftStruct = new ScroogeStructConverter().convert(thriftClass);
    return new ThriftSchemaConverter(fieldProjectionFilter).convert(thriftStruct);
  }
}


text:
namespace mojo {

class TraceControllerImpl : public tracing::TraceController {
 public:
  explicit TraceControllerImpl(
      InterfaceRequest<tracing::TraceController> request);

  ~TraceControllerImpl() override;

 private:
  // tracing::TraceController implementation:
  void StartTracing(const String& categories,
                    tracing::TraceDataCollectorPtr collector) override;
  void StopTracing() override;

  void SendChunk(const scoped_refptr<base::RefCountedString>& events_str,
                 bool has_more_events);

  tracing::TraceDataCollectorPtr collector_;
  StrongBinding<tracing::TraceController> binding_;

  DISALLOW_COPY_AND_ASSIGN(TraceControllerImpl);
};

}  // namespace mojo

#endif  // MOJO_COMMON_TRACING_CONTROLLER_IMPL_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
  ~
  ~ Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium.
  ~
  ~ The program is available in open source according to the Apache
  ~ License, Version 2.0. All contributions in this program are covered
  ~ by the Geomajas Contributors License Agreement. For full licensing
  ~ details, see LICENSE.txt in the project root.
  -->

<Filter xmlns="http://www.opengis.net/ogc">
	<FeatureId fid="TREESA_1M.1234" />
</Filter>


text:
import { optionsFromArguments } from "../core/util/Defaults";
import { WaveShaper } from "../signal/WaveShaper";
import { Effect, EffectOptions } from "./Effect";

export interface DistortionOptions extends EffectOptions {
	distortion: number;
	oversample: OverSampleType;
}

/**
 * A simple distortion effect using Tone.WaveShaper.
 * Algorithm from [this stackoverflow answer](http://stackoverflow.com/a/22313408).
 *
 * @example
 * const dist = new Tone.Distortion(0.8).toDestination();
 * const fm = new Tone.FMSynth().connect(dist);
 * fm.triggerAttackRelease("A1", "8n");
 * @category Effect
 */
export class Distortion extends Effect<DistortionOptions> {

	readonly name: string = "Distortion";

	/**
	 * The waveshaper which does the distortion
	 */
	private _shaper: WaveShaper;

	/**
	 * Stores the distortion value
	 */
	private _distortion: number;

	/**
	 * @param distortion The amount of distortion (nominal range of 0-1)
	 */
	constructor(distortion?: number);
	constructor(options?: Partial<DistortionOptions>);
	constructor() {

		super(optionsFromArguments(Distortion.getDefaults(), arguments, ["distortion"]));
		const options = optionsFromArguments(Distortion.getDefaults(), arguments, ["distortion"]);

		this._shaper = new WaveShaper({
			context: this.context,
			length: 4096,
		});

		this._distortion = options.distortion;

		this.connectEffect(this._shaper);
		this.distortion = options.distortion;
		this.oversample = options.oversample;
	}

	static getDefaults(): DistortionOptions {
		return Object.assign(Effect.getDefaults(), {
			distortion: 0.4,
			oversample: "none" as OverSampleType,
		});
	}

	/**
	 * The amount of distortion. Nominal range is between 0 and 1.
	 */
	get distortion(): number {
		return this._distortion;
	}
	set distortion(amount) {
		this._distortion = amount;
		const k = amount * 100;
		const deg = Math.PI / 180;
		this._shaper.setMap((x) => {
			if (Math.abs(x) < 0.001) {
				// should output 0 when input is 0
				return 0;
			} else {
				return (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x));
			}
		});
	}

	/**
	 * The oversampling of the effect. Can either be "none", "2x" or "4x".
	 */
	get oversample(): OverSampleType {
		return this._shaper.oversample;
	}
	set oversample(oversampling) {
		this._shaper.oversample = oversampling;
	}

	dispose(): this {
		super.dispose();
		this._shaper.dispose();
		return this;
	}
}