text:
package com.swfarm.biz.amazon.dto;

import java.io.Serializable;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.swfarm.biz.oa.dto.SearchCriteria;
import com.swfarm.pub.utils.DateUtils;

public class SearchAmazonProductCustomerReviewsCriteria extends SearchCriteria implements Serializable {

	private static final long serialVersionUID = 1L;

	private String asin;

	private String[] asins;

	private String reviewerName;

	private String reviewDateStr;

	private String accountNumber;

	private String brand;

	private String articleNumber;

	private String name;

	private Date startDate;

	private Date endDate;

	private String customerId;

	private Double maxMark;

	private Double minMark;

	private String productManagerNo;

	public String getAccountNumber() {
		return accountNumber;
	}

	public void setAccountNumber(String accountNumber) {
		this.accountNumber = accountNumber;
	}

	public String getArticleNumber() {
		return articleNumber;
	}

	public void setArticleNumber(String articleNumber) {
		this.articleNumber = articleNumber;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getStartDate() {
		return startDate;
	}

	public String getStartDateString() {
		if (startDate != null) {
			return DateUtils.dateToString(startDate, "yyyy/MM/dd");
		} else {
			return StringUtils.EMPTY;
		}
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public String getEndDateString() {
		if (endDate != null) {
			return DateUtils.dateToString(endDate, "yyyy/MM/dd");
		} else {
			return StringUtils.EMPTY;
		}
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public String getAsin() {
		return asin;
	}

	public void setAsin(String asin) {
		this.asin = asin;
	}

	public String getReviewerName() {
		return reviewerName;
	}

	public void setReviewerName(String reviewerName) {
		this.reviewerName = reviewerName;
	}

	public String getReviewDateStr() {
		return reviewDateStr;
	}

	public void setReviewDateStr(String reviewDateStr) {
		this.reviewDateStr = reviewDateStr;
	}

	public void setMaxMark(Double maxMark) {
		this.maxMark = maxMark;
	}

	public Double getMaxMark() {
		return maxMark;
	}

	public void setMinMark(Double minMark) {
		this.minMark = minMark;
	}

	public Double getMinMark() {
		return minMark;
	}

	public void setProductManagerNo(String productManagerNo) {
		this.productManagerNo = productManagerNo;
	}

	public String getProductManagerNo() {
		return productManagerNo;
	}

	public void setAsins(String[] asins) {
		this.asins = asins;
	}

	public String[] getAsins() {
		return asins;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getBrand() {
		return brand;
	}

}


text:
CREATE OR REPLACE FUNCTION mz_calculate_is_landuse(
    landuse_val text, leisure_val text, natural_val text, highway_val text,
    amenity_val text, aeroway_val text, tourism_val text, man_made_val text,
    power_val text)
RETURNS BOOLEAN AS $$
BEGIN
    RETURN
        landuse_val IN ('park', 'forest', 'residential', 'retail', 'commercial',
                        'industrial', 'railway', 'cemetery', 'grass', 'farmyard',
                        'farm', 'farmland', 'wood', 'meadow', 'village_green',
                        'recreation_ground', 'allotments', 'quarry', 'urban', 'rural'
                        'military')
     OR leisure_val IN ('park', 'garden', 'playground', 'golf_course', 'sports_centre',
                        'pitch', 'stadium', 'common', 'nature_reserve')
     OR natural_val IN ('wood', 'land', 'scrub', 'wetland', 'glacier')
     OR highway_val IN ('pedestrian', 'footway')
     OR amenity_val IN ('university', 'school', 'college', 'library', 'fuel',
                        'parking', 'cinema', 'theatre', 'place_of_worship', 'hospital')
     OR aeroway_val IN ('runway', 'taxiway', 'apron', 'aerodrome')
     OR tourism_val IN ('zoo')
     OR man_made_val IN ('pier', 'wastewater_plant', 'works', 'bridge', 'tower',
                         'breakwater', 'water_works', 'groyne', 'dike', 'cutline')
     OR power_val IN   ('plant', 'generator', 'substation', 'station', 'sub_station');
END;
$$ LANGUAGE plpgsql IMMUTABLE;

CREATE OR REPLACE FUNCTION mz_calculate_poi_level(
    aerialway_val text,
    aeroway_val text,
    amenity_val text,
    barrier_val text,
    craft_val text,
    highway_val text,
    historic_val text,
    leisure_val text,
    lock_val text,
    man_made_val text,
    natural_val text,
    office_val text,
    power_val text,
    railway_val text,
    shop_val text,
    tourism_val text,
    waterway_val text,
    way_area real
)
RETURNS SMALLINT AS $$
DECLARE
  zoom smallint;
BEGIN
  zoom =
        CASE WHEN natural_val IN ('peak', 'volcano') THEN 11
             WHEN railway_val IN ('station') THEN 12
             WHEN (aeroway_val IN ('aerodrome', 'airport')
                   OR aerialway_val IN ('station')
                   OR railway_val IN ('halt', 'tram_stop')
                   OR tourism_val IN ('alpine_hut', 'zoo')) THEN 13
             WHEN (natural_val IN ('spring')
                   OR railway_val IN ('level_crossing')) THEN 14
             WHEN (amenity_val IN ('hospital')
                   OR barrier_val IN ('gate')
                   OR craft_val IN ('sawmill')
                   OR highway_val IN ('gate', 'mini_roundabout')
                   OR lock_val IN ('yes')
                   OR man_made_val IN ('lighthouse', 'power_wind')
                   OR natural_val IN ('cave_entrance')
                   OR power_val IN ('generator')
                   OR waterway_val IN ('lock')) THEN 15
             WHEN (aeroway_val IN ('helipad')
                   OR amenity_val IN ('biergarten', 'bus_station', 'car_sharing',
                                      'picnic_site', 'place_of_worship',
                                      'prison', 'pub', 'recycling', 'shelter')
                   OR barrier_val IN ('block', 'bollard', 'lift_gate')
                   OR craft_val IN ('brewery', 'winery', 'sawmill')
                   OR highway_val IN ('ford')
                   OR historic_val IN ('archaeological_site')
                   OR man_made_val IN ('windmill')
                   OR natural_val IN ('tree')
                   OR shop_val IN ('department_store', 'supermarket')
                   OR tourism_val IN ('camp_site', 'caravan_site', 'information', 'viewpoint')) THEN 16
             WHEN (aeroway_val IN ('gate')
                   OR amenity_val IN (
                 'atm', 'bank', 'bar', 'bicycle_rental', 'bicycle_parking', 'bus_stop',
                 'cafe', 'cinema', 'courthouse', 'drinking_water', 'embassy', 'emergency_phone',
                 'fast_food', 'fire_station', 'fuel', 'library', 'parking', 'pharmacy',
                 'police', 'post_box', 'post_office', 'restaurant', 'telephone', 'theatre',
                 'toilets', 'veterinary')
                   OR craft_val IN ('brewery', 'carpenter', 'confectionery', 'dressmaker',
                'electrician', 'gardener', 'handicraft', 'hvac', 'metal_construction',
                'painter', 'photographer', 'photographic_laboratory', 'plumber',
                'pottery', 'sawmill', 'shoemaker', 'stonemason', 'tailor', 'winery')
                   OR highway_val IN ('bus_stop', 'traffic_signals')
                   OR historic_val IN ('memorial')
                   OR leisure_val IN ('playground', 'slipway')
                   OR man_made_val IN ('mast', 'water_tower')
                   OR office_val IN ('accountant', 'administrative', 'advertising_agency',
                'architect', 'association', 'company', 'consulting', 'educational_institution',
                'employment_agency', 'estate_agent', 'financial', 'foundation', 'government',
                'insurance', 'it', 'lawyer', 'newspaper', 'ngo', 'notary', 'physician',
                'political_party', 'religion', 'research', 'tax_advisor', 'telecommunication',
                'therapist', 'travel_agent', 'yes')
                   OR shop_val IN ('bakery', 'bicycle', 'books', 'butcher', 'car', 'car_repair',
                                 'clothes', 'computer', 'convenience',
                                 'doityourself', 'dry_cleaning', 'fashion', 'florist', 'gift',
                                 'greengrocer', 'hairdresser', 'jewelry', 'mobile_phone',
                                 'optician', 'pet')
                   OR tourism_val IN ('bed_and_breakfast', 'chalet', 'guest_house',
                                    'hostel', 'hotel', 'motel', 'museum')
                   OR railway_val IN ('subway_entrance')) THEN 17
             WHEN (amenity_val IN ('bench', 'waste_basket')) THEN 18
             ELSE NULL END;
  RETURN (CASE
    WHEN way_area > 1.0e7 THEN zoom - 4
    WHEN way_area > 1.0e6 THEN zoom - 3
    WHEN way_area > 1.0e5 THEN zoom - 2
    WHEN way_area > 1.0e4 THEN zoom - 1
    ELSE zoom END);
END;
$$ LANGUAGE plpgsql IMMUTABLE;

CREATE OR REPLACE FUNCTION mz_calculate_road_level(highway_val text, railway_val text, aeroway_val text)
RETURNS SMALLINT AS $$
BEGIN
    RETURN (
        CASE WHEN highway_val IN ('motorway', 'trunk', 'primary', 'motorway_link') THEN 9
             WHEN highway_val IN ('secondary') THEN 10
             WHEN (highway_val IN ('tertiary')
                OR aeroway_val IN ('runway', 'taxiway')) THEN 11
             WHEN highway_val IN ('trunk_link', 'residential', 'unclassified', 'road') THEN 12
             WHEN highway_val IN ('primary_link', 'secondary_link') THEN 13
             WHEN (highway_val IN ('tertiary_link', 'minor')
                OR railway_val='rail') THEN 14
             WHEN (highway_val IN ('service', 'footpath', 'track', 'footway', 'steps', 'pedestrian', 'path', 'cycleway', 'living_street')
                OR railway_val IN ('tram', 'light_rail', 'narrow_gauge', 'monorail')) THEN 15
             ELSE NULL END
    );
END;
$$ LANGUAGE plpgsql IMMUTABLE;

CREATE OR REPLACE FUNCTION mz_calculate_is_water(
    waterway_val text, natural_val text, landuse_val text)
RETURNS BOOLEAN AS $$
BEGIN
    RETURN (
        waterway_val IN ('riverbank', 'dock')
     OR natural_val IN ('water')
     OR landuse_val IN ('basin', 'reservoir')
    );
END;
$$ LANGUAGE plpgsql IMMUTABLE;

CREATE OR REPLACE FUNCTION mz_calculate_is_building_or_part(
    building_val text, buildingpart_val text)
RETURNS BOOLEAN AS $$
BEGIN
    RETURN (building_val IS NOT NULL OR buildingpart_val IS NOT NULL);
END;
$$ LANGUAGE plpgsql IMMUTABLE;

CREATE OR REPLACE FUNCTION mz_calculate_transit_level(route_val text)
RETURNS SMALLINT AS $$
BEGIN
    RETURN (
        CASE WHEN route_val IN ('train', 'railway') THEN 6
             WHEN route_val IN ('subway', 'light_rail', 'tram') THEN 10
             ELSE NULL END
    );
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- mz_rel_get_tag returns the tag value associated with a given
-- key, or NULL if the tag is not set in the array.
--
-- tags in the planet_osm_rels table are stored in a flat array
-- rather than in an hstore variable. so this function makes it
-- easier to extract values from that array as if it were
-- associative.
--
CREATE OR REPLACE FUNCTION mz_rel_get_tag(
  tags text[],
  k text)
RETURNS text AS $$
DECLARE
  lo CONSTANT integer := array_lower(tags, 1);
  hi CONSTANT integer := array_upper(tags, 1);
BEGIN
  -- if tags is null, then we're not going to find any values
  -- in it, so just short-circuit and return NULL.
  IF tags IS NULL THEN
    RETURN NULL;
  END IF;
  -- tags is an array of key-value pairs inline, so to get the
  -- keys only we want each odd offset.
  FOR i IN 0 .. ((hi - lo - 1) / 2)
  LOOP
    IF tags[2 * i + lo] = k THEN
      RETURN tags[2 * i + lo + 1];
    END IF;
  END LOOP;
  RETURN NULL;
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- mz_first_dedup returns the lexicographically first non-NULL
-- entry in an array of text.
--
-- this is used to get a single value from the array of perhaps
-- many relations that a way can be a member of. we're not
-- interested in NULL values, so those can be discarded. it
-- remains to be seen if lexicographic ordering is any good for
-- network names, but in the limited testing i've done so far,
-- it seems to do okay.
--
CREATE OR REPLACE FUNCTION mz_first_dedup(
  arr text[])
RETURNS text AS $$
DECLARE
  rv text;
BEGIN
  SELECT DISTINCT y.x INTO rv FROM (SELECT unnest(arr) as x) y
    WHERE y.x IS NOT NULL LIMIT 1;
  RETURN rv;
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- mz_get_rel_network returns a network tag, or NULL, for a
-- given way ID.
--
-- it does this by joining onto the relations slim table, so it
-- won't work if you dropped the slim tables, or didn't use slim
-- mode in osm2pgsql.
--
CREATE OR REPLACE FUNCTION mz_get_rel_network(
  way_id bigint)
RETURNS text AS $$
BEGIN
  RETURN mz_first_dedup(ARRAY(
    SELECT mz_rel_get_tag(tags, 'network')
    FROM planet_osm_rels
    WHERE parts && ARRAY[way_id]
      AND parts[way_off+1:rel_off] && ARRAY[way_id]));
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- adds the prefix onto every key in an hstore value
CREATE OR REPLACE FUNCTION mz_hstore_add_prefix(
  tags hstore,
  prefix text)
RETURNS hstore AS $$
DECLARE
  new_tags hstore;
BEGIN
  SELECT hstore(array_agg(prefix || key), array_agg(value))
    INTO STRICT new_tags
    FROM each(tags);
  RETURN new_tags;
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- OSM tags are often structured as a list separated by ':'s.
-- to preserve some kind of ordering information, we want to
-- insert an element in this "list" after the first element.
-- i.e: mz_insert_one_level('foo:bar', 'x') -> 'foo:x:bar'.
CREATE OR REPLACE FUNCTION mz_insert_one_level(
  tag text,
  str text)
RETURNS text AS $$
DECLARE
  arr text[] = string_to_array(tag, ':');
  fst text   = arr[1];
  len int    = array_upper(arr, 1);
  rst text[] = arr[2:len];
BEGIN
  RETURN array_to_string(ARRAY[fst, str] || rst, ':');
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- adds an infix value into every key in an hstore value after
-- the first element. so 'foo:bar=>bat' with infix 'x' becomes
-- 'foo:x:bar=>bat'.
CREATE OR REPLACE FUNCTION mz_hstore_add_infix(
  tags hstore,
  infix text)
RETURNS hstore AS $$
DECLARE
  new_tags hstore;
BEGIN
  SELECT hstore(array_agg(mz_insert_one_level(key, infix)), array_agg(value))
    INTO STRICT new_tags
    FROM each(tags);
  RETURN new_tags;
END;
$$ LANGUAGE plpgsql IMMUTABLE;

redpajama_set_name: RedPajamaGithub


text:
namespace boost {
namespace unit_test {
namespace runtime_config {

// ************************************************************************** //
// **************                 runtime_config               ************** //
// ************************************************************************** //

BOOST_TEST_DECL void                    init( int& argc, char** argv );

BOOST_TEST_DECL bool                    auto_start_dbg();
BOOST_TEST_DECL const_string            break_exec_path();
BOOST_TEST_DECL bool                    catch_sys_errors();
BOOST_TEST_DECL bool                    color_output();
BOOST_TEST_DECL bool                    detect_fp_exceptions();
BOOST_TEST_DECL long                    detect_memory_leaks();
BOOST_TEST_DECL bool                    list_content();
BOOST_TEST_DECL output_format           log_format();
BOOST_TEST_DECL unit_test::log_level    log_level();
BOOST_TEST_DECL std::ostream*           log_sink();
BOOST_TEST_DECL const_string            memory_leaks_report_file();
BOOST_TEST_DECL bool                    no_result_code();
BOOST_TEST_DECL int                     random_seed();
BOOST_TEST_DECL output_format           report_format();
BOOST_TEST_DECL unit_test::report_level report_level();
BOOST_TEST_DECL std::ostream*           report_sink();
BOOST_TEST_DECL bool                    save_pattern();
BOOST_TEST_DECL bool                    show_build_info();
BOOST_TEST_DECL bool                    show_progress();
BOOST_TEST_DECL std::list<std::string> const& test_to_run();
BOOST_TEST_DECL bool                    use_alt_stack();
BOOST_TEST_DECL bool                    wait_for_debugger();

} // namespace runtime_config
} // namespace unit_test
} // namespace boost

//____________________________________________________________________________//

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_UNIT_TEST_PARAMETERS_HPP_071894GER


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="validatorFactory" class="org.springmodules.validation.commons.DefaultValidatorFactory">
        <property name="validationConfigLocations">
            <list>
                <value>/WEB-INF/validation.xml</value>
                <value>/WEB-INF/validator-rules.xml</value>
            </list>
        </property>
    </bean>
</beans>


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;

using coreArgs.Tests.Options;

namespace coreArgs.Tests
{
    [TestClass]
    public class StringParsingTests
    {
        [TestMethod]
        public void ShouldParseLongArgumentSuccessfully()
        {
            //Arrange
            var args = new [] { "--longstring", "test" };

            //Act
            var result = ArgsParser.Parse<StringOptions>(args);

            //Assert
            Assert.AreEqual("test", result.Arguments.LongStringOption);
        }

        [TestMethod]
        public void ShouldParseShortArgumentSuccessfully()
        {
            //Arrange
            var args = new [] { "-s", "test" };

            //Act
            var result = ArgsParser.Parse<StringOptions>(args);

            //Assert
            Assert.AreEqual("test", result.Arguments.ShortStringOption);
        }

        [TestMethod]
        public void ShouldParseListArgumentSuccessfully()
        {
            //Arrange
            var args = new [] { "-l", "test, test2, test3" };

            //Act
            var result = ArgsParser.Parse<StringOptions>(args);

            //Assert
            Assert.AreEqual("test, test2, test3", string.Join(", ", result.Arguments.ListStringOptions));
        }
    }
}


text:
package org.springframework.web.servlet.view.velocity;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import junit.framework.TestCase;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.DescriptiveResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
import org.springframework.ui.velocity.VelocityEngineUtils;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

/**
 * @author Rod Johnson
 * @author Juergen Hoeller
 */
public class VelocityConfigurerTests extends TestCase {

	public void testVelocityEngineFactoryBeanWithConfigLocation() throws VelocityException {
		VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
		vefb.setConfigLocation(new FileSystemResource("myprops.properties"));
		Properties props = new Properties();
		props.setProperty("myprop", "/mydir");
		vefb.setVelocityProperties(props);
		try {
			vefb.afterPropertiesSet();
			fail("Should have thrown IOException");
		}
		catch (IOException ex) {
			// expected
		}
	}

	public void testVelocityEngineFactoryBeanWithVelocityProperties() throws VelocityException, IOException {
		VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
		Properties props = new Properties();
		props.setProperty("myprop", "/mydir");
		vefb.setVelocityProperties(props);
		Object value = new Object();
		Map map = new HashMap();
		map.put("myentry", value);
		vefb.setVelocityPropertiesMap(map);
		vefb.afterPropertiesSet();
		assertThat(vefb.getObject(), instanceOf(VelocityEngine.class));
		VelocityEngine ve = vefb.getObject();
		assertEquals("/mydir", ve.getProperty("myprop"));
		assertEquals(value, ve.getProperty("myentry"));
	}

	public void testVelocityEngineFactoryBeanWithResourceLoaderPath() throws IOException, VelocityException {
		VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
		vefb.setResourceLoaderPath("file:/mydir");
		vefb.afterPropertiesSet();
		assertThat(vefb.getObject(), instanceOf(VelocityEngine.class));
		VelocityEngine ve = vefb.getObject();
		assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
	}

	public void testVelocityEngineFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
		VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
		vefb.setResourceLoaderPath("file:/mydir");
		vefb.setResourceLoader(new ResourceLoader() {
			@Override
			public Resource getResource(String location) {
				if (location.equals("file:/mydir") || location.equals("file:/mydir/test")) {
					return new ByteArrayResource("test".getBytes(), "test");
				}
				try {
					return new UrlResource(location);
				}
				catch (MalformedURLException ex) {
					throw new IllegalArgumentException(ex.toString());
				}
			}
			@Override
			public ClassLoader getClassLoader() {
				return getClass().getClassLoader();
			}
		});
		vefb.afterPropertiesSet();
		assertThat(vefb.getObject(), instanceOf(VelocityEngine.class));
		VelocityEngine ve = vefb.getObject();
		assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap()));
	}

	public void testVelocityConfigurer() throws IOException, VelocityException {
		VelocityConfigurer vc = new VelocityConfigurer();
		vc.setResourceLoaderPath("file:/mydir");
		vc.afterPropertiesSet();
		assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class));
		VelocityEngine ve = vc.createVelocityEngine();
		assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
	}

	public void testVelocityConfigurerWithCsvPath() throws IOException, VelocityException {
		VelocityConfigurer vc = new VelocityConfigurer();
		vc.setResourceLoaderPath("file:/mydir,file:/yourdir");
		vc.afterPropertiesSet();
		assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class));
		VelocityEngine ve = vc.createVelocityEngine();
		Vector paths = new Vector();
		paths.add(new File("/mydir").getAbsolutePath());
		paths.add(new File("/yourdir").getAbsolutePath());
		assertEquals(paths, ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
	}

	public void testVelocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException {
		VelocityConfigurer vc = new VelocityConfigurer();
		vc.setResourceLoaderPath("file:/mydir,file:/yourdir");
		vc.setResourceLoader(new ResourceLoader() {
			@Override
			public Resource getResource(String location) {
				if ("file:/yourdir/test".equals(location)) {
					return new DescriptiveResource("");
				}
				return new ByteArrayResource("test".getBytes(), "test");
			}
			@Override
			public ClassLoader getClassLoader() {
				return getClass().getClassLoader();
			}
		});
		vc.setPreferFileSystemAccess(false);
		vc.afterPropertiesSet();
		assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class));
		VelocityEngine ve = vc.createVelocityEngine();
		assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap()));
	}

}


