text:
package API::Deliveryservice;
#
#
# 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.
#
#
#
# a note about locations and cachegroups. This used to be "Location", before we had physical locations in 12M. Very confusing.
# What used to be called a location is now called a "cache group" and location is now a physical address, not a group of caches working together.
#

# JvD Note: you always want to put Utils as the first use. Sh*t don't work if it's after the Mojo lines.
use UI::Utils;

use Mojo::Base 'Mojolicious::Controller';
use Data::Dumper;
use JSON;
use MojoPlugins::Response;
use UI::DeliveryService;
use Validate::Tiny ':all';

sub index {
	my $self         = shift;
	my $orderby      = $self->param('orderby') || "xml_id";
	my $cdn_id       = $self->param('cdn');
	my $profile_id   = $self->param('profile');
	my $type_id      = $self->param('type');
	my $logs_enabled = $self->param('logsEnabled');
	my $current_user = $self->current_user()->{username};
	my @data;

	my %criteria;
	if ( defined $cdn_id ) {
		$criteria{'me.cdn_id'} = $cdn_id;
	}
	if ( defined $profile_id ) {
		$criteria{'me.profile'} = $profile_id;
	}
	if ( defined $type_id ) {
		$criteria{'me.type'} = $type_id;
	}
	if ( defined $logs_enabled ) {
		$criteria{'me.logs_enabled'} = $logs_enabled ? 1 : 0;    # converts bool to 0|1
	}

	if ( !&is_privileged($self) ) {
		my $tm_user = $self->db->resultset('TmUser')->search( { username => $current_user } )->single();
		my @ds_ids = $self->db->resultset('DeliveryserviceTmuser')->search( { tm_user_id => $tm_user->id } )->get_column('deliveryservice')->all();
		$criteria{'me.id'} = { -in => \@ds_ids },;
	}

	my $rs_data = $self->db->resultset("Deliveryservice")->search(
		\%criteria,
		{ prefetch => [ 'cdn', { 'deliveryservice_regexes' => { 'regex' => 'type' } }, 'profile', 'type' ], order_by => 'me.' . $orderby }
	);

	while ( my $row = $rs_data->next ) {

		# build example urls for each delivery service
		my @example_urls = ();
		my $cdn_domain   = $row->cdn->domain_name;
		my $ds_regexes = $row->deliveryservice_regexes;
		my $regexp_set;
		my $i = 0;

		while ( my $ds_regex = $ds_regexes->next ) {
			$regexp_set->[$i]->{id}         = $ds_regex->id;
			$regexp_set->[$i]->{pattern}    = $ds_regex->regex->pattern;
			$regexp_set->[$i]->{type}    	= $ds_regex->regex->type->name;
			$regexp_set->[$i]->{set_number} = $ds_regex->set_number;
			$i++;
		}

		@example_urls = &UI::DeliveryService::get_example_urls( $self, $row->id, $regexp_set, $row, $cdn_domain, $row->protocol );

		push(
			@data, {
				"active"               => \$row->active,
				"cacheurl"             => $row->cacheurl,
				"ccrDnsTtl"            => $row->ccr_dns_ttl,
				"cdnId"                => $row->cdn->id,
				"cdnName"              => $row->cdn->name,
				"checkPath"            => $row->check_path,
				"displayName"          => $row->display_name,
				"dnsBypassCname"       => $row->dns_bypass_cname,
				"dnsBypassIp"          => $row->dns_bypass_ip,
				"dnsBypassIp6"         => $row->dns_bypass_ip6,
				"dnsBypassTtl"         => $row->dns_bypass_ttl,
				"dscp"                 => $row->dscp,
				"edgeHeaderRewrite"    => $row->edge_header_rewrite,
				"exampleURLs"          => \@example_urls,
				"geoLimitRedirectURL"  => $row->geolimit_redirect_url,
				"geoLimit"             => $row->geo_limit,
				"geoLimitCountries"    => $row->geo_limit_countries,
				"geoProvider"          => $row->geo_provider,
				"globalMaxMbps"        => $row->global_max_mbps,
				"globalMaxTps"         => $row->global_max_tps,
				"httpBypassFqdn"       => $row->http_bypass_fqdn,
				"id"                   => $row->id,
				"infoUrl"              => $row->info_url,
				"initialDispersion"    => $row->initial_dispersion,
				"ipv6RoutingEnabled"   => \$row->ipv6_routing_enabled,
				"lastUpdated"          => $row->last_updated,
				"logsEnabled"          => \$row->logs_enabled,
				"longDesc"             => $row->long_desc,
				"longDesc1"            => $row->long_desc_1,
				"longDesc2"            => $row->long_desc_2,
				"maxDnsAnswers"        => $row->max_dns_answers,
				"midHeaderRewrite"     => $row->mid_header_rewrite,
				"missLat"              => defined( $row->miss_lat ) ? 0.0 + $row->miss_lat : undef,
				"missLong"             => defined( $row->miss_long ) ? 0.0 + $row->miss_long : undef,
				"multiSiteOrigin"      => \$row->multi_site_origin,
				"orgServerFqdn"        => $row->org_server_fqdn,
				"originShield"         => $row->origin_shield,
				"profileId"            => defined( $row->profile ) ? $row->profile->id : undef,
				"profileName"          => defined( $row->profile ) ? $row->profile->name : undef,
				"profileDescription"   => defined( $row->profile ) ? $row->profile->description : undef,
				"protocol"             => $row->protocol,
				"qstringIgnore"        => $row->qstring_ignore,
				"rangeRequestHandling" => $row->range_request_handling,
				"regexRemap"           => $row->regex_remap,
				"regionalGeoBlocking"  => \$row->regional_geo_blocking,
				"remapText"            => $row->remap_text,
				"signed"               => \$row->signed,
				"sslKeyVersion"        => $row->ssl_key_version,
				"trRequestHeaders"     => $row->tr_request_headers,
				"trResponseHeaders"    => $row->tr_response_headers,
				"type"                 => $row->type->name,
				"typeId"               => $row->type->id,
				"xmlId"                => $row->xml_id
			}
		);
	}
	$self->success( \@data );
}

sub show {
	my $self         = shift;
	my $id           = $self->param('id');
	my $current_user = $self->current_user()->{username};
	my @data;

	if ( !&is_privileged($self) ) {

		# check to see if deliveryservice is assigned to user, if not return forbidden
		my $tm_user = $self->db->resultset('TmUser')->search( { username => $current_user } )->single();
		my @ds_ids = $self->db->resultset('DeliveryserviceTmuser')->search( { tm_user_id => $tm_user->id } )->get_column('deliveryservice')->all();
		my %map = map { $_ => 1 } @ds_ids;    # turn the array of dsIds into a hash with dsIds as the keys
		return $self->forbidden() if ( !exists( $map{$id} ) );
	}

	my $rs = $self->db->resultset("Deliveryservice")->search(
		{ 'me.id' => $id },
		{ prefetch => [ 'cdn', { 'deliveryservice_regexes' => { 'regex' => 'type' } }, 'profile', 'type' ] }
	);
	while ( my $row = $rs->next ) {

		# build the matchlist (the list of ds regexes and their type)
		my @matchlist  = ();
		my $ds_regexes = $row->deliveryservice_regexes;

		while ( my $ds_regex = $ds_regexes->next ) {
			push(
				@matchlist, {
					type      => $ds_regex->regex->type->name,
					pattern   => $ds_regex->regex->pattern,
					setNumber => $ds_regex->set_number
				}
			);
		}

		# build example urls for the delivery service
		my @example_urls = ();
		my $cdn_domain   = $row->cdn->domain_name;

		$ds_regexes->reset; # need to reset the curson
		my $regexp_set;
		my $i = 0;

		while ( my $ds_regex = $ds_regexes->next ) {
			$regexp_set->[$i]->{id}         = $ds_regex->id;
			$regexp_set->[$i]->{pattern}    = $ds_regex->regex->pattern;
			$regexp_set->[$i]->{type}    	= $ds_regex->regex->type->name;
			$regexp_set->[$i]->{set_number} = $ds_regex->set_number;
			$i++;
		}

		@example_urls = &UI::DeliveryService::get_example_urls( $self, $row->id, $regexp_set, $row, $cdn_domain, $row->protocol );

		push(
			@data, {
				"active"               => \$row->active,
				"cacheurl"             => $row->cacheurl,
				"ccrDnsTtl"            => $row->ccr_dns_ttl,
				"cdnId"                => $row->cdn->id,
				"cdnName"              => $row->cdn->name,
				"checkPath"            => $row->check_path,
				"displayName"          => $row->display_name,
				"dnsBypassCname"       => $row->dns_bypass_cname,
				"dnsBypassIp"          => $row->dns_bypass_ip,
				"dnsBypassIp6"         => $row->dns_bypass_ip6,
				"dnsBypassTtl"         => $row->dns_bypass_ttl,
				"dscp"                 => $row->dscp,
				"edgeHeaderRewrite"    => $row->edge_header_rewrite,
				"exampleURLs"          => \@example_urls,
				"geoLimitRedirectURL"  => $row->geolimit_redirect_url,
				"geoLimit"             => $row->geo_limit,
				"geoLimitCountries"    => $row->geo_limit_countries,
				"geoProvider"          => $row->geo_provider,
				"globalMaxMbps"        => $row->global_max_mbps,
				"globalMaxTps"         => $row->global_max_tps,
				"httpBypassFqdn"       => $row->http_bypass_fqdn,
				"id"                   => $row->id,
				"infoUrl"              => $row->info_url,
				"initialDispersion"    => $row->initial_dispersion,
				"ipv6RoutingEnabled"   => \$row->ipv6_routing_enabled,
				"lastUpdated"          => $row->last_updated,
				"logsEnabled"          => \$row->logs_enabled,
				"longDesc"             => $row->long_desc,
				"longDesc1"            => $row->long_desc_1,
				"longDesc2"            => $row->long_desc_2,
				"matchList"            => \@matchlist,
				"maxDnsAnswers"        => $row->max_dns_answers,
				"midHeaderRewrite"     => $row->mid_header_rewrite,
				"missLat"              => defined( $row->miss_lat ) ? 0.0 + $row->miss_lat : undef,
				"missLong"             => defined( $row->miss_long ) ? 0.0 + $row->miss_long : undef,
				"multiSiteOrigin"      => \$row->multi_site_origin,
				"orgServerFqdn"        => $row->org_server_fqdn,
				"originShield"         => $row->origin_shield,
				"profileId"            => defined( $row->profile ) ? $row->profile->id : undef,
				"profileName"          => defined( $row->profile ) ? $row->profile->name : undef,
				"profileDescription"   => defined( $row->profile ) ? $row->profile->description : undef,
				"protocol"             => $row->protocol,
				"qstringIgnore"        => $row->qstring_ignore,
				"rangeRequestHandling" => $row->range_request_handling,
				"regexRemap"           => $row->regex_remap,
				"regionalGeoBlocking"  => \$row->regional_geo_blocking,
				"remapText"            => $row->remap_text,
				"signed"               => \$row->signed,
				"sslKeyVersion"        => $row->ssl_key_version,
				"trRequestHeaders"     => $row->tr_request_headers,
				"trResponseHeaders"    => $row->tr_response_headers,
				"type"                 => $row->type->name,
				"typeId"               => $row->type->id,
				"xmlId"                => $row->xml_id
			}
		);
	}
	$self->success( \@data );
}

