text:
package org.apache.flink.runtime.resourcemanager.slotmanager;

import org.apache.flink.api.common.JobID;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.instance.InstanceID;
import org.apache.flink.runtime.resourcemanager.registration.TaskExecutorConnection;
import org.apache.flink.runtime.slots.ResourceCounter;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;

/** Tracks TaskManager's resource and slot status. */
interface TaskManagerTracker {

    // ---------------------------------------------------------------------------------------------
    // Add / Remove (pending) Resource
    // ---------------------------------------------------------------------------------------------

    /**
     * Register a new task manager.
     *
     * @param taskExecutorConnection of the new task manager
     * @param totalResourceProfile of the new task manager
     * @param defaultSlotResourceProfile of the new task manager
     */
    void addTaskManager(
            TaskExecutorConnection taskExecutorConnection,
            ResourceProfile totalResourceProfile,
            ResourceProfile defaultSlotResourceProfile);

    /**
     * Unregister a task manager with the given instance id.
     *
     * @param instanceId of the task manager
     */
    void removeTaskManager(InstanceID instanceId);

    /**
     * Add a new pending task manager.
     *
     * @param pendingTaskManager to be added
     */
    void addPendingTaskManager(PendingTaskManager pendingTaskManager);

    /**
     * Remove a pending task manager and it associated allocation records.
     *
     * @param pendingTaskManagerId of the pending task manager
     * @return the allocation records associated to the removed pending task manager
     */
    Map<JobID, ResourceCounter> removePendingTaskManager(PendingTaskManagerId pendingTaskManagerId);

    // ---------------------------------------------------------------------------------------------
    // Slot status updates
    // ---------------------------------------------------------------------------------------------

    /**
     * Notifies the tracker about the slot status.
     *
     * @param allocationId of the slot
     * @param jobId of the slot
     * @param instanceId of the slot
     * @param resourceProfile of the slot
     * @param slotState of the slot
     */
    void notifySlotStatus(
            AllocationID allocationId,
            JobID jobId,
            InstanceID instanceId,
            ResourceProfile resourceProfile,
            SlotState slotState);

    /**
     * Clear all previous pending slot allocation records if any, and record new pending slot
     * allocations.
     *
     * @param pendingSlotAllocations new pending slot allocations be recorded
     */
    void replaceAllPendingAllocations(
            Map<PendingTaskManagerId, Map<JobID, ResourceCounter>> pendingSlotAllocations);

    // ---------------------------------------------------------------------------------------------
    // Getters
    // ---------------------------------------------------------------------------------------------

    /**
     * Get the pending allocations of the given pending task manager.
     *
     * @param pendingTaskManagerId of the pending task manager
     * @return pending allocations, mapped by jobId
     */
    Map<JobID, ResourceCounter> getPendingAllocationsOfPendingTaskManager(
            PendingTaskManagerId pendingTaskManagerId);

    /**
     * Get the {@link TaskManagerInfo}s of all registered task managers.
     *
     * @return a collection of {@link TaskManagerInfo}s of all registered task managers.
     */
    Collection<? extends TaskManagerInfo> getRegisteredTaskManagers();

    /**
     * Get the {@link TaskManagerInfo} of a registered task manager with the given instanceId
     *
     * @param instanceId of the task manager
     * @return An Optional of {@link TaskManagerInfo}, if find, of the task manager
     */
    Optional<TaskManagerInfo> getRegisteredTaskManager(InstanceID instanceId);

    /**
     * Get all pending task managers.
     *
     * @return a collection of {@link PendingTaskManager}s.
     */
    Collection<PendingTaskManager> getPendingTaskManagers();

    /**
     * Get the {@link TaskManagerSlotInformation} of the allocated slot with the given allocationId.
     *
     * @param allocationId of the slot
     * @return An Optional of {@link TaskManagerSlotInformation}, if find, of the slot
     */
    Optional<TaskManagerSlotInformation> getAllocatedOrPendingSlot(AllocationID allocationId);

    /**
     * Get the current {@link ClusterResourceOverview}.
     *
     * @return the current {@link ClusterResourceOverview}
     */
    ClusterResourceOverview getClusterResourceOverview();

    /** Removes all state from the tracker. */
    void clear();
}


text:
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TemplateHaskell,
             FlexibleInstances, FlexibleContexts, MultiParamTypeClasses,
             TypeOperators, TypeSynonymInstances, GeneralizedNewtypeDeriving #-}

module Distribution.Server.Packages.Platform where

import Data.Acid (Query, Update, makeAcidic)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.SafeCopy (base, deriveSafeCopy)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Typeable

import Distribution.Server.Framework.Instances ()
import Distribution.Package
import Distribution.Version

import Control.Monad.Reader (ask, asks)
import Control.Monad.State (put, modify)

newtype PlatformPackages = PlatformPackages {
    blessedPackages :: Map PackageName (Set Version)
} deriving (Show, Typeable)
emptyPlatformPackages :: PlatformPackages
emptyPlatformPackages = PlatformPackages Map.empty

getPlatformPackages :: Query PlatformPackages PlatformPackages
getPlatformPackages = ask

getPlatformPackage :: PackageName -> Query PlatformPackages (Set Version)
getPlatformPackage pkgname = asks (Map.findWithDefault Set.empty pkgname . blessedPackages)

setPlatformPackage :: PackageName -> Set Version -> Update PlatformPackages ()
setPlatformPackage pkgname versions = modify $ \p -> case Set.null versions of
    True  -> p { blessedPackages = Map.delete pkgname $ blessedPackages p }
    False -> p { blessedPackages = Map.insert pkgname versions $ blessedPackages p }

replacePlatformPackages :: PlatformPackages -> Update PlatformPackages ()
replacePlatformPackages = put

