text:
package org.elasticsearch.index.mapper.geo;

import com.spatial4j.core.shape.Shape;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.spatial.prefix.PrefixTreeStrategy;
import org.apache.lucene.spatial.prefix.RecursivePrefixTreeStrategy;
import org.apache.lucene.spatial.prefix.TermQueryPrefixTreeStrategy;
import org.apache.lucene.spatial.prefix.tree.GeohashPrefixTree;
import org.apache.lucene.spatial.prefix.tree.PackedQuadPrefixTree;
import org.apache.lucene.spatial.prefix.tree.QuadPrefixTree;
import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree;
import org.elasticsearch.Version;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.geo.GeoUtils;
import org.elasticsearch.common.geo.SpatialStrategy;
import org.elasticsearch.common.geo.builders.ShapeBuilder;
import org.elasticsearch.common.geo.builders.ShapeBuilder.Orientation;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.mapper.core.AbstractFieldMapper;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.mapper.MapperBuilders.geoShapeField;

/**
 * FieldMapper for indexing {@link com.spatial4j.core.shape.Shape}s.
 *

 * Currently Shapes can only be indexed and can only be queried using
 * {@link org.elasticsearch.index.query.GeoShapeQueryParser}, consequently
 * a lot of behavior in this Mapper is disabled.
 *

 * Format supported:
 *

 * "field" : {
 * "type" : "polygon",
 * "coordinates" : [
 * [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
 * ]
 * }
 */
public class GeoShapeFieldMapper extends AbstractFieldMapper {

    public static final String CONTENT_TYPE = "geo_shape";

    public static class Names {
        public static final String TREE = "tree";
        public static final String TREE_GEOHASH = "geohash";
        public static final String TREE_QUADTREE = "quadtree";
        public static final String TREE_LEVELS = "tree_levels";
        public static final String TREE_PRESISION = "precision";
        public static final String DISTANCE_ERROR_PCT = "distance_error_pct";
        public static final String ORIENTATION = "orientation";
        public static final String STRATEGY = "strategy";
    }

    public static class Defaults {
        public static final String TREE = Names.TREE_GEOHASH;
        public static final String STRATEGY = SpatialStrategy.RECURSIVE.getStrategyName();
        public static final int GEOHASH_LEVELS = GeoUtils.geoHashLevelsForPrecision("50m");
        public static final int QUADTREE_LEVELS = GeoUtils.quadTreeLevelsForPrecision("50m");
        public static final double LEGACY_DISTANCE_ERROR_PCT = 0.025d;
        public static final Orientation ORIENTATION = Orientation.RIGHT;

        public static final MappedFieldType FIELD_TYPE = new GeoShapeFieldType();

        static {
            // setting name here is a hack so freeze can be called...instead all these options should be
            // moved to the default ctor for GeoShapeFieldType, and defaultFieldType() should be removed from mappers...
            FIELD_TYPE.setNames(new MappedFieldType.Names("DoesNotExist"));
            FIELD_TYPE.setIndexOptions(IndexOptions.DOCS);
            FIELD_TYPE.setTokenized(false);
            FIELD_TYPE.setStored(false);
            FIELD_TYPE.setStoreTermVectors(false);
            FIELD_TYPE.setOmitNorms(true);
            FIELD_TYPE.freeze();
        }
    }

    public static class Builder extends AbstractFieldMapper.Builder<Builder, GeoShapeFieldMapper> {

        public Builder(String name) {
            super(name, Defaults.FIELD_TYPE);
        }

        public GeoShapeFieldType fieldType() {
            return (GeoShapeFieldType)fieldType;
        }

        @Override
        public GeoShapeFieldMapper build(BuilderContext context) {
            GeoShapeFieldType geoShapeFieldType = (GeoShapeFieldType)fieldType;

            if (geoShapeFieldType.tree.equals("quadtree") && context.indexCreatedVersion().before(Version.V_2_0_0)) {
                geoShapeFieldType.setTree("legacyquadtree");
            }

            if (context.indexCreatedVersion().before(Version.V_2_0_0) ||
                (geoShapeFieldType.treeLevels() == 0 && geoShapeFieldType.precisionInMeters() < 0)) {
                geoShapeFieldType.setDefaultDistanceErrorPct(Defaults.LEGACY_DISTANCE_ERROR_PCT);
            }
            setupFieldType(context);

            return new GeoShapeFieldMapper(name, fieldType, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
        }
    }

    public static class TypeParser implements Mapper.TypeParser {