sub update {
	my $self   = shift;
	my $id     = $self->param('id');
	my $params = $self->req->json;

	if ( !&is_oper($self) ) {
		return $self->forbidden();
	}

	my ( $is_valid, $result ) = $self->is_deliveryservice_valid($params);
	if ( !$is_valid ) {
		return $self->alert($result);
	}

	my $ds = $self->db->resultset('Deliveryservice')->find( { id => $id } );
	if ( !defined($ds) ) {
		return $self->not_found();
	}

	my $xml_id = $params->{xmlId};
	if ( $ds->xml_id ne $xml_id ) {
		my $existing = $self->db->resultset('Deliveryservice')->find( { xml_id => $xml_id } );
		if ($existing) {
			return $self->alert( "A deliveryservice with xmlId " . $xml_id . " already exists." );
		}
	}

	my $values = {
		active                 => $params->{active},
		cacheurl               => $params->{cacheurl},
		ccr_dns_ttl            => $params->{ccrDnsTtl},
		cdn_id                 => $params->{cdnId},
		check_path             => $params->{checkPath},
		display_name           => $params->{displayName},
		dns_bypass_cname       => $params->{dnsBypassCname},
		dns_bypass_ip          => $params->{dnsBypassIp},
		dns_bypass_ip6         => $params->{dnsBypassIp6},
		dns_bypass_ttl         => $params->{dnsBypassTtl},
		dscp                   => $params->{dscp},
		edge_header_rewrite    => $params->{edgeHeaderRewrite},
		geolimit_redirect_url  => $params->{geoLimitRedirectURL},
		geo_limit              => $params->{geoLimit},
		geo_limit_countries    => sanitize_geo_limit_countries( $params->{geoLimitCountries} ),
		geo_provider           => $params->{geoProvider},
		global_max_mbps        => $params->{globalMaxMbps},
		global_max_tps         => $params->{globalMaxTps},
		http_bypass_fqdn       => $params->{httpBypassFqdn},
		info_url               => $params->{infoUrl},
		initial_dispersion     => $params->{initialDispersion},
		ipv6_routing_enabled   => $params->{ipv6RoutingEnabled},
		logs_enabled           => $params->{logsEnabled},
		long_desc              => $params->{longDesc},
		long_desc_1            => $params->{longDesc1},
		long_desc_2            => $params->{longDesc2},
		max_dns_answers        => $params->{maxDnsAnswers},
		mid_header_rewrite     => $params->{midHeaderRewrite},
		miss_lat               => $params->{missLat},
		miss_long              => $params->{missLong},
		multi_site_origin      => $params->{multiSiteOrigin},
		org_server_fqdn        => $params->{orgServerFqdn},
		origin_shield          => $params->{originShield},
		profile                => $params->{profileId},
		protocol               => $params->{protocol},
		qstring_ignore         => $params->{qstringIgnore},
		range_request_handling => $params->{rangeRequestHandling},
		regex_remap            => $params->{regexRemap},
		regional_geo_blocking  => $params->{regionalGeoBlocking},
		remap_text             => $params->{remapText},
		signed                 => $params->{signed},
		ssl_key_version        => $params->{sslKeyVersion},
		tr_request_headers     => $params->{trRequestHeaders},
		tr_response_headers    => $params->{trResponseHeaders},
		type                   => $params->{typeId},
		xml_id                 => $params->{xmlId},
	};

	my $rs = $ds->update($values);
	if ($rs) {

		# create location parameters for header_rewrite*, regex_remap* and cacheurl* config files if necessary
		&UI::DeliveryService::header_rewrite( $self, $rs->id, $params->{profileId}, $params->{xmlId}, $params->{edgeHeaderRewrite}, "edge" );
		&UI::DeliveryService::header_rewrite( $self, $rs->id, $params->{profileId}, $params->{xmlId}, $params->{midHeaderRewrite},  "mid" );
		&UI::DeliveryService::regex_remap( $self, $rs->id, $params->{profileId}, $params->{xmlId}, $params->{regexRemap} );
		&UI::DeliveryService::cacheurl( $self, $rs->id, $params->{profileId}, $params->{xmlId}, $params->{cacheurl} );

		# build example urls
		my @example_urls  = ();
		my $cdn_domain    = $rs->cdn->domain_name;
		my $regexp_set   = &UI::DeliveryService::get_regexp_set( $self, $rs->id );
		@example_urls = &UI::DeliveryService::get_example_urls( $self, $rs->id, $regexp_set, $rs, $cdn_domain, $rs->protocol );

		# build the matchlist (the list of ds regexes and their type)
		my @matchlist  = ();
		my $ds_regexes = $self->db->resultset('DeliveryserviceRegex')->search( { deliveryservice => $rs->id }, { prefetch => [ { 'regex' => 'type' } ] } );
		while ( my $ds_regex = $ds_regexes->next ) {
			push(
				@matchlist, {
					type      => $ds_regex->regex->type->name,
					pattern   => $ds_regex->regex->pattern,
					setNumber => $ds_regex->set_number
				}
			);
		}

		my @response;
		push(
			@response, {
				"active"                   => $rs->active,
				"cacheurl"                 => $rs->cacheurl,
				"ccrDnsTtl"                => $rs->ccr_dns_ttl,
				"cdnId"                    => $rs->cdn->id,
				"cdnName"                  => $rs->cdn->name,
				"checkPath"                => $rs->check_path,
				"displayName"              => $rs->display_name,
				"dnsBypassCname"           => $rs->dns_bypass_cname,
				"dnsBypassIp"              => $rs->dns_bypass_ip,
				"dnsBypassIp6"             => $rs->dns_bypass_ip6,
				"dnsBypassTtl"             => $rs->dns_bypass_ttl,
				"dscp"                     => $rs->dscp,
				"edgeHeaderRewrite"        => $rs->edge_header_rewrite,
				"exampleURLs"              => \@example_urls,
				"geoLimitRedirectURL"      => $rs->geolimit_redirect_url,
				"geoLimit"                 => $rs->geo_limit,
				"geoLimitCountries"        => $rs->geo_limit_countries,
				"geoProvider"              => $rs->geo_provider,
				"globalMaxMbps"            => $rs->global_max_mbps,
				"globalMaxTps"             => $rs->global_max_tps,
				"httpBypassFqdn"           => $rs->http_bypass_fqdn,
				"id"                       => $rs->id,
				"infoUrl"                  => $rs->info_url,
				"initialDispersion"        => $rs->initial_dispersion,
				"ipv6RoutingEnabled"       => $rs->ipv6_routing_enabled,
				"lastUpdated"              => $rs->last_updated,
				"logsEnabled"              => $rs->logs_enabled,
				"longDesc"                 => $rs->long_desc,
				"longDesc1"                => $rs->long_desc_1,
				"longDesc2"                => $rs->long_desc_2,
				"matchList"                => \@matchlist,
				"maxDnsAnswers"            => $rs->max_dns_answers,
				"midHeaderRewrite"         => $rs->mid_header_rewrite,
				"missLat"                  => defined($rs->miss_lat) ? 0.0 + $rs->miss_lat : undef,
				"missLong"                 => defined($rs->miss_long) ? 0.0 + $rs->miss_long : undef,
				"multiSiteOrigin"          => $rs->multi_site_origin,
				"orgServerFqdn"            => $rs->org_server_fqdn,
				"originShield"             => $rs->origin_shield,
				"profileId"                => defined($rs->profile) ? $rs->profile->id : undef,
				"profileName"              => defined($rs->profile) ? $rs->profile->name : undef,
				"profileDescription"       => defined($rs->profile) ? $rs->profile->description : undef,
				"protocol"                 => $rs->protocol,
				"qstringIgnore"            => $rs->qstring_ignore,
				"rangeRequestHandling"     => $rs->range_request_handling,
				"regexRemap"               => $rs->regex_remap,
				"regionalGeoBlocking"      => $rs->regional_geo_blocking,
				"remapText"                => $rs->remap_text,
				"signed"                   => $rs->signed,
				"sslKeyVersion"            => $rs->ssl_key_version,
				"trRequestHeaders"         => $rs->tr_request_headers,
				"trResponseHeaders"        => $rs->tr_response_headers,
				"type"                     => $rs->type->name,
				"typeId"                   => $rs->type->id,
				"xmlId"                    => $rs->xml_id
			}
		);

		&log( $self, "Updated deliveryservice [ '" . $rs->xml_id . "' ] with id: " . $rs->id, "APICHANGE" );

		return $self->success( \@response, "Deliveryservice update was successful." );
	}
	else {
		return $self->alert("Deliveryservice update failed.");
	}
}

