text:
author: victor
excerpt: ''
categories:
    - PHP
tags:
    - 'servidor web embebido'
permalink: /el-servidor-web-incluido-en-php-5-4
no_html_extension: true
layout: post
title: 'El servidor web incluido en PHP 5.4'

---
Entre las muchas mejoras que introdujo PHP 5.4, una de ellas fue la inclusión de serie de un servidor web embebido al estilo Python built in server. La intención es permitir realizar pruebas de nuestros proyectos y no es apto para entornos de producción. El servidor resuelve las peticiones de forma secuencial y es posible indicar el root document o directorio de trabajo. Además, también podemos proporcionar un script que hará de enrutador para las peticiones.

La forma más sencilla de iniciar el servidor es la siguiente (desde la consola):

$ php -S localhost:8000

El comando anterior levanta el servidor en el puerto 8000 y toma como root document el directorio actual:

PHP 5.4.11 Servidor de desarrollo iniciado en Domingo Enero 27 12:27:01 2013
Escuchando en localhost:8000
La raíz de documentos es /var/www-interno
Presione Ctrl-C para salir

Si queremos usar otro directorio de trabajo debemos añadir la opción -t:

$ php -S localhost:8000 -t /home/yosymfony/html-publico

El servidor es capaz de devolver el MIME type adecuado para los siguientes recursos: .css, .gif, .htm, .html, .jpe, .jpeg, .jpg, .js, .png, .svg, y .txt. Desde la versión 5.4.4 en adelante también soporta .htm y .svg. Si quisieramos agregar un nuevo tipo no soportado, usaríamos un script enrutador que se lanza con cada petición:

// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path["extension"] == "ogg") {
    header("Content-Type: video/ogg");
    readfile($_SERVER["SCRIPT_FILENAME"]); // Se devuelve el contenido del fichero
}
else {
    return FALSE; // Continúa resolviéndose la petición
}

Y ahora solo queda levantar el servidor con los nuevos parámetros:

$ php -S localhost:8000 -t /home/yosymfony/html-publico router.php

Más información: Servidor web embebido en PHP


text:
<?php

namespace IronBound\DB\Extensions\Trash;

use IronBound\DB\Table\Table;

/**
 * Interface TrashTable
 * @package IronBound\DB\Table\Trash
 */
interface TrashTable extends Table {

	/**
	 * Get the name of the deleted at column.
	 *
	 * This MUST correspond to a DATETIME colun.
	 *
	 * @since 2.0
	 *
	 * @return string
	 */
	public function get_deleted_at_column();
}

redpajama_set_name: RedPajamaGithub


text:
package org.gwtlib.client.ui;

import java.util.EventListener;

/**
 * Event listener interface for MessageBox events.
 *
 * @author Sander Berents
 */
public interface MessageBoxListener extends EventListener {
  void onMessageBoxClosed(MessageBox sender, MessageBox.ButtonType buttonClicked);
}


text:
package poc.hortonworks.storm.truck.service;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import poc.hortonworks.domain.transport.TruckDriverViolationEvent;

@Service
public class DriverEventsService {

	private static String HBASE_ZOOKEEPER_HOST = "";
	private static final String DRIVER_EVENTS_TABLE = "driver_dangerous_events";
	private static String DRIVER_EVENTS_COLUMN_FAMILY_NAME = "events";

	private static final String DRIVER_EVENTS_COUNT_TABLE = "driver_dangerous_events_count";
	private static String DRIVER_EVENTS_COUNT_COLUMN_FAMILY_NAME = "counters";

	private static final Logger LOG = Logger.getLogger(DriverEventsService.class);

	private HTableInterface driverEventsTable;
	private HTableInterface driverEventsCountTable;

	public DriverEventsService() {
		Properties properties = new Properties();
		try{
			properties.load(new FileInputStream(new File("/etc/storm_demo/config.properties")));
		}
		catch(Exception ex){
			System.err.println("Unable to locate config file: /etc/storm_demo/config.properties");
			System.exit(0);
		}

		HBASE_ZOOKEEPER_HOST = properties.getProperty("hbase.zookeeper.server");

		try {
			Configuration config = constructConfiguration();
			HConnection connection = HConnectionManager.createConnection(config);
			driverEventsTable = connection.getTable(DRIVER_EVENTS_TABLE);
			driverEventsCountTable = connection.getTable(DRIVER_EVENTS_COUNT_TABLE);
		} catch (Exception e) {
			LOG.error("Error connectiong to HBase", e);
			throw new RuntimeException("Error Connecting to HBase", e);
		}
	}

	public Collection<TruckDriverViolationEvent> getLatestEventsForAllDrivers() {
		try {
			ResultScanner resultScanner = driverEventsTable.getScanner(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME));
			Map<Integer, TruckDriverViolationEvent> eventsMap = new HashMap<Integer, TruckDriverViolationEvent> ();
			for(Result result = resultScanner.next(); result != null ; result = resultScanner.next()) {

				//String key = Bytes.toString(result.getRow());
				int driverId = Bytes.toInt(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("driverId")));
				if(eventsMap.get(driverId) == null) {
					int truckId = Bytes.toInt(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("truckId")));
					String truckDriverEventKey = driverId + "|" + truckId;

					long eventTimeLong = Bytes.toLong(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("eventTime")));
					SimpleDateFormat sdf = new SimpleDateFormat();
					String timeStampString = sdf.format(eventTimeLong);

					double longitude = Bytes.toDouble(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("longitudeColumn")));
					double latitude = Bytes.toDouble(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("longitudeColumn")));

					String lastInfraction = Bytes.toString(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("eventType")));
					long numberOfInfractions = getInfractionCountForDriver(driverId);

					int routeId = Bytes.toInt(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("routeId")));
					String driverName = Bytes.toString(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("driverName")));

					String routeName = Bytes.toString(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COLUMN_FAMILY_NAME), Bytes.toBytes("routeName")));

					TruckDriverViolationEvent event = new TruckDriverViolationEvent(truckDriverEventKey, driverId, truckId, eventTimeLong,
										timeStampString, longitude, latitude, lastInfraction, numberOfInfractions, driverName, routeId, routeName );

					eventsMap.put(driverId, event);
				}
			}
			return eventsMap.values();
		} catch (Exception e) {
			LOG.error("Error getting driver events", e);
			throw new RuntimeException("Error getting driver events", e);
		}
	}

	private long getInfractionCountForDriver(int driverId) {
		try {
			byte[] driverCount = Bytes.toBytes(driverId);
			Get get = new Get(driverCount);
			Result result = driverEventsCountTable.get(get);
			long count = Bytes.toLong(result.getValue(Bytes.toBytes(DRIVER_EVENTS_COUNT_COLUMN_FAMILY_NAME), Bytes.toBytes("incidentRunningTotal")));
			return count;
		} catch (Exception e) {
			LOG.error("Error getting infraction count", e);
			throw new RuntimeException("Error getting infraction count");
		}
	}

	private Configuration constructConfiguration() throws Exception {
		Configuration config = HBaseConfiguration.create();
		config.set("hbase.zookeeper.quorum",
				HBASE_ZOOKEEPER_HOST);
		config.set("hbase.zookeeper.property.clientPort", "2181");
		config.set("zookeeper.znode.parent", "/hbase-unsecure");
		//HBaseAdmin.checkHBaseAvailable(config);
		return config;
	}

}


text:
module SellObject
	module Buscape
		def self.included(base)
	  	base.extend ClassMethods
	  end

	  def self.wrap_xml(elements, store_name = nil)
	  	store_name ||= SellObject::Config.store_name
	  	raise ArgumentError, 'No store name found (nil). You have to either pass it as an argument or set it up in SellObject::Config' if store_name.nil?
	  	store_name = store_name.gsub(/ +/, '_')
	  	result = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
	  		xml.comment timestamp
	  		xml.send(store_name) {
	  			xml.produtos do
	  				xml << elements
	  			end
	  		}
	  	end
	  	result.to_xml
	  end

	  def self.timestamp
	  	now = Time.now
    	zone_diff = now.strftime("%z").to_i / 100
    	time = now.strftime "%Y-%m-%dT%H:%M:%SGMT#{'+' if zone_diff >= 0}#{zone_diff}"
	  	"Generated at #{time}"
	  end

	  module ClassMethods
			# Class methods added on inclusion

			def to_buscape(objects, store_name = nil)
				elements = objects.map {|obj| SellObject::XmlFormatter.format obj, :buscape, :produto, SellObject::Buscape::FormatterProxy.new(obj) }.join ''
				SellObject::Buscape.wrap_xml elements, store_name
			end
		end

		# Instance methods added on inclusion

		def to_buscape(store_name = nil)
			self.class.to_buscape [self], store_name
		end
	end
end


text:
package thahn.java.agui.view;

import thahn.java.agui.app.Context;
import thahn.java.agui.app.Intent;
import thahn.java.agui.exception.NotExistException;
import thahn.java.agui.graphics.Drawable;
import thahn.java.agui.widget.TextView;

public class MenuItemImpl implements MenuItem {

	Context															mContext;
	int 															id;
	int 															groupId;
	int 															order;
	int 															showAsAction;
	int 															layoutId;
	String 															title;
	Drawable														icon;
	View															actionView;
	MenuItem.OnMenuItemClickListener								menuItemClickListener;

	public static final MenuItem makeMenuItem(Context context, int id) {
		MenuItem item = new MenuItemImpl(context, id);
		return item;
	}

	private MenuItemImpl(Context context, int id) {
		mContext = context;
		this.id = id;
	}

	MenuItemImpl(Context context, AttributeSet a) {
		mContext = context;

		id = a.getResourceId(thahn.java.agui.R.attr.Menu_id, -1);
		setIcon(a.getDrawable(thahn.java.agui.R.attr.Menu_icon, -1));
		setTitle(a.getString(thahn.java.agui.R.attr.Menu_title, ""));

		layoutId = a.getLayoutId(thahn.java.agui.R.attr.ActionBar_actionLayout, -1);
		if(layoutId == -1) {
			actionView = LayoutInflater.inflate(context, thahn.java.agui.R.layout.agui_actionbar_item, null);
			actionView.setId(id);
			if(icon != null) actionView.findViewById(thahn.java.agui.R.id.item_icon).setBackgroundDrawable(icon);
			if(title != null) ((TextView)actionView.findViewById(thahn.java.agui.R.id.item_title)).setText(title);
		} else {
			actionView = LayoutInflater.inflate(context, layoutId, null);
		}
		order = a.getInt(thahn.java.agui.R.attr.ActionBar_orderInCategory, -1);
		setShowAsAction(a.getIntFromEnum(thahn.java.agui.R.attr.ActionBar_showAsAction, MenuItem.SHOW_AS_ACTION_ALWAYS));
	}

	@Override
	public int getItemId() {
		return id;
	}

	@Override
	public int getGroupId() {
		return 0;
	}

	@Override
	public int getOrder() {
		return 0;
	}

	@Override
	public MenuItem setTitle(CharSequence title) {
		this.title = String.valueOf(title);
		if(layoutId == -1) ((TextView)actionView.findViewById(thahn.java.agui.R.id.item_title)).setText(this.title);
		return this;
	}

	@Override
	public MenuItem setTitle(int title) {
		String ret = mContext.getResources().getString(title);
		if(ret != null) {
			setTitle(ret);
		} else {
			throw new NotExistException("resource id : " + title + " not exist");
		}
		return this;
	}