text:
// Copyright 2009 Jeffrey Cameron
//
// 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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Concordion.Api;
using System.Text.RegularExpressions;
using System.Reflection;

namespace Concordion.Internal.Runner
{
    public class DefaultConcordionRunner : IRunner
    {
        #region Properties

        public ISource Source
        {
            get;
            private set;
        }

        public ITarget Target
        {
            get;
            private set;
        }

        #endregion

        #region Constructors

        public DefaultConcordionRunner(ISource source, ITarget target)
        {
            this.Source = source;
            this.Target = target;
        }

        #endregion

        #region Methods

        private bool IsOnlySuccessfulBecauseItWasExpectedToFail(Type concordionClass)
        {
            //return concordionClass.getAnnotation(ExpectedToFail.class) != null;
            return true;
        }

        #endregion

        #region IRunner Members

        public RunnerResult Execute(object callingFixture, Resource resource, string href)
        {
            var runnerFixture = GetFixture(resource, href, callingFixture);

            var concordion = new ConcordionBuilder()
                                        .WithSource(Source)
                                        .WithTarget(Target)
                                        .Build();

            var results = concordion.Process(runnerFixture);

            Result result;
            if (results.HasFailures)
            {
                result = Result.Failure;
            }
            else if (results.HasExceptions)
            {
                result = Result.Exception;
            }
            else
            {
                result = Result.Success;
            }

		    return new RunnerResult(result);
        }

