text:
/*	$NetBSD: aclconf.c,v 1.7.2.1 2014/12/22 03:28:47 msaitoh Exp $	*/

/*
 * Copyright (C) 2004-2014  Internet Systems Consortium, Inc. ("ISC")
 * Copyright (C) 1999-2002  Internet Software Consortium.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * 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.
 */

/* Id */

#include <config.h>

#include <isc/mem.h>
#include <isc/string.h>		/* Required for HP/UX (and others?) */
#include <isc/util.h>

#include <isccfg/namedconf.h>
#include <isccfg/aclconf.h>

#include <dns/acl.h>
#include <dns/iptable.h>
#include <dns/fixedname.h>
#include <dns/log.h>

#ifdef HAVE_GEOIP
#include <stdlib.h>
#include <math.h>
#endif /* HAVE_GEOIP */

#define LOOP_MAGIC ISC_MAGIC('L','O','O','P')

isc_result_t
cfg_aclconfctx_create(isc_mem_t *mctx, cfg_aclconfctx_t **ret) {
	isc_result_t result;
	cfg_aclconfctx_t *actx;

	REQUIRE(mctx != NULL);
	REQUIRE(ret != NULL && *ret == NULL);

	actx = isc_mem_get(mctx, sizeof(*actx));
	if (actx == NULL)
		return (ISC_R_NOMEMORY);

	result = isc_refcount_init(&actx->references, 1);
	if (result != ISC_R_SUCCESS)
		goto cleanup;

	actx->mctx = NULL;
	isc_mem_attach(mctx, &actx->mctx);
	ISC_LIST_INIT(actx->named_acl_cache);

#ifdef HAVE_GEOIP
	actx->geoip = NULL;
#endif

	*ret = actx;
	return (ISC_R_SUCCESS);

 cleanup:
	isc_mem_put(mctx, actx, sizeof(*actx));
	return (result);
}

void
cfg_aclconfctx_attach(cfg_aclconfctx_t *src, cfg_aclconfctx_t **dest) {
	REQUIRE(src != NULL);
	REQUIRE(dest != NULL && *dest == NULL);

	isc_refcount_increment(&src->references, NULL);
	*dest = src;
}

void
cfg_aclconfctx_detach(cfg_aclconfctx_t **actxp) {
	cfg_aclconfctx_t *actx;
	dns_acl_t *dacl, *next;
	unsigned int refs;

	REQUIRE(actxp != NULL && *actxp != NULL);

	actx = *actxp;

	isc_refcount_decrement(&actx->references, &refs);
	if (refs == 0) {
		for (dacl = ISC_LIST_HEAD(actx->named_acl_cache);
		     dacl != NULL;
		     dacl = next)
		{
			next = ISC_LIST_NEXT(dacl, nextincache);
			ISC_LIST_UNLINK(actx->named_acl_cache, dacl,
					nextincache);
			dns_acl_detach(&dacl);
		}
		isc_mem_putanddetach(&actx->mctx, actx, sizeof(*actx));
	}

	*actxp = NULL;
}

/*
 * Find the definition of the named acl whose name is "name".
 */
static isc_result_t
get_acl_def(const cfg_obj_t *cctx, const char *name, const cfg_obj_t **ret) {
	isc_result_t result;
	const cfg_obj_t *acls = NULL;
	const cfg_listelt_t *elt;

	result = cfg_map_get(cctx, "acl", &acls);
	if (result != ISC_R_SUCCESS)
		return (result);
	for (elt = cfg_list_first(acls);
	     elt != NULL;
	     elt = cfg_list_next(elt)) {
		const cfg_obj_t *acl = cfg_listelt_value(elt);
		const char *aclname = cfg_obj_asstring(cfg_tuple_get(acl, "name"));
		if (strcasecmp(aclname, name) == 0) {
			if (ret != NULL) {
				*ret = cfg_tuple_get(acl, "value");
			}
			return (ISC_R_SUCCESS);
		}
	}
	return (ISC_R_NOTFOUND);
}

static isc_result_t
convert_named_acl(const cfg_obj_t *nameobj, const cfg_obj_t *cctx,
		  isc_log_t *lctx, cfg_aclconfctx_t *ctx,
		  isc_mem_t *mctx, unsigned int nest_level,
		  dns_acl_t **target)
{
	isc_result_t result;
	const cfg_obj_t *cacl = NULL;
	dns_acl_t *dacl;
	dns_acl_t loop;
	const char *aclname = cfg_obj_asstring(nameobj);

	/* Look for an already-converted version. */
	for (dacl = ISC_LIST_HEAD(ctx->named_acl_cache);
	     dacl != NULL;
	     dacl = ISC_LIST_NEXT(dacl, nextincache))
	{
		if (strcasecmp(aclname, dacl->name) == 0) {
			if (ISC_MAGIC_VALID(dacl, LOOP_MAGIC)) {
				cfg_obj_log(nameobj, lctx, ISC_LOG_ERROR,
					    "acl loop detected: %s", aclname);
				return (ISC_R_FAILURE);
			}
			dns_acl_attach(dacl, target);
			return (ISC_R_SUCCESS);
		}
	}
	/* Not yet converted.  Convert now. */
	result = get_acl_def(cctx, aclname, &cacl);
	if (result != ISC_R_SUCCESS) {
		cfg_obj_log(nameobj, lctx, ISC_LOG_WARNING,
			    "undefined ACL '%s'", aclname);
		return (result);
	}
	/*
	 * Add a loop detection element.
	 */
	memset(&loop, 0, sizeof(loop));
	ISC_LINK_INIT(&loop, nextincache);
	DE_CONST(aclname, loop.name);
	loop.magic = LOOP_MAGIC;
	ISC_LIST_APPEND(ctx->named_acl_cache, &loop, nextincache);
	result = cfg_acl_fromconfig(cacl, cctx, lctx, ctx, mctx,
				    nest_level, &dacl);
	ISC_LIST_UNLINK(ctx->named_acl_cache, &loop, nextincache);
	loop.magic = 0;
	loop.name = NULL;
	if (result != ISC_R_SUCCESS)
		return (result);
	dacl->name = isc_mem_strdup(dacl->mctx, aclname);
	if (dacl->name == NULL)
		return (ISC_R_NOMEMORY);
	ISC_LIST_APPEND(ctx->named_acl_cache, dacl, nextincache);
	dns_acl_attach(dacl, target);
	return (ISC_R_SUCCESS);
}

static isc_result_t
convert_keyname(const cfg_obj_t *keyobj, isc_log_t *lctx, isc_mem_t *mctx,
		dns_name_t *dnsname)
{
	isc_result_t result;
	isc_buffer_t buf;
	dns_fixedname_t fixname;
	unsigned int keylen;
	const char *txtname = cfg_obj_asstring(keyobj);

	keylen = strlen(txtname);
	isc_buffer_constinit(&buf, txtname, keylen);
	isc_buffer_add(&buf, keylen);
	dns_fixedname_init(&fixname);
	result = dns_name_fromtext(dns_fixedname_name(&fixname), &buf,
				   dns_rootname, 0, NULL);
	if (result != ISC_R_SUCCESS) {
		cfg_obj_log(keyobj, lctx, ISC_LOG_WARNING,
			    "key name '%s' is not a valid domain name",
			    txtname);
		return (result);
	}
	return (dns_name_dup(dns_fixedname_name(&fixname), mctx, dnsname));
}

/*
 * Recursively pre-parse an ACL definition to find the total number
 * of non-IP-prefix elements (localhost, localnets, key) in all nested
 * ACLs, so that the parent will have enough space allocated for the
 * elements table after all the nested ACLs have been merged in to the
 * parent.
 */
static isc_result_t
count_acl_elements(const cfg_obj_t *caml, const cfg_obj_t *cctx,
		   isc_log_t *lctx, cfg_aclconfctx_t *ctx, isc_mem_t *mctx,
		   isc_uint32_t *count, isc_boolean_t *has_negative)
{
	const cfg_listelt_t *elt;
	isc_result_t result;
	isc_uint32_t n = 0;

	REQUIRE(count != NULL);

	if (has_negative != NULL)
		*has_negative = ISC_FALSE;

	for (elt = cfg_list_first(caml);
	     elt != NULL;
	     elt = cfg_list_next(elt)) {
		const cfg_obj_t *ce = cfg_listelt_value(elt);

		/* might be a negated element, in which case get the value. */
		if (cfg_obj_istuple(ce)) {
			const cfg_obj_t *negated =
				cfg_tuple_get(ce, "negated");
			if (! cfg_obj_isvoid(negated)) {
				ce = negated;
				if (has_negative != NULL)
					*has_negative = ISC_TRUE;
			}
		}

		if (cfg_obj_istype(ce, &cfg_type_keyref)) {
			n++;
		} else if (cfg_obj_islist(ce)) {
			isc_boolean_t negative;
			isc_uint32_t sub;
			result = count_acl_elements(ce, cctx, lctx, ctx, mctx,
						    &sub, &negative);
			if (result != ISC_R_SUCCESS)
				return (result);
			n += sub;
			if (negative)
				n++;
#ifdef HAVE_GEOIP
		} else if (cfg_obj_istuple(ce) &&
			   cfg_obj_isvoid(cfg_tuple_get(ce, "negated")))
		{
			n++;
#endif /* HAVE_GEOIP */
		} else if (cfg_obj_isstring(ce)) {
			const char *name = cfg_obj_asstring(ce);
			if (strcasecmp(name, "localhost") == 0 ||
			    strcasecmp(name, "localnets") == 0) {
				n++;
			} else if (strcasecmp(name, "any") != 0 &&
				   strcasecmp(name, "none") != 0) {
				dns_acl_t *inneracl = NULL;
				/*
				 * Convert any named acls we reference now if
				 * they have not already been converted.
				 */
				result = convert_named_acl(ce, cctx, lctx, ctx,
							   mctx, 0, &inneracl);
				if (result == ISC_R_SUCCESS) {
					if (inneracl->has_negatives)
						n++;
					else
						n += inneracl->length;
					dns_acl_detach(&inneracl);
				} else
					return (result);
			}
		}
	}

	*count = n;
	return (ISC_R_SUCCESS);
}

