text:
// Copyright 2012 Google Inc.  All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distrib-
// uted 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
// specific language governing permissions and limitations under the License.

/**
 * @fileoverview Model for a map layer.
 * @author kpy@google.com (Ka-Ping Yee)
 */
goog.provide('cm.LayerModel');

goog.require('cm');
goog.require('cm.Html');
goog.require('cm.LatLonBox');
goog.require('goog.Uri');
goog.require('goog.functions');
goog.require('goog.math');
goog.require('goog.object');
goog.require('goog.structs.Set');

/**
 * Model for a layer.  Clients are free to get and set properties of this
 * MVCObject and insert or remove elements of the 'sublayers' property.
 * @constructor
 * @extends google.maps.MVCObject
 */
cm.LayerModel = function() {
  google.maps.MVCObject.call(this);
};
goog.inherits(cm.LayerModel, google.maps.MVCObject);

/** @enum {string} */
cm.LayerModel.Type = {
  FOLDER: 'FOLDER',
  KML: 'KML',
  GEOJSON: 'GEOJSON',
  GEORSS: 'GEORSS',
  TILE: 'TILE',
  CSV: 'CSV',
  GOOGLE_SPREADSHEET: 'GOOGLE_SPREADSHEET',
  FUSION: 'FUSION',
  MAPS_ENGINE: 'MAPS_ENGINE',
  TRAFFIC: 'TRAFFIC',
  TRANSIT: 'TRANSIT',
  WEATHER: 'WEATHER',
  CLOUD: 'CLOUD',
  PLACES: 'PLACES',
  WMS: 'WMS',
  GOOGLE_MAPS_ENGINE_LITE_OR_PRO: 'GOOGLE_MAPS_ENGINE_LITE_OR_PRO'
};

/** @enum {string} */
cm.LayerModel.FolderType = {
  UNLOCKED: 'UNLOCKED',
  LOCKED: 'LOCKED',
  SINGLE_SELECT: 'SINGLE_SELECT'
};

/** @type Object.<cm.LayerModel.Type> */
cm.LayerModel.MAPROOT_TO_MODEL_LAYER_TYPES = {
  'FOLDER': cm.LayerModel.Type.FOLDER,
  'KML': cm.LayerModel.Type.KML,
  'GEOJSON': cm.LayerModel.Type.GEOJSON,
  'GEORSS': cm.LayerModel.Type.GEORSS,
  'GOOGLE_MAP_TILES': cm.LayerModel.Type.TILE,
  'TILE': cm.LayerModel.Type.TILE,
  'CSV': cm.LayerModel.Type.CSV,
  'GOOGLE_SPREADSHEET': cm.LayerModel.Type.GOOGLE_SPREADSHEET,
  'GOOGLE_FUSION_TABLES': cm.LayerModel.Type.FUSION,
  'GOOGLE_MAP_DATA': cm.LayerModel.Type.MAPS_ENGINE,
  'GOOGLE_MAPS_ENGINE': cm.LayerModel.Type.MAPS_ENGINE,
  'GOOGLE_TRAFFIC': cm.LayerModel.Type.TRAFFIC,
  'GOOGLE_TRANSIT': cm.LayerModel.Type.TRANSIT,
  'GOOGLE_WEATHER': cm.LayerModel.Type.WEATHER,
  'GOOGLE_CLOUD_IMAGERY': cm.LayerModel.Type.CLOUD,
  'WMS': cm.LayerModel.Type.WMS,
  'GOOGLE_MAPS_ENGINE_LITE_OR_PRO':
      cm.LayerModel.Type.GOOGLE_MAPS_ENGINE_LITE_OR_PRO,
  'GOOGLE_PLACES': cm.LayerModel.Type.PLACES
};

/**
 * Mapping from layer type to attribution information that should always be
 * displayed for this layer.
 * @type Object.<string>
 */
cm.LayerModel.LAYER_TYPE_TO_ATTRIBUTION = goog.object.create(
  cm.LayerModel.Type.PLACES, cm.MSG_SOURCE_GOOGLE_MAPS
);

/** @enum {string} */
cm.LayerModel.TileCoordinateType = {
  GOOGLE: 'GOOGLE',
  BING: 'BING',
  TMS: 'TMS'
};

/** @type Object.<cm.LayerModel.Type> */
cm.LayerModel.MAPROOT_TO_MODEL_TILE_COORDINATE_TYPES = {
  'GOOGLE': cm.LayerModel.TileCoordinateType.GOOGLE,
  'BING': cm.LayerModel.TileCoordinateType.BING,
  'TMS': cm.LayerModel.TileCoordinateType.TMS
};

/** @type Object.<string> */
cm.LayerModel.MODEL_TO_MAPROOT_TILE_COORDINATE_TYPES = goog.object.create(
  cm.LayerModel.TileCoordinateType.GOOGLE, 'GOOGLE',
  cm.LayerModel.TileCoordinateType.BING, 'BING',
  cm.LayerModel.TileCoordinateType.TMS, 'TMS'
);

/** @enum {string} */
cm.LayerModel.LabelColor = {
  BLACK: 'BLACK',
  WHITE: 'WHITE'
};

/** @enum {string} */
cm.LayerModel.TemperatureUnit = {
  CELSIUS: 'CELSIUS',
  FAHRENHEIT: 'FAHRENHEIT'
};

/** @enum {string} */
cm.LayerModel.WindSpeedUnit = {
  KILOMETERS_PER_HOUR: 'KILOMETERS_PER_HOUR',
  METERS_PER_SECOND: 'METERS_PER_SECOND',
  MILES_PER_HOUR: 'MILES_PER_HOUR'
};

/** @type Object.<cm.LayerModel.LabelColor> */
cm.LayerModel.MAPROOT_TO_MODEL_LABEL_COLORS = {
  'BLACK': cm.LayerModel.LabelColor.BLACK,
  'WHITE': cm.LayerModel.LabelColor.WHITE
};

/** @type Object.<string> */
cm.LayerModel.MODEL_TO_MAPROOT_LABEL_COLORS = goog.object.create(
  cm.LayerModel.LabelColor.BLACK, 'BLACK',
  cm.LayerModel.LabelColor.WHITE, 'WHITE'
);

/** @type Object.<cm.LayerModel.TemperatureUnit> */
cm.LayerModel.MAPROOT_TO_MODEL_TEMPERATURE_UNITS = {
  'CELSIUS': cm.LayerModel.TemperatureUnit.CELSIUS,
  'FAHRENHEIT': cm.LayerModel.TemperatureUnit.FAHRENHEIT
};

/** @type Object.<string> */
cm.LayerModel.MODEL_TO_MAPROOT_TEMPERATURE_UNITS = goog.object.create(
  cm.LayerModel.TemperatureUnit.CELSIUS, 'CELSIUS',
  cm.LayerModel.TemperatureUnit.FAHRENHEIT, 'FAHRENHEIT'
);

/** @type Object.<cm.LayerModel.WindSpeedUnit> */
cm.LayerModel.MAPROOT_TO_MODEL_WIND_SPEED_UNITS = {
  'KILOMETERS_PER_HOUR': cm.LayerModel.WindSpeedUnit.KILOMETERS_PER_HOUR,
  'METERS_PER_SECOND': cm.LayerModel.WindSpeedUnit.METERS_PER_SECOND,
  'MILES_PER_HOUR': cm.LayerModel.WindSpeedUnit.MILES_PER_HOUR
};

/** @type Object.<string> */
cm.LayerModel.MODEL_TO_MAPROOT_WIND_SPEED_UNITS = goog.object.create(
  cm.LayerModel.WindSpeedUnit.KILOMETERS_PER_HOUR, 'KILOMETERS_PER_HOUR',
  cm.LayerModel.WindSpeedUnit.METERS_PER_SECOND, 'METERS_PER_SECOND',
  cm.LayerModel.WindSpeedUnit.MILES_PER_HOUR, 'MILES_PER_HOUR'
);

/** @type Object.<cm.LayerModel.FolderType> */
cm.LayerModel.MAPROOT_TO_MODEL_FOLDER_TYPES = {
  'CHECK': cm.LayerModel.FolderType.UNLOCKED,
  'CHECK_HIDE_CHILDREN': cm.LayerModel.FolderType.LOCKED,
  'RADIO_FOLDER': cm.LayerModel.FolderType.SINGLE_SELECT
};

/**
 * @param {Object} maproot A MapRoot JS layer object.
 * @return {cm.LayerModel} A newly constructed LayerModel, or null if the
 *     'type' member was not a recognized type name.
 */
cm.LayerModel.newFromMapRoot = function(maproot) {
  var type = cm.LayerModel.MAPROOT_TO_MODEL_LAYER_TYPES[maproot['type']];
  if (!type) {
    return null;
  }
  var source = maproot['source'] || {};
  var model = new cm.LayerModel();
  // If the ID is empty, it will be set by cm.MapModel.registerLayer_.
  model.set('id', maproot['id'] || '');
  model.set('type', type);
  model.set('title', maproot['title'] || '');
  model.set('description', new cm.Html(maproot['description'] || ''));
  model.set('legend', new cm.Html(maproot['legend'] || ''));
  model.set('viewport', cm.LatLonBox.fromMapRoot(
      (maproot['viewport'] || {})['lat_lon_alt_box']));
  model.set('full_extent', cm.LatLonBox.fromMapRoot(
      (maproot['full_extent'] || {})['lat_lon_alt_box']));
  model.set('default_visibility', maproot['visibility'] === 'DEFAULT_ON' ||
                                 maproot['visibility'] === 'ALWAYS_ON');
  model.set('min_zoom', maproot['min_zoom'] || null);
  model.set('max_zoom', maproot['max_zoom'] || null);
  model.set('opacity', 'opacity' in maproot ?
      goog.math.clamp(maproot['opacity'] / 100, 0, 1) : 1);
  model.set('suppress_download_link',
            maproot['suppress_download_link'] || null);
  model.set('suppress_info_windows', maproot['suppress_info_windows'] || null);
  model.set('clip_to_viewport', maproot['clip_to_viewport'] || null);

  switch (type) {
    case cm.LayerModel.Type.KML:
      var kml = source['kml'] || {};
      model.set('url', kml['url']);
      break;
    case cm.LayerModel.Type.GEORSS:
      var georss = source['georss'] || {};
      model.set('url', georss['url']);
      break;
    case cm.LayerModel.Type.GOOGLE_MAPS_ENGINE_LITE_OR_PRO:
      var mapsEngine = source['google_maps_engine_lite_or_pro'] || {};
      var mapsEngineUrl = mapsEngine['maps_engine_url'];
      model.set('maps_engine_url', mapsEngineUrl);
      model.set('url', mapsEngine['url'] ||
          cm.LayerModel.getKmlUrlFromMapsEngineLiteOrProUrl_(mapsEngineUrl));
      break;
    case cm.LayerModel.Type.TILE:
      var tile = source['tile'] || source['google_map_tiles'] || {};
      model.set('url', tile['url']);
      model.set('url_is_tile_index', tile['url_is_tile_index']);
      model.set('tile_coordinate_type',
          cm.LayerModel.MODEL_TO_MAPROOT_TILE_COORDINATE_TYPES[
            tile['tile_coordinate_type']] ||
            cm.LayerModel.TileCoordinateType.GOOGLE);
      break;
    case cm.LayerModel.Type.GEOJSON:
    case cm.LayerModel.Type.CSV:
    case cm.LayerModel.Type.GOOGLE_SPREADSHEET:
      var params = source[type.toLowerCase()] || {};
      model.set('url', params['url'] || '');
      model.set('title_template', params['title_template'] || '');
      model.set('description_template',
                new cm.Html(params['description_template'] || ''));
      model.set('latitude_field', params['latitude_field'] || '');
      model.set('longitude_field', params['longitude_field'] || '');
      model.set('icon_url_template', params['icon_url_template'] || '');
      model.set('color_template', params['color_template'] || '');
      model.set('hotspot_template', params['hotspot_template'] || '');
      var conditions = params['conditions'] || ['', '', ''];
      model.set('condition0', conditions[0] || '');
      model.set('condition1', conditions[1] || '');
      model.set('condition2', conditions[2] || '');
      break;
    case cm.LayerModel.Type.FUSION:
      var fusion = source['google_fusion_tables'] || {};
      model.set('ft_select', fusion['select']);
      model.set('ft_from', fusion['from']);
      model.set('ft_where', fusion['where']);
      model.set('ft_heatmap', fusion['heatmap_enabled'] || null);
      break;
    case cm.LayerModel.Type.MAPS_ENGINE:
      var maps_engine = source['google_maps_engine'] ||
          source['google_map_data'] || {};
      model.set('maps_engine_map_id', maps_engine['map_id']);
      model.set('maps_engine_layer_id', maps_engine['layer_id']);
      model.set('maps_engine_layer_key', maps_engine['layer_key']);

      break;
    case cm.LayerModel.Type.WEATHER:
      var weather = source['google_weather'] || source['weather'] || {};
      model.set('label_color',
          cm.LayerModel.MAPROOT_TO_MODEL_LABEL_COLORS[
              weather['label_color']] ||
          cm.LayerModel.LabelColor.BLACK);
      model.set('temperature_unit',
          cm.LayerModel.MAPROOT_TO_MODEL_TEMPERATURE_UNITS[
              weather['temperature_unit']] ||
          cm.LayerModel.TemperatureUnit.CELSIUS);
      model.set('wind_speed_unit',
          cm.LayerModel.MAPROOT_TO_MODEL_WIND_SPEED_UNITS[
              weather['wind_speed_unit']] ||
          cm.LayerModel.WindSpeedUnit.KILOMETERS_PER_HOUR);
      break;
    case cm.LayerModel.Type.FOLDER:
      model.set('folder_type', cm.LayerModel.MAPROOT_TO_MODEL_FOLDER_TYPES[
          maproot['list_item_type']]);
      break;
    case cm.LayerModel.Type.WMS:
      var wms = source['wms'] || {};
      model.set('url', wms['url']);
      model.set('wms_layers', wms['layer_names']);
      break;
    case cm.LayerModel.Type.PLACES:
      var places = source['google_places'] || source['places'] || {};
      model.set('places_icon_url', places['icon_url']);
      model.set('places_keyword', places['keyword']);
      model.set('places_name', places['name']);
      model.set('places_types', places['types']);
      break;
  }

  // Construct sublayer models.
  var sublayers = new google.maps.MVCArray();
  model.set('sublayers', sublayers);
  cm.events.listen(sublayers, 'insert_at', function(i) {
    sublayers.getAt(i).set('parent', this);
  }, model);
  goog.array.forEach(maproot['sublayers'] || [], function(layerMapRoot) {
    var layer = cm.LayerModel.newFromMapRoot(layerMapRoot);
    layer && sublayers.push(layer);
  });

  cm.events.onChange(model, 'type', function() {
    if (model.get('type') !== cm.LayerModel.Type.FOLDER) {
      model.set('folder_type', null);
    }
  });
  cm.events.onChange(model, 'maps_engine_url', function() {
    if (model.get('type') ===
        cm.LayerModel.Type.GOOGLE_MAPS_ENGINE_LITE_OR_PRO) {
      var url = /** @type string */(model.get('maps_engine_url'));
      model.set('maps_engine_url', url);
      model.set('url', cm.LayerModel.getKmlUrlFromMapsEngineLiteOrProUrl_(url));
    }
  });

  return model;
};