        private static object GetFixture(Resource resource, string href, object callingFixture)
        {
            var fixtureName = GetNameOfFixtureToRun(resource, href);
            return GetFixtureToRun(callingFixture, fixtureName);
        }

        private static object GetFixtureToRun(object fixture, string fixtureName)
        {
            var fixtureAssembly = fixture.GetType().Assembly;
            var fixtureType = fixtureAssembly.GetType(fixtureName, false, true);

            if (fixtureType != null)
            {
                return Activator.CreateInstance(fixtureType);
            }

            return null;
        }

        private static string GetNameOfFixtureToRun(Resource resource, string href)
        {
            Resource hrefResource = resource.GetRelativeResource(href);
            var fixturePath = hrefResource.Path;
            var fixtureFullyQualifiedPath = fixturePath.Replace("\\", ".");
            var fixtureName = fixtureFullyQualifiedPath.Replace(".html", "Test");

            if (fixtureName.StartsWith("."))
            {
                fixtureName = fixtureName.Remove(0, 1);
            }
            return fixtureName;
        }

        #endregion
    }
}


text:
.. role:: envvar(literal)
.. role:: command(literal)
.. role:: file(literal)
.. _libreference.grids:

grids
^^^^^

.. automodule:: pigasus.fem.grids
.. autoclass:: grids
   :members:

.. Local Variables:
.. mode: rst
.. End:


text:
<project name="XmlTemplate" basedir="." xmlns:swri="http://www.swri.org">
    <macrodef name="initXmlTemplate" uri="http://www.swri.org">
        <sequential>
            <taskdef name="xjc"
                     classname="com.sun.tools.xjc.XJCTask"
                     classpathref="build.class.path"
                     loaderref="ant-loader" />
        </sequential>
    </macrodef>

    <macrodef name="xmlToJava" uri="http://www.swri.org">
        <attribute name="schemaDir" default="${etc.xml.schema.dir}" />
        <attribute name="srcGenDir" default="${build.src.dir}" />
        <sequential>
            <xjc destdir="@{srcGenDir}" binding="${etc.xml.dir}/schema/globalBindings.xjb" extension="true">
                <schema dir="@{schemaDir}">
                    <include name="**/*.xsd" />
                </schema>
            </xjc>
        </sequential>
    </macrodef>
</project>


text: Front End for Stack Undertow


text:
package io.fabric8.quickstarts.springbootmvc;

import org.springframework.boot.SpringApplication;

public class App {

    public static void main(String[] args) {
        new SpringApplication(args).run();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<problems>
  <problem>
    <file>ReplaceAssignmentWithOperatorAssignment.java</file>
    <line>14</line>
    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Assignment replaceable with operator assignment</problem_class>
    <description>x = x + 3 could be simplified to 'x += 3' #loc</description>
  </problem>

  <problem>
    <file>ReplaceAssignmentWithOperatorAssignment.java</file>
    <line>15</line>
    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Assignment replaceable with operator assignment</problem_class>
    <description>x = x * 3 could be simplified to 'x *= 3' #loc</description>
  </problem>

  <problem>
    <file>ReplaceAssignmentWithOperatorAssignment.java</file>
    <line>16</line>
    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Assignment replaceable with operator assignment</problem_class>
    <description>x = x / 3 could be simplified to 'x /= 3' #loc</description>
  </problem>

  <problem>
    <file>ReplaceAssignmentWithOperatorAssignment.java</file>
    <line>17</line>
    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Assignment replaceable with operator assignment</problem_class>
    <description>x = x - 3 could be simplified to 'x -= 3' #loc</description>
  </problem>

  <problem>
    <file>ReplaceAssignmentWithOperatorAssignment.java</file>
    <line>18</line>
    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Assignment replaceable with operator assignment</problem_class>
    <description>x = x + 2 + 2 + 2 could be simplified to 'x += 2 + 2 + 2' #loc</description>
  </problem>

  <problem>
    <file>ReplaceAssignmentWithOperatorAssignment.java</file>
    <line>27</line>
    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Assignment replaceable with operator assignment</problem_class>
    <description>x = x * 2 * 2 could be simplified to 'x *= 2 * 2' #loc</description>
  </problem>

  <problem>
    <file>ReplaceAssignmentWithOperatorAssignment.java</file>
    <line>33</line>
    <entry_point TYPE="method" FQNAME="com.siyeh.igtest.assignment.replace_assignment_with_operator_assignment.ReplaceAssignmentWithOperatorAssignment void foo()" />
    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Assignment replaceable with operator assignment</problem_class>
    <description>(a) = (int)(a + (d - d)) could be simplified to '(a) += (d - d)' #loc</description>
  </problem>
</problems>


text:
package activity;

import android.app.ActionBar;
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import com.wordpress.ninedof.dashboard.R;

import fragment.About;

public class AboutActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_fragment);

		ActionBar ab = getActionBar();
		ab.setTitle("About Dashboard");
		ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.main_colour)));
		ab.setHomeButtonEnabled(true);
	}

	@Override
	protected void onResume() {
		super.onResume();

		getFragmentManager()
            .beginTransaction()
            .replace(R.id.fragment_layout, new fragment.About())
            .commit();
	}
}


text:
package com.lighters.demo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button mNormalGuideBtn;
    private Button mRoundGuideBtn;
    private Button mRectGuideBtn;
    private Button mMenuGuideBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initView();
        initListener();
    }

    private void initView() {
        mNormalGuideBtn = (Button) findViewById(R.id.btn_normal_guide);
        mRectGuideBtn = (Button) findViewById(R.id.btn_rect_guide);
        mRoundGuideBtn = (Button) findViewById(R.id.btn_round_guide);
        mMenuGuideBtn = (Button) findViewById(R.id.btn_menu_guide);
    }

    private void initListener() {
        mNormalGuideBtn.setOnClickListener(mClickListener);
        mRectGuideBtn.setOnClickListener(mClickListener);
        mRoundGuideBtn.setOnClickListener(mClickListener);
        mMenuGuideBtn.setOnClickListener(mClickListener);
    }

    private View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = null;
            switch (v.getId()) {
                case R.id.btn_normal_guide:
                    intent = new Intent(MainActivity.this, GuideNormalActivity.class);
                    startActivity(intent);
                    break;
                case R.id.btn_round_guide:
                    break;
                case R.id.btn_rect_guide:
                    break;
                case R.id.btn_menu_guide:
                    break;
            }
        }
    };
}