	@Override
	public CharSequence getTitle() {
		String ret = null;
		if(layoutId == -1) ret = ((TextView)actionView.findViewById(thahn.java.agui.R.id.item_title)).getText();
		return ret;
	}

	@Override
	public MenuItem setTitleCondensed(CharSequence title) {
		return null;
	}

	@Override
	public CharSequence getTitleCondensed() {
		return null;
	}

	@Override
	public MenuItem setIcon(Drawable icon) {
		if(icon != null) {
			this.icon = icon;
		}
		return this;
	}

	@Override
	public MenuItem setIcon(int iconRes) {
		this.icon = mContext.getResources().getDrawable(iconRes);
		return this;
	}

	@Override
	public Drawable getIcon() {
		return this.icon;
	}

	@Override
	public MenuItem setIntent(Intent intent) {
		return null;
	}

	@Override
	public Intent getIntent() {
		return null;
	}

	@Override
	public MenuItem setShortcut(char numericChar, char alphaChar) {
		return null;
	}

	@Override
	public MenuItem setNumericShortcut(char numericChar) {
		return null;
	}

	@Override
	public char getNumericShortcut() {
		return 0;
	}

	@Override
	public MenuItem setAlphabeticShortcut(char alphaChar) {
		return null;
	}

	@Override
	public char getAlphabeticShortcut() {
		return 0;
	}

	@Override
	public MenuItem setCheckable(boolean checkable) {
		return null;
	}

	@Override
	public boolean isCheckable() {
		return false;
	}

	@Override
	public MenuItem setChecked(boolean checked) {
		return null;
	}

	@Override
	public boolean isChecked() {
		return false;
	}

	@Override
	public MenuItem setVisible(boolean visible) {
		return null;
	}

	@Override
	public boolean isVisible() {
		return false;
	}

	@Override
	public MenuItem setEnabled(boolean enabled) {
		return null;
	}

	@Override
	public boolean isEnabled() {
		return false;
	}

	@Override
	public boolean hasSubMenu() {
		return false;
	}

	@Override
	public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
		this.menuItemClickListener = menuItemClickListener;
		return this;
	}

	@Override
	public void setShowAsAction(int actionEnum) {
		showAsAction = actionEnum;
		switch (showAsAction) {
		case MenuItem.SHOW_AS_ACTION_ALWAYS:
			if(layoutId == -1) {
				actionView.setVisibility(View.VISIBLE);
				actionView.findViewById(thahn.java.agui.R.id.item_title).setVisibility(View.GONE);
			}
			break;
		case MenuItem.SHOW_AS_ACTION_WITH_TEXT:
			if(layoutId == -1) {
				actionView.setVisibility(View.VISIBLE);
				actionView.findViewById(thahn.java.agui.R.id.item_title).setVisibility(View.VISIBLE);
			}
			break;
		case MenuItem.SHOW_AS_ACTION_NEVER:
			actionView.setVisibility(View.GONE);
			break;
		case MenuItem.SHOW_AS_ACTION_IF_ROOM:
			break;
		case MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW:
			break;
		}
	}

	@Override
	public MenuItem setShowAsActionFlags(int actionEnum) {
		return null;
	}

	@Override
	public MenuItem setActionView(View view) {
		actionView = view;
		return this;
	}

	@Override
	public MenuItem setActionView(int resId) {
		return null;
	}

	@Override
	public View getActionView() {
		return actionView;
	}

	@Override
	public boolean expandActionView() {
		return false;
	}

	@Override
	public boolean collapseActionView() {
		return false;
	}

	@Override
	public boolean isActionViewExpanded() {
		return false;
	}

	@Override
	public MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
		return null;
	}
}


text:
#ifndef NATIVE_CLIENT_SRC_UNTRUSTED_NACL_NACL_STARTUP_H_
#define NATIVE_CLIENT_SRC_UNTRUSTED_NACL_NACL_STARTUP_H_ 1

#ifdef __cplusplus
extern "C" {
#endif

/*
 * The true entry point for untrusted code is called with the normal C ABI,
 * taking one argument.  This is a pointer to stack space containing these
 * words:
 *      [0]             cleanup function pointer (always NULL in actual startup)
 *      [1]             envc, count of envp[] pointers
 *      [2]             argc, count of argv[] pointers
 *      [3]             argv[0..argc] pointers, argv[argc] being NULL
 *      [3+argc]        envp[0..envc] pointers, envp[envc] being NULL
 *      [3+argc+envc]   auxv[] pairs
 */

enum NaClStartupInfoIndex {
  NACL_STARTUP_FINI,  /* Cleanup function pointer for dynamic linking.  */
  NACL_STARTUP_ENVC,  /* Count of envp[] pointers.  */
  NACL_STARTUP_ARGC,  /* Count of argv[] pointers.  */
  NACL_STARTUP_ARGV   /* argv[0] pointer.  */
};

/*
 * Return the dynamic linker finalizer function.
 */
static inline __attribute__((unused))
void (*nacl_startup_fini(const uint32_t info[]))(void) {
  return (void (*)(void)) info[NACL_STARTUP_FINI];
}

/*
 * Return the count of argument strings.
 */
static inline __attribute__((unused))
int nacl_startup_argc(const uint32_t info[]) {
  return info[NACL_STARTUP_ARGC];
}

/*
 * Return the vector of argument strings.
 */
static inline __attribute__((unused))
char **nacl_startup_argv(const uint32_t info[]) {
  return (char **) &info[NACL_STARTUP_ARGV];
}

/*
 * Return the count of environment strings.
 */
static inline __attribute__((unused))
int nacl_startup_envc(const uint32_t info[]) {
  return info[NACL_STARTUP_ENVC];
}

/*
 * Return the vector of environment strings.
 */
static inline __attribute__((unused))
char **nacl_startup_envp(const uint32_t info[]) {
  return &nacl_startup_argv(info)[nacl_startup_argc(info) + 1];
}

/*
 * Return the vector of auxiliary data items.
 */
static inline __attribute__((unused))
Elf32_auxv_t *nacl_startup_auxv(const uint32_t info[]) {
  char **envend = &nacl_startup_envp(info)[nacl_startup_envc(info) + 1];
  return (Elf32_auxv_t *) envend;
}

/*
 * The main entry point.
 */
extern void _start(uint32_t info[]);

#ifdef __cplusplus
}
#endif

#endif  /* NATIVE_CLIENT_SRC_UNTRUSTED_NACL_NACL_STARTUP_H_ */


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<ILConfig>
  <AASettings>
    <minSampleRate>0</minSampleRate>
    <maxSampleRate>2</maxSampleRate>
    <contrast>0.1</contrast>
    <diagnose>false</diagnose>
    <clamp>false</clamp>
    <samplingMode>Adaptive</samplingMode>
    <filter>Gauss</filter>
    <filterSize>
      <x>2.2</x>
      <y>2.2</y>
    </filterSize>
  </AASettings>
  <RenderSettings>
    <bias>0.005</bias>
    <giTransparencyDepth>2</giTransparencyDepth>
    <ignoreLightLinks>false</ignoreLightLinks>
    <maxRayDepth>6</maxRayDepth>
    <maxShadowRays>10000</maxShadowRays>
    <minShadowRays>0</minShadowRays>
    <reflectionDepth>2</reflectionDepth>
    <reflectionThreshold>0.001</reflectionThreshold>
    <shadowDepth>2</shadowDepth>
    <shadowsIgnoreLightLinks>false</shadowsIgnoreLightLinks>
    <transparencyDepth>50</transparencyDepth>
    <tsIntersectionNormalization>true</tsIntersectionNormalization>
    <tsIntersectionOrthogonalization>true</tsIntersectionOrthogonalization>
    <tsOddUVFlipping>true</tsOddUVFlipping>
    <tsVertexNormalization>true</tsVertexNormalization>
    <tsVertexOrthogonalization>true</tsVertexOrthogonalization>
    <vertexMergeThreshold>0.001</vertexMergeThreshold>
  </RenderSettings>
  <EnvironmentSettings>
    <giEnvironment>None</giEnvironment>
    <skyLightColor>
      <r>0.86</r>
      <g>0.93</g>
      1
      1
    </skyLightColor>
    <giEnvironmentIntensity>0.2</giEnvironmentIntensity>
    <iblImageFile />
    <iblBandingVsNoise>1</iblBandingVsNoise>
    <iblEmitDiffuse>true</iblEmitDiffuse>
    <iblEmitLight>false</iblEmitLight>
    <iblEmitSpecular>false</iblEmitSpecular>
    <iblGIEnvBlur>0.05</iblGIEnvBlur>
    <iblIntensity>1</iblIntensity>
    <iblSamples>300</iblSamples>
    <iblShadows>true</iblShadows>
    <iblSpecularBoost>1</iblSpecularBoost>
    <iblSwapYZ>false</iblSwapYZ>
    <iblTurnDome>0</iblTurnDome>
  </EnvironmentSettings>
  <FrameSettings>
    <autoThreads>true</autoThreads>
    <autoThreadsSubtract>0</autoThreadsSubtract>
    <renderThreads>2</renderThreads>
    <dither>true</dither>
    <inputGamma>1</inputGamma>
    <outputCorrection>
      <colorCorrection>None</colorCorrection>
      <gamma>1</gamma>
    </outputCorrection>
    <premultiply>true</premultiply>
    <premultiplyThreshold>0</premultiplyThreshold>
    <outputVerbosity>
      <errorPrint>true</errorPrint>
      <warningPrint>true</warningPrint>
      <benchmarkPrint>false</benchmarkPrint>
      <progressPrint>true</progressPrint>
      <infoPrint>false</infoPrint>
      <verbosePrint>false</verbosePrint>
      <debugPrint>false</debugPrint>
      <debugFile>false</debugFile>
    </outputVerbosity>
  </FrameSettings>
  <GISettings>
    <clampMaterials>None</clampMaterials>
    <diffuseBoost>1</diffuseBoost>
    <emissiveScale>1</emissiveScale>
    <enableCaustics>false</enableCaustics>
    <enableGI>true</enableGI>
    <ignoreNonDiffuse>true</ignoreNonDiffuse>
    <prepassMaxSampleRate>0</prepassMaxSampleRate>
    <prepassMinSampleRate>-4</prepassMinSampleRate>
    <primaryIntegrator>FinalGather</primaryIntegrator>
    <primaryIntensity>1</primaryIntensity>
    <primarySaturation>1</primarySaturation>
    <secondaryIntegrator>None</secondaryIntegrator>
    <secondaryIntensity>1</secondaryIntensity>
    <secondarySaturation>1</secondarySaturation>
    <specularScale>1</specularScale>
    <fgAOContrast>1</fgAOContrast>
    <fgAOInfluence>0</fgAOInfluence>
    <fgAOMaxDistance>0.3</fgAOMaxDistance>
    <fgAOScale>2</fgAOScale>
    <fgAOVisualize>false</fgAOVisualize>
    <fgAttenuationStart>0</fgAttenuationStart>
    <fgAttenuationStop>0</fgAttenuationStop>
    <fgCacheDirectLight>false</fgCacheDirectLight>
    <fgCheckVisibility>true</fgCheckVisibility>
    <fgCheckVisibilityDepth>1</fgCheckVisibilityDepth>
    <fgClampRadiance>false</fgClampRadiance>
    <fgContrastThreshold>0.05</fgContrastThreshold>
    <fgDepth>1</fgDepth>
    <fgEstimatePoints>15</fgEstimatePoints>
    <fgExploitFrameCoherence>false</fgExploitFrameCoherence>
    <fgFalloffExponent>0</fgFalloffExponent>
    <fgGradientThreshold>0.5</fgGradientThreshold>
    <fgInterpolationPoints>15</fgInterpolationPoints>
    <fgLightLeakRadius>0</fgLightLeakRadius>
    <fgLightLeakReduction>false</fgLightLeakReduction>
    <fgMaxRayLength>0</fgMaxRayLength>
    <fgNormalThreshold>0.2</fgNormalThreshold>
    <fgPreview>false</fgPreview>
    <fgRays>1000</fgRays>
    <fgUseCache>Irradiance</fgUseCache>
    <ptAccuracy>1</ptAccuracy>
    <ptCacheDirectLight>false</ptCacheDirectLight>
    <ptCheckVisibility>true</ptCheckVisibility>
    <ptConservativeEnergyLimit>0.95</ptConservativeEnergyLimit>
    <ptDefaultColor>
      <r>0</r>
      <g>0</g>
      0
      1
    </ptDefaultColor>
    <ptDepth>5</ptDepth>
    <ptDiffuseIllum>true</ptDiffuseIllum>
    <ptFile />
    <ptFilterSize>3</ptFilterSize>
    <ptFilterType>Gauss</ptFilterType>
    <ptNormalThreshold>0.7</ptNormalThreshold>
    <ptPointSize>0</ptPointSize>
    <ptPrecalcIrradiance>true</ptPrecalcIrradiance>
    <ptPreview>false</ptPreview>
    <ptSpecularIllum>true</ptSpecularIllum>
    <ptTransmissiveIllum>true</ptTransmissiveIllum>
    <mcDepth>2</mcDepth>
    <mcMaxRayLength>0</mcMaxRayLength>
    <mcRays>16</mcRays>
  </GISettings>
  <SurfaceTransferSettings>
    <frontRange>0</frontRange>
    <frontBias>0</frontBias>
    <backRange>2</backRange>
    <backBias>-1</backBias>
    <selectionMode>Normal</selectionMode>
  </SurfaceTransferSettings>
  <TextureBakeSettings>
    <bgColor>
      <r>1</r>
      <g>1</g>
      1
      1
    </bgColor>
    <bilinearFilter>true</bilinearFilter>
    <conservativeRasterization>true</conservativeRasterization>
    <edgeDilation>3</edgeDilation>
  </TextureBakeSettings>