/** @return {Object} This layer as a MapRoot JS layer object. */
cm.LayerModel.prototype.toMapRoot = function() {
  var type = this.get('type');
  var source = {};
  var sublayers = [];
  switch (type) {
    case cm.LayerModel.Type.KML:
      source['kml'] = {'url': this.get('url')};
      break;
    case cm.LayerModel.Type.GEORSS:
      source['georss'] = {'url': this.get('url')};
      break;
    case cm.LayerModel.Type.GOOGLE_MAPS_ENGINE_LITE_OR_PRO:
      source['google_maps_engine_lite_or_pro'] = {
        'maps_engine_url': this.get('maps_engine_url'),
        'url': this.get('url')
      };
      break;
    case cm.LayerModel.Type.TILE:
      source['tile'] = {
        'url': this.get('url'),
        'url_is_tile_index': this.get('url_is_tile_index'),
        'tile_coordinate_type':
          cm.LayerModel.MODEL_TO_MAPROOT_TILE_COORDINATE_TYPES[
            this.get('tile_coordinate_type')]
      };
      break;
    case cm.LayerModel.Type.GEOJSON:
    case cm.LayerModel.Type.CSV:
    case cm.LayerModel.Type.GOOGLE_SPREADSHEET:
      var description = this.get('description_template') || cm.Html.EMPTY;
      var conditions = [];
      if (this.get('condition0')) conditions.push(this.get('condition0'));
      if (this.get('condition1')) conditions.push(this.get('condition1'));
      if (this.get('condition2')) conditions.push(this.get('condition2'));
      source[type.toLowerCase()] = {
        'url': this.get('url'),
        'title_template': this.get('title_template'),
        'description_template': description.getUnsanitizedHtml(),
        'latitude_field': this.get('latitude_field'),
        'longitude_field': this.get('longitude_field'),
        'icon_url_template': this.get('icon_url_template'),
        'color_template': this.get('color_template'),
        'hotspot_template': this.get('hotspot_template'),
        'conditions': conditions
      };
      break;
    case cm.LayerModel.Type.FUSION:
      source['google_fusion_tables'] = {
        'select': this.get('ft_select'),
        'from': this.get('ft_from'),
        'where': this.get('ft_where'),
        'heatmap_enabled': this.get('ft_heatmap')
      };
      break;
    case cm.LayerModel.Type.MAPS_ENGINE:
      source['google_maps_engine'] = {
        'layer_id': this.get('maps_engine_layer_id'),
        'layer_key': this.get('maps_engine_layer_key'),
        'map_id': this.get('maps_engine_map_id')
      };
      break;
    case cm.LayerModel.Type.WEATHER:
      source['google_weather'] = {
        'label_color': cm.LayerModel.MODEL_TO_MAPROOT_LABEL_COLORS[
            this.get('label_color')] || 'BLACK',
        'temperature_unit': cm.LayerModel.MODEL_TO_MAPROOT_TEMPERATURE_UNITS[
            this.get('temperature_unit')] || 'CELSIUS',
        'wind_speed_unit': cm.LayerModel.MODEL_TO_MAPROOT_WIND_SPEED_UNITS[
            this.get('wind_speed_unit')] || 'KILOMETERS_PER_HOUR'
      };
      break;
    case cm.LayerModel.Type.FOLDER:
      this.get('sublayers').forEach(
          function(sublayer) { sublayers.push(sublayer.toMapRoot()); });
      break;
    case cm.LayerModel.Type.WMS:
      // The layer model represents WMS layers as objects, but the
      // maproot only stores the stirngs.
      var layers = /** @type Array.<string> */(this.get('wms_layers')) || [];
      source['wms'] = {
        'url': this.get('url'),
        'layer_names': layers
      };
      break;
    case cm.LayerModel.Type.PLACES:
      source['google_places'] = {
        'icon_url': this.get('places_icon_url'),
        'keyword': this.get('places_keyword'),
        'name': this.get('places_name'),
        'types': this.get('places_types')
      };
      break;
  }

  // Null fields will be removed from the maproot object by cm.util.removeNulls.
  var viewport = /** @type cm.LatLonBox */(this.get('viewport'));
  var extent = /** @type cm.LatLonBox */(this.get('full_extent'));
  var opacity = Math.round(/** @type number */(this.get('opacity')) * 100);
  var maproot = {
    'id': this.get('id'),
    'title': this.get('title'),
    'description': this.get('description').getUnsanitizedHtml(),
    'legend': this.get('legend').getUnsanitizedHtml(),
    'visibility': this.get('default_visibility') ? 'DEFAULT_ON' : 'DEFAULT_OFF',
    'viewport': viewport && {'lat_lon_alt_box': viewport.round(4).toMapRoot()},
    'full_extent': extent && {'lat_lon_alt_box': extent.round(4).toMapRoot()},
    'type': goog.object.transpose(
        cm.LayerModel.MAPROOT_TO_MODEL_LAYER_TYPES)[type],
    'min_zoom': this.get('min_zoom'),
    'max_zoom': this.get('max_zoom'),
    'opacity': opacity < 100 ? opacity : null,
    'suppress_download_link': this.get('suppress_download_link'),
    'suppress_info_windows': this.get('suppress_info_windows'),
    'clip_to_viewport': this.get('clip_to_viewport'),
    'list_item_type': goog.object.transpose(cm.LayerModel.
        MAPROOT_TO_MODEL_FOLDER_TYPES)[this.get('folder_type')]
  };
  if (type === cm.LayerModel.Type.FOLDER) {
    maproot['sublayers'] = sublayers;
  } else {
    maproot['source'] = source;
  }
  return /** @type Object */(cm.util.removeNulls(maproot));
};

/**
 * Transforms a Maps Engine Lite/Pro (My Maps) URL into a URL where we can
 * fetch KML.
 * @param {string} url the MEL/MEP URL to transform.
 * @return {string} A URL to fetch KML for the MEL/MEP layer, or empty string
 *     if the given URL was empty or null.
 * @private
 */
cm.LayerModel.getKmlUrlFromMapsEngineLiteOrProUrl_ = function(url) {
  // Supports mapsengine.google.com/map/viewer or google.com/maps/d/viewer
  var regex = new RegExp('(/map/|/maps/\\w+/)(.*?\\?)');
  return url ? url.replace(regex, '$1kml?') : '';
};

/** @override */
cm.LayerModel.prototype.changed = function(key) {
  if (key === 'folder_type') {
    cm.events.emit(this, cm.events.MODEL_CHANGED, {model: this});
  } else {
    cm.events.emit(this, cm.events.MODEL_CHANGED);
  }
};

// Export this method so it can be called by the MVCObject machinery.
goog.exportProperty(cm.LayerModel.prototype, 'changed',
                    cm.LayerModel.prototype.changed);

/**
 * Returns a string that represents the address of a layer. The format of the
 * string depends on the type of the layer.
 * NOTE: This method should be in sync with maproot.py.
 * TODO(cimamoglu): Implement this for other layer types.
 * @return {string} The address string if it's found, empty string otherwise.
 */
cm.LayerModel.prototype.getSourceAddress = function() {
  var type = this.get('type');
  switch (type) {
    case cm.LayerModel.Type.KML:
    case cm.LayerModel.Type.GEOJSON:
    case cm.LayerModel.Type.GEORSS:
    case cm.LayerModel.Type.TILE:
    case cm.LayerModel.Type.CSV:
    case cm.LayerModel.Type.WMS:
    case cm.LayerModel.Type.GOOGLE_MAPS_ENGINE_LITE_OR_PRO:
      var url = /** @type string */(this.get('url') || '');
      if (type === cm.LayerModel.Type.WMS) {
        url = new goog.Uri(url, true)
            .removeParameter('service')
            .removeParameter('version')
            .removeParameter('request')
            .toString();
      }
      return goog.object.transpose(
          cm.LayerModel.MAPROOT_TO_MODEL_LAYER_TYPES)[type] +
              ':' + url;
    default:
      return '';
  }
};

/**
 * Returns a set of all IDs of this layer's sublayer.
 * @return {Array.<string>} The array of sublayer IDs.
 */
cm.LayerModel.prototype.getSublayerIds = function() {
  return goog.array.map(this.get('sublayers').getArray(), function(sublayer) {
    return sublayer.get('id'); });
};

/**
 * Returns the layer model for the given sublayer's ID.
 * @param {string} layerId The sublayer's ID.
 * @return {?cm.LayerModel} The sublayer model if it exists.
 */
cm.LayerModel.prototype.getSublayer = function(layerId) {
  var sublayer = null;
  this.get('sublayers').forEach(function(layer) {
    if (layerId === layer.get('id')) {
      sublayer = layer;
    }
  });
  return sublayer;
};