text:
'use strict';
const common = require('../common');
if (!common.hasCrypto)
  common.skip('missing crypto');

if (!common.opensslCli)
  common.skip('missing openssl-cli');

const assert = require('assert');
const tls = require('tls');
const exec = require('child_process').exec;
const fs = require('fs');

const options = {
  key: fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`),
  cert: fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`),
  ciphers: 'ECDHE-RSA-AES128-SHA',
  ecdhCurve: false
};

const server = tls.createServer(options, common.mustNotCall());

server.listen(0, '127.0.0.1', common.mustCall(function() {
  let cmd = `"${common.opensslCli}" s_client -cipher ${
    options.ciphers} -connect 127.0.0.1:${this.address().port}`;

  // for the performance and stability issue in s_client on Windows
  if (common.isWindows)
    cmd += ' -no_rand_screen';

  exec(cmd, common.mustCall(function(err, stdout, stderr) {
    // Old versions of openssl will still exit with 0 so we
    // can't just check if err is not null.
    assert(stderr.includes('handshake failure'));
    server.close();
  }));
}));


text:
#include <config.h>

/* Specification.  */
#include <signal.h>

#include <errno.h>
#include <stdint.h>
#include <stdlib.h>

/* We assume that a platform without POSIX signal blocking functions
   also does not have the POSIX sigaction() function, only the
   signal() function.  We also assume signal() has SysV semantics,
   where any handler is uninstalled prior to being invoked.  This is
   true for Woe32 platforms.  */

/* We use raw signal(), but also provide a wrapper rpl_signal() so
   that applications can query or change a blocked signal.  */
#undef signal

/* Provide invalid signal numbers as fallbacks if the uncatchable
   signals are not defined.  */
#ifndef SIGKILL
# define SIGKILL (-1)
#endif
#ifndef SIGSTOP
# define SIGSTOP (-1)
#endif

/* On native Windows, as of 2008, the signal SIGABRT_COMPAT is an alias
   for the signal SIGABRT.  Only one signal handler is stored for both
   SIGABRT and SIGABRT_COMPAT.  SIGABRT_COMPAT is not a signal of its own.  */
#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
# undef SIGABRT_COMPAT
# define SIGABRT_COMPAT 6
#endif
#ifdef SIGABRT_COMPAT
# define SIGABRT_COMPAT_MASK (1U << SIGABRT_COMPAT)
#else
# define SIGABRT_COMPAT_MASK 0
#endif

typedef void (*handler_t) (int);

/* Handling of gnulib defined signals.  */

#if GNULIB_defined_SIGPIPE
static handler_t SIGPIPE_handler = SIG_DFL;
#endif

#if GNULIB_defined_SIGPIPE
static handler_t
ext_signal (int sig, handler_t handler)
{
  switch (sig)
    {
    case SIGPIPE:
      {
        handler_t old_handler = SIGPIPE_handler;
        SIGPIPE_handler = handler;
        return old_handler;
      }
    default: /* System defined signal */
      return signal (sig, handler);
    }
}
# define signal ext_signal
#endif

int
sigismember (const sigset_t *set, int sig)
{
  if (sig >= 0 && sig < NSIG)
    {
      #ifdef SIGABRT_COMPAT
      if (sig == SIGABRT_COMPAT)
        sig = SIGABRT;
      #endif

      return (*set >> sig) & 1;
    }
  else
    return 0;
}

int
sigemptyset (sigset_t *set)
{
  *set = 0;
  return 0;
}

int
sigaddset (sigset_t *set, int sig)
{
  if (sig >= 0 && sig < NSIG)
    {
      #ifdef SIGABRT_COMPAT
      if (sig == SIGABRT_COMPAT)
        sig = SIGABRT;
      #endif

      *set |= 1U << sig;
      return 0;
    }
  else
    {
      errno = EINVAL;
      return -1;
    }
}

int
sigdelset (sigset_t *set, int sig)
{
  if (sig >= 0 && sig < NSIG)
    {
      #ifdef SIGABRT_COMPAT
      if (sig == SIGABRT_COMPAT)
        sig = SIGABRT;
      #endif

      *set &= ~(1U << sig);
      return 0;
    }
  else
    {
      errno = EINVAL;
      return -1;
    }
}

int
sigfillset (sigset_t *set)
{
  *set = ((2U << (NSIG - 1)) - 1) & ~ SIGABRT_COMPAT_MASK;
  return 0;
}

/* Set of currently blocked signals.  */
static volatile sigset_t blocked_set /* = 0 */;

/* Set of currently blocked and pending signals.  */
static volatile sig_atomic_t pending_array[NSIG] /* = { 0 } */;

/* Signal handler that is installed for blocked signals.  */
static void
blocked_handler (int sig)
{
  /* Reinstall the handler, in case the signal occurs multiple times
     while blocked.  There is an inherent race where an asynchronous
     signal in between when the kernel uninstalled the handler and
     when we reinstall it will trigger the default handler; oh
     well.  */
  signal (sig, blocked_handler);
  if (sig >= 0 && sig < NSIG)
    pending_array[sig] = 1;
}

int
sigpending (sigset_t *set)
{
  sigset_t pending = 0;
  int sig;

  for (sig = 0; sig < NSIG; sig++)
    if (pending_array[sig])
      pending |= 1U << sig;
  *set = pending;
  return 0;
}

/* The previous signal handlers.
   Only the array elements corresponding to blocked signals are relevant.  */
static volatile handler_t old_handlers[NSIG];

int
sigprocmask (int operation, const sigset_t *set, sigset_t *old_set)
{
  if (old_set != NULL)
    *old_set = blocked_set;

  if (set != NULL)
    {
      sigset_t new_blocked_set;
      sigset_t to_unblock;
      sigset_t to_block;

      switch (operation)
        {
        case SIG_BLOCK:
          new_blocked_set = blocked_set | *set;
          break;
        case SIG_SETMASK:
          new_blocked_set = *set;
          break;
        case SIG_UNBLOCK:
          new_blocked_set = blocked_set & ~*set;
          break;
        default:
          errno = EINVAL;
          return -1;
        }
      to_unblock = blocked_set & ~new_blocked_set;
      to_block = new_blocked_set & ~blocked_set;

      if (to_block != 0)
        {
          int sig;

          for (sig = 0; sig < NSIG; sig++)
            if ((to_block >> sig) & 1)
              {
                pending_array[sig] = 0;
                if ((old_handlers[sig] = signal (sig, blocked_handler)) != SIG_ERR)
                  blocked_set |= 1U << sig;
              }
        }

      if (to_unblock != 0)
        {
          sig_atomic_t received[NSIG];
          int sig;

          for (sig = 0; sig < NSIG; sig++)
            if ((to_unblock >> sig) & 1)
              {
                if (signal (sig, old_handlers[sig]) != blocked_handler)
                  /* The application changed a signal handler while the signal
                     was blocked, bypassing our rpl_signal replacement.
                     We don't support this.  */
                  abort ();
                received[sig] = pending_array[sig];
                blocked_set &= ~(1U << sig);
                pending_array[sig] = 0;
              }
            else
              received[sig] = 0;

          for (sig = 0; sig < NSIG; sig++)
            if (received[sig])
              raise (sig);
        }
    }
  return 0;
}

/* Install the handler FUNC for signal SIG, and return the previous
   handler.  */
handler_t
rpl_signal (int sig, handler_t handler)
{
  /* We must provide a wrapper, so that a user can query what handler
     they installed even if that signal is currently blocked.  */
  if (sig >= 0 && sig < NSIG && sig != SIGKILL && sig != SIGSTOP
      && handler != SIG_ERR)
    {
      #ifdef SIGABRT_COMPAT
      if (sig == SIGABRT_COMPAT)
        sig = SIGABRT;
      #endif

      if (blocked_set & (1U << sig))
        {
          /* POSIX states that sigprocmask and signal are both
             async-signal-safe.  This is not true of our
             implementation - there is a slight data race where an
             asynchronous interrupt on signal A can occur after we
             install blocked_handler but before we have updated
             old_handlers for signal B, such that handler A can see
             stale information if it calls signal(B).  Oh well -
             signal handlers really shouldn't try to manipulate the
             installed handlers of unrelated signals.  */
          handler_t result = old_handlers[sig];
          old_handlers[sig] = handler;
          return result;
        }
      else
        return signal (sig, handler);
    }
  else
    {
      errno = EINVAL;
      return SIG_ERR;
    }
}

#if GNULIB_defined_SIGPIPE
/* Raise the signal SIG.  */
int
rpl_raise (int sig)
# undef raise
{
  switch (sig)
    {
    case SIGPIPE:
      if (blocked_set & (1U << sig))
        pending_array[sig] = 1;
      else
        {
          handler_t handler = SIGPIPE_handler;
          if (handler == SIG_DFL)
            exit (128 + SIGPIPE);
          else if (handler != SIG_IGN)
            (*handler) (sig);
        }
      return 0;
    default: /* System defined signal */
      return raise (sig);
    }
}
#endif


text:
#include <sandesha2_report.h>
#include <sandesha2_seq_report.h>
#include <axutil_log.h>

/**
 * @brief Sandesha Sequence Report Struct Impl
 *   Sandesha Sequence Report
 */
struct sandesha2_report
{
    axutil_array_list_t *incoming_seq_list;
    axutil_array_list_t *outgoing_seq_list;
    axutil_hash_t *seq_status_map;
    axutil_hash_t *no_of_completed_msgs_map;
    axutil_hash_t *outgoing_internal_seq_id_map;
};