</ILConfig>


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Component\Webspace\Tests\Functional\Analyzer;

use PHPUnit_Framework_MockObject_MockObject;
use Prophecy\Argument;
use Sulu\Component\Content\Mapper\ContentMapperInterface;
use Sulu\Component\Localization\Localization;
use Sulu\Component\Webspace\Analyzer\Attributes\RequestAttributes;
use Sulu\Component\Webspace\Analyzer\Attributes\WebsiteRequestProcessor;
use Sulu\Component\Webspace\Analyzer\RequestAnalyzer;
use Sulu\Component\Webspace\Analyzer\RequestAnalyzerInterface;
use Sulu\Component\Webspace\Manager\WebspaceManagerInterface;
use Sulu\Component\Webspace\Portal;
use Sulu\Component\Webspace\PortalInformation;
use Sulu\Component\Webspace\Url\ReplacerInterface;
use Sulu\Component\Webspace\Webspace;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\RequestStack;

class RequestAnalyzerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var RequestAnalyzer
     */
    private $requestAnalyzer;

    /**
     * @var PHPUnit_Framework_MockObject_MockObject
     */
    private $webspaceManager;

    /**
     * @var ContentMapperInterface
     */
    private $contentMapper;

    /**
     * @var ReplacerInterface
     */
    private $replacer;

    /**
     * @var RequestStack
     */
    private $requestStack;

    public function setUp()
    {
        $this->webspaceManager = $this->prophesize(WebspaceManagerInterface::class);
        $this->contentMapper = $this->prophesize(ContentMapperInterface::class);
        $this->requestStack = $this->prophesize(RequestStack::class);
        $this->replacer = $this->prophesize(ReplacerInterface::class);

        $this->requestAnalyzer = new RequestAnalyzer(
            $this->requestStack->reveal(),
            [
                new WebsiteRequestProcessor(
                    $this->webspaceManager->reveal(), $this->contentMapper->reveal(), $this->replacer->reveal(), 'prod'
                ),
            ]
        );
    }

    /**
     * @param $portalInformation
     */
    protected function prepareWebspaceManager($portalInformation)
    {
        $this->webspaceManager->findPortalInformationsByUrl(Argument::any(), Argument::any())
            ->willReturn([$portalInformation]);
        $this->webspaceManager->getPortalInformations(Argument::any())->willReturn([]);
    }

    public function provideAnalyze()
    {
        return [
            [
                [
                    'portal_url' => 'sulu.lo/test',
                    'path_info' => '/test/path/to',
                    'match_type' => RequestAnalyzerInterface::MATCH_TYPE_FULL,
                    'redirect' => '',
                ],
                [
                    'redirect' => null,
                    'resource_locator_prefix' => '/test',
                    'resource_locator' => '/path/to',
                    'portal_url' => 'sulu.lo/test',
                ],
            ],
            [
                [
                    'portal_url' => 'sulu.lo',
                    'path_info' => '/test/path/to',
                    'match_type' => RequestAnalyzerInterface::MATCH_TYPE_PARTIAL,
                    'redirect' => 'sulu.lo/test',
                ],
                [
                    'redirect' => 'sulu.lo/test',
                    'resource_locator_prefix' => '',
                    'resource_locator' => '/test/path/to',
                    'portal_url' => 'sulu.lo',
                ],
            ],
        ];
    }

    public function provideAnalyzeWithFormat()
    {
        return [
            [
                [
                    'portal_url' => 'sulu.lo/test',
                    'path_info' => '/test/path/to.html',
                    'match_type' => RequestAnalyzerInterface::MATCH_TYPE_FULL,
                    'redirect' => '',
                ],
                [
                    'redirect' => null,
                    'resource_locator_prefix' => '/test',
                    'resource_locator' => '/path/to',
                    'portal_url' => 'sulu.lo/test',
                    'format' => 'html',
                ],
            ],
            [
                [
                    'portal_url' => 'sulu.lo',
                    'path_info' => '/test/path/to.rss',
                    'match_type' => RequestAnalyzerInterface::MATCH_TYPE_PARTIAL,
                    'redirect' => 'sulu.lo/test',
                ],
                [
                    'redirect' => 'sulu.lo/test',
                    'resource_locator_prefix' => '',
                    'resource_locator' => '/test/path/to',
                    'portal_url' => 'sulu.lo',
                    'format' => 'rss',
                ],
            ],
            [
                [
                    'portal_url' => 'sulu.lo/test',
                    'path_info' => '/test/path/to',
                    'match_type' => RequestAnalyzerInterface::MATCH_TYPE_FULL,
                    'redirect' => '',
                ],
                [
                    'redirect' => null,
                    'resource_locator_prefix' => '/test',
                    'resource_locator' => '/path/to',
                    'portal_url' => 'sulu.lo/test',
                    'format' => null,
                ],
            ],
            [
                [
                    'portal_url' => 'sulu.lo/test',
                    'path_info' => '/test/path/to/test.min.css',
                    'match_type' => RequestAnalyzerInterface::MATCH_TYPE_FULL,
                    'redirect' => '',
                ],
                [
                    'redirect' => null,
                    'resource_locator_prefix' => '/test',
                    'resource_locator' => '/path/to/test',
                    'portal_url' => 'sulu.lo/test',
                    'format' => 'css',
                ],
            ],
        ];
    }

    /**
     * @dataProvider provideAnalyze
     */
    public function testAnalyze($config, $expected = [])
    {
        $webspace = new Webspace();
        $webspace->setKey('sulu');

        $portal = new Portal();
        $portal->setKey('sulu');

        $localization = new Localization();
        $localization->setCountry('at');
        $localization->setLanguage('de');

        $portalInformation = new PortalInformation(
            $config['match_type'],
            $webspace,
            $portal,
            $localization,
            $config['portal_url'],
            null,
            $config['redirect']
        );

        $this->prepareWebspaceManager($portalInformation);

        $requestBag = $this->prophesize(ParameterBag::class);
        $requestBag->all()->willReturn(['post' => 1]);
        $queryBag = $this->prophesize(ParameterBag::class);
        $queryBag->all()->willReturn(['get' => 1]);
        $attributesBag = $this->prophesize(ParameterBag::class);
        $attributesBag->get('_sulu')->willReturn(null);
        $attributesBag->has('_sulu')->willReturn(true);
        $attributesBag->set('_sulu', Argument::type(RequestAttributes::class))->shouldBeCalledTimes(1)->will(
            function ($arguments) use ($attributesBag) {
                $attributesBag->get('_sulu')->willReturn($arguments[1]);
            }
        );

        $request = $this->getMock('\Symfony\Component\HttpFoundation\Request');
        $request->request = $requestBag->reveal();
        $request->query = $queryBag->reveal();
        $request->attributes = $attributesBag->reveal();

        $request->expects($this->any())->method('getHost')->will($this->returnValue('sulu.lo'));
        $request->expects($this->any())->method('getPathInfo')->will($this->returnValue($config['path_info']));
        $request->expects($this->any())->method('getScheme')->willReturn('http');
        $request->expects($this->once())->method('setLocale')->with('de_at');
        $this->requestStack->getCurrentRequest()->willReturn($request);

        $this->requestAnalyzer->analyze($request);

        $this->assertEquals('de_at', $this->requestAnalyzer->getCurrentLocalization()->getLocalization());
        $this->assertEquals('sulu', $this->requestAnalyzer->getWebspace()->getKey());
        $this->assertEquals('sulu', $this->requestAnalyzer->getPortal()->getKey());
        $this->assertEquals(null, $this->requestAnalyzer->getSegment());
        $this->assertEquals($expected['portal_url'], $this->requestAnalyzer->getPortalUrl());
        $this->assertEquals($expected['redirect'], $this->requestAnalyzer->getRedirect());
        $this->assertEquals($expected['resource_locator'], $this->requestAnalyzer->getResourceLocator());
        $this->assertEquals($expected['resource_locator_prefix'], $this->requestAnalyzer->getResourceLocatorPrefix());
        $this->assertEquals(['post' => 1], $this->requestAnalyzer->getPostParameters());
        $this->assertEquals(['get' => 1], $this->requestAnalyzer->getGetParameters());
    }

    /**
     * @dataProvider provideAnalyzeWithFormat
     */
    public function testAnalyzeWithFormat($config, $expected = [])
    {
        $webspace = new Webspace();
        $webspace->setKey('sulu');

        $portal = new Portal();
        $portal->setKey('sulu');

        $localization = new Localization();
        $localization->setCountry('at');
        $localization->setLanguage('de');

        $portalInformation = new PortalInformation(
            $config['match_type'],
            $webspace,
            $portal,
            $localization,
            $config['portal_url'],
            null,
            $config['redirect']
        );

        $this->prepareWebspaceManager($portalInformation);

        $requestFormat = false;

        $requestBag = $this->prophesize(ParameterBag::class);
        $requestBag->all()->willReturn(['post' => 1]);
        $queryBag = $this->prophesize(ParameterBag::class);
        $queryBag->all()->willReturn(['get' => 1]);
        $attributesBag = $this->prophesize(ParameterBag::class);
        $attributesBag->has('_sulu')->willReturn(true);
        $attributesBag->get('_sulu')->willReturn(null);
        $attributesBag->set('_sulu', Argument::type(RequestAttributes::class))->shouldBeCalledTimes(1)->will(
            function ($arguments) use ($attributesBag) {
                $attributesBag->get('_sulu')->willReturn($arguments[1]);
            }
        );

        $request = $this->getMock('\Symfony\Component\HttpFoundation\Request');
        $request->request = $requestBag->reveal();
        $request->query = $queryBag->reveal();
        $request->attributes = $attributesBag->reveal();
        $request->expects($this->any())->method('getHost')->will($this->returnValue('sulu.lo'));
        $request->expects($this->any())->method('getPathInfo')->will($this->returnValue($config['path_info']));
        $request->expects($this->once())->method('setLocale')->with('de_at');
        $request->expects($this->any())->method('getScheme')->willReturn('http');

        if ($expected['format']) {
            $request->expects($this->once())->method('setRequestFormat')->will(
                $this->returnCallback(
                    function ($format) use (&$requestFormat) {
                        $requestFormat = $format;
                    }
                )
            );
        }

        $request->expects($this->once())->method('getRequestFormat')->will(
            $this->returnCallback(
                function () use (&$requestFormat) {
                    return $requestFormat;
                }
            )
        );

        $this->requestStack->getCurrentRequest()->willReturn($request);
        $this->requestAnalyzer->analyze($request);

        $this->assertEquals('de_at', $this->requestAnalyzer->getCurrentLocalization()->getLocalization());
        $this->assertEquals('sulu', $this->requestAnalyzer->getWebspace()->getKey());
        $this->assertEquals('sulu', $this->requestAnalyzer->getPortal()->getKey());
        $this->assertEquals(null, $this->requestAnalyzer->getSegment());
        $this->assertEquals($expected['portal_url'], $this->requestAnalyzer->getPortalUrl());
        $this->assertEquals($expected['redirect'], $this->requestAnalyzer->getRedirect());
        $this->assertEquals($expected['resource_locator'], $this->requestAnalyzer->getResourceLocator());
        $this->assertEquals(
            $expected['resource_locator_prefix'],
            $this->requestAnalyzer->getResourceLocatorPrefix()
        );
        $this->assertEquals($expected['format'], $request->getRequestFormat());
        $this->assertEquals(['post' => 1], $this->requestAnalyzer->getPostParameters());
        $this->assertEquals(['get' => 1], $this->requestAnalyzer->getGetParameters());
    }

    /**
     * @expectedException \Sulu\Component\Webspace\Analyzer\Exception\UrlMatchNotFoundException
     */
    public function testAnalyzeNotExisting()
    {
        $this->webspaceManager->findPortalInformationsByUrl(Argument::any(), Argument::any())->willReturn(null);
        $this->webspaceManager->getPortalInformations(Argument::any())->willReturn([]);

        $request = $this->getMock('\Symfony\Component\HttpFoundation\Request');
        $request->request = new ParameterBag(['post' => 1]);
        $request->query = new ParameterBag(['get' => 1]);
        $request->attributes = new ParameterBag();

        $this->requestAnalyzer->analyze($request);
        $this->requestAnalyzer->validate($request);
    }

    /**
     * @dataProvider provideAnalyze
     */
    public function testAnalyzeCurrentRequest($config, $expected = [])
    {
        $webspace = new Webspace();
        $webspace->setKey('sulu');

        $portal = new Portal();
        $portal->setKey('sulu');

        $localization = new Localization();
        $localization->setCountry('at');
        $localization->setLanguage('de');

        $portalInformation = new PortalInformation(
            $config['match_type'],
            $webspace,
            $portal,
            $localization,
            $config['portal_url'],
            null,
            $config['redirect']
        );

        $this->prepareWebspaceManager($portalInformation);

        $request = $this->getMock('\Symfony\Component\HttpFoundation\Request');
        $request->request = new ParameterBag(['post' => 1]);
        $request->query = new ParameterBag(['get' => 1]);
        $request->attributes = new ParameterBag();
        $request->expects($this->any())->method('getHost')->will($this->returnValue('sulu.lo'));
        $request->expects($this->any())->method('getPathInfo')->will($this->returnValue($config['path_info']));
        $request->expects($this->any())->method('getScheme')->willReturn('http');
        $request->expects($this->once())->method('setLocale')->with('de_at');

        // this request will be analyzed only once
        $this->requestStack->getCurrentRequest()->willReturn($request)->shouldBeCalled();

        $this->requestAnalyzer->analyze($request);
        $this->requestAnalyzer->validate($request);

        $this->assertEquals('de_at', $this->requestAnalyzer->getCurrentLocalization()->getLocalization());
        $this->assertEquals('sulu', $this->requestAnalyzer->getWebspace()->getKey());
        $this->assertEquals('sulu', $this->requestAnalyzer->getPortal()->getKey());
        $this->assertEquals(null, $this->requestAnalyzer->getSegment());
        $this->assertEquals($expected['portal_url'], $this->requestAnalyzer->getPortalUrl());
        $this->assertEquals($expected['redirect'], $this->requestAnalyzer->getRedirect());
        $this->assertEquals($expected['resource_locator'], $this->requestAnalyzer->getResourceLocator());
        $this->assertEquals($expected['resource_locator_prefix'], $this->requestAnalyzer->getResourceLocatorPrefix());
        $this->assertEquals(['post' => 1], $this->requestAnalyzer->getPostParameters());
        $this->assertEquals(['get' => 1], $this->requestAnalyzer->getGetParameters());
    }

    public function testAnalyzeNoCurrentRequest()
    {
        $this->requestStack->getCurrentRequest()->willReturn(null);

        $this->assertNull($this->requestAnalyzer->getAttribute('test'));
    }
}