/**
 * Convenience function for testing whether a layer is a single-select folder.
 * @return {boolean} True if the layer is a single-select folder.
 */
cm.LayerModel.prototype.isSingleSelect = function() {
  return this.get('folder_type') === cm.LayerModel.FolderType.SINGLE_SELECT;
};

/**
 * Convenience for figuring out if a given zoom level is inside the min/max zoom
 * levels for the layer.
 * @param {?number} zoomLevel The current zoom level; null or undefined is
 *   considered "unknown zoom level", and this function will return true.
 * @return {boolean} True if the zoom level is within the layer's acceptable
     zoom range; false otherwise.
 */
cm.LayerModel.prototype.insideZoomBounds = function(zoomLevel) {
  if (!goog.isNumber(zoomLevel)) return true;

  var minZoom = this.get('min_zoom');
  if (goog.isNumber(minZoom) && zoomLevel < minZoom) return false;

  var maxZoom = this.get('max_zoom');
  if (goog.isNumber(maxZoom) && zoomLevel > maxZoom) return false;

  return true;
};


text:
echo '(4a) slip into sql and create a report of the duplicate files'
sqlite3 $HOME/dup_pics/data/hashdb.sqlite3 <<-EOF
	.separator "\t"
	.header on

	.output $HOME/dup_pics/dup_files_report.txt
	/* limit dup fname to 1 per "collision" */
	/*
	SELECT f.hash,
	       f.fname
	  FROM ftable f
	 WHERE f."ROWID" IN (
	 	SELECT min(ft."ROWID")
		  FROM ftable as ft
		 WHERE ft.hash = f.hash
		 GROUP by ft.hash
		HAVING count(ft.hash) > 1
		ORDER BY ft.fname
		)
	 ORDER BY f.hash, f.fname;

	select x.tally,
	       f.hash,
	       f.fname
	  from ftable f,
	       (select count(hash) as tally, hash
		  from ftable
		 group by hash
		having tally > 1) as x
	 where f.hash = x.hash
	   and f.fname like '%Master%'
	 order by x.tally desc,
	          f.hash,
		  f.fname;
	  */

	/* original report */
	select x.tally,
	       f.hash,
	       f.fname
	  from ftable f,
	       (select count(hash) as tally, hash
		  from ftable
		 group by hash
		having tally > 1) as x
	 where f.hash = x.hash
	 order by x.tally desc,
	          f.hash,
		  f.fname;

	.exit

EOF

echo "(5) see report of dup files in '$HOME/dup_pics/dup_files_report.txt'"

redpajama_set_name: RedPajamaGithub


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

	<wicket:panel>
		<form wicket:id="form" style="margin-left: 10px;">

				<button wicket:id="editOrder" type="button" class="btn btn-primary">

					Edit
				</button>
				<button wicket:id="cancelOrder" type="reset" class="btn">

					Cancel
				</button>
				<button wicket:id="saveOrder" type="submit" class="btn btn-success">

					Save
				</button>

						<input wicket:id="positionField" class="position" />

		</form>

	</wicket:panel>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package shopcar.gui;

import java.util.Optional;
import org.controlsfx.control.action.Action;
import org.controlsfx.dialog.Dialogs;

/**
 *
 * @author info1
 */
public class DialogsHelper
{
    public static void createInfoDialog(Object owner, String title, String masthead
            , String message)
    {
        Dialogs.create()
                    .owner(owner)
                    .title(title)
                    .masthead(masthead)
                    .message(message)
                    .showInformation();
    }

    public static void createErrorDialog(Object owner, String title, String masthead
            , String message)
    {
        Dialogs.create()
                    .owner(owner)
                    .title(title)
                    .masthead(masthead)
                    .message(message)

                    .showError();
    }

    public static void createExceptionDialog(Object owner, String title, String masthead
            , String message, Exception ex)
    {
        Dialogs.create()
                    .owner(owner)
                    .title(title)
                    .masthead(masthead)
                    .message(message)
                    .showException(ex);
    }

    public static void createInputDialog(Object owner, String title,
            String masthead, String message)
    {
        Optional<String> response = Dialogs.create()
                    .owner(owner)
                    .title(title)
                    .masthead(masthead)
                    .message(message)
                    //.lightweight()
                    .showTextInput("Placa: ");
    }

    public static boolean createQuestionDialog(Object owner, String title,
            String masthead, String message, Action returnTrueAction ,Action... action)
    {
        Action response = Dialogs.create()
                    .owner(owner)
                    .title(title)
                    .masthead(masthead)
                    .message(message)
                    .actions(action)
                    .showConfirm();

        return response == returnTrueAction;
    }

//    public static User createLoginDialog(Node node)
//    {
//        Dialog dlg = new Dialog(node, "Login");
//        final User user = new User();
//        final TextField txtLogin = new TextField();
//        final PasswordField txtPasswd = new PasswordField();
//        final GridPane pane = new GridPane();
//
//        final Action actionLogin = new org.controlsfx.control.action.Action
//        (
//            s ->
//            {
//                Dialog d = (Dialog) s.getSource();
//                d.hide();
//            }
//        );
//
//        pane.setVgap(10);
//        pane.setHgap(15);
//
//        pane.add(new Label("Username: "), 2, 2, 1, 1);
//        pane.add(txtLogin, 3, 2, 2, 1);
//        pane.add(new Label("Password: "), 2, 3, 1, 1);
//        pane.add(txtPasswd, 3, 3, 2, 1);
//
//        ButtonBar.setType(actionLogin, ButtonBar.ButtonType.OK_DONE);
//        actionLogin.disabledProperty().set(true);
//        dlg.setMasthead("Entre com o seu login e senha: ");
//        dlg.setContent(pane);
//        dlg.getActions().addAll(actionLogin, Dialog.ACTION_CANCEL);
//        dlg.setClosable(false);
//
//        Platform.runLater(() -> txtLogin.requestFocus());
//
//        dlg.show();
//
//        return user;
//    }
}


text:
Program for cycling workout - short intencive workout the right thing for people with a confining job.
1 You can create/read/update/delete new cycles, new exercises, set execution time for exercises.
2 You can add new translation.
3 While doing workout you will see total time, remaining time of current exercise, name of current exercise and, of course, selected cycle name.


text:
<TITLE>OpenBSD - Secure by Default</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

<< Back
INDEX
Next >>

Page 9

OpenBSD - Secure by Default

        Provide safe configuration out of the box; see Theo's talk (Thursday 1:30)!

    Total Code Audit: Multi-year, multi-national, ongoing

    Integrated cryptography (kernel and userland)

    Thorough documentation: man, faq

        faq is at http://www.openbsd.org/faq/, and on the CD

        Please learn to RTFM :-)


text:
class Radi < Cask
  version :latest
  sha256 :no_check

  url 'http://radiapp.com/Radi.zip'
  homepage 'http://radiapp.com/'
  license :closed

  app 'Radi.app'
end


text:
package com.appleframework.tools.io;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import com.appleframework.tools.util.CharsetUtil;
import com.appleframework.tools.util.StrUtil;

/**
 * {@link ByteBuffer} 工具类

 * 此工具来自于 t-io 项目以及其它项目的相关部分收集

 * ByteBuffer的相关介绍见:https://www.cnblogs.com/ruber/p/6857159.html
 *
 * @author tanyaowu, cruise.xu
 * @since 4.0.0
 *
 */
public class BufferUtil {

	/**
	 * 拷贝到一个新的ByteBuffer
	 *
	 * @param src 源ByteBuffer
	 * @param start 起始位置(包括)
	 * @param end 结束位置(不包括)
	 * @return 新的ByteBuffer
	 */
	public static ByteBuffer copy(ByteBuffer src, int start, int end) {
		return copy(src, ByteBuffer.allocate(end - start));
	}

	/**
	 * 拷贝ByteBuffer
	 *
	 * @param src 源ByteBuffer
	 * @param dest 目标ByteBuffer
	 * @return 目标ByteBuffer
	 */
	public static ByteBuffer copy(ByteBuffer src, ByteBuffer dest) {
		return copy(src, dest, Math.min(src.limit(), dest.remaining()));
	}

	/**
	 * 拷贝ByteBuffer
	 *
	 * @param src 源ByteBuffer
	 * @param dest 目标ByteBuffer
	 * @param length 长度
	 * @return 目标ByteBuffer
	 */
	public static ByteBuffer copy(ByteBuffer src, ByteBuffer dest, int length) {
		return copy(src, src.position(), dest, dest.position(), length);
	}

	/**
	 * 拷贝ByteBuffer
	 *
	 * @param src 源ByteBuffer
	 * @param srcStart 源开始的位置
	 * @param dest 目标ByteBuffer
	 * @param destStart 目标开始的位置
	 * @param length 长度
	 * @return 目标ByteBuffer
	 */
	public static ByteBuffer copy(ByteBuffer src, int srcStart, ByteBuffer dest, int destStart, int length) {
		System.arraycopy(src.array(), srcStart, dest.array(), destStart, length);
		return dest;
	}

	/**
	 * 读取剩余部分并转为UTF-8编码字符串
	 *
	 * @param buffer ByteBuffer
	 * @return 字符串
	 * @since 4.5.0
	 */
	public static String readUtf8Str(ByteBuffer buffer) {
		return readStr(buffer, CharsetUtil.CHARSET_UTF_8);
	}

	/**
	 * 读取剩余部分并转为字符串
	 *
	 * @param buffer ByteBuffer
	 * @param charset 编码
	 * @return 字符串
	 * @since 4.5.0
	 */
	public static String readStr(ByteBuffer buffer, Charset charset) {
		return StrUtil.str(readBytes(buffer), charset);
	}

	/**
	 * 读取剩余部分bytes

	 *
	 * @param buffer ByteBuffer
	 * @return bytes
	 */
	public static byte[] readBytes(ByteBuffer buffer) {
		final int remaining = buffer.remaining();
		byte[] ab = new byte[remaining];
		buffer.get(ab);
		return ab;
	}

	/**
	 * 读取指定长度的bytes

	 * 如果长度不足,则读取剩余部分,此时buffer必须为读模式
	 *
	 * @param buffer ByteBuffer
	 * @param maxLength 最大长度
	 * @return bytes
	 */
	public static byte[] readBytes(ByteBuffer buffer, int maxLength) {
		final int remaining = buffer.remaining();
		if (maxLength > remaining) {
			maxLength = remaining;
		}
		byte[] ab = new byte[maxLength];
		buffer.get(ab);
		return ab;
	}

	/**
	 * 读取指定区间的数据
	 *
	 * @param buffer {@link ByteBuffer}
	 * @param start 开始位置
	 * @param end 结束位置
	 * @return bytes
	 */
	public static byte[] readBytes(ByteBuffer buffer, int start, int end) {
		byte[] bs = new byte[end - start];
		System.arraycopy(buffer.array(), start, bs, 0, bs.length);
		return bs;
	}

	/**
	 * 一行的末尾位置,查找位置时位移ByteBuffer到结束位置
	 *
	 * @param buffer {@link ByteBuffer}
	 * @return 末尾位置,未找到或达到最大长度返回-1
	 */
	public static int lineEnd(ByteBuffer buffer) {
		return lineEnd(buffer, buffer.remaining());
	}

	/**
	 * 一行的末尾位置,查找位置时位移ByteBuffer到结束位置

	 * 支持的换行符如下:
	 *
	 *

	 * 1. \r\n
	 * 2. \n
	 *

	 *
	 * @param buffer {@link ByteBuffer}
	 * @param maxLength 读取最大长度
	 * @return 末尾位置,未找到或达到最大长度返回-1
	 */
	public static int lineEnd(ByteBuffer buffer, int maxLength) {
		int primitivePosition = buffer.position();
		boolean canEnd = false;
		int charIndex = primitivePosition;
		byte b;
		while (buffer.hasRemaining()) {
			b = buffer.get();
			charIndex++;
			if (b == StrUtil.C_CR) {
				canEnd = true;
			} else if (b == StrUtil.C_LF) {
				return canEnd ? charIndex - 2 : charIndex - 1;
			} else {
				// 只有\r无法确认换行
				canEnd = false;
			}

			if (charIndex - primitivePosition > maxLength) {
				// 查找到尽头,未找到,还原位置
				buffer.position(primitivePosition);
				throw new IndexOutOfBoundsException(StrUtil.format("Position is out of maxLength: {}", maxLength));
			}
		}

		// 查找到buffer尽头,未找到,还原位置
		buffer.position(primitivePosition);
		// 读到结束位置
		return -1;
	}

