text:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import org.vu.contest.ContestEvaluation;
import org.vu.contest.ContestSubmission;
import java.io.FileWriter;
import java.io.IOException;

public class player201 implements ContestSubmission{

	// declaration of variables
	static ContestEvaluation eval;
	static Random rand = new Random();
	static NumberFormat formatter  = new DecimalFormat("+#0.0;-#0.0");
	static NumberFormat formatter2 = new DecimalFormat("+#0.0000;-#0.0000");
	static NumberFormat formatter3 = new DecimalFormat("#00000");
	static int max_evals;
	static int evals = 0;
	static boolean isMultimodal;
    static boolean hasStructure;
    static boolean isSeparable;
    ArrayList<Tuple>  tuples;
    static boolean testing = false;

    Combinator combinator = new CombineRandomWeightedCrossover();
    Selector   selector   = new RankSelect();
    Mutator    mutator    = new MutateAddGaussian(0.005);
    ListCombinator lcombinator = new allCombine();
    ListMutator lmutator = new mutateList();

    // needed for evaluation
    int count = 0;
    int mutation_increased = 0;
    int added_individuals  = 0;
    Double best = Double.NaN;
    ArrayList<Double> progress = new ArrayList<Double>();
    ArrayList<Double> speed    = new ArrayList<Double>();
    ArrayList<Double> mean_sd  = new ArrayList<Double>();
    ArrayList<Integer> mut_inc = new ArrayList<Integer>();
    ArrayList<Integer> add_ind = new ArrayList<Integer>();
    ArrayList<Double> maximum = new ArrayList<Double>();

    //// settings
    static int initial; // initial population
    static int recombine; // # of individuals to recombine

    // This method is called when you press Run in Eclipse
	// It creates an instance of player20, gives it a
	// ContestEvaluation object and calls testrun()
	public static void main(String[] args) {
		testing = true;
		player201 sub = new player201();
		sub.setEvaluation(new FletcherPowellEvaluation());
		sub.run();
	}