        @Override
        public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
            Builder builder = geoShapeField(name);
            for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry<String, Object> entry = iterator.next();
                String fieldName = Strings.toUnderscoreCase(entry.getKey());
                Object fieldNode = entry.getValue();
                if (Names.TREE.equals(fieldName)) {
                    builder.fieldType().setTree(fieldNode.toString());
                    iterator.remove();
                } else if (Names.TREE_LEVELS.equals(fieldName)) {
                    builder.fieldType().setTreeLevels(Integer.parseInt(fieldNode.toString()));
                    iterator.remove();
                } else if (Names.TREE_PRESISION.equals(fieldName)) {
                    builder.fieldType().setPrecisionInMeters(DistanceUnit.parse(fieldNode.toString(), DistanceUnit.DEFAULT, DistanceUnit.DEFAULT));
                    iterator.remove();
                } else if (Names.DISTANCE_ERROR_PCT.equals(fieldName)) {
                    builder.fieldType().setDistanceErrorPct(Double.parseDouble(fieldNode.toString()));
                    iterator.remove();
                } else if (Names.ORIENTATION.equals(fieldName)) {
                    builder.fieldType().setOrientation(ShapeBuilder.orientationFromString(fieldNode.toString()));
                    iterator.remove();
                } else if (Names.STRATEGY.equals(fieldName)) {
                    builder.fieldType().setStrategyName(fieldNode.toString());
                    iterator.remove();
                }
            }
            return builder;
        }
    }

    public static final class GeoShapeFieldType extends MappedFieldType {

        private String tree = Defaults.TREE;
        private String strategyName = Defaults.STRATEGY;
        private int treeLevels = 0;
        private double precisionInMeters = -1;
        private Double distanceErrorPct;
        private double defaultDistanceErrorPct = 0.0;
        private Orientation orientation = Defaults.ORIENTATION;

        // these are built when the field type is frozen
        private PrefixTreeStrategy defaultStrategy;
        private RecursivePrefixTreeStrategy recursiveStrategy;
        private TermQueryPrefixTreeStrategy termStrategy;

        public GeoShapeFieldType() {}

        protected GeoShapeFieldType(GeoShapeFieldType ref) {
            super(ref);
            this.tree = ref.tree;
            this.strategyName = ref.strategyName;
            this.treeLevels = ref.treeLevels;
            this.precisionInMeters = ref.precisionInMeters;
            this.distanceErrorPct = ref.distanceErrorPct;
            this.defaultDistanceErrorPct = ref.defaultDistanceErrorPct;
            this.orientation = ref.orientation;
        }

        @Override
        public GeoShapeFieldType clone() {
            return new GeoShapeFieldType(this);
        }

        @Override
        public boolean equals(Object o) {
            if (!super.equals(o)) return false;
            GeoShapeFieldType that = (GeoShapeFieldType) o;
            return treeLevels == that.treeLevels &&
                precisionInMeters == that.precisionInMeters &&
                defaultDistanceErrorPct == that.defaultDistanceErrorPct &&
                Objects.equals(tree, that.tree) &&
                Objects.equals(strategyName, that.strategyName) &&
                Objects.equals(distanceErrorPct, that.distanceErrorPct) &&
                orientation == that.orientation;
        }

        @Override
        public int hashCode() {
            return Objects.hash(super.hashCode(), tree, strategyName, treeLevels, precisionInMeters, distanceErrorPct, defaultDistanceErrorPct, orientation);
        }

        @Override
        public String typeName() {
            return CONTENT_TYPE;
        }

        @Override
        public void freeze() {
            super.freeze();
            // This is a bit hackish: we need to setup the spatial tree and strategies once the field name is set, which
            // must be by the time freeze is called.
            SpatialPrefixTree prefixTree;
            if ("geohash".equals(tree)) {
                prefixTree = new GeohashPrefixTree(ShapeBuilder.SPATIAL_CONTEXT, getLevels(treeLevels, precisionInMeters, Defaults.GEOHASH_LEVELS, true));
            } else if ("legacyquadtree".equals(tree)) {
                prefixTree = new QuadPrefixTree(ShapeBuilder.SPATIAL_CONTEXT, getLevels(treeLevels, precisionInMeters, Defaults.QUADTREE_LEVELS, false));
            } else if ("quadtree".equals(tree)) {
                prefixTree = new PackedQuadPrefixTree(ShapeBuilder.SPATIAL_CONTEXT, getLevels(treeLevels, precisionInMeters, Defaults.QUADTREE_LEVELS, false));
            } else {
                throw new IllegalArgumentException("Unknown prefix tree type [" + tree + "]");
            }

            recursiveStrategy = new RecursivePrefixTreeStrategy(prefixTree, names().indexName());
            recursiveStrategy.setDistErrPct(distanceErrorPct());
            recursiveStrategy.setPruneLeafyBranches(false);
            termStrategy = new TermQueryPrefixTreeStrategy(prefixTree, names().indexName());
            termStrategy.setDistErrPct(distanceErrorPct());
            defaultStrategy = resolveStrategy(strategyName);
        }

        @Override
        public void checkCompatibility(MappedFieldType fieldType, List<String> conflicts, boolean strict) {
            super.checkCompatibility(fieldType, conflicts, strict);
            GeoShapeFieldType other = (GeoShapeFieldType)fieldType;
            // prevent user from changing strategies
            if (strategyName().equals(other.strategyName()) == false) {
                conflicts.add("mapper [" + names().fullName() + "] has different strategy");
            }

            // prevent user from changing trees (changes encoding)
            if (tree().equals(other.tree()) == false) {
                conflicts.add("mapper [" + names().fullName() + "] has different tree");
            }

            // TODO we should allow this, but at the moment levels is used to build bookkeeping variables
            // in lucene's SpatialPrefixTree implementations, need a patch to correct that first
            if (treeLevels() != other.treeLevels()) {
                conflicts.add("mapper [" + names().fullName() + "] has different tree_levels");
            }
            if (precisionInMeters() != other.precisionInMeters()) {
                conflicts.add("mapper [" + names().fullName() + "] has different precision");
            }
        }

        private static int getLevels(int treeLevels, double precisionInMeters, int defaultLevels, boolean geoHash) {
            if (treeLevels > 0 || precisionInMeters >= 0) {
                return Math.max(treeLevels, precisionInMeters >= 0 ? (geoHash ? GeoUtils.geoHashLevelsForPrecision(precisionInMeters)
                    : GeoUtils.quadTreeLevelsForPrecision(precisionInMeters)) : 0);
            }
            return defaultLevels;
        }

        public String tree() {
            return tree;
        }

        public void setTree(String tree) {
            checkIfFrozen();
            this.tree = tree;
        }

        public String strategyName() {
            return strategyName;
        }

        public void setStrategyName(String strategyName) {
            checkIfFrozen();
            this.strategyName = strategyName;
        }

        public int treeLevels() {
            return treeLevels;
        }

        public void setTreeLevels(int treeLevels) {
            checkIfFrozen();
            this.treeLevels = treeLevels;
        }

        public double precisionInMeters() {
            return precisionInMeters;
        }

        public void setPrecisionInMeters(double precisionInMeters) {
            checkIfFrozen();
            this.precisionInMeters = precisionInMeters;
        }

        public double distanceErrorPct() {
            return distanceErrorPct == null ? defaultDistanceErrorPct : distanceErrorPct;
        }

        public void setDistanceErrorPct(double distanceErrorPct) {
            checkIfFrozen();
            this.distanceErrorPct = distanceErrorPct;
        }

        public void setDefaultDistanceErrorPct(double defaultDistanceErrorPct) {
            checkIfFrozen();
            this.defaultDistanceErrorPct = defaultDistanceErrorPct;
        }

        public Orientation orientation() { return this.orientation; }

        public void setOrientation(Orientation orientation) {
            checkIfFrozen();
            this.orientation = orientation;
        }

        public PrefixTreeStrategy defaultStrategy() {
            return this.defaultStrategy;
        }

        public PrefixTreeStrategy resolveStrategy(String strategyName) {
            if (SpatialStrategy.RECURSIVE.getStrategyName().equals(strategyName)) {
                return recursiveStrategy;
            }
            if (SpatialStrategy.TERM.getStrategyName().equals(strategyName)) {
                return termStrategy;
            }
            throw new IllegalArgumentException("Unknown prefix tree strategy [" + strategyName + "]");
        }

        @Override
        public String value(Object value) {
            throw new UnsupportedOperationException("GeoShape fields cannot be converted to String values");
        }

    }

    public GeoShapeFieldMapper(String simpleName, MappedFieldType fieldType, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
        super(simpleName, fieldType, false, null, indexSettings, multiFields, copyTo);
    }

    @Override
    public GeoShapeFieldType fieldType() {
        return (GeoShapeFieldType) super.fieldType();
    }

    @Override
    public MappedFieldType defaultFieldType() {
        return Defaults.FIELD_TYPE;
    }

    @Override
    public FieldDataType defaultFieldDataType() {
        return null;
    }

    @Override
    public Mapper parse(ParseContext context) throws IOException {
        try {
            Shape shape = context.parseExternalValue(Shape.class);
            if (shape == null) {
                ShapeBuilder shapeBuilder = ShapeBuilder.parse(context.parser(), this);
                if (shapeBuilder == null) {
                    return null;
                }
                shape = shapeBuilder.build();
            }
            Field[] fields = fieldType().defaultStrategy().createIndexableFields(shape);
            if (fields == null || fields.length == 0) {
                return null;
            }
            for (Field field : fields) {
                if (!customBoost()) {
                    field.setBoost(fieldType().boost());
                }
                context.doc().add(field);
            }
        } catch (Exception e) {
            throw new MapperParsingException("failed to parse [" + fieldType().names().fullName() + "]", e);
        }
        return null;
    }

    @Override
    protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
    }

    @Override
    protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
        builder.field("type", contentType());

        if (includeDefaults || fieldType().tree().equals(Defaults.TREE) == false) {
            builder.field(Names.TREE, fieldType().tree());
        }
        if (includeDefaults || fieldType().treeLevels() != 0) {
            builder.field(Names.TREE_LEVELS, fieldType().treeLevels());
        }
        if (includeDefaults || fieldType().precisionInMeters() != -1) {
            builder.field(Names.TREE_PRESISION, DistanceUnit.METERS.toString(fieldType().precisionInMeters()));
        }
        if (includeDefaults || fieldType().strategyName() != Defaults.STRATEGY) {
            builder.field(Names.STRATEGY, fieldType().strategyName());
        }
        if (includeDefaults || fieldType().distanceErrorPct() != fieldType().defaultDistanceErrorPct) {
            builder.field(Names.DISTANCE_ERROR_PCT, fieldType().distanceErrorPct());
        }
        if (includeDefaults || fieldType().orientation() != Defaults.ORIENTATION) {
            builder.field(Names.ORIENTATION, fieldType().orientation());
        }
    }

    @Override
    protected String contentType() {
        return CONTENT_TYPE;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<oobe-adaptive-dialog id="themeSelectionDialog" role="presentation"
    for-step="overview">
  <iron-icon slot="icon" icon="oobe-32:stars"></iron-icon>

    [[i18nDynamic(locale, 'themeSelectionScreenTitle')]]

    [[i18nDynamic(locale, 'themeSelectionScreenDescriptionClamshell')]]

    [[i18nDynamic(locale, 'themeSelectionScreenDescriptionTablet')]]

    <cr-radio-group id="theme" selected="{{selectedTheme}}">
      <cr-card-radio-button id="lightThemeButton" class="flex" name="light">

              [[i18nDynamic(locale, 'lightThemeLabel')]]

              [[i18nDynamic(locale, 'lightThemeDescription')]]

      </cr-card-radio-button>
      <cr-card-radio-button id="darkThemeButton" class="flex"
          name="dark">

              [[i18nDynamic(locale, 'darkThemeLabel')]]

              [[i18nDynamic(locale, 'darkThemeDescription')]]

      </cr-card-radio-button>
      <cr-card-radio-button id="autoThemeButton" class="flex"
          name="auto">

              [[i18nDynamic(locale, 'autoThemeLabel')]]

              [[i18nDynamic(locale, 'autoThemeDescription')]]

      </cr-card-radio-button>
    </cr-radio-group>

    <oobe-next-button id="nextButton" class="focus-on-show"
      on-click="onNextClicked_">
    </oobe-next-button>

</oobe-adaptive-dialog>


text:
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { chainPropTypes } from '@material-ui/utils';
import withStyles from '../styles/withStyles';
import useTheme from '../styles/useTheme';
import { fade, lighten, darken } from '../styles/colorManipulator';
import useIsFocusVisible from '../utils/useIsFocusVisible';
import useEnhancedEffect from '../utils/useEnhancedEffect';
import ownerDocument from '../utils/ownerDocument';
import useEventCallback from '../utils/useEventCallback';
import useForkRef from '../utils/useForkRef';
import capitalize from '../utils/capitalize';
import useControlled from '../utils/useControlled';
import ValueLabel from './ValueLabel';

function asc(a, b) {
  return a - b;
}

function clamp(value, min, max) {
  return Math.min(Math.max(min, value), max);
}

function findClosest(values, currentValue) {
  const {
    index: closestIndex
  } = values.reduce((acc, value, index) => {
    const distance = Math.abs(currentValue - value);

    if (acc === null || distance < acc.distance || distance === acc.distance) {
      return {
        distance,
        index
      };
    }

    return acc;
  }, null);
  return closestIndex;
}

function trackFinger(event, touchId) {
  if (touchId.current !== undefined && event.changedTouches) {
    for (let i = 0; i < event.changedTouches.length; i += 1) {
      const touch = event.changedTouches[i];

      if (touch.identifier === touchId.current) {
        return {
          x: touch.clientX,
          y: touch.clientY
        };
      }
    }

    return false;
  }

  return {
    x: event.clientX,
    y: event.clientY
  };
}

function valueToPercent(value, min, max) {
  return (value - min) * 100 / (max - min);
}

function percentToValue(percent, min, max) {
  return (max - min) * percent + min;
}

function getDecimalPrecision(num) {
  // This handles the case when num is very small (0.00000001), js will turn this into 1e-8.
  // When num is bigger than 1 or less than -1 it won't get converted to this notation so it's fine.
  if (Math.abs(num) < 1) {
    const parts = num.toExponential().split('e-');
    const matissaDecimalPart = parts[0].split('.')[1];
    return (matissaDecimalPart ? matissaDecimalPart.length : 0) + parseInt(parts[1], 10);
  }

  const decimalPart = num.toString().split('.')[1];
  return decimalPart ? decimalPart.length : 0;
}

function roundValueToStep(value, step, min) {
  const nearest = Math.round((value - min) / step) * step + min;
  return Number(nearest.toFixed(getDecimalPrecision(step)));
}

function setValueIndex({
  values,
  source,
  newValue,
  index
}) {
  // Performance shortcut
  if (source[index] === newValue) {
    return source;
  }

  const output = values.slice();
  output[index] = newValue;
  return output;
}

function focusThumb({
  sliderRef,
  activeIndex,
  setActive
}) {
  const doc = ownerDocument(sliderRef.current);

  if (!sliderRef.current.contains(doc.activeElement) || Number(doc.activeElement.getAttribute('data-index')) !== activeIndex) {
    sliderRef.current.querySelector(`[role="slider"][data-index="${activeIndex}"]`).focus();
  }

  if (setActive) {
    setActive(activeIndex);
  }
}

const axisProps = {
  horizontal: {
    offset: percent => ({
      left: `${percent}%`
    }),
    leap: percent => ({
      width: `${percent}%`
    })
  },
  'horizontal-reverse': {
    offset: percent => ({
      right: `${percent}%`
    }),
    leap: percent => ({
      width: `${percent}%`
    })
  },
  vertical: {
    offset: percent => ({
      bottom: `${percent}%`
    }),
    leap: percent => ({
      height: `${percent}%`
    })
  }
};

const Identity = x => x; // TODO: remove support for Safari < 13.
// https://caniuse.com/#search=touch-action
//
// Safari, on iOS, supports touch action since v13.
// Over 80% of the iOS phones are compatible
// in August 2020.

let cachedSupportsTouchActionNone;

function doesSupportTouchActionNone() {
  if (cachedSupportsTouchActionNone === undefined) {
    const element = document.createElement('div');
    element.style.touchAction = 'none';
    document.body.appendChild(element);
    cachedSupportsTouchActionNone = window.getComputedStyle(element).touchAction === 'none';
    element.parentElement.removeChild(element);
  }

  return cachedSupportsTouchActionNone;
}

export const styles = theme => ({
  /* Styles applied to the root element. */
  root: {
    height: 2,
    width: '100%',
    boxSizing: 'content-box',
    padding: '13px 0',
    display: 'inline-block',
    position: 'relative',
    cursor: 'pointer',
    // Disable scroll capabilities.
    touchAction: 'none',
    color: theme.palette.primary.main,
    WebkitTapHighlightColor: 'transparent',
    '&$disabled': {
      pointerEvents: 'none',
      cursor: 'default',
      color: theme.palette.grey[400]
    },
    '&$vertical': {
      width: 2,
      height: '100%',
      padding: '0 13px'
    },
    // The primary input mechanism of the device includes a pointing device of limited accuracy.
    '@media (pointer: coarse)': {
      // Reach 42px touch target, about ~8mm on screen.
      padding: '20px 0',
      '&$vertical': {
        padding: '0 20px'
      }
    },
    '@media print': {
      colorAdjust: 'exact'
    }
  },

  /* Styles applied to the root element if `color="primary"`. */
  colorPrimary: {// TODO v5: move the style here
  },

  /* Styles applied to the root element if `color="secondary"`. */
  colorSecondary: {
    color: theme.palette.secondary.main
  },

  /* Styles applied to the root element if `marks` is provided with at least one label. */
  marked: {
    marginBottom: 20,
    '&$vertical': {
      marginBottom: 'auto',
      marginRight: 20
    }
  },

  /* Pseudo-class applied to the root element if `orientation="vertical"`. */
  vertical: {},

  /* Pseudo-class applied to the root and thumb element if `disabled={true}`. */
  disabled: {},

  /* Styles applied to the rail element. */
  rail: {
    display: 'block',
    position: 'absolute',
    width: '100%',
    height: 2,
    borderRadius: 1,
    backgroundColor: 'currentColor',
    opacity: 0.38,
    '$vertical &': {
      height: '100%',
      width: 2
    }
  },

  /* Styles applied to the track element. */
  track: {
    display: 'block',
    position: 'absolute',
    height: 2,
    borderRadius: 1,
    backgroundColor: 'currentColor',
    '$vertical &': {
      width: 2
    }
  },

  /* Styles applied to the track element if `track={false}`. */
  trackFalse: {
    '& $track': {
      display: 'none'
    }
  },

  /* Styles applied to the track element if `track="inverted"`. */
  trackInverted: {
    '& $track': {
      backgroundColor: // Same logic as the LinearProgress track color
      theme.palette.mode === 'light' ? lighten(theme.palette.primary.main, 0.62) : darken(theme.palette.primary.main, 0.5)
    },
    '& $rail': {
      opacity: 1
    }
  },

  /* Styles applied to the thumb element. */
  thumb: {
    position: 'absolute',
    width: 12,
    height: 12,
    marginLeft: -6,
    marginTop: -5,
    boxSizing: 'border-box',
    borderRadius: '50%',
    outline: 0,
    backgroundColor: 'currentColor',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    transition: theme.transitions.create(['box-shadow'], {
      duration: theme.transitions.duration.shortest
    }),
    '&::after': {
      position: 'absolute',
      content: '""',
      borderRadius: '50%',
      // reach 42px hit target (2 * 15 + thumb diameter)
      left: -15,
      top: -15,
      right: -15,
      bottom: -15
    },
    '&:hover, &$focusVisible': {
      boxShadow: `0px 0px 0px 8px ${fade(theme.palette.primary.main, 0.16)}`,
      '@media (hover: none)': {
        boxShadow: 'none'
      }
    },
    '&$active': {
      boxShadow: `0px 0px 0px 14px ${fade(theme.palette.primary.main, 0.16)}`
    },
    '&$disabled': {
      width: 8,
      height: 8,
      marginLeft: -4,
      marginTop: -3,
      '&:hover': {
        boxShadow: 'none'
      }
    },
    '$vertical &': {
      marginLeft: -5,
      marginBottom: -6
    },
    '$vertical &$disabled': {
      marginLeft: -3,
      marginBottom: -4
    }
  },

  /* Styles applied to the thumb element if `color="primary"`. */
  thumbColorPrimary: {// TODO v5: move the style here
  },

  /* Styles applied to the thumb element if `color="secondary"`. */
  thumbColorSecondary: {
    '&$focusVisible,&:hover': {
      boxShadow: `0px 0px 0px 8px ${fade(theme.palette.secondary.main, 0.16)}`
    },
    '&$active': {
      boxShadow: `0px 0px 0px 14px ${fade(theme.palette.secondary.main, 0.16)}`
    }
  },

  /* Pseudo-class applied to the thumb element if it's active. */
  active: {},

  /* Pseudo-class applied to the thumb element if keyboard focused. */
  focusVisible: {},

  /* Styles applied to the thumb label element. */
  valueLabel: {
    // IE 11 centering bug, to remove from the customization demos once no longer supported
    left: 'calc(-50% - 4px)'
  },

  /* Styles applied to the mark element. */
  mark: {
    position: 'absolute',
    width: 2,
    height: 2,
    borderRadius: 1,
    backgroundColor: 'currentColor'
  },

  /* Styles applied to the mark element if active (depending on the value). */
  markActive: {
    backgroundColor: theme.palette.background.paper,
    opacity: 0.8
  },

  /* Styles applied to the mark label element. */
  markLabel: _extends({}, theme.typography.body2, {
    color: theme.palette.text.secondary,
    position: 'absolute',
    top: 26,
    transform: 'translateX(-50%)',
    whiteSpace: 'nowrap',
    '$vertical &': {
      top: 'auto',
      left: 26,
      transform: 'translateY(50%)'
    },
    '@media (pointer: coarse)': {
      top: 40,
      '$vertical &': {
        left: 31
      }
    }
  }),

  /* Styles applied to the mark label element if active (depending on the value). */
  markLabelActive: {
    color: theme.palette.text.primary
  }
});

const Forward = ({
  children
}) => children;

const Slider = /*#__PURE__*/React.forwardRef(function Slider(props, ref) {
  const {
    'aria-label': ariaLabel,
    'aria-labelledby': ariaLabelledby,
    'aria-valuetext': ariaValuetext,
    classes,
    className,
    color = 'primary',
    component: Component = 'span',
    defaultValue,
    disabled = false,
    getAriaLabel,
    getAriaValueText,
    marks: marksProp = false,
    max = 100,
    min = 0,
    name,
    onChange,
    onChangeCommitted,
    onMouseDown,
    orientation = 'horizontal',
    scale = Identity,
    step = 1,
    ThumbComponent = 'span',
    track = 'normal',
    value: valueProp,
    ValueLabelComponent: ValueLabelComponentProp = ValueLabel,
    valueLabelDisplay = 'off',
    valueLabelFormat = Identity
  } = props,
        other = _objectWithoutPropertiesLoose(props, ["aria-label", "aria-labelledby", "aria-valuetext", "classes", "className", "color", "component", "defaultValue", "disabled", "getAriaLabel", "getAriaValueText", "marks", "max", "min", "name", "onChange", "onChangeCommitted", "onMouseDown", "orientation", "scale", "step", "ThumbComponent", "track", "value", "ValueLabelComponent", "valueLabelDisplay", "valueLabelFormat"]);

  const theme = useTheme();
  const touchId = React.useRef(); // We can't use the :active browser pseudo-classes.
  // - The active state isn't triggered when clicking on the rail.
  // - The active state isn't transfered when inversing a range slider.

  const [active, setActive] = React.useState(-1);
  const [open, setOpen] = React.useState(-1);
  const [valueDerived, setValueState] = useControlled({
    controlled: valueProp,
    default: defaultValue,
    name: 'Slider'
  });

  const handleChange = onChange && ((event, value) => {
    if (!(event instanceof Event)) event.persist(); // Redefine target to allow name and value to be read.
    // This allows seamless integration with the most popular form libraries.
    // https://github.com/mui-org/material-ui/issues/13485#issuecomment-676048492

    Object.defineProperty(event, 'target', {
      writable: true,
      value: {
        value,
        name
      }
    });
    onChange(event, value);
  });

  const range = Array.isArray(valueDerived);
  let values = range ? valueDerived.slice().sort(asc) : [valueDerived];
  values = values.map(value => clamp(value, min, max));
  const marks = marksProp === true && step !== null ? [...Array(Math.floor((max - min) / step) + 1)].map((_, index) => ({
    value: min + step * index
  })) : marksProp || [];
  const {
    isFocusVisibleRef,
    onBlur: handleBlurVisible,
    onFocus: handleFocusVisible,
    ref: focusVisibleRef
  } = useIsFocusVisible();
  const [focusVisible, setFocusVisible] = React.useState(-1);
  const sliderRef = React.useRef();
  const handleFocusRef = useForkRef(focusVisibleRef, sliderRef);
  const handleRef = useForkRef(ref, handleFocusRef);
  const handleFocus = useEventCallback(event => {
    const index = Number(event.currentTarget.getAttribute('data-index'));
    handleFocusVisible(event);

    if (isFocusVisibleRef.current === true) {
      setFocusVisible(index);
    }

    setOpen(index);
  });
  const handleBlur = useEventCallback(event => {
    handleBlurVisible(event);

    if (isFocusVisibleRef.current === false) {
      setFocusVisible(-1);
    }

    setOpen(-1);
  });
  const handleMouseOver = useEventCallback(event => {
    const index = Number(event.currentTarget.getAttribute('data-index'));
    setOpen(index);
  });
  const handleMouseLeave = useEventCallback(() => {
    setOpen(-1);
  });
  useEnhancedEffect(() => {
    if (disabled && sliderRef.current.contains(document.activeElement)) {
      // This is necessary because Firefox and Safari will keep focus
      // on a disabled element:
      // https://codesandbox.io/s/mui-pr-22247-forked-h151h?file=/src/App.js
      document.activeElement.blur();
    }
  }, [disabled]);

  if (disabled && active !== -1) {
    setActive(-1);
  }

  if (disabled && focusVisible !== -1) {
    setFocusVisible(-1);
  }

  const isRtl = theme.direction === 'rtl';
  const handleKeyDown = useEventCallback(event => {
    const index = Number(event.currentTarget.getAttribute('data-index'));
    const value = values[index];
    const tenPercents = (max - min) / 10;
    const marksValues = marks.map(mark => mark.value);
    const marksIndex = marksValues.indexOf(value);
    let newValue;
    const increaseKey = isRtl ? 'ArrowLeft' : 'ArrowRight';
    const decreaseKey = isRtl ? 'ArrowRight' : 'ArrowLeft';

    switch (event.key) {
      case 'Home':
        newValue = min;
        break;

      case 'End':
        newValue = max;
        break;

      case 'PageUp':
        if (step) {
          newValue = value + tenPercents;
        }

        break;

      case 'PageDown':
        if (step) {
          newValue = value - tenPercents;
        }

        break;

      case increaseKey:
      case 'ArrowUp':
        if (step) {
          newValue = value + step;
        } else {
          newValue = marksValues[marksIndex + 1] || marksValues[marksValues.length - 1];
        }

        break;

      case decreaseKey:
      case 'ArrowDown':
        if (step) {
          newValue = value - step;
        } else {
          newValue = marksValues[marksIndex - 1] || marksValues[0];
        }

        break;

      default:
        return;
    } // Prevent scroll of the page

    event.preventDefault();

    if (step) {
      newValue = roundValueToStep(newValue, step, min);
    }

    newValue = clamp(newValue, min, max);

    if (range) {
      const previousValue = newValue;
      newValue = setValueIndex({
        values,
        source: valueDerived,
        newValue,
        index
      }).sort(asc);
      focusThumb({
        sliderRef,
        activeIndex: newValue.indexOf(previousValue)
      });
    }

    setValueState(newValue);
    setFocusVisible(index);

    if (handleChange) {
      handleChange(event, newValue);
    }

    if (onChangeCommitted) {
      onChangeCommitted(event, newValue);
    }
  });
  const previousIndex = React.useRef();
  let axis = orientation;

  if (isRtl && orientation !== "vertical") {
    axis += '-reverse';
  }

  const getFingerNewValue = ({
    finger,
    move = false,
    values: values2,
    source
  }) => {
    const {
      current: slider
    } = sliderRef;
    const {
      width,
      height,
      bottom,
      left
    } = slider.getBoundingClientRect();
    let percent;

    if (axis.indexOf('vertical') === 0) {
      percent = (bottom - finger.y) / height;
    } else {
      percent = (finger.x - left) / width;
    }

    if (axis.indexOf('-reverse') !== -1) {
      percent = 1 - percent;
    }

    let newValue;
    newValue = percentToValue(percent, min, max);

    if (step) {
      newValue = roundValueToStep(newValue, step, min);
    } else {
      const marksValues = marks.map(mark => mark.value);
      const closestIndex = findClosest(marksValues, newValue);
      newValue = marksValues[closestIndex];
    }

    newValue = clamp(newValue, min, max);
    let activeIndex = 0;

    if (range) {
      if (!move) {
        activeIndex = findClosest(values2, newValue);
      } else {
        activeIndex = previousIndex.current;
      }

      const previousValue = newValue;
      newValue = setValueIndex({
        values: values2,
        source,
        newValue,
        index: activeIndex
      }).sort(asc);
      activeIndex = newValue.indexOf(previousValue);
      previousIndex.current = activeIndex;
    }

    return {
      newValue,
      activeIndex
    };
  };

  const handleTouchMove = useEventCallback(nativeEvent => {
    const finger = trackFinger(nativeEvent, touchId);

    if (!finger) {
      return;
    } // Cancel move in case some other element consumed a mouseup event and it was not fired.

    if (nativeEvent.type === 'mousemove' && nativeEvent.buttons === 0) {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      handleTouchEnd(nativeEvent);
      return;
    }

    const {
      newValue,
      activeIndex
    } = getFingerNewValue({
      finger,
      move: true,
      values,
      source: valueDerived
    });
    focusThumb({
      sliderRef,
      activeIndex,
      setActive
    });
    setValueState(newValue);

    if (handleChange) {
      handleChange(nativeEvent, newValue);
    }
  });
  const handleTouchEnd = useEventCallback(nativeEvent => {
    const finger = trackFinger(nativeEvent, touchId);

    if (!finger) {
      return;
    }

    const {
      newValue
    } = getFingerNewValue({
      finger,
      values,
      source: valueDerived
    });
    setActive(-1);

    if (nativeEvent.type === 'touchend') {
      setOpen(-1);
    }

    if (onChangeCommitted) {
      onChangeCommitted(nativeEvent, newValue);
    }

    touchId.current = undefined; // eslint-disable-next-line @typescript-eslint/no-use-before-define

    stopListening();
  });
  const handleTouchStart = useEventCallback(event => {
    // If touch-action: none; is not supported we need to prevent the scroll manually.
    if (!doesSupportTouchActionNone()) {
      event.preventDefault();
    }

    const touch = event.changedTouches[0];

    if (touch != null) {
      // A number that uniquely identifies the current finger in the touch session.
      touchId.current = touch.identifier;
    }

    const finger = trackFinger(event, touchId);
    const {
      newValue,
      activeIndex
    } = getFingerNewValue({
      finger,
      values,
      source: valueDerived
    });
    focusThumb({
      sliderRef,
      activeIndex,
      setActive
    });
    setValueState(newValue);

    if (handleChange) {
      handleChange(event, newValue);
    }

    const doc = ownerDocument(sliderRef.current);
    doc.addEventListener('touchmove', handleTouchMove);
    doc.addEventListener('touchend', handleTouchEnd);
  });
  const stopListening = React.useCallback(() => {
    const doc = ownerDocument(sliderRef.current);
    doc.removeEventListener('mousemove', handleTouchMove);
    doc.removeEventListener('mouseup', handleTouchEnd);
    doc.removeEventListener('touchmove', handleTouchMove);
    doc.removeEventListener('touchend', handleTouchEnd);
  }, [handleTouchEnd, handleTouchMove]);
  React.useEffect(() => {
    const {
      current: slider
    } = sliderRef;
    slider.addEventListener('touchstart', handleTouchStart, {
      passive: doesSupportTouchActionNone()
    });
    return () => {
      slider.removeEventListener('touchstart', handleTouchStart, {
        passive: doesSupportTouchActionNone()
      });
      stopListening();
    };
  }, [stopListening, handleTouchStart]);
  React.useEffect(() => {
    if (disabled) {
      stopListening();
    }
  }, [disabled, stopListening]);
  const handleMouseDown = useEventCallback(event => {
    if (onMouseDown) {
      onMouseDown(event);
    } // Only handle left clicks

    if (event.button !== 0) {
      return;
    }

    event.preventDefault();
    const finger = trackFinger(event, touchId);
    const {
      newValue,
      activeIndex
    } = getFingerNewValue({
      finger,
      values,
      source: valueDerived
    });
    focusThumb({
      sliderRef,
      activeIndex,
      setActive
    });
    setValueState(newValue);

    if (handleChange) {
      handleChange(event, newValue);
    }

    const doc = ownerDocument(sliderRef.current);
    doc.addEventListener('mousemove', handleTouchMove);
    doc.addEventListener('mouseup', handleTouchEnd);
  });
  const trackOffset = valueToPercent(range ? values[0] : min, min, max);
  const trackLeap = valueToPercent(values[values.length - 1], min, max) - trackOffset;

  const trackStyle = _extends({}, axisProps[axis].offset(trackOffset), axisProps[axis].leap(trackLeap));

  return /*#__PURE__*/React.createElement(Component, _extends({
    ref: handleRef,
    className: clsx(classes.root, classes[`color${capitalize(color)}`], className, disabled && classes.disabled, marks.length > 0 && marks.some(mark => mark.label) && classes.marked, track === false && classes.trackFalse, orientation === 'vertical' && classes.vertical, track === 'inverted' && classes.trackInverted),
    onMouseDown: handleMouseDown
  }, other), /*#__PURE__*/React.createElement("span", {
    className: classes.rail
  }), /*#__PURE__*/React.createElement("span", {
    className: classes.track,
    style: trackStyle
  }), /*#__PURE__*/React.createElement("input", {
    value: values.join(','),
    name: name,
    type: "hidden"
  }), marks.map((mark, index) => {
    const percent = valueToPercent(mark.value, min, max);
    const style = axisProps[axis].offset(percent);
    let markActive;

    if (track === false) {
      markActive = values.indexOf(mark.value) !== -1;
    } else {
      markActive = track === 'normal' && (range ? mark.value >= values[0] && mark.value <= values[values.length - 1] : mark.value <= values[0]) || track === 'inverted' && (range ? mark.value <= values[0] || mark.value >= values[values.length - 1] : mark.value >= values[0]);
    }

    return /*#__PURE__*/React.createElement(React.Fragment, {
      key: mark.value
    }, /*#__PURE__*/React.createElement("span", {
      style: style,
      "data-index": index,
      className: clsx(classes.mark, markActive && classes.markActive)
    }), mark.label != null ? /*#__PURE__*/React.createElement("span", {
      "aria-hidden": true,
      "data-index": index,
      style: style,
      className: clsx(classes.markLabel, markActive && classes.markLabelActive)
    }, mark.label) : null);
  }), values.map((value, index) => {
    const percent = valueToPercent(value, min, max);
    const style = axisProps[axis].offset(percent);
    const ValueLabelComponent = valueLabelDisplay === 'off' ? Forward : ValueLabelComponentProp;
    return /*#__PURE__*/React.createElement(ValueLabelComponent, {
      key: index,
      valueLabelFormat: valueLabelFormat,
      valueLabelDisplay: valueLabelDisplay,
      className: classes.valueLabel,
      value: typeof valueLabelFormat === 'function' ? valueLabelFormat(scale(value), index) : valueLabelFormat,
      index: index,
      open: open === index || active === index || valueLabelDisplay === 'on',
      disabled: disabled
    }, /*#__PURE__*/React.createElement(ThumbComponent, {
      className: clsx(classes.thumb, classes[`thumbColor${capitalize(color)}`], active === index && classes.active, disabled && classes.disabled, focusVisible === index && classes.focusVisible),
      tabIndex: disabled ? null : 0,
      role: "slider",
      style: style,
      "data-index": index,
      "aria-label": getAriaLabel ? getAriaLabel(index) : ariaLabel,
      "aria-labelledby": ariaLabelledby,
      "aria-orientation": orientation,
      "aria-valuemax": scale(max),
      "aria-valuemin": scale(min),
      "aria-valuenow": scale(value),
      "aria-valuetext": getAriaValueText ? getAriaValueText(scale(value), index) : ariaValuetext,
      onKeyDown: handleKeyDown,
      onFocus: handleFocus,
      onBlur: handleBlur,
      onMouseOver: handleMouseOver,
      onMouseLeave: handleMouseLeave
    }));
  }));
});
process.env.NODE_ENV !== "production" ? Slider.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * The label of the slider.
   */
  'aria-label': chainPropTypes(PropTypes.string, props => {
    const range = Array.isArray(props.value || props.defaultValue);

    if (range && props['aria-label'] != null) {
      return new Error('Material-UI: You need to use the `getAriaLabel` prop instead of `aria-label` when using a range slider.');
    }

    return null;
  }),

  /**
   * The id of the element containing a label for the slider.
   */
  'aria-labelledby': PropTypes.string,

  /**
   * A string value that provides a user-friendly name for the current value of the slider.
   */
  'aria-valuetext': chainPropTypes(PropTypes.string, props => {
    const range = Array.isArray(props.value || props.defaultValue);

    if (range && props['aria-valuetext'] != null) {
      return new Error('Material-UI: You need to use the `getAriaValueText` prop instead of `aria-valuetext` when using a range slider.');
    }

    return null;
  }),

  /**
   * @ignore
   */
  children: PropTypes.node,

  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,

  /**
   * @ignore
   */
  className: PropTypes.string,

  /**
   * The color of the component. It supports those theme colors that make sense for this component.
   * @default 'primary'
   */
  color: PropTypes.oneOf(['primary', 'secondary']),

  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,

  /**
   * The default element value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]),

  /**
   * If `true`, the slider will be disabled.
   * @default false
   */
  disabled: PropTypes.bool,

  /**
   * Accepts a function which returns a string value that provides a user-friendly name for the thumb labels of the slider.
   *
   * @param {number} index The thumb label's index to format.
   * @returns {string}
   */
  getAriaLabel: PropTypes.func,

  /**
   * Accepts a function which returns a string value that provides a user-friendly name for the current value of the slider.
   *
   * @param {number} value The thumb label's value to format.
   * @param {number} index The thumb label's index to format.
   * @returns {string}
   */
  getAriaValueText: PropTypes.func,

  /**
   * Marks indicate predetermined values to which the user can move the slider.
   * If `true` the marks will be spaced according the value of the `step` prop.
   * If an array, it should contain objects with `value` and an optional `label` keys.
   * @default false
   */
  marks: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.shape({
    label: PropTypes.node,
    value: PropTypes.number.isRequired
  })), PropTypes.bool]),

  /**
   * The maximum allowed value of the slider.
   * Should not be equal to min.
   * @default 100
   */
  max: PropTypes.number,

  /**
   * The minimum allowed value of the slider.
   * Should not be equal to max.
   * @default 0
   */
  min: PropTypes.number,

  /**
   * Name attribute of the hidden `input` element.
   */
  name: PropTypes.string,

  /**
   * Callback function that is fired when the slider's value changed.
   *
   * @param {object} event The event source of the callback. **Warning**: This is a generic event not a change event.
   * @param {number | number[]} value The new value.
   */
  onChange: PropTypes.func,

  /**
   * Callback function that is fired when the `mouseup` is triggered.
   *
   * @param {object} event The event source of the callback. **Warning**: This is a generic event not a change event.
   * @param {number | number[]} value The new value.
   */
  onChangeCommitted: PropTypes.func,

  /**
   * @ignore
   */
  onMouseDown: PropTypes.func,

  /**
   * The slider orientation.
   * @default 'horizontal'
   */
  orientation: PropTypes.oneOf(['horizontal', 'vertical']),

  /**
   * A transformation function, to change the scale of the slider.
   * @default (x) => x
   */
  scale: PropTypes.func,

  /**
   * The granularity with which the slider can step through values. (A "discrete" slider.)
   * The `min` prop serves as the origin for the valid values.
   * We recommend (max - min) to be evenly divisible by the step.
   *
   * When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop.
   * @default 1
   */
  step: PropTypes.number,

  /**
   * The component used to display the value label.
   * @default 'span'
   */
  ThumbComponent: PropTypes.elementType,

  /**
   * The track presentation:
   *
   * - `normal` the track will render a bar representing the slider value.
   * - `inverted` the track will render a bar representing the remaining slider value.
   * - `false` the track will render without a bar.
   * @default 'normal'
   */
  track: PropTypes.oneOf(['inverted', 'normal', false]),

  /**
   * The value of the slider.
   * For ranged sliders, provide an array with two values.
   */
  value: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]),

  /**
   * The value label component.
   * @default ValueLabel
   */
  ValueLabelComponent: PropTypes.elementType,

  /**
   * Controls when the value label is displayed:
   *
   * - `auto` the value label will display when the thumb is hovered or focused.
   * - `on` will display persistently.
   * - `off` will never display.
   * @default 'off'
   */
  valueLabelDisplay: PropTypes.oneOf(['auto', 'off', 'on']),

  /**
   * The format function the value label's value.
   *
   * When a function is provided, it should have the following signature:
   *
   * - {number} value The value label's value to format
   * - {number} index The value label's index to format
   * @default (x) => x
   */
  valueLabelFormat: PropTypes.oneOfType([PropTypes.func, PropTypes.string])
} : void 0;
export default withStyles(styles, {
  name: 'MuiSlider'
})(Slider);