text:
using System.Linq;
using Xunit;
using Xunit.Extensions;

namespace AutoFixture.Xunit.UnitTest
{
    public class DependencyConstraints
    {
        [Theory]
        [InlineData("Moq")]
        [InlineData("Rhino.Mocks")]
        public void AutoFixtureXunitDoesNotReference(string assemblyName)
        {
            // Arrange
            // Act
            var references = typeof(AutoDataAttribute).Assembly.GetReferencedAssemblies();
            // Assert
            Assert.False(references.Any(an => an.Name == assemblyName));
        }

        [Theory]
        [InlineData("Moq")]
        [InlineData("Rhino.Mocks")]
        public void AutoFixtureXunitUnitTestsDoNotReference(string assemblyName)
        {
            // Arrange
            // Act
            var references = this.GetType().Assembly.GetReferencedAssemblies();
            // Assert
            Assert.False(references.Any(an => an.Name == assemblyName));
        }
    }
}


text:
set(OGRE_DEPENDENCIES_DIR "" CACHE PATH "Path to prebuilt OGRE dependencies")
include(FindPkgMacros)
getenv_path(OGRE_DEPENDENCIES_DIR)
if(OGRE_BUILD_PLATFORM_IPHONE)
  set(OGRE_DEP_SEARCH_PATH
    ${OGRE_DEPENDENCIES_DIR}
    ${ENV_OGRE_DEPENDENCIES_DIR}
    "${OGRE_BINARY_DIR}/iPhoneDependencies"
    "${OGRE_SOURCE_DIR}/iPhoneDependencies"
    "${OGRE_BINARY_DIR}/../iPhoneDependencies"
    "${OGRE_SOURCE_DIR}/../iPhoneDependencies"
  )
else()
  set(OGRE_DEP_SEARCH_PATH
    ${OGRE_DEPENDENCIES_DIR}
    ${ENV_OGRE_DEPENDENCIES_DIR}
    "${OGRE_BINARY_DIR}/Dependencies"
    "${OGRE_SOURCE_DIR}/Dependencies"
    "${OGRE_BINARY_DIR}/../Dependencies"
    "${OGRE_SOURCE_DIR}/../Dependencies"
  )
endif()

message(STATUS "Search path: ${OGRE_DEP_SEARCH_PATH}")

# Set hardcoded path guesses for various platforms
if (UNIX)
  set(OGRE_DEP_SEARCH_PATH ${OGRE_DEP_SEARCH_PATH} /usr/local)
endif ()

# give guesses as hints to the find_package calls
set(CMAKE_PREFIX_PATH ${OGRE_DEP_SEARCH_PATH} ${CMAKE_PREFIX_PATH})
set(CMAKE_FRAMEWORK_PATH ${OGRE_DEP_SEARCH_PATH} ${CMAKE_FRAMEWORK_PATH})

#######################################################################
# Core dependencies
#######################################################################

# Find zlib
find_package(ZLIB)
macro_log_feature(ZLIB_FOUND "zlib" "Simple data compression library" "http://www.zlib.net" FALSE "" "")

if (ZLIB_FOUND)
  # Find zziplib
  find_package(ZZip)
  macro_log_feature(ZZip_FOUND "zziplib" "Extract data from zip archives" "http://zziplib.sourceforge.net" FALSE "" "")
endif ()

# Find FreeImage
find_package(FreeImage)
macro_log_feature(FreeImage_FOUND "freeimage" "Support for commonly used graphics image formats" "http://freeimage.sourceforge.net" FALSE "" "")

# Find FreeType
find_package(Freetype)
macro_log_feature(FREETYPE_FOUND "freetype" "Portable font engine" "http://www.freetype.org" TRUE "" "")

# Find X11
if (UNIX)
	find_package(X11)
	macro_log_feature(X11_FOUND "X11" "X Window system" "http://www.x.org" TRUE "" "")
	macro_log_feature(X11_Xt_FOUND "Xt" "X Toolkit" "http://www.x.org" TRUE "" "")
	find_library(XAW_LIBRARY NAMES Xaw Xaw7 PATHS ${DEP_LIB_SEARCH_DIR} ${X11_LIB_SEARCH_PATH})
	macro_log_feature(XAW_LIBRARY "Xaw" "X11 Athena widget set" "http://www.x.org" TRUE "" "")
  mark_as_advanced(XAW_LIBRARY)
endif ()

#######################################################################
# RenderSystem dependencies
#######################################################################

# Find OpenGL
find_package(OpenGL)
macro_log_feature(OPENGL_FOUND "OpenGL" "Support for the OpenGL render system" "http://www.opengl.org/" FALSE "" "")

# Find OpenGL ES
find_package(OpenGLES)
macro_log_feature(OPENGLES_FOUND "OpenGL ES 1.x" "Support for the OpenGL ES 1.x render system" "http://www.khronos.org/opengles/" FALSE "" "")

# Find OpenGL ES 2.x
find_package(OpenGLES2)
macro_log_feature(OPENGLES2_FOUND "OpenGL ES 2.x" "Support for the OpenGL ES 2.x render system" "http://www.khronos.org/opengles/" FALSE "" "")

# Find DirectX
if(WIN32)
	find_package(DirectX)
	macro_log_feature(DirectX_FOUND "DirectX" "Support for the DirectX render system" "http://msdn.microsoft.com/en-us/directx/" FALSE "" "")
endif()

#######################################################################
# Additional features
#######################################################################

# Find Cg
if (NOT OGRE_BUILD_PLATFORM_IPHONE)
  find_package(Cg)
  macro_log_feature(Cg_FOUND "cg" "C for graphics shader language" "http://developer.nvidia.com/object/cg_toolkit.html" FALSE "" "")
endif (NOT OGRE_BUILD_PLATFORM_IPHONE)