	// Work in progress, a simple evolutionary algorithm
	// is implemented, but it's probably not perfect.
	public void run() {
		ArrayList<Tuple> parentSelection = new ArrayList<Tuple>();
		ArrayList<Tuple> survivorSelection = new ArrayList<Tuple>();
		ArrayList<Tuple> happyChildren = new ArrayList<Tuple>();
		ArrayList<Tuple> sadChildren = new ArrayList<Tuple>();
		tuples = new ArrayList<Tuple>();

		int numberOfParents = 50;
		int numberOfChildren = 100;

		// Initialize the population
		for(int i = 0; i < initial; i++){
			Tuple t = new Tuple();
			Evaluate(t);
			survivorSelection.add(t);
		}

<<<<<<< HEAD

		System.out.println("Start");
=======

>>>>>>> refs/remotes/origin/master
		System.out.println("initial population: " + initial);
		System.out.println("number of parents: " + numberOfParents);
		System.out.println("number of selected children: " + numberOfChildren);
		System.out.println("Starting... \n");

		// Run the algorithm while we are allowed to
		while(evals < max_evals){

			// select parents
			parentSelection.addAll(selector.select(survivorSelection, numberOfParents));
			sadChildren.clear();
			survivorSelection.clear();

			// have some children
			happyChildren.addAll(lcombinator.combinelist(parentSelection, combinator));
			parentSelection.clear();

			// mutate the offspring
			sadChildren.addAll(lmutator.mutatelist(happyChildren, mutator));
			happyChildren.clear();

			// check fitness
			for(Tuple t : sadChildren){
				Evaluate(t);
			}

			// select survivors
			survivorSelection.addAll(selector.select(sadChildren, numberOfChildren));

			tuples.addAll(survivorSelection);

		}

		System.out.println("number of combine population: " + sadChildren.size());
		System.out.println("Evals: " + formatter3.format(evals));
		System.out.println();
		Collections.sort(tuples, Collections.reverseOrder());
		System.out.println("Done. \nTop 5:");
		for(int i = 0; i < 5; i++){
			System.out.println(tuples.get(i).toString());
		}

		// if we're testing (i.e. running locally)
		// generate result files and plot them with Python
		if(testing){
			writeToFile(progress, "progress.txt" );
			writeToFile(speed,    "speed.txt"    );
			writeToFile(mean_sd,  "mean_sd.txt"  );
			writeToFile(add_ind,  "add_ind.txt"  );
			writeToFile(mut_inc,  "mut_inc.txt"  );
			//writeToFile(maximum,  "maximum.txt"  );

			try {
				Runtime.getRuntime().exec("python3 plot_progress.py");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// This method is called by the test system of the VU
	// We will receive a ContestEvaluation object through this
	// method, that will gives us the opportunity to request
	// some basic properties of the contest function.
	public void setEvaluation(ContestEvaluation evaluation) {
		eval = evaluation;

		Properties props = evaluation.getProperties();

        max_evals = Integer.parseInt(props.getProperty("Evaluations"));

        initial   = Math.round((float)0.1*max_evals);
        recombine = Math.round((float)0.001*max_evals);

		// Property keys depend on specific evaluation
		// E.g. double param = Double.parseDouble(props.getProperty("property_name"));
        boolean isMultimodal = Boolean.parseBoolean(props.getProperty("Multimodal"));
        boolean hasStructure = Boolean.parseBoolean(props.getProperty("Regular"));
        boolean isSeparable = Boolean.parseBoolean(props.getProperty("Separable"));

		// Relevant settings to adapt to different function properties.
        if(isMultimodal){
            //
            combinator = new CombineRandomWeightedCrossover();
            selector   = new SelectTopN();
            mutator    = new MutateAddGaussian(0.01);

            //ect.....

        }else{
        	selector = new SelectTopN();
        	mutator  = new MutateAddGaussian(0.1);
            //
        }

        if(hasStructure){
            //

        }else{
            //
        }

        if(isSeparable){
            //

        }else{
            //
        }
	}

	// We use a random number generator in our code a few times
	// If you set the seed of this RNG to the same value, we will
	// get the same result. Maybe they use this to detect cheating
	// or something.
	public void setSeed(long seed) {
		rand.setSeed(seed);
	}

	// Evaluate a Tuple. This is also where we keep track of our
	// progress and diversity.
	public void Evaluate(Tuple t){
		if(evals < max_evals){
			t.evaluate(eval);
			evals++;
			progress.add(t.fitness);
			//update the current best score
			if(t.fitness > best  || best.isNaN() ){
				best = t.fitness;
			}
			maximum.add(best);

			if(evals > initial + recombine){
				double curr_mean_sd = genMeanSd();
				mean_sd.add(new Double(curr_mean_sd));
				List<Double> current  =
						progress.subList(progress.size()-100, progress.size());
				List<Double> previous =
						progress.subList( progress.size() - 300, progress.size() - 200);
				Collections.sort(current);
				Collections.sort(previous);
				List<Double> currenttop  = current.subList(0, 50);
				List<Double> previoustop = previous.subList(0,50);
				double current_avg_progress = Statistics.getMean(currenttop);
				double previous_avg_progress = Statistics.getMean(previoustop);
				double currentspeed = current_avg_progress - previous_avg_progress;
				speed.add(currentspeed);

				// if were progressing too slowly
//				if(currentspeed < 1 && (count++ % 1000 == 0 )){
//					//System.out.println(">>> Speed lower than 1, evals:" + evals);
//
//					// if diversity is too small, add individuals (max. 1 time)
//					if(curr_mean_sd < 0.1 && added_individuals < 1){
//						added_individuals++;
//						System.out.println("Low diversity deviation: " + formatter2.format(curr_mean_sd));
//						addIndividuals();
//					}
//
//
//					// if our best is pretty bad, increase mutation (max. 5 times)
//					if(best < 7 && mutation_increased < 5){
//						System.out.println("Speed: " + formatter2.format(currentspeed)
//								+ ", best score: "+ formatter2.format(best) + " increasing mutation");
//						increaseMutation();
//					}
//					// if our best is still pretty bad, add some individuals
//					if(best < 7 && mutation_increased >= 5){
//						System.out.println("Adding individuals, evals: " +evals);
//						addIndividuals();
//					}
//					// if we used 50% of iterations and we're still not
//					// close to 10, create some new individuals
//					if(best < 9.5 && (evals/max_evals > 1/2 && added_individuals < 5)){
//						System.out.println("Going pretty well. " + formatter2.format(evals/max_evals)
//								+ "% of evals done, score: " + formatter.format(best));
//						addIndividuals();
//					}
//					// if we're almost out of iterations and have a good score
//					// reduce mutation
//					if(evals/max_evals > 5/10 && best > 9.3){
//						scaleMutation(0.2);
//					}
//				}

			} else{
				mean_sd.add(Double.NaN);
				speed.add(Double.NaN);
			}
//
//			double percentage = 100* (evals / max_evals);
//			if(evals % 500 == 0){
//				double[] sds = gen_sd();
//				String percentagestring = Integer.toString((int)Math.round(percentage));
//				System.out.println(percentagestring + "% of evals used, standard deviations:");
//				System.out.println( Arrays.toString(sds));
//				System.out.println("Average standard deviation: " +
//									Double.toString(Statistics.getMean(sds)));
//				System.out.println();
//			}
		}
	}

	public double genMeanSd(){
		return Statistics.getMean(genSD());
	}

	public void increaseMutation(){
		scaleMutation(1.5);
	}

	public void scaleMutation(double s){
		mut_inc.add(evals);
		System.out.println("Increasing mutation by factor " + s);
		mutator.scale(s);
		mutation_increased++;
	}

	public void addIndividuals(){
		addIndividuals(Math.round(initial));
	}

	public void addIndividuals(int n){
		add_ind.add(evals);
		ArrayList<Tuple> new_tuples = new ArrayList<Tuple>();
		System.out.println("Creating " + n +" new individuals.");
		for(int i = 0; i < Math.round(n); i++){
			Tuple t_new = new Tuple();
			t_new.evaluate(eval);
			evals++;
			new_tuples.add(t_new);
		}
		Collections.sort(new_tuples,Collections.reverseOrder());
		System.out.println("Recombining the best " + recombine/2 +" new individuals");
		for(int i = 0; i < recombine/2; i++){
			for(int j = 0; j < i; j++){
				if(i != j && evals < max_evals){
					Tuple combination = combinator.combine(
							new_tuples.get(i), new_tuples.get(j));
					combination.evaluate(eval);
					evals++;
					tuples.add(combination) ;
				}
			}
		}
		Collections.sort(tuples, Collections.reverseOrder());
	}

	public double best(){
		if(tuples.size() > 0){
			ArrayList<Tuple> templist = tuples;
			Collections.sort(templist, Collections.reverseOrder());
			return templist.get(0).fitness;
		} else{
			return Double.NaN;
		}
	}

	public double[] genSD(){
		double[] sds = new double[10];
		for(int i = 0; i < 10; i++){
			double[] temp = new double[tuples.size()/10];
			for(int j = 0; j < 0.01*tuples.size(); j += 1){
				temp[j] = tuples.get(j).vector[i];
			}
			sds[i] = Statistics.getStdDev(temp);
		}
		return sds;
	}

	public void writeToFile(ArrayList<?> list, String filename){
		try{
			FileWriter writer = new FileWriter(filename);
			for(Object d : list){
				writer.write(d.toString());
				writer.write("\n");
			}
			writer.close();
		}
		catch(IOException e){
			System.out.println(e.getMessage());
		}
	}

}


text:
package org.apache.calcite.adapter.enumerable;

import org.apache.calcite.adapter.java.JavaTypeFactory;
import org.apache.calcite.interpreter.Row;
import org.apache.calcite.linq4j.tree.Expression;
import org.apache.calcite.linq4j.tree.Expressions;
import org.apache.calcite.linq4j.tree.IndexExpression;
import org.apache.calcite.linq4j.tree.MemberExpression;
import org.apache.calcite.linq4j.tree.MethodCallExpression;
import org.apache.calcite.linq4j.tree.Types;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.runtime.FlatLists;
import org.apache.calcite.runtime.Unit;
import org.apache.calcite.util.BuiltInMethod;

import java.lang.reflect.Type;
import java.util.List;

/**
 * How a row is represented as a Java value.
 */
public enum JavaRowFormat {
  CUSTOM {
    Type javaRowClass(
        JavaTypeFactory typeFactory,
        RelDataType type) {
      assert type.getFieldCount() > 1;
      return typeFactory.getJavaClass(type);
    }

    @Override Type javaFieldClass(JavaTypeFactory typeFactory, RelDataType type,
        int index) {
      return typeFactory.getJavaClass(type.getFieldList().get(index).getType());
    }

    public Expression record(
        Type javaRowClass, List<Expression> expressions) {
      switch (expressions.size()) {
      case 0:
        assert javaRowClass == Unit.class;
        return Expressions.field(null, javaRowClass, "INSTANCE");
      default:
        return Expressions.new_(javaRowClass, expressions);
      }
    }

    public MemberExpression field(Expression expression, int field,
        Type fromType, Type fieldType) {
      final Type type = expression.getType();
      if (type instanceof Types.RecordType) {
        Types.RecordType recordType = (Types.RecordType) type;
        Types.RecordField recordField =
            recordType.getRecordFields().get(field);
        return Expressions.field(expression, recordField.getDeclaringClass(),
            recordField.getName());
      } else {
        return Expressions.field(expression, Types.nthField(field, type));
      }
    }
  },

  SCALAR {
    Type javaRowClass(
        JavaTypeFactory typeFactory,
        RelDataType type) {
      assert type.getFieldCount() == 1;
      return typeFactory.getJavaClass(
          type.getFieldList().get(0).getType());
    }

    @Override Type javaFieldClass(JavaTypeFactory typeFactory, RelDataType type,
        int index) {
      return javaRowClass(typeFactory, type);
    }

    public Expression record(Type javaRowClass, List<Expression> expressions) {
      assert expressions.size() == 1;
      return expressions.get(0);
    }

    public Expression field(Expression expression, int field, Type fromType,
        Type fieldType) {
      assert field == 0;
      return expression;
    }
  },

  /** A list that is comparable and immutable. Useful for records with 0 fields
   * (empty list is a good singleton) but sometimes also for records with 2 or
   * more fields that you need to be comparable, say as a key in a lookup. */
  LIST {
    Type javaRowClass(
        JavaTypeFactory typeFactory,
        RelDataType type) {
      return FlatLists.ComparableList.class;
    }

    @Override Type javaFieldClass(JavaTypeFactory typeFactory, RelDataType type,
        int index) {
      return Object.class;
    }

    public Expression record(
        Type javaRowClass, List<Expression> expressions) {
      switch (expressions.size()) {
      case 0:
        return Expressions.field(
          null,
          FlatLists.class,
          "COMPARABLE_EMPTY_LIST");
      case 2:
        return Expressions.convert_(
            Expressions.call(
                List.class,
                null,
                BuiltInMethod.LIST2.method,
                expressions),
            List.class);
      case 3:
        return Expressions.convert_(
            Expressions.call(
                List.class,
                null,
                BuiltInMethod.LIST3.method,
                expressions),
            List.class);
      case 4:
        return Expressions.convert_(
            Expressions.call(
                List.class,
                null,
                BuiltInMethod.LIST4.method,
                expressions),
            List.class);
      case 5:
        return Expressions.convert_(
            Expressions.call(
                List.class,
                null,
                BuiltInMethod.LIST5.method,
                expressions),
            List.class);
      case 6:
        return Expressions.convert_(
            Expressions.call(
                List.class,
                null,
                BuiltInMethod.LIST6.method,
                expressions),
            List.class);
      default:
        return Expressions.convert_(
            Expressions.call(
                List.class,
                null,
                BuiltInMethod.LIST_N.method,
                Expressions.newArrayInit(
                    Comparable.class,
                    expressions)),
            List.class);
      }
    }

    public Expression field(Expression expression, int field, Type fromType,
        Type fieldType) {
      final MethodCallExpression e = Expressions.call(expression,
          BuiltInMethod.LIST_GET.method, Expressions.constant(field));
      if (fromType == null) {
        fromType = e.getType();
      }
      return EnumUtils.convert(e, fromType, fieldType);
    }
  },

  /**
   * See {@link org.apache.calcite.interpreter.Row}
   */
  ROW {
    @Override Type javaRowClass(JavaTypeFactory typeFactory, RelDataType type) {
      return Row.class;
    }

    @Override Type javaFieldClass(JavaTypeFactory typeFactory, RelDataType type,
        int index) {
      return Object.class;
    }

    @Override public Expression record(Type javaRowClass,
        List<Expression> expressions) {
      return Expressions.call(BuiltInMethod.ROW_AS_COPY.method, expressions);
    }

    public Expression field(Expression expression, int field, Type fromType,
        Type fieldType) {
      final Expression e = Expressions.call(expression,
          BuiltInMethod.ROW_VALUE.method, Expressions.constant(field));
      if (fromType == null) {
        fromType = e.getType();
      }
      return EnumUtils.convert(e, fromType, fieldType);
    }
  },

  ARRAY {
    Type javaRowClass(
        JavaTypeFactory typeFactory,
        RelDataType type) {
      return Object[].class;
    }

    @Override Type javaFieldClass(JavaTypeFactory typeFactory, RelDataType type,
        int index) {
      return Object.class;
    }

    public Expression record(Type javaRowClass, List<Expression> expressions) {
      return Expressions.newArrayInit(Object.class, expressions);
    }

    @Override public Expression comparer() {
      return Expressions.call(BuiltInMethod.ARRAY_COMPARER.method);
    }

    public Expression field(Expression expression, int field, Type fromType,
        Type fieldType) {
      final IndexExpression e = Expressions.arrayIndex(expression,
          Expressions.constant(field));
      if (fromType == null) {
        fromType = e.getType();
      }
      return EnumUtils.convert(e, fromType, fieldType);
    }
  };

  public JavaRowFormat optimize(RelDataType rowType) {
    switch (rowType.getFieldCount()) {
    case 0:
      return LIST;
    case 1:
      return SCALAR;
    default:
      if (this == SCALAR) {
        return LIST;
      }
      return this;
    }
  }

  abstract Type javaRowClass(JavaTypeFactory typeFactory, RelDataType type);

  /**
   * Returns the java class that is used to physically store the given field.
   * For instance, a non-null int field can still be stored in a field of type
   * {@code Object.class} in {@link JavaRowFormat#ARRAY} case.
   *
   * @param typeFactory type factory to resolve java types
   * @param type row type
   * @param index field index
   * @return java type used to store the field
   */
  abstract Type javaFieldClass(JavaTypeFactory typeFactory, RelDataType type,
      int index);

  public abstract Expression record(
      Type javaRowClass, List<Expression> expressions);

  public Expression comparer() {
    return null;
  }

  /** Returns a reference to a particular field.
   *
   * <p>{@code fromType} may be null; if null, uses the natural type of the
   * field.
   */
  public abstract Expression field(Expression expression, int field,
      Type fromType, Type fieldType);
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.olingo.commons.api.edm.geo;

import java.io.Serializable;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;

/**
 * Base class for all geospatial info.
 */
public abstract class Geospatial implements Serializable {

  private static final long serialVersionUID = 5409612902190067390L;

  public enum Dimension {

    GEOMETRY,
    GEOGRAPHY

  }

  public enum Type {

    /**
     * The OGIS geometry type number for points.
     */
    POINT,
    /**
     * The OGIS geometry type number for lines.
     */
    LINESTRING,
    /**
     * The OGIS geometry type number for polygons.
     */
    POLYGON,
    /**
     * The OGIS geometry type number for aggregate points.
     */
    MULTIPOINT,
    /**
     * The OGIS geometry type number for aggregate lines.
     */
    MULTILINESTRING,
    /**
     * The OGIS geometry type number for aggregate polygons.
     */
    MULTIPOLYGON,
    /**
     * The OGIS geometry type number for feature collections.
     */
    GEOSPATIALCOLLECTION

  }

  protected final Dimension dimension;

  protected final Type type;

  /**
   * Null value means it is expected to vary per instance.
   */
  protected final SRID srid;

  /**
   * Constructor.
   *
   * @param dimension dimension.
   * @param type type.
   * @param srid SRID
   */
  protected Geospatial(final Dimension dimension, final Type type, final SRID srid) {
    this.dimension = dimension;
    this.type = type;
    this.srid = srid == null
        ? new SRID()
    : srid;
        this.srid.setDimension(dimension);
  }

  /**
   * Gets dimension.
   *
   * @return dimension.
   * @see Dimension
   */
  public Dimension getDimension() {
    return dimension;
  }

  /**
   * Gets type.
   *
   * @return type.
   * @see Type
   */
  public Type getType() {
    return type;
  }

  /**
   * Gets s-rid.
   *
   * @return s-rid.
   */
  public SRID getSrid() {
    return srid;
  }

  public abstract EdmPrimitiveTypeKind getEdmPrimitiveTypeKind();

  @Override
  public boolean equals(final Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
  }

  @Override
  public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
  }

  @Override
  public String toString() {
    return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
  }
}


text:
'use strict';

angular.module('myApp.peopleReport', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/peopleReport', {
            templateUrl: 'peopleReport/peopleReportView.html',
            controller: 'peopleReportController'
        });
    }])

    .controller('peopleReportController', ['$scope', function ($scope) {
        $scope.page = 'peopleReport';
    }]);


text:
'use strict';

System.register(['../dialog-controller'], function (_export, _context) {
  var DialogController, _class, _temp, Prompt;

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

  return {
    setters: [function (_dialogController) {
      DialogController = _dialogController.DialogController;
    }],
    execute: function () {
      _export('Prompt', Prompt = (_temp = _class = function () {
        function Prompt(controller) {
          _classCallCheck(this, Prompt);

          this.controller = controller;
          this.answer = null;

          controller.settings.lock = false;
        }

        Prompt.prototype.activate = function activate(question) {
          this.question = question;
        };

        return Prompt;
      }(), _class.inject = [DialogController], _temp));

      _export('Prompt', Prompt);
    }
  };
});


text:
**React-lazy-hero** is a flexible hero component for React with image preloading, a fade-in effect, a semi-transparent color overlay and an optional parallax effect.

## Installation

```sh
yarn add react-lazy-hero styled-components
```

Or alternatively via npm:
```sh
npm i --save react-lazy-hero styled-components
```

## Basic Usage

```js
import React from 'react';
import LazyHero from 'react-lazy-hero';

export default MyLandingPage() {
    return (
        <div>
            <LazyHero imageSrc="https://unsplash.it/2000/1000">
                <h1>Generic Startup Hype Headline</h1>
            </LazyHero>

            {/* ... */}
        </div>
    );
}
```

Click above in the menu bar on **Properties** to list all available options.