	/**
	 * 读取一行,如果buffer中最后一部分并非完整一行,则返回null

	 * 支持的换行符如下:
	 *
	 *

	 * 1. \r\n
	 * 2. \n
	 *

	 *
	 * @param buffer ByteBuffer
	 * @param charset 编码
	 * @return 一行
	 */
	public static String readLine(ByteBuffer buffer, Charset charset) {
		final int startPosition = buffer.position();
		final int endPosition = lineEnd(buffer);

		if (endPosition > startPosition) {
			byte[] bs = readBytes(buffer, startPosition, endPosition);
			return StrUtil.str(bs, charset);
		} else if (endPosition == startPosition) {
			return StrUtil.EMPTY;
		}

		return null;
	}

	/**
	 * 创建新Buffer
	 *
	 * @param data 数据
	 * @return {@link ByteBuffer}
	 * @since 4.5.0
	 */
	public static ByteBuffer create(byte[] data) {
		return ByteBuffer.wrap(data);
	}

	/**
	 * 从字符串创建新Buffer
	 *
	 * @param data 数据
	 * @param charset 编码
	 * @return {@link ByteBuffer}
	 * @since 4.5.0
	 */
	public static ByteBuffer create(CharSequence data, Charset charset) {
		return create(StrUtil.bytes(data, charset));
	}

	/**
	 * 从字符串创建新Buffer,使用UTF-8编码
	 *
	 * @param data 数据
	 * @return {@link ByteBuffer}
	 * @since 4.5.0
	 */
	public static ByteBuffer createUtf8(CharSequence data) {
		return create(StrUtil.utf8Bytes(data));
	}
}


text:
// <copyright file="InvalidWhenAsyncOperator.cs" company="Kyubisation">
// Copyright (c) Kyubisation. All rights reserved.
// </copyright>

// ReSharper disable once CheckNamespace
namespace FluentRestBuilder
{
    using System;
    using System.Threading.Tasks;
    using Operators;
    using Operators.Exceptions;

    public static class InvalidWhenAsyncOperator
    {
        /// <summary>
        /// If the check returns <c>true</c>, <see cref="ValidationException"/>
        /// is emitted as an error with the given status code.
        /// Otherwise the given value is emitted.
        /// </summary>
        /// <typeparam name="TSource">The type of the value.</typeparam>
        /// <param name="observable">The parent observable.</param>
        /// <param name="invalidCheck">The invalidCheck function.</param>
        /// <param name="statusCode">The status code of the error.</param>
        /// <param name="errorFactory">The error factory method.</param>
        /// <returns>An instance of <see cref="IProviderObservable{TSource}"/>.</returns>
        public static IProviderObservable<TSource> InvalidWhenAsync<TSource>(
            this IProviderObservable<TSource> observable,
            Func<TSource, Task<bool>> invalidCheck,
            int statusCode,
            Func<TSource, object> errorFactory = null) =>
            new InvalidWhenAsyncObservable<TSource>(invalidCheck, statusCode, errorFactory, observable);

        private sealed class InvalidWhenAsyncObservable<TSource> : Operator<TSource, TSource>
        {
            private readonly Func<TSource, Task<bool>> invalidCheck;
            private readonly int statusCode;
            private readonly Func<TSource, object> errorFactory;

            public InvalidWhenAsyncObservable(
                Func<TSource, Task<bool>> invalidCheck,
                int statusCode,
                Func<TSource, object> errorFactory,
                IProviderObservable<TSource> observable)
                : base(observable)
            {
                Check.IsNull(invalidCheck, nameof(invalidCheck));
                this.invalidCheck = invalidCheck;
                this.statusCode = statusCode;
                this.errorFactory = errorFactory;
            }

            protected override IObserver<TSource> Create(
                IObserver<TSource> observer, IDisposable disposable) =>
                new InvalidWhenAsyncObserver(
                    this.invalidCheck, this.statusCode, this.errorFactory, observer, disposable);

            private sealed class InvalidWhenAsyncObserver : SafeAsyncObserver
            {
                private readonly Func<TSource, Task<bool>> invalidCheck;
                private readonly int statusCode;
                private readonly Func<TSource, object> errorFactory;

                public InvalidWhenAsyncObserver(
                    Func<TSource, Task<bool>> invalidCheck,
                    int statusCode,
                    Func<TSource, object> errorFactory,
                    IObserver<TSource> child,
                    IDisposable disposable)
                    : base(child, disposable)
                {
                    this.invalidCheck = invalidCheck;
                    this.statusCode = statusCode;
                    this.errorFactory = errorFactory;
                }

                protected override async Task<TSource> SafeOnNext(TSource value)
                {
                    if (!await this.invalidCheck(value))
                    {
                        return value;
                    }

                    var error = this.errorFactory?.Invoke(value);
                    this.EmitError(new ValidationException(this.statusCode, error));
                    return default(TSource);
                }
            }
        }
    }
}


text:
@implementation NSDictionary (AvoidCrash)

+ (void)avoidCrashExchangeMethod {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        [AvoidCrash exchangeClassMethod:self method1Sel:@selector(dictionaryWithObjects:forKeys:count:) method2Sel:@selector(avoidCrashDictionaryWithObjects:forKeys:count:)];
    });
}

+ (instancetype)avoidCrashDictionaryWithObjects:(const id  _Nonnull __unsafe_unretained *)objects forKeys:(const id<NSCopying>  _Nonnull __unsafe_unretained *)keys count:(NSUInteger)cnt {

    id instance = nil;

    @try {
        instance = [self avoidCrashDictionaryWithObjects:objects forKeys:keys count:cnt];
    }
    @catch (NSException *exception) {

        NSString *defaultToDo = @"This framework default is to remove nil key-values and instance a dictionary.";
        [AvoidCrash noteErrorWithException:exception defaultToDo:defaultToDo];

        //处理错误的数据,然后重新初始化一个字典
        NSUInteger index = 0;
        id  _Nonnull __unsafe_unretained newObjects[cnt];
        id  _Nonnull __unsafe_unretained newkeys[cnt];

        for (int i = 0; i < cnt; i++) {
            if (objects[i] && keys[i]) {
                newObjects[index] = objects[i];
                newkeys[index] = keys[i];
                index++;
            }
        }
        instance = [self avoidCrashDictionaryWithObjects:newObjects forKeys:newkeys count:index];
    }
    @finally {
        return instance;
    }
}

@end


text:
package mil.nga.giat.geowave.analytics.tools;

import java.io.IOException;
import java.io.Serializable;

import mil.nga.giat.geowave.index.ByteArrayId;
import mil.nga.giat.geowave.store.CloseableIterator;
import mil.nga.giat.geowave.store.adapter.AdapterStore;
import mil.nga.giat.geowave.store.adapter.DataAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * Support for adapter stores that are Serializable. Rather than for an adapter
 * store to serialize its state, wrap an adapter store. If the adapter store is
 * not serializable, then log a warning message upon serialization.
 *
 *
 */

public class SerializableAdapterStore implements
		AdapterStore,
		Serializable
{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	final static Logger LOGGER = LoggerFactory.getLogger(SerializableAdapterStore.class);

	transient AdapterStore adapterStore;

	public SerializableAdapterStore() {

	}

	public SerializableAdapterStore(
			AdapterStore adapterStore ) {
		super();
		this.adapterStore = adapterStore;
	}

	private AdapterStore getAdapterStore() {
		if (adapterStore == null) {
			throw new IllegalStateException(
					"AdapterStore has not been initialized");
		}
		return adapterStore;
	}

	@Override
	public void addAdapter(
			final DataAdapter<?> adapter ) {
		getAdapterStore().addAdapter(
				adapter);
	}

	@Override
	public DataAdapter<?> getAdapter(
			final ByteArrayId adapterId ) {
		return getAdapterStore().getAdapter(
				adapterId);
	}

	@Override
	public boolean adapterExists(
			final ByteArrayId adapterId ) {
		return getAdapterStore().adapterExists(
				adapterId);
	}

	@Override
	public CloseableIterator<DataAdapter<?>> getAdapters() {
		return getAdapterStore().getAdapters();
	}

	private void writeObject(
			final java.io.ObjectOutputStream out )
			throws IOException {
		if (adapterStore instanceof Serializable) {
			out.writeBoolean(true);
			out.writeObject(adapterStore);
		}
		else {
			out.writeBoolean(false);
		}
	}

	private void readObject(
			final java.io.ObjectInputStream in )
			throws IOException,
			ClassNotFoundException {
		if (in.readBoolean()) {
			adapterStore = (AdapterStore) in.readObject();
		}
		else {
			LOGGER.warn("Unable to initialized AdapterStore; the store is not serializable");
		}
	}
}


text:
<?php

namespace Angie\AdminBundle\Controller\Category;

use Admingenerated\AngieAdminBundle\BaseCategoryController\ShowController as BaseShowController;

/**
 * ShowController
 */
class ShowController extends BaseShowController
{
}


text:
package pump.uno

import spray.http.HttpCookie

package object model {

  case class Forum(id: Long, name: String, url: String)

  case class Topic(id: Long, name: String, url: String)

  case class ForumPage(forums: Seq[Forum], topics: Seq[Topic], totalPages: Long)

  case class TopicPage()

  case class Fetch(url: String, auth: HttpCookie)

}


text:
#ifndef _EFI_PCI_H_
#define _EFI_PCI_H_

//#include "pci22.h"
//#include "pci23.h"
//#include "pci30.h"

#pragma pack(push, 1)

typedef struct {
  UINT8 Register;
  UINT8 Function;
  UINT8 Device;
  UINT8 Bus;
  UINT8 Reserved[4];
} DEFIO_PCI_ADDR;

#define EFI_ROOT_BRIDGE_LIST                            'eprb'
#define EFI_PCI_EXPANSION_ROM_HEADER_EFISIGNATURE       0x0EF1

typedef struct {
  UINT16  Signature;    // 0xaa55
  UINT16  InitializationSize;
  UINT32  EfiSignature; // 0x0EF1
  UINT16  EfiSubsystem;
  UINT16  EfiMachineType;
  UINT16  CompressionType;
  UINT8   Reserved[8];
  UINT16  EfiImageHeaderOffset;
  UINT16  PcirOffset;
} EFI_PCI_EXPANSION_ROM_HEADER;

typedef union {
  UINT8                           *Raw;
  PCI_EXPANSION_ROM_HEADER        *Generic;
  EFI_PCI_EXPANSION_ROM_HEADER    *Efi;
  EFI_LEGACY_EXPANSION_ROM_HEADER *PcAt;
} EFI_PCI_ROM_HEADER;

#pragma pack(pop)

#endif


text:
jzy3d-main
==========

This is a main Git repository for Jzy3d providing multiple maven modules.