sub create {
	my $self   = shift;
	my $params = $self->req->json;

	if ( !&is_oper($self) ) {
		return $self->forbidden();
	}

	my ( $is_valid, $result ) = $self->is_deliveryservice_valid($params);

	if ( !$is_valid ) {
		return $self->alert($result);
	}

	my $xml_id = $params->{xmlId};
	my $existing = $self->db->resultset('Deliveryservice')->find( { xml_id => $xml_id } );
	if ($existing) {
		return $self->alert( "A deliveryservice with xmlId " . $xml_id . " already exists." );
	}

	my $values = {
		active                 => $params->{active},
		cacheurl               => $params->{cacheurl},
		ccr_dns_ttl            => $params->{ccrDnsTtl},
		cdn_id                 => $params->{cdnId},
		check_path             => $params->{checkPath},
		display_name           => $params->{displayName},
		dns_bypass_cname       => $params->{dnsBypassCname},
		dns_bypass_ip          => $params->{dnsBypassIp},
		dns_bypass_ip6         => $params->{dnsBypassIp6},
		dns_bypass_ttl         => $params->{dnsBypassTtl},
		dscp                   => $params->{dscp},
		edge_header_rewrite    => $params->{edgeHeaderRewrite},
		geolimit_redirect_url  => $params->{geoLimitRedirectURL},
		geo_limit              => $params->{geoLimit},
		geo_limit_countries    => sanitize_geo_limit_countries( $params->{geoLimitCountries} ),
		geo_provider           => $params->{geoProvider},
		global_max_mbps        => $params->{globalMaxMbps},
		global_max_tps         => $params->{globalMaxTps},
		http_bypass_fqdn       => $params->{httpBypassFqdn},
		info_url               => $params->{infoUrl},
		initial_dispersion     => $params->{initialDispersion},
		ipv6_routing_enabled   => $params->{ipv6RoutingEnabled},
		logs_enabled           => $params->{logsEnabled},
		long_desc              => $params->{longDesc},
		long_desc_1            => $params->{longDesc1},
		long_desc_2            => $params->{longDesc2},
		max_dns_answers        => $params->{maxDnsAnswers},
		mid_header_rewrite     => $params->{midHeaderRewrite},
		miss_lat               => $params->{missLat},
		miss_long              => $params->{missLong},
		multi_site_origin      => $params->{multiSiteOrigin},
		org_server_fqdn        => $params->{orgServerFqdn},
		origin_shield          => $params->{originShield},
		profile                => $params->{profileId},
		protocol               => $params->{protocol},
		qstring_ignore         => $params->{qstringIgnore},
		range_request_handling => $params->{rangeRequestHandling},
		regex_remap            => $params->{regexRemap},
		regional_geo_blocking  => $params->{regionalGeoBlocking},
		remap_text             => $params->{remapText},
		signed                 => $params->{signed},
		ssl_key_version        => $params->{sslKeyVersion},
		tr_request_headers     => $params->{trRequestHeaders},
		tr_response_headers    => $params->{trResponseHeaders},
		type                   => $params->{typeId},
		xml_id                 => $params->{xmlId},
	};

	my $insert = $self->db->resultset('Deliveryservice')->create($values)->insert();
	if ($insert) {

		&log( $self, "Created delivery service [ '" . $insert->xml_id . "' ] with id: " . $insert->id, "APICHANGE" );

		# create location parameters for header_rewrite*, regex_remap* and cacheurl* config files if necessary
		&UI::DeliveryService::header_rewrite( $self, $insert->id, $params->{profileId}, $params->{xmlId}, $params->{edgeHeaderRewrite}, "edge" );
		&UI::DeliveryService::header_rewrite( $self, $insert->id, $params->{profileId}, $params->{xmlId}, $params->{midHeaderRewrite},  "mid" );
		&UI::DeliveryService::regex_remap( $self, $insert->id, $params->{profileId}, $params->{xmlId}, $params->{regexRemap} );
		&UI::DeliveryService::cacheurl( $self, $insert->id, $params->{profileId}, $params->{xmlId}, $params->{cacheurl} );

		# create a default deliveryservice_regex in the format .*\.xml-id\..*
		$self->create_default_ds_regex( $insert->id, '.*\.' . $insert->xml_id . '\..*' );

		# create dnssec keys if necessary
		my $cdn = $self->db->resultset('Cdn')->search( { id => $params->{cdnId} } )->single();
		my $dnssec_enabled = $cdn->dnssec_enabled;
		if ($dnssec_enabled) {
			&UI::DeliveryService::create_dnssec_keys( $self, $cdn->name, $params->{xmlId}, $insert->id );
			&log( $self, "Created delivery service dnssec keys for [ '" . $insert->xml_id . "' ]", "APICHANGE" );
		}

		# build example urls
		my @example_urls  = ();
		my $cdn_domain   = $insert->cdn->domain_name;
		my $regexp_set   = &UI::DeliveryService::get_regexp_set( $self, $insert->id );
		@example_urls = &UI::DeliveryService::get_example_urls( $self, $insert->id, $regexp_set, $insert, $cdn_domain, $insert->protocol );

		# build the matchlist (the list of ds regexes and their type)
		my @matchlist  = ();
		my $ds_regexes = $self->db->resultset('DeliveryserviceRegex')->search( { deliveryservice => $insert->id }, { prefetch => [ { 'regex' => 'type' } ] } );
		while ( my $ds_regex = $ds_regexes->next ) {
			push(
				@matchlist, {
					type      => $ds_regex->regex->type->name,
					pattern   => $ds_regex->regex->pattern,
					setNumber => $ds_regex->set_number
				}
			);
		}

		my @response;
		push(
			@response, {
				"active"                   => $insert->active,
				"cacheurl"                 => $insert->cacheurl,
				"ccrDnsTtl"                => $insert->ccr_dns_ttl,
				"cdnId"                    => $insert->cdn->id,
				"cdnName"                  => $insert->cdn->name,
				"checkPath"                => $insert->check_path,
				"displayName"              => $insert->display_name,
				"dnsBypassCname"           => $insert->dns_bypass_cname,
				"dnsBypassIp"              => $insert->dns_bypass_ip,
				"dnsBypassIp6"             => $insert->dns_bypass_ip6,
				"dnsBypassTtl"             => $insert->dns_bypass_ttl,
				"dscp"                     => $insert->dscp,
				"edgeHeaderRewrite"        => $insert->edge_header_rewrite,
				"exampleURLs"              => \@example_urls,
				"geoLimitRedirectURL"      => $insert->geolimit_redirect_url,
				"geoLimit"                 => $insert->geo_limit,
				"geoLimitCountries"        => $insert->geo_limit_countries,
				"geoProvider"              => $insert->geo_provider,
				"globalMaxMbps"            => $insert->global_max_mbps,
				"globalMaxTps"             => $insert->global_max_tps,
				"httpBypassFqdn"           => $insert->http_bypass_fqdn,
				"id"                       => $insert->id,
				"infoUrl"                  => $insert->info_url,
				"initialDispersion"        => $insert->initial_dispersion,
				"ipv6RoutingEnabled"       => $insert->ipv6_routing_enabled,
				"lastUpdated"              => $insert->last_updated,
				"logsEnabled"              => $insert->logs_enabled,
				"longDesc"                 => $insert->long_desc,
				"longDesc1"                => $insert->long_desc_1,
				"longDesc2"                => $insert->long_desc_2,
				"matchList"                => \@matchlist,
				"maxDnsAnswers"            => $insert->max_dns_answers,
				"midHeaderRewrite"         => $insert->mid_header_rewrite,
				"missLat"                  => defined($insert->miss_lat) ? 0.0 + $insert->miss_lat : undef,
				"missLong"                 => defined($insert->miss_long) ? 0.0 + $insert->miss_long : undef,
				"multiSiteOrigin"          => $insert->multi_site_origin,
				"orgServerFqdn"            => $insert->org_server_fqdn,
				"originShield"             => $insert->origin_shield,
				"profileId"                => defined($insert->profile) ? $insert->profile->id : undef,
				"profileName"              => defined($insert->profile) ? $insert->profile->name : undef,
				"profileDescription"       => defined($insert->profile) ? $insert->profile->description : undef,
				"protocol"                 => $insert->protocol,
				"qstringIgnore"            => $insert->qstring_ignore,
				"rangeRequestHandling"     => $insert->range_request_handling,
				"regexRemap"               => $insert->regex_remap,
				"regionalGeoBlocking"      => $insert->regional_geo_blocking,
				"remapText"                => $insert->remap_text,
				"signed"                   => $insert->signed,
				"sslKeyVersion"            => $insert->ssl_key_version,
				"trRequestHeaders"         => $insert->tr_request_headers,
				"trResponseHeaders"        => $insert->tr_response_headers,
				"type"                     => $insert->type->name,
				"typeId"                   => $insert->type->id,
				"xmlId"                    => $insert->xml_id
			}
		);

		return $self->success( \@response, "Deliveryservice creation was successful." );
	}
	else {
		return $self->alert("Deliveryservice creation failed.");
	}
}

sub delete {
	my $self = shift;
	my $id   = $self->param('id');

	if ( !&is_oper($self) ) {
		return $self->forbidden();
	}

	my $ds = $self->db->resultset('Deliveryservice')->find( { id => $id } );
	if ( !defined($ds) ) {
		return $self->not_found();
	}

	my @regexp_id_list = $self->db->resultset('DeliveryserviceRegex')->search( { deliveryservice => $id } )->get_column('regex')->all();

	my $dsname = $self->db->resultset('Deliveryservice')->search( { id => $id } )->get_column('xml_id')->single();
	my $delete = $self->db->resultset('Deliveryservice')->search( { id => $id } );
	$delete->delete();

	my $delete_re = $self->db->resultset('Regex')->search( { id => { -in => \@regexp_id_list } } );
	$delete_re->delete();

	my @cfg_prefixes = ( "hdr_rw_", "hdr_rw_mid_", "regex_remap_", "cacheurl_" );
	foreach my $cfg_prefix (@cfg_prefixes) {
		my $cfg_file = $cfg_prefix . $ds->xml_id . ".config";
		&UI::DeliveryService::delete_cfg_file( $self, $cfg_file );
	}

	&log( $self, "Delete deliveryservice with id: " . $id . " and name " . $dsname, " APICHANGE" );

	return $self->success_message("Delivery service was deleted.");
}

sub get_deliveryservices_by_serverId {
	my $self      = shift;
	my $server_id = $self->param('id');

	my $server_ds_ids = $self->db->resultset('DeliveryserviceServer')->search( { server => $server_id } );

	my $deliveryservices = $self->db->resultset('Deliveryservice')
		->search( { 'me.id' => { -in => $server_ds_ids->get_column('deliveryservice')->as_query } }, { prefetch => [ 'cdn', 'profile', 'type' ] } );

	my @data;
	if ( defined($deliveryservices) ) {
		while ( my $row = $deliveryservices->next ) {
			push(
				@data, {
					"active"               => \$row->active,
					"cacheurl"             => $row->cacheurl,
					"ccrDnsTtl"            => $row->ccr_dns_ttl,
					"cdnId"                => $row->cdn->id,
					"cdnName"              => $row->cdn->name,
					"checkPath"            => $row->check_path,
					"displayName"          => $row->display_name,
					"dnsBypassCname"       => $row->dns_bypass_cname,
					"dnsBypassIp"          => $row->dns_bypass_ip,
					"dnsBypassIp6"         => $row->dns_bypass_ip6,
					"dnsBypassTtl"         => $row->dns_bypass_ttl,
					"dscp"                 => $row->dscp,
					"edgeHeaderRewrite"    => $row->edge_header_rewrite,
					"geoLimitRedirectURL"  => $row->geolimit_redirect_url,
					"geoLimit"             => $row->geo_limit,
					"geoLimitCountries"    => $row->geo_limit_countries,
					"geoProvider"          => $row->geo_provider,
					"globalMaxMbps"        => $row->global_max_mbps,
					"globalMaxTps"         => $row->global_max_tps,
					"httpBypassFqdn"       => $row->http_bypass_fqdn,
					"id"                   => $row->id,
					"infoUrl"              => $row->info_url,
					"initialDispersion"    => $row->initial_dispersion,
					"ipv6RoutingEnabled"   => \$row->ipv6_routing_enabled,
					"lastUpdated"          => $row->last_updated,
					"logsEnabled"          => \$row->logs_enabled,
					"longDesc"             => $row->long_desc,
					"longDesc1"            => $row->long_desc_1,
					"longDesc2"            => $row->long_desc_2,
					"maxDnsAnswers"        => $row->max_dns_answers,
					"midHeaderRewrite"     => $row->mid_header_rewrite,
					"missLat"              => defined( $row->miss_lat ) ? 0.0 + $row->miss_lat : undef,
					"missLong"             => defined( $row->miss_long ) ? 0.0 + $row->miss_long : undef,
					"multiSiteOrigin"      => \$row->multi_site_origin,
					"orgServerFqdn"        => $row->org_server_fqdn,
					"originShield"         => $row->origin_shield,
					"profileId"            => defined( $row->profile ) ? $row->profile->id : undef,
					"profileName"          => defined( $row->profile ) ? $row->profile->name : undef,
					"profileDescription"   => defined( $row->profile ) ? $row->profile->description : undef,
					"protocol"             => $row->protocol,
					"qstringIgnore"        => $row->qstring_ignore,
					"rangeRequestHandling" => $row->range_request_handling,
					"regexRemap"           => $row->regex_remap,
					"regionalGeoBlocking"  => \$row->regional_geo_blocking,
					"remapText"            => $row->remap_text,
					"signed"               => \$row->signed,
					"sslKeyVersion"        => $row->ssl_key_version,
					"trRequestHeaders"     => $row->tr_request_headers,
					"trResponseHeaders"    => $row->tr_response_headers,
					"type"                 => $row->type->name,
					"typeId"               => $row->type->id,
					"xmlId"                => $row->xml_id
				}
			);
		}
	}

	return $self->success( \@data );
}