text:
class BypassUnsubscribeManagement(object):
    """Setting for Bypass Unsubscribe Management

    Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients.
    Bounce and spam report lists will still be checked; addresses on these other lists will not receive
    the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes.
    This filter cannot be combined with the bypass_list_management filter.
    """

    def __init__(self, enable=None):
        """Create a BypassUnsubscribeManagement.

        :param enable: Whether emails should bypass unsubscribe management.
        :type enable: boolean, optional
        """
        self._enable = None

        if enable is not None:
            self.enable = enable

    @property
    def enable(self):
        """Indicates if this setting is enabled.

        :rtype: boolean
        """
        return self._enable

    @enable.setter
    def enable(self, value):
        """Indicates if this setting is enabled.

        :param value: Indicates if this setting is enabled.
        :type value: boolean
        """
        self._enable = value

    def get(self):
        """
        Get a JSON-ready representation of this BypassUnsubscribeManagement.

        :returns: This BypassUnsubscribeManagement, ready for use in a request body.
        :rtype: dict
        """
        bypass_unsubscribe_management = {}
        if self.enable is not None:
            bypass_unsubscribe_management["enable"] = self.enable
        return bypass_unsubscribe_management


text:
using System.IO;
using System.Threading.Tasks;

namespace SpeakEasy
{
    public abstract class FileUpload : IFile
    {
        public static FileUpload FromBytes(string name, string fileName, byte[] contents)
        {
            return new FileUploadByteArray(name, fileName, contents);
        }

        public static FileUpload FromStream(string name, string fileName, Stream contents)
        {
            return new FileUploadStream(name, fileName, contents);
        }

        public static FileUpload FromPath(string name, string filePath)
        {
            return new FileUploadPath(name, filePath);
        }

        protected FileUpload(string name, string fileName)
        {
            Name = name;
            FileName = fileName;
        }

        public string Name { get; set; }

        public string FileName { get; set; }

        public string ContentType { get; set; }

        public abstract Task WriteToAsync(Stream stream);
    }
}


text:
[CmdletBinding()]
param()

. "$PSScriptRoot\Test-ApplicationVersions.ps1" PreviousPkg -Service1Changed


text:
<?php

namespace Tangent\Bundle\BookTrackerBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class AuthorType extends AbstractType {

    public function buildForm(FormBuilder $builder, array $options) {
        $builder
                ->add('firstName', 'text')
                ->add('lastName', 'text')
        ;
    }

    public function getName() {
        return 'author';
    }

}


text:
layout: post
title: Week five at Uni
---
A week dominated by editing video.

## GoPro
First up, I attached my GoPro to the front of Aidan's car and set it off on some timelapses:

## Frisbee
The video that dominated a Wednesday evening and Thursday was a highlights reel of a Firebirds friendly. We were meant to play Worcester, but for they didn't show up so we played a training match; 'twas a lot of fun:

## Other stuff
On Saturday I went to the first half of the Men's Regionals tournament in Coventry to support the team and I also filmed the matches. I'm still editing the videos, but a few are up. If you're particularly interested they're on the Firebirds' YouTube channel here: https://www.youtube.com/channel/UC-4U6mldf-hGVl7pkTZbu-g. The matches are uploaded at 50 frames per second (instead of 25 or 30), so the motion should be pretty clear. Huge files though

On Sunday my family visted, we went out for a pub lunch and had a little wander, then Hannah stayed for a few days. That'll be covered in week 6 at Uni though


text:
clean :
	rm -rf build/

compile : clean
	mkdir -p build/
	gcc -o build/hellomake.out hello.c

install : compile
	cp build/hellomake.out /bin/hellomake


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/dli_button_ll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_margin="20dp"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/btn_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:src="@drawable/ic_pause_white_24dp" />

        <ImageButton
            android:id="@+id/btn_continue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:src="@drawable/ic_play_arrow_white_24dp"
            android:visibility="gone" />

        <ImageButton
            android:id="@+id/btn_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:src="@drawable/ic_delete_white_24dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/dli_button_ll"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ProgressBar
            android:id="@+id/progress_bar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="15dp"
            android:max="100" />

        <TextView
            android:id="@+id/speed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</RelativeLayout>


text:
var cardsServices = angular.module('cardsServices', ['ngResource']);

cardsServices.factory('Cards', ['$resource',
  function ($resource) {
      return $resource('/Api/Cards', {}, {
          query: { method: 'GET', params: { }, isArray: true }
      });
  }]);


text:
<?php
/**
 * Iterator to allow a slice to be used like an array
 */

namespace Qaribou\Iterator;

use ArrayAccess;
use LimitIterator;
use JsonSerializable;
use Countable;
use Iterator;
use InvalidArgumentException;
use RuntimeException;

class SliceIterator extends LimitIterator implements ArrayAccess, Countable, JsonSerializable
{
    protected $count = 0;
    protected $begin = 0;

    const INVALID_INDEX = 'Index invalid or out of range';

    /**
     * Build an iterator over a slice of an ArrayAccess object
     * Unlike a LimitIterator, the $end defines the last index, not the count
     *
     * @param Iterator $iterator An ArrayAccess iterator, e.g. SplFixedArray
     * @param int $begin The starting offset of the slice
     * @param int $end The last index of the slice
     */
    public function __construct(Iterator $iterator, $begin = 0, $end = null)
    {
        if ($iterator instanceof ArrayAccess && $iterator instanceof Countable) {
            $count = count($iterator);

            // Negative begin means start from the end
            if ($begin < 0) {
                $begin = max(0, $count + $begin);
            }

            // If no end set, assume whole array
            if ($end === null) {
                $end = $count;
            } else if ($end < 0) {
                // Ends counting back from start
                $end = max($begin, $count + $end);
            }

            // Set the size of iterable object, for quick-lookup
            $this->count = max(0, $end - $begin);

            // Need to store the starting offset to adjust by
            $this->begin = $begin;

            // Init as LimitIterator
            parent::__construct($iterator, $this->begin, $this->count);
        } else {
            throw new InvalidArgumentException('Iterator must be a Countable ArrayAccess');
        }
    }

    /**
     * Rewind, extended for clean results on empty sets
     */
    public function rewind()
    {
        // no need to rewind on empty sets
        if ($this->count > 0) {
            parent::rewind();
        }
    }

    /**
     * Countable
     */
    public function count()
    {
        return $this->count;
    }

    /**
     * ArrayAccess
     */
    public function offsetExists($offset)
    {
        return $offset >= 0 && $offset < $this->count;
    }

    public function offsetGet($offset)
    {
        if ($this->offsetExists($offset)) {
            return $this->getInnerIterator()->offsetGet($offset + $this->begin);
        } else {
            throw new RuntimeException(self::INVALID_INDEX);
        }
    }

    public function offsetSet($offset, $value)
    {
        return $this->getInnerIterator()->offsetSet($offset + $this->begin, $value);
    }

    public function offsetUnset($offset)
    {
        return $this->getInnerIterator()->offsetUnset($offset + $this->begin);
    }

    /**
     * JsonSerializable
     */
    public function jsonSerialize()
    {
        return $this->toArray();
    }

    public function toArray()
    {
        return iterator_to_array($this, false);
    }
}


text:
package com.redthirddivision.mods.am2;

import java.util.ArrayList;
import java.util.List;

import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;

import com.redthirddivision.mods.am2.proxies.CommonProxy;
import com.redthirddivision.mods.am2.utils.LogHelper;

/**
 * Project: Minecraft

 * File: AimlessMod2.java
 *
 * @author  Matthew Rogers
 */
@Mod(name = Constants.MOD_NAME, version = Constants.MOD_VERSION, modid = Constants.MOD_ID, useMetadata = true)
public class AimlessMod2 implements Constants {

    private static final List<String> authors = new ArrayList<String>();

    @Instance(MOD_ID)
    public static AimlessMod2         instance;

    @SidedProxy(clientSide = PROXY_CLIENT, serverSide = PROXY_SERVER)
    public static CommonProxy         proxy;

    @EventHandler
    public void preInit(FMLPreInitializationEvent e) {
        LogHelper.init();
        authors.add("BossLetsPlays");
        e.getModMetadata().authorList = authors;
        e.getModMetadata().version = MOD_VERSION;
        e.getModMetadata().description = "Aimless; No goal; Adds a bunch of random fun crap";
        e.getModMetadata().name = MOD_NAME;
        e.getModMetadata().modId = MOD_ID;

        proxy.registerRenders();
        proxy.preInit(e);
    }

    @EventHandler
    public void init(FMLInitializationEvent e) {
        proxy.init(e);
    }

    @EventHandler
    public void postInit(FMLPostInitializationEvent e) {
        proxy.postInit(e);
    }
}


text:
<?php

/* La class qui va gerer un membre , tout ce que peut faire un membre */

class ManagerMembre
{
	// Les constantes de la classe

    const ERR_IS_CO =  'Vous etes deja connecter';
    const ERR_IS_NOT_CO =  'Vous devez d\'abord vous connecter ';
    const VALIDE = 1 ;
    const NON_VALIDE = 0;
    const ERR_AUTH_ADMIN = "Acces restraint aux Administrateurs ";

	protected $_db;
	protected $_errors = array();
	public $nombresErreurs = 0;

	public function __construct(PDO $db)
	{
		$this->setDb($db) ;
	}

	public function setDb($db)
	{
		$this->_db = $db ;
	}

	public function pseudoLibre($pseudo)
	{
		$req = $this->_db->prepare("SELECT COUNT(*)
			                 AS nbr
			                 FROM membres
			                 WHERE pseudo = :pseudo");
		$req->bindValue(":pseudo",$pseudo,PDO::PARAM_STR);
		$req->execute();
		$nombresMembres = $req->fetchColumn();

		if($nombresMembres != 0)
		{
			$this->nombresErreurs++;
			$this->_errors["pseudo1"] = "Votre pseudo est dejas pris , nous sommes desolé ";
		}

	}

	public function pseudoValide($pseudo)
	{
		if (strlen($pseudo) < 3 || strlen($pseudo) > 15  || !preg_match('#^[a-zA-Z0-9_]+$#',$pseudo))
        {
               $this->_errors["pseudo2"] = "Votre pseudo est soit trop grand, soit trop petit, soit il ne respecte les caracteres autorisées";
               $this->nombresErreurs++;
        }

	}

	public function emailValide($email)
	{
		$query = $this->_db->prepare('SELECT COUNT(*) AS nbr FROM membres WHERE email =:mail');
        $query->bindValue(':mail',$email, PDO::PARAM_STR);
        $query->execute();
        $nombresEmails = $query->fetchColumn();

        if($nombresEmails != 0 || empty($email) || !filter_var($email,FILTER_VALIDATE_EMAIL))
        {
        	$this->nombresErreurs++;
        	$this->_errors["mail1"] = " Votre email est soit deja prise , soit ne respecte pas le format ";
        }

	}

    public function verifyPassword(Membre $membreAInscrire)
    {
    	$password = $membreAInscrire->password();
    	$confirmPassword = $membreAInscrire->confirmPassword();

    	if($password != $confirmPassword || empty($confirmPassword) || empty($password))
        {
            $this->_errors["password"] = "Votre mot de passe et votre confirmation diffèrent, ou sont vides";
            $this->nombresErreurs++;
        }

        else{

	  	   $pass = PASSWORD_HASH($membreAInscrire->password(),PASSWORD_BCRYPT);
	       $membreAInscrire->setPassword($pass);
	       $membreAInscrire->setConfirmPassword(NULL);
        }
    }

    /*
    **@function retuourne true  si l'image est bien uploader , false si non;
    */

    public function verifAvatar($avatar)
    {
		  if (!empty($avatar['size']))
		  {
		    //On définit les variables :

		    $maxsize = 54000; //Poid de l'image
		    $maxwidth = 500; //Largeur de l'image
		    $maxheight = 500; //Longueur de l'image

		    $extensions_valides = array( 'jpg' , 'jpeg' , 'gif' , 'png', 'bmp' );

		    //Liste des extensions valides

		    if ($avatar['error'] > 0)
		    {
			      $this->_errors["avatar1"] = "Erreur lors du transfert de l'avatar  ";
			      $this->nombresErreurs++;
		    }

		    if ($avatar['size'] > $maxsize)
		    {
		        $this->nombresErreurs++;
		        $this->_errors["avatar2"] = 'Le fichier est trop gros :('.$avatar['size'].' Octets contre '.$maxsize.' Octets)';
		    }

		    $image_sizes = getimagesize($avatar['tmp_name']);

		    if ($image_sizes[0] > $maxwidth OR $image_sizes[1] > $maxheight)
		    {
			      $this->nombresErreurs++;
			      $this->_errors["avatar3"] = "Image trop large ou trop longue : (".$image_sizes[0]."x".$image_sizes[1]." contre
			      ".$maxwidth."x".$maxheight.")";
		    }

		    $extension_upload = strtolower(substr(strrchr($avatar['name'], '.') ,1));

		    if(!in_array($extension_upload,$extensions_valides) )
		    {
			      $this->nombresErreurs++;
			      $this->_errors["avatar4"] = "Extension de l'avatar incorrecte";
		    }

		      return TRUE;

		  }
		  else
		  	 return FALSE;
    }