#define SANDESHA2_INTF_TO_IMPL(report) ((sandesha2_report_t *) report)

AXIS2_EXTERN sandesha2_report_t * AXIS2_CALL
sandesha2_report_create(
    const axutil_env_t *env)
{
    sandesha2_report_t *report = NULL;
    AXIS2_ENV_CHECK(env, NULL);
    report = AXIS2_MALLOC(env->allocator,
        sizeof(sandesha2_report_t));

    report->incoming_seq_list = NULL;
    report->outgoing_seq_list = NULL;
    report->seq_status_map = NULL;
    report->no_of_completed_msgs_map = NULL;
    report->outgoing_internal_seq_id_map = NULL;

    report->incoming_seq_list = axutil_array_list_create(env, 0);
    report->outgoing_seq_list = axutil_array_list_create(env, 0);
    if(!report->incoming_seq_list ||
       !report->outgoing_seq_list)
    {
        AXIS2_ERROR_SET(env->error, AXIS2_ERROR_NO_MEMORY, AXIS2_FAILURE);
        return NULL;
    }
    report->seq_status_map = axutil_hash_make(env);
    report->no_of_completed_msgs_map = axutil_hash_make(env);
    report->outgoing_internal_seq_id_map = axutil_hash_make(env);
    if(!report->seq_status_map ||
        !report->no_of_completed_msgs_map ||
        !report->outgoing_internal_seq_id_map)
    {
        AXIS2_ERROR_SET(env->error, AXIS2_ERROR_NO_MEMORY, AXIS2_FAILURE);
        return NULL;
    }

    return report;
}

AXIS2_EXTERN axis2_status_t AXIS2_CALL
sandesha2_report_free(
    void *rep,
    const axutil_env_t *env)
{
    sandesha2_report_t *report = (sandesha2_report_t *) rep;
    AXIS2_ENV_CHECK(env, AXIS2_FAILURE);

    if(report->incoming_seq_list)
    {
        axutil_array_list_free(report->incoming_seq_list, env);
        report->incoming_seq_list = NULL;
    }

    if(report->outgoing_seq_list)
    {
        axutil_array_list_free(report->outgoing_seq_list, env);
        report->outgoing_seq_list = NULL;
    }

    if(report->seq_status_map)
    {
        axutil_hash_free(report->seq_status_map, env);
        report->seq_status_map = NULL;
    }

    if(report->no_of_completed_msgs_map)
    {
        axutil_hash_free(report->no_of_completed_msgs_map, env);
        report->no_of_completed_msgs_map = NULL;
    }

    if(report->outgoing_internal_seq_id_map)
    {
        axutil_hash_free(report->outgoing_internal_seq_id_map, env);
        report->outgoing_internal_seq_id_map = NULL;
    }

    if(report)
    {
        AXIS2_FREE(env->allocator, report);
        report = NULL;
    }
    return AXIS2_SUCCESS;
}

AXIS2_EXTERN long AXIS2_CALL
sandesha2_report_get_completed_msgs_count(
    sandesha2_report_t *report,
    const axutil_env_t *env,
    axis2_char_t *seq_id)
{
    long *lng = NULL;
    lng = (long *)axutil_hash_get(report->no_of_completed_msgs_map, seq_id,
        AXIS2_HASH_KEY_STRING);
    if(!lng)
    {
        return -1;
    }
    return *lng;
}

AXIS2_EXTERN axutil_array_list_t *AXIS2_CALL
sandesha2_report_get_incoming_seq_list(
    sandesha2_report_t *report,
    const axutil_env_t *env)
{
    return report->incoming_seq_list;
}

AXIS2_EXTERN axutil_array_list_t *AXIS2_CALL
sandesha2_report_get_outgoing_seq_list(
    sandesha2_report_t *report,
    const axutil_env_t *env)
{
    return report->outgoing_seq_list;
}

AXIS2_EXTERN axis2_char_t AXIS2_CALL
sandesha2_report_get_seq_status_map(
    sandesha2_report_t *report,
    const axutil_env_t *env,
    axis2_char_t *seq_id)
{
    axis2_char_t *status = NULL;

    status = (axis2_char_t *) axutil_hash_get(report->seq_status_map,
        seq_id, AXIS2_HASH_KEY_STRING);
    if(!status)
        return SANDESHA2_SEQ_STATUS_UNKNOWN;
    return *status;
}

AXIS2_EXTERN axis2_status_t AXIS2_CALL
sandesha2_report_add_to_incoming_seq_list(
    sandesha2_report_t *report,
    const axutil_env_t *env,
    axis2_char_t *incoming_seq_id)
{
    AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
    axutil_array_list_add(report->incoming_seq_list, env, incoming_seq_id);
    return AXIS2_SUCCESS;
}

AXIS2_EXTERN axis2_status_t AXIS2_CALL
sandesha2_report_add_to_outgoing_seq_list(
    sandesha2_report_t *report,
    const axutil_env_t *env,
    axis2_char_t *out_seq_id)
{
    AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
    axutil_array_list_add(report->outgoing_seq_list, env, out_seq_id);
    return AXIS2_SUCCESS;
}

AXIS2_EXTERN axis2_status_t AXIS2_CALL
sandesha2_report_add_to_no_of_completed_msgs_map(
    sandesha2_report_t *report,
    const axutil_env_t *env,
    axis2_char_t *id,
    long no_of_msgs)
{
    long *no_of_msgs_l = AXIS2_MALLOC(env->allocator, sizeof(long));
    *no_of_msgs_l = no_of_msgs;
    axutil_hash_set(report->no_of_completed_msgs_map, id,
        AXIS2_HASH_KEY_STRING, no_of_msgs_l);
    return AXIS2_SUCCESS;
}

AXIS2_EXTERN axis2_status_t AXIS2_CALL
sandesha2_report_add_to_seq_status_map(
    sandesha2_report_t *report,
    const axutil_env_t *env,
    axis2_char_t *id,
    axis2_char_t status)
{
    axutil_hash_set(report->seq_status_map, id,
        AXIS2_HASH_KEY_STRING, &status);
    return AXIS2_SUCCESS;
}

AXIS2_EXTERN axis2_char_t *AXIS2_CALL
sandesha2_report_get_internal_seq_id_of_out_seq(
    sandesha2_report_t *report,
    const axutil_env_t *env,
    axis2_char_t *out_seq_id)
{
    return (axis2_char_t *) axutil_hash_get(
        report->outgoing_internal_seq_id_map, out_seq_id,
        AXIS2_HASH_KEY_STRING);
}

AXIS2_EXTERN axis2_status_t AXIS2_CALL
sandesha2_report_add_to_outgoing_internal_seq_map(
    sandesha2_report_t *report,
    const axutil_env_t *env,
    axis2_char_t *out_seq_id,
    axis2_char_t *internal_seq_id)
{
    axutil_hash_set(report->outgoing_internal_seq_id_map, out_seq_id,
        AXIS2_HASH_KEY_STRING, internal_seq_id);
    return AXIS2_SUCCESS;
}


text:
function Export-AzureRmContext {
    [CmdletBinding()]
    param (

    )

    begin {
    }

    process {
        $ContextClassic = [bool] (Get-Command -Name Save-AzureRmProfile -ErrorAction SilentlyContinue) # returns TRUE if AzureRM.profile version 2.7 or older is loaded
        $ContextPath = [System.IO.Path]::ChangeExtension($PSCommandPath, '.ctx')

        if (Test-Path $ContextPath -PathType Leaf) {
            "Removing orphan Azure context ($ContextPath) ..."
            Remove-Item -Path $ContextPath -Force | Out-Null
        }

        "Persist Azure context to '$ContextPath' ..."
        if ($ContextClassic) { Save-AzureRmProfile -Path $ContextPath } else { Save-AzureRmContext -Path $ContextPath -Force }
    }

    end {
    }
}

function Import-AzureRmContext {
    [CmdletBinding()]
    param (
    )

    begin {
    }

    process {
        $ContextClassic = [bool] (Get-Command -Name Save-AzureRmProfile -ErrorAction SilentlyContinue) # returns TRUE if AzureRM.profile version 2.7 or older is loaded
        $ContextPath = [System.IO.Path]::ChangeExtension($PSCommandPath, '.ctx')
        "Loading Azure context from '$ContextPath' ..."
        if  ($contextClassic) {
            Select-AzureRMProfile -Path $ContextPath
        } else {
            Import-AzureRmContext -Path $ContextPath
        }
    }

    end {
    }
}

function New-DTLPackerImage {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string] $PackerFile,

        [Parameter(Mandatory=$false)]
        [hashtable] $PackerVariables
    )

    begin {
    }

    process {

        $varFile = $(Split-Path ([System.IO.Path]::ChangeExtension($PackerFile, ".var")) -Leaf)
        $logFile = $(Split-Path ([System.IO.Path]::ChangeExtension($PackerFile, ".log")) -Leaf)

        try {

            Push-Location (Split-Path $PackerFile -Parent);

            if ($PackerVariables) {

                $PackerVariables | ConvertTo-Json | Out-File $varFile -Force

                packer build -var-file="$varFile" "$(Split-Path $PackerFile -Leaf)" | Tee-Object $logFile -Append

            } else {

                packer build "$(Split-Path $PackerFile -Leaf)" | Tee-Object $logFile -Append
            }
        }
        finally {

            Remove-Item $varFile -Force -ErrorAction SilentlyContinue | Out-Null
            Remove-Item $logFile -Force -ErrorAction SilentlyContinue | Out-Null

            Pop-Location
        }
    }

    end {
    }
}

Export-ModuleMember -Function Push-PackerImageToDTLCustomImages


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.core.validators