Travis build status : [![Build Status](https://travis-ci.org/jzy3d/jzy3d-api.svg?branch=master)](https://travis-ci.org/jzy3d/jzy3d-api)

API and modules
-----------------------------------
- jzy3d-tutorials : few examples for building main chart families (surfaces, scatters, etc).

Application will require jzy3d-api plus classes to address a specific windowing environement (AWT, SWT, Swing). The API itself has no dependency to AWT, making it buildable for Android environement.

Code specific to a target windowing environement is made available through modules (or sometime source folder separation):
- jzy3d-awt : provides AWT canvases (source folder separation but part of jzy3d-api build)
- jzy3d-swing : provides Swing canvases  (source folder separation but jzy3d-api build)
- jzy3d-swt : provides a wrapper on AWT canvas to embed a chart in a SWT application.
- jzy3d-jdt-core : a clone of JDT, for Java Delaunay Triangulation

The API has optional extensions bundled by a parent and several children module stored in separated Git repositories:
- jzy3d-extensions : gather 5 optional modules that may be checkout separately as well (Depth peeling, Graphs, G2D, )

Jzy3d Maven Repository
-----------------------------------
- Release versions WILL stand on maven central
- Snapshot versions stand on Jzy3d maven repository:

<repositories>
  <repository>
	 <id>jzy3d-snapshots</id>
	 <name>Jzy3d Snapshots</name>
	 <url>http://maven.jzy3d.org/snapshots </url>
  </repository>
  <repository>
	 <id>jzy3d-releases</id>
	 <name>Jzy3d Snapshots</name>
	 <url>http://maven.jzy3d.org/releases </url>
  </repository>
</repositories>

Building the projects with Maven
-----------------------------------
Build all module from master repository by calling
- mvn install

To be friendly with Eclipse-but-non-Maven users, we add .project and .classpath files to the repositories. If you want to regenerate this files with maven and have the projects linked all together, simply run
- mvn eclipse:eclipse -Declipse.workspace=~[your current eclipse workspace folder]
- then edit jzy3d-api project properties to export all dependencies to other projects (Properties > Java Build Path > Order and Export > Select All. Then remove JRE System libraries).

Building the projects without Maven
-----------------------------------
We kept the repository easy to use for non-maven users.
- Eclipse project files (.project & .classpath) with inter-project relations are commited to the repositories
- Some modules have a lib/ directory containing required Jars. If you want to use these jars, simply edit the libraries dependencies of the Eclipse project to use them instead of the maven dependencies.

License
--------------
New BSD

More information
--------------
http://www.jzy3d.org


text:
import React from 'react';

export default class TodosListHeader extends React.Component {  //this is what were calling our component
  render () {
    return (   //keeps code organzed, putting divs in there

              Task	{/* where the actual todo will live*/}
              Action	{/*options to do with the task such as edit delete */}

    );
  }
}


text:
<?php
add_action( 'widgets_init', 'jellywp_recent_comments_widgets' );

function jellywp_recent_comments_widgets() {
	register_widget( 'jellywp_recent_comments_widget' );
}

class jellywp_recent_comments_widget extends WP_Widget {

/*-----------------------------------------------------------------------------------*/
/*	Widget Setup
/*-----------------------------------------------------------------------------------*/

	function jellywp_recent_comments_widget() {
		$widget_ops = array( 'classname' => 'post_list_widget comment_widget', 'description' => esc_attr__('Displays recent comments.', 'jelly_text_main') );
		$this->WP_Widget( 'jellywp_recent_comments_widget', esc_attr__('jellywp: Recent Comments', 'jelly_text_main'), $widget_ops);
	}

/*-----------------------------------------------------------------------------------*/
/*	Display Widget
/*-----------------------------------------------------------------------------------*/

	function widget( $args, $instance ) {

		extract( $args );
	    $title = apply_filters('widget_title', $instance['title'] );
		echo $before_widget;
		if ( $title )
		echo $before_title . $title . $after_title;

       ?>
       <?php
	   $entries_display = $instance['entries_display']; ?>

            <?php
                $args = array(
                       'status' => 'approve',
                        'number' => $entries_display
					);

				$postcount=0;
                $comments = get_comments($args);

                foreach($comments as $comment) :
						$postcount++;
                        $commentcontent = strip_tags($comment->comment_content);
                        if (strlen($commentcontent)> 100) {
                            $commentcontent = mb_substr($commentcontent, 0, 90) . "...";
                        }
                        $commentauthor = $comment->comment_author;
                        if (strlen($commentauthor)> 30) {
                            $commentauthor = mb_substr($commentauthor, 0, 29) . "...";
                        }
                        $commentid = $comment->comment_ID;
                        $commenturl = get_comment_link($commentid); ?>
                      <li class="clearfix <?php if(!of_get_option('disable_css_animation')==1){echo esc_attr("appear_animation");}?>">
							<?php echo get_avatar( $comment, '75' ); ?>

<a class="post-title <?php if($postcount==1) { ?> first<?php } ?>" href="<?php echo esc_attr($commenturl); ?>"> <?php echo esc_attr($commentauthor); ?>

									 <?php echo esc_attr($commentcontent); ?>

            <?php endforeach; ?>

	   <?php

		echo $after_widget;
	}

	function form( $instance ) {
		$defaults = array('title' => 'Recent Comments', 'entries_display' => 5);
		$instance = wp_parse_args((array) $instance, $defaults);
	?>

<label for="<?php echo esc_attr($this->get_field_id( 'title' )); ?>"><?php esc_attr_e('Title:', 'jellywp'); ?>
        <input type="text" width="100%" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" value="<?php echo esc_attr($instance['title']); ?>" style="width:100%;" />

<label for="<?php echo esc_attr($this->get_field_id( 'entries_display' )); ?>"><?php esc_attr_e('How many entries to display?', 'jellywp'); ?>
		<input type="text" width="100%" id="<?php echo esc_attr($this->get_field_id('entries_display')); ?>" name="<?php echo esc_attr($this->get_field_name('entries_display')); ?>" value="<?php echo esc_attr($instance['entries_display']); ?>" style="width:100%;" />

	<?php
	}
}
?>


text:
namespace v8 {
namespace internal {

IsolateAllocationMode Isolate::isolate_allocation_mode() {
  return isolate_allocator_->mode();
}

void Isolate::set_context(Context context) {
  DCHECK(context.is_null() || context->IsContext());
  thread_local_top()->context_ = context;
}

Handle<NativeContext> Isolate::native_context() {
  return handle(context()->native_context(), this);
}

NativeContext Isolate::raw_native_context() {
  return context()->native_context();
}

Object Isolate::pending_exception() {
  DCHECK(has_pending_exception());
  DCHECK(!thread_local_top()->pending_exception_->IsException(this));
  return thread_local_top()->pending_exception_;
}

void Isolate::set_pending_exception(Object exception_obj) {
  DCHECK(!exception_obj->IsException(this));
  thread_local_top()->pending_exception_ = exception_obj;
}

void Isolate::clear_pending_exception() {
  DCHECK(!thread_local_top()->pending_exception_->IsException(this));
  thread_local_top()->pending_exception_ = ReadOnlyRoots(this).the_hole_value();
}

bool Isolate::has_pending_exception() {
  DCHECK(!thread_local_top()->pending_exception_->IsException(this));
  return !thread_local_top()->pending_exception_->IsTheHole(this);
}

void Isolate::clear_pending_message() {
  thread_local_top()->pending_message_obj_ =
      ReadOnlyRoots(this).the_hole_value();
}

Object Isolate::scheduled_exception() {
  DCHECK(has_scheduled_exception());
  DCHECK(!thread_local_top()->scheduled_exception_->IsException(this));
  return thread_local_top()->scheduled_exception_;
}

bool Isolate::has_scheduled_exception() {
  DCHECK(!thread_local_top()->scheduled_exception_->IsException(this));
  return thread_local_top()->scheduled_exception_ !=
         ReadOnlyRoots(this).the_hole_value();
}

void Isolate::clear_scheduled_exception() {
  DCHECK(!thread_local_top()->scheduled_exception_->IsException(this));
  thread_local_top()->scheduled_exception_ =
      ReadOnlyRoots(this).the_hole_value();
}

bool Isolate::is_catchable_by_javascript(Object exception) {
  return exception != ReadOnlyRoots(heap()).termination_exception();
}

void Isolate::FireBeforeCallEnteredCallback() {
  for (auto& callback : before_call_entered_callbacks_) {
    callback(reinterpret_cast<v8::Isolate*>(this));
  }
}

Handle<JSGlobalObject> Isolate::global_object() {
  return handle(context()->global_object(), this);
}

Handle<JSGlobalProxy> Isolate::global_proxy() {
  return handle(context()->global_proxy(), this);
}

Isolate::ExceptionScope::ExceptionScope(Isolate* isolate)
    : isolate_(isolate),
      pending_exception_(isolate_->pending_exception(), isolate_) {}

Isolate::ExceptionScope::~ExceptionScope() {
  isolate_->set_pending_exception(*pending_exception_);
}

#define NATIVE_CONTEXT_FIELD_ACCESSOR(index, type, name)     \
  Handle<type> Isolate::name() {                             \
    return Handle<type>(raw_native_context()->name(), this); \
  }                                                          \
  bool Isolate::is_##name(type value) {                      \
    return raw_native_context()->is_##name(value);           \
  }
NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_FIELD_ACCESSOR)
#undef NATIVE_CONTEXT_FIELD_ACCESSOR

bool Isolate::IsArrayConstructorIntact() {
  Cell array_constructor_cell =
      Cell::cast(root(RootIndex::kArrayConstructorProtector));
  return array_constructor_cell->value() == Smi::FromInt(kProtectorValid);
}

bool Isolate::IsArraySpeciesLookupChainIntact() {
  // Note: It would be nice to have debug checks to make sure that the
  // species protector is accurate, but this would be hard to do for most of
  // what the protector stands for:
  // - You'd need to traverse the heap to check that no Array instance has
  //   a constructor property
  // - To check that Array[Symbol.species] == Array, JS code has to execute,
  //   but JS cannot be invoked in callstack overflow situations
  // All that could be checked reliably is that
  // Array.prototype.constructor == Array. Given that limitation, no check is
  // done here. In place, there are mjsunit tests harmony/array-species* which
  // ensure that behavior is correct in various invalid protector cases.

  PropertyCell species_cell =
      PropertyCell::cast(root(RootIndex::kArraySpeciesProtector));
  return species_cell->value()->IsSmi() &&
         Smi::ToInt(species_cell->value()) == kProtectorValid;
}

bool Isolate::IsTypedArraySpeciesLookupChainIntact() {
  PropertyCell species_cell =
      PropertyCell::cast(root(RootIndex::kTypedArraySpeciesProtector));
  return species_cell->value()->IsSmi() &&
         Smi::ToInt(species_cell->value()) == kProtectorValid;
}

bool Isolate::IsRegExpSpeciesLookupChainIntact() {
  PropertyCell species_cell =
      PropertyCell::cast(root(RootIndex::kRegExpSpeciesProtector));
  return species_cell->value()->IsSmi() &&
         Smi::ToInt(species_cell->value()) == kProtectorValid;
}

bool Isolate::IsPromiseSpeciesLookupChainIntact() {
  PropertyCell species_cell =
      PropertyCell::cast(root(RootIndex::kPromiseSpeciesProtector));
  return species_cell->value()->IsSmi() &&
         Smi::ToInt(species_cell->value()) == kProtectorValid;
}

bool Isolate::IsStringLengthOverflowIntact() {
  Cell string_length_cell = Cell::cast(root(RootIndex::kStringLengthProtector));
  return string_length_cell->value() == Smi::FromInt(kProtectorValid);
}

bool Isolate::IsArrayBufferDetachingIntact() {
  PropertyCell buffer_detaching =
      PropertyCell::cast(root(RootIndex::kArrayBufferDetachingProtector));
  return buffer_detaching->value() == Smi::FromInt(kProtectorValid);
}

bool Isolate::IsArrayIteratorLookupChainIntact() {
  PropertyCell array_iterator_cell =
      PropertyCell::cast(root(RootIndex::kArrayIteratorProtector));
  return array_iterator_cell->value() == Smi::FromInt(kProtectorValid);
}

bool Isolate::IsMapIteratorLookupChainIntact() {
  PropertyCell map_iterator_cell =
      PropertyCell::cast(root(RootIndex::kMapIteratorProtector));
  return map_iterator_cell->value() == Smi::FromInt(kProtectorValid);
}

bool Isolate::IsSetIteratorLookupChainIntact() {
  PropertyCell set_iterator_cell =
      PropertyCell::cast(root(RootIndex::kSetIteratorProtector));
  return set_iterator_cell->value() == Smi::FromInt(kProtectorValid);
}

bool Isolate::IsStringIteratorLookupChainIntact() {
  PropertyCell string_iterator_cell =
      PropertyCell::cast(root(RootIndex::kStringIteratorProtector));
  return string_iterator_cell->value() == Smi::FromInt(kProtectorValid);
}

}  // namespace internal
}  // namespace v8