sub get_deliveryservices_by_userId {
	my $self    = shift;
	my $user_id = $self->param('id');

	my $user_ds_ids = $self->db->resultset('DeliveryserviceTmuser')->search( { tm_user_id => $user_id } );

	my $deliveryservices = $self->db->resultset('Deliveryservice')
		->search( { 'me.id' => { -in => $user_ds_ids->get_column('deliveryservice')->as_query } }, { prefetch => [ 'cdn', 'profile', 'type' ] } );

	my @data;
	if ( defined($deliveryservices) ) {
		while ( my $row = $deliveryservices->next ) {
			push(
				@data, {
					"active"               => \$row->active,
					"cacheurl"             => $row->cacheurl,
					"ccrDnsTtl"            => $row->ccr_dns_ttl,
					"cdnId"                => $row->cdn->id,
					"cdnName"              => $row->cdn->name,
					"checkPath"            => $row->check_path,
					"displayName"          => $row->display_name,
					"dnsBypassCname"       => $row->dns_bypass_cname,
					"dnsBypassIp"          => $row->dns_bypass_ip,
					"dnsBypassIp6"         => $row->dns_bypass_ip6,
					"dnsBypassTtl"         => $row->dns_bypass_ttl,
					"dscp"                 => $row->dscp,
					"edgeHeaderRewrite"    => $row->edge_header_rewrite,
					"geoLimitRedirectURL"  => $row->geolimit_redirect_url,
					"geoLimit"             => $row->geo_limit,
					"geoLimitCountries"    => $row->geo_limit_countries,
					"geoProvider"          => $row->geo_provider,
					"globalMaxMbps"        => $row->global_max_mbps,
					"globalMaxTps"         => $row->global_max_tps,
					"httpBypassFqdn"       => $row->http_bypass_fqdn,
					"id"                   => $row->id,
					"infoUrl"              => $row->info_url,
					"initialDispersion"    => $row->initial_dispersion,
					"ipv6RoutingEnabled"   => \$row->ipv6_routing_enabled,
					"lastUpdated"          => $row->last_updated,
					"logsEnabled"          => \$row->logs_enabled,
					"longDesc"             => $row->long_desc,
					"longDesc1"            => $row->long_desc_1,
					"longDesc2"            => $row->long_desc_2,
					"maxDnsAnswers"        => $row->max_dns_answers,
					"midHeaderRewrite"     => $row->mid_header_rewrite,
					"missLat"              => defined( $row->miss_lat ) ? 0.0 + $row->miss_lat : undef,
					"missLong"             => defined( $row->miss_long ) ? 0.0 + $row->miss_long : undef,
					"multiSiteOrigin"      => \$row->multi_site_origin,
					"orgServerFqdn"        => $row->org_server_fqdn,
					"originShield"         => $row->origin_shield,
					"profileId"            => defined( $row->profile ) ? $row->profile->id : undef,
					"profileName"          => defined( $row->profile ) ? $row->profile->name : undef,
					"profileDescription"   => defined( $row->profile ) ? $row->profile->description : undef,
					"protocol"             => $row->protocol,
					"qstringIgnore"        => $row->qstring_ignore,
					"rangeRequestHandling" => $row->range_request_handling,
					"regexRemap"           => $row->regex_remap,
					"regionalGeoBlocking"  => \$row->regional_geo_blocking,
					"remapText"            => $row->remap_text,
					"signed"               => \$row->signed,
					"sslKeyVersion"        => $row->ssl_key_version,
					"trRequestHeaders"     => $row->tr_request_headers,
					"trResponseHeaders"    => $row->tr_response_headers,
					"type"                 => $row->type->name,
					"typeId"               => $row->type->id,
					"xmlId"                => $row->xml_id
				}
			);
		}
	}

	return $self->success( \@data );
}

sub routing {
	my $self = shift;

	# get and pass { cdn_name => $foo } into get_routing_stats
	my $id = $self->param('id');

	if ( $self->is_valid_delivery_service($id) ) {
		if ( $self->is_delivery_service_assigned($id) || &is_admin($self) || &is_oper($self) ) {
			my $result = $self->db->resultset("Deliveryservice")->search( { 'me.id' => $id }, { prefetch => [ 'cdn', 'type' ] } )->single();
			my $cdn_name = $result->cdn->name;

			# we expect type to be a dns or http type, but strip off any trailing bit
			my $stat_key = lc( $result->type->name );
			$stat_key =~ s/^(dns|http).*/$1/;
			$stat_key .= "Map";
			my $re_rs = $result->deliveryservice_regexes;
			my @patterns;
			while ( my $re_row = $re_rs->next ) {
				push( @patterns, $re_row->regex->pattern );
			}

			my $e = $self->get_routing_stats( { stat_key => $stat_key, patterns => \@patterns, cdn_name => $cdn_name } );
			if ( defined($e) ) {
				$self->alert($e);
			}
		}
		else {
			$self->forbidden("Forbidden. Delivery service not assigned to user.");
		}
	}
	else {
		$self->not_found();
	}
}

sub capacity {
	my $self = shift;

	# get and pass { cdn_name => $foo } into get_cache_capacity
	my $id = $self->param('id');

	if ( $self->is_valid_delivery_service($id) ) {
		if ( $self->is_delivery_service_assigned($id) || &is_admin($self) || &is_oper($self) ) {
			my $result = $self->db->resultset("Deliveryservice")->search( { 'me.id' => $id }, { prefetch => ['cdn'] } )->single();
			my $cdn_name = $result->cdn->name;

			$self->get_cache_capacity( { delivery_service => $result->xml_id, cdn_name => $cdn_name } );
		}
		else {
			$self->forbidden("Forbidden. Delivery service not assigned to user.");
		}
	}
	else {
		$self->not_found();
	}
}

sub health {
	my $self = shift;
	my $id   = $self->param('id');

	if ( $self->is_valid_delivery_service($id) ) {
		if ( $self->is_delivery_service_assigned($id) || &is_admin($self) || &is_oper($self) ) {
			my $result = $self->db->resultset("Deliveryservice")->search( { 'me.id' => $id }, { prefetch => ['cdn'] } )->single();
			my $cdn_name = $result->cdn->name;

			return ( $self->get_cache_health( { server_type => "caches", delivery_service => $result->xml_id, cdn_name => $cdn_name } ) );
		}
		else {
			$self->forbidden("Forbidden. Delivery service not assigned to user.");
		}
	}
	else {
		$self->not_found();
	}
}

sub state {

	my $self = shift;
	my $id   = $self->param('id');

	if ( $self->is_valid_delivery_service($id) ) {
		if ( $self->is_delivery_service_assigned($id) || &is_admin($self) || &is_oper($self) ) {
			my $result      = $self->db->resultset("Deliveryservice")->search( { 'me.id' => $id }, { prefetch => ['cdn'] } )->single();
			my $cdn_name    = $result->cdn->name;
			my $ds_name     = $result->xml_id;
			my $rascal_data = $self->get_rascal_state_data( { type => "RASCAL", state_type => "deliveryServices", cdn_name => $cdn_name } );

			# scalar refs get converted into json booleans
			my $data = {
				enabled  => \0,
				failover => {
					enabled     => \0,
					configured  => \0,
					destination => undef,
					locations   => []
				}
			};

			if ( exists( $rascal_data->{$cdn_name} ) && exists( $rascal_data->{$cdn_name}->{state}->{$ds_name} ) ) {
				my $health_config = $self->get_health_config($cdn_name);
				my $c             = $rascal_data->{$cdn_name}->{config}->{deliveryServices}->{$ds_name};
				my $r             = $rascal_data->{$cdn_name}->{state}->{$ds_name};

				if ( exists( $health_config->{deliveryServices}->{$ds_name} ) ) {
					my $h = $health_config->{deliveryServices}->{$ds_name};

					if ( $h->{status} eq "REPORTED" ) {
						$data->{enabled} = \1;
					}

					if ( !$r->{isAvailable} ) {
						$data->{failover}->{enabled}   = \1;
						$data->{failover}->{locations} = $r->{disabledLocations};
					}

					if ( exists( $h->{"health.threshold.total.kbps"} ) ) {

						# get current kbps, calculate percent used
						$data->{failover}->{configured} = \1;
						push( @{ $data->{failover}->{limits} }, { metric => "total_kbps", limit => $h->{"health.threshold.total.kbps"} } );
					}

					if ( exists( $h->{"health.threshold.total.tps_total"} ) ) {

						# get current tps, calculate percent used
						$data->{failover}->{configured} = \1;
						push( @{ $data->{failover}->{limits} }, { metric => "total_tps", limit => $h->{"health.threshold.total.tps_total"} } );
					}

					if ( exists( $c->{bypassDestination} ) ) {
						my @k        = keys( %{ $c->{bypassDestination} } );
						my $type     = shift(@k);
						my $location = undef;

						if ( $type =~ /^DNS/ ) {
							$location = $c->{bypassDestination}->{$type}->{ip};
						}
						elsif ( $type =~ /^HTTP/ ) {
							my $port = ( exists( $c->{bypassDestination}->{$type}->{port} ) ) ? ":" . $c->{bypassDestination}->{$type}->{port} : "";
							$location = sprintf( "http://%s%s", $c->{bypassDestination}->{$type}->{fqdn}, $port );
						}

						$data->{failover}->{destination} = {
							type     => $type,
							location => $location
						};
					}
				}
			}

			$self->success($data);
		}
		else {
			$self->forbidden("Forbidden. Delivery service not assigned to user.");
		}
	}
	else {
		$self->not_found();
	}
}

sub request {
	my $self     = shift;
	my $email_to = $self->req->json->{emailTo};
	my $details  = $self->req->json->{details};

	my $is_email_valid = Email::Valid->address($email_to);

	if ( !$is_email_valid ) {
		return $self->alert("Please provide a valid email address to send the delivery service request to.");
	}

	my ( $is_valid, $result ) = $self->is_deliveryservice_request_valid($details);

	if ($is_valid) {
		if ( $self->send_deliveryservice_request( $email_to, $details ) ) {
			return $self->success_message( "Delivery Service request sent to " . $email_to );
		}
	}
	else {
		return $self->alert($result);
	}
}

sub assign_servers {
	my $self      = shift;
	my $ds_xml_Id = $self->param('xml_id');
	my $params    = $self->req->json;

	if ( !defined($params) ) {
		return $self->alert("parameters are JSON format, please check!");
	}
	if ( !&is_oper($self) ) {
		return $self->alert("You must be an ADMIN or OPER to perform this operation!");
	}

	if ( !exists( $params->{serverNames} ) ) {
		return $self->alert("Parameter 'serverNames' is required.");
	}

	my $dsid = $self->db->resultset('Deliveryservice')->search( { xml_id => $ds_xml_Id } )->get_column('id')->single();
	if ( !defined($dsid) ) {
		return $self->alert( "DeliveryService[" . $ds_xml_Id . "] is not found." );
	}

	my @server_ids;
	my $svrs = $params->{serverNames};
	foreach my $svr (@$svrs) {
		my $svr_id = $self->db->resultset('Server')->search( { host_name => $svr } )->get_column('id')->single();
		if ( !defined($svr_id) ) {
			return $self->alert( "Server[" . $svr . "] is not found in database." );
		}
		push( @server_ids, $svr_id );
	}

	# clean up
	my $delete = $self->db->resultset('DeliveryserviceServer')->search( { deliveryservice => $dsid } );
	$delete->delete();

	# assign servers
	foreach my $s_id (@server_ids) {
		my $insert = $self->db->resultset('DeliveryserviceServer')->create(
			{
				deliveryservice => $dsid,
				server          => $s_id,
			}
		);
		$insert->insert();
	}

	my $ds = $self->db->resultset('Deliveryservice')->search( { id => $dsid } )->single();
	&UI::DeliveryService::header_rewrite( $self, $ds->id, $ds->profile, $ds->xml_id, $ds->edge_header_rewrite, "edge" );

	my $response;
	$response->{xmlId} = $ds->xml_id;
	$response->{'serverNames'} = \@$svrs;

	return $self->success($response);
}