    public function inscription(Membre $membreA)
    {
    	$query = $this->_db->prepare("INSERT INTO membres(pseudo,password, email, avatar, inscrit,token)
                                      VALUES(:pseudo, :pass, :email , :nomavatar, NULL, :token)");
    	$query->execute(array("pseudo" => $membreA->pseudo(),
    		                  "pass"   => $membreA->password(),
    		                  "email"  => $membreA->email(),
    		                  "nomavatar" => $membreA->avatar(),
    		                  "token"     => $membreA->token()));
    	$query->closeCursor();

    	$id = $this->_db->lastInsertId();
    	$token = $membreA->token();

    	$membreA->setID($id);

    	$this->envoyerMail($membreA->email() , "Inscription sur le Site du Savoir", "Cliquez ou copier le lien dans votre navigateur https://".$_SERVER['SERVER_NAME']."/confirm.php?id=$id&token=$token");

    }

    public function envoyerMail($email,$titre,$message,$header="sitedusavoir.com")
    {
         mail($email,$titre,$message,$header);
    }

	public function errors()
	{
         return $this->_errors;
    }

    public function infosMembre($info,$dateInscription = 'IS NOT NULL')
    {
    	  $id = (int)$info;

    	  if($id == 0)
    	  {
    	  	    $query = $this->_db->prepare('
    	  	    	                          SELECT id,pseudo,password,siteweb,email,signature,avatar,localisation,token,cookiee,reset,reset_at,rang,posts,inscrit, visite
    	  	    	                          FROM membres
    	  	    	                          WHERE pseudo = :info AND inscrit '.$dateInscription);

    		    $query->bindValue(':info',$info,PDO::PARAM_STR);

          }
          else
          {
          	    $query = $this->_db->prepare('
          	    	                          SELECT id,pseudo,password,siteweb,email,avatar,signature,localisation,token,cookiee,reset,reset_at,rang,posts, inscrit , visite
    	  	    	                          FROM membres
    	  	    	                          WHERE id = :info AND inscrit '.$dateInscription);

    		    $query->bindValue(':info',$info,PDO::PARAM_INT);

          }

            $query->execute();

            $donnees = $query->fetch();

            if(!empty($donnees))
                    return $donnees;
            else
                return array();
    }

    /*
    **@function mise ajours infos
    **@param Membre
    **
    */

    public function miseAjoursMembre(Membre $membreAjour)
    {
    	$query = $this->_db->prepare('UPDATE membres SET pseudo = :pseudo ,email = :mail , password = :password , posts = :posts ,localisation = :localisation,signature = :signature , siteweb = :siteweb ,avatar = :avatar WHERE id = :id');

    	$query->execute(array(

    		    'id' => $membreAjour->id(),
    		    'pseudo' => $membreAjour->pseudo(),
    		    'password' => $membreAjour->password(),
    		    'mail' => $membreAjour->email(),
                'localisation' => $membreAjour->localisation(),
                'avatar' => $membreAjour->avatar(),
                'siteweb' => $membreAjour->siteweb(),
                'signature' => $membreAjour->signature(),
                'posts'     => $membreAjour->posts()
    		));

    	$query->closeCursor();
    }

    /*
    *@function confrirmerCompte
    **@param Membre
    ** Permet de confirmer un compte d'utilisateur
    */

    public function confirmerCompte(Membre $membre)
    {
        $query = $this->_db->prepare('UPDATE membres SET visite = NOW() ,inscrit = NOW() ,token = NULL
        	                          WHERE id = :id');
        $query->bindValue(":id",$membre->id(),PDO::PARAM_INT);
        $query->execute();
    }

    /*
    **@function reconnected_from_cookie
    ** Reconnecte un utilisateur s'il a un cookie poster dans son navigateur
    */

    public function reconnected_from_cookie()
    {

		if(session_status() == PHP_SESSION_NONE)
		{
		    session_start();
		}

	    if(isset($_COOKIE['souvenir']) && !isset($_SESSION['id']))
	    {

	       $cookie = $_COOKIE['souvenir'];
	       $parts =  explode('==',$cookie);
	       $user_id = $parts[0];

	       $donnees = $this->infosMembre($user_id);

	       $membre = new Membre($donnees);

	       if($membre)
	       {
	            $expected = $user_id.'=='.$membre->cookiee().sha1($membre->id().'MALNUX667');

	            if($expected == $cookie)
	            {

	                setcookie('souvenir',$cookie,time()+60*60*24*7);

	                $_SESSION['pseudo'] = $membre->pseudo();
	                $_SESSION['level'] = $membre->rang();
	                $_SESSION['id'] = $membre->id();

	                $this->derniereVisite($membre->id());
	            }
	            else
	            {
	                  setcookie('souvenir',NULL,-1);
	            }

	        }

	        else
	        {
	          setcookie('souvenir',NULL,-1);
	        }

	     }
	}

	public function derniereVisite($id)
	{
		$query = $this->_db->prepare("UPDATE membres SET visite = NOW() WHERE id = :id");
		$query->bindValue(":id",$id, PDO::PARAM_INT);
		$query->execute();
	}

	public function souviensToiDeMoi($id ,$cookie)
	{
		$req = $this->_db->prepare("UPDATE membres
                                      SET cookiee = :cookie
                                      WHERE id = :id");

		$req->bindValue(':id',$id, PDO::PARAM_INT);
		$req->bindValue(':cookie',$cookie, PDO::PARAM_INT);
		$req->execute();

	}

	public function OublieMoi($id)
	{
		$query = $this->_db->prepare("UPDATE membres SET cookiee = NULL WHERE id = :id");
		$query->bindValue(':id' , $id ,PDO::PARAM_INT);
	}

	/*
	**@param array $donnees
	** retourne un membre si aucune erreur ne survienne , sinon renvoie NULL
	*/

	public function connexion(array $donnees)
	{

		if(empty($donnees['pseudo']) || empty($donnees['password']))
		{
			$this->_errors["champsVides"] = "Une erreure s'est produite vous devez remplir tous les champs";
			$this->nombresErreurs++;

		}
		else
		{
			$datas = $this->infosMembre($donnees["pseudo"]);
			$membreAEnvoyer = new Membre($datas);

			if(PASSWORD_VERIFY($donnees["password"] ,$membreAEnvoyer->password()))
			{
				if($membreAEnvoyer->rang() == 0 )
				{
					$this->nombresErreurs++;
				    $this->_errors["rang"] = "Vous avez été Banni du site , impossible de vous connecter sur ce site.";
				}
				else
				{
					if(!empty($donnees["souvenir"]))
					{
						$cookie = Membre::str_random(60);
						$this->souviensToiDeMoi($membreAEnvoyer->id() ,$cookie);
						setcookie('souvenir',$membreAEnvoyer->id().'=='.$cookie.sha1($membreAEnvoyer->id().'MALNUX667'),time() + 60 * 60 *24 *7 );

					}

					$_SESSION['pseudo'] = $membreAEnvoyer->pseudo();
    				$_SESSION['level'] = $membreAEnvoyer->rang();
    				$_SESSION['id'] = $membreAEnvoyer->id();
    				$_SESSION["flash"]["success"] = 'Bienvenue '.$membreAEnvoyer->pseudo().', vous êtes maintenant connecté ! ';

    				$this->derniereVisite($membreAEnvoyer->id());
				}

			}
			else
			{
				$this->nombresErreurs++;
				$this->_errors["Motdepasse"] = "Mot de passe ou pseudo incorrecte veuillez reessayez";
			}

		}

		if($this->nombresErreurs != 0)
		{
			return NULL;
		}
		else
		{
			return $membreAEnvoyer;
		}

	}

	public function totalDesMembres()
	{
		$query = $this->_db->query('SELECT COUNT(*) AS nbr FROM membres');
		$donnees = $query->fetch();

		return $donnees["nbr"];
	}

	public function dernierInscrit()
	{
		$query = $this->_db->query('SELECT * FROM membres ORDER BY id DESC LIMIT 0, 1');
		$donnees = $query->fetch();

		return $donnees;
	}

	public function augmenterNombrePostMembre($idMembre)
	{
		$query = $this->_db->prepare('UPDATE membres SET posts = posts + 1 WHERE id = :id');

		$query->bindValue(':id', $idMembre, PDO::PARAM_INT);
		$query->execute();
		$query->CloseCursor();

	}

	public function diminuerNombrePostMembre($idMembre , $nbrePost = -1)
	{
		$query = $this->_db->prepare('UPDATE membres SET posts = posts + :nbr WHERE id = :id');

		$query->bindValue(':id', $idMembre, PDO::PARAM_INT);
		$query->bindValue(':nbr' , $nbrePost , PDO::PARAM_INT);
		$query->execute();
		$query->CloseCursor();

	}

	public function listeDesMembres($premier , $membreParPage , $champOrdre , $ordre)
	{
		$query = $this->_db->prepare('SELECT id, pseudo,inscrit, posts, visite, online_id
                          FROM membres
                          LEFT JOIN whoisonline
                          ON online_id = id
                          ORDER BY '.$champOrdre.' '.$ordre.'
                          LIMIT :premier, :membreparpage');

        $query->bindValue(':premier',$premier,PDO::PARAM_INT);
        $query->bindValue(':membreparpage',$membreParPage, PDO::PARAM_INT);
        $query->execute();

        $datas = $query->fetchAll();

        return $datas;
	}

	public function infosMembreParEmail($email)
	{
		$req = $this->_db->prepare('SELECT * FROM membres WHERE email = :email AND inscrit IS NOT NULL');
        $req->execute(array('email' => $email));

        $user = $req->fetch();

        if(!empty($user))
               return $user;
        else
            return array();
	}

	public function prepareInitialisationPassword($idM)
	{
		$token = Membre::str_random(60);
        $req = $this->_db->prepare('UPDATE membres SET reset = :token , reset_at = NOW() WHERE id = :id');

        $req->execute(array(
                            'token'=> $token,
                            'id'  => $idM
      ));

        return $token;
	}

	public function initialisationPassword($membre)
	{
		$req = $this->_db->prepare('UPDATE membres SET password = :pass, reset = NULL, reset_at = NULL WHERE id = :id');
            $req->execute(array('pass'=> $membre->password(),'id'=> $membre->id()));
	}

	public function tousLesBannis()
	{
		$query = $this->_db->query('SELECT id, pseudo FROM membres WHERE rang = 0');
		$datas = $query->fetchAll();

		return $datas;
	}

	public function recupereLeMembre($pseudo)
	{
		$query = $this->_db->prepare('SELECT * FROM membres WHERE LOWER(pseudo) = :pseudo');
		$query->bindValue(':pseudo', strtolower($pseudo) , PDO::PARAM_STR);
		$query->execute();

		$data = $query->fetch();
		return $data;
	}

	public function promouvoirMembre(Membre $membre)
	{
		 $query = $this->_db->prepare('UPDATE membres
                                  SET rang = :rang
                                  WHERE LOWER(pseudo) = :pseudo');

            $query->bindValue(':rang',(int)$membre->rang(), PDO::PARAM_INT);
            $query->bindValue(':pseudo',strtolower($membre->pseudo()), PDO::PARAM_STR);

            $query->execute();
            $query->CloseCursor();
	}

}


text:
from google.cloud import dialogflow_v2

def sample_get_version():
    # Create a client
    client = dialogflow_v2.VersionsClient()

    # Initialize request argument(s)
    request = dialogflow_v2.GetVersionRequest(
        name="name_value",
    )

    # Make the request
    response = client.get_version(request=request)

    # Handle the response
    print(response)

# [END dialogflow_v2_generated_Versions_GetVersion_sync]


text:
<?php

namespace Phs\Backend\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\EntityManager;

use Phs\Backend\Entity\Users;

class AdminPanelController extends Controller
{

  /**
  *The main of file when login into Backend
  **/
  public function indexAction(){
    $checklogin = $this->get('authlogin')->checkLogin();
    if($checklogin == 0){
      return $this->redirectToRoute("logincp");
    }
  }

/**
* Function: Login into System
* Return:
*/
  public function loginAction(){
    $checklogin = $this->get('authlogin')->checkLogin();
    if($checklogin == 0){
        $request = Request::createFromGlobals();
        $result = "";
        $name = $request->request->get('username');
        $pass = $request->request->get('userpass');
        $params = array(
          'username'=>$name,
          'userpass'=>$pass,
        );

        $db = $this->getDoctrine()->getManager();
        $result = $db->getDoctrine()->getRepository('BackendBundle:Users')->findOneBy($params);

        if(!$result){
          $result = "User not exits";
        }else {
          //Set session
          $this->get('authlogin')->setSessiongLogin($result->getUsername(),$result->getId(),$result->getUsertype());
          return $this->redirectToRoute('admincp');
        }
        return $this->render('backend\login.html.twig');
    }else{
      return redirectToRoute('admincp');
    }
  }
}


text:
#include "wabt/validator.h"

#include <cassert>
#include <cinttypes>
#include <cstdarg>
#include <cstdio>

#include "wabt/config.h"

#include "wabt/binary-reader.h"
#include "wabt/cast.h"
#include "wabt/expr-visitor.h"
#include "wabt/ir.h"
#include "wabt/shared-validator.h"

namespace wabt {

namespace {

class ScriptValidator {
 public:
  WABT_DISALLOW_COPY_AND_ASSIGN(ScriptValidator);
  ScriptValidator(Errors*, const Script*, const ValidateOptions& options);

  Result CheckScript();

 private:
  struct ActionResult {
    enum class Kind {
      Error,
      Types,
      Type,
    } kind;

    union {
      const TypeVector* types;
      Type type;
    };
  };

  void WABT_PRINTF_FORMAT(3, 4)
      PrintError(const Location* loc, const char* fmt, ...);
  void CheckTypeIndex(const Location* loc,
                      Type actual,
                      Type expected,
                      const char* desc,
                      Index index,
                      const char* index_kind);
  void CheckResultTypes(const Location* loc,
                        const TypeVector& actual,
                        const TypeVector& expected,
                        const char* desc);

  const TypeVector* CheckInvoke(const InvokeAction* action);
  Result CheckGet(const GetAction* action, Type* out_type);
  ActionResult CheckAction(const Action* action);
  void CheckCommand(const Command* command);

  const ValidateOptions& options_;
  Errors* errors_ = nullptr;
  const Script* script_ = nullptr;

  Result result_ = Result::Ok;
};

class Validator : public ExprVisitor::Delegate {
 public:
  Validator(Errors*, const Module* module, const ValidateOptions& options);

  Result CheckModule();

  Result OnBinaryExpr(BinaryExpr*) override;
  Result BeginBlockExpr(BlockExpr*) override;
  Result EndBlockExpr(BlockExpr*) override;
  Result OnBrExpr(BrExpr*) override;
  Result OnBrIfExpr(BrIfExpr*) override;
  Result OnBrTableExpr(BrTableExpr*) override;
  Result OnCallExpr(CallExpr*) override;
  Result OnCallIndirectExpr(CallIndirectExpr*) override;
  Result OnCallRefExpr(CallRefExpr*) override;
  Result OnCodeMetadataExpr(CodeMetadataExpr*) override;
  Result OnCompareExpr(CompareExpr*) override;
  Result OnConstExpr(ConstExpr*) override;
  Result OnConvertExpr(ConvertExpr*) override;
  Result OnDropExpr(DropExpr*) override;
  Result OnGlobalGetExpr(GlobalGetExpr*) override;
  Result OnGlobalSetExpr(GlobalSetExpr*) override;
  Result BeginIfExpr(IfExpr*) override;
  Result AfterIfTrueExpr(IfExpr*) override;
  Result EndIfExpr(IfExpr*) override;
  Result OnLoadExpr(LoadExpr*) override;
  Result OnLocalGetExpr(LocalGetExpr*) override;
  Result OnLocalSetExpr(LocalSetExpr*) override;
  Result OnLocalTeeExpr(LocalTeeExpr*) override;
  Result BeginLoopExpr(LoopExpr*) override;
  Result EndLoopExpr(LoopExpr*) override;
  Result OnMemoryCopyExpr(MemoryCopyExpr*) override;
  Result OnDataDropExpr(DataDropExpr*) override;
  Result OnMemoryFillExpr(MemoryFillExpr*) override;
  Result OnMemoryGrowExpr(MemoryGrowExpr*) override;
  Result OnMemoryInitExpr(MemoryInitExpr*) override;
  Result OnMemorySizeExpr(MemorySizeExpr*) override;
  Result OnTableCopyExpr(TableCopyExpr*) override;
  Result OnElemDropExpr(ElemDropExpr*) override;
  Result OnTableInitExpr(TableInitExpr*) override;
  Result OnTableGetExpr(TableGetExpr*) override;
  Result OnTableSetExpr(TableSetExpr*) override;
  Result OnTableGrowExpr(TableGrowExpr*) override;
  Result OnTableSizeExpr(TableSizeExpr*) override;
  Result OnTableFillExpr(TableFillExpr*) override;
  Result OnRefFuncExpr(RefFuncExpr*) override;
  Result OnRefNullExpr(RefNullExpr*) override;
  Result OnRefIsNullExpr(RefIsNullExpr*) override;
  Result OnNopExpr(NopExpr*) override;
  Result OnReturnExpr(ReturnExpr*) override;
  Result OnReturnCallExpr(ReturnCallExpr*) override;
  Result OnReturnCallIndirectExpr(ReturnCallIndirectExpr*) override;
  Result OnSelectExpr(SelectExpr*) override;
  Result OnStoreExpr(StoreExpr*) override;
  Result OnUnaryExpr(UnaryExpr*) override;
  Result OnUnreachableExpr(UnreachableExpr*) override;
  Result BeginTryExpr(TryExpr*) override;
  Result OnCatchExpr(TryExpr*, Catch*) override;
  Result OnDelegateExpr(TryExpr*) override;
  Result EndTryExpr(TryExpr*) override;
  Result OnThrowExpr(ThrowExpr*) override;
  Result OnRethrowExpr(RethrowExpr*) override;
  Result OnAtomicWaitExpr(AtomicWaitExpr*) override;
  Result OnAtomicFenceExpr(AtomicFenceExpr*) override;
  Result OnAtomicNotifyExpr(AtomicNotifyExpr*) override;
  Result OnAtomicLoadExpr(AtomicLoadExpr*) override;
  Result OnAtomicStoreExpr(AtomicStoreExpr*) override;
  Result OnAtomicRmwExpr(AtomicRmwExpr*) override;
  Result OnAtomicRmwCmpxchgExpr(AtomicRmwCmpxchgExpr*) override;
  Result OnTernaryExpr(TernaryExpr*) override;
  Result OnSimdLaneOpExpr(SimdLaneOpExpr*) override;
  Result OnSimdLoadLaneExpr(SimdLoadLaneExpr*) override;
  Result OnSimdStoreLaneExpr(SimdStoreLaneExpr*) override;
  Result OnSimdShuffleOpExpr(SimdShuffleOpExpr*) override;
  Result OnLoadSplatExpr(LoadSplatExpr*) override;
  Result OnLoadZeroExpr(LoadZeroExpr*) override;

 private:
  Type GetDeclarationType(const FuncDeclaration&);
  Var GetFuncTypeIndex(const Location&, const FuncDeclaration&);

  const ValidateOptions& options_;
  Errors* errors_ = nullptr;
  SharedValidator validator_;
  const Module* current_module_ = nullptr;
  Result result_ = Result::Ok;
};

ScriptValidator::ScriptValidator(Errors* errors,
                                 const Script* script,
                                 const ValidateOptions& options)
    : options_(options), errors_(errors), script_(script) {}

void ScriptValidator::PrintError(const Location* loc, const char* format, ...) {
  result_ = Result::Error;
  WABT_SNPRINTF_ALLOCA(buffer, length, format);
  errors_->emplace_back(ErrorLevel::Error, *loc, buffer);
}

void ScriptValidator::CheckTypeIndex(const Location* loc,
                                     Type actual,
                                     Type expected,
                                     const char* desc,
                                     Index index,
                                     const char* index_kind) {
  if (Failed(TypeChecker::CheckType(actual, expected))) {
    PrintError(loc,
               "type mismatch for %s %" PRIindex " of %s. got %s, expected %s",
               index_kind, index, desc, actual.GetName().c_str(),
               expected.GetName().c_str());
  }
}

void ScriptValidator::CheckResultTypes(const Location* loc,
                                       const TypeVector& actual,
                                       const TypeVector& expected,
                                       const char* desc) {
  if (actual.size() == expected.size()) {
    for (size_t i = 0; i < actual.size(); ++i) {
      CheckTypeIndex(loc, actual[i], expected[i], desc, i, "result");
    }
  } else {
    PrintError(loc, "expected %" PRIzd " results, got %" PRIzd, expected.size(),
               actual.size());
  }
}

Type Validator::GetDeclarationType(const FuncDeclaration& decl) {
  if (decl.has_func_type) {
    return Type(decl.type_var.index());
  }
  if (decl.sig.param_types.empty()) {
    if (decl.sig.result_types.empty()) {
      return Type::Void;
    }
    if (decl.sig.result_types.size() == 1) {
      return decl.sig.result_types[0];
    }
  }
  return Type(current_module_->GetFuncTypeIndex(decl));
}

Var Validator::GetFuncTypeIndex(const Location& default_loc,
                                const FuncDeclaration& decl) {
  if (decl.has_func_type) {
    return decl.type_var;
  }
  return Var(current_module_->GetFuncTypeIndex(decl), default_loc);
}

Result Validator::OnBinaryExpr(BinaryExpr* expr) {
  result_ |= validator_.OnBinary(expr->loc, expr->opcode);
  return Result::Ok;
}

Result Validator::BeginBlockExpr(BlockExpr* expr) {
  result_ |=
      validator_.OnBlock(expr->loc, GetDeclarationType(expr->block.decl));
  return Result::Ok;
}

Result Validator::EndBlockExpr(BlockExpr* expr) {
  result_ |= validator_.OnEnd(expr->block.end_loc);
  return Result::Ok;
}

Result Validator::OnBrExpr(BrExpr* expr) {
  result_ |= validator_.OnBr(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnBrIfExpr(BrIfExpr* expr) {
  result_ |= validator_.OnBrIf(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnBrTableExpr(BrTableExpr* expr) {
  result_ |= validator_.BeginBrTable(expr->loc);
  for (const Var& var : expr->targets) {
    result_ |= validator_.OnBrTableTarget(expr->loc, var);
  }
  result_ |= validator_.OnBrTableTarget(expr->loc, expr->default_target);
  result_ |= validator_.EndBrTable(expr->loc);
  return Result::Ok;
}

Result Validator::OnCallExpr(CallExpr* expr) {
  result_ |= validator_.OnCall(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnCallIndirectExpr(CallIndirectExpr* expr) {
  result_ |= validator_.OnCallIndirect(
      expr->loc, GetFuncTypeIndex(expr->loc, expr->decl), expr->table);
  return Result::Ok;
}

Result Validator::OnCallRefExpr(CallRefExpr* expr) {
  Index function_type_index;
  result_ |= validator_.OnCallRef(expr->loc, &function_type_index);
  if (Succeeded(result_)) {
    expr->function_type_index = Var{function_type_index, expr->loc};
    return Result::Ok;
  }

  return Result::Error;
}

Result Validator::OnCodeMetadataExpr(CodeMetadataExpr* expr) {
  return Result::Ok;
}

Result Validator::OnCompareExpr(CompareExpr* expr) {
  result_ |= validator_.OnCompare(expr->loc, expr->opcode);
  return Result::Ok;
}

Result Validator::OnConstExpr(ConstExpr* expr) {
  result_ |= validator_.OnConst(expr->loc, expr->const_.type());
  return Result::Ok;
}

Result Validator::OnConvertExpr(ConvertExpr* expr) {
  result_ |= validator_.OnConvert(expr->loc, expr->opcode);
  return Result::Ok;
}

Result Validator::OnDropExpr(DropExpr* expr) {
  result_ |= validator_.OnDrop(expr->loc);
  return Result::Ok;
}

Result Validator::OnGlobalGetExpr(GlobalGetExpr* expr) {
  result_ |= validator_.OnGlobalGet(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnGlobalSetExpr(GlobalSetExpr* expr) {
  result_ |= validator_.OnGlobalSet(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::BeginIfExpr(IfExpr* expr) {
  result_ |= validator_.OnIf(expr->loc, GetDeclarationType(expr->true_.decl));
  return Result::Ok;
}

Result Validator::AfterIfTrueExpr(IfExpr* expr) {
  if (!expr->false_.empty()) {
    result_ |= validator_.OnElse(expr->true_.end_loc);
  }
  return Result::Ok;
}

Result Validator::EndIfExpr(IfExpr* expr) {
  result_ |= validator_.OnEnd(expr->false_.empty() ? expr->true_.end_loc
                                                   : expr->false_end_loc);
  return Result::Ok;
}

Result Validator::OnLoadExpr(LoadExpr* expr) {
  result_ |= validator_.OnLoad(expr->loc, expr->opcode, expr->memidx,
                               expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnLocalGetExpr(LocalGetExpr* expr) {
  result_ |= validator_.OnLocalGet(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnLocalSetExpr(LocalSetExpr* expr) {
  result_ |= validator_.OnLocalSet(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnLocalTeeExpr(LocalTeeExpr* expr) {
  result_ |= validator_.OnLocalTee(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::BeginLoopExpr(LoopExpr* expr) {
  result_ |= validator_.OnLoop(expr->loc, GetDeclarationType(expr->block.decl));
  return Result::Ok;
}

Result Validator::EndLoopExpr(LoopExpr* expr) {
  result_ |= validator_.OnEnd(expr->block.end_loc);
  return Result::Ok;
}

Result Validator::OnMemoryCopyExpr(MemoryCopyExpr* expr) {
  result_ |=
      validator_.OnMemoryCopy(expr->loc, expr->srcmemidx, expr->destmemidx);
  return Result::Ok;
}

Result Validator::OnDataDropExpr(DataDropExpr* expr) {
  result_ |= validator_.OnDataDrop(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnMemoryFillExpr(MemoryFillExpr* expr) {
  result_ |= validator_.OnMemoryFill(expr->loc, expr->memidx);
  return Result::Ok;
}

Result Validator::OnMemoryGrowExpr(MemoryGrowExpr* expr) {
  result_ |= validator_.OnMemoryGrow(expr->loc, expr->memidx);
  return Result::Ok;
}

Result Validator::OnMemoryInitExpr(MemoryInitExpr* expr) {
  result_ |= validator_.OnMemoryInit(expr->loc, expr->var, expr->memidx);
  return Result::Ok;
}

Result Validator::OnMemorySizeExpr(MemorySizeExpr* expr) {
  result_ |= validator_.OnMemorySize(expr->loc, expr->memidx);
  return Result::Ok;
}

Result Validator::OnTableCopyExpr(TableCopyExpr* expr) {
  result_ |=
      validator_.OnTableCopy(expr->loc, expr->dst_table, expr->src_table);
  return Result::Ok;
}

Result Validator::OnElemDropExpr(ElemDropExpr* expr) {
  result_ |= validator_.OnElemDrop(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnTableInitExpr(TableInitExpr* expr) {
  result_ |=
      validator_.OnTableInit(expr->loc, expr->segment_index, expr->table_index);
  return Result::Ok;
}

Result Validator::OnTableGetExpr(TableGetExpr* expr) {
  result_ |= validator_.OnTableGet(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnTableSetExpr(TableSetExpr* expr) {
  result_ |= validator_.OnTableSet(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnTableGrowExpr(TableGrowExpr* expr) {
  result_ |= validator_.OnTableGrow(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnTableSizeExpr(TableSizeExpr* expr) {
  result_ |= validator_.OnTableSize(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnTableFillExpr(TableFillExpr* expr) {
  result_ |= validator_.OnTableFill(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnRefFuncExpr(RefFuncExpr* expr) {
  result_ |= validator_.OnRefFunc(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnRefNullExpr(RefNullExpr* expr) {
  result_ |= validator_.OnRefNull(expr->loc, expr->type);
  return Result::Ok;
}

Result Validator::OnRefIsNullExpr(RefIsNullExpr* expr) {
  result_ |= validator_.OnRefIsNull(expr->loc);
  return Result::Ok;
}

Result Validator::OnNopExpr(NopExpr* expr) {
  result_ |= validator_.OnNop(expr->loc);
  return Result::Ok;
}

Result Validator::OnReturnExpr(ReturnExpr* expr) {
  result_ |= validator_.OnReturn(expr->loc);
  return Result::Ok;
}

Result Validator::OnReturnCallExpr(ReturnCallExpr* expr) {
  result_ |= validator_.OnReturnCall(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnReturnCallIndirectExpr(ReturnCallIndirectExpr* expr) {
  result_ |= validator_.OnReturnCallIndirect(
      expr->loc, GetFuncTypeIndex(expr->loc, expr->decl), expr->table);
  return Result::Ok;
}

Result Validator::OnSelectExpr(SelectExpr* expr) {
  result_ |= validator_.OnSelect(expr->loc, expr->result_type.size(),
                                 expr->result_type.data());
  // TODO: Existing behavior fails when select fails.
#if 0
  return Result::Ok;
#else
  return result_;
#endif
}

Result Validator::OnStoreExpr(StoreExpr* expr) {
  result_ |= validator_.OnStore(expr->loc, expr->opcode, expr->memidx,
                                expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnUnaryExpr(UnaryExpr* expr) {
  result_ |= validator_.OnUnary(expr->loc, expr->opcode);
  return Result::Ok;
}

Result Validator::OnUnreachableExpr(UnreachableExpr* expr) {
  result_ |= validator_.OnUnreachable(expr->loc);
  return Result::Ok;
}

Result Validator::BeginTryExpr(TryExpr* expr) {
  result_ |= validator_.OnTry(expr->loc, GetDeclarationType(expr->block.decl));
  return Result::Ok;
}

Result Validator::OnCatchExpr(TryExpr*, Catch* catch_) {
  result_ |= validator_.OnCatch(catch_->loc, catch_->var, catch_->IsCatchAll());
  return Result::Ok;
}

Result Validator::OnDelegateExpr(TryExpr* expr) {
  result_ |= validator_.OnDelegate(expr->loc, expr->delegate_target);
  return Result::Ok;
}

Result Validator::EndTryExpr(TryExpr* expr) {
  result_ |= validator_.OnEnd(expr->block.end_loc);
  return Result::Ok;
}

Result Validator::OnThrowExpr(ThrowExpr* expr) {
  result_ |= validator_.OnThrow(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnRethrowExpr(RethrowExpr* expr) {
  result_ |= validator_.OnRethrow(expr->loc, expr->var);
  return Result::Ok;
}

Result Validator::OnAtomicWaitExpr(AtomicWaitExpr* expr) {
  result_ |= validator_.OnAtomicWait(expr->loc, expr->opcode, expr->memidx,
                                     expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnAtomicFenceExpr(AtomicFenceExpr* expr) {
  result_ |= validator_.OnAtomicFence(expr->loc, expr->consistency_model);
  return Result::Ok;
}

Result Validator::OnAtomicNotifyExpr(AtomicNotifyExpr* expr) {
  result_ |= validator_.OnAtomicNotify(expr->loc, expr->opcode, expr->memidx,
                                       expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnAtomicLoadExpr(AtomicLoadExpr* expr) {
  result_ |= validator_.OnAtomicLoad(expr->loc, expr->opcode, expr->memidx,
                                     expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnAtomicStoreExpr(AtomicStoreExpr* expr) {
  result_ |= validator_.OnAtomicStore(expr->loc, expr->opcode, expr->memidx,
                                      expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnAtomicRmwExpr(AtomicRmwExpr* expr) {
  result_ |= validator_.OnAtomicRmw(expr->loc, expr->opcode, expr->memidx,
                                    expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnAtomicRmwCmpxchgExpr(AtomicRmwCmpxchgExpr* expr) {
  result_ |=
      validator_.OnAtomicRmwCmpxchg(expr->loc, expr->opcode, expr->memidx,
                                    expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnTernaryExpr(TernaryExpr* expr) {
  result_ |= validator_.OnTernary(expr->loc, expr->opcode);
  return Result::Ok;
}

Result Validator::OnSimdLaneOpExpr(SimdLaneOpExpr* expr) {
  result_ |= validator_.OnSimdLaneOp(expr->loc, expr->opcode, expr->val);
  return Result::Ok;
}

Result Validator::OnSimdLoadLaneExpr(SimdLoadLaneExpr* expr) {
  result_ |= validator_.OnSimdLoadLane(expr->loc, expr->opcode, expr->memidx,
                                       expr->opcode.GetAlignment(expr->align),
                                       expr->val);
  return Result::Ok;
}

Result Validator::OnSimdStoreLaneExpr(SimdStoreLaneExpr* expr) {
  result_ |= validator_.OnSimdStoreLane(expr->loc, expr->opcode, expr->memidx,
                                        expr->opcode.GetAlignment(expr->align),
                                        expr->val);
  return Result::Ok;
}

Result Validator::OnSimdShuffleOpExpr(SimdShuffleOpExpr* expr) {
  result_ |= validator_.OnSimdShuffleOp(expr->loc, expr->opcode, expr->val);
  return Result::Ok;
}

Result Validator::OnLoadSplatExpr(LoadSplatExpr* expr) {
  result_ |= validator_.OnLoadSplat(expr->loc, expr->opcode, expr->memidx,
                                    expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Result Validator::OnLoadZeroExpr(LoadZeroExpr* expr) {
  result_ |= validator_.OnLoadZero(expr->loc, expr->opcode, expr->memidx,
                                   expr->opcode.GetAlignment(expr->align));
  return Result::Ok;
}

Validator::Validator(Errors* errors,
                     const Module* module,
                     const ValidateOptions& options)
    : options_(options),
      errors_(errors),
      validator_(errors_, options_),
      current_module_(module) {}

Result Validator::CheckModule() {
  const Module* module = current_module_;

  // Type section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<TypeModuleField>(&field)) {
      switch (f->type->kind()) {
        case TypeEntryKind::Func: {
          FuncType* func_type = cast<FuncType>(f->type.get());
          result_ |= validator_.OnFuncType(
              field.loc, func_type->sig.param_types.size(),
              func_type->sig.param_types.data(),
              func_type->sig.result_types.size(),
              func_type->sig.result_types.data(),
              module->GetFuncTypeIndex(func_type->sig));
          break;
        }

        case TypeEntryKind::Struct: {
          StructType* struct_type = cast<StructType>(f->type.get());
          TypeMutVector type_muts;
          for (auto&& field : struct_type->fields) {
            type_muts.push_back(TypeMut{field.type, field.mutable_});
          }
          result_ |= validator_.OnStructType(field.loc, type_muts.size(),
                                             type_muts.data());
          break;
        }

        case TypeEntryKind::Array: {
          ArrayType* array_type = cast<ArrayType>(f->type.get());
          result_ |= validator_.OnArrayType(
              field.loc,
              TypeMut{array_type->field.type, array_type->field.mutable_});
          break;
        }
      }
    }
  }

  // Import section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<ImportModuleField>(&field)) {
      switch (f->import->kind()) {
        case ExternalKind::Func: {
          auto&& func = cast<FuncImport>(f->import.get())->func;
          result_ |= validator_.OnFunction(
              field.loc, GetFuncTypeIndex(field.loc, func.decl));
          break;
        }

        case ExternalKind::Table: {
          auto&& table = cast<TableImport>(f->import.get())->table;
          result_ |=
              validator_.OnTable(field.loc, table.elem_type, table.elem_limits);
          break;
        }

        case ExternalKind::Memory: {
          auto&& memory = cast<MemoryImport>(f->import.get())->memory;
          result_ |= validator_.OnMemory(field.loc, memory.page_limits);
          break;
        }

        case ExternalKind::Global: {
          auto&& global = cast<GlobalImport>(f->import.get())->global;
          result_ |= validator_.OnGlobalImport(field.loc, global.type,
                                               global.mutable_);
          break;
        }

        case ExternalKind::Tag: {
          auto&& tag = cast<TagImport>(f->import.get())->tag;
          result_ |= validator_.OnTag(field.loc,
                                      GetFuncTypeIndex(field.loc, tag.decl));
          break;
        }
      }
    }
  }

  // Func section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<FuncModuleField>(&field)) {
      result_ |= validator_.OnFunction(
          field.loc, GetFuncTypeIndex(field.loc, f->func.decl));
    }
  }

  // Table section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<TableModuleField>(&field)) {
      result_ |= validator_.OnTable(field.loc, f->table.elem_type,
                                    f->table.elem_limits);
    }
  }

  // Memory section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<MemoryModuleField>(&field)) {
      result_ |= validator_.OnMemory(field.loc, f->memory.page_limits);
    }
  }

  // Global section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<GlobalModuleField>(&field)) {
      result_ |=
          validator_.OnGlobal(field.loc, f->global.type, f->global.mutable_);

      // Init expr.
      result_ |= validator_.BeginInitExpr(field.loc, f->global.type);
      ExprVisitor visitor(this);
      result_ |=
          visitor.VisitExprList(const_cast<ExprList&>(f->global.init_expr));
      result_ |= validator_.EndInitExpr();
    }
  }

  // Tag section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<TagModuleField>(&field)) {
      result_ |=
          validator_.OnTag(field.loc, GetFuncTypeIndex(field.loc, f->tag.decl));
    }
  }

  // Export section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<ExportModuleField>(&field)) {
      result_ |= validator_.OnExport(field.loc, f->export_.kind, f->export_.var,
                                     f->export_.name);
    }
  }

  // Start section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<StartModuleField>(&field)) {
      result_ |= validator_.OnStart(field.loc, f->start);
    }
  }

  // Elem segment section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<ElemSegmentModuleField>(&field)) {
      result_ |= validator_.OnElemSegment(field.loc, f->elem_segment.table_var,
                                          f->elem_segment.kind);

      result_ |= validator_.OnElemSegmentElemType(field.loc,
                                                  f->elem_segment.elem_type);

      // Init expr.
      if (f->elem_segment.offset.size()) {
        result_ |= validator_.BeginInitExpr(field.loc, Type::I32);
        ExprVisitor visitor(this);
        result_ |= visitor.VisitExprList(
            const_cast<ExprList&>(f->elem_segment.offset));
        result_ |= validator_.EndInitExpr();
      }

      // Element expr.
      for (auto&& elem_expr : f->elem_segment.elem_exprs) {
        if (elem_expr.size() == 1) {
          const Expr* expr = &elem_expr.front();
          switch (expr->type()) {
            case ExprType::RefNull:
              result_ |= validator_.OnElemSegmentElemExpr_RefNull(
                  expr->loc, cast<RefNullExpr>(expr)->type);
              break;
            case ExprType::RefFunc:
              result_ |= validator_.OnElemSegmentElemExpr_RefFunc(
                  expr->loc, cast<RefFuncExpr>(expr)->var);
              break;
            default:
              result_ |= validator_.OnElemSegmentElemExpr_Other(expr->loc);
              break;
          }
        } else if (elem_expr.size() > 1) {
          result_ |= validator_.OnElemSegmentElemExpr_Other(field.loc);
        }
      }
    }
  }

  // DataCount section.
  validator_.OnDataCount(module->data_segments.size());

  // Code section.
  Index func_index = module->num_func_imports;
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<FuncModuleField>(&field)) {
      const Location& body_start = f->func.loc;
      const Location& body_end =
          f->func.exprs.empty() ? body_start : f->func.exprs.back().loc;
      result_ |= validator_.BeginFunctionBody(body_start, func_index++);

      for (auto&& decl : f->func.local_types.decls()) {
        result_ |= validator_.OnLocalDecl(body_start, decl.second, decl.first);
      }

      ExprVisitor visitor(this);
      result_ |= visitor.VisitExprList(const_cast<ExprList&>(f->func.exprs));
      result_ |= validator_.EndFunctionBody(body_end);
    }
  }

  // Data segment section.
  for (const ModuleField& field : module->fields) {
    if (auto* f = dyn_cast<DataSegmentModuleField>(&field)) {
      result_ |= validator_.OnDataSegment(field.loc, f->data_segment.memory_var,
                                          f->data_segment.kind);

      // Init expr.
      if (f->data_segment.offset.size()) {
        Type offset_type = Type::I32;
        Index memory_index = module->GetMemoryIndex(f->data_segment.memory_var);
        if (memory_index < module->memories.size() &&
            module->memories[memory_index]->page_limits.is_64) {
          offset_type = Type::I64;
        }
        result_ |= validator_.BeginInitExpr(field.loc, offset_type);
        ExprVisitor visitor(this);
        result_ |= visitor.VisitExprList(
            const_cast<ExprList&>(f->data_segment.offset));
        result_ |= validator_.EndInitExpr();
      }
    }
  }

  result_ |= validator_.EndModule();

  return result_;
}

// Returns the result type of the invoked function, checked by the caller;
// returning nullptr means that another error occured first, so the result type
// should be ignored.
const TypeVector* ScriptValidator::CheckInvoke(const InvokeAction* action) {
  const Module* module = script_->GetModule(action->module_var);
  if (!module) {
    PrintError(&action->loc, "unknown module");
    return nullptr;
  }

  const Export* export_ = module->GetExport(action->name);
  if (!export_) {
    PrintError(&action->loc, "unknown function export \"%s\"",
               action->name.c_str());
    return nullptr;
  }

  const Func* func = module->GetFunc(export_->var);
  if (!func) {
    // This error will have already been reported, just skip it.
    return nullptr;
  }

  size_t actual_args = action->args.size();
  size_t expected_args = func->GetNumParams();
  if (expected_args != actual_args) {
    PrintError(&action->loc,
               "too %s parameters to function. got %" PRIzd
               ", expected %" PRIzd,
               actual_args > expected_args ? "many" : "few", actual_args,
               expected_args);
    return nullptr;
  }
  for (size_t i = 0; i < actual_args; ++i) {
    const Const* const_ = &action->args[i];
    CheckTypeIndex(&const_->loc, const_->type(), func->GetParamType(i),
                   "invoke", i, "argument");
  }

  return &func->decl.sig.result_types;
}

Result ScriptValidator::CheckGet(const GetAction* action, Type* out_type) {
  const Module* module = script_->GetModule(action->module_var);
  if (!module) {
    PrintError(&action->loc, "unknown module");
    return Result::Error;
  }

  const Export* export_ = module->GetExport(action->name);
  if (!export_) {
    PrintError(&action->loc, "unknown global export \"%s\"",
               action->name.c_str());
    return Result::Error;
  }

  const Global* global = module->GetGlobal(export_->var);
  if (!global) {
    // This error will have already been reported, just skip it.
    return Result::Error;
  }

  *out_type = global->type;
  return Result::Ok;
}

ScriptValidator::ActionResult ScriptValidator::CheckAction(
    const Action* action) {
  ActionResult result;
  ZeroMemory(result);

  switch (action->type()) {
    case ActionType::Invoke:
      result.types = CheckInvoke(cast<InvokeAction>(action));
      result.kind =
          result.types ? ActionResult::Kind::Types : ActionResult::Kind::Error;
      break;

    case ActionType::Get:
      if (Succeeded(CheckGet(cast<GetAction>(action), &result.type))) {
        result.kind = ActionResult::Kind::Type;
      } else {
        result.kind = ActionResult::Kind::Error;
      }
      break;
  }

  return result;
}

void ScriptValidator::CheckCommand(const Command* command) {
  switch (command->type) {
    case CommandType::Module: {
      Validator module_validator(errors_, &cast<ModuleCommand>(command)->module,
                                 options_);
      module_validator.CheckModule();
      break;
    }

    case CommandType::ScriptModule: {
      Validator module_validator(
          errors_, &cast<ScriptModuleCommand>(command)->module, options_);
      module_validator.CheckModule();
      break;
    }

    case CommandType::Action:
      // Ignore result type.
      CheckAction(cast<ActionCommand>(command)->action.get());
      break;

    case CommandType::Register:
    case CommandType::AssertMalformed:
    case CommandType::AssertInvalid:
    case CommandType::AssertUnlinkable:
    case CommandType::AssertUninstantiable:
      // Ignore.
      break;

    case CommandType::AssertReturn: {
      auto* assert_return_command = cast<AssertReturnCommand>(command);
      const Action* action = assert_return_command->action.get();
      ActionResult result = CheckAction(action);
      // Here we take the concrete expected output types verify those actains
      // the types that are the result of the action.
      TypeVector actual_types;
      for (auto ex : assert_return_command->expected) {
        actual_types.push_back(ex.type());
      }
      switch (result.kind) {
        case ActionResult::Kind::Types:
          CheckResultTypes(&action->loc, actual_types, *result.types, "action");
          break;

        case ActionResult::Kind::Type:
          CheckResultTypes(&action->loc, actual_types, {result.type}, "action");
          break;

        case ActionResult::Kind::Error:
          // Error occurred, don't do any further checks.
          break;
      }
      break;
    }

    case CommandType::AssertTrap:
      // ignore result type.
      CheckAction(cast<AssertTrapCommand>(command)->action.get());
      break;
    case CommandType::AssertExhaustion:
      // ignore result type.
      CheckAction(cast<AssertExhaustionCommand>(command)->action.get());
      break;
    case CommandType::AssertException:
      // ignore result type.
      CheckAction(cast<AssertExceptionCommand>(command)->action.get());
      break;
  }
}

Result ScriptValidator::CheckScript() {
  for (const std::unique_ptr<Command>& command : script_->commands)
    CheckCommand(command.get());
  return result_;
}

}  // end anonymous namespace

Result ValidateScript(const Script* script,
                      Errors* errors,
                      const ValidateOptions& options) {
  ScriptValidator validator(errors, script, options);

  return validator.CheckScript();
}

Result ValidateModule(const Module* module,
                      Errors* errors,
                      const ValidateOptions& options) {
  Validator validator(errors, module, options);

  return validator.CheckModule();
}

}  // namespace wabt


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=struct.SEFMAP.html">

Redirecting to struct.SEFMAP.html...


text:
package uk.gov.nationalarchives.droid.profile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;

import org.apache.commons.io.DirectoryWalker;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.schlichtherle.truezip.zip.ZipFile;
import de.schlichtherle.truezip.zip.ZipEntry;
import de.schlichtherle.truezip.zip.ZipOutputStream;
import uk.gov.nationalarchives.droid.results.handlers.ProgressObserver;
import uk.gov.nationalarchives.droid.util.FileUtil;

/**
 * @author rflitcroft
 *
 */
public class ProfileDiskAction {

    private static final int UNITY_PERCENT = 100;
    private static final int BUFFER_SIZE = 8192;
    private static final char FORWARD_SLASH = '/';
    private static final char BACKWARD_SLASH = '\\';

    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * Saves the profile to disk by zipping it up.
     *
     * @param baseDir
     *            the base direcytory of the zip operation
     * @param destination
     *            the ntarget zip file
     * @param callback
     *            a progress observer, notified on progress
     * @throws IOException
     *             if a file IO operation failed
     */
    public void saveProfile(final Path baseDir, final Path destination,
            final ProgressObserver callback) throws IOException {

        log.info(String.format("Saving profile [%s] to [%s]", baseDir, destination));

        final Path output = destination.resolveSibling(destination.getFileName().toString() + ".tmp~");
        if (!FileUtil.deleteQuietly(output)) {
            String message = String.format("Could not delete original profile file: %s. "
                    + "Will try to delete on exit.", output.toAbsolutePath().toString());
            log.warn(message);
            output.toFile().deleteOnExit();
        }

        if (!Files.exists(output)) {
            try {
                Files.createFile(output);
            } catch (FileAlreadyExistsException e) {
                throw new IOException(String.format("Error creating tmp file [%s]", output));
            }
        }

        final ProfileWalker profileWalker = new ProfileWalker(baseDir, output, callback);

        try {
            profileWalker.save();
            callback.onProgress(UNITY_PERCENT);
            if (Files.exists(destination)) {
                if (!FileUtil.deleteQuietly(destination)) {
                    throw new IOException(String.format("Error removing old file [%s]", destination));
                }
            }
            if (!Files.exists(Files.move(output, destination))) {
                throw new IOException(String.format("Error creating saved file [%s]", destination));
            }
        } finally {
            profileWalker.close();
        }
    }

    /**
     * Walks directories and files in a profile.
     *
     * @author rflitcroft
     *
     */
    private final class ProfileWalker extends DirectoryWalker {
        private Path destination;
        private ZipOutputStream out;
        private Path source;
        private ProgressObserver callback;
        private final long bytesToProcess;
        private long bytesProcessed;

        /**
         * @param source
         * @param destination
         * @param callback
         */
        public ProfileWalker(final Path source, final Path destination,
                final ProgressObserver callback) {
            this.source = source;
            this.destination = destination;
            this.callback = callback;

            bytesToProcess = FileUtil.sizeQuietly(source);
        }

        /**
         * @throws IOException
         *
         */
        public void close() throws IOException {
            out.close();
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void handleStart(final File startDirectory, final Collection results)
            throws IOException {

            //out = new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(destination)));
            out = new ZipOutputStream(Files.newOutputStream(destination));
            out.setMethod(ZipEntry.DEFLATED);
        }

        /**
         * {@inheritDoc}
         */
        @SuppressWarnings("unchecked")
        @Override
        protected void handleEnd(Collection results) throws IOException {
            out.close();
        }

        @SuppressWarnings("unchecked")
        @Override
        protected boolean handleDirectory(File directory, int depth,
                Collection results) {
            return true;
        }

        /**
         * {@inheritDoc}
         */
        @SuppressWarnings("unchecked")
        @Override
        protected void handleDirectoryStart(final File directory, final int depth, final Collection results) {
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void handleFile(final File file, final int depth, final Collection results)
            throws IOException {

            final String entryPath = getUnixStylePath(StringUtils.substringAfter(file.getAbsolutePath(), source.toAbsolutePath().toString() + File.separator));

            //ZipArchiveEntry entry = (ZipArchiveEntry) out.createArchiveEntry(file, entryPath);
            //out.putArchiveEntry(entry);
            final ZipEntry entry = new ZipEntry(entryPath);
            out.putNextEntry(entry);

            try (final InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
                bytesProcessed = writeFile(in, out, callback, bytesProcessed, bytesToProcess);
            } finally {
                //out.closeArchiveEntry();
                out.closeEntry();
            }

        }

        protected void save() throws IOException {
            walk(source.toFile(), Collections.EMPTY_LIST);
        }
    }

    /**
     * Loads a droid file from disk.
     *
     * @param source
     *            the droid file to load
     * @param destination
     *            the target directory where the source should be unpacked
     * @param observer
     *            a progress observer which is notified on progress
     * @throws IOException
     *             if the file operations failed
     */
    public void load(final Path source, final Path destination, ProgressObserver observer)
        throws IOException {

        // Delete any remnants of this expanded profile
        if (Files.exists(destination)) {
            FileUtil.deleteQuietly(destination);
        }

        final ZipFile zip = new ZipFile(source.toFile());

        try {
            // count the zip entries so we can do progress bar
            long totalSize = 0L;
            for (final Enumeration<? extends ZipEntry> it = zip.entries(); it
                    .hasMoreElements();) {
                ZipEntry e = it.nextElement();
                totalSize += e.getSize();
            }

            long bytesSoFar = 0L;
            for (final Enumeration<? extends ZipEntry> it = zip.entries(); it
                    .hasMoreElements();) {
                ZipEntry entry = it.nextElement();

                // zip entries can be created on windows or unix, and can retain
                // the path separator for that platform.  We must ensure that
                // the paths we find inside the zip file will work on the platform
                // we are running on.  Technically, zip entry paths should be
                // created using the unix separator, no matter what platform they
                // are created on - but this is not always done correctly.
                final String entryName = getPlatformSpecificPath(entry.getName());

                final Path expandedFile = destination.resolve(entryName);

                Files.createDirectories(expandedFile.getParent());

                try (final InputStream in = new BufferedInputStream(zip.getInputStream(entry));
                        final OutputStream out = new BufferedOutputStream(Files.newOutputStream(expandedFile))) {
                    bytesSoFar = readFile(in, out, observer, bytesSoFar, totalSize);
                }
            }
            observer.onProgress(UNITY_PERCENT);
        } finally {
            zip.close();
        }

    }

    /**
     * Replace all path separators in the path with the correct one for the
     * platform we are running on.  This enables us to correctly recreate the
     * directory structure for zip entries on the platform we are running on,
     * even if the zip file was created using path separators from another platform.
     *
     * @param path the path to be made platform specific.
     * @return a platform specific path.
     */
    private String getPlatformSpecificPath(final String path) {
        // NOTE: there is a "bug" in the Java String replaceAll function, noted as such in the
        // the java bug databases.
        // If the replacement string is a backslash (platform specific file separator in windows),
        // then the replace function thinks it's merely the first character in an escaped string,
        // and should be doubled up.  Needless to say, we can't simply double up all path separators,
        // as the forward slash would replace with //, instead of /, whereas \\ would give \.
        // So, the following generates an error when the File separator is a backslash.
        //final String platformPath = path.replaceAll("[\\\\/]", File.separator);
        String platformPath = null;
        switch (File.separatorChar) {
            case BACKWARD_SLASH:
                platformPath = path.replace(FORWARD_SLASH, BACKWARD_SLASH);
                break;
            case FORWARD_SLASH:
                platformPath = path.replace(BACKWARD_SLASH, FORWARD_SLASH);
                break;
            default: // file separator is not a Windows OR Unix convention...
                platformPath = path.replaceAll("[\\\\/]", File.separator);
        }
        return platformPath;
    }

    /**
     * Replaces any back slashes with forward slashes, to give a unix style path.
     * Zip files should use the / instead of the \ separator (no matter what platform
     * they are created on), as this will work on both platforms with zip software.
     * @param path of file
     * @return String a unix style path (all separators are forward slashes)
     */
    private String getUnixStylePath(final String path) {
        return path.replace(BACKWARD_SLASH, FORWARD_SLASH);
    }

    private long readFile(final InputStream in, final OutputStream out,
            final ProgressObserver observer, final long bytesSoFar, final long totalSize)
        throws IOException {
        long totalBytesRead = bytesSoFar;
        int bytesIn = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesIn = in.read(buffer)) != -1) {
            totalBytesRead += bytesIn;
            int progressSoFar = (int) ((UNITY_PERCENT * totalBytesRead) / totalSize);
            observer.onProgress(progressSoFar);
            out.write(buffer, 0, bytesIn);
        }
        return totalBytesRead;
    }

    private long writeFile(final InputStream in, final ZipOutputStream out, //ZipArchiveOutputStream out,
            final ProgressObserver observer, final long bytesSoFar, final long totalSize)
        throws IOException {
        long totalBytesWritten = bytesSoFar;
        int bytesIn = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesIn = in.read(buffer)) != -1) {
            totalBytesWritten += bytesIn;
            int progressSoFar = (int) ((UNITY_PERCENT * totalBytesWritten) / totalSize);
            observer.onProgress(progressSoFar);
            out.write(buffer, 0, bytesIn);
        }
        return totalBytesWritten;
    }
}