# Find Boost
# Prefer static linking in all cases
if (WIN32 OR APPLE)
	set(Boost_USE_STATIC_LIBS TRUE)
else ()
	# Statically linking boost to a dynamic Ogre build doesn't work on Linux 64bit
	set(Boost_USE_STATIC_LIBS ${OGRE_STATIC})
endif ()
if (APPLE)
	if(OGRE_BUILD_PLATFORM_IPHONE)
		set(Boost_COMPILER "-xgcc42")
	else()
	    # Boost tries to detect the gcc compiler version by calling the command-line
	    # However we build with gcc 4.0 for OS X 10.4 compatibility, command-line default might be different
		set(Boost_COMPILER "-xgcc40")
	endif()
endif()
set(Boost_ADDITIONAL_VERSIONS "1.42" "1.42.0" "1.41.0" "1.41" "1.40.0" "1.40" "1.39.0" "1.39" "1.38.0" "1.38" "1.37.0" "1.37" )
# Components that need linking (NB does not include header-only components like bind)
set(OGRE_BOOST_COMPONENTS thread date_time)
find_package(Boost COMPONENTS ${OGRE_BOOST_COMPONENTS} QUIET)
if (NOT Boost_FOUND)
	# Try again with the other type of libs
	if(Boost_USE_STATIC_LIBS)
		set(Boost_USE_STATIC_LIBS)
	else()
		set(Boost_USE_STATIC_LIBS ON)
	endif()
	find_package(Boost COMPONENTS ${OGRE_BOOST_COMPONENTS} QUIET)
endif()
find_package(Boost QUIET)
# Optional Boost libs (Boost_${COMPONENT}_FOUND
macro_log_feature(Boost_FOUND "boost" "Boost (general)" "http://boost.org" FALSE "" "")
macro_log_feature(Boost_THREAD_FOUND "boost-thread" "Used for threading support" "http://boost.org" FALSE "" "")
macro_log_feature(Boost_DATE_TIME_FOUND "boost-date_time" "Used for threading support" "http://boost.org" FALSE "" "")

# POCO
find_package(POCO)
macro_log_feature(POCO_FOUND "POCO" "POCO framework" "http://pocoproject.org/" FALSE "" "")

# ThreadingBuildingBlocks
find_package(TBB)
macro_log_feature(TBB_FOUND "tbb" "Threading Building Blocks" "http://www.threadingbuildingblocks.org/" FALSE "" "")

#######################################################################
# Samples dependencies
#######################################################################

# Find OIS
find_package(OIS)
macro_log_feature(OIS_FOUND "OIS" "Input library needed for the samples" "http://sourceforge.net/projects/wgois" FALSE "" "")

#######################################################################
# Tools
#######################################################################

find_package(Doxygen)
macro_log_feature(DOXYGEN_FOUND "Doxygen" "Tool for building API documentation" "http://doxygen.org" FALSE "" "")

#######################################################################
# Tests
#######################################################################

find_package(CppUnit)
macro_log_feature(CppUnit_FOUND "CppUnit" "Library for performing unit tests" "http://cppunit.sourceforge.net" FALSE "" "")

#######################################################################
# Apple-specific
#######################################################################
if (APPLE)
  if (OGRE_BUILD_PLATFORM_IPHONE)
    find_package(iPhoneSDK)
    macro_log_feature(iPhoneSDK_FOUND "iPhone SDK" "iPhone SDK" "http://developer.apple.com/iphone" FALSE "" "")
  else()
    find_package(Carbon)
    macro_log_feature(Carbon_FOUND "Carbon" "Carbon" "http://developer.apple.com/mac" TRUE "" "")

    find_package(Cocoa)
    macro_log_feature(Cocoa_FOUND "Cocoa" "Cocoa" "http://developer.apple.com/mac" TRUE "" "")

    find_package(IOKit)
    macro_log_feature(IOKit_FOUND "IOKit" "IOKit HID framework needed by the samples" "http://developer.apple.com/mac" FALSE "" "")
  endif (OGRE_BUILD_PLATFORM_IPHONE)
endif(APPLE)

# Display results, terminate if anything required is missing
MACRO_DISPLAY_FEATURE_LOG()

# Add library and include paths from the dependencies
include_directories(
  ${ZLIB_INCLUDE_DIRS}
  ${ZZip_INCLUDE_DIRS}
  ${FreeImage_INCLUDE_DIRS}
  ${FREETYPE_INCLUDE_DIRS}
  ${OPENGL_INCLUDE_DIRS}
  ${OPENGLES_INCLUDE_DIRS}
  ${OPENGLES2_INCLUDE_DIRS}
  ${OIS_INCLUDE_DIRS}
  ${Cg_INCLUDE_DIRS}
  ${X11_INCLUDE_DIR}
  ${DirectX_INCLUDE_DIRS}
  ${CppUnit_INCLUDE_DIRS}
  ${Carbon_INCLUDE_DIRS}
  ${Cocoa_INCLUDE_DIRS}
)

link_directories(
  ${OPENGL_LIBRARY_DIRS}
  ${OPENGLES_LIBRARY_DIRS}
  ${OPENGLES2_LIBRARY_DIRS}
  ${Cg_LIBRARY_DIRS}
  ${X11_LIBRARY_DIRS}
  ${DirectX_LIBRARY_DIRS}
  ${CppUnit_LIBRARY_DIRS}
)

if (Boost_FOUND)
  include_directories(${Boost_INCLUDE_DIRS})
  link_directories(${Boost_LIBRARY_DIRS})
endif ()

# provide option to install dependencies on Windows
include(InstallDependencies)


text:
<?php

namespace app\modules\setting\Models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\setting\Models\DbCrPaymentmethod;

/**
 * DbCrPaymentmethodSearch represents the model behind the search form about `app\modules\setting\Models\DbCrPaymentmethod`.
 */
class DbCrPaymentmethodSearch extends DbCrPaymentmethod
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['paymentid', 'paymenttype', 'receipttype', 'usepreprintedstationery', 'opencashdrawer'], 'integer'],
            [['paymentname'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = DbCrPaymentmethod::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'paymentid' => $this->paymentid,
            'paymenttype' => $this->paymenttype,
            'receipttype' => $this->receipttype,
            'usepreprintedstationery' => $this->usepreprintedstationery,
            'opencashdrawer' => $this->opencashdrawer,
        ]);

        $query->andFilterWhere(['like', 'paymentname', $this->paymentname]);

        return $dataProvider;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/jolopay_btn_green_press" />
    <item android:state_pressed="false" android:drawable="@drawable/jolopay_btn_green_normal" />
</selector>


text:
import pytest

from pg_grant import NoSuchObjectError
from pg_grant.query import get_all_sequence_acls, get_sequence_acl

expected_acls = {
    'public': {
        # seq1 has default privileges, so None is returned.
        'seq1': None,
        # alice is owner, bob was granted all
        'seq2': ['alice=rwU/alice', 'bob=rwU/alice'],
    },
    'schema1': {
        'seq3': None,
    }
}

@pytest.mark.parametrize('name, acls', expected_acls['public'].items())
def test_get_sequence_acl_visible(connection, name, acls):
    """Find visible (i.e. in search path) sequences matching ``name``."""
    sequence = get_sequence_acl(connection, name)
    assert sequence.acl == acls

@pytest.mark.parametrize('schema, name, acls', [
    (schema, seq, acl)
    for schema, d in expected_acls.items()
    for seq, acl in d.items()
])
def test_get_sequence_acl_schema(connection, schema, name, acls):
    """Find sequences  from ``schema`` matching ``name``."""
    sequence = get_sequence_acl(connection, name, schema)
    assert sequence.acl == acls

def test_get_all_sequence_acls(connection):
    """Get all sequences in all schemas."""
    sequences = get_all_sequence_acls(connection)
    assert {x.schema for x in sequences} == {'public', 'schema1'}

    tested = 0

    for sequence in sequences:
        if sequence.schema not in expected_acls:
            continue

        if sequence.name not in expected_acls[sequence.schema]:
            continue

        assert sequence.acl == expected_acls[sequence.schema][sequence.name]
        tested += 1

    assert tested == sum(len(v) for v in expected_acls.values())

def test_no_such_object(connection):
    with pytest.raises(NoSuchObjectError):
        get_sequence_acl(connection, 'seq3')


text:
<?xml version="1.0" encoding="UTF-8"?>
<g:element xmlns:g="http://www.esri.com/geoportal/gxe"
           xmlns:h="http://www.esri.com/geoportal/gxe/html"
           g:extends="$base/schema/gco/xtn/Wrapped_CodePropertyType.xml">
  <g:body>
    <g:element g:minOccurs="$parent"
      g:extends="$base/schema/gmd/identification/MD_TopicCategoryCode.xml"/>
  </g:body>
</g:element>


text:
<?php

// No direct access
defined('_HZEXEC_') or die();

$this->css()
     ->js('curation.js');

Toolbar::title(Lang::txt('COM_PUBLICATIONS_PUBLICATION') . ' ' . Lang::txt('COM_PUBLICATIONS_MASTER_TYPE') . ' - ' . $this->row->type . ': ' . Lang::txt('COM_PUBLICATIONS_FIELD_CURATION_ADD_BLOCK'), 'publications');
Toolbar::save('saveblock');
Toolbar::cancel();

$params = new \Hubzero\Config\Registry($this->row->params);
$manifest  = $this->curation->_manifest;
$curParams = $manifest->params;
$blocks    = $manifest->blocks;

$blockSelection = array('active' => array());
$masterBlocks = array();
foreach ($this->blocks as $b)
{
	$masterBlocks[$b->block] = $b;
}
foreach ($blocks as $blockId => $block)
{
	$blockSelection['active'][] = $block->name;
}

?>

<form action="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller); ?>" method="post" id="item-form" name="adminForm">

<a class="button" href="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller . '&task=edit&id=' . $this->row->id); ?>"><?php echo Lang::txt('COM_PUBLICATIONS_MTYPE_BACK') . ' ' . $this->row->type . ' ' . Lang::txt('COM_PUBLICATIONS_MASTER_TYPE'); ?>

	<fieldset class="adminform">
		<legend><?php echo Lang::txt('COM_PUBLICATIONS_FIELD_CURATION_ADD_BLOCK'); ?></legend>

		<input type="hidden" name="id" value="<?php echo $this->row->id; ?>" />
		<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
		<input type="hidden" name="controller" value="<?php echo $this->controller; ?>" />
		<input type="hidden" name="task" value="saveblock" />

			<?php echo Lang::txt('COM_PUBLICATIONS_CURATION_SELECT_BLOCK'); ?>:
			<select name="newblock" id="field-newblock">
			<?php
			foreach ($this->blocks as $sBlock)
			{
				if (!in_array($sBlock->block, $blockSelection['active']) || $sBlock->maximum > 1)
				{
					?>
					<option value="<?php echo $sBlock->block; ?>"><?php echo $sBlock->block; ?></option>
					<?php
				}
			}
			?>
			</select>

			<?php echo Lang::txt('COM_PUBLICATIONS_CURATION_INSERT_BLOCK_BEFORE'); ?>:
			<select name="before" id="field-order">
				<?php foreach ($blocks as $blockId => $block) { ?>
					<option value="<?php echo $blockId; ?>"><?php echo $block->name; ?></option>
				<?php } ?>
			</select>

	</fieldset>

	<?php echo Html::input('token'); ?>
</form>