sub is_deliveryservice_request_valid {
	my $self    = shift;
	my $details = shift;

	my $rules = {
		fields => [
			qw/customer contentType deliveryProtocol routingType serviceDesc peakBPSEstimate peakTPSEstimate maxLibrarySizeEstimate originURL hasOriginDynamicRemap originTestFile hasOriginACLWhitelist originHeaders otherOriginSecurity queryStringHandling rangeRequestHandling hasSignedURLs hasNegativeCachingCustomization negativeCachingCustomizationNote serviceAliases rateLimitingGBPS rateLimitingTPS overflowService headerRewriteEdge headerRewriteMid headerRewriteRedirectRouter notes/
		],

		# Validation checks to perform
		checks => [

			# required deliveryservice request fields
			[
				qw/customer contentType deliveryProtocol routingType serviceDesc peakBPSEstimate peakTPSEstimate maxLibrarySizeEstimate originURL hasOriginDynamicRemap originTestFile hasOriginACLWhitelist queryStringHandling rangeRequestHandling hasSignedURLs hasNegativeCachingCustomization rateLimitingGBPS rateLimitingTPS/
			] => is_required("is required")

		]
	};

	# Validate the input against the rules
	my $result = validate( $details, $rules );

	if ( $result->{success} ) {
		return ( 1, $result->{data} );
	}
	else {
		return ( 0, $result->{error} );
	}
}

sub is_deliveryservice_valid {
	my $self   = shift;
	my $params = shift;

	if ( !$self->is_valid_deliveryservice_type( $params->{typeId} ) ) {
		return ( 0, "Invalid deliveryservice type" );
	}

	my $rules = {
		fields => [
			qw/active cacheurl ccrDnsTtl cdnId checkPath displayName dnsBypassCname dnsBypassIp dnsBypassIp6 dnsBypassTtl dscp edgeHeaderRewrite geoLimitRedirectURL geoLimit geoLimitCountries geoProvider globalMaxMbps globalMaxTps httpBypassFqdn infoUrl initialDispersion ipv6RoutingEnabled logsEnabled longDesc longDesc1 longDesc2 maxDnsAnswers midHeaderRewrite missLat missLong multiSiteOrigin multiSiteOriginAlgorithm orgServerFqdn originShield profileId protocol qstringIgnore rangeRequestHandling regexRemap regionalGeoBlocking remapText signed sslKeyVersion trRequestHeaders trResponseHeaders typeId xmlId/
		],

		# Validation checks to perform
		checks => [
			xmlId                => [ is_required("is required"), is_like( qr/^\S*$/, "no spaces" ), is_long_at_most( 48, 'too long' ) ],
			typeId               => [ is_required("is required") ],
			cdnId                => [ is_required("is required") ],
			active               => [ is_required("is required") ],
			displayName          => [ is_required("is required"), is_long_at_most( 48, 'too long' ) ],
			dscp                 => [ is_required("is required"), is_like( qr/^\d+$/, "digits only" ) ],
			geoLimit             => [ is_required("is required"), is_like( qr/^\d+$/, "digits only" ) ],
			geoProvider          => [ is_required("is required"), is_like( qr/^\d+$/, "digits only" ) ],
			initialDispersion    => [ is_required("is required"), is_like( qr/^\d+$/, "digits only" ) ],
			ipv6RoutingEnabled   => [ is_required("is required") ],
			logsEnabled          => [ is_required("is required") ],
			missLat              => [ \&is_valid_lat ],
			missLong             => [ \&is_valid_long ],
			multiSiteOrigin      => [ is_required("is required") ],
			orgServerFqdn        => [ sub { is_valid_org_server_fqdn($self, @_) } ],
			protocol             => [ is_required("is required"), is_like( qr/^\d+$/, "digits only" ) ],
			qstringIgnore        => [ is_required("is required"), is_like( qr/^\d+$/, "digits only" ) ],
			rangeRequestHandling => [ is_required("is required"), is_like( qr/^\d+$/, "digits only" ) ],
			regionalGeoBlocking  => [ is_required("is required") ],
			signed               => [ is_required("is required") ],
		]
	};

	# Validate the input against the rules
	my $result = validate( $params, $rules );

	if ( $result->{success} ) {
		return ( 1, $result->{data} );
	}
	else {
		return ( 0, $result->{error} );
	}
}

sub is_valid_deliveryservice_type {
	my $self    = shift;
	my $type_id = shift;

	my $rs = $self->db->resultset("Type")->find( { id => $type_id } );
	if ( defined($rs) && ( $rs->use_in_table eq "deliveryservice" ) ) {
		return 1;
	}
	return 0;
}

sub is_valid_lat {
	my ( $value, $params ) = @_;

	if ( !defined $value or $value eq '' ) {
		return undef;
	}

	if ( !( $value =~ /^[-]*[0-9]+[.]*[0-9]*/ ) ) {
		return "invalid. Must be a float number.";
	}

	if ( abs $value > 90 ) {
		return "invalid. May not exceed +- 90.0.";
	}

	return undef;
}

sub is_valid_long {
	my ( $value, $params ) = @_;

	if ( !defined $value or $value eq '' ) {
		return undef;
	}

	if ( !( $value =~ /^[-]*[0-9]+[.]*[0-9]*/ ) ) {
		return "invalid. Must be a float number.";
	}

	if ( abs $value > 180 ) {
		return "invalid. May not exceed +- 180.0.";
	}

	return undef;
}

sub is_valid_org_server_fqdn {
	my $self    = shift;
	my ( $value, $params ) = @_;

	if ( (!defined $value or $value eq '') ) {
		my $type_name = $self->db->resultset("Type")->find( { id => $params->{typeId} } )->get_column('name') // undef;
		if ( defined($type_name) && ( $type_name =~ /(^ANY_MAP$|^.*STEERING.*$)/ ) ) {
			return undef;
		}
	}

	if ( !( $value =~ /^(https?:\/\/)/ ) ) {
		return "invalid. Must start with http:// or https://.";
	}

	return undef;
}

sub sanitize_geo_limit_countries {
	my $geo_limit_countries = shift;

	if ( !defined($geo_limit_countries) ) {
		return "";
	}

	$geo_limit_countries =~ s/\s+//g;
	$geo_limit_countries = uc($geo_limit_countries);
	return $geo_limit_countries;
}

sub create_default_ds_regex {
	my $self    = shift;
	my $ds_id   = shift;
	my $pattern = shift;

	my $type_id = $self->db->resultset('Type')->find( { name => 'HOST_REGEXP' } );

	my $values = {
		type    => $type_id,
		pattern => $pattern,
	};

	my $rs_regex = $self->db->resultset('Regex')->create($values)->insert();
	if ($rs_regex) {

		# now insert the regex into the deliveryservice_regex table with set number = 0
		$self->db->resultset('DeliveryserviceRegex')->create( { deliveryservice => $ds_id, regex => $rs_regex->id, set_number => 0 } )->insert();
		&log( $self, "Created delivery service regex at position 0 [ " . $rs_regex->pattern . " ] for deliveryservice: " . $ds_id, "APICHANGE" );
	}

}

sub get_regexp_set {
	my $self    	= shift;
	my @ds_regexes 	= shift;

	my $regexp_set;
	my $i = 0;

	foreach my $ds_regex (@ds_regexes) {
		$regexp_set->[$i]->{id}         = $ds_regex->id;
		$regexp_set->[$i]->{pattern}    = $ds_regex->regex->pattern;
		$regexp_set->[$i]->{type}    	= $ds_regex->regex->type->name;
		$regexp_set->[$i]->{set_number} = $ds_regex->set_number;
		$i++;
	}

	return $regexp_set;
}

1;


text:
package net.akehurst.app.dotEditor.application.web.vertx;

import net.akehurst.application.framework.realisation.ApplicationFramework;

public class DotEditorVertxMain {

