text:
'use strict';

angular.module('ui.models')
  .factory('RandomBaseDataModel', function (WidgetDataModel, Visibility) {
    function RandomBaseDataModel() {
    }

    RandomBaseDataModel.prototype = Object.create(WidgetDataModel.prototype);
    RandomBaseDataModel.prototype.constructor = WidgetDataModel;

    angular.extend(RandomBaseDataModel.prototype, {
      init: function () {
        this.stopUpdates = false;
        this.visibilityListener = Visibility.change(function (e, state) {
          if (state === 'hidden') {
            this.stopUpdates = true;
          } else {
            this.stopUpdates = false;
          }
        }.bind(this));
      },

      updateScope: function (data) {
        if (!this.stopUpdates) {
          WidgetDataModel.prototype.updateScope.call(this, data);
        }
      },

      destroy: function () {
        WidgetDataModel.prototype.destroy.call(this);
        Visibility.unbind(this.visibilityListener);
      }
    });

    return RandomBaseDataModel;
  })
  .factory('RandomPercentageDataModel', function (RandomBaseDataModel, $interval) {
    function RandomPercentageDataModel() {
    }

    RandomPercentageDataModel.prototype = Object.create(RandomBaseDataModel.prototype);

    RandomPercentageDataModel.prototype.init = function () {
      var value = 50;

      this.intervalPromise = $interval(function () {
        value += Math.random() * 40 - 20;
        value = value < 0 ? 0 : value > 100 ? 100 : value;

        this.updateScope(value);
      }.bind(this), 500);
    };

    RandomPercentageDataModel.prototype.destroy = function () {
      RandomBaseDataModel.prototype.destroy.call(this);
      $interval.cancel(this.intervalPromise);
    };

    return RandomPercentageDataModel;
  })
  .factory('RandomTopNDataModel', function (RandomBaseDataModel, $interval) {
    function RandomTopNDataModel() {
    }

    RandomTopNDataModel.prototype = Object.create(RandomBaseDataModel.prototype);

    RandomTopNDataModel.prototype.init = function () {
      this.intervalPromise = $interval(function () {
        var topTen = _.map(_.range(0, 10), function (index) {
          return {
            name: 'item' + index,
            value: Math.floor(Math.random() * 100)
          };
        });
        this.updateScope(topTen);
      }.bind(this), 500);
    };

    RandomTopNDataModel.prototype.destroy = function () {
      RandomBaseDataModel.prototype.destroy.call(this);
      $interval.cancel(this.intervalPromise);
    };

    return RandomTopNDataModel;
  })
  .factory('RandomBaseTimeSeriesDataModel', function (RandomBaseDataModel, $interval) {
    function RandomTimeSeriesDataModel(options) {
      this.upperBound = (options && options.upperBound) ? options.upperBound : 100;
      this.rate = (options && options.rate) ? options.rate : Math.round(this.upperBound / 2);
    }

    RandomTimeSeriesDataModel.prototype = Object.create(RandomBaseDataModel.prototype);
    RandomTimeSeriesDataModel.prototype.constructor = RandomBaseDataModel;

    angular.extend(RandomTimeSeriesDataModel.prototype, {
      init: function () {
        RandomBaseDataModel.prototype.init.call(this);

        var max = 30;
        var upperBound = this.upperBound;
        var data = [];
        var chartValue = Math.round(upperBound / 2);
        var rate = this.rate;

        function nextValue() {
          chartValue += Math.random() * rate - rate / 2;
          chartValue = chartValue < 0 ? 0 : chartValue > upperBound ? upperBound : chartValue;
          return Math.round(chartValue);
        }

        var now = Date.now();
        for (var i = max - 1; i >= 0; i--) {
          data.push({
            timestamp: now - i * 1000,
            value: nextValue()
          });
        }

        this.updateScope(data);

        this.intervalPromise = $interval(function () {
          if (data.length >= max) {
            data.shift();
          }
          data.push({
            timestamp: Date.now(),
            value: nextValue()
          });

          this.updateScope(data);
        }.bind(this), 1000);
      },

      destroy: function () {
        RandomBaseDataModel.prototype.destroy.call(this);
        $interval.cancel(this.intervalPromise);
      }
    });

    return RandomTimeSeriesDataModel;
  })
  .factory('RandomTimeSeriesDataModel', function (RandomBaseTimeSeriesDataModel) {
    function RandomTimeSeriesDataModel(options) {
      RandomBaseTimeSeriesDataModel.call(this, options);
    }

    RandomTimeSeriesDataModel.prototype = Object.create(RandomBaseTimeSeriesDataModel.prototype);

    angular.extend(RandomTimeSeriesDataModel.prototype, {
      updateScope: function (data) {
        var chart = {
          data: data,
          max: 30,
          chartOptions: {
            vAxis: {}
          }
        };

        RandomBaseTimeSeriesDataModel.prototype.updateScope.call(this, chart);
      }
    });

    return RandomTimeSeriesDataModel;
  })
  .factory('RandomMetricsTimeSeriesDataModel', function (RandomBaseTimeSeriesDataModel) {
    function RandomMetricsTimeSeriesDataModel(options) {
      RandomBaseTimeSeriesDataModel.call(this, options);
    }

    RandomMetricsTimeSeriesDataModel.prototype = Object.create(RandomBaseTimeSeriesDataModel.prototype);

    angular.extend(RandomMetricsTimeSeriesDataModel.prototype, {
      updateScope: function (data) {
        var chart = [
          {
            key: 'Stream1',
            values: data
          },
          {
            key: 'Stream2',
            values: _.map(data, function (item) {
              return { timestamp: item.timestamp, value: item.value + 10 };
            })
          }
        ];

        RandomBaseTimeSeriesDataModel.prototype.updateScope.call(this, chart);
      }
    });

    return RandomMetricsTimeSeriesDataModel;
  })
  .factory('RandomNVD3TimeSeriesDataModel', function (RandomBaseTimeSeriesDataModel) {
    function RandomTimeSeriesDataModel(options) {
      RandomBaseTimeSeriesDataModel.call(this, options);
    }

    RandomTimeSeriesDataModel.prototype = Object.create(RandomBaseTimeSeriesDataModel.prototype);

    angular.extend(RandomTimeSeriesDataModel.prototype, {
      updateScope: function (data) {
        var chart = [
          {
            key: 'Data',
            values: data
          }
        ];

        RandomBaseTimeSeriesDataModel.prototype.updateScope.call(this, chart);
      }
    });

    return RandomTimeSeriesDataModel;
  })
  .factory('RandomMinutesDataModel', function (RandomBaseDataModel, $interval) {
    function RandomTimeSeriesDataModel(options) {
      this.limit = (options && options.limit) ? options.limit : 500;
    }

    RandomTimeSeriesDataModel.prototype = Object.create(RandomBaseDataModel.prototype);

    RandomTimeSeriesDataModel.prototype.init = function () {
      this.generateChart();
      this.intervalPromise = $interval(this.generateChart.bind(this), 2000);
    };

    RandomTimeSeriesDataModel.prototype.generateChart = function () {
      var minuteCount = 30;
      var data = [];
      var limit = this.limit;
      var chartValue = limit / 2;

      function nextValue() {
        chartValue += Math.random() * (limit * 0.4) - (limit * 0.2);
        chartValue = chartValue < 0 ? 0 : chartValue > limit ? limit : chartValue;
        return chartValue;
      }

      var now = Date.now();

      for (var i = minuteCount - 1; i >= 0; i--) {
        data.push({
          timestamp: now - i * 1000 * 60,
          value: nextValue()
        });
      }

      var widgetData = [
        {
          key: 'Data',
          values: data
        }
      ];

      this.updateScope(widgetData);
    };

    RandomTimeSeriesDataModel.prototype.destroy = function () {
      RandomBaseDataModel.prototype.destroy.call(this);
      $interval.cancel(this.intervalPromise);
    };

    return RandomTimeSeriesDataModel;
  });