#endif  // V8_ISOLATE_INL_H_


text:
import graphene

from ..core.types import SortInputObjectType

class WebhookSortField(graphene.Enum):
    NAME = "name"
    SERVICE_ACCOUNT = "service_account__name"
    TARGET_URL = "target_url"

    @property
    def description(self):
        # pylint: disable=no-member
        if self in [
            WebhookSortField.NAME,
            WebhookSortField.SERVICE_ACCOUNT,
            WebhookSortField.TARGET_URL,
        ]:
            sort_name = self.name.lower().replace("_", " ")
            return f"Sort webhooks by {sort_name}."
        raise ValueError("Unsupported enum value: %s" % self.value)

class WebhookSortingInput(SortInputObjectType):
    class Meta:
        sort_enum = WebhookSortField
        type_name = "webhooks"


text:
package xwpeng.android.testrx;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

import xwpeng.android.testrx.present.TestRetrofit;
import xwpeng.android.testrx.present.TestRetrofitRx;
import xwpeng.android.testrx.present.TestRx;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView mImageView;
    private ImageView mImageView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        findViewById(R.id.testRx_button).setOnClickListener(this);
        findViewById(R.id.testRetrofit_button).setOnClickListener(this);
        findViewById(R.id.testRetrofitRx_button).setOnClickListener(this);
    }

    private void initView() {
        mImageView = (ImageView) findViewById(R.id.main_imageview);
        mImageView2 = (ImageView) findViewById(R.id.main_imageview2);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.testRx_button:
                TestRx.base(getApplicationContext(), mImageView);
                break;
            case R.id.testRetrofit_button:
//                TestRetrofit.base();
//                  TestRetrofit.query();
//                TestRetrofit.queryMap();
//                TestRetrofit.responseConverter();
                TestRetrofit.annotationURl();
                break;
            case R.id.testRetrofitRx_button:
                TestRetrofitRx.base();
                break;
        }
    }
}


text:
var Flint = require('node-flint');
var webhook = require('node-flint/webhook');
var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// flint options
var config = {
  webhookUrl: process.env.SPARK_WEBHOOKURL,
  token: process.env.SPARK_TOKEN,
  port: process.env.SOILSENSOR_PORT || 8080
};

console.log('config: ' + JSON.stringify(config));

//init flint
var flint = new Flint(config);
// Define markdown as default
flint.messageFormat = 'markdown';
flint.start();

// say hello
flint.hears('hello', function(bot, trigger) {
  console.log('print hello');
  bot.say('Hello **'+trigger.personDisplayName+'**! Print **help** if you need some.');
});

flint.hears('help', function(bot, trigger) {
  console.log('print help');
  bot.say('##I\'m SoilSensor, the bot telling you when your plant needs water.\n'+
          'You can ask me the following commands:\n'+
          '- **get all** will tell you whether to put water or not for all your plants\n'+
          '- **get <sensorId>** will tell you whether to put water from a particular sensor measure\n'+
          '- **help** will print this help');
});

// you can adjust the threshold value
var THRESHOLD_VALUE = 800;

function measureToWaterStatusString(measure) {
  if (measure < THRESHOLD_VALUE) {
    return 'Doesn\'t need watering';
  } else {
    return 'Time to water your plant';
  }
}

function getResponseForSensor(id) {
  return 'Sensor #'+id+': **'+devicesLastMeasures[id]+'** -> '+measureToWaterStatusString(devicesLastMeasures[id]);
}

flint.hears('get', function(bot, trigger) {

  var sensorId = trigger.args[1];
  var response = '**Status of your plants:**\n';

  if (sensorId === 'all') {
    for (id in devicesLastMeasures) {
      response += '- '+getResponseForSensor(id) + '\n';
    }
  }
  else if (devicesLastMeasures.hasOwnProperty(sensorId)) {
    response += '- '+getResponseForSensor(sensorId);
  }
  else {
    response = 'Cannot find sensor #'+sensorId;
  }

  console.log('response: '+response);
  bot.say(response);
});

// default message for unrecognized commands
flint.hears(/.*/, function(bot, trigger) {
  bot.say('Could you please rephrase?');
}, 20);

// define express path for incoming webhooks
app.post('/', webhook(flint));

// Last measures stored per deviceID
var devicesLastMeasures = {
  12345: 50,
  67890: 900
 };

// define express path for incoming sensor notifications
app.post('/soilmoisturesensor/:deviceId', function(req, res) {
  var moistureLevel = req.body.moistureLevel || -1;
  console.log('DevideId: '+ req.params.deviceId +' -> Moisture Level: ' + moistureLevel);

  devicesLastMeasures[req.params.deviceId] = moistureLevel;

  if (moistureLevel >= 0) {
    res.send('OK');
  } else {
    res.send('wrong moistureLevel value ' + moistureLevel);
  }
});

app.get('/soilmoisturesensor/:deviceId', function(req, res) {
  var moistureLevel = req.query.moistureLevel || -1;
  console.log('DevideId: '+ req.params.deviceId +' -> Moisture Level: ' + moistureLevel);

  devicesLastMeasures[req.params.deviceId] = moistureLevel;

  if (moistureLevel >= 0) {
    res.send('OK');
  } else {
    res.send('wrong moistureLevel value ' + moistureLevel);
  }
});

// start express server
var server = app.listen(config.port, function() {
  flint.debug('Flint listening on port %s', config.port);
});

server.on('error', onError);
server.on('listening', onListening);

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  flint.debug('Listening on ' + bind);
}

// gracefully shutdown (crtl-c)
process.on('SIGINT', function() {
  flint.debug('stopping...');
  server.close();
  flint.stop().then(function() {
    process.exit();
  });
});


text:
package runtime

import (
	"internal/goarch"
	"unsafe"
)

type mOS struct{}

//go:noescape
//extern _umtx_op
func sys_umtx_op(addr *uint32, mode int32, val uint32, uaddr1 uinptr, ts *umtx_time) int32

//go:noescape
//extern sysctl
func sysctl(*uint32, uint32, *byte, *uintptr, *byte, uintptr) int32

const (
	_CTL_MAXNAME     = 24
	_CPU_LEVEL_WHICH = 3
	_CPU_WHICH_PID   = 2
)

// From FreeBSD's <sys/sysctl.h>
const (
	_CTL_HW      = 6
	_HW_PAGESIZE = 7
)

// Undocumented numbers from FreeBSD's lib/libc/gen/sysctlnametomib.c.
const (
	_CTL_QUERY     = 0
	_CTL_QUERY_MIB = 3
)

// sysctlnametomib fill mib with dynamically assigned sysctl entries of name,
// return count of effected mib slots, return 0 on error.
func sysctlnametomib(name []byte, mib *[_CTL_MAXNAME]uint32) uint32 {
	oid := [2]uint32{_CTL_QUERY, _CTL_QUERY_MIB}
	miblen := uintptr(_CTL_MAXNAME)
	if sysctl(&oid[0], 2, (*byte)(unsafe.Pointer(mib)), &miblen, (*byte)(unsafe.Pointer(&name[0])), (uintptr)(len(name))) < 0 {
		return 0
	}
	miblen /= unsafe.Sizeof(uint32(0))
	if miblen <= 0 {
		return 0
	}
	return uint32(miblen)
}

const (
	_CPU_CURRENT_PID = -1 // Current process ID.
)

//go:noescape
//extern cpuset_getaffinity
func cpuset_getaffinity(level int32, which int32, id int64, size uintptr, mask *byte) int32

//go:systemstack
func getncpu() int32 {
	// Use a large buffer for the CPU mask. We're on the system
	// stack, so this is fine, and we can't allocate memory for a
	// dynamically-sized buffer at this point.
	const maxCPUs = 64 * 1024
	var mask [maxCPUs / 8]byte
	var mib [_CTL_MAXNAME]uint32

	// According to FreeBSD's /usr/src/sys/kern/kern_cpuset.c,
	// cpuset_getaffinity return ERANGE when provided buffer size exceed the limits in kernel.
	// Querying kern.smp.maxcpus to calculate maximum buffer size.
	// See https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=200802

	// Variable kern.smp.maxcpus introduced at Dec 23 2003, revision 123766,
	// with dynamically assigned sysctl entries.
	miblen := sysctlnametomib([]byte("kern.smp.maxcpus"), &mib)
	if miblen == 0 {
		return 1
	}

	// Query kern.smp.maxcpus.
	dstsize := uintptr(4)
	maxcpus := uint32(0)
	if sysctl(&mib[0], miblen, (*byte)(unsafe.Pointer(&maxcpus)), &dstsize, nil, 0) != 0 {
		return 1
	}

	maskSize := int(maxcpus+7) / 8
	if maskSize < goarch.PtrSize {
		maskSize = goarch.PtrSize
	}
	if maskSize > uintptr(len(mask)) {
		maskSize = uintptr(len(mask))
	}

	if cpuset_getaffinity(_CPU_LEVEL_WHICH, _CPU_WHICH_PID, _CPU_CURRENT_PID,
		maskSize, (*byte)(unsafe.Pointer(&mask[0]))) != 0 {
		return 1
	}
	n := int32(0)
	for _, v := range mask[:maskSize] {
		for v != 0 {
			n += int32(v & 1)
			v >>= 1
		}
	}
	if n == 0 {
		return 1
	}
	return n
}

func getPageSize() uintptr {
	mib := [2]uint32{_CTL_HW, _HW_PAGESIZE}
	out := uint32(0)
	nout := unsafe.Sizeof(out)
	ret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0)
	if ret >= 0 {
		return uintptr(out)
	}
	return 0
}

// FreeBSD's umtx_op syscall is effectively the same as Linux's futex, and
// thus the code is largely similar. See Linux implementation
// and lock_futex.go for comments.

//go:nosplit
func futexsleep(addr *uint32, val uint32, ns int64) {
	systemstack(func() {
		futexsleep1(addr, val, ns)
	})
}

func futexsleep1(addr *uint32, val uint32, ns int64) {
	var utp *umtx_time
	if ns >= 0 {
		var ut umtx_time
		ut._clockid = _CLOCK_MONOTONIC
		ut._timeout.setNsec(ns)
		utp = &ut
	}
	ret := sys_umtx_op(addr, _UMTX_OP_WAIT_UINT_PRIVATE, val, unsafe.Sizeof(*utp), utp)
	if ret >= 0 || ret == -_EINTR || ret == -_ETIMEDOUT {
		return
	}
	print("umtx_wait addr=", addr, " val=", val, " ret=", ret, "\n")
	*(*int32)(unsafe.Pointer(uintptr(0x1005))) = 0x1005
}

//go:nosplit
func futexwakeup(addr *uint32, cnt uint32) {
	ret := sys_umtx_op(addr, _UMTX_OP_WAKE_PRIVATE, cnt, 0, nil)
	if ret >= 0 {
		return
	}

	systemstack(func() {
		print("umtx_wake_addr=", addr, " ret=", ret, "\n")
	})
}

func osinit() {
	ncpu = getncpu()
	if physPageSize == 0 {
		physPageSize = getPageSize()
	}
}

func sysargs(argc int32, argv **byte) {
	n := argc + 1

	// skip over argv, envp to get to auxv
	for argv_index(argv, n) != nil {
		n++
	}

	// skip NULL separator
	n++

	// now argv+n is auxv
	auxv := (*[1 << 28]uintptr)(add(unsafe.Pointer(argv), uintptr(n)*goarch.PtrSize))
	sysauxv(auxv[:])
}