#ifdef HAVE_GEOIP
static dns_geoip_subtype_t
get_subtype(const cfg_obj_t *obj, isc_log_t *lctx,
	    dns_geoip_subtype_t subtype, const char *dbname)
{
	if (dbname == NULL)
		return (subtype);

	switch (subtype) {
	case dns_geoip_countrycode:
		if (strcasecmp(dbname, "city") == 0)
			return (dns_geoip_city_countrycode);
		else if (strcasecmp(dbname, "region") == 0)
			return (dns_geoip_region_countrycode);
		else if (strcasecmp(dbname, "country") == 0)
			return (dns_geoip_country_code);
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "invalid GeoIP DB specified for "
			    "country search: ignored");
		return (subtype);
	case dns_geoip_countrycode3:
		if (strcasecmp(dbname, "city") == 0)
			return (dns_geoip_city_countrycode3);
		else if (strcasecmp(dbname, "country") == 0)
			return (dns_geoip_country_code3);
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "invalid GeoIP DB specified for "
			    "country search: ignored");
		return (subtype);
	case dns_geoip_countryname:
		if (strcasecmp(dbname, "city") == 0)
			return (dns_geoip_city_countryname);
		else if (strcasecmp(dbname, "country") == 0)
			return (dns_geoip_country_name);
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "invalid GeoIP DB specified for "
			    "country search: ignored");
		return (subtype);
	case dns_geoip_region:
		if (strcasecmp(dbname, "city") == 0)
			return (dns_geoip_city_region);
		else if (strcasecmp(dbname, "region") == 0)
			return (dns_geoip_region_code);
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "invalid GeoIP DB specified for "
			    "region search: ignored");
		return (subtype);
	case dns_geoip_regionname:
		if (strcasecmp(dbname, "city") == 0)
			return (dns_geoip_city_region);
		else if (strcasecmp(dbname, "region") == 0)
			return (dns_geoip_region_name);
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "invalid GeoIP DB specified for "
			    "region search: ignored");
		return (subtype);

	/*
	 * Log a warning if the wrong database was specified
	 * on an unambiguous query
	 */
	case dns_geoip_city_name:
	case dns_geoip_city_postalcode:
	case dns_geoip_city_metrocode:
	case dns_geoip_city_areacode:
	case dns_geoip_city_continentcode:
	case dns_geoip_city_timezonecode:
		if (strcasecmp(dbname, "city") != 0)
			cfg_obj_log(obj, lctx, ISC_LOG_WARNING,
				    "invalid GeoIP DB specified for "
				    "a 'city'-only search type: ignoring");
		return (subtype);
	case dns_geoip_isp_name:
		if (strcasecmp(dbname, "isp") != 0)
			cfg_obj_log(obj, lctx, ISC_LOG_WARNING,
				    "invalid GeoIP DB specified for "
				    "an 'isp' search: ignoring");
		return (subtype);
	case dns_geoip_org_name:
		if (strcasecmp(dbname, "org") != 0)
			cfg_obj_log(obj, lctx, ISC_LOG_WARNING,
				    "invalid GeoIP DB specified for "
				    "an 'org' search: ignoring");
		return (subtype);
	case dns_geoip_as_asnum:
		if (strcasecmp(dbname, "asnum") != 0)
			cfg_obj_log(obj, lctx, ISC_LOG_WARNING,
				    "invalid GeoIP DB specified for "
				    "an 'asnum' search: ignoring");
		return (subtype);
	case dns_geoip_domain_name:
		if (strcasecmp(dbname, "domain") != 0)
			cfg_obj_log(obj, lctx, ISC_LOG_WARNING,
				    "invalid GeoIP DB specified for "
				    "a 'domain' search: ignoring");
		return (subtype);
	case dns_geoip_netspeed_id:
		if (strcasecmp(dbname, "netspeed") != 0)
			cfg_obj_log(obj, lctx, ISC_LOG_WARNING,
				    "invalid GeoIP DB specified for "
				    "a 'netspeed' search: ignoring");
		return (subtype);
	default:
		INSIST(0);
	}
}

static isc_boolean_t
geoip_can_answer(dns_aclelement_t *elt, cfg_aclconfctx_t *ctx) {
	if (ctx->geoip == NULL)
		return (ISC_TRUE);

	switch (elt->geoip_elem.subtype) {
	case dns_geoip_countrycode:
	case dns_geoip_countrycode3:
	case dns_geoip_countryname:
		if (ctx->geoip->city_v4 != NULL ||
		    ctx->geoip->city_v6 != NULL ||
		    ctx->geoip->country_v4 != NULL ||
		    ctx->geoip->country_v6 != NULL ||
		    ctx->geoip->region != NULL)
			return (ISC_TRUE);
	case dns_geoip_region:
	case dns_geoip_regionname:
		if (ctx->geoip->city_v4 != NULL ||
		    ctx->geoip->city_v6 != NULL ||
		    ctx->geoip->region != NULL)
			return (ISC_TRUE);
	case dns_geoip_country_code:
	case dns_geoip_country_code3:
	case dns_geoip_country_name:
		if (ctx->geoip->country_v4 != NULL ||
		    ctx->geoip->country_v6 != NULL)
			return (ISC_TRUE);
	case dns_geoip_region_countrycode:
	case dns_geoip_region_code:
	case dns_geoip_region_name:
		if (ctx->geoip->region != NULL)
			return (ISC_TRUE);
	case dns_geoip_city_countrycode:
	case dns_geoip_city_countrycode3:
	case dns_geoip_city_countryname:
	case dns_geoip_city_region:
	case dns_geoip_city_regionname:
	case dns_geoip_city_name:
	case dns_geoip_city_postalcode:
	case dns_geoip_city_metrocode:
	case dns_geoip_city_areacode:
	case dns_geoip_city_continentcode:
	case dns_geoip_city_timezonecode:
		if (ctx->geoip->city_v4 != NULL ||
		    ctx->geoip->city_v6 != NULL)
			return (ISC_TRUE);
	case dns_geoip_isp_name:
		if (ctx->geoip->isp != NULL)
			return (ISC_TRUE);
	case dns_geoip_org_name:
		if (ctx->geoip->org != NULL)
			return (ISC_TRUE);
	case dns_geoip_as_asnum:
		if (ctx->geoip->as != NULL)
			return (ISC_TRUE);
	case dns_geoip_domain_name:
		if (ctx->geoip->domain != NULL)
			return (ISC_TRUE);
	case dns_geoip_netspeed_id:
		if (ctx->geoip->netspeed != NULL)
			return (ISC_TRUE);
	}

	return (ISC_FALSE);
}

static isc_result_t
parse_geoip_element(const cfg_obj_t *obj, isc_log_t *lctx,
		    cfg_aclconfctx_t *ctx, dns_aclelement_t *dep)
{
	const cfg_obj_t *ge;
	const char *dbname = NULL;
	const char *stype, *search;
	dns_geoip_subtype_t subtype;
	dns_aclelement_t de;
	size_t len;

	REQUIRE(dep != NULL);

	de = *dep;

	ge = cfg_tuple_get(obj, "db");
	if (!cfg_obj_isvoid(ge))
		dbname = cfg_obj_asstring(ge);

	stype = cfg_obj_asstring(cfg_tuple_get(obj, "subtype"));
	search = cfg_obj_asstring(cfg_tuple_get(obj, "search"));
	len = strlen(search);

	if (len == 0) {
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "zero-length geoip search field");
		return (ISC_R_FAILURE);
	}

	if (strcasecmp(stype, "country") == 0 && len == 2) {
		/* Two-letter country code */
		subtype = dns_geoip_countrycode;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "country") == 0 && len == 3) {
		/* Three-letter country code */
		subtype = dns_geoip_countrycode3;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "country") == 0) {
		/* Country name */
		subtype = dns_geoip_countryname;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "region") == 0 && len == 2) {
		/* Two-letter region code */
		subtype = dns_geoip_region;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "region") == 0) {
		/* Region name */
		subtype = dns_geoip_regionname;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "city") == 0) {
		/* City name */
		subtype = dns_geoip_city_name;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "postal") == 0 && len < 7) {
		subtype = dns_geoip_city_postalcode;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "postal") == 0) {
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "geoiop postal code (%s) too long", search);
		return (ISC_R_FAILURE);
	} else if (strcasecmp(stype, "metro") == 0) {
		subtype = dns_geoip_city_metrocode;
		de.geoip_elem.as_int = atoi(search);
	} else if (strcasecmp(stype, "area") == 0) {
		subtype = dns_geoip_city_areacode;
		de.geoip_elem.as_int = atoi(search);
	} else if (strcasecmp(stype, "tz") == 0) {
		subtype = dns_geoip_city_timezonecode;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "continent") == 0 && len == 2) {
		/* Two-letter continent code */
		subtype = dns_geoip_city_continentcode;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "continent") == 0) {
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "geoiop continent code (%s) too long", search);
		return (ISC_R_FAILURE);
	} else if (strcasecmp(stype, "isp") == 0) {
		subtype = dns_geoip_isp_name;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "asnum") == 0) {
		subtype = dns_geoip_as_asnum;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "org") == 0) {
		subtype = dns_geoip_org_name;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "domain") == 0) {
		subtype = dns_geoip_domain_name;
		strlcpy(de.geoip_elem.as_string, search,
			sizeof(de.geoip_elem.as_string));
	} else if (strcasecmp(stype, "netspeed") == 0) {
		subtype = dns_geoip_netspeed_id;
		de.geoip_elem.as_int = atoi(search);
	} else
		INSIST(0);

	de.geoip_elem.subtype = get_subtype(obj, lctx, subtype, dbname);

	if (! geoip_can_answer(&de, ctx)) {
		cfg_obj_log(obj, lctx, ISC_LOG_ERROR,
			    "no GeoIP database installed which can answer "
			    "queries of type '%s'", stype);
		return (ISC_R_FAILURE);
	}

	*dep = de;

	return (ISC_R_SUCCESS);
}
#endif

isc_result_t
cfg_acl_fromconfig(const cfg_obj_t *caml, const cfg_obj_t *cctx,
		   isc_log_t *lctx, cfg_aclconfctx_t *ctx,
		   isc_mem_t *mctx, unsigned int nest_level,
		   dns_acl_t **target)
{
	return (cfg_acl_fromconfig2(caml, cctx, lctx, ctx, mctx,
				    nest_level, 0, target));
}