text:
var pageMain = {
  board: undefined,
  displayed: false,

  initialize: function(board) {
    this.board = board;
  },

  getPageID: function() { return 'pageMain'; },

  getHeaderInfo: function() {
    return {'title':R.text('appTitle'), 'mainButton':'normal', 'menu':{'gear':1}};
  },

  /** whether remains in page history or not */
  isHistoric: function() { return true; },

  onActivated: function(prevMgr, options) {
    if( this.displayed ) { return; }

    // TODO 설명 이미지
    // this.board.append( $('

').html(' ') );

    // margin
    this.board.append( $('

').html(' ') );

    this.board.append(uitool.genMenu([
      {'title':R.text('study'), 'icon':'fa-edit', 'colorClass':'w3-teal', 'handler': function(){ app.showPage(studyMgr); } },
      {'title':R.text('test'), 'icon':'fa-check', 'colorClass':'w3-khaki', 'handler': function(){ app.showPage(testMgr); } },
      {'title':R.text('review'), 'icon':'fa-refresh', 'colorClass':'w3-orange', 'handler': function(){ app.showPage(reviewMgr); } }
    ]));

    this.displayed = true;
  },

  adjustLayout: function(w, h) {
    //
  },

  onDeactivated: function(activePage) {
    //
  },

  actionButton: function(buttonName) {
    if( 'gear' === buttonName ) {
      app.showPage(settingMgr);
    }
  }
};

redpajama_set_name: RedPajamaGithub


text: Solution with DaC and dynamic programming


text:
Fork this website on GitHub.

License

Privacy

Swift@IBM


text:
class PaymentGatewayRequest
  include Rails.application.routes.url_helpers

  attr_reader :payment
  attr_reader :gateway_request
  attr_reader :gateway_response

  def initialize(payment, gateway_request=PagSeguro::PaymentRequest.new)
    @payment = payment
    @gateway_request = gateway_request
    @gateway_response = nil
    build_gateway_request_from_payment
  end

  def checkout_code
    gateway_response.try(:code)
  end

  def checkout_url
    gateway_response.try(:url)
  end

  def created_at
    gateway_response.try(:created_at)
  end

  def errors
    gateway_response.try(:errors) || {}
  end

  def save
    send_request_to_gateway
    gateway_response.errors.empty?
  end

  private

  def send_request_to_gateway
    @gateway_response = gateway_request.register
  end

  def app_host
    # PagSeguro does not accept URL's with port numbers, nor from localhost or 127.0.0.1, nor from 'fake' domains
    if (Rails.env.test? || Rails.env.development?)
      'bolao2014.example.com'
    else
      Rails.configuration.action_mailer.default_url_options[:host]
    end
  end

  def notification_host
    # Uses UltraHook to be able to receive webhooks on localhost
    if Rails.env.development?
      "pagseguro.#{ENV['ULTRAHOOK_USERNAME']}.ultrahook.com"
    else
      app_host
    end
  end

  def build_gateway_request_from_payment
    gateway_request.reference = payment.reference
    gateway_request.notification_url = payment_notifications_url(host: notification_host)
    gateway_request.redirect_url = my_bet_payment_url(host: app_host)
    gateway_request.abandon_url = my_bet_payment_url(host: app_host) # TODO use a diferent page?
    # gateway_request.max_age = ??? # TODO use this?
    # gateway_request.max_uses = ??? # TODO use this?
    # gateway_request.sender = {email: payment.bet.user.email} # TODO use this?
    gateway_request.items << {
      id: payment.bet.id,
      description: I18n.t('activerecord.other.payment.item_description', app_name: ENV['APP_NAME']),
      amount: payment.amount.to_f
    }
  end

end


text:
package client.locale;

import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;

import server.logica.Giocatore;
import server.modellodati.Dinosauro;

/**
 * Classe che si occupa di inizializzare il Panel con il riassunto
 * sullo stato del Dinosauro selezionato e del Giocatore.
 */
public class DatiGuiLocale {

	private JLabel userRis;
	private JLabel nomeSpecieRis;
	private JLabel etaRis;
	private JLabel tNascitaGiocatoreRis;
	private JLabel idDinosauroRis;
	private JLabel dimensioneRis;
	private JLabel forzaRis;
	private JLabel energiaRis;
	private JLabel energiaMaxRis;
	private JLabel tNascitaDinoRis;
	private JLabel posRis;
	private Dinosauro dino;
	private JPanel creaDatiPanel;

	/**
	 * Costruttore della classe DatiGui che si occupa di inizializzare tutte le JLabel
	 * contenenti le informazioni sul Giocatore e sui Dinosauri.
	 * @param giocatore Giocatore alla quale e' assegnato il Turno.
	 */
	public DatiGuiLocale() {
		this.userRis = new JLabel();
		this.nomeSpecieRis = new JLabel();
		this.etaRis = new JLabel();
		this.tNascitaGiocatoreRis = new JLabel();
		this.idDinosauroRis = new JLabel();
		this.dimensioneRis = new JLabel();
		this.forzaRis = new JLabel();
		this.energiaRis = new JLabel();
		this.energiaMaxRis = new JLabel();
		this.tNascitaDinoRis = new JLabel();
		this.posRis = new JLabel();
	}

	/**
	 * Metodo che aggiorna i dati nella JLabel del JPanel.
	 * @param indiceDino int che rappresenta il numero del Dinosauro selezionato.
	 */
	public void aggiornaDati(int indiceDino, Giocatore giocatore) {
		this.dino = giocatore.getDinosauri().get(indiceDino);

		this.userRis.setText(giocatore.getIdGiocatore() + "");
		this.nomeSpecieRis.setText(giocatore.getNomeSpecie());
		this.etaRis.setText(giocatore.getEtaAttuale() + "");
		this.tNascitaGiocatoreRis.setText(giocatore.getTurnoNascita() + "");

		this.idDinosauroRis.setText(dino.getId());
		this.dimensioneRis.setText((dino.getEnergiaMax() / 1000) + "");
		this.forzaRis.setText(dino.calcolaForza() + "");
		this.energiaRis.setText(dino.getEnergia() + "");
		this.energiaMaxRis.setText(dino.getEnergiaMax() + "");
		this.tNascitaDinoRis.setText(dino.getTurnoNascita() + "");
		this.posRis.setText(dino.getRiga() + "," + dino.getColonna());
	}

	/**
	 * Metodo per creare il JPanel contente le informazioni sul Giocatore e sui Dinosauri.
	 * @param indice int che rappresenta l'indice del Dinosauro selezionato.
	 * @return Un JPanel contente tutti gli elementi grafici sul Giocatore e sui Dinosauri.
	 */
	public JPanel creaDati(int indice,Giocatore giocatore) {

		this.aggiornaDati(indice,giocatore);
		creaDatiPanel = new JPanel();
		creaDatiPanel.setLayout(new GridLayout(14,2));

		JLabel userGiocatore = new JLabel(" User: ");
		creaDatiPanel.add(userGiocatore);
		creaDatiPanel.add(userRis);

		JLabel nomeSpecie = new JLabel(" Specie: ");
		creaDatiPanel.add(nomeSpecie);
		creaDatiPanel.add(nomeSpecieRis);

		JLabel eta = new JLabel(" Eta: ");
		creaDatiPanel.add(eta);
		creaDatiPanel.add(etaRis);

		JLabel tNascitaGiocatore = new JLabel(" Nascita: ");
		creaDatiPanel.add(tNascitaGiocatore);
		creaDatiPanel.add(tNascitaGiocatoreRis);

		creaDatiPanel.add(new JLabel());
		creaDatiPanel.add(new JLabel());

		JLabel idDinosauro = new JLabel(" Id: ");
		creaDatiPanel.add(idDinosauro);
		creaDatiPanel.add(idDinosauroRis);

		JLabel dimensione = new JLabel(" Dim: ");
		creaDatiPanel.add(dimensione);
		creaDatiPanel.add(dimensioneRis);

		JLabel forza = new JLabel(" Forza: ");
		creaDatiPanel.add(forza);
		creaDatiPanel.add(forzaRis);

		JLabel energia = new JLabel(" Energia: ");
		creaDatiPanel.add(energia);
		creaDatiPanel.add(energiaRis);

		JLabel energiaMax = new JLabel(" EnergiaMax: ");
		creaDatiPanel.add(energiaMax);
		creaDatiPanel.add(energiaMaxRis);

		JLabel tNascitaDino = new JLabel(" Nascita: ");
		creaDatiPanel.add(tNascitaDino);
		creaDatiPanel.add(tNascitaDinoRis);

		JLabel pos = new JLabel(" Pos: ");
		creaDatiPanel.add(pos);
		creaDatiPanel.add(posRis);

		return creaDatiPanel;
	}
}


text:
/*
	OTA_HotelDescriptiveInfoSudzc.h
	Creates a list of the services available with the OTA_HotelDescriptiveInfo prefix.
	Generated by SudzC.com
*/
#import "OTA_HotelDescriptiveInfoOTA_HotelDescriptiveInfo.h"

@interface OTA_HotelDescriptiveInfoSudzC : NSObject {
	BOOL logging;
	NSString* server;
	NSString* defaultServer;
OTA_HotelDescriptiveInfoOTA_HotelDescriptiveInfo* oTA_HotelDescriptiveInfo;

}

-(id)initWithServer:(NSString*)serverName;
-(void)updateService:(SoapService*)service;
-(void)updateServices;
+(OTA_HotelDescriptiveInfoSudzC*)sudzc;
+(OTA_HotelDescriptiveInfoSudzC*)sudzcWithServer:(NSString*)serverName;

@property (nonatomic) BOOL logging;
@property (nonatomic, retain) NSString* server;
@property (nonatomic, retain) NSString* defaultServer;

@property (nonatomic, retain, readonly) OTA_HotelDescriptiveInfoOTA_HotelDescriptiveInfo* oTA_HotelDescriptiveInfo;

@end


text:
package it.uniroma2.sag.kelp.data.example;

import it.uniroma2.sag.kelp.data.label.Label;
import it.uniroma2.sag.kelp.data.manipulator.Manipulator;
import it.uniroma2.sag.kelp.data.representation.Representation;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

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

import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * An Example composed by a set of Representations.
 * @author Simone Filice
 */
@JsonTypeName("simple")
public class SimpleExample extends Example {

	protected Logger logger = LoggerFactory.getLogger(Example.class);
	/**
	 *
	 */
	private static final long serialVersionUID = -8619029107770256417L;

	private HashMap<String,Representation> representations;

	/**
	 * Initializes an empty example (0 labels and 0 representations)
	 */
	public SimpleExample(){
		super();
		this.representations = new HashMap<String,Representation>();
	}

	/**
	 * Initializes a SimpleExample with the input representations and labels
	 *
	 * @param labels
	 *            the classes whose this instance is a positive example
	 * @param representations
	 *            the various representations in which the instance is
	 *            represented
	 */
	public SimpleExample(Label[] labels, HashMap<String, Representation> representations) {
		this();
		this.setLabels(labels);
		this.setRepresentations(representations);
	}

	@Override
	public void setRepresentations(HashMap<String, Representation> representations) {

		this.representations.clear();
		this.representations=representations;
	}

	@Override
	public Map<String, Representation> getRepresentations() {
		return this.representations;
	}

	@Override
	public void addRepresentation(String representationName, Representation representation) {
		representations.put(representationName, representation);
	}

	@Override
	public int getNumberOfRepresentations() {
		return representations.size();
	}

	@Override
	public Representation getRepresentation(String representationName) {
		return this.representations.get(representationName);
	}

	@Override
	public boolean equals(Object example){
		if(example instanceof SimpleExample){
			SimpleExample that = (SimpleExample) example;
			return super.equals(that) && this.equalsIgnoreLabels(that);
		}
		return false;
	}

	/**
	 * Asserts whether this example and the input one have identical
	 * representations, ignoring their labels
	 *
	 * @param example
	 * @return true if this example and the input one have identical
	 *         representations, false otherwise
	 */
	public boolean equalsIgnoreLabels(SimpleExample example) {
		if (example == null) {
			return false;
		}
		if (this == example) {
			return true;
		}
		if (this.getNumberOfRepresentations() == example.getNumberOfRepresentations()) {
			for(Entry<String, Representation> entry: this.representations.entrySet()){
				if(!entry.getValue().equals(example.getRepresentation(entry.getKey()))){
					return false;
				}
			}

		} else {
			return false;
		}

		return true;
	}

	@Override
	public String toString() {
		String ret = this.getTextualLabelPart();
		for(Entry<String, Representation> entry: this.representations.entrySet()){
			Representation representation = entry.getValue();
			String identifier = entry.getKey();

			ret += ExampleFactory.getTextualRepresentation(representation, identifier)
					+ ExampleFactory.REPRESENTATION_SEPARATOR;

		}
		return ret.toString();
	}

	public String printExample(String... representations) {
		if (representations == null || representations.length==0) {
			return toString();
		} else {
			StringBuilder ret = new StringBuilder();
			ret.append(this.getTextualLabelPart());
			for (String repr : representations) {
				Representation representation = this.representations.get(repr);
				ret.append(ExampleFactory.getTextualRepresentation(representation, repr)
						+ ExampleFactory.REPRESENTATION_SEPARATOR);
			}
			return ret.toString().trim();
		}
	}

//	@Override
//	public Vector getZeroVector(String representationIdentifier) {
//		Vector rep = (Vector) getRepresentation(representationIdentifier);
//		return rep.getZeroVector();
//	}

	@Override
	public void manipulate(Manipulator manipulator){
		manipulator.manipulate(this);
	}

	@Override
	public boolean isCompatible(Example example) {

		if(example.getNumberOfRepresentations()!=this.getNumberOfRepresentations()){
			logger.error("examples are incompatible because they have a different number of representations: " + this.getNumberOfRepresentations() + " vs " + example.getNumberOfRepresentations());
			return false;
		}
		for(Entry<String, Representation> entry : this.representations.entrySet()){
			Representation repThat = example.getRepresentation(entry.getKey());
			if(repThat==null){
				logger.error("examples are incompatible because the representation \"" + entry.getKey() + "\" is only in one of them");
				return false;
			}
			if(!entry.getValue().isCompatible(repThat)){
				return false;
			}
		}

		return true;
	}
}


text:
class AppsController < ApplicationController
  before_action :check_login_status
  before_action :set_app, only: [:show, :edit, :update, :destroy]

  # GET /apps
  # GET /apps.json
  def index
    @apps = App.find_all_by_developer_id(session[:developer_id])
  end

  # GET /apps/1
  # GET /apps/1.json
  def show
  end

  # GET /apps/new
  def new
    @app = current_developer.apps.build

  end

  # GET /apps/1/edit
  def edit
  end

  # POST /apps
  # POST /apps.json
  def create
    @app = App.new(app_params)

    respond_to do |format|
      if @app.save
        format.html { redirect_to @app, notice: 'App was successfully created.' }
        format.json { render action: 'show', status: :created, location: @app }
      else
        format.html { render action: 'new' }
        format.json { render json: @app.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /apps/1
  # PATCH/PUT /apps/1.json
  def update
    respond_to do |format|
      if @app.update(app_params)
        format.html { redirect_to @app, notice: 'App was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @app.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /apps/1
  # DELETE /apps/1.json
  def destroy
    @app.destroy
    respond_to do |format|
      format.html { redirect_to apps_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_app
      @app = App.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def app_params
      params.require(:app).permit(:icon, :name, :app_key, :developer_id)
    end
end


text:
package iris

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/geekypanda/httpcache"
	"github.com/kataras/go-errors"
)

const (
	// Version is the current version number of the Iris web framework
	Version = "6.2.0"

	codeName = `√Νεxτ`

	banner = `         _____      _
        |_   _|    (_)
          | |  ____ _  ___
          | | | __|| |/ __|
         _| |_| |  | |\__ \
        |_____|_|  |_||___/ ` + codeName
)

// Default is the field which keeps an empty `Framework`
// instance with its default configuration (config can change at runtime).
//
// Use that as `iris.Default.Handle(...)`
// or create a new, ex: `app := iris.New(); app.Handle(...)`
var (
	Default *Framework
	// ResetDefault resets the `.Default`
	// to an empty *Framework with the default configuration.
	//
	// Note: ResetDefault field itself can be setted
	//       to custom function too.
	ResetDefault = func() { Default = New() }
)

func init() {
	ResetDefault()
}

// Framework is our God |\| Google.Search('Greek mythology Iris').
type Framework struct {
	// Router is the Router API, REST Routing, Static files & favicon,
	// Grouping, Custom HTTP Errors,  Subdomains and more.
	//
	// This field is available before 'Boot' but the routes are actually registered after 'Boot'
	// if no RouterBuilderPolicy was .Adapt(ed) by user then
	// it throws a panic with detailed information of how-to-fix it.
	*Router

	// Config contains the configuration fields
	// all fields defaults to something that is working, developers don't have to set it.
	//
	// can be setted via .New, .Set and .New(.YAML)
	Config *Configuration

	// policies contains the necessary information about the application's components.
	// - LoggerPolicy
	// - EventPolicy
	//      - Boot
	//      - Build
	//      - Interrupted
	//      - Recover
	// - RouterReversionPolicy
	//      - StaticPath
	//      - WildcardPath
	//      - Param
	//      - URLPath
	// - RouterBuilderPolicy
	// - RouterWrapperPolicy
	// - RenderPolicy
	// - TemplateFuncsPolicy
	// - SessionsPolicy
	//
	// These are setted by user's call to .Adapt
	policies Policies

	// TLSNextProto optionally specifies a function to take over
	// ownership of the provided TLS connection when an NPN/ALPN
	// protocol upgrade has occurred. The map key is the protocol
	// name negotiated. The Handler argument should be used to
	// handle HTTP requests and will initialize the Request's TLS
	// and RemoteAddr if not already set. The connection is
	// automatically closed when the function returns.
	// If TLSNextProto is nil, HTTP/2 support is enabled automatically.
	TLSNextProto map[string]func(*http.Server, *tls.Conn, http.Handler) // same as http.Server.TLSNextProto

	// ConnState specifies an optional callback function that is
	// called when a client connection changes state. See the
	// ConnState type and associated constants for details.
	ConnState func(net.Conn, http.ConnState) // same as http.Server.ConnState

	// Shutdown gracefully shuts down the server without interrupting any
	// active connections. Shutdown works by first closing all open
	// listeners, then closing all idle connections, and then waiting
	// indefinitely for connections to return to idle and then shut down.
	// If the provided context expires before the shutdown is complete,
	// then the context's error is returned.
	//
	// Shutdown does not attempt to close nor wait for hijacked
	// connections such as WebSockets. The caller of Shutdown should
	// separately notify such long-lived connections of shutdown and wait
	// for them to close, if desired.
	Shutdown func(context.Context) error

	closedManually bool // true if closed via .Shutdown, used to not throw a panic on s.handlePanic when closing the app's server

	once sync.Once // used to 'Boot' once
}

var defaultGlobalLoggerOuput = log.New(os.Stdout, "", log.LstdFlags)

// DevLogger returns a new Logger which prints both ProdMode and DevMode messages
// to the default global logger printer.
//
// Usage: app := iris.New()
//        app.Adapt(iris.DevLogger())
//
// Users can always ignore that and adapt a custom LoggerPolicy,
// which will use your custom printer instead.
func DevLogger() LoggerPolicy {
	lastLog := time.Now()
	distanceDuration := 850 * time.Millisecond
	return func(mode LogMode, logMessage string) {
		if strings.Contains(logMessage, banner) {
			fmt.Print(logMessage)
			lastLog = time.Now()
			return
		}
		nowLog := time.Now()
		if nowLog.Before(lastLog.Add(distanceDuration)) {
			// don't use the log.Logger to print this message
			// if the last one was printed before some seconds.
			fmt.Println(logMessage)
			lastLog = nowLog
			return
		}
		// begin with new line in order to have the time once at the top
		// and the child logs below it.
		defaultGlobalLoggerOuput.Println("\u2192\n" + logMessage)
		lastLog = nowLog
	}
}

// New creates and returns a fresh Iris *Framework instance
// with the default configuration if no 'setters' parameters passed.
func New(setters ...OptionSetter) *Framework {
	cfg := DefaultConfiguration()
	s := &Framework{Config: &cfg}

	//  +------------------------------------------------------------+
	//  | Set the config passed from setters                         |
	//  | or use the default one                                     |
	//  +------------------------------------------------------------+
	s.Set(setters...)
	{
		//  +------------------------------------------------------------+
		//  | Module Name: Logger                                        |
		//  | On Init: If user didn't adapt a custom loggger then attach |
		//  |           a new logger using log.Logger as printer with    |
		//  |          some default options                              |
		//  +------------------------------------------------------------+

		// The logger policy is never nil and it doesn't defaults to an empty func,
		// instead it defaults to a logger with os.Stdout as the print target which prints
		// ONLY prodction level messages.
		// While in ProdMode Iris logs only panics and fatal errors.
		// You can override the default log policy with app.Adapt(iris.DevLogger())
		//                            or app.Adapt(iris.LoggerPolicy(customLogger))
		// to log both ProdMode and DevMode messages.
		//
		// Note:
		// The decision to not log everything and use middleware for http requests instead of built'n
		// is because I'm using Iris on production so I don't want many logs to my screens
		// while server is running.
		s.Adapt(LoggerPolicy(func(mode LogMode, logMessage string) {
			if mode == ProdMode {
				defaultGlobalLoggerOuput.Println(logMessage)
			}
		}))

		s.Adapt(EventPolicy{Boot: func(*Framework) {
			// Print the banner first, even if we have to print errors later.
			s.Log(DevMode, banner+"\n\n")
		}})

	}

	//  +------------------------------------------------------------+
	//  |                                                            |
	//  | Please take a look at the policy.go file first.            |
	//  | The EventPolicy contains all the necessary information     |
	//  | user should know about the framework's flow.               |
	//  |                                                            |
	//  +------------------------------------------------------------+

	//  +------------------------------------------------------------+
	//  | On Boot: Set the VHost and VScheme config fields           |
	//  |           based on the net.Listener which (or not)         |
	//  |           setted on Serve and Listen funcs.                |
	//  |                                                            |
	//  |           It's the only pre-defined Boot event because of  |
	//  |           any user's custom 'Build' events should know     |
	//  |           the Host of the server.                          |
	//  +------------------------------------------------------------+
	s.Adapt(EventPolicy{Boot: func(s *Framework) {
		// set the host and scheme
		if s.Config.VHost == "" { // if not setted by Listen functions
			s.Config.VHost = DefaultServerAddr
		}
		// if user didn't specified a scheme then get it from the VHost,
		// which is already setted at before statements
		if s.Config.VScheme == "" {
			// if :443 or :https then returns https:// otherwise http://
			s.Config.VScheme = ParseScheme(s.Config.VHost)
		}

	}})

	{
		//  +------------------------------------------------------------+
		//  | Module Name: Renderer                                      |
		//  | On Init: set templates and serializers                     |
		//  | and adapt the RenderPolicy for both                        |
		//  | templates and content-type specific renderer (serializer)  |
		//  | On Build: build the serializers and templates              |
		//  | based on the user's calls                                  |
		//  +------------------------------------------------------------+

		{
			//  +------------------------------------------------------------+
			//  | Module Name: Rich Content-Type Renderer                    |
			//  | On Init: Attach a new empty content-type serializers.      |
			//  | Adapt one RenderPolicy which is responsible                |
			//  | for json,jsonp,xml and markdown rendering                  |
			//  +------------------------------------------------------------+
			s.Adapt(restRenderPolicy)
		}
		{
			//  +------------------------------------------------------------+
			//  | Module Name: Template engine's funcs                       |
			//  | On Init: Adapt the reverse routing tmpl funcs              |
			//  |          for any template engine that will be registered   |
			//  +------------------------------------------------------------+
			s.Adapt(TemplateFuncsPolicy{
				"url":     s.URL,
				"urlpath": s.Path,
			}) // the entire template registration logic lives inside the ./adaptors/view now.

		}

	}

	{
		//  +------------------------------------------------------------+
		//  | Module Name: Router                                        |
		//  | On Init: Attach a new router, pass a new repository,       |
		//  |    an empty error handlers list, the context pool binded   |
		//  |    to the Framework and the root path "/"                  |
		//  | On Build: Use the policies to build the router's handler   |
		//  |            based on its route repository                   |
		//  +------------------------------------------------------------+

		s.Router = &Router{
			repository: new(routeRepository),
			Errors: &ErrorHandlers{
				handlers: make(map[int]Handler, 0),
			},
			Context: &contextPool{
				sync.Pool{New: func() interface{} { return &Context{framework: s} }},
			},
			relativePath: "/",
		}

		s.Adapt(EventPolicy{Build: func(*Framework) {
			// Author's notes:
			// Proxy for example has 0 routes registered but still uses the RouterBuilderPolicy
			// so we can't check only for it, we can check if it's nil and it has more than one registered
			// routes, then panic, if has no registered routes the user don't want to get errors about the router.

			// first check if it's not setted already by any Boot event.
			if s.Router.handler == nil {
				hasRoutes := s.Router.repository.Len() > 0
				routerBuilder := s.policies.RouterBuilderPolicy
				// and most importantly, check if the user has provided a router adaptor
				//                    at the same time has registered at least one route,
				// if not then it should panic here, iris can't run without a router attached to it
				// and default router not any more, user should select one from ./adaptors or
				// any other third-party adaptor may done by community.
				// I was coding the new iris version for more than 20 days(~200+ hours of code)
				// and I hope that once per application the addition of +1 line users have to put,
				// is not a big deal.
				if hasRoutes {
					if routerBuilder == nil {
						// this is important panic and app can't continue as we said.
						s.handlePanic(errRouterIsMissing.Format(s.Config.VHost))
						// don't trace anything else,
						// the detailed errRouterIsMissing message will tell the user what to do to fix that.
						os.Exit(0)
					}
				}

				if routerBuilder != nil {
					// buid the router using user's selection build policy
					s.Router.build(routerBuilder)

					s.Router.repository.OnMethodChanged(func(route RouteInfo, oldMethod string) {
						// set service not available temporarily until the router completes the building
						// this won't take more than 100ms, but we want to inform the user.
						s.Router.handler = ToNativeHandler(s, HandlerFunc(func(ctx *Context) {
							ctx.EmitError(StatusServiceUnavailable)
						}))
						// Re-build the whole router if state changed (from offline to online state mostly)
						s.Router.build(routerBuilder)
					})
				}
			}
		}})

	}

	{
		//  +------------------------------------------------------------+
		//  | Module Name: System                                        |
		//  | On Build: Check for updates on Build, async                |
		//  +------------------------------------------------------------+

		// On Build: local repository updates
		s.Adapt(EventPolicy{Build: func(*Framework) {
			if s.Config.CheckForUpdates {
				go CheckForUpdates(false)
			}
		}})
	}

	return s
}

// Set sets an option, configuration field to its Config
func (s *Framework) Set(setters ...OptionSetter) {
	for _, setter := range setters {
		setter.Set(s.Config)
	}
}

// Log logs to the defined logger policy.
//
// The default outputs to the os.Stdout when EnvMode is 'iris.ProdMode'
func (s *Framework) Log(mode LogMode, log string) {
	s.policies.LoggerPolicy(mode, log)
}

// Author's note:
//
// I implemented this and worked for configuration fields logs but I'm not sure
// if users want to print adaptor's configuration, i.e: websocket, sessions
// so comment this feature, and
// if/when I get good feedback from the private beta testers I'll uncomment these on public repo too.
//
//
// Logf same as .Log but receives arguments like fmt.Printf.
// Note: '%#v' and '%+v' named arguments are being printed, pretty.
//
// The default outputs to the os.Stdout when EnvMode is 'iris.ProdMode'
// func (s *Framework) Logf(mode LogMode, format string, v ...interface{}) {
// 	if mode == DevMode {
// 		marker := 0
// 		for i := 0; i < len(format); i++ {
// 			if format[i] == '%' {
// 				if i < len(format)-2 {
// 					if part := format[i : i+3]; part == "%#v" || part == "%+v" {
// 						if len(v) > marker {
// 							spew.Config.Indent = "\t\t\t"
// 							spew.Config.DisablePointerAddresses = true
// 							spew.Config.DisableCapacities = true
// 							spew.Config.DisablePointerMethods = true
// 							spew.Config.DisableMethods = true
// 							arg := v[marker]
// 							format = strings.Replace(format, part, "%s", 1)
// 							v[marker] = spew.Sdump(arg)
// 						}
// 					}
// 				}
// 				marker++
// 			}
// 		}
// 	}
//
// 	log := fmt.Sprintf(format, v...)
//
// 	s.policies.LoggerPolicy(mode, log)
// }

// Must checks if the error is not nil, if it isn't
// panics on registered iris' logger or
// to a recovery event handler, otherwise does nothing.
func (s *Framework) Must(err error) {
	if err != nil {
		s.handlePanic(err)
	}
}

func (s *Framework) handlePanic(err error) {
	// if x, ok := err.(*net.OpError); ok && x.Op == "accept" {
	// 	return
	// }

	if err.Error() == http.ErrServerClosed.Error() && s.closedManually {
		//.Shutdown was called, log to dev not in prod (prod is only for critical errors.)
		// also do not try to recover from this error, remember, Shutdown was called manually here.
		s.Log(DevMode, "HTTP Server closed manually")
		return
	}

	if recoveryHandler := s.policies.EventPolicy.Recover; recoveryHandler != nil {
		recoveryHandler(s, err)
		return
	}
	// if not a registered recovery event handler found
	// then call the logger's Panic.
	s.Log(ProdMode, err.Error())
}

// Boot runs only once, automatically
//  when 'Serve/Listen/ListenTLS/ListenUNIX/ListenLETSENCRYPT' called.
// It's exported because you may want to build the router
//  and its components but not run the server.
//
// See ./httptest/httptest.go to understand its usage.
func (s *Framework) Boot() (firstTime bool) {
	s.once.Do(func() {
		// here execute the boot events, before build events, if exists, here is
		// where the user can make an event module to adapt custom routers and other things
		// fire the before build event
		s.policies.EventPolicy.Fire(s.policies.EventPolicy.Boot, s)

		// here execute the build events if exists
		// right before the Listen, all methods have been setted
		// usually is used to adapt third-party servers or proxies or load balancer(s)
		s.policies.EventPolicy.Fire(s.policies.EventPolicy.Build, s)
		firstTime = true
	})
	return
}

func (s *Framework) setupServe() (srv *http.Server, deferFn func()) {
	s.closedManually = false

	s.Boot()

	deferFn = func() {
		// post any panics to the user defined logger.
		if rerr := recover(); rerr != nil {
			if err, ok := rerr.(error); ok {
				s.handlePanic(err)
			}
		}
	}

	srv = &http.Server{
		ReadTimeout:    s.Config.ReadTimeout,
		WriteTimeout:   s.Config.WriteTimeout,
		MaxHeaderBytes: s.Config.MaxHeaderBytes,
		TLSNextProto:   s.TLSNextProto,
		ConnState:      s.ConnState,
		Addr:           s.Config.VHost,
		ErrorLog:       s.policies.LoggerPolicy.ToLogger(log.LstdFlags),
		Handler:        s.Router,
	}

	// Set the grace shutdown, it's just a func no need to make things complicated
	// all are managed by net/http now.
	s.Shutdown = func(ctx context.Context) error {
		// order matters, look s.handlePanic
		s.closedManually = true
		err := srv.Shutdown(ctx)
		return err
	}

	return
}

// Serve serves incoming connections from the given listener.
//
// Serve blocks until the given listener returns permanent error.
func (s *Framework) Serve(ln net.Listener) error {
	if ln == nil {
		return errors.New("nil net.Listener on Serve")
	}

	// if user called .Serve and doesn't uses any nginx-like balancers.
	if s.Config.VHost == "" {
		s.Config.VHost = ParseHost(ln.Addr().String())
	} // Scheme will be checked from Boot state.

	srv, fn := s.setupServe()
	defer fn()

	// print the banner and wait for system channel interrupt
	go s.postServe()
	return srv.Serve(ln)
}

func (s *Framework) postServe() {
	routerInfo := ""
	if routerNameVal := s.Config.Other[RouterNameConfigKey]; routerNameVal != nil {
		if routerName, ok := routerNameVal.(string); ok {
			routerInfo = "using " + routerName
		}
	}

	bannerMessage := fmt.Sprintf("Serving HTTP on %s port %d %s", ParseHostname(s.Config.VHost), ParsePort(s.Config.VHost), routerInfo)

	s.Log(DevMode, bannerMessage)

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt)
	<-ch

	// fire any custom interrupted events and at the end close and exit
	// if the custom event blocks then it decides what to do next.
	s.policies.Fire(s.policies.Interrupted, s)

	s.Shutdown(context.Background())
	os.Exit(1)
}

// Listen starts the standalone http server
// which listens to the addr parameter which as the form of
// host:port
//
// If you need to manually monitor any error please use `.Serve` instead.
func (s *Framework) Listen(addr string) {
	addr = ParseHost(addr)

	// if .Listen called normally and VHost is not setted,
	// so it's Host is the Real listening addr and user-given
	if s.Config.VHost == "" {
		s.Config.VHost = addr // as it is
		// this will be set as the front-end listening addr
	} // VScheme will be checked on Boot.

	// this check, only here, other Listen functions should throw an error if port is missing.
	if portIdx := strings.IndexByte(addr, ':'); portIdx < 0 {
		// missing port part, add it
		addr = addr + ":80"
	}

	ln, err := TCPKeepAlive(addr)
	if err != nil {
		s.handlePanic(err)
		return
	}

	s.Must(s.Serve(ln))
}

// ListenTLS Starts a https server with certificates,
// if you use this method the requests of the form of 'http://' will fail
// only https:// connections are allowed
// which listens to the addr parameter which as the form of
// host:port
//
//
// If you need to manually monitor any error please use `.Serve` instead.
func (s *Framework) ListenTLS(addr string, certFile, keyFile string) {
	addr = ParseHost(addr)

	{
		// set it before Boot, be-careful VHost and VScheme are used by nginx users too
		// we don't want to alt them.
		if s.Config.VHost == "" {
			s.Config.VHost = addr
			// this will be set as the front-end listening addr
		}
		if s.Config.VScheme == "" {
			s.Config.VScheme = SchemeHTTPS
		}
	}

	srv, fn := s.setupServe()
	// We are doing the same parts as .Serve does but instead we run srv.ListenAndServeTLS
	// because of un-exported net/http.server.go:setupHTTP2_ListenAndServeTLS function which
	// broke our previous flow but no problem :)
	defer fn()
	// print the banner and wait for system channel interrupt
	go s.postServe()
	s.Must(srv.ListenAndServeTLS(certFile, keyFile))
}

// ListenLETSENCRYPT starts a server listening at the specific nat address
// using key & certification taken from the letsencrypt.org 's servers
// it's also starts a second 'http' server to redirect all 'http://$ADDR_HOSTNAME:80' to the' https://$ADDR'
// it creates a cache file to store the certifications, for performance reasons, this file by-default is "./certcache"
// if you skip the second parameter then the cache file is "./letsencrypt.cache"
// if you want to disable cache then simple pass as second argument an empty empty string ""
//
// Note: HTTP/2 Push is not working with LETSENCRYPT, you have to use ListenTLS to enable HTTP/2
// Because net/http's author didn't exported the functions to tell the server that is using HTTP/2...
//
// example: https://github.com/kataras/iris/blob/v6/_examples/beginner/listen-letsencrypt/main.go
func (s *Framework) ListenLETSENCRYPT(addr string, cacheFileOptional ...string) {
	addr = ParseHost(addr)

	{
		// set it before Boot, be-careful VHost and VScheme are used by nginx users too
		// we don't want to alt them.
		if s.Config.VHost == "" {
			s.Config.VHost = addr
			// this will be set as the front-end listening addr
		}
		if s.Config.VScheme == "" {
			s.Config.VScheme = SchemeHTTPS
		}
	}

	ln, err := LETSENCRYPT(addr, addr, cacheFileOptional...)
	if err != nil {
		s.handlePanic(err)
		return
	}

	// starts a second server which listening on HOST:80 to redirect all requests to the HTTPS://HOST:PORT
	Proxy(ParseHostname(addr)+":80", "https://"+addr)
	s.Must(s.Serve(ln))
}

// ListenUNIX starts the process of listening to the new requests using a 'socket file',
// Note: this works only on unix
//
// If you need to manually monitor any error please use `.Serve` instead.
//
// example: https://github.com/kataras/iris/blob/v6/_examples/beginner/listen-unix/main.go
func (s *Framework) ListenUNIX(socketFile string, mode os.FileMode) {
	ln, err := UNIX(socketFile, mode)
	if err != nil {
		s.handlePanic(err)
		return
	}
	// *on unix listen we don't parse the host, because sometimes it causes problems to the user
	if s.Config.VHost == "" {
		s.Config.VHost = ln.Addr().String()
		// this will be set as the front-end listening addr
	}
	s.Must(s.Serve(ln))
}

func (s *Framework) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.Router.ServeHTTP(w, r)
}

// Adapt adapds a policy to the Framework.
// It accepts single or more objects that implements the iris.Policy.
// Iris provides some of them but you can build your own based on one or more of these:
// - iris.EventPolicy
// - iris.RouterReversionPolicy
// - iris.RouterBuilderPolicy
// - iris.RouterWrapperPolicy
// - iris.TemplateRenderPolicy
// - iris.TemplateFuncsPolicy
//
// With a Policy you can change the behavior of almost each of the existing Iris' features.
// See policy.go for more.
func (s *Framework) Adapt(policies ...Policy) {
	for i := range policies {
		policies[i].Adapt(&s.policies)
	}
}

// cachedMuxEntry is just a wrapper for the Cache functionality
// it seems useless but I prefer to keep the cached handler on its own memory stack,
// reason:  no clojures hell in the Cache function
type cachedMuxEntry struct {
	cachedHandler http.Handler
}

func newCachedMuxEntry(s *Framework, bodyHandler HandlerFunc, expiration time.Duration) *cachedMuxEntry {
	httpHandler := ToNativeHandler(s, bodyHandler)

	cachedHandler := httpcache.Cache(httpHandler, expiration)
	return &cachedMuxEntry{
		cachedHandler: cachedHandler,
	}
}

func (c *cachedMuxEntry) Serve(ctx *Context) {
	c.cachedHandler.ServeHTTP(ctx.ResponseWriter, ctx.Request)
}

// Cache is just a wrapper for a route's handler which you want to enable body caching
// Usage: iris.Default.Get("/", iris.Cache(func(ctx *iris.Context){
//    ctx.WriteString("Hello, world!") // or a template or anything else
// }, time.Duration(10*time.Second))) // duration of expiration
// if <=time.Second then it tries to find it though request header's "cache-control" maxage value
func (s *Framework) Cache(bodyHandler HandlerFunc, expiration time.Duration) HandlerFunc {
	ce := newCachedMuxEntry(s, bodyHandler, expiration)
	return ce.Serve
}

// Path used to check arguments with the route's named parameters and return the correct url
// if parse failed returns empty string.
// Used for reverse routing, depends on router adaptor.
//
// Examples:
// https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_3 (gorillamux)
// https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_4 (httprouter)
func (s *Framework) Path(routeName string, args ...interface{}) string {
	r := s.Router.Routes().Lookup(routeName)
	if r == nil {
		return ""
	}

	// why receive interface{}
	// but need string?
	// because the key:value are string for a route path
	// but in the template functions all works fine with ...string
	// except when the developer wants to pass that string from a binding
	// via Render, then the template will fail to render
	// because of expecting string; but got []string

	var argsString []string
	if len(args) > 0 {
		argsString = make([]string, len(args))
	}

	for i, v := range args {
		if s, ok := v.(string); ok {
			argsString[i] = s
		} else if num, ok := v.(int); ok {
			argsString[i] = strconv.Itoa(num)
		} else if b, ok := v.(bool); ok {
			argsString[i] = strconv.FormatBool(b)
		} else if arr, ok := v.([]string); ok {
			if len(arr) > 0 {
				argsString[i] = arr[0]
				argsString = append(argsString, arr[1:]...)
			}
		}
	}

	return s.policies.RouterReversionPolicy.URLPath(r, argsString...)
}

// URL returns the subdomain + host + Path(...optional named parameters if route is dynamic)
// returns an empty string if parse is failed.
// Used for reverse routing, depends on router adaptor.
//
// Examples:
// https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_3 (gorillamux)
// https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_4 (httprouter)
func (s *Framework) URL(routeName string, args ...interface{}) (url string) {
	r := s.Router.Routes().Lookup(routeName)
	if r == nil {
		return
	}

	scheme := s.Config.VScheme // if s.Config.VScheme was setted, that will be used instead of the real, in order to make easy to run behind nginx
	host := s.Config.VHost     // if s.Config.VHost was setted, that will be used instead of the real, in order to make easy to run behind nginx

	// if it's dynamic subdomain then the first argument is the subdomain part
	// for this part we are responsible not the custom routers
	if r.Subdomain() == DynamicSubdomainIndicator {
		if len(args) == 0 { // it's a wildcard subdomain but not arguments
			return
		}

		if subdomain, ok := args[0].(string); ok {
			host = subdomain + "." + host
		} else {
			// it is not array because we join them before. if not pass a string then this is not a subdomain part, return empty uri
			return
		}
		args = args[1:] // remove the subdomain part for the arguments,
	}

	if parsedPath := s.Path(routeName, args...); parsedPath != "" {
		url = scheme + host + parsedPath
	}

	return
}

// Regex takes pairs with the named path (without symbols) following by its expression
// and returns a middleware which will do a pure but effective validation using the regexp package.
//
// Note: '/adaptors/gorillamux' already supports regex path validation.
// It's useful while the developer uses the '/adaptors/httprouter' instead.
func (s *Framework) Regex(pairParamExpr ...string) HandlerFunc {
	srvErr := func(ctx *Context) {
		ctx.EmitError(StatusInternalServerError)
	}

	// just to check if router is adapted.
	wp := s.policies.RouterReversionPolicy.WildcardPath
	if wp == nil {
		s.Log(ProdMode, "regex cannot be used when a router policy is missing\n"+errRouterIsMissing.Format(s.Config.VHost).Error())
		return srvErr
	}

	if len(pairParamExpr)%2 != 0 {
		s.Log(ProdMode,
			"regex pre-compile error: the correct format is paramName, expression"+
				"paramName2, expression2. The len should be %2==0")
		return srvErr
	}

	// we do compile first to reduce the performance cost at serve time.
	pairs := make(map[string]*regexp.Regexp, len(pairParamExpr)/2)

	for i := 0; i < len(pairParamExpr)-1; i++ {
		expr := pairParamExpr[i+1]
		r, err := regexp.Compile(expr)
		if err != nil {
			s.Log(ProdMode, "regex '"+expr+"' failed. Trace: "+err.Error())
			return srvErr
		}

		pairs[pairParamExpr[i]] = r
		i++
	}

	// return the middleware
	return func(ctx *Context) {
		for k, v := range pairs {
			if !ctx.ParamValidate(v, k) {
				ctx.EmitError(StatusNotFound)
				return
			}
		}
		// otherwise continue to the next handler...
		ctx.Next()
	}
}

func (s *Framework) RegexSingle(paramName string, expr string, onFail HandlerFunc) HandlerFunc {

	// just to check if router is adapted.
	wp := s.policies.RouterReversionPolicy.WildcardPath
	if wp == nil {
		s.Log(ProdMode, "regex cannot be used when a router policy is missing\n"+errRouterIsMissing.Format(s.Config.VHost).Error())
		return onFail
	}

	// we do compile first to reduce the performance cost at serve time.
	r, err := regexp.Compile(expr)
	if err != nil {
		s.Log(ProdMode, "regex '"+expr+"' failed. Trace: "+err.Error())
		return onFail
	}

	// return the middleware
	return func(ctx *Context) {
		if !ctx.ParamValidate(r, paramName) {
			onFail(ctx)
			return
		}
		// otherwise continue to the next handler...
		ctx.Next()
	}
}

// RouteParam returns a named parameter as each router defines named path parameters.
// For example, with the httprouter(: as named param symbol):
// userid should return :userid.
// with gorillamux, userid should return {userid}
// or userid[1-9]+ should return {userid[1-9]+}.
// so basically we just wrap the raw parameter name
// with the start (and end) dynamic symbols of each router implementing the RouterReversionPolicy.
// It's an optional functionality but it can be used to create adaptors without even know the router
// that the user uses (which can be taken by app.Config.Other[iris.RouterNameConfigKey].
//
// Note: we don't need a function like ToWildcardParam because the developer
// can use the RouterParam with a combination with RouteWildcardPath.
//
// Example: https://github.com/iris-contrib/adaptors/blob/master/oauth/oauth.go
func (s *Framework) RouteParam(paramName string) string {
	if s.policies.RouterReversionPolicy.Param == nil {
		// all Iris' routers are implementing all features but third-parties may not, so make sure that the user
		// will get a useful message back.
		s.Log(DevMode, "cannot wrap a route named path parameter because the functionality was not implemented by the current router.")
		return ""
	}

	return s.policies.RouterReversionPolicy.Param(paramName)
}

// RouteWildcardPath returns a path converted to a 'dynamic' path
// for example, with the httprouter(wildcard symbol: '*'):
// ("/static", "path") should return /static/*path
// ("/myfiles/assets", "anything") should return /myfiles/assets/*anything
func (s *Framework) RouteWildcardPath(path string, paramName string) string {
	if s.policies.RouterReversionPolicy.WildcardPath == nil {
		s.Log(DevMode, "please use WildcardPath after .Adapt(router).\n"+errRouterIsMissing.Format(s.Config.VHost).Error())
		return ""
	}
	return s.policies.RouterReversionPolicy.WildcardPath(path, paramName)
}

// DecodeQuery returns the uri parameter as url (string)
// useful when you want to pass something to a database and be valid to retrieve it via context.Param
// use it only for special cases, when the default behavior doesn't suits you.
//
// http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
// it uses just the url.QueryUnescape
func DecodeQuery(path string) string {
	if path == "" {
		return ""
	}
	encodedPath, err := url.QueryUnescape(path)
	if err != nil {
		return path
	}
	return encodedPath
}

// DecodeURL returns the decoded uri
// useful when you want to pass something to a database and be valid to retrieve it via context.Param
// use it only for special cases, when the default behavior doesn't suits you.
//
// http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
// it uses just the url.Parse
func DecodeURL(uri string) string {
	u, err := url.Parse(uri)
	if err != nil {
		return uri
	}
	return u.String()
}

var errTemplateRendererIsMissing = errors.New(
	`
manually call of Render for a template: '%s' without specified RenderPolicy!
Please .Adapt one of the available view engines inside 'kataras/iris/adaptors/view'.
By-default Iris supports five template engines:
 - standard html  | view.HTML(...)
 - django         | view.Django(...)
 - handlebars     | view.Handlebars(...)
 - pug(jade)      | view.Pug(...)
 - amber          | view.Amber(...)

Edit your main .go source file to adapt one of these and restart your app.
	i.e: lines (<---) were missing.
	-------------------------------------------------------------------
	import (
		"github.com/iris-framework/iris"
		"github.com/iris-framework/iris/adaptors/httprouter" // or gorillamux
		"github.com/iris-framework/iris/adaptors/view" // <--- this line
	)

	func main(){
		app := iris.New()
		// right below the iris.New():
		app.Adapt(httprouter.New()) // or gorillamux.New()

		app.Adapt(view.HTML("./templates", ".html")) // <--- and this line were missing.

		// the rest of your source code...
		// ...

		app.Listen("%s")
	}
	-------------------------------------------------------------------
 `)

// RenderOptions is a helper type for  the optional runtime options can be passed by user when Render called.
// I.e the "layout" or "gzip" option
// same as iris.Map but more specific name
type RenderOptions map[string]interface{}

// Render renders using the specific template or any other rich content renderer to the 'w'.
//
// Example of usage:
// - send an e-mail using a template engine that you already
//   adapted via: app.Adapt(view.HTML("./templates", ".html"))  or app.Adapt(iris.RenderPolicy(mycustomRenderer)).
//
// It can also render json,xml,jsonp and markdown by-default before or after .Build too.
func (s *Framework) Render(w io.Writer, name string, bind interface{}, options ...map[string]interface{}) error {
	ok, err := s.policies.RenderPolicy(w, name, bind, options...)
	if !ok {
		// ok is false ONLY WHEN there is no registered render policy
		// that is responsible for that 'name` (if contains dot '.' it's for templates).
		// We don't use default template engines on the new version,
		// so we should notice the user here, we could make it to panic but because that is on runtime
		// we don't want to panic for that, let's give a message if the user adapted a logger for dev.
		// And return that error in the case the user wasn't in dev mode, she/he can catch this error.

		// Also on the README we will add the .Adapt(iris.DevLogger()) to mention that
		// logging for any runtime info(except http server's panics and unexpected serious errors) is not enabled by-default.
		if strings.Contains(name, ".") {
			err = errTemplateRendererIsMissing.Format(name, s.Config.VHost)
			s.Log(DevMode, err.Error())
			return err
		}

	}
	return err
}


text:
    About the Author

{{site.owner.name}}

{{site.owner.bio}}

        {% for network in site.social %}

        {% endfor %}


text: BaconBot a Private Bot For Discord


text:
/**
 *
 */
package info.novatec.beantest.demo.entities;

import java.util.Locale;

import javax.persistence.Entity;

/**
 * @author Carlos Barragan
 *
 */
@Entity
public class ShippingAddress extends BaseEntity {

	private Locale country;

	private String street;

	private String zipCode;

	protected ShippingAddress() {
		// For JPA.
	}

	/**
	 * @param country
	 * @param street
	 * @param zipCode
	 */
	public ShippingAddress(Locale country, String street, String zipCode) {
		this.country = country;
		this.street = street;
		this.zipCode = zipCode;
	}

	/**
	 * @return the country
	 */
	public Locale getCountry() {
		return country;
	}

	/**
	 * @param country
	 *            the country to set
	 */
	public void setCountry(Locale country) {
		this.country = country;
	}

	/**
	 * @return the street
	 */
	public String getStreet() {
		return street;
	}

	/**
	 * @param street
	 *            the street to set
	 */
	public void setStreet(String street) {
		this.street = street;
	}

	/**
	 * @return the zipCode
	 */
	public String getZipCode() {
		return zipCode;
	}

	/**
	 * @param zipCode
	 *            the zipCode to set
	 */
	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}

}


text:
var config = require('config')
var debug = require('debug')
var fmt = require('fmt')
var request = require('./client/request')

/**
 * Format Errors
 */

fmt.e = function (e) {
  e = e || 'No error'
  var s = e.fileName || ''
  s += e.lineNumber ? ':' + e.lineNumber : ''
  s += e.columnNumber ? ':' + e.columnNumber + '\n' : ''
  s += e.stack ? e.stack : e + ''
  return s
}

/**
 * Logging levels
 */

var levels = ['silly', 'debug', 'verbose', 'info', 'warn', 'error']
var infoIndex = levels.indexOf('info')

/**
 * Expose `log`
 */

module.exports = function (name) {
  var _debug = debug(config.application() + ':' + name)

  function _log (type, text) {
    if (levels.indexOf(type) === -1) {
      text = fmt.apply(null, arguments)
      type = 'verbose'
    }

    // Send to console
    _debug(text)

    // Save info & above
    if (levels.indexOf(type) >= infoIndex) {
      // Send to server
      request.post('/log', {
        text: text,
        type: type
      })
    }
  }

  levels.forEach(function (level) {
    _log[level] = function () {
      _log(level, fmt.apply(null, arguments))
    }
  })

  return _log
}


text:
<?php
namespace Procure\Infrastructure\Mapper;

use Application\Entity\NmtApplicationCompany;
use Application\Entity\NmtApplicationCurrency;
use Application\Entity\NmtApplicationIncoterms;
use Application\Entity\NmtApplicationPmtMethod;
use Application\Entity\NmtApplicationPmtTerm;
use Application\Entity\NmtBpVendor;
use Application\Entity\NmtFinPostingPeriod;
use Application\Entity\NmtInventoryWarehouse;
use Procure\Domain\DocSnapshot;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class HeaderMapper
{

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtApplicationIncoterms $entity
     */
    public static function updateIncotermDetails(DocSnapshot $snapshot, NmtApplicationIncoterms $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->incoterm = $entity->getId();
        $snapshot->incotermCode = $entity->getIncoterm();
        $snapshot->incotermName = $entity->getIncoterm();
        return $snapshot;
    }

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtInventoryWarehouse $entity
     * @return NULL|\Procure\Domain\DocSnapshot
     */
    public static function updateWarehouseDetails(DocSnapshot $snapshot, NmtInventoryWarehouse $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->warehouse = $entity->getId();
        $snapshot->warehouseCode = $entity->getWhCode();
        $snapshot->warehouseName = $entity->getWhName();
        return $snapshot;
    }

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtFinPostingPeriod $entity
     * @return NULL|\Procure\Domain\DocSnapshot
     */
    public static function updatePostingPeriodDetails(DocSnapshot $snapshot, NmtFinPostingPeriod $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->postingPeriod = $entity->getId();
        $snapshot->postingPeriodId = $entity->getId();
        // $snapshot->postingPeriodFrom = $entity->getPostingFromDate();
        // $snapshot->postingPeriodTo = $entity->getPostingToDate();
        return $snapshot;
    }

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtApplicationPmtTerm $entity
     * @return NULL|\Procure\Domain\DocSnapshot
     */
    public static function updatePmtTermDetails(DocSnapshot $snapshot, NmtApplicationPmtTerm $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->pmtTerm = $entity->getId();
        $snapshot->paymentTermName = $entity->getPmtTermName();
        $snapshot->paymentTermCode = $entity->getPmtTermCode();

        return $snapshot;
    }

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtApplicationCurrency $entity
     * @return NULL|\Procure\Domain\DocSnapshot
     */
    public static function updateLocalCurrencyDetails(DocSnapshot $snapshot, NmtApplicationCurrency $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->localCurrency = $entity->getId();
        $snapshot->localCurrencyId = $snapshot->localCurrency;
        $snapshot->localCurrencyISO = $entity->getCurrency();

        return $snapshot;
    }

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtApplicationCurrency $entity
     * @return NULL|\Procure\Domain\DocSnapshot
     */
    public static function updateDocCurrencyDetails(DocSnapshot $snapshot, NmtApplicationCurrency $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->docCurrency = $entity->getId();
        $snapshot->currencyIso3 = $entity->getCurrency();
        $snapshot->docCurrencyId = $snapshot->docCurrency;
        $snapshot->docCurrencyISO = $snapshot->getCurrencyIso3();

        return $snapshot;
    }

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtApplicationPmtMethod $entity
     * @return NULL|\Procure\Domain\DocSnapshot
     */
    public static function updatePmtMethodDetails(DocSnapshot $snapshot, NmtApplicationPmtMethod $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->paymentMethod = $entity->getId();
        $snapshot->paymentMethodName = $entity->getMethodName();
        $snapshot->paymentMethodCode = $entity->getMethodCode();

        return $snapshot;
    }

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtApplicationCompany $entity
     * @return NULL|\Procure\Domain\DocSnapshot
     */
    public static function updateCompanyDetails(DocSnapshot $snapshot, NmtApplicationCompany $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->company = $entity->getId();
        $snapshot->companyName = $entity->getCompanyName();
        $snapshot->companyCode = $entity->getCompanyCode();
        $snapshot->companyToken = $entity->getToken();
        return $snapshot;
    }

    /**
     *
     * @param \Procure\Domain\DocSnapshot $snapshot
     * @param \Application\Entity\NmtBpVendor $entity
     * @return NULL|\Procure\Domain\DocSnapshot
     */
    public static function updateVendorDetails(DocSnapshot $snapshot, NmtBpVendor $entity)
    {
        if ($snapshot == null) {
            return null;
        }

        if ($entity == null) {
            return $snapshot;
        }

        $snapshot->vendor = $entity->getId();
        $snapshot->vendorName = $entity->getVendorName();
        $snapshot->vendorId = $snapshot->vendor;
        $snapshot->vendorToken = $entity->getToken();
        $snapshot->vendorAddress = sprintf("%s %s", $entity->getStreet(), $entity->getCity());

        if ($entity->getCountry() !== null) {
            $snapshot->vendorCountry = $entity->getCountry()->getCountryName();
        }

        return $snapshot;
    }
}


text:
package org.jnd.product.repository;

import org.jnd.model.Product;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Component;

/**
 * Created by justin on 13/10/2015.
 */
@Component("ProductRepository")
public interface ProductRepository extends MongoRepository<Product, String>{
    Product findById(String id);
}


text:
Read this in other languages:
- [English](README.md)
- [عربى](README.ar.md)

# What it does

Language code in URL:

- jorider.com/en/about
- jorider.com/ar/about

The [CodeIgniter Language Class][1] is used in order to fetch and display (directly in the HTML) the appropriate text defined in the respective language file.

## Examples

View file

<?php echo lang('I\'m a man')?>

English language file

    $lang['I\'m a man'] = "I'm a man";
Arabic language file

    $lang['I\'m a man'] = "انا رجل";
Result with jorider.com/en/about

I'm a man

Result with jorider.com/ar/about

انا رجل

# Usage

Before using this library, please read and learn about the [CodeIgniter Language Class][1] concepts and methods.

## Installation

- Clone repository;
- Place the `MY_Lang.php` and `MY_Config.php` files together in the `application/core` folder.

# Example of bilingual English/Arabic website:

## Configuration

In _application/config/routes.php_ add:

    // example: '/en/about' -> use controller 'about'
    $route['^en/(.+)$'] = "$1";
    $route['^ar/(.+)$'] = "$1";
    // '/en' and '/ar' -> use default controller
    $route['^(en|ar)$'] = $route['default_controller'];

Other routing examples:

    $route['^(en|ar)/contact'] = "pages/contact";
    $route['^(en|ar)/privacy-policy$'] = "pages/index/privacy_policy";
    $route['^(en|ar)/terms-of-use$'] = "pages/index/terms_of_use";

Important Note: make sure to add other routs before wildcards regular expression routes above:

    $route['^(en|ar)/contact'] = "pages/contact";
    $route['^(en|ar)/privacy-policy$'] = "pages/index/privacy_policy";
    $route['^(en|ar)/terms-of-use$'] = "pages/index/terms_of_use";
    // example: '/en/about' -> use controller 'about'
    $route['^en/(.+)$'] = "$1";
    $route['^ar/(.+)$'] = "$1";
    // '/en' and '/ar' -> use default controller
    $route['^(en|ar)$'] = $route['default_controller'];

### Create _Language Files_

- `application/language/english/about_lang.php`

      <?php

      $lang['I\'m a man'] = "I'm a man";

- `application/language/arabic/about_lang.php`

      <?php

      $lang['I\'m a man'] = "انا رجل";

### Load the language helper and file in the respective _Controller_

`application/controllers/about.php`

    <?php
    class About extends CI_Controller {

      function index()
      {
        // you might want to just autoload these two helpers
        $this->load->helper(['language', 'url']);

        // load language file
        $this->lang->load('about');

        $this->load->view('about');
      }
    }

### Invoke directly the `lang` method in the _View_

`application/views/about.php`

<?php echo lang('I\'m a man')?>

## Test

`http://your_base_url/en/about`

I'm a man

`http://your_base_url/ar/about`

انا رجل

## Notes

- You might need to translate some of CodeIgniter's language files in `system/language`. Example: if you're using the [Form Validation][2] library for Arabic pages, translate `system/language/english/form_validation_lang.php` to `application/language/arabic/form_validation_lang.php`.

- links to internal pages are prefixed by the current language, but links to files are not.

      site_url('about/my_work');
      // http://mywebsite.com/en/about/my_work

      base_url('css/styles.css');
      // http://mywebsite.com/css/styles.css

- Get the current language:

      $this->lang->lang();
      // en

- Switch to another language:

      anchor($this->lang->switch_uri('ar'),'Display current page in Arabic');

- the root page (`/`) is supposed to be some kind of splash page, without any specific language. However, this can be changed. Read the **No splash page** section below.

- the CodeIgniter `system/core/Config.php` `site_url()` method is overridden in `MY_Config.php`: a language segment can be added (when appropriate) to generated URLs. It is also used by `anchor()`, `form_open()`...

- If a key is not found in the language file's array, a file called `strings_lang.php` will be created and the key and value will be added to it. E.g. if `line('xyz')` is not available, `strings_lang.php` will be created and will contain:

      <?php

      defined('BASEPATH') OR exit('No direct script access allowed');

      $lang['xyz'] = "xyz";

# Options

## Special URIs

A special URI is not prefixed by a language. The root URI (`/`) is by default a special URI.

You might need other special URIs, like for an admin section in just one language.

In `application/core/MY_Lang.php`, by adding the `'admin'` string to the `$special` array, links to the admin page will not be prefixed by the current language.

    site_url('admin');
    // http://your_base_url/admin

## No splash page

In `application/core/MY_Lang.php`:

1. remove `""` from the `$special` array;
2. set `$default_uri` to something else like `home`;
3. if English is your default language, now a request to `/` will be redirected to `en/home`;
4. the default language is the first item of the `$languages` array.

## Add a new language

`application/core/MY_Lang.php`: add a new language to `$languages` array

    // example: German (de)
    'de' => 'german',

`application/config/routes.php`: add new routes

    // example: German (de)
    $route['^de/(.+)$'] = "$1";
    $route['^(en|ar|de)$'] = $route['default_controller'];

- create the corresponding language folder in application/language. For this _German_ example, it would be called `german`.

[1]: https://codeigniter.com/user_guide/libraries/language.html
[2]: https://codeigniter.com/user_guide/libraries/form_validation.html


text:
import React from 'react';

import { createChapter } from 'components/chapter';

const title = 'Primer naloge';

function Chapter() {
    return (

                ...

    );
}

export default createChapter(title, Chapter);


text:
package jumpingalien.model.programs.statements;

import jumpingalien.model.programs.Environment;
import jumpingalien.model.programs.Statement;
import jumpingalien.part3.programs.SourceLocation;

import java.util.List;

public class SequenceStatement extends Statement
{
	private final List<Statement> statementList;

	public SequenceStatement(SourceLocation sourceLocation, List<Statement> statements)
	{
		super(sourceLocation);
		statementList = statements;
	}

	public void exe(Environment env)
	{
		for (Statement statement : statementList)
		{
			statement.exe(env);
		}
		//statementList.stream().forEach(obj -> obj.exe(env));
	}

	public List<Statement> getStatementList()
	{
		return statementList;
	}
}


text:
angular.module('orderCloud')
	.controller('PaymentCtrl', PaymentController)
;

function PaymentController($scope, $rootScope, OrderCloudSDK, ocCheckoutPaymentService, CheckoutConfig) {
	if (!$scope.methods) $scope.methods = CheckoutConfig.AvailablePaymentMethods;
	if (!$scope.payment) {
		OrderCloudSDK.Payments.List('outgoing', $scope.order.ID)
			.then(function(data) {
				if (ocCheckoutPaymentService.PaymentsExceedTotal(data, $scope.order.Total)) {
					ocCheckoutPaymentService.RemoveAllPayments(data, $scope.order)
						.then(function(data) {
							var payment = {
								Type: CheckoutConfig.AvailablePaymentMethods[0],
								DateCreated: new Date().toISOString(),
								CreditCardID: null,
								SpendingAccountID: null,
								Description: null,
								Amount: $scope.order.Total,
								xp: {}
							};
							$scope.payment = payment;
						});
				}
				else if (data.Items.length) {
					$scope.payment = data.Items[0];
					if ($scope.methods.length == 1) $scope.payment.Type = $scope.methods[0];
				} else {
					var payment = {
						Type: CheckoutConfig.AvailablePaymentMethods[0],
						DateCreated: new Date().toISOString(),
						CreditCardID: null,
						SpendingAccountID: null,
						Description: null,
						Amount: $scope.order.Total,
						xp: {},
						Editing: true
					};
					$scope.payment = payment;
				}
			});
	} else if ($scope.methods.length == 1) {
		$scope.payment.Type = $scope.methods[0];
	}

	$rootScope.$on('OCPaymentUpdated', function(event, payment) {
		$scope.payment = payment;
	});

	$scope.savePayment = function(payment) {
		if (payment.ID) {
			OrderCloudSDK.Payments.Delete('outgoing', $scope.order.ID, payment.ID)
				.then(function() {
					delete payment.ID;
					createPayment(payment);
				});
		} else {
			createPayment(payment);
		}

		function createPayment(newPayment) {
			if (angular.isDefined(newPayment.Accepted)) delete newPayment.Accepted;
			OrderCloudSDK.Payments.Create('outgoing', $scope.order.ID, newPayment)
				.then(function(data) {
					data.Editing = false;
					$scope.OCPayment.$setValidity('ValidPayment', true);
					$scope.payment = data;
				});
		}
	};

	$scope.paymentValid = function(payment) {
		if (!payment || payment.Editing || payment.Amount != $scope.order.Total) return false; //TODO: refactor for multiple payments

		var valid = false;

		switch(payment.Type) {
			case 'CreditCard':
				valid = payment.CreditCardID != null;
				break;
			case 'SpendingAccount':
				valid = payment.SpendingAccountID != null;
				break;
			case 'PurchaseOrder':
				valid = true;
				break;
		}

		$scope.OCPayment.$setValidity('ValidPayment', (valid && !payment.Editing));

		return valid;
	};
}


text:
layout: post
title: Big Butt Oil Orgy 3
titleinfo: pornvd
desc: Watch Big Butt Oil Orgy 3. Pornhub is the ultimate xxx porn and sex site.
---

Big Butt Oil Orgy 3

Watch Big Butt Oil Orgy 3. Pornhub is the ultimate xxx porn and sex site.


text:
<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;

class SalidasRepository extends EntityRepository
{
    public function buscar($id, $select = null, $hydrationMode = null)
    {
        if(!$select) {
            $select = "sls, pgs, ecs, dts";
        }

        if(!$hydrationMode) {
            $hydrationMode = 'HYDRATE_OBJECT';
        }

        $qb = $this->createQueryBuilder('sls');

        $qb->select($select)
            ->innerJoin('sls.programa', 'pgs')
            ->innerJoin('sls.ejercicio', 'ecs')
            ->innerJoin('sls.destino', 'dts')
            ->innerJoin('ecs.almacen', 'ams')
            ->andWhere('sls.id = :id')
            ->setParameter('id', $id)
        ;

        $query = $qb->getQuery();

        switch($hydrationMode) {
            case "HYDRATE_ARRAY":
                $hydration = $query::HYDRATE_ARRAY;
                break;

            case "HYDRATE_OBJECT":
                $hydration = $query::HYDRATE_OBJECT;
                break;

        }
        try {
            return $query->getSingleResult($hydration);
        } catch (NoResultException $ex) {
            return null;
        }

    }

    public function contarEnSalidas($salidaId)
    {
        $dql = "SELECT COUNT(sds.id) FROM AppBundle:SalidaDetalles AS sds "
                . "INNER JOIN sds.salida AS sls "
                . "WHERE sds.salida = :salida";

        $q = $this->getEntityManager()->createQuery($dql)
                ->setParameter('salida', $salidaId);

        return $q->getSingleScalarResult();
    }
}


text:
<form class="form-horizontal">
<fieldset>

<legend>Generate Meta Data</legend>

    Candidate Name

      <input type="text"
             cam-variable-name="candidateName"
             cam-variable-type="String"
             required
             readonly
             class="form-control" />

    Application Link

  Region

    <select id="selectbasic" name="selectbasic" class="form-control"
    	cam-variable-name="region"
        cam-variable-type="String" >
      <option value="berlin">Berlin</option>
      <option value="dublin">Dublin</option>
      <option value="austin">Austin</option>
      <option value="pretoria">Pretoria</option>
    </select>

  Claim Type

    <select id="selectbasic" name="selectbasic" class="form-control"
    	cam-variable-name="claimType"
        cam-variable-type="String">
      <option value="car">Car</option>
      <option value="home">Home</option>
      <option value="personal">Personal</option>
    </select>

  Claim Amount

  <input id="Duration" name="Duration" type="text" placeholder="total amount" class="form-control input-md"
  		cam-variable-name="claimAmount"
  		cam-variable-type="Double">
  enter the total amount requested in the claim

</fieldset>
</form>


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:background="#f1f1f1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="com.garyhu.citypickerdemo.widget.third.ZoomHeaderBehavior"
        />

    <RelativeLayout
        android:layout_gravity="bottom"
        android:id="@+id/rv_bottom"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="60dp">

        <ImageView
            android:alpha="5"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:src="@drawable/cart" />

        <View
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:background="#88000000" />
    </RelativeLayout>

    <com.garyhu.citypickerdemo.widget.third.ZoomHeaderView
        android:id="@+id/zoomHeader"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:clipChildren="false"
        android:gravity="center"
        android:orientation="vertical"
        >
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="200dp"
            >
            <View
                android:layout_width="match_parent"
                android:layout_height="200dp"
                />
            <TextView
                android:alpha="0"
                android:id="@+id/tv_close"
                android:layout_marginBottom="10dp"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:text = "下滑关闭"
                android:textColor="#fff"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </RelativeLayout>
        <com.garyhu.citypickerdemo.widget.third.ZoomHeaderViewPager
            android:id="@+id/viewpager"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:clipChildren="false"
            />
    </com.garyhu.citypickerdemo.widget.third.ZoomHeaderView>

</android.support.design.widget.CoordinatorLayout>