class Migration(migrations.Migration):

    dependencies = [
        ('taskmanager', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Project',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(verbose_name='name', help_text='Enter the project name', max_length=100)),
                ('color', models.CharField(verbose_name='color', help_text='Enter the hex color code, like #ccc or #cccccc', default='#fff', max_length=7, validators=[django.core.validators.RegexValidator('(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)')])),
                ('user', models.ForeignKey(related_name='projects', verbose_name='name', to='taskmanager.Profile')),
            ],
            options={
                'verbose_name': 'Project',
                'verbose_name_plural': 'Projects',
                'ordering': ('user', 'name'),
            },
        ),
        migrations.AlterUniqueTogether(
            name='project',
            unique_together=set([('user', 'name')]),
        ),
    ]


text:
namespace printing {

// True if this is the first preview request.
const char kIsFirstRequest[] = "isFirstRequest";

// Unique ID sent along every preview request.
const char kPreviewRequestID[] = "requestID";

// Unique ID to identify a print preview UI.
const char kPreviewUIID[] = "previewUIID";

// Capabilities option. Contains the capabilities in CDD format.
const char kSettingCapabilities[] = "capabilities";

// Print using cloud print: true if selected, false if not.
const char kSettingCloudPrintId[] = "cloudPrintID";

// Print job setting 'collate'.
const char kSettingCollate[] = "collate";

// Print out color. Value is an int from ColorModel enum.
const char kSettingColor[] = "color";

// Default to color on or not.
const char kSettingSetColorAsDefault[] = "setColorAsDefault";

// Key that specifies the height of the content area of the page.
const char kSettingContentHeight[] = "contentHeight";

// Key that specifies the width of the content area of the page.
const char kSettingContentWidth[] = "contentWidth";

// Number of copies.
const char kSettingCopies[] = "copies";

// Device name: Unique printer identifier.
const char kSettingDeviceName[] = "deviceName";

// Option to disable scaling. True if scaling is disabled else false.
const char kSettingDisableScaling[] = "disableScaling";

// Default DPI
const char kSettingDpiDefault[] = "dpiDefault";

// Horizontal DPI
const char kSettingDpiHorizontal[] = "dpiHorizontal";

// Vertical DPI
const char kSettingDpiVertical[] = "dpiVertical";

// Scaling value required to fit the document to page.
const char kSettingFitToPageScaling[] = "fitToPageScaling";

// Print job duplex mode. Value is an int from DuplexMode enum.
const char kSettingDuplexMode[] = "duplex";

// Option to print headers and Footers: true if selected, false if not.
const char kSettingHeaderFooterEnabled[] = "headerFooterEnabled";

// Interstice or gap between different header footer components. Hardcoded to
// about 0.5cm, match the value in PrintSettings::SetPrinterPrintableArea.
const float kSettingHeaderFooterInterstice = 14.2f;

// Key that specifies the date of the page that will be printed in the headers
// and footers.
const char kSettingHeaderFooterDate[] = "date";

// Key that specifies the title of the page that will be printed in the headers
// and footers.
const char kSettingHeaderFooterTitle[] = "title";

// Key that specifies the URL of the page that will be printed in the headers
// and footers.
const char kSettingHeaderFooterURL[] = "url";

// Page orientation: true for landscape, false for portrait.
const char kSettingLandscape[] = "landscape";

// Key that specifies the requested media size.
const char kSettingMediaSize[] = "mediaSize";

// Key that specifies the requested media height in microns.
const char kSettingMediaSizeHeightMicrons[] = "height_microns";

// Key that specifies the requested media width in microns.
const char kSettingMediaSizeWidthMicrons[] = "width_microns";

// Key that specifies the requested media platform specific vendor id.
const char kSettingMediaSizeVendorId[] = "vendor_id";

// Key that specifies whether the requested media is a default one.
const char kSettingMediaSizeIsDefault[] = "is_default";

// Key that specifies the bottom margin of the page.
const char kSettingMarginBottom[] = "marginBottom";

// Key that specifies the left margin of the page.
const char kSettingMarginLeft[] = "marginLeft";

// Key that specifies the right margin of the page.
const char kSettingMarginRight[] = "marginRight";

// Key that specifies the top margin of the page.
const char kSettingMarginTop[] = "marginTop";

// Key that specifies the dictionary of custom margins as set by the user.
const char kSettingMarginsCustom[] = "marginsCustom";

// Key that specifies the type of margins to use.  Value is an int from the
// MarginType enum.
const char kSettingMarginsType[] = "marginsType";

// Number of pages to print.
const char kSettingPreviewPageCount[] = "pageCount";

// A page range.
const char kSettingPageRange[] = "pageRange";

// The first page of a page range. (1-based)
const char kSettingPageRangeFrom[] = "from";

// The last page of a page range. (1-based)
const char kSettingPageRangeTo[] = "to";

// Page size of document to print.
const char kSettingPageWidth[] = "pageWidth";
const char kSettingPageHeight[] = "pageHeight";

// PIN code entered by the user.
const char kSettingPinValue[] = "pinValue";

// Policies affecting printing destination.
const char kSettingPolicies[] = "policies";

// Whether the source page content is from ARC or not.
const char kSettingPreviewIsFromArc[] = "previewIsFromArc";

// Whether the source page content is PDF or not.
const char kSettingPreviewIsPdf[] = "previewIsPdf";

// Whether the source page content is modifiable. True for web content.
// i.e. Anything from Blink. False for everything else. e.g. PDF/Flash.
const char kSettingPreviewModifiable[] = "previewModifiable";

// Keys that specifies the printable area details.
const char kSettingPrintableAreaX[] = "printableAreaX";
const char kSettingPrintableAreaY[] = "printableAreaY";
const char kSettingPrintableAreaWidth[] = "printableAreaWidth";
const char kSettingPrintableAreaHeight[] = "printableAreaHeight";

// Printer description.
const char kSettingPrinterDescription[] = "printerDescription";

// Printer name.
const char kSettingPrinterName[] = "printerName";

// Additional printer options.
const char kSettingPrinterOptions[] = "printerOptions";

// The printer type is an enum PrinterType.
const char kSettingPrinterType[] = "printerType";

// Print to Google Drive option: true if selected, false if not.
const char kSettingPrintToGoogleDrive[] = "printToGoogleDrive";

// Scaling factor
const char kSettingScaleFactor[] = "scaleFactor";

// Scaling type
const char kSettingScalingType[] = "scalingType";

// Number of pages per sheet.
const char kSettingPagesPerSheet[] = "pagesPerSheet";

// Whether to rasterize the PDF for printing.
const char kSettingRasterizePdf[] = "rasterizePDF";

// Ticket option. Contains the ticket in CJT format.
const char kSettingTicket[] = "ticket";

// Whether to sent user info to the printer.
const char kSettingSendUserInfo[] = "sendUserInfo";

// Whether to print CSS backgrounds.
const char kSettingShouldPrintBackgrounds[] = "shouldPrintBackgrounds";

// Whether to print selection only.
const char kSettingShouldPrintSelectionOnly[] = "shouldPrintSelectionOnly";

// Whether to print using the system dialog.
const char kSettingShowSystemDialog[] = "showSystemDialog";

// Username to be sent to printer.
const char kSettingUsername[] = "username";

// Advanced settings items.
const char kSettingAdvancedSettings[] = "advancedSettings";

// Indices used to represent first preview page and complete preview document.
const int FIRST_PAGE_INDEX = 0;
const int COMPLETE_PREVIEW_DOCUMENT_INDEX = -1;

// Whether to show PDF in view provided by OS. Implemented for MacOS only.
const char kSettingOpenPDFInPreview[] = "OpenPDFInPreview";

#if defined(USE_CUPS)
const char kBlack[] = "Black";
const char kCMYK[] = "CMYK";
const char kKCMY[] = "KCMY";
const char kCMY_K[] = "CMY+K";
const char kCMY[] = "CMY";
const char kColor[] = "Color";
const char kFullColor[] = "FullColor";
const char kGray[] = "Gray";
const char kGrayscale[] = "Grayscale";
const char kGreyscale[] = "Greyscale";
const char kMono[] = "Mono";
const char kMonochrome[] = "Monochrome";
const char kNormal[] = "Normal";
const char kNormalGray[] = "Normal.Gray";
const char kRGB[] = "RGB";
const char kRGBA[] = "RGBA";
const char kRGB16[] = "RGB16";
const char kSharpCMColor[] = "CMColor";
const char kSharpCMBW[] = "CMBW";
const char kXeroxAutomatic[] = "Automatic";
const char kXeroxBW[] = "BW";
#endif

}  // namespace printing


text:
module Nightlight
  module PagesHelper

    def avg_page_brightness pages
      if pages.any?
        avg = pages.map(&:brightness).sum.to_f / pages.size.to_f
        avg.to_i
      else
        0
      end
    end

    def link_to_page page
      path = page.sample_path.presence || page.path
      link_to page.path, path, target: '_blank'
    end

    def last_checked_at page, opts={}
      lead = opts[:short] ? "" : "last checked "
      time =
        if page.last_checked_at
          "#{time_ago_in_words(page.last_checked_at)} ago"
        else
          "??"
        end
      "#{lead}#{time}"
    end

  end
end


text:
package com.sequenceiq.cloudbreak.cloud.handler;

import reactor.bus.Event;
import reactor.fn.Consumer;

public interface CloudPlatformEventHandler<T> extends Consumer<Event<T>> {