isc_result_t
cfg_acl_fromconfig2(const cfg_obj_t *caml, const cfg_obj_t *cctx,
		   isc_log_t *lctx, cfg_aclconfctx_t *ctx,
		   isc_mem_t *mctx, unsigned int nest_level,
		   isc_uint16_t family, dns_acl_t **target)
{
	isc_result_t result;
	dns_acl_t *dacl = NULL, *inneracl = NULL;
	dns_aclelement_t *de;
	const cfg_listelt_t *elt;
	dns_iptable_t *iptab;
	int new_nest_level = 0;

	if (nest_level != 0)
		new_nest_level = nest_level - 1;

	REQUIRE(target != NULL);
	REQUIRE(*target == NULL || DNS_ACL_VALID(*target));

	if (*target != NULL) {
		/*
		 * If target already points to an ACL, then we're being
		 * called recursively to configure a nested ACL.  The
		 * nested ACL's contents should just be absorbed into its
		 * parent ACL.
		 */
		dns_acl_attach(*target, &dacl);
		dns_acl_detach(target);
	} else {
		/*
		 * Need to allocate a new ACL structure.  Count the items
		 * in the ACL definition that will require space in the
		 * elements table.  (Note that if nest_level is nonzero,
		 * *everything* goes in the elements table.)
		 */
		isc_uint32_t nelem;

		if (nest_level == 0) {
			result = count_acl_elements(caml, cctx, lctx, ctx,
						    mctx, &nelem, NULL);
			if (result != ISC_R_SUCCESS)
				return (result);
		} else
			nelem = cfg_list_length(caml, ISC_FALSE);

		result = dns_acl_create(mctx, nelem, &dacl);
		if (result != ISC_R_SUCCESS)
			return (result);
	}

	de = dacl->elements;
	for (elt = cfg_list_first(caml);
	     elt != NULL;
	     elt = cfg_list_next(elt)) {
		const cfg_obj_t *ce = cfg_listelt_value(elt);
		isc_boolean_t neg = ISC_FALSE;

		INSIST(dacl->length <= dacl->alloc);

		if (cfg_obj_istuple(ce)) {
			/* Might be a negated element */
			const cfg_obj_t *negated =
				cfg_tuple_get(ce, "negated");
			if (! cfg_obj_isvoid(negated)) {
				neg = ISC_TRUE;
				dacl->has_negatives = ISC_TRUE;
				ce = negated;
			}
		}

		/*
		 * If nest_level is nonzero, then every element is
		 * to be stored as a separate, nested ACL rather than
		 * merged into the main iptable.
		 */
		iptab = dacl->iptable;

		if (nest_level != 0) {
			result = dns_acl_create(mctx,
						cfg_list_length(ce, ISC_FALSE),
						&de->nestedacl);
			if (result != ISC_R_SUCCESS)
				goto cleanup;
			iptab = de->nestedacl->iptable;
		}

		if (cfg_obj_isnetprefix(ce)) {
			/* Network prefix */
			isc_netaddr_t	addr;
			unsigned int	bitlen;

			cfg_obj_asnetprefix(ce, &addr, &bitlen);
			if (family != 0 && family != addr.family) {
				char buf[ISC_NETADDR_FORMATSIZE + 1];
				isc_netaddr_format(&addr, buf, sizeof(buf));
				cfg_obj_log(ce, lctx, ISC_LOG_WARNING,
					    "'%s': incorrect address family; "
					    "ignoring", buf);
				if (nest_level != 0)
					dns_acl_detach(&de->nestedacl);
				continue;
			}

			/*
			 * If nesting ACLs (nest_level != 0), we negate
			 * the nestedacl element, not the iptable entry.
			 */
			result = dns_iptable_addprefix(iptab, &addr, bitlen,
					      ISC_TF(nest_level != 0 || !neg));
			if (result != ISC_R_SUCCESS)
				goto cleanup;

			if (nest_level > 0) {
				INSIST(dacl->length < dacl->alloc);
				de->type = dns_aclelementtype_nestedacl;
				de->negative = neg;
			} else
				continue;
		} else if (cfg_obj_islist(ce)) {
			/*
			 * If we're nesting ACLs, put the nested
			 * ACL onto the elements list; otherwise
			 * merge it into *this* ACL.  We nest ACLs
			 * in two cases: 1) sortlist, 2) if the
			 * nested ACL contains negated members.
			 */
			if (inneracl != NULL)
				dns_acl_detach(&inneracl);
			result = cfg_acl_fromconfig(ce, cctx, lctx,
						    ctx, mctx, new_nest_level,
						    &inneracl);
			if (result != ISC_R_SUCCESS)
				goto cleanup;
nested_acl:
			if (nest_level > 0 || inneracl->has_negatives) {
				INSIST(dacl->length < dacl->alloc);
				de->type = dns_aclelementtype_nestedacl;
				de->negative = neg;
				if (de->nestedacl != NULL)
					dns_acl_detach(&de->nestedacl);
				dns_acl_attach(inneracl,
					       &de->nestedacl);
				dns_acl_detach(&inneracl);
				/* Fall through. */
			} else {
				INSIST(dacl->length + inneracl->length
				       <= dacl->alloc);
				dns_acl_merge(dacl, inneracl,
					      ISC_TF(!neg));
				de += inneracl->length;  /* elements added */
				dns_acl_detach(&inneracl);
				INSIST(dacl->length <= dacl->alloc);
				continue;
			}
		} else if (cfg_obj_istype(ce, &cfg_type_keyref)) {
			/* Key name. */
			INSIST(dacl->length < dacl->alloc);
			de->type = dns_aclelementtype_keyname;
			de->negative = neg;
			dns_name_init(&de->keyname, NULL);
			result = convert_keyname(ce, lctx, mctx,
						 &de->keyname);
			if (result != ISC_R_SUCCESS)
				goto cleanup;
#ifdef HAVE_GEOIP
		} else if (cfg_obj_istuple(ce) &&
			   cfg_obj_isvoid(cfg_tuple_get(ce, "negated")))
		{
			INSIST(dacl->length < dacl->alloc);
			result = parse_geoip_element(ce, lctx, ctx, de);
			if (result != ISC_R_SUCCESS)
				goto cleanup;
			de->type = dns_aclelementtype_geoip;
			de->negative = neg;
#endif /* HAVE_GEOIP */
		} else if (cfg_obj_isstring(ce)) {
			/* ACL name. */
			const char *name = cfg_obj_asstring(ce);
			if (strcasecmp(name, "any") == 0) {
				/* Iptable entry with zero bit length. */
				result = dns_iptable_addprefix(iptab, NULL, 0,
					      ISC_TF(nest_level != 0 || !neg));
				if (result != ISC_R_SUCCESS)
					goto cleanup;

				if (nest_level != 0) {
					INSIST(dacl->length < dacl->alloc);
					de->type = dns_aclelementtype_nestedacl;
					de->negative = neg;
				} else
					continue;
			} else if (strcasecmp(name, "none") == 0) {
				/* none == !any */
				/*
				 * We don't unconditional set
				 * dacl->has_negatives and
				 * de->negative to true so we can handle
				 * "!none;".
				 */
				result = dns_iptable_addprefix(iptab, NULL, 0,
					      ISC_TF(nest_level != 0 || neg));
				if (result != ISC_R_SUCCESS)
					goto cleanup;

				if (!neg)
					dacl->has_negatives = !neg;

				if (nest_level != 0) {
					INSIST(dacl->length < dacl->alloc);
					de->type = dns_aclelementtype_nestedacl;
					de->negative = !neg;
				} else
					continue;
			} else if (strcasecmp(name, "localhost") == 0) {
				INSIST(dacl->length < dacl->alloc);
				de->type = dns_aclelementtype_localhost;
				de->negative = neg;
			} else if (strcasecmp(name, "localnets") == 0) {
				INSIST(dacl->length < dacl->alloc);
				de->type = dns_aclelementtype_localnets;
				de->negative = neg;
			} else {
				if (inneracl != NULL)
					dns_acl_detach(&inneracl);
				/*
				 * This call should just find the cached
				 * of the named acl.
				 */
				result = convert_named_acl(ce, cctx, lctx, ctx,
							   mctx, new_nest_level,
							   &inneracl);
				if (result != ISC_R_SUCCESS)
					goto cleanup;

				goto nested_acl;
			}
		} else {
			cfg_obj_log(ce, lctx, ISC_LOG_WARNING,
				    "address match list contains "
				    "unsupported element type");
			result = ISC_R_FAILURE;
			goto cleanup;
		}

		/*
		 * This should only be reached for localhost, localnets
		 * and keyname elements, and nested ACLs if nest_level is
		 * nonzero (i.e., in sortlists).
		 */
		if (de->nestedacl != NULL &&
		    de->type != dns_aclelementtype_nestedacl)
			dns_acl_detach(&de->nestedacl);

		dacl->node_count++;
		de->node_num = dacl->node_count;

		dacl->length++;
		de++;
		INSIST(dacl->length <= dacl->alloc);
	}

	dns_acl_attach(dacl, target);
	result = ISC_R_SUCCESS;

 cleanup:
	if (inneracl != NULL)
		dns_acl_detach(&inneracl);
	dns_acl_detach(&dacl);
	return (result);
}


text:
#import "ApplicationRouting.h"
#import <Foundation/Foundation.h>

@implementation ApplicationRouting

+ (NSData *)resolveAppAsset:(NSString *)path;
{
  return nil;
}

@end

redpajama_set_name: RedPajamaGithub


text:
package LWP::Protocol::cassandra;

use vars qw(@ISA);
require LWP::Protocol;
@ISA = qw(LWP::Protocol);

use strict;
use warnings;
use Net::Cassandra::Cassandra;

use Thrift;
use Thrift::Socket;
use Thrift::FramedTransport;
use Thrift::BinaryProtocol;

require HTTP::Request;
require HTTP::Response;
require HTTP::Status;
require HTTP::Date;
require Net::SMTP;

my $EXPECTED_CLUS_NAME = 'Sessions';