text:
"""Momentum for TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
from tensorflow.python.training import optimizer
from tensorflow.python.training import training_ops

class MomentumOptimizer(optimizer.Optimizer):
  """Optimizer that implements the Momentum algorithm.

  @@__init__
  """

  def __init__(self, learning_rate, momentum,
               use_locking=False, name="Momentum"):
    """Construct a new Momentum optimizer.

    Args:
      learning_rate: A `Tensor` or a floating point value.  The learning rate.
      momentum: A `Tensor` or a floating point value.  The momentum.
      use_locking: If `True` use locks for update operations.
      name: Optional name prefix for the operations created when applying
        gradients.  Defaults to "Momentum".
    """
    super(MomentumOptimizer, self).__init__(use_locking, name)
    self._learning_rate = learning_rate
    self._momentum = momentum

  def _create_slots(self, var_list):
    for v in var_list:
      self._zeros_slot(v, "momentum", self._name)

  def _prepare(self):
    self._learning_rate_tensor = ops.convert_to_tensor(self._learning_rate,
                                                       name="learning_rate")
    self._momentum_tensor = ops.convert_to_tensor(self._momentum,
                                                  name="momentum")

  def _apply_dense(self, grad, var):
    mom = self.get_slot(var, "momentum")
    return training_ops.apply_momentum(
        var, mom,
        math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),
        grad,
        math_ops.cast(self._momentum_tensor, var.dtype.base_dtype),
        use_locking=self._use_locking).op

  def _apply_sparse(self, grad, var):
    mom = self.get_slot(var, "momentum")
    return training_ops.sparse_apply_momentum(
        var, mom,
        math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),
        grad.values, grad.indices,
        math_ops.cast(self._momentum_tensor, var.dtype.base_dtype),
        use_locking=self._use_locking).op


text:
@implementation BuildFactory

- (id)initWithToken:(NSString*)token
{
    self = [self init];
    if (self) {
        self.token = token;
    }

    return self;
}

- (void)fetchWithSuccess:(FetchBuildCallback)success failure:(void (^)(NSError *)) failure
{
    [NSException raise:NSInternalInconsistencyException format:@"Must be called from subclass: %@", NSStringFromSelector(_cmd)];
}

- (NSArray *)removeExistingBuilds:(NSArray *)retrievedBuilds
{
    NSMutableSet *savedBuilds = [NSMutableSet setWithArray: [Build saved]];

    // Remove saved builds
    NSArray *exclusiveBuilds = _.filter(retrievedBuilds, ^BOOL(Build* build) {
        NSInteger overlaps = [[savedBuilds objectsPassingTest: ^BOOL(id savedBuild, BOOL *stop) {
            return [savedBuild isSimilarTo:build];
        }] count];

        return overlaps == 0;
    });

    // Sort by project
    NSMutableArray *array = [NSMutableArray arrayWithArray:exclusiveBuilds];
    [array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [[obj1 project] localizedCaseInsensitiveCompare:[obj2 project]];
    }];

    return array;
}

@end


text:
import unittest
import sys
import traceback

import testcases
from vm import VM
from vmhost import VMhost
from vmpoolstate import VMPoolState
from vmpoolstateerrors import VMPoolStateSanityError
from aspiers import VMPoolAdamPathFinder

#STRATEGY = VMPoolShortestPathFinder
STRATEGY = VMPoolAdamPathFinder

testcase = 'simple_swap'
if len(sys.argv) == 2:
    testcase = sys.argv[1]
testcase = getattr(testcases.fixed, "case_%s" % testcase)

stateA, stateB, expected_path = testcase()
stateA = VMPoolState().init_by_vmhosts(stateA)
stateB = VMPoolState().init_by_vmhosts(stateB)

current_state = stateA

path_finder = STRATEGY(current_state, stateB)
print path_finder.path.challenge_visualization(10, 80)

first = True

while True:
    if first:
        msg = "Enter migration " \
              "(VM name and destination host separated by a space) > "
        first = False
    else:
        msg = "Enter migration > "
    command = raw_input(msg)
    vm_name, to_host_name = command.split()
    to_host = VMhost.vmhosts[to_host_name]
    try:
        current_state = \
            current_state.check_migration_sane(vm_name, to_host)
    except VMPoolStateSanityError, exc:
        print exc
        print

    path_finder = STRATEGY(current_state, stateB)
    print path_finder.path.challenge_visualization(10, 80)


text:
<!doctype html>
<html>
	<head>
		<title>`paper-datatable-card` playground</title>
		<script src="../../../webcomponentsjs/webcomponents-lite.js"></script>
		<link rel="import" href="../../../polymer/polymer.html">
		<link rel="import" href="../../paper-datatable-card.html">
		<link rel="import" href="../../paper-datatable.html">
		<link rel="import" href="../../docs/documentation-menu.html">

	</head>
	<body>

		<template is="dom-bind" id="app">
			<demo-menu>
				<style is="custom-style">
					body{
						background: #f5f5f5;
					}
				</style>

				<paper-datatable-card id="datatableCard" header="Document library" page-size="10" data-source="{{data}}" id-property="i" selected-ids="{{selectedIds}}">
					<div toolbar-main>
						<paper-icon-button icon="add" on-tap="addNew"></paper-icon-button>
					</div>
					<div toolbar-select>
						<paper-icon-button icon="delete"></paper-icon-button>
					</div>
					<paper-datatable selectable multi-selection>
						<paper-datatable-column header="ID" property="i" type="String" tooltip="Some title" sortable align="center" style="min-width: 40px" sorted></paper-datatable-column>
						<paper-datatable-column header="Author" property="author" tooltip="The total amount of..." style="min-width: 500px" default='{"first": "", "last": ""}' editable>
							<template>
								<paper-input value="{{value.first}}" no-label-float style="display:inline-block;width:49%;"></paper-input>
								<paper-input value="{{value.last}}" no-label-float style="display:inline-block;width:49%;"></paper-input>
							</template>
						</paper-datatable-column>
						<paper-datatable-column header="Document title" property="title" type="String" tooltip="Some title" sortable style="width: 99%"></paper-datatable-column>
						<paper-datatable-column header="Rating" property="rating" type="Number" tooltip="The total amount of..." sortable style="min-width: 200px" editable>
							<template>
								<paper-input value="{{value}}" no-label-float></paper-input>
							</template>
						</paper-datatable-column>
						<paper-datatable-column property="reserved" header="Reserved" type="boolean" default="false" style="min-width: 100px" cell-style="padding-left:40px;" align="center" editable>
							<template>
								<paper-checkbox checked="{{value}}"></paper-checkbox>
							</template>
						</paper-datatable-column>
					</paper-datatable>
				</paper-datatable-card>

				<div style="padding:20px">
					Selected IDs: {{outputSelectedIds(selectedIds.splices)}}
				</div>
			</demo-menu>
		</template>

		<script>
			var app = document.querySelector('#app');

			var myData = [];
			for (var i=0; i<142; i++) {
				var id = i*10000+Math.round(Math.random() * 500);
				var rating = Math.round(Math.random() * 2000)+1000;
				myData.push({
					i: i,
					title: "title"+id,
					rating: rating,
					author: {
						first: "David",
						last: "Mulder "+ i
					},
					reserved: (Math.random() > 0.9 ? true : undefined)
				});
			}
			window.myData = myData;

			app.data = {
				get: function(sort, page, pageSize){
					console.log('just once? :/');
					return new Promise(function(resolve, reject){
						myData.sort(function(a,b){
							if(sort.direction == "desc"){
								var c = a;
								a = b;
								b = c;
							}
							if(a[sort.property] > b[sort.property]) return 1;
							if(a[sort.property] < b[sort.property]) return -1;
							return 0;
						});
						resolve(myData.slice((page-1)*pageSize, page*pageSize));
					});
				},
				set: function(item, property, value){
					return new Promise(function(resolve, reject){
						console.info("a save was triggered", [item, property, value]);
						if(item.id === '__new__'){
							//validate item, if invalid (and thus not savable yet) reject, otherwise return it's new id
							console.warn('this is for the time being deprecated');
							/*
							if(item.author.first.length > 0 && item.author.last.length > 0){
								console.log('trigger save');
								var id = Math.round(Math.random() * 10000);

								item.id = id;
								myData.push(item);
								app.set('data.length', myData.length);
								resolve(id);
							}else{
								console.log('no luck yet');
								reject();
							}*/
						}else{
							var myItem = myData.find(function(thisItem){
								return thisItem.id == item.id;
							});
							myItem[property] = value;
							resolve(true);
						}
					});

				},
				length:myData.length
			};

			app.addNew = function(){
				this.$.datatableCard.addNew();
			};

			app.outputSelectedIds = function(){
				return app.selectedIds.join(', ');
			}

		</script>

	</body>
</html>


text:
<?php
// (C) Catchoom Technologies S.L.
// Licensed under the MIT license.
// https://github.com/Catchoom/craftar-php/blob/master/LICENSE
// All warranties and liabilities are disclaimed.

namespace craftar;

require_once("Request.php");

class Recognition extends Request{

    const API_VERSION_0 = "v0";
    const API_VERSION_1 = "v1";

    private $token;
    private $apiVersion;
    private $host;

    public function __construct($apiVersion, $token, $host = 'https://search.craftar.net'){
        $this->token = $token;
        $this->apiVersion = $apiVersion;
        $this->host = $host;
    }

    public function search($queryImage, $options = array()){
        $url = "{$this->host}/{$this->apiVersion}/search";
        $data= array('token' => $this->token, 'image' => $this->file_create($queryImage));
        return $this->multipartPost($url, array_merge($data, $options));
    }

}


text: There is no solution to this program, it's for you to try it out!


text:
dol-monitor-service
===================

Dead or alive detection service for Language grid.


text:
import React from 'react'
import {shallow} from 'enzyme'
import PolluterMarker from './PolluterMarker'

describe('components', () => {
  describe('PolluterMarker', () => {
    it('Should have text inside with 0 end', () => {
      const wrapper = shallow(<PolluterMarker />)

      expect(wrapper.text()).toBe('Polluter Marker - 0')
    })

  })
})


text:
from netaddr import IPAddress
from netaddr import IPNetwork

from nailgun import consts
from nailgun.db.sqlalchemy.models import Cluster
from nailgun.db.sqlalchemy.models import NetworkGroup
from nailgun.db.sqlalchemy.models import NeutronConfig
from nailgun.db.sqlalchemy.models import NovaNetworkConfig
from nailgun.test.base import BaseIntegrationTest

class TestNetworkChecking(BaseIntegrationTest):

    def find_net_by_name(self, name):
        for net in self.nets['networks']:
            if net['name'] == name:
                return net

    def check_result_format(self, task, cluster_id):
        if task.get('result'):
            result = task['result']
            self.assertIsInstance(result, list)
            ng_fields = \
                NetworkGroup.__mapper__.columns.keys() + ["ip_ranges"]
            cluster_db = self.db.query(Cluster).get(cluster_id)
            ng_fields += NeutronConfig.__mapper__.columns.keys() \
                if cluster_db.net_provider == 'neutron' else \
                NovaNetworkConfig.__mapper__.columns.keys()
            for res in result:
                if 'ids' in res:
                    self.assertIsInstance(res['ids'], list)
                if 'errors' in res:
                    self.assertIsInstance(res['errors'], list)
                    for f in res['errors']:
                        self.assertIn(f, ng_fields)

    def set_cluster_changes_w_error(self, cluster_id):
        resp = self.env.cluster_changes_put(cluster_id,
                                            expect_errors=True)
        self.assertEqual(resp.status_code, 200)
        task = resp.json_body
        self.assertEqual(task['status'], consts.TASK_STATUSES.error)
        self.assertEqual(task['progress'], 100)
        self.assertEqual(task['name'], consts.TASK_NAMES.deploy)
        self.check_result_format(task, cluster_id)
        return task

    def update_nova_networks_w_error(self, cluster_id, nets):
        resp = self.env.nova_networks_put(cluster_id, nets,
                                          expect_errors=True)
        self.assertEqual(resp.status_code, 200)
        task = resp.json_body
        self.assertEqual(task['status'], consts.TASK_STATUSES.error)
        self.assertEqual(task['progress'], 100)
        self.assertEqual(task['name'], consts.TASK_NAMES.check_networks)
        self.check_result_format(task, cluster_id)
        return task

    def update_nova_networks_success(self, cluster_id, nets):
        resp = self.env.nova_networks_put(cluster_id, nets)
        self.assertEqual(resp.status_code, 200)
        task = resp.json_body
        self.assertEqual(task['status'], consts.TASK_STATUSES.ready)
        self.assertEqual(task['progress'], 100)
        self.assertEqual(task['name'], consts.TASK_NAMES.check_networks)
        return task

    def update_neutron_networks_w_error(self, cluster_id, nets):
        resp = self.env.neutron_networks_put(cluster_id, nets,
                                             expect_errors=True)
        self.assertEqual(resp.status_code, 200)
        task = resp.json_body
        self.assertEqual(task['status'], consts.TASK_STATUSES.error)
        self.assertEqual(task['progress'], 100)
        self.assertEqual(task['name'], consts.TASK_NAMES.check_networks)
        self.check_result_format(task, cluster_id)
        return task

    def update_neutron_networks_success(self, cluster_id, nets):
        resp = self.env.neutron_networks_put(cluster_id, nets)
        self.assertEqual(resp.status_code, 200)
        task = resp.json_body
        self.assertEqual(task['status'], consts.TASK_STATUSES.ready)
        self.assertEqual(task['progress'], 100)
        self.assertEqual(task['name'], consts.TASK_NAMES.check_networks)
        return task

class TestNovaHandlers(TestNetworkChecking):

    def setUp(self):
        super(TestNovaHandlers, self).setUp()
        meta = self.env.default_metadata()
        self.env.set_interfaces_in_meta(meta, [
            {"name": "eth0", "mac": "00:00:00:00:00:66"},
            {"name": "eth1", "mac": "00:00:00:00:00:77"}])
        self.env.create(
            cluster_kwargs={},
            nodes_kwargs=[
                {"api": True,
                 "meta": meta,
                 "pending_addition": True},
            ]
        )
        self.cluster = self.env.clusters[0]
        resp = self.env.nova_networks_get(self.cluster.id)
        self.nets = resp.json_body

    def test_network_checking(self):
        self.update_nova_networks_success(self.cluster.id, self.nets)

        ngs_created = self.db.query(NetworkGroup).filter(
            NetworkGroup.name.in_([n['name'] for n in self.nets['networks']])
        ).all()
        self.assertEqual(len(ngs_created), len(self.nets['networks']))

    def test_network_checking_fails_if_admin_intersection(self):
        admin_ng = self.env.network_manager.get_admin_network_group()
        self.nets['networking_parameters']["fixed_networks_cidr"] = \
            admin_ng.cidr

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertIn(
            "Address space intersection between networks:\n",
            task['message'])
        self.assertIn("admin (PXE)", task['message'])
        self.assertIn("fixed", task['message'])

    def test_network_checking_fails_if_admin_intersection_ip_range(self):
        admin_ng = self.env.network_manager.get_admin_network_group()
        cidr = IPNetwork(admin_ng.cidr)
        flt_r0 = str(IPAddress(cidr.first + 2))
        flt_r1 = str(IPAddress(cidr.last))
        self.nets['networking_parameters']['floating_ranges'] = \
            [[flt_r0, flt_r1]]

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            "Address space intersection between floating range '{0}-{1}' and "
            "'admin (PXE)' network.".format(flt_r0, flt_r1),
            task['message'])

    def test_network_checking_fails_if_networks_cidr_intersection(self):
        self.find_net_by_name('management')["cidr"] = \
            self.find_net_by_name('storage')["cidr"]

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertIn(
            "Address space intersection between networks:\n",
            task['message'])
        self.assertIn("management", task['message'])
        self.assertIn("storage", task['message'])

    def test_network_checking_fails_if_untagged_intersection(self):
        self.find_net_by_name('management')["vlan_start"] = None
        self.env.nova_networks_put(self.cluster.id, self.nets)

        task = self.set_cluster_changes_w_error(self.cluster.id)
        self.assertIn(
            'Some untagged networks are assigned to the same physical '
            'interface. You should assign them to different physical '
            'interfaces. Affected:\n',
            task['message'])
        self.assertIn('"management"', task['message'])
        self.assertIn(' networks at node "Untitled', task['message'])

    def test_network_checking_fails_if_networks_cidr_range_intersection(self):
        self.find_net_by_name('public')["ip_ranges"] = \
            [['192.18.17.65', '192.18.17.143']]
        self.find_net_by_name('public')["gateway"] = '192.18.17.1'
        self.find_net_by_name('public')["cidr"] = '192.18.17.0/24'
        self.find_net_by_name('management')["cidr"] = '192.18.17.0/25'

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertIn(
            "Address space intersection between networks:\n",
            task['message'])
        self.assertIn("public", task['message'])
        self.assertIn("management", task['message'])

    def test_network_checking_no_public_floating_ranges_intersection(self):
        self.find_net_by_name('public')["ip_ranges"] = \
            [['192.18.17.5', '192.18.17.43'],
             ['192.18.17.59', '192.18.17.90']]
        self.nets['networking_parameters']["floating_ranges"] = \
            [['192.18.17.125', '192.18.17.143'],
             ['192.18.17.159', '192.18.17.190']]
        self.find_net_by_name('public')["gateway"] = '192.18.17.1'
        self.find_net_by_name('public')["cidr"] = '192.18.17.0/24'

        self.update_nova_networks_success(self.cluster.id, self.nets)

    def test_network_checking_fails_if_public_ranges_intersection(self):
        self.find_net_by_name('public')["ip_ranges"] = \
            [['192.18.17.65', '192.18.17.123'],
             ['192.18.17.99', '192.18.17.129']]
        self.find_net_by_name('public')["gateway"] = '192.18.17.1'
        self.find_net_by_name('public')["cidr"] = '192.18.17.0/24'

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address space intersection between ranges of public network."
        )

    def test_network_checking_fails_if_public_gateway_not_in_cidr(self):
        self.find_net_by_name('public')["ip_ranges"] = \
            [['192.18.17.5', '192.18.17.43'],
             ['192.18.17.59', '192.18.17.90']]
        self.find_net_by_name('public')["gateway"] = '192.18.18.1'
        self.find_net_by_name('public')["cidr"] = '192.18.18.0/24'

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Public gateway and public ranges are not in one CIDR."
        )

    def test_network_checking_fails_if_public_gateway_range_intersection(self):
        self.find_net_by_name('public')["ip_ranges"] = \
            [['192.18.17.5', '192.18.17.43'],
             ['192.18.17.59', '192.18.17.90']]
        self.find_net_by_name('public')["gateway"] = '192.18.17.77'
        self.find_net_by_name('public')["cidr"] = '192.18.17.0/24'

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address intersection between public gateway and IP range of "
            "public network."
        )

        self.find_net_by_name('public')["ip_ranges"] = \
            [['192.18.17.5', '192.18.17.99']]
        self.find_net_by_name('public')["gateway"] = '192.18.17.55'

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address intersection between public gateway and IP range of "
            "public network."
        )

    def test_network_checking_fails_if_floating_ranges_intersection(self):
        self.nets['networking_parameters']["floating_ranges"] = \
            [['192.18.17.129', '192.18.17.143'],
             ['192.18.17.133', '192.18.17.190']]

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address space intersection between ranges of floating network."
        )

    def test_network_checking_fails_if_vlan_ids_intersection(self):
        self.find_net_by_name('public')["vlan_start"] = 111
        self.find_net_by_name('management')["vlan_start"] = 111

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertIn(
            " networks use the same VLAN ID(s). "
            "You should assign different VLAN IDs to every network.",
            task['message'])
        self.assertIn("management", task['message'])
        self.assertIn("public", task['message'])

    def test_network_checking_fails_if_vlan_id_in_fixed_vlan_range(self):
        self.nets['networking_parameters']['net_manager'] = 'VLANManager'
        self.find_net_by_name('public')["vlan_start"] = 1111
        self.nets['networking_parameters']['fixed_networks_vlan_start'] = \
            1100
        self.nets['networking_parameters']['fixed_networks_amount'] = 20

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertIn(
            " networks use the same VLAN ID(s). "
            "You should assign different VLAN IDs to every network.",
            task['message'])
        self.assertIn("fixed", task['message'])
        self.assertIn("public", task['message'])

    def test_network_checking_fails_if_vlan_id_not_in_allowed_range(self):
        self.find_net_by_name('public')["vlan_start"] = 5555

        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "VLAN ID(s) is out of range for public network."
        )

    def test_network_size_not_fit_cidr_in_flatdhcp(self):
        self.nets['networking_parameters']['net_manager'] = 'FlatDHCPManager'
        self.nets['networking_parameters']['fixed_networks_cidr'] = \
            "10.10.0.0/28"
        self.nets['networking_parameters']['fixed_networks_amount'] = 1
        self.nets['networking_parameters']['fixed_network_size'] = \
            "256"
        task = self.update_nova_networks_success(self.cluster.id, self.nets)

        self.assertEqual(task['status'], consts.TASK_STATUSES.ready)

    def test_network_size_and_amount_not_fit_cidr(self):
        self.nets['networking_parameters']['net_manager'] = 'VlanManager'
        self.nets['networking_parameters']['fixed_networks_cidr'] = \
            "10.10.0.0/24"
        self.nets['networking_parameters']['fixed_networks_amount'] = 8
        self.nets['networking_parameters']['fixed_network_size'] = \
            "32"
        self.update_nova_networks_success(self.cluster.id, self.nets)

        self.nets['networking_parameters']['fixed_networks_amount'] = 32
        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Number of fixed networks (32) doesn't fit into "
            "fixed CIDR (10.10.0.0/24) and size of one fixed network (32)."
        )

    def test_network_fit_abc_classes_exclude_loopback(self):
        self.find_net_by_name('management')['cidr'] = '127.19.216.0/24'
        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "management network address space is inside loopback range "
            "(127.0.0.0/8). It must have no intersection with "
            "loopback range."
        )

        self.find_net_by_name('management')['cidr'] = '227.19.216.0/24'
        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "management network address space does not belong to "
            "A, B, C network classes. It must belong to either "
            "A, B or C network class."
        )

    def test_network_gw_and_ranges_intersect_w_subnet_or_broadcast(self):
        self.find_net_by_name('public')['gateway'] = '172.16.0.0'
        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "public network gateway address is equal to either subnet address "
            "or broadcast address of the network."
        )

        self.find_net_by_name('public')['gateway'] = '172.16.0.255'
        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "public network gateway address is equal to either subnet address "
            "or broadcast address of the network."
        )

        self.find_net_by_name('public')['gateway'] = '172.16.0.125'
        self.find_net_by_name('public')['ip_ranges'] = [['172.16.0.0',
                                                         '172.16.0.122']]
        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "public network IP range [172.16.0.0-172.16.0.122] intersect "
            "with either subnet address or broadcast address of the network."
        )

        self.find_net_by_name('public')['ip_ranges'] = [['172.16.0.255',
                                                         '172.16.0.255']]
        task = self.update_nova_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "public network IP range [172.16.0.255-172.16.0.255] intersect "
            "with either subnet address or broadcast address of the network."
        )

        self.find_net_by_name('public')['ip_ranges'] = [['172.16.0.2',
                                                         '172.16.0.122']]
        self.update_nova_networks_success(self.cluster.id, self.nets)

class TestNeutronHandlersGre(TestNetworkChecking):

    def setUp(self):
        super(TestNeutronHandlersGre, self).setUp()
        meta = self.env.default_metadata()
        self.env.set_interfaces_in_meta(meta, [
            {"name": "eth0", "mac": "00:00:00:00:00:66"},
            {"name": "eth1", "mac": "00:00:00:00:00:77"}])
        self.env.create(
            cluster_kwargs={
                'net_provider': 'neutron',
                'net_segment_type': 'gre'
            },
            nodes_kwargs=[
                {'api': True,
                 'pending_addition': True,
                 'meta': meta}
            ]
        )
        self.cluster = self.env.clusters[0]
        resp = self.env.neutron_networks_get(self.cluster.id)
        self.nets = resp.json_body

    def test_network_checking(self):
        self.update_neutron_networks_success(self.cluster.id, self.nets)

        ngs_created = self.db.query(NetworkGroup).filter(
            NetworkGroup.name.in_([n['name'] for n in self.nets['networks']])
        ).all()
        self.assertEqual(len(ngs_created), len(self.nets['networks']))

    # TODO(adanin) Provide a positive test that it's allowed to move any
    #      network to the Admin interface.

    def test_network_checking_fails_if_admin_intersection(self):
        admin_ng = self.env.network_manager.get_admin_network_group()
        self.find_net_by_name('storage')["cidr"] = admin_ng.cidr

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertIn(
            "Address space intersection between networks:\n",
            task['message'])
        self.assertIn("admin (PXE)", task['message'])
        self.assertIn("storage", task['message'])

    def test_network_checking_fails_if_untagged_intersection(self):
        for n in self.nets['networks']:
            n['vlan_start'] = None

        self.update_neutron_networks_success(self.cluster.id, self.nets)

        task = self.set_cluster_changes_w_error(self.cluster.id)
        self.assertIn(
            "Some untagged networks are "
            "assigned to the same physical interface. "
            "You should assign them to "
            "different physical interfaces. Affected:\n",
            task['message']
        )
        self.assertIn("admin (PXE)", task['message'])
        self.assertIn("storage", task['message'])
        self.assertIn("management", task['message'])

    def test_network_checking_fails_if_public_gateway_not_in_cidr(self):
        self.find_net_by_name('public')['cidr'] = '172.16.10.0/24'
        self.find_net_by_name('public')['gateway'] = '172.16.10.1'
        self.nets['networking_parameters']['floating_ranges'] = \
            [['172.16.10.130', '172.16.10.254']]

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Public gateway and public ranges are not in one CIDR."
        )

    def test_network_checking_fails_if_public_gateway_range_intersection(self):
        self.find_net_by_name('public')["ip_ranges"] = \
            [['172.16.0.5', '172.16.0.43'],
             ['172.16.0.59', '172.16.0.90']]
        self.find_net_by_name('public')["gateway"] = '172.16.0.77'

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address intersection between public gateway and IP range of "
            "public network."
        )

        self.find_net_by_name('public')["ip_ranges"] = \
            [['172.16.0.5', '172.16.0.99']]
        self.find_net_by_name('public')["gateway"] = '172.16.0.55'

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address intersection between public gateway and IP range of "
            "public network."
        )

    def test_network_checking_fails_if_public_float_range_not_in_cidr(self):
        self.find_net_by_name('public')['cidr'] = '172.16.10.0/24'
        self.find_net_by_name('public')['gateway'] = '172.16.10.1'

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Floating address range 172.16.0.130:172.16.0.254 is not in "
            "public address space 172.16.10.0/24."
        )

    def test_network_checking_fails_if_network_ranges_intersect(self):
        self.find_net_by_name('management')['cidr'] = \
            self.find_net_by_name('storage')['cidr']

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertIn(
            "Address space intersection between networks:\n",
            task['message'])
        self.assertIn("management", task['message'])
        self.assertIn("storage", task['message'])

    def test_network_checking_fails_if_public_gw_ranges_intersect(self):
        self.find_net_by_name('public')['gateway'] = '172.16.0.11'

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address intersection between public gateway "
            "and IP range of public network."
        )

    def test_network_checking_fails_if_public_ranges_intersect(self):
        self.find_net_by_name('public')['ip_ranges'] = \
            [['172.16.0.2', '172.16.0.77'],
             ['172.16.0.55', '172.16.0.121']]

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address space intersection between ranges "
            "of public network."
        )

    def test_network_checking_fails_if_public_float_ranges_intersect(self):
        self.find_net_by_name('public')['ip_ranges'] = \
            [['172.16.0.2', '172.16.0.33'],
             ['172.16.0.55', '172.16.0.222']]

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Address space intersection between ranges "
            "of public and external network."
        )

    def test_network_checking_public_network_cidr_became_smaller(self):
        self.find_net_by_name('public')['cidr'] = '172.16.0.0/25'
        self.find_net_by_name('public')['gateway'] = '172.16.0.1'
        self.find_net_by_name('public')['ip_ranges'] = [['172.16.0.2',
                                                         '172.16.0.77']]
        self.nets['networking_parameters']['floating_ranges'] = \
            [['172.16.0.99', '172.16.0.111']]

        self.update_neutron_networks_success(self.cluster.id, self.nets)
        resp = self.env.neutron_networks_get(self.cluster.id)
        self.nets = resp.json_body
        self.assertEqual(self.find_net_by_name('public')['cidr'],
                         '172.16.0.0/25')

    def test_network_checking_fails_on_network_vlan_match(self):
        self.find_net_by_name('management')['vlan_start'] = '111'
        self.find_net_by_name('storage')['vlan_start'] = '111'

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertIn(
            " networks use the same VLAN tags. "
            "You should assign different VLAN tag "
            "to every network.",
            task['message'])
        self.assertIn("management", task['message'])
        self.assertIn("storage", task['message'])

    def test_network_checking_fails_if_internal_gateway_not_in_cidr(self):
        self.nets['networking_parameters']['internal_gateway'] = '172.16.10.1'

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Internal gateway 172.16.10.1 is not in "
            "internal address space 192.168.111.0/24."
        )

    def test_network_checking_fails_if_internal_w_floating_intersection(self):
        self.nets['networking_parameters']['internal_cidr'] = '172.16.0.128/26'
        self.nets['networking_parameters']['internal_gateway'] = '172.16.0.129'

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Intersection between internal CIDR and floating range."
        )

    def test_network_fit_abc_classes_exclude_loopback(self):
        self.find_net_by_name('management')['cidr'] = '127.19.216.0/24'
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "management network address space is inside loopback range "
            "(127.0.0.0/8). It must have no intersection with "
            "loopback range."
        )

        self.find_net_by_name('management')['cidr'] = '227.19.216.0/24'
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "management network address space does not belong to "
            "A, B, C network classes. It must belong to either "
            "A, B or C network class."
        )

    def test_network_gw_and_ranges_intersect_w_subnet_or_broadcast(self):
        self.find_net_by_name('public')['gateway'] = '172.16.0.0'
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "public network gateway address is equal to either subnet address "
            "or broadcast address of the network."
        )

        self.find_net_by_name('public')['gateway'] = '172.16.0.255'
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "public network gateway address is equal to either subnet address "
            "or broadcast address of the network."
        )

        self.find_net_by_name('public')['gateway'] = '172.16.0.125'
        self.find_net_by_name('public')['ip_ranges'] = [['172.16.0.0',
                                                         '172.16.0.122']]
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "public network IP range [172.16.0.0-172.16.0.122] intersect "
            "with either subnet address or broadcast address of the network."
        )

        self.find_net_by_name('public')['ip_ranges'] = [['172.16.0.255',
                                                         '172.16.0.255']]
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "public network IP range [172.16.0.255-172.16.0.255] intersect "
            "with either subnet address or broadcast address of the network."
        )

        self.find_net_by_name('public')['ip_ranges'] = [['172.16.0.55',
                                                         '172.16.0.99']]
        self.nets['networking_parameters']['floating_ranges'] = \
            [['172.16.0.0', '172.16.0.33']]
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Neutron L3 external floating range [172.16.0.0-172.16.0.33] "
            "intersect with either subnet address or broadcast address "
            "of public network."
        )

        self.nets['networking_parameters']['floating_ranges'] = \
            [['172.16.0.155', '172.16.0.255']]
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Neutron L3 external floating range [172.16.0.155-172.16.0.255] "
            "intersect with either subnet address or broadcast address "
            "of public network."
        )

        self.nets['networking_parameters']['floating_ranges'] = \
            [['172.16.0.155', '172.16.0.199']]
        self.nets['networking_parameters']['internal_cidr'] = \
            '192.168.111.0/24'
        self.nets['networking_parameters']['internal_gateway'] = \
            '192.168.111.0'
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Neutron L3 internal network gateway address is equal to "
            "either subnet address or broadcast address of the network."
        )

        self.nets['networking_parameters']['internal_gateway'] = \
            '192.168.111.255'
        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "Neutron L3 internal network gateway address is equal to "
            "either subnet address or broadcast address of the network."
        )

class TestNeutronHandlersVlan(TestNetworkChecking):

    def setUp(self):
        super(TestNeutronHandlersVlan, self).setUp()
        meta = self.env.default_metadata()
        self.env.set_interfaces_in_meta(meta, [
            {"name": "eth0", "mac": "00:00:00:00:00:66"},
            {"name": "eth1", "mac": "00:00:00:00:00:77"}])
        self.env.create(
            cluster_kwargs={
                'net_provider': 'neutron',
                'net_segment_type': 'vlan'
            },
            nodes_kwargs=[
                {'api': True,
                 'pending_addition': True,
                 'meta': meta}
            ]
        )
        self.cluster = self.env.clusters[0]
        resp = self.env.neutron_networks_get(self.cluster.id)
        self.nets = resp.json_body

    def test_network_checking(self):
        self.update_neutron_networks_success(self.cluster.id, self.nets)

        ngs_created = self.db.query(NetworkGroup).filter(
            NetworkGroup.name.in_([n['name'] for n in self.nets['networks']])
        ).all()
        self.assertEqual(len(ngs_created), len(self.nets['networks']))

    def test_network_checking_failed_if_networks_tags_in_neutron_range(self):
        self.find_net_by_name('storage')['vlan_start'] = 1000

        task = self.update_neutron_networks_w_error(self.cluster.id, self.nets)
        self.assertEqual(
            task['message'],
            "VLAN tags of storage network(s) intersect with "
            "VLAN ID range defined for Neutron L2. "
            "Networks VLAN tags must not intersect "
            "with Neutron L2 VLAN ID range.")


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports["default"] = renderCheckbox;

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }

/**
 * 渲染checkbox
 * @param Checkbox
 * @param Icon
 * @returns {CheckboxRender}
 */
function renderCheckbox(Checkbox, Icon) {
    return function (_Component) {
        _inherits(CheckboxRender, _Component);

        function CheckboxRender() {
            var _temp, _this, _ret;

            _classCallCheck(this, CheckboxRender);

            for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }

            return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = {
                value: _this.props.value,
                editable: false
            }, _this.handleChange = function (e) {
                var value = e.target.value;
                _this.setState({ value: value });
            }, _this.check = function () {
                _this.setState({ editable: false });
                if (_this.props.onChange) {
                    _this.props.onChange(_this.state.value);
                }
            }, _this.edit = function () {
                _this.setState({ editable: true });
            }, _this.handleKeydown = function (event) {
                if (event.keyCode == 13) {
                    _this.check();
                }
            }, _temp), _possibleConstructorReturn(_this, _ret);
        }

        CheckboxRender.prototype.render = function render() {
            var _state = this.state,
                value = _state.value,
                editable = _state.editable;

            var cellContent = "";
            if (editable) {
                cellContent = _react2["default"].createElement(
                    "div",
                    { className: "editable-cell-input-wrapper" },
                    _react2["default"].createElement(Checkbox, {
                        onChange: this.handleChange,
                        onKeyDown: this.handleKeydown,
                        onBlur: this.check,
                        autoFocus: true,
                        value: value
                    })
                );
            } else {
                cellContent = _react2["default"].createElement(
                    "div",
                    { className: "editable-cell-text-wrapper" },
                    value || " ",
                    _react2["default"].createElement(Icon, {
                        type: "uf-pencil",
                        className: "editable-cell-icon",
                        onClick: this.edit
                    })
                );
            }
            return _react2["default"].createElement(
                "div",
                { className: "editable-cell" },
                cellContent
            );
        };

        return CheckboxRender;
    }(_react.Component);
}
module.exports = exports["default"];