	public static void main(String[] args) {
		ApplicationFramework.start(DotEditorVertxApplication.class, args);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>NVAPI Reference Documentation</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

NVAPI Reference Documentation

        NVIDIA

Release 337: May 2

        2014

Main Page

Related Pages

Modules

Data Structures

Files

File List

Globals

Deprecated.txt File Reference

 Copyright (c) 2007-2014 NVIDIA Corporation. All rights reserved.


text:
package com.june.service.information.pictures;

import org.springframework.stereotype.Service;

import com.june.service.common.BaseService;
import com.june.util.PageData;

@Service("picturesService")
public class PicturesService extends BaseService{

	/*
	* 删除图片
	*/
	public void delTp(PageData pd)throws Exception{
		dao.update("PicturesMapper.delTp", pd);
	}

	@Override
	public String xmlMapper() {
		return "PicturesMapper";
	}

}


text:
title: Prize Strings
localeTitle: Призовые строки
---
## Задача 191: Призовые строки

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-191-prize-strings/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
"""empty message

Revision ID: 0203_fix_old_incomplete_jobs
Revises: 0202_new_letter_pricing
Create Date: 2017-06-29 12:44:16.815039

"""

# revision identifiers, used by Alembic.
revision = "0203_fix_old_incomplete_jobs"
down_revision = "0202_new_letter_pricing"

from alembic import op

def upgrade():
    op.execute(
        """
        UPDATE
            jobs
        SET
            processing_started = created_at
        WHERE
            processing_started IS NULL
            AND
            job_status = 'in progress'
    """
    )

def downgrade():
    pass


text:
using Adaptive.Agrona;
using Adaptive.Agrona.Concurrent;

namespace Adaptive.Aeron.LogBuffer
{
    public static class HandlerHelper
    {
        private class FragmentHandlerWrapper : IFragmentHandler
        {
            private readonly FragmentHandler _delegate;

            public FragmentHandlerWrapper(FragmentHandler @delegate)
            {
                _delegate = @delegate;
            }

            public void OnFragment(IDirectBuffer buffer, int offset, int length, Header header)
            {
                _delegate(buffer, offset, length, header);
            }
        }

        private class ControlledFragmentHandlerWrapper : IControlledFragmentHandler
        {
            private readonly ControlledFragmentHandler _delegate;

            public ControlledFragmentHandlerWrapper(ControlledFragmentHandler @delegate)
            {
                _delegate = @delegate;
            }

            public ControlledFragmentHandlerAction OnFragment(IDirectBuffer buffer, int offset, int length, Header header)
            {
                return _delegate(buffer, offset, length, header);
            }
        }

        private class BlockHandlerWrapper : IBlockHandler
        {
            private readonly BlockHandler _delegate;

            public BlockHandlerWrapper(BlockHandler @delegate)
            {
                _delegate = @delegate;
            }

            public void OnBlock(IDirectBuffer buffer, int offset, int length, int sessionId, int termId)
            {
                _delegate(buffer, offset, length, sessionId, termId);
            }
        }

        public static IFragmentHandler ToFragmentHandler(FragmentHandler @delegate)
        {
            return new FragmentHandlerWrapper(@delegate);
        }

        public static IControlledFragmentHandler ToControlledFragmentHandler(ControlledFragmentHandler @delegate)
        {
            return new ControlledFragmentHandlerWrapper(@delegate);
        }

        public static IBlockHandler ToBlockHandler(BlockHandler @delegate)
        {
            return new BlockHandlerWrapper(@delegate);
        }
    }
}


text:
<?php

/**
 * Create a special or ordinary file (POSIX.1)
 *
 * @phpstub
 *
 * @param string $pathname
 * @param int $mode
 * @param int $major
 * @param int $minor
 *
 * @return bool
 */
function posix_mknod($pathname, $mode, $major = false, $minor = false)
{
}


text:
package com.futonredemption.volumewidget;

import java.util.ArrayList;
import java.util.List;

import org.beryl.app.AndroidVersion;

import android.content.Context;
import android.media.AudioManager;

public class VolumeStreamList {

	private final Context context;
	public VolumeStreamList(final Context context) {
		this.context = context;
	}

	public List<VolumeStreamItem> createList() {
		final List<VolumeStreamItem> result = new ArrayList<VolumeStreamItem>();
		result.add(createItem(AudioManager.STREAM_ALARM, R.string.alarm));
		result.add(createItem(AudioManager.STREAM_MUSIC, R.string.music));
		result.add(createItem(AudioManager.STREAM_NOTIFICATION, R.string.notification));
		result.add(createItem(AudioManager.STREAM_RING, R.string.ringer));

		if(AndroidVersion.isBeforeIceCreamSandwich()) {
			result.add(createItem(AudioManager.STREAM_SYSTEM, R.string.system));
		}

		result.add(createItem(AudioManager.STREAM_VOICE_CALL, R.string.voice));

		if(AndroidVersion.isEclairOrHigher() && AndroidVersion.isBeforeHoneycomb()) {
			result.add(createItem(AudioManager.STREAM_DTMF, R.string.touchtone));
		}

		return result;
	}

	private VolumeStreamItem createItem(int streamId, int resId) {
		final VolumeStreamItem item = new VolumeStreamItem();
		item.StreamId = streamId;
		item.StreamName = context.getText(resId);

		return item;
	}
}


text:
package org.d2;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.d2.annotations.D2Entity;
import org.d2.context.D2Context;
import org.d2.pluggable.IndexerFactory;
import org.d2.pluggable.StorageFactory;
import org.d2.serialize.D2Serializer;
import org.d2.serialize.SerializerFactory;
import org.nkts.util.StringVisitor;
import org.nkts.util.Util;

public class D2Impl implements D2
{
    private List<Bucket> buckets = new ArrayList<Bucket>();

    private StorageFactory defaultStorageFactory;
    private IndexerFactory defaultIndexerFactory;
    private SerializerFactory defaultSerializerFactory;

    private long indexTime;
    private long storageTime;

    public D2Impl(StorageFactory defaultStorageFactory, IndexerFactory defaultIndexerFactory, SerializerFactory defaultSerializerFactory)
    {
        this.defaultStorageFactory = defaultStorageFactory;
        this.defaultIndexerFactory = defaultIndexerFactory;
        this.defaultSerializerFactory = defaultSerializerFactory;
    }

    // ====================================================
    // logic
    // ====================================================
    /* (non-Javadoc)
     * @see com.pitcru.persistence.d2.D2#registerBucket(com.pitcru.persistence.d2.D2Bucket)
     */
    public void registerBucket(Bucket bucket)
    {
        for(Bucket b : buckets)
        {
            if(b.getClazz()==bucket.getClazz()) return;
        }
        bucket.setD2(this);
        buckets.add(bucket);
    }

    /* (non-Javadoc)
     * @see com.pitcru.persistence.d2.D2#save(com.pitcru.persistence.d2.Object)
     */
    public void save(Object obj, D2Context context)
    {
        Operation operation = new Operation();
        // FIXME - nondeterministic
        Date now = new Date();

        context = useObjectContextIfPossible(obj, context);
        saveInternal(obj, context, operation, now);

        Object objectToSave;
        while((objectToSave = operation.pollCascadeSave())!=null)
        {
            saveInternal(objectToSave, context, operation, now);
        }
    }

    public void saveInternal(Object obj, D2Context context, Operation operation, Date now)
    {
        D2Serializer xs = defaultSerializerFactory.createSerializer();
        Bucket bucket = prepareSerializerAndFindBucket(obj.getClass(), xs, new Date(), context, operation);

        // check constraint here!

        obj = bucket.applyConstraints(obj, context);

        assignId(obj, bucket.getClazz(), bucket);
        String xmlStr = xs.serialize(obj);

        String id = IdFinder.getId(obj);
        bucket.getStorage().acquireWriteLock(id);
        try
        {
            long starta = System.currentTimeMillis();
            bucket.getStorage().saveDocument(id, xmlStr, now);
            setMetadata(obj, xmlStr, now, LoadStatus.LOADED, context);
            storageTime += (System.currentTimeMillis()-starta);

            if(bucket.getIndexer()!=null)
            {
                long startb = System.currentTimeMillis();
                bucket.getIndexer().indexObject(obj);
                indexTime += (System.currentTimeMillis()-startb);
            }
        }
        finally
        {
            bucket.getStorage().releaseWriteLock(id);
        }

        context.registerInstanceToCache(bucket, obj);
    }

    private void setMetadata(Object obj, String xml, Date now, LoadStatus status, D2Context context)
    {
        D2Metadata md = IdFinder.getMd(obj);
        if(md==null)
        {
            md = new D2Metadata();
            IdFinder.setMd(obj, md);
        }
        if(status!=null) md.setStatus(status);
        if(now!=null) md.setSaveTimestamp(now);
        if(xml!=null) md.setLoadedXml(xml);
        if(context!=null) md.setContext(context);
    }

    /* (non-Javadoc)
     * @see com.pitcru.persistence.d2.D2#loadAll(java.lang.Class)
     */
    public <T> List<T> loadAll(final Class<T> clazz, final D2Context context)
    {
        final Operation operation = new Operation();
        final List<T> out = new ArrayList<T>();

        final Bucket bucket = prepareSerializerAndFindBucket(clazz, null, null, context, operation);

        bucket.getStorage().eachId(new StringVisitor(){
            @Override
            public void visit(String id)
            {
                // it's inefficient to prepare a new XS for each load... but right now we need to, because we must reset the
                // converter for this type... so that it will unmarshall the root-level object properly
                D2Serializer xs = defaultSerializerFactory.createSerializer();
                prepareSerializerAndFindBucket(clazz, xs, null, context, operation);
                T obj = loadOneObject(clazz, id, xs, bucket, context, true, operation);
                out.add(obj);
            }
        });

        return out;
    }

    public void reindexAll(final Class<? extends Object> clazz, final D2Context context)
    {
        final Operation operation = new Operation();
        final Bucket bucket = prepareSerializerAndFindBucket(clazz, null, null, context, operation);
        if(bucket.getIndexer()==null) throw new RuntimeException("Cannot index "+clazz.getSimpleName()+" because indexer is null");

        bucket.getStorage().eachId(new StringVisitor(){
            @Override
            public void visit(String id)
            {
                // it's inefficient to prepare a new XS for each load... but right now we need to, because we must reset the
                // converter for this type... so that it will unmarshall the root-level object properly
                D2Serializer xs = defaultSerializerFactory.createSerializer();
                prepareSerializerAndFindBucket(clazz, xs, null, context, operation);
                Object obj = loadOneObject(clazz, id, xs, bucket, context, true, operation);

                bucket.getIndexer().indexObject(obj);
            }
        });

    }

    /* (non-Javadoc)
     * @see com.pitcru.persistence.d2.D2#deleteById(java.lang.Class, java.lang.Long)
     */
    public void deleteById(Class<? extends Object> clazz, String id, D2Context context)
    {
        Operation operation = new Operation();
        try
        {
            Bucket bucket = prepareSerializerAndFindBucket(clazz, null, null, context, operation);

            bucket.getStorage().deleteDocument(id);
            bucket.getIndexer().deleteDocument(id);
            context.removeFromCache(bucket, id);
        }
        catch (Exception e)
        {
            throw Util.wrap(e);
        }
    }

    /* (non-Javadoc)
     * @see com.pitcru.persistence.d2.D2#loadById(java.lang.Class, java.lang.Long)
     */
    public <T> T loadById(Class<T> clazz, String id, D2Context context)
    {
        Operation operation = new Operation();
        try
        {
            D2Serializer xs = defaultSerializerFactory.createSerializer();
            Bucket bucket = prepareSerializerAndFindBucket(clazz, xs, null, context, operation);

            return loadOneObject(clazz, id, xs, bucket, context, true, operation);
        }
        catch (Exception e)
        {
            throw Util.wrap(e);
        }
    }

    public <T> T loadCachedOnlyById(Class<T> clazz, String id, D2Context context, boolean createStandin)
    {
        Operation operation = new Operation();
        try
        {
            D2Serializer xs = defaultSerializerFactory.createSerializer();
            Bucket bucket = prepareSerializerAndFindBucket(clazz, xs, null, context, operation);

            return getCachedObjectOrStandin(clazz, id, bucket, context, createStandin);
        }
        catch (Exception e)
        {
            throw Util.wrap(e);
        }
    }

    @SuppressWarnings("unchecked")
    private <T> T loadOneObject(Class<T> clazz, String id, D2Serializer xs, Bucket bucket, D2Context context, boolean forceReload, Operation operation)
    {
        T object = getCachedObjectOrStandin(clazz, id, bucket, context, false);

        if(object==null || IdFinder.getMd(object).isStandin() || forceReload)
        {
            object = realizeObject(clazz, id, xs, bucket, context, object);
            if(object==null) return null;

//            TreeWalker.walk(new LoadStandins(this, context), object);
            T objectToLoad;
            while((objectToLoad = (T)operation.pollCascadeLoads())!=null)
            {
                realizeObject(objectToLoad, context, operation);
            }

        }
        return object;
    }

    public void realizeObject(Object obj, D2Context context)
    {
        realizeObject(obj, context, new Operation());
    }

    private void realizeObject(Object obj, D2Context context, Operation operation)
    {
        Class<?> clazz = obj.getClass();
        String id = IdFinder.getId(obj);
        try
        {
            D2Serializer xs = defaultSerializerFactory.createSerializer();
            Bucket bucket = prepareSerializerAndFindBucket(clazz, xs, null, context, operation);

            loadOneObject(clazz, id, xs, bucket, context, true, operation);
        }
        catch (Exception e)
        {
            throw Util.wrap(e);
        }
    }

    private <T> T realizeObject(Class<T> clazz, String id, D2Serializer xs, Bucket bucket, D2Context context, T object)
    {
        String xmlStr = null;
        bucket.getStorage().acquireReadLock(id);
        try
        {
            xmlStr = bucket.getStorage().loadDocument(id);
        }
        finally
        {
            bucket.getStorage().releaseReadLock(id);
        }
        if(xmlStr==null) return null;

        if(object==null)
        {
            object = clazz.cast(context.createAndRegisterStandin(bucket, clazz, id));
        }
        else
        {
            // skip reload if document is an exact match to what we had before
            D2Metadata md = IdFinder.getMd(object);
            if(md!=null && xmlStr.equals(md.getLoadedXml())) return object;
        }

        xs.deserialize(xmlStr, object);

        setMetadata(object, xmlStr, null, LoadStatus.LOADED, context);
        return object;
    }

    private <T> T getCachedObjectOrStandin(Class<T> clazz, String id, Bucket bucket, D2Context context, boolean createStandin)
    {
        if(!bucket.getStorage().isIdValid(id)) return null;

        Object cached = context.lookInCache(bucket, id);
        if(cached!=null) return clazz.cast(cached);

        if(!createStandin) return null;

        T standin = clazz.cast(context.createAndRegisterStandin(bucket, clazz, id));

        return standin;
    }

    /**
     * TODO move this to LocalFileStorage
     *
     * @param obj
     * @param bucketClass
     * @param bucket
     */
    private void assignId(Object obj, @SuppressWarnings("rawtypes") Class bucketClass, Bucket bucket)
    {
        if(bucket==null) throw new RuntimeException("bucket is null");
        if(bucket.getStorage()==null) throw new RuntimeException("bucket's storage system is null");
        if(IdFinder.getMd(obj).isNew() && IdFinder.getId(obj)==null)
        {
            String id = bucket.getStorage().getSeqNextVal(bucketClass.getSimpleName());
            IdFinder.setId(obj, id);
        }
        else
        {
            bucket.getStorage().setSequenceIfMore(obj.getClass().getSimpleName(), IdFinder.getId(obj));
        }
    }

    public Bucket prepareSerializerAndFindBucket(Class<?> clazz, D2Serializer xs, Date now, D2Context context, Operation operation)
    {
        Bucket thisBucket = null;
        for(Bucket bucket : buckets)
        {
            if(bucket.getClazz().isAssignableFrom(clazz))
            {
                if(xs!=null) xs.prepareForRootBucket(clazz, this, now, context, operation, bucket);
                thisBucket = bucket;
            }
            else
            {
                if(xs!=null) xs.prepareForNonRootBucket(this, now, context, operation, bucket);
            }
        }
        return thisBucket;
    }

    public String getAlias(Class<?> clazz)
    {
        D2Entity entityAnnotation = clazz.getAnnotation(D2Entity.class);
        return entityAnnotation==null?clazz.getName():entityAnnotation.alias();
    }

    private static D2Context useObjectContextIfPossible(Object obj, D2Context context)
    {
        D2Metadata md = IdFinder.getMd(obj);
        if(md!=null && md.getContext()!=null)
        {
            context = md.getContext();
        }
        return context;
    }

    // ====================================================
    // getters/setters
    // ====================================================
    public List<Bucket> getBuckets()
    {
        return buckets;
    }

    public void setBuckets(List<Bucket> buckets)
    {
        this.buckets = buckets;
    }

    public StorageFactory getDefaultStorageFactory()
    {
        return defaultStorageFactory;
    }

    public IndexerFactory getDefaultIndexerFactory()
    {
        return defaultIndexerFactory;
    }

    @Override
    public void close()
    {
        for(Bucket b : buckets)
        {
            if(b.getIndexer()==null) throw new RuntimeException("indexer is null "+b.getName());
            b.getIndexer().close();
        }
    }

    @Override
    public void resetAllIndexLocks()
    {
        for(Bucket b : buckets)
        {
            b.getIndexer().resetLocks();
        }
    }

    public long getIndexTime()
    {
        return indexTime;
    }

    public void setIndexTime(long indexTime)
    {
        this.indexTime = indexTime;
    }

    public long getStorageTime()
    {
        return storageTime;
    }

    public void setStorageTime(long storageTime)
    {
        this.storageTime = storageTime;
    }

}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kappi"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <application
      android:name=".MainApplication"
      android:allowBackup="true"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

      <activity
                android:name="com.facebook.FacebookActivity"
                android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
                android:label="@string/app_name"
                android:theme="@android:style/Theme.Translucent.NoTitleBar"/>

        <!--reference your fb_app_id-->
        <meta-data
                android:name="com.facebook.sdk.ApplicationId"
                android:value="@string/fb_app_id"/>

      <!-- <service android:name="io.fullstack.firestack.FirestackMessagingService">
           <intent-filter>
             <action android:name="com.google.firebase.MESSAGING_EVENT"/>
           </intent-filter>
         </service>

         <service android:name="io.fullstack.firestack.FirestackInstanceIdService" android:exported="false">
           <intent-filter>
             <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
           </intent-filter>
       </service> -->

    </application>

</manifest>


text:
@import AVFoundation;

#import "CameraPermissionUtils.h"
#import "CameraProperties.h"
#import "FLTCam.h"
#import "FLTThreadSafeEventChannel.h"
#import "FLTThreadSafeFlutterResult.h"
#import "FLTThreadSafeMethodChannel.h"
#import "FLTThreadSafeTextureRegistry.h"
#import "QueueUtils.h"

@interface CameraPlugin ()
@property(readonly, nonatomic) FLTThreadSafeTextureRegistry *registry;
@property(readonly, nonatomic) NSObject<FlutterBinaryMessenger> *messenger;
@end

@implementation CameraPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
  FlutterMethodChannel *channel =
      [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/camera_avfoundation"
                                  binaryMessenger:[registrar messenger]];
  CameraPlugin *instance = [[CameraPlugin alloc] initWithRegistry:[registrar textures]
                                                        messenger:[registrar messenger]];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (instancetype)initWithRegistry:(NSObject<FlutterTextureRegistry> *)registry
                       messenger:(NSObject<FlutterBinaryMessenger> *)messenger {
  self = [super init];
  NSAssert(self, @"super init cannot be nil");
  _registry = [[FLTThreadSafeTextureRegistry alloc] initWithTextureRegistry:registry];
  _messenger = messenger;
  _captureSessionQueue = dispatch_queue_create("io.flutter.camera.captureSessionQueue", NULL);
  dispatch_queue_set_specific(_captureSessionQueue, FLTCaptureSessionQueueSpecific,
                              (void *)FLTCaptureSessionQueueSpecific, NULL);

  [self initDeviceEventMethodChannel];
  [self startOrientationListener];
  return self;
}

- (void)initDeviceEventMethodChannel {
  FlutterMethodChannel *methodChannel = [FlutterMethodChannel
      methodChannelWithName:@"plugins.flutter.io/camera_avfoundation/fromPlatform"
            binaryMessenger:_messenger];
  _deviceEventMethodChannel =
      [[FLTThreadSafeMethodChannel alloc] initWithMethodChannel:methodChannel];
}

- (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
  [UIDevice.currentDevice endGeneratingDeviceOrientationNotifications];
}

- (void)startOrientationListener {
  [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(orientationChanged:)
                                               name:UIDeviceOrientationDidChangeNotification
                                             object:[UIDevice currentDevice]];
}

- (void)orientationChanged:(NSNotification *)note {
  UIDevice *device = note.object;
  UIDeviceOrientation orientation = device.orientation;

  if (orientation == UIDeviceOrientationFaceUp || orientation == UIDeviceOrientationFaceDown) {
    // Do not change when oriented flat.
    return;
  }

  __weak typeof(self) weakSelf = self;
  dispatch_async(self.captureSessionQueue, ^{
    // `FLTCam::setDeviceOrientation` must be called on capture session queue.
    [weakSelf.camera setDeviceOrientation:orientation];
    // `CameraPlugin::sendDeviceOrientation` can be called on any queue.
    [weakSelf sendDeviceOrientation:orientation];
  });
}

- (void)sendDeviceOrientation:(UIDeviceOrientation)orientation {
  [_deviceEventMethodChannel
      invokeMethod:@"orientation_changed"
         arguments:@{@"orientation" : FLTGetStringForUIDeviceOrientation(orientation)}];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
  // Invoke the plugin on another dispatch queue to avoid blocking the UI.
  __weak typeof(self) weakSelf = self;
  dispatch_async(self.captureSessionQueue, ^{
    FLTThreadSafeFlutterResult *threadSafeResult =
        [[FLTThreadSafeFlutterResult alloc] initWithResult:result];
    [weakSelf handleMethodCallAsync:call result:threadSafeResult];
  });
}

- (void)handleMethodCallAsync:(FlutterMethodCall *)call
                       result:(FLTThreadSafeFlutterResult *)result {
  if ([@"availableCameras" isEqualToString:call.method]) {
    if (@available(iOS 10.0, *)) {
      NSMutableArray *discoveryDevices =
          [@[ AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInTelephotoCamera ]
              mutableCopy];
      if (@available(iOS 13.0, *)) {
        [discoveryDevices addObject:AVCaptureDeviceTypeBuiltInUltraWideCamera];
      }
      AVCaptureDeviceDiscoverySession *discoverySession = [AVCaptureDeviceDiscoverySession
          discoverySessionWithDeviceTypes:discoveryDevices
                                mediaType:AVMediaTypeVideo
                                 position:AVCaptureDevicePositionUnspecified];
      NSArray<AVCaptureDevice *> *devices = discoverySession.devices;
      NSMutableArray<NSDictionary<NSString *, NSObject *> *> *reply =
          [[NSMutableArray alloc] initWithCapacity:devices.count];
      for (AVCaptureDevice *device in devices) {
        NSString *lensFacing;
        switch ([device position]) {
          case AVCaptureDevicePositionBack:
            lensFacing = @"back";
            break;
          case AVCaptureDevicePositionFront:
            lensFacing = @"front";
            break;
          case AVCaptureDevicePositionUnspecified:
            lensFacing = @"external";
            break;
        }
        [reply addObject:@{
          @"name" : [device uniqueID],
          @"lensFacing" : lensFacing,
          @"sensorOrientation" : @90,
        }];
      }
      [result sendSuccessWithData:reply];
    } else {
      [result sendNotImplemented];
    }
  } else if ([@"create" isEqualToString:call.method]) {
    [self handleCreateMethodCall:call result:result];
  } else if ([@"startImageStream" isEqualToString:call.method]) {
    [_camera startImageStreamWithMessenger:_messenger];
    [result sendSuccess];
  } else if ([@"stopImageStream" isEqualToString:call.method]) {
    [_camera stopImageStream];
    [result sendSuccess];
  } else if ([@"receivedImageStreamData" isEqualToString:call.method]) {
    [_camera receivedImageStreamData];
    [result sendSuccess];
  } else {
    NSDictionary *argsMap = call.arguments;
    NSUInteger cameraId = ((NSNumber *)argsMap[@"cameraId"]).unsignedIntegerValue;
    if ([@"initialize" isEqualToString:call.method]) {
      NSString *videoFormatValue = ((NSString *)argsMap[@"imageFormatGroup"]);
      [_camera setVideoFormat:FLTGetVideoFormatFromString(videoFormatValue)];

      __weak CameraPlugin *weakSelf = self;
      _camera.onFrameAvailable = ^{
        if (![weakSelf.camera isPreviewPaused]) {
          [weakSelf.registry textureFrameAvailable:cameraId];
        }
      };
      FlutterMethodChannel *methodChannel = [FlutterMethodChannel
          methodChannelWithName:
              [NSString stringWithFormat:@"plugins.flutter.io/camera_avfoundation/camera%lu",
                                         (unsigned long)cameraId]
                binaryMessenger:_messenger];
      FLTThreadSafeMethodChannel *threadSafeMethodChannel =
          [[FLTThreadSafeMethodChannel alloc] initWithMethodChannel:methodChannel];
      _camera.methodChannel = threadSafeMethodChannel;
      [threadSafeMethodChannel
          invokeMethod:@"initialized"
             arguments:@{
               @"previewWidth" : @(_camera.previewSize.width),
               @"previewHeight" : @(_camera.previewSize.height),
               @"exposureMode" : FLTGetStringForFLTExposureMode([_camera exposureMode]),
               @"focusMode" : FLTGetStringForFLTFocusMode([_camera focusMode]),
               @"exposurePointSupported" :
                   @([_camera.captureDevice isExposurePointOfInterestSupported]),
               @"focusPointSupported" : @([_camera.captureDevice isFocusPointOfInterestSupported]),
             }];
      [self sendDeviceOrientation:[UIDevice currentDevice].orientation];
      [_camera start];
      [result sendSuccess];
    } else if ([@"takePicture" isEqualToString:call.method]) {
      if (@available(iOS 10.0, *)) {
        [_camera captureToFile:result];
      } else {
        [result sendNotImplemented];
      }
    } else if ([@"dispose" isEqualToString:call.method]) {
      [_registry unregisterTexture:cameraId];
      [_camera close];
      [result sendSuccess];
    } else if ([@"prepareForVideoRecording" isEqualToString:call.method]) {
      [self.camera setUpCaptureSessionForAudio];
      [result sendSuccess];
    } else if ([@"startVideoRecording" isEqualToString:call.method]) {
      [_camera startVideoRecordingWithResult:result];
    } else if ([@"stopVideoRecording" isEqualToString:call.method]) {
      [_camera stopVideoRecordingWithResult:result];
    } else if ([@"pauseVideoRecording" isEqualToString:call.method]) {
      [_camera pauseVideoRecordingWithResult:result];
    } else if ([@"resumeVideoRecording" isEqualToString:call.method]) {
      [_camera resumeVideoRecordingWithResult:result];
    } else if ([@"getMaxZoomLevel" isEqualToString:call.method]) {
      [_camera getMaxZoomLevelWithResult:result];
    } else if ([@"getMinZoomLevel" isEqualToString:call.method]) {
      [_camera getMinZoomLevelWithResult:result];
    } else if ([@"setZoomLevel" isEqualToString:call.method]) {
      CGFloat zoom = ((NSNumber *)argsMap[@"zoom"]).floatValue;
      [_camera setZoomLevel:zoom Result:result];
    } else if ([@"setFlashMode" isEqualToString:call.method]) {
      [_camera setFlashModeWithResult:result mode:call.arguments[@"mode"]];
    } else if ([@"setExposureMode" isEqualToString:call.method]) {
      [_camera setExposureModeWithResult:result mode:call.arguments[@"mode"]];
    } else if ([@"setExposurePoint" isEqualToString:call.method]) {
      BOOL reset = ((NSNumber *)call.arguments[@"reset"]).boolValue;
      double x = 0.5;
      double y = 0.5;
      if (!reset) {
        x = ((NSNumber *)call.arguments[@"x"]).doubleValue;
        y = ((NSNumber *)call.arguments[@"y"]).doubleValue;
      }
      [_camera setExposurePointWithResult:result x:x y:y];
    } else if ([@"getMinExposureOffset" isEqualToString:call.method]) {
      [result sendSuccessWithData:@(_camera.captureDevice.minExposureTargetBias)];
    } else if ([@"getMaxExposureOffset" isEqualToString:call.method]) {
      [result sendSuccessWithData:@(_camera.captureDevice.maxExposureTargetBias)];
    } else if ([@"getExposureOffsetStepSize" isEqualToString:call.method]) {
      [result sendSuccessWithData:@(0.0)];
    } else if ([@"setExposureOffset" isEqualToString:call.method]) {
      [_camera setExposureOffsetWithResult:result
                                    offset:((NSNumber *)call.arguments[@"offset"]).doubleValue];
    } else if ([@"lockCaptureOrientation" isEqualToString:call.method]) {
      [_camera lockCaptureOrientationWithResult:result orientation:call.arguments[@"orientation"]];
    } else if ([@"unlockCaptureOrientation" isEqualToString:call.method]) {
      [_camera unlockCaptureOrientationWithResult:result];
    } else if ([@"setFocusMode" isEqualToString:call.method]) {
      [_camera setFocusModeWithResult:result mode:call.arguments[@"mode"]];
    } else if ([@"setFocusPoint" isEqualToString:call.method]) {
      BOOL reset = ((NSNumber *)call.arguments[@"reset"]).boolValue;
      double x = 0.5;
      double y = 0.5;
      if (!reset) {
        x = ((NSNumber *)call.arguments[@"x"]).doubleValue;
        y = ((NSNumber *)call.arguments[@"y"]).doubleValue;
      }
      [_camera setFocusPointWithResult:result x:x y:y];
    } else if ([@"pausePreview" isEqualToString:call.method]) {
      [_camera pausePreviewWithResult:result];
    } else if ([@"resumePreview" isEqualToString:call.method]) {
      [_camera resumePreviewWithResult:result];
    } else {
      [result sendNotImplemented];
    }
  }
}

- (void)handleCreateMethodCall:(FlutterMethodCall *)call
                        result:(FLTThreadSafeFlutterResult *)result {
  // Create FLTCam only if granted camera access (and audio access if audio is enabled)
  __weak typeof(self) weakSelf = self;
  FLTRequestCameraPermissionWithCompletionHandler(^(FlutterError *error) {
    typeof(self) strongSelf = weakSelf;
    if (!strongSelf) return;

    if (error) {
      [result sendFlutterError:error];
    } else {
      // Request audio permission on `create` call with `enableAudio` argument instead of the
      // `prepareForVideoRecording` call. This is because `prepareForVideoRecording` call is
      // optional, and used as a workaround to fix a missing frame issue on iOS.
      BOOL audioEnabled = [call.arguments[@"enableAudio"] boolValue];
      if (audioEnabled) {
        // Setup audio capture session only if granted audio access.
        FLTRequestAudioPermissionWithCompletionHandler(^(FlutterError *error) {
          // cannot use the outter `strongSelf`
          typeof(self) strongSelf = weakSelf;
          if (!strongSelf) return;
          if (error) {
            [result sendFlutterError:error];
          } else {
            [strongSelf createCameraOnSessionQueueWithCreateMethodCall:call result:result];
          }
        });
      } else {
        [strongSelf createCameraOnSessionQueueWithCreateMethodCall:call result:result];
      }
    }
  });
}

- (void)createCameraOnSessionQueueWithCreateMethodCall:(FlutterMethodCall *)createMethodCall
                                                result:(FLTThreadSafeFlutterResult *)result {
  __weak typeof(self) weakSelf = self;
  dispatch_async(self.captureSessionQueue, ^{
    typeof(self) strongSelf = weakSelf;
    if (!strongSelf) return;

    NSString *cameraName = createMethodCall.arguments[@"cameraName"];
    NSString *resolutionPreset = createMethodCall.arguments[@"resolutionPreset"];
    NSNumber *enableAudio = createMethodCall.arguments[@"enableAudio"];
    NSError *error;
    FLTCam *cam = [[FLTCam alloc] initWithCameraName:cameraName
                                    resolutionPreset:resolutionPreset
                                         enableAudio:[enableAudio boolValue]
                                         orientation:[[UIDevice currentDevice] orientation]
                                 captureSessionQueue:strongSelf.captureSessionQueue
                                               error:&error];

    if (error) {
      [result sendError:error];
    } else {
      if (strongSelf.camera) {
        [strongSelf.camera close];
      }
      strongSelf.camera = cam;
      [strongSelf.registry registerTexture:cam
                                completion:^(int64_t textureId) {
                                  [result sendSuccessWithData:@{
                                    @"cameraId" : @(textureId),
                                  }];
                                }];
    }
  });
}

@end


text:
namespace JabbR.Models
{
    public class ClientNotification
    {
        public string Room { get; set; }
        public string ImageUrl { get; set; }
        public string Source { get; set; }
        public string Content { get; set; }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Alternaria: an identification manual 506 (2007)

#### Original name
Alternaria soliaegyptiaca E.G. Simmons

### Remarks
null


text:
using HoloJson.Parser.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HoloJson.Parser.Exceptions
{
    /// <summary>
    /// Indicates parse failure due to an unknown reason.
    /// </summary>
    public class UnknownParserException : JsonParserException
    {
        private const long serialVersionUID = 1L;

        public UnknownParserException() : base()
        {
        }
        public UnknownParserException(char[] tail) : base(tail)
        {
        }
        public UnknownParserException(char[] tail, char[] head) : base(tail, head)
        {
        }
        public UnknownParserException(ErrorContext context) : base(context)
        {
        }

        public UnknownParserException(string message) : base(message)
        {
        }
        public UnknownParserException(string message, string context) : base(message, context)
        {
        }
        public UnknownParserException(string message, char[] tail) : base(message, tail)
        {
        }
        public UnknownParserException(string message, char[] tail, char[] head) : base(message, tail, head)
        {
        }
        public UnknownParserException(string message, ErrorContext context) : base(message, context)
        {
        }

        public UnknownParserException(Exception cause) : base(cause)
        {
        }
        public UnknownParserException(Exception cause, string context) : base(cause, context)
        {
        }
        public UnknownParserException(Exception cause, char[] tail) : base(cause, tail)
        {
        }
        public UnknownParserException(Exception cause, char[] tail, char[] head) : base(cause, tail, head)
        {
        }
        public UnknownParserException(Exception cause, ErrorContext context) : base(cause, context)
        {
        }

        public UnknownParserException(string message, Exception cause) : base(message, cause)
        {
        }
        public UnknownParserException(string message, Exception cause, string context) : base(message, cause, context)
        {
        }
        public UnknownParserException(string message, Exception cause, char[] tail) : base(message, cause, tail)
        {
        }
        public UnknownParserException(string message, Exception cause, char[] tail, char[] head) : base(message, cause, tail, head)
        {
        }
        public UnknownParserException(string message, Exception cause, ErrorContext context) : base(message, cause, context)
        {
        }

    }

}


text:
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="description" content="">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <title>Yoh | Career Portal</title>

        <!-- default font -->
        <link  href="https://fonts.googleapis.com/css?family=Raleway:400,700,300" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Oswald:400,700,300" rel="stylesheet" type="text/css">

        <!-- Shortcut icons -->
        <link rel="apple-touch-icon" sizes="57x57" href="assets/images/apple-touch-icon-57x57.png" />
        <link rel="apple-touch-icon" sizes="60x60" href="assets/images/apple-touch-icon-60x60.png" />
        <link rel="apple-touch-icon" sizes="72x72" href="assets/images/apple-touch-icon-72x72.png" />
        <link rel="apple-touch-icon" sizes="76x76" href="assets/images/apple-touch-icon-76x76.png" />
        <link rel="apple-touch-icon" sizes="114x114" href="assets/images/apple-touch-icon-114x114.png" />
        <link rel="apple-touch-icon" sizes="120x120" href="assets/images/apple-touch-icon-120x120.png" />
        <link rel="apple-touch-icon" sizes="144x144" href="assets/images/apple-touch-icon-144x144.png" />
        <link rel="apple-touch-icon" sizes="152x152" href="assets/images/apple-touch-icon-152x152.png" />
        <link rel="apple-touch-icon" sizes="180x180" href="assets/images/apple-touch-icon-180x180.png" />
        <link rel="icon" type="image/png" href="assets/images/favicon-32x32.png" sizes="32x32" />
        <link rel="icon" type="image/png" href="assets/images/android-chrome-192x192.png" sizes="192x192" />
        <link rel="icon" type="image/png" href="assets/images/favicon-96x96.png" sizes="96x96" />
        <link rel="icon" type="image/png" href="assets/images/favicon-16x16.png" sizes="16x16" />

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

        <script>
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

            ga('create', 'UA-2656686-1', 'auto');
            //ga('send', 'pageview');
        </script>

        <script type="text/javascript">
            /*
            function recordOutboundLink(link, category, action, opt_label, opt_value) {
                _gat._getTrackerByName()._trackEvent(category, action, opt_label, opt_value);
                setTimeout('document.location = "' + link.href + '"', 100);
            }
            */
        </script>

        <!-- build:css({.tmp/serve,src}) styles/vendor.css -->
        <!-- bower:css -->
        <!-- run `gulp inject` to automatically populate bower styles dependencies -->
        <!-- endbower -->
        <!-- endbuild -->

        <!-- build:css({.tmp/serve,src}) styles/app.css -->
        <!-- inject:css -->
        <!-- css files will be automatically insert here -->
        <!-- endinject -->
        <!-- endbuild -->
    </head>
    <body>

        <!-- Main Application Tag (Angular2 Ready :)) -->
        <main></main>

        <!-- build:js(src) scripts/vendor.js -->
        <!-- bower:js -->
        <!-- run `gulp inject` to automatically populate bower script dependencies -->
        <!-- endbower -->
        <script src="../lib/ng-file-upload/ng-file-upload.js"></script>
        <!-- endbuild -->

        <!-- build:js({.tmp/serve,.tmp/partials}) scripts/app.js -->
        <!-- inject:js -->
        <!-- js files will be automatically insert here -->
        <!-- endinject -->

        <!-- inject:partials -->
        <!-- angular templates will be automatically converted in js and inserted here -->
        <!-- endinject -->
        <!-- endbuild -->

        <script type="text/javascript">
            $('#ethnicity').click(function() {
                if (this.checked) {
                    $("#eeoc-race").prop("disabled", "disabled");
                }
                else {
                    $("#eeoc-race").prop("disabled", false);
                }
            });
        </script>
    </body>
</html>


text:
import { Entity, Column, PrimaryGeneratedColumn } from "../../../../src"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string
}