sub request
{
  my($self, $request, $proxy, $arg, $size) = @_;
  my $proto = "cassandra";

  # check proxy
  if (defined $proxy)
  {
      return new HTTP::Response &HTTP::Status::RC_BAD_REQUEST,
        "You can not proxy through $proto";
  }

  # check method
  my $method = $request->method;
  unless ($method eq 'GET' || $method eq 'HEAD') {
return new HTTP::Response &HTTP::Status::RC_BAD_REQUEST,
        'Library does not allow method ' .
        "$method for '$proto:' URLs";
  }

  # check url
  my $url = $request->url;
  my $scheme = $url->scheme;
  if ($scheme ne $proto ) {
  return new HTTP::Response &HTTP::Status::RC_INTERNAL_SERVER_ERROR,
    ref($self) . "::request called for '$scheme'";
  }

  # URL OK, look at file
  my $path  = $url->path;
  my $rc =  check_cassandra(split(':',$url->authority ));
  # test file exists and is readable
  if ($rc != 0 ) {
    return new HTTP::Response &HTTP::Status::RC_NOT_FOUND, "Failed cassandra check";
  }
  # XXX should check Accept headers?
  # Ok, should be an OK response by now...
  my $response = new HTTP::Response &HTTP::Status::RC_OK;
  if ($method ne "HEAD") {
    $response =  $self->collect_once($arg, $response, '');
  }
  return $response;
}

# check_cassandra($server, $port)
# returns 0 for success, 1 else
sub check_cassandra
{
  my ($server, $d_port) = @_;

  my $socket = new Thrift::Socket($server, $d_port);
  my $transport = new Thrift::FramedTransport($socket,1024,1024);
  my $protocol = new Thrift::BinaryProtocol($transport);
  my $client = new Net::Cassandra::CassandraClient($protocol);

  eval {
     $transport->open();
     my $cluster_name = $client->describe_cluster_name();
     die 'Unexpected cluster name!' if not($cluster_name eq $EXPECTED_CLUS_NAME);
     $transport->close();
  };

  if ($@) {
    return 1;
  }
  else {
    return 0;
  }
}

1;


text:
PHP-Web-services-Api
====================

PHP RESTful Web services Api with Twitter Bootstrap


text:
namespace libmv {
namespace euclidean {
namespace euclidean2D {
namespace kernel {

void TwoPointSolver::Solve(const Mat &x1, const Mat &x2, vector<Mat3> *Hs) {
  Mat3 M;
  if (Euclidean2DFromCorrespondencesLinear(x1,x2, &M)) {
    Hs->push_back(M);
  }
}

}  // namespace kernel
}  // namespace euclidean2D
}  // namespace euclidean
}  // namespace libmv


text:
namespace Lumix
{

	class IAllocator;

	class LUMIX_ENGINE_API InputSystem
	{
		public:
			enum InputType
			{
				PRESSED,
				DOWN,
				MOUSE_X,
				MOUSE_Y,
				LTHUMB_X,
				LTHUMB_Y,
				RTHUMB_X,
				RTHUMB_Y,
				RTRIGGER,
				LTRIGGER
			};

		public:

			static InputSystem* create(IAllocator& allocator);
			static void destroy(InputSystem& system);

			virtual ~InputSystem() {}
			virtual void enable(bool enabled) = 0;
			virtual void update(float dt) = 0;
			virtual float getActionValue(uint32 action) = 0;
			virtual void injectMouseXMove(float value) = 0;
			virtual void injectMouseYMove(float value) = 0;
			virtual float getMouseXMove() const = 0;
			virtual float getMouseYMove() const = 0;
			virtual void addAction(uint32 action, InputType type, int key, int controller_id) = 0;
	};

} // ~namespace Lumix