$(deriveSafeCopy 0 'base ''PlatformPackages)

initialPlatformPackages :: PlatformPackages
initialPlatformPackages = emptyPlatformPackages

$(makeAcidic ''PlatformPackages ['getPlatformPackages
                                ,'getPlatformPackage
                                ,'setPlatformPackage
                                ,'replacePlatformPackages
                                ])

redpajama_set_name: RedPajamaGithub


text:
/*

  ## RangeFacet

  ### Parameters
  * 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
  * spyable ::  Dislay the 'eye' icon that show the last elasticsearch query
  * zoomlinks :: Show the zoom links?
  * bars :: Show bars in the chart
  * 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',
  'jquery.flot.axislabels'
],
function (angular, app, $, _, kbn, moment, timeSeries) {
  'use strict';

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

  module.controller('rangeFacet', 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  : "Beta",
      description : "Histogram view across any numeric field using Solr's range.facet functionality. Works similar to the time series histogram, allowing selection of ranges, and zooming in/out to the desired numeric range. Range selections in panel are reflected across the entire dashboard."
    };

    // Set and populate defaults
    var _d = {
      mode        : 'count',
      time_field  : '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,
      fill        : 0,
      linewidth   : 3,
      auto_int    : true,
      resolution  : 100,
      interval    : '10',
      resolutions : [5,10,25,50,75,100],
      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
      },
      showChart:true,
      show_queries:true,
    };

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

    $scope.init = function() {
      // Hide view options by default
      $scope.options = false;
      $scope.$on('refresh',function(){
        $scope.get_data();
        if (filterSrv.idsByTypeAndField('range',$scope.panel.range_field).length > 0) {
          $scope.panel.showChart =  true;
        } else {
          $scope.panel.showChart =  false;
        }
      });

      $scope.get_data();

    };

    $scope.set_precision = function(precision) {
      $scope.panel.resolution = precision;
    };

    $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;
      return interval;
    };

    /**
     * The facet range effecting the panel
     * return type {from:number, to:number}
     */
    $scope.get_facet_range = function () {
      var range = $scope.facet_range = filterSrv.facetRange($scope.panel.range_field);
      return range;
    };

    /*
     * get interval to be used
     */
    $scope.get_interval = function () {
      var interval = $scope.panel.interval,
                      range;
      if ($scope.panel.auto_int) {
        range = $scope.get_facet_range();
        if (range) {
          interval = kbn.calculate_gap(range.from, range.to, $scope.panel.resolution, 0);
        }
      }
      $scope.panel.interval = interval || '10';
      return $scope.panel.interval;
    };

    $scope.set_range_filter = function(from,to){
      filterSrv.removeByTypeAndField('range',$scope.panel.range_field);
      filterSrv.set({
        type: 'range',
        from: parseInt(from),
        to: parseInt(to),
        field: $scope.panel.range_field
      });
      dashboard.refresh();
    };

    // set the configrations in settings
    $scope.set_configrations = function(from,to){
      $scope.panel.minimum = parseInt(from);
      $scope.panel.maximum = parseInt(to);
    };

    //set the range filter from old configrations
    $scope.range_apply = function(){
      filterSrv.set({
        type: 'range',
        from: parseInt($scope.panel.minimum),
        to: parseInt($scope.panel.maximum),
        field: $scope.panel.range_field
      });
      dashboard.refresh();
    };

    /**
     * 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, numeric_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_facet_range();

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

      $scope.panelMeta.loading = true;

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

      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.facetFilter($scope.sjs.QueryFilter(query));

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

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

      // Build Solr query
      var fq = '';
      if (filterSrv.getSolrFq() && filterSrv.getSolrFq() != '') {
        fq = '&' + filterSrv.getSolrFq();
      }
      var wt_json = '&wt=json';
      var rows_limit = '&rows=0'; // for RangeFacet, we do not need the actual response doc, so set rows=0
      var facet = '&facet=true' +
                  '&facet.range=' + $scope.panel.range_field +
                  '&facet.range.start=' + $scope.panel.minimum +
                  '&facet.range.end=' + (parseInt($scope.panel.maximum)+1) +
                  '&facet.range.gap=' + $scope.panel.interval;

      var promises = [];
      $scope.panel.queries.query = "";

       _.each($scope.panel.queries.ids, function(id) {
        var temp_q =  querySrv.getQuery(id) + wt_json + rows_limit + fq + facet ;
        $scope.panel.queries.query += temp_q + "\n";
        if ($scope.panel.queries.custom !== null) {
          request = request.setQuery(temp_q + $scope.panel.queries.custom);
        } else {
          request = request.setQuery(temp_q);
        }
        promises.push(request.doSearch());
      });
      // Populate scope when we have results
      $q.all(promises).then(function(results) {
        var _range = $scope.get_facet_range();

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

        // 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,
            numeric_series,
            hits;

          _.each($scope.panel.queries.ids, function(id,index) {

            // Check for error and abort if found
            if (!(_.isUndefined(results[index].error))) {
              $scope.panel.error = $scope.parse_error(results[index].error.msg);
              return;
            }
            // 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) {
              numeric_series = new timeSeries.ZeroFilled({
                start_date: _range && _range.from,
                end_date: _range && _range.to,
                fill_style: 'minimal'
              });
              hits = 0;
            } else {
              numeric_series = $scope.data[i].numeric_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;
            }
            $scope.range_count = 0;
            // Solr facet counts response is in one big array.
            // So no need to get each segment like Elasticsearch does.
            // Entries from facet_ranges counts
            var entries = results[index].facet_counts.facet_ranges[$scope.panel.range_field].counts;
            for (var j = 0; j < entries.length; j++) {
              var entry_time = entries[j]; // convert to millisec
              j++;
              var entry_count = entries[j];
              numeric_series.addValue(entry_time, entry_count);
              hits += entry_count; // The series level hits counter
              $scope.hits += entry_count; // Entire dataset level hits counter
              $scope.range_count += 1; // count the number of ranges to help later in bar width
            }

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

            i++;
          });

          // Tell the RangeFacet 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.facetRange($scope.panel.range_field)[1];
      if (_.isUndefined(_range)){
        _range = {
          from: $scope.panel.minimum,
          to: $scope.panel.maximum
        };
      }

      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);

      $scope.set_range_filter(_from, _to);
      $scope.set_configrations(_from, _to);
      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.set_range_filter($scope.panel.minimum,$scope.panel.maximum);
      $scope.refresh =  false;
      $scope.$emit('render');
    };

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

  });

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

',
      link: function(scope, elem) {

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

        scope.set_range_filter(scope.panel.minimum,scope.panel.maximum);
        // 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 = scope.panel.maximum - scope.panel.minimum;
          // var count = scope.range_count > 15 ? scope.range_count : 15;
          var stack = scope.panel.stack ? true : null;
          var facet_range = scope.get_facet_range();
          // 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*scope.range_count),
                  zero: false,
                  lineWidth: 0
                },
                points: {
                  show: scope.panel.points,
                  fill: 1,
                  fillColor: false,
                  radius: 5
                },
                shadowSize: 1
              },
              axisLabels: {
                show: true
              },
              yaxis: {
                show: scope.panel['y-axis'],
                min: 0,
                max: scope.panel.percentage && scope.panel.stack ? 100 : null,
                axisLabel: 'count'
              },
              xaxis: {
                show: scope.panel['x-axis'],
                min: facet_range.from - 1,
                max: facet_range.to + 1,
                autoscaleMargin : scope.panel.interval,
                minTickSize : scope.panel.interval,
                tickDecimals: 0,
                axisLabel: scope.panel.range_field
              },
              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.numeric_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].numeric_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++) { // jshint ignore: line
                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;
              }
            }

            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);
          }
        }

        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 + dashboard.numberWithCommas(value) + " [" + item.datapoint[0]+" - "+ (item.datapoint[0] + (scope.panel.interval-1)) +"]"
              )
              .place_tt(pos.pageX, pos.pageY);
          } else {
            $tooltip.detach();
          }
        });

        elem.bind("plotselected", function (event, ranges) {
          scope.set_range_filter(ranges.xaxis.from, ranges.xaxis.to);
          scope.set_configrations(ranges.xaxis.from, ranges.xaxis.to);
          dashboard.refresh();
        });
      }
    };
  });

});


text:
macro(proj_version)
  parse_arguments(THIS_VERSION "MAJOR;MINOR;PATCH;"
    ""
    ${ARGN})

  # Set version components
  set(${PROJECT_INTERN_NAME}_VERSION_MAJOR ${THIS_VERSION_MAJOR})
  set(${PROJECT_INTERN_NAME}_VERSION_MINOR ${THIS_VERSION_MINOR})
  set(${PROJECT_INTERN_NAME}_VERSION_PATCH ${THIS_VERSION_PATCH})

  # Set VERSION string
  set(${PROJECT_INTERN_NAME}_VERSION
    "${${PROJECT_INTERN_NAME}_VERSION_MAJOR}.${${PROJECT_INTERN_NAME}_VERSION_MINOR}.${${PROJECT_INTERN_NAME}_VERSION_PATCH}")

  # Set ABI version string used to name binary output
  # On Windows, ABI version is specified using binary file name suffix.
  if(WIN32)
    set(${PROJECT_INTERN_NAME}_ABI_VERSION
      "${${PROJECT_INTERN_NAME}_VERSION_MAJOR}_${${PROJECT_INTERN_NAME}_VERSION_MINOR}")
  endif()

  message(STATUS "")
  boost_report_value(${PROJECT_INTERN_NAME}_VERSION)
  if(WIN32)
    boost_report_value(${PROJECT_INTERN_NAME}_ABI_VERSION)
  endif(WIN32)
endmacro()


text:
@interface AIDocument (Ragel2)

- (int)contentObjectNumber;

@end


text:
/*!
対応するYAMLファイルを読み込む
 */
import glob from 'glob'
import yaml from 'js-yaml'
import fs from 'fs'
import path from 'path'

export default function(dir){
  let target_dir = path.resolve(dir)
  let file_list = glob.sync(`${target_dir}/**/[!_]*.yml`)

  let reg1 = new RegExp(`${target_dir}/`)
  let reg2 = new RegExp(`.yml$`)

  let entries = {}

  file_list.forEach(item=>{
    let key = item.replace(reg1, '')
    key = key.replace(reg2, '')

    entries[key] = yaml.safeLoad(fs.readFileSync(item, 'utf-8'))
  })

  return entries
}


text:
"""Working with built in CX Validation featrure."""

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

import logging
import re
from typing import Dict
import pandas as pd

from dfcx_scrapi.core.scrapi_base import ScrapiBase
from dfcx_scrapi.core.agents import Agents
from dfcx_scrapi.core.flows import Flows

SCOPES = [
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/dialogflow",
]

class ValidationUtil(ScrapiBase):
    """Class that extends the built in CX Validation feature."""

    def __init__(
        self,
        creds_path: str = None,
        creds_dict: Dict = None,
        creds=None,
        scope=False,
    ):
        super().__init__(
            creds_path=creds_path,
            creds_dict=creds_dict,
            creds=creds,
            scope=scope,
        )

        self.agents = Agents(creds_path=creds_path, creds_dict=creds_dict)
        self.flows = Flows(creds_path=creds_path, creds_dict=creds_dict)

    def validation_results_to_dataframe(self, validation_results: Dict):
        """ "Transform the Validation results into a dataframe.
        Note will not work if you call get_validation_result with a
        flow_id specified. For calling validate ensure lro is complete

        Args:
          validation_results: dictionary of validation results
            assed back from get_validation_result or validate functions

        Return:
          Dataframe containing the validation results
        """

        agent_id = "/".join(validation_results["name"].split("/")[0:6])

        flows_map = self.flows.get_flows_map(agent_id)
        max_cols_old = 0
        dataframe = pd.DataFrame()

        for flow in validation_results["flowValidationResults"]:

            temp = "/".join(flow["name"].split("/")[:-1])
            val_msg = flow.get("validationMessages", {})
            if bool(val_msg):
                temp_df = pd.DataFrame(val_msg)
                temp_df.insert(0, "flow", flows_map[temp])

                max_cols_new = max([len(x) for x in temp_df.resourceNames])

                if max_cols_new > max_cols_old:
                    for i in range(1, max_cols_new + 1):
                        temp_df[f"resource{i}"] = None
                    max_cols_old = max_cols_new

                for index in temp_df.index:
                    i = 1
                    for frame in temp_df["resourceNames"][index]:
                        temp_df[f"resource{i}"][index] = frame[
                            "displayName"
                        ]
                        i += 1

                dataframe = pd.concat([dataframe, temp_df])
                max_cols_old = 0

        return dataframe

    def intent_disambiguation(self, agent_id, refresh=False, flow=None):
        """Obtains the intent disambiguation tasks from the validation tool

        Args:
          refresh: (optional) False means validation results are pulled
            as is. True means the validation tool is refreshed then
            results are pulled
          flow: (optional) If specified results are returned for the
            indicated flow display name

        Returns:
          Dictionary of intent disambiguation Validation results
          in two dataframes.
            extended: All intent disambiguation validtion results as
              seperate instances. If 5 training phrases conflict
              in 5 intents they will be shown as 5 rows.
            compact: Only showing the first instance of a conflict
              for each grouping. If 5 trainig phrases conflic in 5 intents
              only the first training phrase will show.
        """

        if refresh:
            validation = self.agents.validate_agent(agent_id)
        else:
            validation = self.agents.get_validation_result(agent_id=agent_id)

        validation_df = self.validation_results_to_dataframe(validation)
        if flow:
            validation_df = validation_df[validation_df["flow"] == flow]

        # Parse df
        resources = validation_df.columns
        resources = [r for r in resources if "resource" in r]
        validation_df = validation_df[["flow", "detail"] + resources]

        disambig_id, intents_list, tp_list, id_ = [], [], [], 0
        flows = []
        phrase = "Multiple intents share training phrases which are too similar"
        for _, row in validation_df.iterrows():
            deets, flow = row["detail"], row["flow"]
            if bool(re.search(phrase, deets)):
                intents = re.findall("Intent '(.*)': training phrase ", deets)
                training_phrases = re.findall("training phrase '(.*)'", deets)
                intents_list = intents_list + intents
                tp_list = tp_list + training_phrases
                disambig_id = disambig_id + ([id_] * len(training_phrases))
                flows = flows + ([flow] * len(training_phrases))
                id_ += 1

        extraction = pd.DataFrame()
        extraction["disambig_id"] = disambig_id
        extraction.insert(0, "flow", flows)
        extraction["intent"] = intents_list
        extraction["training_phrase"] = tp_list

        if extraction.empty:
            logging.info(
                "Validation results do not contain clashing intent phrases.")
            return None

        intent_options = (
            extraction.groupby(["disambig_id"])["intent"]
            .apply(list)
            .reset_index()
            .rename(columns={"intent": "intents"})
        )
        intent_options["intents"] = intent_options.apply(
            lambda x: list(set(x["intents"])), axis=1
        )

        extraction = pd.merge(
            extraction, intent_options, on=["disambig_id"], how="left"
        )

        internal = extraction.copy()

        internal["intent_count"] = internal.apply(
            lambda x: len(x["intents"]), axis=1
        )
        external = (
            extraction.groupby(["flow", "disambig_id"])
            .agg(
                {
                    "training_phrase": "first",
                    "intents": "first",
                    "intent": "count",
                }
            )
            .reset_index()
            .rename(columns={"intent": "conflicting_tp_count"})
        )
        external["intent_count"] = external.apply(
            lambda x: len(x["intents"]), axis=1
        )

        return {"extended": internal, "compact": external}


text:
sap.ui.define(['sap/ui/core/mvc/Controller','sap/ui/model/json/JSONModel'],
	function(Controller, JSONModel) {
	"use strict";

	var CController = Controller.extend("sap.m.sample.TextAreaValueUpdate.C", {

		onInit: function () {
			var oModel = new JSONModel({data: {}});
			this.getView().setModel(oModel);
		},

		handleLiveChange: function(oEvent) {
			var sValue = oEvent.getParameter("value");
			this.byId("getValue").setText(sValue);
		}
	});

	return CController;

});


text:
@interface S3ZDownloadManager : NSObject

+ (void)setupWithConfiguration:(S3ZConfiguration *)configuration;
+ (instancetype)sharedInstance;

- (void)downloadURL:(NSURL *)url
          withBlock:(void (^)(BOOL succeeded, NSURL *location, NSError *error))block
      progressBlock:(void (^)(float downloadProgress))progressBlock;

@end


text:
import { FETCH_COLLECTIONS_FAIL_TYPE, FETCH_COLLECTIONS_START_TYPE, FETCH_COLLECTIONS_SUCCESS_TYPE, DISPLAY_COLLECTION_TYPE }
    from './collections-list-actions';

const defaultCollectionState = { response: [], showCompleted: false };

const collections = (state = defaultCollectionState, action) => {
    switch (action.type) {
        case FETCH_COLLECTIONS_START_TYPE:
            return Object.assign({}, state, { fetching: true });
        case FETCH_COLLECTIONS_FAIL_TYPE:
            return Object.assign({}, state, { fetching: false, error: Object.assign({}, action.error) });
        case FETCH_COLLECTIONS_SUCCESS_TYPE:
            return Object.assign({}, state, { fetching: false, response: [].concat(action.response) });
        case DISPLAY_COLLECTION_TYPE:
            return Object.assign({}, state, { showCompleted: !state.showCompleted });
        default:
            return state;
    }
};

export default collections;


text:
moduloDirectivas.component('key', {
    templateUrl: "js/system/components/key/key.html",
    controllerAs: 'k',
    controller: key,
    bindings: {
        ide: '=',
        name: '<',
        disable: '<'
    }

});

function key() {

}


text:
using System;

namespace Efrpg
{
    // Settings to allow selective code generation
    [Flags]
    public enum Elements
    {
        None = 0,
        Poco = 1,
        Context = 2,
        Interface = 4,
        PocoConfiguration = 8,
        Enum = 16
    };
}


text:
import json, urllib2
import pandas as pd

# vars
withgeoCount = 0  # count languoids with lat/long coordinates
nongeoCount = 0  # count languoids without lat/long coordinates
maxclass = 0  # what's the longest classification?
NONGEOs = []; IDs = []; NAMEs = []; TYPEs = []; CLASS1s = []; CLASS2s = []; CLASS3s = []; LONGs = []; LATs = []; STATUSes = []; TTIPs = []; ISOs = []  # empty lists for data

## procedure for those languoids with geo-coordinates
def withlatlong(langID, lon, lat, name, langdata, langtype, withgeoCount, maxclass):
    withgeoCount += 1
    langstatus = langdata['status']
#    langstatus = 'Unknown'  # default endangerment level: find out if info exists
#    if 'endangerment' in langdata['jsondata']:
#        langstatus = 'Living' if langdata['jsondata']['endangerment'] is None else langdata['jsondata']['endangerment']
    class1 = 'Unknown'  # take the 1st language family classification, if any found
    if len(langdata['classification']) > 0:
        class1 = langdata['classification'][0]['name']
    classlist = 'family:' + class1  # start class list for tooltip
    class2 = '-'  # and the 2nd, if found
    if len(langdata['classification']) > 1:
        class2 = langdata['classification'][1]['name']
        classlist += ',' + class2
    class3 = '-'  # and the 3rd, if found
    if len(langdata['classification']) > 2:
        class3 = langdata['classification'][2]['name']
        classlist += ',' + class3
    if len(langdata['classification']) > maxclass:
        maxclass = len(langdata['classification'])
    if 'iso639-3' in langdata:
        iso = langdata['iso639-3']
    else:
        iso = 'none'
    tooltip = "" + name + "
" + classlist + "
type:" + langtype + "
status:" + langstatus + ""
    print "withgeo: ", withgeoCount, name, langtype, iso
    print "family: ", class1, class2, class3
    print "lat/long: ", lon, lat; print "status: ", langstatus
    IDs.append(langID); NAMEs.append(name); TYPEs.append(langtype); CLASS1s.append(class1); CLASS2s.append(class2); CLASS3s.append(class3); LONGs.append(lon); LATs.append(lat); STATUSes.append(langstatus); TTIPs.append(tooltip); ISOs.append(iso)  # build lists
    return withgeoCount, maxclass

## and for those without geo-coordinates
def nonlatlong(nongeoCount, langID, name, langtype):
    nongeoCount += 1
    NONGEOs.append(langtype)
    print "nongeo: ", nongeoCount, name, langtype
    return nongeoCount

## closing print actions
def finishUp():
    print "\n-----\n-----\nLanguoids with geo-coords: ", withgeoCount  # how many languoids with lat/long coordinates?
    print "\n-----\n-----\nLanguoids w/o geo-coords: ", nongeoCount  # how many languoids without lat/long coordinates?
    from collections import Counter
    print(Counter(NONGEOs))
    print "\n-----\n-----\nMax classification: ", maxclass  # languoid with longest classification?

    ## merge vectors and convert to dataframe
    ## Pandas commands from: http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/01%20-%20Lesson.ipynb
    glottoData = zip(IDs, ISOs, NAMEs, TYPEs, CLASS1s, CLASS2s, CLASS3s, LONGs, LATs, STATUSes, TTIPs)
    glottoDF = pd.DataFrame(data = glottoData, columns = ['id', 'iso639-3', 'name', 'type', 'family1', 'family2', 'family3', 'long', 'lat', 'status', 'tooltip'])

    ## export to csv
    glottoDF.to_csv('shinyApp/data/glottologLanguoids.csv', encoding='utf-8')

## MAIN

## [1] list of Glottolog language resources (save to file)
response = urllib2.urlopen('http://glottolog.org/resourcemap.json?rsc=language')
data = json.load(response)
with open('glottologResourceMap.json', 'w') as outfile:
    json.dump(data, outfile)
outfile.close()

## [2] loop over all languoids, fetch jsondata, make list of dictionaries
nres = len(data['resources'])
print "\n-----\nNumber of rows in resources list: ", nres
for n in range(0, nres):
    langID = data['resources'][n]['id']
    lon = data['resources'][n]['longitude']
    lat = data['resources'][n]['latitude']
    name = data['resources'][n]['name']
    url = 'http://glottolog.org/resource/languoid/id/' + langID + '.json'  # now fetch languoid specific data
    langresp = urllib2.urlopen(url)
    langdata = json.load(langresp)
    langtype = langdata['level']  # 'language' or other?
    print "\n-----\nlanguoid ID: ", langID
    if lon is not None:
        (withgeoCount, maxclass) = withlatlong(langID, lon, lat, name, langdata, langtype, withgeoCount, maxclass)  # only those resources for which there are lat/long coordinates
    else:
        nongeoCount = nonlatlong(nongeoCount, langID, name, langtype)  # interested in non-lat/long languoids?

## [3] the end: print statements and print to file
finishUp()


text:
"""
Window class of Nexted -- Python+PyGTK text editor
Copyright (C) 2013 Ignacio Alvarez <someoneigna@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

from editor import Editor
from gi.repository import Gtk
import os

class Window:
    """Conects the signals to handle widgets and
        is connected to a Editor instance"""
    def __init__(self, start_file=None):
        #Read app xml file and prepare the window
        builder = Gtk.Builder()
        builder.add_from_file("gui_nexted.GtkBuilder")

        self.window = builder.get_object("EditorWindow")
        self.window.set_default_size(700, 400)
        self.title = self.window.get_title()

        #Contains a Editor

        #self.eb = Gtk.EventBox()
        self.textview = builder.get_object("textview")
        #self.eb.add(self.textview)
        #self.eb.modify_bg(Gtk.StateNormal, Gtk.gdk.color_parse("blue"))
        self.editor = Editor(self.textview)

        #And a statusbar
        self.statusbar = builder.get_object("statusbar")

        #Used for the title
        self.current_filename = None

        #Connect signals----- ENCAPSULATE -------
        signals = {
                'onFileNew': self.onFileNew,
                'onSaveFile': self.onSaveFile,
                'onOpenFile': self.onOpenFile,
                'onSaveAsFile': self.onSaveAsFile,
                'onQuit': Gtk.main_quit,
                'onAboutInfo': self.onAboutInfo,
                'hitCopy': self.onHitCopy,
                'hitBackspace': self.onHitBackspace,
                'hitCut': self.onHitCut,
                'onUpdateStatusTextPush': self.onUpdateStatusTextPush,
                'onUpdateStatusTextPop': self.onUpdateStatusTextPop,
                'onChooseFont': self.onChooseFont,
                'onChooseColor': self.onChooseColor
        }
        builder.connect_signals(signals)

        #Check passed commandline file
        self.startWithFile(start_file)

    def get_window(self):
        return self.window

    def setEditorColor(self, fg, bg):
        self.textview.modify_bg(Gtk.StateType.NORMAL, bg)
        self.textview.modify_fg(Gtk.StateType.NORMAL, fg)

    #----Encapsulate in class(ex: EventHandler)
    def onHitCut(self, data):
        pass
    def onHitBackspace(self, data):
        pass
    def onHitCopy(self, data):
        pass
    def onAboutInfo(self, data):
        dialog = Gtk.AboutDialog()
        dialog.set_authors("Ignacio Alvarez <someoneigna@gmail.com>")
        dialog.set_program_name("Nexted")
        dialog.set_version("0.1v")
        dialog.set_license(open("LICENSE", "r").read())
        dialog.set_website("https://github.com/someoneigna/python-projects/tree/master/nexted")
        dialog.set_website_label("Nexted github repository")
        dialog.run()
        dialog.destroy()

    def onChooseFont(self, data):
        dialog = Gtk.FontSelectionDialog("Choose a font")
        preview_text = "#include<stdio.h>\n"\
                "int main(){\n"\
                "    printf(\"Do you like this font?\\n\");\n"\
                "    return 0;\n}"
        dialog.set_preview_text(preview_text.decode('ascii'))
        response = dialog.run()
        dialog.destroy()

    def onFileInexistant(self, filename):
        """Warn about commandline passed file not existing"""
        file_basename = os.path.basename(filename)
        path = os.path.dirname(filename)
        message = ''.join('File: ' + file_basename + \
                '\nIn: ' + path + " doesn't exists.")

        dialog = Gtk.MessageDialog(
                None, 0,Gtk.MessageType.WARNING,
                Gtk.ButtonsType.OK, message
                )
        dialog.set_modal(True)
        dialog.run()
        dialog.destroy()
        self.current_filename = "Unnamed"
        self.update_title()

    def askReplace(self):
        dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.WARNING,
            Gtk.ButtonsType.OK_CANCEL, "Do you really want to replace the file?")
        dialog.set_modal(True)
        response = dialog.run()
        dialog.destroy()
        return(response)

    def askToSave(self):
        if not self.editor.isFileSaved():
            dialog = Gtk.Dialog("Do you wanna save this file?", None,\
                    Gtk.DIALOG_MODAL, (Gtk.STOCK_CANCEL, Gtk.RESPONSE_REJECT,\
                        Gtk.STOCK_OK, Gtk.RESPONSE_ACCEPT))
            dialog.set_modal(True)
            response = dialog.run()

            if response == Gtk.ResponseType.OK:
                if(self.editor.save() == 'SELECT_FILE'):
                    self.onSaveAsFile('TEMP')

    def update_title(self):
        filename = os.path.basename(self.current_filename)
        newtitle = ''.join(
                    self.title + '  --> '
                    + filename + ' <-- ' + self.current_filename + ' --'
                    )
        self.window.set_title(newtitle)

    def onFileNew(self, data):
        self.current_filename = "Unnamed"
        self.update_title()
        self.editor.new_file()

    def onSaveFile(self, data):
        #Save and check if we have an open file handle
        if self.editor.save() == 'SELECT_FILE':
            #No file is open, choose where to save
            self.onSaveAsFile('TEMP')

    def onSaveAsFile(self, data):
        dialog = Gtk.FileChooserDialog("Choose where to save", None,\
                                       Gtk.FileChooserAction.SAVE,\
                                       (Gtk.STOCK_CANCEL,\
                                        Gtk.ResponseType.CANCEL,\
                                        Gtk.STOCK_SAVE,\
                                        Gtk.ResponseType.OK))
        dialog.set_current_folder(os.getcwd())
        response = dialog.run()
        self.current_filename = dialog.get_filename()

        if response == Gtk.ResponseType.OK:
            if os.path.exists(self.current_filename):
                if self.askReplace() == Gtk.ResponseType.OK:
                    dialog.destroy()
                    self.editor.replace(self.current_filename)
                    return
            else:
                self.editor.save_as_file(self.current_filename)

        dialog.destroy()

    def startWithFile(self, filename):
        self.current_filename = filename

        #If a file was passed as arg
        if self.current_filename:
            #Open and show file
            status = self.editor.open_file(self.current_filename)
            if status == "INEXISTANT":
                self.onFileInexistant(self.current_filename)
            self.update_title()
        else:
            return

    def onChooseColor(self, data):
        color_fg, color_bg = 0, 0
        dialog = Gtk.ColorSelectionDialog("Choose editor foreground")
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            color_fg = dialog.get_color_selection().get_current_color()

        dialog.destroy()

        dialog = Gtk.ColorSelectionDialog("Choose editor background")
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            color_bg = dialog.get_color_selection().get_current_color()
        else:
            return

        dialog.destroy()

        self.setEditorColor(color_fg, color_bg)

    def onOpenFile(self, data):
        dialog = Gtk.FileChooserDialog("Choose file to open", None,\
                                    Gtk.FileChooserAction.OPEN,\
                                    (Gtk.STOCK_CANCEL,\
                                    Gtk.ResponseType.CANCEL,\
                                    Gtk.STOCK_OPEN,\
                                    Gtk.ResponseType.OK))

        dialog.set_current_folder(os.getcwd())
        response = dialog.run()

        if response == Gtk.ResponseType.OK:
            self.current_filename = dialog.get_filename()
            self.editor.new_file(self.current_filename)
        dialog.destroy()
        self.update_title()

    #TODO: find out the correct way to use Gtk.StatusBar
    def onUpdateStatusTextPush(self, data):
#        self.textview.get_buffer().set_modified(True)
#        text_buffer = self.textview.get_buffer()
#        chars = text_buffer.get_char_count()
#        lines = text_buffer.get_line_count()
#        text_info = "Lines:{lines} | Chars:{chars}".\
#        format(lines= lines, chars= chars)
#
#        statusbar_context =  self.statusbar.get_context()
#        self.statusbar.remove_all(statusbar_context)
#        self.statusbar.push(statusbar_context, text_info )
        pass

    def onUpdateStatusTextPop(self, data):
#        self.textview.get_buffer().set_modified(True)
#        text_buffer = self.textview.get_buffer()
#        chars = text_buffer.get_char_count()
#        lines = text_buffer.get_line_count()
#        text_info = "Lines:{lines} | Chars:{chars}".\
#        format(lines= lines, chars= chars)
#        statusbar_context =  self.statusbar.get_context()
#        self.statusbar.remove_all(statusbar_context)
#        self.statusbar.push(statusbar_context, text_info )
        pass

    def onQuit(self, data):
        self.editor.exit()
        raise "QUIT"


text:
#ifndef ALINOUS_WEB_PARSE_HTMLXML_HTMLXMLPARSERCONSTANTS_H_
#define ALINOUS_WEB_PARSE_HTMLXML_HTMLXMLPARSERCONSTANTS_H_
namespace java {namespace lang {
class IObject;
}}

namespace alinous {
class ThreadContext;
}

namespace alinous {namespace web {namespace parse {namespace htmlxml {

using namespace ::alinous;
using namespace ::java::lang;
using ::java::util::Iterator;

class HtmlXmlParserConstants : public virtual IObject {
public:
	HtmlXmlParserConstants(const HtmlXmlParserConstants& base) = default;
public:
	HtmlXmlParserConstants(ThreadContext* ctx) throw() ;
	void __construct_impl(ThreadContext* ctx) throw() ;
	virtual ~HtmlXmlParserConstants() throw();
	virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
public:
	constexpr static const long long EOF{0};
	constexpr static const long long br{1};
	constexpr static const long long img{2};
	constexpr static const long long link{3};
	constexpr static const long long meta{4};
	constexpr static const long long col{5};
	constexpr static const long long param{6};
	constexpr static const long long base{7};
	constexpr static const long long area{8};
	constexpr static const long long hr{9};
	constexpr static const long long input{10};
	constexpr static const long long GT{11};
	constexpr static const long long LT{12};
	constexpr static const long long LT_SLASH{13};
	constexpr static const long long GT_SLASH{14};
	constexpr static const long long EQUALS{15};
	constexpr static const long long CDATA_START{16};
	constexpr static const long long CDATA_END{17};
	constexpr static const long long XML_HEADER_START{18};
	constexpr static const long long XML_HEADER_END{19};
	constexpr static const long long DOCTYPE{20};
	constexpr static const long long COM_START{21};
	constexpr static const long long COMMENT{22};
	constexpr static const long long WHITE_SPACE{24};
	constexpr static const long long STRING_LITERAL{25};
	constexpr static const long long SQ_STRING_LITERAL{26};
	constexpr static const long long IDENTIFIER_BASE{27};
	constexpr static const long long IDENTIFIER{28};
	constexpr static const long long HTML_BODY_STRING{29};
	constexpr static const long long DEFAULT{0};
	constexpr static const long long COMM{1};
	static const StaticArrayObject<UnicodeStringWrapper> __tokenImage;
	static IArrayObject<String>* tokenImage;
public:
	static bool __init_done;
	static bool __init_static_variables();
public:
	static void __cleanUp(ThreadContext* ctx);
};

}}}}

#endif /* end of ALINOUS_WEB_PARSE_HTMLXML_HTMLXMLPARSERCONSTANTS_H_ */


text:
ActiveRecord::Schema.define(:version => 0) do
  create_table "movies", :force => true do |t|
    t.string   "title"
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end


text:
package org.apache.giraph.types;

import org.apache.hadoop.io.BooleanWritable;

/**
 * Converts Booleans to BooleanWritables
 */
public class BooleanToBooleanWritableWrapper
    implements WritableWrapper<BooleanWritable, Boolean> {
  @Override
  public BooleanWritable wrap(Boolean javaValue) {
    return new BooleanWritable(javaValue);
  }
}


text:
'use strict'

const semver = require('semver')

module.exports = function (version) {
  if (!version) { return '' }

  if (semver.satisfies(version, '>= 1.0.0')) {
    return `https://github.com/nodejs/node/blob/${version}/CHANGELOG.md`
  }

  return `https://github.com/nodejs/node-v0.x-archive/blob/${version}/ChangeLog`
}


text:
<?php

namespace ShaneDaSilva\Darklaunch\Operator;

use ShaneDaSilva\Darklaunch\FeatureOperator;

class GreaterThan extends FeatureOperator {

    /**
     * @var string
     */
    protected $name = 'greaterThan';

    /**
     * @var mixed
     */
    protected $value;

    /**
     * @param mixed $value
     */
    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return mixed The value compared to
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @param $argument
     *
     * @return bool
     */
    public function appliesTo($argument)
    {
        return $argument > $this->value;
    }

}


text:
#define LOG_TAG "APM::Serializer"
//#define LOG_NDEBUG 0

#include "Serializer.h"
#include <media/convert.h>
#include "TypeConverter.h"
#include <libxml/parser.h>
#include <libxml/xinclude.h>
#include <string>
#include <sstream>
#include <istream>

using std::string;

namespace android {

string getXmlAttribute(const xmlNode *cur, const char *attribute)
{
    xmlChar *xmlValue = xmlGetProp(cur, (const xmlChar*)attribute);
    if (xmlValue == NULL) {
        return "";
    }
    string value((const char*)xmlValue);
    xmlFree(xmlValue);
    return value;
}

using utilities::convertTo;

const char *const PolicySerializer::rootName = "audioPolicyConfiguration";
const char *const PolicySerializer::versionAttribute = "version";
const uint32_t PolicySerializer::gMajor = 1;
const uint32_t PolicySerializer::gMinor = 0;
static const char *const gReferenceElementName = "reference";
static const char *const gReferenceAttributeName = "name";

template <class Trait>
static void getReference(const _xmlNode *root, const _xmlNode *&refNode, const string &refName)
{
    const _xmlNode *col = root;
    while (col != NULL) {
        if (!xmlStrcmp(col->name, (const xmlChar *)Trait::collectionTag)) {
            const xmlNode *cur = col->children;
            while (cur != NULL) {
                if ((!xmlStrcmp(cur->name, (const xmlChar *)gReferenceElementName))) {
                    string name = getXmlAttribute(cur, gReferenceAttributeName);
                    if (refName == name) {
                        refNode = cur;
                        return;
                    }
                }
                cur = cur->next;
            }
        }
        col = col->next;
    }
    return;
}

template <class Trait>
static status_t deserializeCollection(_xmlDoc *doc, const _xmlNode *cur,
                                      typename Trait::Collection &collection,
                                      typename Trait::PtrSerializingCtx serializingContext)
{
    const xmlNode *root = cur->xmlChildrenNode;
    while (root != NULL) {
        if (xmlStrcmp(root->name, (const xmlChar *)Trait::collectionTag) &&
                xmlStrcmp(root->name, (const xmlChar *)Trait::tag)) {
            root = root->next;
            continue;
        }
        const xmlNode *child = root;
        if (!xmlStrcmp(child->name, (const xmlChar *)Trait::collectionTag)) {
            child = child->xmlChildrenNode;
        }
        while (child != NULL) {
            if (!xmlStrcmp(child->name, (const xmlChar *)Trait::tag)) {
                typename Trait::PtrElement element;
                status_t status = Trait::deserialize(doc, child, element, serializingContext);
                if (status != NO_ERROR) {
                    return status;
                }
                if (collection.add(element) < 0) {
                    ALOGE("%s: could not add element to %s collection", __FUNCTION__,
                          Trait::collectionTag);
                }
            }
            child = child->next;
        }
        if (!xmlStrcmp(root->name, (const xmlChar *)Trait::tag)) {
            return NO_ERROR;
        }
        root = root->next;
    }
    return NO_ERROR;
}

const char *const AudioGainTraits::tag = "gain";
const char *const AudioGainTraits::collectionTag = "gains";

const char AudioGainTraits::Attributes::mode[] = "mode";
const char AudioGainTraits::Attributes::channelMask[] = "channel_mask";
const char AudioGainTraits::Attributes::minValueMB[] = "minValueMB";
const char AudioGainTraits::Attributes::maxValueMB[] = "maxValueMB";
const char AudioGainTraits::Attributes::defaultValueMB[] = "defaultValueMB";
const char AudioGainTraits::Attributes::stepValueMB[] = "stepValueMB";
const char AudioGainTraits::Attributes::minRampMs[] = "minRampMs";
const char AudioGainTraits::Attributes::maxRampMs[] = "maxRampMs";

status_t AudioGainTraits::deserialize(_xmlDoc */*doc*/, const _xmlNode *root, PtrElement &gain,
                                      PtrSerializingCtx /*serializingContext*/)
{
    static uint32_t index = 0;
    gain = new Element(index++, true);

    string mode = getXmlAttribute(root, Attributes::mode);
    if (!mode.empty()) {
        gain->setMode(GainModeConverter::maskFromString(mode));
    }

    string channelsLiteral = getXmlAttribute(root, Attributes::channelMask);
    if (!channelsLiteral.empty()) {
        gain->setChannelMask(channelMaskFromString(channelsLiteral));
    }

    string minValueMBLiteral = getXmlAttribute(root, Attributes::minValueMB);
    int32_t minValueMB;
    if (!minValueMBLiteral.empty() && convertTo(minValueMBLiteral, minValueMB)) {
        gain->setMinValueInMb(minValueMB);
    }

    string maxValueMBLiteral = getXmlAttribute(root, Attributes::maxValueMB);
    int32_t maxValueMB;
    if (!maxValueMBLiteral.empty() && convertTo(maxValueMBLiteral, maxValueMB)) {
        gain->setMaxValueInMb(maxValueMB);
    }

    string defaultValueMBLiteral = getXmlAttribute(root, Attributes::defaultValueMB);
    int32_t defaultValueMB;
    if (!defaultValueMBLiteral.empty() && convertTo(defaultValueMBLiteral, defaultValueMB)) {
        gain->setDefaultValueInMb(defaultValueMB);
    }

    string stepValueMBLiteral = getXmlAttribute(root, Attributes::stepValueMB);
    uint32_t stepValueMB;
    if (!stepValueMBLiteral.empty() && convertTo(stepValueMBLiteral, stepValueMB)) {
        gain->setStepValueInMb(stepValueMB);
    }

    string minRampMsLiteral = getXmlAttribute(root, Attributes::minRampMs);
    uint32_t minRampMs;
    if (!minRampMsLiteral.empty() && convertTo(minRampMsLiteral, minRampMs)) {
        gain->setMinRampInMs(minRampMs);
    }

    string maxRampMsLiteral = getXmlAttribute(root, Attributes::maxRampMs);
    uint32_t maxRampMs;
    if (!maxRampMsLiteral.empty() && convertTo(maxRampMsLiteral, maxRampMs)) {
        gain->setMaxRampInMs(maxRampMs);
    }
    ALOGV("%s: adding new gain mode %08x channel mask %08x min mB %d max mB %d", __FUNCTION__,
          gain->getMode(), gain->getChannelMask(), gain->getMinValueInMb(),
          gain->getMaxValueInMb());

    if (gain->getMode() == 0) {
        return BAD_VALUE;
    }
    return NO_ERROR;
}

const char *const AudioProfileTraits::collectionTag = "profiles";
const char *const AudioProfileTraits::tag = "profile";

const char AudioProfileTraits::Attributes::name[] = "name";
const char AudioProfileTraits::Attributes::samplingRates[] = "samplingRates";
const char AudioProfileTraits::Attributes::format[] = "format";
const char AudioProfileTraits::Attributes::channelMasks[] = "channelMasks";

status_t AudioProfileTraits::deserialize(_xmlDoc */*doc*/, const _xmlNode *root, PtrElement &profile,
                                         PtrSerializingCtx /*serializingContext*/)
{
    string samplingRates = getXmlAttribute(root, Attributes::samplingRates);
    string format = getXmlAttribute(root, Attributes::format);
    string channels = getXmlAttribute(root, Attributes::channelMasks);

    profile = new Element(formatFromString(format, gDynamicFormat),
                          channelMasksFromString(channels, ","),
                          samplingRatesFromString(samplingRates, ","));

    profile->setDynamicFormat(profile->getFormat() == gDynamicFormat);
    profile->setDynamicChannels(profile->getChannels().isEmpty());
    profile->setDynamicRate(profile->getSampleRates().isEmpty());

    return NO_ERROR;
}

const char *const MixPortTraits::collectionTag = "mixPorts";
const char *const MixPortTraits::tag = "mixPort";

const char MixPortTraits::Attributes::name[] = "name";
const char MixPortTraits::Attributes::role[] = "role";
const char MixPortTraits::Attributes::flags[] = "flags";
const char MixPortTraits::Attributes::maxOpenCount[] = "maxOpenCount";
const char MixPortTraits::Attributes::maxActiveCount[] = "maxActiveCount";

status_t MixPortTraits::deserialize(_xmlDoc *doc, const _xmlNode *child, PtrElement &mixPort,
                                    PtrSerializingCtx /*serializingContext*/)
{
    string name = getXmlAttribute(child, Attributes::name);
    if (name.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::name);
        return BAD_VALUE;
    }
    ALOGV("%s: %s %s=%s", __FUNCTION__, tag, Attributes::name, name.c_str());
    string role = getXmlAttribute(child, Attributes::role);
    if (role.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::role);
        return BAD_VALUE;
    }
    ALOGV("%s: Role=%s", __FUNCTION__, role.c_str());
    audio_port_role_t portRole = role == "source" ? AUDIO_PORT_ROLE_SOURCE : AUDIO_PORT_ROLE_SINK;

    mixPort = new Element(String8(name.c_str()), portRole);

    AudioProfileTraits::Collection profiles;
    deserializeCollection<AudioProfileTraits>(doc, child, profiles, NULL);
    if (profiles.isEmpty()) {
        sp <AudioProfile> dynamicProfile = new AudioProfile(gDynamicFormat,
                                                            ChannelsVector(), SampleRateVector());
        dynamicProfile->setDynamicFormat(true);
        dynamicProfile->setDynamicChannels(true);
        dynamicProfile->setDynamicRate(true);
        profiles.add(dynamicProfile);
    }
    mixPort->setAudioProfiles(profiles);

    string flags = getXmlAttribute(child, Attributes::flags);
    if (!flags.empty()) {
        // Source role
        if (portRole == AUDIO_PORT_ROLE_SOURCE) {
            mixPort->setFlags(OutputFlagConverter::maskFromString(flags));
        } else {
            // Sink role
            mixPort->setFlags(InputFlagConverter::maskFromString(flags));
        }
    }
    string maxOpenCount = getXmlAttribute(child, Attributes::maxOpenCount);
    if (!maxOpenCount.empty()) {
        convertTo(maxOpenCount, mixPort->maxOpenCount);
    }
    string maxActiveCount = getXmlAttribute(child, Attributes::maxActiveCount);
    if (!maxActiveCount.empty()) {
        convertTo(maxActiveCount, mixPort->maxActiveCount);
    }
    // Deserialize children
    AudioGainTraits::Collection gains;
    deserializeCollection<AudioGainTraits>(doc, child, gains, NULL);
    mixPort->setGains(gains);

    return NO_ERROR;
}

const char *const DevicePortTraits::tag = "devicePort";
const char *const DevicePortTraits::collectionTag = "devicePorts";

const char DevicePortTraits::Attributes::tagName[] = "tagName";
const char DevicePortTraits::Attributes::type[] = "type";
const char DevicePortTraits::Attributes::role[] = "role";
const char DevicePortTraits::Attributes::address[] = "address";
const char DevicePortTraits::Attributes::roleSource[] = "source";

status_t DevicePortTraits::deserialize(_xmlDoc *doc, const _xmlNode *root, PtrElement &deviceDesc,
                                       PtrSerializingCtx /*serializingContext*/)
{
    string name = getXmlAttribute(root, Attributes::tagName);
    if (name.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::tagName);
        return BAD_VALUE;
    }
    ALOGV("%s: %s %s=%s", __FUNCTION__, tag, Attributes::tagName, name.c_str());
    string typeName = getXmlAttribute(root, Attributes::type);
    if (typeName.empty()) {
        ALOGE("%s: no type for %s", __FUNCTION__, name.c_str());
        return BAD_VALUE;
    }
    ALOGV("%s: %s %s=%s", __FUNCTION__, tag, Attributes::type, typeName.c_str());
    string role = getXmlAttribute(root, Attributes::role);
    if (role.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::role);
        return BAD_VALUE;
    }
    ALOGV("%s: %s %s=%s", __FUNCTION__, tag, Attributes::role, role.c_str());
    audio_port_role_t portRole = (role == Attributes::roleSource) ?
                AUDIO_PORT_ROLE_SOURCE : AUDIO_PORT_ROLE_SINK;

    audio_devices_t type = AUDIO_DEVICE_NONE;
    if (!deviceFromString(typeName, type) ||
            (!audio_is_input_device(type) && portRole == AUDIO_PORT_ROLE_SOURCE) ||
            (!audio_is_output_devices(type) && portRole == AUDIO_PORT_ROLE_SINK)) {
        ALOGW("%s: bad type %08x", __FUNCTION__, type);
        return BAD_VALUE;
    }
    deviceDesc = new Element(type, String8(name.c_str()));

    string address = getXmlAttribute(root, Attributes::address);
    if (!address.empty()) {
        ALOGV("%s: address=%s for %s", __FUNCTION__, address.c_str(), name.c_str());
        deviceDesc->mAddress = String8(address.c_str());
    }

    AudioProfileTraits::Collection profiles;
    deserializeCollection<AudioProfileTraits>(doc, root, profiles, NULL);
    if (profiles.isEmpty()) {
        sp <AudioProfile> dynamicProfile = new AudioProfile(gDynamicFormat,
                                                            ChannelsVector(), SampleRateVector());
        dynamicProfile->setDynamicFormat(true);
        dynamicProfile->setDynamicChannels(true);
        dynamicProfile->setDynamicRate(true);
        profiles.add(dynamicProfile);
    }
    deviceDesc->setAudioProfiles(profiles);

    // Deserialize AudioGain children
    deserializeCollection<AudioGainTraits>(doc, root, deviceDesc->mGains, NULL);
    ALOGV("%s: adding device tag %s type %08x address %s", __FUNCTION__,
          deviceDesc->getName().string(), type, deviceDesc->mAddress.string());
    return NO_ERROR;
}

const char *const RouteTraits::tag = "route";
const char *const RouteTraits::collectionTag = "routes";

const char RouteTraits::Attributes::type[] = "type";
const char RouteTraits::Attributes::typeMix[] = "mix";
const char RouteTraits::Attributes::sink[] = "sink";
const char RouteTraits::Attributes::sources[] = "sources";

status_t RouteTraits::deserialize(_xmlDoc */*doc*/, const _xmlNode *root, PtrElement &element,
                                  PtrSerializingCtx ctx)
{
    string type = getXmlAttribute(root, Attributes::type);
    if (type.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::type);
        return BAD_VALUE;
    }
    audio_route_type_t routeType = (type == Attributes::typeMix) ?
                AUDIO_ROUTE_MIX : AUDIO_ROUTE_MUX;

    ALOGV("%s: %s %s=%s", __FUNCTION__, tag, Attributes::type, type.c_str());
    element = new Element(routeType);

    string sinkAttr = getXmlAttribute(root, Attributes::sink);
    if (sinkAttr.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::sink);
        return BAD_VALUE;
    }
    // Convert Sink name to port pointer
    sp<AudioPort> sink = ctx->findPortByTagName(String8(sinkAttr.c_str()));
    if (sink == NULL) {
        ALOGE("%s: no sink found with name=%s", __FUNCTION__, sinkAttr.c_str());
        return BAD_VALUE;
    }
    element->setSink(sink);

    string sourcesAttr = getXmlAttribute(root, Attributes::sources);
    if (sourcesAttr.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::sources);
        return BAD_VALUE;
    }
    // Tokenize and Convert Sources name to port pointer
    AudioPortVector sources;
    char *sourcesLiteral = strndup(sourcesAttr.c_str(), strlen(sourcesAttr.c_str()));
    char *devTag = strtok(sourcesLiteral, ",");
    while (devTag != NULL) {
        if (strlen(devTag) != 0) {
            sp<AudioPort> source = ctx->findPortByTagName(String8(devTag));
            if (source == NULL) {
                ALOGE("%s: no source found with name=%s", __FUNCTION__, devTag);
                free(sourcesLiteral);
                return BAD_VALUE;
            }
            sources.add(source);
        }
        devTag = strtok(NULL, ",");
    }
    free(sourcesLiteral);

    sink->addRoute(element);
    for (size_t i = 0; i < sources.size(); i++) {
        sp<AudioPort> source = sources.itemAt(i);
        source->addRoute(element);
    }
    element->setSources(sources);
    return NO_ERROR;
}

const char *const ModuleTraits::childAttachedDevicesTag = "attachedDevices";
const char *const ModuleTraits::childAttachedDeviceTag = "item";
const char *const ModuleTraits::childDefaultOutputDeviceTag = "defaultOutputDevice";

const char *const ModuleTraits::tag = "module";
const char *const ModuleTraits::collectionTag = "modules";

const char ModuleTraits::Attributes::name[] = "name";
const char ModuleTraits::Attributes::version[] = "halVersion";

status_t ModuleTraits::deserialize(xmlDocPtr doc, const xmlNode *root, PtrElement &module,
                                   PtrSerializingCtx ctx)
{
    string name = getXmlAttribute(root, Attributes::name);
    if (name.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::name);
        return BAD_VALUE;
    }
    uint32_t versionMajor = 0, versionMinor = 0;
    string versionLiteral = getXmlAttribute(root, Attributes::version);
    if (!versionLiteral.empty()) {
        sscanf(versionLiteral.c_str(), "%u.%u", &versionMajor, &versionMinor);
        ALOGV("%s: mHalVersion = major %u minor %u",  __FUNCTION__,
              versionMajor, versionMajor);
    }

    ALOGV("%s: %s %s=%s", __FUNCTION__, tag, Attributes::name, name.c_str());

    module = new Element(name.c_str(), versionMajor, versionMinor);

    // Deserialize childrens: Audio Mix Port, Audio Device Ports (Source/Sink), Audio Routes
    MixPortTraits::Collection mixPorts;
    deserializeCollection<MixPortTraits>(doc, root, mixPorts, NULL);
    module->setProfiles(mixPorts);

    DevicePortTraits::Collection devicePorts;
    deserializeCollection<DevicePortTraits>(doc, root, devicePorts, NULL);
    module->setDeclaredDevices(devicePorts);

    RouteTraits::Collection routes;
    deserializeCollection<RouteTraits>(doc, root, routes, module.get());
    module->setRoutes(routes);

    const xmlNode *children = root->xmlChildrenNode;
    while (children != NULL) {
        if (!xmlStrcmp(children->name, (const xmlChar *)childAttachedDevicesTag)) {
            ALOGV("%s: %s %s found", __FUNCTION__, tag, childAttachedDevicesTag);
            const xmlNode *child = children->xmlChildrenNode;
            while (child != NULL) {
                if (!xmlStrcmp(child->name, (const xmlChar *)childAttachedDeviceTag)) {
                    xmlChar *attachedDevice = xmlNodeListGetString(doc, child->xmlChildrenNode, 1);
                    if (attachedDevice != NULL) {
                        ALOGV("%s: %s %s=%s", __FUNCTION__, tag, childAttachedDeviceTag,
                              (const char*)attachedDevice);
                        sp<DeviceDescriptor> device =
                                module->getDeclaredDevices().getDeviceFromTagName(String8((const char*)attachedDevice));
                        ctx->addAvailableDevice(device);
                        xmlFree(attachedDevice);
                    }
                }
                child = child->next;
            }
        }
        if (!xmlStrcmp(children->name, (const xmlChar *)childDefaultOutputDeviceTag)) {
            xmlChar *defaultOutputDevice = xmlNodeListGetString(doc, children->xmlChildrenNode, 1);;
            if (defaultOutputDevice != NULL) {
                ALOGV("%s: %s %s=%s", __FUNCTION__, tag, childDefaultOutputDeviceTag,
                      (const char*)defaultOutputDevice);
                sp<DeviceDescriptor> device =
                        module->getDeclaredDevices().getDeviceFromTagName(String8((const char*)defaultOutputDevice));
                if (device != 0 && ctx->getDefaultOutputDevice() == 0) {
                    ctx->setDefaultOutputDevice(device);
                    ALOGV("%s: default is %08x", __FUNCTION__, ctx->getDefaultOutputDevice()->type());
                }
                xmlFree(defaultOutputDevice);
            }
        }
        children = children->next;
    }
    return NO_ERROR;
}

const char *const GlobalConfigTraits::tag = "globalConfiguration";

const char GlobalConfigTraits::Attributes::speakerDrcEnabled[] = "speaker_drc_enabled";

status_t GlobalConfigTraits::deserialize(const xmlNode *cur, AudioPolicyConfig &config)
{
    const xmlNode *root = cur->xmlChildrenNode;
    while (root != NULL) {
        if (!xmlStrcmp(root->name, (const xmlChar *)tag)) {
            string speakerDrcEnabled =
                    getXmlAttribute(root, Attributes::speakerDrcEnabled);
            bool isSpeakerDrcEnabled;
            if (!speakerDrcEnabled.empty() &&
                    convertTo<string, bool>(speakerDrcEnabled, isSpeakerDrcEnabled)) {
                config.setSpeakerDrcEnabled(isSpeakerDrcEnabled);
            }
            return NO_ERROR;
        }
        root = root->next;
    }
    return NO_ERROR;
}

const char *const VolumeTraits::tag = "volume";
const char *const VolumeTraits::collectionTag = "volumes";
const char *const VolumeTraits::volumePointTag = "point";

const char VolumeTraits::Attributes::stream[] = "stream";
const char VolumeTraits::Attributes::deviceCategory[] = "deviceCategory";
const char VolumeTraits::Attributes::reference[] = "ref";

status_t VolumeTraits::deserialize(_xmlDoc *doc, const _xmlNode *root, PtrElement &element,
                                   PtrSerializingCtx /*serializingContext*/)
{
    string streamTypeLiteral = getXmlAttribute(root, Attributes::stream);
    if (streamTypeLiteral.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::stream);
        return BAD_VALUE;
    }
    audio_stream_type_t streamType;
    if (!StreamTypeConverter::fromString(streamTypeLiteral, streamType)) {
        ALOGE("%s: Invalid %s", __FUNCTION__, Attributes::stream);
        return BAD_VALUE;
    }
    string deviceCategoryLiteral = getXmlAttribute(root, Attributes::deviceCategory);
    if (deviceCategoryLiteral.empty()) {
        ALOGE("%s: No %s found", __FUNCTION__, Attributes::deviceCategory);
        return BAD_VALUE;
    }
    device_category deviceCategory;
    if (!DeviceCategoryConverter::fromString(deviceCategoryLiteral, deviceCategory)) {
        ALOGE("%s: Invalid %s=%s", __FUNCTION__, Attributes::deviceCategory,
              deviceCategoryLiteral.c_str());
        return BAD_VALUE;
    }

    string referenceName = getXmlAttribute(root, Attributes::reference);
    const _xmlNode *ref = NULL;
    if (!referenceName.empty()) {
        getReference<VolumeTraits>(root->parent, ref, referenceName);
        if (ref == NULL) {
            ALOGE("%s: No reference Ptr found for %s", __FUNCTION__, referenceName.c_str());
            return BAD_VALUE;
        }
    }

    element = new Element(deviceCategory, streamType);

    const xmlNode *child = referenceName.empty() ? root->xmlChildrenNode : ref->xmlChildrenNode;
    while (child != NULL) {
        if (!xmlStrcmp(child->name, (const xmlChar *)volumePointTag)) {
            xmlChar *pointDefinition = xmlNodeListGetString(doc, child->xmlChildrenNode, 1);;
            if (pointDefinition == NULL) {
                return BAD_VALUE;
            }
            ALOGV("%s: %s=%s", __FUNCTION__, tag, (const char*)pointDefinition);
            Vector<int32_t> point;
            collectionFromString<DefaultTraits<int32_t> >((const char*)pointDefinition, point, ",");
            if (point.size() != 2) {
                ALOGE("%s: Invalid %s: %s", __FUNCTION__, volumePointTag,
                      (const char*)pointDefinition);
                return BAD_VALUE;
            }
            element->add(CurvePoint(point[0], point[1]));
            xmlFree(pointDefinition);
        }
        child = child->next;
    }
    return NO_ERROR;
}

PolicySerializer::PolicySerializer() : mRootElementName(rootName)
{
    std::ostringstream oss;
    oss << gMajor << "." << gMinor;
    mVersion = oss.str();
    ALOGV("%s: Version=%s Root=%s", __FUNCTION__, mVersion.c_str(), mRootElementName.c_str());
}

status_t PolicySerializer::deserialize(const char *configFile, AudioPolicyConfig &config)
{
    xmlDocPtr doc;
    doc = xmlParseFile(configFile);
    if (doc == NULL) {
        ALOGE("%s: Could not parse %s document.", __FUNCTION__, configFile);
        return BAD_VALUE;
    }
    xmlNodePtr cur = xmlDocGetRootElement(doc);
    if (cur == NULL) {
        ALOGE("%s: Could not parse %s document: empty.", __FUNCTION__, configFile);
        xmlFreeDoc(doc);
        return BAD_VALUE;
    }
    if (xmlXIncludeProcess(doc) < 0) {
         ALOGE("%s: libxml failed to resolve XIncludes on %s document.", __FUNCTION__, configFile);
    }

    if (xmlStrcmp(cur->name, (const xmlChar *) mRootElementName.c_str()))  {
        ALOGE("%s: No %s root element found in xml data %s.", __FUNCTION__, mRootElementName.c_str(),
              (const char *)cur->name);
        xmlFreeDoc(doc);
        return BAD_VALUE;
    }

    string version = getXmlAttribute(cur, versionAttribute);
    if (version.empty()) {
        ALOGE("%s: No version found in root node %s", __FUNCTION__, mRootElementName.c_str());
        return BAD_VALUE;
    }
    if (version != mVersion) {
        ALOGE("%s: Version does not match; expect %s got %s", __FUNCTION__, mVersion.c_str(),
              version.c_str());
        return BAD_VALUE;
    }
    // Lets deserialize children
    // Modules
    ModuleTraits::Collection modules;
    deserializeCollection<ModuleTraits>(doc, cur, modules, &config);
    config.setHwModules(modules);

    // deserialize volume section
    VolumeTraits::Collection volumes;
    deserializeCollection<VolumeTraits>(doc, cur, volumes, &config);
    config.setVolumes(volumes);

    // Global Configuration
    GlobalConfigTraits::deserialize(cur, config);

    xmlFreeDoc(doc);
    return android::OK;
}

} // namespace android


text:
import {global} from '@angular/common/src/facade/lang';
import {Compiler, SystemJsNgModuleLoader} from '@angular/core';
import {async, tick} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';

function mockSystem(modules: {[module: string]: any}) {
  return {
    'import': (target: string) => {
      expect(modules[target]).not.toBe(undefined);
      return Promise.resolve(modules[target]);
    }
  };
}

export function main() {
  describe('SystemJsNgModuleLoader', () => {
    let oldSystem: any = null;
    beforeEach(() => {
      oldSystem = (global as any).System;
      (global as any).System = mockSystem({
        'test.ngfactory':
            {'default': 'test module factory', 'NamedNgFactory': 'test NamedNgFactory'},
        'prefixed/test/suffixed': {'NamedNgFactory': 'test module factory'}
      });
    });
    afterEach(() => { (global as any).System = oldSystem; });

    it('loads a default factory by appending the factory suffix', async(() => {
         let loader = new SystemJsNgModuleLoader(new Compiler());
         loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });
       }));
    it('loads a named factory by appending the factory suffix', async(() => {
         let loader = new SystemJsNgModuleLoader(new Compiler());
         loader.load('test#Named').then(contents => {
           expect(contents).toBe('test NamedNgFactory');
         });
       }));
    it('loads a named factory with a configured prefix and suffix', async(() => {
         let loader = new SystemJsNgModuleLoader(new Compiler(), {
           factoryPathPrefix: 'prefixed/',
           factoryPathSuffix: '/suffixed',
         });
         loader.load('test#Named').then(contents => {
           expect(contents).toBe('test module factory');
         });
       }));
  });
};


text:
package org.gyt.web.admin;

import org.apache.commons.lang3.StringUtils;
import org.gyt.web.api.service.ArticleService;
import org.gyt.web.api.service.FellowshipService;
import org.gyt.web.api.utils.ModelAndViewUtils;
import org.gyt.web.model.Article;
import org.gyt.web.model.ArticleStatus;
import org.gyt.web.model.Fellowship;
import org.gyt.web.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 后台页面路由器
 * Created by Administrator on 2016/9/16.
 */
@RestController
@RequestMapping("/admin")
public class AdminArticlePageController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private FellowshipService fellowshipService;

    @Autowired
    private ModelAndViewUtils modelAndViewUtils;

    @RequestMapping("/article")
    public ModelAndView tablePage(
            @RequestParam(required = false) String type
    ) {
        ModelAndView modelAndView = modelAndViewUtils.newAdminModelAndView("admin-article");

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        List<Article> articleList = articleService.getFromUser(user.getUsername());

        if (StringUtils.isEmpty(type)) {
            modelAndView.addObject("items", articleService.getFromUser(user.getUsername()));
            modelAndView.addObject("subtitle", "我的文章");
            type = "MINE";
        } else if (type.equalsIgnoreCase("RAW")) {
            modelAndView.addObject("items", articleList.stream().filter(article -> article.getStatus().equals(ArticleStatus.RAW)).collect(Collectors.toList()));
            modelAndView.addObject("subtitle", "我的草稿箱");
        } else if (type.equalsIgnoreCase("AUDIT")) {
            if (user.getRoles().stream().anyMatch(role -> role.getAuthorities().stream().anyMatch(s -> s.equals("ROLE_MANAGE_ARTICLE")))) {
                modelAndView.addObject("items", articleService.getAll().stream().filter(article -> article.getStatus().equals(ArticleStatus.AUDITING)).collect(Collectors.toList()));
            } else {
                modelAndView.addObject("items", articleList.stream().filter(article -> article.getStatus().equals(ArticleStatus.AUDITING)).collect(Collectors.toList()));
            }
            modelAndView.addObject("subtitle", "待审核文章");
        } else if (type.equalsIgnoreCase("PUBLISH")) {
            if (user.getRoles().stream().anyMatch(role -> role.getAuthorities().stream().anyMatch(s -> s.equals("ROLE_MANAGE_ARTICLE")))) {
                modelAndView.addObject("items", articleService.getAll().stream().filter(article -> article.getStatus().equals(ArticleStatus.PUBLISHED)).collect(Collectors.toList()));
            } else {
                modelAndView.addObject("items", articleList.stream().filter(article -> article.getStatus().equals(ArticleStatus.PUBLISHED)).collect(Collectors.toList()));
            }
            modelAndView.addObject("subtitle", "已发布文章");
        } else if (type.equalsIgnoreCase("REJECT")) {
            modelAndView.addObject("items", articleList.stream().filter(article -> article.getStatus().equals(ArticleStatus.REJECTED)).collect(Collectors.toList()));
            modelAndView.addObject("subtitle", "我的驳回文章");
        } else {
            modelAndView.addObject("items", new ArrayList<>());
            modelAndView.addObject("subtitle", "未知类型");
        }

        modelAndView.addObject("type", type);
        return modelAndView;
    }

    @RequestMapping("/article/{id}")
    public ModelAndView detailsPage(
            @PathVariable String id
    ) {
        ModelAndView modelAndView = modelAndViewUtils.newAdminModelAndView("admin-article-details");
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        Article article = articleService.get(Long.valueOf(id));

        if (null == article) {
            modelAndView.setViewName("404");
            modelAndView.addObject("message", String.format("找不到文章:%s", id));
        } else {
            modelAndView.addObject("title", article.getTitle());
            modelAndView.addObject("subtitle", "文章预览");
            modelAndView.addObject("item", article);
            modelAndView.addObject("user", user);
        }

        return modelAndView;
    }

    @RequestMapping("/article/{id}/edit")
    public ModelAndView editArticlePage(
            @PathVariable String id
    ) {
        ModelAndView modelAndView = modelAndViewUtils.newAdminModelAndView("admin-article-editor");
        modelAndView.addObject("title", "编辑文章");

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Article article = articleService.get(Long.valueOf(id));

        if (article == null) {
            modelAndView.addObject("error", "文章不存在");
        } else if (!article.getAuthor().getUsername().equals(user.getUsername())) {
            modelAndView.addObject("error", "只能编辑自己的文章");
        } else {
            modelAndView.addObject("item", article);
            modelAndView.addObject("edit", true);
            Set<Fellowship> fellowshipSet = new HashSet<>();
            fellowshipSet.addAll(fellowshipService.getUserOwnerFellowship(user.getUsername()));
            fellowshipSet.addAll(fellowshipService.getUserAdminFellowship(user.getUsername()));
            modelAndView.addObject("fellowship", fellowshipSet);
        }

        return modelAndView;
    }

    @RequestMapping("/article/{id}/audit")
    public ModelAndView auditArticlePage(
            @PathVariable String id
    ) {
        ModelAndView modelAndView = modelAndViewUtils.newAdminModelAndView("admin-article-audit");
        modelAndView.addObject("title", "审核文章");

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Article article = articleService.get(Long.valueOf(id));

        if (article == null) {
            modelAndView.addObject("error", "文章不存在");
        } else {
            modelAndView.addObject("item", article);
        }

        return modelAndView;
    }

    @RequestMapping("/article/new")
    public ModelAndView newArticlePage() {
        ModelAndView modelAndView = modelAndViewUtils.newAdminModelAndView("admin-article-editor");
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (fellowshipService.getUserOwnerFellowship(user.getUsername()).isEmpty() && fellowshipService.getUserAdminFellowship(user.getUsername()).isEmpty()) {
            modelAndView.setViewName("403");
            modelAndView.addObject("message", "抱歉,您还没有任何团契的管理权限,不能发布文章到团契");
            return modelAndView;
        }

        modelAndView.addObject("title", "新建文章");
        modelAndView.addObject("item", new Article());

        Set<Fellowship> fellowshipSet = new HashSet<>();
        fellowshipSet.addAll(fellowshipService.getUserOwnerFellowship(user.getUsername()));
        fellowshipSet.addAll(fellowshipService.getUserAdminFellowship(user.getUsername()));
        modelAndView.addObject("fellowship", fellowshipSet);
        return modelAndView;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ScalaCompilerConfiguration">
    <profile name="SBT 1" modules="apachecmda_frontend">
      <option name="deprecationWarnings" value="true" />
      <option name="uncheckedWarnings" value="true" />
      <parameters>
        <parameter value="-encoding" />
        <parameter value="utf8" />
      </parameters>
    </profile>
  </component>
</project>


text:
@interface WSDLProxyTests : SenTestCase

@end


text:
[![UGOforNODE](https://raw.github.com/bluedge/gh-pages/master/images/UGOforNODE.png)](https://github.com/bluedge/UGOforNODE)
#UGOforNODE

Lightweight module for UNIX Symbolic notation "rwxrwxr--" to Octal notation "774" conversion.
[![Build Status](https://travis-ci.org/bluedge/UGOforNODE.png?branch=master)](https://travis-ci.org/bluedge)

## Install

```bash
npm install ugofornode
```

## Features List
	- toOctal from Symbolic notation to Octal notation
	- toSymbolic from Octal notation to Symbolic notation
	- getPermissionByClass return the Symbolic notation for a class (User, Group, Other)
	- isSymbolicValid check Symbolic notation validity
	- isOctalValid check the Octal notation validity

### Usage Example

```js
	var UGOforNODE 			= require('ugofornode')
		, ugo 				= new UGOforNODE();

	// Get Octal notation from Array
	permission1 = ugo.toOctal( ["rwx", "rwx", "r--"]; // 774

	// Get Octal notation from String
	permission2 = ugo.toOctal( "rwxrwxr--" ); // 774

	// Get Symbolic notation (Array) from Octal
	permission3 = ugo.toSymbolic( 774 ); // ["rwx","rwx","r--"]

	// Get Symbolic notation (String) from Octal
	permission4 = ugo.toSymbolic( 774, "string" ); // "rwxrwxr--"

	// Get Symbolic notation of the specified class from Octal Notation
	permission5 = ugo.getPermissionByClass( 774, 'OTHER' ); // "r--"

	// Get Symbolic notation of the specified class from Symbolic Notation (Array)
	permission6 = ugo.getPermissionByClass( ["rwx","rwx","r--"], 'OTHER' ); // "r--"

	// Validate Symbolic notation (Array)
	permission7 = ugo.isSymbolicValid( ["rwx","rwx","r--"] ); // true;

	// Validate Symbolic notation (String)
	permission8 = ugo.isSymbolicValid( "rwxrwxr--" ); // true;

	// Validate Octal notation
	permission9 = ugo.isOctalValid( 555 ); // true;
```

### Sponsors
UGOforNODE was created as part of a custom node development initiative sponsored by Bureaucloud (http://bureaucloud.com) & Bluedge(http://bluedge.co.uk) for a private application.
This simple and lean module quickly became so convenient for addressing permissions, we decided to share it with others.


text:
<?php

namespace Tests\AppBundle\Controller;

use Tests\Fixtures\CuratedDomainUserData;
use Tests\WebTestCase;

class CuratedDomainControllerTest extends WebTestCase
{
    public function testAll()
    {
        $this->loadFixtures([CuratedDomainUserData::class]);
        $session = $this->makeSession([
            'username' => 'curator',
            'password' => 'curator',
        ]);
        $session->visit('/curation/domains');
        $this->assertTrue($session->getPage()->hasContent('No entries found.'));

        $session->getPage()->clickLink('Create new entry');
        $this->assertPath($session, '/curation/domains/new');

        $session->getPage()->fillField('curated_domain_domain', 'example.com');
        $session->getPage()->fillField('curated_domain_reason', 'I do not like examples.');
        $session->getPage()->pressButton('Save');
        $this->assertPath($session, '/curation/domains');

        $row = $session->getPage()->find('css', 'table tbody tr');
        $this->assertStringContainsString('example.com', $row->getText());
        $this->assertStringContainsString('Blocked', $row->getText());
        $this->assertStringContainsString('by @curator', $row->getText());
        $this->assertStringContainsString('I do not like examples.', $row->getText());
        $this->assertStringContainsString('Edit', $row->getText());
        $this->assertStringContainsString('Delete', $row->getText());

        $row->clickLink('Edit');
        $this->assertPath($session, '/curation/domains/1/edit');
        $session->getPage()->findField('curated_domain_type_1')->setValue('V');
        $session->getPage()->pressButton('Update');
        $this->assertPath($session, '/curation/domains');

        $row = $session->getPage()->find('css', 'table tbody tr');
        $this->assertStringContainsString('example.com', $row->getText());
        $this->assertStringContainsString('Verified', $row->getText());
        $this->assertStringContainsString('by @curator', $row->getText());
        $this->assertStringContainsString('I do not like examples.', $row->getText());
        $this->assertStringContainsString('Edit', $row->getText());
        $this->assertStringContainsString('Delete', $row->getText());

        $row->pressButton('Delete');
        $this->assertPath($session, '/curation/domains');
        $this->assertTrue($session->getPage()->hasContent('No entries found.'));
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<title>ArgCV: argcv/sync/sync.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="doxygenextra.css" rel="stylesheet" type="text/css"/>

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

sync.h

Go to the documentation of this file.

    1 // Copyright 2021 Yu Jing

    2 #ifndef ARGCV_SYNC_SYNC_H_

    3 #define ARGCV_SYNC_SYNC_H_

    4

    5 #include "argcv/sync/base.h"

    6 #include "argcv/sync/mutex.h"

    7 #include "argcv/sync/once.h"

    8 #include "argcv/sync/wait_group.h"

    9

   10 #endif  //  ARGCV_SYNC_SYNC_H_

mutex.h

once.h

base.h

wait_group.h

argcv

sync

sync.h


text:
<?php

$body .= <<<HTML

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

Title

        Body

HTML;


text:
<?php
namespace App\Model;

use JayaCode\Framework\Core\Database\Model\Model as BaseModel;

/**
 * Class Model
 * @package App\Model
 */
class Model extends BaseModel
{

    /**
     * @param array $data
     * @param bool $isNewRow
     */
    public function __construct($data = array(), $isNewRow = true)
    {
        parent::__construct($data, $isNewRow);
    }
}