text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
	class Register extends CI_Controller{
//----------------Method to call view---------------
		public function index(){
		//---------Variable-------------
			$data['title'] = 'Register';
            $data['active']=5;
        //------------------------------
        //---------Helper---------------
            $this->load->helper('url');
        //------------------------------
        //---------Models-------------
            $this->load->model('register_model');
            $data['fun']=$this->register_model->fun();
            $data['total_compensation']=$this->register_model->total_compensation();
        //---------------------------
            $this->head($data);
            $this->index_header();
            $this->load->view('jobseeker/register', $data);
            $this->footer();
		}
//------------------load head view-----------------------
		public function head($data){
            $this->load->view('jobseeker/section/head', $data);
        }
//------------------load index_header view-----------------------
        public function index_header(){
            $this->load->view('jobseeker/section/index_header');
        }
//------------------load footer view-----------------------
        public function footer(){
            //--------------load model------------------------
            $this->load->model('footer_links');
            $data['footer_links']=$this->footer_links->get_footer_links();
            //--------------load view--------------------------
            $this->load->view('jobseeker/section/footer',$data);
        }
//------------------load register view with valid form value-----------------------
        public function sign_up(){
        //--------------load library----------------------
            $this->load->library('form_validation');

        //----------------form validation---------------
            $this->form_validation->set_error_delimiters('
', '
');

            $this->form_validation->set_rules('first_name', 'First Name',  'trim|required');
            $this->form_validation->set_rules('last_name', 'Last Name',  'trim|required');
            $this->form_validation->set_rules('e_mail', 'E-mail',  'trim|required|valid_email|callback_check_if_email_exists');
            $this->form_validation->set_rules('password', 'Password', 'trim|required');
            $this->form_validation->set_rules('target_job_title', "Target Job Title", 'trim');
            $this->form_validation->set_rules('function', 'Function',  'trim|required');
            $this->form_validation->set_rules('total_compensation', 'Total Compensation',  'trim|required');

        //----------------check form validation-------------
            if ($this->form_validation->run() == FALSE)//not valid
            {
                $this->index();
            }
            else{
                $this->account_created();
            }

        }
//-------------------------when account created--------------------------
        public function account_created(){
        //----------------variables-----------------
            $data['created'] ='created';
            $data['title']='Account Created';
            $data['active']=null;
        //---------Helper---------------
            $this->load->helper('url');
        //-----------load model----------
            $this->load->model('register_model');
            $query = $this->register_model->create_account();
        //-----------load view-----------
            if($query){
                $this->head($data);
                $this->index_header();
                $this->load->view('jobseeker/created_account', $data);
                $this->footer();
            }
            else{
                $this->index();
            }
        }
//------------------------call back function--------------------
        public function check_if_email_exists($requested_email){
        //-------------load model------------
            $this->load->model('register_model');
            $email_available = $this->register_model->check_if_email_exists($requested_email);
            if($email_available){
                return TRUE;
            }
            else{
                return FALSE;
            }
        }
	}
?>


text:
package org.apache.hadoop.hive.ql.udf.generic;

import static java.util.Collections.singletonList;
import static org.apache.hadoop.hive.ql.util.DirectionUtils.DESCENDING_CODE;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.exec.WindowFunctionDescription;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.serde2.io.DoubleWritable;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableConstantIntObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.shims.ShimLoader;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.LongWritable;

/**
 * GenericUDAFPercentileCont.
 */
@Description(
        name = "dense_rank",
        value = "_FUNC_(input, pc) "
                + "- Returns the percentile of expr at pc (range: [0,1]).")
@WindowFunctionDescription(
        supportsWindow = false,
        pivotResult = true,
        orderedAggregate = true)
public class GenericUDAFPercentileCont extends AbstractGenericUDAFResolver {

  private static final Comparator<LongWritable> LONG_COMPARATOR;
  private static final Comparator<DoubleWritable> DOUBLE_COMPARATOR;

  static {
    LONG_COMPARATOR = ShimLoader.getHadoopShims().getLongComparator();
    DOUBLE_COMPARATOR = new Comparator<DoubleWritable>() {
      @Override
      public int compare(DoubleWritable o1, DoubleWritable o2) {
        return o1.compareTo(o2);
      }
    };
  }

  @Override
  public GenericUDAFEvaluator getEvaluator(TypeInfo[] parameters) throws SemanticException {
    if (parameters.length == 2) { // column ref, expression (0 <= percentile <= 1)
      return getGenericUDAFEvaluator(parameters[0], parameters[1]);
    } else if (parameters.length == 4) {
      // expression (0 <= percentile <= 1), order by column ref, order direction, null ordering
      return getGenericUDAFEvaluator(parameters[1], parameters[0]);
    } else {
      throw new UDFArgumentTypeException(parameters.length - 1, "Only 1 argument and a single order column " +
              "reference expected.");
    }
  }

  private GenericUDAFEvaluator getGenericUDAFEvaluator(TypeInfo orderByColumn, TypeInfo percentile)
          throws UDFArgumentTypeException {
    if (orderByColumn.getCategory() != ObjectInspector.Category.PRIMITIVE) {
      throw new UDFArgumentTypeException(0, "Only primitive type arguments are accepted but "
              + orderByColumn.getTypeName() + " is passed.");
    }

    switch (((PrimitiveTypeInfo) orderByColumn).getPrimitiveCategory()) {
    case BYTE:
    case SHORT:
    case INT:
    case LONG:
    case VOID:
      return createLongEvaluator(percentile);
    case FLOAT:
    case DOUBLE:
    case DECIMAL:
      return createDoubleEvaluator(percentile);
    case STRING:
    case TIMESTAMP:
    case VARCHAR:
    case CHAR:
    case BOOLEAN:
    case DATE:
    default:
      throw new UDFArgumentTypeException(0,
          "Only numeric arguments are accepted but " + orderByColumn.getTypeName() + " is passed.");
    }
  }

  protected GenericUDAFEvaluator createLongEvaluator(TypeInfo percentile) {
    return percentile.getCategory() == ObjectInspector.Category.LIST ?
            new PercentileContLongArrayEvaluator() : new PercentileContLongEvaluator();
  }

  protected GenericUDAFEvaluator createDoubleEvaluator(TypeInfo percentile) {
    return percentile.getCategory() == ObjectInspector.Category.LIST ?
            new PercentileContDoubleArrayEvaluator() : new PercentileContDoubleEvaluator();
  }

  /**
   * A comparator to sort the entries in order - Long.
   */
  @SuppressWarnings("serial")
  public static class LongComparator
      implements Comparator<Map.Entry<LongWritable, LongWritable>>, Serializable {
    @Override
    public int compare(Map.Entry<LongWritable, LongWritable> o1,
        Map.Entry<LongWritable, LongWritable> o2) {
      return LONG_COMPARATOR.compare(o1.getKey(), o2.getKey());
    }
  }

  /**
   * A comparator to sort the entries in order - Double.
   */
  @SuppressWarnings("serial")
  public static class DoubleComparator
      implements Comparator<Map.Entry<DoubleWritable, LongWritable>>, Serializable {
    @Override
    public int compare(Map.Entry<DoubleWritable, LongWritable> o1,
        Map.Entry<DoubleWritable, LongWritable> o2) {
      return DOUBLE_COMPARATOR.compare(o1.getKey(), o2.getKey());
    }
  }

  protected interface PercentileCalculator<U> {
    double getPercentile(List<Map.Entry<U, LongWritable>> entriesList, double position);
  }

  /**
   * An abstract class to hold the generic udf functions for calculating percentile.
   */
  public abstract static class PercentileContEvaluator<T, U> extends GenericUDAFEvaluator {
    PercentileCalculator<U> calc = getCalculator();

    protected PercentileContEvaluator(Comparator<Entry<U, LongWritable>> comparator, Converter converter) {
      this.comparator = comparator;
      this.converter = converter;
    }

    /**
     * A state class to store intermediate aggregation results.
     */
    public class PercentileAgg extends AbstractAggregationBuffer {
      Map<U, LongWritable> counts;
      List<DoubleWritable> percentiles;
      boolean isAscending;
    }

    // For PARTIAL1 and COMPLETE
    protected PrimitiveObjectInspector inputOI;
    MapObjectInspector countsOI;
    ListObjectInspector percentilesOI;

    // For PARTIAL1 and PARTIAL2
    protected transient Object[] partialResult;

    // FINAL and COMPLETE output
    protected List<DoubleWritable> results;

    // PARTIAL2 and FINAL inputs
    protected transient StructObjectInspector soi;
    protected transient StructField countsField;
    protected transient StructField percentilesField;
    protected transient StructField isAscendingField;

    private final transient Comparator<Entry<U, LongWritable>> comparator;
    private final transient Converter converter;
    protected transient boolean isAscending;

    public ObjectInspector init(Mode m, ObjectInspector[] parameters) throws HiveException {
      super.init(m, parameters);

      if (mode == Mode.PARTIAL1 || mode == Mode.COMPLETE) {// ...for real input data
        if (parameters.length == 2) { // Order direction was not given, default to asc
          initInspectors((PrimitiveObjectInspector) parameters[0]);
        } else {
          initInspectors((PrimitiveObjectInspector) parameters[1], (WritableConstantIntObjectInspector) parameters[2]);
        }
      } else { // ...for partial result as input
        initPartialInspectors((StructObjectInspector) parameters[0]);
      }

      if (mode == Mode.PARTIAL1 || mode == Mode.PARTIAL2) {// ...for partial result
        partialResult = new Object[3];

        ArrayList<ObjectInspector> foi = getPartialInspectors();

        ArrayList<String> fname = new ArrayList<String>();
        fname.add("counts");
        fname.add("percentiles");
        fname.add("isAscending");

        return ObjectInspectorFactory.getStandardStructObjectInspector(fname, foi);
      } else { // ...for final result
        results = null;
        return converter.getResultObjectInspector();
      }
    }

    protected abstract PercentileCalculator<U> getCalculator();

    protected abstract ArrayList<ObjectInspector> getPartialInspectors();

    protected abstract T getInput(Object object, PrimitiveObjectInspector inputOI);

    protected abstract U wrapInput(T input);

    protected abstract U copyInput(U input);

    private void sortEntries(List<Entry<U, LongWritable>> entriesList, boolean isAscending) {
      entriesList.sort(isAscending ? comparator : comparator.reversed());
    }

    // ...for real input data, no order direction
    protected void initInspectors(PrimitiveObjectInspector orderByColumnOI) {
      inputOI = orderByColumnOI;
      isAscending = true;
    }

    // ...for real input data, with order direction
    protected void initInspectors(
            PrimitiveObjectInspector orderByColumnOI, WritableConstantIntObjectInspector orderDirectionOI) {
      inputOI = orderByColumnOI;
      isAscending = orderDirectionOI.getWritableConstantValue().get() != DESCENDING_CODE;
    }

    // ...for partial result as input
    protected void initPartialInspectors(StructObjectInspector objectInspector) {
      soi = objectInspector;

      countsField = soi.getStructFieldRef("counts");
      percentilesField = soi.getStructFieldRef("percentiles");
      isAscendingField = soi.getStructFieldRef("isAscending");

      countsOI = (MapObjectInspector) countsField.getFieldObjectInspector();
      percentilesOI = (ListObjectInspector) percentilesField.getFieldObjectInspector();
    }

    @Override
    public AggregationBuffer getNewAggregationBuffer() throws HiveException {
      PercentileAgg agg = new PercentileAgg();
      agg.isAscending = isAscending;
      return agg;
    }

    @Override
    public void reset(AggregationBuffer agg) throws HiveException {
      PercentileAgg percAgg = (PercentileAgg) agg;
      if (percAgg.counts != null) {
        percAgg.counts.clear();
      }
    }

    @Override
    public void iterate(AggregationBuffer agg, Object[] parameters) throws HiveException {
      PercentileAgg percAgg = (PercentileAgg) agg;
      if (parameters.length == 4) {
        iterate(percAgg, parameters[0], parameters[1]);
      } else {
        iterate(percAgg, parameters[1], parameters[0]);
      }
    }

    private void iterate(PercentileAgg percAgg, Object percentiles, Object oderByColumnValue) {
      if (percAgg.percentiles == null) {
        percAgg.percentiles = converter.convertPercentileParameter(percentiles);
      }

      if (oderByColumnValue == null) {
        return;
      }

      T input = getInput(oderByColumnValue, inputOI);

      if (input != null) {
        increment(percAgg, wrapInput(input), 1);
      }
    }

    protected void increment(PercentileAgg s, U input, long i) {
      if (s.counts == null) {
        s.counts = new HashMap<U, LongWritable>();
      }
      LongWritable count = s.counts.get(input);
      if (count == null) {
        s.counts.put(copyInput(input), new LongWritable(i));
      } else {
        count.set(count.get() + i);
      }
    }

    @Override
    public void merge(AggregationBuffer agg, Object partial) throws HiveException {
      if (partial == null) {
        return;
      }

      Object objCounts = soi.getStructFieldData(partial, countsField);
      Object objPercentiles = soi.getStructFieldData(partial, percentilesField);
      Object objIsAscending = soi.getStructFieldData(partial, isAscendingField);

      Map<U, LongWritable> counts = (Map<U, LongWritable>) countsOI.getMap(objCounts);
      List<DoubleWritable> percentiles =
          (List<DoubleWritable>) percentilesOI.getList(objPercentiles);

      if (counts == null || percentiles == null) {
        return;
      }

      PercentileAgg percAgg = (PercentileAgg) agg;

      if (percAgg.percentiles == null) {
        percAgg.percentiles = new ArrayList<DoubleWritable>(percentiles);
      }
      percAgg.isAscending = ((BooleanWritable)objIsAscending).get();

      for (Map.Entry<U, LongWritable> e : counts.entrySet()) {
        increment(percAgg, e.getKey(), e.getValue().get());
      }
    }

    @Override
    public Object terminate(AggregationBuffer agg) throws HiveException {
      PercentileAgg percAgg = (PercentileAgg) agg;

      // No input data.
      if (percAgg.counts == null || percAgg.counts.size() == 0) {
        return null;
      }

      // Get all items into an array and sort them.
      Set<Map.Entry<U, LongWritable>> entries = percAgg.counts.entrySet();
      List<Map.Entry<U, LongWritable>> entriesList =
          new ArrayList<Map.Entry<U, LongWritable>>(entries);
      sortEntries(entriesList, percAgg.isAscending);

      // Accumulate the counts.
      long total = getTotal(entriesList);
      if (results == null) {
        results = new ArrayList<>(percAgg.percentiles.size());
        for (int i = 0; i < percAgg.percentiles.size(); ++i) {
          results.add(new DoubleWritable(0));
        }
      }
      calculatePercentile(percAgg.percentiles, entriesList, total, results);
      return converter.convertResults(results);
    }

    @Override
    public Object terminatePartial(AggregationBuffer agg) throws HiveException {
      PercentileAgg percAgg = (PercentileAgg) agg;
      partialResult[0] = percAgg.counts;
      partialResult[1] = percAgg.percentiles;
      partialResult[2] = new BooleanWritable(percAgg.isAscending);

      return partialResult;
    }

    protected long getTotal(List<Map.Entry<U, LongWritable>> entriesList) {
      long total = 0;
      for (int i = 0; i < entriesList.size(); i++) {
        LongWritable count = entriesList.get(i).getValue();
        total += count.get();
        count.set(total);
      }
      return total;
    }

    public static void validatePercentile(Double percentile) {
      if (percentile < 0.0 || percentile > 1.0) {
        throw new RuntimeException("Percentile value must be within the range of 0 to 1.");
      }
    }

    protected List<DoubleWritable> calculatePercentile(List<DoubleWritable> percentiles,
        List<Map.Entry<U, LongWritable>> entriesList, long total, List<DoubleWritable> results) {
      // maxPosition is the 1.0 percentile
      long maxPosition = total - 1;
      for (int i = 0; i < percentiles.size(); ++i) {
        DoubleWritable percentile = percentiles.get(i);
        double position = maxPosition * percentile.get();
        results.get(i).set(calc.getPercentile(entriesList, position));
      }

      return results;
    }

  }

  private interface Converter {
    List<DoubleWritable> convertPercentileParameter(Object parameter);
    Object convertResults(List<DoubleWritable> results);
    ObjectInspector getResultObjectInspector();
  }

  private static class PrimitiveConverter implements Converter {

    @Override
    public List<DoubleWritable> convertPercentileParameter(Object parameter) {
      Double percentile = ((HiveDecimalWritable) parameter).getHiveDecimal().doubleValue();
      PercentileContEvaluator.validatePercentile(percentile);
      return singletonList(new DoubleWritable(percentile));
    }

    @Override
    public Object convertResults(List<DoubleWritable> results) {
      return results.get(0);
    }

    public ObjectInspector getResultObjectInspector() {
      return PrimitiveObjectInspectorFactory.writableDoubleObjectInspector;
    }
  }

  private static class ArrayConverter implements Converter {
    public List<DoubleWritable> convertPercentileParameter(Object parameter) {
      ArrayList<HiveDecimalWritable> percentilesParameter = (ArrayList<HiveDecimalWritable>) parameter;
      List<DoubleWritable> percentileList = new ArrayList<>(percentilesParameter.size());
      for (HiveDecimalWritable hiveDecimalWritable : percentilesParameter) {
        Double percentile = hiveDecimalWritable.getHiveDecimal().doubleValue();
        PercentileContEvaluator.validatePercentile(percentile);
        percentileList.add(new DoubleWritable(percentile));
      }
      return percentileList;
    }

    @Override
    public Object convertResults(List<DoubleWritable> results) {
      return results;
    }

    @Override
    public ObjectInspector getResultObjectInspector() {
      return ObjectInspectorFactory.getStandardListObjectInspector(
              PrimitiveObjectInspectorFactory.writableDoubleObjectInspector);
    }
  }

  /**
   * The evaluator for percentile computation based on long.
   */
  public static class PercentileContLongEvaluator
      extends PercentileContEvaluator<Long, LongWritable> {

    public PercentileContLongEvaluator() {
      this(new PrimitiveConverter());
    }

    public PercentileContLongEvaluator(Converter converter) {
      super(new LongComparator(), converter);
    }

    protected ArrayList<ObjectInspector> getPartialInspectors() {
      ArrayList<ObjectInspector> foi = new ArrayList<ObjectInspector>();

      foi.add(ObjectInspectorFactory.getStandardMapObjectInspector(
          PrimitiveObjectInspectorFactory.writableLongObjectInspector,
          PrimitiveObjectInspectorFactory.writableLongObjectInspector));
      foi.add(ObjectInspectorFactory.getStandardListObjectInspector(
          PrimitiveObjectInspectorFactory.writableDoubleObjectInspector));
      foi.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector);
      return foi;
    }

    protected Long getInput(Object parameter, PrimitiveObjectInspector inputOI) {
      return PrimitiveObjectInspectorUtils.getLong(parameter, inputOI);
    }

    protected LongWritable wrapInput(Long input) {
      return new LongWritable(input);
    }

    protected LongWritable copyInput(LongWritable input) {
      return new LongWritable(input.get());
    }

    @Override
    protected PercentileCalculator<LongWritable> getCalculator() {
      return new PercentileContLongCalculator();
    }
  }

  /**
   * The evaluator for percentile computation based on array of longs.
   */
  public static class PercentileContLongArrayEvaluator extends PercentileContLongEvaluator {
    public PercentileContLongArrayEvaluator() {
      super(new ArrayConverter());
    }
  }

  /**
   * The evaluator for percentile computation based on double.
   */
  public static class PercentileContDoubleEvaluator
      extends PercentileContEvaluator<Double, DoubleWritable> {
    public PercentileContDoubleEvaluator() {
      this(new PrimitiveConverter());
    }

    public PercentileContDoubleEvaluator(Converter converter) {
      super(new DoubleComparator(), converter);
    }

    @Override
    protected ArrayList<ObjectInspector> getPartialInspectors() {
      ArrayList<ObjectInspector> foi = new ArrayList<ObjectInspector>();

      foi.add(ObjectInspectorFactory.getStandardMapObjectInspector(
          PrimitiveObjectInspectorFactory.writableDoubleObjectInspector,
          PrimitiveObjectInspectorFactory.writableLongObjectInspector));
      foi.add(ObjectInspectorFactory.getStandardListObjectInspector(
          PrimitiveObjectInspectorFactory.writableDoubleObjectInspector));
      foi.add(PrimitiveObjectInspectorFactory.writableBooleanObjectInspector);
      return foi;
    }

    @Override
    protected Double getInput(Object parameter, PrimitiveObjectInspector inputOI) {
      return PrimitiveObjectInspectorUtils.getDouble(parameter, inputOI);
    }

    @Override
    protected DoubleWritable wrapInput(Double input) {
      return new DoubleWritable(input);
    }

    protected DoubleWritable copyInput(DoubleWritable input) {
      return new DoubleWritable(input.get());
    }

    @Override
    protected PercentileCalculator<DoubleWritable> getCalculator() {
      return new PercentileContDoubleCalculator();
    }
  }

  /**
   * The evaluator for percentile computation based on array of doubles.
   */
  public static class PercentileContDoubleArrayEvaluator extends PercentileContDoubleEvaluator {
    public PercentileContDoubleArrayEvaluator() {
      super(new ArrayConverter());
    }
  }

  /**
   * continuous percentile calculators
   */
  public static class PercentileContLongCalculator implements PercentileCalculator<LongWritable> {
    /**
     * Get the percentile value.
     */
    public double getPercentile(List<Entry<LongWritable, LongWritable>> entriesList,
        double position) {
      // We may need to do linear interpolation to get the exact percentile
      long lower = (long) Math.floor(position);
      long higher = (long) Math.ceil(position);

      // Linear search since this won't take much time from the total execution anyway
      // lower has the range of [0 .. total-1]
      // The first entry with accumulated count (lower+1) corresponds to the lower position.
      int i = 0;
      while (entriesList.get(i).getValue().get() < lower + 1) {
        i++;
      }

      long lowerKey = entriesList.get(i).getKey().get();
      if (higher == lower) {
        // no interpolation needed because position does not have a fraction
        return lowerKey;
      }

      if (entriesList.get(i).getValue().get() < higher + 1) {
        i++;
      }
      long higherKey = entriesList.get(i).getKey().get();

      if (higherKey == lowerKey) {
        // no interpolation needed because lower position and higher position has the same key
        return lowerKey;
      }

      // Linear interpolation to get the exact percentile
      return (higher - position) * lowerKey + (position - lower) * higherKey;
    }
  }

  public static class PercentileContDoubleCalculator
      implements PercentileCalculator<DoubleWritable> {

    public double getPercentile(List<Map.Entry<DoubleWritable, LongWritable>> entriesList,
        double position) {
      long lower = (long) Math.floor(position);
      long higher = (long) Math.ceil(position);

      int i = 0;
      while (entriesList.get(i).getValue().get() < lower + 1) {
        i++;
      }

      double lowerKey = entriesList.get(i).getKey().get();
      if (higher == lower) {
        return lowerKey;
      }

      if (entriesList.get(i).getValue().get() < higher + 1) {
        i++;
      }
      double higherKey = entriesList.get(i).getKey().get();

      if (higherKey == lowerKey) {
        return lowerKey;
      }

      return (higher - position) * lowerKey + (position - lower) * higherKey;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>Day After Day</title>

    <meta charset="utf-8">
    <meta name=viewport content="width=device-width, initial-scale=1">

    <link rel=stylesheet href="styles.css">
    <link href='https://fonts.googleapis.com/css?family=Josefin+Slab' rel='stylesheet' type='text/css'>

        energy

        mood

        You have run out of energy. Depression makes it feel as though every action, no matter how small, takes a great amount of effort. Would you like to start over?

You have run out of mood. Feelings of helplessness and hopelessness are common with depression, and can prove to be very draining. Would you like to start over?

start over


text:
module Rackspace
  module Scaling
    module CmdUtil

      def find_instance_by_ip(target_ip, server_list)
        server_list.each do |server|
          server['addresses'].each do |k, v|
            v.each do |ip|
              if(ip['addr'] == target_ip)
                return server
              end
            end
          end
        end

        nil
      end

      def find_image_by_name(name, images)
        images.sort!{ |a, b| b['created'] <=> a['created']}
        found_image = nil

        images.each do |image|
          if(image['name'] == name)
            found_image = image
            break
          end
        end

        found_image
      end

    end
  end
end


text:
/* eslint-disable no-console */
import { readFileSync } from 'fs';
import prettyjson from 'prettyjson';
import { Sdp } from '../src';
const rawSdp = readFileSync('./test/assets/testSmall.sdp').toString();

Sdp.parse(rawSdp).then((sdp) => {
  // console.log(prettyjson.render(sdp.toJson()));
  console.log(JSON.stringify(sdp.toJson(), null, 2));
}).catch((err) => {
  if (err.stack) {
    console.error(err.stack);
  } else {
    console.error(err);
  }
});


text:
Namespace Authentication

	''' Enum Representing JWT Hash Algorithms
	''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
	''' <generator-date>01/02/2014 12:14:35</generator-date>
	''' <generator-functions>1</generator-functions>
	''' <generator-source>Hermes_\_Authentication\Enums\JwtHashAlgorithm.tt</generator-source>
	''' <generator-version>1</generator-version>
	<System.CodeDom.Compiler.GeneratedCode("Hermes_\_Authentication\Enums\JwtHashAlgorithm.tt", "1")> _
	Public Enum JwtHashAlgorithm As System.Int32

		''' HS256
		HS256 = 1

		''' HS384
		HS384 = 2

		''' HS512
		HS512 = 3

	End Enum

End Namespace


text:
package me.lactem.pvz.team.plant;

public enum PlantType {
	PEASHOOTER, REPEATER, BONK_CHOY, WINTER_MELON, SUNFLOWER;
}


text:
import sys

input_file = sys.argv[1]
with open(input_file, 'r') as test_cases:
    numbers = []
    for case in test_cases:
        num = int(case.rstrip())
        numbers.append(num)
    print(sum(numbers))
sys.exit(0)


text:
layout: post
title:  "DevFestMN 2016 Coming Soon!"
date:   2015-09-30 08:00:00
isStaticPost: false
---

We're extremely excited to announce 2016 DevFestMN - Twin Cities! [GDG DevFest 2014](http://devfest.gdg.org.ua/).

This year we will host the third ever developer focused conference in the heart of Minneapolis at the University of St. Thomas' Schulze Hall. We're so excited to you to come... and here's why!

* **Attendance**: We're expecting over 250 attendees
* **Topic**: A full day of technology and design focused on Google technologies
* **Date**: February 6, expect a full day packed with several parallel tracks and workshops to keep you entertained
* **Venue**:  Easy to get to Schulze Hall at the University of St. Thomas
* **Speakers**: Our call for speakers has gone out - reach out if you're interested in speaking

but we've already secured a first batch of experts:

* **Dan Lewis** - Android Developer from Trello, who is excited about Android styles and themes

* **Virginia Poltrack** - Designer of Fit Cat for Wear and many more watch faces

* **Stephen Fluin** - Our very own GDG Organizer and Chrome GDE to talk about the future of web

More details about speakers and the event will appear in subsequent posts, but in the meantime like us on [Facebook](https://facebook.com/DevFestMN), follow on [Twitter](https://twitter.com/GDGTC), add to circles in [Google+](https://plus.google.com/+GDGTC) or subcribe to our [mailing list](http://gdg.us5.list-manage1.com/subscribe/post?u=9fc8aa205b0521b5f05fc8e1e&id=ae0fb459fc) and [RSS feed](http://devfest.gdg.org.ua/feed.xml) in order not to miss any cool stuff about festival.


text:
{-# LANGUAGE OverloadedStrings #-}
module Main where

import Test.Hspec
import Abacus

main = hspec $
  describe "getNumbers" $ do
    it "should get numbers from an empty array" $
      getNumbers "[]" `shouldBe` []
    it "should get numbers from an empty object" $
      getNumbers "{}" `shouldBe` []
    it "should get numbers from an array" $
      getNumbers "[1,2,3]" `shouldBe` [1,2,3]
    it "should get numbers from a simple object" $
      getNumbers "{\"a\":2,\"b\":4}" `shouldBe` [2,4]
    it "should get numbers from a nested array" $
      getNumbers "[[[3]]]" `shouldBe` [3]
    it "should get numbers from a nested array" $
      getNumbers "{\"a\":{\"b\":4},\"c\":-1}" `shouldBe` [4,-1]


text: export { default } from 'ember-cognito/utils/cognito-storage';


text:
package com.ltsllc.miranda.network;

import com.ltsllc.miranda.Consumer;
import com.ltsllc.miranda.Message;
import com.ltsllc.miranda.Panic;
import com.ltsllc.miranda.clientinterface.MirandaException;
import com.ltsllc.miranda.miranda.Miranda;
import com.ltsllc.miranda.network.messages.*;
import com.ltsllc.miranda.network.states.NetworkReadyState;
import com.ltsllc.miranda.node.networkMessages.WireMessage;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

/**
 * This class takes care of mapping from integer handles to Handle objects.
 */
abstract public class Network extends Consumer {
    abstract public Handle basicConnectTo(String host, int port) throws MirandaException;

    abstract public Handle createHandle(Object o);

    private static Logger logger = Logger.getLogger(ConnectionListener.class);
    private static Network ourInstance;

    private Map<Integer, Handle> integerToHandle = new HashMap<Integer, Handle>();
    private int handleCount = 0;
    private String truststorePassword;
    private String keystorePassword;

    public String getKeystorePassword() {
        return keystorePassword;
    }

    public String getTruststorePassword() {
        return truststorePassword;
    }

    public void setTruststorePassword(String truststorePassword) {
        this.truststorePassword = truststorePassword;
    }

    public Network() throws MirandaException {
        super("network");

        NetworkReadyState networkReadyState = new NetworkReadyState(this);
        setCurrentState(networkReadyState);
    }

    public static Network getInstance() {
        return ourInstance;
    }

    public static synchronized void setInstance(Network network) {
        if (null == ourInstance) {
            ourInstance = network;
        }
    }

    public Handle getHandle(int handle) {
        return integerToHandle.get(handle);
    }

    public Map<Integer, Handle> getHandleMap() {
        return integerToHandle;
    }

    public int nextHandle() {
        return handleCount++;
    }

    public void setHandle(int handle, Handle theHandle) {
        integerToHandle.put(handle, theHandle);
    }

    public int getHandleCount() {
        return handleCount;
    }

    public void clearHandle(int handle) {
        integerToHandle.put(handle, null);
    }

    public void connect(ConnectToMessage connectToMessage) throws MirandaException {
        try {
            Handle handle = basicConnectTo(connectToMessage.getHost(), connectToMessage.getPort());

            if (null == handle) {
                ConnectFailedMessage connectFailedMessage = new ConnectFailedMessage(getQueue(), this, null);
                connectToMessage.reply(connectFailedMessage);
            } else {
                int handleId = nextHandle();
                setHandle(handleId, handle);

                ConnectSucceededMessage connectSucceededMessage = new ConnectSucceededMessage(getQueue(), this, handleId);
                connectToMessage.reply(connectSucceededMessage);
            }
        } catch (MirandaException e) {
            ConnectFailedMessage message = new ConnectFailedMessage(getQueue(), this, e.getCause());
            connectToMessage.reply(message);
        }
    }

    public void disconnect(CloseMessage closeMessage) throws MirandaException {
        Handle handle = getHandle(closeMessage.getHandle());

        if (null == handle) {
            UnknownHandleMessage unknownHandleMessage = new UnknownHandleMessage(getQueue(), this, closeMessage.getHandle());
            closeMessage.reply(unknownHandleMessage);
        } else {
            handle.close();

            setHandle(closeMessage.getHandle(), null);

            DisconnectedMessage disconnectedMessage = new DisconnectedMessage(getQueue(), this, closeMessage.getHandle());
            closeMessage.reply(disconnectedMessage);
        }
    }

    /**
     * Something Very Bad happend.  Decide if we should shut down.
     *
     * @param panic The problem that caused the panic
     * @return true if we should shut down, false otherwise
     */
    public boolean panic(Panic panic) {
        //
        // if one of our connections failed, and other connections are working,
        // then try to keep going
        //
        if (
                panic.getReason() == Panic.Reasons.NetworkThreadCrashed
                        && integerToHandle.size() > 1) {
            return false;
        }

        //
        // if we can't talk to anyone, ask the system what to do
        //
        else if (panic.getReason() == Panic.Reasons.NetworkThreadCrashed) {
            Panic newPanic = new Panic(panic.getCause(), Panic.Reasons.Network);
            Miranda.getInstance().panic(newPanic);
        }

        return false;
    }

    /**
     * Close the connection, without sending a sign-off.
     *
     * @param handleID The handle to disconnect from.
     */
    public void forceDisconnect(int handleID) {
        Handle handle = getHandle(handleID);

        if (null != handle) {
            handle.panic();
            clearHandle(handleID);
        }
    }

    /**
     * This is called when the {@link ConnectionListener} gets a new connection.
     *

     *

     * The handle rturned can be used in susequent {@link SendMessageMessage} and
     * {@link CloseMessage}s.
     *

     *
     * @param handle The new connection.
     * @return The handle for the new connection.
     */
    public int newConnection(Handle handle) {
        int handleId = nextHandle();

        setHandle(handleId, handle);

        return handleId;
    }

    public void sendOnNetwork(SendNetworkMessage sendNetworkMessage) throws NetworkException {
        Handle handle = integerToHandle.get(sendNetworkMessage.getHandle());

        if (handle == null) {
            throw new NetworkException("Unrecognized handle: " + sendNetworkMessage.getHandle(), NetworkException.Errors.UnrecognizedHandle);
        }

        handle.send(sendNetworkMessage.getWireMessage());
    }

    /**
     * Tell the network to close a connection.
     */
    public void sendClose(BlockingQueue<Message> senderQueue, Object sender, int handle) {
        CloseMessage closeMessage = new CloseMessage(senderQueue, sender, handle);
        sendToMe(closeMessage);
    }

    /**
     * Ask the network to send a message.
     */
    public void sendMessage(BlockingQueue<Message> senderQueue, Object sender, int handle, WireMessage wireMessage) {
        SendNetworkMessage sendNetworkMessage = new SendNetworkMessage(senderQueue, sender, wireMessage, handle);
        sendToMe(sendNetworkMessage);
    }

    /**
     * Ask the network to create a connection to someone
     */
    public void sendConnect(BlockingQueue<Message> senderQueue, Object sender, String host, int port) {
        ConnectToMessage connectToMessage = new ConnectToMessage(host, port, senderQueue, sender);
        sendToMe(connectToMessage);
    }

    /**
     * This is called when we have successfully made a connection.
     *
     * @param handleID The handle ID
     * @param handle   The handle that it maps to
     */
    public void mapHandle(int handleID, Handle handle) {
        integerToHandle.put(handleID, handle);
    }

    public void sendNetworkMessage(BlockingQueue<Message> senderQueue, Object sender, int handle, WireMessage wireMessage) {
        SendNetworkMessage sendNetworkMessage = new SendNetworkMessage(senderQueue, sender, wireMessage, handle);
        sendToMe(sendNetworkMessage);
    }

    public void sendCloseMessage(BlockingQueue<Message> senderQueue, Object sender, int handle) {
        CloseMessage closeMessage = new CloseMessage(senderQueue, sender, handle);
        sendToMe(closeMessage);
    }
}


text:
      <button type="button" class="navbar-toggle" ng-click="$ctrl.isNavCollapsed = !$ctrl.isNavCollapsed">
        Toggle navigation

      </button>

Play Game

Hightest Scores


text:
ENV['RAILS_ENV'] ||= 'test'
require 'active_record'
require 'timecop'
require 'hideable'
require 'setup'

RSpec.configure do |config|
  config.color_enabled = true
  config.order = 'random'
end


text:
require_relative 'strrand'

# Handles validation of UK-style postcodes
class Postkode
  # Validating UK Postcodes
  # Correct as at 2014-09-15
  # References below
  # https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/283357/ILRSpecification2013_14Appendix_C_Dec2012_v1.pdf
  # http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation
  # Areas with only single-digit districts: BR, FY, HA, HD, HG, HR, HS, HX, JE,
  #       LD, SM, SR, WC, WN, ZE (although WC is always subdivided by a
  #       further letter, e.g. WC1A).
  # Areas with only double-digit districts: AB, LL, SO.
  # Areas with a district '0' (zero): BL, BS, CM, CR, FY, HA, PR, SL, SS (BS is
  #       the only area to have both a district 0 and a district 10).
  # The following central London single-digit districts have been further
  #       divided by inserting a letter after the digit and before the space:
  #       EC1-EC4 (but not EC50), SW1, W1, WC1, WC2, and part of E1 (E1W),
  #       N1 (N1C and N1P), NW1 (NW1W) and SE1 (SE1P).
  # The letters QVX are not used in the first position.
  # The letters IJZ are not used in the second position.
  # The only letters to appear in the third position are ABCDEFGHJKPSTUW when
  #       the structure starts with A9A.
  # The only letters to appear in the fourth position are ABEHMNPRVWXY when
  #       the structure starts with AA9A.
  # The final two letters do not use the letters CIKMOV, so as not to resemble
  #       digits or each other when hand-written.
  # Post code sectors are one of ten digits: 0 to 9 with 0 only used once 9
  #       has been used in a post town, save for Croydon and Newport (above).

  A1    = '[A-PR-UWYZ]'
  A2    = '[A-HK-Y]'
  A3    = '[A-HJKPS-UW]'
  A4    = '[ABEHMNPRV-XY]'
  A5    = '[ABD-HJLN-UW-Z]'
  N     = '[0-9]'
  AANN  = A1 + A2 + N + N     # the six possible first-part combos
  AANA  = A1 + A2 + N + A4
  ANA   = A1 + N + A3
  ANN   = A1 + N + N
  AAN   = A1 + A2 + N
  AN    = A1 + N
  PART_ONE = [AANN, AANA, ANA, ANN, AAN, AN].join('|')
  PART_TWO = N + A5 + A5

  NORMAL_POSTCODE_VALID         = "^(#{PART_ONE})[ ]*(#{PART_TWO})$"
  NORMAL_POSTCODE_PATTERN       = /(#{PART_ONE})[ ]*(#{PART_TWO})/
  NORMAL_PART_POSTCODE_PATTERN  = /[ ]*(#{PART_ONE})[ ]*/
  NORMAL_POSTCODE_RE = Regexp.new(NORMAL_POSTCODE_VALID, Regexp::IGNORECASE)

  def self.validate(string, return_parts = false)
    return false if string.nil? || string == '' || string == false
    result = string.match(NORMAL_POSTCODE_RE)
    return false if result.nil?

    return_parts ? result[1..2] : true
  end

  def self.get_first_section(string)
    get_outcode(string)
  end

  def self.get_outcode(string)
    found = Postkode.validate(string, true)
    found ? found[0] : nil
  end

  def self.get_inward(string)
    found = Postkode.validate(string, true)
    found ? found[1] : nil
  end

  def self.find_in_string(string)
    res = string.upcase.scan(NORMAL_POSTCODE_PATTERN)
    res.length > 0 ? res : nil
  end

  def self.find_partial_in_string(string)
    res = string.upcase.scan(NORMAL_PART_POSTCODE_PATTERN)
    res.length > 0 ? res : nil
  end

  def self.validate_and_normalize(string)
    return nil unless validate(string)
    validate(string, true).
      map(&:to_s).
      map(&:upcase).
      join(" ")
  end

  def self.random()
    generator_pattern = "#{[AANN, AANA, ANA, ANN, AAN, AN].sample} #{PART_TWO}"
    StringRandom.random_regex(generator_pattern)
  end
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.cloudchannel.v1.model;

/**
 * The payment plan for the Offer. Describes how to make a payment.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Channel API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudChannelV1Plan extends com.google.api.client.json.GenericJson {

  /**
   * Reseller Billing account to charge after an offer transaction. Only present for Google Cloud
   * Platform offers.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String billingAccount;

  /**
   * Describes how frequently the reseller will be billed, such as once per month.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudChannelV1Period paymentCycle;

  /**
   * Describes how a reseller will be billed.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String paymentPlan;

  /**
   * Specifies when the payment needs to happen.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String paymentType;

  /**
   * Present for Offers with a trial period. For trial-only Offers, a paid service needs to start
   * before the trial period ends for continued service. For Regular Offers with a trial period, the
   * regular pricing goes into effect when trial period ends, or if paid service is started before
   * the end of the trial period.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudChannelV1Period trialPeriod;

  /**
   * Reseller Billing account to charge after an offer transaction. Only present for Google Cloud
   * Platform offers.
   * @return value or {@code null} for none
   */
  public java.lang.String getBillingAccount() {
    return billingAccount;
  }

  /**
   * Reseller Billing account to charge after an offer transaction. Only present for Google Cloud
   * Platform offers.
   * @param billingAccount billingAccount or {@code null} for none
   */
  public GoogleCloudChannelV1Plan setBillingAccount(java.lang.String billingAccount) {
    this.billingAccount = billingAccount;
    return this;
  }

  /**
   * Describes how frequently the reseller will be billed, such as once per month.
   * @return value or {@code null} for none
   */
  public GoogleCloudChannelV1Period getPaymentCycle() {
    return paymentCycle;
  }

  /**
   * Describes how frequently the reseller will be billed, such as once per month.
   * @param paymentCycle paymentCycle or {@code null} for none
   */
  public GoogleCloudChannelV1Plan setPaymentCycle(GoogleCloudChannelV1Period paymentCycle) {
    this.paymentCycle = paymentCycle;
    return this;
  }

  /**
   * Describes how a reseller will be billed.
   * @return value or {@code null} for none
   */
  public java.lang.String getPaymentPlan() {
    return paymentPlan;
  }

  /**
   * Describes how a reseller will be billed.
   * @param paymentPlan paymentPlan or {@code null} for none
   */
  public GoogleCloudChannelV1Plan setPaymentPlan(java.lang.String paymentPlan) {
    this.paymentPlan = paymentPlan;
    return this;
  }

  /**
   * Specifies when the payment needs to happen.
   * @return value or {@code null} for none
   */
  public java.lang.String getPaymentType() {
    return paymentType;
  }

  /**
   * Specifies when the payment needs to happen.
   * @param paymentType paymentType or {@code null} for none
   */
  public GoogleCloudChannelV1Plan setPaymentType(java.lang.String paymentType) {
    this.paymentType = paymentType;
    return this;
  }

  /**
   * Present for Offers with a trial period. For trial-only Offers, a paid service needs to start
   * before the trial period ends for continued service. For Regular Offers with a trial period, the
   * regular pricing goes into effect when trial period ends, or if paid service is started before
   * the end of the trial period.
   * @return value or {@code null} for none
   */
  public GoogleCloudChannelV1Period getTrialPeriod() {
    return trialPeriod;
  }

  /**
   * Present for Offers with a trial period. For trial-only Offers, a paid service needs to start
   * before the trial period ends for continued service. For Regular Offers with a trial period, the
   * regular pricing goes into effect when trial period ends, or if paid service is started before
   * the end of the trial period.
   * @param trialPeriod trialPeriod or {@code null} for none
   */
  public GoogleCloudChannelV1Plan setTrialPeriod(GoogleCloudChannelV1Period trialPeriod) {
    this.trialPeriod = trialPeriod;
    return this;
  }

  @Override
  public GoogleCloudChannelV1Plan set(String fieldName, Object value) {
    return (GoogleCloudChannelV1Plan) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudChannelV1Plan clone() {
    return (GoogleCloudChannelV1Plan) super.clone();
  }

}


text:
/**
 * Region 大区域渲染器
 * @author Brian Li
 * @email lbxxlht@163.com
 * @version 0.0.2.1
 */
define(function (require) {

    var React = require('react');
    var CheckBox = require('../../CheckBox.jsx');
    var Radio = require('../../Radio.jsx');

    var tools = require('../../core/regionTools');
    var language = require('../../core/language').region;

    return React.createClass({
        /**
         * @properties
         * @param {Number} id 省所属的编号
         * @param {Object} value Region组件转译后的value,以省市编号为key,有哪个key,代表哪个地区被选中
         * @param {ReactComponent} parent 渲染器所属的Region组件实例
         * @param {Boolean} disabled 渲染器是否处于禁用状态
         * @param {String} type 渲染器的选择状态,'single'表示单选,其他为多选
         * @param {Function} onChange 选择状态改变后的回调
         */
        // @override
        getDefaultProps: function getDefaultProps() {
            return {
                type: 'multi',
                disabled: false,
                id: -1,
                value: {},
                parent: {},
                onChange: function onChange() {}
            };
        },
        // @override
        getInitialState: function getInitialState() {
            return {};
        },
        onRegionChange: function onRegionChange(e) {
            if (this.props.disabled) return;
            this.props.onChange(e);
        },
        render: function render() {
            var selected = tools.getSelectedState(this.props.id, this.props.value, this.props.parent.props.noLinkage);
            var prop = {
                label: language.regionName[this.props.id],
                labelPosition: 'right',
                value: this.props.id,
                disabled: this.props.disabled,
                checked: selected.checked,
                indeterminate: selected.indeterminate,
                onChange: this.onRegionChange
            };

            if (this.props.type === 'single') {
                return React.createElement(Radio, prop);
            }
            return React.createElement(CheckBox, prop);
        }
    });
});


text:
Very basic converter from Nepal Dates (BS) to AD dates.
Note only currently converts from Nepal Dates

## Installation

Add this line to your application's Gemfile:

    gem 'nepal_date_converter'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install nepal_date_converter

## Usage

NepalDateConverter.convert\_to\_ad\_date('2002-2-9')
# => '1945-05-22'

## Other resources
http://en.wikipedia.org/wiki/Nepali_calendar

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.nishant.example;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

/**
Main Spring Configuration
 */
@Configuration
@ImportResource({ "classpath:spring/applicationContext.xml", "classpath:spring/dao.xml" })
@ComponentScan(basePackages = {"com.nishant.example"})
public class MyAppSpringConfiguration {

}


text:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
import java.util.*;
import java.awt.image.*;

public class Map extends Applet
implements MouseListener, Runnable // ActionListener

{String mytext, thecorrectanswer ; String question="", evaluation="";
  Font questionf= new Font("Dialog", Font.BOLD, 18);
 Image img, a_tick,a_cross, evalimg, offScreen;
 Graphics imggr,  offS;
Color grass =new Color(130,244,138);Color greenPastel= new Color(185,249,190);
  String ansLabel[]=new String[8]; //normally only 5
       boolean step1=true, step2=false;
   boolean quizOver=false, isrunning=false;
    int  index, correctanswers, totalanswers, totalitems;
    int ncorrect, chosenanswer, width,height;
 String quizItem[]= new String[100];
   Random rs = new Random();
  Thread roller;

public void init()
{height=Integer.parseInt(getParameter("height")); width=Integer.parseInt(getParameter("width"));
 offScreen=createImage(width, height);  offS=offScreen.getGraphics();
 offS.setColor(grass); offS.fillRect(0,0,width, height);
mytext=getParameter("text");
for (int i=0; i<50;i++){quizItem[i]="";}
correctanswers=totalanswers=0;
setFont(questionf);
addMouseListener(this);
 Image correctimg=getImage(getClass().getResource("tick.gif")); Image wrongimg=getImage(getClass().getResource("cross.gif"));
a_tick=getAlpha(correctimg,104,77); a_cross=getAlpha(wrongimg,77,60);
 }
public void start()
{if(roller==null)
  {roller=new Thread(this);}
   readyingForStart();isrunning=true;    roller.start();}

public void stop()
{if(roller!=null)  {roller=null;}
   isrunning=false;
}
public void readyingForStart()
 {totalitems=0; index=0;
String inLine=null; InputStreamReader instream =null;
 try{
 instream= new InputStreamReader(getClass().getResourceAsStream("Quiz.txt"));
 BufferedReader dataStream = new BufferedReader(instream);
  while ((inLine=dataStream.readLine())!=null)
       {quizItem[totalitems]=inLine;totalitems++;}
     }catch(IOException e){showStatus ("error in data reading");}
////mix questions
for (int ii=0;ii<50;ii++)
{int i1=rs.nextInt(totalitems);
 int i2=rs.nextInt(totalitems);
String tempostr=quizItem[i1];
quizItem[i1]=quizItem[i2];
quizItem[i2]=tempostr;}
}

public void run()
{while( isrunning==true)
  {while(index<totalitems)
    {
    if(step1==true)
     {step2=false;
      String s[]= new String[9];
      String  q = quizItem[index];
         StringTokenizer t = new StringTokenizer(q,"$");
         int ii=0;
         while (t.hasMoreTokens())
    	{s[ii] = t.nextToken();
	  ii++;
	 }
    thecorrectanswer=s[2];
    question=s[1];
    Image im=null;
    img=createImage(550, height-2);imggr=img.getGraphics();
    imggr.setColor(grass); imggr.fillRect(0,0,550,height-2);
   try{MediaTracker tracker = new MediaTracker(this);
	im=getImage(getClass().getResource(s[0]));
  	tracker.addImage(im, 0);
	tracker.waitForAll();
       }catch(InterruptedException e){showStatus("No picture found");}
  imggr.drawImage(im,0,0,this);
  if(s[7].equals("?")){}
  else {  int offsetx=10; int offsety=20;
	int mx=Integer.parseInt(s[7]);
	int my=Integer.parseInt(s[8]);
	imggr.setColor(Color.black);
	imggr.setFont(new Font("Dialog", Font.BOLD, 36));
	imggr.drawString("*", mx-offsetx, my+offsety);
           }
   do {ncorrect=(rs.nextInt()%5);} while(ncorrect<0);
     int j=0, i=3;
   while (j<5)
         {  if (j==ncorrect){ansLabel[j]=s[2]; j++;}
             else {ansLabel[j]=s[i]; i++; j++;}
         }
 index++;   evaluation=""; evalimg=null;
  offS.setColor(grass);  offS.fillRect(0,0,width,height);
  int jj=0;
step1=false;
 while(jj<width)
   { repaint(jj,0,jj+10,height);
     try{roller.sleep(30);}catch(InterruptedException e){};
     jj+=10;}
for (int ik=0; i<2000; i++)
      { try{roller.sleep(30);}catch(InterruptedException e){};
        if((step1==true)||(step2==true)) break;}
}                 //close if step1==true
if (step2==true)
{    showScore(chosenanswer);
     repaint();
     try{roller.sleep(1000);}catch(InterruptedException e){};
     step2=false; step1=true;}
} //close  while
quizOver=true; evaluation= "YOUR FINAL SCORE :  "; evalimg=null;
repaint();}}

public Image getAlpha(Image img, int imwidth, int imheight)
{Image a_img;
int[] pixels= new int[imwidth*imheight];
PixelGrabber pg= new PixelGrabber(img,0,0,imwidth,imheight,pixels,0,imwidth);
try{pg.grabPixels();}catch(InterruptedException ie){};
for(int i=0; i<pixels.length; i++)
{int p = pixels[i];
 int red = 0xff&(p>>16);
 int green = 0xff&(p>>8);
 int blue = 0xff&(p);
if ((red>245)&&(green>245)&&(blue>245)){pixels[i]=(0x00000000);}
}
a_img=createImage(new MemoryImageSource(imwidth,imheight,pixels,0,imwidth));
return a_img;
}
/*
public void actionPerformed(ActionEvent e)
    {   if (e.getActionCommand()== "Next")
	{displayNextQuizItem();      } }
*/
public void mouseClicked(MouseEvent me)
{ chosenanswer=0;
      if(step1==false)
   {      int coX=me.getX(); int coY=me.getY();
           if((coX>590)&&(coY<420)&&(coY>100))
           { chosenanswer=(int)((coY-100)/50);
                step2=true;  }
           else{};
} }
void showScore(int chosenl)
{ if (chosenl==ncorrect)
	{ evaluation="CORRECT";correctanswers++;
	    evalimg=a_tick;
	 }
   else
	{evaluation= "WRONG, it is  "+thecorrectanswer;
	     evalimg=a_cross;
	 }
       totalanswers++;
   //  showStatus(evaluation+correctanswers+" / "+totalanswers);
    offS.setColor(grass); offS.fillRect(560,400, width-560, height-400);
    offS.setColor(Color.black); offS.drawString(evaluation,660,420);
    offS.drawString("SCORE=  : "+correctanswers+" / "+totalanswers, 620, 460);
      repaint();    //(500,400,width-500,height-400);
     }
   public void mousePressed(MouseEvent e){};
   public void mouseReleased(MouseEvent e){};
   public void mouseEntered(MouseEvent e){};
   public void mouseExited(MouseEvent e){};

public void update(Graphics g)
{if(quizOver==false)
{    if(img==null)  {offS.drawString("no picture",20, 50);}
  else {offS.drawImage(img,20,2,this);}
   FontMetrics fm;
      offS.setFont(questionf);
  offS.setColor(Color.black); offS.drawString("SCORE=  : "+correctanswers+" / "+totalanswers, 620, 460);
          fm=offS.getFontMetrics();
        int linel=fm.stringWidth(question);
        int lineheight=fm.getHeight();
        if(linel<440)
          {offS.setColor(greenPastel); offS.fillRect(550,( 55-lineheight+4),450 ,lineheight+6);
             offS.setColor(Color.black);offS.drawString(question,560,55);}
       else
           {int spacelength = fm.stringWidth(" ");
             int  y=55,wl=0; linel=0;					//length of the text
             StringTokenizer tt=new StringTokenizer(question+" ?");
             String word, linee="";    					//contains the text
             while(tt.hasMoreTokens())
	{ word= tt.nextToken();
	   if (word.equals("?"))
	      {offS.setColor(greenPastel); offS.fillRect(550,y-lineheight+4,450, lineheight+6);
                        offS.setColor(Color.black);  offS.drawString (linee+"  ?", 560, y);}
	  else    {
	  wl=fm.stringWidth(word);
	  linel=linel+spacelength+wl;
	   if (linel>440)
	         {offS.setColor(greenPastel); offS.fillRect(550,y-lineheight+4,450,lineheight+6);
                            offS.setColor(Color.black);   offS.drawString (linee, 560, y);
	           y=y+lineheight; linel=wl; linee=word;
	         }
	      else
	        {linee=linee+" "+word;}
	     }
	}//end of while
            } // end of else

 for(int k=0;k<5;k++)
   {   fm=offS.getFontMetrics();
       linel=fm.stringWidth(ansLabel[k]);
        int  y=100;
        if(linel<440)
         { offS.setColor(greenPastel);  offS.fillRect(590,100+k*50+2,400,lineheight+2);
           offS.setColor(Color.black); offS.drawString(ansLabel[k],  600, k*50+100+lineheight);
         }
       else
           {int spacelength = fm.stringWidth(" ");
             int wl=0; linel=0;
             StringTokenizer tt=new StringTokenizer(ansLabel[k]);
             String word, linee="";
             while(tt.hasMoreTokens())
	 {word= tt.nextToken();
	   wl=fm.stringWidth(word);
	       linel=linel+spacelength+wl;
	       if (linel>440)
	         {offS.setColor(greenPastel);  offS.fillRect(590,k*50+y+2,400,lineheight+2);
                           offS.setColor(Color.black);offS.drawString (linee, 600, k*50+y+lineheight);
	           y=y+lineheight; linel=wl; linee=word;
	         }
	      else
	        {linee=linee+" "+word;}
	}//end of while
                          offS.setColor(greenPastel);  offS.fillRect(590,k*50+y+2,400,lineheight+2 );
                           offS.setColor(Color.black);offS.drawString (linee, 600, y+k*50+lineheight);
	            } // end of else
  }// end of for
if(step2==true){offS.drawImage(evalimg,550,102+chosenanswer*50, 40,32,this);
                      offS.drawImage(a_tick, 550,102+ncorrect*50,40,32,this);}
}
else if (quizOver==true){
  offS.setColor(grass); offS.fillRect(0,0,width, height);
  offS.setColor(Color.black);offS.drawString(evaluation,620,420);
    offS.drawString("SCORE=  : "+correctanswers+" / "+totalanswers, 620, 460);
 offS.drawString("Program written by annemarie.govindraj@gmail.com", 20, 490);
 }
paint(g);
}
public void paint(Graphics g)
{g.drawImage(offScreen,0,0,this);}}