text:
"""
    verktyg.response
    ~~~~~~~~~~~~~~~~

    The wrappers are simple request and response objects which you can
    subclass to do whatever you want them to do.  The request object contains
    the information transmitted by the client (webbrowser) and the response
    object contains all the information sent back to the browser.

    An important detail is that the request object is created with the WSGI
    environ and will act as high-level proxy whereas the response object is an
    actual WSGI application.

    Like everything else in Werkzeug these objects will work correctly with
    unicode data.  Incoming form data parsed by the response object will be
    decoded into an unicode object if possible and if it makes sense.

    :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from datetime import datetime, timedelta
from urllib.parse import urljoin

from verktyg.urls import iri_to_uri
from verktyg.utils import cached_property, header_property, get_content_type
from verktyg.datastructures import CallbackDict
from verktyg.http import (
    Headers, ResponseCacheControl, ContentRange,
    HTTP_STATUS_CODES, parse_cache_control_header, parse_date, generate_etag,
    is_resource_modified, unquote_etag, quote_etag, parse_set_header,
    parse_www_authenticate_header, remove_entity_headers, parse_options_header,
    dump_options_header, http_date, dump_cookie, parse_content_range_header,
    dump_header,
)
from verktyg.wsgi import get_current_url, ClosingIterator

def _run_wsgi_app(*args):
    """This function replaces itself to ensure that the test module is not
    imported unless required.  DO NOT USE!
    """
    global _run_wsgi_app
    from verktyg.test import run_wsgi_app as _run_wsgi_app
    return _run_wsgi_app(*args)

def _warn_if_string(iterable):
    """Helper for the response objects to check if the iterable returned
    to the WSGI server is not a string.
    """
    if isinstance(iterable, str):
        from warnings import warn
        warn(Warning(
            'response iterable was set to a string.  This appears to work but '
            'means that the server will send the data to the client char, by '
            'char.  This is almost never intended behavior, use response.data '
            'to assign strings to the response object.'
        ), stacklevel=2)

def _iter_encoded(iterable, charset):
    for item in iterable:
        if isinstance(item, str):
            yield item.encode(charset)
        else:
            yield item

class BaseResponse(object):

    """Base response class.  The most important fact about a response object
    is that it's a regular WSGI application.  It's initialized with a couple
    of response parameters (headers, body, status code etc.) and will start a
    valid WSGI response when called with the environ and start response
    callable.

    Because it's a WSGI application itself processing usually ends before the
    actual response is sent to the server.  This helps debugging systems
    because they can catch all the exceptions before responses are started.

    Here a small example WSGI application that takes advantage of the
    response objects::

        from verktyg.wrappers import BaseResponse as Response

        def index():
            return Response('Index page')

        def application(environ, start_response):
            path = environ.get('PATH_INFO') or '/'
            if path == '/':
                response = index()
            else:
                response = Response('Not Found', status=404)
            return response(environ, start_response)

    Like :class:`BaseRequest` which object is lacking a lot of functionality
    implemented in mixins.  This gives you a better control about the actual
    API of your response objects, so you can create subclasses and add custom
    functionality.  A full featured response object is available as
    :class:`Response` which implements a couple of useful mixins.

    To enforce a new type of already existing responses you can use the
    :meth:`force_type` method.  This is useful if you're working with different
    subclasses of response objects and you want to post process them with a
    known interface.

    Per default the request object will assume all the text data is `utf-8`
    encoded.  Please refer to `the unicode chapter <unicode.txt>`_ for more
    details about customizing the behavior.

    Response can be any kind of iterable or string.  If it's a string it's
    considered being an iterable with one item which is the string passed.
    Headers can be a list of tuples or a :class:`~verktyg.http.Headers` object.

    Special note for `mimetype` and `content_type`:  For most mime types
    `mimetype` and `content_type` work the same, the difference affects
    only 'text' mimetypes.  If the mimetype passed with `mimetype` is a
    mimetype starting with `text/`, the charset parameter of the response
    object is appended to it.  In contrast the `content_type` parameter is
    always added as header unmodified.

    :param response:
        A string or response iterable.
    :param status:
        A string with a status or an integer with the status code.
    :param headers:
        A list of headers or a :class:`~verktyg.http.Headers` object.
    :param mimetype:
        The mimetype for the request.  See notice above.
    :param content_type:
        The content type for the request.  See notice above.
    :param direct_passthrough:
        If set to `True` :meth:`iter_encoded` is not called before iteration
        which makes it possible to pass special iterators through unchanged
        (see :func:`wrap_file` for more details.)
    """

    #: the charset of the response.
    charset = 'utf-8'

    #: the default status if none is provided.
    default_status = 200

    #: the default mimetype if none is provided.
    default_mimetype = 'text/plain'

    #: if set to `False` accessing properties on the response object will
    #: not try to consume the response iterator and convert it into a list.
    implicit_sequence_conversion = True

    #: Should this response object correct the location header to be RFC
    #: conformant?  This is true by default.
    autocorrect_location_header = True

    #: Should this response object automatically set the content-length
    #: header if possible?  This is true by default.
    automatically_set_content_length = True

    def __init__(
        self, response=None, status=None, headers=None,
        mimetype=None, content_type=None, direct_passthrough=False,
    ):
        if isinstance(headers, Headers):
            self.headers = headers
        elif not headers:
            self.headers = Headers()
        else:
            self.headers = Headers(headers)

        if content_type is None:
            if mimetype is None and 'content-type' not in self.headers:
                mimetype = self.default_mimetype
            if mimetype is not None:
                mimetype = get_content_type(mimetype, self.charset)
            content_type = mimetype
        if content_type is not None:
            self.headers['Content-Type'] = content_type
        if status is None:
            status = self.default_status
        if isinstance(status, int):
            self.status_code = status
        else:
            self.status = status

        self.direct_passthrough = direct_passthrough
        self._on_close = []

        # we set the response after the headers so that if a class changes
        # the charset attribute, the data is set in the correct charset.
        if response is None:
            self.response = []
        elif isinstance(response, (str, bytes, bytearray)):
            self.set_data(response)
        else:
            self.response = response

    def call_on_close(self, func):
        """Adds a function to the internal list of functions that should
        be called as part of closing down the response.  Since 0.7 this
        function also returns the function that was passed so that this
        can be used as a decorator.
        """
        self._on_close.append(func)
        return func

    def __repr__(self):
        if self.is_sequence:
            body_info = '%d bytes' % sum(map(len, self.iter_encoded()))
        else:
            body_info = 'streamed' if self.is_streamed else 'likely-streamed'
        return '<%s %s [%s]>' % (
            self.__class__.__name__,
            body_info,
            self.status
        )

    @classmethod
    def force_type(cls, response, environ=None):
        """Enforce that the WSGI response is a response object of the current
        type.  Werkzeug will use the :class:`BaseResponse` internally in many
        situations like the exceptions.  If you call :meth:`get_response` on an
        exception you will get back a regular :class:`BaseResponse` object,
        even if you are using a custom subclass.

        This method can enforce a given response type, and it will also
        convert arbitrary WSGI callables into response objects if an environ
        is provided::

            # convert a Werkzeug response object into an instance of the
            # MyResponseClass subclass.
            response = MyResponseClass.force_type(response)

            # convert any WSGI application into a response object
            response = MyResponseClass.force_type(response, environ)

        This is especially useful if you want to post-process responses in
        the main dispatcher and use functionality provided by your subclass.

        Keep in mind that this will modify response objects in place if
        possible!

        :param response:
            A response object or wsgi application.
        :param environ:
            A WSGI environment object.
        :return:
            A response object.
        """
        if not isinstance(response, BaseResponse):
            if environ is None:
                raise TypeError(
                    'cannot convert WSGI application into '
                    'response objects without an environ'
                )
            response = BaseResponse(*_run_wsgi_app(response, environ))
        response.__class__ = cls
        return response

    @classmethod
    def from_app(cls, app, environ, buffered=False):
        """Create a new response object from an application output.  This
        works best if you pass it an application that returns a generator all
        the time.  Sometimes applications may use the `write()` callable
        returned by the `start_response` function.  This tries to resolve such
        edge cases automatically.  But if you don't get the expected output
        you should set `buffered` to `True` which enforces buffering.

        :param app:
            The WSGI application to execute.
        :param environ:
            The WSGI environment to execute against.
        :param buffered:
            Set to `True` to enforce buffering.
        :return:
            A response object.
        """
        return cls(*_run_wsgi_app(app, environ, buffered))

    def _get_status_code(self):
        return self._status_code

    def _set_status_code(self, code):
        self._status_code = code
        try:
            self._status = '%d %s' % (code, HTTP_STATUS_CODES[code].upper())
        except KeyError:
            self._status = '%d UNKNOWN' % code
    status_code = property(
        _get_status_code, _set_status_code,
        doc='The HTTP Status code as number',
    )
    del _get_status_code, _set_status_code

    def _get_status(self):
        return self._status

    def _set_status(self, value):
        self._status = value
        try:
            self._status_code = int(self._status.split(None, 1)[0])
        except ValueError:
            self._status_code = 0
            self._status = '0 %s' % self._status
    status = property(_get_status, _set_status, doc='The HTTP Status code')
    del _get_status, _set_status

    def get_data(self, as_text=False):
        """The string representation of the request body.  Whenever you call
        this property the request iterable is encoded and flattened.  This
        can lead to unwanted behavior if you stream big data.

        This behavior can be disabled by setting
        :attr:`implicit_sequence_conversion` to `False`.

        If `as_text` is set to `True` the return value will be a decoded
        unicode string.
        """
        self._ensure_sequence()
        rv = b''.join(self.iter_encoded())
        if as_text:
            rv = rv.decode(self.charset)
        return rv

    def set_data(self, value):
        """Sets a new string as response.  The value set must either by a
        unicode or bytestring.  If a unicode string is set it's encoded
        automatically to the charset of the response (utf-8 by default).
        """
        # if an unicode string is set, it's encoded directly so that we
        # can set the content length
        if isinstance(value, str):
            value = value.encode(self.charset)
        else:
            value = bytes(value)
        self.response = [value]
        if self.automatically_set_content_length:
            self.headers['Content-Length'] = str(len(value))

    def calculate_content_length(self):
        """Returns the content length if available or `None` otherwise."""
        try:
            self._ensure_sequence()
        except RuntimeError:
            return None
        return sum(len(x) for x in self.response)

    def _ensure_sequence(self, mutable=False):
        """This method can be called by methods that need a sequence.  If
        `mutable` is true, it will also ensure that the response sequence
        is a standard Python list.
        """
        if self.is_sequence:
            # if we need a mutable object, we ensure it's a list.
            if mutable and not isinstance(self.response, list):
                self.response = list(self.response)
            return
        if self.direct_passthrough:
            raise RuntimeError(
                'Attempted implicit sequence conversion but the response '
                'object is in direct passthrough mode.'
            )
        if not self.implicit_sequence_conversion:
            raise RuntimeError(
                'The response object required the iterable to be a sequence, '
                'but the implicit conversion was disabled.  Call '
                'make_sequence() yourself.'
            )
        self.make_sequence()

    def make_sequence(self):
        """Converts the response iterator in a list.  By default this happens
        automatically if required.  If `implicit_sequence_conversion` is
        disabled, this method is not automatically called and some properties
        might raise exceptions.  This also encodes all the items.
        """
        if not self.is_sequence:
            # if we consume an iterable we have to ensure that the close
            # method of the iterable is called if available when we tear
            # down the response
            close = getattr(self.response, 'close', None)
            self.response = list(self.iter_encoded())
            if close is not None:
                self.call_on_close(close)

    def iter_encoded(self):
        """Iter the response encoded with the encoding of the response.
        If the response object is invoked as WSGI application the return
        value of this method is used as application iterator unless
        :attr:`direct_passthrough` was activated.
        """
        if __debug__:
            _warn_if_string(self.response)
        # Encode in a separate function so that self.response is fetched
        # early.  This allows us to wrap the response with the return
        # value from get_app_iter or iter_encoded.
        return _iter_encoded(self.response, self.charset)

    def set_cookie(
        self, key, value='', max_age=None, expires=None,
        path='/', domain=None, secure=None, httponly=False,
    ):
        """Sets a cookie. The parameters are the same as in the cookie `Morsel`
        object in the Python standard library but it accepts unicode data, too.

        :param key:
            The key (name) of the cookie to be set.
        :param value:
            The value of the cookie.
        :param max_age:
            Should be a number of seconds, or `None` (default) if the cookie
            should last only as long as the client's browser session.
        :param expires:
            Should be a `datetime` object or UNIX timestamp.
        :param domain:
            If you want to set a cross-domain cookie.  For example,
            ``domain=".example.com"`` will set a cookie that is readable by the
            domain ``www.example.com``, ``foo.example.com`` etc.  Otherwise, a
            cookie will only be readable by the domain that set it.
        :param path:
            Limits the cookie to a given path, per default it will span the
            whole domain.
        """
        self.headers.add(
            'Set-Cookie', dump_cookie(
                key, value, max_age, expires,
                path, domain, secure, httponly,
                self.charset
            )
        )

    def delete_cookie(self, key, path='/', domain=None):
        """Delete a cookie.  Fails silently if key doesn't exist.

        :param key:
            The key (name) of the cookie to be deleted.
        :param path:
            If the cookie that should be deleted was limited to a path, the
            path has to be defined here.
        :param domain:
            If the cookie that should be deleted was limited to a domain, that
            domain has to be defined here.
        """
        self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)

    @property
    def is_streamed(self):
        """If the response is streamed (the response is not an iterable with
        a length information) this property is `True`.  In this case streamed
        means that there is no information about the number of iterations.
        This is usually `True` if a generator is passed to the response object.

        This is useful for checking before applying some sort of post
        filtering that should not take place for streamed responses.
        """
        try:
            len(self.response)
        except (TypeError, AttributeError):
            return True
        return False

    @property
    def is_sequence(self):
        """If the iterator is buffered, this property will be `True`.  A
        response object will consider an iterator to be buffered if the
        response attribute is a list or tuple.
        """
        return isinstance(self.response, (tuple, list))

    def close(self):
        """Close the wrapped response if possible.  You can also use the object
        in a with statement which will automatically close it.
        """
        if hasattr(self.response, 'close'):
            self.response.close()
        for func in self._on_close:
            func()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, tb):
        self.close()

    def freeze(self):
        """Call this method if you want to make your response object ready for
        being pickled.  This buffers the generator if there is one.  It will
        also set the `Content-Length` header to the length of the body.
        """
        # we explicitly set the length to a list of the *encoded* response
        # iterator.  Even if the implicit sequence conversion is disabled.
        self.response = list(self.iter_encoded())
        self.headers['Content-Length'] = str(sum(map(len, self.response)))

    def get_wsgi_headers(self, environ):
        """This is automatically called right before the response is started
        and returns headers modified for the given environment.  It returns a
        copy of the headers from the response with some modifications applied
        if necessary.

        For example the location header (if present) is joined with the root
        URL of the environment.  Also the content length is automatically set
        to zero here for certain status codes.

        :param environ:
            The WSGI environment of the request.
        :return:
            Returns a new :class:`~verktyg.http.Headers` object.
        """
        headers = Headers(self.headers)
        location = None
        content_location = None
        content_length = None
        status = self.status_code

        # iterate over the headers to find all values in one go.  Because
        # get_wsgi_headers is used each response that gives us a tiny
        # speedup.
        for key, value in headers:
            ikey = key.lower()
            if ikey == u'location':
                location = value
            elif ikey == u'content-location':
                content_location = value
            elif ikey == u'content-length':
                content_length = value

        # make sure the location header is an absolute URL
        if location is not None:
            old_location = location
            if isinstance(location, str):
                # Safe conversion is necessary here as we might redirect
                # to a broken URI scheme (for instance itms-services).
                location = iri_to_uri(location)

            if self.autocorrect_location_header:
                current_url = get_current_url(environ, root_only=True)
                if isinstance(current_url, str):
                    current_url = iri_to_uri(current_url)
                location = urljoin(current_url, location)
            if location != old_location:
                headers['Location'] = location

        # make sure the content location is a URL
        if (
            content_location is not None and
            isinstance(content_location, str)
        ):
            headers['Content-Location'] = iri_to_uri(content_location)

        # remove entity headers and set content length to zero if needed.
        # Also update content_length accordingly so that the automatic
        # content length detection does not trigger in the following
        # code.
        if 100 <= status < 200 or status == 204:
            headers['Content-Length'] = content_length = u'0'
        elif status == 304:
            remove_entity_headers(headers)

        # if we can determine the content length automatically, we
        # should try to do that.  But only if this does not involve
        # flattening the iterator or encoding of unicode strings in
        # the response.  We however should not do that if we have a 304
        # response.
        if (
            self.automatically_set_content_length and
            self.is_sequence and content_length is None and status != 304
        ):
            content_length = sum(len(x) for x in self.response)
            headers['Content-Length'] = str(content_length)

        return headers

    def get_app_iter(self, environ):
        """Returns the application iterator for the given environ.  Depending
        on the request method and the current status code the return value
        might be an empty response rather than the one from the response.

        If the request method is `HEAD` or the status code is in a range
        where the HTTP specification requires an empty response, an empty
        iterable is returned.

        :param environ:
            The WSGI environment of the request.
        :return:
            A response iterable.
        """
        status = self.status_code
        if (
            environ['REQUEST_METHOD'] == 'HEAD' or
            100 <= status < 200 or status in (204, 304)
        ):
            iterable = ()
        elif self.direct_passthrough:
            if __debug__:
                _warn_if_string(self.response)
            return self.response
        else:
            iterable = self.iter_encoded()
        return ClosingIterator(iterable, self.close)

    def get_wsgi_response(self, environ):
        """Returns the final WSGI response as tuple.  The first item in
        the tuple is the application iterator, the second the status and
        the third the list of headers.  The response returned is created
        specially for the given environment.  For example if the request
        method in the WSGI environment is ``'HEAD'`` the response will
        be empty and only the headers and status code will be present.

        :param environ:
            The WSGI environment of the request.
        :return:
            An ``(app_iter, status, headers)`` tuple.
        """
        headers = self.get_wsgi_headers(environ)
        app_iter = self.get_app_iter(environ)
        return app_iter, self.status, headers.to_wsgi_list()

    def __call__(self, environ, start_response):
        """Process this response as WSGI application.

        :param environ:
            The WSGI environment.
        :param start_response:
            The response callable provided by the WSGI server.
        :return:
            An application iterator
        """
        app_iter, status, headers = self.get_wsgi_response(environ)
        start_response(status, headers)
        return app_iter

class StreamOnlyMixin(object):

    """If mixed in before the request object this will change the bahavior
    of it to disable handling of form parsing.  This disables the
    :attr:`files`, :attr:`form` attributes and will just provide a
    :attr:`stream` attribute that however is always available.
    """

    disable_data_descriptor = True
    want_form_data_parsed = False

class ETagResponseMixin(object):

    """Adds extra functionality to a response object for etag and cache
    handling.  This mixin requires an object with at least a `headers`
    object that implements a dict like interface similar to
    :class:`~verktyg.http.Headers`.

    If you want the :meth:`freeze` method to automatically add an etag, you
    have to mixin this method before the response base class.  The default
    response class does not do that.
    """

    @property
    def cache_control(self):
        """The Cache-Control general-header field is used to specify
        directives that MUST be obeyed by all caching mechanisms along the
        request/response chain.
        """
        def on_update(cache_control):
            if not cache_control and 'cache-control' in self.headers:
                del self.headers['cache-control']
            elif cache_control:
                self.headers['Cache-Control'] = cache_control.to_header()
        return parse_cache_control_header(
            self.headers.get('cache-control'), on_update, ResponseCacheControl,
        )

    def make_conditional(self, request_or_environ):
        """Make the response conditional to the request.  This method works
        best if an etag was defined for the response already.  The `add_etag`
        method can be used to do that.  If called without etag just the date
        header is set.

        This does nothing if the request method in the request or environ is
        anything but GET or HEAD.

        It does not remove the body of the response because that's something
        the :meth:`__call__` function does for us automatically.

        Returns self so that you can do ``return resp.make_conditional(req)``
        but modifies the object in-place.

        :param request_or_environ:
            A request object or WSGI environment to be used to make the
            response conditional against.
        """
        environ = getattr(request_or_environ, 'environ', request_or_environ)
        assert isinstance(environ, dict)
        if environ['REQUEST_METHOD'] in ('GET', 'HEAD'):
            # if the date is not in the headers, add it now.  We however
            # will not override an already existing header.  Unfortunately
            # this header will be overriden by many WSGI servers including
            # wsgiref.
            if 'date' not in self.headers:
                self.headers['Date'] = http_date()
            if (
                self.automatically_set_content_length and
                'content-length' not in self.headers
            ):
                length = self.calculate_content_length()
                if length is not None:
                    self.headers['Content-Length'] = length
            if not is_resource_modified(
                    environ, self.headers.get('etag'),
                    None, self.headers.get('last-modified')):
                self.status_code = 304
        return self

    def add_etag(self, overwrite=False, weak=False):
        """Add an etag for the current response if there is none yet."""
        if overwrite or 'etag' not in self.headers:
            self.set_etag(generate_etag(self.get_data()), weak)

    def set_etag(self, etag, weak=False):
        """Set the etag, and override the old one if there was one."""
        self.headers['ETag'] = quote_etag(etag, weak)

    def get_etag(self):
        """Return a tuple in the form ``(etag, is_weak)``.  If there is no
        ETag the return value is ``(None, None)``.
        """
        return unquote_etag(self.headers.get('ETag'))

    def freeze(self, no_etag=False):
        """Call this method if you want to make your response object ready for
        pickeling.  This buffers the generator if there is one.  This also
        sets the etag unless `no_etag` is set to `True`.
        """
        if not no_etag:
            self.add_etag()
        super(ETagResponseMixin, self).freeze()

    accept_ranges = header_property('Accept-Ranges', doc='''
        The `Accept-Ranges` header.  Even though the name would indicate
        that multiple values are supported, it must be one string token only.

        The values ``'bytes'`` and ``'none'`` are common.''')

    def _get_content_range(self):
        def on_update(rng):
            if not rng:
                del self.headers['content-range']
            else:
                self.headers['Content-Range'] = rng.to_header()
        rv = parse_content_range_header(
            self.headers.get('content-range'), on_update,
        )
        # always provide a content range object to make the descriptor
        # more user friendly.  It provides an unset() method that can be
        # used to remove the header quickly.
        if rv is None:
            rv = ContentRange(None, None, None, on_update=on_update)
        return rv

    def _set_content_range(self, value):
        if not value:
            del self.headers['content-range']
        elif isinstance(value, str):
            self.headers['Content-Range'] = value
        else:
            self.headers['Content-Range'] = value.to_header()
    content_range = property(_get_content_range, _set_content_range, doc='''
        The `Content-Range` header as
        :class:`~verktyg.http.ContentRange` object.  Even if the
        header is not set it wil provide such an object for easier
        manipulation.''')
    del _get_content_range, _set_content_range

class ResponseStream(object):

    """A file descriptor like object used by the :class:`ResponseStreamMixin`
    to represent the body of the stream.  It directly pushes into the response
    iterable of the response object.
    """

    mode = 'wb+'

    def __init__(self, response):
        self.response = response
        self.closed = False

    def write(self, value):
        if self.closed:
            raise ValueError('I/O operation on closed file')
        self.response._ensure_sequence(mutable=True)
        self.response.response.append(value)
        self.response.headers.pop('Content-Length', None)

    def writelines(self, seq):
        for item in seq:
            self.write(item)

    def close(self):
        self.closed = True

    def flush(self):
        if self.closed:
            raise ValueError('I/O operation on closed file')

    def isatty(self):
        if self.closed:
            raise ValueError('I/O operation on closed file')
        return False

    @property
    def encoding(self):
        return self.response.charset

class ResponseStreamMixin(object):

    """Mixin for :class:`BaseRequest` subclasses.  Classes that inherit from
    this mixin will automatically get a :attr:`stream` property that provides
    a write-only interface to the response iterable.
    """

    @cached_property
    def stream(self):
        """The response iterable as write-only stream."""
        return ResponseStream(self)

class CommonResponseDescriptorsMixin(object):

    """A mixin for :class:`BaseResponse` subclasses.  Response objects that
    mix this class in will automatically get descriptors for a couple of
    HTTP headers with automatic type conversion.
    """

    def _get_mimetype(self):
        ct = self.headers.get('content-type')
        if ct:
            return ct.split(';')[0].strip()

    def _set_mimetype(self, value):
        self.headers['Content-Type'] = get_content_type(value, self.charset)

    def _get_mimetype_params(self):
        def on_update(d):
            self.headers['Content-Type'] = dump_options_header(
                self.mimetype, d
            )
        d = parse_options_header(self.headers.get('content-type', ''))[1]
        return CallbackDict(d, on_update)

    mimetype = property(_get_mimetype, _set_mimetype, doc='''
        The mimetype (content type without charset etc.)''')
    mimetype_params = property(_get_mimetype_params, doc='''
        The mimetype parameters as dict.  For example if the content
        type is ``text/html; charset=utf-8`` the params would be
        ``{'charset': 'utf-8'}``.
        ''')
    location = header_property('Location', doc='''
        The Location response-header field is used to redirect the recipient
        to a location other than the Request-URI for completion of the request
        or identification of a new resource.''')
    age = header_property('Age', None, parse_date, http_date, doc='''
        The Age response-header field conveys the sender's estimate of the
        amount of time since the response (or its revalidation) was
        generated at the origin server.

        Age values are non-negative decimal integers, representing time in
        seconds.''')
    content_type = header_property('Content-Type', doc='''
        The Content-Type entity-header field indicates the media type of the
        entity-body sent to the recipient or, in the case of the HEAD method,
        the media type that would have been sent had the request been a GET.
    ''')
    content_length = header_property('Content-Length', None, int, str, doc='''
        The Content-Length entity-header field indicates the size of the
        entity-body, in decimal number of OCTETs, sent to the recipient or,
        in the case of the HEAD method, the size of the entity-body that would
        have been sent had the request been a GET.''')
    content_location = header_property('Content-Location', doc='''
        The Content-Location entity-header field MAY be used to supply the
        resource location for the entity enclosed in the message when that
        entity is accessible from a location separate from the requested
        resource's URI.''')
    content_encoding = header_property('Content-Encoding', doc='''
        The Content-Encoding entity-header field is used as a modifier to the
        media-type.  When present, its value indicates what additional content
        codings have been applied to the entity-body, and thus what decoding
        mechanisms must be applied in order to obtain the media-type
        referenced by the Content-Type header field.''')
    content_md5 = header_property('Content-MD5', doc='''
         The Content-MD5 entity-header field, as defined in RFC 1864, is an
         MD5 digest of the entity-body for the purpose of providing an
         end-to-end message integrity check (MIC) of the entity-body.  (Note:
         a MIC is good for detecting accidental modification of the
         entity-body in transit, but is not proof against malicious attacks.)
        ''')
    date = header_property('Date', None, parse_date, http_date, doc='''
        The Date general-header field represents the date and time at which
        the message was originated, having the same semantics as orig-date
        in RFC 822.''')
    expires = header_property('Expires', None, parse_date, http_date, doc='''
        The Expires entity-header field gives the date/time after which the
        response is considered stale. A stale cache entry may not normally be
        returned by a cache.''')
    last_modified = header_property(
        'Last-Modified', None, parse_date, http_date, doc='''
        The Last-Modified entity-header field indicates the date and time at
        which the origin server believes the variant was last modified.'''
    )

    def _get_retry_after(self):
        value = self.headers.get('retry-after')
        if value is None:
            return
        elif value.isdigit():
            return datetime.utcnow() + timedelta(seconds=int(value))
        return parse_date(value)

    def _set_retry_after(self, value):
        if value is None:
            if 'retry-after' in self.headers:
                del self.headers['retry-after']
            return
        elif isinstance(value, datetime):
            value = http_date(value)
        else:
            value = str(value)
        self.headers['Retry-After'] = value

    retry_after = property(_get_retry_after, _set_retry_after, doc='''
        The Retry-After response-header field can be used with a 503 (Service
        Unavailable) response to indicate how long the service is expected
        to be unavailable to the requesting client.

        Time in seconds until expiration or date.''')

    def _set_property(name, doc=None):
        def fget(self):
            def on_update(header_set):
                if not header_set and name in self.headers:
                    del self.headers[name]
                elif header_set:
                    self.headers[name] = header_set.to_header()
            return parse_set_header(self.headers.get(name), on_update)

        def fset(self, value):
            if not value:
                del self.headers[name]
            elif isinstance(value, str):
                self.headers[name] = value
            else:
                self.headers[name] = dump_header(value)
        return property(fget, fset, doc=doc)

    vary = _set_property('Vary', doc='''
         The Vary field value indicates the set of request-header fields that
         fully determines, while the response is fresh, whether a cache is
         permitted to use the response to reply to a subsequent request
         without revalidation.''')
    content_language = _set_property('Content-Language', doc='''
         The Content-Language entity-header field describes the natural
         language(s) of the intended audience for the enclosed entity.  Note
         that this might not be equivalent to all the languages used within
         the entity-body.''')
    allow = _set_property('Allow', doc='''
        The Allow entity-header field lists the set of methods supported
        by the resource identified by the Request-URI. The purpose of this
        field is strictly to inform the recipient of valid methods
        associated with the resource. An Allow header field MUST be
        present in a 405 (Method Not Allowed) response.''')

    del (
        _set_property,
        _get_mimetype, _set_mimetype,
        _get_retry_after, _set_retry_after
    )

class WWWAuthenticateMixin(object):

    """Adds a :attr:`www_authenticate` property to a response object."""

    @property
    def www_authenticate(self):
        """The `WWW-Authenticate` header in a parsed form."""
        def on_update(www_auth):
            if not www_auth and 'www-authenticate' in self.headers:
                del self.headers['www-authenticate']
            elif www_auth:
                self.headers['WWW-Authenticate'] = www_auth.to_header()
        header = self.headers.get('www-authenticate')
        return parse_www_authenticate_header(header, on_update)

class Response(
    BaseResponse, ETagResponseMixin, ResponseStreamMixin,
    CommonResponseDescriptorsMixin,
    WWWAuthenticateMixin,
):

    """Full featured response object implementing the following mixins:

    - :class:`ETagResponseMixin` for etag and cache control handling
    - :class:`ResponseStreamMixin` to add support for the `stream` property
    - :class:`CommonResponseDescriptorsMixin` for various HTTP descriptors
    - :class:`WWWAuthenticateMixin` for HTTP authentication support
    """


text:
using Prism.Mvvm;
using Prism.Navigation;

namespace Demo.ViewModels
{
    public class ViewModelBase : BindableBase, IInitialize, INavigationAware, IDestructible
    {
        protected INavigationService NavigationService { get; private set; }

        private string _title;
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public ViewModelBase(INavigationService navigationService)
        {
            NavigationService = navigationService;
        }

        public virtual void Initialize(INavigationParameters parameters)
        {

        }

        public virtual void OnNavigatedFrom(INavigationParameters parameters)
        {

        }

        public virtual void OnNavigatedTo(INavigationParameters parameters)
        {

        }

        public virtual void Destroy()
        {

        }
    }
}


text:
namespace PlexAlloc
{
	// CAtlPlex-like allocator compatible with node-based STL collections (linked lists, RB trees, hash maps).
	template <typename T, size_t nBlockSize = 10, size_t align = alignof ( T )>
	class Allocator
	{
		Plex<T, nBlockSize, align> m_plex;
		FreeList<T> m_freeList;

	public:
		using value_type = T;
		using size_type = std::size_t;
		using propagate_on_container_move_assignment = std::true_type;

		template<class U>
		struct rebind { using other = Allocator<U, nBlockSize, align>; };

		Allocator() noexcept {};

		Allocator( const Allocator& ) noexcept {};

		template <typename U, size_t bs, size_t a>
		Allocator( const Allocator<U, bs, a>& ) noexcept {};

		Allocator( Allocator&& other ) noexcept: m_plex( other.m_plex ), m_freeList( other.m_freeList ) { }

		Allocator& operator = ( const Allocator& ) noexcept
		{
			return *this;
		}

		Allocator& operator = ( Allocator&& other ) noexcept
		{
			m_freeList = other.m_freeList;
			m_plex = other.m_plex;
			return *this;
		}

		~Allocator() noexcept = default;

		T* allocate( size_type n )
		{
			if( 1 == n )
			{
				if( m_freeList.empty() )
					return m_plex.allocate();
				return m_freeList.pop();
			}
			// Fall back to malloc.
			// This is used in e.g. Microsoft's std::unordered_map, which holds both individual nodes of type _List_node<pair<K,V>>, and also a vector of _List_unchecked_iterator<_List_val<_List_simple_types<pair<K,V>>>>
			void* const pArray = alignedMalloc( n * sizeof( T ), align );
			if( nullptr == pArray )
				throw std::bad_alloc();
			return static_cast<T*>( pArray );
		}

		void deallocate( T* ptr, size_type n ) noexcept
		{
			if( 1 == n )
				m_freeList.push( ptr );
			else
				alignedFree( ptr );
		}
	};

#ifdef _MSC_VER
	// In Microsoft's version of STL, when _ITERATOR_DEBUG_LEVEL is non-zero, each collection contains a dynamically-allocated pointer to a _Container_proxy instance.
	// We don't want to use PlexAlloc allocator for that one.
	template<size_t nBlockSize, size_t align>
	class Allocator<std::_Container_proxy, nBlockSize, align>: public std::allocator<std::_Container_proxy>
	{
	public:
		Allocator() noexcept {};
		Allocator( const Allocator& ) noexcept = default;

		template <typename U, size_t bs, size_t a>
		Allocator( const Allocator<U, bs, a>& ) noexcept {}

		template<class U>
		struct rebind { using other = Allocator<U, nBlockSize, align>; };
	};
#endif
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
    <title>Université d'Oran 1 Ahmed Ben Bella - Accueil</title>

    <link href="../../css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
    <link href="../../css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
    <link href="../../css/material-icons.css" rel="stylesheet">
    <link rel="icon" type="image/png" href="../../image/favicon.ico"/>

SYSTEMES ET RESEAUX

MAISON DE DOCTORANT

UCI

C.E.I.L

BLEU01

PRESENTATION

BILAN TELE-ENSEIGNEMENT

COURS EN LIGNE

INSCRIPTION ENSEIGNATNTS

INSCRIPTION ETUDIANTS

FORMATION: LICENCE

FORMATION: MASTER

ACTUALITES

PREAMBULE

objectifs et finalites

Modalités pratiques

EVALUATIONS DU DISPOSITIF TUTORAL

DOCUMENTS UTILES

PUO/RUO

VISIO CONFERENCE

PRESENTATION

RECHERCHE SCIENTIFIQUE

SYSTEMES ET RESEAUX

MAISON DE DOCTORANT

UCI

C.E.I.L

BLEU01

PRESENTATION

BILAN TELE-ENSEIGNEMENT

COURS EN LIGNE

INSCRIPTION ENSEIGNATNTS

INSCRIPTION ETUDIANTS

FORMATION: LICENCE

FORMATION: MASTER

ACTUALITES

PREAMBULE

objectifs et finalites

Modalités pratiques

EVALUATIONS DISPOSITIF TUTORAL

DOCUMENTS UTILES

PUO/RUO

VISIO CONFERENCE

PRESENTATION

RECHERCHE SCIENTIFIQUE

        menu

ACCEUIL

FACULTES

NO SERVICESarrow_drop_down

TELE-ENSEIGNEMENTarrow_drop_down

GRADUATIONarrow_drop_down

TUTORATarrow_drop_down

LIENS UTILESarrow_drop_down

search

ACCEUIL

FACULTES

NO SERVICESarrow_drop_down

TELE-ENSEIGNEMENTarrow_drop_down

GRADUATIONarrow_drop_down

TUTORATarrow_drop_down

LIENS UTILESarrow_drop_down

        <form>

                <input id="search" type="search" required>

search

        </form>

            Acceuil
            Tutorat
            Documents utiles

Documents Utiles

-Guide Tutorat FR

-Guide Tutorat AR

-Manuel

© Université d'Oran 1 Ahmed Ben Bella 2017

L'Université d'Oran est pluridisciplinaire, elle assure la formation
                    et la recherche dans de nombreux domaines: sciences, techniques, santé, sciences sociales et
                    humaines, économie, gestion, droit, lettres, langues et arts.

Nous contacter

                            Contacte

Contact

Téléphone : +213 (0) 41 51 92 34

                                    Courriel : contact@univ-oran.dz

                                    Facebook

Adresse postale : BP 1524 ELM_Naouer 31000 oran, algérie

                            Mail

                            FTP

Réseau social

                            LinkedIn

                            Twitter

                            Facebook

            Made by  DJEZIRI Ibtissem
            &  CHOUIB Chawki


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

    <EditText
        android:id="@+id/textToBeSaved"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/saveDataButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save Data" />

    <Button
        android:id="@+id/loadDataButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load Saved Data" />

</LinearLayout>


text:
package gedi.util.io.randomaccess.diskarray;

import gedi.util.io.randomaccess.PageFile;
import gedi.util.io.randomaccess.PageFileView;
import gedi.util.io.randomaccess.serialization.BinarySerializable;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Collection;
import java.util.function.Supplier;

/**
 * Format: n longs for pointers to data region, then dataregion
 * @author erhard
 *
 */
public class VariableSizeDiskArray<T extends BinarySerializable> extends DiskArray<T> {

	private long len;
	private PageFileView index;

	public VariableSizeDiskArray(String path) throws IOException {
		this(path,null);
	}

	public VariableSizeDiskArray(String path, Supplier<T> supplier) throws IOException {
		super(path,supplier);
		file = new RandomAccessFile(new File(path),"r");
		this.supplier = supplier;
	}

	public long indexToOffset(long index) throws IOException {
		return this.index.getLong(index*Long.BYTES);
	}

	public long length() {
		return len/Long.BYTES;
	}

	@Override
	protected PageFileView createData(String path) throws IOException {
		len = file.readLong();
		index = new PageFileView(new PageFile(path),0,len);
		return new PageFileView(new PageFile(path),len,file.length());
	}

	public <C extends Collection<? super T>> C getCollection(long index, C re) throws IOException {
		long nextOffset;
		if (index==length()-1) nextOffset = this.data.getEnd();
		else nextOffset = indexToOffset(index+1);

		long offset = indexToOffset(index);
		data.position(offset-data.getStart());
		while (data.position()<nextOffset-data.getStart()) {
			T r = supplier.get();
			r.deserialize(data);
			re.add(r);
		}

		return re;
	}

}


text:
package cmd

import (
	"fmt"
	"os"
	"text/template"

	"github.com/docker/machine/libmachine/state"
	"github.com/golang/glog"
	"github.com/spf13/cobra"
	cmdUtil "k8s.io/minikube/cmd/util"
	"k8s.io/minikube/pkg/minikube/cluster"
	"k8s.io/minikube/pkg/minikube/config"
	"k8s.io/minikube/pkg/minikube/constants"
	"k8s.io/minikube/pkg/minikube/machine"
	"k8s.io/minikube/pkg/util/kubeconfig"
)

var statusFormat string

type Status struct {
	MinikubeStatus   string
	LocalkubeStatus  string
	KubeconfigStatus string
}

// statusCmd represents the status command
var statusCmd = &cobra.Command{
	Use:   "status",
	Short: "Gets the status of a local kubernetes cluster",
	Long:  `Gets the status of a local kubernetes cluster.`,
	Run: func(cmd *cobra.Command, args []string) {
		api, err := machine.NewAPIClient()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error getting client: %s\n", err)
			os.Exit(1)
		}
		defer api.Close()

		ms, err := cluster.GetHostStatus(api)
		if err != nil {
			glog.Errorln("Error getting machine status:", err)
			cmdUtil.MaybeReportErrorAndExit(err)
		}

		ls := state.None.String()
		ks := state.None.String()
		if ms == state.Running.String() {
			ls, err = cluster.GetLocalkubeStatus(api)
			if err != nil {
				glog.Errorln("Error localkube status:", err)
				cmdUtil.MaybeReportErrorAndExit(err)
			}
			ip, err := cluster.GetHostDriverIP(api)
			if err != nil {
				glog.Errorln("Error host driver ip status:", err)
				cmdUtil.MaybeReportErrorAndExit(err)
			}
			kstatus, err := kubeconfig.GetKubeConfigStatus(ip, cmdUtil.GetKubeConfigPath(), config.GetMachineName())
			if err != nil {
				glog.Errorln("Error kubeconfig status:", err)
				cmdUtil.MaybeReportErrorAndExit(err)
			}
			if kstatus {
				ks = "Correctly Configured: pointing to minikube-vm at " + ip.String()
			} else {
				ks = "Misconfigured: pointing to stale minikube-vm." +
					"\nTo fix the kubectl context, run minikube update-context"
			}
		}

		status := Status{ms, ls, ks}

		tmpl, err := template.New("status").Parse(statusFormat)
		if err != nil {
			glog.Errorln("Error creating status template:", err)
			os.Exit(1)
		}
		err = tmpl.Execute(os.Stdout, status)
		if err != nil {
			glog.Errorln("Error executing status template:", err)
			os.Exit(1)
		}
	},
}

func init() {
	statusCmd.Flags().StringVar(&statusFormat, "format", constants.DefaultStatusFormat,
		`Go template format string for the status output.  The format for Go templates can be found here: https://golang.org/pkg/text/template/
For the list accessible variables for the template, see the struct values here: https://godoc.org/k8s.io/minikube/cmd/minikube/cmd#Status`)
	RootCmd.AddCommand(statusCmd)
}


text:
namespace FootballBetting.Models
{
    public class Competition
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public CompetitionType CompetitionType { get; set; }
    }
}


text:
package com.github.j5ik2o.forseti.adaptor.repository

trait IdConfig {

  val timestampBits: Int

  val dataCenterIdBits: Int

  val workerIdBits: Int

  val sequenceBits: Int

  val epoch: Long

  lazy val maxTimestamp: Long = -1L ^ (-1L << timestampBits)

  lazy val maxDataCenterId: Long = -1L ^ (-1L << dataCenterIdBits)

  lazy val maxIdWorkerId: Long = -1L ^ (-1L << workerIdBits)

  lazy val maxSequence: Long = -1L ^ (-1L << sequenceBits)

  lazy val timestampShift: Int = sequenceBits + workerIdBits + dataCenterIdBits

  lazy val dataCenterIdShift = sequenceBits + workerIdBits

  lazy val workerIdShift: Int = sequenceBits

  lazy val timestampMask: Long = -1L ^ (-1L << (timestampBits + timestampShift))

  lazy val dataCenterIdMask: Long = -1L ^ (-1L << (dataCenterIdBits + dataCenterIdShift))

  lazy val workerIdMask: Long = -1L ^ (-1L << (workerIdBits + workerIdShift))

  lazy val sequenceMask: Long = -1L ^ (-1L << sequenceBits)

}

object IdConfig {

  def apply(
      timestampBits: Int,
      dataCenterIdBits: Int,
      workerIdBits: Int,
      sequenceBits: Int,
      epoch: Long
  ): IdConfig =
    Default(timestampBits, dataCenterIdBits, workerIdBits, sequenceBits, epoch)

  private case class Default(
      timestampBits: Int,
      dataCenterIdBits: Int,
      workerIdBits: Int,
      sequenceBits: Int,
      epoch: Long
  ) extends IdConfig

}


text:
package com.guyazhou.examples.dp.factory.abstract_factory;

/**
 * Created by YaZhou.Gu on 2017/9/19.
 */
public interface AbstractFactory {

    Cpu createCpu();

    Mainboard createMainboard();

}


text:
using System;
using Famoser.SyncApi.Enums;

namespace Famoser.SyncApi.Storage.Roaming
{
    public class ApiRoamingEntity
    {
        public Guid UserId { get; set; }
        public int PersonalSeed { get; set; }
        public int RequestCount { get; set; } = 0;
        public AuthenticationState AuthenticationState { get; set; }
        public DateTime CreatedAt { get; set; }
    }
}


text:
FluidVids is a raw JavaScript solution for responsive and fluid YouTube and Vimeo video embeds. It's extremely lightweight, and comes with a minified version for production environments. FluidVids comes preconfigured to make YouTube and Vimeo videos fluid, but you can add more as you please. You don't need to call FluidVids, it will just work its magic on video embeds automatically.

## Demo
Check out a [demo of FluidVids](http://toddmotto.com/labs/fluidvids).

## Installing with Bower
To install FluidVids into your project using Bower, use the GitHub repository hook:

```
bower install https://github.com/toddmotto/fluidvids.git
```

## Manual installation
Drop your files into your required folders, make sure you're using the files from the `dist` folder, which is the compiled production-ready code. Ensure you place the script before the closing `</body>` tag so the DOM tree is populated when the script runs.

```html
<body>
	<!-- html content above -->
	<script src="dist/fluidvids.js"></script>
</body>
```

## Scaffolding
Project files and folder structure.

```
├── dist/
│   ├── fluidvids.js
│   └── fluidvids.min.js
├── src/
│   └── fluidvids.js
├── .editorconfig
├── .gitignore
├── .jshintrc
├── .travis.yml
├── Gruntfile.js
├── config.json
└── package.json
```

## Grunt tasks
FluidVids comes pre-configured with `Gruntfile.js` which contains all of Grunt's tasks. These tasks are `grunt-contrib-concat` for concatenating files, `grunt-contrib-jshint` for JSHinting the project files, `grunt-contrib-uglify` for minifying the code. The hidden file `.jshintrc` contains the configuration for the JSHint tests.

## Adding more video players
FluidVids use a Regular Expression and searches the `src=""` attribute of any `iframe` tags on the page. If the RegExp matches the attribute, FluidVids will then do it's thing and make your videos responsive.

Here's the line you'll need to change:

```javascript
players = /www.youtube.com|player.vimeo.com/;
```

The dividing `|` operator is essentially 'or' in RegExp. For instance, if you wanted to add the no cookies version of YouTube, you could action the following:

```javascript
players = /www.youtube.com|www.youtube-nocookie.com|player.vimeo.com/;
```

## License
MIT license


text:
#ifndef __S1SBP6A_WATCHDOG_H
#define __S1SBP6A_WATCHDOG_H

/* Control Register 0 */
#define WDOGCTRL_RESET_ENABLE_SHIFT            (0)
#define WDOGCTRL_INT_ENABLE_SHIFT              (1)

#define WDOGCTRL_RESET_ENABLE_MASK            (0x01 << WDOGCTRL_RESET_ENABLE_SHIFT)
#define WDOGCTRL_INT_ENABLE_MASK              (0x01 << WDOGCTRL_INT_ENABLE_SHIFT)

#define WDOGCTRL_RESET_ENABLE(c)              ((c) << WDOGCTRL_RESET_ENABLE_SHIFT)
#define WDOGCTRL_INT_ENABLE(c)                ((c) << WDOGCTRL_INT_ENABLE_SHIFT)

void bp6a_wdog_init(uint32_t timeout);
void bp6a_watchdog_enable(bool enable);
void bp6a_wdog_reset_enable(bool enable);
void bp6a_wdog_set_reload_time(uint32_t ms);

#endif /* __S1SBP6A_WATCHDOG_H */


text:
using ReMi.BusinessEntities.ProductRequests;
using ReMi.Contracts.Cqrs.Commands;

namespace ReMi.Commands.ProductRequests
{
    [Command("Update product request type", CommandGroup.ProductRequest)]
    public class UpdateProductRequestTypeCommand : ICommand
    {
        public CommandContext CommandContext { get; set; }

        public ProductRequestType RequestType { get; set; }

        public override string ToString()
        {
            return string.Format("[RequestType={0}, CommandContext={1}]",
                RequestType, CommandContext);
        }
    }
}