text:
package sgdi.pr3.grupo03.shared;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ConsoleUtil {
    // --------------------------------------------------------------------------------------
    // Constants:
    // --------------------------------------------------------------------------------------

    public static final int DEFAULT_INT = 0;
    public static final String DEFAULT_STRING = "";
    public static final String DEFAULT_OFFSET = "    ";

    // --------------------------------------------------------------------------------------
    // Basic input:
    // --------------------------------------------------------------------------------------

    public static Object getDefaultValue(Class<?> type) {
        if (type == String.class) {
            return DEFAULT_STRING;
        } else if (type == int.class) {
            return DEFAULT_INT;
        }
        return null;
    }

    public static Object getValue(Class<?> type, Object defaultValue) {
        Scanner scanner = new Scanner(System.in);
        try {
            if (type == String.class) {
                return scanner.nextLine();
            } else if (type == int.class) {
                return scanner.nextInt();
            }
        } catch (Exception ex) {
        }
        return defaultValue;
    }

    public static Object getValue(Class<?> type) {
        return getValue(type, getDefaultValue(type));
    }

    public static int getInt() {
        return (int) getValue(int.class, DEFAULT_INT);
    }

    public static String getString() {
        return (String) getValue(String.class, DEFAULT_STRING);
    }

    public static int getInt(int defaultValue) {
        return (int) getValue(int.class, defaultValue);
    }

    public static String getString(String defaultValue) {
        return (String) getValue(String.class, defaultValue);
    }

    // --------------------------------------------------------------------------------------
    // Build objects:
    // --------------------------------------------------------------------------------------

    public static <T extends Object> T getObject(Class<T> type,
            CustomReferenceFieldInput refFieldInput)
            throws NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        return getObject(type, refFieldInput, "");
    }

    public static <T extends Object> T getObject(Class<T> type,
            CustomReferenceFieldInput refFieldInput, String offset)
            throws NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        if (type == null)
            return null;
        T object = type.getConstructor().newInstance();
        Field[] fields = type.getDeclaredFields();
        int idx = 0, total = fields.length - getIgnoredFields(fields);
        for (Field field : fields) {
            if (!isIgnoreInputField(field)) {
                ++idx;
                field.setAccessible(true);
                System.out.println(offset + "[" + idx + "/" + total + "] "
                        + getOutputText(field));

                Object fvalue = null;
                Class<?> ftype = field.getType();
                ReferenceFieldType rft = getReferenceFieldType(field);
                if (rft != ReferenceFieldType.None) {
                    if (refFieldInput != null) {
                        fvalue = refFieldInput.getReference(rft, offset
                                + DEFAULT_OFFSET);
                        if (fvalue == null) {
                            field.setAccessible(false);
                            if (ftype == List.class) {
                                return null;
                            }
                            return object;
                        }
                    } else {
                        field.setAccessible(false);
                        continue;
                    }
                } else {
                    if (ftype == List.class) {
                        fvalue = getList(
                                ((ParameterizedType) field.getGenericType())
                                        .getActualTypeArguments()[0],
                                refFieldInput, offset + DEFAULT_OFFSET);

                    } else if (ftype.isPrimitive() || ftype == String.class) {
                        System.out.print(offset + "? ");
                        fvalue = getValue(ftype);

                    } else {
                        fvalue = getObject(ftype, refFieldInput, offset
                                + DEFAULT_OFFSET);
                    }
                }

                if (fvalue != null) {
                    field.set(object, fvalue);
                } else if (rft == ReferenceFieldType.None
                        || refFieldInput != null) {
                    System.err.println("Valor nulo en el campo: "
                            + field.getName() + " -> " + ftype.getName());
                }
                field.setAccessible(false);
            }
        }
        return object;
    }

    public static List getList(Type ltype,
            CustomReferenceFieldInput refFieldInput, String offset)
            throws NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        if (ltype == null)
            return null;
        List victims = new ArrayList();

        int listOfWhat;
        final int LPRIMITIVE = 1;
        final int LOBJECT = 2;
        final int LLIST = 3;
        Class<?> ctype = null;
        Type ptype = null;
        if (ltype instanceof Class<?>) {
            ctype = (Class<?>) ltype;
            if (ctype.isPrimitive() || ctype == String.class) {
                listOfWhat = LPRIMITIVE;
            } else {
                listOfWhat = LOBJECT;
            }
        } else {
            ptype = ((ParameterizedType) ltype).getActualTypeArguments()[0];
            listOfWhat = LLIST;
        }

        String input;
        boolean exit;
        int idx = 0;
        if (listOfWhat == LPRIMITIVE) {
            System.out.println(offset
                    + "Añadir elementos a la lista (. para terminar)");
        }
        do {
            if (listOfWhat == LOBJECT || listOfWhat == LLIST) {
                System.out.println(offset
                        + "¿Añadir un objeto a la lista? (. para terminar)");
            }
            System.out.print(offset + ++idx + " ? ");
            input = getString();
            exit = input.equals(".");
            if (!exit) {
                if (listOfWhat == LPRIMITIVE) {
                    if (ctype == String.class) {
                        victims.add(input);
                    } else {
                        try {
                            victims.add(Integer.parseInt(input));
                        } catch (Exception ex) {
                            victims.add(0);
                        }
                    }
                } else if (listOfWhat == LOBJECT) {
                    Object object = getObject(ctype, refFieldInput, offset
                            + DEFAULT_OFFSET);
                    if (object != null) {
                        victims.add(object);
                    }
                } else if (listOfWhat == LLIST) {
                    victims.add(getList(ptype, refFieldInput, offset
                            + DEFAULT_OFFSET));
                }
            }
        } while (!exit);
        return victims;
    }

    private static int getIgnoredFields(Field[] fields) {
        int total = 0;
        for (Field field : fields) {
            if (isIgnoreInputField(field)) {
                total++;
            }
        }
        return total;
    }

    public static <T extends Object> T modifyObject(T object, Class<T> clazz)
            throws NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        return modifyObject(object, null, clazz, "");
    }

    public static <T extends Object> T modifyObject(T object,
            CustomReferenceFieldInput input, Class<T> clazz)
            throws NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        return modifyObject(object, input, clazz, "");
    }

    public static <T extends Object> T modifyObject(T object,
            CustomReferenceFieldInput refInput, Class<T> type, String offset)
            throws NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        if (type == null)
            return null;
        Field[] fields = type.getDeclaredFields();

        int idx = 0, total = fields.length - getIgnoredFields(fields);
        for (Field field : fields) {
            if (!isIgnoreInputField(field)) {
                ReferenceFieldType rft = getReferenceFieldType(field);
                if (rft != ReferenceFieldType.None) {
                    continue;
                }
                ++idx;
                field.setAccessible(true);

                String fieldName = getOutputText(field);
                System.out.println(offset + "[" + idx + "/" + total + "] "
                        + fieldName);
                Object fieldValue = field.get(object);

                String currentValue = displayValue(fieldValue);

                System.out.println(offset + "Valor actual: " + currentValue);
                System.out
                        .println("Pulsa . para saltar este campo, introduce cualquier otro texto para modificarlo.");

                String input = getString(".");
                if (input.equals(".")) {
                    continue;
                }
                System.out.println("Modificando " + fieldName + "...");

                Object newFvalue = null;
                Class<?> ftype = field.getType();
                if (ftype == List.class) {
                    newFvalue = getList(
                            ((ParameterizedType) field.getGenericType())
                                    .getActualTypeArguments()[0],
                            refInput, offset + DEFAULT_OFFSET);

                } else if (ftype.isPrimitive() || ftype == String.class) {
                    System.out.print(offset + "? ");
                    newFvalue = getValue(ftype);

                } else {
                    newFvalue = getObject(ftype, refInput, offset
                            + DEFAULT_OFFSET);
                }

                if (newFvalue != null) {
                    field.set(object, newFvalue);
                } else {
                    System.err.println("Valor nulo en el campo: "
                            + field.getName() + " -> " + type.getName());
                }
                field.setAccessible(false);
            }
        }
        return (T) object;
    }

    private static String displayValue(Object object)
            throws IllegalArgumentException, IllegalAccessException {
        if (object instanceof List) {
            return displayList((List) object);
        } else if (object instanceof String) {
            return (String) object;
        } else if (object instanceof Integer) {
            return ((Integer) object).toString();
        } else {
            Field[] fields = object.getClass().getDeclaredFields();
            String msg = "{";
            int idx = 0, total = fields.length - getIgnoredFields(fields);
            for (Field field : fields) {
                if (!isIgnoreInputField(field)) {
                    ReferenceFieldType rft = getReferenceFieldType(field);
                    if (rft != ReferenceFieldType.None) {
                        continue;
                    }
                    ++idx;
                    field.setAccessible(true);
                    msg += getOutputText(field) + ": "
                            + displayValue(field.get(object));
                    if (idx < total) {
                        msg += ", ";
                    }
                    field.setAccessible(false);
                }
            }

            return msg + "}";
        }
    }

    private static String displayList(List list)
            throws IllegalArgumentException, IllegalAccessException {
        String msg = "[";
        if (list.isEmpty()) {
            msg += "lista vacía";
        } else {
            msg += displayValue(list.get(0));
            for (int i = 1, n = list.size(); i < n; ++i) {
                msg += ", " + displayValue(list.get(i));
            }
        }
        return msg + "]";
    }

    // --------------------------------------------------------------------------------------
    // Input annotations:
    // --------------------------------------------------------------------------------------
    public static String getOutputText(Object element) {
        if (element instanceof AnnotatedElement) {
            AnnotatedElement elem = (AnnotatedElement) element;
            if (elem.isAnnotationPresent(UserInputField.class)) {
                UserInputField uif = (UserInputField) elem
                        .getAnnotation(UserInputField.class);
                return uif.outputText();
            } else if (elem instanceof Field) {
                return ((Field) elem).getName();
            } else if (elem instanceof Class) {
                return ((Class) elem).getSimpleName();
            }
        } else if (element != null) {
            return element.toString();
        }
        return null;
    }

    public static boolean isIgnoreInputField(Field field) {
        return field.isAnnotationPresent(IgnoreInputField.class);
    }

    public static void drawMenu(String título, int returnInt,
            Object... opciones) {
        System.out.println("\n--" + título + " (" + returnInt
                + " para volver) --\n");
        for (int i = 0, n = opciones.length; i < n; ++i) {
            Object opcion = opciones[i];
            String mensajeOpcion;
            if (opcion instanceof AnnotatedElement) {
                mensajeOpcion = ConsoleUtil
                        .getOutputText((AnnotatedElement) opcion);
            } else {
                mensajeOpcion = opcion.toString();
            }
            System.out.println(i + "\t" + mensajeOpcion);
        }
        System.out.print("> ");
    }

    public static ReferenceFieldType getReferenceFieldType(Field field) {
        if (field != null && field.isAnnotationPresent(UserInputField.class)) {
            UserInputField uif = (UserInputField) field
                    .getAnnotation(UserInputField.class);
            return uif.referenceType();
        }
        return ReferenceFieldType.None;
    }

}


text:
function getQueryParams(qs)
{
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while ((tokens = re.exec(qs))) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

function initAutoCompletionForElement(element)
{
    var options = {
      componentRestrictions: {country: 'fr'}
    };
    var autocomplete = new google.maps.places.Autocomplete(element, options);
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        $(element).trigger('place_changed');
        return false;
    });
}


text:
//========================================================================
//Copyright 2007-2009 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//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.
//========================================================================