const (
	_AT_NULL     = 0  // Terminates the vector
	_AT_PAGESZ   = 6  // Page size in bytes
	_AT_TIMEKEEP = 22 // Pointer to timehands.
	_AT_HWCAP    = 25 // CPU feature flags
	_AT_HWCAP2   = 26 // CPU feature flags 2
)

func sysauxv(auxv []uintptr) {
	for i := 0; auxv[i] != _AT_NULL; i += 2 {
		tag, val := auxv[i], auxv[i+1]
		switch tag {
		// _AT_NCPUS from auxv shouldn't be used due to golang.org/issue/15206
		case _AT_PAGESZ:
			physPageSize = val
		case _AT_TIMEKEEP:
			timekeepSharedPage = (*vdsoTimekeep)(unsafe.Pointer(val))
		}

		archauxv(tag, val)
	}
}


text:
PROJECT=$(readlink -f $(dirname $0)/../../..)
UBUNTU_DIR=${PROJECT}/package/ubuntu/hyperstart
VERSION=0.7.0

if [ $# -gt 0 ] ; then
    VERSION=$1
fi

# install addtional pkgs in order to build deb pkg
sudo apt-get install -y autoconf automake pkg-config dh-make

# get hyperstart tar ball
cd $PROJECT/../hyperstart
git archive --format=tar.gz master > ${UBUNTU_DIR}/hyperstart-${VERSION}.tar.gz

# prepair to create source pkg
mkdir -p ${UBUNTU_DIR}/hyperstart-${VERSION}
cd ${UBUNTU_DIR}
tar -zxvf hyperstart-${VERSION}.tar.gz -C ${UBUNTU_DIR}/hyperstart-${VERSION}

# in order to use debian/* to create deb, so put them in the hyperstart.
cp -a ${UBUNTU_DIR}/debian ${UBUNTU_DIR}/hyperstart-${VERSION}

# run dh_make
cd ${UBUNTU_DIR}/hyperstart-${VERSION}
dh_make -s -y -f ../hyperstart-${VERSION}.tar.gz

# run dpkg-buildpackage
dpkg-buildpackage -us -uc -rfakeroot

#clean up intermediate files
rm -rf ${UBUNTU_DIR}/hyperstart-${VERSION}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/taskLineHeight"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/taskLinePriority"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/main_activity_horizontal_margin"
        android:layout_marginTop="@dimen/main_activity_horizontal_margin"
        android:src="@drawable/highpriority" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/taskLineHeight"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/titleTask"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/taskLineTitleMargin"
            android:layout_marginRight="@dimen/taskLineTitleMargin"
            android:maxLines="@integer/taskLineTitleMaxLine"
            android:text="adadasd4131231221da1111dsad"
            android:textColor="@color/taskLineTitleFG"
            android:textSize="@dimen/taskLineTitleFontSize" />

        <TextView
            android:id="@+id/dateTask"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="@dimen/taskLineDateMargin"
            android:text="20 March 2013"
            android:gravity="center_vertical"
            android:textColor="@color/taskLineTimeFG"
            android:textSize="@dimen/taskLineDateFontSize" />
    </LinearLayout>

</LinearLayout>


text:
import BaseMocha from './baseMocha'
import mocha from 'gulp-mocha'
import debug from 'gulp-debug'
import gulpif from 'gulp-if'

export const Default = {
  task: {
    name: 'mocha'
  },
  options: {
    reporter: 'nyan'
  }
}

const Mocha = class extends BaseMocha {

  /**
   *
   * @param gulp - gulp instance
   * @param preset - base preset configuration - either one from preset.js or a custom hash
   * @param configs - customized overrides for this recipe
   */
  constructor(gulp, preset, ...configs) {
    super(gulp, preset, Default, ...configs)
  }

  run(done, watching = false) {
    let bundle = this.gulp.src(this.config.test.glob, this.config.test.options)
      .pipe(gulpif(this.config.debug, debug(this.debugOptions())))
      .pipe(mocha(this.config.options)) // gulp-mocha needs filepaths so you can't have any plugins before it
      .on('error', (error) => {
        this.notifyError(error, done, watching)
      })

    return bundle
  }
}

export default Mocha


text:
require 'core/spec_helper'

RSpec.describe ZendeskAPI::Tag, :vcr, :not_findable do
  [organization, user, ticket].each do |object|
    raise "Your setup is invalid, see spec/live/Readme.md" unless object

    under object do
      before do
        parent.tags = %w{tag2 tag3}
        parent.tags.save!
      end

      it "can be set" do
        expect(tags).to eq(%w{tag2 tag3})
      end

      it "should be removable" do
        parent.tags.destroy!(:id => "tag2")

        expect(tags).to eq(%w{tag3})
      end

      it "shouldn't re-save destroyed tags" do
        parent.tags.first.destroy!
        parent.tags.save!

        expect(tags).to eq(%w{tag3})
      end

      it "should be updatable" do
        parent.tags.update!(:id => "tag4")

        expect(tags).to eq(%w{tag2 tag3 tag4})
      end

      it "should be savable" do
        parent.tags << "tag4"
        parent.tags.save!

        expect(tags).to eq(%w{tag2 tag3 tag4})
      end

      it "should be modifiable" do
        parent.tags.delete(ZendeskAPI::Tag.new(nil, :id => "tag2"))
        parent.tags.save!

        expect(tags).to eq(%w{tag3})

        parent.tags.delete_if { |tag| tag.id == "tag3" }
        parent.tags.save!

        expect(tags).to be_empty
      end
    end
  end

  def tags
    parent.tags.fetch!(:reload).map(&:id).sort
  end
end


text:
package sort

import (
	securityv1 "github.com/openshift/api/security/v1"
	securityapi "github.com/openshift/origin/pkg/security/apis/security"
	securityapiv1 "github.com/openshift/origin/pkg/security/apis/security/v1"
)

// ByPriority is a helper to sort SCCs based on priority.  If priorities are equal
// a string compare of the name is used.
type ByPriority []*securityv1.SecurityContextConstraints

func (s ByPriority) Len() int {
	return len(s)
}
func (s ByPriority) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s ByPriority) Less(i, j int) bool {
	iSCC := s[i]
	jSCC := s[j]

	iSCCPriority := getPriority(iSCC)
	jSCCPriority := getPriority(jSCC)

	// a higher priority is considered "less" so that it moves to the front of the line
	if iSCCPriority > jSCCPriority {
		return true
	}

	if iSCCPriority < jSCCPriority {
		return false
	}

	// priorities are equal, let's try point values
	iRestrictionScore := pointValue(iSCC)
	jRestrictionScore := pointValue(jSCC)

	// a lower restriction score is considered "less" so that it moves to the front of the line
	// (the greater the score, the more lax the SCC is)
	if iRestrictionScore < jRestrictionScore {
		return true
	}

	if iRestrictionScore > jRestrictionScore {
		return false
	}

	// they are still equal, sort by name
	return iSCC.Name < jSCC.Name
}

func getPriority(scc *securityv1.SecurityContextConstraints) int {
	if scc.Priority == nil {
		return 0
	}
	return int(*scc.Priority)
}

func ByPriorityConvert(toConvert []*securityapi.SecurityContextConstraints) (ByPriority, error) {
	converted := []*securityv1.SecurityContextConstraints{}
	for _, internal := range toConvert {
		external := &securityv1.SecurityContextConstraints{}
		if err := securityapiv1.Convert_security_SecurityContextConstraints_To_v1_SecurityContextConstraints(internal, external, nil); err != nil {
			return nil, err
		}
	}
	return converted, nil
}


text:
<?php

/**
 * The concrete command that save theme options.
 *
 * @author     Time.ly Network Inc.
 * @since      2.0
 *
 * @package    AI1EC
 * @subpackage AI1EC.Command
 */
class Ai1ec_Command_Save_Theme_Options extends Ai1ec_Command_Save_Abstract {

	/* (non-PHPdoc)
	 * @see Ai1ec_Command::is_this_to_execute()
	*/
	public function do_execute() {
		$variables = array();

		// Handle updating of theme options.
		if ( isset( $_POST[Ai1ec_View_Theme_Options::SUBMIT_ID] ) ) {
			$_POST     = stripslashes_deep( $_POST );
			$lessphp   = $this->_registry->get( 'less.lessphp' );
			$variables = $lessphp->get_saved_variables();
			foreach ( $variables as $variable_name => $variable_params ) {
				if ( isset( $_POST[$variable_name] ) ) {
					// Avoid problems for those who are foolish enough to leave php.ini
					// settings at their defaults, which has magic quotes enabled.
					if ( get_magic_quotes_gpc() ) {
						$_POST[$variable_name] = stripslashes( $_POST[$variable_name] );
					}
					if (
						Ai1ec_Less_Variable_Font::CUSTOM_FONT === $_POST[$variable_name]
					) {
						$_POST[$variable_name] = $_POST[$variable_name .
							Ai1ec_Less_Variable_Font::CUSTOM_FONT_ID_SUFFIX];
					}
					// update the original array
					$variables[$variable_name]['value'] = $_POST[$variable_name];
				}
			}
			$_POST = add_magic_quotes( $_POST );

		}
		// Handle reset of theme options.
		elseif ( isset( $_POST[Ai1ec_View_Theme_Options::RESET_ID] ) ) {
			$option = $this->_registry->get( 'model.option' );
			$option->delete( 'ai1ec_less_variables' );
			$option->delete( 'ai1ec_render_css' );
			do_action( 'ai1ec_reset_less_variables' );
		}

		$css = $this->_registry->get( 'css.frontend' );

		$css->update_variables_and_compile_css(
			$variables,
			isset(
				$_POST[Ai1ec_View_Theme_Options::RESET_ID]
			)
		);

		return array(
			'url'        => ai1ec_admin_url(
				'edit.php?post_type=ai1ec_event&page=all-in-one-event-calendar-edit-css'
			),
			'query_args' => array(),
		);
	}

}


text:
using System.Windows.Forms;
using Rhino.Licensing.AdminTool.ViewModels;
using OpenDialog = System.Windows.Forms.OpenFileDialog;

namespace Rhino.Licensing.AdminTool.Dialogs
{
    public class OpenFileDialog : FileDialog<IOpenFileDialogViewModel>
    {
        private readonly OpenDialog _openFileDialog;

        public OpenFileDialog()
        {
            _openFileDialog = new OpenDialog();
        }

        protected override FileDialog Dialog
        {
            get { return _openFileDialog; }
        }