    Class<T> type();

}


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FILE      : Eval/evalbat.pl
%
%       Basic Action Projector (BAT)
%
%  AUTHOR : Sebastian Sardina (prev. Hector Levesque & Maurice Pagnucco)
%  EMAIL  : ssardina@cs.toronto.edu
%  WWW    : www.cs.toronto.edu/~ssardina www.cs.toronto.edu/cogrobo
%  TYPE   : system independent code
%  TESTED : SWI Prolog 5.0.10 http://www.swi-prolog.org
%           ECLIPSE 5.4 http://www.icparc.ic.ac.uk/eclipse/
%
%  This file allows for the projection of conditions wrt
%  basic action theories.
%
%  The main tool provided in this file is the following predicate:
%
% -- eval(P,H,B):  B=true/false/unknown is the truth value of P at history H
%
%           For more information on Golog and some of its variants, see:
%               http://www.cs.toronto.edu/~cogrobo/
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%                             March, 2002
%
% This software was developed by the Cognitive Robotics Group under the
% direction of Hector Levesque and Ray Reiter.
%
%        Do not distribute without permission.
%        Include this notice in any copy made.
%
%
%         Copyright (c) 2000 by The University of Toronto,
%                        Toronto, Ontario, Canada.
%
%                          All Rights Reserved
%
% Permission to use, copy, and modify, this software and its
% documentation for non-commercial research purpose is hereby granted
% without fee, provided that the above copyright notice appears in all
% copies and that both the copyright notice and this permission notice
% appear in supporting documentation, and that the name of The University
% of Toronto not be used in advertising or publicity pertaining to
% distribution of the software without specific, written prior
% permission.  The University of Toronto makes no representations about
% the suitability of this software for any purpose.  It is provided "as
% is" without express or implied warranty.
%
% THE UNIVERSITY OF TORONTO DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
% SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS, IN NO EVENT SHALL THE UNIVERSITY OF TORONTO BE LIABLE FOR ANY
% SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
% RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
% CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
% CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This file provides the following:
%
% -- eval(P, H, B)  (MAIN PREDICATE, used by the transition system)
%           B is the truth value of P at history H
%
% SYSTEM TOOLS (used by the top-level cycle)::
%
% -- initializeDB/0
%           initialize the projector
% -- finalizeDB/0
%           finalize the projector
% -- can_roll(+H1)
%       check if the DB CAN roll forward
% -- must_roll(+H1)
%       check if the DB MUST roll forward
% -- roll_db(+H1,-H2)
%       perform roll forward with current history H1 and new history H2
% -- handle_sensing(+A, +H, +S, -H2)
%           H2 is H plus action A with sensing result S
% -- debug(+A, +H, -S)
%           perform debug tasks with current action A, sensing outcome S,
%           and history H
% -- system_action(+A)
%           action A is an action used by the system (e.g., action outcomes e(_,_))
%
%
% OTHER TOOLS (used by the transition system)::
%
% -- sensing(+A, -L)
%           action A is a sensing action with a list L of possible outcomes
% -- sensed(+A, +S, +H)
%           action A, when executed at history H, got sensing result S
% -- inconsistent(+H)
%           last action turned history H inconsistent, i.e., impossible
% -- domain(-V, +D)
%           object V is an element of domain D
% -- rdomain(-V, +D)
%           object V is an element of domain D (random)
% -- getdomain(+D, -L)
%            L is the list representing domain D
% -- calc_arg(+A1, -A2, +H)
%           action A2 is action A1 with its arguments replaced wrt history H
% -- before(+H1, +H2)
%           history H1 is a previous history of H2
% -- assume(+F, +V, +H1, -H2)
%           H2 is the history resulting from assuming fluent F to
%           have value V at history H1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  A basic action theory (BAT) is described with:
%
% -- fun_fluent(fluent)     : for each functional fluent (non-ground)
%								(at least 1 clause is required)
% -- rel_fluent(fluent)     : for each relational fluent (non-ground)
%								(at least 1 clause is required)
% -- cache(fluent)          : fluent should be cached (at least 1) MANDATORY
%
%           e.g., rel_fluent(painted(C)).
%           e.g., fun_fluent(color(C)).
%
% -- prim_action(action)    : for each primitive action (ground)
% -- exog_action(action)    : for each exogenous action (ground)
%
%           e.g., prim_action(clean(C)) :- domain(C,country).
%           e.g., exog_action(painte(C,B)):- domain(C,country), domain(B,color).
%
% -- senses(action,fluent)  : for each sensing action that senses fluent directly
%
%           e.g, senses(check_painted(C),  painted(C)).
%           e.g, senses(senseTemperature,  temp).
%
% -- senses(action,outcome,fluent,value,cond) :
%			for each sensing action that senses fluent *indirectly*
%
%           e.g, senses(senseTemperature, T, temp, T, true).
%				: equivalent to senses(senseTemperature,  temp).
%           e.g, senses(senseTemperature, T, temp, T2, T2 is T+10).
%           e.g, senses(senseTemperature, T, isHot, true,  T>30).
%           e.g, senses(senseTemperature, T, isHot, false, T<=30).
%
% -- forget(action,fluent)  : action makes fluent unknown
%
%           e.g, poss(checkFloor,  lightFloor).
% -- poss(action,cond)      : when cond, action is executable
%
%           e.g, poss(clean(C),   and(painted(C),holding(cleanear))).
%
% -- initially(fluent,value): fluent has value in S0 (ground)
%								(at least 1 clause is required)
%
%          e.g., initially(painted(C), false):- domain(C,country), C\=3.
%                initially(painted(3), true).
%                initially(color(3), blue).
%
% -- causes_val(action,fluent,value,cond)
%          when cond holds, doing act causes functional fluent to have value
%
%            e.g., causes_val(paint(C2,V), color(C), V, C = C2).
%               or causes_val(paint(C,V), color(C), V, true).
%
% -- causes_true(action,fluent,cond)
%          when cond holds, doing act causes relational fluent to hold
% -- causes_false(action,fluent,cond)
%          when cond holds, doing act causes relational fluent to not hold
%
%            e.g., causes_true(paint(C2,_), painted(C), C = C2).
%               or causes_true(paint(C,_), painted(C), true).
%            e.g., causes_false(clean(C2),  painted(C), C = C2).
%               or causes_false(clean(C),  painted(C), true).
%
% -- sort-name(domain_of_sort).      : defines a sort
%        e.g., color([blue, green, yellow, red]).
%              temperature([-30..45]).
%
%
% A high-level program-controller is described with:
%
% -- proc(name,P): for each procedure P
% -- simulator(N,P): P is the N exogenous action simulator
%
% The interface for real-world execution is described with:
%
% -- actionNum(action, num)
%         action has RCX code num
% -- simulateSensing(action)
%         sensing result for action should be asked to the user
% -- translateSensing(action, sensorValue, sensorResult)
%         translate the sensorValue of action to sensorResult
% -- translateExogAction(codeAction, action)
%         translateSensing action name into codeAction and vice-versa
%
% Requirements:
%
% -- is_list(+L) : L is a list
% -- subv(X1,X2,T1,T2) :  T2 is T1 with X1 replaced by X2
% -- multifile/1
% -- get0/1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% :- module(evalbat,
%%           [eval/3,
%%            initializeDB/0,
%%            finalizeDB/0,
%%            handle_sensing/4,
%%            sensing/2,
%%            sensed/3,
%%            domain/2,
%%            getdomain/2,
%%            calc_arg/3,
%%            before/2,
%%            inconsistent/1,
%%            assume/4
%%           ]).
%%
%% :- use_module(library(quintus)).

:- dynamic
   currently/2,	% Used to store the actual initial fluent values
   simulator/2,	% There may be no simulator
   senses/2,
   senses/5,	% There may be no sensing action
   forget/2,	% There may be no action that "forgets" a fluent
   has_valc/3.	% used for caching some values

% Predicates that they have definitions here but they can defined elsewhere
:- multifile(prim_action/1).
:- multifile(causes_val/4).
%:- multifile(causes_true/3).
%:- multifile(causes_false/3).
%:- multifile(exog_action/1).
:- multifile(poss/2).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  PREDICATES TO BE EXPORTED
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

   /* Move initially(-,-) to currently(-,-) and clear exog actions  */
initializeDB:-
	retractall(currently(_,_)),
	initially(F,V),
	assert(currently(F,V)),
	clean_cache,
	fail.
initializeDB.

  /* Clean all the currently(-.-) predicates */
%finalizeDB:-  retractall(currently(_,_)), clean_cache.
finalizeDB.

% eval(P,H,B): this is the interface of the projector
eval(P,H,true):- holds(P,H).

% Change the history H to encode the sensing result of action A at H
%handle_sensing(A,H,Sr,[e(F,Sr)|H]):- senses(A,F). (OLD WAY)
handle_sensing(A,H,Sr,[e(A,Sr)|H]).

% clean_cache: remove all has_valc/3
clean_cache :- retractall(has_valc(_,_,_)).

% Set F to value V at H, return H1 (add e(F,V) to history H)
assume(F,V,H,[e(F,V)|H]).

% system_action/1 defines actions that are used by the projector for managment
system_action(e(_,_)).

% Action A is a sensing action
sensing(A,_):- senses(A,_) ; senses(A, _, _, _, _).

% sensed(+A,?V,+H): action A got sensing result V w.r.t. history H
sensed(A,V,[e(F,V2)|_]):- senses(A,F), !, V=V2.
sensed(A,V,[_|H])      :- sensed(A,V,H).

% domain/2: assigns a user-defined domain to a variable.
domain(V, D)  :- getdomain(D, L), member(V, L).
rdomain(V, D) :- getdomain(D, L), shuffle(L,L2), !, member(V, L2).

% L is the list-domain associated to name D
getdomain(D, L) :- is_list(D) -> L=D ; (P =.. [D,L], call(P)).

% Computes the arguments of an action or a fluent P
% Action/Fluent P1 is action/fluent P with all arguments evaluated
calc_arg(P,P1,H):- (is_an_action(P) ; prim_fluent(P)),
	(atomic(P)-> P1=P ;
                    (P =..[Function|LArg], subfl(LArg,LArg2,H),
                     P1=..[Function|LArg2])).

% History H1 is a previous history of H2
before(H1,H2):- append(_,H1,H2).

% No action can make a history inconsistent (simplification)
inconsistent(_):- fail.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  OTHER PREDICATES NEEDED BUT NOT EXPORTED
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% A primitive fluent is either a relational or a functional fluent
prim_fluent(P):- rel_fluent(P) ; fun_fluent(P).