package com.dyuproject.openid.ext;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import com.dyuproject.openid.OpenIdUser;
import com.dyuproject.util.ClassLoaderUtil;
import com.dyuproject.util.http.UrlEncodedParameterMap;

/**
 * Simple Registration Extension
 * See http://openid.net/specs/openid-simple-registration-extension-1_1-01.html
 *
 * @author David Yu
 * @created May 27, 2009
 */

public final class SRegExtension extends AbstractExtension
{

    /**
     * "openid.ns.sreg"
     */
    public static final String NS_KEY = "openid.ns.sreg";
    /**
     * "openid.sreg.optional"
     */
    public static final String OPTIONAL_KEY = "openid.sreg.optional";
    /**
     * "http://openid.net/extensions/sreg/1.1"
     */
    public static final String NAMESPACE = "http://openid.net/extensions/sreg/1.1";
    /**
     * The attribute name set on the {@link OpenIdUser}. ("sreg")
     */
    public static final String ATTR_NAME = "sreg";

    /**
     * Gets the sreg value set on the {@link OpenIdUser user}.
     */
    @SuppressWarnings("unchecked")
    public static Map<String,String> get(OpenIdUser user)
    {
        return (Map<String,String>)user.getAttribute(ATTR_NAME);
    }

    /**
     * Removes the sreg value set on the {@link OpenIdUser user}.
     */
    @SuppressWarnings("unchecked")
    public static Map<String,String> remove(OpenIdUser user)
    {
        return (Map<String,String>)user.removeAttribute(ATTR_NAME);
    }

    private static final Properties __sregConfig = new Properties();
    private static final String __optional;

    static
    {
        try
        {
            __sregConfig.load(ClassLoaderUtil.getResource("com/dyuproject/openid/ext/sreg.properties",
                    AxSchemaExtension.class).openStream());
            __optional = (String)__sregConfig.remove("sreg.optional");
        }
        catch(Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    private final Map<String,Exchange> _exchanges = new HashMap<String,Exchange>();
    private String _checkKey;

    public SRegExtension()
    {
        super("sreg", NAMESPACE);
    }

    /**
     * Adds an exchange (field) to be included in the extension parameters.
     */
    public SRegExtension addExchange(String alias)
    {
        if(alias==null)
            throw new IllegalArgumentException("alias must be specified.");
        if(!__sregConfig.containsKey(alias))
            throw new IllegalArgumentException("'" + alias + "' not found. The ff are supported:\n" + __optional);

        return addExchange(new SimpleExchange(alias));
    }

    protected SRegExtension addExchange(Exchange exchange)
    {
        // 1 single test key (email recommended)
        if(_exchanges.size()==0)
            _checkKey = "openid.sreg." + exchange.getAlias();
        _exchanges.put(exchange.getAlias(), exchange);
        return this;
    }

    public void onPreAuthenticate(OpenIdUser user, HttpServletRequest request,
            UrlEncodedParameterMap params)
    {
        params.put(NS_KEY, NAMESPACE);
        StringBuilder optional = new StringBuilder();
        for(String alias : _exchanges.keySet())
            optional.append(alias).append(',');

        params.put(OPTIONAL_KEY, optional.substring(0, optional.length()-1));
    }

    public void onAuthenticate(OpenIdUser user, HttpServletRequest request)
    {
        String alias = user.getExtension(getNamespace());
        if(alias!=null || NAMESPACE.equals(request.getParameter(NS_KEY))
                || request.getParameter(_checkKey)!=null)
        {
            Map<String,String> attributes = new HashMap<String,String>(new Double(_exchanges.size()/.75).intValue()+1);
            user.setAttribute(ATTR_NAME, attributes);
            for(Exchange e : _exchanges.values())
                e.parseAndPut(user, request, attributes, getAlias());
        }
    }

    /**
     * SimpleExchange - parses the value denoted by "openid.sreg.$alias = value".
     */
    public static final class SimpleExchange implements Exchange
    {

        private final String _alias, _key;

        public SimpleExchange(String alias)
        {
            _alias = alias;
            _key = "openid.sreg." + _alias;
        }

        public String getAlias()
        {
            return _alias;
        }

        public void put(OpenIdUser user, HttpServletRequest request,
                UrlEncodedParameterMap params, String extensionAlias)
        {

        }

        public void parseAndPut(OpenIdUser user, HttpServletRequest request,
                Map<String, String> attributes, String extensionAlias)
        {
            String value = request.getParameter(_key);
            if(value!=null)
                attributes.put(_alias, value);
        }

    }

}


text:
package com.android.server.content;

import android.content.pm.PackageManager;
import android.content.SyncAdapterType;
import android.content.SyncAdaptersCache;
import android.content.pm.RegisteredServicesCache.ServiceInfo;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.format.DateUtils;
import android.util.Log;
import android.util.Pair;

import com.google.android.collect.Maps;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Queue of pending sync operations. Not inherently thread safe, external
 * callers are responsible for locking.
 *
 * @hide
 */
public class SyncQueue {
    private static final String TAG = "SyncManager";
    private final SyncStorageEngine mSyncStorageEngine;
    private final SyncAdaptersCache mSyncAdapters;
    private final PackageManager mPackageManager;

    // A Map of SyncOperations operationKey -> SyncOperation that is designed for
    // quick lookup of an enqueued SyncOperation.
    private final HashMap<String, SyncOperation> mOperationsMap = Maps.newHashMap();

    public SyncQueue(PackageManager packageManager, SyncStorageEngine syncStorageEngine,
            final SyncAdaptersCache syncAdapters) {
        mPackageManager = packageManager;
        mSyncStorageEngine = syncStorageEngine;
        mSyncAdapters = syncAdapters;
    }

    public void addPendingOperations(int userId) {
        for (SyncStorageEngine.PendingOperation op : mSyncStorageEngine.getPendingOperations()) {
            final SyncStorageEngine.EndPoint info = op.target;
            if (info.userId != userId) continue;

            final Pair<Long, Long> backoff = mSyncStorageEngine.getBackoff(info);
            SyncOperation operationToAdd;
            if (info.target_provider) {
                final ServiceInfo<SyncAdapterType> syncAdapterInfo = mSyncAdapters.getServiceInfo(
                        SyncAdapterType.newKey(info.provider, info.account.type), info.userId);
                if (syncAdapterInfo == null) {
                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "Missing sync adapter info for authority " + op.target);
                    }
                    continue;
                }
                operationToAdd = new SyncOperation(
                        info.account, info.userId, op.reason, op.syncSource, info.provider,
                        op.extras,
                        op.expedited ? -1 : 0 /* delay */,
                        0 /* flex */,
                        backoff != null ? backoff.first : 0L,
                        mSyncStorageEngine.getDelayUntilTime(info),
                        syncAdapterInfo.type.allowParallelSyncs());
                operationToAdd.pendingOperation = op;
                add(operationToAdd, op);
            } else if (info.target_service) {
                try {
                    mPackageManager.getServiceInfo(info.service, 0);
                } catch (PackageManager.NameNotFoundException e) {
                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.w(TAG, "Missing sync service for authority " + op.target);
                    }
                    continue;
                }
                operationToAdd = new SyncOperation(
                        info.service, info.userId, op.reason, op.syncSource,
                        op.extras,
                        op.expedited ? -1 : 0 /* delay */,
                        0 /* flex */,
                        backoff != null ? backoff.first : 0,
                        mSyncStorageEngine.getDelayUntilTime(info));
                operationToAdd.pendingOperation = op;
                add(operationToAdd, op);
            }
        }
    }

    public boolean add(SyncOperation operation) {
        return add(operation, null /* this is not coming from the database */);
    }

    /**
     * Adds a SyncOperation to the queue and creates a PendingOperation object to track that sync.
     * If an operation is added that already exists, the existing operation is updated if the newly
     * added operation occurs before (or the interval overlaps).
     */
    private boolean add(SyncOperation operation,
            SyncStorageEngine.PendingOperation pop) {
        // If an operation with the same key exists and this one should run sooner/overlaps,
        // replace the run interval of the existing operation with this new one.
        // Complications: what if the existing operation is expedited but the new operation has an
        // earlier run time? Will not be a problem for periodic syncs (no expedited flag), and for
        // one-off syncs we only change it if the new sync is sooner.
        final String operationKey = operation.key;
        final SyncOperation existingOperation = mOperationsMap.get(operationKey);

        if (existingOperation != null) {
            boolean changed = false;
            if (operation.compareTo(existingOperation) <= 0 ) {
                long newRunTime =
                        Math.min(existingOperation.latestRunTime, operation.latestRunTime);
                // Take smaller runtime.
                existingOperation.latestRunTime = newRunTime;
                // Take newer flextime.
                existingOperation.flexTime = operation.flexTime;
                changed = true;
            }
            return changed;
        }

        operation.pendingOperation = pop;
        // Don't update the PendingOp if one already exists. This really is just a placeholder,
        // no actual scheduling info is placed here.
        if (operation.pendingOperation == null) {
            pop = mSyncStorageEngine.insertIntoPending(operation);
            if (pop == null) {
                throw new IllegalStateException("error adding pending sync operation "
                        + operation);
            }
            operation.pendingOperation = pop;
        }

        mOperationsMap.put(operationKey, operation);
        return true;
    }

    public void removeUserLocked(int userId) {
        ArrayList<SyncOperation> opsToRemove = new ArrayList<SyncOperation>();
        for (SyncOperation op : mOperationsMap.values()) {
            if (op.target.userId == userId) {
                opsToRemove.add(op);
            }
        }
            for (SyncOperation op : opsToRemove) {
                remove(op);
            }
    }

    /**
     * Remove the specified operation if it is in the queue.
     * @param operation the operation to remove
     */
    public void remove(SyncOperation operation) {
        boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
        SyncOperation operationToRemove = mOperationsMap.remove(operation.key);
        if (isLoggable) {
            Log.v(TAG, "Attempting to remove: " + operation.key);
        }
        if (operationToRemove == null) {
            if (isLoggable) {
                Log.v(TAG, "Could not find: " + operation.key);
            }
            return;
        }
        if (!mSyncStorageEngine.deleteFromPending(operationToRemove.pendingOperation)) {
            final String errorMessage = "unable to find pending row for " + operationToRemove;
            Log.e(TAG, errorMessage, new IllegalStateException(errorMessage));
        }
    }

    /** Reset backoffs for all operations in the queue. */
    public void clearBackoffs() {
        for (SyncOperation op : mOperationsMap.values()) {
            op.backoff = 0L;
            op.updateEffectiveRunTime();
        }
    }

    public void onBackoffChanged(SyncStorageEngine.EndPoint target, long backoff) {
        // For each op that matches the target of the changed op, update its
        // backoff and effectiveStartTime
        for (SyncOperation op : mOperationsMap.values()) {
            if (op.target.matchesSpec(target)) {
                op.backoff = backoff;
                op.updateEffectiveRunTime();
            }
        }
    }

    public void onDelayUntilTimeChanged(SyncStorageEngine.EndPoint target, long delayUntil) {
        // for each op that matches the target info of the provided op, change the delay time.
        for (SyncOperation op : mOperationsMap.values()) {
            if (op.target.matchesSpec(target)) {
                op.delayUntil = delayUntil;
                op.updateEffectiveRunTime();
            }
        }
    }

    /**
     * Remove all of the SyncOperations associated with a given target.
     *
     * @param info target object provided here can have null Account/provider. This is the case
     * where you want to remove all ops associated with a provider (null Account) or all ops
     * associated with an account (null provider).
     * @param extras option bundle to include to further specify which operation to remove. If this
     * bundle contains sync settings flags, they are ignored.
     */
    public void remove(final SyncStorageEngine.EndPoint info, Bundle extras) {
        Iterator<Map.Entry<String, SyncOperation>> entries = mOperationsMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, SyncOperation> entry = entries.next();
            SyncOperation syncOperation = entry.getValue();
            final SyncStorageEngine.EndPoint opInfo = syncOperation.target;
            if (!opInfo.matchesSpec(info)) {
                continue;
            }
            if (extras != null
                    && !SyncManager.syncExtrasEquals(
                        syncOperation.extras,
                        extras,
                        false /* no config flags*/)) {
                continue;
            }
            entries.remove();
            if (!mSyncStorageEngine.deleteFromPending(syncOperation.pendingOperation)) {
                final String errorMessage = "unable to find pending row for " + syncOperation;
                Log.e(TAG, errorMessage, new IllegalStateException(errorMessage));
            }
        }
    }

    public Collection<SyncOperation> getOperations() {
        return mOperationsMap.values();
    }

    public void dump(StringBuilder sb) {
        final long now = SystemClock.elapsedRealtime();
        sb.append("SyncQueue: ").append(mOperationsMap.size()).append(" operation(s)\n");
        for (SyncOperation operation : mOperationsMap.values()) {
            sb.append("  ");
            if (operation.effectiveRunTime <= now) {
                sb.append("READY");
            } else {
                sb.append(DateUtils.formatElapsedTime((operation.effectiveRunTime - now) / 1000));
            }
            sb.append(" - ");
            sb.append(operation.dump(mPackageManager, false)).append("\n");
        }
    }
}