        protected override void BindDialogToViewModel()
        {
            base.BindDialogToViewModel();

            _openFileDialog.AddExtension = ViewModel.AddExtension;
            _openFileDialog.CheckFileExists = ViewModel.CheckFileExists;
            _openFileDialog.CheckPathExists = ViewModel.CheckPathExists;
            _openFileDialog.DefaultExt = ViewModel.DefaultExtension;
            _openFileDialog.FileName = ViewModel.FileName;
            _openFileDialog.Filter = ViewModel.Filter;
            _openFileDialog.InitialDirectory = ViewModel.InitialDirectory;
            _openFileDialog.Multiselect = ViewModel.MultiSelect;
            _openFileDialog.Title = ViewModel.Title;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ssh_crm</display-name>

  <!-- spring监听器,在服务器启动的时候 加载spring配置文件 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:bean.xml</param-value>
  </context-param>

  <!-- 配置让session延迟关闭-->
  <filter>
  	<filter-name>openSessionInViewFilter</filter-name>
  	<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>openSessionInViewFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- struts2过滤器 -->
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>


text:
require 'spec_helper'

RSpec.describe 'stripe endpoint routing', type: :functional do
  let(:app) { Webhook::Web }

  it 'returns 200 on post' do
    post '/stripe', '{}'
    expect(last_response.status).to eq(200)
  end

  it 'returns empty body post' do
    post '/stripe', '{}'
    expect(last_response.body).to eq('')
  end

  it 'returns 404 on get' do
    get '/stripe'
    expect(last_response.status).to eq(404)
  end
end


text:
using System;
using System.Linq;

namespace Yobisoft.Core.Extensions
{
    public static class DateTimeExtension
    {
        public static DateTime ChangeYears(this DateTime dateTime, int years)
        {
            return new DateTime(
                years,
                dateTime.Month,
                dateTime.Day,
                dateTime.Hour,
                dateTime.Minute,
                dateTime.Second,
                dateTime.Millisecond,
                dateTime.Kind);
        }

        public static DateTime ChangeMonths(this DateTime dateTime, int months)
        {
            return new DateTime(
                dateTime.Year,
                months,
                dateTime.Day,
                dateTime.Hour,
                dateTime.Minute,
                dateTime.Second,
                dateTime.Millisecond,
                dateTime.Kind);
        }

        public static DateTime ChangeDays(this DateTime dateTime, int days)
        {
            return new DateTime(
                dateTime.Year,
                dateTime.Month,
                days,
                dateTime.Hour,
                dateTime.Minute,
                dateTime.Second,
                dateTime.Millisecond,
                dateTime.Kind);
        }

        public static DateTime ChangeHours(this DateTime dateTime, int hours)
        {
            return new DateTime(
                dateTime.Year,
                dateTime.Month,
                dateTime.Day,
                hours,
                dateTime.Minute,
                dateTime.Second,
                dateTime.Millisecond,
                dateTime.Kind);
        }
        public static DateTime ChangeMinutes(this DateTime dateTime, int minutes)
        {
            return new DateTime(
                dateTime.Year,
                dateTime.Month,
                dateTime.Day,
                dateTime.Hour,
                minutes,
                dateTime.Second,
                dateTime.Millisecond,
                dateTime.Kind);
        }

        public static DateTime ChangeSeconds(this DateTime dateTime, int seconds)
        {
            return new DateTime(
                dateTime.Year,
                dateTime.Month,
                dateTime.Day,
                dateTime.Hour,
                dateTime.Minute,
                seconds,
                dateTime.Millisecond,
                dateTime.Kind);
        }

        public static DateTime ChangeMilliseconds(this DateTime dateTime, int milliseconds)
        {
            return new DateTime(
                dateTime.Year,
                dateTime.Month,
                dateTime.Day,
                dateTime.Hour,
                dateTime.Minute,
                dateTime.Second,
                milliseconds,
                dateTime.Kind);
        }

        public static DateTime Max(params DateTime[] timestamps)
        {
            return timestamps.Max();
        }

        public static DateTime Min(params DateTime[] timestamps)
        {
            return timestamps.Min();
        }
    }
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { Comp626Component } from './comp-626.component';

describe('Comp626Component', () => {
  let component: Comp626Component;
  let fixture: ComponentFixture<Comp626Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ Comp626Component ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Comp626Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
namespace chromeos {

namespace {

ShillManagerClient* g_instance = nullptr;

// The ShillManagerClient implementation.
class ShillManagerClientImpl : public ShillManagerClient {
 public:
  ShillManagerClientImpl() = default;

  ShillManagerClientImpl(const ShillManagerClientImpl&) = delete;
  ShillManagerClientImpl& operator=(const ShillManagerClientImpl&) = delete;

  ~ShillManagerClientImpl() override = default;

  ////////////////////////////////////
  // ShillManagerClient overrides.
  void AddPropertyChangedObserver(
      ShillPropertyChangedObserver* observer) override {
    helper_->AddPropertyChangedObserver(observer);
  }

  void RemovePropertyChangedObserver(
      ShillPropertyChangedObserver* observer) override {
    helper_->RemovePropertyChangedObserver(observer);
  }

  void GetProperties(DBusMethodCallback<base::Value> callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kGetPropertiesFunction);
    helper_->CallValueMethod(
        &method_call,
        base::BindOnce(&ShillClientHelper::OnGetProperties,
                       dbus::ObjectPath(shill::kFlimflamServicePath),
                       std::move(callback)));
  }

  void GetNetworksForGeolocation(
      DBusMethodCallback<base::Value> callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kGetNetworksForGeolocation);
    helper_->CallValueMethod(&method_call, std::move(callback));
  }

  void SetProperty(const std::string& name,
                   const base::Value& value,
                   base::OnceClosure callback,
                   ErrorCallback error_callback) override {
    // This property is read-only and can only be mutated by the specialized
    // method exposed in DBus API.
    if (name == shill::kDNSProxyDOHProvidersProperty) {
      SetDNSProxyDOHProviders(value, std::move(callback),
                              std::move(error_callback));
      return;
    }

    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kSetPropertyFunction);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(name);
    ShillClientHelper::AppendValueDataAsVariant(&writer, value);
    helper_->CallVoidMethodWithErrorCallback(&method_call, std::move(callback),
                                             std::move(error_callback));
  }

  void RequestScan(const std::string& type,
                   base::OnceClosure callback,
                   ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kRequestScanFunction);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(type);
    helper_->CallVoidMethodWithErrorCallback(&method_call, std::move(callback),
                                             std::move(error_callback));
  }

  void EnableTechnology(const std::string& type,
                        base::OnceClosure callback,
                        ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kEnableTechnologyFunction);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(type);
    helper_->CallVoidMethodWithErrorCallback(&method_call, std::move(callback),
                                             std::move(error_callback));
  }

  void SetNetworkThrottlingStatus(const NetworkThrottlingStatus& status,
                                  base::OnceClosure callback,
                                  ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kSetNetworkThrottlingFunction);
    dbus::MessageWriter writer(&method_call);
    writer.AppendBool(status.enabled);
    writer.AppendUint32(status.upload_rate_kbits);
    writer.AppendUint32(status.download_rate_kbits);
    helper_->CallVoidMethodWithErrorCallback(&method_call, std::move(callback),
                                             std::move(error_callback));
  }

  void DisableTechnology(const std::string& type,
                         base::OnceClosure callback,
                         ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kDisableTechnologyFunction);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(type);
    helper_->CallVoidMethodWithErrorCallback(&method_call, std::move(callback),
                                             std::move(error_callback));
  }

  void ConfigureService(const base::Value& properties,
                        ObjectPathCallback callback,
                        ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kConfigureServiceFunction);
    dbus::MessageWriter writer(&method_call);
    ShillClientHelper::AppendServiceProperties(&writer, properties);
    helper_->CallObjectPathMethodWithErrorCallback(
        &method_call, std::move(callback), std::move(error_callback));
  }

  void ConfigureServiceForProfile(const dbus::ObjectPath& profile_path,
                                  const base::Value& properties,
                                  ObjectPathCallback callback,
                                  ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kConfigureServiceForProfileFunction);
    dbus::MessageWriter writer(&method_call);
    writer.AppendObjectPath(dbus::ObjectPath(profile_path));
    ShillClientHelper::AppendServiceProperties(&writer, properties);
    helper_->CallObjectPathMethodWithErrorCallback(
        &method_call, std::move(callback), std::move(error_callback));
  }

  void GetService(const base::Value& properties,
                  ObjectPathCallback callback,
                  ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kGetServiceFunction);
    dbus::MessageWriter writer(&method_call);
    ShillClientHelper::AppendServiceProperties(&writer, properties);
    helper_->CallObjectPathMethodWithErrorCallback(
        &method_call, std::move(callback), std::move(error_callback));
  }

  void ConnectToBestServices(base::OnceClosure callback,
                             ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kConnectToBestServicesFunction);
    helper_->CallVoidMethodWithErrorCallback(&method_call, std::move(callback),
                                             std::move(error_callback));
  }

  void AddPasspointCredentials(const dbus::ObjectPath& profile_path,
                               const base::Value& properties,
                               base::OnceClosure callback,
                               ErrorCallback error_callback) override {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kAddPasspointCredentialsFunction);
    dbus::MessageWriter writer(&method_call);
    writer.AppendObjectPath(profile_path);
    ShillClientHelper::AppendServiceProperties(&writer, properties);
    helper_->CallVoidMethodWithErrorCallback(&method_call, std::move(callback),
                                             std::move(error_callback));
  }

  TestInterface* GetTestInterface() override { return nullptr; }

  void Init(dbus::Bus* bus) {
    proxy_ = bus->GetObjectProxy(shill::kFlimflamServiceName,
                                 dbus::ObjectPath(shill::kFlimflamServicePath));
    helper_ = std::make_unique<ShillClientHelper>(proxy_);
    helper_->MonitorPropertyChanged(shill::kFlimflamManagerInterface);
  }

 private:
  // Used by SetProperty call to reroute kDNSProxyDOHProviders to the underlying
  // specialized method in the DBus API.
  void SetDNSProxyDOHProviders(const base::Value& providers,
                               base::OnceClosure callback,
                               ErrorCallback error_callback) {
    dbus::MethodCall method_call(shill::kFlimflamManagerInterface,
                                 shill::kSetDNSProxyDOHProvidersFunction);
    dbus::MessageWriter writer(&method_call);
    ShillClientHelper::AppendServiceProperties(&writer, providers);
    helper_->CallVoidMethodWithErrorCallback(&method_call, std::move(callback),
                                             std::move(error_callback));
  }

  dbus::ObjectProxy* proxy_ = nullptr;
  std::unique_ptr<ShillClientHelper> helper_;
};

}  // namespace

ShillManagerClient::ShillManagerClient() {
  DCHECK(!g_instance);
  g_instance = this;
}

ShillManagerClient::~ShillManagerClient() {
  DCHECK_EQ(this, g_instance);
  g_instance = nullptr;
}

// static
void ShillManagerClient::Initialize(dbus::Bus* bus) {
  DCHECK(bus);
  (new ShillManagerClientImpl)->Init(bus);
}

// static
void ShillManagerClient::InitializeFake() {
  new FakeShillManagerClient();
}

// static
void ShillManagerClient::Shutdown() {
  DCHECK(g_instance);
  delete g_instance;
}

// static
ShillManagerClient* ShillManagerClient::Get() {
  return g_instance;
}

}  // namespace chromeos


text:
module Helper
  # Rounds float with given precision.
  def round(float, precision = 2)
    m = 10**precision
    (float.to_f*m).round.to_f/m
  end
end


text:
import re, os
from sys import argv, exit

defaults = {
	"NAME" : "crowdata_db",
	"USER" : "crowdata_user",
	"PASSWORD" : "crowdata",
	"HOST" : "localhost",
	"EMAIL" : "crowdata@blahblah.com",
	"WITH_DB" : None
}

def dbPop():
	for directive in ["USER", "EMAIL", "PASSWORD", "WITH_DB"]:
		if "crowdata_%s" % directive not in os.environ.keys():
			os.environ['crowdata_%s' % directive] = defaults[directive]

	if os.environ['crowdata_WITH_DB'] is not None:
		print "Populating database from backup %s" % os.environ['crowdata_WITH_DB']
		import subprocess

		subprocess.call(("pg_restore --dbname=%s --verbose %s --clean" % (os.environ['crowdata_NAME'], os.environ['crowdata_WITH_DB'])).split(" "))

	# superuser
	print "Creating superuser"
	from django.db import DEFAULT_DB_ALIAS as database
	from django.contrib.auth.models import User

	User.objects.db_manager(database).create_superuser(
		os.environ['crowdata_USER'], os.environ['crowdata_EMAIL'], os.environ['crowdata_PASSWORD'])

def init():
	local_settings = []

	with open('local_settings.py.example', 'rb') as C:
		for line in C.read().split('\n'):
			for directive in ["NAME", "USER", "PASSWORD", "HOST"]:
				if re.match(re.compile('.*\'%s\':' % directive), line) is not None:
					if "crowdata_%s" % directive not in os.environ.keys():
						print "No directive set for %s. using default value %s" % (directive, defaults[directive])
						os.environ["crowdata_%s" % directive] = defaults[directive]

					idx = line.find("\'\'") + 1
					line = "%s%s%s" % (line[:idx], os.environ["crowdata_%s" % directive], line[idx:])

			local_settings.append(line)

	with open('local_settings.py', 'wb+') as C:
		C.write('\n'.join(local_settings))

if __name__ == "__main__": main()
	if len(argv) != 2: exit(-1)

	if argv[1] == "-init": init()
	elif argv[1] == "-db_pop": dbPop()
	else: exit(-1)

	exit(0)