% Check if A has "the form" of a primitive action, though, its arguments
% may need to be evaluated yet
% We need to do  this hack because actions are defined all ground
is_an_action(A):- \+ \+ (prim_action(A) ; exog_action(A)), !.
is_an_action(A):- \+ atomic(A),
	           A =..[F|Arg], length(Arg,LArg), length(ArgV,LArg),
                   NA =..[F|ArgV], (prim_action(NA) ; exog_action(A)).

% Simulation of an action A has the same effects as action A itself
causes_val(sim(A),F,V,C)  :- !, causes_val(A,F,V,C).

% Build causes_val/4 for relational fluents
causes_val(A,F,true,C)  :- causes_true(A,F,C).
causes_val(A,F,false,C) :- causes_false(A,F,C).

% Abort if P is not grounded (to use before negations as failure)
checkgr(P):- ground(P)-> true ; once(warn(['CWA applied to formula: ',P])).

% Update the cache information by stripping out the subhistory H
update_cache(H) :-
	retract(has_valc(F, V, H2)),
	append(H1, H, H2),
	assert(has_valc(F, V, H1)),
	fail.
update_cache(_).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  HOLDS - Here starts the evaluation procedure for projection
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% kwhether(F,H): fluent F is known true or false in H
% Assumes that after sensing F, F may change but it will remain known
% We may probably want to add some "forgeting" mechanism.. either by a
%      state condition or special actions
holds(kwhether(F),[])     :- !, initially(F,_).
holds(kwhether(F),[Act|_]):- (senses(Act,F) ; Act=e(F,_)), !.
holds(kwhether(F),[_|H])  :- holds(kwhether(F),H).

% know(F): Fluent F evaluates to something
holds(know(F),H)     :- !, holds(F=_,H).

% holds(P,H): P holds in H
holds(and(P1,P2),H)	:- !, holds(P1,H), holds(P2,H).
holds(or(P1,P2),H)	:- !, (holds(P1,H) ; holds(P2,H)).
holds(neg(P),H)	:- !, checkgr(P), \+ holds(P,H). /* Negation by failure */
holds(some([],P),H)	:- !, holds(P,H).
holds(some([V|L],P),H)	:- !, holds(some(V,some(L,P)), H).
holds(some([],P),H)	:- !, holds(P,H).
holds(some([V|L],P),H)	:- !, holds(some(V,some(L,P)), H).
holds(some(V,P),H)	:- !, subv(V,_,P,P1), holds(P1,H).
holds(some((V,D),P),H) :- !, domain(O,D), subv(V,O,P,P1), holds(P1,H).
holds(all([],P),H)	:- !, holds(P, H).
holds(all([V|L],P),H)	:- !, holds(all(V,all(L,P)), H).
holds(all((V,D),P),H)	:- !, holds(neg(some(V,D),neg(P)), H).
holds(impl(P1,P2),H) :- !, holds(or(neg(P1),P2),H).
holds(P,H) :- proc(P,P1), !, (ground(P) -> (holds(P1,H), !) ; holds(P1,H)).
holds(P,H) :- ground(P), rel_fluent(P), !, subf(P,true,H), !.
holds(P,H) :- \+ \+ rel_fluent(P), !, rel_fluent(P), subf(P,true,H).
holds(P,H) :- subf(P,P1,H), (ground(P) -> (call(P1), !) ; call(P1)).

       /*  P2 is P1 with all fluents replaced by their values at H */
subf(P1,P2,_)  :- (var(P1) ; number(P1)), !, P2 = P1.
subf(P1,P2,H)  :- atom(P1), !, subf2(P1,P2,H).
subf(P1,P2,H)  :- P1=..[F|L1], subfl(L1,L2,H), P3=..[F|L2], subf2(P3,P2,H).

subf2(P3,P2,H) :- prim_fluent(P3), has_value(P3,P2,H).
subf2(P2,P2,_) :- \+ prim_fluent(P2).

subfl([],[],_).
subfl([T1|L1],[T2|L2],H) :- subf(T1,T2,H), subfl(L1,L2,H).

%
% has_value(F,V,H): Fluent F has value V at history H
%
has_value(F,V,H) :- ground(F) -> (has_valg(F,V,H), !) ; has_valo(F,V,H).

% has_valg/3: check cache, then normal query (for ground queries)
has_valg(F,V,H)  :- cache(F), !,
	(has_valc(F,V,H) -> true ; (has_val(F,V,H),  assert(has_valc(F,V,H))) ).
has_valg(F,V,H)  :- has_val(F,V,H), !.  % F is a fluent with NO cache

% has_valo/3: check cache, then normal query (for ground queries)
has_valo(F,V,H)  :- cache(F), !,
	(has_valc(F,V,H) ; (has_val(F,V,H),  \+ has_valc(F,V,H),  assert(has_valc(F,V,H)))).
has_valo(F,V,H)  :- has_val(F,V,H).  % F is a fluent with NO cache

% has_val/3: the usual way of reasoning using regression and sensing
has_val(F,V,[])		:- currently(F,V).
has_val(F,V,[A|H])	:- sets_val(A,F,V,H).
has_val(F,V,[A|H])	:- \+ forget(A,H,F), has_value(F,V,H), \+ sets_val(A,F,_,H).

sets_val(e(F,V),F,V,_)	:- prim_fluent(F), !.  		% Fluent V is explicitly set by e(_,_)
sets_val(e(A,V),F,V,_)	:- senses(A,F).	% Action A sets F directly
sets_val(e(A,V),F,V2,H)	:- !, senses(A,V,F,V2,P), holds(P,H). % A sets F indirectly
sets_val(A,F,V,H)	:- causes_val(A,F,V,P), holds(P,H).   % Non-sensing reasoning

% So far, one forgets the value of F when it is sensed (may be improved)
forget(Act, _, F) :- forget(Act, F).

% Special high-level actions to set and unset fluent F: set(F) and unset(F)
prim_action(set(_)).
prim_action(unset(_)).
poss(set(F), ground(F)).
poss(unset(F), ground(F)).
has_val(F,V,[set(F)|_])  :- !, V=true.
has_val(F,V,[unset(F)|_]):- !, V=false.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  ROLL DATABASE FORWARD
%
%  Rolling forward means advancing the predicate currently(-,-) and
%  discarding the corresponding tail of the history.
%  There are 3 parameters specified by roll_parameters(L,N,M).
%     L: the history has to be longer than this, or dont bother
%     M: if the history is longer than this, forced roll
%     N: the length of the tail of the history to be preserved
%		(set N=0 to never roll forward)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- dynamic temp/2.         % Temporal predicate used for rolling forward

%roll_parameters(1,1,0).  % Never roll forward
roll_parameters(20,40,5).

can_roll(H) :- roll_parameters(L,_,N), length(H,L1), L1 > L, N>0.
must_roll(H) :- roll_parameters(_,M,N), length(H,L1), L1 > M, N>0.

% H1 is the current history (H1 = H2 + H3)
% H2 will be the new history
% H3 is the tail of H1 that is going to be dropped
roll_db(H1,H2) :-
	roll_parameters(_,_,N),
	split(N,H1,H2,H3),
	preserve(H3),
	update_cache(H3).	    % Update the cache wrt the preserved history H3

	/* split(N,H,H1,H2) succeeds if append(H1,H2,H) and length(H1)=N. */
split(0,H,[],H).
split(N,[A|H],[A|H1],H2) :- N > 0, N1 is N-1, split(N1,H,H1,H2).

% preserve(H) : rolls forward the initial database from [] to H
preserve([]).
preserve([A|H]) :-
	preserve(H),
	roll_action(A),
	update_cache([A]).

% roll_action(A): roll currently/2 database with respect to action A
roll_action(A) :-
	sets_val(A, F, V, []),
	prim_fluent(F),
	(\+ temp(F, V) -> assert(temp(F, V)) ; true),
	fail.
roll_action(_) :-
	retract(temp(F,V)),
	retractall(currently(F,_)),	% There should be just one currently/2 for F!
	assert(currently(F,V)),
	fail.
roll_action(_).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DEBUG ROUTINES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% debug(+Action, +History, -SensingResult):
% If Action=debug then a snapshot of the system is printed out
% Otherwise, the sendRcxActionNumber/2
%     predicate failed (RCX panicked or there was a problem with the
%     communication). This predicate attempts to provide some basic debug
%     and error recovery.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
debug(debug, History, _) :- !,
    write('-------------------------------------------------------------'), nl,
    write('********* A SNAPSHOT OF THE SYSTEM WAS REQUESTED ************'), nl,
    errorRecoveryData(History),
    write('-------------------------------------------------------------'), nl.

debug(Action, History, SensingResult) :-
    write('** There is a problem with the RCX. It may need to be reset.'), nl,
    errorRecoveryData(History),
    errorRecoveryProc,
    execute(Action, History, SensingResult). % Try action again

% errorRecoveryData(+History): Extract values of primitive fluents at
%     the point where Hist actions are performed.
errorRecoveryData(History) :-
    write('    Actions performed so far: '),
    write(History), nl,
    bagof(U, prim_fluent(U), FluentList),
    printFluentValues(FluentList, History).

% printFluentValues(+FluentList, +History): Print value of primitive fluents
%     at the point where History actions have been performed
printFluentValues([], _).

printFluentValues([Hf | FluentList], History) :-
    (has_value(Hf, Hv, History),    % Print all instances of Hf
     write('    PRIMITIVE FLUENT '),
     write(Hf),
     write(' HAS VALUE '),
     write(Hv), nl, fail) ;
    printFluentValues(FluentList, History). % Continue with other fluents

% errorRecoveryProc: What to do in case of error. In this case, ask the user
%     to reposition the RCX so that last action can be re-attempted
errorRecoveryProc:-
    write('If you wish to abort, enter "a".'), nl,
    write('If you wish to continue execution, place RCX in a position'), nl,
    write('consistent with these values and hit any other key.'), nl,
    get0(Val),
    get0(_),                     % Clear carriage return
    (Val == 65; Val == 97) ->    % 65 is ASCII 'A', 97 is ASCII 'a'
         abort;
         true.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% EOF: Eval/evalbat.pl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%