text:
var fs = require("fs");
var nodePath = require("path");

var originalDateToString = Date.prototype.toString;

var testUtil = module.exports = {
  expectFile: function(path, content) {
    expect(fs.readFileSync(path, "utf8")).toEqual(content);
  },

  rmdirSyncRecursive: function(dir) {
    fs.readdirSync(dir).forEach(function(fileName) {
      var filePath = nodePath.join(dir, fileName);
      if (fs.statSync(filePath).isDirectory()) {
        testUtil.rmdirSyncRecursive(filePath);
      } else {
        fs.unlinkSync(filePath);
      }
    });

    fs.rmdirSync(dir);
  },

  createFilesFromTree: function(structure, prefix) {
    if (prefix === undefined) return testUtil.createFilesFromTree(structure, process.cwd());

    Object.keys(structure).forEach(function(name) {
      var path = nodePath.join(prefix, name);
      if (typeof structure[name] === "string") {
        fs.writeFileSync(path, structure[name]);
      } else {
        fs.mkdirSync(path, "777");
        testUtil.createFilesFromTree(structure[name], path);
      }
    });
  },

  createStandardFileStructure: function() {
    testUtil.createFilesFromTree({ "1a": { filea: "filea" },
                                   "1b": { fileb: "fileb",
                                           "2b": { filec: "filec",
                                                   "3b": {
                                                     "4b": { filed: "filed" }}}}});
  },

  createDeeplyNestedFileStructure: function() {
    testUtil.createFilesFromTree({ filea: "filea",
                                   fileb: "fileb",
                                   c1: { filec: "filec" },
                                   d1: { filed: "filed" },
                                   e1: { e2: { filee: "filee" }},
                                   f1: { f2: { filef: "filef" }},
                                   g1: { g2: { g3: { fileg: "fileg" }}},
                                   h1: { h2: { h3: { fileh: "fileh" }}}});
  },

  index: function() {
    return (fs.existsSync(".gitlet/index") ? fs.readFileSync(".gitlet/index", "utf8") : "\n")
      .split("\n")
      .filter(function(l) { return l !== ""; })
      .map(function(blobStr) {
        var blobData = blobStr.split(/ /);
        return { path: blobData[0], stage: parseInt(blobData[1]), hash: blobData[2] };
      });
  },

  initTestDataDir: function() {
    var testDataDir = __dirname + "/testData";
    process.chdir(__dirname)
    if (fs.existsSync(testDataDir)) {
      testUtil.rmdirSyncRecursive(testDataDir);
    }

    fs.mkdirSync(testDataDir);
    process.chdir(testDataDir);
    fs.mkdirSync("repo1");
    process.chdir("repo1");
    expect(fs.readdirSync(process.cwd()).length).toEqual(0);
  },

  makeRemoteRepo: function() {
    process.chdir("../");
    fs.mkdirSync("sub");
    process.chdir("sub");
    fs.mkdirSync("repo2");
    process.chdir("repo2");
    return process.cwd();
  },

  pinDate: function() {
    global.Date.prototype.toString = function() {
      return "Sat Aug 30 2014 09:16:45 GMT-0400 (EDT)";
    };
  },

  unpinDate: function() {
    global.Date.prototype.toString = originalDateToString;
  },

  readFile: function(path) {
    return fs.readFileSync(path, "utf8");
  },

  hash: function(string) {
    var hashInt = 0;
    for (var i = 0; i < string.length; i++) {
      hashInt = hashInt * 31 + string.charCodeAt(i);
      hashInt = hashInt | 0;
    }

    return Math.abs(hashInt).toString(16);
  },

  refHash: function(ref) {
    return testUtil.readFile(nodePath.join(".gitlet", ref));
  },

  headHash: function() {
    var ref = testUtil.readFile(".gitlet/HEAD").match("ref: (refs/heads/.+)")[1];
    return testUtil.readFile(nodePath.join(".gitlet", ref));
  }
};


text:
<?php

namespace PiPHP\GPIO\Pin;

interface InputPinInterface extends PinInterface
{
    public const EDGE_NONE = 'none';
    public const EDGE_BOTH = 'both';
    public const EDGE_RISING = 'rising';
    public const EDGE_FALLING = 'falling';

    /**
     * Get the pin edge.
     *
     * @return string The pin edge value
     */
    public function getEdge();

    /**
     * Set the pin edge.
     *
     * @param string $edge The pin edge value to set
     */
    public function setEdge($edge);
}


text:
#define SGUI_BUILDING_DLL
#include "sgui_label.h"
#include "sgui_canvas.h"
#include "sgui_skin.h"
#include "sgui_font.h"
#include "sgui_internal.h"
#include "sgui_utf8.h"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

typedef struct
{
    sgui_widget super;

    char* text;
}
sgui_label;

static void label_draw( sgui_widget* super )
{
    sgui_label* this = (sgui_label*)super;

    sgui_skin_draw_text( super->canvas, super->area.left, super->area.top,
                         this->text );
}

static void label_destroy( sgui_widget* this )
{
    free( ((sgui_label*)this)->text );
    free( this );
}

sgui_widget* sgui_label_create( int x, int y, const char* text )
{
    sgui_label* this;
    sgui_widget* super;

    /* create widget */
    this = calloc( 1, sizeof(sgui_label) );
    super = (sgui_widget*)this;

    if( !this || !(this->text = sgui_strdup( text )) )
    {
        free( this );
        return NULL;
    }

    /* initialise the base widget */
    sgui_widget_init( (sgui_widget*)this, 0, 0, 0, 0 );

    super->draw          = label_draw;
    super->destroy       = label_destroy;
    super->flags         = SGUI_WIDGET_VISIBLE;

    /* compute the text area */
    sgui_skin_get_text_extents( text, &super->area );
    sgui_rect_set_position( &super->area, x, y );

    return (sgui_widget*)this;
}


text:
@interface Controller : NSObject<IPlayer> {
 @public
    id<IPlayer> __Player;
    Loader * __Loader;
    Container *__Container;
    Handler *__Handler;
}
- (id<IPlayer>)getPlayer;
- (void)setPlayer:(id<IPlayer>)value;
- (void)loadController:(NSString *)file;
- (void)ask;
+ (int)Main:(NSArray *)args;
- (void)loadFieldWithName:(NSString *)name
                 withValue:(NSString *)value;
- (id)initWithSurveyId:(NSString*)surveyId;

@end


text:
package voicenavigator

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// GetRealTimeConcurrency invokes the voicenavigator.GetRealTimeConcurrency API synchronously
func (client *Client) GetRealTimeConcurrency(request *GetRealTimeConcurrencyRequest) (response *GetRealTimeConcurrencyResponse, err error) {
	response = CreateGetRealTimeConcurrencyResponse()
	err = client.DoAction(request, response)
	return
}

// GetRealTimeConcurrencyWithChan invokes the voicenavigator.GetRealTimeConcurrency API asynchronously
func (client *Client) GetRealTimeConcurrencyWithChan(request *GetRealTimeConcurrencyRequest) (<-chan *GetRealTimeConcurrencyResponse, <-chan error) {
	responseChan := make(chan *GetRealTimeConcurrencyResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.GetRealTimeConcurrency(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// GetRealTimeConcurrencyWithCallback invokes the voicenavigator.GetRealTimeConcurrency API asynchronously
func (client *Client) GetRealTimeConcurrencyWithCallback(request *GetRealTimeConcurrencyRequest, callback func(response *GetRealTimeConcurrencyResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *GetRealTimeConcurrencyResponse
		var err error
		defer close(result)
		response, err = client.GetRealTimeConcurrency(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// GetRealTimeConcurrencyRequest is the request struct for api GetRealTimeConcurrency
type GetRealTimeConcurrencyRequest struct {
	*requests.RpcRequest
	InstanceId string `position:"Query" name:"InstanceId"`
}

// GetRealTimeConcurrencyResponse is the response struct for api GetRealTimeConcurrency
type GetRealTimeConcurrencyResponse struct {
	*responses.BaseResponse
	RequestId           string `json:"RequestId" xml:"RequestId"`
	Timestamp           int64  `json:"Timestamp" xml:"Timestamp"`
	RealTimeConcurrency int64  `json:"RealTimeConcurrency" xml:"RealTimeConcurrency"`
	MaxConcurrency      int64  `json:"MaxConcurrency" xml:"MaxConcurrency"`
}

// CreateGetRealTimeConcurrencyRequest creates a request to invoke GetRealTimeConcurrency API
func CreateGetRealTimeConcurrencyRequest() (request *GetRealTimeConcurrencyRequest) {
	request = &GetRealTimeConcurrencyRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("VoiceNavigator", "2018-06-12", "GetRealTimeConcurrency", "voicebot", "openAPI")
	request.Method = requests.GET
	return
}

// CreateGetRealTimeConcurrencyResponse creates a response to parse from GetRealTimeConcurrency response
func CreateGetRealTimeConcurrencyResponse() (response *GetRealTimeConcurrencyResponse) {
	response = &GetRealTimeConcurrencyResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
package config

type StageDependencies struct {
	Install     []string
	Setup       []string
	BeforeSetup []string

	raw *rawStageDependencies
}

func (c *StageDependencies) validate() error {
	if !allRelativePaths(c.Install) {
		return newDetailedConfigError("`install: [PATH, ...]|PATH` should be relative paths!", c.raw, c.raw.rawGit.rawStapelImage.doc)
	} else if !allRelativePaths(c.Setup) {
		return newDetailedConfigError("`setup: [PATH, ...]|PATH` should be relative paths!", c.raw, c.raw.rawGit.rawStapelImage.doc)
	} else if !allRelativePaths(c.BeforeSetup) {
		return newDetailedConfigError("`beforeSetup: [PATH, ...]|PATH` should be relative paths!", c.raw, c.raw.rawGit.rawStapelImage.doc)
	}
	return nil
}